@wtfalch/email 0.12.0 → 0.13.1

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
@@ -50,7 +50,13 @@ call them on every keystroke. `send` creates the draft, submits it, and files
50
50
  it in Sent; a `delay` in seconds holds it there first, and `cancel` unsends
51
51
  it while `undoStatus` is still `'pending'` — the only honest sign the window
52
52
  is still open, since a server not set up for held delivery answers `'final'`
53
- regardless. `attach` uploads a file and gives back what a draft carries; the
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
54
60
  upload is refused before any of it is sent when the file is over the
55
61
  session's `maxSizeUpload`, which `client.session()` reports alongside
56
62
  `maxSizeAttachmentsPerEmail`.
@@ -267,11 +273,25 @@ impossible; the guesses were wrong, not the feature.
267
273
  `createApiKey` therefore mints a scoped key by default. `DASHBOARD_PERMISSIONS`
268
274
  is the set verified on 0.16.20: `authenticate` plus `sysAccountQuery`,
269
275
  `sysAccountGet`, `sysAccountCreate`, `sysAccountUpdate`, `sysDomainQuery`,
270
- `sysDomainGet` and `sysSystemSettingsGet`. It serves every `/email` page, and
276
+ `sysDomainGet`, `sysSystemSettingsGet`, `sysMtaExtensionsGet`,
277
+ `sysMtaExtensionsUpdate` and `sysActionCreate`. It serves every `/email` page, and
271
278
  it is `forbidden` on `Email/query` for every account on the instance —
272
279
  including its own, so the key administers mail and cannot read any. Pass
273
280
  `'inherit'` for a key as powerful as the account; prefer not to.
274
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
+
275
295
  **An API key can never create a credential.** It authenticates, and both
276
296
  `x:ApiKey/set` and `x:AppPassword/set` answer `forbidden` whatever permissions
277
297
  it holds, so a key cannot mint its own successor. Rotating one needs the
@@ -315,7 +335,7 @@ instead.
315
335
 
316
336
  ## The audit
317
337
 
318
- `createMailbox`, `addAlias`, `removeAlias` and `revokeAppPassword` take an
338
+ `createMailbox`, `addAlias`, `removeAlias`, `revokeAppPassword` and `enableHolding` take an
319
339
  optional last argument, a `PostmasterAudit`: a `write` the host bound to its
320
340
  own ledger, the principal it resolved for this request, and the request id
321
341
  its log uses. Without one, nothing changes.
@@ -25,6 +25,14 @@ 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;
30
38
  /** The fake's clock. Fixed at construction and moved only by `advance()`
@@ -361,7 +369,7 @@ export class FakeMailbox {
361
369
  const sendAt = new Date(this.#now.getTime() + (holdFor ?? 0) * 1000);
362
370
  const undoStatus = holdFor ? 'pending' : 'final';
363
371
  this.#submissionState.set(id, { emailId: submission.emailId, sendAt, undoStatus });
364
- created[key] = { id, sendAt: sendAt.toISOString(), undoStatus };
372
+ created[key] = { id, sendAt: jmapDate(sendAt), undoStatus };
365
373
  // The move to Sent that `onSuccessUpdateEmail` asks for. It runs
366
374
  // immediately even on a held message: holding delays delivery,
367
375
  // not filing.
@@ -436,6 +444,57 @@ export class FakeMailbox {
436
444
  notDestroyed: Object.keys(notDestroyed).length > 0 ? notDestroyed : null,
437
445
  };
438
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
+ };
497
+ }
439
498
  default:
440
499
  return {
441
500
  type: 'unknownMethod',
@@ -19,7 +19,7 @@ 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 { cancel, draftPatch, draftToEmail, send, sentPatch } from './submit.ts';
22
+ export { cancel, draftPatch, draftToEmail, queued, send, sentPatch } from './submit.ts';
23
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';
@@ -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 { cancel, draftPatch, 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";
@@ -12,20 +12,25 @@
12
12
  * - `wide` — mailboxes, list and message side by side. Selecting a
13
13
  * conversation reveals it; there is nothing to navigate to.
14
14
  * - `medium` — the mailboxes collapse to a rail of icons, and the list and
15
- * the message share what is left. Below `@wtfalch/design`'s `wide` breakpoint
16
- * (1150px) a 3-column layout puts the reading measure under 45 characters,
15
+ * the message share what is left. Below 1150px a 3-column layout puts the reading measure under 45 characters,
17
16
  * which is where prose stops being readable, and the mailbox names are the
18
17
  * least valuable of the three.
19
- * - `narrow` — one at a time, with the mailboxes in a drawer. Measured at
20
- * `@wtfalch/design`'s `medium` breakpoint (860px), where the list's
18
+ * - `narrow` — one at a time, with the mailboxes in a drawer. Below 860px, where the list's
21
19
  * two-line row can no longer hold a sender, a time and a subject without
22
20
  * the subject truncating to nothing.
23
21
  *
24
- * The widths themselves live in `@wtfalch/design`'s `MEDIA_QUERIES` (and
25
- * `BREAKPOINTS`), not here: one source, shared with the stylesheet-facing
26
- * side of the design system, rather than a second copy that can drift from
27
- * it.
22
+ * **The two widths live here, not in `@wtfalch/design`.** They used to be
23
+ * read from its `PANE_QUERIES.wide` and `.medium`. Design 0.18.0 moved to
24
+ * Tailwind's sm-2xl scale and dropped both names, and the peer range here is
25
+ * `>=0.16.0`, so a host on a newer design got `matchMedia(undefined)`, which
26
+ * never matches: every window was `narrow`, and the two- and three-pane
27
+ * layouts were unreachable. These widths come from measuring this layout,
28
+ * not from the design system's scale, so they belong to this file.
28
29
  */
30
+ export declare const PANE_QUERIES: {
31
+ readonly wide: "(min-width: 1150px)";
32
+ readonly medium: "(min-width: 860px)";
33
+ };
29
34
  export type Panes = 'wide' | 'medium' | 'narrow';
30
35
  /**
31
36
  * The current layout, updated as the window changes.
@@ -1,14 +1,46 @@
1
- import { MEDIA_QUERIES } from '@wtfalch/design';
2
1
  import { useEffect, useState } from 'react';
2
+ /**
3
+ * How many panes fit.
4
+ *
5
+ * A mail client is three columns on a desk and one column on a phone, and the
6
+ * difference is not a matter of styling: at one column the list and the
7
+ * message are the *same* space, so which of them is on screen becomes state
8
+ * the shell has to hold. CSS can narrow a column and cannot answer that, which
9
+ * is why this is a hook and not a media query in the stylesheet.
10
+ *
11
+ * Three, not a continuum:
12
+ *
13
+ * - `wide` — mailboxes, list and message side by side. Selecting a
14
+ * conversation reveals it; there is nothing to navigate to.
15
+ * - `medium` — the mailboxes collapse to a rail of icons, and the list and
16
+ * the message share what is left. Below 1150px a 3-column layout puts the reading measure under 45 characters,
17
+ * which is where prose stops being readable, and the mailbox names are the
18
+ * least valuable of the three.
19
+ * - `narrow` — one at a time, with the mailboxes in a drawer. Below 860px, where the list's
20
+ * two-line row can no longer hold a sender, a time and a subject without
21
+ * the subject truncating to nothing.
22
+ *
23
+ * **The two widths live here, not in `@wtfalch/design`.** They used to be
24
+ * read from its `PANE_QUERIES.wide` and `.medium`. Design 0.18.0 moved to
25
+ * Tailwind's sm-2xl scale and dropped both names, and the peer range here is
26
+ * `>=0.16.0`, so a host on a newer design got `matchMedia(undefined)`, which
27
+ * never matches: every window was `narrow`, and the two- and three-pane
28
+ * layouts were unreachable. These widths come from measuring this layout,
29
+ * not from the design system's scale, so they belong to this file.
30
+ */
31
+ export const PANE_QUERIES = {
32
+ wide: '(min-width: 1150px)',
33
+ medium: '(min-width: 860px)',
34
+ };
3
35
  function read() {
4
36
  /* Server rendering, and jsdom without the shim, both land here. `wide` is
5
37
  the right default for both: it is the layout with no hidden state, so a
6
38
  render that never gets a second chance still shows everything. */
7
39
  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function')
8
40
  return 'wide';
9
- if (window.matchMedia(MEDIA_QUERIES.wide).matches)
41
+ if (window.matchMedia(PANE_QUERIES.wide).matches)
10
42
  return 'wide';
11
- if (window.matchMedia(MEDIA_QUERIES.medium).matches)
43
+ if (window.matchMedia(PANE_QUERIES.medium).matches)
12
44
  return 'medium';
13
45
  return 'narrow';
14
46
  }
@@ -25,10 +57,7 @@ export function usePanes() {
25
57
  useEffect(() => {
26
58
  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function')
27
59
  return;
28
- const queries = [
29
- window.matchMedia(MEDIA_QUERIES.wide),
30
- window.matchMedia(MEDIA_QUERIES.medium),
31
- ];
60
+ const queries = [window.matchMedia(PANE_QUERIES.wide), window.matchMedia(PANE_QUERIES.medium)];
32
61
  const update = () => setPanes(read());
33
62
  for (const query of queries)
34
63
  query.addEventListener('change', update);
@@ -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>;
@@ -60,5 +60,36 @@ export declare function send(client: MailClient, draft: Draft, options?: SendOpt
60
60
  * `Email/set` and returns it under the update's own method call id, which a
61
61
  * multi-call reader that maps responses by id would lose. See the docblock
62
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`.
63
94
  */
64
- export declare function cancel(client: MailClient, sent: Sent, options?: CancelOptions): Promise<void>;
95
+ export declare function queued(client: MailClient): Promise<Queued[]>;
@@ -233,6 +233,10 @@ export async function send(client, draft, options = {}) {
233
233
  * `Email/set` and returns it under the update's own method call id, which a
234
234
  * multi-call reader that maps responses by id would lose. See the docblock
235
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.
236
240
  */
237
241
  export async function cancel(client, sent, options = {}) {
238
242
  const { jam, accountId } = await client.connect();
@@ -267,3 +271,59 @@ export async function cancel(client, sent, options = {}) {
267
271
  unsendFailed(result.notUpdated);
268
272
  });
269
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
+ }
@@ -211,6 +211,23 @@ export type Sent = {
211
211
  * for delivery. */
212
212
  sendAt: string;
213
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';
230
+ };
214
231
  /** The per-type state strings a push event carries. A value that differs
215
232
  * from the one a previous call returned means that type changed. */
216
233
  export type ChangedState = {
@@ -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", "sysMtaExtensionsGet"];
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,15 +48,19 @@ export const DASHBOARD_PERMISSIONS = [
48
48
  'sysDomainQuery',
49
49
  'sysDomainGet',
50
50
  'sysSystemSettingsGet',
51
- // Read-only, and the one permission here that is not about the `/email`
52
- // pages: `MtaExtensions` holds `futureRelease`, the setting that decides
53
- // whether a held message is really held. Without it a held send cannot even
54
- // be confirmed — the key is `forbidden` on `x:MtaExtensions/get`, and a
55
- // server that has the setting off accepts the submission, drops the hold and
56
- // reports success. The matching `sysMtaExtensionsUpdate` is deliberately not
57
- // here: provisioning writes that object with an administrative credential,
58
- // so the dashboard never needs to rewrite the MTA's extension config.
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`).
59
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',
60
64
  ];
61
65
  /** Which scheme a secret wants, from its own shape, for a caller holding one opaque string. */
62
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
@@ -115,14 +128,7 @@ export function mailObjects(i) {
115
128
  key: 'extensions',
116
129
  object: 'MtaExtensions',
117
130
  match: { id: 'singleton' },
118
- // futureRelease gates the SMTP FUTURERELEASE extension. Empty by
119
- // default, and empty means Stalwart's MAIL FROM handler skips the hold
120
- // block entirely: a held submission is sent immediately, silently, and
121
- // the client is told it succeeded. 30d matches the `maxDelayedSend` the
122
- // server advertises to clients unconditionally, so nothing smaller
123
- // would make that advertised capability a lie for a submission in
124
- // between.
125
- value: { futureRelease: { else: "'30d'" } },
131
+ value: { futureRelease: FUTURE_RELEASE },
126
132
  },
127
133
  {
128
134
  key: 'reload',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/email",
3
- "version": "0.12.0",
3
+ "version": "0.13.1",
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",