From 2bc0a8c6cee8bfbb601720e4154bcafee26e62e8 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:44:01 +0900 Subject: [PATCH 1/8] =?UTF-8?q?=EB=B0=9B=EC=9D=80=20=EC=B2=A8=EB=B6=80?= =?UTF-8?q?=ED=8C=8C=EC=9D=BC=20=EB=AA=A9=EB=A1=9D=20=ED=91=9C=EC=8B=9C?= =?UTF-8?q?=EC=99=80=20=EC=A0=80=EC=9E=A5=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/core/i18n/language_controller.dart | 6 + .../lib/features/message/attachment_list.dart | 76 ++++++++++++ .../lib/features/message/message_page.dart | 7 ++ apps/client/lib/services/mail_api_client.dart | 63 ++++++++++ .../Flutter/GeneratedPluginRegistrant.swift | 2 + .../macos/Runner/DebugProfile.entitlements | 2 + apps/client/macos/Runner/Release.entitlements | 2 + apps/client/pubspec.lock | 80 ++++++++++++ apps/client/pubspec.yaml | 1 + apps/client/test/widget_test.dart | 17 +++ apps/server/package.json | 2 +- apps/server/src/api/routes.ts | 58 ++++++++- apps/server/src/domain/types.ts | 16 +++ apps/server/src/mail/ImapReceiver.ts | 60 ++++++++- apps/server/src/mail/MailReceiver.ts | 7 ++ apps/server/src/mail/Pop3Receiver.ts | 12 +- apps/server/src/mail/attachments.ts | 28 +++++ apps/server/src/server.ts | 9 ++ apps/server/test/accountReconnect.test.ts | 3 +- apps/server/test/accountValidate.test.ts | 1 + apps/server/test/attachments.test.ts | 114 ++++++++++++++++++ 21 files changed, 557 insertions(+), 9 deletions(-) create mode 100644 apps/client/lib/features/message/attachment_list.dart create mode 100644 apps/server/src/mail/attachments.ts create mode 100644 apps/server/test/attachments.test.ts diff --git a/apps/client/lib/core/i18n/language_controller.dart b/apps/client/lib/core/i18n/language_controller.dart index 443bb5f..3915c55 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -136,6 +136,12 @@ class AppStrings { : 'The new password is checked before saving. Stored mail and settings are kept.'; String get reconnectSucceeded => _ko ? '다시 연결했습니다. 메일을 가져오는 중입니다.' : 'Reconnected. Fetching mail now.'; + String get attachments => _ko ? '첨부파일' : 'Attachments'; + String get saveAttachment => _ko ? '저장' : 'Save'; + String attachmentSaved(String path) => + _ko ? '$path에 저장했습니다' : 'Saved to $path'; + String get attachmentSaveFailed => + _ko ? '첨부파일을 저장하지 못했습니다' : 'Could not save the attachment'; String get messageLoadFailedTitle => _ko ? '메일 본문을 불러오지 못했습니다' : 'Could not open this message'; String syncFailure(String? code, String? error) { diff --git a/apps/client/lib/features/message/attachment_list.dart b/apps/client/lib/features/message/attachment_list.dart new file mode 100644 index 0000000..38298e5 --- /dev/null +++ b/apps/client/lib/features/message/attachment_list.dart @@ -0,0 +1,76 @@ +import 'package:file_selector/file_selector.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../core/i18n/language_controller.dart'; +import '../../services/mail_api_client.dart'; + +class AttachmentList extends ConsumerWidget { + const AttachmentList({ + super.key, + required this.accountId, + required this.messageId, + required this.attachments, + }); + + final String accountId; + final String messageId; + final List attachments; + + Future _save( + BuildContext context, + WidgetRef ref, + MessageAttachment attachment, + ) async { + final strings = ref.read(appStringsProvider); + final messenger = ScaffoldMessenger.of(context); + try { + // shortcut: file_selector save dialog is desktop only, add a mobile + // share/save flow in a follow-up. + final location = await getSaveLocation( + suggestedName: attachment.filename, + ); + if (location == null) return; + await ref.read(mailApiClientProvider).downloadAttachment( + accountId: accountId, + messageId: messageId, + part: attachment.part, + savePath: location.path, + ); + messenger.showSnackBar( + SnackBar(content: Text(strings.attachmentSaved(location.path))), + ); + } catch (_) { + messenger.showSnackBar( + SnackBar(content: Text(strings.attachmentSaveFailed)), + ); + } + } + + @override + Widget build(BuildContext context, WidgetRef ref) { + final strings = ref.watch(appStringsProvider); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Divider(height: 32), + Text(strings.attachments, + style: Theme.of(context).textTheme.titleSmall), + for (final attachment in attachments) + ListTile( + contentPadding: EdgeInsets.zero, + leading: const Icon(Icons.attach_file), + title: Text(attachment.filename), + subtitle: Text( + '${formatAttachmentSize(attachment.size)} · ${attachment.contentType}', + ), + trailing: IconButton( + tooltip: strings.saveAttachment, + onPressed: () => _save(context, ref, attachment), + icon: const Icon(Icons.download), + ), + ), + ], + ); + } +} diff --git a/apps/client/lib/features/message/message_page.dart b/apps/client/lib/features/message/message_page.dart index 6f43d92..85a449b 100644 --- a/apps/client/lib/features/message/message_page.dart +++ b/apps/client/lib/features/message/message_page.dart @@ -5,6 +5,7 @@ import 'package:go_router/go_router.dart'; import '../../core/i18n/language_controller.dart'; import '../../services/mail_api_client.dart'; import '../../widgets/app_shell.dart'; +import 'attachment_list.dart'; import 'linked_message_body.dart'; typedef MessageRequest = ({String messageId, String? accountId}); @@ -81,6 +82,12 @@ class MessagePage extends ConsumerWidget { Text(item.receivedAtLabel), const Divider(height: 32), LinkedMessageBody(body: item.body, links: item.links), + if (item.attachments.isNotEmpty && accountId != null) + AttachmentList( + accountId: accountId!, + messageId: messageId, + attachments: item.attachments, + ), ], ), loading: () => const Center(child: CircularProgressIndicator()), diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index 721252c..a05a41e 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -1,3 +1,5 @@ +import 'dart:io'; + import 'package:dio/dio.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -93,6 +95,26 @@ class MailApiClient { return MessageDetail.fromJson(response.data ?? {}); } + Future downloadAttachment({ + required String accountId, + required String messageId, + required String part, + required String savePath, + }) async { + try { + await _dio.download( + '/accounts/$accountId/messages/$messageId/attachments/$part', + savePath, + options: Options(receiveTimeout: const Duration(minutes: 2)), + ); + } catch (_) { + // Do not leave a truncated file at the location the user picked. + final partial = File(savePath); + if (partial.existsSync()) partial.deleteSync(); + rethrow; + } + } + Future addAccount({ required String providerId, required String emailAddress, @@ -288,6 +310,7 @@ class MessageDetail { required this.body, required this.links, required this.receivedAtLabel, + this.attachments = const [], }); final String id; @@ -296,6 +319,7 @@ class MessageDetail { final String body; final List links; final String receivedAtLabel; + final List attachments; factory MessageDetail.fromJson(Map json) { return MessageDetail( @@ -308,10 +332,49 @@ class MessageDetail { .map(MessageLink.fromJson) .toList(growable: false), receivedAtLabel: _formatReceivedAt(json['receivedAt'] as String?), + attachments: (json['attachments'] as List? ?? const []) + .whereType>() + .map(MessageAttachment.fromJson) + .toList(growable: false), ); } } +class MessageAttachment { + const MessageAttachment({ + required this.part, + required this.filename, + required this.contentType, + required this.size, + }); + + final String part; + final String filename; + final String contentType; + final int size; + + factory MessageAttachment.fromJson(Map json) { + return MessageAttachment( + part: json['part'] as String? ?? '', + filename: json['filename'] as String? ?? '', + contentType: json['contentType'] as String? ?? '', + size: (json['size'] as num?)?.toInt() ?? 0, + ); + } +} + +String formatAttachmentSize(int bytes) { + if (bytes < 1024) return '$bytes B'; + const units = ['KB', 'MB', 'GB']; + var value = bytes / 1024; + var unit = 0; + while (value >= 1024 && unit < units.length - 1) { + value /= 1024; + unit += 1; + } + return '${value.toStringAsFixed(value < 10 ? 1 : 0)} ${units[unit]}'; +} + class MessageLink { const MessageLink({required this.url, required this.label}); diff --git a/apps/client/macos/Flutter/GeneratedPluginRegistrant.swift b/apps/client/macos/Flutter/GeneratedPluginRegistrant.swift index 8236f57..4e44bc8 100644 --- a/apps/client/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/apps/client/macos/Flutter/GeneratedPluginRegistrant.swift @@ -5,8 +5,10 @@ import FlutterMacOS import Foundation +import file_selector_macos import url_launcher_macos func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) } diff --git a/apps/client/macos/Runner/DebugProfile.entitlements b/apps/client/macos/Runner/DebugProfile.entitlements index b76b509..9b6cac7 100644 --- a/apps/client/macos/Runner/DebugProfile.entitlements +++ b/apps/client/macos/Runner/DebugProfile.entitlements @@ -6,6 +6,8 @@ development com.apple.security.app-sandbox + com.apple.security.files.user-selected.read-write + com.apple.security.cs.allow-jit com.apple.security.network.client diff --git a/apps/client/macos/Runner/Release.entitlements b/apps/client/macos/Runner/Release.entitlements index 39bde18..2a72027 100644 --- a/apps/client/macos/Runner/Release.entitlements +++ b/apps/client/macos/Runner/Release.entitlements @@ -6,6 +6,8 @@ development com.apple.security.app-sandbox + com.apple.security.files.user-selected.read-write + com.apple.security.network.client diff --git a/apps/client/pubspec.lock b/apps/client/pubspec.lock index 7ed6b11..7922d10 100644 --- a/apps/client/pubspec.lock +++ b/apps/client/pubspec.lock @@ -41,6 +41,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.19.1" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: f141ea4f277af142a0356955707f6556f37b03947d39d55585981a06ca437bd6 + url: "https://pub.dev" + source: hosted + version: "0.3.5+5" cupertino_icons: dependency: "direct main" description: @@ -73,6 +81,70 @@ packages: url: "https://pub.dev" source: hosted version: "1.3.3" + file_selector: + dependency: "direct main" + description: + name: file_selector + sha256: bd15e43e9268db636b53eeaca9f56324d1622af30e5c34d6e267649758c84d9a + url: "https://pub.dev" + source: hosted + version: "1.1.0" + file_selector_android: + dependency: transitive + description: + name: file_selector_android + sha256: d670cd0ce77a2e785b18d8b4d0a8d6a222d6a813ec9b7ddf2790a1b4fb6fa92c + url: "https://pub.dev" + source: hosted + version: "0.5.2+11" + file_selector_ios: + dependency: transitive + description: + name: file_selector_ios + sha256: "97269e5307a0ab813b1fa2430bada0a96e0afb74848417f8676f64ba5de0051c" + url: "https://pub.dev" + source: hosted + version: "0.5.3+6" + file_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: da76400e7872ce7637ffdce12749ec24169c25f6195c28372208e65a24bcd2ab + url: "https://pub.dev" + source: hosted + version: "0.9.4+1" + file_selector_macos: + dependency: transitive + description: + name: file_selector_macos + sha256: d57c62362766b5e7ae739448650b66c6aab7a68ba7ecc65e04018652645ae0f4 + url: "https://pub.dev" + source: hosted + version: "0.9.5+1" + file_selector_platform_interface: + dependency: transitive + description: + name: file_selector_platform_interface + sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85" + url: "https://pub.dev" + source: hosted + version: "2.7.0" + file_selector_web: + dependency: transitive + description: + name: file_selector_web + sha256: "73181fbc5257776d8ecaa6a94ab3c8e920ad143b9132a6d984a9271dfc6928d3" + url: "https://pub.dev" + source: hosted + version: "0.9.5" + file_selector_windows: + dependency: transitive + description: + name: file_selector_windows + sha256: fbefc5fb92c6d3cbe8d284a2cd971b593bb07d2cd6da8557b81a862250b4acec + url: "https://pub.dev" + source: hosted + version: "0.9.3+6" flutter: dependency: "direct main" description: flutter @@ -117,6 +189,14 @@ packages: url: "https://pub.dev" source: hosted version: "14.8.1" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" http_parser: dependency: transitive description: diff --git a/apps/client/pubspec.yaml b/apps/client/pubspec.yaml index 15b3c93..6727fc8 100644 --- a/apps/client/pubspec.yaml +++ b/apps/client/pubspec.yaml @@ -17,6 +17,7 @@ dependencies: go_router: ^14.6.2 intl: ^0.20.1 url_launcher: ^6.3.2 + file_selector: ^1.1.0 dev_dependencies: flutter_test: diff --git a/apps/client/test/widget_test.dart b/apps/client/test/widget_test.dart index 52f8487..37a2fba 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -437,6 +437,23 @@ void main() { ); }); + test('parses attachments and formats their size', () { + final detail = MessageDetail.fromJson({ + 'attachments': [ + { + 'part': '2', + 'filename': '보고서.pdf', + 'contentType': 'application/pdf', + 'size': 1536, + }, + ], + }); + + expect(detail.attachments.single.filename, '보고서.pdf'); + expect(formatAttachmentSize(detail.attachments.single.size), '1.5 KB'); + expect(formatAttachmentSize(20 * 1024 * 1024), '20 MB'); + }); + test('replaces a long mail link with its anchor title', () { const url = 'https://example.com/very/long/path?tracking=123'; final segments = parseMessageBody( diff --git a/apps/server/package.json b/apps/server/package.json index 982da57..b06a769 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "dev": "tsx src/server.ts", - "test": "tsx --test test/imapSequenceRanges.test.ts test/mailSyncWorker.test.ts test/accountValidate.test.ts test/accountReconnect.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts", + "test": "tsx --test test/imapSequenceRanges.test.ts test/mailSyncWorker.test.ts test/accountValidate.test.ts test/accountReconnect.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts test/attachments.test.ts", "typecheck": "tsc --noEmit", "start": "node dist/server.js", "build": "tsc" diff --git a/apps/server/src/api/routes.ts b/apps/server/src/api/routes.ts index 6e2ebd1..b72717d 100644 --- a/apps/server/src/api/routes.ts +++ b/apps/server/src/api/routes.ts @@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto"; import { z } from "zod"; import type { MailSender } from "../mail/MailSender.js"; import type { + AttachmentDownload, AuthMode, IncomingMessageContent, IncomingMessageSummary, @@ -83,6 +84,11 @@ export async function registerRoutes( account: MailAccount, message: IncomingMessageSummary ) => Promise; + downloadAttachment: ( + account: MailAccount, + message: IncomingMessageSummary, + part: string + ) => Promise; startAccountSync: (account: MailAccount) => Promise; resumeAccountSync: (account: MailAccount) => Promise; stopAccountSync: (accountId: string) => Promise; @@ -302,10 +308,57 @@ export async function registerRoutes( receivedAt: message.receivedAt.toISOString(), body: content.text, bodyTruncated: content.truncated, - bodyLinks: content.links + bodyLinks: content.links, + attachments: content.attachments }; }); + app.get( + "/accounts/:accountId/messages/:messageId/attachments/:part", + async (request, reply) => { + const params = z.object({ + accountId: z.string(), + messageId: z.string(), + part: z.string().regex(/^\d+(\.\d+)*$/) + }).parse(request.params); + const account = await deps.accounts.getAccount(params.accountId); + + if (!account || account.userId !== demoUserId) { + return reply.code(404).send({ error: "Account not found" }); + } + + const messages = await deps.accounts.listInbox(demoUserId); + const message = messages.find( + (item) => item.accountId === params.accountId && + item.providerMessageId === params.messageId + ); + if (!message) { + return reply.code(404).send({ error: "Message not found" }); + } + + const download = await deps.downloadAttachment( + account, + message, + params.part + ); + if (!download) { + return reply.code(404).send({ error: "Attachment not found" }); + } + + const closeOnce = () => void download.close(); + reply.raw.once("close", closeOnce); + download.stream.once("error", closeOnce); + download.stream.once("end", closeOnce); + return reply + .header("Content-Type", download.contentType) + .header( + "Content-Disposition", + `attachment; filename*=UTF-8''${encodeURIComponent(download.filename)}` + ) + .send(download.stream); + } + ); + app.get("/mail/inbox", async () => { const messages = await deps.accounts.listInbox(demoUserId); return messages.map((message) => ({ @@ -334,7 +387,8 @@ export async function registerRoutes( receivedAt: message.receivedAt.toISOString(), body: content.text, bodyTruncated: content.truncated, - bodyLinks: content.links + bodyLinks: content.links, + attachments: content.attachments }; }); diff --git a/apps/server/src/domain/types.ts b/apps/server/src/domain/types.ts index ad7152b..b1a7852 100644 --- a/apps/server/src/domain/types.ts +++ b/apps/server/src/domain/types.ts @@ -81,6 +81,22 @@ export interface IncomingMessageContent { text: string; truncated: boolean; links: IncomingMessageLink[]; + attachments: IncomingMessageAttachment[]; +} + +export interface IncomingMessageAttachment { + part: string; + filename: string; + contentType: string; + /** Encoded size reported by IMAP, so slightly larger than the file. */ + size: number; +} + +export interface AttachmentDownload { + filename: string; + contentType: string; + stream: NodeJS.ReadableStream; + close: () => Promise; } export interface IncomingMessageLink { diff --git a/apps/server/src/mail/ImapReceiver.ts b/apps/server/src/mail/ImapReceiver.ts index 4160d89..a923fe1 100644 --- a/apps/server/src/mail/ImapReceiver.ts +++ b/apps/server/src/mail/ImapReceiver.ts @@ -3,6 +3,8 @@ import type { FetchMessageObject, MessageStructureObject } from "imapflow"; import { simpleParser } from "mailparser"; import type { OAuthTokenManager } from "../auth/OAuthTokenManager.js"; import type { + AttachmentDownload, + IncomingMessageAttachment, IncomingMessageContent, IncomingMessageLink, IncomingMessageSummary, @@ -17,6 +19,7 @@ import { newestFirstUidBatches } from "./imapSequenceRanges.js"; import { isAuthenticationFailure } from "./authenticationFailure.js"; +import { extractAttachments } from "./attachments.js"; import { extractMessageLinks } from "./messageLinks.js"; export class ImapReceiver implements MailReceiver { @@ -122,6 +125,7 @@ export class ImapReceiver implements MailReceiver { throw new Error("Message body was not found on the IMAP server."); } + const attachments = extractAttachments(message.bodyStructure); const bodyParts = selectBodyParts(message.bodyStructure); let htmlFallback: IncomingMessageContent | null = null; let htmlLinks: IncomingMessageLink[] = []; @@ -141,7 +145,7 @@ export class ImapReceiver implements MailReceiver { if (bodyPart.type.toLowerCase() !== "text/html") { const text = cleanMessageText(decoded); - if (text) return { text, truncated, links: htmlLinks }; + if (text) return { text, truncated, links: htmlLinks, attachments }; continue; } @@ -167,18 +171,66 @@ export class ImapReceiver implements MailReceiver { htmlFallback = { text, truncated, - links: htmlLinks + links: htmlLinks, + attachments }; } } - if (htmlFallback) return { ...htmlFallback, links: htmlLinks }; - return { text: "", truncated: false, links: [] }; + if (htmlFallback) { + return { ...htmlFallback, links: htmlLinks, attachments }; + } + return { text: "", truncated: false, links: [], attachments }; } finally { await client.logout().catch(() => undefined); } } + async downloadAttachment( + account: MailAccount, + mailbox: string, + providerMessageId: string, + part: string + ): Promise { + const client = await this.createClient(account); + await client.connect(); + const close = async () => { + await client.logout().catch(() => undefined); + }; + + try { + await client.mailboxOpen(mailbox, { readOnly: true }); + const message = await client.fetchOne( + providerMessageId, + { bodyStructure: true }, + { uid: true } + ); + const attachment: IncomingMessageAttachment | undefined = message && + message.bodyStructure + ? extractAttachments(message.bodyStructure).find( + (item) => item.part === part + ) + : undefined; + if (!attachment) { + await close(); + return null; + } + + const download = await client.download(providerMessageId, part, { + uid: true + }); + return { + filename: attachment.filename, + contentType: attachment.contentType, + stream: download.content, + close + }; + } catch (error) { + await close(); + throw error; + } + } + async watch( account: MailAccount, mailbox: string, diff --git a/apps/server/src/mail/MailReceiver.ts b/apps/server/src/mail/MailReceiver.ts index 6b3bfce..c487c92 100644 --- a/apps/server/src/mail/MailReceiver.ts +++ b/apps/server/src/mail/MailReceiver.ts @@ -1,4 +1,5 @@ import type { + AttachmentDownload, IncomingMessageContent, IncomingMessageSummary, MailAccount @@ -16,6 +17,12 @@ export interface MailReceiver { mailbox: string, providerMessageId: string ): Promise; + downloadAttachment( + account: MailAccount, + mailbox: string, + providerMessageId: string, + part: string + ): Promise; watch?( account: MailAccount, mailbox: string, diff --git a/apps/server/src/mail/Pop3Receiver.ts b/apps/server/src/mail/Pop3Receiver.ts index b9c7b61..21ab272 100644 --- a/apps/server/src/mail/Pop3Receiver.ts +++ b/apps/server/src/mail/Pop3Receiver.ts @@ -1,4 +1,5 @@ import type { + AttachmentDownload, IncomingMessageContent, IncomingMessageSummary, MailAccount @@ -35,6 +36,15 @@ export class Pop3Receiver implements MailReceiver { _mailbox: string, _providerMessageId: string ): Promise { - return { text: "", truncated: false, links: [] }; + return { text: "", truncated: false, links: [], attachments: [] }; + } + + async downloadAttachment( + _account: MailAccount, + _mailbox: string, + _providerMessageId: string, + _part: string + ): Promise { + return null; } } diff --git a/apps/server/src/mail/attachments.ts b/apps/server/src/mail/attachments.ts new file mode 100644 index 0000000..b79db87 --- /dev/null +++ b/apps/server/src/mail/attachments.ts @@ -0,0 +1,28 @@ +import type { MessageStructureObject } from "imapflow"; +import type { IncomingMessageAttachment } from "../domain/types.js"; + +// imapflow already decodes RFC 2231 / encoded-word names in the parameters. +export function extractAttachments( + root: MessageStructureObject +): IncomingMessageAttachment[] { + const found: IncomingMessageAttachment[] = []; + + const visit = (node: MessageStructureObject): void => { + for (const child of node.childNodes ?? []) visit(child); + if (node.childNodes?.length || !node.part) return; + + const filename = + node.dispositionParameters?.filename ?? node.parameters?.name; + if (node.disposition?.toLowerCase() !== "attachment" && !filename) return; + + found.push({ + part: node.part, + filename: filename || `attachment-${node.part}`, + contentType: node.type.toLowerCase(), + size: node.size ?? 0 + }); + }; + + visit(root); + return found; +} diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 47ce656..5cbba86 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -68,6 +68,15 @@ await registerRoutes(app, { message.providerMessageId ); }, + downloadAttachment: async (account, message, part) => { + const receiver = account.incomingProtocol === "imap" ? imap : pop3; + return receiver.downloadAttachment( + account, + message.mailbox, + message.providerMessageId, + part + ); + }, startAccountSync: async (account) => worker.startAccount(account), resumeAccountSync: async (account) => worker.resumeAccount(account), stopAccountSync: async (accountId) => worker.stopAccount(accountId) diff --git a/apps/server/test/accountReconnect.test.ts b/apps/server/test/accountReconnect.test.ts index 7661503..6d020ca 100644 --- a/apps/server/test/accountReconnect.test.ts +++ b/apps/server/test/accountReconnect.test.ts @@ -58,7 +58,8 @@ async function setup(account: MailAccount) { sender: {} as never, fetchMessageContent: async () => { throw new Error("unused"); - } + }, + downloadAttachment: async () => null }); new OAuthAccountFlow(deps).register(app); return { app, accounts, calls }; diff --git a/apps/server/test/accountValidate.test.ts b/apps/server/test/accountValidate.test.ts index 8c52780..e16c9c8 100644 --- a/apps/server/test/accountValidate.test.ts +++ b/apps/server/test/accountValidate.test.ts @@ -30,6 +30,7 @@ async function validate(syncErrorCode: MailAccount["syncErrorCode"]) { fetchMessageContent: async () => { throw new Error("unused"); }, + downloadAttachment: async () => null, startAccountSync: async () => undefined, resumeAccountSync: async () => { starts += 1; diff --git a/apps/server/test/attachments.test.ts b/apps/server/test/attachments.test.ts new file mode 100644 index 0000000..ca2e846 --- /dev/null +++ b/apps/server/test/attachments.test.ts @@ -0,0 +1,114 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { extractAttachments } from "../src/mail/attachments.js"; + +test("extracts attachment parts and skips body parts", () => { + const result = extractAttachments({ + type: "multipart/mixed", + childNodes: [ + { + part: "1", + type: "multipart/alternative", + childNodes: [ + { part: "1.1", type: "text/plain" }, + { part: "1.2", type: "text/html" } + ] + }, + { + part: "2", + type: "application/pdf", + size: 1234, + disposition: "attachment", + dispositionParameters: { filename: "보고서.pdf" } + }, + { + part: "3", + type: "IMAGE/PNG", + size: 10, + parameters: { name: "inline.png" } + }, + { part: "4", type: "application/zip", disposition: "attachment" } + ] + }); + + assert.deepEqual(result, [ + { part: "2", filename: "보고서.pdf", contentType: "application/pdf", size: 1234 }, + { part: "3", filename: "inline.png", contentType: "image/png", size: 10 }, + { part: "4", filename: "attachment-4", contentType: "application/zip", size: 0 } + ]); +}); + +test("attachment route streams the part with an encoded filename", async () => { + const { default: Fastify } = await import("fastify"); + const { Readable } = await import("node:stream"); + const { registerRoutes } = await import("../src/api/routes.js"); + const { InMemoryAccountRepository } = await import( + "../src/workers/AccountRepository.js" + ); + const now = new Date(); + const accounts = new InMemoryAccountRepository(); + await accounts.addAccount({ + id: "a1", + userId: "demo-user", + providerId: "naver", + emailAddress: "u@example.com", + authMode: "app-password", + incomingProtocol: "imap", + encryptedSecretRef: "x", + syncStatus: "idle", + createdAt: now, + updatedAt: now + }); + await accounts.saveIncomingMessage( + { + accountId: "a1", + providerMessageId: "7", + mailbox: "INBOX", + from: "", + subject: "", + receivedAt: now, + hasAttachments: true + } + ); + let closed = false; + const app = Fastify(); + await registerRoutes(app, { + accounts, + sender: {} as never, + validateAccount: async () => undefined, + fetchMessageContent: async () => { + throw new Error("unused"); + }, + downloadAttachment: async (_account, _message, part) => + part === "2" + ? { + filename: "보고서.pdf", + contentType: "application/pdf", + stream: Readable.from([Buffer.from("abc")]), + close: async () => { + closed = true; + } + } + : null, + startAccountSync: async () => undefined, + resumeAccountSync: async () => undefined, + stopAccountSync: async () => undefined + }); + + const ok = await app.inject("/accounts/a1/messages/7/attachments/2"); + assert.equal(ok.statusCode, 200); + assert.equal(ok.body, "abc"); + assert.match( + String(ok.headers["content-disposition"]), + /filename\*=UTF-8''%EB%B3%B4%EA%B3%A0%EC%84%9C\.pdf/ + ); + assert.equal(closed, true); + assert.equal( + (await app.inject("/accounts/a1/messages/7/attachments/9")).statusCode, + 404 + ); + assert.equal( + (await app.inject("/accounts/a1/messages/7/attachments/..%2Fx")).statusCode, + 500 + ); +}); From e284391d0012e1e3f684af7b708a130a13f6ba7d Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:50:03 +0900 Subject: [PATCH 2/8] =?UTF-8?q?=EC=B2=A8=EB=B6=80=20=EB=8B=A4=EC=9A=B4?= =?UTF-8?q?=EB=A1=9C=EB=93=9C=20=EC=8B=A4=ED=8C=A8=20=EC=8B=9C=20=EA=B8=B0?= =?UTF-8?q?=EC=A1=B4=20=ED=8C=8C=EC=9D=BC=20=EB=B3=B4=EC=A1=B4,=20?= =?UTF-8?q?=EC=B2=A8=EB=B6=80=20=EB=A9=94=EC=9D=BC(rfc822)=20=EC=9E=90?= =?UTF-8?q?=EC=B2=B4=EB=A5=BC=20=EC=B2=A8=EB=B6=80=EB=A1=9C=20=EB=85=B8?= =?UTF-8?q?=EC=B6=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/client/lib/services/mail_api_client.dart | 9 ++++--- apps/client/test/widget_test.dart | 17 ++++++++++++ apps/server/src/mail/attachments.ts | 27 ++++++++++++------- apps/server/test/attachments.test.ts | 22 +++++++++++++++ 4 files changed, 61 insertions(+), 14 deletions(-) diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index a05a41e..5bd58e8 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -101,16 +101,17 @@ class MailApiClient { required String part, required String savePath, }) async { + // Write to a temp file so a failed download never touches an existing file. + final temp = File('$savePath.part'); try { await _dio.download( '/accounts/$accountId/messages/$messageId/attachments/$part', - savePath, + temp.path, options: Options(receiveTimeout: const Duration(minutes: 2)), ); + await temp.rename(savePath); } catch (_) { - // Do not leave a truncated file at the location the user picked. - final partial = File(savePath); - if (partial.existsSync()) partial.deleteSync(); + if (temp.existsSync()) temp.deleteSync(); rethrow; } } diff --git a/apps/client/test/widget_test.dart b/apps/client/test/widget_test.dart index 37a2fba..45addfb 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -1,3 +1,5 @@ +import 'dart:io'; + import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -9,6 +11,21 @@ import 'package:daily_postbox/main.dart'; import 'package:daily_postbox/services/mail_api_client.dart'; void main() { + test('failed attachment download keeps the existing destination file', + () async { + final dir = Directory.systemTemp.createTempSync('dl'); + addTearDown(() => dir.deleteSync(recursive: true)); + final target = File('${dir.path}/a.txt')..writeAsStringSync('keep'); + final client = MailApiClient(baseUrl: 'http://127.0.0.1:1'); + await expectLater( + client.downloadAttachment( + accountId: 'a', messageId: 'm', part: '1', savePath: target.path), + throwsA(isA()), + ); + expect(target.readAsStringSync(), 'keep'); + expect(File('${target.path}.part').existsSync(), isFalse); + }); + testWidgets('renders mail app shell', (WidgetTester tester) async { await tester.pumpWidget( ProviderScope( diff --git a/apps/server/src/mail/attachments.ts b/apps/server/src/mail/attachments.ts index b79db87..97bc90f 100644 --- a/apps/server/src/mail/attachments.ts +++ b/apps/server/src/mail/attachments.ts @@ -8,19 +8,26 @@ export function extractAttachments( const found: IncomingMessageAttachment[] = []; const visit = (node: MessageStructureObject): void => { - for (const child of node.childNodes ?? []) visit(child); - if (node.childNodes?.length || !node.part) return; - const filename = node.dispositionParameters?.filename ?? node.parameters?.name; - if (node.disposition?.toLowerCase() !== "attachment" && !filename) return; + const isAttachment = + node.disposition?.toLowerCase() === "attachment" || Boolean(filename); + const type = node.type.toLowerCase(); + const hasChildren = Boolean(node.childNodes?.length); - found.push({ - part: node.part, - filename: filename || `attachment-${node.part}`, - contentType: node.type.toLowerCase(), - size: node.size ?? 0 - }); + // An attached message carries child parts, but the message itself is the attachment. + if (node.part && isAttachment && (!hasChildren || type === "message/rfc822")) { + found.push({ + part: node.part, + filename: + filename || + `attachment-${node.part}${type === "message/rfc822" ? ".eml" : ""}`, + contentType: type, + size: node.size ?? 0 + }); + return; + } + for (const child of node.childNodes ?? []) visit(child); }; visit(root); diff --git a/apps/server/test/attachments.test.ts b/apps/server/test/attachments.test.ts index ca2e846..b5e7ba3 100644 --- a/apps/server/test/attachments.test.ts +++ b/apps/server/test/attachments.test.ts @@ -38,6 +38,28 @@ test("extracts attachment parts and skips body parts", () => { ]); }); +test("exposes an attached message itself instead of its inner parts", () => { + const result = extractAttachments({ + type: "multipart/mixed", + childNodes: [ + { part: "1", type: "text/plain" }, + { + part: "2", + type: "message/rfc822", + size: 500, + disposition: "attachment", + dispositionParameters: { filename: "forwarded.eml" }, + childNodes: [ + { part: "2.1", type: "application/pdf", disposition: "attachment" } + ] + } + ] + }); + assert.deepEqual(result, [ + { part: "2", filename: "forwarded.eml", contentType: "message/rfc822", size: 500 } + ]); +}); + test("attachment route streams the part with an encoded filename", async () => { const { default: Fastify } = await import("fastify"); const { Readable } = await import("node:stream"); From bcd2b54e040566b999e9462b3797ddd31547513c Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:55:18 +0900 Subject: [PATCH 3/8] =?UTF-8?q?=EC=B2=A8=EB=B6=80=20=EB=8B=A4=EC=9A=B4?= =?UTF-8?q?=EB=A1=9C=EB=93=9C=EB=A5=BC=20=EC=95=B1=20=EC=9E=84=EC=8B=9C=20?= =?UTF-8?q?=ED=8F=B4=EB=8D=94=EC=97=90=20=EB=B0=9B=EC=9D=80=20=EB=92=A4=20?= =?UTF-8?q?=EC=84=B1=EA=B3=B5=20=EC=8B=9C=EC=97=90=EB=A7=8C=20=EB=8C=80?= =?UTF-8?q?=EC=83=81=20=ED=8C=8C=EC=9D=BC=EB=A1=9C=20=EB=B3=B5=EC=82=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/client/lib/services/mail_api_client.dart | 13 ++++++------ apps/client/test/widget_test.dart | 21 +++++++++++++++++++ 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index 5bd58e8..f4b255d 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -101,18 +101,19 @@ class MailApiClient { required String part, required String savePath, }) async { - // Write to a temp file so a failed download never touches an existing file. - final temp = File('$savePath.part'); + // Download into a unique app-accessible temp dir (the sandbox may deny + // writes next to the selected file); touch the destination only on success. + final tempDir = await Directory.systemTemp.createTemp('attachment_'); try { + final temp = File('${tempDir.path}/download'); await _dio.download( '/accounts/$accountId/messages/$messageId/attachments/$part', temp.path, options: Options(receiveTimeout: const Duration(minutes: 2)), ); - await temp.rename(savePath); - } catch (_) { - if (temp.existsSync()) temp.deleteSync(); - rethrow; + await temp.copy(savePath); + } finally { + await tempDir.delete(recursive: true); } } diff --git a/apps/client/test/widget_test.dart b/apps/client/test/widget_test.dart index 45addfb..588f78d 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -26,6 +26,27 @@ void main() { expect(File('${target.path}.part').existsSync(), isFalse); }); + test('successful attachment download writes destination, leaves no temp', + () async { + HttpOverrides.global = null; // test binding stubs HTTP with 400 + final server = await HttpServer.bind('127.0.0.1', 0); + addTearDown(() => server.close(force: true)); + server.listen((req) { + req.response.add([1, 2, 3]); + req.response.close(); + }); + final dir = Directory.systemTemp.createTempSync('dl'); + addTearDown(() => dir.deleteSync(recursive: true)); + final target = File('${dir.path}/a.bin')..writeAsStringSync('old'); + final sibling = File('${dir.path}/a.bin.part')..writeAsStringSync('other'); + final client = MailApiClient(baseUrl: 'http://127.0.0.1:${server.port}'); + await client.downloadAttachment( + accountId: 'a', messageId: 'm', part: '1', savePath: target.path); + expect(target.readAsBytesSync(), [1, 2, 3]); + expect(sibling.readAsStringSync(), 'other'); + expect(dir.listSync().length, 2); + }); + testWidgets('renders mail app shell', (WidgetTester tester) async { await tester.pumpWidget( ProviderScope( From 9d9f3790325fe461b0753bc781584307623b8a76 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:03:21 +0900 Subject: [PATCH 4/8] =?UTF-8?q?=EC=9D=B8=EC=A6=9D=20=EC=A0=84=EC=97=90?= =?UTF-8?q?=EB=8A=94=20=EC=B2=A8=EB=B6=80=20=EB=8B=A4=EC=9A=B4=EB=A1=9C?= =?UTF-8?q?=EB=93=9C=EB=A5=BC=20=EB=A1=9C=EC=BB=AC=20=EC=9A=94=EC=B2=AD?= =?UTF-8?q?=EC=97=90=EB=A7=8C=20=ED=97=88=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 실제 사용자 인증(#20) 전까지 네트워크 호출자가 첨부 원문을 받지 못하게 막는다. ALLOW_REMOTE_MAIL_ACCESS=true로만 원격 허용. --- apps/server/.env.example | 2 + apps/server/package.json | 2 +- apps/server/src/api/routes.ts | 10 +++ apps/server/test/attachmentAccess.test.ts | 74 +++++++++++++++++++++++ 4 files changed, 87 insertions(+), 1 deletion(-) create mode 100644 apps/server/test/attachmentAccess.test.ts diff --git a/apps/server/.env.example b/apps/server/.env.example index 8f64eca..aca3733 100644 --- a/apps/server/.env.example +++ b/apps/server/.env.example @@ -17,3 +17,5 @@ GOOGLE_OAUTH_CLIENT_ID= GOOGLE_OAUTH_CLIENT_SECRET= OUTLOOK_OAUTH_CLIENT_ID= OUTLOOK_OAUTH_CLIENT_SECRET= +# UNSAFE until user auth exists (#20): lets non-loopback callers download mail attachments. +ALLOW_REMOTE_MAIL_ACCESS=false diff --git a/apps/server/package.json b/apps/server/package.json index b06a769..ec0cb07 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "dev": "tsx src/server.ts", - "test": "tsx --test test/imapSequenceRanges.test.ts test/mailSyncWorker.test.ts test/accountValidate.test.ts test/accountReconnect.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts test/attachments.test.ts", + "test": "tsx --test test/imapSequenceRanges.test.ts test/mailSyncWorker.test.ts test/accountValidate.test.ts test/accountReconnect.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts test/attachments.test.ts test/attachmentAccess.test.ts", "typecheck": "tsc --noEmit", "start": "node dist/server.js", "build": "tsc" diff --git a/apps/server/src/api/routes.ts b/apps/server/src/api/routes.ts index b72717d..2bbbce7 100644 --- a/apps/server/src/api/routes.ts +++ b/apps/server/src/api/routes.ts @@ -74,6 +74,13 @@ const accountSchema = z.object({ const demoUserId = "demo-user"; +// shortcut: no real auth yet (issue #20), so attachment downloads are +// loopback-only unless ALLOW_REMOTE_MAIL_ACCESS=true. +function canReadAttachments(ip: string): boolean { + return process.env.ALLOW_REMOTE_MAIL_ACCESS === "true" || + ip === "127.0.0.1" || ip === "::1" || ip === "::ffff:127.0.0.1"; +} + export async function registerRoutes( app: FastifyInstance, deps: { @@ -316,6 +323,9 @@ export async function registerRoutes( app.get( "/accounts/:accountId/messages/:messageId/attachments/:part", async (request, reply) => { + if (!canReadAttachments(request.ip)) { + return reply.code(403).send({ error: "Attachments are only available locally." }); + } const params = z.object({ accountId: z.string(), messageId: z.string(), diff --git a/apps/server/test/attachmentAccess.test.ts b/apps/server/test/attachmentAccess.test.ts new file mode 100644 index 0000000..20de148 --- /dev/null +++ b/apps/server/test/attachmentAccess.test.ts @@ -0,0 +1,74 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { Readable } from "node:stream"; +import Fastify from "fastify"; +import { registerRoutes } from "../src/api/routes.js"; +import { InMemoryAccountRepository } from "../src/workers/AccountRepository.js"; + +async function build() { + const now = new Date(); + const accounts = new InMemoryAccountRepository(); + await accounts.addAccount({ + id: "a1", + userId: "demo-user", + providerId: "naver", + emailAddress: "u@example.test", + authMode: "app-password", + incomingProtocol: "imap", + encryptedSecretRef: "x", + syncStatus: "idle", + createdAt: now, + updatedAt: now + }); + await accounts.saveIncomingMessage({ + accountId: "a1", + providerMessageId: "7", + mailbox: "INBOX", + from: "", + subject: "", + receivedAt: now, + hasAttachments: true + }); + let downloads = 0; + const app = Fastify(); + await registerRoutes(app, { + accounts, + downloadAttachment: async () => { + downloads++; + return { + filename: "a.txt", + contentType: "text/plain", + stream: Readable.from([Buffer.from("abc")]), + close: async () => undefined + }; + } + } as never); + return { app, downloads: () => downloads }; +} + +const url = "/accounts/a1/messages/7/attachments/2"; + +test("loopback may download attachments", async () => { + const { app } = await build(); + for (const remoteAddress of ["127.0.0.1", "::1", "::ffff:127.0.0.1"]) { + assert.equal((await app.inject({ url, remoteAddress })).statusCode, 200); + } +}); + +test("remote callers get 403 and nothing is fetched", async () => { + const { app, downloads } = await build(); + const res = await app.inject({ url, remoteAddress: "192.168.0.5" }); + assert.equal(res.statusCode, 403); + assert.equal(downloads(), 0); +}); + +test("ALLOW_REMOTE_MAIL_ACCESS=true opts remote callers in", async () => { + process.env.ALLOW_REMOTE_MAIL_ACCESS = "true"; + try { + const { app } = await build(); + const res = await app.inject({ url, remoteAddress: "192.168.0.5" }); + assert.equal(res.statusCode, 200); + } finally { + delete process.env.ALLOW_REMOTE_MAIL_ACCESS; + } +}); From c4a3681bff7a01a15c344ee9241ac61cba81157e Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:05:09 +0900 Subject: [PATCH 5/8] =?UTF-8?q?=EC=B2=A8=EB=B6=80=20=EB=8B=A4=EC=9A=B4?= =?UTF-8?q?=EB=A1=9C=EB=93=9C=EC=97=90=20Host=C2=B7Origin=20=EA=B2=80?= =?UTF-8?q?=EC=82=AC=EB=A5=BC=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit loopback 요청이라도 Host가 loopback이 아니거나 Origin 헤더가 있으면(브라우저 경유, DNS 리바인딩) 403으로 막는다. ALLOW_REMOTE_MAIL_ACCESS=true면 모두 허용. --- apps/server/src/api/routes.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/apps/server/src/api/routes.ts b/apps/server/src/api/routes.ts index 2bbbce7..d501543 100644 --- a/apps/server/src/api/routes.ts +++ b/apps/server/src/api/routes.ts @@ -75,10 +75,14 @@ const accountSchema = z.object({ const demoUserId = "demo-user"; // shortcut: no real auth yet (issue #20), so attachment downloads are -// loopback-only unless ALLOW_REMOTE_MAIL_ACCESS=true. -function canReadAttachments(ip: string): boolean { - return process.env.ALLOW_REMOTE_MAIL_ACCESS === "true" || - ip === "127.0.0.1" || ip === "::1" || ip === "::ffff:127.0.0.1"; +// loopback-only unless ALLOW_REMOTE_MAIL_ACCESS=true. Host and Origin checks +// also block DNS rebinding and cross-site browser requests to localhost. +function canReadAttachments(request: FastifyRequest): boolean { + if (process.env.ALLOW_REMOTE_MAIL_ACCESS === "true") return true; + const host = (request.headers.host ?? "").replace(/:\d+$/, "").toLowerCase(); + return ["127.0.0.1", "::1", "::ffff:127.0.0.1"].includes(request.ip) && + ["127.0.0.1", "localhost", "[::1]"].includes(host) && + request.headers.origin === undefined; } export async function registerRoutes( @@ -323,7 +327,7 @@ export async function registerRoutes( app.get( "/accounts/:accountId/messages/:messageId/attachments/:part", async (request, reply) => { - if (!canReadAttachments(request.ip)) { + if (!canReadAttachments(request)) { return reply.code(403).send({ error: "Attachments are only available locally." }); } const params = z.object({ From d82bf590e74442bb736d622e8baf5ee579d38011 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:05:22 +0900 Subject: [PATCH 6/8] =?UTF-8?q?=EC=B2=A8=EB=B6=80=20Host=C2=B7Origin=20?= =?UTF-8?q?=EA=B2=80=EC=82=AC=20import=20=EB=88=84=EB=9D=BD=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=20=EB=B0=8F=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/server/src/api/routes.ts | 2 +- apps/server/test/attachmentAccess.test.ts | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/apps/server/src/api/routes.ts b/apps/server/src/api/routes.ts index d501543..430ebc7 100644 --- a/apps/server/src/api/routes.ts +++ b/apps/server/src/api/routes.ts @@ -1,4 +1,4 @@ -import type { FastifyInstance } from "fastify"; +import type { FastifyInstance, FastifyRequest } from "fastify"; import { randomUUID } from "node:crypto"; import { z } from "zod"; import type { MailSender } from "../mail/MailSender.js"; diff --git a/apps/server/test/attachmentAccess.test.ts b/apps/server/test/attachmentAccess.test.ts index 20de148..13b55fd 100644 --- a/apps/server/test/attachmentAccess.test.ts +++ b/apps/server/test/attachmentAccess.test.ts @@ -62,6 +62,18 @@ test("remote callers get 403 and nothing is fetched", async () => { assert.equal(downloads(), 0); }); +test("Origin header or non-loopback Host gets 403 even from loopback", async () => { + const { app, downloads } = await build(); + const remoteAddress = "127.0.0.1"; + const origin = await app.inject({ url, remoteAddress, headers: { origin: "https://evil.example" } }); + assert.equal(origin.statusCode, 403); + const host = await app.inject({ url, remoteAddress, headers: { host: "evil.example" } }); + assert.equal(host.statusCode, 403); + assert.equal(downloads(), 0); + const ok = await app.inject({ url, remoteAddress, headers: { host: "[::1]:8080" } }); + assert.equal(ok.statusCode, 200); +}); + test("ALLOW_REMOTE_MAIL_ACCESS=true opts remote callers in", async () => { process.env.ALLOW_REMOTE_MAIL_ACCESS = "true"; try { From 4809bd61021294aa484c7209c1ad11407155856b Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:12:12 +0900 Subject: [PATCH 7/8] =?UTF-8?q?base64=20=EC=B2=A8=EB=B6=80=20=ED=81=AC?= =?UTF-8?q?=EA=B8=B0=EB=A5=BC=20=EB=94=94=EC=BD=94=EB=94=A9=20=EA=B8=B0?= =?UTF-8?q?=EC=A4=80=20=EC=B6=94=EC=A0=95=EA=B0=92=EC=9C=BC=EB=A1=9C=20?= =?UTF-8?q?=ED=91=9C=EC=8B=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit IMAP BODYSTRUCTURE 크기는 전송 인코딩 크기라 실제 파일보다 크게 보였다. base64 파트는 줄바꿈 오버헤드를 빼고 3/4로 환산한 추정 크기를 반환한다. --- apps/server/src/mail/attachments.ts | 9 ++++++++- apps/server/test/attachments.test.ts | 19 ++++++++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/apps/server/src/mail/attachments.ts b/apps/server/src/mail/attachments.ts index 97bc90f..936bbc5 100644 --- a/apps/server/src/mail/attachments.ts +++ b/apps/server/src/mail/attachments.ts @@ -2,6 +2,13 @@ import type { MessageStructureObject } from "imapflow"; import type { IncomingMessageAttachment } from "../domain/types.js"; // imapflow already decodes RFC 2231 / encoded-word names in the parameters. +// IMAP BODYSTRUCTURE size is the transfer-encoded size; estimate the decoded size for base64. +// shortcut: assumes 76-char lines + CRLF, quoted-printable keeps the encoded size. +export function estimateDecodedSize(size: number, encoding?: string): number { + if (encoding?.toLowerCase() !== "base64") return size; + return Math.floor(((size - Math.floor(size / 78) * 2) * 3) / 4); +} + export function extractAttachments( root: MessageStructureObject ): IncomingMessageAttachment[] { @@ -23,7 +30,7 @@ export function extractAttachments( filename || `attachment-${node.part}${type === "message/rfc822" ? ".eml" : ""}`, contentType: type, - size: node.size ?? 0 + size: estimateDecodedSize(node.size ?? 0, node.encoding) }); return; } diff --git a/apps/server/test/attachments.test.ts b/apps/server/test/attachments.test.ts index b5e7ba3..a69559f 100644 --- a/apps/server/test/attachments.test.ts +++ b/apps/server/test/attachments.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { extractAttachments } from "../src/mail/attachments.js"; +import { estimateDecodedSize, extractAttachments } from "../src/mail/attachments.js"; test("extracts attachment parts and skips body parts", () => { const result = extractAttachments({ @@ -134,3 +134,20 @@ test("attachment route streams the part with an encoded filename", async () => { 500 ); }); + +test("estimates decoded size for base64 parts only", () => { + // Real file was 3,655 bytes; IMAP reported 5,012 encoded bytes. + const decoded = estimateDecodedSize(5012, "base64"); + assert.equal(decoded, 3663); + assert.ok(Math.abs(decoded - 3655) / 3655 < 0.01); + assert.equal(estimateDecodedSize(5012, "quoted-printable"), 5012); + assert.equal(estimateDecodedSize(5012), 5012); + + const [att] = extractAttachments({ + type: "multipart/mixed", + childNodes: [ + { part: "1", type: "image/png", size: 5012, encoding: "BASE64", disposition: "attachment" } + ] + }); + assert.equal(att.size, 3663); +}); From 22bb0eaa052c5b9630d41463c554d63b15e77a15 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:08:39 +0900 Subject: [PATCH 8/8] =?UTF-8?q?=EB=8B=A8=EC=9D=BC=20=ED=8C=8C=ED=8A=B8=20?= =?UTF-8?q?=EC=B2=A8=EB=B6=80=EB=A5=BC=20=EB=85=B8=EC=B6=9C=ED=95=98?= =?UTF-8?q?=EA=B3=A0=20=ED=85=8D=EC=8A=A4=ED=8A=B8=20=EC=B2=A8=EB=B6=80?= =?UTF-8?q?=EB=A5=BC=20=EC=9B=90=EB=B3=B8=20=EB=B0=94=EC=9D=B4=ED=8A=B8?= =?UTF-8?q?=EB=A1=9C=20=EB=82=B4=EB=A0=A4=EB=B0=9B=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 본문 전체가 첨부인 단일 파트 메일의 루트를 part 1로 정규화해 목록·다운로드에 포함 - inline/무disposition text/plain·text/html 첨부는 ImapFlow download의 UTF-8 변환·format=flowed 해제를 피해 BODY[] 원문을 받아 전송 인코딩만 디코딩 --- apps/server/src/mail/ImapReceiver.ts | 31 +++++++++- apps/server/src/mail/attachments.ts | 52 ++++++++++++++++- apps/server/test/attachments.test.ts | 85 +++++++++++++++++++++++++++- 3 files changed, 163 insertions(+), 5 deletions(-) diff --git a/apps/server/src/mail/ImapReceiver.ts b/apps/server/src/mail/ImapReceiver.ts index 46ee15f..6ae96a1 100644 --- a/apps/server/src/mail/ImapReceiver.ts +++ b/apps/server/src/mail/ImapReceiver.ts @@ -24,7 +24,12 @@ import { newestFirstUidBatches } from "./imapSequenceRanges.js"; import { isAuthenticationFailure } from "./authenticationFailure.js"; -import { extractAttachments } from "./attachments.js"; +import { Readable } from "node:stream"; +import { + decodeTransferEncoding, + extractAttachments, + rawAttachmentFetch +} from "./attachments.js"; import { extractMessageLinks } from "./messageLinks.js"; import { createExistsQueue } from "./existsQueue.js"; @@ -246,6 +251,30 @@ export class ImapReceiver implements MailReceiver { return null; } + const raw = rawAttachmentFetch( + (message as FetchMessageObject).bodyStructure!, + part + ); + if (raw) { + // shortcut: buffers the whole text part in memory; stream it if large text attachments matter. + const fetched = await client.fetchOne( + providerMessageId, + { bodyParts: [raw.key] }, + { uid: true } + ); + const bytes = fetched ? fetched.bodyParts?.get(raw.key) : undefined; + if (!bytes) { + await close(); + return null; + } + return { + filename: attachment.filename, + contentType: attachment.contentType, + stream: Readable.from([decodeTransferEncoding(bytes, raw.encoding)]), + close + }; + } + const download = await client.download(providerMessageId, part, { uid: true }); diff --git a/apps/server/src/mail/attachments.ts b/apps/server/src/mail/attachments.ts index 936bbc5..8e19098 100644 --- a/apps/server/src/mail/attachments.ts +++ b/apps/server/src/mail/attachments.ts @@ -21,14 +21,16 @@ export function extractAttachments( node.disposition?.toLowerCase() === "attachment" || Boolean(filename); const type = node.type.toLowerCase(); const hasChildren = Boolean(node.childNodes?.length); + // ImapFlow gives a single-part message root no part number; its body is part "1". + const part = node.part ?? (node === root && !hasChildren ? "1" : undefined); // An attached message carries child parts, but the message itself is the attachment. - if (node.part && isAttachment && (!hasChildren || type === "message/rfc822")) { + if (part && isAttachment && (!hasChildren || type === "message/rfc822")) { found.push({ - part: node.part, + part, filename: filename || - `attachment-${node.part}${type === "message/rfc822" ? ".eml" : ""}`, + `attachment-${part}${type === "message/rfc822" ? ".eml" : ""}`, contentType: type, size: estimateDecodedSize(node.size ?? 0, node.encoding) }); @@ -40,3 +42,47 @@ export function extractAttachments( visit(root); return found; } + +function findPart( + root: MessageStructureObject, + part: string +): MessageStructureObject | undefined { + if (part === "1" && !root.part && !root.childNodes?.length) return root; + if (root.part === part) return root; + for (const child of root.childNodes ?? []) { + const found = findPart(child, part); + if (found) return found; + } + return undefined; +} + +// ImapFlow download() converts inline/undisposed text parts to UTF-8 and +// unwraps format=flowed (imapflow 1.4.3 lib/imap-flow.js), which alters the +// file. For those types, return the raw BODY[] key and its transfer encoding +// so the caller fetches and decodes the original bytes itself. +export function rawAttachmentFetch( + root: MessageStructureObject, + part: string +): { key: string; encoding?: string } | null { + const node = findPart(root, part); + const type = node?.type.toLowerCase(); + if (!node || !["text/plain", "text/html", "text/x-amp-html"].includes(type!)) { + return null; + } + return { + key: node === root && !root.part ? "text" : part, + encoding: node.encoding?.toLowerCase() + }; +} + +export function decodeTransferEncoding(raw: Buffer, encoding?: string): Buffer { + if (encoding === "base64") return Buffer.from(raw.toString("latin1"), "base64"); + if (encoding !== "quoted-printable") return raw; + const decoded = raw + .toString("latin1") + .replace(/=\r?\n/g, "") + .replace(/=([0-9A-Fa-f]{2})/g, (_, hex: string) => + String.fromCharCode(parseInt(hex, 16)) + ); + return Buffer.from(decoded, "latin1"); +} diff --git a/apps/server/test/attachments.test.ts b/apps/server/test/attachments.test.ts index a69559f..6805b68 100644 --- a/apps/server/test/attachments.test.ts +++ b/apps/server/test/attachments.test.ts @@ -1,6 +1,12 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { estimateDecodedSize, extractAttachments } from "../src/mail/attachments.js"; +import { + decodeTransferEncoding, + estimateDecodedSize, + extractAttachments, + rawAttachmentFetch +} from "../src/mail/attachments.js"; +import { ImapReceiver } from "../src/mail/ImapReceiver.js"; test("extracts attachment parts and skips body parts", () => { const result = extractAttachments({ @@ -151,3 +157,80 @@ test("estimates decoded size for base64 parts only", () => { }); assert.equal(att.size, 3663); }); + +test("exposes a single-part message whose whole body is an attachment as part 1", () => { + const root = { + type: "application/pdf", + size: 100, + disposition: "attachment", + dispositionParameters: { filename: "scan.pdf" } + }; + assert.deepEqual(extractAttachments(root), [ + { part: "1", filename: "scan.pdf", contentType: "application/pdf", size: 100 } + ]); + assert.deepEqual(extractAttachments({ type: "text/plain" }), []); +}); + +test("picks a raw fetch for text attachments ImapFlow would convert", () => { + const multipart = { + type: "multipart/mixed", + childNodes: [ + { part: "1", type: "text/plain" }, + { part: "2", type: "TEXT/PLAIN", encoding: "QUOTED-PRINTABLE", parameters: { name: "a.txt" } }, + { part: "3", type: "application/pdf", disposition: "attachment" } + ] + }; + assert.deepEqual(rawAttachmentFetch(multipart, "2"), { key: "2", encoding: "quoted-printable" }); + assert.equal(rawAttachmentFetch(multipart, "3"), null); + assert.deepEqual( + rawAttachmentFetch({ type: "text/html", encoding: "base64", parameters: { name: "p.html" } }, "1"), + { key: "text", encoding: "base64" } + ); +}); + +test("decodes only the transfer encoding and keeps charset bytes", () => { + // EUC-KR "가" is B0 A1; it must not be converted to UTF-8. + assert.deepEqual(decodeTransferEncoding(Buffer.from("=B0=A1 =\r\nx"), "quoted-printable"), Buffer.from([0xb0, 0xa1, 0x20, 0x78])); + assert.deepEqual(decodeTransferEncoding(Buffer.from("sKE=\r\n"), "base64"), Buffer.from([0xb0, 0xa1])); + const flowed = Buffer.from("line \r\nwrap"); + assert.deepEqual(decodeTransferEncoding(flowed, "7bit"), flowed); +}); + +test("downloadAttachment returns original bytes for named inline text parts", async () => { + const bodyStructure = { + type: "multipart/mixed", + childNodes: [ + { part: "1", type: "text/plain" }, + { + part: "2", + type: "text/plain", + encoding: "quoted-printable", + parameters: { name: "memo.txt", charset: "euc-kr", format: "flowed" } + } + ] + }; + const calls: string[] = []; + const client = { + connect: async () => undefined, + logout: async () => undefined, + mailboxOpen: async () => undefined, + fetchOne: async (_uid: string, query: { bodyParts?: string[] }) => + query.bodyParts + ? { bodyParts: new Map([[query.bodyParts[0], Buffer.from("=B0=A1 =\r\nx")]]) } + : { bodyStructure }, + download: async () => { + calls.push("download"); + return { content: null }; + } + }; + const receiver = Object.assign(new ImapReceiver({} as never, {} as never), { + createClient: async () => client + }); + const result = await receiver.downloadAttachment({} as never, "INBOX", "7", "2"); + assert.ok(result); + const chunks: Buffer[] = []; + for await (const chunk of result.stream) chunks.push(chunk as Buffer); + assert.deepEqual(Buffer.concat(chunks), Buffer.from([0xb0, 0xa1, 0x20, 0x78])); + assert.deepEqual(calls, []); + await result.close(); +});