diff --git a/apps/client/lib/core/i18n/language_controller.dart b/apps/client/lib/core/i18n/language_controller.dart index 39fdfd7..e1f1657 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -179,6 +179,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 dd035dc..797b25f 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,16 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { @override void didUpdateWidget(covariant _MailboxContent oldWidget) { super.didUpdateWidget(oldWidget); - final wasSyncing = - const {'syncing', 'validating'}.contains(oldWidget.account.syncStatus); + 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', + }.contains(oldWidget.account.syncStatus); if (oldWidget.account.id == widget.account.id && wasSyncing && !_isSyncing) { @@ -96,9 +102,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); + } + // The server saves IDLE mail at any time, so the list keeps polling after // sync too, just less often. Duration get _refreshInterval => @@ -135,6 +158,40 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { if (mounted && _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; @@ -190,82 +247,95 @@ 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, + 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), ), - 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}, - ), - ); - }, - ); - }, - loading: () => const Center(child: CircularProgressIndicator()), - error: (error, stackTrace) => Center( - child: Text(strings.mailLoadFailedTitle), ), ), ), + Expanded( + child: _search != null + ? 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.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 c11ef10..900bf00 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -51,6 +51,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 9b2c683..3c3d15d 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'; @@ -147,6 +149,119 @@ 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 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( @@ -379,7 +494,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(); @@ -693,6 +811,54 @@ 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 _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'); diff --git a/apps/server/.env.example b/apps/server/.env.example index d4a1291..de42ced 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 6454c16..e62ea47 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/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/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 9a28302..337c993 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 type { FastifyInstance, FastifyRequest } 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, @@ -18,6 +19,11 @@ import { applySyncFailure, isAuthenticationFailure } from "../mail/authenticationFailure.js"; +import { + SearchQueryError, + parseSearchQuery, + toImapSearch +} from "../mail/searchQuery.js"; const sendSchema = z.object({ accountId: z.string(), @@ -85,6 +91,18 @@ 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; + 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( app: FastifyInstance, deps: { @@ -95,6 +113,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; @@ -307,6 +333,39 @@ export async function registerRoutes( })); }); + app.get("/accounts/:id/search", async (request, reply) => { + if (!canReadUnstoredMail(request)) { + 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); + + 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(), @@ -319,10 +378,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" && canReadUnstoredMail(request) + ? 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 7c92838..03f0543 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 { @@ -139,6 +143,38 @@ export class ImapReceiver implements MailReceiver { return initial.result; } + // 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 306ada3..bf569c0 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -66,6 +66,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/mailSearchAccess.test.ts b/apps/server/test/mailSearchAccess.test.ts new file mode 100644 index 0000000..a092153 --- /dev/null +++ b/apps/server/test/mailSearchAccess.test.ts @@ -0,0 +1,95 @@ +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", + from: "sender@example.test", + 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; + } +}); + +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); +}); 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); +});