@wtfalch/email 0.11.0 → 0.13.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.
package/README.md CHANGED
@@ -47,7 +47,16 @@ by JMAP result reference in a single request.
47
47
  compute the recipients, the subject prefix, the `In-Reply-To` and `References`
48
48
  chain and the quoted body, with no client and no network, so a composer can
49
49
  call them on every keystroke. `send` creates the draft, submits it, and files
50
- it in Sent. `attach` uploads a file and gives back what a draft carries; the
50
+ it in Sent; a `delay` in seconds holds it there first, and `cancel` unsends
51
+ it while `undoStatus` is still `'pending'` — the only honest sign the window
52
+ is still open, since a server not set up for held delivery answers `'final'`
53
+ regardless. `queued` lists everything still held, soonest first, for a
54
+ "scheduled" view that survives a reload: it filters its query on `undoStatus`
55
+ rather than reading the field off an unfiltered one, since that filter is
56
+ what makes the server recheck each submission against the mail queue and
57
+ demote one that already went, instead of answering a stale `'pending'`. Every
58
+ row it returns is safe to hand straight to `cancel`. `attach` uploads a file
59
+ and gives back what a draft carries; the
51
60
  upload is refused before any of it is sent when the file is over the
52
61
  session's `maxSizeUpload`, which `client.session()` reports alongside
53
62
  `maxSizeAttachmentsPerEmail`.
@@ -264,11 +273,25 @@ impossible; the guesses were wrong, not the feature.
264
273
  `createApiKey` therefore mints a scoped key by default. `DASHBOARD_PERMISSIONS`
265
274
  is the set verified on 0.16.20: `authenticate` plus `sysAccountQuery`,
266
275
  `sysAccountGet`, `sysAccountCreate`, `sysAccountUpdate`, `sysDomainQuery`,
267
- `sysDomainGet` and `sysSystemSettingsGet`. It serves every `/email` page, and
276
+ `sysDomainGet`, `sysSystemSettingsGet`, `sysMtaExtensionsGet`,
277
+ `sysMtaExtensionsUpdate` and `sysActionCreate`. It serves every `/email` page, and
268
278
  it is `forbidden` on `Email/query` for every account on the instance —
269
279
  including its own, so the key administers mail and cannot read any. Pass
270
280
  `'inherit'` for a key as powerful as the account; prefer not to.
271
281
 
282
+ `sysActionCreate` is the widest of these: Stalwart has one permission for
283
+ every action, so the key that can reload settings can also pause the mail
284
+ queue. It is there because a changed setting does nothing until a
285
+ `ReloadSettings` action runs. A key minted before a name joined the set does
286
+ not gain it; mint a new one.
287
+
288
+ **A server that is not holding mail says nothing.** With
289
+ `MtaExtensions.futureRelease` unset, Stalwart sends a held submission at once
290
+ and reports it as held. Provisioning sets it (`FUTURE_RELEASE`, 30 days); an
291
+ instance provisioned before it did stays off. `holdLimit(instance)` returns
292
+ the limit, or `null` when the server will not hold at all, and
293
+ `enableHolding(instance)` sets it and reloads.
294
+
272
295
  **An API key can never create a credential.** It authenticates, and both
273
296
  `x:ApiKey/set` and `x:AppPassword/set` answer `forbidden` whatever permissions
274
297
  it holds, so a key cannot mint its own successor. Rotating one needs the
@@ -312,7 +335,7 @@ instead.
312
335
 
313
336
  ## The audit
314
337
 
315
- `createMailbox`, `addAlias`, `removeAlias` and `revokeAppPassword` take an
338
+ `createMailbox`, `addAlias`, `removeAlias`, `revokeAppPassword` and `enableHolding` take an
316
339
  optional last argument, a `PostmasterAudit`: a `write` the host bound to its
317
340
  own ledger, the principal it resolved for this request, and the request id
318
341
  its log uses. Without one, nothing changes.
@@ -62,6 +62,11 @@ export declare class FakeMailbox {
62
62
  size: number;
63
63
  }[];
64
64
  constructor(options?: FakeOptions);
65
+ /** Move the fake's clock forward by `ms` milliseconds. The only way `#now`
66
+ * changes after construction, so a test can hold a submission, advance
67
+ * past its `sendAt`, and see the cancel window close -- deterministically,
68
+ * with no real wait and no wall-clock read. */
69
+ advance(ms: number): void;
65
70
  /** Put a thread in the mailbox. Returns its id. */
66
71
  add(seed: SeedThread): string;
67
72
  /** The session document, as Stalwart writes it. */
@@ -25,8 +25,19 @@ const MAILBOXES = [
25
25
  ];
26
26
  /** Stalwart's default for both limits, as `fixtures/instance-one.json` has it. */
27
27
  const STALWART_MAX_SIZE = 50_000_000;
28
+ /** A UTC instant the way a JMAP server writes one. RFC 8620 §1.4 requires the
29
+ * fractional part to be **omitted when it is zero**, which
30
+ * `Date.prototype.toISOString()` never does -- it always pads three digits.
31
+ * A fake that only ever emits `.000` hides every bug that depends on a real
32
+ * server's mixed precision, so it emits the spec's shape instead. */
33
+ function jmapDate(at) {
34
+ return at.toISOString().replace(/\.000Z$/, 'Z');
35
+ }
28
36
  export class FakeMailbox {
29
37
  me;
38
+ /** The fake's clock. Fixed at construction and moved only by `advance()`
39
+ * -- never a wall-clock read, so a cancel-window test stays
40
+ * deterministic. */
30
41
  #now;
31
42
  #latency;
32
43
  #maxSizeUpload;
@@ -36,6 +47,10 @@ export class FakeMailbox {
36
47
  /** Everything `EmailSubmission/set` accepted, for a test that asserts a
37
48
  * message was actually sent rather than only composed. */
38
49
  submissions = [];
50
+ /** Each submission's send-hold state, keyed by its id -- what the update
51
+ * (cancel) path needs to know that the flat `submissions` list above,
52
+ * kept only for the tests above, does not carry. */
53
+ #submissionState = new Map();
39
54
  /** Every blob uploaded, for a test that asserts the bytes reached the
40
55
  * server rather than only the composer. */
41
56
  uploads = [];
@@ -47,6 +62,13 @@ export class FakeMailbox {
47
62
  for (const seed of options.threads ?? [])
48
63
  this.add(seed);
49
64
  }
65
+ /** Move the fake's clock forward by `ms` milliseconds. The only way `#now`
66
+ * changes after construction, so a test can hold a submission, advance
67
+ * past its `sendAt`, and see the cancel window close -- deterministically,
68
+ * with no real wait and no wall-clock read. */
69
+ advance(ms) {
70
+ this.#now = new Date(this.#now.getTime() + ms);
71
+ }
50
72
  /** Put a thread in the mailbox. Returns its id. */
51
73
  add(seed) {
52
74
  const threadId = `t${++this.#counter}`;
@@ -329,17 +351,149 @@ export class FakeMailbox {
329
351
  case 'EmailSubmission/set': {
330
352
  const create = (args.create ?? {});
331
353
  const created = {};
354
+ const notCreated = {};
332
355
  for (const [key, submission] of Object.entries(create)) {
333
- this.submissions.push(submission);
334
- created[key] = { id: `sub-${this.submissions.length}`, undoStatus: 'final' };
335
- // The move to Sent that `onSuccessUpdateEmail` asks for.
356
+ // RFC 4865's send-delay parameter rides in the envelope, not a
357
+ // `sendAt` property, and Stalwart validates it as 1..=999999999.
358
+ const holdFor = this.#holdForSeconds(submission.envelope);
359
+ if (holdFor === 'invalid') {
360
+ notCreated[key] = {
361
+ type: 'invalidProperties',
362
+ properties: ['envelope'],
363
+ description: 'Failed to parse mailFrom parameters: HOLDFOR.',
364
+ };
365
+ continue;
366
+ }
367
+ this.submissions.push({ emailId: submission.emailId, identityId: submission.identityId });
368
+ const id = `sub-${this.submissions.length}`;
369
+ const sendAt = new Date(this.#now.getTime() + (holdFor ?? 0) * 1000);
370
+ const undoStatus = holdFor ? 'pending' : 'final';
371
+ this.#submissionState.set(id, { emailId: submission.emailId, sendAt, undoStatus });
372
+ created[key] = { id, sendAt: jmapDate(sendAt), undoStatus };
373
+ // The move to Sent that `onSuccessUpdateEmail` asks for. It runs
374
+ // immediately even on a held message: holding delays delivery,
375
+ // not filing.
336
376
  const email = this.#emails.find((one) => one.id === submission.emailId);
337
377
  if (email) {
338
378
  email.mailboxIds = { 'mb-sent': true };
339
379
  email.keywords = { $seen: true };
340
380
  }
341
381
  }
342
- return { accountId: ACCOUNT, oldState: '2', newState: '3', created, notCreated: null };
382
+ // `undoStatus: 'canceled'` is the only update this server accepts,
383
+ // and it is the unsend: valid only while the submission is still
384
+ // `pending` and its `sendAt` has not arrived. Destroy is handled
385
+ // separately below, and is not a cancel.
386
+ const update = (args.update ?? {});
387
+ const updated = {};
388
+ const notUpdated = {};
389
+ for (const [id, patch] of Object.entries(update)) {
390
+ if (patch.undoStatus !== 'canceled') {
391
+ notUpdated[id] = {
392
+ type: 'invalidProperties',
393
+ properties: ['undoStatus'],
394
+ description: 'Email submissions can only be cancelled.',
395
+ };
396
+ continue;
397
+ }
398
+ const record = this.#submissionState.get(id);
399
+ if (!record ||
400
+ record.undoStatus !== 'pending' ||
401
+ record.sendAt.getTime() <= this.#now.getTime()) {
402
+ notUpdated[id] = {
403
+ type: 'cannotUnsend',
404
+ description: 'The requested message is no longer in the queue.',
405
+ };
406
+ continue;
407
+ }
408
+ record.undoStatus = 'canceled';
409
+ updated[id] = null;
410
+ // The move back to Drafts that `onSuccessUpdateEmail` asks for on
411
+ // an unsend, the mirror of the create path's move to Sent above.
412
+ const email = this.#emails.find((one) => one.id === record.emailId);
413
+ if (email) {
414
+ email.mailboxIds = { 'mb-drafts': true };
415
+ email.keywords = { $draft: true, $seen: true };
416
+ }
417
+ }
418
+ // Destroy is not a cancel: Stalwart forgets the submission record
419
+ // but still sends the mail, so this only drops it from
420
+ // `#submissionState`. It must not touch a submission's status or
421
+ // move its email, or a destroy would silently double as an unsend --
422
+ // the asymmetry that makes destroy a trap rather than a shortcut.
423
+ const destroy = (args.destroy ?? []);
424
+ const destroyed = [];
425
+ const notDestroyed = {};
426
+ for (const id of destroy) {
427
+ if (this.#submissionState.has(id)) {
428
+ this.#submissionState.delete(id);
429
+ destroyed.push(id);
430
+ }
431
+ else {
432
+ notDestroyed[id] = { type: 'notFound' };
433
+ }
434
+ }
435
+ return {
436
+ accountId: ACCOUNT,
437
+ oldState: '2',
438
+ newState: '3',
439
+ created,
440
+ notCreated: Object.keys(notCreated).length > 0 ? notCreated : null,
441
+ updated: Object.keys(updated).length > 0 ? updated : null,
442
+ notUpdated: Object.keys(notUpdated).length > 0 ? notUpdated : null,
443
+ destroyed: destroyed.length > 0 ? destroyed : null,
444
+ notDestroyed: Object.keys(notDestroyed).length > 0 ? notDestroyed : null,
445
+ };
446
+ }
447
+ case 'EmailSubmission/query': {
448
+ const filter = (args.filter ?? {});
449
+ // Mirrors Stalwart's own rule (crates/jmap/src/submission/query.rs
450
+ // 106-127): a submission is only rechecked against the clock, and
451
+ // demoted from `pending` to `final` once its `sendAt` has passed,
452
+ // when the query itself filters on `undoStatus`. Do this
453
+ // unconditionally instead and every query -- not just the ones
454
+ // `queued()` sends -- would tell a caller a message had already
455
+ // gone, which is not what the real server does.
456
+ if (filter.undoStatus !== undefined) {
457
+ for (const record of this.#submissionState.values()) {
458
+ if (record.undoStatus === 'pending' && record.sendAt.getTime() <= this.#now.getTime()) {
459
+ record.undoStatus = 'final';
460
+ }
461
+ }
462
+ }
463
+ const ids = [...this.#submissionState.entries()]
464
+ .filter(([, record]) => filter.undoStatus === undefined || record.undoStatus === filter.undoStatus)
465
+ .map(([id]) => id);
466
+ return {
467
+ accountId: ACCOUNT,
468
+ queryState: 'sub-q1',
469
+ canCalculateChanges: false,
470
+ position: 0,
471
+ ids,
472
+ };
473
+ }
474
+ case 'EmailSubmission/get': {
475
+ const ids = (args.ids ?? []);
476
+ const list = ids.flatMap((id) => {
477
+ const record = this.#submissionState.get(id);
478
+ if (!record)
479
+ return [];
480
+ const email = this.#emails.find((one) => one.id === record.emailId);
481
+ return [
482
+ {
483
+ id,
484
+ emailId: record.emailId,
485
+ threadId: email?.threadId ?? '',
486
+ sendAt: jmapDate(record.sendAt),
487
+ undoStatus: record.undoStatus,
488
+ },
489
+ ];
490
+ });
491
+ return {
492
+ accountId: ACCOUNT,
493
+ state: 'sub-g1',
494
+ list,
495
+ notFound: ids.filter((id) => !this.#submissionState.has(id)),
496
+ };
343
497
  }
344
498
  default:
345
499
  return {
@@ -348,6 +502,23 @@ export class FakeMailbox {
348
502
  };
349
503
  }
350
504
  }
505
+ /** RFC 4865's send-delay SMTP parameter, read the way Stalwart reads it:
506
+ * case-insensitively, since the server uppercases every `mailFrom`
507
+ * parameter key before matching. `undefined` means no `holdFor` was
508
+ * sent; `'invalid'` means one was sent but failed the 1..=999999999
509
+ * range. `holdUntil` is not supported yet, so it is ignored. */
510
+ #holdForSeconds(envelope) {
511
+ const parameters = envelope?.mailFrom?.parameters;
512
+ if (!parameters)
513
+ return undefined;
514
+ const key = Object.keys(parameters).find((name) => name.toUpperCase() === 'HOLDFOR');
515
+ if (key === undefined)
516
+ return undefined;
517
+ const seconds = Number(parameters[key]);
518
+ if (!Number.isInteger(seconds) || seconds < 1 || seconds > 999_999_999)
519
+ return 'invalid';
520
+ return seconds;
521
+ }
351
522
  #matches(email, filter) {
352
523
  const mailboxIds = email.mailboxIds;
353
524
  if (typeof filter.inMailbox === 'string' && !mailboxIds[filter.inMailbox])
@@ -19,8 +19,8 @@ export type { SearchOptions } from './search.ts';
19
19
  export { identities } from './identities.ts';
20
20
  export { attribution, formatAddress, forwardDraft, forwardIntroduction, forwardSubject, quoteText, replyDraft, replySubject, } from './drafts.ts';
21
21
  export type { ForwardOptions, ReplyOptions } from './drafts.ts';
22
- export { draftToEmail, send, sentPatch } from './submit.ts';
23
- export type { SendOptions } from './submit.ts';
22
+ export { cancel, draftPatch, draftToEmail, queued, send, sentPatch } from './submit.ts';
23
+ export type { CancelOptions, SendOptions } from './submit.ts';
24
24
  export { attach } from './attach.ts';
25
25
  export { moveThread, moveToRole, removeFromMailbox, setFlagged, setRead, } from './mutate.ts';
26
26
  export type { MoveOptions } from './mutate.ts';
@@ -29,4 +29,4 @@ export type { DownloadOptions } from './download.ts';
29
29
  export { push } from './push.ts';
30
30
  export type { PushHandle, PushOptions } from './push.ts';
31
31
  export { expandTemplate } from './uri.ts';
32
- export type { Attachment, ChangedState, Draft, DraftAttachment, EmailAddress, MailFilter, MailIdentity, MailSession, MailSort, MailboxNode, MailboxRole, Message, Sent, ThreadDetail, ThreadPage, ThreadSummary, } from './types.ts';
32
+ export type { Attachment, ChangedState, Draft, DraftAttachment, EmailAddress, MailFilter, MailIdentity, MailSession, MailSort, MailboxNode, MailboxRole, Message, Queued, Sent, ThreadDetail, ThreadPage, ThreadSummary, } from './types.ts';
@@ -12,7 +12,7 @@ export { DEFAULT_MAX_BODY_BYTES, thread, toMessage } from "./thread.js";
12
12
  export { search } from "./search.js";
13
13
  export { identities } from "./identities.js";
14
14
  export { attribution, formatAddress, forwardDraft, forwardIntroduction, forwardSubject, quoteText, replyDraft, replySubject, } from "./drafts.js";
15
- export { draftToEmail, send, sentPatch } from "./submit.js";
15
+ export { cancel, draftPatch, draftToEmail, queued, send, sentPatch } from "./submit.js";
16
16
  export { attach } from "./attach.js";
17
17
  export { moveThread, moveToRole, removeFromMailbox, setFlagged, setRead, } from "./mutate.js";
18
18
  export { DEFAULT_MAX_DOWNLOAD_BYTES, downloadAttachment } from "./download.js";
@@ -150,6 +150,25 @@
150
150
  white-space: nowrap;
151
151
  }
152
152
 
153
+ /* Said when the push stream is not connected. Quiet on purpose: nothing is
154
+ broken for the reader, and a list that has stopped growing is the only
155
+ symptom, so this is the one thing on screen that explains it. It borrows
156
+ the warning colour rather than the danger one -- mail is still arriving,
157
+ it is just not being announced. */
158
+ .mail-offline {
159
+ display: flex;
160
+ align-items: center;
161
+ gap: var(--space-1);
162
+ color: var(--warn);
163
+ font-size: var(--text-sm);
164
+ white-space: nowrap;
165
+ min-width: 0;
166
+ }
167
+
168
+ .mail-offline-word {
169
+ white-space: nowrap;
170
+ }
171
+
153
172
  .mail-panes {
154
173
  display: flex;
155
174
  flex: 1 1 auto;
@@ -1124,6 +1143,14 @@
1124
1143
  display: none;
1125
1144
  }
1126
1145
 
1146
+ /* The same bargain the compose word makes: at narrow widths the glyph carries
1147
+ it, and the wording survives in the tooltip and in the refresh button's
1148
+ accessible name. */
1149
+ .mail.is-narrow .mail-offline-word,
1150
+ .mail.is-medium .mail-offline-word {
1151
+ display: none;
1152
+ }
1153
+
1127
1154
  .mail.is-narrow .mail-compose-word {
1128
1155
  /* The pen alone. The button keeps its name from the `aria-label` the icon
1129
1156
  is given, so this is a visual change and not a semantic one. */
@@ -45,6 +45,13 @@ import { saveBlob } from "./save.js";
45
45
  * focus, or `c` could never be typed into a subject.
46
46
  */
47
47
  const PAGE = 50;
48
+ /** Said in the control's label and in the marker's tooltip, so the two cannot
49
+ * drift apart and describe the same state differently. */
50
+ const OFFLINE_TITLE = 'Not receiving new mail automatically. Refresh to check.';
51
+ /** How long the stream may be down before the reader is told. Long enough that
52
+ * a reconnect nobody needed to know about stays invisible, short enough that
53
+ * a reader who is about to wonder why nothing is arriving is told first. */
54
+ const OFFLINE_GRACE_MS = 10_000;
48
55
  /** A logo or a signature is kilobytes; five megabytes is a photograph, and
49
56
  * past that it is an attachment wearing a `cid:`. */
50
57
  const INLINE_MAX_BYTES = 5 * 1024 * 1024;
@@ -135,7 +142,27 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
135
142
  boxes.reload();
136
143
  threads.reload();
137
144
  }, [boxes.reload, threads.reload]);
138
- usePush(refresh, client);
145
+ /* `usePush` reconnects on its own, with backoff, and resends `Last-Event-ID`
146
+ so nothing is missed across a drop. What it cannot do is get through a
147
+ proxy that buffers a long-lived response -- and a reader whose stream is
148
+ dead sees a list that simply stops growing, which reads as "no new mail"
149
+ rather than "not listening". So the state is drawn, and a refresh is
150
+ always within reach. */
151
+ const { connected } = usePush(refresh, client);
152
+ /* `connected` is false for the moment before the stream comes up, so drawing
153
+ the marker straight from it would flash a warning on every load. It is
154
+ also false forever when a proxy swallows the stream entirely, which is the
155
+ case that started all this -- so a grace period rather than "has it ever
156
+ connected", which would stay silent in exactly that case. */
157
+ const [live, setLive] = useState(true);
158
+ useEffect(() => {
159
+ if (connected) {
160
+ setLive(true);
161
+ return;
162
+ }
163
+ const timer = setTimeout(() => setLive(false), OFFLINE_GRACE_MS);
164
+ return () => clearTimeout(timer);
165
+ }, [connected]);
139
166
  /* Errors reach the application, but only when they change: these hooks hold
140
167
  their last error while a retry is in flight, so forwarding on every
141
168
  render would call `onError` sixty times for one dead token. */
@@ -398,6 +425,10 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
398
425
  startForward(newest);
399
426
  break;
400
427
  }
428
+ case '.':
429
+ event.preventDefault();
430
+ refresh();
431
+ break;
401
432
  case 'Escape':
402
433
  if (threadId && panes === 'narrow')
403
434
  setThreadId(null);
@@ -423,6 +454,7 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
423
454
  setThreadId,
424
455
  archiveBox,
425
456
  trashBox,
457
+ refresh,
426
458
  ]);
427
459
  const paletteGroups = useMemo(() => [
428
460
  {
@@ -447,7 +479,7 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
447
479
  ...(threadId
448
480
  ? [{ id: 'unread', label: 'Mark unread', shortcut: 'U', onRun: markUnread }]
449
481
  : []),
450
- { id: 'refresh', label: 'Refresh', shortcut: 'R', onRun: refresh },
482
+ { id: 'refresh', label: 'Refresh', shortcut: '.', onRun: refresh },
451
483
  {
452
484
  id: 'help',
453
485
  label: 'Keyboard shortcuts',
@@ -483,7 +515,7 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
483
515
  }, "aria-label": "Clear the search", children: _jsx(Icon, { name: "close", size: 13 }) })) : (_jsx("span", { className: "mail-search-key", "aria-hidden": "true", children: "/" }))] }));
484
516
  const list = (_jsx(ThreadList, { page: threads.data, selectedId: threadId, onSelect: openThread, onPage: (threads.data?.total ?? 0) > PAGE ? setPosition : undefined, limit: PAGE, loading: threads.loading, now: now, title: query ? `Results for “${query}”` : current?.name, empty: query ? _jsxs("p", { className: "threads-quiet", children: ["Nothing matches \u201C", query, "\u201D."] }) : undefined }));
485
517
  const reader = (_jsx(ThreadView, { thread: thread.data, loading: thread.loading, onReply: startReply, onForward: startForward, onArchive: archiveBox ? archive : undefined, onTrash: trashBox ? trash : undefined, onMarkUnread: markUnread, onFlag: flag, onDownload: (file) => void download(file), downloading: downloading, fetchInline: fetchInline, flagged: summary?.isFlagged ?? false, busy: acting, onBack: panes === 'narrow' ? () => setThreadId(null) : undefined }));
486
- return (_jsxs("div", { className: `mail is-${panes}${className ? ` ${className}` : ''}`, children: [_jsxs("header", { className: "mail-bar", children: [_jsxs("div", { className: "mail-bar-start", children: [panes === 'narrow' && (_jsx(Button, { kind: "ghost", iconOnly: true, onClick: () => setDrawerOpen(true), "aria-label": "Mailboxes", children: _jsx(Icon, { name: "menu" }) })), _jsx("span", { className: "mail-wordmark", children: "Mail" })] }), searchBox, _jsxs("div", { className: "mail-bar-end", children: [_jsxs(Button, { kind: "primary", size: "sm", onClick: startNew, disabled: !identity, children: [_jsx(Icon, { name: "pen", size: 15 }), " ", _jsx("span", { className: "mail-compose-word", children: "Compose" })] }), account] })] }), panes === 'wide' && (_jsxs(SplitPane, { className: "mail-panes", label: "Mailbox list width", defaultSize: 15, min: 11, max: 28, storageKey: "mail-sidebar", children: [_jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading }), _jsxs(SplitPane, { label: "Conversation list width", defaultSize: 36, min: 26, max: 55, storageKey: "mail-list", children: [list, reader] })] })), panes === 'medium' && (_jsxs("div", { className: "mail-panes", children: [_jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading, rail: true }), _jsxs(SplitPane, { className: "mail-panes-split", label: "Conversation list width", defaultSize: 40, min: 28, max: 60, storageKey: "mail-list", children: [list, reader] })] })), panes === 'narrow' && _jsx("div", { className: "mail-panes", children: reading ? reader : list }), drawerOpen && (_jsx(Modal, { title: "Mailboxes", width: "20rem", onClose: () => setDrawerOpen(false), children: _jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading }) })), _jsx(Command, { open: paletteOpen, onOpenChange: setPaletteOpen, groups: paletteGroups }), helpOpen && (_jsx(Modal, { title: "Keyboard shortcuts", width: "26rem", onClose: () => setHelpOpen(false), children: _jsx(Shortcuts, {}) })), draft && (_jsx(Modal, { title: draft.subject ? draft.subject : 'New message', width: "46rem", onClose: sending ? undefined : () => setDraft(null), closeDisabled: sending, children: _jsx(Composer, { draft: draft, onChange: setDraft, onSend: doSend, onCancel: () => setDraft(null), identities: identities.data ?? [], onAttach: (file, signal) => attach(client, file, { signal }), limits: limits, sending: sending, error: sendError }, drafted) })), _jsx(Note, { said: note, onDone: () => setNote(null) })] }));
518
+ return (_jsxs("div", { className: `mail is-${panes}${className ? ` ${className}` : ''}`, children: [_jsxs("header", { className: "mail-bar", children: [_jsxs("div", { className: "mail-bar-start", children: [panes === 'narrow' && (_jsx(Button, { kind: "ghost", iconOnly: true, onClick: () => setDrawerOpen(true), "aria-label": "Mailboxes", children: _jsx(Icon, { name: "menu" }) })), _jsx("span", { className: "mail-wordmark", children: "Mail" })] }), searchBox, _jsxs("div", { className: "mail-bar-end", children: [!live && (_jsxs("span", { className: "mail-offline", title: OFFLINE_TITLE, children: [_jsx(Icon, { name: "wifi-off", size: 15 }), _jsx("span", { className: "mail-offline-word", children: "Not live" })] })), _jsx(Button, { kind: "ghost", iconOnly: true, onClick: refresh, "aria-label": live ? 'Refresh' : OFFLINE_TITLE, children: _jsx(Icon, { name: "refresh", size: 15 }) }), _jsxs(Button, { kind: "primary", size: "sm", onClick: startNew, disabled: !identity, children: [_jsx(Icon, { name: "pen", size: 15 }), " ", _jsx("span", { className: "mail-compose-word", children: "Compose" })] }), account] })] }), panes === 'wide' && (_jsxs(SplitPane, { className: "mail-panes", label: "Mailbox list width", defaultSize: 15, min: 11, max: 28, storageKey: "mail-sidebar", children: [_jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading }), _jsxs(SplitPane, { label: "Conversation list width", defaultSize: 36, min: 26, max: 55, storageKey: "mail-list", children: [list, reader] })] })), panes === 'medium' && (_jsxs("div", { className: "mail-panes", children: [_jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading, rail: true }), _jsxs(SplitPane, { className: "mail-panes-split", label: "Conversation list width", defaultSize: 40, min: 28, max: 60, storageKey: "mail-list", children: [list, reader] })] })), panes === 'narrow' && _jsx("div", { className: "mail-panes", children: reading ? reader : list }), drawerOpen && (_jsx(Modal, { title: "Mailboxes", width: "20rem", onClose: () => setDrawerOpen(false), children: _jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading }) })), _jsx(Command, { open: paletteOpen, onOpenChange: setPaletteOpen, groups: paletteGroups }), helpOpen && (_jsx(Modal, { title: "Keyboard shortcuts", width: "26rem", onClose: () => setHelpOpen(false), children: _jsx(Shortcuts, {}) })), draft && (_jsx(Modal, { title: draft.subject ? draft.subject : 'New message', width: "46rem", onClose: sending ? undefined : () => setDraft(null), closeDisabled: sending, children: _jsx(Composer, { draft: draft, onChange: setDraft, onSend: doSend, onCancel: () => setDraft(null), identities: identities.data ?? [], onAttach: (file, signal) => attach(client, file, { signal }), limits: limits, sending: sending, error: sendError }, drafted) })), _jsx(Note, { said: note, onDone: () => setNote(null) })] }));
487
519
  }
488
520
  /**
489
521
  * What just happened, said once and then gone.
@@ -524,6 +556,7 @@ function Shortcuts() {
524
556
  ['#', 'Delete'],
525
557
  ['U', 'Mark unread'],
526
558
  ['S', 'Flag'],
559
+ ['.', 'Refresh'],
527
560
  ['?', 'This list'],
528
561
  ];
529
562
  return (_jsx("dl", { className: "keys", children: rows.map(([key, what]) => (_jsxs("div", { className: "keys-row", children: [_jsx("dt", { children: _jsx("kbd", { children: key }) }), _jsx("dd", { children: what })] }, key))) }));
@@ -1,5 +1,5 @@
1
1
  import { type MailClient } from './client.ts';
2
- import type { Draft, EmailAddress, MailIdentity, MailboxNode, Sent } from './types.ts';
2
+ import type { Draft, EmailAddress, MailIdentity, MailboxNode, Queued, Sent } from './types.ts';
3
3
  /** The JMAP `Email` object a draft becomes. Exported so the shape can be
4
4
  * asserted without a server. */
5
5
  export declare function draftToEmail(draft: Draft, from: readonly EmailAddress[], draftsMailboxId: string): Record<string, unknown>;
@@ -10,6 +10,13 @@ export declare function sentPatch(draftsMailboxId: string, sentMailboxId: string
10
10
  'keywords/$draft': null;
11
11
  'keywords/$seen': boolean;
12
12
  };
13
+ /** The patch that unsends a message: out of Sent, into Drafts, a draft
14
+ * again -- the exact reverse of `sentPatch`. */
15
+ export declare function draftPatch(sentMailboxId: string, draftsMailboxId: string): {
16
+ [x: string]: boolean | null;
17
+ 'keywords/$draft': boolean;
18
+ 'keywords/$seen': null;
19
+ };
13
20
  export type SendOptions = {
14
21
  /** The identity to send as, when the caller already has it. Saves an
15
22
  * `Identity/get`. */
@@ -17,6 +24,16 @@ export type SendOptions = {
17
24
  /** The mailbox tree, when the caller already has it. Saves a
18
25
  * `Mailbox/get`. */
19
26
  mailboxes?: readonly MailboxNode[];
27
+ /** Whole seconds to hold the message before it goes out, giving the
28
+ * sender a window to `cancel()` it. `0` or omitted sends immediately,
29
+ * byte-identical to a plain send. Travels as RFC 4865's `holdFor` SMTP
30
+ * parameter, which the server validates as 1..=999999999. */
31
+ delay?: number;
32
+ };
33
+ export type CancelOptions = {
34
+ /** The mailbox tree, when the caller already has it. Saves a
35
+ * `Mailbox/get`. */
36
+ mailboxes?: readonly MailboxNode[];
20
37
  };
21
38
  /**
22
39
  * Send a draft.
@@ -33,3 +50,46 @@ export type SendOptions = {
33
50
  * submission leaves the message in Drafts rather than losing it.
34
51
  */
35
52
  export declare function send(client: MailClient, draft: Draft, options?: SendOptions): Promise<Sent>;
53
+ /**
54
+ * Unsend a message inside its hold window.
55
+ *
56
+ * `undoStatus: 'canceled'` is an update, not a destroy: `EmailSubmission/
57
+ * destroy` deletes the submission record but still sends the mail, so it is
58
+ * never used here. This is the same single-call path `send()` uses, and for
59
+ * the same reason -- RFC 8621 §7.5's `onSuccessUpdateEmail` runs an implicit
60
+ * `Email/set` and returns it under the update's own method call id, which a
61
+ * multi-call reader that maps responses by id would lose. See the docblock
62
+ * above `send()`.
63
+ *
64
+ * The second argument only needs `submissionId`, so a `Sent` (what `send()`
65
+ * returned) and a `Queued` (what `queued()` lists after a reload, once that
66
+ * object is gone) both work here unchanged.
67
+ */
68
+ export declare function cancel(client: MailClient, sent: Pick<Sent, 'submissionId'>, options?: CancelOptions): Promise<void>;
69
+ /**
70
+ * Everything currently held, soonest first -- what survives a reload, when
71
+ * the `Sent` object `send()` returned is gone and `cancel()` needs a
72
+ * `submissionId` from somewhere else.
73
+ *
74
+ * **The `undoStatus: 'pending'` filter is not a convenience -- it is what
75
+ * makes the result honest.** RFC 8621 lets a server answer a plain
76
+ * `EmailSubmission/get` with a `pending` it has not rechecked, and Stalwart
77
+ * does exactly that: it only re-verifies a held submission against the
78
+ * live mail queue, and reclassifies it to `final` if the message has
79
+ * already gone, when the *query* itself filters on `undoStatus`
80
+ * (`crates/jmap/src/submission/query.rs:106-127` in Stalwart v0.16.20). Ask
81
+ * any other way -- no filter, or a filter on something else -- and a
82
+ * message that already sent can still read back as `pending`. Filtering
83
+ * here is the only way this function's list is trustworthy enough to offer
84
+ * `cancel()` on.
85
+ *
86
+ * Sorted in this package rather than asked of the server: one fewer
87
+ * assumption about what a JMAP server supports for `EmailSubmission` sort
88
+ * comparators, and a held list is small enough that client-side sorting
89
+ * costs nothing. The comparator parses each `sendAt` rather than comparing
90
+ * the two strings: RFC 8620 1.4 requires a zero fractional part to be
91
+ * omitted, so a server's timestamps vary in precision, and as text `.`
92
+ * sorts before `Z` -- which would put `12:00:00.500Z` ahead of
93
+ * `12:00:00Z`.
94
+ */
95
+ export declare function queued(client: MailClient): Promise<Queued[]>;
@@ -14,6 +14,50 @@ function failed(operation, notCreated) {
14
14
  operation,
15
15
  });
16
16
  }
17
+ /** A `notUpdated` entry of type `cannotUnsend` means the window closed
18
+ * before the request arrived; everything else keeps the server's own type
19
+ * and description, the way `failed()` does for a create. */
20
+ function unsendFailed(notUpdated) {
21
+ const first = notUpdated ? Object.values(notUpdated)[0] : undefined;
22
+ if (first?.type === 'cannotUnsend') {
23
+ throw new MailError('the message has already gone; it can no longer be unsent', {
24
+ type: 'cannotUnsend',
25
+ operation: 'cancel',
26
+ });
27
+ }
28
+ throw new MailError(first?.description ?? 'the server refused to cancel the submission', {
29
+ type: first?.type ?? 'unknown',
30
+ operation: 'cancel',
31
+ });
32
+ }
33
+ /** RFC 4865's send-delay SMTP parameter travels as a string of seconds and
34
+ * Stalwart validates it as 1..=999999999 -- `holdFor: "0"` is refused
35
+ * outright, which is why a delay of zero omits the parameter entirely
36
+ * rather than sending a zero. Checked here so a bad `delay` fails with a
37
+ * clear message before anything goes to the wire, not as an opaque server
38
+ * refusal. */
39
+ function checkDelay(delay) {
40
+ if (delay === undefined)
41
+ return;
42
+ if (!Number.isInteger(delay) || delay < 0 || delay > 999_999_999) {
43
+ throw new MailError(`delay must be a whole number of seconds from 0 to 999999999, got ${delay}`, { type: 'invalidProperties', operation: 'send' });
44
+ }
45
+ }
46
+ /** `to`, `cc` and `bcc` combined for the envelope's `rcptTo`, deduplicated.
47
+ * Without an envelope the server derives recipients from the headers, but
48
+ * it strips the Bcc header before delivery, so a delayed send has to list
49
+ * every recipient explicitly here or the blind ones are silently dropped. */
50
+ function uniqueAddresses(addresses) {
51
+ const seen = new Set();
52
+ const result = [];
53
+ for (const address of addresses) {
54
+ if (seen.has(address.email))
55
+ continue;
56
+ seen.add(address.email);
57
+ result.push({ email: address.email });
58
+ }
59
+ return result;
60
+ }
17
61
  /** The JMAP `Email` object a draft becomes. Exported so the shape can be
18
62
  * asserted without a server. */
19
63
  export function draftToEmail(draft, from, draftsMailboxId) {
@@ -71,6 +115,16 @@ export function sentPatch(draftsMailboxId, sentMailboxId) {
71
115
  'keywords/$seen': true,
72
116
  };
73
117
  }
118
+ /** The patch that unsends a message: out of Sent, into Drafts, a draft
119
+ * again -- the exact reverse of `sentPatch`. */
120
+ export function draftPatch(sentMailboxId, draftsMailboxId) {
121
+ return {
122
+ [`mailboxIds/${pointer(sentMailboxId)}`]: null,
123
+ [`mailboxIds/${pointer(draftsMailboxId)}`]: true,
124
+ 'keywords/$draft': true,
125
+ 'keywords/$seen': null,
126
+ };
127
+ }
74
128
  /**
75
129
  * Send a draft.
76
130
  *
@@ -86,6 +140,7 @@ export function sentPatch(draftsMailboxId, sentMailboxId) {
86
140
  * submission leaves the message in Drafts rather than losing it.
87
141
  */
88
142
  export async function send(client, draft, options = {}) {
143
+ checkDelay(options.delay);
89
144
  const { jam, accountId } = await client.connect();
90
145
  const tree = options.mailboxes ?? (await mailboxes(client));
91
146
  const drafts = findRole(tree, 'drafts');
@@ -103,19 +158,35 @@ export async function send(client, draft, options = {}) {
103
158
  });
104
159
  }
105
160
  let from = draft.from;
106
- if (!from || from.length === 0) {
107
- const identity = options.identity ?? (await identities(client)).find((one) => one.id === draft.identityId);
161
+ let identity;
162
+ // A delay needs the identity's own address for the envelope's `mailFrom`
163
+ // even when `from` was already supplied, so it is resolved whenever
164
+ // either is missing.
165
+ if (!from || from.length === 0 || options.delay) {
166
+ identity =
167
+ options.identity ?? (await identities(client)).find((one) => one.id === draft.identityId);
108
168
  if (!identity) {
109
169
  throw new MailError(`no identity ${draft.identityId} on this account`, {
110
170
  type: 'notFound',
111
171
  operation: 'send',
112
172
  });
113
173
  }
114
- // RFC 8621 §7.1: a server may refuse a submission whose From header does
115
- // not match the identity, so the header is filled from the identity
116
- // rather than left to the server to guess.
117
- from = [{ name: identity.name, email: identity.email }];
174
+ if (!from || from.length === 0) {
175
+ // RFC 8621 §7.1: a server may refuse a submission whose From header
176
+ // does not match the identity, so the header is filled from the
177
+ // identity rather than left to the server to guess.
178
+ from = [{ name: identity.name, email: identity.email }];
179
+ }
118
180
  }
181
+ // Without a delay, no envelope is built at all: the server derives
182
+ // recipients from the headers, and this stays byte-identical to a plain
183
+ // send, which is the path in production today.
184
+ const envelope = options.delay && identity
185
+ ? {
186
+ mailFrom: { email: identity.email, parameters: { holdFor: String(options.delay) } },
187
+ rcptTo: uniqueAddresses([...draft.to, ...(draft.cc ?? []), ...(draft.bcc ?? [])]),
188
+ }
189
+ : undefined;
119
190
  return guard('send', async () => {
120
191
  const [created] = await jam.api.Email.set({
121
192
  accountId,
@@ -130,6 +201,7 @@ export async function send(client, draft, options = {}) {
130
201
  submission: {
131
202
  identityId: draft.identityId,
132
203
  emailId: email.id,
204
+ ...(envelope ? { envelope } : {}),
133
205
  },
134
206
  },
135
207
  onSuccessUpdateEmail: { '#submission': sentPatch(drafts.id, sent.id) },
@@ -146,6 +218,112 @@ export async function send(client, draft, options = {}) {
146
218
  submissionId: submission.id,
147
219
  emailId: email.id,
148
220
  threadId: email.threadId,
221
+ undoStatus: submission.undoStatus,
222
+ sendAt: submission.sendAt,
149
223
  };
150
224
  });
151
225
  }
226
+ /**
227
+ * Unsend a message inside its hold window.
228
+ *
229
+ * `undoStatus: 'canceled'` is an update, not a destroy: `EmailSubmission/
230
+ * destroy` deletes the submission record but still sends the mail, so it is
231
+ * never used here. This is the same single-call path `send()` uses, and for
232
+ * the same reason -- RFC 8621 §7.5's `onSuccessUpdateEmail` runs an implicit
233
+ * `Email/set` and returns it under the update's own method call id, which a
234
+ * multi-call reader that maps responses by id would lose. See the docblock
235
+ * above `send()`.
236
+ *
237
+ * The second argument only needs `submissionId`, so a `Sent` (what `send()`
238
+ * returned) and a `Queued` (what `queued()` lists after a reload, once that
239
+ * object is gone) both work here unchanged.
240
+ */
241
+ export async function cancel(client, sent, options = {}) {
242
+ const { jam, accountId } = await client.connect();
243
+ const tree = options.mailboxes ?? (await mailboxes(client));
244
+ const sentBox = findRole(tree, 'sent');
245
+ const drafts = findRole(tree, 'drafts');
246
+ if (!sentBox) {
247
+ throw new MailError('the account has no Sent mailbox the message is filed in', {
248
+ type: 'notFound',
249
+ operation: 'cancel',
250
+ });
251
+ }
252
+ if (!drafts) {
253
+ throw new MailError('the account has no Drafts mailbox to move the message back to', {
254
+ type: 'notFound',
255
+ operation: 'cancel',
256
+ });
257
+ }
258
+ return guard('cancel', async () => {
259
+ const [result] = await jam.api.EmailSubmission.set({
260
+ accountId,
261
+ update: { [sent.submissionId]: { undoStatus: 'canceled' } },
262
+ onSuccessUpdateEmail: { [sent.submissionId]: draftPatch(sentBox.id, drafts.id) },
263
+ },
264
+ // Same reason as `send()`: `onSuccessUpdateEmail` runs an Email/set,
265
+ // so the request needs the mail capability declared alongside
266
+ // submission.
267
+ { using: ['urn:ietf:params:jmap:mail'], ...JAM_FETCH });
268
+ const updated = result.updated;
269
+ if (updated && sent.submissionId in updated)
270
+ return;
271
+ unsendFailed(result.notUpdated);
272
+ });
273
+ }
274
+ /**
275
+ * Everything currently held, soonest first -- what survives a reload, when
276
+ * the `Sent` object `send()` returned is gone and `cancel()` needs a
277
+ * `submissionId` from somewhere else.
278
+ *
279
+ * **The `undoStatus: 'pending'` filter is not a convenience -- it is what
280
+ * makes the result honest.** RFC 8621 lets a server answer a plain
281
+ * `EmailSubmission/get` with a `pending` it has not rechecked, and Stalwart
282
+ * does exactly that: it only re-verifies a held submission against the
283
+ * live mail queue, and reclassifies it to `final` if the message has
284
+ * already gone, when the *query* itself filters on `undoStatus`
285
+ * (`crates/jmap/src/submission/query.rs:106-127` in Stalwart v0.16.20). Ask
286
+ * any other way -- no filter, or a filter on something else -- and a
287
+ * message that already sent can still read back as `pending`. Filtering
288
+ * here is the only way this function's list is trustworthy enough to offer
289
+ * `cancel()` on.
290
+ *
291
+ * Sorted in this package rather than asked of the server: one fewer
292
+ * assumption about what a JMAP server supports for `EmailSubmission` sort
293
+ * comparators, and a held list is small enough that client-side sorting
294
+ * costs nothing. The comparator parses each `sendAt` rather than comparing
295
+ * the two strings: RFC 8620 1.4 requires a zero fractional part to be
296
+ * omitted, so a server's timestamps vary in precision, and as text `.`
297
+ * sorts before `Z` -- which would put `12:00:00.500Z` ahead of
298
+ * `12:00:00Z`.
299
+ */
300
+ export async function queued(client) {
301
+ const { jam, accountId } = await client.connect();
302
+ return guard('queued', async () => {
303
+ const [results] = await jam.requestMany((t) => {
304
+ const query = t.EmailSubmission.query({
305
+ accountId,
306
+ filter: { undoStatus: 'pending' },
307
+ });
308
+ const submissions = t.EmailSubmission.get({
309
+ accountId,
310
+ ids: query.$ref('/ids'),
311
+ });
312
+ // `query` has to come back too, or it is never turned into a method
313
+ // call at all -- only the invocations named in this returned record
314
+ // are sent, the way `threads.ts`'s four-call chain returns every one
315
+ // of its steps even though only the last is read here.
316
+ return { query, submissions };
317
+ }, JAM_FETCH);
318
+ const submissions = results.submissions;
319
+ return submissions.list
320
+ .map((submission) => ({
321
+ submissionId: submission.id,
322
+ emailId: submission.emailId,
323
+ threadId: submission.threadId,
324
+ sendAt: submission.sendAt,
325
+ undoStatus: submission.undoStatus,
326
+ }))
327
+ .sort((a, b) => Date.parse(a.sendAt) - Date.parse(b.sendAt));
328
+ });
329
+ }
@@ -201,6 +201,32 @@ export type Sent = {
201
201
  /** The id the message has once it is in Sent. */
202
202
  emailId: string;
203
203
  threadId: string;
204
+ /** Whether the message can still be `cancel()`ed. `'pending'` is the ONLY
205
+ * honest signal that a regret window exists: a server not configured for
206
+ * held delivery accepts the submission, ignores the hold, and answers
207
+ * `'final'` anyway, with no error anywhere. `'canceled'` is what `send`
208
+ * never returns -- it only ever comes back from a successful `cancel()`. */
209
+ undoStatus: 'pending' | 'final' | 'canceled';
210
+ /** The ISO 8601 UTC instant the server will (or did) release the message
211
+ * for delivery. */
212
+ sendAt: string;
213
+ };
214
+ /** A submission `queued()` found still held. Carries the same fields
215
+ * `cancel()` reads off a `Sent`, so a `Queued` is safe to pass to `cancel()`
216
+ * directly -- the whole point of `queued()` is to let a host cancel a
217
+ * submission after a reload, once the `Sent` object `send()` returned is
218
+ * long gone from memory. */
219
+ export type Queued = {
220
+ submissionId: string;
221
+ emailId: string;
222
+ threadId: string;
223
+ /** The ISO 8601 UTC instant the server will release the message for
224
+ * delivery. */
225
+ sendAt: string;
226
+ /** `queued()` filters on this, so every row it returns has it `'pending'`
227
+ * -- carried anyway because it is what the server actually said, not an
228
+ * assumption this type bakes in. */
229
+ undoStatus: 'pending' | 'final' | 'canceled';
204
230
  };
205
231
  /** The per-type state strings a push event carries. A value that differs
206
232
  * from the one a previous call returned means that type changed. */
@@ -2,7 +2,7 @@ import type { PostmasterAudit } from './audit.js';
2
2
  import type { Instance } from './instance.js';
3
3
  export interface Applied {
4
4
  /** For the audit row's `targetType`. */
5
- readonly targetType: 'mailbox' | 'mail_alias' | 'mail_app_password';
5
+ readonly targetType: 'mailbox' | 'mail_alias' | 'mail_app_password' | 'mail_settings';
6
6
  /** For its `targetId`: the address or the credential, never a secret. */
7
7
  readonly targetId: string;
8
8
  readonly before: unknown;
@@ -60,3 +60,27 @@ export declare function revokeAppPassword(instance: Instance, input: {
60
60
  domainId: string;
61
61
  apex: string;
62
62
  }, audit?: PostmasterAudit): Promise<Applied>;
63
+ /**
64
+ * How long this instance will hold a message before sending it, as the
65
+ * server's own duration (`'30d'`), or `null` when it will not hold one at
66
+ * all. `null` means a held send goes out at once and is reported as held,
67
+ * which is what `enableHolding` fixes.
68
+ *
69
+ * Only the expression's `else` is read. Provisioning and `enableHolding`
70
+ * write nothing else, and a rule someone added by hand in the web admin is
71
+ * theirs to read there.
72
+ */
73
+ export declare function holdLimit(instance: Instance): Promise<string | null>;
74
+ /**
75
+ * Make this instance hold a message until its `sendAt`, up to the limit
76
+ * provisioning sets (`FUTURE_RELEASE`). For an instance provisioned before
77
+ * provisioning set it, which otherwise sends every held message at once.
78
+ *
79
+ * **The reload is not optional.** Stalwart applies a changed setting only
80
+ * after a `ReloadSettings` action; its own FUTURERELEASE test writes the
81
+ * object and then reloads (`tests/src/smtp/inbound/ehlo.rs`, v0.16.20).
82
+ * Without it the write is stored and the server keeps sending held mail at
83
+ * once. The limit is re-read afterwards, so what is recorded is what the
84
+ * server now says.
85
+ */
86
+ export declare function enableHolding(instance: Instance, audit?: PostmasterAudit): Promise<Applied>;
@@ -1,3 +1,4 @@
1
+ import { FUTURE_RELEASE } from './objects.js';
1
2
  import { MailWriteRefused, newAccount, withAlias, withoutAlias, withoutAppPassword, } from './writes.js';
2
3
  /**
3
4
  * The four writes `/email` makes, each as one round trip against the mail
@@ -204,3 +205,43 @@ export async function revokeAppPassword(instance, input, audit) {
204
205
  message: `That app password no longer works${description ? ` (${description})` : ''}. Any mail client using it will be asked to sign in again.${lost}`,
205
206
  });
206
207
  }
208
+ /**
209
+ * How long this instance will hold a message before sending it, as the
210
+ * server's own duration (`'30d'`), or `null` when it will not hold one at
211
+ * all. `null` means a held send goes out at once and is reported as held,
212
+ * which is what `enableHolding` fixes.
213
+ *
214
+ * Only the expression's `else` is read. Provisioning and `enableHolding`
215
+ * write nothing else, and a rule someone added by hand in the web admin is
216
+ * theirs to read there.
217
+ */
218
+ export async function holdLimit(instance) {
219
+ const ext = await instance.client.getSingleton('MtaExtensions');
220
+ const value = (ext.futureRelease?.else ?? '').replace(/^'(.*)'$/, '$1').trim();
221
+ return value === '' || value === 'false' ? null : value;
222
+ }
223
+ /**
224
+ * Make this instance hold a message until its `sendAt`, up to the limit
225
+ * provisioning sets (`FUTURE_RELEASE`). For an instance provisioned before
226
+ * provisioning set it, which otherwise sends every held message at once.
227
+ *
228
+ * **The reload is not optional.** Stalwart applies a changed setting only
229
+ * after a `ReloadSettings` action; its own FUTURERELEASE test writes the
230
+ * object and then reloads (`tests/src/smtp/inbound/ehlo.rs`, v0.16.20).
231
+ * Without it the write is stored and the server keeps sending held mail at
232
+ * once. The limit is re-read afterwards, so what is recorded is what the
233
+ * server now says.
234
+ */
235
+ export async function enableHolding(instance, audit) {
236
+ const before = await holdLimit(instance);
237
+ await instance.client.update('MtaExtensions', 'singleton', { futureRelease: FUTURE_RELEASE });
238
+ await instance.client.create('Action', { '@type': 'ReloadSettings' });
239
+ const after = await holdLimit(instance);
240
+ return recorded(audit, 'mail.holding_enabled', {
241
+ targetType: 'mail_settings',
242
+ targetId: 'futureRelease',
243
+ before: { holdLimit: before },
244
+ after: { holdLimit: after },
245
+ message: `This server now holds a message for up to ${after} before sending it, so a delayed send and undo send work.`,
246
+ });
247
+ }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The events the postmaster's four writes record, when a caller hands them
2
+ * The events the postmaster's five writes record, when a caller hands them
3
3
  * an audit. Declared here so a host can merge them into its ledger's
4
4
  * vocabulary before it binds a writer to the `mail` namespace; the names sit
5
5
  * in that namespace and nowhere else. `tenantVisible` is true throughout:
@@ -18,6 +18,9 @@ export declare const POSTMASTER_AUDIT_EVENTS: {
18
18
  readonly 'mail.app_password_revoked': {
19
19
  readonly tenantVisible: true;
20
20
  };
21
+ readonly 'mail.holding_enabled': {
22
+ readonly tenantVisible: true;
23
+ };
21
24
  };
22
25
  export type PostmasterAuditAction = keyof typeof POSTMASTER_AUDIT_EVENTS;
23
26
  /** One write, as the host's writer receives it. `targetId` is an address or a credential id, never a secret. */
@@ -28,7 +31,7 @@ export interface PostmasterAuditEvent {
28
31
  readonly display: string;
29
32
  };
30
33
  readonly target: {
31
- readonly type: 'mailbox' | 'mail_alias' | 'mail_app_password';
34
+ readonly type: 'mailbox' | 'mail_alias' | 'mail_app_password' | 'mail_settings';
32
35
  readonly id: string;
33
36
  };
34
37
  readonly outcome: 'success';
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The events the postmaster's four writes record, when a caller hands them
2
+ * The events the postmaster's five writes record, when a caller hands them
3
3
  * an audit. Declared here so a host can merge them into its ledger's
4
4
  * vocabulary before it binds a writer to the `mail` namespace; the names sit
5
5
  * in that namespace and nowhere else. `tenantVisible` is true throughout:
@@ -10,4 +10,5 @@ export const POSTMASTER_AUDIT_EVENTS = {
10
10
  'mail.alias_added': { tenantVisible: true },
11
11
  'mail.alias_removed': { tenantVisible: true },
12
12
  'mail.app_password_revoked': { tenantVisible: true },
13
+ 'mail.holding_enabled': { tenantVisible: true },
13
14
  };
@@ -49,7 +49,7 @@ export declare const API_KEY_PREFIX = "API_";
49
49
  * are Stalwart's management vocabulary (`enums.Permission`), which is why the
50
50
  * earlier guessed names all failed.
51
51
  */
52
- export declare const DASHBOARD_PERMISSIONS: readonly ["authenticate", "sysAccountQuery", "sysAccountGet", "sysAccountCreate", "sysAccountUpdate", "sysDomainQuery", "sysDomainGet", "sysSystemSettingsGet"];
52
+ export declare const DASHBOARD_PERMISSIONS: readonly ["authenticate", "sysAccountQuery", "sysAccountGet", "sysAccountCreate", "sysAccountUpdate", "sysDomainQuery", "sysDomainGet", "sysSystemSettingsGet", "sysMtaExtensionsGet", "sysMtaExtensionsUpdate", "sysActionCreate"];
53
53
  /** Which scheme a secret wants, from its own shape, for a caller holding one opaque string. */
54
54
  export declare function authFor(secret: string, user?: string): StalwartAuth;
55
55
  export declare class StalwartError extends Error {
@@ -48,6 +48,19 @@ export const DASHBOARD_PERMISSIONS = [
48
48
  'sysDomainQuery',
49
49
  'sysDomainGet',
50
50
  'sysSystemSettingsGet',
51
+ // `MtaExtensions` holds `futureRelease`, the setting that decides whether a
52
+ // held message is really held. A server with it off accepts a held
53
+ // submission, drops the hold and reports success. Provisioning sets it, but
54
+ // an instance provisioned before provisioning did stays off forever unless
55
+ // something can change it later, so the dashboard reads it
56
+ // (`holdLimit`) and can turn it on (`enableHolding`).
57
+ 'sysMtaExtensionsGet',
58
+ 'sysMtaExtensionsUpdate',
59
+ // A changed setting takes effect only after a `ReloadSettings` action, and
60
+ // Stalwart has one permission for every action. This also lets the key
61
+ // pause the mail queue, update apps and clear caches. Accepted for
62
+ // `enableHolding`, which is otherwise a write that does nothing.
63
+ 'sysActionCreate',
51
64
  ];
52
65
  /** Which scheme a secret wants, from its own shape, for a caller holding one opaque string. */
53
66
  export function authFor(secret, user) {
@@ -17,9 +17,9 @@
17
17
  export { API_KEY_PREFIX, DASHBOARD_PERMISSIONS, StalwartClient, StalwartError, authFor, type Credential, type StalwartAuth, } from './client.js';
18
18
  export { type Instance, InstanceRefused, openInstance, type RefusalReason } from './instance.js';
19
19
  export { loadOverview } from './load.js';
20
- export { applyObjects, mailObjects, ref, type MailObjectsInput, type PlannedObject, } from './objects.js';
20
+ export { FUTURE_RELEASE, applyObjects, mailObjects, ref, type MailObjectsInput, type PlannedObject, } from './objects.js';
21
21
  export { planMailboxes, withPassword } from './mailboxes.js';
22
22
  export { overview, pickDomain, type AccountView, type CredentialSummary, type DomainView, type Managed, type Overview, type OverviewInput, type PeopleView, type Person, type WireAccount, type WireAlias, type WireDomain, type WireSystemSettings, } from './overview.js';
23
23
  export { MailWriteRefused, newAccount, withAlias, withoutAlias, withoutAppPassword, } from './writes.js';
24
- export { addAlias, createMailbox, removeAlias, revokeAppPassword, type Applied, } from './apply.js';
24
+ export { addAlias, createMailbox, enableHolding, holdLimit, removeAlias, revokeAppPassword, type Applied, } from './apply.js';
25
25
  export { POSTMASTER_AUDIT_EVENTS, type PostmasterAudit, type PostmasterAuditAction, type PostmasterAuditEvent, } from './audit.js';
@@ -17,9 +17,9 @@
17
17
  export { API_KEY_PREFIX, DASHBOARD_PERMISSIONS, StalwartClient, StalwartError, authFor, } from './client.js';
18
18
  export { InstanceRefused, openInstance } from './instance.js';
19
19
  export { loadOverview } from './load.js';
20
- export { applyObjects, mailObjects, ref, } from './objects.js';
20
+ export { FUTURE_RELEASE, applyObjects, mailObjects, ref, } from './objects.js';
21
21
  export { planMailboxes, withPassword } from './mailboxes.js';
22
22
  export { overview, pickDomain, } from './overview.js';
23
23
  export { MailWriteRefused, newAccount, withAlias, withoutAlias, withoutAppPassword, } from './writes.js';
24
- export { addAlias, createMailbox, removeAlias, revokeAppPassword, } from './apply.js';
24
+ export { addAlias, createMailbox, enableHolding, holdLimit, removeAlias, revokeAppPassword, } from './apply.js';
25
25
  export { POSTMASTER_AUDIT_EVENTS, } from './audit.js';
@@ -53,6 +53,21 @@ export interface PlannedObject {
53
53
  match: Record<string, unknown>;
54
54
  value: Record<string, unknown>;
55
55
  }
56
+ /**
57
+ * `MtaExtensions.futureRelease`: how long the server will hold a message
58
+ * before sending it. It gates the SMTP FUTURERELEASE extension. Empty by
59
+ * default, and empty means Stalwart's MAIL FROM handler skips the hold block
60
+ * entirely: a held submission is sent immediately, silently, and the client
61
+ * is told it succeeded. 30d matches the `maxDelayedSend` the server
62
+ * advertises to clients unconditionally, so nothing smaller would make that
63
+ * advertised capability a lie for a submission in between.
64
+ *
65
+ * Provisioning writes it (`mailObjects`), and so does `enableHolding` for an
66
+ * instance provisioned before provisioning did.
67
+ */
68
+ export declare const FUTURE_RELEASE: {
69
+ readonly else: "'30d'";
70
+ };
56
71
  /**
57
72
  * The full configuration of an instance as data, in dependency order. Pure,
58
73
  * so it is unit-tested; `applyObjects` resolves the `$ref`s against the
@@ -1,6 +1,19 @@
1
1
  /** A value that names an object created earlier in the same plan. */
2
2
  export const ref = (key) => ({ $ref: key });
3
3
  const env = (variableName) => ({ '@type': 'EnvironmentVariable', variableName });
4
+ /**
5
+ * `MtaExtensions.futureRelease`: how long the server will hold a message
6
+ * before sending it. It gates the SMTP FUTURERELEASE extension. Empty by
7
+ * default, and empty means Stalwart's MAIL FROM handler skips the hold block
8
+ * entirely: a held submission is sent immediately, silently, and the client
9
+ * is told it succeeded. 30d matches the `maxDelayedSend` the server
10
+ * advertises to clients unconditionally, so nothing smaller would make that
11
+ * advertised capability a lie for a submission in between.
12
+ *
13
+ * Provisioning writes it (`mailObjects`), and so does `enableHolding` for an
14
+ * instance provisioned before provisioning did.
15
+ */
16
+ export const FUTURE_RELEASE = { else: "'30d'" };
4
17
  /**
5
18
  * The full configuration of an instance as data, in dependency order. Pure,
6
19
  * so it is unit-tested; `applyObjects` resolves the `$ref`s against the
@@ -111,6 +124,12 @@ export function mailObjects(i) {
111
124
  },
112
125
  ]
113
126
  : []),
127
+ {
128
+ key: 'extensions',
129
+ object: 'MtaExtensions',
130
+ match: { id: 'singleton' },
131
+ value: { futureRelease: FUTURE_RELEASE },
132
+ },
114
133
  {
115
134
  key: 'reload',
116
135
  object: 'Action',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/email",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "The wtfalch estate: reading a mailbox over JMAP, and administering the Stalwart server it lives on. Two entries with no code in common.",
5
5
  "license": "MIT",
6
6
  "type": "module",