From c194551044aaec0915e372a9a8e6cc3e71c079ba Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:43:37 +0900 Subject: [PATCH 1/5] =?UTF-8?q?=EA=B3=84=EC=A0=95=EB=B3=84=20IMAP=20?= =?UTF-8?q?=EB=A9=94=EC=9D=BC=20=EA=B2=80=EC=83=89=20=EC=B6=94=EA=B0=80=20?= =?UTF-8?q?(=EB=B3=B4=EB=82=B8=20=EC=82=AC=EB=9E=8C=C2=B7=EC=A0=9C?= =?UTF-8?q?=EB=AA=A9=C2=B7=EA=B8=B0=EA=B0=84)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/core/i18n/language_controller.dart | 7 + .../accounts/account_mailbox_page.dart | 224 +++++++++++------- apps/client/lib/services/mail_api_client.dart | 15 ++ apps/client/test/widget_test.dart | 5 +- apps/server/package.json | 2 +- apps/server/src/api/routes.ts | 49 +++- apps/server/src/mail/ImapReceiver.ts | 38 ++- apps/server/src/mail/searchQuery.ts | 74 ++++++ apps/server/src/server.ts | 3 + apps/server/test/searchQuery.test.ts | 37 +++ 10 files changed, 369 insertions(+), 85 deletions(-) create mode 100644 apps/server/src/mail/searchQuery.ts create mode 100644 apps/server/test/searchQuery.test.ts diff --git a/apps/client/lib/core/i18n/language_controller.dart b/apps/client/lib/core/i18n/language_controller.dart index 443bb5f..b224dff 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -125,6 +125,13 @@ class AppStrings { String get syncRange => _ko ? '동기화 범위' : 'Sync range'; String get comingSoon => _ko ? '준비 중' : 'Coming soon'; String get noAccountSelected => _ko ? '계정을 선택하세요' : 'Select an account'; + String get searchMail => _ko ? '메일 검색' : 'Search mail'; + String get searchHint => _ko + ? '검색: 제목·보낸 사람, from: subject: after: before:' + : 'Search subject or sender, from: subject: after: before:'; + String get clearSearch => _ko ? '검색 지우기' : 'Clear search'; + String get noSearchResults => _ko ? '검색 결과가 없습니다' : 'No messages found'; + String get searchFailedTitle => _ko ? '검색하지 못했습니다' : 'Search failed'; String get noMessagesForAccount => _ko ? '이 계정에 표시할 메일이 없습니다' : 'No mail for this account yet'; String get loadingAccountMail => _ko ? '메일을 가져오는 중입니다' : 'Importing mail'; diff --git a/apps/client/lib/features/accounts/account_mailbox_page.dart b/apps/client/lib/features/accounts/account_mailbox_page.dart index ed0617e..622fa85 100644 --- a/apps/client/lib/features/accounts/account_mailbox_page.dart +++ b/apps/client/lib/features/accounts/account_mailbox_page.dart @@ -11,10 +11,7 @@ import 'account_providers.dart'; import 'accounts_page.dart' show reconnectAccount; class AccountMailboxPage extends ConsumerWidget { - const AccountMailboxPage({ - super.key, - required this.accountId, - }); + const AccountMailboxPage({super.key, required this.accountId}); final String accountId; @@ -43,9 +40,8 @@ class AccountMailboxPage extends ConsumerWidget { return _MailboxContent(account: account); }, loading: () => const Center(child: CircularProgressIndicator()), - error: (error, stackTrace) => Center( - child: Text(strings.accountLoadFailedTitle), - ), + error: (error, stackTrace) => + Center(child: Text(strings.accountLoadFailedTitle)), ), ); } @@ -63,6 +59,8 @@ class _MailboxContent extends ConsumerStatefulWidget { class _MailboxContentState extends ConsumerState<_MailboxContent> { Timer? _refreshTimer; bool _refreshing = false; + final _searchController = TextEditingController(); + Future>? _search; bool get _isSyncing => const {'syncing', 'validating'}.contains(widget.account.syncStatus); @@ -76,8 +74,10 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { @override void didUpdateWidget(covariant _MailboxContent oldWidget) { super.didUpdateWidget(oldWidget); - final wasSyncing = - const {'syncing', 'validating'}.contains(oldWidget.account.syncStatus); + final wasSyncing = const { + 'syncing', + 'validating', + }.contains(oldWidget.account.syncStatus); if (oldWidget.account.id == widget.account.id && wasSyncing && !_isSyncing) { @@ -96,9 +96,26 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { @override void dispose() { _refreshTimer?.cancel(); + _searchController.dispose(); super.dispose(); } + void _runSearch(String value) { + final query = value.trim(); + setState(() { + _search = query.isEmpty + ? null + : ref + .read(mailApiClientProvider) + .searchAccountMessages(widget.account.id, query); + }); + } + + void _clearSearch() { + _searchController.clear(); + setState(() => _search = null); + } + void _configureRefreshTimer() { if (_isSyncing) { if (_refreshTimer == null && !_refreshing) _scheduleRefresh(); @@ -134,6 +151,40 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { if (mounted && _isSyncing && _refreshTimer == null) _scheduleRefresh(); } + Widget _messageList(List items) { + final account = widget.account; + return ListView.separated( + itemCount: items.length, + separatorBuilder: (context, index) => const Divider(height: 1), + itemBuilder: (context, index) { + final message = items[index]; + return ListTile( + minLeadingWidth: 28, + leading: Icon( + message.unread + ? Icons.mark_email_unread_outlined + : Icons.mail_outline, + ), + title: Text( + message.subject, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + subtitle: Text( + '${message.sender}\n${message.snippet}', + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + trailing: Text(message.receivedAtLabel), + onTap: () => context.go( + '/accounts/${account.id}/messages/${Uri.encodeComponent(message.id)}', + extra: const {'disableTransition': true}, + ), + ); + }, + ); + } + @override Widget build(BuildContext context) { final account = widget.account; @@ -189,82 +240,93 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { ), ], ), - Expanded( - child: messages.when( - data: (items) { - if (items.isEmpty) { - return Center( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - if (_isSyncing) - const SizedBox.square( - dimension: 44, - child: CircularProgressIndicator(strokeWidth: 3), - ) - else - Icon( - Icons.inbox_outlined, - size: 56, - color: Theme.of(context).colorScheme.secondary, - ), - const SizedBox(height: 16), - Text( - _isSyncing - ? strings.loadingAccountMail - : strings.noMessagesForAccount, - style: Theme.of(context).textTheme.titleLarge, - textAlign: TextAlign.center, - ), - if (_isSyncing) ...[ - const SizedBox(height: 8), - Text( - strings.loadingAccountMailDescription, - textAlign: TextAlign.center, - ), - ], - ], - ), - ); - } - - return ListView.separated( - itemCount: items.length, - separatorBuilder: (context, index) => const Divider(height: 1), - itemBuilder: (context, index) { - final message = items[index]; - return ListTile( - minLeadingWidth: 28, - leading: Icon( - message.unread - ? Icons.mark_email_unread_outlined - : Icons.mail_outline, - ), - title: Text( - message.subject, - maxLines: 1, - overflow: TextOverflow.ellipsis, + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), + child: TextField( + controller: _searchController, + textInputAction: TextInputAction.search, + onSubmitted: _runSearch, + decoration: InputDecoration( + isDense: true, + border: const OutlineInputBorder(), + prefixIcon: const Icon(Icons.search), + hintText: strings.searchHint, + suffixIcon: _search == null + ? null + : IconButton( + tooltip: strings.clearSearch, + onPressed: _clearSearch, + icon: const Icon(Icons.close), ), - subtitle: Text( - '${message.sender}\n${message.snippet}', - maxLines: 2, - overflow: TextOverflow.ellipsis, - ), - trailing: Text(message.receivedAtLabel), - onTap: () => context.go( - '/accounts/${account.id}/messages/${Uri.encodeComponent(message.id)}', - extra: const {'disableTransition': true}, - ), - ); - }, - ); - }, - loading: () => const Center(child: CircularProgressIndicator()), - error: (error, stackTrace) => Center( - child: Text(strings.mailLoadFailedTitle), ), ), ), + Expanded( + child: _search != null + ? FutureBuilder>( + future: _search, + builder: (context, snapshot) { + if (snapshot.hasError) { + return Center(child: Text(strings.searchFailedTitle)); + } + final results = snapshot.data; + if (results == null) { + return const Center(child: CircularProgressIndicator()); + } + if (results.isEmpty) { + return Center(child: Text(strings.noSearchResults)); + } + return _messageList(results); + }, + ) + : messages.when( + data: (items) { + if (items.isEmpty) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (_isSyncing) + const SizedBox.square( + dimension: 44, + child: CircularProgressIndicator( + strokeWidth: 3, + ), + ) + else + Icon( + Icons.inbox_outlined, + size: 56, + color: Theme.of(context).colorScheme.secondary, + ), + const SizedBox(height: 16), + Text( + _isSyncing + ? strings.loadingAccountMail + : strings.noMessagesForAccount, + style: Theme.of(context).textTheme.titleLarge, + textAlign: TextAlign.center, + ), + if (_isSyncing) ...[ + const SizedBox(height: 8), + Text( + strings.loadingAccountMailDescription, + textAlign: TextAlign.center, + ), + ], + ], + ), + ); + } + + return _messageList(items); + }, + loading: () => + const Center(child: CircularProgressIndicator()), + error: (error, stackTrace) => + Center(child: Text(strings.mailLoadFailedTitle)), + ), + ), ], ); } diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index 721252c..abff854 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -59,6 +59,21 @@ class MailApiClient { .toList(); } + Future> searchAccountMessages( + String accountId, + String query, + ) async { + final response = await _dio.get>( + '/accounts/$accountId/search', + queryParameters: {'q': query}, + options: Options(receiveTimeout: const Duration(seconds: 60)), + ); + final data = response.data ?? []; + return data + .map((item) => MailSummary.fromJson(item as Map)) + .toList(); + } + Future> fetchAccounts() async { final response = await _dio.get>('/accounts'); final data = response.data ?? []; diff --git a/apps/client/test/widget_test.dart b/apps/client/test/widget_test.dart index 52f8487..496fa39 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -328,7 +328,10 @@ void main() { final loadsBeforeReconnect = messageLoads; await tester.tap(find.widgetWithText(TextButton, '다시 연결')); await tester.pumpAndSettle(); - await tester.enterText(find.byType(TextField), 'new-app-password'); + await tester.enterText( + find.descendant( + of: find.byType(AlertDialog), matching: find.byType(TextField)), + 'new-app-password'); await tester.tap(find.widgetWithText(FilledButton, '다시 연결')); await tester.pumpAndSettle(); diff --git a/apps/server/package.json b/apps/server/package.json index 982da57..98c4fb6 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/searchQuery.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.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..5b5109a 100644 --- a/apps/server/src/api/routes.ts +++ b/apps/server/src/api/routes.ts @@ -1,6 +1,7 @@ import type { FastifyInstance } from "fastify"; import { randomUUID } from "node:crypto"; import { z } from "zod"; +import type { SearchObject } from "imapflow"; import type { MailSender } from "../mail/MailSender.js"; import type { AuthMode, @@ -17,6 +18,11 @@ import { applySyncFailure, isAuthenticationFailure } from "../mail/authenticationFailure.js"; +import { + SearchQueryError, + parseSearchQuery, + toImapSearch +} from "../mail/searchQuery.js"; const sendSchema = z.object({ accountId: z.string(), @@ -83,6 +89,14 @@ export async function registerRoutes( account: MailAccount, message: IncomingMessageSummary ) => Promise; + searchMessages: ( + account: MailAccount, + query: SearchObject + ) => Promise; + fetchMessageSummary: ( + account: MailAccount, + providerMessageId: string + ) => Promise; startAccountSync: (account: MailAccount) => Promise; resumeAccountSync: (account: MailAccount) => Promise; stopAccountSync: (accountId: string) => Promise; @@ -274,6 +288,36 @@ export async function registerRoutes( })); }); + app.get("/accounts/:id/search", async (request, reply) => { + const params = z.object({ id: z.string() }).parse(request.params); + const { q } = z.object({ q: z.string().max(500) }).parse(request.query); + const account = await deps.accounts.getAccount(params.id); + + if (!account || account.userId !== demoUserId) { + return reply.code(404).send({ error: "Account not found" }); + } + if (account.incomingProtocol !== "imap") { + return reply.code(400).send({ error: "Search needs an IMAP account." }); + } + + let query: SearchObject; + try { + query = toImapSearch(parseSearchQuery(q)); + } catch (error) { + if (error instanceof SearchQueryError) { + return reply.code(400).send({ error: error.message }); + } + throw error; + } + + const messages = await deps.searchMessages(account, query); + return messages.map((message) => ({ + ...message, + id: message.providerMessageId, + receivedAt: message.receivedAt.toISOString() + })); + }); + app.get("/accounts/:accountId/messages/:messageId", async (request, reply) => { const params = z.object({ accountId: z.string(), @@ -286,10 +330,13 @@ export async function registerRoutes( } const messages = await deps.accounts.listInbox(demoUserId); + // Search results can point at mail that was never imported. const message = messages.find( (item) => item.accountId === params.accountId && item.providerMessageId === params.messageId - ); + ) ?? (account.incomingProtocol === "imap" + ? await deps.fetchMessageSummary(account, params.messageId) + : null); if (!message) { return reply.code(404).send({ error: "Message not found" }); } diff --git a/apps/server/src/mail/ImapReceiver.ts b/apps/server/src/mail/ImapReceiver.ts index 4160d89..2950ad8 100644 --- a/apps/server/src/mail/ImapReceiver.ts +++ b/apps/server/src/mail/ImapReceiver.ts @@ -1,5 +1,9 @@ import { ImapFlow } from "imapflow"; -import type { FetchMessageObject, MessageStructureObject } from "imapflow"; +import type { + FetchMessageObject, + MessageStructureObject, + SearchObject +} from "imapflow"; import { simpleParser } from "mailparser"; import type { OAuthTokenManager } from "../auth/OAuthTokenManager.js"; import type { @@ -103,6 +107,38 @@ export class ImapReceiver implements MailReceiver { } } + // Searches the server, so messages that were never imported are found too. + async search( + account: MailAccount, + query: SearchObject, + limit = 50 + ): Promise { + return this.withConnectedClient(account, async (client) => { + await client.mailboxOpen("INBOX", { readOnly: true }); + const found = (await client.search(query, { uid: true })) || []; + const newest = found.sort((a, b) => b - a).slice(0, limit); + if (newest.length === 0) return []; + const summaries = await this.fetchUids(client, account, "INBOX", newest); + return summaries.sort( + (a, b) => b.receivedAt.getTime() - a.receivedAt.getTime() + ); + }); + } + + async fetchSummary( + account: MailAccount, + mailbox: string, + providerMessageId: string + ): Promise { + const uid = Number(providerMessageId); + if (!Number.isInteger(uid) || uid <= 0) return null; + return this.withConnectedClient(account, async (client) => { + await client.mailboxOpen(mailbox, { readOnly: true }); + const [summary] = await this.fetchUids(client, account, mailbox, [uid]); + return summary ?? null; + }); + } + async fetchMessageContent( account: MailAccount, mailbox: string, diff --git a/apps/server/src/mail/searchQuery.ts b/apps/server/src/mail/searchQuery.ts new file mode 100644 index 0000000..94c543b --- /dev/null +++ b/apps/server/src/mail/searchQuery.ts @@ -0,0 +1,74 @@ +import type { SearchObject } from "imapflow"; + +export interface ParsedSearchQuery { + from?: string; + subject?: string; + after?: Date; + before?: Date; + text?: string; +} + +export class SearchQueryError extends Error {} + +// Tokens are `key:value`, `key:"quoted value"`, `"quoted text"` or a bare word. +const tokenPattern = /(?:(\w+):)?(?:"([^"]*)"|(\S+))/g; + +function parseDate(value: string): Date { + const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value); + const date = match + ? new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]))) + : null; + if (!date || Number.isNaN(date.getTime()) || + date.toISOString().slice(0, 10) !== value) { + throw new SearchQueryError(`Invalid date: ${value} (use YYYY-MM-DD)`); + } + return date; +} + +export function parseSearchQuery(query: string): ParsedSearchQuery { + const parsed: ParsedSearchQuery = {}; + const words: string[] = []; + + for (const match of query.matchAll(tokenPattern)) { + const key = match[1]?.toLowerCase(); + const value = match[2] ?? match[3] ?? ""; + switch (key) { + case "from": + parsed.from = value; + break; + case "subject": + parsed.subject = value; + break; + case "after": + parsed.after = parseDate(value); + break; + case "before": + parsed.before = parseDate(value); + break; + default: + // Unknown `key:` is left as text, e.g. a URL or time like 10:30. + words.push(key ? `${match[1]}:${value}` : value); + } + } + + const text = words.join(" ").trim(); + if (text) parsed.text = text; + if (!parsed.from && !parsed.subject && !parsed.after && !parsed.before && + !parsed.text) { + throw new SearchQueryError("Search query is empty"); + } + return parsed; +} + +// Plain text matches the subject OR the sender; every other condition is ANDed. +export function toImapSearch(parsed: ParsedSearchQuery): SearchObject { + const search: SearchObject = {}; + if (parsed.from) search.from = parsed.from; + if (parsed.subject) search.subject = parsed.subject; + if (parsed.after) search.since = parsed.after; + if (parsed.before) search.before = parsed.before; + if (parsed.text) { + search.or = [{ subject: parsed.text }, { from: parsed.text }]; + } + return search; +} diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 47ce656..88e7fe0 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -68,6 +68,9 @@ await registerRoutes(app, { message.providerMessageId ); }, + searchMessages: async (account, query) => imap.search(account, query), + fetchMessageSummary: async (account, providerMessageId) => + imap.fetchSummary(account, "INBOX", providerMessageId), startAccountSync: async (account) => worker.startAccount(account), resumeAccountSync: async (account) => worker.resumeAccount(account), stopAccountSync: async (accountId) => worker.stopAccount(accountId) diff --git a/apps/server/test/searchQuery.test.ts b/apps/server/test/searchQuery.test.ts new file mode 100644 index 0000000..c95fb1c --- /dev/null +++ b/apps/server/test/searchQuery.test.ts @@ -0,0 +1,37 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + SearchQueryError, + parseSearchQuery, + toImapSearch +} from "../src/mail/searchQuery.js"; + +test("plain text searches subject or sender", () => { + assert.deepEqual(toImapSearch(parseSearchQuery("invoice march")), { + or: [{ subject: "invoice march" }, { from: "invoice march" }] + }); +}); + +test("parses operators with quotes and combines them", () => { + const search = toImapSearch( + parseSearchQuery('from:alice@example.com subject:"주간 보고" after:2026-01-02 before:2026-02-01') + ); + assert.equal(search.from, "alice@example.com"); + assert.equal(search.subject, "주간 보고"); + assert.equal((search.since as Date).toISOString(), "2026-01-02T00:00:00.000Z"); + assert.equal((search.before as Date).toISOString(), "2026-02-01T00:00:00.000Z"); + assert.equal(search.or, undefined); +}); + +test("keeps unknown operators as text and mixes them with operators", () => { + assert.deepEqual(parseSearchQuery("from:bob 10:30 lunch"), { + from: "bob", + text: "10:30 lunch" + }); +}); + +test("rejects empty queries and invalid dates", () => { + assert.throws(() => parseSearchQuery(" "), SearchQueryError); + assert.throws(() => parseSearchQuery("before:2026-02-31"), SearchQueryError); + assert.throws(() => parseSearchQuery("after:yesterday"), SearchQueryError); +}); From a83fd39e58cb65802827f221458eab956eb1b720 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:47:39 +0900 Subject: [PATCH 2/5] =?UTF-8?q?=EA=B3=84=EC=A0=95=EC=9D=84=20=EB=B0=94?= =?UTF-8?q?=EA=BE=B8=EB=A9=B4=20=EC=9D=B4=EC=A0=84=20=EA=B3=84=EC=A0=95?= =?UTF-8?q?=EC=9D=98=20=EA=B2=80=EC=83=89=20=EA=B2=B0=EA=B3=BC=EC=99=80=20?= =?UTF-8?q?=EA=B2=80=EC=83=89=EC=96=B4=EB=A5=BC=20=EC=A7=80=EC=9B=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../accounts/account_mailbox_page.dart | 6 ++ apps/client/test/widget_test.dart | 82 +++++++++++++++++++ 2 files changed, 88 insertions(+) diff --git a/apps/client/lib/features/accounts/account_mailbox_page.dart b/apps/client/lib/features/accounts/account_mailbox_page.dart index 622fa85..7a86933 100644 --- a/apps/client/lib/features/accounts/account_mailbox_page.dart +++ b/apps/client/lib/features/accounts/account_mailbox_page.dart @@ -74,6 +74,12 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { @override void didUpdateWidget(covariant _MailboxContent oldWidget) { super.didUpdateWidget(oldWidget); + if (oldWidget.account.id != widget.account.id) { + // Search results belong to the previous account; their UIDs are not + // valid for the newly selected one. + _searchController.clear(); + _search = null; + } final wasSyncing = const { 'syncing', 'validating', diff --git a/apps/client/test/widget_test.dart b/apps/client/test/widget_test.dart index 496fa39..b5ed0ff 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -96,6 +96,65 @@ void main() { expect(find.text(account.emailAddress), findsWidgets); }); + testWidgets('clears search results when switching to another account', + (WidgetTester tester) async { + const first = MailAccountSummary( + id: 'account-a', + providerId: 'gmail', + emailAddress: 'first@example.com', + incomingProtocol: 'imap', + authMode: 'oauth2', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'now', + ); + const second = MailAccountSummary( + id: 'account-b', + providerId: 'gmail', + emailAddress: 'second@example.com', + incomingProtocol: 'imap', + authMode: 'oauth2', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'now', + ); + final api = _SearchApi(); + await tester.binding.setSurfaceSize(const Size(1200, 800)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + mailApiClientProvider.overrideWithValue(api), + accountsProvider.overrideWith((ref) async => const [first, second]), + providersProvider.overrideWith((ref) async => const []), + accountMessagesProvider.overrideWith((ref, accountId) async => const []), + ], + child: const DailyPostBoxApp(), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text(first.emailAddress).first); + await tester.pumpAndSettle(); + final searchField = find.descendant( + of: find.byType(Scaffold).last, + matching: find.byType(TextField), + ); + await tester.enterText(searchField.first, 'invoice'); + await tester.testTextInput.receiveAction(TextInputAction.search); + await tester.pumpAndSettle(); + expect(find.text(_SearchApi.resultSubject), findsOneWidget); + + await tester.tap(find.text(second.emailAddress).first); + await tester.pumpAndSettle(); + + expect(find.text(_SearchApi.resultSubject), findsNothing); + expect(find.text('invoice'), findsNothing); + }); + testWidgets('shows a progressive loading state during account sync', (WidgetTester tester) async { const account = MailAccountSummary( @@ -509,6 +568,29 @@ void main() { }); } +class _SearchApi extends MailApiClient { + _SearchApi() : super(baseUrl: 'http://127.0.0.1:1'); + + static const resultSubject = '첫 계정 검색 결과'; + + @override + Future> searchAccountMessages( + String accountId, + String query, + ) async { + return [ + const MailSummary( + id: 'uid-1', + sender: 'billing@example.com', + subject: resultSubject, + snippet: '', + receivedAtLabel: 'now', + unread: false, + ), + ]; + } +} + class _CredentialRecordingApi extends MailApiClient { _CredentialRecordingApi() : super(baseUrl: 'http://127.0.0.1:1'); From 04c0d7295218860e20c2206aa05139a00df7a1e1 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:57:53 +0900 Subject: [PATCH 3/5] =?UTF-8?q?=EC=9D=B8=EC=A6=9D=20=EC=A0=84=EC=97=90?= =?UTF-8?q?=EB=8A=94=20=EB=A9=94=EC=9D=BC=20=EA=B2=80=EC=83=89=EA=B3=BC=20?= =?UTF-8?q?=EB=AF=B8=EA=B0=80=EC=A0=B8=EC=98=A8=20=EB=A9=94=EC=9D=BC=20?= =?UTF-8?q?=EC=A1=B0=ED=9A=8C=EB=A5=BC=20=EB=A1=9C=EC=BB=AC=20=EC=9A=94?= =?UTF-8?q?=EC=B2=AD=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) 전까지 네트워크 호출자가 IMAP 자격증명으로 미가져온 본문을 읽지 못하게 막는다. ALLOW_REMOTE_MAIL_SEARCH=true로만 원격 허용. --- apps/server/.env.example | 2 + apps/server/package.json | 2 +- apps/server/src/api/routes.ts | 12 ++++- apps/server/test/mailSearchAccess.test.ts | 64 +++++++++++++++++++++++ 4 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 apps/server/test/mailSearchAccess.test.ts diff --git a/apps/server/.env.example b/apps/server/.env.example index 8f64eca..4b4ccab 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 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 98c4fb6..e30e26d 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": "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", "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 5b5109a..1d0d5e2 100644 --- a/apps/server/src/api/routes.ts +++ b/apps/server/src/api/routes.ts @@ -79,6 +79,13 @@ const accountSchema = z.object({ const demoUserId = "demo-user"; +// shortcut: no real auth yet (issue #20), so mail search and the IMAP +// fallback are loopback-only unless ALLOW_REMOTE_MAIL_SEARCH=true. +function canReadUnstoredMail(ip: string): boolean { + return process.env.ALLOW_REMOTE_MAIL_SEARCH === "true" || + ip === "127.0.0.1" || ip === "::1" || ip === "::ffff:127.0.0.1"; +} + export async function registerRoutes( app: FastifyInstance, deps: { @@ -289,6 +296,9 @@ export async function registerRoutes( }); app.get("/accounts/:id/search", async (request, reply) => { + if (!canReadUnstoredMail(request.ip)) { + return reply.code(403).send({ error: "Search is only available locally." }); + } const params = z.object({ id: z.string() }).parse(request.params); const { q } = z.object({ q: z.string().max(500) }).parse(request.query); const account = await deps.accounts.getAccount(params.id); @@ -334,7 +344,7 @@ export async function registerRoutes( const message = messages.find( (item) => item.accountId === params.accountId && item.providerMessageId === params.messageId - ) ?? (account.incomingProtocol === "imap" + ) ?? (account.incomingProtocol === "imap" && canReadUnstoredMail(request.ip) ? await deps.fetchMessageSummary(account, params.messageId) : null); if (!message) { diff --git a/apps/server/test/mailSearchAccess.test.ts b/apps/server/test/mailSearchAccess.test.ts new file mode 100644 index 0000000..ea44027 --- /dev/null +++ b/apps/server/test/mailSearchAccess.test.ts @@ -0,0 +1,64 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import Fastify from "fastify"; +import { registerRoutes } from "../src/api/routes.js"; +import { InMemoryAccountRepository } from "../src/workers/AccountRepository.js"; +import type { IncomingMessageSummary, MailAccount } from "../src/domain/types.js"; + +const account = { + id: "a1", + userId: "demo-user", + providerId: "custom", + emailAddress: "me@example.test", + authMode: "password", + incomingProtocol: "imap", + encryptedSecretRef: "x" +} as unknown as MailAccount; + +const summary = { + accountId: "a1", + providerMessageId: "9", + receivedAt: new Date(0) +} as unknown as IncomingMessageSummary; + +async function build() { + const accounts = new InMemoryAccountRepository(); + await accounts.addAccount(account); + let fetched = 0; + const app = Fastify(); + await registerRoutes(app, { + accounts, + searchMessages: async () => [summary], + fetchMessageSummary: async () => { fetched++; return summary; }, + fetchMessageContent: async () => ({ text: "secret" }) + } as never); + return { app, fetched: () => fetched }; +} + +test("loopback may search and use the IMAP fallback", async () => { + const { app } = await build(); + const search = await app.inject({ url: "/accounts/a1/search?q=hi", remoteAddress: "127.0.0.1" }); + assert.equal(search.statusCode, 200); + const detail = await app.inject({ url: "/accounts/a1/messages/9", remoteAddress: "::1" }); + assert.equal(detail.statusCode, 200); +}); + +test("remote callers get 403 on search and 404 without IMAP fallback", async () => { + const { app, fetched } = await build(); + const search = await app.inject({ url: "/accounts/a1/search?q=hi", remoteAddress: "192.168.0.5" }); + assert.equal(search.statusCode, 403); + const detail = await app.inject({ url: "/accounts/a1/messages/9", remoteAddress: "192.168.0.5" }); + assert.equal(detail.statusCode, 404); + assert.equal(fetched(), 0); +}); + +test("ALLOW_REMOTE_MAIL_SEARCH=true opts remote callers in", async () => { + process.env.ALLOW_REMOTE_MAIL_SEARCH = "true"; + try { + const { app } = await build(); + const res = await app.inject({ url: "/accounts/a1/search?q=hi", remoteAddress: "192.168.0.5" }); + assert.equal(res.statusCode, 200); + } finally { + delete process.env.ALLOW_REMOTE_MAIL_SEARCH; + } +}); From 304ceb297a593eaaeb1d98e406a31804082c53fb Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:05:34 +0900 Subject: [PATCH 4/5] =?UTF-8?q?=EB=A9=94=EC=9D=BC=20=EA=B2=80=EC=83=89=20?= =?UTF-8?q?=EC=A0=91=EA=B7=BC=20=EC=A0=9C=ED=95=9C=EC=97=90=20Host=C2=B7Or?= =?UTF-8?q?igin=20=EA=B2=80=EC=A6=9D=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 루프백 IP만으로는 브라우저 웹 페이지(DNS 리바인딩 포함)를 막지 못하므로, Host가 루프백이 아니거나 Origin 헤더가 있는 요청은 403으로 거부한다. --- apps/server/src/api/routes.ts | 19 ++++++++------ apps/server/test/mailSearchAccess.test.ts | 30 +++++++++++++++++++++++ 2 files changed, 42 insertions(+), 7 deletions(-) diff --git a/apps/server/src/api/routes.ts b/apps/server/src/api/routes.ts index 1d0d5e2..7cd8554 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 { SearchObject } from "imapflow"; @@ -80,10 +80,15 @@ const accountSchema = z.object({ const demoUserId = "demo-user"; // shortcut: no real auth yet (issue #20), so mail search and the IMAP -// fallback are loopback-only unless ALLOW_REMOTE_MAIL_SEARCH=true. -function canReadUnstoredMail(ip: string): boolean { - return process.env.ALLOW_REMOTE_MAIL_SEARCH === "true" || - ip === "127.0.0.1" || ip === "::1" || ip === "::ffff:127.0.0.1"; +// 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; + 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( @@ -296,7 +301,7 @@ export async function registerRoutes( }); app.get("/accounts/:id/search", async (request, reply) => { - if (!canReadUnstoredMail(request.ip)) { + if (!canReadUnstoredMail(request)) { return reply.code(403).send({ error: "Search is only available locally." }); } const params = z.object({ id: z.string() }).parse(request.params); @@ -344,7 +349,7 @@ export async function registerRoutes( const message = messages.find( (item) => item.accountId === params.accountId && item.providerMessageId === params.messageId - ) ?? (account.incomingProtocol === "imap" && canReadUnstoredMail(request.ip) + ) ?? (account.incomingProtocol === "imap" && canReadUnstoredMail(request) ? await deps.fetchMessageSummary(account, params.messageId) : null); if (!message) { diff --git a/apps/server/test/mailSearchAccess.test.ts b/apps/server/test/mailSearchAccess.test.ts index ea44027..d9eb050 100644 --- a/apps/server/test/mailSearchAccess.test.ts +++ b/apps/server/test/mailSearchAccess.test.ts @@ -62,3 +62,33 @@ test("ALLOW_REMOTE_MAIL_SEARCH=true opts remote callers in", async () => { delete process.env.ALLOW_REMOTE_MAIL_SEARCH; } }); + +test("loopback peer with an Origin header is rejected (browser)", async () => { + const { app } = await build(); + const res = await app.inject({ + url: "/accounts/a1/search?q=hi", + remoteAddress: "127.0.0.1", + headers: { origin: "https://evil.example" } + }); + assert.equal(res.statusCode, 403); +}); + +test("loopback peer with a non-loopback Host is rejected (DNS rebinding)", async () => { + const { app } = await build(); + const res = await app.inject({ + url: "/accounts/a1/search?q=hi", + remoteAddress: "127.0.0.1", + headers: { host: "evil.example:8080" } + }); + assert.equal(res.statusCode, 403); +}); + +test("plain loopback with 127.0.0.1:port Host is allowed", async () => { + const { app } = await build(); + const res = await app.inject({ + url: "/accounts/a1/search?q=hi", + remoteAddress: "127.0.0.1", + headers: { host: "127.0.0.1:8080" } + }); + assert.equal(res.statusCode, 200); +}); From 9ba335b7a1d360aef34879947814de817aae70b6 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:08:03 +0900 Subject: [PATCH 5/5] =?UTF-8?q?=EC=83=88=20=EA=B2=80=EC=83=89=20=EC=A4=91?= =?UTF-8?q?=EC=97=90=EB=8A=94=20=EC=9D=B4=EC=A0=84=20=EA=B2=80=EC=83=89=20?= =?UTF-8?q?=EA=B2=B0=EA=B3=BC=20=EB=8C=80=EC=8B=A0=20=EB=A1=9C=EB=94=A9=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 FutureBuilder가 새 검색어의 Future로 바뀌어도 이전 snapshot의 data·error를 유지하므로 connectionState가 done일 때만 결과를 그린다. 지연 fake로 두 번째 검색 대기 중 이전 결과가 남지 않는지 위젯 테스트를 추가했다. --- .../accounts/account_mailbox_page.dart | 10 ++- apps/client/test/widget_test.dart | 81 +++++++++++++++++++ 2 files changed, 87 insertions(+), 4 deletions(-) diff --git a/apps/client/lib/features/accounts/account_mailbox_page.dart b/apps/client/lib/features/accounts/account_mailbox_page.dart index 7a86933..a31b806 100644 --- a/apps/client/lib/features/accounts/account_mailbox_page.dart +++ b/apps/client/lib/features/accounts/account_mailbox_page.dart @@ -272,13 +272,15 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { ? FutureBuilder>( future: _search, builder: (context, snapshot) { + // A new future keeps the previous snapshot's data/error + // while waiting, so check the state before rendering it. + if (snapshot.connectionState != ConnectionState.done) { + return const Center(child: CircularProgressIndicator()); + } if (snapshot.hasError) { return Center(child: Text(strings.searchFailedTitle)); } - final results = snapshot.data; - if (results == null) { - return const Center(child: CircularProgressIndicator()); - } + final results = snapshot.data!; if (results.isEmpty) { return Center(child: Text(strings.noSearchResults)); } diff --git a/apps/client/test/widget_test.dart b/apps/client/test/widget_test.dart index b08f4e3..57fdb74 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -155,6 +157,60 @@ void main() { expect(find.text('invoice'), findsNothing); }); + testWidgets('shows loading instead of previous results for a new search', + (WidgetTester tester) async { + const account = MailAccountSummary( + id: 'account-a', + providerId: 'gmail', + emailAddress: 'first@example.com', + incomingProtocol: 'imap', + authMode: 'oauth2', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'now', + ); + final api = _DelayedSearchApi(); + await tester.binding.setSurfaceSize(const Size(1200, 800)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + mailApiClientProvider.overrideWithValue(api), + accountsProvider.overrideWith((ref) async => const [account]), + providersProvider.overrideWith((ref) async => const []), + accountMessagesProvider.overrideWith((ref, accountId) async => const []), + ], + child: const DailyPostBoxApp(), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text(account.emailAddress).first); + await tester.pumpAndSettle(); + final searchField = find.descendant( + of: find.byType(Scaffold).last, + matching: find.byType(TextField), + ).first; + await tester.enterText(searchField, 'invoice'); + await tester.testTextInput.receiveAction(TextInputAction.search); + await tester.pump(); + api.pending.removeAt(0).complete(const [_DelayedSearchApi.firstResult]); + await tester.pumpAndSettle(); + expect(find.text(_DelayedSearchApi.firstResult.subject), findsOneWidget); + + await tester.enterText(searchField, 'receipt'); + await tester.testTextInput.receiveAction(TextInputAction.search); + await tester.pump(); + + expect(find.text(_DelayedSearchApi.firstResult.subject), findsNothing); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + + api.pending.removeAt(0).complete(const []); + await tester.pumpAndSettle(); + }); + testWidgets('shows a progressive loading state during account sync', (WidgetTester tester) async { const account = MailAccountSummary( @@ -624,6 +680,31 @@ class _SearchApi extends MailApiClient { } } +class _DelayedSearchApi extends MailApiClient { + _DelayedSearchApi() : super(baseUrl: 'http://127.0.0.1:1'); + + static const firstResult = MailSummary( + id: 'uid-1', + sender: 'billing@example.com', + subject: '이전 검색 결과', + snippet: '', + receivedAtLabel: 'now', + unread: false, + ); + + final pending = >>[]; + + @override + Future> searchAccountMessages( + String accountId, + String query, + ) { + final completer = Completer>(); + pending.add(completer); + return completer.future; + } +} + class _CredentialRecordingApi extends MailApiClient { _CredentialRecordingApi() : super(baseUrl: 'http://127.0.0.1:1');