fluxmail 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +1 -1
  2. package/dist/accounts/googleAuth.d.ts +4 -2
  3. package/dist/accounts/googleAuth.d.ts.map +1 -1
  4. package/dist/accounts/googleAuth.js +20 -85
  5. package/dist/accounts/googleAuth.js.map +1 -1
  6. package/dist/accounts/microsoftAuth.d.ts +2 -1
  7. package/dist/accounts/microsoftAuth.d.ts.map +1 -1
  8. package/dist/accounts/microsoftAuth.js +16 -80
  9. package/dist/accounts/microsoftAuth.js.map +1 -1
  10. package/dist/accounts/oauthCallback.d.ts +52 -0
  11. package/dist/accounts/oauthCallback.d.ts.map +1 -0
  12. package/dist/accounts/oauthCallback.js +237 -0
  13. package/dist/accounts/oauthCallback.js.map +1 -0
  14. package/dist/accounts/registry.d.ts.map +1 -1
  15. package/dist/accounts/registry.js +12 -5
  16. package/dist/accounts/registry.js.map +1 -1
  17. package/dist/accounts/telemetry.d.ts +6 -0
  18. package/dist/accounts/telemetry.d.ts.map +1 -1
  19. package/dist/accounts/telemetry.js +19 -0
  20. package/dist/accounts/telemetry.js.map +1 -1
  21. package/dist/cli.d.ts.map +1 -1
  22. package/dist/cli.js +114 -36
  23. package/dist/cli.js.map +1 -1
  24. package/dist/cliInstances.d.ts +5 -2
  25. package/dist/cliInstances.d.ts.map +1 -1
  26. package/dist/cliInstances.js +74 -22
  27. package/dist/cliInstances.js.map +1 -1
  28. package/dist/cliMail.d.ts +2 -0
  29. package/dist/cliMail.d.ts.map +1 -1
  30. package/dist/cliMail.js +113 -19
  31. package/dist/cliMail.js.map +1 -1
  32. package/dist/cliOutput.d.ts +9 -0
  33. package/dist/cliOutput.d.ts.map +1 -0
  34. package/dist/cliOutput.js +76 -0
  35. package/dist/cliOutput.js.map +1 -0
  36. package/dist/context.js +1 -1
  37. package/dist/context.js.map +1 -1
  38. package/dist/http/admin.d.ts.map +1 -1
  39. package/dist/http/admin.js +2 -0
  40. package/dist/http/admin.js.map +1 -1
  41. package/dist/http/app.d.ts.map +1 -1
  42. package/dist/http/app.js +4 -0
  43. package/dist/http/app.js.map +1 -1
  44. package/dist/http/identity.d.ts.map +1 -1
  45. package/dist/http/identity.js +2 -0
  46. package/dist/http/identity.js.map +1 -1
  47. package/dist/http/rest.d.ts.map +1 -1
  48. package/dist/http/rest.js +270 -48
  49. package/dist/http/rest.js.map +1 -1
  50. package/dist/licensing/entitlements.d.ts +23 -5
  51. package/dist/licensing/entitlements.d.ts.map +1 -1
  52. package/dist/licensing/entitlements.js +101 -22
  53. package/dist/licensing/entitlements.js.map +1 -1
  54. package/dist/licensing/lease.d.ts +1 -1
  55. package/dist/licensing/lease.d.ts.map +1 -1
  56. package/dist/licensing/refresher.d.ts.map +1 -1
  57. package/dist/licensing/refresher.js +5 -2
  58. package/dist/licensing/refresher.js.map +1 -1
  59. package/dist/mcp/buildServer.d.ts.map +1 -1
  60. package/dist/mcp/buildServer.js +236 -78
  61. package/dist/mcp/buildServer.js.map +1 -1
  62. package/dist/mcp/outputSchemas.d.ts +2923 -0
  63. package/dist/mcp/outputSchemas.d.ts.map +1 -0
  64. package/dist/mcp/outputSchemas.js +108 -0
  65. package/dist/mcp/outputSchemas.js.map +1 -0
  66. package/dist/scheduler/sendScheduler.d.ts +2 -0
  67. package/dist/scheduler/sendScheduler.d.ts.map +1 -1
  68. package/dist/scheduler/sendScheduler.js +13 -3
  69. package/dist/scheduler/sendScheduler.js.map +1 -1
  70. package/dist/service/deliveryCoordinator.d.ts +45 -0
  71. package/dist/service/deliveryCoordinator.d.ts.map +1 -0
  72. package/dist/service/deliveryCoordinator.js +296 -0
  73. package/dist/service/deliveryCoordinator.js.map +1 -0
  74. package/dist/service/emailService.d.ts +48 -5
  75. package/dist/service/emailService.d.ts.map +1 -1
  76. package/dist/service/emailService.js +258 -37
  77. package/dist/service/emailService.js.map +1 -1
  78. package/dist/service/publicErrors.d.ts +12 -0
  79. package/dist/service/publicErrors.d.ts.map +1 -0
  80. package/dist/service/publicErrors.js +41 -0
  81. package/dist/service/publicErrors.js.map +1 -0
  82. package/dist/service/searchCursor.d.ts +2 -0
  83. package/dist/service/searchCursor.d.ts.map +1 -1
  84. package/dist/service/searchCursor.js +6 -2
  85. package/dist/service/searchCursor.js.map +1 -1
  86. package/dist/storage/db.d.ts +252 -2
  87. package/dist/storage/db.d.ts.map +1 -1
  88. package/dist/storage/db.js +57 -1
  89. package/dist/storage/db.js.map +1 -1
  90. package/dist/storage/members.d.ts.map +1 -1
  91. package/dist/storage/members.js +3 -1
  92. package/dist/storage/members.js.map +1 -1
  93. package/dist/storage/restIdempotency.d.ts +6 -0
  94. package/dist/storage/restIdempotency.d.ts.map +1 -1
  95. package/dist/storage/restIdempotency.js +8 -0
  96. package/dist/storage/restIdempotency.js.map +1 -1
  97. package/dist/storage/scheduledSends.d.ts +2 -1
  98. package/dist/storage/scheduledSends.d.ts.map +1 -1
  99. package/dist/storage/scheduledSends.js +6 -0
  100. package/dist/storage/scheduledSends.js.map +1 -1
  101. package/package.json +5 -5
@@ -1,10 +1,13 @@
1
- import { computeReplyRecipients, EmailError, formatAddressList, forwardSubject, isEmailError, isPortableFolderRole, normalizeEmailQuery, parseSingleAddress, supportsPortableEmailQuery, } from '@fluxmail/core';
1
+ import { computeReplyRecipients, EmailError, formatAddressList, forwardSubject, isEmailError, isPortableFolderRole, normalizeEmailQuery, parseSingleAddress, replySubject, supportsPortableEmailQuery, } from '@fluxmail/core';
2
2
  import { randomBytes } from 'node:crypto';
3
3
  import { assertWithinQuota, checkLicenseState } from '../licensing/entitlements.js';
4
4
  import { listMembers } from '../storage/members.js';
5
5
  import { canAccessAccount, canAdminister, canSeeAccountMetadata } from '../authorization.js';
6
6
  import { cancelScheduledSend, countPending, createScheduledSend, findPendingByDraft, getScheduledSend, listScheduledSends, markSent, } from '../storage/scheduledSends.js';
7
7
  import { SearchCursorCodec } from './searchCursor.js';
8
+ import { DeliveryCoordinator, isDefiniteDeliveryFailure } from './deliveryCoordinator.js';
9
+ import { ClientInputError } from './publicErrors.js';
10
+ import { DEFAULT_MAX_ATTACHMENT_BYTES } from '../config.js';
8
11
  import { listConfiguredSendAs, replaceConfiguredSendAs } from '../storage/sendAs.js';
9
12
  const SCHEDULE_GRACE_MS = 60_000;
10
13
  const SCHEDULE_MAX_HORIZON_MS = 365 * 24 * 3_600_000;
@@ -64,13 +67,13 @@ export function resolveSendAt(sendAtIso, now = Date.now()) {
64
67
  // Require an ISO 8601 shape: Date.parse alone is lenient enough to accept junk.
65
68
  const sendAt = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(sendAtIso) ? Date.parse(sendAtIso) : NaN;
66
69
  if (Number.isNaN(sendAt)) {
67
- throw new EmailError('invalid_request', `Could not parse sendAt: "${sendAtIso}" (expected ISO 8601)`);
70
+ throw new ClientInputError('invalid_request', `Could not parse sendAt: "${sendAtIso}" (expected ISO 8601)`);
68
71
  }
69
72
  if (sendAt < now - SCHEDULE_GRACE_MS) {
70
- throw new EmailError('invalid_request', 'sendAt is in the past; leave it out to send now');
73
+ throw new ClientInputError('invalid_request', 'sendAt is in the past; leave it out to send now');
71
74
  }
72
75
  if (sendAt > now + SCHEDULE_MAX_HORIZON_MS) {
73
- throw new EmailError('invalid_request', 'sendAt is more than a year away');
76
+ throw new ClientInputError('invalid_request', 'sendAt is more than a year away');
74
77
  }
75
78
  return sendAt;
76
79
  }
@@ -98,14 +101,16 @@ export class EmailService {
98
101
  registry;
99
102
  db;
100
103
  principal;
104
+ maxAttachmentBytes;
101
105
  /** Wired to SendScheduler.wake() in long-lived processes; a no-op for one-shot CLI commands. */
102
106
  onScheduleChanged = () => { };
103
107
  cursorSecret;
104
108
  cursorCodec;
105
- constructor(registry, db, principal, cursorSecret) {
109
+ constructor(registry, db, principal, cursorSecret, maxAttachmentBytes = DEFAULT_MAX_ATTACHMENT_BYTES) {
106
110
  this.registry = registry;
107
111
  this.db = db;
108
112
  this.principal = principal;
113
+ this.maxAttachmentBytes = maxAttachmentBytes;
109
114
  this.cursorSecret = cursorSecret ?? randomBytes(32);
110
115
  this.cursorCodec = new SearchCursorCodec(this.cursorSecret);
111
116
  }
@@ -114,7 +119,7 @@ export class EmailService {
114
119
  * allowlist. Internal background workers use the default service instead.
115
120
  */
116
121
  withPrincipal(principal) {
117
- const scoped = new EmailService(this.registry, this.db, principal, this.cursorSecret);
122
+ const scoped = new EmailService(this.registry, this.db, principal, this.cursorSecret, this.maxAttachmentBytes);
118
123
  scoped.onScheduleChanged = () => this.onScheduleChanged();
119
124
  return scoped;
120
125
  }
@@ -151,10 +156,10 @@ export class EmailService {
151
156
  return this.registry.resolveAccountId();
152
157
  const accessible = this.accessibleAccounts();
153
158
  if (accessible.length === 0) {
154
- throw new EmailError('invalid_request', 'No email accounts are available for this member.');
159
+ throw new ClientInputError('invalid_request', 'No email accounts are available for this member.');
155
160
  }
156
161
  if (accessible.length > 1) {
157
- throw new EmailError('invalid_request', `Multiple accounts are available; specify accountId. Available: ${accessible
162
+ throw new ClientInputError('invalid_request', `Multiple accounts are available; specify accountId. Available: ${accessible
158
163
  .map((a) => `${a.id} (${a.email})`)
159
164
  .join(', ')}`);
160
165
  }
@@ -169,7 +174,7 @@ export class EmailService {
169
174
  const resolvedId = this.resolveScopedAccountId(accountId);
170
175
  const account = this.registry.getAccount(resolvedId);
171
176
  if (account.status === 'disabled') {
172
- throw new EmailError('invalid_request', `Account ${resolvedId} is disabled`);
177
+ throw new ClientInputError('invalid_request', `Account ${resolvedId} is disabled`);
173
178
  }
174
179
  try {
175
180
  const result = await fn(this.registry.getProvider(resolvedId), resolvedId, account);
@@ -240,15 +245,17 @@ export class EmailService {
240
245
  };
241
246
  }
242
247
  /**
243
- * Gate for MCP tool calls: throws once a lapsed license leaves the instance
244
- * over the entitled caps; returns a renewal warning to attach to results
245
- * while the license is in its grace period or has lapsed.
248
+ * Gate for MCP tool calls: throws once the instance is over the entitled
249
+ * caps, after a lapse or once a cap reduction's grace period ends; returns a
250
+ * warning to attach to results while a grace period runs or after a lapse.
246
251
  */
247
252
  enforceQuota() {
248
253
  if (!this.isInternal() && (!this.principal || !canAdminister(this.principal, 'admin.license'))) {
249
254
  const state = checkLicenseState(this.db);
250
- if (state.overQuota) {
251
- throw new EmailError('entitlement_exceeded', 'This Fluxmail instance is over its plan limits. Ask an administrator to renew the license or reduce usage.');
255
+ if (state.blocked) {
256
+ throw new EmailError('entitlement_exceeded', 'This Fluxmail instance is over its plan limits. Ask an administrator to ' +
257
+ (state.entitlements.licensed ? 'upgrade the plan' : 'renew the license') +
258
+ ' or reduce usage.');
252
259
  }
253
260
  // License dates and renewal state are instance administration details.
254
261
  return undefined;
@@ -296,14 +303,14 @@ export class EmailService {
296
303
  const normalized = identities.map((identity) => {
297
304
  const parsed = parseSingleAddress(identity.email.trim());
298
305
  if (!parsed)
299
- throw new EmailError('invalid_request', `Could not parse sender address: "${identity.email}"`);
306
+ throw new ClientInputError('invalid_request', `Could not parse sender address: "${identity.email}"`);
300
307
  const email = parsed.email;
301
308
  const key = email.toLowerCase();
302
309
  if (key === account.email.toLowerCase()) {
303
- throw new EmailError('invalid_request', 'Do not include the connected account address in configured aliases.');
310
+ throw new ClientInputError('invalid_request', 'Do not include the connected account address in configured aliases.');
304
311
  }
305
312
  if (seen.has(key))
306
- throw new EmailError('invalid_request', `Duplicate sender address: "${email}"`);
313
+ throw new ClientInputError('invalid_request', `Duplicate sender address: "${email}"`);
307
314
  seen.add(key);
308
315
  const name = identity.name?.trim();
309
316
  return { email, ...(name ? { name } : {}) };
@@ -322,11 +329,14 @@ export class EmailService {
322
329
  async listMessages(accountId, q, page = {}) {
323
330
  const normalized = normalizeEmailQuery(q);
324
331
  if (!normalized.success) {
325
- throw new EmailError('invalid_request', normalized.diagnostics.map((item) => item.message).join(' '), {
332
+ throw new ClientInputError('invalid_request', normalized.diagnostics.map((item) => item.message).join(' '), {
326
333
  diagnostics: normalized.diagnostics,
327
334
  });
328
335
  }
329
336
  const query = normalized.query;
337
+ if (page.includeSearchContext && !query.text) {
338
+ throw new ClientInputError('invalid_request', 'includeSearchContext requires a portable text query.');
339
+ }
330
340
  const pageSize = Math.min(Math.max(page.pageSize ?? 25, 1), 100);
331
341
  const ownsController = page.signal === undefined;
332
342
  const controller = ownsController ? new AbortController() : undefined;
@@ -341,6 +351,9 @@ export class EmailService {
341
351
  try {
342
352
  const operation = this.withProvider(accountId, async (provider, resolvedId, account) => {
343
353
  assertSearchCapabilities(provider.capabilities.search, query);
354
+ if (page.includeSearchContext && provider.capabilities.searchContext !== true) {
355
+ throw new EmailError('unsupported_capability', 'This provider does not support search context.');
356
+ }
344
357
  const providerToken = page.pageToken
345
358
  ? this.cursorCodec.decode(page.pageToken, {
346
359
  accountId: resolvedId,
@@ -348,12 +361,14 @@ export class EmailService {
348
361
  query,
349
362
  pageSize,
350
363
  ...(page.includeSnippet !== undefined ? { includeSnippet: page.includeSnippet } : {}),
364
+ ...(page.includeSearchContext !== undefined ? { includeSearchContext: page.includeSearchContext } : {}),
351
365
  })
352
366
  : undefined;
353
367
  const result = await provider.listMessages(query, {
354
368
  pageSize,
355
369
  ...(providerToken ? { pageToken: providerToken } : {}),
356
370
  ...(page.includeSnippet !== undefined ? { includeSnippet: page.includeSnippet } : {}),
371
+ ...(page.includeSearchContext !== undefined ? { includeSearchContext: page.includeSearchContext } : {}),
357
372
  signal,
358
373
  softDeadlineAt,
359
374
  });
@@ -368,6 +383,9 @@ export class EmailService {
368
383
  query,
369
384
  pageSize,
370
385
  ...(page.includeSnippet !== undefined ? { includeSnippet: page.includeSnippet } : {}),
386
+ ...(page.includeSearchContext !== undefined
387
+ ? { includeSearchContext: page.includeSearchContext }
388
+ : {}),
371
389
  providerToken: result.nextPageToken,
372
390
  }),
373
391
  }
@@ -396,21 +414,24 @@ export class EmailService {
396
414
  }
397
415
  async searchMessagesBatch(input) {
398
416
  if (input.accounts.length < 1 || input.accounts.length > 20) {
399
- throw new EmailError('invalid_request', 'Batch search requires between 1 and 20 accounts.');
417
+ throw new ClientInputError('invalid_request', 'Batch search requires between 1 and 20 accounts.');
400
418
  }
401
419
  const seen = new Set();
402
420
  for (const account of input.accounts) {
403
421
  if (seen.has(account.accountId))
404
- throw new EmailError('invalid_request', 'Batch account IDs must be distinct.');
422
+ throw new ClientInputError('invalid_request', 'Batch account IDs must be distinct.');
405
423
  seen.add(account.accountId);
406
424
  }
407
425
  const normalized = normalizeEmailQuery(input.query);
408
426
  if (!normalized.success) {
409
- throw new EmailError('invalid_request', normalized.diagnostics.map((item) => item.message).join(' '), {
427
+ throw new ClientInputError('invalid_request', normalized.diagnostics.map((item) => item.message).join(' '), {
410
428
  diagnostics: normalized.diagnostics,
411
429
  });
412
430
  }
413
431
  const pageSize = Math.min(Math.max(input.pageSize ?? 25, 1), 100);
432
+ if (input.includeSearchContext && !normalized.query.text) {
433
+ throw new ClientInputError('invalid_request', 'includeSearchContext requires a portable text query.');
434
+ }
414
435
  const controller = new AbortController();
415
436
  const startedAt = Date.now();
416
437
  const softDeadlineAt = startedAt + SEARCH_SOFT_BUDGET_MS;
@@ -433,6 +454,7 @@ export class EmailService {
433
454
  pageSize,
434
455
  ...(account.pageToken ? { pageToken: account.pageToken } : {}),
435
456
  ...(input.includeSnippet !== undefined ? { includeSnippet: input.includeSnippet } : {}),
457
+ ...(input.includeSearchContext !== undefined ? { includeSearchContext: input.includeSearchContext } : {}),
436
458
  signal: controller.signal,
437
459
  softDeadlineAt,
438
460
  });
@@ -457,12 +479,14 @@ export class EmailService {
457
479
  getThread(accountId, threadId) {
458
480
  return this.withProvider(accountId, (p) => p.getThread(threadId));
459
481
  }
460
- createDraft(accountId, d) {
482
+ async createDraft(accountId, d) {
483
+ this.assertMailContent(d);
461
484
  return this.withProvider(accountId, async (p, _id, account) => {
462
485
  return p.createDraft(await this.resolveRecipients(p, account, d));
463
486
  });
464
487
  }
465
- updateDraft(accountId, draftId, d) {
488
+ async updateDraft(accountId, draftId, d) {
489
+ this.assertMailContent(d);
466
490
  return this.withProvider(accountId, async (p, _id, account) => {
467
491
  return p.updateDraft(draftId, await this.resolveRecipients(p, account, d));
468
492
  });
@@ -470,7 +494,125 @@ export class EmailService {
470
494
  deleteDraft(accountId, draftId) {
471
495
  return this.withProvider(accountId, (p) => p.deleteDraft(draftId));
472
496
  }
473
- send(accountId, input) {
497
+ getDraft(accountId, draftId) {
498
+ return this.withProvider(accountId, (p) => p.getDraft(draftId));
499
+ }
500
+ previewSend(accountId, input) {
501
+ return this.withProvider(accountId, async (provider, resolvedId, account) => {
502
+ if ('draftId' in input) {
503
+ const draft = await provider.getDraft(input.draftId);
504
+ if (draft.from?.email && draft.from.email.toLowerCase() !== account.email.toLowerCase()) {
505
+ await this.validateSender(provider, resolvedId, account, draft.from.email);
506
+ }
507
+ return {
508
+ accountId: resolvedId,
509
+ from: draft.from?.email ?? account.email,
510
+ to: draft.to,
511
+ cc: draft.cc ?? [],
512
+ bcc: draft.bcc ?? [],
513
+ subject: draft.subject,
514
+ attachments: (draft.attachments ?? []).map(({ filename, mimeType, sizeBytes }) => ({
515
+ filename,
516
+ mimeType,
517
+ sizeBytes,
518
+ })),
519
+ bodyTextChars: draft.body?.text?.length ?? 0,
520
+ bodyHtmlChars: draft.body?.html?.length ?? 0,
521
+ };
522
+ }
523
+ this.assertMailContent(input);
524
+ const resolved = await this.resolveRecipients(provider, account, input);
525
+ const subject = resolved.subject ??
526
+ (input.replyToMessageId ? replySubject((await provider.getMessage(input.replyToMessageId)).subject) : '');
527
+ return {
528
+ accountId: resolvedId,
529
+ from: resolved.from ?? account.email,
530
+ to: resolved.to ?? [],
531
+ cc: resolved.cc ?? [],
532
+ bcc: resolved.bcc ?? [],
533
+ subject,
534
+ attachments: (resolved.attachments ?? []).map(({ filename, mimeType, content }) => ({
535
+ filename,
536
+ mimeType,
537
+ sizeBytes: Buffer.byteLength(content, 'base64'),
538
+ })),
539
+ bodyTextChars: resolved.body.text?.length ?? 0,
540
+ bodyHtmlChars: resolved.body.html?.length ?? 0,
541
+ };
542
+ });
543
+ }
544
+ getDelivery(accountId, operationId) {
545
+ this.assertAccountAccess(accountId);
546
+ if (!this.principal)
547
+ throw new EmailError('permission_denied', 'A member session is required.');
548
+ return new DeliveryCoordinator(this.db).get(this.principal.principalId, this.principal.memberId, accountId, operationId);
549
+ }
550
+ deliver(accountId, input, key) {
551
+ const resolvedId = this.resolveScopedAccountId(accountId);
552
+ if (!this.principal)
553
+ throw new EmailError('permission_denied', 'A member session is required.');
554
+ return new DeliveryCoordinator(this.db).run({
555
+ principalId: this.principal.principalId,
556
+ memberId: this.principal.memberId,
557
+ accountId: resolvedId,
558
+ key,
559
+ kind: 'send',
560
+ request: input,
561
+ }, () => this.send(resolvedId, input));
562
+ }
563
+ deliverForward(accountId, input, key) {
564
+ const resolvedId = this.resolveScopedAccountId(accountId);
565
+ if (!this.principal)
566
+ throw new EmailError('permission_denied', 'A member session is required.');
567
+ return new DeliveryCoordinator(this.db).run({
568
+ principalId: this.principal.principalId,
569
+ memberId: this.principal.memberId,
570
+ accountId: resolvedId,
571
+ key,
572
+ kind: 'forward',
573
+ request: input,
574
+ }, () => this.forward(resolvedId, input));
575
+ }
576
+ deliverScheduled(accountId, draftId, scheduleId) {
577
+ return new DeliveryCoordinator(this.db).fireScheduled(accountId, draftId, scheduleId, () => this.withProvider(accountId, async (provider, resolvedId, account) => {
578
+ const draft = await provider.getDraft(draftId);
579
+ if (draft.from?.email && draft.from.email.toLowerCase() !== account.email.toLowerCase()) {
580
+ await this.validateSender(provider, resolvedId, account, draft.from.email);
581
+ }
582
+ }), () => this.withProvider(accountId, async (provider, resolvedId) => {
583
+ const result = await provider.send({ draftId });
584
+ const pending = findPendingByDraft(this.db, resolvedId, draftId);
585
+ if (pending) {
586
+ markSent(this.db, pending.id, result);
587
+ this.onScheduleChanged();
588
+ }
589
+ return result;
590
+ }));
591
+ }
592
+ scheduleDelivery(accountId, input, sendAt, key) {
593
+ const resolvedId = this.resolveScopedAccountId(accountId);
594
+ if (!this.principal)
595
+ throw new EmailError('permission_denied', 'A member session is required.');
596
+ let createdSchedule = false;
597
+ const scheduled = new DeliveryCoordinator(this.db).schedule({
598
+ principalId: this.principal.principalId,
599
+ memberId: this.principal.memberId,
600
+ accountId: resolvedId,
601
+ key,
602
+ request: { input, sendAt },
603
+ }, async () => {
604
+ const result = await this.createSchedule(resolvedId, input, sendAt);
605
+ createdSchedule = true;
606
+ return result;
607
+ });
608
+ return scheduled.finally(() => {
609
+ if (createdSchedule)
610
+ this.onScheduleChanged();
611
+ });
612
+ }
613
+ async send(accountId, input) {
614
+ if (!('draftId' in input))
615
+ this.assertMailContent(input);
474
616
  return this.withProvider(accountId, async (p, resolvedId, account) => {
475
617
  if ('draftId' in input) {
476
618
  const draft = await p.getDraft(input.draftId);
@@ -494,6 +636,13 @@ export class EmailService {
494
636
  * immediately; only the schedule (draft id + fire time) is stored locally.
495
637
  */
496
638
  async scheduleSend(accountId, input, sendAtIso) {
639
+ const scheduled = await this.createSchedule(accountId, input, sendAtIso);
640
+ this.onScheduleChanged();
641
+ return scheduled;
642
+ }
643
+ async createSchedule(accountId, input, sendAtIso) {
644
+ if (!('draftId' in input))
645
+ this.assertMailContent(input);
497
646
  const sendAt = resolveSendAt(sendAtIso);
498
647
  const { draft, resolvedId } = await this.withProvider(accountId, async (p, id, account) => {
499
648
  let message;
@@ -503,7 +652,7 @@ export class EmailService {
503
652
  else {
504
653
  const resolved = await this.resolveRecipients(p, account, input);
505
654
  if (!resolved.to?.length && !resolved.cc?.length && !resolved.bcc?.length) {
506
- throw new EmailError('invalid_request', 'Cannot schedule a message with no recipients');
655
+ throw new ClientInputError('invalid_request', 'Cannot schedule a message with no recipients');
507
656
  }
508
657
  message = await p.createDraft(resolved);
509
658
  }
@@ -519,19 +668,23 @@ export class EmailService {
519
668
  ...(draft.subject !== undefined ? { subject: draft.subject } : {}),
520
669
  ...(draft.to?.length ? { toRecipients: formatAddressList(draft.to) } : {}),
521
670
  });
522
- this.onScheduleChanged();
523
671
  return toScheduledInfo(row);
524
672
  }
525
673
  listScheduled(accountId) {
674
+ const coordinator = new DeliveryCoordinator(this.db);
675
+ const withOperation = (row) => {
676
+ const operationId = coordinator.findScheduled(row.accountId, row.id)?.operationId;
677
+ return { ...toScheduledInfo(row), ...(operationId ? { operationId } : {}) };
678
+ };
526
679
  if (accountId !== undefined) {
527
- return listScheduledSends(this.db, this.resolveScopedAccountId(accountId)).map(toScheduledInfo);
680
+ return listScheduledSends(this.db, this.resolveScopedAccountId(accountId)).map(withOperation);
528
681
  }
529
682
  // Listing must work across accounts, but a member key only sees its own mailboxes'.
530
683
  const rows = listScheduledSends(this.db);
531
684
  if (this.isInternal())
532
- return rows.map(toScheduledInfo);
685
+ return rows.map(withOperation);
533
686
  const accessible = new Set(this.accessibleAccounts().map((a) => a.id));
534
- return rows.filter((r) => accessible.has(r.accountId)).map(toScheduledInfo);
687
+ return rows.filter((r) => accessible.has(r.accountId)).map(withOperation);
535
688
  }
536
689
  /** Cancels a pending schedule; the provider draft is kept. */
537
690
  cancelScheduled(scheduleId) {
@@ -541,11 +694,12 @@ export class EmailService {
541
694
  throw new EmailError('not_found', `No scheduled send with id ${scheduleId}`);
542
695
  }
543
696
  if (row.status !== 'pending') {
544
- throw new EmailError('invalid_request', `Scheduled send ${scheduleId} is already ${row.status}`);
697
+ throw new ClientInputError('invalid_request', `Scheduled send ${scheduleId} is already ${row.status}`);
545
698
  }
546
699
  if (!cancelScheduledSend(this.db, scheduleId)) {
547
- throw new EmailError('invalid_request', `Scheduled send ${scheduleId} has already started sending`);
700
+ throw new ClientInputError('invalid_request', `Scheduled send ${scheduleId} has already started sending`);
548
701
  }
702
+ new DeliveryCoordinator(this.db).cancelScheduled(row.accountId, scheduleId);
549
703
  this.onScheduleChanged();
550
704
  return { scheduleId, draftId: row.draftId, draftKept: true };
551
705
  }
@@ -609,7 +763,7 @@ export class EmailService {
609
763
  async validateSender(provider, accountId, account, sender, known) {
610
764
  const parsed = parseSingleAddress(sender.trim());
611
765
  if (!parsed)
612
- throw new EmailError('invalid_request', `Could not parse sender address: "${sender}"`);
766
+ throw new ClientInputError('invalid_request', `Could not parse sender address: "${sender}"`);
613
767
  if (parsed.email.toLowerCase() === account.email.toLowerCase()) {
614
768
  return {
615
769
  email: account.email,
@@ -620,7 +774,7 @@ export class EmailService {
620
774
  }
621
775
  const identity = (known ?? (await this.sendAsIdentities(provider, accountId, account))).find((candidate) => candidate.email.toLowerCase() === parsed.email.toLowerCase());
622
776
  if (!identity)
623
- throw new EmailError('invalid_request', `Sender address "${parsed.email}" is not available.`);
777
+ throw new ClientInputError('invalid_request', `Sender address "${parsed.email}" is not available.`);
624
778
  return identity;
625
779
  }
626
780
  selectReplySender(original, identities) {
@@ -635,13 +789,22 @@ export class EmailService {
635
789
  }
636
790
  return identities.find((identity) => identity.isPrimary) ?? identities[0];
637
791
  }
638
- forward(accountId, input) {
792
+ async forward(accountId, input) {
793
+ if (Buffer.byteLength(input.comment ?? '', 'utf8') > 1024 * 1024) {
794
+ throw new ClientInputError('invalid_request', 'Forward comment exceeds the 1 MiB body limit.');
795
+ }
639
796
  return this.withProvider(accountId, async (p, resolvedId, account) => {
640
797
  const original = await p.getMessage(input.messageId);
641
798
  const includeAttachments = input.includeAttachments ?? true;
642
799
  const attachments = [];
643
800
  if (includeAttachments) {
644
- for (const meta of original.attachments ?? []) {
801
+ const metadata = original.attachments ?? [];
802
+ if (metadata.length > 20)
803
+ throw new ClientInputError('invalid_request', 'A message may have at most 20 attachments.');
804
+ if (metadata.reduce((total, item) => total + item.sizeBytes, 0) > this.maxAttachmentBytes) {
805
+ throw new ClientInputError('invalid_request', 'Combined attachments exceed the configured size limit.');
806
+ }
807
+ for (const meta of metadata) {
645
808
  const { content } = await p.getAttachment(original.id, meta.id);
646
809
  attachments.push({
647
810
  filename: meta.filename,
@@ -660,15 +823,73 @@ export class EmailService {
660
823
  body: buildForwardBody(original, input.comment),
661
824
  ...(attachments.length ? { attachments } : {}),
662
825
  };
826
+ this.assertMailContent(draft);
663
827
  return p.send(draft);
664
828
  });
665
829
  }
666
- modify(accountId, ids, action) {
667
- return this.withProvider(accountId, (p) => p.modify(ids, action));
830
+ async modify(accountId, ids, action) {
831
+ const unique = [...new Set(ids)];
832
+ if (unique.length < 1 || unique.length > 100) {
833
+ throw new ClientInputError('invalid_request', 'Modify between 1 and 100 distinct messages.');
834
+ }
835
+ const resolvedId = this.resolveScopedAccountId(accountId);
836
+ const result = await this.withProvider(resolvedId, async (provider) => {
837
+ const outcomes = Array.from({ length: unique.length }, () => 'uncertain');
838
+ let next = 0;
839
+ const worker = async () => {
840
+ for (;;) {
841
+ const index = next++;
842
+ if (index >= unique.length)
843
+ return;
844
+ try {
845
+ await provider.modify([unique[index]], action);
846
+ outcomes[index] = 'succeeded';
847
+ }
848
+ catch (error) {
849
+ outcomes[index] = isDefiniteDeliveryFailure(error)
850
+ ? { code: isEmailError(error) ? error.code : 'internal' }
851
+ : 'uncertain';
852
+ }
853
+ }
854
+ };
855
+ await Promise.all(Array.from({ length: Math.min(4, unique.length) }, () => worker()));
856
+ return {
857
+ action,
858
+ succeededIds: unique.filter((_, index) => outcomes[index] === 'succeeded'),
859
+ failed: unique.flatMap((messageId, index) => {
860
+ const outcome = outcomes[index];
861
+ return typeof outcome === 'object' ? [{ messageId, code: outcome.code }] : [];
862
+ }),
863
+ uncertainIds: unique.filter((_, index) => outcomes[index] === 'uncertain'),
864
+ };
865
+ });
866
+ if (result.failed.some(({ code }) => code === 'auth_expired')) {
867
+ this.registry.markStatus(resolvedId, 'auth_error');
868
+ }
869
+ return result;
668
870
  }
669
871
  getAttachment(accountId, messageId, attachmentId, maxBytes) {
670
872
  return this.withProvider(accountId, (p) => p.getAttachment(messageId, attachmentId, { maxBytes }));
671
873
  }
874
+ assertMailContent(input) {
875
+ const bodyBytes = Buffer.byteLength(input.body.text ?? '', 'utf8') + Buffer.byteLength(input.body.html ?? '', 'utf8');
876
+ if (bodyBytes > 1024 * 1024) {
877
+ throw new ClientInputError('invalid_request', 'Text and HTML bodies together must be at most 1 MiB.');
878
+ }
879
+ const attachments = input.attachments ?? [];
880
+ if (attachments.length > 20)
881
+ throw new ClientInputError('invalid_request', 'A message may have at most 20 attachments.');
882
+ let total = 0;
883
+ for (const attachment of attachments) {
884
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(attachment.content)) {
885
+ throw new ClientInputError('invalid_request', 'Attachment content must be base64.');
886
+ }
887
+ total += Buffer.byteLength(attachment.content, 'base64');
888
+ if (total > this.maxAttachmentBytes) {
889
+ throw new ClientInputError('invalid_request', 'Combined attachments exceed the configured size limit.');
890
+ }
891
+ }
892
+ }
672
893
  }
673
894
  export function buildForwardBody(original, comment) {
674
895
  const headerLines = [