@wtfalch/email 0.18.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
@@ -815,3 +815,74 @@ documents for IMAP. The alternative is a Graph `Mail.Read` application
815
815
  permission instead, which is what `import exchange-graph` would need; this
816
816
  package uses the IMAP path instead (see above), so `IMAP.AccessAsApp` is
817
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.
@@ -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() {
@@ -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.18.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",