@wtfalch/email 0.21.0 → 0.24.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.
@@ -1,5 +1,8 @@
1
- import { JAM_FETCH } from "./client.js";
1
+ import { JAM_FETCH, SIEVE_CAPABILITY } from "./client.js";
2
2
  import { MailError, guard } from "./errors.js";
3
+ import { identities } from "./identities.js";
4
+ import { combineScript, splitScript } from "./rules.js";
5
+ import { activateSieveScript, saveSieveScript, sieveScriptText, sieveScripts } from "./sieve.js";
3
6
  /**
4
7
  * The vacation auto-reply: RFC 8621 §8's `VacationResponse`, over the
5
8
  * `urn:ietf:params:jmap:vacationresponse` capability.
@@ -20,9 +23,12 @@ import { MailError, guard } from "./errors.js";
20
23
  * by hand; a plain `VacationResponse/get` or `/set` names itself.
21
24
  */
22
25
  const SINGLETON = 'singleton';
26
+ const SCRIPT_NAME = 'wtfalch-mail';
27
+ const AUDIENCES = ['anyone', 'company', 'nobody'];
23
28
  function fromRaw(raw) {
24
29
  return {
25
30
  isEnabled: raw.isEnabled,
31
+ audience: 'anyone',
26
32
  fromDate: raw.fromDate ?? null,
27
33
  toDate: raw.toDate ?? null,
28
34
  subject: raw.subject ?? null,
@@ -30,9 +36,8 @@ function fromRaw(raw) {
30
36
  htmlBody: raw.htmlBody ?? null,
31
37
  };
32
38
  }
33
- /** The account's vacation response as it stands now. */
34
- export async function vacationResponse(client) {
35
- const { jam, accountId } = await client.connect();
39
+ async function readJmap(connection) {
40
+ const { jam, accountId } = connection;
36
41
  return guard('vacation response', async () => {
37
42
  const [result] = await jam.api.VacationResponse.get({ accountId }, JAM_FETCH);
38
43
  const found = result.list[0];
@@ -45,6 +50,41 @@ export async function vacationResponse(client) {
45
50
  return fromRaw(found);
46
51
  });
47
52
  }
53
+ function hasSieve(connection) {
54
+ return connection.doc.capabilities?.[SIEVE_CAPABILITY] !== undefined;
55
+ }
56
+ /** The script the away reply lives in -- the active one, else (for a write)
57
+ * an inactive one named `wtfalch-mail` -- and what it was built from;
58
+ * `split` is null for a hand-written one. */
59
+ async function activeScript(client, orNamed = false) {
60
+ const scripts = await sieveScripts(client);
61
+ const active = scripts.find((script) => script.isActive) ?? null;
62
+ const target = active ?? (orNamed ? scripts.find((s) => s.name === SCRIPT_NAME) : undefined);
63
+ if (!target)
64
+ return { target: null, active, split: { rules: null, vacation: null } };
65
+ const split = splitScript(await sieveScriptText(client, target.id));
66
+ return { target, active, split };
67
+ }
68
+ /** The account's vacation response as it stands now. */
69
+ export async function vacationResponse(client) {
70
+ const connection = await client.connect();
71
+ if (hasSieve(connection)) {
72
+ const { split } = await activeScript(client);
73
+ const section = split?.vacation;
74
+ if (section) {
75
+ return {
76
+ isEnabled: section.isEnabled,
77
+ audience: section.audience,
78
+ fromDate: section.fromDate,
79
+ toDate: section.toDate,
80
+ subject: section.subject,
81
+ textBody: section.textBody,
82
+ htmlBody: section.htmlBody,
83
+ };
84
+ }
85
+ }
86
+ return readJmap(connection);
87
+ }
48
88
  /**
49
89
  * Set the vacation response: whether it is on, its window, and its message.
50
90
  *
@@ -56,13 +96,81 @@ export async function vacationResponse(client) {
56
96
  * responder back on does not need to resupply them.
57
97
  */
58
98
  export async function setVacationResponse(client, options) {
59
- const { jam, accountId } = await client.connect();
60
- const { isEnabled, ...rest } = options;
61
- const patch = { isEnabled };
62
- for (const [key, value] of Object.entries(rest)) {
63
- if (value !== undefined)
64
- patch[key] = value;
99
+ const { audience } = options;
100
+ if (audience !== undefined && !AUDIENCES.includes(audience)) {
101
+ throw new MailError('audience must be "anyone", "company" or "nobody"', {
102
+ type: 'invalidArguments',
103
+ operation: 'set vacation response',
104
+ });
105
+ }
106
+ const connection = await client.connect();
107
+ const { isEnabled, audience: _audience, ...rest } = options;
108
+ const jmapPatch = (fields) => updateJmap(connection, fields);
109
+ if (!hasSieve(connection)) {
110
+ if (audience === 'company' || audience === 'nobody') {
111
+ throw new MailError('this server has no sieve support, so the away reply is for anyone', {
112
+ type: 'unsupported',
113
+ operation: 'set vacation response',
114
+ });
115
+ }
116
+ const patch = { isEnabled };
117
+ for (const [key, value] of Object.entries(rest)) {
118
+ if (value !== undefined)
119
+ patch[key] = value;
120
+ }
121
+ return jmapPatch(patch);
122
+ }
123
+ const { target, active, split } = await activeScript(client, true);
124
+ if (split === null) {
125
+ if (isEnabled) {
126
+ throw new MailError('the active sieve script was not written by this app; not replacing it', {
127
+ type: 'conflict',
128
+ operation: 'set vacation response',
129
+ });
130
+ }
131
+ return jmapPatch({ isEnabled: false });
132
+ }
133
+ const stored = split.vacation ?? {
134
+ ...(await readJmap(connection)),
135
+ domain: null,
136
+ };
137
+ const next = {
138
+ isEnabled,
139
+ audience: audience ?? stored.audience,
140
+ domain: stored.domain,
141
+ fromDate: rest.fromDate !== undefined ? rest.fromDate : stored.fromDate,
142
+ toDate: rest.toDate !== undefined ? rest.toDate : stored.toDate,
143
+ subject: rest.subject !== undefined ? rest.subject : stored.subject,
144
+ textBody: rest.textBody !== undefined ? rest.textBody : stored.textBody,
145
+ htmlBody: rest.htmlBody !== undefined ? rest.htmlBody : stored.htmlBody,
146
+ };
147
+ if (next.audience === 'company' &&
148
+ isEnabled &&
149
+ (audience === 'company' || next.domain === null)) {
150
+ const [first] = await identities(client);
151
+ if (!first) {
152
+ throw new MailError('the account has no identity to take the company domain from', {
153
+ type: 'notFound',
154
+ operation: 'set vacation response',
155
+ });
156
+ }
157
+ next.domain = first.email.slice(first.email.lastIndexOf('@') + 1);
65
158
  }
159
+ const text = combineScript(split.rules, next);
160
+ const saved = await saveSieveScript(client, target?.name ?? SCRIPT_NAME, text, target ? { scriptId: target.id } : {});
161
+ if (!active)
162
+ await activateSieveScript(client, saved.id);
163
+ return jmapPatch({
164
+ isEnabled: false,
165
+ fromDate: next.fromDate,
166
+ toDate: next.toDate,
167
+ subject: next.subject,
168
+ textBody: next.textBody,
169
+ htmlBody: next.htmlBody,
170
+ });
171
+ }
172
+ async function updateJmap(connection, patch) {
173
+ const { jam, accountId } = connection;
66
174
  return guard('set vacation response', async () => {
67
175
  const [result] = await jam.api.VacationResponse.set({ accountId, update: { [SINGLETON]: patch } }, JAM_FETCH);
68
176
  const notUpdated = result.notUpdated;
@@ -105,6 +105,26 @@ export declare function revokeAppPassword(instance: Instance, input: {
105
105
  domainId: string;
106
106
  apex: string;
107
107
  }, audit?: PostmasterAudit): Promise<Applied>;
108
+ /**
109
+ * Stop every app password on the account working at once, used when a
110
+ * person must be shut out of mail immediately — disabling their sign-in
111
+ * alone does not do this, because IMAP and SMTP never consult the issuer
112
+ * and an app password they minted keeps authenticating after it.
113
+ *
114
+ * Same self-protection as `revokeAppPassword`, for the same reason: an
115
+ * instance whose administrator credential is itself an app password (a
116
+ * laptop, or an instance provisioned before slice 3) must not be able to
117
+ * revoke its own way in from inside the panel.
118
+ *
119
+ * Secrets are never read, here or anywhere else: surviving credentials
120
+ * (the account `Password`, any `ApiKey`) go back exactly as the server sent
121
+ * them, which it reads as "leave this one alone".
122
+ */
123
+ export declare function revokeAllAppPasswords(instance: Instance, input: {
124
+ accountId: string;
125
+ domainId: string;
126
+ apex: string;
127
+ }, audit?: PostmasterAudit): Promise<Applied>;
108
128
  /**
109
129
  * Stop one API key working. The secret is never read, here or anywhere
110
130
  * else: the entry is identified by its id and the surviving entries go back
@@ -1,5 +1,5 @@
1
1
  import { FUTURE_RELEASE } from './objects.js';
2
- import { MailWriteRefused, membershipIds, newAccount, newGroup, withAlias, withMembership, withoutAlias, withoutApiKey, withoutAppPassword, withoutMembership, } from './writes.js';
2
+ import { MailWriteRefused, membershipIds, newAccount, newGroup, withAlias, withMembership, withoutAlias, withoutAllAppPasswords, withoutApiKey, withoutAppPassword, withoutMembership, } from './writes.js';
3
3
  /**
4
4
  * The four writes `/email` makes, each as one round trip against the mail
5
5
  * instance's management API.
@@ -322,6 +322,53 @@ export async function revokeAppPassword(instance, input, audit) {
322
322
  message: `That app password no longer works${description ? ` (${description})` : ''}. Any mail client using it will be asked to sign in again.${lost}`,
323
323
  });
324
324
  }
325
+ /**
326
+ * Stop every app password on the account working at once, used when a
327
+ * person must be shut out of mail immediately — disabling their sign-in
328
+ * alone does not do this, because IMAP and SMTP never consult the issuer
329
+ * and an app password they minted keeps authenticating after it.
330
+ *
331
+ * Same self-protection as `revokeAppPassword`, for the same reason: an
332
+ * instance whose administrator credential is itself an app password (a
333
+ * laptop, or an instance provisioned before slice 3) must not be able to
334
+ * revoke its own way in from inside the panel.
335
+ *
336
+ * Secrets are never read, here or anywhere else: surviving credentials
337
+ * (the account `Password`, any `ApiKey`) go back exactly as the server sent
338
+ * them, which it reads as "leave this one alone".
339
+ */
340
+ export async function revokeAllAppPasswords(instance, input, audit) {
341
+ const account = await readAccount(instance, input.accountId, input.domainId);
342
+ if (isOurOwnAccount(instance, account, input.apex)) {
343
+ throw new MailWriteRefused(`${instance.user} is the account this management app signs in as, and one of its app passwords is serving this request. Manage its credentials in the web admin.`);
344
+ }
345
+ // The same filter that decides what `withoutAllAppPasswords` removes,
346
+ // so the audited and reported count can never disagree with what was
347
+ // actually revoked. `description`/`credentialId` are both optional on
348
+ // `Credential`, so an entry naming neither still counts — it is named
349
+ // '(unnamed)' rather than silently dropped, which would otherwise read
350
+ // as "nothing revoked" while the write still stripped it.
351
+ const before = Object.values(account.credentials ?? {}).filter((c) => c['@type'] === 'AppPassword');
352
+ const revoked = before.map((c) => typeof c.description === 'string'
353
+ ? c.description
354
+ : typeof c.credentialId === 'string'
355
+ ? c.credentialId
356
+ : '(unnamed)');
357
+ const credentials = withoutAllAppPasswords(account);
358
+ await instance.client.update('Account', account.id, { credentials });
359
+ const lost = missingSince(Object.values(credentials)
360
+ .map((c) => c.credentialId)
361
+ .filter((id) => typeof id === 'string'), await credentialIds(instance, account.id));
362
+ return recorded(audit, 'mail.app_passwords_revoked', {
363
+ targetType: 'mail_app_password',
364
+ targetId: `${account.name}@${input.apex}`,
365
+ before: { mailbox: `${account.name}@${input.apex}`, revoked },
366
+ after: null,
367
+ message: `${revoked.length === 0
368
+ ? `${account.name}@${input.apex} had no app passwords to revoke.`
369
+ : `Every app password on ${account.name}@${input.apex} (${revoked.length}) no longer works. Any mail client using one will be asked to sign in again.`}${lost}`,
370
+ });
371
+ }
325
372
  /**
326
373
  * Stop one API key working. The secret is never read, here or anywhere
327
374
  * else: the entry is identified by its id and the surviving entries go back
@@ -27,6 +27,9 @@ export declare const POSTMASTER_AUDIT_EVENTS: {
27
27
  readonly 'mail.app_password_revoked': {
28
28
  readonly tenantVisible: true;
29
29
  };
30
+ readonly 'mail.app_passwords_revoked': {
31
+ readonly tenantVisible: true;
32
+ };
30
33
  readonly 'mail.api_key_revoked': {
31
34
  readonly tenantVisible: true;
32
35
  };
@@ -13,6 +13,7 @@ export const POSTMASTER_AUDIT_EVENTS = {
13
13
  'mail.alias_added': { tenantVisible: true },
14
14
  'mail.alias_removed': { tenantVisible: true },
15
15
  'mail.app_password_revoked': { tenantVisible: true },
16
+ 'mail.app_passwords_revoked': { tenantVisible: true },
16
17
  'mail.api_key_revoked': { tenantVisible: true },
17
18
  'mail.holding_enabled': { tenantVisible: true },
18
19
  'mail.spam_settings_updated': { tenantVisible: true },
@@ -20,10 +20,11 @@ export { loadOverview } from './load.js';
20
20
  export { FUTURE_RELEASE, applyObjects, mailObjects, platformMailSettingsObjects, ref, type MailObjectsInput, type PlannedObject, type PlatformMailSettingsInput, } from './objects.js';
21
21
  export { planMailboxes, withPassword } from './mailboxes.js';
22
22
  export { overview, pickDomain, type AccountView, type CredentialSummary, type DomainView, type Managed, type Overview, type OverviewInput, type PeopleView, type Person, type WireAccount, type WireAlias, type WireDomain, type WireSystemSettings, } from './overview.js';
23
- 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';
23
+ export { MailWriteRefused, membershipIds, newAccount, newGroup, withAlias, withMembership, withoutAlias, withoutAllAppPasswords, withoutApiKey, withoutAppPassword, withoutMembership, } from './writes.js';
24
+ export { addAlias, addToGroup, createGroupMailbox, createMailbox, enableHolding, holdLimit, purgeQueuedMessage, removeAlias, removeFromGroup, retryQueuedMessage, revokeAllAppPasswords, revokeApiKey, revokeAppPassword, spamSettings, updateSpamSettings, type Applied, type SpamSettingsInput, type SpamSettingsView, } from './apply.js';
25
25
  export { loadQueue, queueMessageView, type QueueMessage, type QueueRecipient, type QueueRecipientState, } from './queue.js';
26
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 { TAKEOUT_MAX_BYTES, mailTakeoutPlan, type MailTakeoutOptions, type MailTakeoutPlan, } from './mail-takeout.js';
29
30
  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';
@@ -20,10 +20,11 @@ export { loadOverview } from './load.js';
20
20
  export { FUTURE_RELEASE, applyObjects, mailObjects, platformMailSettingsObjects, ref, } from './objects.js';
21
21
  export { planMailboxes, withPassword } from './mailboxes.js';
22
22
  export { overview, pickDomain, } from './overview.js';
23
- 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';
23
+ export { MailWriteRefused, membershipIds, newAccount, newGroup, withAlias, withMembership, withoutAlias, withoutAllAppPasswords, withoutApiKey, withoutAppPassword, withoutMembership, } from './writes.js';
24
+ export { addAlias, addToGroup, createGroupMailbox, createMailbox, enableHolding, holdLimit, purgeQueuedMessage, removeAlias, removeFromGroup, retryQueuedMessage, revokeAllAppPasswords, revokeApiKey, revokeAppPassword, spamSettings, updateSpamSettings, } from './apply.js';
25
25
  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 { TAKEOUT_MAX_BYTES, mailTakeoutPlan, } from './mail-takeout.js';
29
30
  export { OrgMailExportRefused, accountsOnDomain, orgMailBackupPlan, orgMailRestorePlan, } from './org-mail-export.js';
@@ -105,6 +105,10 @@
105
105
  * `impersonate` rather than trying to pre-arrange per-account ACL shares.
106
106
  */
107
107
  export type MailCopyProvider = 'google' | 'microsoft';
108
+ /** The env var name every bare `--auth-bearer` resolves (`src/secret.rs:12-30`).
109
+ * Named once so the import and export sides are visibly the same
110
+ * variable, not two names that happen to collide. */
111
+ export declare const VANDELAY_TOKEN = "VANDELAY_TOKEN";
108
112
  export declare class MailCopyPlanRefused extends Error {
109
113
  }
110
114
  export interface MailCopyAccount {
@@ -121,7 +125,7 @@ export interface MailCopyOptions {
121
125
  readonly provider: MailCopyProvider;
122
126
  readonly accounts: readonly MailCopyAccount[];
123
127
  /** The Stalwart JMAP base URL `export --url` writes to, e.g.
124
- * `https://mail.wtfalch.dev`. */
128
+ * `https://mail.companyincluded.com`. */
125
129
  readonly stalwartUrl: string;
126
130
  /** Directory holding one Vandelay SQLite archive per account. */
127
131
  readonly archiveDir: string;
@@ -146,6 +150,13 @@ export interface MailCopyPlan {
146
150
  readonly provider: MailCopyProvider;
147
151
  readonly accounts: readonly MailCopyAccountPlan[];
148
152
  }
153
+ /** `--account-id=<id>` or `--account-name=<name>`, refusing both or
154
+ * neither rather than silently preferring one — the same exactly-one rule
155
+ * Vandelay's own `export` enforces with an `ArgGroup` (`src/cli.rs:301`).
156
+ * The `=` form, rather than two argv elements, so a value starting with
157
+ * `-` (an id or name clap would otherwise mistake for another flag) still
158
+ * parses as this flag's value. */
159
+ export declare function accountSelectorArgv(account: MailCopyAccount): string;
149
160
  /**
150
161
  * The Vandelay commands foundry runs to copy every account of one org's old
151
162
  * mail from `input.provider` into Stalwart: one `import imap` and one
@@ -119,7 +119,7 @@ const IMAP_URL = {
119
119
  /** The env var name every bare `--auth-bearer` resolves (`src/secret.rs:12-30`).
120
120
  * Named once so the import and export sides are visibly the same
121
121
  * variable, not two names that happen to collide. */
122
- const VANDELAY_TOKEN = 'VANDELAY_TOKEN';
122
+ export const VANDELAY_TOKEN = 'VANDELAY_TOKEN';
123
123
  export class MailCopyPlanRefused extends Error {
124
124
  }
125
125
  /** A very small email shape check: exactly one `@`, something on both
@@ -159,7 +159,7 @@ function archiveFileName(source) {
159
159
  * The `=` form, rather than two argv elements, so a value starting with
160
160
  * `-` (an id or name clap would otherwise mistake for another flag) still
161
161
  * parses as this flag's value. */
162
- function accountSelectorArgv(account) {
162
+ export function accountSelectorArgv(account) {
163
163
  const { targetAccountId, targetAccountName } = account;
164
164
  if (targetAccountId && targetAccountName) {
165
165
  throw new MailCopyPlanRefused(`${account.source} names both a target account id and a target account name; export takes exactly one`);
@@ -0,0 +1,31 @@
1
+ import type { MailCopyEnv } from './mail-copy.js';
2
+ /** The largest archive accepted: 50 GiB. A Takeout over this is split by
3
+ * Google into several archives anyway. */
4
+ export declare const TAKEOUT_MAX_BYTES: number;
5
+ export interface MailTakeoutOptions {
6
+ /** Absolute path to the uploaded `.mbox`, under `uploadDir`, alone in its
7
+ * own directory. */
8
+ readonly mboxPath: string;
9
+ /** Its size in bytes, as the caller measured it. */
10
+ readonly sizeBytes: number;
11
+ /** The directory uploads live under. */
12
+ readonly uploadDir: string;
13
+ /** Directory holding the Vandelay SQLite archive. */
14
+ readonly archiveDir: string;
15
+ readonly stalwartUrl: string;
16
+ readonly targetAccountId?: string;
17
+ readonly targetAccountName?: string;
18
+ /** The export credential's value, when the caller has it in hand. Never
19
+ * placed in argv; only used to redact it from a refusal message and to
20
+ * refuse an input that contains it. */
21
+ readonly exportToken?: string;
22
+ }
23
+ export interface MailTakeoutPlan {
24
+ readonly archive: string;
25
+ readonly importArgv: readonly string[];
26
+ /** Import needs no credential. */
27
+ readonly importEnv: readonly MailCopyEnv[];
28
+ readonly exportArgv: readonly string[];
29
+ readonly exportEnv: readonly MailCopyEnv[];
30
+ }
31
+ export declare function mailTakeoutPlan(input: MailTakeoutOptions): MailTakeoutPlan;
@@ -0,0 +1,113 @@
1
+ /**
2
+ * The exact Vandelay command lines foundry runs to import one uploaded
3
+ * Google Takeout mbox archive into one Stalwart account (`wtfalch/email#152`).
4
+ * Like `./mail-copy.ts` it only decides argv: it never spawns Vandelay,
5
+ * touches a network or reads a credential.
6
+ *
7
+ * **Source** (`stalwartlabs/vandelay` commit
8
+ * `42f7c879115cd2179eff067f01ac14cdc4fad0ec`): `import takeout [--noautomap]
9
+ * <PATH> <ARCHIVE>` (`src/cli.rs:662-686`). `PATH` is a *directory tree*
10
+ * scanned recursively for `.mbox`/`.ics`/`.vcf` files
11
+ * (`src/sync/import_takeout/walk.rs:56-130`); a file path is not read. So
12
+ * this plans `PATH` as the mbox's parent directory, and the caller must
13
+ * keep each upload in a directory of its own, or a neighbour's mbox would
14
+ * import into this account. Import then export, two launches, exactly as in
15
+ * `mailCopyPlan`; export is the same step with the same rules: the
16
+ * credential is only named in `exportEnv`, never in argv.
17
+ *
18
+ * **Labels.** Vandelay reads Gmail's `X-Gmail-Labels` header
19
+ * (`src/sync/import_takeout/labels.rs`): each label becomes a mailbox of
20
+ * that name (`Archived` becomes `Archive`); with automap on (the default,
21
+ * kept here) `Inbox`, `Sent`, `Drafts`, `Trash`, `Spam` and `Archive` get
22
+ * the Stalwart roles inbox/sent/drafts/trash/junk/archive; `Starred`,
23
+ * `Important` and `Opened` become the `$flagged`, `$important` and `$seen`
24
+ * keywords; `Category …` labels are dropped. The spike on #148 could not be
25
+ * read from here, so this follows the Vandelay source alone.
26
+ */
27
+ import { MailCopyPlanRefused, VANDELAY_TOKEN, accountSelectorArgv } from './mail-copy.js';
28
+ /** The largest archive accepted: 50 GiB. A Takeout over this is split by
29
+ * Google into several archives anyway. */
30
+ export const TAKEOUT_MAX_BYTES = 50 * 1024 ** 3;
31
+ function cleanDir(value, what) {
32
+ const dir = value.trim().replace(/\/+$/, '');
33
+ if (!dir.startsWith('/'))
34
+ throw new MailCopyPlanRefused(`${what} must be an absolute path`);
35
+ return dir;
36
+ }
37
+ export function mailTakeoutPlan(input) {
38
+ const token = input.exportToken;
39
+ const redact = (text) => (token ? text.split(token).join('[redacted]') : text);
40
+ const refuse = (message) => {
41
+ throw new MailCopyPlanRefused(redact(message));
42
+ };
43
+ if (token) {
44
+ const fields = [
45
+ input.mboxPath,
46
+ input.uploadDir,
47
+ input.archiveDir,
48
+ input.stalwartUrl,
49
+ input.targetAccountId ?? '',
50
+ input.targetAccountName ?? '',
51
+ ];
52
+ if (fields.some((field) => field.includes(token))) {
53
+ refuse('the export token appears in the input; it belongs only in the environment');
54
+ }
55
+ }
56
+ const uploadDir = cleanDir(input.uploadDir, 'the upload directory');
57
+ const archiveDir = cleanDir(input.archiveDir, 'the archive directory');
58
+ const path = input.mboxPath.trim();
59
+ if ([...path].some((char) => char.charCodeAt(0) < 0x20 || char.charCodeAt(0) === 0x7f))
60
+ refuse('the archive path holds a control character');
61
+ if (path.split('/').some((part) => part === '.' || part === '..')) {
62
+ refuse(`"${path}" must not contain "." or ".." segments`);
63
+ }
64
+ if (path.includes('//'))
65
+ refuse(`"${path}" must not contain empty path segments`);
66
+ if (!path.startsWith(`${uploadDir}/`) || !/\.mbox$/.test(path)) {
67
+ refuse(`"${path}" must be a .mbox file under ${uploadDir}`);
68
+ }
69
+ const dir = path.slice(0, path.lastIndexOf('/'));
70
+ if (dir === uploadDir) {
71
+ refuse(`"${path}" must sit in its own directory under ${uploadDir}, not in it`);
72
+ }
73
+ if (!Number.isSafeInteger(input.sizeBytes) || input.sizeBytes <= 0) {
74
+ refuse(`the archive size must be a positive whole number of bytes, got ${input.sizeBytes}`);
75
+ }
76
+ if (input.sizeBytes > TAKEOUT_MAX_BYTES) {
77
+ refuse(`the archive is ${input.sizeBytes} bytes; the limit is ${TAKEOUT_MAX_BYTES}`);
78
+ }
79
+ const stalwartUrl = input.stalwartUrl.trim().replace(/\/+$/, '');
80
+ if (!/^https:\/\//.test(stalwartUrl)) {
81
+ refuse(`the Stalwart URL must be https, got "${input.stalwartUrl}"`);
82
+ }
83
+ let parsed;
84
+ try {
85
+ parsed = new URL(stalwartUrl);
86
+ }
87
+ catch {
88
+ return refuse(`"${input.stalwartUrl}" is not a valid URL`);
89
+ }
90
+ if (parsed.username || parsed.password) {
91
+ refuse('the Stalwart URL must not carry embedded credentials; use --auth-bearer instead');
92
+ }
93
+ let accountFlag;
94
+ try {
95
+ accountFlag = accountSelectorArgv({
96
+ source: path,
97
+ targetAccountId: input.targetAccountId,
98
+ targetAccountName: input.targetAccountName,
99
+ });
100
+ }
101
+ catch (error) {
102
+ return refuse(error instanceof Error ? error.message : String(error));
103
+ }
104
+ const target = input.targetAccountId ?? input.targetAccountName ?? '';
105
+ const archive = `${archiveDir}/takeout-${encodeURIComponent(target)}.sqlite`;
106
+ return {
107
+ archive,
108
+ importArgv: ['import', 'takeout', '--', dir, archive],
109
+ importEnv: [],
110
+ exportArgv: ['export', '--url', stalwartUrl, '--auth-bearer', accountFlag, '--', archive],
111
+ exportEnv: [{ name: VANDELAY_TOKEN, purpose: `the Stalwart account credential for ${target}` }],
112
+ };
113
+ }
@@ -108,7 +108,7 @@ export interface OrgMailExportEnv {
108
108
  }
109
109
  export interface OrgMailBackupOptions {
110
110
  readonly accounts: readonly OrgMailExportAccount[];
111
- /** The shared Stalwart instance being backed up, e.g. `https://mail.wtfalch.dev`. */
111
+ /** The shared Stalwart instance being backed up, e.g. `https://mail.companyincluded.com`. */
112
112
  readonly stalwartUrl: string;
113
113
  /** Directory to hold one Vandelay SQLite archive per account. */
114
114
  readonly archiveDir: string;
@@ -149,7 +149,7 @@ export interface OrgMailRestoreAccount {
149
149
  export interface OrgMailRestoreOptions {
150
150
  readonly accounts: readonly OrgMailRestoreAccount[];
151
151
  /** The — possibly different — shared Stalwart instance being restored
152
- * into, e.g. `https://mail.wtfalch.dev`. */
152
+ * into, e.g. `https://mail.companyincluded.com`. */
153
153
  readonly stalwartUrl: string;
154
154
  /** The same directory `orgMailBackupPlan` wrote into: restore reads the
155
155
  * archive a backup already produced, it never creates one. */
@@ -41,6 +41,19 @@ export declare function withoutAlias(account: Pick<WireAccount, 'aliases'>, name
41
41
  * relies on.
42
42
  */
43
43
  export declare function withoutAppPassword(account: Pick<WireAccount, 'credentials'>, credentialId: string): Record<string, Credential>;
44
+ /**
45
+ * The `credentials` list to send so that every app password on the account
46
+ * stops working at once, used when a person must be shut out of mail
47
+ * immediately: IMAP and SMTP never consult the issuer, so a revoked sign-in
48
+ * there does nothing while an app password it minted keeps authenticating.
49
+ *
50
+ * Same type guard as `withoutAppPassword`, applied to every entry rather
51
+ * than one: `Password` and `ApiKey` entries are never this action's to
52
+ * touch and survive untouched, masked secrets and all. An account with no
53
+ * app password at all is not refused — there is nothing to revoke, and the
54
+ * empty list it already has is exactly what gets sent back.
55
+ */
56
+ export declare function withoutAllAppPasswords(account: Pick<WireAccount, 'credentials'>): Record<string, Credential>;
44
57
  /**
45
58
  * The `credentials` list to send so that one API key stops working and
46
59
  * every other credential survives.
@@ -63,7 +76,7 @@ export declare function withoutApiKey(account: Pick<WireAccount, 'credentials'>,
63
76
  * **No credential, ever.** On a domain the issuer holds (`directoryId` set,
64
77
  * which is every domain `mail-configure --mail-audience` has touched) the
65
78
  * server refuses one anyway and the person signs in through
66
- * auth.wtfalch.dev. On a domain with the instance's own directory a new
79
+ * auth.companyincluded.com. On a domain with the instance's own directory a new
67
80
  * account needs a first password, which `mail:sync` prints once to a
68
81
  * terminal — a web page is the wrong place to show a secret and a worse
69
82
  * place to store one, so this refuses that case and says which tool does it.
@@ -94,6 +94,22 @@ export function withoutAppPassword(account, credentialId) {
94
94
  }
95
95
  return indexed(existing.filter((c) => c !== target));
96
96
  }
97
+ /**
98
+ * The `credentials` list to send so that every app password on the account
99
+ * stops working at once, used when a person must be shut out of mail
100
+ * immediately: IMAP and SMTP never consult the issuer, so a revoked sign-in
101
+ * there does nothing while an app password it minted keeps authenticating.
102
+ *
103
+ * Same type guard as `withoutAppPassword`, applied to every entry rather
104
+ * than one: `Password` and `ApiKey` entries are never this action's to
105
+ * touch and survive untouched, masked secrets and all. An account with no
106
+ * app password at all is not refused — there is nothing to revoke, and the
107
+ * empty list it already has is exactly what gets sent back.
108
+ */
109
+ export function withoutAllAppPasswords(account) {
110
+ const existing = entriesOf(account.credentials);
111
+ return indexed(existing.filter((c) => c['@type'] !== 'AppPassword'));
112
+ }
97
113
  /**
98
114
  * The `credentials` list to send so that one API key stops working and
99
115
  * every other credential survives.
@@ -126,7 +142,7 @@ export function withoutApiKey(account, credentialId) {
126
142
  * **No credential, ever.** On a domain the issuer holds (`directoryId` set,
127
143
  * which is every domain `mail-configure --mail-audience` has touched) the
128
144
  * server refuses one anyway and the person signs in through
129
- * auth.wtfalch.dev. On a domain with the instance's own directory a new
145
+ * auth.companyincluded.com. On a domain with the instance's own directory a new
130
146
  * account needs a first password, which `mail:sync` prints once to a
131
147
  * terminal — a web page is the wrong place to show a secret and a worse
132
148
  * place to store one, so this refuses that case and says which tool does it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/email",
3
- "version": "0.21.0",
3
+ "version": "0.24.0",
4
4
  "description": "The wtfalch estate: reading a mailbox over JMAP, administering the Stalwart server it lives on, and iTIP scheduling over iMIP. Three entries with no code in common.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -17,10 +17,6 @@
17
17
  "types": "./dist/mailbox/react/index.d.ts",
18
18
  "default": "./dist/mailbox/react/index.js"
19
19
  },
20
- "./mailbox/fake": {
21
- "types": "./dist/mailbox/fake/index.d.ts",
22
- "default": "./dist/mailbox/fake/index.js"
23
- },
24
20
  "./mailbox/mail.css": "./dist/mailbox/mail.css",
25
21
  "./imip": {
26
22
  "types": "./dist/imip/index.d.ts",
@@ -1,34 +0,0 @@
1
- /**
2
- * A mailbox in memory, for stories, for a development build with no server,
3
- * and for tests that want to exercise this package rather than a stub.
4
- *
5
- * ```ts
6
- * import { fakeMail } from '@wtfalch/email/mailbox/fake'
7
- *
8
- * const { client, mailbox, dispose } = fakeMail()
9
- * const tree = await mailboxes(client) // the real function
10
- * ```
11
- */
12
- import { MailClient } from '../client.ts';
13
- import { FakeMailbox, type FakeOptions, type SeedMessage, type SeedPrincipal, type SeedThread } from './mailbox.ts';
14
- import { SAMPLE } from './sample.ts';
15
- export { FakeMailbox };
16
- export type { FakeOptions, SeedMessage, SeedPrincipal, SeedThread };
17
- export { SAMPLE };
18
- export type FakeMail = {
19
- /** A real `MailClient`. Everything this package exports works against it
20
- * unchanged, through the real wire code. */
21
- client: MailClient;
22
- /** The mailbox behind it, to seed more mail or to assert on what was sent. */
23
- mailbox: FakeMailbox;
24
- /** Stop intercepting. Call it when a story or a test is done; leaving it
25
- * installed leaves the fake answering for the rest of the process. */
26
- dispose: () => void;
27
- };
28
- /**
29
- * A client and the mailbox it talks to.
30
- *
31
- * Seeded with `SAMPLE` unless told otherwise, because a fake with an empty
32
- * inbox demonstrates the empty state and nothing else.
33
- */
34
- export declare function fakeMail(options?: FakeOptions): FakeMail;