@wtfalch/email 0.16.0 → 0.18.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.
package/README.md CHANGED
@@ -306,6 +306,29 @@ otherwise builds a URL addressing the wrong thing.
306
306
  display name. `src/mailbox/fixtures/instance-one.json` is recorded from a live
307
307
  0.16.20 instance and pins it.
308
308
 
309
+ **`Message.senderAuthenticated` reads the `Authentication-Results` header
310
+ Stalwart's inbound `DATA` handling stamps on accepted mail**, merging its
311
+ DKIM/DKIM2, SPF, IPREV and DMARC checks into one header
312
+ (`crates/smtp/src/inbound/data.rs`, `stalwartlabs/stalwart`, gated on a
313
+ config toggle, `dc.add_auth_results`, this package has not confirmed is on
314
+ for any real deployment), in the wire format
315
+ `stalwartlabs/mail-auth`'s `AuthenticationResults` `HeaderWriter` builds
316
+ (`src/auth_results.rs`). `thread()` reads every instance with RFC 8621
317
+ §4.1.3's `header:Authentication-Results:asRaw:all`, confirmed as a generic
318
+ `EmailProperty::Header` case (`crates/jmap/src/email/get.rs`) rather than a
319
+ hand-picked header list, and `mailbox/auth-results.ts` derives `true` from a
320
+ DKIM signature whose `header.d=`/`header.i=` domain exactly matches the
321
+ message's `from[0]` domain, or a `dmarc=pass`. **Fails closed**: a sender can write its own `Authentication-Results`
322
+ header, and the server hostname is public, so a matching `authserv-id` alone
323
+ proves nothing. Stalwart prepends its own header (`add_auth_results`, on by
324
+ default) and never strips incoming ones, so only the topmost instance is
325
+ read. `senderAuthenticated` is always `false` unless the caller passes
326
+ `{ trustedAuthServId }` (the instance's Stalwart `hostname`), and then only
327
+ if the first instance carries that `authserv-id` (case-insensitive); later
328
+ instances are never read. Setting the option asserts the receiving server
329
+ prepends its own header on every message; if it does not, leave it unset.
330
+ **Not confirmed**: which hostname a real instance uses.
331
+
309
332
  **`jmap-jam` is kept internal.** It ships raw TypeScript with `.ts` import
310
333
  specifiers, which only compiles under `allowImportingTsExtensions`; nothing of
311
334
  it reaches this package's public types, so a consumer does not inherit the
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Reading the `Authentication-Results` header (RFC 8601) Stalwart stamps on
3
+ * inbound mail it accepts, reduced to the one question `senderAuthenticated`
4
+ * answers: did this message's `From` domain pass DKIM alignment, or did the
5
+ * message pass DMARC.
6
+ *
7
+ * **What is confirmed, and how.** Stalwart's inbound `DATA` handling builds
8
+ * one `AuthenticationResults` value per message from its DKIM/DKIM2, SPF
9
+ * (HELO and MAIL FROM), IPREV and DMARC checks and writes it as a single
10
+ * `Authentication-Results` header (`crates/smtp/src/inbound/data.rs`,
11
+ * `stalwartlabs/stalwart`, functions building `auth_results` then calling
12
+ * `auth_results.write_header(&mut headers)`), gated on a config toggle
13
+ * (`dc.add_auth_results`) that a caller has not confirmed is enabled on any
14
+ * particular deployment. The wire format of each `resinfo` segment — `;`,
15
+ * then (on a fold) CRLF + tab, then `dkim=<result> header.d=<domain>
16
+ * header.s=<selector> header.i=<identity> header.b=<snippet>`, `spf=<result>
17
+ * smtp.helo=<domain>` / `smtp.mailfrom=<address>`, or `dmarc=<result>
18
+ * header.from=<domain> policy.dmarc=<policy>` — is
19
+ * `stalwartlabs/mail-auth`'s `AuthenticationResults`
20
+ * `HeaderWriter`/`with_dkim_results`/`with_spf_*_result`/`with_dmarc_result`
21
+ * (`src/auth_results.rs`), which Stalwart depends on for exactly this. RFC
22
+ * 8621 §4.1.3's `header:<Name>:asRaw:all` pseudo-property, which fetches
23
+ * every instance of a header field as its raw text, is confirmed as a
24
+ * genuine `EmailProperty::Header` case Stalwart resolves generically
25
+ * (`crates/jmap/src/email/get.rs`), not a hand-picked list of known headers.
26
+ *
27
+ * **What is not confirmed.** No live Stalwart deployment's `hostname`
28
+ * (RFC 8601's `authserv-id`, the first token of the header) was read to write
29
+ * this. RFC 8601 §5 warns that anything upstream of the trust boundary can
30
+ * plant its own `Authentication-Results` header, and the hostname is public,
31
+ * so a matching `authserv-id` alone proves nothing. What does hold: Stalwart
32
+ * prepends its own header (`add_auth_results`, on by default) and never
33
+ * strips incoming ones, so its instance is always the topmost.
34
+ * `senderAuthenticatedFrom` therefore fails closed and reads only the first
35
+ * instance: false with no `trustedAuthServId`, false if the first instance's
36
+ * `authserv-id` differs (case-insensitively), and it never looks further
37
+ * down. Setting `trustedAuthServId` asserts that the receiving server
38
+ * prepends its own header on every inbound message; if it does not, leave
39
+ * the option unset.
40
+ */
41
+ /** One `method=result` segment of a parsed `Authentication-Results` header,
42
+ * with its `ptype.property=value` pairs — RFC 8601 §2.2's `resinfo`. */
43
+ export type AuthResultSegment = {
44
+ method: string;
45
+ result: string;
46
+ properties: Readonly<Record<string, string>>;
47
+ };
48
+ export type ParsedAuthenticationResults = {
49
+ authServId: string;
50
+ results: readonly AuthResultSegment[];
51
+ };
52
+ /**
53
+ * One `Authentication-Results` header's raw text, folded or not, into its
54
+ * `authserv-id` and `resinfo` segments. `null` for text with no `authserv-id`
55
+ * (an empty or malformed header) — this never throws, since it reads a
56
+ * header nobody here wrote.
57
+ */
58
+ export declare function parseAuthenticationResults(raw: string): ParsedAuthenticationResults | null;
59
+ /** The domain of a mailbox address, lower-cased — everything after the last
60
+ * `@`, which is right even for a local part that itself contains one
61
+ * (a quoted local part can). Empty for an address with none. */
62
+ export declare function domainOf(email: string): string;
63
+ /**
64
+ * Did `fromEmail`'s domain pass DKIM alignment, or did the message pass
65
+ * DMARC — per the trust caveat this module's header comment spells out, read
66
+ * only from the first (topmost) `Authentication-Results` instance, and only
67
+ * if its `authserv-id` equals `trustedAuthServId`. Without a `trustedAuthServId` this is always
68
+ * false (fail closed): an unattributed header can be forged by the sender.
69
+ *
70
+ * **DKIM alignment is exact-domain, not relaxed-with-suffix.** RFC 7489's
71
+ * relaxed mode allows a signing domain that is an ancestor of the `From`
72
+ * domain, which needs a public-suffix list to compute correctly (otherwise
73
+ * two unrelated accounts under a shared public suffix such as `github.io`
74
+ * would read as aligned). This package carries no such list, so alignment
75
+ * here is exact match only — strict mode, one of RFC 7489's two defined
76
+ * modes, not an invention. A message DMARC itself judged aligned but that
77
+ * this exact check misses still passes, since the `dmarc=pass` branch below
78
+ * catches it independently.
79
+ */
80
+ export declare function senderAuthenticatedFrom(headers: readonly string[] | undefined, fromEmail: string | undefined, trustedAuthServId?: string): boolean;
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Reading the `Authentication-Results` header (RFC 8601) Stalwart stamps on
3
+ * inbound mail it accepts, reduced to the one question `senderAuthenticated`
4
+ * answers: did this message's `From` domain pass DKIM alignment, or did the
5
+ * message pass DMARC.
6
+ *
7
+ * **What is confirmed, and how.** Stalwart's inbound `DATA` handling builds
8
+ * one `AuthenticationResults` value per message from its DKIM/DKIM2, SPF
9
+ * (HELO and MAIL FROM), IPREV and DMARC checks and writes it as a single
10
+ * `Authentication-Results` header (`crates/smtp/src/inbound/data.rs`,
11
+ * `stalwartlabs/stalwart`, functions building `auth_results` then calling
12
+ * `auth_results.write_header(&mut headers)`), gated on a config toggle
13
+ * (`dc.add_auth_results`) that a caller has not confirmed is enabled on any
14
+ * particular deployment. The wire format of each `resinfo` segment — `;`,
15
+ * then (on a fold) CRLF + tab, then `dkim=<result> header.d=<domain>
16
+ * header.s=<selector> header.i=<identity> header.b=<snippet>`, `spf=<result>
17
+ * smtp.helo=<domain>` / `smtp.mailfrom=<address>`, or `dmarc=<result>
18
+ * header.from=<domain> policy.dmarc=<policy>` — is
19
+ * `stalwartlabs/mail-auth`'s `AuthenticationResults`
20
+ * `HeaderWriter`/`with_dkim_results`/`with_spf_*_result`/`with_dmarc_result`
21
+ * (`src/auth_results.rs`), which Stalwart depends on for exactly this. RFC
22
+ * 8621 §4.1.3's `header:<Name>:asRaw:all` pseudo-property, which fetches
23
+ * every instance of a header field as its raw text, is confirmed as a
24
+ * genuine `EmailProperty::Header` case Stalwart resolves generically
25
+ * (`crates/jmap/src/email/get.rs`), not a hand-picked list of known headers.
26
+ *
27
+ * **What is not confirmed.** No live Stalwart deployment's `hostname`
28
+ * (RFC 8601's `authserv-id`, the first token of the header) was read to write
29
+ * this. RFC 8601 §5 warns that anything upstream of the trust boundary can
30
+ * plant its own `Authentication-Results` header, and the hostname is public,
31
+ * so a matching `authserv-id` alone proves nothing. What does hold: Stalwart
32
+ * prepends its own header (`add_auth_results`, on by default) and never
33
+ * strips incoming ones, so its instance is always the topmost.
34
+ * `senderAuthenticatedFrom` therefore fails closed and reads only the first
35
+ * instance: false with no `trustedAuthServId`, false if the first instance's
36
+ * `authserv-id` differs (case-insensitively), and it never looks further
37
+ * down. Setting `trustedAuthServId` asserts that the receiving server
38
+ * prepends its own header on every inbound message; if it does not, leave
39
+ * the option unset.
40
+ */
41
+ /** Splits `text` on `sep` outside of a double-quoted run, honouring `\"` and
42
+ * `\\` as RFC 8601's `quoted-string` (borrowed from RFC 5322) escapes. */
43
+ function splitUnquoted(text, sep) {
44
+ const parts = [];
45
+ let current = '';
46
+ let inQuotes = false;
47
+ for (let i = 0; i < text.length; i++) {
48
+ const char = text[i];
49
+ if (char === '\\' && inQuotes && i + 1 < text.length) {
50
+ current += char + text[i + 1];
51
+ i++;
52
+ continue;
53
+ }
54
+ if (char === '"') {
55
+ inQuotes = !inQuotes;
56
+ current += char;
57
+ continue;
58
+ }
59
+ if (!inQuotes && char === sep) {
60
+ parts.push(current);
61
+ current = '';
62
+ continue;
63
+ }
64
+ current += char;
65
+ }
66
+ parts.push(current);
67
+ return parts;
68
+ }
69
+ /** Strips a `pvalue`'s surrounding quotes and un-escapes `\"`/`\\`, if it was
70
+ * quoted at all — `push_quoted_pvalue` only quotes a value that needs it. */
71
+ function unquote(value) {
72
+ const trimmed = value.trim();
73
+ if (trimmed.length < 2 || !trimmed.startsWith('"') || !trimmed.endsWith('"'))
74
+ return trimmed;
75
+ return trimmed.slice(1, -1).replace(/\\(.)/g, '$1');
76
+ }
77
+ /**
78
+ * One `Authentication-Results` header's raw text, folded or not, into its
79
+ * `authserv-id` and `resinfo` segments. `null` for text with no `authserv-id`
80
+ * (an empty or malformed header) — this never throws, since it reads a
81
+ * header nobody here wrote.
82
+ */
83
+ export function parseAuthenticationResults(raw) {
84
+ // RFC 5322 folding inserts CRLF before whitespace; a run of any whitespace
85
+ // reads the same as the single space it folds from.
86
+ const normalized = raw.replace(/\s+/g, ' ').trim();
87
+ if (!normalized)
88
+ return null;
89
+ const segments = splitUnquoted(normalized, ';').map((segment) => segment.trim());
90
+ const authServId = segments[0];
91
+ if (!authServId)
92
+ return null;
93
+ const results = [];
94
+ for (const segment of segments.slice(1)) {
95
+ if (!segment || segment.toLowerCase() === 'none')
96
+ continue;
97
+ const tokens = splitUnquoted(segment, ' ').filter((token) => token.length > 0);
98
+ const head = tokens[0];
99
+ if (!head)
100
+ continue;
101
+ const eq = head.indexOf('=');
102
+ if (eq < 0)
103
+ continue;
104
+ const method = head.slice(0, eq).trim().toLowerCase();
105
+ const result = head
106
+ .slice(eq + 1)
107
+ .trim()
108
+ .toLowerCase();
109
+ if (!method || !result)
110
+ continue;
111
+ const properties = {};
112
+ for (const token of tokens.slice(1)) {
113
+ const propEq = token.indexOf('=');
114
+ if (propEq < 0)
115
+ continue;
116
+ const key = token.slice(0, propEq).trim().toLowerCase();
117
+ const value = unquote(token.slice(propEq + 1));
118
+ if (key)
119
+ properties[key] = value;
120
+ }
121
+ results.push({ method, result, properties });
122
+ }
123
+ return { authServId, results };
124
+ }
125
+ /** The domain of a mailbox address, lower-cased — everything after the last
126
+ * `@`, which is right even for a local part that itself contains one
127
+ * (a quoted local part can). Empty for an address with none. */
128
+ export function domainOf(email) {
129
+ const at = email.lastIndexOf('@');
130
+ return at < 0 ? '' : email.slice(at + 1).toLowerCase();
131
+ }
132
+ /**
133
+ * Did `fromEmail`'s domain pass DKIM alignment, or did the message pass
134
+ * DMARC — per the trust caveat this module's header comment spells out, read
135
+ * only from the first (topmost) `Authentication-Results` instance, and only
136
+ * if its `authserv-id` equals `trustedAuthServId`. Without a `trustedAuthServId` this is always
137
+ * false (fail closed): an unattributed header can be forged by the sender.
138
+ *
139
+ * **DKIM alignment is exact-domain, not relaxed-with-suffix.** RFC 7489's
140
+ * relaxed mode allows a signing domain that is an ancestor of the `From`
141
+ * domain, which needs a public-suffix list to compute correctly (otherwise
142
+ * two unrelated accounts under a shared public suffix such as `github.io`
143
+ * would read as aligned). This package carries no such list, so alignment
144
+ * here is exact match only — strict mode, one of RFC 7489's two defined
145
+ * modes, not an invention. A message DMARC itself judged aligned but that
146
+ * this exact check misses still passes, since the `dmarc=pass` branch below
147
+ * catches it independently.
148
+ */
149
+ export function senderAuthenticatedFrom(headers, fromEmail, trustedAuthServId) {
150
+ if (!trustedAuthServId || !fromEmail)
151
+ return false;
152
+ const header = headers?.[0];
153
+ if (!header)
154
+ return false;
155
+ const parsed = parseAuthenticationResults(header);
156
+ if (!parsed || parsed.authServId.toLowerCase() !== trustedAuthServId.toLowerCase()) {
157
+ return false;
158
+ }
159
+ const fromDomain = domainOf(fromEmail);
160
+ if (!fromDomain)
161
+ return false;
162
+ for (const segment of parsed.results) {
163
+ if (segment.result !== 'pass')
164
+ continue;
165
+ if (segment.method === 'dmarc') {
166
+ const headerFrom = segment.properties['header.from'];
167
+ if (headerFrom?.toLowerCase() === fromDomain)
168
+ return true;
169
+ continue;
170
+ }
171
+ if (segment.method === 'dkim' || segment.method === 'dkim2') {
172
+ const d = segment.properties['header.d'];
173
+ if (d?.toLowerCase() === fromDomain)
174
+ return true;
175
+ const i = segment.properties['header.i'];
176
+ if (i && domainOf(i) === fromDomain)
177
+ return true;
178
+ }
179
+ }
180
+ return false;
181
+ }
@@ -15,7 +15,7 @@ export type { ListOptions } from './threads.ts';
15
15
  export { CANNOT_CALCULATE_CHANGES, emailChanges, emailHeaders, isCannotCalculateChanges, mailboxChanges, } from './changes.ts';
16
16
  export type { Changes, ChangesOptions, EmailHeaders, EmailHeadersPage } from './changes.ts';
17
17
  export { DEFAULT_MAX_BODY_BYTES, thread, toMessage } from './thread.ts';
18
- export type { RawMessage, ThreadOptions } from './thread.ts';
18
+ export type { RawMessage, ThreadOptions, ToMessageOptions } from './thread.ts';
19
19
  export { search } from './search.ts';
20
20
  export type { SearchOptions } from './search.ts';
21
21
  export { identities } from './identities.ts';
@@ -40,22 +40,32 @@ export type RawMessage = {
40
40
  htmlBody?: BodyPart[];
41
41
  attachments?: BodyPart[];
42
42
  bodyValues?: Record<string, BodyValue>;
43
+ 'header:Authentication-Results:asRaw:all'?: (string | null)[];
43
44
  };
44
45
  /** How many bytes of each body part to fetch. A message with a megabyte of
45
46
  * quoted history should not stall a thread view; anything cut short is
46
47
  * reported as `isTruncated`. */
47
48
  export declare const DEFAULT_MAX_BODY_BYTES: number;
49
+ export type ToMessageOptions = {
50
+ /** The `authserv-id` (Stalwart's `hostname`) the topmost
51
+ * `Authentication-Results` instance must carry for `senderAuthenticated`
52
+ * to read it, compared case-insensitively. Setting it asserts the receiving
53
+ * server prepends its own header on every inbound message (Stalwart's
54
+ * `add_auth_results`, on by default); if it does not, leave this unset.
55
+ * Unset means `senderAuthenticated` is always false. */
56
+ trustedAuthServId?: string;
57
+ };
48
58
  /** Turn one `Email/get` result into a `Message`, resolving its bodies and
49
59
  * giving every attachment a download URL. */
50
60
  export declare function toMessage(raw: RawMessage, downloadUrlFor: (blob: {
51
61
  blobId: string;
52
62
  name: string;
53
63
  type: string;
54
- }) => string): Message;
64
+ }) => string, options?: ToMessageOptions): Message;
55
65
  export type ThreadOptions = {
56
66
  /** Bytes of each body part to fetch. */
57
67
  maxBodyBytes?: number;
58
- };
68
+ } & ToMessageOptions;
59
69
  /** One thread, with every message's body and attachments, oldest first. */
60
70
  export declare function thread(client: MailClient, threadId: string, options?: ThreadOptions): Promise<ThreadDetail>;
61
71
  export {};
@@ -1,3 +1,4 @@
1
+ import { senderAuthenticatedFrom } from "./auth-results.js";
1
2
  import { JAM_FETCH } from "./client.js";
2
3
  import { MailError, guard } from "./errors.js";
3
4
  import { expandTemplate } from "./uri.js";
@@ -25,6 +26,9 @@ const MESSAGE_PROPERTIES = [
25
26
  'htmlBody',
26
27
  'attachments',
27
28
  'bodyValues',
29
+ // RFC 8621 §4.1.3: every instance of the header, raw. See
30
+ // `auth-results.ts`'s module doc for the header this reads.
31
+ 'header:Authentication-Results:asRaw:all',
28
32
  ];
29
33
  const BODY_PROPERTIES = [
30
34
  'partId',
@@ -74,10 +78,11 @@ function joinParts(parts, values, type) {
74
78
  }
75
79
  /** Turn one `Email/get` result into a `Message`, resolving its bodies and
76
80
  * giving every attachment a download URL. */
77
- export function toMessage(raw, downloadUrlFor) {
81
+ export function toMessage(raw, downloadUrlFor, options = {}) {
78
82
  const text = joinParts(raw.textBody, raw.bodyValues, 'text/plain');
79
83
  const html = joinParts(raw.htmlBody, raw.bodyValues, 'text/html');
80
84
  const keywords = raw.keywords ?? {};
85
+ const authResultsHeaders = (raw['header:Authentication-Results:asRaw:all'] ?? []).filter((header) => typeof header === 'string' && header.length > 0);
81
86
  const attachments = (raw.attachments ?? [])
82
87
  // A part with no blob cannot be fetched, so it is not an attachment a
83
88
  // reader can do anything with.
@@ -121,6 +126,7 @@ export function toMessage(raw, downloadUrlFor) {
121
126
  isUnread: keywords.$seen !== true,
122
127
  isFlagged: keywords.$flagged === true,
123
128
  isDraft: keywords.$draft === true,
129
+ senderAuthenticated: senderAuthenticatedFrom(authResultsHeaders, raw.from?.[0]?.email, options.trustedAuthServId),
124
130
  };
125
131
  }
126
132
  /** One thread, with every message's body and attachments, oldest first. */
@@ -155,7 +161,7 @@ export async function thread(client, threadId, options = {}) {
155
161
  blobId: blob.blobId,
156
162
  name: blob.name,
157
163
  type: blob.type,
158
- })))
164
+ }), { trustedAuthServId: options.trustedAuthServId }))
159
165
  // A thread reads oldest first, whatever order the server listed it in.
160
166
  .sort((a, b) => (a.receivedAt < b.receivedAt ? -1 : a.receivedAt > b.receivedAt ? 1 : 0));
161
167
  return {
@@ -181,6 +181,16 @@ export type Message = {
181
181
  isUnread: boolean;
182
182
  isFlagged: boolean;
183
183
  isDraft: boolean;
184
+ /** Did `from[0]`'s domain pass DKIM alignment, or did the message pass
185
+ * DMARC, per the `Authentication-Results` header Stalwart stamps on
186
+ * accepted inbound mail. `false` for a message with no such header (a
187
+ * sent message, one from before this deployment enabled it, or a
188
+ * deployment with it off), one whose checks failed outright, and a
189
+ * forwarded message whose own alignment rarely survives a second hop —
190
+ * `false` never distinguishes those from each other. See
191
+ * `mailbox/auth-results.ts`'s module doc for what is and is not confirmed
192
+ * about this header on a real deployment. */
193
+ senderAuthenticated: boolean;
184
194
  };
185
195
  /** A thread, opened. */
186
196
  export type ThreadDetail = {
@@ -17,7 +17,7 @@
17
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
- export { FUTURE_RELEASE, applyObjects, mailObjects, ref, type MailObjectsInput, type PlannedObject, } from './objects.js';
20
+ export { FUTURE_RELEASE, applyObjects, mailObjects, platformMailSettingsObjects, ref, type MailObjectsInput, type PlannedObject, type PlatformMailSettingsInput, } from './objects.js';
21
21
  export { planMailboxes, withPassword } from './mailboxes.js';
22
22
  export { overview, pickDomain, type AccountView, type CredentialSummary, type DomainView, type Managed, type Overview, type OverviewInput, type PeopleView, type Person, type WireAccount, type WireAlias, type WireDomain, type WireSystemSettings, } from './overview.js';
23
23
  export { MailWriteRefused, membershipIds, newAccount, newGroup, withAlias, withMembership, withoutAlias, withoutApiKey, withoutAppPassword, withoutMembership, } from './writes.js';
@@ -17,7 +17,7 @@
17
17
  export { API_KEY_PREFIX, DASHBOARD_PERMISSIONS, StalwartClient, StalwartError, authFor, } from './client.js';
18
18
  export { InstanceRefused, openInstance } from './instance.js';
19
19
  export { loadOverview } from './load.js';
20
- export { FUTURE_RELEASE, applyObjects, mailObjects, ref, } from './objects.js';
20
+ export { FUTURE_RELEASE, applyObjects, mailObjects, platformMailSettingsObjects, ref, } from './objects.js';
21
21
  export { planMailboxes, withPassword } from './mailboxes.js';
22
22
  export { overview, pickDomain, } from './overview.js';
23
23
  export { MailWriteRefused, membershipIds, newAccount, newGroup, withAlias, withMembership, withoutAlias, withoutApiKey, withoutAppPassword, withoutMembership, } from './writes.js';
@@ -53,6 +53,30 @@ export interface PlannedObject {
53
53
  match: Record<string, unknown>;
54
54
  value: Record<string, unknown>;
55
55
  }
56
+ export interface PlatformMailSettingsInput {
57
+ /** The platform's own apex domain, written lowercased as `usernameDomain`. */
58
+ apex: string;
59
+ /** The MX target and TLS name, e.g. `mx.example.com`. */
60
+ mailHost: string;
61
+ oidc: {
62
+ issuerUrl: string;
63
+ audience: string;
64
+ requireScopes?: Record<string, boolean>;
65
+ claimUsername?: string;
66
+ };
67
+ }
68
+ /**
69
+ * The platform's own mail settings: Stalwart's default hostname and an OIDC
70
+ * sign-in directory, and nothing else. `mailObjects` cannot stand in for
71
+ * this — it also writes an `AcmeProvider`, a `DnsServer` and a Resend
72
+ * `MtaRoute`, none of which the platform step wants.
73
+ *
74
+ * A blank `mailHost`, `apex`, `oidc.issuerUrl` or `oidc.audience` throws,
75
+ * naming the field: each reaches a live server, and a blank audience in
76
+ * particular lets Stalwart skip the audience check, so any token from the
77
+ * issuer would sign in.
78
+ */
79
+ export declare function platformMailSettingsObjects(input: PlatformMailSettingsInput): PlannedObject[];
56
80
  /**
57
81
  * `MtaExtensions.futureRelease`: how long the server will hold a message
58
82
  * before sending it. It gates the SMTP FUTURERELEASE extension. Empty by
@@ -2,6 +2,115 @@ import { outboundRoute } from './org-mail.js';
2
2
  /** A value that names an object created earlier in the same plan. */
3
3
  export const ref = (key) => ({ $ref: key });
4
4
  const env = (variableName) => ({ '@type': 'EnvironmentVariable', variableName });
5
+ /**
6
+ * The `Directory` of `@type: 'Oidc'` that signs people in against an
7
+ * identity provider, in the one field shape both `mailObjects` (an org
8
+ * domain) and `platformMailSettingsObjects` (the platform's own server)
9
+ * write it in. Shared so the two never drift apart.
10
+ */
11
+ function oidcDirectoryObject(apex, oidc) {
12
+ const description = `${oidc.issuerUrl} (${apex})`;
13
+ return {
14
+ key: 'oidc',
15
+ object: 'Directory',
16
+ match: { description },
17
+ value: {
18
+ '@type': 'Oidc',
19
+ description,
20
+ issuerUrl: oidc.issuerUrl,
21
+ requireAudience: oidc.audience,
22
+ requireScopes: oidc.requireScopes ?? {},
23
+ claimUsername: oidc.claimUsername ?? 'preferred_username',
24
+ usernameDomain: apex,
25
+ claimName: 'name',
26
+ },
27
+ };
28
+ }
29
+ function requireNonBlank(value, fieldName) {
30
+ const trimmed = value.trim();
31
+ if (!trimmed)
32
+ throw new Error(`platformMailSettingsObjects: "${fieldName}" must not be blank`);
33
+ return trimmed;
34
+ }
35
+ /**
36
+ * Stalwart compares `iss` as a plain string, and the Directory's `match` key
37
+ * is built from the raw issuer, so a respelling of the same issuer creates a
38
+ * second Directory instead of updating the first. This rejects every
39
+ * respelling rather than normalising it: a non-canonical issuer in the
40
+ * caller's config is a configuration bug worth surfacing, not silently
41
+ * fixing up.
42
+ */
43
+ function validatedIssuerUrl(raw) {
44
+ const issuerUrl = requireNonBlank(raw, 'oidc.issuerUrl');
45
+ if (issuerUrl.endsWith('/')) {
46
+ throw new Error('platformMailSettingsObjects: "oidc.issuerUrl" must not end with a trailing slash');
47
+ }
48
+ let url;
49
+ try {
50
+ url = new URL(issuerUrl);
51
+ }
52
+ catch {
53
+ throw new Error('platformMailSettingsObjects: "oidc.issuerUrl" must be a valid URL');
54
+ }
55
+ if (url.protocol !== 'https:') {
56
+ throw new Error('platformMailSettingsObjects: "oidc.issuerUrl" must be https');
57
+ }
58
+ const canonical = url.origin + (url.pathname === '/' ? '' : url.pathname);
59
+ if (canonical !== issuerUrl) {
60
+ throw new Error('platformMailSettingsObjects: "oidc.issuerUrl" must be in canonical form (no case, userinfo, query, fragment, or respelling)');
61
+ }
62
+ return issuerUrl;
63
+ }
64
+ function validatedClaimUsername(raw) {
65
+ if (raw === undefined)
66
+ return 'preferred_username';
67
+ return requireNonBlank(raw, 'oidc.claimUsername');
68
+ }
69
+ /**
70
+ * The platform's own mail settings: Stalwart's default hostname and an OIDC
71
+ * sign-in directory, and nothing else. `mailObjects` cannot stand in for
72
+ * this — it also writes an `AcmeProvider`, a `DnsServer` and a Resend
73
+ * `MtaRoute`, none of which the platform step wants.
74
+ *
75
+ * A blank `mailHost`, `apex`, `oidc.issuerUrl` or `oidc.audience` throws,
76
+ * naming the field: each reaches a live server, and a blank audience in
77
+ * particular lets Stalwart skip the audience check, so any token from the
78
+ * issuer would sign in.
79
+ */
80
+ export function platformMailSettingsObjects(input) {
81
+ const mailHost = requireNonBlank(input.mailHost, 'mailHost');
82
+ const apex = requireNonBlank(input.apex, 'apex').toLowerCase();
83
+ const issuerUrl = validatedIssuerUrl(input.oidc.issuerUrl);
84
+ const audience = requireNonBlank(input.oidc.audience, 'oidc.audience');
85
+ const claimUsername = validatedClaimUsername(input.oidc.claimUsername);
86
+ const directory = oidcDirectoryObject(apex, {
87
+ issuerUrl,
88
+ audience,
89
+ requireScopes: input.oidc.requireScopes,
90
+ claimUsername,
91
+ });
92
+ return [
93
+ {
94
+ key: 'system',
95
+ object: 'SystemSettings',
96
+ match: { id: 'singleton' },
97
+ value: { defaultHostname: mailHost },
98
+ },
99
+ directory,
100
+ {
101
+ key: 'auth',
102
+ object: 'Authentication',
103
+ match: { id: 'singleton' },
104
+ value: { directoryId: ref('oidc') },
105
+ },
106
+ {
107
+ key: 'reload',
108
+ object: 'Action',
109
+ match: {},
110
+ value: { '@type': 'ReloadSettings' },
111
+ },
112
+ ];
113
+ }
5
114
  /**
6
115
  * `MtaExtensions.futureRelease`: how long the server will hold a message
7
116
  * before sending it. It gates the SMTP FUTURERELEASE extension. Empty by
@@ -21,26 +130,7 @@ export const FUTURE_RELEASE = { else: "'30d'" };
21
130
  * server. What each object is for is in wtfalch-manage's docs/plans/email.md (E3 to E5).
22
131
  */
23
132
  export function mailObjects(i) {
24
- const oidcDescription = i.oidc ? `${i.oidc.issuerUrl} (${i.apex})` : undefined;
25
- const directory = i.oidc
26
- ? [
27
- {
28
- key: 'oidc',
29
- object: 'Directory',
30
- match: { description: oidcDescription },
31
- value: {
32
- '@type': 'Oidc',
33
- description: oidcDescription,
34
- issuerUrl: i.oidc.issuerUrl,
35
- requireAudience: i.oidc.audience,
36
- requireScopes: i.oidc.requireScopes ?? {},
37
- claimUsername: i.oidc.claimUsername ?? 'preferred_username',
38
- usernameDomain: i.apex,
39
- claimName: 'name',
40
- },
41
- },
42
- ]
43
- : [];
133
+ const directory = i.oidc ? [oidcDirectoryObject(i.apex, i.oidc)] : [];
44
134
  return [
45
135
  {
46
136
  key: 'acme',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/email",
3
- "version": "0.16.0",
3
+ "version": "0.18.0",
4
4
  "description": "The wtfalch estate: reading a mailbox over JMAP, administering the Stalwart server it lives on, and iTIP scheduling over iMIP. Three entries with no code in common.",
5
5
  "license": "MIT",
6
6
  "type": "module",