fluxmail 0.27.0 → 0.29.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 (59) hide show
  1. package/dist/cli.d.ts +2 -1
  2. package/dist/cli.d.ts.map +1 -1
  3. package/dist/cli.js +22 -3
  4. package/dist/cli.js.map +1 -1
  5. package/dist/cliCloudClient.d.ts +2 -0
  6. package/dist/cliCloudClient.d.ts.map +1 -1
  7. package/dist/cliCloudClient.js +18 -3
  8. package/dist/cliCloudClient.js.map +1 -1
  9. package/dist/cliMail.d.ts +3 -0
  10. package/dist/cliMail.d.ts.map +1 -1
  11. package/dist/cliMail.js +18 -1
  12. package/dist/cliMail.js.map +1 -1
  13. package/dist/cliMailBackend.d.ts +3 -0
  14. package/dist/cliMailBackend.d.ts.map +1 -1
  15. package/dist/cliMailBackend.js +6 -0
  16. package/dist/cliMailBackend.js.map +1 -1
  17. package/dist/http/rest.d.ts.map +1 -1
  18. package/dist/http/rest.js +63 -16
  19. package/dist/http/rest.js.map +1 -1
  20. package/dist/mcp/buildServer.d.ts.map +1 -1
  21. package/dist/mcp/buildServer.js +143 -32
  22. package/dist/mcp/buildServer.js.map +1 -1
  23. package/dist/mcp/missingTools.d.ts +10 -0
  24. package/dist/mcp/missingTools.d.ts.map +1 -0
  25. package/dist/mcp/missingTools.js +50 -0
  26. package/dist/mcp/missingTools.js.map +1 -0
  27. package/dist/mcp/outputSchemas.d.ts +6 -0
  28. package/dist/mcp/outputSchemas.d.ts.map +1 -1
  29. package/dist/mcp/outputSchemas.js +1 -0
  30. package/dist/mcp/outputSchemas.js.map +1 -1
  31. package/dist/mcp/pdfTextWorker.js +8 -3
  32. package/dist/mcp/pdfTextWorker.js.map +1 -1
  33. package/dist/permissions.js +1 -1
  34. package/dist/permissions.js.map +1 -1
  35. package/dist/service/deliveryCoordinator.d.ts +54 -0
  36. package/dist/service/deliveryCoordinator.d.ts.map +1 -1
  37. package/dist/service/deliveryCoordinator.js +144 -7
  38. package/dist/service/deliveryCoordinator.js.map +1 -1
  39. package/dist/service/emailService.d.ts +80 -5
  40. package/dist/service/emailService.d.ts.map +1 -1
  41. package/dist/service/emailService.js +303 -43
  42. package/dist/service/emailService.js.map +1 -1
  43. package/dist/service/publicErrors.d.ts +14 -0
  44. package/dist/service/publicErrors.d.ts.map +1 -1
  45. package/dist/service/publicErrors.js +21 -2
  46. package/dist/service/publicErrors.js.map +1 -1
  47. package/dist/storage/db.d.ts +21 -2
  48. package/dist/storage/db.d.ts.map +1 -1
  49. package/dist/storage/db.js +10 -1
  50. package/dist/storage/db.js.map +1 -1
  51. package/dist/storage/scheduledSends.d.ts +7 -0
  52. package/dist/storage/scheduledSends.d.ts.map +1 -1
  53. package/dist/storage/scheduledSends.js +16 -0
  54. package/dist/storage/scheduledSends.js.map +1 -1
  55. package/dist/telemetry.d.ts +27 -0
  56. package/dist/telemetry.d.ts.map +1 -1
  57. package/dist/telemetry.js +53 -1
  58. package/dist/telemetry.js.map +1 -1
  59. package/package.json +9 -8
@@ -1,17 +1,21 @@
1
1
  import { assertSearchCapabilities, buildForwardBody, buildReplyBody, isValidTimeZone, quotedImages, computeReplyRecipients, EmailError, formatAddressList, forwardSubject, isEmailError, normalizeEmailQuery, parseSingleAddress, replySubject, selectReplySender, } from '@fluxmail/core';
2
- import { randomBytes } from 'node:crypto';
2
+ import { createHmac, randomBytes } from 'node:crypto';
3
+ import { isSendConfirmationKey, issueSendConfirmationKey, readSendConfirmationKey, repeatsCardSend, SEND_CONFIRMATION_REPEAT_MESSAGE, SEND_CONFIRMATION_REPEAT_WINDOW_MS, sendConfirmationContentHash, sendConfirmationKeyContentHash, sendConfirmationMatchHash, } from '@fluxmail/core/mcp';
3
4
  import { SearchCursorCodec } from '@fluxmail/core/search-cursor';
4
5
  import { assertWithinQuota, checkLicenseState } from '../licensing/entitlements.js';
5
6
  import { listMembers } from '../storage/members.js';
6
7
  import { canAccessAccount, canAdminister, canSeeAccountMetadata } from '../authorization.js';
7
- import { cancelScheduledSend, countPending, createScheduledSend, findPendingByDraft, getScheduledSend, listScheduledSends, markSent, } from '../storage/scheduledSends.js';
8
- import { DeliveryCoordinator, isDefiniteDeliveryFailure } from './deliveryCoordinator.js';
9
- import { ClientInputError } from './publicErrors.js';
8
+ import { hasCapability } from '../permissions.js';
9
+ import { cancelScheduledSend, countPending, createScheduledSend, findActiveByDraft, findPendingByDraft, getScheduledSend, listScheduledSends, markSent, updateActiveSummary, } from '../storage/scheduledSends.js';
10
+ import { DeliveryCoordinator, deliveryFailure, isDefiniteDeliveryFailure, refuseBeforeSend, wasRefusedBeforeSend, } from './deliveryCoordinator.js';
11
+ import { asCardRefusal, ClientInputError, MissingCapabilityError, SendConfirmationError } from './publicErrors.js';
10
12
  import { logFailure } from '../logging.js';
11
13
  import { DEFAULT_MAX_ATTACHMENT_BYTES } from '../config.js';
12
14
  import { listConfiguredSendAs, replaceConfiguredSendAs } from '../storage/sendAs.js';
13
15
  const BATCH_REJECTIONS_TO_RETRY = new Set(['invalid_request', 'not_found', 'unsupported_capability']);
14
16
  const SCHEDULE_GRACE_MS = 60_000;
17
+ /** How long a preview waits for the sender's display name before showing the address alone. */
18
+ export const SENDER_NAME_TIMEOUT_MS = 2_000;
15
19
  const SCHEDULE_MAX_HORIZON_MS = 365 * 24 * 3_600_000;
16
20
  const SEARCH_SOFT_BUDGET_MS = 15_000;
17
21
  export const SEARCH_HARD_DEADLINE_MS = 30_000;
@@ -295,6 +299,15 @@ export class EmailService {
295
299
  listFolders(accountId) {
296
300
  return this.withProvider(accountId, (p) => p.listFolders());
297
301
  }
302
+ /** Creates a folder, or returns the existing one with that name. */
303
+ createFolder(accountId, name) {
304
+ return this.withProvider(accountId, (p) => {
305
+ if (!p.createFolder) {
306
+ throw new EmailError('unsupported_capability', 'This mailbox does not support creating folders.');
307
+ }
308
+ return p.createFolder(name);
309
+ });
310
+ }
298
311
  listLabels(accountId) {
299
312
  return this.withProvider(accountId, (p) => p.listLabels());
300
313
  }
@@ -498,26 +511,152 @@ export class EmailService {
498
511
  return p.createDraft(await this.resolveRecipients(p, account, d));
499
512
  });
500
513
  }
501
- async updateDraft(accountId, draftId, d) {
514
+ async updateDraft(accountId, draftId, d, options = {}) {
502
515
  this.assertMailContent(d);
503
- return this.withProvider(accountId, async (p, _id, account) => {
504
- return p.updateDraft(draftId, await this.resolveRecipients(p, account, d));
516
+ // Checked before the provider runs, so a refusal isn't reported as a provider failure.
517
+ const resolvedId = this.resolveScopedAccountId(accountId);
518
+ this.assertScheduledDraftChangeable(resolvedId, draftId, options);
519
+ const { updated, matched } = await this.withProvider(resolvedId, async (p, _id, account) => {
520
+ const { draft, subject } = await this.resolveSend(p, account, d);
521
+ return { updated: await p.updateDraft(draftId, draft), matched: { ...draft, subject } };
522
+ });
523
+ // A scheduled draft sends as edited, so the schedule shows its new subject and recipients, and a send
524
+ // card compares against the new ones.
525
+ updateActiveSummary(this.db, resolvedId, draftId, {
526
+ subject: updated.subject ?? null,
527
+ toRecipients: updated.to?.length ? formatAddressList(updated.to) : null,
505
528
  });
529
+ // The draft is already changed, so a failure here is only logged, as for a send's digest.
530
+ try {
531
+ new DeliveryCoordinator(this.db).setDraftMatchHash(resolvedId, draftId, this.matchHash(matched));
532
+ }
533
+ catch (error) {
534
+ logFailure(this.logger, 'mail.delivery_match_failed', error);
535
+ }
536
+ return updated;
506
537
  }
507
- deleteDraft(accountId, draftId) {
508
- return this.withProvider(accountId, (p) => p.deleteDraft(draftId));
538
+ async deleteDraft(accountId, draftId, options = {}) {
539
+ const resolvedId = this.resolveScopedAccountId(accountId);
540
+ this.assertScheduledDraftChangeable(resolvedId, draftId, options);
541
+ return this.withProvider(resolvedId, (p) => p.deleteDraft(draftId));
542
+ }
543
+ /**
544
+ * A scheduled draft is sent later by the instance, so a connection that can't send may not change or
545
+ * delete it while it waits: it could otherwise decide what goes out. Connections with mail.send can.
546
+ */
547
+ assertScheduledDraftChangeable(accountId, draftId, options) {
548
+ const canSend = options.canSend ?? (this.principal ? hasCapability(this.principal.permissions, 'mail.send') : true);
549
+ if (canSend)
550
+ return;
551
+ const schedule = findActiveByDraft(this.db, accountId, draftId);
552
+ if (!schedule)
553
+ return;
554
+ throw new MissingCapabilityError(schedule.status === 'sending'
555
+ ? 'This draft is being sent now, so changing it requires mail.send permission.'
556
+ : 'This draft is scheduled to send, so changing it requires mail.send permission. Cancel the scheduled send first, then edit the draft.', ['mail.send']);
509
557
  }
510
558
  getDraft(accountId, draftId) {
511
559
  return this.withProvider(accountId, (p) => p.getDraft(draftId));
512
560
  }
513
- previewSend(accountId, input) {
514
- return this.withProvider(accountId, async (provider, resolvedId, account) => {
515
- if ('draftId' in input) {
516
- const draft = await provider.getDraft(input.draftId);
517
- if (draft.from?.email && draft.from.email.toLowerCase() !== account.email.toLowerCase()) {
518
- await this.validateSender(provider, resolvedId, account, draft.from.email);
519
- }
520
- return {
561
+ async previewSend(accountId, input) {
562
+ return (await this.previewSendWithBody(accountId, input)).preview;
563
+ }
564
+ /** The secret that signs send confirmation card keys, derived from the store's persistent secret. */
565
+ get confirmationSecret() {
566
+ return createHmac('sha256', this.cursorSecret).update('fluxmail send confirmation key').digest();
567
+ }
568
+ /** A card idempotency key bound to this preview's resolved message and time. */
569
+ sendConfirmationKey(preview, body) {
570
+ return issueSendConfirmationKey(this.confirmationSecret, sendConfirmationContentHash({ ...preview, body }));
571
+ }
572
+ /**
573
+ * Refuses a send from a confirmation card when the key is not one this server issued, the message no longer
574
+ * matches the preview the user approved, or the same email was sent or scheduled from the mailbox after the
575
+ * preview. A repeat of the card's own send passes, so the ledger returns its saved result.
576
+ */
577
+ async checkConfirmedSend(accountId, input, key) {
578
+ const card = readSendConfirmationKey(this.confirmationSecret, key);
579
+ if (!card)
580
+ return;
581
+ if (card === 'invalid') {
582
+ throw asCardRefusal(new ClientInputError('invalid_request', 'This preview has expired. Ask for a new preview.'), 'expired');
583
+ }
584
+ const resolvedId = this.resolveScopedAccountId(accountId);
585
+ if (!this.principal)
586
+ throw new EmailError('permission_denied', 'A member session is required.');
587
+ const coordinator = new DeliveryCoordinator(this.db);
588
+ const { principalId, memberId } = this.principal;
589
+ if (coordinator.findByKey(principalId, key))
590
+ return;
591
+ const sent = () => asCardRefusal(new SendConfirmationError('This email may have been sent already. Check your Sent folder.'), 'sent');
592
+ let resolved;
593
+ try {
594
+ resolved = await this.previewSendWithBody(accountId, input);
595
+ }
596
+ catch (error) {
597
+ // A draft that was sent is gone, so the message can't be compared: any later send counts. A schedule
598
+ // that hasn't fired keeps its draft, so it doesn't explain the failure.
599
+ if (coordinator.deliverySince(memberId, resolvedId, card.issuedAt, key) === 'sent')
600
+ throw sent();
601
+ throw asCardRefusal(error, 'unresolved');
602
+ }
603
+ if (sendConfirmationContentHash({ ...resolved.preview, body: resolved.body }) !== card.contentHash) {
604
+ throw asCardRefusal(new SendConfirmationError('This email changed after the preview. Ask for a new preview.'), 'changed');
605
+ }
606
+ const overtaken = coordinator.deliverySince(memberId, resolvedId, card.issuedAt, key, {
607
+ matchHash: this.matchHash(resolved.preview),
608
+ ...('draftId' in input ? { draftId: input.draftId } : {}),
609
+ });
610
+ if (overtaken === 'scheduled') {
611
+ throw asCardRefusal(new SendConfirmationError('This email is already scheduled. To send it now, cancel the scheduled send and ask for a new preview.'), 'scheduled');
612
+ }
613
+ if (overtaken)
614
+ throw sent();
615
+ }
616
+ /**
617
+ * Refuses a send made without the card when a card just sent the same email, so a user who clicked Send on
618
+ * the card and then told the assistant to send doesn't send it twice. It runs once the send has claimed
619
+ * its key and resolved its message, just before the message goes out or is saved to send later, so it sees
620
+ * a card send that started in the meantime and reads nothing from the provider itself. A failure to read
621
+ * the ledger must not stop the send.
622
+ */
623
+ refuseCardRepeat(coordinator, accountId, key, contentHash, sendsAt = Date.now()) {
624
+ // A card's own send is checked by `checkConfirmedSend`, and a forward is never what a card sent.
625
+ if (!contentHash || isSendConfirmationKey(key))
626
+ return;
627
+ let repeated;
628
+ try {
629
+ const cardSends = coordinator
630
+ .sendsSince(this.principal.memberId, accountId, sendsAt - SEND_CONFIRMATION_REPEAT_WINDOW_MS)
631
+ .flatMap(({ key: sentKey, sentAt }) => {
632
+ const sentHash = sendConfirmationKeyContentHash(sentKey);
633
+ return sentHash ? [{ contentHash: sentHash, sentAt }] : [];
634
+ });
635
+ repeated = cardSends.length > 0 && repeatsCardSend(contentHash(), cardSends, sendsAt);
636
+ }
637
+ catch (error) {
638
+ logFailure(this.logger, 'mail.card_repeat_check_failed', error);
639
+ return;
640
+ }
641
+ if (repeated)
642
+ throw refuseBeforeSend(new SendConfirmationError(SEND_CONFIRMATION_REPEAT_MESSAGE));
643
+ }
644
+ /**
645
+ * Reports a delivery that `refuseCardRepeat` stopped. The delivery is recorded as failed, so a retry of its
646
+ * key returns that, and this call tells the caller why. The error is made here, outside the provider call,
647
+ * so it carries no provider.
648
+ */
649
+ throwIfCardRepeat(operation) {
650
+ if (wasRefusedBeforeSend(deliveryFailure(operation)?.cause)) {
651
+ throw asCardRefusal(new SendConfirmationError(SEND_CONFIRMATION_REPEAT_MESSAGE), 'repeated');
652
+ }
653
+ }
654
+ /** The preview a card shows for a resolved message, the body it sends, and so the hash the card gives it. */
655
+ shownMessage(resolvedId, account, message) {
656
+ if ('saved' in message) {
657
+ const draft = message.saved;
658
+ return {
659
+ preview: {
521
660
  accountId: resolvedId,
522
661
  from: draft.from?.email ?? account.email,
523
662
  to: draft.to,
@@ -531,13 +670,13 @@ export class EmailService {
531
670
  })),
532
671
  bodyTextChars: draft.body?.text?.length ?? 0,
533
672
  bodyHtmlChars: draft.body?.html?.length ?? 0,
534
- };
535
- }
536
- this.assertMailContent(input);
537
- const resolved = await this.resolveRecipients(provider, account, input);
538
- const subject = resolved.subject ??
539
- (input.replyToMessageId ? replySubject((await provider.getMessage(input.replyToMessageId)).subject) : '');
540
- return {
673
+ },
674
+ body: draft.body ?? {},
675
+ };
676
+ }
677
+ const { draft: resolved, subject } = message;
678
+ return {
679
+ preview: {
541
680
  accountId: resolvedId,
542
681
  from: resolved.from ?? account.email,
543
682
  to: resolved.to ?? [],
@@ -551,9 +690,90 @@ export class EmailService {
551
690
  })),
552
691
  bodyTextChars: resolved.body.text?.length ?? 0,
553
692
  bodyHtmlChars: resolved.body.html?.length ?? 0,
693
+ },
694
+ body: resolved.body,
695
+ };
696
+ }
697
+ contentHash(resolvedId, account, message) {
698
+ const shown = this.shownMessage(resolvedId, account, message);
699
+ return sendConfirmationContentHash({ ...shown.preview, body: shown.body });
700
+ }
701
+ /**
702
+ * Stores a delivery's match digest. A failure must not stop the send: a delivery without a digest counts
703
+ * as the same email for every card issued before it, and a schedule without one also once it fires.
704
+ */
705
+ recordMatch(coordinator, key, message) {
706
+ try {
707
+ coordinator.setMatchHash(this.principal.principalId, key, this.matchHash(message));
708
+ }
709
+ catch (error) {
710
+ logFailure(this.logger, 'mail.delivery_match_failed', error);
711
+ }
712
+ }
713
+ /** The digest a delivery is matched by: who it goes to and its subject. */
714
+ matchHash(message) {
715
+ return sendConfirmationMatchHash(this.confirmationSecret, {
716
+ to: message.to ?? [],
717
+ cc: message.cc ?? [],
718
+ bcc: message.bcc ?? [],
719
+ subject: message.subject ?? '',
720
+ });
721
+ }
722
+ /**
723
+ * The preview and the body as it will be sent, including a quoted original. With `senderName`, also the
724
+ * display name the From header will carry, left out when there is none or it can't be known.
725
+ */
726
+ previewSendWithBody(accountId, input, options = {}) {
727
+ return this.withProvider(accountId, async (provider, resolvedId, account) => {
728
+ if ('draftId' in input) {
729
+ const draft = await provider.getDraft(input.draftId);
730
+ if (draft.from?.email && draft.from.email.toLowerCase() !== account.email.toLowerCase()) {
731
+ await this.validateSender(provider, resolvedId, account, draft.from.email);
732
+ }
733
+ // Draft attachments carry no content, so the card shows their inline images as placeholders.
734
+ // A saved draft is sent as stored, so it keeps the name it has.
735
+ const fromName = options.senderName ? draft.from?.name : undefined;
736
+ return {
737
+ ...this.shownMessage(resolvedId, account, { saved: draft }),
738
+ inlineImages: [],
739
+ ...(fromName ? { fromName } : {}),
740
+ };
741
+ }
742
+ this.assertMailContent(input);
743
+ const { draft: resolved, subject } = await this.resolveSend(provider, account, input);
744
+ const inlineImages = (resolved.attachments ?? []).filter((attachment) => attachment.contentId);
745
+ const fromName = options.senderName ? await this.senderName(provider, resolved.from) : undefined;
746
+ return {
747
+ ...this.shownMessage(resolvedId, account, { draft: resolved, subject }),
748
+ inlineImages,
749
+ ...(fromName ? { fromName } : {}),
554
750
  };
555
751
  });
556
752
  }
753
+ /**
754
+ * The name a send from this address will carry. The name only decorates the preview, so a lookup that
755
+ * fails or takes longer than SENDER_NAME_TIMEOUT_MS leaves it out instead of failing or holding the preview.
756
+ */
757
+ async senderName(provider, from) {
758
+ if (!provider.senderName)
759
+ return undefined;
760
+ let timer;
761
+ try {
762
+ return await Promise.race([
763
+ provider.senderName(from),
764
+ new Promise((resolve) => {
765
+ timer = setTimeout(() => resolve(undefined), SENDER_NAME_TIMEOUT_MS);
766
+ }),
767
+ ]);
768
+ }
769
+ catch (error) {
770
+ logFailure(this.logger, 'mail.sender_name_failed', error);
771
+ return undefined;
772
+ }
773
+ finally {
774
+ clearTimeout(timer);
775
+ }
776
+ }
557
777
  getDelivery(accountId, operationId) {
558
778
  // Like a send, the lookup defaults to the only account this connection can use.
559
779
  const resolvedId = this.resolveScopedAccountId(accountId);
@@ -561,19 +781,28 @@ export class EmailService {
561
781
  throw new EmailError('permission_denied', 'A member session is required.');
562
782
  return new DeliveryCoordinator(this.db).get(this.principal.principalId, this.principal.memberId, resolvedId, operationId);
563
783
  }
564
- async deliver(accountId, input, key) {
784
+ async deliver(accountId, input, key,
785
+ // Set for a send an assistant makes over MCP, which may repeat one its user just made from the card.
786
+ options = {}) {
565
787
  const resolvedId = this.resolveScopedAccountId(accountId);
566
788
  if (!this.principal)
567
789
  throw new EmailError('permission_denied', 'A member session is required.');
568
790
  let sent;
569
- const operation = await new DeliveryCoordinator(this.db).run({
570
- principalId: this.principal.principalId,
791
+ const coordinator = new DeliveryCoordinator(this.db);
792
+ const { principalId } = this.principal;
793
+ const operation = await coordinator.run({
794
+ principalId,
571
795
  memberId: this.principal.memberId,
572
796
  accountId: resolvedId,
573
797
  key,
574
798
  kind: 'send',
575
799
  request: input,
576
- }, async () => (sent = await this.sendMessage(resolvedId, input)).result);
800
+ }, async () => (sent = await this.sendMessage(resolvedId, input, (message, contentHash) => {
801
+ if (options.refuseCardRepeat)
802
+ this.refuseCardRepeat(coordinator, resolvedId, key, contentHash);
803
+ this.recordMatch(coordinator, key, message);
804
+ })).result);
805
+ this.throwIfCardRepeat(operation);
577
806
  await this.markOriginal(resolvedId, sent);
578
807
  return operation;
579
808
  }
@@ -582,14 +811,17 @@ export class EmailService {
582
811
  if (!this.principal)
583
812
  throw new EmailError('permission_denied', 'A member session is required.');
584
813
  let sent;
585
- const operation = await new DeliveryCoordinator(this.db).run({
586
- principalId: this.principal.principalId,
814
+ const coordinator = new DeliveryCoordinator(this.db);
815
+ const { principalId } = this.principal;
816
+ const operation = await coordinator.run({
817
+ principalId,
587
818
  memberId: this.principal.memberId,
588
819
  accountId: resolvedId,
589
820
  key,
590
821
  kind: 'forward',
591
822
  request: input,
592
- }, async () => (sent = await this.forwardMessage(resolvedId, input)).result);
823
+ }, async () => (sent = await this.forwardMessage(resolvedId, input, (message) => this.recordMatch(coordinator, key, message)))
824
+ .result);
593
825
  await this.markOriginal(resolvedId, sent);
594
826
  return operation;
595
827
  }
@@ -611,21 +843,34 @@ export class EmailService {
611
843
  return result;
612
844
  }), ownsClaim);
613
845
  }
614
- scheduleDelivery(accountId, input, sendAt, key) {
846
+ scheduleDelivery(accountId, input, sendAt, key,
847
+ // Set for a schedule an assistant makes over MCP, which may repeat a send its user just made from the card.
848
+ options = {}) {
615
849
  const resolvedId = this.resolveScopedAccountId(accountId);
616
850
  if (!this.principal)
617
851
  throw new EmailError('permission_denied', 'A member session is required.');
618
852
  let createdSchedule = false;
619
- const scheduled = new DeliveryCoordinator(this.db).schedule({
853
+ const coordinator = new DeliveryCoordinator(this.db);
854
+ const scheduled = coordinator
855
+ .schedule({
620
856
  principalId: this.principal.principalId,
621
857
  memberId: this.principal.memberId,
622
858
  accountId: resolvedId,
623
859
  key,
624
860
  request: { input, sendAt },
625
861
  }, async () => {
626
- const result = await this.createSchedule(resolvedId, input, sendAt);
862
+ const result = await this.createSchedule(resolvedId, input, sendAt, (message, contentHash, sendTime) => {
863
+ if (options.refuseCardRepeat) {
864
+ this.refuseCardRepeat(coordinator, resolvedId, key, contentHash, sendTime);
865
+ }
866
+ this.recordMatch(coordinator, key, message);
867
+ });
627
868
  createdSchedule = true;
628
869
  return result;
870
+ })
871
+ .then((operation) => {
872
+ this.throwIfCardRepeat(operation);
873
+ return operation;
629
874
  });
630
875
  return scheduled.finally(() => {
631
876
  if (createdSchedule)
@@ -637,7 +882,7 @@ export class EmailService {
637
882
  await this.markOriginal(accountId, sent);
638
883
  return sent.result;
639
884
  }
640
- async sendMessage(accountId, input) {
885
+ async sendMessage(accountId, input, onResolved) {
641
886
  if (!('draftId' in input))
642
887
  this.assertMailContent(input);
643
888
  return this.withProvider(accountId, async (p, resolvedId, account) => {
@@ -648,6 +893,7 @@ export class EmailService {
648
893
  }
649
894
  // Sending removes the draft, so find the message it replies to first.
650
895
  const repliedTo = await this.findRepliedMessage(p, input.draftId);
896
+ onResolved?.(draft, () => this.contentHash(resolvedId, account, { saved: draft }));
651
897
  const result = await p.send({ draftId: input.draftId });
652
898
  // Sending a scheduled draft now supersedes its schedule.
653
899
  const pending = findPendingByDraft(this.db, resolvedId, input.draftId);
@@ -657,7 +903,9 @@ export class EmailService {
657
903
  }
658
904
  return { result, ...(repliedTo ? { original: { id: repliedTo, action: 'reply' } } : {}) };
659
905
  }
660
- const result = await p.send(await this.resolveRecipients(p, account, input));
906
+ const { draft, subject } = await this.resolveSend(p, account, input);
907
+ onResolved?.({ ...draft, subject }, () => this.contentHash(resolvedId, account, { draft, subject }));
908
+ const result = await p.send(draft);
661
909
  return {
662
910
  result,
663
911
  ...(input.replyToMessageId ? { original: { id: input.replyToMessageId, action: 'reply' } } : {}),
@@ -699,24 +947,31 @@ export class EmailService {
699
947
  this.onScheduleChanged();
700
948
  return scheduled;
701
949
  }
702
- async createSchedule(accountId, input, sendAtIso) {
950
+ async createSchedule(accountId, input, sendAtIso, onResolved) {
703
951
  if (!('draftId' in input) && !('forward' in input))
704
952
  this.assertMailContent(input);
705
953
  const sendAt = resolveSendAt(sendAtIso);
706
954
  const { draft, resolvedId } = await this.withProvider(accountId, async (p, id, account) => {
955
+ // The match digest comes from the message as resolved here, as a send computes it, and before the
956
+ // provider saves the draft, which may not return every field.
707
957
  let message;
708
958
  if ('draftId' in input) {
709
- message = await p.getDraft(input.draftId);
959
+ const saved = await p.getDraft(input.draftId);
960
+ message = saved;
961
+ onResolved?.(saved, () => this.contentHash(id, account, { saved }), sendAt);
710
962
  }
711
963
  else if ('forward' in input) {
712
964
  // A scheduled forward is saved as a draft now, with the original's attachments, and sent later.
713
- message = await p.createDraft((await this.forwardDraft(p, id, account, input.forward)).draft);
965
+ const { draft: forward } = await this.forwardDraft(p, id, account, input.forward);
966
+ onResolved?.(forward, undefined, sendAt);
967
+ message = await p.createDraft(forward);
714
968
  }
715
969
  else {
716
- const resolved = await this.resolveRecipients(p, account, input);
970
+ const { draft: resolved, subject } = await this.resolveSend(p, account, input);
717
971
  if (!resolved.to?.length && !resolved.cc?.length && !resolved.bcc?.length) {
718
972
  throw new ClientInputError('invalid_request', 'Cannot schedule a message with no recipients');
719
973
  }
974
+ onResolved?.({ ...resolved, subject }, () => this.contentHash(id, account, { draft: resolved, subject }), sendAt);
720
975
  message = await p.createDraft(resolved);
721
976
  }
722
977
  return { draft: message, resolvedId: id };
@@ -774,6 +1029,10 @@ export class EmailService {
774
1029
  * reply; plus original To/Cc (minus our own address) for reply-all.
775
1030
  */
776
1031
  async resolveRecipients(p, account, input) {
1032
+ return (await this.resolveSend(p, account, input)).draft;
1033
+ }
1034
+ /** The message as the provider will send it, and its subject: a reply without one gets the original's. */
1035
+ async resolveSend(p, account, input) {
777
1036
  const { replyAll, timeZone, quoteOriginal, ...draft } = input;
778
1037
  if (timeZone !== undefined && !isValidTimeZone(timeZone)) {
779
1038
  throw new ClientInputError('invalid_request', 'timeZone must be an IANA time zone name, such as America/New_York.');
@@ -781,7 +1040,7 @@ export class EmailService {
781
1040
  if (!draft.replyToMessageId) {
782
1041
  if (draft.from)
783
1042
  draft.from = (await this.validateSender(p, account.id, account, draft.from)).email;
784
- return draft;
1043
+ return { draft, subject: draft.subject ?? '' };
785
1044
  }
786
1045
  const original = await p.getMessage(draft.replyToMessageId);
787
1046
  const identities = await this.sendAsIdentities(p, account.id, account);
@@ -808,7 +1067,7 @@ export class EmailService {
808
1067
  if (recipients.cc.length && !draft.cc?.length)
809
1068
  draft.cc = recipients.cc;
810
1069
  }
811
- return draft;
1070
+ return { draft, subject: draft.subject ?? replySubject(original.subject) };
812
1071
  }
813
1072
  /**
814
1073
  * The images the quoted original's HTML shows, within the message's attachment limits. An image that
@@ -886,9 +1145,10 @@ export class EmailService {
886
1145
  await this.markOriginal(accountId, sent);
887
1146
  return sent.result;
888
1147
  }
889
- async forwardMessage(accountId, input) {
1148
+ async forwardMessage(accountId, input, onResolved) {
890
1149
  return this.withProvider(accountId, async (p, resolvedId, account) => {
891
1150
  const { draft, original } = await this.forwardDraft(p, resolvedId, account, input);
1151
+ onResolved?.(draft);
892
1152
  return { result: await p.send(draft), original: { id: original.id, action: 'forward' } };
893
1153
  });
894
1154
  }