@wtfalch/email 0.13.1 → 0.15.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.
Files changed (60) hide show
  1. package/README.md +390 -12
  2. package/dist/imip/compose.d.ts +5 -0
  3. package/dist/imip/compose.js +84 -0
  4. package/dist/imip/index.d.ts +15 -0
  5. package/dist/imip/index.js +14 -0
  6. package/dist/imip/lookup.d.ts +21 -0
  7. package/dist/imip/lookup.js +26 -0
  8. package/dist/imip/parse.d.ts +11 -0
  9. package/dist/imip/parse.js +116 -0
  10. package/dist/imip/types.d.ts +57 -0
  11. package/dist/imip/types.js +9 -0
  12. package/dist/mailbox/client.d.ts +28 -1
  13. package/dist/mailbox/client.js +51 -0
  14. package/dist/mailbox/fake/mailbox.js +567 -7
  15. package/dist/mailbox/index.d.ts +16 -8
  16. package/dist/mailbox/index.js +8 -4
  17. package/dist/mailbox/mail.css +13 -0
  18. package/dist/mailbox/mailboxes.d.ts +95 -1
  19. package/dist/mailbox/mailboxes.js +243 -1
  20. package/dist/mailbox/mutate.d.ts +21 -0
  21. package/dist/mailbox/mutate.js +71 -0
  22. package/dist/mailbox/quoted.d.ts +94 -0
  23. package/dist/mailbox/quoted.js +158 -0
  24. package/dist/mailbox/react/Composer.js +13 -1
  25. package/dist/mailbox/react/Mail.js +273 -33
  26. package/dist/mailbox/react/ThreadView.d.ts +13 -1
  27. package/dist/mailbox/react/ThreadView.js +5 -4
  28. package/dist/mailbox/react/index.d.ts +3 -1
  29. package/dist/mailbox/react/index.js +2 -1
  30. package/dist/mailbox/react/quotedHtml.d.ts +105 -0
  31. package/dist/mailbox/react/quotedHtml.js +163 -0
  32. package/dist/mailbox/sieve.d.ts +76 -0
  33. package/dist/mailbox/sieve.js +241 -0
  34. package/dist/mailbox/snooze.d.ts +48 -0
  35. package/dist/mailbox/snooze.js +176 -0
  36. package/dist/mailbox/submit.d.ts +56 -2
  37. package/dist/mailbox/submit.js +145 -11
  38. package/dist/mailbox/threads.js +2 -0
  39. package/dist/mailbox/types.d.ts +60 -0
  40. package/dist/mailbox/vacation.d.ts +32 -0
  41. package/dist/mailbox/vacation.js +79 -0
  42. package/dist/postmaster/apply.d.ts +154 -1
  43. package/dist/postmaster/apply.js +336 -1
  44. package/dist/postmaster/audit.d.ts +22 -1
  45. package/dist/postmaster/audit.js +7 -0
  46. package/dist/postmaster/client.d.ts +49 -0
  47. package/dist/postmaster/client.js +43 -0
  48. package/dist/postmaster/index.d.ts +6 -3
  49. package/dist/postmaster/index.js +5 -2
  50. package/dist/postmaster/mail-copy.d.ts +169 -0
  51. package/dist/postmaster/mail-copy.js +259 -0
  52. package/dist/postmaster/objects.js +11 -0
  53. package/dist/postmaster/org-mail.d.ts +117 -0
  54. package/dist/postmaster/org-mail.js +206 -0
  55. package/dist/postmaster/overview.d.ts +4 -0
  56. package/dist/postmaster/queue.d.ts +111 -0
  57. package/dist/postmaster/queue.js +64 -0
  58. package/dist/postmaster/writes.d.ts +59 -0
  59. package/dist/postmaster/writes.js +106 -0
  60. package/package.json +8 -3
@@ -7,8 +7,15 @@
7
7
  */
8
8
  export const POSTMASTER_AUDIT_EVENTS = {
9
9
  'mail.mailbox_created': { tenantVisible: true },
10
+ 'mail.group_created': { tenantVisible: true },
11
+ 'mail.group_member_added': { tenantVisible: true },
12
+ 'mail.group_member_removed': { tenantVisible: true },
10
13
  'mail.alias_added': { tenantVisible: true },
11
14
  'mail.alias_removed': { tenantVisible: true },
12
15
  'mail.app_password_revoked': { tenantVisible: true },
16
+ 'mail.api_key_revoked': { tenantVisible: true },
13
17
  'mail.holding_enabled': { tenantVisible: true },
18
+ 'mail.spam_settings_updated': { tenantVisible: true },
19
+ 'mail.queue_message_retried': { tenantVisible: true },
20
+ 'mail.queue_message_purged': { tenantVisible: true },
14
21
  };
@@ -76,12 +76,47 @@ export declare class StalwartClient {
76
76
  id: string;
77
77
  }>(object: string, ids: string[]): Promise<T[]>;
78
78
  getSingleton<T>(object: string): Promise<T>;
79
+ /**
80
+ * The standard JMAP Session resource (RFC 8620 §2), for whatever
81
+ * credential this client holds — a plain `GET`, not a `methodCalls`
82
+ * request, since the session resource is not one of this package's
83
+ * management objects and does not live under `x:<Object>/get`.
84
+ *
85
+ * Stalwart derives `username`/`accounts` straight from the credential's
86
+ * own embedded account id, for a Bearer `ApiKey` exactly as for Basic
87
+ * (confirmed against 0.16.20; see
88
+ * `.claude/scout/2026-09-22-bearer-whoami.md`). That makes this the one
89
+ * way to learn which account a Bearer credential belongs to — {@link
90
+ * Instance.user} (in `./instance.ts`) is `null` for that credential type.
91
+ * `revokeApiKey`'s self-revocation guard is the only caller.
92
+ *
93
+ * **A missing `username` throws rather than defaulting.** A real,
94
+ * authenticated JMAP session always carries one — RFC 8620 requires it,
95
+ * and Stalwart sets it from `account.name()` on every request that
96
+ * reaches this handler. An empty one here means something is badly wrong
97
+ * (a proxy swallowing the body, a wrong path resolving to a different
98
+ * handler), and silently returning `''` would make the guard compare
99
+ * against a value no real account ever has — the caller's own account
100
+ * would never match, and a self-revocation would go through unguarded.
101
+ * Failing loud here is what keeps that failure mode closed rather than
102
+ * open.
103
+ */
104
+ session(): Promise<SessionInfo>;
79
105
  /** Every object of a type. Filters are matched client-side by the caller. */
80
106
  list<T extends {
81
107
  id: string;
82
108
  }>(object: string): Promise<T[]>;
83
109
  create(object: string, value: Record<string, unknown>): Promise<string>;
84
110
  update(object: string, id: string, patch: Record<string, unknown>): Promise<void>;
111
+ /** Destroy one or more objects. Returns what the server actually did:
112
+ * `destroyed` are gone, `notDestroyed` names why each of the rest is not. */
113
+ destroy(object: string, ids: readonly string[]): Promise<{
114
+ destroyed: string[];
115
+ notDestroyed: Record<string, {
116
+ type: string;
117
+ description?: string;
118
+ }>;
119
+ }>;
85
120
  /**
86
121
  * Mint an API key for the authenticated account through the self-service
87
122
  * API, and return its secret, which is in the response and nowhere else.
@@ -145,3 +180,17 @@ export interface Credential {
145
180
  secret?: string;
146
181
  [property: string]: unknown;
147
182
  }
183
+ /**
184
+ * The two fields of the JMAP Session resource this package reads. The
185
+ * server sends a good deal more (`capabilities`, `apiUrl`, `state`, …);
186
+ * only `username` and `accounts` are named, for the same reason
187
+ * `WireAccount` (in `./overview.ts`) names only what it reads.
188
+ */
189
+ export interface SessionInfo {
190
+ /** The authenticated account's local part — `account.name()`, not an address. */
191
+ readonly username: string;
192
+ /** Keyed by the account's JMAP id. Exactly one entry, for a Bearer or a Basic credential alike. */
193
+ readonly accounts: Readonly<Record<string, {
194
+ readonly name?: string;
195
+ }>>;
196
+ }
@@ -172,6 +172,43 @@ export class StalwartClient {
172
172
  throw new StalwartError(`x:${object}/get`, 'notFound', 'singleton');
173
173
  return one;
174
174
  }
175
+ /**
176
+ * The standard JMAP Session resource (RFC 8620 §2), for whatever
177
+ * credential this client holds — a plain `GET`, not a `methodCalls`
178
+ * request, since the session resource is not one of this package's
179
+ * management objects and does not live under `x:<Object>/get`.
180
+ *
181
+ * Stalwart derives `username`/`accounts` straight from the credential's
182
+ * own embedded account id, for a Bearer `ApiKey` exactly as for Basic
183
+ * (confirmed against 0.16.20; see
184
+ * `.claude/scout/2026-09-22-bearer-whoami.md`). That makes this the one
185
+ * way to learn which account a Bearer credential belongs to — {@link
186
+ * Instance.user} (in `./instance.ts`) is `null` for that credential type.
187
+ * `revokeApiKey`'s self-revocation guard is the only caller.
188
+ *
189
+ * **A missing `username` throws rather than defaulting.** A real,
190
+ * authenticated JMAP session always carries one — RFC 8620 requires it,
191
+ * and Stalwart sets it from `account.name()` on every request that
192
+ * reaches this handler. An empty one here means something is badly wrong
193
+ * (a proxy swallowing the body, a wrong path resolving to a different
194
+ * handler), and silently returning `''` would make the guard compare
195
+ * against a value no real account ever has — the caller's own account
196
+ * would never match, and a self-revocation would go through unguarded.
197
+ * Failing loud here is what keeps that failure mode closed rather than
198
+ * open.
199
+ */
200
+ async session() {
201
+ const r = await fetch(`${this.base}/jmap/session`, { headers: this.headers() });
202
+ if (r.status === 401)
203
+ throw new StalwartError('session', 'unauthorized', 'wrong credential');
204
+ if (!r.ok)
205
+ throw new StalwartError('session', `http ${r.status}`, (await r.text()).slice(0, 300));
206
+ const json = (await r.json());
207
+ if (!json.username) {
208
+ throw new StalwartError('session', 'malformed', 'no username in the session resource');
209
+ }
210
+ return { username: json.username, accounts: json.accounts ?? {} };
211
+ }
175
212
  /** Every object of a type. Filters are matched client-side by the caller. */
176
213
  async list(object) {
177
214
  const q = await this.call(`x:${object}/query`, {});
@@ -197,6 +234,12 @@ export class StalwartClient {
197
234
  throw new StalwartError(`x:${object}/set`, failure.type, `${failure.description ?? ''}${failure.properties ? ` (${failure.properties.join(', ')})` : ''}`);
198
235
  }
199
236
  }
237
+ /** Destroy one or more objects. Returns what the server actually did:
238
+ * `destroyed` are gone, `notDestroyed` names why each of the rest is not. */
239
+ async destroy(object, ids) {
240
+ const res = await this.call(`x:${object}/set`, { destroy: ids });
241
+ return { destroyed: res.destroyed ?? [], notDestroyed: res.notDestroyed ?? {} };
242
+ }
200
243
  /**
201
244
  * Mint an API key for the authenticated account through the self-service
202
245
  * API, and return its secret, which is in the response and nowhere else.
@@ -14,12 +14,15 @@
14
14
  * The main entry is pure Node so a provisioning script can use it. The
15
15
  * components live behind `@wtfalch/email/postmaster/react`.
16
16
  */
17
- export { API_KEY_PREFIX, DASHBOARD_PERMISSIONS, StalwartClient, StalwartError, authFor, type Credential, type StalwartAuth, } from './client.js';
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
20
  export { FUTURE_RELEASE, applyObjects, mailObjects, ref, type MailObjectsInput, type PlannedObject, } from './objects.js';
21
21
  export { planMailboxes, withPassword } from './mailboxes.js';
22
22
  export { overview, pickDomain, type AccountView, type CredentialSummary, type DomainView, type Managed, type Overview, type OverviewInput, type PeopleView, type Person, type WireAccount, type WireAlias, type WireDomain, type WireSystemSettings, } from './overview.js';
23
- export { MailWriteRefused, newAccount, withAlias, withoutAlias, withoutAppPassword, } from './writes.js';
24
- export { addAlias, createMailbox, enableHolding, holdLimit, removeAlias, revokeAppPassword, type Applied, } from './apply.js';
23
+ export { MailWriteRefused, membershipIds, newAccount, newGroup, withAlias, withMembership, withoutAlias, withoutApiKey, withoutAppPassword, withoutMembership, } from './writes.js';
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
+ 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';
25
27
  export { POSTMASTER_AUDIT_EVENTS, type PostmasterAudit, type PostmasterAuditAction, type PostmasterAuditEvent, } from './audit.js';
28
+ export { MailCopyPlanRefused, mailCopyPlan, type MailCopyAccount, type MailCopyAccountPlan, type MailCopyEnv, type MailCopyOptions, type MailCopyPlan, type MailCopyProvider, } from './mail-copy.js';
@@ -20,6 +20,9 @@ export { loadOverview } from './load.js';
20
20
  export { FUTURE_RELEASE, applyObjects, mailObjects, ref, } from './objects.js';
21
21
  export { planMailboxes, withPassword } from './mailboxes.js';
22
22
  export { overview, pickDomain, } from './overview.js';
23
- export { MailWriteRefused, newAccount, withAlias, withoutAlias, withoutAppPassword, } from './writes.js';
24
- export { addAlias, createMailbox, enableHolding, holdLimit, removeAlias, revokeAppPassword, } from './apply.js';
23
+ export { MailWriteRefused, membershipIds, newAccount, newGroup, withAlias, withMembership, withoutAlias, withoutApiKey, withoutAppPassword, withoutMembership, } from './writes.js';
24
+ export { addAlias, addToGroup, createGroupMailbox, createMailbox, enableHolding, holdLimit, purgeQueuedMessage, removeAlias, removeFromGroup, retryQueuedMessage, revokeApiKey, revokeAppPassword, spamSettings, updateSpamSettings, } from './apply.js';
25
+ export { loadQueue, queueMessageView, } from './queue.js';
26
+ export { applyOrgMail, dkimRecordsFromZoneFile, parkOrgMail, } from './org-mail.js';
25
27
  export { POSTMASTER_AUDIT_EVENTS, } from './audit.js';
28
+ export { MailCopyPlanRefused, mailCopyPlan, } from './mail-copy.js';
@@ -0,0 +1,169 @@
1
+ /**
2
+ * The exact Vandelay command lines foundry runs to copy one org's old mail
3
+ * from Google Workspace or Microsoft 365 into Stalwart
4
+ * (`wtfalch/email#108`), and nothing else: this module never spawns
5
+ * Vandelay, never touches a network, and never reads a real credential — it
6
+ * only decides argv.
7
+ *
8
+ * **Vandelay, not our own copier.** The user's choice, 2026-09-26: Stalwart
9
+ * ships `stalwartlabs/vandelay` (dual-licensed `Apache-2.0 OR MIT` — the
10
+ * SPDX header on every source file, e.g. `src/cli.rs:1-5`, and
11
+ * `LICENSES/Apache-2.0.txt`/`LICENSES/MIT.txt` at the repo root; commit
12
+ * `42f7c879115cd2179eff067f01ac14cdc4fad0ec`, `main` as of 2026-09-26), a
13
+ * JMAP importer-exporter that already speaks IMAP, JMAP, DAV, Exchange and
14
+ * Google Takeout. `import` reads a source account into a local SQLite
15
+ * archive; `export` pushes that archive into a target JMAP account — the
16
+ * two never talk to each other directly (vandelay `README.md:39`).
17
+ *
18
+ * **Both providers go through `import imap`, not a provider-specific
19
+ * importer.** Vandelay's IMAP importer authenticates with XOAUTH2
20
+ * (`--auth-bearer` + `--auth-user`, `src/cli.rs:206-219`) and imports "mail
21
+ * (and only mail)" (vandelay `README.md:167`) — exactly what this module
22
+ * needs, for either provider, with one argv shape. Microsoft also ships
23
+ * `import exchange-graph` (`src/cli.rs:1091-1284`), but it is one of the two
24
+ * importers the tool's own docs call experimental (vandelay `README.md:54-55`;
25
+ * stalw.art/docs/migration/import-export/import/exchange-graph/: "The
26
+ * Microsoft Exchange importers are experimental. The flag surface and
27
+ * behaviour may change between releases."), and its non-interactive path
28
+ * still needs an access token acquired *outside* Vandelay — `GraphAuth` is
29
+ * `PreAcquired` or an interactive `DeviceCode`, never a client-credentials
30
+ * flow Vandelay drives itself (`src/cli.rs:1262-1284`; contrast
31
+ * `exchange-ews`'s built-in `OAuthFlow::ClientCredentials`,
32
+ * `src/cli.rs:1066-1089`). Google's service-account flow and Microsoft's
33
+ * `IMAP.AccessAsApp` app-only flow (see the README's admin setup) both mint
34
+ * a bearer token before Vandelay ever runs either way, so Graph buys
35
+ * nothing by switching providers and costs a second, less-stable argv
36
+ * shape. Decision, 2026-09-26.
37
+ *
38
+ * **No secret ever lands in argv.** Every secret-bearing Vandelay flag
39
+ * (`--auth-password`, `--auth-bearer`, `--access-token`, `--ews-client-secret`)
40
+ * takes an *optional* inline value (`num_args = 0..=1` in `src/cli.rs`);
41
+ * passed bare, Vandelay resolves it from a same-named environment variable
42
+ * and finally an interactive, no-echo TTY prompt — never a file
43
+ * (`src/secret.rs:12-30`: flag value, then `$VAR`, then a TTY prompt, else a
44
+ * usage error naming the variable). Vandelay's own README recommends
45
+ * exactly this, never argv: "Credentials should be supplied via the ...
46
+ * environment variables, or via an interactive prompt; passing them on the
47
+ * command line is supported but not recommended" (`README.md:131`), and its
48
+ * quick start sets the variable and passes the flag bare (`README.md:92-109`).
49
+ * This module follows that: every `MailCopyEnv` names a variable and never
50
+ * carries a value, and every argv array this returns passes `--auth-bearer`
51
+ * with nothing after it.
52
+ *
53
+ * **The import token and the export token read the *same* variable name.**
54
+ * A bare `--auth-bearer` always resolves `$VANDELAY_TOKEN`, whether it is
55
+ * `import imap`'s source credential or `export`'s Stalwart credential
56
+ * (both resolved by the same `secret::resolve(bearer, "VANDELAY_TOKEN", ...)`
57
+ * call shape, `src/cli.rs:848` and `src/cli.rs:1322`) — Vandelay has no flag
58
+ * to pick a different variable name. Import and export are two separate
59
+ * process launches, never concurrent, so this is safe *only* if the caller
60
+ * sets `VANDELAY_TOKEN` to the source token for the import launch and to
61
+ * the Stalwart credential for the export launch, and never merges the two
62
+ * into one environment. `MailCopyAccountPlan.importEnv` and `.exportEnv`
63
+ * both name `VANDELAY_TOKEN` for exactly this reason: same name, two
64
+ * different moments, never both set at once.
65
+ *
66
+ * **Rerunning is safe.** Both commands are "convergent": import "picks up
67
+ * where it left off" on an interrupted run, or "pick[s] up new mail since
68
+ * the last snapshot" on a later one (vandelay `README.md:57,112`), matching
69
+ * blobs by BLAKE3 hash (`README.md:59`); export is "stateless re-matching
70
+ * on every run" and "upsert-only: matched items are updated, unmatched
71
+ * local items are created, but pre-existing target items not covered by the
72
+ * archive are left alone" (`README.md:56,277`) — a rerun never recopies or
73
+ * duplicates a message already on the Stalwart account. This module never
74
+ * sets `--prune`, so a plan built here can never delete anything on the
75
+ * target either.
76
+ *
77
+ * **Export targets a Stalwart account by id or name, with its own
78
+ * credential.** `--account-id`/`--account-name` (exactly one, `src/cli.rs:301`'s
79
+ * `ArgGroup`) names the target account; its auth (`--auth-basic`/`--auth-bearer`,
80
+ * same file, line 300) is separate from whatever authenticated the import.
81
+ * `./client.ts`'s own `StalwartClient` only accepts a Stalwart API key as
82
+ * `Authorization: Bearer` — never Basic, confirmed against a live instance
83
+ * (this package's README, "What it knows that the docs do not") — so
84
+ * export always uses `--auth-bearer` here, never `--auth-basic`.
85
+ *
86
+ * **Vandelay never checks that the export credential may write into that
87
+ * account — Stalwart does.** `--account-id`/`--account-name` is resolved
88
+ * verbatim and used as-is (`AccountSelector::Id(id) => Ok(id.clone())`,
89
+ * vandelay `src/jmap/account.rs:30`; `connect::prepare` then uses that id
90
+ * with no authorization check of its own, `src/jmap/connect.rs:39`). The
91
+ * gate is entirely server-side: Stalwart's request dispatcher requires
92
+ * `access_token.assert_has_access(account_id, Collection::Email)` for
93
+ * `Email/set` and the equivalent for `Mailbox/set`
94
+ * (`stalwartlabs/stalwart` `crates/jmap/src/api/request.rs:475,481` at
95
+ * commit `02503015580abd6706923d34e9d8e501e76f8634`), which
96
+ * `AccessToken::has_access` grants only when the credential either
97
+ * `is_member` of the target account — its own account, a group it belongs
98
+ * to, or holds the `impersonate` permission outright
99
+ * (`crates/common/src/auth/access_token.rs:476-480`) — or has been given
100
+ * ACL/shared access to that account's `Email` collection specifically
101
+ * (same file, lines 696-704). `impersonate` is already a name this
102
+ * package's own API keys can hold (see "What it knows that the docs do
103
+ * not", above), and is the practical choice for a migration credential
104
+ * that writes into many different accounts: mint the export key with
105
+ * `impersonate` rather than trying to pre-arrange per-account ACL shares.
106
+ */
107
+ export type MailCopyProvider = 'google' | 'microsoft';
108
+ export declare class MailCopyPlanRefused extends Error {
109
+ }
110
+ export interface MailCopyAccount {
111
+ /** The mailbox to read at the source, e.g. `alice@acme.com`. Also the
112
+ * XOAUTH2 identity Vandelay's `--auth-user` sends. */
113
+ readonly source: string;
114
+ /** The Stalwart account this org's mail lands on. Exactly one of
115
+ * `targetAccountId`/`targetAccountName`, mirroring Vandelay's own
116
+ * `export` `ArgGroup` (`src/cli.rs:301`). */
117
+ readonly targetAccountId?: string;
118
+ readonly targetAccountName?: string;
119
+ }
120
+ export interface MailCopyOptions {
121
+ readonly provider: MailCopyProvider;
122
+ readonly accounts: readonly MailCopyAccount[];
123
+ /** The Stalwart JMAP base URL `export --url` writes to, e.g.
124
+ * `https://mail.wtfalch.dev`. */
125
+ readonly stalwartUrl: string;
126
+ /** Directory holding one Vandelay SQLite archive per account. */
127
+ readonly archiveDir: string;
128
+ }
129
+ /** An environment variable one Vandelay invocation needs — never its
130
+ * value. The caller sets it for that one subprocess launch. */
131
+ export interface MailCopyEnv {
132
+ readonly name: string;
133
+ readonly purpose: string;
134
+ }
135
+ export interface MailCopyAccountPlan {
136
+ readonly source: string;
137
+ /** The local SQLite archive this account's import fills and its export
138
+ * reads back. */
139
+ readonly archive: string;
140
+ readonly importArgv: readonly string[];
141
+ readonly importEnv: readonly MailCopyEnv[];
142
+ readonly exportArgv: readonly string[];
143
+ readonly exportEnv: readonly MailCopyEnv[];
144
+ }
145
+ export interface MailCopyPlan {
146
+ readonly provider: MailCopyProvider;
147
+ readonly accounts: readonly MailCopyAccountPlan[];
148
+ }
149
+ /**
150
+ * The Vandelay commands foundry runs to copy every account of one org's old
151
+ * mail from `input.provider` into Stalwart: one `import imap` and one
152
+ * `export` per account, plus the environment variable names (never values)
153
+ * each needs. Pure and idempotent — calling this twice with the same input
154
+ * returns the same plan, and running the returned commands twice against
155
+ * the same archive and account is exactly the rerun Vandelay is built to
156
+ * support (see this file's module doc comment).
157
+ *
158
+ * Refuses before building anything: a `stalwartUrl` that is not https (a
159
+ * bearer credential over http is the credential in clear, the same rule
160
+ * `openInstance` applies in `./instance.ts`), a `stalwartUrl` carrying
161
+ * embedded userinfo (`https://user:secret@host/`, which would put that
162
+ * secret straight into `exportArgv`), an empty `archiveDir`, no accounts, an
163
+ * account whose `source` is not email-shaped, an account that names both or
164
+ * neither of `targetAccountId`/`targetAccountName`, or two accounts that
165
+ * would land on the same archive file (see `archiveFileName`) — always a
166
+ * mistake, since it means one account's mail would import into the other's
167
+ * archive.
168
+ */
169
+ export declare function mailCopyPlan(input: MailCopyOptions): MailCopyPlan;
@@ -0,0 +1,259 @@
1
+ /**
2
+ * The exact Vandelay command lines foundry runs to copy one org's old mail
3
+ * from Google Workspace or Microsoft 365 into Stalwart
4
+ * (`wtfalch/email#108`), and nothing else: this module never spawns
5
+ * Vandelay, never touches a network, and never reads a real credential — it
6
+ * only decides argv.
7
+ *
8
+ * **Vandelay, not our own copier.** The user's choice, 2026-09-26: Stalwart
9
+ * ships `stalwartlabs/vandelay` (dual-licensed `Apache-2.0 OR MIT` — the
10
+ * SPDX header on every source file, e.g. `src/cli.rs:1-5`, and
11
+ * `LICENSES/Apache-2.0.txt`/`LICENSES/MIT.txt` at the repo root; commit
12
+ * `42f7c879115cd2179eff067f01ac14cdc4fad0ec`, `main` as of 2026-09-26), a
13
+ * JMAP importer-exporter that already speaks IMAP, JMAP, DAV, Exchange and
14
+ * Google Takeout. `import` reads a source account into a local SQLite
15
+ * archive; `export` pushes that archive into a target JMAP account — the
16
+ * two never talk to each other directly (vandelay `README.md:39`).
17
+ *
18
+ * **Both providers go through `import imap`, not a provider-specific
19
+ * importer.** Vandelay's IMAP importer authenticates with XOAUTH2
20
+ * (`--auth-bearer` + `--auth-user`, `src/cli.rs:206-219`) and imports "mail
21
+ * (and only mail)" (vandelay `README.md:167`) — exactly what this module
22
+ * needs, for either provider, with one argv shape. Microsoft also ships
23
+ * `import exchange-graph` (`src/cli.rs:1091-1284`), but it is one of the two
24
+ * importers the tool's own docs call experimental (vandelay `README.md:54-55`;
25
+ * stalw.art/docs/migration/import-export/import/exchange-graph/: "The
26
+ * Microsoft Exchange importers are experimental. The flag surface and
27
+ * behaviour may change between releases."), and its non-interactive path
28
+ * still needs an access token acquired *outside* Vandelay — `GraphAuth` is
29
+ * `PreAcquired` or an interactive `DeviceCode`, never a client-credentials
30
+ * flow Vandelay drives itself (`src/cli.rs:1262-1284`; contrast
31
+ * `exchange-ews`'s built-in `OAuthFlow::ClientCredentials`,
32
+ * `src/cli.rs:1066-1089`). Google's service-account flow and Microsoft's
33
+ * `IMAP.AccessAsApp` app-only flow (see the README's admin setup) both mint
34
+ * a bearer token before Vandelay ever runs either way, so Graph buys
35
+ * nothing by switching providers and costs a second, less-stable argv
36
+ * shape. Decision, 2026-09-26.
37
+ *
38
+ * **No secret ever lands in argv.** Every secret-bearing Vandelay flag
39
+ * (`--auth-password`, `--auth-bearer`, `--access-token`, `--ews-client-secret`)
40
+ * takes an *optional* inline value (`num_args = 0..=1` in `src/cli.rs`);
41
+ * passed bare, Vandelay resolves it from a same-named environment variable
42
+ * and finally an interactive, no-echo TTY prompt — never a file
43
+ * (`src/secret.rs:12-30`: flag value, then `$VAR`, then a TTY prompt, else a
44
+ * usage error naming the variable). Vandelay's own README recommends
45
+ * exactly this, never argv: "Credentials should be supplied via the ...
46
+ * environment variables, or via an interactive prompt; passing them on the
47
+ * command line is supported but not recommended" (`README.md:131`), and its
48
+ * quick start sets the variable and passes the flag bare (`README.md:92-109`).
49
+ * This module follows that: every `MailCopyEnv` names a variable and never
50
+ * carries a value, and every argv array this returns passes `--auth-bearer`
51
+ * with nothing after it.
52
+ *
53
+ * **The import token and the export token read the *same* variable name.**
54
+ * A bare `--auth-bearer` always resolves `$VANDELAY_TOKEN`, whether it is
55
+ * `import imap`'s source credential or `export`'s Stalwart credential
56
+ * (both resolved by the same `secret::resolve(bearer, "VANDELAY_TOKEN", ...)`
57
+ * call shape, `src/cli.rs:848` and `src/cli.rs:1322`) — Vandelay has no flag
58
+ * to pick a different variable name. Import and export are two separate
59
+ * process launches, never concurrent, so this is safe *only* if the caller
60
+ * sets `VANDELAY_TOKEN` to the source token for the import launch and to
61
+ * the Stalwart credential for the export launch, and never merges the two
62
+ * into one environment. `MailCopyAccountPlan.importEnv` and `.exportEnv`
63
+ * both name `VANDELAY_TOKEN` for exactly this reason: same name, two
64
+ * different moments, never both set at once.
65
+ *
66
+ * **Rerunning is safe.** Both commands are "convergent": import "picks up
67
+ * where it left off" on an interrupted run, or "pick[s] up new mail since
68
+ * the last snapshot" on a later one (vandelay `README.md:57,112`), matching
69
+ * blobs by BLAKE3 hash (`README.md:59`); export is "stateless re-matching
70
+ * on every run" and "upsert-only: matched items are updated, unmatched
71
+ * local items are created, but pre-existing target items not covered by the
72
+ * archive are left alone" (`README.md:56,277`) — a rerun never recopies or
73
+ * duplicates a message already on the Stalwart account. This module never
74
+ * sets `--prune`, so a plan built here can never delete anything on the
75
+ * target either.
76
+ *
77
+ * **Export targets a Stalwart account by id or name, with its own
78
+ * credential.** `--account-id`/`--account-name` (exactly one, `src/cli.rs:301`'s
79
+ * `ArgGroup`) names the target account; its auth (`--auth-basic`/`--auth-bearer`,
80
+ * same file, line 300) is separate from whatever authenticated the import.
81
+ * `./client.ts`'s own `StalwartClient` only accepts a Stalwart API key as
82
+ * `Authorization: Bearer` — never Basic, confirmed against a live instance
83
+ * (this package's README, "What it knows that the docs do not") — so
84
+ * export always uses `--auth-bearer` here, never `--auth-basic`.
85
+ *
86
+ * **Vandelay never checks that the export credential may write into that
87
+ * account — Stalwart does.** `--account-id`/`--account-name` is resolved
88
+ * verbatim and used as-is (`AccountSelector::Id(id) => Ok(id.clone())`,
89
+ * vandelay `src/jmap/account.rs:30`; `connect::prepare` then uses that id
90
+ * with no authorization check of its own, `src/jmap/connect.rs:39`). The
91
+ * gate is entirely server-side: Stalwart's request dispatcher requires
92
+ * `access_token.assert_has_access(account_id, Collection::Email)` for
93
+ * `Email/set` and the equivalent for `Mailbox/set`
94
+ * (`stalwartlabs/stalwart` `crates/jmap/src/api/request.rs:475,481` at
95
+ * commit `02503015580abd6706923d34e9d8e501e76f8634`), which
96
+ * `AccessToken::has_access` grants only when the credential either
97
+ * `is_member` of the target account — its own account, a group it belongs
98
+ * to, or holds the `impersonate` permission outright
99
+ * (`crates/common/src/auth/access_token.rs:476-480`) — or has been given
100
+ * ACL/shared access to that account's `Email` collection specifically
101
+ * (same file, lines 696-704). `impersonate` is already a name this
102
+ * package's own API keys can hold (see "What it knows that the docs do
103
+ * not", above), and is the practical choice for a migration credential
104
+ * that writes into many different accounts: mint the export key with
105
+ * `impersonate` rather than trying to pre-arrange per-account ACL shares.
106
+ */
107
+ /**
108
+ * The IMAP host Vandelay's `--url` targets, confirmed live on each
109
+ * provider's own settings page: `imap.gmail.com:993`
110
+ * (developers.google.com/workspace/gmail/imap/imap-smtp: "Incoming
111
+ * connections to the IMAP server at imap.gmail.com:993") and
112
+ * `outlook.office365.com:993`
113
+ * (support.microsoft.com/article/pop-and-imap-email-settings-for-outlook-8361e398-8af4-4e97-b147-6c6c4ac95353).
114
+ */
115
+ const IMAP_URL = {
116
+ google: 'imaps://imap.gmail.com',
117
+ microsoft: 'imaps://outlook.office365.com',
118
+ };
119
+ /** The env var name every bare `--auth-bearer` resolves (`src/secret.rs:12-30`).
120
+ * Named once so the import and export sides are visibly the same
121
+ * variable, not two names that happen to collide. */
122
+ const VANDELAY_TOKEN = 'VANDELAY_TOKEN';
123
+ export class MailCopyPlanRefused extends Error {
124
+ }
125
+ /** A very small email shape check: exactly one `@`, something on both
126
+ * sides. Vandelay and both providers accept far more than this; the point
127
+ * here is only to refuse an empty string or a pasted display name before
128
+ * it becomes an XOAUTH2 identity. */
129
+ function assertEmailish(value) {
130
+ const at = value.indexOf('@');
131
+ if (at <= 0 || at === value.length - 1 || value.indexOf('@', at + 1) !== -1) {
132
+ throw new MailCopyPlanRefused(`"${value}" does not look like an email address`);
133
+ }
134
+ }
135
+ /**
136
+ * A filesystem-safe archive filename derived only from the account's
137
+ * address, never from anything time-based — so two calls with the same
138
+ * input produce the same path, which is what makes a rerun's plan
139
+ * idempotent.
140
+ *
141
+ * `encodeURIComponent` rather than a hand-rolled collapse of "unsafe"
142
+ * characters to `_`: two different addresses must never fold onto the same
143
+ * file, or their mail crosses between accounts. A collapse is not
144
+ * injective — `alice+bob@acme.com` and `alice_bob@acme.com` both
145
+ * flattened to `alice_bob_at_acme.com` — while percent-encoding only ever
146
+ * rewrites a character to a fixed, distinct token (`+` to `%2B`, `@` to
147
+ * `%40`, …) and leaves `_` alone, so no two distinct inputs can collide
148
+ * through this function alone. `mailCopyPlan` still checks the *result*
149
+ * for collisions across a whole plan (case-folding two spellings of one
150
+ * mailbox together, for instance), since that is a real answer, not a bug
151
+ * in the encoding.
152
+ */
153
+ function archiveFileName(source) {
154
+ return `${encodeURIComponent(source.toLowerCase())}.sqlite`;
155
+ }
156
+ /** `--account-id=<id>` or `--account-name=<name>`, refusing both or
157
+ * neither rather than silently preferring one — the same exactly-one rule
158
+ * Vandelay's own `export` enforces with an `ArgGroup` (`src/cli.rs:301`).
159
+ * The `=` form, rather than two argv elements, so a value starting with
160
+ * `-` (an id or name clap would otherwise mistake for another flag) still
161
+ * parses as this flag's value. */
162
+ function accountSelectorArgv(account) {
163
+ const { targetAccountId, targetAccountName } = account;
164
+ if (targetAccountId && targetAccountName) {
165
+ throw new MailCopyPlanRefused(`${account.source} names both a target account id and a target account name; export takes exactly one`);
166
+ }
167
+ if (targetAccountId)
168
+ return `--account-id=${targetAccountId}`;
169
+ if (targetAccountName)
170
+ return `--account-name=${targetAccountName}`;
171
+ throw new MailCopyPlanRefused(`${account.source} needs a target Stalwart account id or name`);
172
+ }
173
+ function planAccount(account, imapUrl, stalwartUrl, archiveDir) {
174
+ assertEmailish(account.source);
175
+ const accountFlag = accountSelectorArgv(account);
176
+ const archive = `${archiveDir}/${archiveFileName(account.source)}`;
177
+ // `--` before the positional archive path: without it, an archiveDir
178
+ // starting with `-` would parse as an unrecognised flag rather than the
179
+ // ARCHIVE positional (clap does not special-case a leading `-` on a
180
+ // positional). Harmless, and always included, when it does not.
181
+ const importArgv = [
182
+ 'import',
183
+ 'imap',
184
+ '--url',
185
+ imapUrl,
186
+ '--auth-bearer',
187
+ `--auth-user=${account.source}`,
188
+ '--',
189
+ archive,
190
+ ];
191
+ const importEnv = [
192
+ { name: VANDELAY_TOKEN, purpose: `the source XOAUTH2 bearer token for ${account.source}` },
193
+ ];
194
+ const exportArgv = ['export', '--url', stalwartUrl, '--auth-bearer', accountFlag, '--', archive];
195
+ const exportEnv = [
196
+ {
197
+ name: VANDELAY_TOKEN,
198
+ purpose: `the Stalwart account credential for ${account.source}'s target account`,
199
+ },
200
+ ];
201
+ return { source: account.source, archive, importArgv, importEnv, exportArgv, exportEnv };
202
+ }
203
+ /**
204
+ * The Vandelay commands foundry runs to copy every account of one org's old
205
+ * mail from `input.provider` into Stalwart: one `import imap` and one
206
+ * `export` per account, plus the environment variable names (never values)
207
+ * each needs. Pure and idempotent — calling this twice with the same input
208
+ * returns the same plan, and running the returned commands twice against
209
+ * the same archive and account is exactly the rerun Vandelay is built to
210
+ * support (see this file's module doc comment).
211
+ *
212
+ * Refuses before building anything: a `stalwartUrl` that is not https (a
213
+ * bearer credential over http is the credential in clear, the same rule
214
+ * `openInstance` applies in `./instance.ts`), a `stalwartUrl` carrying
215
+ * embedded userinfo (`https://user:secret@host/`, which would put that
216
+ * secret straight into `exportArgv`), an empty `archiveDir`, no accounts, an
217
+ * account whose `source` is not email-shaped, an account that names both or
218
+ * neither of `targetAccountId`/`targetAccountName`, or two accounts that
219
+ * would land on the same archive file (see `archiveFileName`) — always a
220
+ * mistake, since it means one account's mail would import into the other's
221
+ * archive.
222
+ */
223
+ export function mailCopyPlan(input) {
224
+ if (input.provider !== 'google' && input.provider !== 'microsoft') {
225
+ throw new MailCopyPlanRefused(`provider must be "google" or "microsoft", got "${String(input.provider)}"`);
226
+ }
227
+ const stalwartUrl = input.stalwartUrl.trim().replace(/\/+$/, '');
228
+ if (!/^https:\/\//.test(stalwartUrl)) {
229
+ throw new MailCopyPlanRefused(`the Stalwart URL must be https, got "${input.stalwartUrl}"`);
230
+ }
231
+ let parsedUrl;
232
+ try {
233
+ parsedUrl = new URL(stalwartUrl);
234
+ }
235
+ catch {
236
+ throw new MailCopyPlanRefused(`"${input.stalwartUrl}" is not a valid URL`);
237
+ }
238
+ if (parsedUrl.username || parsedUrl.password) {
239
+ throw new MailCopyPlanRefused('the Stalwart URL must not carry embedded credentials; use --auth-bearer instead');
240
+ }
241
+ const archiveDir = input.archiveDir.trim().replace(/\/+$/, '');
242
+ if (!archiveDir) {
243
+ throw new MailCopyPlanRefused('an archive directory is required');
244
+ }
245
+ if (input.accounts.length === 0) {
246
+ throw new MailCopyPlanRefused('at least one account is required');
247
+ }
248
+ const imapUrl = IMAP_URL[input.provider];
249
+ const accounts = input.accounts.map((account) => planAccount(account, imapUrl, stalwartUrl, archiveDir));
250
+ const seenArchives = new Map();
251
+ for (const account of accounts) {
252
+ const collidesWith = seenArchives.get(account.archive);
253
+ if (collidesWith) {
254
+ throw new MailCopyPlanRefused(`${account.source} and ${collidesWith} would both use the archive "${account.archive}"; give them distinct addresses or split the plan`);
255
+ }
256
+ seenArchives.set(account.archive, account.source);
257
+ }
258
+ return { provider: input.provider, accounts };
259
+ }
@@ -114,6 +114,17 @@ export function mailObjects(i) {
114
114
  match: { id: 'singleton' },
115
115
  value: { defaultHostname: i.mailHost, defaultDomainId: ref('domain') },
116
116
  },
117
+ {
118
+ key: 'http',
119
+ object: 'Http',
120
+ match: { id: 'singleton' },
121
+ // Wildcard-only on 0.16: there is no per-origin allowlist to scope this
122
+ // to, and once on it answers every route, JMAP and management alike,
123
+ // including the preflight. That is safe here only because nothing
124
+ // reaches this server except through the tunnel, and the hub's own
125
+ // audience check on the token still stands in front of every request.
126
+ value: { usePermissiveCors: true },
127
+ },
117
128
  ...(i.oidc
118
129
  ? [
119
130
  {