@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,79 @@
1
+ import { JAM_FETCH } from "./client.js";
2
+ import { MailError, guard } from "./errors.js";
3
+ /**
4
+ * The vacation auto-reply: RFC 8621 §8's `VacationResponse`, over the
5
+ * `urn:ietf:params:jmap:vacationresponse` capability.
6
+ *
7
+ * **One object per account, and it is never created or destroyed.** RFC 8621
8
+ * §8.1 fixes its id at `singleton`, so `vacationResponse()` always reads that
9
+ * one object and `setVacationResponse()` always **updates** it -- there is no
10
+ * `create` here the way `createMailbox` has one.
11
+ *
12
+ * **No `using` override is needed, unlike `submit.ts`'s `send`/`cancel`.**
13
+ * `jmap-jam` derives the capabilities a request declares from the method
14
+ * names it is sending, and its own built-in map already keys `VacationResponse`
15
+ * to `urn:ietf:params:jmap:vacationresponse` (`jmap-jam`'s `Requests`/capability
16
+ * table, alongside `Mailbox` → mail and `EmailSubmission` → submission) --
17
+ * confirmed against the installed `jmap-jam@0.13.6`. That table is keyed by
18
+ * the method name being *sent*, so it is only `send`/`cancel`'s implicit
19
+ * `Email/set` (a method never named in the request) that needs `using` forced
20
+ * by hand; a plain `VacationResponse/get` or `/set` names itself.
21
+ */
22
+ const SINGLETON = 'singleton';
23
+ function fromRaw(raw) {
24
+ return {
25
+ isEnabled: raw.isEnabled,
26
+ fromDate: raw.fromDate ?? null,
27
+ toDate: raw.toDate ?? null,
28
+ subject: raw.subject ?? null,
29
+ textBody: raw.textBody ?? null,
30
+ htmlBody: raw.htmlBody ?? null,
31
+ };
32
+ }
33
+ /** The account's vacation response as it stands now. */
34
+ export async function vacationResponse(client) {
35
+ const { jam, accountId } = await client.connect();
36
+ return guard('vacation response', async () => {
37
+ const [result] = await jam.api.VacationResponse.get({ accountId }, JAM_FETCH);
38
+ const found = result.list[0];
39
+ if (!found) {
40
+ throw new MailError('the account has no vacation response to read', {
41
+ type: 'notFound',
42
+ operation: 'vacation response',
43
+ });
44
+ }
45
+ return fromRaw(found);
46
+ });
47
+ }
48
+ /**
49
+ * Set the vacation response: whether it is on, its window, and its message.
50
+ *
51
+ * A field left out of `options` is not sent, so the server keeps whatever it
52
+ * already has for that field; pass `null` to clear one. `isEnabled` is the
53
+ * only field that always goes -- **clearing the response, in the sense the
54
+ * host acts on, is `setVacationResponse(client, { isEnabled: false })`**,
55
+ * which leaves the dates and the message as they were so turning the
56
+ * responder back on does not need to resupply them.
57
+ */
58
+ 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;
65
+ }
66
+ return guard('set vacation response', async () => {
67
+ const [result] = await jam.api.VacationResponse.set({ accountId, update: { [SINGLETON]: patch } }, JAM_FETCH);
68
+ const notUpdated = result.notUpdated;
69
+ const failure = notUpdated?.[SINGLETON];
70
+ if (failure) {
71
+ throw new MailError(failure.description ?? 'the server refused to set the vacation response', { type: failure.type ?? 'unknown', operation: 'set vacation response' });
72
+ }
73
+ });
74
+ }
75
+ /** Turn the vacation response off, leaving its dates and message untouched.
76
+ * The one-field shorthand for `setVacationResponse(client, { isEnabled: false })`. */
77
+ export function clearVacationResponse(client) {
78
+ return setVacationResponse(client, { isEnabled: false });
79
+ }
@@ -2,7 +2,7 @@ import type { PostmasterAudit } from './audit.js';
2
2
  import type { Instance } from './instance.js';
3
3
  export interface Applied {
4
4
  /** For the audit row's `targetType`. */
5
- readonly targetType: 'mailbox' | 'mail_alias' | 'mail_app_password' | 'mail_settings';
5
+ readonly targetType: 'mailbox' | 'mail_group' | 'mail_group_member' | 'mail_alias' | 'mail_app_password' | 'mail_api_key' | 'mail_settings' | 'mail_queue_message';
6
6
  /** For its `targetId`: the address or the credential, never a secret. */
7
7
  readonly targetId: string;
8
8
  readonly before: unknown;
@@ -23,6 +23,51 @@ export declare function createMailbox(instance: Instance, input: {
23
23
  description?: string | null;
24
24
  external: boolean;
25
25
  }, audit?: PostmasterAudit): Promise<Applied>;
26
+ /**
27
+ * Make a shared mailbox — one address a team reads together, each with their
28
+ * own login.
29
+ *
30
+ * The same duplicate check as `createMailbox`, and against the same accounts:
31
+ * a group and a person compete for one local part, because both are accounts
32
+ * and mail to the address goes to exactly one of them.
33
+ *
34
+ * It is created empty. Nobody reads it until `addToGroup` names somebody,
35
+ * which is also why this needs no password: a shared mailbox is never signed
36
+ * in to.
37
+ */
38
+ export declare function createGroupMailbox(instance: Instance, input: {
39
+ local: string;
40
+ domainId: string;
41
+ apex: string;
42
+ description?: string | null;
43
+ }, audit?: PostmasterAudit): Promise<Applied>;
44
+ /**
45
+ * Let somebody read a shared mailbox, with their own login.
46
+ *
47
+ * The membership is written on the *person*, not on the mailbox: Stalwart
48
+ * turns an account's `memberGroupIds` into secondary accounts on that
49
+ * person's session, which is how `hr@` appears beside their own mail.
50
+ *
51
+ * Both accounts are re-read first, and both are confined to the domain the
52
+ * caller resolved — the same reason every other write here re-reads. The
53
+ * group is read as well as the person because a membership naming an account
54
+ * that is not a shared mailbox would be accepted by the server and mean
55
+ * nothing.
56
+ */
57
+ export declare function addToGroup(instance: Instance, input: {
58
+ accountId: string;
59
+ groupId: string;
60
+ domainId: string;
61
+ apex: string;
62
+ }, audit?: PostmasterAudit): Promise<Applied>;
63
+ /** Take a shared mailbox away from somebody. Their own mail is untouched:
64
+ * this removes the membership, not the account. */
65
+ export declare function removeFromGroup(instance: Instance, input: {
66
+ accountId: string;
67
+ groupId: string;
68
+ domainId: string;
69
+ apex: string;
70
+ }, audit?: PostmasterAudit): Promise<Applied>;
26
71
  export declare function addAlias(instance: Instance, input: {
27
72
  accountId: string;
28
73
  name: string;
@@ -60,6 +105,30 @@ export declare function revokeAppPassword(instance: Instance, input: {
60
105
  domainId: string;
61
106
  apex: string;
62
107
  }, audit?: PostmasterAudit): Promise<Applied>;
108
+ /**
109
+ * Stop one API key working. The secret is never read, here or anywhere
110
+ * else: the entry is identified by its id and the surviving entries go back
111
+ * with the masked secrets the server sent, which it reads as "leave these
112
+ * alone".
113
+ *
114
+ * **Never on the account the acting credential belongs to.** Every API key
115
+ * this package mints (`StalwartClient.createApiKey`) is as powerful as the
116
+ * whole account it was minted for, and this app itself may be authenticated
117
+ * as one — carrying no account name, so `revokeAppPassword`'s
118
+ * `isOurOwnAccount` cannot see it (`instance.user` is `null` for an
119
+ * `ApiKey`). `isCallersOwnAccount` asks the server instead, over a fresh
120
+ * `GET /jmap/session` made with this same credential, and refuses to touch
121
+ * *any* credential on the account it names back — the whole account, not
122
+ * only the literal key in use, the same width `revokeAppPassword` blocks
123
+ * for the administrator's app passwords, because a second key left on that
124
+ * account is still this panel's own way back in.
125
+ */
126
+ export declare function revokeApiKey(instance: Instance, input: {
127
+ accountId: string;
128
+ credentialId: string;
129
+ domainId: string;
130
+ apex: string;
131
+ }, audit?: PostmasterAudit): Promise<Applied>;
63
132
  /**
64
133
  * How long this instance will hold a message before sending it, as the
65
134
  * server's own duration (`'30d'`), or `null` when it will not hold one at
@@ -84,3 +153,87 @@ export declare function holdLimit(instance: Instance): Promise<string | null>;
84
153
  * server now says.
85
154
  */
86
155
  export declare function enableHolding(instance: Instance, audit?: PostmasterAudit): Promise<Applied>;
156
+ export interface SpamSettingsView {
157
+ readonly enabled: boolean;
158
+ /** Mail from an address in the recipient's own contacts skips scoring. */
159
+ readonly trustContacts: boolean;
160
+ /** A reply to a thread the account started skips scoring. */
161
+ readonly trustReplies: boolean;
162
+ /** How long a first-time sender is held before being let through, in
163
+ * milliseconds. `null` for no greylisting. */
164
+ readonly greylistForMs: number | null;
165
+ /** The score at and above which a message is tagged spam. */
166
+ readonly scoreSpam: number;
167
+ /** The score at and above which a message is silently discarded. */
168
+ readonly scoreDiscard: number;
169
+ /** The score at and above which a message is rejected at SMTP time. */
170
+ readonly scoreReject: number;
171
+ /** A URL the server pulls extra scoring rules from. `null` for none. */
172
+ readonly rulesUrl: string | null;
173
+ }
174
+ /**
175
+ * Whether this instance filters spam at all, and where its thresholds sit.
176
+ * Every tenant's mail gets whatever this singleton says until a caller
177
+ * changes it -- there is no per-mailbox override in Stalwart 0.16.
178
+ */
179
+ export declare function spamSettings(instance: Instance): Promise<SpamSettingsView>;
180
+ export interface SpamSettingsInput {
181
+ enabled?: boolean;
182
+ trustContacts?: boolean;
183
+ trustReplies?: boolean;
184
+ greylistForMs?: number | null;
185
+ scoreSpam?: number;
186
+ scoreDiscard?: number;
187
+ scoreReject?: number;
188
+ rulesUrl?: string | null;
189
+ }
190
+ /**
191
+ * Change baseline spam control for every mailbox this instance serves:
192
+ * whether filtering runs at all, the three score thresholds, whether a
193
+ * contact or a reply skips scoring, greylisting, and the extra-rules URL.
194
+ *
195
+ * **The reload is not optional**, for the same reason `enableHolding`'s
196
+ * is not: Stalwart applies a changed setting only after a `ReloadSettings`
197
+ * action, and a write without one is stored but inert until the next
198
+ * restart. `before`/`after` are both read fresh, so what is recorded is
199
+ * what the server now actually enforces.
200
+ *
201
+ * Every field is checked before the wire: a non-finite score is refused
202
+ * the way the server's own `Float` would refuse it (its `RegistryJsonPatch`
203
+ * impl, in `registry::types::float::Float`, rejects NaN and infinities on
204
+ * a patch), a `greylistForMs` of zero or less is refused the way its
205
+ * `Duration` would be (`registry::types::duration::Duration`'s own patch
206
+ * requires a positive u64), and an empty patch is refused because a write
207
+ * that changes nothing
208
+ * still bumps this instance's every mailbox onto a fresh `ReloadSettings`
209
+ * for no reason.
210
+ */
211
+ export declare function updateSpamSettings(instance: Instance, input: SpamSettingsInput, audit?: PostmasterAudit): Promise<Applied>;
212
+ /**
213
+ * Try every still-pending recipient on a queued message again, right now,
214
+ * instead of waiting for its scheduled retry.
215
+ *
216
+ * Only `scheduled` and `deferred` recipients are patched — a `delivered` or
217
+ * `failed` one has nothing left to retry, and the server itself ignores a
218
+ * `retryDue` write against a `PermanentFailure` recipient (confirmed in
219
+ * `tests/src/smtp/management/queue.rs`), so this does not even try. A
220
+ * message with nothing pending is refused before the wire, since patching
221
+ * zero recipients would report success for a retry that touched nothing.
222
+ *
223
+ * **The read this refuses on, and the write right after it, are not one
224
+ * transaction.** Stalwart 0.16 has no `ifInState` for this object either
225
+ * (the reason `missingSince` exists for Account writes, in the header
226
+ * above), and here the other party racing the write is not a second admin
227
+ * but the server's own delivery engine, which resolves recipients
228
+ * continuously. A recipient this call means to retry can deliver, or fail
229
+ * for good, in the moment between the read and the write — so this re-reads
230
+ * once more after writing and reports what is actually still pending,
231
+ * rather than assuming the patch reached everyone it was sent for.
232
+ */
233
+ export declare function retryQueuedMessage(instance: Instance, id: string, audit?: PostmasterAudit): Promise<Applied>;
234
+ /**
235
+ * Take a message out of the queue for good. It will not be retried, and
236
+ * nothing tells whoever sent it or the recipients it was ever delivered —
237
+ * the same silence a real MTA gives a message it drops.
238
+ */
239
+ export declare function purgeQueuedMessage(instance: Instance, id: string, audit?: PostmasterAudit): Promise<Applied>;
@@ -1,5 +1,5 @@
1
1
  import { FUTURE_RELEASE } from './objects.js';
2
- import { MailWriteRefused, newAccount, withAlias, withoutAlias, withoutAppPassword, } from './writes.js';
2
+ import { MailWriteRefused, membershipIds, newAccount, newGroup, withAlias, withMembership, withoutAlias, 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.
@@ -62,6 +62,21 @@ async function aliasNames(instance, accountId) {
62
62
  const [fresh] = await instance.client.get('Account', [accountId]);
63
63
  return Object.values(fresh?.aliases ?? {}).map((a) => a.name);
64
64
  }
65
+ /** The shared mailboxes an account reads, as the server has them right now. */
66
+ async function membershipsOf(instance, accountId) {
67
+ const [fresh] = await instance.client.get('Account', [accountId]);
68
+ return membershipIds(fresh ?? {});
69
+ }
70
+ /** The account as the server has it, refused unless it really is a shared
71
+ * mailbox. A membership naming a person's account would be stored happily
72
+ * and give nobody access to anything. */
73
+ async function readGroup(instance, groupId, domainId) {
74
+ const group = await readAccount(instance, groupId, domainId);
75
+ if (group['@type'] !== 'Group') {
76
+ throw new MailWriteRefused('that mailbox belongs to a person, not to a team');
77
+ }
78
+ return group;
79
+ }
65
80
  /** The credential ids on an account, as the server has them right now. */
66
81
  async function credentialIds(instance, accountId) {
67
82
  const [fresh] = await instance.client.get('Account', [accountId]);
@@ -114,6 +129,36 @@ function isOurOwnAccount(instance, account, apex) {
114
129
  return false;
115
130
  return `${account.name}@${apex}`.toLowerCase() === instance.user.toLowerCase();
116
131
  }
132
+ /**
133
+ * Whether `account` is the one the credential serving *this very request*
134
+ * authenticates as, as the server itself reports it — the check
135
+ * `isOurOwnAccount` cannot make for a Bearer `ApiKey`, since that credential
136
+ * carries no account name (`instance.user` is `null` for it) and
137
+ * `isOurOwnAccount` would silently say "not ours" for every account.
138
+ *
139
+ * `session` is a fresh `GET /jmap/session` made with the same credential
140
+ * that is about to revoke, so this asks the server, not the browser: even a
141
+ * minimally-scoped dashboard key answers its own session resource
142
+ * (confirmed on 0.16.20, see `.claude/scout/2026-09-22-bearer-whoami.md`).
143
+ *
144
+ * Matched two ways, either sufficient: by the account's JMAP id, present in
145
+ * `session.accounts` (the precise signal — Stalwart keys that map with the
146
+ * exact id the credential resolves to); and, belt and braces, by comparing
147
+ * `session.username` to the account's own local part. A caller that revokes
148
+ * a stranger's key on another domain sharing that local part sees a refusal
149
+ * it did not need — an acceptable false refusal. A caller that lets this
150
+ * credential revoke its own account's key is not: that takes the panel
151
+ * offline from inside the panel, and there is no undo.
152
+ */
153
+ function isCallersOwnAccount(session, account) {
154
+ // `Object.hasOwn`, not `in`: `session.accounts` is parsed straight from
155
+ // the wire, and `in` walks the prototype chain too, so an id that happens
156
+ // to collide with an inherited name like "constructor" would read as
157
+ // present when it is not on the map at all.
158
+ if (Object.hasOwn(session.accounts, account.id))
159
+ return true;
160
+ return account.name.toLowerCase() === session.username.toLowerCase();
161
+ }
117
162
  /**
118
163
  * Give a person a mailbox. The address is checked against the server rather
119
164
  * than against the page: two admins pressing "create" for the same person at
@@ -139,6 +184,78 @@ export async function createMailbox(instance, input, audit) {
139
184
  message: `${address} now has a mailbox. They sign in through the issuer and make an app password for their mail client.`,
140
185
  });
141
186
  }
187
+ /**
188
+ * Make a shared mailbox — one address a team reads together, each with their
189
+ * own login.
190
+ *
191
+ * The same duplicate check as `createMailbox`, and against the same accounts:
192
+ * a group and a person compete for one local part, because both are accounts
193
+ * and mail to the address goes to exactly one of them.
194
+ *
195
+ * It is created empty. Nobody reads it until `addToGroup` names somebody,
196
+ * which is also why this needs no password: a shared mailbox is never signed
197
+ * in to.
198
+ */
199
+ export async function createGroupMailbox(instance, input, audit) {
200
+ const value = newGroup(input);
201
+ const local = value.name;
202
+ const address = `${local}@${input.apex}`;
203
+ const existing = (await instance.client.list('Account')).find((a) => a.domainId === input.domainId && a.name.toLowerCase() === local);
204
+ if (existing) {
205
+ throw new MailWriteRefused(`${address} already has a mailbox`);
206
+ }
207
+ const id = await instance.client.create('Account', value);
208
+ return recorded(audit, 'mail.group_created', {
209
+ targetType: 'mail_group',
210
+ targetId: address,
211
+ before: null,
212
+ after: { id, name: local, domainId: input.domainId, description: input.description ?? null },
213
+ message: `${address} is now a shared mailbox. Nobody reads it yet — add whoever should.`,
214
+ });
215
+ }
216
+ /**
217
+ * Let somebody read a shared mailbox, with their own login.
218
+ *
219
+ * The membership is written on the *person*, not on the mailbox: Stalwart
220
+ * turns an account's `memberGroupIds` into secondary accounts on that
221
+ * person's session, which is how `hr@` appears beside their own mail.
222
+ *
223
+ * Both accounts are re-read first, and both are confined to the domain the
224
+ * caller resolved — the same reason every other write here re-reads. The
225
+ * group is read as well as the person because a membership naming an account
226
+ * that is not a shared mailbox would be accepted by the server and mean
227
+ * nothing.
228
+ */
229
+ export async function addToGroup(instance, input, audit) {
230
+ const account = await readAccount(instance, input.accountId, input.domainId);
231
+ const group = await readGroup(instance, input.groupId, input.domainId);
232
+ const memberGroupIds = withMembership(account, group.id);
233
+ await instance.client.update('Account', account.id, { memberGroupIds });
234
+ const lost = missingSince(Object.keys(memberGroupIds), await membershipsOf(instance, account.id));
235
+ return recorded(audit, 'mail.group_member_added', {
236
+ targetType: 'mail_group_member',
237
+ targetId: `${group.name}@${input.apex}`,
238
+ before: null,
239
+ after: { group: group.name, member: `${account.name}@${input.apex}` },
240
+ message: `${account.name}@${input.apex} now reads ${group.name}@${input.apex}, signed in as themselves.${lost}`,
241
+ });
242
+ }
243
+ /** Take a shared mailbox away from somebody. Their own mail is untouched:
244
+ * this removes the membership, not the account. */
245
+ export async function removeFromGroup(instance, input, audit) {
246
+ const account = await readAccount(instance, input.accountId, input.domainId);
247
+ const group = await readGroup(instance, input.groupId, input.domainId);
248
+ const memberGroupIds = withoutMembership(account, group.id);
249
+ await instance.client.update('Account', account.id, { memberGroupIds });
250
+ const lost = missingSince(Object.keys(memberGroupIds), await membershipsOf(instance, account.id));
251
+ return recorded(audit, 'mail.group_member_removed', {
252
+ targetType: 'mail_group_member',
253
+ targetId: `${group.name}@${input.apex}`,
254
+ before: { group: group.name, member: `${account.name}@${input.apex}` },
255
+ after: null,
256
+ message: `${account.name}@${input.apex} no longer reads ${group.name}@${input.apex}.${lost}`,
257
+ });
258
+ }
142
259
  export async function addAlias(instance, input, audit) {
143
260
  const account = await readAccount(instance, input.accountId, input.domainId);
144
261
  const aliases = withAlias(account, { name: input.name, domainId: input.domainId });
@@ -205,6 +322,45 @@ export async function revokeAppPassword(instance, input, audit) {
205
322
  message: `That app password no longer works${description ? ` (${description})` : ''}. Any mail client using it will be asked to sign in again.${lost}`,
206
323
  });
207
324
  }
325
+ /**
326
+ * Stop one API key working. The secret is never read, here or anywhere
327
+ * else: the entry is identified by its id and the surviving entries go back
328
+ * with the masked secrets the server sent, which it reads as "leave these
329
+ * alone".
330
+ *
331
+ * **Never on the account the acting credential belongs to.** Every API key
332
+ * this package mints (`StalwartClient.createApiKey`) is as powerful as the
333
+ * whole account it was minted for, and this app itself may be authenticated
334
+ * as one — carrying no account name, so `revokeAppPassword`'s
335
+ * `isOurOwnAccount` cannot see it (`instance.user` is `null` for an
336
+ * `ApiKey`). `isCallersOwnAccount` asks the server instead, over a fresh
337
+ * `GET /jmap/session` made with this same credential, and refuses to touch
338
+ * *any* credential on the account it names back — the whole account, not
339
+ * only the literal key in use, the same width `revokeAppPassword` blocks
340
+ * for the administrator's app passwords, because a second key left on that
341
+ * account is still this panel's own way back in.
342
+ */
343
+ export async function revokeApiKey(instance, input, audit) {
344
+ const account = await readAccount(instance, input.accountId, input.domainId);
345
+ const session = await instance.client.session();
346
+ if (isCallersOwnAccount(session, account)) {
347
+ throw new MailWriteRefused(`this management app is authenticated on ${account.name}@${input.apex}, and one of its API keys is serving this request. Manage its credentials in the web admin.`);
348
+ }
349
+ const before = Object.values(account.credentials ?? {}).find((c) => c.credentialId === input.credentialId);
350
+ const credentials = withoutApiKey(account, input.credentialId);
351
+ await instance.client.update('Account', account.id, { credentials });
352
+ const description = typeof before?.description === 'string' ? before.description : null;
353
+ const lost = missingSince(Object.values(credentials)
354
+ .map((c) => c.credentialId)
355
+ .filter((id) => typeof id === 'string'), await credentialIds(instance, account.id));
356
+ return recorded(audit, 'mail.api_key_revoked', {
357
+ targetType: 'mail_api_key',
358
+ targetId: input.credentialId,
359
+ before: { mailbox: `${account.name}@${input.apex}`, description },
360
+ after: null,
361
+ message: `That API key no longer works${description ? ` (${description})` : ''}. Anything using it gets 401 from here on.${lost}`,
362
+ });
363
+ }
208
364
  /**
209
365
  * How long this instance will hold a message before sending it, as the
210
366
  * server's own duration (`'30d'`), or `null` when it will not hold one at
@@ -245,3 +401,182 @@ export async function enableHolding(instance, audit) {
245
401
  message: `This server now holds a message for up to ${after} before sending it, so a delayed send and undo send work.`,
246
402
  });
247
403
  }
404
+ function spamSettingsView(wire) {
405
+ return {
406
+ enabled: wire.enable === true,
407
+ trustContacts: wire.trustContacts === true,
408
+ trustReplies: wire.trustReplies === true,
409
+ greylistForMs: typeof wire.greylistFor === 'number' ? wire.greylistFor : null,
410
+ scoreSpam: typeof wire.scoreSpam === 'number' ? wire.scoreSpam : 0,
411
+ scoreDiscard: typeof wire.scoreDiscard === 'number' ? wire.scoreDiscard : 0,
412
+ scoreReject: typeof wire.scoreReject === 'number' ? wire.scoreReject : 0,
413
+ rulesUrl: typeof wire.spamFilterRulesUrl === 'string' ? wire.spamFilterRulesUrl : null,
414
+ };
415
+ }
416
+ /**
417
+ * Whether this instance filters spam at all, and where its thresholds sit.
418
+ * Every tenant's mail gets whatever this singleton says until a caller
419
+ * changes it -- there is no per-mailbox override in Stalwart 0.16.
420
+ */
421
+ export async function spamSettings(instance) {
422
+ const wire = await instance.client.getSingleton('SpamSettings');
423
+ return spamSettingsView(wire);
424
+ }
425
+ function toWirePatch(input) {
426
+ const patch = {};
427
+ if (input.enabled !== undefined)
428
+ patch.enable = input.enabled;
429
+ if (input.trustContacts !== undefined)
430
+ patch.trustContacts = input.trustContacts;
431
+ if (input.trustReplies !== undefined)
432
+ patch.trustReplies = input.trustReplies;
433
+ if (input.greylistForMs !== undefined)
434
+ patch.greylistFor = input.greylistForMs;
435
+ if (input.scoreSpam !== undefined)
436
+ patch.scoreSpam = input.scoreSpam;
437
+ if (input.scoreDiscard !== undefined)
438
+ patch.scoreDiscard = input.scoreDiscard;
439
+ if (input.scoreReject !== undefined)
440
+ patch.scoreReject = input.scoreReject;
441
+ if (input.rulesUrl !== undefined)
442
+ patch.spamFilterRulesUrl = input.rulesUrl;
443
+ return patch;
444
+ }
445
+ /**
446
+ * Change baseline spam control for every mailbox this instance serves:
447
+ * whether filtering runs at all, the three score thresholds, whether a
448
+ * contact or a reply skips scoring, greylisting, and the extra-rules URL.
449
+ *
450
+ * **The reload is not optional**, for the same reason `enableHolding`'s
451
+ * is not: Stalwart applies a changed setting only after a `ReloadSettings`
452
+ * action, and a write without one is stored but inert until the next
453
+ * restart. `before`/`after` are both read fresh, so what is recorded is
454
+ * what the server now actually enforces.
455
+ *
456
+ * Every field is checked before the wire: a non-finite score is refused
457
+ * the way the server's own `Float` would refuse it (its `RegistryJsonPatch`
458
+ * impl, in `registry::types::float::Float`, rejects NaN and infinities on
459
+ * a patch), a `greylistForMs` of zero or less is refused the way its
460
+ * `Duration` would be (`registry::types::duration::Duration`'s own patch
461
+ * requires a positive u64), and an empty patch is refused because a write
462
+ * that changes nothing
463
+ * still bumps this instance's every mailbox onto a fresh `ReloadSettings`
464
+ * for no reason.
465
+ */
466
+ export async function updateSpamSettings(instance, input, audit) {
467
+ const patch = toWirePatch(input);
468
+ if (Object.keys(patch).length === 0) {
469
+ throw new MailWriteRefused('nothing to change');
470
+ }
471
+ for (const [key, value] of Object.entries(patch)) {
472
+ if (typeof value === 'number' && !Number.isFinite(value)) {
473
+ throw new MailWriteRefused(`${key} must be a real number`);
474
+ }
475
+ }
476
+ if (typeof patch.greylistFor === 'number' && patch.greylistFor <= 0) {
477
+ throw new MailWriteRefused('greylistForMs must be a positive number of milliseconds, or null to turn greylisting off');
478
+ }
479
+ const before = spamSettingsView(await instance.client.getSingleton('SpamSettings'));
480
+ await instance.client.update('SpamSettings', 'singleton', patch);
481
+ await instance.client.create('Action', { '@type': 'ReloadSettings' });
482
+ const after = spamSettingsView(await instance.client.getSingleton('SpamSettings'));
483
+ return recorded(audit, 'mail.spam_settings_updated', {
484
+ targetType: 'mail_settings',
485
+ targetId: 'spamSettings',
486
+ before,
487
+ after,
488
+ message: after.enabled
489
+ ? `Spam filtering is on. A message scoring ${after.scoreSpam} or higher is tagged spam, ${after.scoreDiscard} or higher is discarded silently, and ${after.scoreReject} or higher is rejected outright.`
490
+ : 'Spam filtering is off. Every message is delivered regardless of score.',
491
+ });
492
+ }
493
+ // ── the mail queue ───────────────────────────────────────────────────────
494
+ /** RFC 6901 §3, the same escape `mailbox/mutate.ts` needs: `~` and `/`
495
+ * inside a pointer segment are escaped, and a recipient address is not
496
+ * this app's to shape — a quoted local part may legally hold either. */
497
+ function pointer(segment) {
498
+ return segment.replaceAll('~', '~0').replaceAll('/', '~1');
499
+ }
500
+ /** Whether a recipient still has a delivery pending, from its `status`
501
+ * tag alone: not yet `Completed` (delivered) and not yet given up on for
502
+ * good (`PermanentFailure`). */
503
+ function isPending(r) {
504
+ const tag = r.status?.['@type'];
505
+ return tag !== 'Completed' && tag !== 'PermanentFailure';
506
+ }
507
+ /**
508
+ * Try every still-pending recipient on a queued message again, right now,
509
+ * instead of waiting for its scheduled retry.
510
+ *
511
+ * Only `scheduled` and `deferred` recipients are patched — a `delivered` or
512
+ * `failed` one has nothing left to retry, and the server itself ignores a
513
+ * `retryDue` write against a `PermanentFailure` recipient (confirmed in
514
+ * `tests/src/smtp/management/queue.rs`), so this does not even try. A
515
+ * message with nothing pending is refused before the wire, since patching
516
+ * zero recipients would report success for a retry that touched nothing.
517
+ *
518
+ * **The read this refuses on, and the write right after it, are not one
519
+ * transaction.** Stalwart 0.16 has no `ifInState` for this object either
520
+ * (the reason `missingSince` exists for Account writes, in the header
521
+ * above), and here the other party racing the write is not a second admin
522
+ * but the server's own delivery engine, which resolves recipients
523
+ * continuously. A recipient this call means to retry can deliver, or fail
524
+ * for good, in the moment between the read and the write — so this re-reads
525
+ * once more after writing and reports what is actually still pending,
526
+ * rather than assuming the patch reached everyone it was sent for.
527
+ */
528
+ export async function retryQueuedMessage(instance, id, audit) {
529
+ const [before] = await instance.client.get('QueuedMessage', [id]);
530
+ if (!before) {
531
+ throw new MailWriteRefused('that message is no longer in the queue');
532
+ }
533
+ const addresses = Object.entries(before.recipients ?? {})
534
+ .filter(([, r]) => isPending(r))
535
+ .map(([address]) => address);
536
+ if (addresses.length === 0) {
537
+ throw new MailWriteRefused('every recipient on this message has already resolved; there is nothing left to retry');
538
+ }
539
+ const now = new Date().toISOString();
540
+ const patch = Object.fromEntries(addresses.map((address) => [`recipients/${pointer(address)}/retryDue`, now]));
541
+ await instance.client.update('QueuedMessage', id, patch);
542
+ const [after] = await instance.client.get('QueuedMessage', [id]);
543
+ const stillPending = after
544
+ ? addresses.filter((address) => {
545
+ const r = after.recipients?.[address];
546
+ return r ? isPending(r) : false;
547
+ })
548
+ : [];
549
+ const settled = addresses.filter((address) => !stillPending.includes(address));
550
+ return recorded(audit, 'mail.queue_message_retried', {
551
+ targetType: 'mail_queue_message',
552
+ targetId: id,
553
+ before: { from: before.returnPath, pending: addresses },
554
+ after: { retryDue: now, retried: stillPending },
555
+ message: settled.length === 0
556
+ ? `Retrying delivery to ${stillPending.length} recipient${stillPending.length === 1 ? '' : 's'} now.`
557
+ : `Retrying delivery to ${stillPending.length} recipient${stillPending.length === 1 ? '' : 's'} now. ${settled.length} more resolved on ${settled.length === 1 ? 'its' : 'their'} own in the moment between the read and the write, and got no new retry.`,
558
+ });
559
+ }
560
+ /**
561
+ * Take a message out of the queue for good. It will not be retried, and
562
+ * nothing tells whoever sent it or the recipients it was ever delivered —
563
+ * the same silence a real MTA gives a message it drops.
564
+ */
565
+ export async function purgeQueuedMessage(instance, id, audit) {
566
+ const [before] = await instance.client.get('QueuedMessage', [id]);
567
+ if (!before) {
568
+ throw new MailWriteRefused('that message is no longer in the queue');
569
+ }
570
+ const { notDestroyed } = await instance.client.destroy('QueuedMessage', [id]);
571
+ const failure = notDestroyed[id];
572
+ if (failure) {
573
+ throw new MailWriteRefused(failure.description ?? 'the server refused to remove that message from the queue');
574
+ }
575
+ return recorded(audit, 'mail.queue_message_purged', {
576
+ targetType: 'mail_queue_message',
577
+ targetId: id,
578
+ before: { from: before.returnPath, to: Object.keys(before.recipients ?? {}) },
579
+ after: null,
580
+ message: `The message from ${before.returnPath || '<>'} is gone from the queue.`,
581
+ });
582
+ }
@@ -9,6 +9,15 @@ export declare const POSTMASTER_AUDIT_EVENTS: {
9
9
  readonly 'mail.mailbox_created': {
10
10
  readonly tenantVisible: true;
11
11
  };
12
+ readonly 'mail.group_created': {
13
+ readonly tenantVisible: true;
14
+ };
15
+ readonly 'mail.group_member_added': {
16
+ readonly tenantVisible: true;
17
+ };
18
+ readonly 'mail.group_member_removed': {
19
+ readonly tenantVisible: true;
20
+ };
12
21
  readonly 'mail.alias_added': {
13
22
  readonly tenantVisible: true;
14
23
  };
@@ -18,9 +27,21 @@ export declare const POSTMASTER_AUDIT_EVENTS: {
18
27
  readonly 'mail.app_password_revoked': {
19
28
  readonly tenantVisible: true;
20
29
  };
30
+ readonly 'mail.api_key_revoked': {
31
+ readonly tenantVisible: true;
32
+ };
21
33
  readonly 'mail.holding_enabled': {
22
34
  readonly tenantVisible: true;
23
35
  };
36
+ readonly 'mail.spam_settings_updated': {
37
+ readonly tenantVisible: true;
38
+ };
39
+ readonly 'mail.queue_message_retried': {
40
+ readonly tenantVisible: true;
41
+ };
42
+ readonly 'mail.queue_message_purged': {
43
+ readonly tenantVisible: true;
44
+ };
24
45
  };
25
46
  export type PostmasterAuditAction = keyof typeof POSTMASTER_AUDIT_EVENTS;
26
47
  /** One write, as the host's writer receives it. `targetId` is an address or a credential id, never a secret. */
@@ -31,7 +52,7 @@ export interface PostmasterAuditEvent {
31
52
  readonly display: string;
32
53
  };
33
54
  readonly target: {
34
- readonly type: 'mailbox' | 'mail_alias' | 'mail_app_password' | 'mail_settings';
55
+ readonly type: 'mailbox' | 'mail_group' | 'mail_group_member' | 'mail_alias' | 'mail_app_password' | 'mail_api_key' | 'mail_settings' | 'mail_queue_message';
35
56
  readonly id: string;
36
57
  };
37
58
  readonly outcome: 'success';