@wtfalch/email 0.15.0 → 0.16.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
@@ -22,6 +22,10 @@ anybody's messages.
22
22
  The post office holds the analogy: one is the letters, one is what's inside a
23
23
  particular kind of envelope, the other is the pigeonholes.
24
24
 
25
+ ## Status
26
+
27
+ Published: yes, v0.15.1, 2026-09-28.
28
+
25
29
  ---
26
30
 
27
31
  ## @wtfalch/email/mailbox
@@ -67,6 +71,25 @@ A page of threads is **one round trip**: the query, the newest message per
67
71
  thread, the threads' member ids and the members are four method calls chained
68
72
  by JMAP result reference in a single request.
69
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
+
70
93
  `replyDraft` and `forwardDraft` are pure — give them a message and they
71
94
  compute the recipients, the subject prefix, the `In-Reply-To` and `References`
72
95
  chain and the quoted body, with no client and no network, so a composer can
@@ -158,7 +181,19 @@ one folder" owns generating that source itself.
158
181
 
159
182
  ### The React
160
183
 
161
- `@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
+
162
197
  `Mail` is the whole client — mailboxes, list, message, composer,
163
198
  search, a toolbar, and a command palette on Cmd-K — and the only piece that
164
199
  holds state or fetches.
@@ -576,9 +611,9 @@ calling Cloudflare itself.
576
611
  ```ts
577
612
  import { applyOrgMail, parkOrgMail } from '@wtfalch/email/postmaster';
578
613
 
579
- const options = { apex: 'wtfalch.dev', mailHost: 'mail.wtfalch.dev' };
614
+ const options = { apex: 'oikos.host', mailHost: 'mail.oikos.host' };
580
615
 
581
- // Level 1: no domain of its own, so it lives at acme.wtfalch.dev and must be hosted.
616
+ // Level 1: no domain of its own, so it lives at acme.oikos.host and must be hosted.
582
617
  await applyOrgMail(client, { slug: 'acme', mode: 'hosted' }, options);
583
618
 
584
619
  // A domain of its own, kept receiving through Google or Microsoft.
@@ -595,6 +630,19 @@ await applyOrgMail(client, { slug: 'acme', domain: 'acme.com', mode: 'hosted' },
595
630
  await parkOrgMail(client, { slug: 'acme', domain: 'acme.com', mode: 'hosted' }, options);
596
631
  ```
597
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
+
598
646
  **One `Domain` per org, upserted by name.** `applyOrgMail` calls the same
599
647
  `Domain` object `mailObjects`/`applyObjects` write for the instance itself,
600
648
  so calling it twice with the same org leaves exactly one `Domain`, and
@@ -635,7 +683,7 @@ publishes.
635
683
 
636
684
  **Level 1 is the slug on the shared apex, and freezes there.** An org with
637
685
  no `domain` gets `${slug}.${apex}` (foundry#7: "Level 1 gets
638
- `@acme.wtfalch.dev`") and its `mode` must be `hosted` — there is nowhere
686
+ `@acme.oikos.host`") and its `mode` must be `hosted` — there is nowhere
639
687
  else for a level-1 org's mail to be `received` at. `applyOrgMail` and
640
688
  `parkOrgMail` both refuse a slug or a domain that is not a lowercase DNS
641
689
  label before making a request.
@@ -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";
@@ -23,6 +23,6 @@ export { overview, pickDomain, type AccountView, type CredentialSummary, type Do
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';
@@ -23,6 +23,6 @@ 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';
@@ -1,3 +1,4 @@
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 });
@@ -173,6 +174,10 @@ export async function applyObjects(client, plan, log) {
173
174
  const ids = {};
174
175
  for (const p of plan) {
175
176
  const value = resolve(p.value, ids);
177
+ // The plan's route is the shared-relay default. Org relay routes live on
178
+ // the server, so they are rebuilt here rather than overwritten.
179
+ if (p.object === 'MtaOutboundStrategy')
180
+ value.route = await outboundRoute(client);
176
181
  if (p.match.id === 'singleton') {
177
182
  await client.update(p.object, 'singleton', value);
178
183
  ids[p.key] = 'singleton';
@@ -64,15 +64,15 @@ export interface OrgMailOrg {
64
64
  readonly mode: OrgMailMode;
65
65
  }
66
66
  export interface OrgMailOptions {
67
- /** The shared mail apex a level-1 org's domain is built under, e.g. `wtfalch.dev`. */
67
+ /** The shared mail apex a level-1 org's domain is built under, e.g. `oikos.host`. */
68
68
  readonly apex: string;
69
- /** The MX target and TLS name every domain on this instance shares, e.g. `mail.wtfalch.dev`. */
69
+ /** The MX target and TLS name every domain on this instance shares, e.g. `mail.oikos.host`. */
70
70
  readonly mailHost: string;
71
71
  }
72
72
  /** One DNS record foundry must publish. `priority` is set only for `MX`. */
73
73
  export interface DnsRecordSpec {
74
74
  readonly type: 'MX' | 'TXT';
75
- /** Fully-qualified, no trailing dot — e.g. `acme.wtfalch.dev` or `selector1._domainkey.acme.wtfalch.dev`. */
75
+ /** Fully-qualified, no trailing dot — e.g. `acme.oikos.host` or `selector1._domainkey.acme.oikos.host`. */
76
76
  readonly name: string;
77
77
  readonly value: string;
78
78
  readonly priority?: number;
@@ -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>;
@@ -16,7 +16,7 @@ function assertDomain(value) {
16
16
  /**
17
17
  * The `Domain` name this org's mail lives on. Refuses before any request: an
18
18
  * org with no domain of its own is level 1, and foundry#7's "Level 1 gets
19
- * `@acme.wtfalch.dev`" fixes both what the name is and that it can only ever
19
+ * `@acme.oikos.host`" fixes both what the name is and that it can only ever
20
20
  * be `hosted` — a level-1 org has nowhere else for mail to be `received` at.
21
21
  */
22
22
  function resolveDomain(org, options) {
@@ -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.0",
3
+ "version": "0.16.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",