@wtfalch/email 0.15.1 → 0.17.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
@@ -71,6 +71,25 @@ A page of threads is **one round trip**: the query, the newest message per
71
71
  thread, the threads' member ids and the members are four method calls chained
72
72
  by JMAP result reference in a single request.
73
73
 
74
+ **Delta sync**, for a follower that has to notice new or moved mail without
75
+ holding a full JMAP client of its own — the gap Activity's mail source had to
76
+ work around by writing one. `emailChanges(client, { sinceState })` and
77
+ `mailboxChanges(client, { sinceState })` are RFC 8620 §5.2's `/changes`:
78
+ `{ oldState, newState, hasMoreChanges, created, updated, destroyed }`, id lists
79
+ only. Watch both — a thread moving folders changes `Mailbox`, not `Email`
80
+ membership, so a follower that only watches `Email` never notices a move.
81
+ `emailHeaders(client, ids)` reads `created`/`updated` back as a header-only
82
+ projection (`id`, `threadId`, `mailboxIds`, `from`, `subject`, `preview`,
83
+ `receivedAt`, `inReplyTo`, `keywords`) that never fetches a body or an
84
+ attachment. When the server can no longer diff from `sinceState`, both
85
+ `changes` calls throw a `MailError` typed `cannotCalculateChanges` —
86
+ `isCannotCalculateChanges(error)` tells a caller apart from any other failure,
87
+ so it knows to resync (list what it wants fresh, and start delta sync again
88
+ from the state that read returns) rather than retry. Works the same with a
89
+ service credential for someone else's account (`MailClientOptions.accountId`
90
+ plus a bearer or app-password credential the caller holds, not the signed-in
91
+ session's own) — Activity's calendar source already does this for calendars.
92
+
74
93
  `replyDraft` and `forwardDraft` are pure — give them a message and they
75
94
  compute the recipients, the subject prefix, the `In-Reply-To` and `References`
76
95
  chain and the quoted body, with no client and no network, so a composer can
@@ -162,7 +181,19 @@ one folder" owns generating that source itself.
162
181
 
163
182
  ### The React
164
183
 
165
- `@wtfalch/email/mailbox/react` draws it, on `@wtfalch/design` >=0.16.0.
184
+ `@wtfalch/email/mailbox/react` draws it, on `@wtfalch/design` ^0.30.0.
185
+
186
+ **Breaking: the floor moved from `^0.28.0` to `^0.30.0`.** 0.30.0 ships a
187
+ rewritten `Toggle` -- a busy state drawn as an opacity pulse and a new spring
188
+ on the knob, keyed to the new `--dur-spring` token -- and this package
189
+ follows the same rule PR #126 set: the peer tracks the design minor this
190
+ package actually builds and tests against, never a range wide enough to
191
+ claim an untested one. No estate host runs design 0.30 yet -- Archon peers
192
+ `0.29.0`, Agora's app resolves `0.28.0` -- so a host on an older design must
193
+ upgrade `@wtfalch/design` to 0.30.x before taking this `@wtfalch/email`
194
+ release; installing this range against an older design is a peer conflict,
195
+ not a silent downgrade.
196
+
166
197
  `Mail` is the whole client — mailboxes, list, message, composer,
167
198
  search, a toolbar, and a command palette on Cmd-K — and the only piece that
168
199
  holds state or fetches.
@@ -599,6 +630,19 @@ await applyOrgMail(client, { slug: 'acme', domain: 'acme.com', mode: 'hosted' },
599
630
  await parkOrgMail(client, { slug: 'acme', domain: 'acme.com', mode: 'hosted' }, options);
600
631
  ```
601
632
 
633
+ **One Lettermint relay per org.** `applyOrgRelay(client, { slug, domain, secret })`
634
+ upserts an `MtaRoute` named `lettermint-<slug>` (`smtp.lettermint.co`, port 465,
635
+ implicit TLS, user `lettermint`, the token as a `Value` secret) and rebuilds
636
+ `MtaOutboundStrategy.route` so mail from `domain` leaves through it and every
637
+ other sender falls back to the shared `resend` route. `removeOrgRelay(client,
638
+ { slug })` deletes the route and rebuilds; a missing route sends nothing.
639
+ `hasOrgRelay(client, { slug })` is true when the route holds a secret, so a
640
+ caller knows whether it needs a fresh token. The domain is kept in the route's
641
+ description, and the expression is rebuilt from the routes that exist, never
642
+ patched. `applyObjects` rebuilds it the same way, so re-applying the instance
643
+ plan keeps every org's route. Relay changes are not locked: two callers at once
644
+ can drop one org's entry until the next change, so run them one at a time.
645
+
602
646
  **One `Domain` per org, upserted by name.** `applyOrgMail` calls the same
603
647
  `Domain` object `mailObjects`/`applyObjects` write for the instance itself,
604
648
  so calling it twice with the same org leaves exactly one `Domain`, and
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Delta sync: "what changed since state S", for `Email` and `Mailbox`.
3
+ *
4
+ * A thread list or a mailbox count only ever refetches everything; a feed
5
+ * source that has to notice new mail without polling the whole account needs
6
+ * RFC 8620 §5.2's `/changes` instead, plus a body-free read of whatever
7
+ * changed. Both live here so a caller like Activity's mail source never has
8
+ * to hold its own JMAP client (activity#85, and the review that found this
9
+ * gap: email#124).
10
+ */
11
+ import { type MailClient } from './client.ts';
12
+ import { MailError } from './errors.ts';
13
+ import type { EmailAddress } from './types.ts';
14
+ /** RFC 8620 §5.2's method-level error: the given `sinceState` is too old (or
15
+ * unknown) for the server to diff against. The caller's only way forward is
16
+ * a resync -- list what it wants from scratch and start delta sync again
17
+ * from the state that read returns. */
18
+ export declare const CANNOT_CALCULATE_CHANGES = "cannotCalculateChanges";
19
+ /** Whether `error` is the server refusing to resume from `sinceState`, i.e.
20
+ * the one condition `changes()` cannot recover from on its own. */
21
+ export declare function isCannotCalculateChanges(error: unknown): error is MailError;
22
+ export type ChangesOptions = {
23
+ /** The state a previous call to this function, or to `Email/Mailbox get`,
24
+ * returned. */
25
+ sinceState: string;
26
+ /** How many ids to return at most. The server may return fewer; never more. */
27
+ maxChanges?: number;
28
+ };
29
+ /** RFC 8620 §5.2's `/changes` response, id lists only -- never the records
30
+ * themselves. `created`/`updated` still need a `get` (`emailHeaders` below,
31
+ * for `Email`) to read; `destroyed` needs nothing further. */
32
+ export type Changes = {
33
+ /** `sinceState` echoed back. */
34
+ oldState: string;
35
+ /** Pass this as the next call's `sinceState`. */
36
+ newState: string;
37
+ /** True when the server capped the page: call again with `newState` to
38
+ * keep draining before doing anything with the result you already have,
39
+ * as changes returned so far are only safe to treat as final once this is
40
+ * false. */
41
+ hasMoreChanges: boolean;
42
+ created: readonly string[];
43
+ updated: readonly string[];
44
+ destroyed: readonly string[];
45
+ };
46
+ /** What changed in `Email` since `sinceState`. Throws a `MailError` typed
47
+ * `cannotCalculateChanges` (see `isCannotCalculateChanges`) when the server
48
+ * can no longer diff from that state. */
49
+ export declare function emailChanges(client: MailClient, options: ChangesOptions): Promise<Changes>;
50
+ /** What changed in `Mailbox` since `sinceState` -- a thread moving between
51
+ * folders (Inbox to Archive, or into Trash) changes `Email.mailboxIds`, not
52
+ * `Email` membership itself, so a follower that only watches `Email`
53
+ * believes nothing happened. Watch both and treat either's change as a
54
+ * reason to reread the affected emails. */
55
+ export declare function mailboxChanges(client: MailClient, options: ChangesOptions): Promise<Changes>;
56
+ /** What a feed source needs from a changed message, and nothing it did not
57
+ * ask for: no body, no attachments. `from`, `subject`, `preview` and
58
+ * `inReplyTo` are absent (not merely empty) on a message whose header they
59
+ * come from was itself absent, which is JMAP's own distinction between
60
+ * "has none" and "was not sent this property" -- collapsing the two would
61
+ * make a message with a blank Subject indistinguishable from one this
62
+ * package failed to project. */
63
+ export type EmailHeaders = {
64
+ id: string;
65
+ threadId: string;
66
+ mailboxIds: Readonly<Record<string, boolean>>;
67
+ from?: readonly EmailAddress[];
68
+ subject?: string;
69
+ preview?: string;
70
+ receivedAt: string;
71
+ /** The `In-Reply-To` header's message ids, parsed (RFC 8621 §4.1.3). */
72
+ inReplyTo?: readonly string[];
73
+ keywords: Readonly<Record<string, boolean>>;
74
+ };
75
+ export type EmailHeadersPage = {
76
+ /** The `Email` type's state at the time of this read. Feed a fresh
77
+ * `changes()` call from here, the same way `ThreadPage.state` does for a
78
+ * thread list. */
79
+ state: string;
80
+ list: readonly EmailHeaders[];
81
+ /** An id `changes()` reported created or updated, but that no longer
82
+ * exists by the time this ran -- treat it the same as `destroyed`. */
83
+ notFound: readonly string[];
84
+ };
85
+ /**
86
+ * Read `emailChanges()`'s `created`/`updated` ids back as header-only
87
+ * projections, matching the shape a mail feed source needs and no more.
88
+ *
89
+ * Never fetches a body, `blobId` or attachment: the properties list is fixed
90
+ * to `HEADER_PROPERTIES`, so a caller cannot widen it into a body fetch by
91
+ * accident. A caller that wants the body opens the message the ordinary way
92
+ * (`thread()`), which a feed source that only indexes headers never does.
93
+ */
94
+ export declare function emailHeaders(client: MailClient, ids: readonly string[]): Promise<EmailHeadersPage>;
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Delta sync: "what changed since state S", for `Email` and `Mailbox`.
3
+ *
4
+ * A thread list or a mailbox count only ever refetches everything; a feed
5
+ * source that has to notice new mail without polling the whole account needs
6
+ * RFC 8620 §5.2's `/changes` instead, plus a body-free read of whatever
7
+ * changed. Both live here so a caller like Activity's mail source never has
8
+ * to hold its own JMAP client (activity#85, and the review that found this
9
+ * gap: email#124).
10
+ */
11
+ import { JAM_FETCH } from "./client.js";
12
+ import { MailError, guard } from "./errors.js";
13
+ /** RFC 8620 §5.2's method-level error: the given `sinceState` is too old (or
14
+ * unknown) for the server to diff against. The caller's only way forward is
15
+ * a resync -- list what it wants from scratch and start delta sync again
16
+ * from the state that read returns. */
17
+ export const CANNOT_CALCULATE_CHANGES = 'cannotCalculateChanges';
18
+ /** Whether `error` is the server refusing to resume from `sinceState`, i.e.
19
+ * the one condition `changes()` cannot recover from on its own. */
20
+ export function isCannotCalculateChanges(error) {
21
+ return error instanceof MailError && error.type === CANNOT_CALCULATE_CHANGES;
22
+ }
23
+ function argsOf(accountId, options) {
24
+ return {
25
+ accountId,
26
+ sinceState: options.sinceState,
27
+ ...(options.maxChanges === undefined ? {} : { maxChanges: options.maxChanges }),
28
+ };
29
+ }
30
+ /** What changed in `Email` since `sinceState`. Throws a `MailError` typed
31
+ * `cannotCalculateChanges` (see `isCannotCalculateChanges`) when the server
32
+ * can no longer diff from that state. */
33
+ export async function emailChanges(client, options) {
34
+ const { jam, accountId } = await client.connect();
35
+ return guard('changes.email', async () => {
36
+ const [result] = await jam.api.Email.changes(argsOf(accountId, options), JAM_FETCH);
37
+ return {
38
+ oldState: result.oldState,
39
+ newState: result.newState,
40
+ hasMoreChanges: result.hasMoreChanges,
41
+ created: result.created,
42
+ updated: result.updated,
43
+ destroyed: result.destroyed,
44
+ };
45
+ });
46
+ }
47
+ /** What changed in `Mailbox` since `sinceState` -- a thread moving between
48
+ * folders (Inbox to Archive, or into Trash) changes `Email.mailboxIds`, not
49
+ * `Email` membership itself, so a follower that only watches `Email`
50
+ * believes nothing happened. Watch both and treat either's change as a
51
+ * reason to reread the affected emails. */
52
+ export async function mailboxChanges(client, options) {
53
+ const { jam, accountId } = await client.connect();
54
+ return guard('changes.mailbox', async () => {
55
+ const [result] = await jam.api.Mailbox.changes(argsOf(accountId, options), JAM_FETCH);
56
+ return {
57
+ oldState: result.oldState,
58
+ newState: result.newState,
59
+ hasMoreChanges: result.hasMoreChanges,
60
+ created: result.created,
61
+ updated: result.updated,
62
+ destroyed: result.destroyed,
63
+ };
64
+ });
65
+ }
66
+ const HEADER_PROPERTIES = [
67
+ 'id',
68
+ 'threadId',
69
+ 'mailboxIds',
70
+ 'from',
71
+ 'subject',
72
+ 'preview',
73
+ 'receivedAt',
74
+ 'inReplyTo',
75
+ 'keywords',
76
+ ];
77
+ /**
78
+ * Read `emailChanges()`'s `created`/`updated` ids back as header-only
79
+ * projections, matching the shape a mail feed source needs and no more.
80
+ *
81
+ * Never fetches a body, `blobId` or attachment: the properties list is fixed
82
+ * to `HEADER_PROPERTIES`, so a caller cannot widen it into a body fetch by
83
+ * accident. A caller that wants the body opens the message the ordinary way
84
+ * (`thread()`), which a feed source that only indexes headers never does.
85
+ */
86
+ export async function emailHeaders(client, ids) {
87
+ const { jam, accountId } = await client.connect();
88
+ return guard('changes.emailHeaders', async () => {
89
+ const [result] = await jam.api.Email.get({ accountId, ids: [...ids], properties: HEADER_PROPERTIES }, JAM_FETCH);
90
+ return {
91
+ state: result.state,
92
+ list: result.list,
93
+ notFound: (result.notFound ?? []),
94
+ };
95
+ });
96
+ }
@@ -12,6 +12,8 @@ export { buildTree, createMailbox, deleteMailbox, findRole, mailboxes, renameMai
12
12
  export type { CreateMailboxOptions, DeleteMailboxOptions, FlatMailbox, NewMailbox, } from './mailboxes.ts';
13
13
  export { listThreads, queryThreads, summarise } from './threads.ts';
14
14
  export type { ListOptions } from './threads.ts';
15
+ export { CANNOT_CALCULATE_CHANGES, emailChanges, emailHeaders, isCannotCalculateChanges, mailboxChanges, } from './changes.ts';
16
+ export type { Changes, ChangesOptions, EmailHeaders, EmailHeadersPage } from './changes.ts';
15
17
  export { DEFAULT_MAX_BODY_BYTES, thread, toMessage } from './thread.ts';
16
18
  export type { RawMessage, ThreadOptions } from './thread.ts';
17
19
  export { search } from './search.ts';
@@ -8,6 +8,7 @@ export { MailClient, MAIL_CAPABILITY, SIEVE_CAPABILITY, SUBMISSION_CAPABILITY }
8
8
  export { MailError, toMailError } from "./errors.js";
9
9
  export { buildTree, createMailbox, deleteMailbox, findRole, mailboxes, renameMailbox, shareMailbox, unshareMailbox, walk, } from "./mailboxes.js";
10
10
  export { listThreads, queryThreads, summarise } from "./threads.js";
11
+ export { CANNOT_CALCULATE_CHANGES, emailChanges, emailHeaders, isCannotCalculateChanges, mailboxChanges, } from "./changes.js";
11
12
  export { DEFAULT_MAX_BODY_BYTES, thread, toMessage } from "./thread.js";
12
13
  export { search } from "./search.js";
13
14
  export { identities } from "./identities.js";
@@ -6,7 +6,7 @@
6
6
  * and reused by an application with its own layout. `Mail` is the one piece
7
7
  * that holds state and calls the hooks.
8
8
  *
9
- * On `@wtfalch/design` >=0.16.0 and `@wtfalch/email/mailbox`. Import `@wtfalch/email/mailbox/mail.css`
9
+ * On `@wtfalch/design` ^0.30.0 and `@wtfalch/email/mailbox`. Import `@wtfalch/email/mailbox/mail.css`
10
10
  * after the design stylesheet.
11
11
  */
12
12
  export { MailProvider, useMailClient, useOptionalMailClient } from './context.tsx';
@@ -6,7 +6,7 @@
6
6
  * and reused by an application with its own layout. `Mail` is the one piece
7
7
  * that holds state and calls the hooks.
8
8
  *
9
- * On `@wtfalch/design` >=0.16.0 and `@wtfalch/email/mailbox`. Import `@wtfalch/email/mailbox/mail.css`
9
+ * On `@wtfalch/design` ^0.30.0 and `@wtfalch/email/mailbox`. Import `@wtfalch/email/mailbox/mail.css`
10
10
  * after the design stylesheet.
11
11
  */
12
12
  export { MailProvider, useMailClient, useOptionalMailClient } from "./context.js";
@@ -17,12 +17,12 @@
17
17
  export { API_KEY_PREFIX, DASHBOARD_PERMISSIONS, StalwartClient, StalwartError, authFor, type Credential, type SessionInfo, 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 { FUTURE_RELEASE, applyObjects, mailObjects, ref, type MailObjectsInput, type PlannedObject, } from './objects.js';
20
+ export { FUTURE_RELEASE, applyObjects, mailObjects, platformMailSettingsObjects, ref, type MailObjectsInput, type PlannedObject, type PlatformMailSettingsInput, } 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, membershipIds, newAccount, newGroup, withAlias, withMembership, withoutAlias, withoutApiKey, withoutAppPassword, withoutMembership, } from './writes.js';
24
24
  export { addAlias, addToGroup, createGroupMailbox, createMailbox, enableHolding, holdLimit, purgeQueuedMessage, removeAlias, removeFromGroup, retryQueuedMessage, revokeApiKey, revokeAppPassword, spamSettings, updateSpamSettings, type Applied, type SpamSettingsInput, type SpamSettingsView, } from './apply.js';
25
25
  export { loadQueue, queueMessageView, type QueueMessage, type QueueRecipient, type QueueRecipientState, } from './queue.js';
26
- export { applyOrgMail, dkimRecordsFromZoneFile, parkOrgMail, type DnsRecordSpec, type OrgMailMode, type OrgMailOptions, type OrgMailOrg, type OrgMailResult, } from './org-mail.js';
26
+ export { applyOrgMail, applyOrgRelay, dkimRecordsFromZoneFile, hasOrgRelay, parkOrgMail, removeOrgRelay, type OrgRelayInput, type OrgRelayOrg, type DnsRecordSpec, type OrgMailMode, type OrgMailOptions, type OrgMailOrg, type OrgMailResult, } from './org-mail.js';
27
27
  export { POSTMASTER_AUDIT_EVENTS, type PostmasterAudit, type PostmasterAuditAction, type PostmasterAuditEvent, } from './audit.js';
28
28
  export { MailCopyPlanRefused, mailCopyPlan, type MailCopyAccount, type MailCopyAccountPlan, type MailCopyEnv, type MailCopyOptions, type MailCopyPlan, type MailCopyProvider, } from './mail-copy.js';
@@ -17,12 +17,12 @@
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 { FUTURE_RELEASE, applyObjects, mailObjects, ref, } from './objects.js';
20
+ export { FUTURE_RELEASE, applyObjects, mailObjects, platformMailSettingsObjects, ref, } from './objects.js';
21
21
  export { planMailboxes, withPassword } from './mailboxes.js';
22
22
  export { overview, pickDomain, } from './overview.js';
23
23
  export { MailWriteRefused, membershipIds, newAccount, newGroup, withAlias, withMembership, withoutAlias, withoutApiKey, withoutAppPassword, withoutMembership, } from './writes.js';
24
24
  export { addAlias, addToGroup, createGroupMailbox, createMailbox, enableHolding, holdLimit, purgeQueuedMessage, removeAlias, removeFromGroup, retryQueuedMessage, revokeApiKey, revokeAppPassword, spamSettings, updateSpamSettings, } from './apply.js';
25
25
  export { loadQueue, queueMessageView, } from './queue.js';
26
- export { applyOrgMail, dkimRecordsFromZoneFile, parkOrgMail, } from './org-mail.js';
26
+ export { applyOrgMail, applyOrgRelay, dkimRecordsFromZoneFile, hasOrgRelay, parkOrgMail, removeOrgRelay, } from './org-mail.js';
27
27
  export { POSTMASTER_AUDIT_EVENTS, } from './audit.js';
28
28
  export { MailCopyPlanRefused, mailCopyPlan, } from './mail-copy.js';
@@ -53,6 +53,30 @@ export interface PlannedObject {
53
53
  match: Record<string, unknown>;
54
54
  value: Record<string, unknown>;
55
55
  }
56
+ export interface PlatformMailSettingsInput {
57
+ /** The platform's own apex domain, written lowercased as `usernameDomain`. */
58
+ apex: string;
59
+ /** The MX target and TLS name, e.g. `mx.example.com`. */
60
+ mailHost: string;
61
+ oidc: {
62
+ issuerUrl: string;
63
+ audience: string;
64
+ requireScopes?: Record<string, boolean>;
65
+ claimUsername?: string;
66
+ };
67
+ }
68
+ /**
69
+ * The platform's own mail settings: Stalwart's default hostname and an OIDC
70
+ * sign-in directory, and nothing else. `mailObjects` cannot stand in for
71
+ * this — it also writes an `AcmeProvider`, a `DnsServer` and a Resend
72
+ * `MtaRoute`, none of which the platform step wants.
73
+ *
74
+ * A blank `mailHost`, `apex`, `oidc.issuerUrl` or `oidc.audience` throws,
75
+ * naming the field: each reaches a live server, and a blank audience in
76
+ * particular lets Stalwart skip the audience check, so any token from the
77
+ * issuer would sign in.
78
+ */
79
+ export declare function platformMailSettingsObjects(input: PlatformMailSettingsInput): PlannedObject[];
56
80
  /**
57
81
  * `MtaExtensions.futureRelease`: how long the server will hold a message
58
82
  * before sending it. It gates the SMTP FUTURERELEASE extension. Empty by
@@ -1,6 +1,116 @@
1
+ import { outboundRoute } from './org-mail.js';
1
2
  /** A value that names an object created earlier in the same plan. */
2
3
  export const ref = (key) => ({ $ref: key });
3
4
  const env = (variableName) => ({ '@type': 'EnvironmentVariable', variableName });
5
+ /**
6
+ * The `Directory` of `@type: 'Oidc'` that signs people in against an
7
+ * identity provider, in the one field shape both `mailObjects` (an org
8
+ * domain) and `platformMailSettingsObjects` (the platform's own server)
9
+ * write it in. Shared so the two never drift apart.
10
+ */
11
+ function oidcDirectoryObject(apex, oidc) {
12
+ const description = `${oidc.issuerUrl} (${apex})`;
13
+ return {
14
+ key: 'oidc',
15
+ object: 'Directory',
16
+ match: { description },
17
+ value: {
18
+ '@type': 'Oidc',
19
+ description,
20
+ issuerUrl: oidc.issuerUrl,
21
+ requireAudience: oidc.audience,
22
+ requireScopes: oidc.requireScopes ?? {},
23
+ claimUsername: oidc.claimUsername ?? 'preferred_username',
24
+ usernameDomain: apex,
25
+ claimName: 'name',
26
+ },
27
+ };
28
+ }
29
+ function requireNonBlank(value, fieldName) {
30
+ const trimmed = value.trim();
31
+ if (!trimmed)
32
+ throw new Error(`platformMailSettingsObjects: "${fieldName}" must not be blank`);
33
+ return trimmed;
34
+ }
35
+ /**
36
+ * Stalwart compares `iss` as a plain string, and the Directory's `match` key
37
+ * is built from the raw issuer, so a respelling of the same issuer creates a
38
+ * second Directory instead of updating the first. This rejects every
39
+ * respelling rather than normalising it: a non-canonical issuer in the
40
+ * caller's config is a configuration bug worth surfacing, not silently
41
+ * fixing up.
42
+ */
43
+ function validatedIssuerUrl(raw) {
44
+ const issuerUrl = requireNonBlank(raw, 'oidc.issuerUrl');
45
+ if (issuerUrl.endsWith('/')) {
46
+ throw new Error('platformMailSettingsObjects: "oidc.issuerUrl" must not end with a trailing slash');
47
+ }
48
+ let url;
49
+ try {
50
+ url = new URL(issuerUrl);
51
+ }
52
+ catch {
53
+ throw new Error('platformMailSettingsObjects: "oidc.issuerUrl" must be a valid URL');
54
+ }
55
+ if (url.protocol !== 'https:') {
56
+ throw new Error('platformMailSettingsObjects: "oidc.issuerUrl" must be https');
57
+ }
58
+ const canonical = url.origin + (url.pathname === '/' ? '' : url.pathname);
59
+ if (canonical !== issuerUrl) {
60
+ throw new Error('platformMailSettingsObjects: "oidc.issuerUrl" must be in canonical form (no case, userinfo, query, fragment, or respelling)');
61
+ }
62
+ return issuerUrl;
63
+ }
64
+ function validatedClaimUsername(raw) {
65
+ if (raw === undefined)
66
+ return 'preferred_username';
67
+ return requireNonBlank(raw, 'oidc.claimUsername');
68
+ }
69
+ /**
70
+ * The platform's own mail settings: Stalwart's default hostname and an OIDC
71
+ * sign-in directory, and nothing else. `mailObjects` cannot stand in for
72
+ * this — it also writes an `AcmeProvider`, a `DnsServer` and a Resend
73
+ * `MtaRoute`, none of which the platform step wants.
74
+ *
75
+ * A blank `mailHost`, `apex`, `oidc.issuerUrl` or `oidc.audience` throws,
76
+ * naming the field: each reaches a live server, and a blank audience in
77
+ * particular lets Stalwart skip the audience check, so any token from the
78
+ * issuer would sign in.
79
+ */
80
+ export function platformMailSettingsObjects(input) {
81
+ const mailHost = requireNonBlank(input.mailHost, 'mailHost');
82
+ const apex = requireNonBlank(input.apex, 'apex').toLowerCase();
83
+ const issuerUrl = validatedIssuerUrl(input.oidc.issuerUrl);
84
+ const audience = requireNonBlank(input.oidc.audience, 'oidc.audience');
85
+ const claimUsername = validatedClaimUsername(input.oidc.claimUsername);
86
+ const directory = oidcDirectoryObject(apex, {
87
+ issuerUrl,
88
+ audience,
89
+ requireScopes: input.oidc.requireScopes,
90
+ claimUsername,
91
+ });
92
+ return [
93
+ {
94
+ key: 'system',
95
+ object: 'SystemSettings',
96
+ match: { id: 'singleton' },
97
+ value: { defaultHostname: mailHost },
98
+ },
99
+ directory,
100
+ {
101
+ key: 'auth',
102
+ object: 'Authentication',
103
+ match: { id: 'singleton' },
104
+ value: { directoryId: ref('oidc') },
105
+ },
106
+ {
107
+ key: 'reload',
108
+ object: 'Action',
109
+ match: {},
110
+ value: { '@type': 'ReloadSettings' },
111
+ },
112
+ ];
113
+ }
4
114
  /**
5
115
  * `MtaExtensions.futureRelease`: how long the server will hold a message
6
116
  * before sending it. It gates the SMTP FUTURERELEASE extension. Empty by
@@ -20,26 +130,7 @@ export const FUTURE_RELEASE = { else: "'30d'" };
20
130
  * server. What each object is for is in wtfalch-manage's docs/plans/email.md (E3 to E5).
21
131
  */
22
132
  export function mailObjects(i) {
23
- const oidcDescription = i.oidc ? `${i.oidc.issuerUrl} (${i.apex})` : undefined;
24
- const directory = i.oidc
25
- ? [
26
- {
27
- key: 'oidc',
28
- object: 'Directory',
29
- match: { description: oidcDescription },
30
- value: {
31
- '@type': 'Oidc',
32
- description: oidcDescription,
33
- issuerUrl: i.oidc.issuerUrl,
34
- requireAudience: i.oidc.audience,
35
- requireScopes: i.oidc.requireScopes ?? {},
36
- claimUsername: i.oidc.claimUsername ?? 'preferred_username',
37
- usernameDomain: i.apex,
38
- claimName: 'name',
39
- },
40
- },
41
- ]
42
- : [];
133
+ const directory = i.oidc ? [oidcDirectoryObject(i.apex, i.oidc)] : [];
43
134
  return [
44
135
  {
45
136
  key: 'acme',
@@ -173,6 +264,10 @@ export async function applyObjects(client, plan, log) {
173
264
  const ids = {};
174
265
  for (const p of plan) {
175
266
  const value = resolve(p.value, ids);
267
+ // The plan's route is the shared-relay default. Org relay routes live on
268
+ // the server, so they are rebuilt here rather than overwritten.
269
+ if (p.object === 'MtaOutboundStrategy')
270
+ value.route = await outboundRoute(client);
176
271
  if (p.match.id === 'singleton') {
177
272
  await client.update(p.object, 'singleton', value);
178
273
  ids[p.key] = 'singleton';
@@ -115,3 +115,50 @@ export declare function applyOrgMail(client: StalwartClient, org: OrgMailOrg, op
115
115
  * already parked: neither sends a request.
116
116
  */
117
117
  export declare function parkOrgMail(client: StalwartClient, org: OrgMailOrg, options: OrgMailOptions): Promise<void>;
118
+ /**
119
+ * One org's outgoing mail through its own Lettermint credential, limited to
120
+ * that org's domain (`wtfalch/email#118`). The shared `resend` route from
121
+ * `mailObjects` stays the `else` fallback, so a domain with no relay of its
122
+ * own still sends.
123
+ *
124
+ * Each org gets an `MtaRoute` named `lettermint-<slug>`. The domain it
125
+ * serves is stored in the route's `description`, because that is the only
126
+ * place a caller can read it back from. After every change the
127
+ * `MtaOutboundStrategy.route` expression is rebuilt from the routes that
128
+ * exist, never patched. The list, write and rebuild are not locked or
129
+ * version-checked: two callers running at once can each list before the other
130
+ * writes, and the later write can leave the other's route out of the expression
131
+ * until the next change rebuilds it. Callers must not run relay changes
132
+ * concurrently.
133
+ */
134
+ export interface OrgRelayOrg {
135
+ readonly slug: string;
136
+ /** The sender domain this relay carries, e.g. `acme.com`. */
137
+ readonly domain: string;
138
+ }
139
+ export interface OrgRelayInput extends OrgRelayOrg {
140
+ /** The Lettermint project token. Sent as `@type: Value` and never logged or thrown. */
141
+ readonly secret: string;
142
+ }
143
+ /** The `MtaOutboundStrategy.route` expression for the relays that exist now.
144
+ * `applyObjects` uses it too, so a re-apply of the instance plan keeps every
145
+ * org's route instead of resetting the expression to the `resend` fallback. */
146
+ export declare function outboundRoute(client: StalwartClient): Promise<Record<string, unknown>>;
147
+ /**
148
+ * Give an org its own Lettermint relay, or replace its token. Idempotent: the
149
+ * route is upserted by name, so calling it twice leaves one route and one
150
+ * entry in the route expression.
151
+ */
152
+ export declare function applyOrgRelay(client: StalwartClient, input: OrgRelayInput): Promise<void>;
153
+ /** Remove an org's relay. A missing route is a no-op: nothing is sent. */
154
+ export declare function removeOrgRelay(client: StalwartClient, org: {
155
+ readonly slug: string;
156
+ }): Promise<void>;
157
+ /**
158
+ * Whether the org's relay exists with a secret set. Foundry uses it to decide
159
+ * whether the relay needs a fresh token. A route whose secret the server does
160
+ * not report counts as not set, which costs one new token, never a missing one.
161
+ */
162
+ export declare function hasOrgRelay(client: StalwartClient, org: {
163
+ readonly slug: string;
164
+ }): Promise<boolean>;
@@ -204,3 +204,112 @@ export async function parkOrgMail(client, org, options) {
204
204
  return;
205
205
  await client.update('Domain', existing.id, { isEnabled: false });
206
206
  }
207
+ const RELAY_PREFIX = 'lettermint-';
208
+ const RELAY_DESCRIPTION = 'Lettermint relay for ';
209
+ const FALLBACK_ROUTE = "'resend'";
210
+ function relayName(slug) {
211
+ assertLabel('an org slug', slug);
212
+ return `${RELAY_PREFIX}${slug}`;
213
+ }
214
+ async function listRelays(client) {
215
+ const routes = await client.list('MtaRoute');
216
+ return routes.filter((r) => r.name?.startsWith(RELAY_PREFIX));
217
+ }
218
+ /** The domain a relay route carries, or undefined if its description is not ours. */
219
+ function relayDomain(route) {
220
+ const d = route.description;
221
+ if (!d?.startsWith(RELAY_DESCRIPTION))
222
+ return undefined;
223
+ const domain = d.slice(RELAY_DESCRIPTION.length);
224
+ // The domain goes into an expression below, so anything that is not a
225
+ // plain domain is dropped rather than interpolated.
226
+ try {
227
+ assertDomain(domain);
228
+ }
229
+ catch {
230
+ return undefined;
231
+ }
232
+ return domain;
233
+ }
234
+ /** One expression rule. Built from entries because Stalwart's key is `then` and a
235
+ * literal `then` property trips the `noThenProperty` lint. */
236
+ function routeRule(domain, routeName) {
237
+ return Object.fromEntries([
238
+ ['if', `sender_domain = '${domain}'`],
239
+ ['then', `'${routeName}'`],
240
+ ]);
241
+ }
242
+ /** The `MtaOutboundStrategy.route` expression for the relays that exist now.
243
+ * `applyObjects` uses it too, so a re-apply of the instance plan keeps every
244
+ * org's route instead of resetting the expression to the `resend` fallback. */
245
+ export async function outboundRoute(client) {
246
+ const entries = (await listRelays(client))
247
+ .flatMap((r) => {
248
+ const domain = relayDomain(r);
249
+ return domain && r.name ? [{ domain, name: r.name }] : [];
250
+ })
251
+ .sort((a, b) => a.name.localeCompare(b.name));
252
+ return entries.length === 0
253
+ ? { else: FALLBACK_ROUTE }
254
+ : {
255
+ match: Object.fromEntries(entries.map((e, i) => [String(i), routeRule(e.domain, e.name)])),
256
+ else: FALLBACK_ROUTE,
257
+ };
258
+ }
259
+ async function rebuildRoute(client) {
260
+ const route = await outboundRoute(client);
261
+ await client.update('MtaOutboundStrategy', 'singleton', { route });
262
+ await client.create('Action', { '@type': 'ReloadSettings' });
263
+ }
264
+ /**
265
+ * Give an org its own Lettermint relay, or replace its token. Idempotent: the
266
+ * route is upserted by name, so calling it twice leaves one route and one
267
+ * entry in the route expression.
268
+ */
269
+ export async function applyOrgRelay(client, input) {
270
+ const name = relayName(input.slug);
271
+ assertDomain(input.domain);
272
+ if (!input.secret)
273
+ throw new MailWriteRefused('a relay needs a non-empty secret');
274
+ const value = {
275
+ '@type': 'Relay',
276
+ name,
277
+ description: `${RELAY_DESCRIPTION}${input.domain}`,
278
+ address: 'smtp.lettermint.co',
279
+ port: 465,
280
+ protocol: 'smtp',
281
+ implicitTls: true,
282
+ authUsername: 'lettermint',
283
+ authSecret: { '@type': 'Value', secret: input.secret },
284
+ };
285
+ // An MtaRoute's `name` is immutable: the server refuses to see it again.
286
+ const { name: _name, ...patch } = value;
287
+ const existing = (await listRelays(client)).find((r) => r.name === name);
288
+ if (existing)
289
+ await client.update('MtaRoute', existing.id, patch);
290
+ else
291
+ await client.create('MtaRoute', value);
292
+ await rebuildRoute(client);
293
+ }
294
+ /** Remove an org's relay. A missing route is a no-op: nothing is sent. */
295
+ export async function removeOrgRelay(client, org) {
296
+ const name = relayName(org.slug);
297
+ const existing = (await listRelays(client)).find((r) => r.name === name);
298
+ if (!existing)
299
+ return;
300
+ const { notDestroyed } = await client.destroy('MtaRoute', [existing.id]);
301
+ const failure = notDestroyed[existing.id];
302
+ if (failure)
303
+ throw new MailWriteRefused(`relay ${name} was not removed: ${failure.type}`);
304
+ await rebuildRoute(client);
305
+ }
306
+ /**
307
+ * Whether the org's relay exists with a secret set. Foundry uses it to decide
308
+ * whether the relay needs a fresh token. A route whose secret the server does
309
+ * not report counts as not set, which costs one new token, never a missing one.
310
+ */
311
+ export async function hasOrgRelay(client, org) {
312
+ const name = relayName(org.slug);
313
+ const route = (await listRelays(client)).find((r) => r.name === name);
314
+ return route?.authSecret?.['@type'] === 'Value' && Boolean(route.authSecret.secret);
315
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/email",
3
- "version": "0.15.1",
3
+ "version": "0.17.0",
4
4
  "description": "The wtfalch estate: reading a mailbox over JMAP, administering the Stalwart server it lives on, and iTIP scheduling over iMIP. Three entries with no code in common.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -46,7 +46,7 @@
46
46
  "record-fixtures": "node scripts/record-fixtures.mjs"
47
47
  },
48
48
  "peerDependencies": {
49
- "@wtfalch/design": ">=0.16.0",
49
+ "@wtfalch/design": "^0.30.0",
50
50
  "react": "^19.0.0",
51
51
  "react-dom": "^19.0.0"
52
52
  },
@@ -65,7 +65,7 @@
65
65
  "@types/node": "^22",
66
66
  "@types/react": "^19",
67
67
  "@types/react-dom": "^19",
68
- "@wtfalch/design": "0.16.0",
68
+ "@wtfalch/design": "0.30.0",
69
69
  "jsdom": "^30.0.1",
70
70
  "react": "^19",
71
71
  "react-dom": "^19",