@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
@@ -0,0 +1,117 @@
1
+ import type { StalwartClient } from './client.js';
2
+ /**
3
+ * One org's mail on the one shared Stalwart server (foundry issue #7,
4
+ * `wtfalch/email#96`): give it a `Domain`, change its mode, or park it —
5
+ * never a second Stalwart, never a per-org instance.
6
+ *
7
+ * **What this does and does not touch.** The shared instance itself —
8
+ * `AcmeProvider`, `DnsServer`, the Resend relay, `SystemSettings` — is
9
+ * provisioned once, by `mailObjects`/`applyObjects` in `./objects.ts`. This
10
+ * module only upserts the one `Domain` object an org needs on top of that,
11
+ * confirmed against `stalwartlabs/stalwart` at commit
12
+ * `02503015580abd6706923d34e9d8e501e76f8634`:
13
+ * `crates/registry/src/schema/structs.rs:2696-2731` is `struct Domain`, whose
14
+ * `isEnabled` (line 2703-2704, `#[serde(rename = "isEnabled")] pub is_enabled:
15
+ * bool`) is the one field `parkOrgMail` writes, and whose
16
+ * `certificateManagement`/`dnsManagement`/`dkimManagement` (lines 2711-2716)
17
+ * are the same three `@type`-tagged blocks `mailObjects` already writes on
18
+ * the instance-level `Domain` object.
19
+ *
20
+ * **`certificateManagement` and `dnsManagement` are `Manual` here on
21
+ * purpose.** `Automatic` on either would have Stalwart call Cloudflare
22
+ * itself (`DnsManagementProperties.dns_server_id`, same file, lines
23
+ * 1311-1320) — but the campaign ledger's non-goals say foundry owns
24
+ * Cloudflare, so this API only *returns* the records foundry must publish
25
+ * and never calls a DNS provider. `dkimManagement` stays `Automatic`
26
+ * (`DkimManagement::Automatic`, lines 998-1016): Stalwart still mints and
27
+ * rotates the signing key itself, on its own background task
28
+ * (`crates/jmap/src/registry/mapping/domain.rs:102-133`, `will_trigger_dkim`
29
+ * queues `Task::DkimManagement` whenever a domain's `dkimManagement` becomes
30
+ * `Automatic`) — this module only reads the key back.
31
+ *
32
+ * **The management API can read back what a domain needs published**,
33
+ * settling the one open question task B step 1 was for. `x:Domain/get`
34
+ * computes an extra `dnsZoneFile` property whenever the caller's
35
+ * `properties` list is empty or names it —
36
+ * `crates/jmap/src/registry/get.rs:297-304` — by calling
37
+ * `Server::build_bind_dns_records` (`crates/common/src/network/dns/records.rs:357-382`),
38
+ * which serializes DKIM, MX, SPF, DMARC, TLS-RPT, CAA and more as a BIND
39
+ * zone file (`stalwartlabs/dns-update`'s `BindSerializer::serialize`,
40
+ * `src/bind.rs:17-78` at commit `40e94d85bdbdeeb3a13d4ac8e84a33de5baa6b49`).
41
+ * `StalwartClient.get` already sends no `properties` argument, so the
42
+ * `dnsZoneFile` text comes back on every plain `Domain` read for free.
43
+ *
44
+ * Only the `_domainkey` lines are worth reading back, because MX and SPF are
45
+ * fully derivable from `apex`/`mailHost` without a round trip — this is the
46
+ * "return the records you can derive" fallback the task brief names, applied
47
+ * unconditionally rather than only when the read fails. DKIM's record name
48
+ * (`<selector>._domainkey.<domain>.`) and value (`v=DKIM1; k=rsa; h=sha256;
49
+ * p=<base64>`) come from `generate_dkim_dns_record`,
50
+ * `crates/common/src/network/dkim.rs:116-149`, same commit as the schema.
51
+ *
52
+ * **The DKIM record can be empty right after the first `applyOrgMail`.**
53
+ * `Task::DkimManagement` runs after the `Domain/set` that queued it, not
54
+ * inside it, and `build_dns_records`'s `Dkim` arm skips any signature that
55
+ * is not yet `is_published()` (`records.rs:41-58`). A caller that needs the
56
+ * key immediately should call `applyOrgMail` again a moment later — it is
57
+ * idempotent, so a repeat costs nothing beyond the read.
58
+ */
59
+ export type OrgMailMode = 'received' | 'hosted';
60
+ export interface OrgMailOrg {
61
+ readonly slug: string;
62
+ /** Absent for a level-1 org: its domain is `${slug}.${apex}` and its mode must be `hosted`. */
63
+ readonly domain?: string;
64
+ readonly mode: OrgMailMode;
65
+ }
66
+ export interface OrgMailOptions {
67
+ /** The shared mail apex a level-1 org's domain is built under, e.g. `wtfalch.dev`. */
68
+ readonly apex: string;
69
+ /** The MX target and TLS name every domain on this instance shares, e.g. `mail.wtfalch.dev`. */
70
+ readonly mailHost: string;
71
+ }
72
+ /** One DNS record foundry must publish. `priority` is set only for `MX`. */
73
+ export interface DnsRecordSpec {
74
+ readonly type: 'MX' | 'TXT';
75
+ /** Fully-qualified, no trailing dot — e.g. `acme.wtfalch.dev` or `selector1._domainkey.acme.wtfalch.dev`. */
76
+ readonly name: string;
77
+ readonly value: string;
78
+ readonly priority?: number;
79
+ }
80
+ export interface OrgMailResult {
81
+ readonly domain: string;
82
+ readonly records: readonly DnsRecordSpec[];
83
+ }
84
+ /**
85
+ * The `_domainkey` TXT records inside a `dnsZoneFile` BIND zone, as
86
+ * `x:Domain/get` returns it. Every other record type in the zone (MX, SPF,
87
+ * DMARC, TLS-RPT, CAA, autoconfig, …) is derived instead of read back, so
88
+ * this reads only the lines whose name contains `._domainkey.`.
89
+ *
90
+ * Handles both shapes `BindSerializer::serialize` emits
91
+ * (`stalwartlabs/dns-update`'s `src/bind.rs:44-56`, commit
92
+ * `40e94d85bdbdeeb3a13d4ac8e84a33de5baa6b49`): a short value on one line
93
+ * (`name IN TXT "value"`), and a value over 255 bytes — every RSA DKIM key
94
+ * — split into a parenthesized block of quoted chunks that this
95
+ * reassembles in order.
96
+ */
97
+ export declare function dkimRecordsFromZoneFile(zoneFile: string): DnsRecordSpec[];
98
+ /**
99
+ * Give an org mail, change its mode, or re-enable a parked one — all the
100
+ * same call. Idempotent: the `Domain` is upserted by `name`, so calling this
101
+ * twice with the same org leaves exactly one `Domain`, and calling it again
102
+ * with a different `mode` changes only the records this returns, never a
103
+ * second `Domain`.
104
+ *
105
+ * Returns the DNS records foundry must publish. This never calls Cloudflare
106
+ * itself — that stays foundry's, by the campaign's non-goals.
107
+ */
108
+ export declare function applyOrgMail(client: StalwartClient, org: OrgMailOrg, options: OrgMailOptions): Promise<OrgMailResult>;
109
+ /**
110
+ * Stop a domain receiving, keeping every mailbox and message — foundry#7's
111
+ * "park keeps mail, never deletes it". Touches only the `Domain`'s
112
+ * `isEnabled`; no `Account`, no message, ever.
113
+ *
114
+ * A no-op, not a refusal, for an org this instance has never heard of or one
115
+ * already parked: neither sends a request.
116
+ */
117
+ export declare function parkOrgMail(client: StalwartClient, org: OrgMailOrg, options: OrgMailOptions): Promise<void>;
@@ -0,0 +1,206 @@
1
+ import { MailWriteRefused } from './writes.js';
2
+ /** A lowercase DNS label: RFC 1035, minus the wire's own length limit — this
3
+ * refuses on shape, not on how long a name can get. */
4
+ const DNS_LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
5
+ function assertLabel(what, value) {
6
+ if (!DNS_LABEL.test(value)) {
7
+ throw new MailWriteRefused(`${what} "${value}" must be a lowercase DNS label`);
8
+ }
9
+ }
10
+ function assertDomain(value) {
11
+ const labels = value.split('.');
12
+ if (labels.length < 2 || labels.some((label) => !DNS_LABEL.test(label))) {
13
+ throw new MailWriteRefused(`"${value}" is not a valid lowercase domain name`);
14
+ }
15
+ }
16
+ /**
17
+ * The `Domain` name this org's mail lives on. Refuses before any request: an
18
+ * org with no domain of its own is level 1, and foundry#7's "Level 1 gets
19
+ * `@acme.wtfalch.dev`" fixes both what the name is and that it can only ever
20
+ * be `hosted` — a level-1 org has nowhere else for mail to be `received` at.
21
+ */
22
+ function resolveDomain(org, options) {
23
+ assertLabel('an org slug', org.slug);
24
+ if (!org.domain) {
25
+ if (org.mode !== 'hosted') {
26
+ throw new MailWriteRefused(`${org.slug} has no domain of its own, so it is level 1 on ${options.apex} and its mode must be "hosted"; "received" needs a domain elsewhere to keep receiving mail`);
27
+ }
28
+ return `${org.slug}.${options.apex}`;
29
+ }
30
+ assertDomain(org.domain);
31
+ return org.domain;
32
+ }
33
+ /**
34
+ * MX and SPF, fully derivable from `apex`/`mailHost` with no round trip.
35
+ *
36
+ * `hosted`: Stalwart holds the MX, so SPF's `mx` mechanism resolves to it
37
+ * exactly the way Stalwart's own `build_dns_records` composes it for a
38
+ * self-hosted MX (`DnsRecordType::Spf`, `records.rs:74-95`: `"v=spf1 mx
39
+ * -all"`).
40
+ *
41
+ * `received`: the MX stays with Google or Microsoft, so `mx` would
42
+ * authorise *their* servers, not Stalwart's dual-delivery sender. The org's
43
+ * own SPF record needs an explicit `include:` of the shared mail host
44
+ * instead, and no MX record is returned at all — foundry must not touch the
45
+ * existing one.
46
+ */
47
+ function mxAndSpf(domain, mode, options) {
48
+ if (mode === 'hosted') {
49
+ return [
50
+ { type: 'MX', name: domain, value: options.mailHost, priority: 10 },
51
+ { type: 'TXT', name: domain, value: 'v=spf1 mx -all' },
52
+ ];
53
+ }
54
+ return [{ type: 'TXT', name: domain, value: `v=spf1 include:${options.mailHost} -all` }];
55
+ }
56
+ function unescapeTxt(s) {
57
+ return s.replace(/\\"/g, '"').replace(/\\\\/g, '\\');
58
+ }
59
+ function stripTrailingDot(name) {
60
+ return name.endsWith('.') ? name.slice(0, -1) : name;
61
+ }
62
+ /**
63
+ * The `_domainkey` TXT records inside a `dnsZoneFile` BIND zone, as
64
+ * `x:Domain/get` returns it. Every other record type in the zone (MX, SPF,
65
+ * DMARC, TLS-RPT, CAA, autoconfig, …) is derived instead of read back, so
66
+ * this reads only the lines whose name contains `._domainkey.`.
67
+ *
68
+ * Handles both shapes `BindSerializer::serialize` emits
69
+ * (`stalwartlabs/dns-update`'s `src/bind.rs:44-56`, commit
70
+ * `40e94d85bdbdeeb3a13d4ac8e84a33de5baa6b49`): a short value on one line
71
+ * (`name IN TXT "value"`), and a value over 255 bytes — every RSA DKIM key
72
+ * — split into a parenthesized block of quoted chunks that this
73
+ * reassembles in order.
74
+ */
75
+ export function dkimRecordsFromZoneFile(zoneFile) {
76
+ const records = [];
77
+ const lines = zoneFile.split('\n');
78
+ for (let i = 0; i < lines.length; i++) {
79
+ const line = lines[i] ?? '';
80
+ const single = /^(\S+)\s+IN\s+TXT\s+"((?:[^"\\]|\\.)*)"\s*$/.exec(line);
81
+ if (single) {
82
+ const [, name, value] = single;
83
+ if (name?.includes('._domainkey.')) {
84
+ records.push({
85
+ type: 'TXT',
86
+ name: stripTrailingDot(name),
87
+ value: unescapeTxt(value ?? ''),
88
+ });
89
+ }
90
+ continue;
91
+ }
92
+ const blockStart = /^(\S+)\s+IN\s+TXT\s+\($/.exec(line);
93
+ if (blockStart) {
94
+ const name = blockStart[1] ?? '';
95
+ const chunks = [];
96
+ let j = i + 1;
97
+ while (j < lines.length && lines[j]?.trim() !== ')') {
98
+ const chunk = /^\s*"((?:[^"\\]|\\.)*)"\s*$/.exec(lines[j] ?? '');
99
+ if (chunk?.[1] !== undefined)
100
+ chunks.push(unescapeTxt(chunk[1]));
101
+ j++;
102
+ }
103
+ if (name.includes('._domainkey.')) {
104
+ records.push({ type: 'TXT', name: stripTrailingDot(name), value: chunks.join('') });
105
+ }
106
+ i = j;
107
+ }
108
+ }
109
+ return records;
110
+ }
111
+ /** The `Domain` value this module writes: `isEnabled` and the three
112
+ * management blocks. `name` travels alongside so a caller can spread this
113
+ * straight into a create, and is excluded from the patch an update sends
114
+ * (the same immutable-match-property rule `applyObjects` follows). */
115
+ function domainValue(domain) {
116
+ return {
117
+ name: domain,
118
+ isEnabled: true,
119
+ certificateManagement: { '@type': 'Manual' },
120
+ dnsManagement: { '@type': 'Manual' },
121
+ dkimManagement: { '@type': 'Automatic' },
122
+ };
123
+ }
124
+ /**
125
+ * The org's `Domain`, found by an exact, server-side filter on `name` —
126
+ * never by listing and scanning every `Domain` on the instance.
127
+ *
128
+ * `client.list` (and so `client.upsert`, which is built on it) calls
129
+ * `x:Domain/query` with no filter at all, which Stalwart caps at
130
+ * `query_max_results` (5000 by default) and never pages past
131
+ * (`crates/jmap/src/registry/query.rs:241-250`,
132
+ * `crates/registry/src/schema/structs_impl.rs:23113` for the default, both
133
+ * at `02503015580abd6706923d34e9d8e501e76f8634`). An instance with more
134
+ * `Domain`s than that would put some past the first page, where a lookup
135
+ * built on `list`/`upsert` would miss an existing one and create a second
136
+ * `Domain` with the same name — this is why `applyOrgMail`/`parkOrgMail` use
137
+ * this filtered lookup instead of `client.upsert`.
138
+ *
139
+ * `ObjectType::Domain`'s `name` index is declared `IndexSchemaType::Unique`
140
+ * / `IndexSchemaValueType::Keyword`
141
+ * (`crates/registry/src/schema/properties_impl.rs:3489-3493`), and a
142
+ * `Keyword` index accepts an exact-match filter
143
+ * (`crates/jmap/src/registry/query.rs:190-193`), sent as a flat
144
+ * `filter: {"name": "…"}` object — a bare property name in the filter is
145
+ * `RegistryFilterOperator::Equal` (`crates/jmap-proto/src/object/registry.rs:123-135`),
146
+ * and a single-key filter object needs no `operator`/`conditions` wrapper
147
+ * (`crates/jmap-proto/src/method/query.rs:214-260`). That filter is
148
+ * evaluated server-side and matches at most one `Domain` — `name` is
149
+ * unique — so it is correct regardless of how many Domains the instance
150
+ * holds or which page this one would fall on.
151
+ */
152
+ async function findDomain(client, domain) {
153
+ const { ids } = await client.call('x:Domain/query', {
154
+ filter: { name: domain },
155
+ });
156
+ const id = ids?.[0];
157
+ if (!id)
158
+ return undefined;
159
+ const [wire] = await client.get('Domain', [id]);
160
+ return wire;
161
+ }
162
+ /**
163
+ * Give an org mail, change its mode, or re-enable a parked one — all the
164
+ * same call. Idempotent: the `Domain` is upserted by `name`, so calling this
165
+ * twice with the same org leaves exactly one `Domain`, and calling it again
166
+ * with a different `mode` changes only the records this returns, never a
167
+ * second `Domain`.
168
+ *
169
+ * Returns the DNS records foundry must publish. This never calls Cloudflare
170
+ * itself — that stays foundry's, by the campaign's non-goals.
171
+ */
172
+ export async function applyOrgMail(client, org, options) {
173
+ const domain = resolveDomain(org, options);
174
+ const value = domainValue(domain);
175
+ const patch = Object.fromEntries(Object.entries(value).filter(([k]) => k !== 'name'));
176
+ const existing = await findDomain(client, domain);
177
+ let id;
178
+ if (existing) {
179
+ await client.update('Domain', existing.id, patch);
180
+ id = existing.id;
181
+ }
182
+ else {
183
+ id = await client.create('Domain', value);
184
+ }
185
+ const [wire] = await client.get('Domain', [id]);
186
+ const records = [
187
+ ...mxAndSpf(domain, org.mode, options),
188
+ ...dkimRecordsFromZoneFile(wire?.dnsZoneFile ?? ''),
189
+ ];
190
+ return { domain, records };
191
+ }
192
+ /**
193
+ * Stop a domain receiving, keeping every mailbox and message — foundry#7's
194
+ * "park keeps mail, never deletes it". Touches only the `Domain`'s
195
+ * `isEnabled`; no `Account`, no message, ever.
196
+ *
197
+ * A no-op, not a refusal, for an org this instance has never heard of or one
198
+ * already parked: neither sends a request.
199
+ */
200
+ export async function parkOrgMail(client, org, options) {
201
+ const domain = resolveDomain(org, options);
202
+ const existing = await findDomain(client, domain);
203
+ if (!existing || existing.isEnabled === false)
204
+ return;
205
+ await client.update('Domain', existing.id, { isEnabled: false });
206
+ }
@@ -63,6 +63,10 @@ export interface WireAccount {
63
63
  } | null;
64
64
  credentials?: Record<string, Credential>;
65
65
  aliases?: Record<string, WireAlias>;
66
+ /** The shared mailboxes this account reads, as a set: `{"<id>": true}`.
67
+ * A group account has no such field of its own — membership lives on the
68
+ * people, not on the mailbox they share. */
69
+ memberGroupIds?: Record<string, boolean>;
66
70
  /**
67
71
  * Present and an object, but every account seen so far has it empty, so
68
72
  * the key a *set* quota uses is still unknown — hence `quotaLimit`'s list
@@ -0,0 +1,111 @@
1
+ /**
2
+ * The server's own outbound mail queue: every message Stalwart has accepted
3
+ * and not yet finished delivering, across every domain the instance serves.
4
+ *
5
+ * `submit.ts`'s `queued()` (in `@wtfalch/email/mailbox`) is a different
6
+ * thing entirely: it reads one signed-in account's own pending
7
+ * `EmailSubmission`s over the mail JMAP capability. This reads the server's
8
+ * queue itself, over the management API's `x:QueuedMessage` object — a
9
+ * message this instance relays for anyone, seen only by an administrator.
10
+ *
11
+ * The wire shape is `registry::schema::structs::QueuedMessage` on the
12
+ * server (checked against the `stalwartlabs/stalwart` source on 2026-09-22,
13
+ * the struct `tests/src/smtp/management/queue.rs` exercises with real
14
+ * requests). It is **not yet confirmed against a live 0.16.20 instance** the way
15
+ * `overview.ts`'s fixture is — nothing in this package read the mail queue
16
+ * before now — so this reads defensively and never assumes a field it
17
+ * cannot see is present.
18
+ */
19
+ import type { Instance } from './instance.js';
20
+ interface WireQueueExpiry {
21
+ '@type'?: string;
22
+ [property: string]: unknown;
23
+ }
24
+ /**
25
+ * `RecipientStatus` on the wire: `{'@type': 'Scheduled'}`,
26
+ * `{'@type': 'Completed', responseMessage, ...}`, or a
27
+ * `{'@type': 'TemporaryFailure' | 'PermanentFailure', errorType,
28
+ * errorMessage, responseMessage, ...}`. Only the fields a readable error
29
+ * sentence needs are named; the rest travels through `[property: string]`
30
+ * without ever reaching {@link QueueRecipient}.
31
+ */
32
+ interface WireRecipientStatus {
33
+ '@type'?: string;
34
+ errorType?: string;
35
+ errorMessage?: string;
36
+ responseMessage?: string;
37
+ [property: string]: unknown;
38
+ }
39
+ interface WireQueuedRecipient {
40
+ [property: string]: unknown;
41
+ retryCount?: number;
42
+ retryDue?: string;
43
+ expires?: WireQueueExpiry;
44
+ status?: WireRecipientStatus;
45
+ }
46
+ interface WireQueuedMessage {
47
+ [property: string]: unknown;
48
+ id: string;
49
+ createdAt: string;
50
+ nextRetry?: string | null;
51
+ returnPath: string;
52
+ recipients?: Record<string, WireQueuedRecipient>;
53
+ size?: number;
54
+ }
55
+ /** Collapsed from the server's four-way `RecipientStatus` tag to what an
56
+ * admin needs: still trying, landed, or stuck. */
57
+ export type QueueRecipientState = 'scheduled' | 'delivered' | 'deferred' | 'failed';
58
+ export interface QueueRecipient {
59
+ readonly address: string;
60
+ readonly state: QueueRecipientState;
61
+ readonly retryCount: number;
62
+ /** When the server will try this recipient again. `null` once it has
63
+ * delivered or permanently failed — there is nothing left to retry. */
64
+ readonly retryDue: string | null;
65
+ /** The server's account of the last attempt, for `deferred` and `failed`
66
+ * only; `null` for `scheduled` and `delivered`, which have nothing to
67
+ * explain. */
68
+ readonly lastError: string | null;
69
+ }
70
+ export interface QueueMessage {
71
+ readonly id: string;
72
+ /** The envelope sender, or `'<>'` for a bounce with none — the server's
73
+ * own placeholder for an empty return path, carried through rather than
74
+ * turned into `null` so what is shown is what SMTP actually sent. */
75
+ readonly from: string;
76
+ readonly to: readonly string[];
77
+ readonly size: number;
78
+ readonly createdAt: string;
79
+ /** The earliest a still-pending recipient will be retried, or `null` once
80
+ * every recipient has resolved — delivered, or given up on for good. */
81
+ readonly nextRetry: string | null;
82
+ readonly recipients: readonly QueueRecipient[];
83
+ }
84
+ /** Pure: the server's `QueuedMessage` as an admin table row. */
85
+ export declare function queueMessageView(wire: WireQueuedMessage): QueueMessage;
86
+ /**
87
+ * Every message still in the outbound queue.
88
+ *
89
+ * Ordered however the server's `x:QueuedMessage/get` sends its `list` back.
90
+ * With no filter and no sort, `queued_message_query` (the Rust handler)
91
+ * walks the queue's own due-time index ascending, so this comes back
92
+ * soonest-due first — the recipient that has been waiting longest sorts
93
+ * near the top, which is what an admin looking for stuck mail wants. Not
94
+ * re-sorted here: doing that would assume `get` preserves the order its own
95
+ * `query` returned, which JMAP does not promise and this package has no
96
+ * fixture to confirm either way for this object.
97
+ *
98
+ * Reading the queue needs a credential wider than the dashboard's own key
99
+ * grants: `DASHBOARD_PERMISSIONS` (in `./client.ts`) is confirmed only for
100
+ * the five `/email` mailbox operations and does not cover `QueuedMessage`.
101
+ * The permission vocabulary has `sysQueuedMessageGet`, `sysQueuedMessageQuery`,
102
+ * `sysQueuedMessageUpdate` and `sysQueuedMessageDestroy`
103
+ * (`stalwartlabs/stalwart`, `crates/registry/src/schema/enums.rs:2028-2032`,
104
+ * `Sys<Object><Verb>` matching the names `DASHBOARD_PERMISSIONS` already
105
+ * uses for other objects) — present in the source, not yet exercised
106
+ * against a live instance, so this reads and writes with an
107
+ * `'inherit'`-scoped key or the instance administrator's own credential
108
+ * until a narrower key is confirmed to work.
109
+ */
110
+ export declare function loadQueue(instance: Instance): Promise<QueueMessage[]>;
111
+ export type { WireQueuedMessage };
@@ -0,0 +1,64 @@
1
+ function recipientView(address, wire) {
2
+ const tag = wire.status?.['@type'];
3
+ const state = tag === 'Completed'
4
+ ? 'delivered'
5
+ : tag === 'PermanentFailure'
6
+ ? 'failed'
7
+ : tag === 'TemporaryFailure'
8
+ ? 'deferred'
9
+ : 'scheduled';
10
+ const lastError = state === 'deferred' || state === 'failed'
11
+ ? (wire.status?.errorMessage ??
12
+ wire.status?.responseMessage ??
13
+ wire.status?.errorType ??
14
+ 'the server did not say why')
15
+ : null;
16
+ return {
17
+ address,
18
+ state,
19
+ retryCount: typeof wire.retryCount === 'number' ? wire.retryCount : 0,
20
+ retryDue: state === 'delivered' || state === 'failed' ? null : (wire.retryDue ?? null),
21
+ lastError,
22
+ };
23
+ }
24
+ /** Pure: the server's `QueuedMessage` as an admin table row. */
25
+ export function queueMessageView(wire) {
26
+ const recipients = Object.entries(wire.recipients ?? {}).map(([address, r]) => recipientView(address, r));
27
+ return {
28
+ id: wire.id,
29
+ from: wire.returnPath || '<>',
30
+ to: recipients.map((r) => r.address),
31
+ size: typeof wire.size === 'number' ? wire.size : 0,
32
+ createdAt: wire.createdAt,
33
+ nextRetry: wire.nextRetry ?? null,
34
+ recipients,
35
+ };
36
+ }
37
+ /**
38
+ * Every message still in the outbound queue.
39
+ *
40
+ * Ordered however the server's `x:QueuedMessage/get` sends its `list` back.
41
+ * With no filter and no sort, `queued_message_query` (the Rust handler)
42
+ * walks the queue's own due-time index ascending, so this comes back
43
+ * soonest-due first — the recipient that has been waiting longest sorts
44
+ * near the top, which is what an admin looking for stuck mail wants. Not
45
+ * re-sorted here: doing that would assume `get` preserves the order its own
46
+ * `query` returned, which JMAP does not promise and this package has no
47
+ * fixture to confirm either way for this object.
48
+ *
49
+ * Reading the queue needs a credential wider than the dashboard's own key
50
+ * grants: `DASHBOARD_PERMISSIONS` (in `./client.ts`) is confirmed only for
51
+ * the five `/email` mailbox operations and does not cover `QueuedMessage`.
52
+ * The permission vocabulary has `sysQueuedMessageGet`, `sysQueuedMessageQuery`,
53
+ * `sysQueuedMessageUpdate` and `sysQueuedMessageDestroy`
54
+ * (`stalwartlabs/stalwart`, `crates/registry/src/schema/enums.rs:2028-2032`,
55
+ * `Sys<Object><Verb>` matching the names `DASHBOARD_PERMISSIONS` already
56
+ * uses for other objects) — present in the source, not yet exercised
57
+ * against a live instance, so this reads and writes with an
58
+ * `'inherit'`-scoped key or the instance administrator's own credential
59
+ * until a narrower key is confirmed to work.
60
+ */
61
+ export async function loadQueue(instance) {
62
+ const wire = await instance.client.list('QueuedMessage');
63
+ return wire.map(queueMessageView);
64
+ }
@@ -41,6 +41,21 @@ 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 one API key stops working and
46
+ * every other credential survives.
47
+ *
48
+ * The mirror image of `withoutAppPassword`'s type guard: an entry whose
49
+ * type is not `ApiKey` is not this action's to touch. `Password` is the
50
+ * account's own password; `AppPassword` is a person's, revoked by
51
+ * `withoutAppPassword`. This function's business is exactly the type that
52
+ * one refuses to touch.
53
+ *
54
+ * Surviving entries keep their masked secrets, which the server reads as
55
+ * "leave this one alone" — the behaviour `withPassword` documents and
56
+ * relies on.
57
+ */
58
+ export declare function withoutApiKey(account: Pick<WireAccount, 'credentials'>, credentialId: string): Record<string, Credential>;
44
59
  /**
45
60
  * The `Account` to create for a person, mirroring what
46
61
  * `scripts/mail-sync.mts` sends, minus the password.
@@ -60,3 +75,47 @@ export declare function newAccount(input: {
60
75
  /** Whether the domain delegates passwords to an external directory. */
61
76
  external: boolean;
62
77
  }): Record<string, unknown>;
78
+ /**
79
+ * A shared mailbox: `hr@`, `support@`, an address a team reads together
80
+ * rather than a person's own.
81
+ *
82
+ * On the server this is an account like any other — the same object, the
83
+ * same delivery, the same aliases — whose `@type` is `Group` instead of
84
+ * `User`. What makes it shared is on the *people*: an account naming this
85
+ * group in `memberGroupIds` reaches it with their own credential, as a
86
+ * second account in the same JMAP session. So a group is created empty here
87
+ * and filled by `addToGroup`.
88
+ *
89
+ * It takes no password and no `external` flag, unlike `newAccount`: nobody
90
+ * ever signs in as a shared mailbox, so there is no first secret to show
91
+ * once, and the question a personal mailbox has to ask — does this domain
92
+ * keep its own passwords — does not arise.
93
+ */
94
+ export declare function newGroup(input: {
95
+ local: string;
96
+ domainId: string;
97
+ description?: string | null;
98
+ }): Record<string, unknown>;
99
+ /**
100
+ * The `memberGroupIds` to send so that this account also reads `groupId`.
101
+ *
102
+ * **A membership map is a set, not a list.** The server sends and takes
103
+ * `{"<id>": true}`, and an entry whose value is not `true` is dropped on the
104
+ * way in, so what is sent is the whole surviving set — the same replace-the-
105
+ * lot rule as `aliases`, and the same reason these functions are worth
106
+ * testing.
107
+ *
108
+ * A duplicate is refused rather than sent, because sending it would report
109
+ * that somebody was added when the set was already exactly this.
110
+ */
111
+ export declare function withMembership(account: Pick<WireAccount, 'memberGroupIds'>, groupId: string): Record<string, boolean>;
112
+ /**
113
+ * The `memberGroupIds` to send so that this account no longer reads
114
+ * `groupId`. Refuses when the membership is absent, so a stale page cannot
115
+ * send the set back unchanged and report that it took access away.
116
+ */
117
+ export declare function withoutMembership(account: Pick<WireAccount, 'memberGroupIds'>, groupId: string): Record<string, boolean>;
118
+ /** The group ids on an account, in the order the server sent them. Only
119
+ * entries the server marked `true` count: it drops the others on read, so a
120
+ * write that kept them would add back what somebody just removed. */
121
+ export declare function membershipIds(account: Pick<WireAccount, 'memberGroupIds'>): string[];