diff --git a/apps/client/lib/core/i18n/language_controller.dart b/apps/client/lib/core/i18n/language_controller.dart index e1f1657..013abaa 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -197,6 +197,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 09e6c14..f734462 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'; import 'reply_draft.dart'; @@ -79,6 +80,12 @@ class MessagePage extends ConsumerWidget { Text(item.receivedAtLabel), const Divider(height: 32), LinkedMessageBody(body: item.body, links: item.links), + if (item.attachments.isNotEmpty) + 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 900bf00..38cc545 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'; @@ -94,6 +96,28 @@ class MailApiClient { return MessageDetail.fromJson(response.data ?? {}); } + Future downloadAttachment({ + required String accountId, + required String messageId, + required String part, + required String savePath, + }) async { + // 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.copy(savePath); + } finally { + await tempDir.delete(recursive: true); + } + } + Future addAccount({ required String providerId, required String emailAddress, @@ -307,6 +331,7 @@ class MessageDetail { required this.body, required this.links, required this.receivedAtLabel, + this.attachments = const [], this.receivedAt, this.accountId, this.messageId, @@ -328,6 +353,7 @@ class MessageDetail { final String body; final List links; final String receivedAtLabel; + final List attachments; final DateTime? receivedAt; factory MessageDetail.fromJson(Map json) { @@ -341,6 +367,10 @@ 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), receivedAt: DateTime.tryParse(json['receivedAt'] as String? ?? '')?.toLocal(), accountId: json['accountId'] as String?, @@ -353,6 +383,41 @@ class MessageDetail { } } +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]}'; +} + List _strings(Object? value) => (value as List? ?? const []).whereType().toList(); diff --git a/apps/client/macos/Flutter/GeneratedPluginRegistrant.swift b/apps/client/macos/Flutter/GeneratedPluginRegistrant.swift index 997e35d..21ae5af 100644 --- a/apps/client/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/apps/client/macos/Flutter/GeneratedPluginRegistrant.swift @@ -5,10 +5,12 @@ import FlutterMacOS import Foundation +import file_selector_macos import shared_preferences_foundation import url_launcher_macos func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) 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 328624d..abbf755 100644 --- a/apps/client/pubspec.lock +++ b/apps/client/pubspec.lock @@ -49,6 +49,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: @@ -97,6 +105,70 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.1" + 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 @@ -141,6 +213,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 b447f78..f72b039 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 shared_preferences: ^2.5.6 dev_dependencies: diff --git a/apps/client/test/widget_test.dart b/apps/client/test/widget_test.dart index 3c3d15d..a58e312 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:io'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; @@ -14,6 +15,42 @@ 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); + }); + + 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); + }); + test('replySubject adds Re: once', () { expect(replySubject('Hello'), 'Re: Hello'); expect(replySubject('Re: Hello'), 'Re: Hello'); @@ -606,6 +643,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/.env.example b/apps/server/.env.example index de42ced..32bff7c 100644 --- a/apps/server/.env.example +++ b/apps/server/.env.example @@ -17,5 +17,7 @@ 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 # UNSAFE until user auth exists (#20): lets non-loopback callers search mail and read unfetched message bodies. ALLOW_REMOTE_MAIL_SEARCH=false diff --git a/apps/server/package.json b/apps/server/package.json index e62ea47..bbeab43 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/searchQuery.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts test/mailSearchAccess.test.ts test/replyRecipients.test.ts test/existsQueue.test.ts test/pop3Unsupported.test.ts test/deletedAccountSync.test.ts test/oauthSessionExpiry.test.ts test/noopPushNotifier.test.ts test/serverExposure.test.ts test/uidValidity.test.ts test/accountScopedMessage.test.ts test/customServerAccount.test.ts", + "test": "tsx --test test/imapSequenceRanges.test.ts test/mailSyncWorker.test.ts test/accountValidate.test.ts test/accountReconnect.test.ts test/searchQuery.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts test/attachments.test.ts test/attachmentAccess.test.ts test/mailSearchAccess.test.ts test/replyRecipients.test.ts test/existsQueue.test.ts test/pop3Unsupported.test.ts test/deletedAccountSync.test.ts test/oauthSessionExpiry.test.ts test/noopPushNotifier.test.ts test/serverExposure.test.ts test/uidValidity.test.ts test/accountScopedMessage.test.ts test/customServerAccount.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 337c993..eade75c 100644 --- a/apps/server/src/api/routes.ts +++ b/apps/server/src/api/routes.ts @@ -4,6 +4,7 @@ import { z } from "zod"; import type { SearchObject } from "imapflow"; import type { MailSender } from "../mail/MailSender.js"; import type { + AttachmentDownload, AuthMode, IncomingMessageContent, IncomingMessageSummary, @@ -91,18 +92,29 @@ const accountSchema = z.object({ const demoUserId = "demo-user"; -// shortcut: no real auth yet (issue #20), so mail search and the IMAP -// fallback require a loopback peer, a loopback Host (blocks DNS rebinding) and -// no Origin header (browsers send one, the native client does not), unless -// ALLOW_REMOTE_MAIL_SEARCH=true. -function canReadUnstoredMail(request: FastifyRequest): boolean { - if (process.env.ALLOW_REMOTE_MAIL_SEARCH === "true") return true; +// shortcut: no real auth yet (issue #20), so mail search, the IMAP fallback +// and attachment downloads require a loopback peer, a loopback Host (blocks +// DNS rebinding) and no Origin header (browsers send one, the native client +// does not), unless their opt-out flag is "true". +function isLocalMailRequest( + request: FastifyRequest, + optOutFlag: "ALLOW_REMOTE_MAIL_SEARCH" | "ALLOW_REMOTE_MAIL_ACCESS" +): boolean { + if (process.env[optOutFlag] === "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; } +function canReadUnstoredMail(request: FastifyRequest): boolean { + return isLocalMailRequest(request, "ALLOW_REMOTE_MAIL_SEARCH"); +} + +function canReadAttachments(request: FastifyRequest): boolean { + return isLocalMailRequest(request, "ALLOW_REMOTE_MAIL_ACCESS"); +} + export async function registerRoutes( app: FastifyInstance, deps: { @@ -113,6 +125,11 @@ export async function registerRoutes( account: MailAccount, message: IncomingMessageSummary ) => Promise; + downloadAttachment: ( + account: MailAccount, + message: IncomingMessageSummary, + part: string + ) => Promise; searchMessages: ( account: MailAccount, query: SearchObject @@ -398,10 +415,64 @@ export async function registerRoutes( body: content.text, bodyTruncated: content.truncated, bodyLinks: content.links, + attachments: content.attachments, ...replyFields(message, content, account) }; }); + app.get( + "/accounts/:accountId/messages/:messageId/attachments/:part", + async (request, reply) => { + if (!canReadAttachments(request)) { + return reply.code(403).send({ error: "Attachments are only available locally." }); + } + 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); + // Search results can point at mail that was never imported; this route + // is already local-only, and canReadUnstoredMail keeps the search gate. + const message = messages.find( + (item) => item.accountId === params.accountId && + item.providerMessageId === params.messageId + ) ?? (account.incomingProtocol === "imap" && canReadUnstoredMail(request) + ? await deps.fetchMessageSummary(account, params.messageId) + : null); + 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) => ({ diff --git a/apps/server/src/domain/types.ts b/apps/server/src/domain/types.ts index 6b70c8a..48b8afd 100644 --- a/apps/server/src/domain/types.ts +++ b/apps/server/src/domain/types.ts @@ -92,11 +92,27 @@ export interface IncomingMessageContent { text: string; truncated: boolean; links: IncomingMessageLink[]; + attachments: IncomingMessageAttachment[]; // Read from the server on each body fetch, so messages saved before reply // support still get a Message-ID without a stored-data migration. thread?: MessageThreadHeaders; } +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 MessageThreadHeaders { messageId?: string; references: string[]; diff --git a/apps/server/src/mail/ImapReceiver.ts b/apps/server/src/mail/ImapReceiver.ts index 03f0543..352af46 100644 --- a/apps/server/src/mail/ImapReceiver.ts +++ b/apps/server/src/mail/ImapReceiver.ts @@ -7,6 +7,8 @@ import type { import { simpleParser } from "mailparser"; import type { OAuthTokenManager } from "../auth/OAuthTokenManager.js"; import type { + AttachmentDownload, + IncomingMessageAttachment, IncomingMessageContent, IncomingMessageLink, IncomingMessageSummary, @@ -27,6 +29,12 @@ import { newestFirstUidBatches } from "./imapSequenceRanges.js"; import { isAuthenticationFailure } from "./authenticationFailure.js"; +import { Readable } from "node:stream"; +import { + decodeTransferEncoding, + extractAttachments, + rawAttachmentFetch +} from "./attachments.js"; import { extractMessageLinks } from "./messageLinks.js"; import { createExistsQueue } from "./existsQueue.js"; @@ -194,6 +202,7 @@ export class ImapReceiver implements MailReceiver { throw new Error("Message body was not found on the IMAP server."); } + const attachments = extractAttachments(message.bodyStructure); const thread = toThreadHeaders(message); const bodyParts = selectBodyParts(message.bodyStructure); let htmlFallback: IncomingMessageContent | null = null; @@ -214,7 +223,9 @@ export class ImapReceiver implements MailReceiver { if (bodyPart.type.toLowerCase() !== "text/html") { const text = cleanMessageText(decoded); - if (text) return { text, truncated, links: htmlLinks, thread }; + if (text) { + return { text, truncated, links: htmlLinks, attachments, thread }; + } continue; } @@ -241,18 +252,88 @@ export class ImapReceiver implements MailReceiver { text, truncated, links: htmlLinks, + attachments, thread }; } } if (htmlFallback) return { ...htmlFallback, links: htmlLinks }; - return { text: "", truncated: false, links: [], thread }; + return { text: "", truncated: false, links: [], attachments, thread }; } 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 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 + }); + 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 b28f252..4832530 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 @@ -37,4 +38,13 @@ export class Pop3Receiver implements MailReceiver { ): Promise { throw pop3Unsupported(); } + + async downloadAttachment( + _account: MailAccount, + _mailbox: string, + _providerMessageId: string, + _part: string + ): Promise { + throw pop3Unsupported(); + } } diff --git a/apps/server/src/mail/attachments.ts b/apps/server/src/mail/attachments.ts new file mode 100644 index 0000000..8e19098 --- /dev/null +++ b/apps/server/src/mail/attachments.ts @@ -0,0 +1,88 @@ +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[] { + const found: IncomingMessageAttachment[] = []; + + const visit = (node: MessageStructureObject): void => { + const filename = + node.dispositionParameters?.filename ?? node.parameters?.name; + const isAttachment = + 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 (part && isAttachment && (!hasChildren || type === "message/rfc822")) { + found.push({ + part, + filename: + filename || + `attachment-${part}${type === "message/rfc822" ? ".eml" : ""}`, + contentType: type, + size: estimateDecodedSize(node.size ?? 0, node.encoding) + }); + return; + } + for (const child of node.childNodes ?? []) visit(child); + }; + + 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/src/server.ts b/apps/server/src/server.ts index bf569c0..00596c0 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -66,6 +66,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 + ); + }, searchMessages: async (account, query) => imap.search(account, query), fetchMessageSummary: async (account, providerMessageId) => imap.fetchSummary(account, "INBOX", providerMessageId), 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 765b969..e1ae571 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/attachmentAccess.test.ts b/apps/server/test/attachmentAccess.test.ts new file mode 100644 index 0000000..0e2a047 --- /dev/null +++ b/apps/server/test/attachmentAccess.test.ts @@ -0,0 +1,102 @@ +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, + fetchMessageSummary: async (_account: unknown, id: string) => id === "9" + ? { accountId: "a1", providerMessageId: "9", mailbox: "INBOX", from: "", subject: "", receivedAt: now, hasAttachments: true } + : null, + 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("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 { + 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; + } +}); + +test("unimported search results download locally but stay behind the search gate", async () => { + const unstored = "/accounts/a1/messages/9/attachments/2"; + const { app } = await build(); + assert.equal((await app.inject({ url: unstored, remoteAddress: "127.0.0.1" })).statusCode, 200); + process.env.ALLOW_REMOTE_MAIL_ACCESS = "true"; + try { + const res = await app.inject({ url: unstored, remoteAddress: "192.168.0.5" }); + assert.equal(res.statusCode, 404); + } finally { + delete process.env.ALLOW_REMOTE_MAIL_ACCESS; + } +}); diff --git a/apps/server/test/attachments.test.ts b/apps/server/test/attachments.test.ts new file mode 100644 index 0000000..6805b68 --- /dev/null +++ b/apps/server/test/attachments.test.ts @@ -0,0 +1,236 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +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({ + 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("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"); + 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 + ); +}); + +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); +}); + +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(); +});