@wtfalch/email 0.13.1 → 0.14.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 (42) hide show
  1. package/README.md +66 -4
  2. package/dist/mailbox/client.d.ts +22 -1
  3. package/dist/mailbox/client.js +45 -0
  4. package/dist/mailbox/fake/mailbox.js +205 -5
  5. package/dist/mailbox/index.d.ts +11 -7
  6. package/dist/mailbox/index.js +5 -3
  7. package/dist/mailbox/mail.css +13 -0
  8. package/dist/mailbox/mailboxes.d.ts +95 -1
  9. package/dist/mailbox/mailboxes.js +243 -1
  10. package/dist/mailbox/mutate.d.ts +21 -0
  11. package/dist/mailbox/mutate.js +71 -0
  12. package/dist/mailbox/quoted.d.ts +94 -0
  13. package/dist/mailbox/quoted.js +158 -0
  14. package/dist/mailbox/react/Composer.js +13 -1
  15. package/dist/mailbox/react/Mail.js +273 -33
  16. package/dist/mailbox/react/ThreadView.d.ts +13 -1
  17. package/dist/mailbox/react/ThreadView.js +5 -4
  18. package/dist/mailbox/react/index.d.ts +3 -1
  19. package/dist/mailbox/react/index.js +2 -1
  20. package/dist/mailbox/react/quotedHtml.d.ts +105 -0
  21. package/dist/mailbox/react/quotedHtml.js +163 -0
  22. package/dist/mailbox/snooze.d.ts +48 -0
  23. package/dist/mailbox/snooze.js +176 -0
  24. package/dist/mailbox/submit.d.ts +26 -0
  25. package/dist/mailbox/submit.js +88 -7
  26. package/dist/mailbox/threads.js +2 -0
  27. package/dist/mailbox/types.d.ts +40 -0
  28. package/dist/postmaster/apply.d.ts +154 -1
  29. package/dist/postmaster/apply.js +336 -1
  30. package/dist/postmaster/audit.d.ts +22 -1
  31. package/dist/postmaster/audit.js +7 -0
  32. package/dist/postmaster/client.d.ts +49 -0
  33. package/dist/postmaster/client.js +43 -0
  34. package/dist/postmaster/index.d.ts +4 -3
  35. package/dist/postmaster/index.js +3 -2
  36. package/dist/postmaster/objects.js +11 -0
  37. package/dist/postmaster/overview.d.ts +4 -0
  38. package/dist/postmaster/queue.d.ts +111 -0
  39. package/dist/postmaster/queue.js +64 -0
  40. package/dist/postmaster/writes.d.ts +59 -0
  41. package/dist/postmaster/writes.js +106 -0
  42. package/package.json +1 -1
@@ -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';
@@ -7,8 +7,15 @@
7
7
  */
8
8
  export const POSTMASTER_AUDIT_EVENTS = {
9
9
  'mail.mailbox_created': { tenantVisible: true },
10
+ 'mail.group_created': { tenantVisible: true },
11
+ 'mail.group_member_added': { tenantVisible: true },
12
+ 'mail.group_member_removed': { tenantVisible: true },
10
13
  'mail.alias_added': { tenantVisible: true },
11
14
  'mail.alias_removed': { tenantVisible: true },
12
15
  'mail.app_password_revoked': { tenantVisible: true },
16
+ 'mail.api_key_revoked': { tenantVisible: true },
13
17
  'mail.holding_enabled': { tenantVisible: true },
18
+ 'mail.spam_settings_updated': { tenantVisible: true },
19
+ 'mail.queue_message_retried': { tenantVisible: true },
20
+ 'mail.queue_message_purged': { tenantVisible: true },
14
21
  };
@@ -76,12 +76,47 @@ export declare class StalwartClient {
76
76
  id: string;
77
77
  }>(object: string, ids: string[]): Promise<T[]>;
78
78
  getSingleton<T>(object: string): Promise<T>;
79
+ /**
80
+ * The standard JMAP Session resource (RFC 8620 §2), for whatever
81
+ * credential this client holds — a plain `GET`, not a `methodCalls`
82
+ * request, since the session resource is not one of this package's
83
+ * management objects and does not live under `x:<Object>/get`.
84
+ *
85
+ * Stalwart derives `username`/`accounts` straight from the credential's
86
+ * own embedded account id, for a Bearer `ApiKey` exactly as for Basic
87
+ * (confirmed against 0.16.20; see
88
+ * `.claude/scout/2026-09-22-bearer-whoami.md`). That makes this the one
89
+ * way to learn which account a Bearer credential belongs to — {@link
90
+ * Instance.user} (in `./instance.ts`) is `null` for that credential type.
91
+ * `revokeApiKey`'s self-revocation guard is the only caller.
92
+ *
93
+ * **A missing `username` throws rather than defaulting.** A real,
94
+ * authenticated JMAP session always carries one — RFC 8620 requires it,
95
+ * and Stalwart sets it from `account.name()` on every request that
96
+ * reaches this handler. An empty one here means something is badly wrong
97
+ * (a proxy swallowing the body, a wrong path resolving to a different
98
+ * handler), and silently returning `''` would make the guard compare
99
+ * against a value no real account ever has — the caller's own account
100
+ * would never match, and a self-revocation would go through unguarded.
101
+ * Failing loud here is what keeps that failure mode closed rather than
102
+ * open.
103
+ */
104
+ session(): Promise<SessionInfo>;
79
105
  /** Every object of a type. Filters are matched client-side by the caller. */
80
106
  list<T extends {
81
107
  id: string;
82
108
  }>(object: string): Promise<T[]>;
83
109
  create(object: string, value: Record<string, unknown>): Promise<string>;
84
110
  update(object: string, id: string, patch: Record<string, unknown>): Promise<void>;
111
+ /** Destroy one or more objects. Returns what the server actually did:
112
+ * `destroyed` are gone, `notDestroyed` names why each of the rest is not. */
113
+ destroy(object: string, ids: readonly string[]): Promise<{
114
+ destroyed: string[];
115
+ notDestroyed: Record<string, {
116
+ type: string;
117
+ description?: string;
118
+ }>;
119
+ }>;
85
120
  /**
86
121
  * Mint an API key for the authenticated account through the self-service
87
122
  * API, and return its secret, which is in the response and nowhere else.
@@ -145,3 +180,17 @@ export interface Credential {
145
180
  secret?: string;
146
181
  [property: string]: unknown;
147
182
  }
183
+ /**
184
+ * The two fields of the JMAP Session resource this package reads. The
185
+ * server sends a good deal more (`capabilities`, `apiUrl`, `state`, …);
186
+ * only `username` and `accounts` are named, for the same reason
187
+ * `WireAccount` (in `./overview.ts`) names only what it reads.
188
+ */
189
+ export interface SessionInfo {
190
+ /** The authenticated account's local part — `account.name()`, not an address. */
191
+ readonly username: string;
192
+ /** Keyed by the account's JMAP id. Exactly one entry, for a Bearer or a Basic credential alike. */
193
+ readonly accounts: Readonly<Record<string, {
194
+ readonly name?: string;
195
+ }>>;
196
+ }
@@ -172,6 +172,43 @@ export class StalwartClient {
172
172
  throw new StalwartError(`x:${object}/get`, 'notFound', 'singleton');
173
173
  return one;
174
174
  }
175
+ /**
176
+ * The standard JMAP Session resource (RFC 8620 §2), for whatever
177
+ * credential this client holds — a plain `GET`, not a `methodCalls`
178
+ * request, since the session resource is not one of this package's
179
+ * management objects and does not live under `x:<Object>/get`.
180
+ *
181
+ * Stalwart derives `username`/`accounts` straight from the credential's
182
+ * own embedded account id, for a Bearer `ApiKey` exactly as for Basic
183
+ * (confirmed against 0.16.20; see
184
+ * `.claude/scout/2026-09-22-bearer-whoami.md`). That makes this the one
185
+ * way to learn which account a Bearer credential belongs to — {@link
186
+ * Instance.user} (in `./instance.ts`) is `null` for that credential type.
187
+ * `revokeApiKey`'s self-revocation guard is the only caller.
188
+ *
189
+ * **A missing `username` throws rather than defaulting.** A real,
190
+ * authenticated JMAP session always carries one — RFC 8620 requires it,
191
+ * and Stalwart sets it from `account.name()` on every request that
192
+ * reaches this handler. An empty one here means something is badly wrong
193
+ * (a proxy swallowing the body, a wrong path resolving to a different
194
+ * handler), and silently returning `''` would make the guard compare
195
+ * against a value no real account ever has — the caller's own account
196
+ * would never match, and a self-revocation would go through unguarded.
197
+ * Failing loud here is what keeps that failure mode closed rather than
198
+ * open.
199
+ */
200
+ async session() {
201
+ const r = await fetch(`${this.base}/jmap/session`, { headers: this.headers() });
202
+ if (r.status === 401)
203
+ throw new StalwartError('session', 'unauthorized', 'wrong credential');
204
+ if (!r.ok)
205
+ throw new StalwartError('session', `http ${r.status}`, (await r.text()).slice(0, 300));
206
+ const json = (await r.json());
207
+ if (!json.username) {
208
+ throw new StalwartError('session', 'malformed', 'no username in the session resource');
209
+ }
210
+ return { username: json.username, accounts: json.accounts ?? {} };
211
+ }
175
212
  /** Every object of a type. Filters are matched client-side by the caller. */
176
213
  async list(object) {
177
214
  const q = await this.call(`x:${object}/query`, {});
@@ -197,6 +234,12 @@ export class StalwartClient {
197
234
  throw new StalwartError(`x:${object}/set`, failure.type, `${failure.description ?? ''}${failure.properties ? ` (${failure.properties.join(', ')})` : ''}`);
198
235
  }
199
236
  }
237
+ /** Destroy one or more objects. Returns what the server actually did:
238
+ * `destroyed` are gone, `notDestroyed` names why each of the rest is not. */
239
+ async destroy(object, ids) {
240
+ const res = await this.call(`x:${object}/set`, { destroy: ids });
241
+ return { destroyed: res.destroyed ?? [], notDestroyed: res.notDestroyed ?? {} };
242
+ }
200
243
  /**
201
244
  * Mint an API key for the authenticated account through the self-service
202
245
  * API, and return its secret, which is in the response and nowhere else.
@@ -14,12 +14,13 @@
14
14
  * The main entry is pure Node so a provisioning script can use it. The
15
15
  * components live behind `@wtfalch/email/postmaster/react`.
16
16
  */
17
- export { API_KEY_PREFIX, DASHBOARD_PERMISSIONS, StalwartClient, StalwartError, authFor, type Credential, type StalwartAuth, } from './client.js';
17
+ export { API_KEY_PREFIX, DASHBOARD_PERMISSIONS, StalwartClient, StalwartError, authFor, type Credential, type SessionInfo, type StalwartAuth, } from './client.js';
18
18
  export { type Instance, InstanceRefused, openInstance, type RefusalReason } from './instance.js';
19
19
  export { loadOverview } from './load.js';
20
20
  export { FUTURE_RELEASE, applyObjects, mailObjects, ref, type MailObjectsInput, type PlannedObject, } from './objects.js';
21
21
  export { planMailboxes, withPassword } from './mailboxes.js';
22
22
  export { overview, pickDomain, type AccountView, type CredentialSummary, type DomainView, type Managed, type Overview, type OverviewInput, type PeopleView, type Person, type WireAccount, type WireAlias, type WireDomain, type WireSystemSettings, } from './overview.js';
23
- export { MailWriteRefused, newAccount, withAlias, withoutAlias, withoutAppPassword, } from './writes.js';
24
- export { addAlias, createMailbox, enableHolding, holdLimit, removeAlias, revokeAppPassword, type Applied, } from './apply.js';
23
+ export { MailWriteRefused, membershipIds, newAccount, newGroup, withAlias, withMembership, withoutAlias, withoutApiKey, withoutAppPassword, withoutMembership, } from './writes.js';
24
+ export { addAlias, addToGroup, createGroupMailbox, createMailbox, enableHolding, holdLimit, purgeQueuedMessage, removeAlias, removeFromGroup, retryQueuedMessage, revokeApiKey, revokeAppPassword, spamSettings, updateSpamSettings, type Applied, type SpamSettingsInput, type SpamSettingsView, } from './apply.js';
25
+ export { loadQueue, queueMessageView, type QueueMessage, type QueueRecipient, type QueueRecipientState, } from './queue.js';
25
26
  export { POSTMASTER_AUDIT_EVENTS, type PostmasterAudit, type PostmasterAuditAction, type PostmasterAuditEvent, } from './audit.js';
@@ -20,6 +20,7 @@ export { loadOverview } from './load.js';
20
20
  export { FUTURE_RELEASE, applyObjects, mailObjects, ref, } from './objects.js';
21
21
  export { planMailboxes, withPassword } from './mailboxes.js';
22
22
  export { overview, pickDomain, } from './overview.js';
23
- export { MailWriteRefused, newAccount, withAlias, withoutAlias, withoutAppPassword, } from './writes.js';
24
- export { addAlias, createMailbox, enableHolding, holdLimit, removeAlias, revokeAppPassword, } from './apply.js';
23
+ export { MailWriteRefused, membershipIds, newAccount, newGroup, withAlias, withMembership, withoutAlias, withoutApiKey, withoutAppPassword, withoutMembership, } from './writes.js';
24
+ export { addAlias, addToGroup, createGroupMailbox, createMailbox, enableHolding, holdLimit, purgeQueuedMessage, removeAlias, removeFromGroup, retryQueuedMessage, revokeApiKey, revokeAppPassword, spamSettings, updateSpamSettings, } from './apply.js';
25
+ export { loadQueue, queueMessageView, } from './queue.js';
25
26
  export { POSTMASTER_AUDIT_EVENTS, } from './audit.js';
@@ -114,6 +114,17 @@ export function mailObjects(i) {
114
114
  match: { id: 'singleton' },
115
115
  value: { defaultHostname: i.mailHost, defaultDomainId: ref('domain') },
116
116
  },
117
+ {
118
+ key: 'http',
119
+ object: 'Http',
120
+ match: { id: 'singleton' },
121
+ // Wildcard-only on 0.16: there is no per-origin allowlist to scope this
122
+ // to, and once on it answers every route, JMAP and management alike,
123
+ // including the preflight. That is safe here only because nothing
124
+ // reaches this server except through the tunnel, and the hub's own
125
+ // audience check on the token still stands in front of every request.
126
+ value: { usePermissiveCors: true },
127
+ },
117
128
  ...(i.oidc
118
129
  ? [
119
130
  {
@@ -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