@wtfalch/email 0.17.0 → 0.18.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
@@ -306,6 +306,29 @@ otherwise builds a URL addressing the wrong thing.
306
306
  display name. `src/mailbox/fixtures/instance-one.json` is recorded from a live
307
307
  0.16.20 instance and pins it.
308
308
 
309
+ **`Message.senderAuthenticated` reads the `Authentication-Results` header
310
+ Stalwart's inbound `DATA` handling stamps on accepted mail**, merging its
311
+ DKIM/DKIM2, SPF, IPREV and DMARC checks into one header
312
+ (`crates/smtp/src/inbound/data.rs`, `stalwartlabs/stalwart`, gated on a
313
+ config toggle, `dc.add_auth_results`, this package has not confirmed is on
314
+ for any real deployment), in the wire format
315
+ `stalwartlabs/mail-auth`'s `AuthenticationResults` `HeaderWriter` builds
316
+ (`src/auth_results.rs`). `thread()` reads every instance with RFC 8621
317
+ §4.1.3's `header:Authentication-Results:asRaw:all`, confirmed as a generic
318
+ `EmailProperty::Header` case (`crates/jmap/src/email/get.rs`) rather than a
319
+ hand-picked header list, and `mailbox/auth-results.ts` derives `true` from a
320
+ DKIM signature whose `header.d=`/`header.i=` domain exactly matches the
321
+ message's `from[0]` domain, or a `dmarc=pass`. **Fails closed**: a sender can write its own `Authentication-Results`
322
+ header, and the server hostname is public, so a matching `authserv-id` alone
323
+ proves nothing. Stalwart prepends its own header (`add_auth_results`, on by
324
+ default) and never strips incoming ones, so only the topmost instance is
325
+ read. `senderAuthenticated` is always `false` unless the caller passes
326
+ `{ trustedAuthServId }` (the instance's Stalwart `hostname`), and then only
327
+ if the first instance carries that `authserv-id` (case-insensitive); later
328
+ instances are never read. Setting the option asserts the receiving server
329
+ prepends its own header on every message; if it does not, leave it unset.
330
+ **Not confirmed**: which hostname a real instance uses.
331
+
309
332
  **`jmap-jam` is kept internal.** It ships raw TypeScript with `.ts` import
310
333
  specifiers, which only compiles under `allowImportingTsExtensions`; nothing of
311
334
  it reaches this package's public types, so a consumer does not inherit the
@@ -792,3 +815,74 @@ documents for IMAP. The alternative is a Graph `Mail.Read` application
792
815
  permission instead, which is what `import exchange-graph` would need; this
793
816
  package uses the IMAP path instead (see above), so `IMAP.AccessAsApp` is
794
817
  the one this plan's admin setup actually needs.
818
+
819
+ ## Backing up and restoring one org's mail
820
+
821
+ Every org's mail lives in the one shared Stalwart instance, scoped only by
822
+ `Domain` — so there is no per-org database or container for a company-wide
823
+ backup ([`archon#132`](https://github.com/wtfalch/archon/issues/132)) to
824
+ snapshot the way it can a company's own Postgres. `accountsOnDomain`,
825
+ `orgMailBackupPlan` and `orgMailRestorePlan`
826
+ ([`wtfalch/email#139`](https://github.com/wtfalch/email/issues/139)) pull
827
+ one org's mail out of the shared instance's own store instead, and plan it
828
+ back into a — possibly different — shared instance later.
829
+
830
+ ```ts
831
+ import {
832
+ accountsOnDomain,
833
+ orgMailBackupPlan,
834
+ orgMailRestorePlan,
835
+ } from '@wtfalch/email/postmaster';
836
+
837
+ // 1. Which accounts does this org have, on the instance being backed up?
838
+ const accounts = await accountsOnDomain(client, 'acme.com');
839
+
840
+ // 2. The Vandelay commands that pull each one's mail into a local archive.
841
+ const backup = orgMailBackupPlan({
842
+ accounts,
843
+ stalwartUrl: 'https://mail.wtfalch.dev',
844
+ archiveDir: '/var/lib/mail-backup/acme',
845
+ });
846
+
847
+ // 3. Later, possibly on a different instance: resolve the same addresses to
848
+ // that instance's own account ids (re-provisioning the org there first,
849
+ // then accountsOnDomain again, gives exactly this), and push the
850
+ // archives back in.
851
+ const restore = orgMailRestorePlan({
852
+ accounts: [{ address: 'alice@acme.com', targetAccountId: 'b1' }],
853
+ stalwartUrl: 'https://mail.wtfalch.dev',
854
+ archiveDir: '/var/lib/mail-backup/acme',
855
+ });
856
+ ```
857
+
858
+ **This is `mail-copy.ts`'s mirror image, not a new mechanism.** Vandelay
859
+ already speaks JMAP on both sides, so a backup is `import jmap` reading
860
+ *this* org's own account off the shared instance — the source is the
861
+ instance itself, not Google or Microsoft — and a restore is the same
862
+ `export` `mailCopyPlan` already uses, into a target account on whichever
863
+ instance the restore runs against. Confirmed against
864
+ `stalwartlabs/vandelay` at commit `486a3847121732fc46c2433de0e0ed50bbcb5825`
865
+ (`main`, 2026-10-04): `Source::Jmap(Box<JmapImportArgs>)` at `src/cli.rs:58`,
866
+ `JmapImportArgs` at `src/cli.rs:131-174`, requiring exactly one of
867
+ `auth_basic`/`auth_bearer` and one of `account_id`/`account_name` — the same
868
+ two `ArgGroup`s `ExportArgs` carries. A bare `--auth-bearer` resolves
869
+ `$VANDELAY_TOKEN` on both sides, exactly as it already does for
870
+ `mailCopyPlan`.
871
+
872
+ **Backup and restore take independent account lists, unlike `mailCopyPlan`'s
873
+ single bundled plan.** A migration's target account is known at plan time;
874
+ a backup's eventual restore target is not — it may be a different instance
875
+ that does not exist yet, resolved only once a restore actually runs. The one
876
+ thing the two plans share is each account's `address`, which is what the
877
+ archive filename is derived from: the file a backup writes is the file its
878
+ later restore reads.
879
+
880
+ **Domain-level settings are not part of this plan.** An org's `Domain` and
881
+ relay are already fully reconstructed by calling `applyOrgMail`/`applyOrgRelay`
882
+ again with the org's own declared config — a restore's first step, and
883
+ nothing new to export.
884
+
885
+ **`accountsOnDomain` scopes by `Domain`, the same exact lookup
886
+ `applyOrgMail` uses**, and returns an empty list rather than refusing for a
887
+ domain this instance has never heard of — the same "no-op, not a refusal"
888
+ `parkOrgMail` already gives that case.
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Reading the `Authentication-Results` header (RFC 8601) Stalwart stamps on
3
+ * inbound mail it accepts, reduced to the one question `senderAuthenticated`
4
+ * answers: did this message's `From` domain pass DKIM alignment, or did the
5
+ * message pass DMARC.
6
+ *
7
+ * **What is confirmed, and how.** Stalwart's inbound `DATA` handling builds
8
+ * one `AuthenticationResults` value per message from its DKIM/DKIM2, SPF
9
+ * (HELO and MAIL FROM), IPREV and DMARC checks and writes it as a single
10
+ * `Authentication-Results` header (`crates/smtp/src/inbound/data.rs`,
11
+ * `stalwartlabs/stalwart`, functions building `auth_results` then calling
12
+ * `auth_results.write_header(&mut headers)`), gated on a config toggle
13
+ * (`dc.add_auth_results`) that a caller has not confirmed is enabled on any
14
+ * particular deployment. The wire format of each `resinfo` segment — `;`,
15
+ * then (on a fold) CRLF + tab, then `dkim=<result> header.d=<domain>
16
+ * header.s=<selector> header.i=<identity> header.b=<snippet>`, `spf=<result>
17
+ * smtp.helo=<domain>` / `smtp.mailfrom=<address>`, or `dmarc=<result>
18
+ * header.from=<domain> policy.dmarc=<policy>` — is
19
+ * `stalwartlabs/mail-auth`'s `AuthenticationResults`
20
+ * `HeaderWriter`/`with_dkim_results`/`with_spf_*_result`/`with_dmarc_result`
21
+ * (`src/auth_results.rs`), which Stalwart depends on for exactly this. RFC
22
+ * 8621 §4.1.3's `header:<Name>:asRaw:all` pseudo-property, which fetches
23
+ * every instance of a header field as its raw text, is confirmed as a
24
+ * genuine `EmailProperty::Header` case Stalwart resolves generically
25
+ * (`crates/jmap/src/email/get.rs`), not a hand-picked list of known headers.
26
+ *
27
+ * **What is not confirmed.** No live Stalwart deployment's `hostname`
28
+ * (RFC 8601's `authserv-id`, the first token of the header) was read to write
29
+ * this. RFC 8601 §5 warns that anything upstream of the trust boundary can
30
+ * plant its own `Authentication-Results` header, and the hostname is public,
31
+ * so a matching `authserv-id` alone proves nothing. What does hold: Stalwart
32
+ * prepends its own header (`add_auth_results`, on by default) and never
33
+ * strips incoming ones, so its instance is always the topmost.
34
+ * `senderAuthenticatedFrom` therefore fails closed and reads only the first
35
+ * instance: false with no `trustedAuthServId`, false if the first instance's
36
+ * `authserv-id` differs (case-insensitively), and it never looks further
37
+ * down. Setting `trustedAuthServId` asserts that the receiving server
38
+ * prepends its own header on every inbound message; if it does not, leave
39
+ * the option unset.
40
+ */
41
+ /** One `method=result` segment of a parsed `Authentication-Results` header,
42
+ * with its `ptype.property=value` pairs — RFC 8601 §2.2's `resinfo`. */
43
+ export type AuthResultSegment = {
44
+ method: string;
45
+ result: string;
46
+ properties: Readonly<Record<string, string>>;
47
+ };
48
+ export type ParsedAuthenticationResults = {
49
+ authServId: string;
50
+ results: readonly AuthResultSegment[];
51
+ };
52
+ /**
53
+ * One `Authentication-Results` header's raw text, folded or not, into its
54
+ * `authserv-id` and `resinfo` segments. `null` for text with no `authserv-id`
55
+ * (an empty or malformed header) — this never throws, since it reads a
56
+ * header nobody here wrote.
57
+ */
58
+ export declare function parseAuthenticationResults(raw: string): ParsedAuthenticationResults | null;
59
+ /** The domain of a mailbox address, lower-cased — everything after the last
60
+ * `@`, which is right even for a local part that itself contains one
61
+ * (a quoted local part can). Empty for an address with none. */
62
+ export declare function domainOf(email: string): string;
63
+ /**
64
+ * Did `fromEmail`'s domain pass DKIM alignment, or did the message pass
65
+ * DMARC — per the trust caveat this module's header comment spells out, read
66
+ * only from the first (topmost) `Authentication-Results` instance, and only
67
+ * if its `authserv-id` equals `trustedAuthServId`. Without a `trustedAuthServId` this is always
68
+ * false (fail closed): an unattributed header can be forged by the sender.
69
+ *
70
+ * **DKIM alignment is exact-domain, not relaxed-with-suffix.** RFC 7489's
71
+ * relaxed mode allows a signing domain that is an ancestor of the `From`
72
+ * domain, which needs a public-suffix list to compute correctly (otherwise
73
+ * two unrelated accounts under a shared public suffix such as `github.io`
74
+ * would read as aligned). This package carries no such list, so alignment
75
+ * here is exact match only — strict mode, one of RFC 7489's two defined
76
+ * modes, not an invention. A message DMARC itself judged aligned but that
77
+ * this exact check misses still passes, since the `dmarc=pass` branch below
78
+ * catches it independently.
79
+ */
80
+ export declare function senderAuthenticatedFrom(headers: readonly string[] | undefined, fromEmail: string | undefined, trustedAuthServId?: string): boolean;
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Reading the `Authentication-Results` header (RFC 8601) Stalwart stamps on
3
+ * inbound mail it accepts, reduced to the one question `senderAuthenticated`
4
+ * answers: did this message's `From` domain pass DKIM alignment, or did the
5
+ * message pass DMARC.
6
+ *
7
+ * **What is confirmed, and how.** Stalwart's inbound `DATA` handling builds
8
+ * one `AuthenticationResults` value per message from its DKIM/DKIM2, SPF
9
+ * (HELO and MAIL FROM), IPREV and DMARC checks and writes it as a single
10
+ * `Authentication-Results` header (`crates/smtp/src/inbound/data.rs`,
11
+ * `stalwartlabs/stalwart`, functions building `auth_results` then calling
12
+ * `auth_results.write_header(&mut headers)`), gated on a config toggle
13
+ * (`dc.add_auth_results`) that a caller has not confirmed is enabled on any
14
+ * particular deployment. The wire format of each `resinfo` segment — `;`,
15
+ * then (on a fold) CRLF + tab, then `dkim=<result> header.d=<domain>
16
+ * header.s=<selector> header.i=<identity> header.b=<snippet>`, `spf=<result>
17
+ * smtp.helo=<domain>` / `smtp.mailfrom=<address>`, or `dmarc=<result>
18
+ * header.from=<domain> policy.dmarc=<policy>` — is
19
+ * `stalwartlabs/mail-auth`'s `AuthenticationResults`
20
+ * `HeaderWriter`/`with_dkim_results`/`with_spf_*_result`/`with_dmarc_result`
21
+ * (`src/auth_results.rs`), which Stalwart depends on for exactly this. RFC
22
+ * 8621 §4.1.3's `header:<Name>:asRaw:all` pseudo-property, which fetches
23
+ * every instance of a header field as its raw text, is confirmed as a
24
+ * genuine `EmailProperty::Header` case Stalwart resolves generically
25
+ * (`crates/jmap/src/email/get.rs`), not a hand-picked list of known headers.
26
+ *
27
+ * **What is not confirmed.** No live Stalwart deployment's `hostname`
28
+ * (RFC 8601's `authserv-id`, the first token of the header) was read to write
29
+ * this. RFC 8601 §5 warns that anything upstream of the trust boundary can
30
+ * plant its own `Authentication-Results` header, and the hostname is public,
31
+ * so a matching `authserv-id` alone proves nothing. What does hold: Stalwart
32
+ * prepends its own header (`add_auth_results`, on by default) and never
33
+ * strips incoming ones, so its instance is always the topmost.
34
+ * `senderAuthenticatedFrom` therefore fails closed and reads only the first
35
+ * instance: false with no `trustedAuthServId`, false if the first instance's
36
+ * `authserv-id` differs (case-insensitively), and it never looks further
37
+ * down. Setting `trustedAuthServId` asserts that the receiving server
38
+ * prepends its own header on every inbound message; if it does not, leave
39
+ * the option unset.
40
+ */
41
+ /** Splits `text` on `sep` outside of a double-quoted run, honouring `\"` and
42
+ * `\\` as RFC 8601's `quoted-string` (borrowed from RFC 5322) escapes. */
43
+ function splitUnquoted(text, sep) {
44
+ const parts = [];
45
+ let current = '';
46
+ let inQuotes = false;
47
+ for (let i = 0; i < text.length; i++) {
48
+ const char = text[i];
49
+ if (char === '\\' && inQuotes && i + 1 < text.length) {
50
+ current += char + text[i + 1];
51
+ i++;
52
+ continue;
53
+ }
54
+ if (char === '"') {
55
+ inQuotes = !inQuotes;
56
+ current += char;
57
+ continue;
58
+ }
59
+ if (!inQuotes && char === sep) {
60
+ parts.push(current);
61
+ current = '';
62
+ continue;
63
+ }
64
+ current += char;
65
+ }
66
+ parts.push(current);
67
+ return parts;
68
+ }
69
+ /** Strips a `pvalue`'s surrounding quotes and un-escapes `\"`/`\\`, if it was
70
+ * quoted at all — `push_quoted_pvalue` only quotes a value that needs it. */
71
+ function unquote(value) {
72
+ const trimmed = value.trim();
73
+ if (trimmed.length < 2 || !trimmed.startsWith('"') || !trimmed.endsWith('"'))
74
+ return trimmed;
75
+ return trimmed.slice(1, -1).replace(/\\(.)/g, '$1');
76
+ }
77
+ /**
78
+ * One `Authentication-Results` header's raw text, folded or not, into its
79
+ * `authserv-id` and `resinfo` segments. `null` for text with no `authserv-id`
80
+ * (an empty or malformed header) — this never throws, since it reads a
81
+ * header nobody here wrote.
82
+ */
83
+ export function parseAuthenticationResults(raw) {
84
+ // RFC 5322 folding inserts CRLF before whitespace; a run of any whitespace
85
+ // reads the same as the single space it folds from.
86
+ const normalized = raw.replace(/\s+/g, ' ').trim();
87
+ if (!normalized)
88
+ return null;
89
+ const segments = splitUnquoted(normalized, ';').map((segment) => segment.trim());
90
+ const authServId = segments[0];
91
+ if (!authServId)
92
+ return null;
93
+ const results = [];
94
+ for (const segment of segments.slice(1)) {
95
+ if (!segment || segment.toLowerCase() === 'none')
96
+ continue;
97
+ const tokens = splitUnquoted(segment, ' ').filter((token) => token.length > 0);
98
+ const head = tokens[0];
99
+ if (!head)
100
+ continue;
101
+ const eq = head.indexOf('=');
102
+ if (eq < 0)
103
+ continue;
104
+ const method = head.slice(0, eq).trim().toLowerCase();
105
+ const result = head
106
+ .slice(eq + 1)
107
+ .trim()
108
+ .toLowerCase();
109
+ if (!method || !result)
110
+ continue;
111
+ const properties = {};
112
+ for (const token of tokens.slice(1)) {
113
+ const propEq = token.indexOf('=');
114
+ if (propEq < 0)
115
+ continue;
116
+ const key = token.slice(0, propEq).trim().toLowerCase();
117
+ const value = unquote(token.slice(propEq + 1));
118
+ if (key)
119
+ properties[key] = value;
120
+ }
121
+ results.push({ method, result, properties });
122
+ }
123
+ return { authServId, results };
124
+ }
125
+ /** The domain of a mailbox address, lower-cased — everything after the last
126
+ * `@`, which is right even for a local part that itself contains one
127
+ * (a quoted local part can). Empty for an address with none. */
128
+ export function domainOf(email) {
129
+ const at = email.lastIndexOf('@');
130
+ return at < 0 ? '' : email.slice(at + 1).toLowerCase();
131
+ }
132
+ /**
133
+ * Did `fromEmail`'s domain pass DKIM alignment, or did the message pass
134
+ * DMARC — per the trust caveat this module's header comment spells out, read
135
+ * only from the first (topmost) `Authentication-Results` instance, and only
136
+ * if its `authserv-id` equals `trustedAuthServId`. Without a `trustedAuthServId` this is always
137
+ * false (fail closed): an unattributed header can be forged by the sender.
138
+ *
139
+ * **DKIM alignment is exact-domain, not relaxed-with-suffix.** RFC 7489's
140
+ * relaxed mode allows a signing domain that is an ancestor of the `From`
141
+ * domain, which needs a public-suffix list to compute correctly (otherwise
142
+ * two unrelated accounts under a shared public suffix such as `github.io`
143
+ * would read as aligned). This package carries no such list, so alignment
144
+ * here is exact match only — strict mode, one of RFC 7489's two defined
145
+ * modes, not an invention. A message DMARC itself judged aligned but that
146
+ * this exact check misses still passes, since the `dmarc=pass` branch below
147
+ * catches it independently.
148
+ */
149
+ export function senderAuthenticatedFrom(headers, fromEmail, trustedAuthServId) {
150
+ if (!trustedAuthServId || !fromEmail)
151
+ return false;
152
+ const header = headers?.[0];
153
+ if (!header)
154
+ return false;
155
+ const parsed = parseAuthenticationResults(header);
156
+ if (!parsed || parsed.authServId.toLowerCase() !== trustedAuthServId.toLowerCase()) {
157
+ return false;
158
+ }
159
+ const fromDomain = domainOf(fromEmail);
160
+ if (!fromDomain)
161
+ return false;
162
+ for (const segment of parsed.results) {
163
+ if (segment.result !== 'pass')
164
+ continue;
165
+ if (segment.method === 'dmarc') {
166
+ const headerFrom = segment.properties['header.from'];
167
+ if (headerFrom?.toLowerCase() === fromDomain)
168
+ return true;
169
+ continue;
170
+ }
171
+ if (segment.method === 'dkim' || segment.method === 'dkim2') {
172
+ const d = segment.properties['header.d'];
173
+ if (d?.toLowerCase() === fromDomain)
174
+ return true;
175
+ const i = segment.properties['header.i'];
176
+ if (i && domainOf(i) === fromDomain)
177
+ return true;
178
+ }
179
+ }
180
+ return false;
181
+ }
@@ -43,6 +43,32 @@ function sizeOf(body) {
43
43
  return body.size;
44
44
  return body.byteLength;
45
45
  }
46
+ /** Put an absolute URL from the session document onto `origin`, keeping its
47
+ * path, query and `{template}` parts byte for byte. A relative URL, or one
48
+ * already on `origin`, is returned as it came. */
49
+ function onOrigin(url, origin) {
50
+ const authority = /^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i.exec(url)?.[0];
51
+ return authority && authority !== origin ? origin + url.slice(authority.length) : url;
52
+ }
53
+ /** A server behind a proxy writes its own host into the session document.
54
+ * A browser that follows those URLs leaves the origin it fetched the session
55
+ * from, so every URL is moved back onto that origin. */
56
+ function keepOnOrigin(doc, sessionUrl) {
57
+ let origin;
58
+ try {
59
+ origin = new URL(sessionUrl).origin;
60
+ }
61
+ catch {
62
+ return doc;
63
+ }
64
+ return {
65
+ ...doc,
66
+ apiUrl: onOrigin(doc.apiUrl, origin),
67
+ downloadUrl: onOrigin(doc.downloadUrl, origin),
68
+ uploadUrl: onOrigin(doc.uploadUrl, origin),
69
+ eventSourceUrl: onOrigin(doc.eventSourceUrl, origin),
70
+ };
71
+ }
46
72
  function looksLikeSession(value) {
47
73
  return (typeof value === 'object' &&
48
74
  value !== null &&
@@ -190,7 +216,7 @@ export class MailClient {
190
216
  if (!looksLikeSession(parsed)) {
191
217
  throw new MailError(`${this.#sessionUrl} did not answer with a JMAP session document (${response.status}): ${body.slice(0, 200)}`, { status: response.status, operation: 'client.connect' });
192
218
  }
193
- return parsed;
219
+ return keepOnOrigin(parsed, this.#sessionUrl);
194
220
  }
195
221
  /** The signed-in person and the account being read. */
196
222
  async session() {
@@ -15,7 +15,7 @@ export type { ListOptions } from './threads.ts';
15
15
  export { CANNOT_CALCULATE_CHANGES, emailChanges, emailHeaders, isCannotCalculateChanges, mailboxChanges, } from './changes.ts';
16
16
  export type { Changes, ChangesOptions, EmailHeaders, EmailHeadersPage } from './changes.ts';
17
17
  export { DEFAULT_MAX_BODY_BYTES, thread, toMessage } from './thread.ts';
18
- export type { RawMessage, ThreadOptions } from './thread.ts';
18
+ export type { RawMessage, ThreadOptions, ToMessageOptions } from './thread.ts';
19
19
  export { search } from './search.ts';
20
20
  export type { SearchOptions } from './search.ts';
21
21
  export { identities } from './identities.ts';
@@ -40,22 +40,32 @@ export type RawMessage = {
40
40
  htmlBody?: BodyPart[];
41
41
  attachments?: BodyPart[];
42
42
  bodyValues?: Record<string, BodyValue>;
43
+ 'header:Authentication-Results:asRaw:all'?: (string | null)[];
43
44
  };
44
45
  /** How many bytes of each body part to fetch. A message with a megabyte of
45
46
  * quoted history should not stall a thread view; anything cut short is
46
47
  * reported as `isTruncated`. */
47
48
  export declare const DEFAULT_MAX_BODY_BYTES: number;
49
+ export type ToMessageOptions = {
50
+ /** The `authserv-id` (Stalwart's `hostname`) the topmost
51
+ * `Authentication-Results` instance must carry for `senderAuthenticated`
52
+ * to read it, compared case-insensitively. Setting it asserts the receiving
53
+ * server prepends its own header on every inbound message (Stalwart's
54
+ * `add_auth_results`, on by default); if it does not, leave this unset.
55
+ * Unset means `senderAuthenticated` is always false. */
56
+ trustedAuthServId?: string;
57
+ };
48
58
  /** Turn one `Email/get` result into a `Message`, resolving its bodies and
49
59
  * giving every attachment a download URL. */
50
60
  export declare function toMessage(raw: RawMessage, downloadUrlFor: (blob: {
51
61
  blobId: string;
52
62
  name: string;
53
63
  type: string;
54
- }) => string): Message;
64
+ }) => string, options?: ToMessageOptions): Message;
55
65
  export type ThreadOptions = {
56
66
  /** Bytes of each body part to fetch. */
57
67
  maxBodyBytes?: number;
58
- };
68
+ } & ToMessageOptions;
59
69
  /** One thread, with every message's body and attachments, oldest first. */
60
70
  export declare function thread(client: MailClient, threadId: string, options?: ThreadOptions): Promise<ThreadDetail>;
61
71
  export {};
@@ -1,3 +1,4 @@
1
+ import { senderAuthenticatedFrom } from "./auth-results.js";
1
2
  import { JAM_FETCH } from "./client.js";
2
3
  import { MailError, guard } from "./errors.js";
3
4
  import { expandTemplate } from "./uri.js";
@@ -25,6 +26,9 @@ const MESSAGE_PROPERTIES = [
25
26
  'htmlBody',
26
27
  'attachments',
27
28
  'bodyValues',
29
+ // RFC 8621 §4.1.3: every instance of the header, raw. See
30
+ // `auth-results.ts`'s module doc for the header this reads.
31
+ 'header:Authentication-Results:asRaw:all',
28
32
  ];
29
33
  const BODY_PROPERTIES = [
30
34
  'partId',
@@ -74,10 +78,11 @@ function joinParts(parts, values, type) {
74
78
  }
75
79
  /** Turn one `Email/get` result into a `Message`, resolving its bodies and
76
80
  * giving every attachment a download URL. */
77
- export function toMessage(raw, downloadUrlFor) {
81
+ export function toMessage(raw, downloadUrlFor, options = {}) {
78
82
  const text = joinParts(raw.textBody, raw.bodyValues, 'text/plain');
79
83
  const html = joinParts(raw.htmlBody, raw.bodyValues, 'text/html');
80
84
  const keywords = raw.keywords ?? {};
85
+ const authResultsHeaders = (raw['header:Authentication-Results:asRaw:all'] ?? []).filter((header) => typeof header === 'string' && header.length > 0);
81
86
  const attachments = (raw.attachments ?? [])
82
87
  // A part with no blob cannot be fetched, so it is not an attachment a
83
88
  // reader can do anything with.
@@ -121,6 +126,7 @@ export function toMessage(raw, downloadUrlFor) {
121
126
  isUnread: keywords.$seen !== true,
122
127
  isFlagged: keywords.$flagged === true,
123
128
  isDraft: keywords.$draft === true,
129
+ senderAuthenticated: senderAuthenticatedFrom(authResultsHeaders, raw.from?.[0]?.email, options.trustedAuthServId),
124
130
  };
125
131
  }
126
132
  /** One thread, with every message's body and attachments, oldest first. */
@@ -155,7 +161,7 @@ export async function thread(client, threadId, options = {}) {
155
161
  blobId: blob.blobId,
156
162
  name: blob.name,
157
163
  type: blob.type,
158
- })))
164
+ }), { trustedAuthServId: options.trustedAuthServId }))
159
165
  // A thread reads oldest first, whatever order the server listed it in.
160
166
  .sort((a, b) => (a.receivedAt < b.receivedAt ? -1 : a.receivedAt > b.receivedAt ? 1 : 0));
161
167
  return {
@@ -181,6 +181,16 @@ export type Message = {
181
181
  isUnread: boolean;
182
182
  isFlagged: boolean;
183
183
  isDraft: boolean;
184
+ /** Did `from[0]`'s domain pass DKIM alignment, or did the message pass
185
+ * DMARC, per the `Authentication-Results` header Stalwart stamps on
186
+ * accepted inbound mail. `false` for a message with no such header (a
187
+ * sent message, one from before this deployment enabled it, or a
188
+ * deployment with it off), one whose checks failed outright, and a
189
+ * forwarded message whose own alignment rarely survives a second hop —
190
+ * `false` never distinguishes those from each other. See
191
+ * `mailbox/auth-results.ts`'s module doc for what is and is not confirmed
192
+ * about this header on a real deployment. */
193
+ senderAuthenticated: boolean;
184
194
  };
185
195
  /** A thread, opened. */
186
196
  export type ThreadDetail = {
@@ -26,3 +26,4 @@ export { loadQueue, queueMessageView, type QueueMessage, type QueueRecipient, ty
26
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';
29
+ export { OrgMailExportRefused, accountsOnDomain, orgMailBackupPlan, orgMailRestorePlan, type OrgMailBackupAccountPlan, type OrgMailBackupOptions, type OrgMailBackupPlan, type OrgMailExportAccount, type OrgMailExportEnv, type OrgMailRestoreAccount, type OrgMailRestoreAccountPlan, type OrgMailRestoreOptions, type OrgMailRestorePlan, } from './org-mail-export.js';
@@ -26,3 +26,4 @@ export { loadQueue, queueMessageView, } from './queue.js';
26
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';
29
+ export { OrgMailExportRefused, accountsOnDomain, orgMailBackupPlan, orgMailRestorePlan, } from './org-mail-export.js';
@@ -0,0 +1,180 @@
1
+ import type { StalwartClient } from './client.js';
2
+ /**
3
+ * A point-in-time backup of one org's mail on the shared Stalwart instance,
4
+ * and the plan to restore it into a — possibly different — shared instance
5
+ * later (`wtfalch/email#139`, for `archon#132`'s whole-company backup).
6
+ *
7
+ * **Why this exists.** Every org's mail lives in the one shared Stalwart
8
+ * server, scoped only by `Domain` (`./org-mail.ts`'s own header comment:
9
+ * "never a second Stalwart, never a per-org instance"). So there is no
10
+ * per-org database or container for a company-wide backup to snapshot the
11
+ * way it can a company's own Boule/Agora Postgres — an org's mail has to be
12
+ * pulled out of the shared instance's own store, by domain, instead.
13
+ *
14
+ * **Vandelay again, not a hand-rolled JMAP walk.** `./mail-copy.ts` already
15
+ * chose `stalwartlabs/vandelay` for moving mail in and out of Stalwart over
16
+ * writing a copier here, and the same reasons apply: it already speaks JMAP
17
+ * on both sides, matches blobs by hash so a rerun never duplicates mail, and
18
+ * `export` is upsert-only so a restore never deletes anything already on
19
+ * the target. This module is almost `mail-copy.ts`'s mirror image — the
20
+ * *source* is this org's own account on the shared instance rather than
21
+ * Google or Microsoft — so it uses Vandelay's `import jmap`, not
22
+ * `import imap`, confirmed against `stalwartlabs/vandelay` at commit
23
+ * `486a3847121732fc46c2433de0e0ed50bbcb5825` (`main`, 2026-10-04):
24
+ * `Source::Jmap(Box<JmapImportArgs>)`, `src/cli.rs:58`, and `JmapImportArgs`
25
+ * at `src/cli.rs:131-174`, whose `#[command(group(...))]` attributes require
26
+ * exactly one of `auth_basic`/`auth_bearer` and exactly one of
27
+ * `account_id`/`account_name` — the same two `ArgGroup`s `ExportArgs`
28
+ * carries (`src/cli.rs:300-313`, the struct `mail-copy.ts` already cites at
29
+ * `src/cli.rs:300-301` from an earlier commit). `resolve_jmap_import`
30
+ * (`src/cli.rs:747-765`) resolves `--auth-bearer`'s bare value the same way
31
+ * `resolve_export`'s does — `secret::resolve(bearer, "VANDELAY_TOKEN", ...)`
32
+ * — so a bare `--auth-bearer` here reads `$VANDELAY_TOKEN` exactly as it
33
+ * does in `mail-copy.ts`.
34
+ *
35
+ * **Backup is `import jmap`, restore is `export` — and they are two
36
+ * separate, independently-callable plans, not one bundled pair the way
37
+ * `mailCopyPlan` returns import+export together.** `mailCopyPlan`'s
38
+ * target is known at plan time (the Stalwart account a migration lands
39
+ * on, chosen once). A backup's eventual restore target is not: the issue
40
+ * asks for a snapshot that can be "restored back into a *possibly
41
+ * different* shared Stalwart instance", and which instance that is, and
42
+ * which account id each address resolves to there, is only known at
43
+ * restore time — often long after the backup ran, against an instance that
44
+ * may not even exist yet. So `orgMailBackupPlan` and `orgMailRestorePlan`
45
+ * take their own, independent account lists: backup keys off the *source*
46
+ * instance's account ids (`OrgMailBackupAccount.accountId`, from
47
+ * `accountsOnDomain` below), restore off the *target* instance's
48
+ * (`OrgMailRestoreAccount.targetAccountId`, resolved separately once a
49
+ * target exists — e.g. by re-provisioning the org there and calling
50
+ * `accountsOnDomain` again). The one thing the two plans must agree on is
51
+ * each account's `address`, which is what `archiveFileName` derives the
52
+ * shared archive path from — the file a backup writes is exactly the file
53
+ * its later restore reads.
54
+ *
55
+ * **Domain-level settings are not part of this plan.** The issue also asks
56
+ * to capture "any per-domain settings this package provisions via
57
+ * `mailObjects`/`org-mail.ts`" — but those settings are exactly what
58
+ * `applyOrgMail`/`applyOrgRelay` already reconstruct from an org's own
59
+ * declared config (`slug`, `domain`, `mode`, the Lettermint secret), the
60
+ * same way any other apply of that config does. A restore's first step is
61
+ * calling `applyOrgMail` (and `applyOrgRelay`, if the org has one) against
62
+ * the target instance with that same declared config — nothing new to
63
+ * export for that half, and nothing this module should duplicate.
64
+ *
65
+ * **No secret ever lands in argv**, and a rerun is safe — both for the same
66
+ * reasons `mail-copy.ts`'s header gives at length: every `--auth-bearer` is
67
+ * passed bare, `import jmap` is convergent (matches by hash, picks up where
68
+ * an interrupted run left off), and `export` is upsert-only with `--prune`
69
+ * never set here, so a restore can never delete anything already on the
70
+ * target.
71
+ */
72
+ export declare class OrgMailExportRefused extends Error {
73
+ }
74
+ export interface OrgMailExportAccount {
75
+ readonly accountId: string;
76
+ readonly address: string;
77
+ }
78
+ /**
79
+ * Every account on one org's domain, on the instance `client` talks to —
80
+ * the accounts a backup or a restore of that org must plan, one per entry.
81
+ *
82
+ * Scopes by `Domain`, the only boundary an org's mail has on the shared
83
+ * instance (see this file's header). Resolves the domain the same exact,
84
+ * server-side-filtered way `applyOrgMail`/`parkOrgMail` do
85
+ * (`findDomain`, from `./org-mail.ts`) — never by listing every `Domain` and
86
+ * scanning for a name match. The accounts themselves are still read with
87
+ * `client.list('Account')` and filtered here on `domainId`, the same
88
+ * client-side filter `overview()`/`loadOverview` already use (`./overview.ts`,
89
+ * `./load.ts`) — not a new, unconfirmed server-side `Account` filter —
90
+ * carrying the same known limit as those: `x:Account/query` with no filter
91
+ * is capped at `query_max_results` (5000 by default) and never paged past,
92
+ * so an instance with more accounts than that can miss some. That is an
93
+ * existing limitation of this package's account listing, not one this
94
+ * function introduces.
95
+ *
96
+ * A domain this instance has never heard of returns an empty list rather
97
+ * than refusing — the same "no-op, not a refusal" the org-mail.ts header
98
+ * gives `parkOrgMail` for exactly this case, since an org that was never
99
+ * provisioned here (or was provisioned on a different shared instance) has
100
+ * nothing of its own on this one to back up.
101
+ */
102
+ export declare function accountsOnDomain(client: StalwartClient, domain: string): Promise<readonly OrgMailExportAccount[]>;
103
+ /** An environment variable one Vandelay invocation needs — never its
104
+ * value. The caller sets it for that one subprocess launch. */
105
+ export interface OrgMailExportEnv {
106
+ readonly name: string;
107
+ readonly purpose: string;
108
+ }
109
+ export interface OrgMailBackupOptions {
110
+ readonly accounts: readonly OrgMailExportAccount[];
111
+ /** The shared Stalwart instance being backed up, e.g. `https://mail.wtfalch.dev`. */
112
+ readonly stalwartUrl: string;
113
+ /** Directory to hold one Vandelay SQLite archive per account. */
114
+ readonly archiveDir: string;
115
+ }
116
+ export interface OrgMailBackupAccountPlan {
117
+ readonly address: string;
118
+ /** The local SQLite archive this account's backup writes, and its later
119
+ * restore reads back. */
120
+ readonly archive: string;
121
+ readonly argv: readonly string[];
122
+ readonly env: readonly OrgMailExportEnv[];
123
+ }
124
+ export interface OrgMailBackupPlan {
125
+ readonly accounts: readonly OrgMailBackupAccountPlan[];
126
+ }
127
+ /**
128
+ * The Vandelay `import jmap` command for every account passed in, reading
129
+ * each one's mail off the shared instance named by `stalwartUrl` into its
130
+ * own local archive. Pure and idempotent — the same input returns the same
131
+ * plan, and running the returned commands twice against the same archive
132
+ * and account is exactly the rerun Vandelay's import is built to support
133
+ * (see this file's header).
134
+ *
135
+ * Refuses before building anything, the same way `mailCopyPlan` does: a
136
+ * `stalwartUrl` that is not https or that carries embedded userinfo, an
137
+ * empty `archiveDir`, no accounts, an account whose `address` is not
138
+ * email-shaped or whose `accountId` is empty, or two accounts that would
139
+ * land on the same archive file.
140
+ */
141
+ export declare function orgMailBackupPlan(input: OrgMailBackupOptions): OrgMailBackupPlan;
142
+ export interface OrgMailRestoreAccount {
143
+ readonly address: string;
144
+ /** The account this address resolved to on the *target* instance —
145
+ * almost always a different id than the same address had on the
146
+ * instance that was backed up. */
147
+ readonly targetAccountId: string;
148
+ }
149
+ export interface OrgMailRestoreOptions {
150
+ readonly accounts: readonly OrgMailRestoreAccount[];
151
+ /** The — possibly different — shared Stalwart instance being restored
152
+ * into, e.g. `https://mail.wtfalch.dev`. */
153
+ readonly stalwartUrl: string;
154
+ /** The same directory `orgMailBackupPlan` wrote into: restore reads the
155
+ * archive a backup already produced, it never creates one. */
156
+ readonly archiveDir: string;
157
+ }
158
+ export interface OrgMailRestoreAccountPlan {
159
+ readonly address: string;
160
+ readonly archive: string;
161
+ readonly argv: readonly string[];
162
+ readonly env: readonly OrgMailExportEnv[];
163
+ }
164
+ export interface OrgMailRestorePlan {
165
+ readonly accounts: readonly OrgMailRestoreAccountPlan[];
166
+ }
167
+ /**
168
+ * The Vandelay `export` command for every account passed in, pushing each
169
+ * one's already-backed-up archive into its account on the target instance
170
+ * named by `stalwartUrl`. Pure and idempotent, for the same reason
171
+ * `orgMailBackupPlan` is: `export` is upsert-only and this never sets
172
+ * `--prune`, so a rerun — or a restore onto an instance that already has
173
+ * some of this mail — never duplicates or deletes anything.
174
+ *
175
+ * Refuses on the same shape mistakes `orgMailBackupPlan` does: a bad
176
+ * `stalwartUrl`, an empty `archiveDir`, no accounts, an account whose
177
+ * `address` is not email-shaped or whose `targetAccountId` is empty, or two
178
+ * accounts that would read the same archive file.
179
+ */
180
+ export declare function orgMailRestorePlan(input: OrgMailRestoreOptions): OrgMailRestorePlan;
@@ -0,0 +1,258 @@
1
+ import { findDomain } from './org-mail.js';
2
+ /**
3
+ * A point-in-time backup of one org's mail on the shared Stalwart instance,
4
+ * and the plan to restore it into a — possibly different — shared instance
5
+ * later (`wtfalch/email#139`, for `archon#132`'s whole-company backup).
6
+ *
7
+ * **Why this exists.** Every org's mail lives in the one shared Stalwart
8
+ * server, scoped only by `Domain` (`./org-mail.ts`'s own header comment:
9
+ * "never a second Stalwart, never a per-org instance"). So there is no
10
+ * per-org database or container for a company-wide backup to snapshot the
11
+ * way it can a company's own Boule/Agora Postgres — an org's mail has to be
12
+ * pulled out of the shared instance's own store, by domain, instead.
13
+ *
14
+ * **Vandelay again, not a hand-rolled JMAP walk.** `./mail-copy.ts` already
15
+ * chose `stalwartlabs/vandelay` for moving mail in and out of Stalwart over
16
+ * writing a copier here, and the same reasons apply: it already speaks JMAP
17
+ * on both sides, matches blobs by hash so a rerun never duplicates mail, and
18
+ * `export` is upsert-only so a restore never deletes anything already on
19
+ * the target. This module is almost `mail-copy.ts`'s mirror image — the
20
+ * *source* is this org's own account on the shared instance rather than
21
+ * Google or Microsoft — so it uses Vandelay's `import jmap`, not
22
+ * `import imap`, confirmed against `stalwartlabs/vandelay` at commit
23
+ * `486a3847121732fc46c2433de0e0ed50bbcb5825` (`main`, 2026-10-04):
24
+ * `Source::Jmap(Box<JmapImportArgs>)`, `src/cli.rs:58`, and `JmapImportArgs`
25
+ * at `src/cli.rs:131-174`, whose `#[command(group(...))]` attributes require
26
+ * exactly one of `auth_basic`/`auth_bearer` and exactly one of
27
+ * `account_id`/`account_name` — the same two `ArgGroup`s `ExportArgs`
28
+ * carries (`src/cli.rs:300-313`, the struct `mail-copy.ts` already cites at
29
+ * `src/cli.rs:300-301` from an earlier commit). `resolve_jmap_import`
30
+ * (`src/cli.rs:747-765`) resolves `--auth-bearer`'s bare value the same way
31
+ * `resolve_export`'s does — `secret::resolve(bearer, "VANDELAY_TOKEN", ...)`
32
+ * — so a bare `--auth-bearer` here reads `$VANDELAY_TOKEN` exactly as it
33
+ * does in `mail-copy.ts`.
34
+ *
35
+ * **Backup is `import jmap`, restore is `export` — and they are two
36
+ * separate, independently-callable plans, not one bundled pair the way
37
+ * `mailCopyPlan` returns import+export together.** `mailCopyPlan`'s
38
+ * target is known at plan time (the Stalwart account a migration lands
39
+ * on, chosen once). A backup's eventual restore target is not: the issue
40
+ * asks for a snapshot that can be "restored back into a *possibly
41
+ * different* shared Stalwart instance", and which instance that is, and
42
+ * which account id each address resolves to there, is only known at
43
+ * restore time — often long after the backup ran, against an instance that
44
+ * may not even exist yet. So `orgMailBackupPlan` and `orgMailRestorePlan`
45
+ * take their own, independent account lists: backup keys off the *source*
46
+ * instance's account ids (`OrgMailBackupAccount.accountId`, from
47
+ * `accountsOnDomain` below), restore off the *target* instance's
48
+ * (`OrgMailRestoreAccount.targetAccountId`, resolved separately once a
49
+ * target exists — e.g. by re-provisioning the org there and calling
50
+ * `accountsOnDomain` again). The one thing the two plans must agree on is
51
+ * each account's `address`, which is what `archiveFileName` derives the
52
+ * shared archive path from — the file a backup writes is exactly the file
53
+ * its later restore reads.
54
+ *
55
+ * **Domain-level settings are not part of this plan.** The issue also asks
56
+ * to capture "any per-domain settings this package provisions via
57
+ * `mailObjects`/`org-mail.ts`" — but those settings are exactly what
58
+ * `applyOrgMail`/`applyOrgRelay` already reconstruct from an org's own
59
+ * declared config (`slug`, `domain`, `mode`, the Lettermint secret), the
60
+ * same way any other apply of that config does. A restore's first step is
61
+ * calling `applyOrgMail` (and `applyOrgRelay`, if the org has one) against
62
+ * the target instance with that same declared config — nothing new to
63
+ * export for that half, and nothing this module should duplicate.
64
+ *
65
+ * **No secret ever lands in argv**, and a rerun is safe — both for the same
66
+ * reasons `mail-copy.ts`'s header gives at length: every `--auth-bearer` is
67
+ * passed bare, `import jmap` is convergent (matches by hash, picks up where
68
+ * an interrupted run left off), and `export` is upsert-only with `--prune`
69
+ * never set here, so a restore can never delete anything already on the
70
+ * target.
71
+ */
72
+ export class OrgMailExportRefused extends Error {
73
+ }
74
+ /**
75
+ * Every account on one org's domain, on the instance `client` talks to —
76
+ * the accounts a backup or a restore of that org must plan, one per entry.
77
+ *
78
+ * Scopes by `Domain`, the only boundary an org's mail has on the shared
79
+ * instance (see this file's header). Resolves the domain the same exact,
80
+ * server-side-filtered way `applyOrgMail`/`parkOrgMail` do
81
+ * (`findDomain`, from `./org-mail.ts`) — never by listing every `Domain` and
82
+ * scanning for a name match. The accounts themselves are still read with
83
+ * `client.list('Account')` and filtered here on `domainId`, the same
84
+ * client-side filter `overview()`/`loadOverview` already use (`./overview.ts`,
85
+ * `./load.ts`) — not a new, unconfirmed server-side `Account` filter —
86
+ * carrying the same known limit as those: `x:Account/query` with no filter
87
+ * is capped at `query_max_results` (5000 by default) and never paged past,
88
+ * so an instance with more accounts than that can miss some. That is an
89
+ * existing limitation of this package's account listing, not one this
90
+ * function introduces.
91
+ *
92
+ * A domain this instance has never heard of returns an empty list rather
93
+ * than refusing — the same "no-op, not a refusal" the org-mail.ts header
94
+ * gives `parkOrgMail` for exactly this case, since an org that was never
95
+ * provisioned here (or was provisioned on a different shared instance) has
96
+ * nothing of its own on this one to back up.
97
+ */
98
+ export async function accountsOnDomain(client, domain) {
99
+ const found = await findDomain(client, domain);
100
+ if (!found)
101
+ return [];
102
+ const accounts = await client.list('Account');
103
+ return accounts
104
+ .filter((a) => a.domainId === found.id)
105
+ .map((a) => ({ accountId: a.id, address: `${a.name}@${domain}` }))
106
+ .sort((a, b) => a.address.localeCompare(b.address));
107
+ }
108
+ /** The env var name every bare `--auth-bearer` resolves (same name
109
+ * `mail-copy.ts` uses, for the same reason: Vandelay has no flag to pick a
110
+ * different one). */
111
+ const VANDELAY_TOKEN = 'VANDELAY_TOKEN';
112
+ /** A very small email shape check, the same one `mail-copy.ts` runs on a
113
+ * source address: exactly one `@`, something on both sides. */
114
+ function assertEmailish(value) {
115
+ const at = value.indexOf('@');
116
+ if (at <= 0 || at === value.length - 1 || value.indexOf('@', at + 1) !== -1) {
117
+ throw new OrgMailExportRefused(`"${value}" does not look like an email address`);
118
+ }
119
+ }
120
+ /** A filesystem-safe archive filename derived only from the account's
121
+ * address, the same `encodeURIComponent` scheme `mail-copy.ts`'s
122
+ * `archiveFileName` uses and for the same reason: two different addresses
123
+ * must never fold onto the same file, or a backup or a restore crosses
124
+ * mail between accounts. This is what ties one account's backup file to
125
+ * its later restore — the same address must produce the same path on
126
+ * both sides. */
127
+ function archiveFileName(address) {
128
+ return `${encodeURIComponent(address.toLowerCase())}.sqlite`;
129
+ }
130
+ /** `https://`, no embedded userinfo — the same checks `mailCopyPlan`
131
+ * applies to `stalwartUrl`, and for the same reason: a bearer credential
132
+ * over `http` is the credential in clear, and `https://user:secret@host/`
133
+ * would put that secret straight into argv. */
134
+ function assertStalwartUrl(value) {
135
+ const url = value.trim().replace(/\/+$/, '');
136
+ if (!/^https:\/\//.test(url)) {
137
+ throw new OrgMailExportRefused(`the Stalwart URL must be https, got "${value}"`);
138
+ }
139
+ let parsed;
140
+ try {
141
+ parsed = new URL(url);
142
+ }
143
+ catch {
144
+ throw new OrgMailExportRefused(`"${value}" is not a valid URL`);
145
+ }
146
+ if (parsed.username || parsed.password) {
147
+ throw new OrgMailExportRefused('the Stalwart URL must not carry embedded credentials; use --auth-bearer instead');
148
+ }
149
+ return url;
150
+ }
151
+ function assertArchiveDir(value) {
152
+ const dir = value.trim().replace(/\/+$/, '');
153
+ if (!dir)
154
+ throw new OrgMailExportRefused('an archive directory is required');
155
+ return dir;
156
+ }
157
+ function assertDistinctArchives(entries) {
158
+ const seen = new Map();
159
+ for (const entry of entries) {
160
+ const collidesWith = seen.get(entry.archive);
161
+ if (collidesWith) {
162
+ throw new OrgMailExportRefused(`${entry.address} and ${collidesWith} would both use the archive "${entry.archive}"; give them distinct addresses or split the plan`);
163
+ }
164
+ seen.set(entry.archive, entry.address);
165
+ }
166
+ }
167
+ /**
168
+ * The Vandelay `import jmap` command for every account passed in, reading
169
+ * each one's mail off the shared instance named by `stalwartUrl` into its
170
+ * own local archive. Pure and idempotent — the same input returns the same
171
+ * plan, and running the returned commands twice against the same archive
172
+ * and account is exactly the rerun Vandelay's import is built to support
173
+ * (see this file's header).
174
+ *
175
+ * Refuses before building anything, the same way `mailCopyPlan` does: a
176
+ * `stalwartUrl` that is not https or that carries embedded userinfo, an
177
+ * empty `archiveDir`, no accounts, an account whose `address` is not
178
+ * email-shaped or whose `accountId` is empty, or two accounts that would
179
+ * land on the same archive file.
180
+ */
181
+ export function orgMailBackupPlan(input) {
182
+ const stalwartUrl = assertStalwartUrl(input.stalwartUrl);
183
+ const archiveDir = assertArchiveDir(input.archiveDir);
184
+ if (input.accounts.length === 0) {
185
+ throw new OrgMailExportRefused('at least one account is required');
186
+ }
187
+ const accounts = input.accounts.map((account) => {
188
+ assertEmailish(account.address);
189
+ if (!account.accountId) {
190
+ throw new OrgMailExportRefused(`${account.address} needs a source Stalwart account id`);
191
+ }
192
+ const archive = `${archiveDir}/${archiveFileName(account.address)}`;
193
+ const argv = [
194
+ 'import',
195
+ 'jmap',
196
+ '--url',
197
+ stalwartUrl,
198
+ '--auth-bearer',
199
+ `--account-id=${account.accountId}`,
200
+ '--',
201
+ archive,
202
+ ];
203
+ const env = [
204
+ {
205
+ name: VANDELAY_TOKEN,
206
+ purpose: `a Stalwart credential able to read ${account.address}'s mail on this instance (e.g. an API key with the impersonate permission, or that account's own credential)`,
207
+ },
208
+ ];
209
+ return { address: account.address, archive, argv, env };
210
+ });
211
+ assertDistinctArchives(accounts);
212
+ return { accounts };
213
+ }
214
+ /**
215
+ * The Vandelay `export` command for every account passed in, pushing each
216
+ * one's already-backed-up archive into its account on the target instance
217
+ * named by `stalwartUrl`. Pure and idempotent, for the same reason
218
+ * `orgMailBackupPlan` is: `export` is upsert-only and this never sets
219
+ * `--prune`, so a rerun — or a restore onto an instance that already has
220
+ * some of this mail — never duplicates or deletes anything.
221
+ *
222
+ * Refuses on the same shape mistakes `orgMailBackupPlan` does: a bad
223
+ * `stalwartUrl`, an empty `archiveDir`, no accounts, an account whose
224
+ * `address` is not email-shaped or whose `targetAccountId` is empty, or two
225
+ * accounts that would read the same archive file.
226
+ */
227
+ export function orgMailRestorePlan(input) {
228
+ const stalwartUrl = assertStalwartUrl(input.stalwartUrl);
229
+ const archiveDir = assertArchiveDir(input.archiveDir);
230
+ if (input.accounts.length === 0) {
231
+ throw new OrgMailExportRefused('at least one account is required');
232
+ }
233
+ const accounts = input.accounts.map((account) => {
234
+ assertEmailish(account.address);
235
+ if (!account.targetAccountId) {
236
+ throw new OrgMailExportRefused(`${account.address} needs a target Stalwart account id`);
237
+ }
238
+ const archive = `${archiveDir}/${archiveFileName(account.address)}`;
239
+ const argv = [
240
+ 'export',
241
+ '--url',
242
+ stalwartUrl,
243
+ '--auth-bearer',
244
+ `--account-id=${account.targetAccountId}`,
245
+ '--',
246
+ archive,
247
+ ];
248
+ const env = [
249
+ {
250
+ name: VANDELAY_TOKEN,
251
+ purpose: `the Stalwart account credential for ${account.address}'s target account on this instance`,
252
+ },
253
+ ];
254
+ return { address: account.address, archive, argv, env };
255
+ });
256
+ assertDistinctArchives(accounts);
257
+ return { accounts };
258
+ }
@@ -95,6 +95,44 @@ export interface OrgMailResult {
95
95
  * reassembles in order.
96
96
  */
97
97
  export declare function dkimRecordsFromZoneFile(zoneFile: string): DnsRecordSpec[];
98
+ export interface WireDomainId {
99
+ id: string;
100
+ name: string;
101
+ isEnabled?: boolean;
102
+ dnsZoneFile?: string;
103
+ }
104
+ /**
105
+ * The org's `Domain`, found by an exact, server-side filter on `name` —
106
+ * never by listing and scanning every `Domain` on the instance.
107
+ *
108
+ * `client.list` (and so `client.upsert`, which is built on it) calls
109
+ * `x:Domain/query` with no filter at all, which Stalwart caps at
110
+ * `query_max_results` (5000 by default) and never pages past
111
+ * (`crates/jmap/src/registry/query.rs:241-250`,
112
+ * `crates/registry/src/schema/structs_impl.rs:23113` for the default, both
113
+ * at `02503015580abd6706923d34e9d8e501e76f8634`). An instance with more
114
+ * `Domain`s than that would put some past the first page, where a lookup
115
+ * built on `list`/`upsert` would miss an existing one and create a second
116
+ * `Domain` with the same name — this is why `applyOrgMail`/`parkOrgMail` use
117
+ * this filtered lookup instead of `client.upsert`.
118
+ *
119
+ * `ObjectType::Domain`'s `name` index is declared `IndexSchemaType::Unique`
120
+ * / `IndexSchemaValueType::Keyword`
121
+ * (`crates/registry/src/schema/properties_impl.rs:3489-3493`), and a
122
+ * `Keyword` index accepts an exact-match filter
123
+ * (`crates/jmap/src/registry/query.rs:190-193`), sent as a flat
124
+ * `filter: {"name": "…"}` object — a bare property name in the filter is
125
+ * `RegistryFilterOperator::Equal` (`crates/jmap-proto/src/object/registry.rs:123-135`),
126
+ * and a single-key filter object needs no `operator`/`conditions` wrapper
127
+ * (`crates/jmap-proto/src/method/query.rs:214-260`). That filter is
128
+ * evaluated server-side and matches at most one `Domain` — `name` is
129
+ * unique — so it is correct regardless of how many Domains the instance
130
+ * holds or which page this one would fall on.
131
+ */
132
+ /** Exported for `./org-mail-export.ts`, which needs the same exact,
133
+ * server-side-filtered lookup to scope a backup to one org's domain
134
+ * without listing and scanning every `Domain` on the shared instance. */
135
+ export declare function findDomain(client: StalwartClient, domain: string): Promise<WireDomainId | undefined>;
98
136
  /**
99
137
  * Give an org mail, change its mode, or re-enable a parked one — all the
100
138
  * same call. Idempotent: the `Domain` is upserted by `name`, so calling this
@@ -149,7 +149,10 @@ function domainValue(domain) {
149
149
  * unique — so it is correct regardless of how many Domains the instance
150
150
  * holds or which page this one would fall on.
151
151
  */
152
- async function findDomain(client, domain) {
152
+ /** Exported for `./org-mail-export.ts`, which needs the same exact,
153
+ * server-side-filtered lookup to scope a backup to one org's domain
154
+ * without listing and scanning every `Domain` on the shared instance. */
155
+ export async function findDomain(client, domain) {
153
156
  const { ids } = await client.call('x:Domain/query', {
154
157
  filter: { name: domain },
155
158
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/email",
3
- "version": "0.17.0",
3
+ "version": "0.18.1",
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",