@wtfalch/email 0.9.0 → 0.10.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 William Tallis Falch
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,345 @@
1
+ # @wtfalch/email
2
+
3
+ The estate's mail, in two entries with **no code in common**:
4
+
5
+ @wtfalch/email/mailbox reading and writing messages (RFC 8620/8621)
6
+ @wtfalch/email/postmaster administering the server (Stalwart's `x:` extension)
7
+
8
+ They share a subject, a scope and a repository, and nothing else. There is
9
+ deliberately no root entry: an entry named for a seam that does not exist is
10
+ worse than no entry at all.
11
+
12
+ `/mailbox` is for the person who has an address — inbox, threads, compose —
13
+ running in their browser as them, able to touch only their own mail.
14
+ `/postmaster` is for whoever runs the server — who gets a mailbox, what name
15
+ is on it, who holds a key — running server-side with an administrator
16
+ credential, and never touching the contents of anybody's messages.
17
+
18
+ The post office holds the analogy: one is the letters, the other is the
19
+ pigeonholes.
20
+
21
+ ---
22
+
23
+ ## @wtfalch/email/mailbox
24
+
25
+ Read and write mail over JMAP: session, mailbox tree, threads, bodies and
26
+ attachments, search, identities, submission and push. RFC 8620 and 8621, over
27
+ [`jmap-jam`](https://github.com/htunnicliff/jmap-jam), so it is not tied to
28
+ Stalwart the way its neighbour is.
29
+
30
+ ```ts
31
+ import { MailClient, mailboxes, findRole, listThreads, thread } from '@wtfalch/email/mailbox';
32
+
33
+ const client = new MailClient({
34
+ sessionUrl: 'https://email.example.com/.well-known/jmap',
35
+ bearerToken: accessToken, // the signed-in person's, from the issuer
36
+ });
37
+
38
+ const tree = await mailboxes(client);
39
+ const page = await listThreads(client, findRole(tree, 'inbox').id, { limit: 50 });
40
+ ```
41
+
42
+ A page of threads is **one round trip**: the query, the newest message per
43
+ thread, the threads' member ids and the members are four method calls chained
44
+ by JMAP result reference in a single request.
45
+
46
+ `replyDraft` and `forwardDraft` are pure — give them a message and they
47
+ compute the recipients, the subject prefix, the `In-Reply-To` and `References`
48
+ chain and the quoted body, with no client and no network, so a composer can
49
+ call them on every keystroke. `send` creates the draft, submits it, and files
50
+ it in Sent. `attach` uploads a file and gives back what a draft carries; the
51
+ upload is refused before any of it is sent when the file is over the
52
+ session's `maxSizeUpload`, which `client.session()` reports alongside
53
+ `maxSizeAttachmentsPerEmail`.
54
+
55
+ `setRead`, `setFlagged`, `moveThread`, `moveToRole` and `removeFromMailbox`
56
+ change mail rather than read it, and every one of them takes a **thread**.
57
+ RFC 8621 has no `Thread/set` — a thread is derived from its messages — so
58
+ each resolves the members and patches all of them in one `Email/set`, because
59
+ a conversation half-archived or half-read is not a thing anybody asked for.
60
+ They resolve when the server has accepted the change; nothing here is
61
+ optimistic, since the count is the one number people trust.
62
+
63
+ ```ts
64
+ await setRead(client, threadId, true);
65
+ await moveToRole(client, threadId, 'archive', { mailboxes: tree });
66
+ ```
67
+
68
+ Note that a stock Stalwart account has **no Archive mailbox** — it creates
69
+ Inbox, Drafts, Sent Items, Junk Mail and Deleted Items — so `moveToRole(…,
70
+ 'archive')` throws there rather than doing nothing, and a caller should offer
71
+ the action only where `findRole(tree, 'archive')` finds one.
72
+
73
+ ### The React
74
+
75
+ `@wtfalch/email/mailbox/react` draws it, on `@wtfalch/design` 0.5.0 or
76
+ later. `Mail` is the whole client — mailboxes, list, message, composer,
77
+ search, a toolbar, and a command palette on Cmd-K — and the only piece that
78
+ holds state or fetches.
79
+ `MailboxTree`, `ThreadList`, `ThreadView` and `Composer` take their data as
80
+ props and know nothing about a client, so an application with its own layout
81
+ takes the four and skips the shell. `HtmlBody`, which `ThreadView` draws a
82
+ message's HTML with, is exported on its own too. Import `@wtfalch/email/mailbox/mail.css`
83
+ after the design stylesheet.
84
+
85
+ **Three layouts, and the middle one is not decoration.** Three panes above
86
+ 1150px, an icon rail and two panes above 860px, one pane at a time below it.
87
+ That last is why `usePanes` is a hook and not a media query: at one column the
88
+ list and the message are the same space, so which of them is showing is state
89
+ the shell has to hold.
90
+
91
+ **The keyboard is the point.** Arrows and `j`/`k` move through the list, which
92
+ is a single tab stop rather than fifty; `c` writes, `r`/`a`/`f` answer,
93
+ `e`/`#`/`u`/`s` file, `/` searches and `?` lists them all. They are ignored
94
+ while a field has focus, or `c` could never be typed into a subject.
95
+
96
+ **Opening a conversation marks it read**, which is what opening means — and
97
+ only when there is something unread in it, because a `set` that changes
98
+ nothing still moves the account's state and wakes every other client's push
99
+ connection.
100
+
101
+ **A file is on the draft only once it has uploaded.** Attach opens the file
102
+ picker, and a file dropped anywhere on the composer is taken too. Until its
103
+ upload lands it sits in the list with a spinner and Send waits, because a
104
+ message that went while a file was on its way arrives without it. One that
105
+ failed says why and can be tried again; one over the server's limits is
106
+ refused before a byte is sent. Either stays in the list, and Send keeps
107
+ waiting, until it is retried or removed. `Composer` takes the upload as an
108
+ `onAttach` prop, since it holds no client, and `Mail` supplies `attach`.
109
+
110
+ **HTML is drawn in a frame it cannot climb out of.** Mail arrives from
111
+ strangers, and a client that injects their markup into its own document is one
112
+ script tag from being read by them. So `HtmlBody` never does. Three walls,
113
+ each of which holds if the other two fall:
114
+
115
+ - **A sandboxed frame.** A `srcdoc` iframe with no `allow-scripts`, no
116
+ `allow-forms` and no `allow-top-navigation`: nothing in it runs, submits or
117
+ replaces the page. Links open a tab of their own. It has
118
+ `allow-same-origin`, deliberately, so the view can size the frame to the
119
+ message; that is safe only because nothing in it can run, and
120
+ `FRAME_SANDBOX` is pinned by a test that fails if `allow-scripts` joins it.
121
+ - **A content policy of its own.** `default-src 'none'`, inline styles and
122
+ nothing else, `form-action` and `base-uri` closed, no fonts, and images from
123
+ `data:` only.
124
+ - **A sanitiser.** An allowlist of elements and attributes, walked over an
125
+ inert `DOMParser` document, for what the other two do not stop — a `<meta>`
126
+ refresh, a `<base>`, a `ping`, a relative address that would fetch from this
127
+ application. CSS is read back through the CSSOM rather than matched with a
128
+ pattern, so `u\72l(` is caught as the `url(` it is.
129
+
130
+ **Remote images wait to be asked for.** An image on the sender's server tells
131
+ the sender the message was opened, when and from where, so they are withheld
132
+ and the reader is told how many, with a button that shows them for that
133
+ message. Inline `cid:` pictures are part of the message and are drawn — fetched
134
+ through `fetchInline`, behind the same credential as everything else.
135
+
136
+ **Plain text first, where there is a choice.** A message with both bodies is
137
+ shown as its text, with the formatted version a button away. HTML is drawn on
138
+ white in either theme, because it was written for white.
139
+
140
+ A `srcdoc` frame inherits the embedding page's content policy as well as
141
+ carrying its own, so a host whose policy has no `style-src 'unsafe-inline'`
142
+ will draw mail unstyled, and one whose `img-src` has no `data:` will draw it
143
+ without pictures.
144
+
145
+ **Mailboxes are drawn in reading order, not the server's.** Stalwart gives all
146
+ five `sortOrder: 0`, so the tie-break by name puts Deleted Items first and
147
+ Inbox third. `mailboxes()` still reports what the server said.
148
+
149
+ ### A mailbox with no server
150
+
151
+ `@wtfalch/email/mailbox/fake` is an inbox in memory, for stories, for a
152
+ development build and for tests.
153
+
154
+ ```ts
155
+ const { client, mailbox, dispose } = fakeMail();
156
+ const tree = await mailboxes(client); // the real function, over the real wire code
157
+ ```
158
+
159
+ **It fakes the transport, not the API.** Stubbing the exported functions would
160
+ mean every story exercises the stub while the four-call chain, the result
161
+ references, the body resolution and the null-handling never run. It answers
162
+ JMAP instead. It replaces the global `fetch`, because `jmap-jam` calls the
163
+ bare global and takes no way to pass another one; the replacement delegates
164
+ anything not addressed to it, and `dispose()` puts it back.
165
+
166
+ ## What it knows that the RFCs do not
167
+
168
+ **RFC 8621 §7.5's `onSuccessUpdateEmail` collides.** The server returns the
169
+ implicit `Email/set` under the *same method call id* as the
170
+ `EmailSubmission/set` that triggered it, so a client reading a multi-call
171
+ response into a map by id loses the submission's own result. `jmap-jam` does
172
+ exactly that, so `send` submits through the single-call path — and creates the
173
+ draft in a separate request, which also leaves a failed send in Drafts rather
174
+ than losing it.
175
+
176
+ **The event source is authenticated**, and the browser `EventSource` cannot
177
+ send a header. `push` reads the stream with `fetch` and parses the
178
+ server-sent events itself.
179
+
180
+ **Session URLs are templates that need encoding.** RFC 8620 §6.2 requires it,
181
+ and `jmap-jam`'s expander does not: an attachment called `Q3 report (final).pdf`
182
+ otherwise builds a URL addressing the wrong thing.
183
+
184
+ **Stalwart sends `null`, not an omitted property**, for an absent header or
185
+ display name. `src/mailbox/fixtures/instance-one.json` is recorded from a live
186
+ 0.16.20 instance and pins it.
187
+
188
+ **`jmap-jam` is kept internal.** It ships raw TypeScript with `.ts` import
189
+ specifiers, which only compiles under `allowImportingTsExtensions`; nothing of
190
+ it reaches this package's public types, so a consumer does not inherit the
191
+ flag.
192
+
193
+ ## @wtfalch/email/postmaster
194
+
195
+ Administer a [Stalwart](https://stalw.art) mail server: its domain, its
196
+ mailboxes, their aliases, their app passwords and their quotas, over the JMAP
197
+ management API.
198
+
199
+ **This is not a JMAP mail client.** It speaks the `urn:stalwart:jmap`
200
+ management extension — `x:Account`, `x:Domain`, `x:ApiKey` and their
201
+ neighbours — which is a different surface from RFC 8620 and 8621 entirely.
202
+
203
+ **The credential is why this entry must never reach a browser.** `/mailbox`
204
+ runs in a browser holding the signed-in person's token. This runs on a server
205
+ holding an administrative one. A minted key **can** be scoped — that is what
206
+ `DASHBOARD_PERMISSIONS` is for — but nothing obliges a caller to hand this
207
+ entry a scoped one, and an account password or an `'inherit'` key is as
208
+ powerful as the account itself.
209
+
210
+ Neither a package boundary nor an entry name enforces that: bundlers follow
211
+ imports. What does is the `browser` condition in the exports map, which
212
+ resolves this entry to a module that throws with an explanatory message. It
213
+ was `server-only` for one commit, which was wrong — that throws in *any*
214
+ environment without React's `react-server` condition, plain Node included, so
215
+ it blocked `pnpm bootstrap` and `mail:sync`, which are exactly the callers
216
+ this entry is Node-safe for. The `browser` condition tells the illegitimate
217
+ caller from the legitimate one; `server-only` could not.
218
+
219
+ ```ts
220
+ import { openInstance, overview } from '@wtfalch/email/postmaster'; // pure Node
221
+ import { DomainCard, Mailboxes, People } from '@wtfalch/email/postmaster/react';
222
+ ```
223
+
224
+ The first entry has no React in it, so a provisioning script can use it. The
225
+ components are server components except the two interactive leaves, and they
226
+ take data and already-bound actions: **nothing here fetches, gates or
227
+ decides.** The consuming app reads the instance, asks its own authorisation,
228
+ binds its own Server Actions and passes the results in — the division
229
+ `@wtfalch/threads` draws, and what keeps a package free of anybody's session.
230
+
231
+ **`openInstance` refuses with a reason, not a sentence.** It throws
232
+ `InstanceRefused`, whose `reason` is `'not-https'` or `'account-missing'`.
233
+ Branch on that. Both refusals were once a plain `Error`, so consumers told
234
+ them apart by matching words in the message, and rewording a sentence here
235
+ quietly changed which error a dashboard showed.
236
+
237
+ ```ts
238
+ try {
239
+ openInstance({ url, secret, user });
240
+ } catch (e) {
241
+ if (e instanceof InstanceRefused && e.reason === 'account-missing') …
242
+ }
243
+ ```
244
+
245
+ `@wtfalch/design` is an optional peer dependency, needed only for `/react`.
246
+
247
+ ## What it knows that the docs do not
248
+
249
+ Every one of these was established against a live 0.16.20 instance, and each
250
+ cost an afternoon.
251
+
252
+ **An API key authenticates as `Authorization: Bearer`, never Basic.** The
253
+ same secret sent as Basic is refused with 401 whatever username accompanies
254
+ it — the account name, the local part, the key itself, none. `authFor` picks
255
+ the scheme from the secret's own shape, since a key is `API_`-prefixed.
256
+
257
+ **An API key is scoped with the `sys*` permission names.** `permissions` takes
258
+ `{'@type': 'Replace', permissions: {…}}`, a Set, so `{sysDomainGet: true}`.
259
+ The names live in `enums.Permission`, and the management ones read
260
+ `sys<Object><Verb>`. An earlier round of sixty guessed names accepted only
261
+ `authenticate` and `impersonate`, which is what made a scoped key look
262
+ impossible; the guesses were wrong, not the feature.
263
+
264
+ `createApiKey` therefore mints a scoped key by default. `DASHBOARD_PERMISSIONS`
265
+ is the set verified on 0.16.20: `authenticate` plus `sysAccountQuery`,
266
+ `sysAccountGet`, `sysAccountCreate`, `sysAccountUpdate`, `sysDomainQuery`,
267
+ `sysDomainGet` and `sysSystemSettingsGet`. It serves every `/email` page, and
268
+ it is `forbidden` on `Email/query` for every account on the instance —
269
+ including its own, so the key administers mail and cannot read any. Pass
270
+ `'inherit'` for a key as powerful as the account; prefer not to.
271
+
272
+ **An API key can never create a credential.** It authenticates, and both
273
+ `x:ApiKey/set` and `x:AppPassword/set` answer `forbidden` whatever permissions
274
+ it holds, so a key cannot mint its own successor. Rotating one needs the
275
+ account's password or app password. On a domain with an external directory the
276
+ account password stops being verified locally as well, which leaves an app
277
+ password the only credential that can still write — and the admin UI will not
278
+ add one from the account form, answering "Secondary credentials cannot be set
279
+ directly". Provision the replacement before revoking the one in use.
280
+
281
+ **A `List<T>` write replaces the whole list.** Adding one alias means sending
282
+ back every alias that survives. A read-modify-write that drops an entry does
283
+ not fail; it deletes somebody's alias, or every app password on their phone.
284
+ `withAlias`, `withoutAlias` and `withoutAppPassword` exist so that arithmetic
285
+ is decided by a unit test rather than at the end of a request.
286
+
287
+ **There is no conditional write.** JMAP's answer to the above is `ifInState`,
288
+ and these objects do not offer it: `x:Account/get` returns `accountId`,
289
+ `list` and `notFound` with no state token, and `x:Account/set` rejects an
290
+ `ifInState` argument outright as `notRequest`. So two overlapping writes to
291
+ one mailbox still lose one, and what `apply.ts` does instead is notice: it
292
+ re-reads afterwards and names anything the caller never touched that has
293
+ gone.
294
+
295
+ **Wire shapes are not what the docs show.** A `List<T>` is a map keyed by
296
+ index (`{"0": …}`), a `Map<T>` is `{"value": true}`, a `SecretKey` from the
297
+ environment is `{"@type":"EnvironmentVariable","variableName":"…"}`, and
298
+ singletons are addressed with the id `singleton`. An administrator's `roles`
299
+ is `{'@type': 'Admin'}`. `usedDiskQuota` is a plain byte count; `quotas` is
300
+ an object whose key for a *set* quota has never been observed, so
301
+ `overview()` reports no limit rather than inventing a number.
302
+
303
+ ## Refusals
304
+
305
+ The write helpers refuse rather than doing something surprising: an alias
306
+ given as a whole address (it would become an address at
307
+ `w@example.com@example.com`), a duplicate (an unreachable second entry),
308
+ revoking an account `Password` or an `ApiKey` through a call meant for app
309
+ passwords, and creating a mailbox on a domain that keeps its own passwords,
310
+ which needs a first password shown once and so points at a terminal tool
311
+ instead.
312
+
313
+ ## The audit
314
+
315
+ `createMailbox`, `addAlias`, `removeAlias` and `revokeAppPassword` take an
316
+ optional last argument, a `PostmasterAudit`: a `write` the host bound to its
317
+ own ledger, the principal it resolved for this request, and the request id
318
+ its log uses. Without one, nothing changes.
319
+
320
+ ```ts
321
+ const applied = await addAlias(instance, { accountId, name, domainId, apex }, {
322
+ write: (event) => ledger.record(event), // the host's, bound to `mail`
323
+ actor: { id: principal.id, display: principal.display },
324
+ requestId,
325
+ });
326
+ ```
327
+
328
+ **A write records what happened, after the server has answered.** The
329
+ event carries the before/after pair the write computed — which alias, on
330
+ which mailbox; which app password, by its description — so a host does not
331
+ reassemble it from `Applied`. It is never a secret: `target.id` is an
332
+ address or a credential id.
333
+
334
+ **A refused write records nothing.** It throws before `write` is called, and
335
+ recording the attempt is the caller's, since only the caller knows who was
336
+ refused and why. Nor can the two be atomic — one is a mail server, the other
337
+ is the host's database — so a crash between them loses the row, and the
338
+ request id is what joins it back to a log line.
339
+
340
+ **The names are `mail.*`, declared in `POSTMASTER_AUDIT_EVENTS`** so a host
341
+ can merge them into its ledger's vocabulary. A host whose vocabulary is
342
+ closed maps them instead: `wtfalch-manage`'s database refuses any action
343
+ outside its authorisation package's set, so its writer puts each back on the
344
+ core event it already recorded these under, and signs the row with the
345
+ principal it resolved rather than the one the event echoes.
@@ -3,7 +3,7 @@
3
3
  * and for tests that want to exercise this package rather than a stub.
4
4
  *
5
5
  * ```ts
6
- * import { fakeMail } from '@wtfalch/mail/fake'
6
+ * import { fakeMail } from '@wtfalch/email/mailbox/fake'
7
7
  *
8
8
  * const { client, mailbox, dispose } = fakeMail()
9
9
  * const tree = await mailboxes(client) // the real function
@@ -3,7 +3,7 @@
3
3
  * and for tests that want to exercise this package rather than a stub.
4
4
  *
5
5
  * ```ts
6
- * import { fakeMail } from '@wtfalch/mail/fake'
6
+ * import { fakeMail } from '@wtfalch/email/mailbox/fake'
7
7
  *
8
8
  * const { client, mailbox, dispose } = fakeMail()
9
9
  * const tree = await mailboxes(client) // the real function
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `@wtfalch/mail` — a JMAP mail client core.
2
+ * `@wtfalch/email/mailbox` — a JMAP mail client core.
3
3
  *
4
4
  * Everything takes a `MailClient` and returns this package's own shapes. The
5
5
  * JMAP wire, and the `jmap-jam` client that speaks it, stay inside.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `@wtfalch/mail` — a JMAP mail client core.
2
+ * `@wtfalch/email/mailbox` — a JMAP mail client core.
3
3
  *
4
4
  * Everything takes a `MailClient` and returns this package's own shapes. The
5
5
  * JMAP wire, and the `jmap-jam` client that speaks it, stay inside.
@@ -1,12 +1,12 @@
1
1
  /**
2
- * `@wtfalch/mail/react` — the components that draw a mailbox.
2
+ * `@wtfalch/email/mailbox/react` — the components that draw a mailbox.
3
3
  *
4
4
  * Everything but `Mail` is pure: props in, markup out, no client and no
5
5
  * fetching. That is what lets each be drawn in a gallery, rendered in a test,
6
6
  * and reused by an application with its own layout. `Mail` is the one piece
7
7
  * that holds state and calls the hooks.
8
8
  *
9
- * On `@wtfalch/design` 0.5.0 and `@wtfalch/mail`. Import `@wtfalch/mail/mail.css`
9
+ * On `@wtfalch/design` 0.5.0 and `@wtfalch/email/mailbox`. Import `@wtfalch/email/mailbox/mail.css`
10
10
  * after the design stylesheet.
11
11
  */
12
12
  export { MailProvider, useMailClient, useOptionalMailClient } from './context.tsx';
@@ -1,12 +1,12 @@
1
1
  /**
2
- * `@wtfalch/mail/react` — the components that draw a mailbox.
2
+ * `@wtfalch/email/mailbox/react` — the components that draw a mailbox.
3
3
  *
4
4
  * Everything but `Mail` is pure: props in, markup out, no client and no
5
5
  * fetching. That is what lets each be drawn in a gallery, rendered in a test,
6
6
  * and reused by an application with its own layout. `Mail` is the one piece
7
7
  * that holds state and calls the hooks.
8
8
  *
9
- * On `@wtfalch/design` 0.5.0 and `@wtfalch/mail`. Import `@wtfalch/mail/mail.css`
9
+ * On `@wtfalch/design` 0.5.0 and `@wtfalch/email/mailbox`. Import `@wtfalch/email/mailbox/mail.css`
10
10
  * after the design stylesheet.
11
11
  */
12
12
  export { MailProvider, useMailClient, useOptionalMailClient } from "./context.js";
@@ -6,7 +6,7 @@
6
6
  * the web admin and `stalwart-cli` speak exactly this.
7
7
  *
8
8
  * Shapes that differ from the docs and were confirmed on 0.16.20 (see
9
- * docs/plans/email/phase-1-runbook.md, "What happened"):
9
+ * wtfalch-manage's docs/plans/email/phase-1-runbook.md, "What happened"):
10
10
  * - a `List<T>` field is a map keyed by index: `{"0": …}`, never an array;
11
11
  * - a `Map<T>` / `Set<T>` field is `{"value": true}`;
12
12
  * - a `SecretKey` from the environment is
@@ -113,7 +113,7 @@ export declare class StalwartClient {
113
113
  * self-service API. The secret is in the response and nowhere else. An app
114
114
  * password is verified locally whatever directory the domain uses, which
115
115
  * is what keeps the bootstrap signed in after the domain moves to OIDC
116
- * (docs/plans/email/phase-4.md).
116
+ * (wtfalch-manage's docs/plans/email/phase-4.md).
117
117
  */
118
118
  createAppPassword(description: string): Promise<string>;
119
119
  /**
@@ -6,7 +6,7 @@
6
6
  * the web admin and `stalwart-cli` speak exactly this.
7
7
  *
8
8
  * Shapes that differ from the docs and were confirmed on 0.16.20 (see
9
- * docs/plans/email/phase-1-runbook.md, "What happened"):
9
+ * wtfalch-manage's docs/plans/email/phase-1-runbook.md, "What happened"):
10
10
  * - a `List<T>` field is a map keyed by index: `{"0": …}`, never an array;
11
11
  * - a `Map<T>` / `Set<T>` field is `{"value": true}`;
12
12
  * - a `SecretKey` from the environment is
@@ -232,7 +232,7 @@ export class StalwartClient {
232
232
  * self-service API. The secret is in the response and nowhere else. An app
233
233
  * password is verified locally whatever directory the domain uses, which
234
234
  * is what keeps the bootstrap signed in after the domain moves to OIDC
235
- * (docs/plans/email/phase-4.md).
235
+ * (wtfalch-manage's docs/plans/email/phase-4.md).
236
236
  */
237
237
  async createAppPassword(description) {
238
238
  const res = await this.call('x:AppPassword/set', {
@@ -12,10 +12,10 @@
12
12
  * import away from something a browser bundles.
13
13
  *
14
14
  * The main entry is pure Node so a provisioning script can use it. The
15
- * components live behind `@wtfalch/postmaster/react`.
15
+ * components live behind `@wtfalch/email/postmaster/react`.
16
16
  */
17
17
  export { API_KEY_PREFIX, DASHBOARD_PERMISSIONS, StalwartClient, StalwartError, authFor, type Credential, type StalwartAuth, } from './client.js';
18
- export { type Instance, openInstance } from './instance.js';
18
+ export { type Instance, InstanceRefused, openInstance, type RefusalReason } from './instance.js';
19
19
  export { loadOverview } from './load.js';
20
20
  export { applyObjects, mailObjects, ref, type MailObjectsInput, type PlannedObject, } from './objects.js';
21
21
  export { planMailboxes, withPassword } from './mailboxes.js';
@@ -12,10 +12,10 @@
12
12
  * import away from something a browser bundles.
13
13
  *
14
14
  * The main entry is pure Node so a provisioning script can use it. The
15
- * components live behind `@wtfalch/postmaster/react`.
15
+ * components live behind `@wtfalch/email/postmaster/react`.
16
16
  */
17
17
  export { API_KEY_PREFIX, DASHBOARD_PERMISSIONS, StalwartClient, StalwartError, authFor, } from './client.js';
18
- export { openInstance } from './instance.js';
18
+ export { InstanceRefused, openInstance } from './instance.js';
19
19
  export { loadOverview } from './load.js';
20
20
  export { applyObjects, mailObjects, ref, } from './objects.js';
21
21
  export { planMailboxes, withPassword } from './mailboxes.js';
@@ -1,11 +1,24 @@
1
1
  import { StalwartClient } from './client.js';
2
+ /**
3
+ * Why `openInstance` refused, as something a caller can branch on.
4
+ *
5
+ * Both refusals used to be a plain `Error`, so every consumer told them apart
6
+ * by matching words in the message — which meant rewording a sentence here
7
+ * silently changed which error a dashboard showed. `reason` is the contract
8
+ * instead; the message is free to change.
9
+ */
10
+ export type RefusalReason = 'not-https' | 'account-missing';
11
+ export declare class InstanceRefused extends Error {
12
+ readonly reason: RefusalReason;
13
+ constructor(reason: RefusalReason, message: string);
14
+ }
2
15
  /**
3
16
  * A mail instance and the credential this program acts on it with.
4
17
  *
5
18
  * Deliberately not built from environment variables here: what those are
6
19
  * called is the consuming app's business, and a package that read
7
20
  * `process.env` would decide it for every consumer. The app reads its own
8
- * names and calls `openInstance`; `@wtfalch/postmaster` only insists that
21
+ * names and calls `openInstance`; `@wtfalch/email/postmaster` only insists that
9
22
  * the URL is https, because a Basic credential over http is the credential
10
23
  * in clear.
11
24
  */
@@ -1,4 +1,12 @@
1
- import { StalwartClient, authFor } from './client.js';
1
+ import { API_KEY_PREFIX, StalwartClient, authFor } from './client.js';
2
+ export class InstanceRefused extends Error {
3
+ reason;
4
+ constructor(reason, message) {
5
+ super(message);
6
+ this.reason = reason;
7
+ this.name = 'InstanceRefused';
8
+ }
9
+ }
2
10
  /**
3
11
  * An instance from a URL and one opaque secret, with the scheme chosen from
4
12
  * the secret's own shape by `authFor`. Confirmed against Stalwart 0.16.20:
@@ -9,7 +17,12 @@ import { StalwartClient, authFor } from './client.js';
9
17
  export function openInstance(input) {
10
18
  const url = input.url.trim().replace(/\/+$/, '');
11
19
  if (!/^https:\/\//.test(url)) {
12
- throw new Error(`a mail instance URL must be https, got "${input.url}"`);
20
+ throw new InstanceRefused('not-https', `a mail instance URL must be https, got "${input.url}"`);
21
+ }
22
+ // Checked before `authFor` rather than inside it, so that the throw carries
23
+ // a reason. `authFor` stays the one place that reads a secret's shape.
24
+ if (!input.secret.startsWith(API_KEY_PREFIX) && !input.user) {
25
+ throw new InstanceRefused('account-missing', 'this secret is not an API key, so it is an account credential and needs the account it belongs to');
13
26
  }
14
27
  const auth = authFor(input.secret, input.user);
15
28
  return {
@@ -12,7 +12,8 @@ export interface MailObjectsInput {
12
12
  resendTokenVar: string;
13
13
  /**
14
14
  * The project's identity provider, once the mail applications are
15
- * registered there (docs/plans/email.md E3, phase-4.md slice 1): tokens
15
+ * registered there (wtfalch-manage's docs/plans/email.md E3, and
16
+ * docs/plans/email/phase-4.md slice 1): tokens
16
17
  * from `issuerUrl` for `audience` (the provider's project or resource id)
17
18
  * sign people in, on the domain and as the server's default. Absent, the
18
19
  * domain keeps the internal directory and people have passwords.
@@ -55,7 +56,7 @@ export interface PlannedObject {
55
56
  /**
56
57
  * The full configuration of an instance as data, in dependency order. Pure,
57
58
  * so it is unit-tested; `applyObjects` resolves the `$ref`s against the
58
- * server. What each object is for is in docs/plans/email.md (E3 to E5).
59
+ * server. What each object is for is in wtfalch-manage's docs/plans/email.md (E3 to E5).
59
60
  */
60
61
  export declare function mailObjects(i: MailObjectsInput): PlannedObject[];
61
62
  /**
@@ -4,7 +4,7 @@ const env = (variableName) => ({ '@type': 'EnvironmentVariable', variableName })
4
4
  /**
5
5
  * The full configuration of an instance as data, in dependency order. Pure,
6
6
  * so it is unit-tested; `applyObjects` resolves the `$ref`s against the
7
- * server. What each object is for is in docs/plans/email.md (E3 to E5).
7
+ * server. What each object is for is in wtfalch-manage's docs/plans/email.md (E3 to E5).
8
8
  */
9
9
  export function mailObjects(i) {
10
10
  const oidcDescription = i.oidc ? `${i.oidc.issuerUrl} (${i.apex})` : undefined;
@@ -80,7 +80,7 @@ export function mailObjects(i) {
80
80
  value: {
81
81
  '@type': 'Relay',
82
82
  name: 'resend',
83
- description: 'Every outbound message relays through Resend (docs/plans/email.md, E4)',
83
+ description: 'Every outbound message relays through Resend',
84
84
  address: 'smtp.resend.com',
85
85
  port: 465,
86
86
  protocol: 'smtp',
@@ -6,7 +6,7 @@ import type { Credential } from './client.js';
6
6
  * unit-tested; `loadOverview` in ./load.ts fetches and calls it.
7
7
  *
8
8
  * Wire shapes are as `x:<Object>/get` returns them on 0.16 (the header of
9
- * ./stalwart.ts, docs/plans/email/phase-1-runbook.md): a `List<T>` is a map
9
+ * ./client.ts's header): a `List<T>` is a map
10
10
  * keyed by index, never an array. Only the properties the view reads are
11
11
  * typed, and **nothing is passed through**: every field of the view is named
12
12
  * and rebuilt here, so a wire property nobody listed cannot reach the page.
@@ -3,7 +3,7 @@
3
3
  * shapes, so what gets sent to a real mail server is decided in a unit test
4
4
  * rather than at the end of a Server Action.
5
5
  *
6
- * The same reasoning as `withPassword` in ./stalwart.ts, and the same rule
6
+ * The same reasoning as `withPassword` in ./client.ts, and the same rule
7
7
  * that governs everything here: **a `List<T>` is a map keyed by index**
8
8
  * (`{"0": …}`), never an array, and the server replaces the whole list when
9
9
  * one is sent. So adding or removing one entry means sending every entry
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/email",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "The wtfalch estate: reading a mailbox over JMAP, and administering the Stalwart server it lives on. Two entries with no code in common.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -35,7 +35,7 @@
35
35
  },
36
36
  "files": ["dist", "LICENSE", "README.md"],
37
37
  "scripts": {
38
- "build": "rm -rf dist && tsc -p tsconfig.build.json && cp src/mailbox/react/mail.css dist/mailbox/mail.css",
38
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && cp src/mailbox/react/mail.css dist/mailbox/mail.css && cp ../../LICENSE ../../README.md .",
39
39
  "prepack": "pnpm build",
40
40
  "typecheck": "tsc --noEmit",
41
41
  "test": "vitest run",
@@ -68,7 +68,7 @@
68
68
  "typescript": "^5.9.0",
69
69
  "vitest": "^4.1.6"
70
70
  },
71
- "sideEffects": false,
71
+ "sideEffects": ["**/*.css"],
72
72
  "publishConfig": {
73
73
  "access": "public"
74
74
  },