@wtfalch/email 0.7.0 → 0.9.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.
@@ -0,0 +1,529 @@
1
+ /**
2
+ * A stranger's HTML, made fit to draw.
3
+ *
4
+ * **This is the third wall, not the only one.** The body is drawn in a frame
5
+ * with no `allow-scripts`, under a content policy of its own that forbids
6
+ * scripts, frames, forms, fonts and every fetch but the images the reader
7
+ * allowed. Each of those holds if this file has a bug. What this adds is what
8
+ * neither can do: taking out the things that misbehave in a frame that
9
+ * cannot run code. A `<meta http-equiv="refresh">` navigates it; a `<base>`
10
+ * repoints every link in it; a `ping` reports a click; a relative `src`
11
+ * resolves against the application's own origin and fetches from it with the
12
+ * reader's cookies.
13
+ *
14
+ * **An allowlist, walked over an inert document.** `DOMParser` builds a
15
+ * document with no browsing context, so nothing in it loads and nothing in it
16
+ * runs while it is being cleaned. Elements not on the list are unwrapped, so
17
+ * their text survives; the few whose content is itself the problem — scripts,
18
+ * frames, plugins, forms' controls, SVG and MathML, and the raw-text elements
19
+ * that parse differently the second time — go whole. Attributes are kept by
20
+ * name, never removed by name, so an attribute the list has not heard of is
21
+ * gone rather than let through.
22
+ *
23
+ * **CSS is read by the browser, not by a regular expression.** `u\72l(` is a
24
+ * `url(`, and so is a dozen other spellings a pattern would miss. Declarations
25
+ * go through the CSSOM, which resolves the escapes, and one that fetches
26
+ * anything the reader has not allowed is dropped. A stylesheet is parsed with
27
+ * `CSSStyleSheet.replaceSync`, which refuses `@import` by itself; `@font-face`
28
+ * and every other at-rule but `@media` and `@supports` are dropped. Where the
29
+ * constructor does not exist the stylesheets are dropped rather than passed.
30
+ *
31
+ * **Why not DOMPurify.** It is the right tool for putting sanitised markup
32
+ * into a live document, where its mutation-XSS defences are the only thing
33
+ * between a parser quirk and script. Here the markup never reaches a document
34
+ * that can run script, the package keeps one runtime dependency on purpose,
35
+ * and what this needs that DOMPurify leaves to hooks — withholding remote
36
+ * images, counting them, resolving `cid:`, reading CSS — is most of the code
37
+ * either way.
38
+ */
39
+ /**
40
+ * Whether a host is the page's own or one of its siblings. The parent domain
41
+ * is the host less its first label, and only where that leaves two labels or
42
+ * more: `email.example.com` covers `*.example.com`, `example.com` covers only
43
+ * itself. Without the public suffix list this can over-reach — on
44
+ * `a.github.io` it refuses every `*.github.io` — which costs a picture, and
45
+ * the other direction would cost a request.
46
+ */
47
+ function sameSite(host, origin) {
48
+ let page;
49
+ try {
50
+ page = new URL(origin).hostname;
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ if (host === page)
56
+ return true;
57
+ const labels = page.split('.');
58
+ if (labels.length < 3 || /^[\d.]+$|:/.test(page))
59
+ return false;
60
+ const parent = labels.slice(1).join('.');
61
+ return host === parent || host.endsWith(`.${parent}`);
62
+ }
63
+ const HTML_NS = 'http://www.w3.org/1999/xhtml';
64
+ /** Kept, with their attributes filtered. */
65
+ const KEEP = new Set([
66
+ 'a',
67
+ 'abbr',
68
+ 'address',
69
+ 'article',
70
+ 'aside',
71
+ 'b',
72
+ 'bdi',
73
+ 'bdo',
74
+ 'big',
75
+ 'blockquote',
76
+ 'body',
77
+ 'br',
78
+ 'caption',
79
+ 'center',
80
+ 'cite',
81
+ 'code',
82
+ 'col',
83
+ 'colgroup',
84
+ 'dd',
85
+ 'del',
86
+ 'details',
87
+ 'dfn',
88
+ 'div',
89
+ 'dl',
90
+ 'dt',
91
+ 'em',
92
+ 'figcaption',
93
+ 'figure',
94
+ 'font',
95
+ 'footer',
96
+ 'h1',
97
+ 'h2',
98
+ 'h3',
99
+ 'h4',
100
+ 'h5',
101
+ 'h6',
102
+ 'header',
103
+ 'hr',
104
+ 'i',
105
+ 'img',
106
+ 'ins',
107
+ 'kbd',
108
+ 'li',
109
+ 'main',
110
+ 'mark',
111
+ 'nav',
112
+ 'ol',
113
+ 'p',
114
+ 'pre',
115
+ 'q',
116
+ 'rp',
117
+ 'rt',
118
+ 'ruby',
119
+ 's',
120
+ 'samp',
121
+ 'section',
122
+ 'small',
123
+ 'span',
124
+ 'strike',
125
+ 'strong',
126
+ 'sub',
127
+ 'summary',
128
+ 'sup',
129
+ 'table',
130
+ 'tbody',
131
+ 'td',
132
+ 'tfoot',
133
+ 'th',
134
+ 'thead',
135
+ 'time',
136
+ 'tr',
137
+ 'tt',
138
+ 'u',
139
+ 'ul',
140
+ 'var',
141
+ 'wbr',
142
+ ]);
143
+ /**
144
+ * Removed with everything inside them. Unwrapping these would keep what
145
+ * makes them dangerous — a script's source as text is harmless, but a
146
+ * `<noscript>` or `<xmp>` body parses as markup the second time it is read,
147
+ * which is the shape every mutation-XSS bug has.
148
+ */
149
+ const DISCARD = new Set([
150
+ 'applet',
151
+ 'area',
152
+ 'audio',
153
+ 'base',
154
+ 'canvas',
155
+ 'datalist',
156
+ 'dialog',
157
+ 'embed',
158
+ 'frame',
159
+ 'frameset',
160
+ 'head',
161
+ 'iframe',
162
+ 'input',
163
+ 'link',
164
+ 'map',
165
+ 'math',
166
+ 'meta',
167
+ 'noembed',
168
+ 'noframes',
169
+ 'noscript',
170
+ 'object',
171
+ 'optgroup',
172
+ 'option',
173
+ 'output',
174
+ 'param',
175
+ 'plaintext',
176
+ 'portal',
177
+ 'script',
178
+ 'select',
179
+ 'slot',
180
+ 'source',
181
+ 'style',
182
+ 'svg',
183
+ 'template',
184
+ 'textarea',
185
+ 'title',
186
+ 'track',
187
+ 'video',
188
+ 'xmp',
189
+ ]);
190
+ /** Presentational and descriptive, and none of them a URL or a handler. */
191
+ const ATTRIBUTES = new Set([
192
+ 'abbr',
193
+ 'align',
194
+ 'alink',
195
+ 'alt',
196
+ 'bgcolor',
197
+ 'border',
198
+ 'cellpadding',
199
+ 'cellspacing',
200
+ 'class',
201
+ 'color',
202
+ 'colspan',
203
+ 'datetime',
204
+ 'dir',
205
+ 'face',
206
+ 'headers',
207
+ 'height',
208
+ 'hspace',
209
+ 'lang',
210
+ 'link',
211
+ 'nowrap',
212
+ 'open',
213
+ 'reversed',
214
+ 'role',
215
+ 'rowspan',
216
+ 'scope',
217
+ 'size',
218
+ 'span',
219
+ 'start',
220
+ 'style',
221
+ 'summary',
222
+ 'text',
223
+ 'title',
224
+ 'type',
225
+ 'valign',
226
+ 'vlink',
227
+ 'vspace',
228
+ 'width',
229
+ ]);
230
+ /** Image types a `data:` URL may carry. Not SVG: it is a document, not a
231
+ * picture, and nothing in mail needs it inline. */
232
+ const RASTER = /^image\/(?:png|gif|jpe?g|webp|avif|bmp)$/i;
233
+ const RASTER_DATA = /^data:image\/(?:png|gif|jpe?g|webp|avif|bmp)(?:;[a-z0-9=._-]*)*,/i;
234
+ /** A CSS value that fetches something, or would if the browser let it. */
235
+ const FETCHES = /(?:url|image-set|image|cross-fade|element|src)\s*\(/i;
236
+ /** The old ways to run script from a stylesheet. No current browser honours
237
+ * them; a stranger's mail is not where to find out which one still does. */
238
+ const HOSTILE_PROPERTY = /^(?:behavior|-moz-binding)$/i;
239
+ const HOSTILE_VALUE = /expression\s*\(|javascript:|vbscript:/i;
240
+ /** Where an image address may point, and whether the reader allowed it. */
241
+ function image(raw, policy) {
242
+ const value = raw.trim();
243
+ if (/^cid:/i.test(value)) {
244
+ const id = safeDecode(value.slice(4));
245
+ const found = policy.inline?.get(id);
246
+ return found && RASTER_DATA.test(found) ? { keep: found } : 'drop';
247
+ }
248
+ if (/^data:/i.test(value))
249
+ return RASTER_DATA.test(value) ? { keep: value } : 'drop';
250
+ // No base: a relative address resolves against whatever page drew the
251
+ // frame, which is this application, so it is refused rather than guessed.
252
+ let url;
253
+ try {
254
+ url = new URL(value);
255
+ }
256
+ catch {
257
+ return 'drop';
258
+ }
259
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
260
+ return 'drop';
261
+ if (policy.origin && sameSite(url.hostname, policy.origin))
262
+ return 'drop';
263
+ return policy.remote ? { keep: url.href } : { blocked: url.href };
264
+ }
265
+ /** Where a link may go. The URL parser, not a pattern, decides the scheme:
266
+ * it strips the tabs, newlines and control characters that `java\tscript:`
267
+ * hides behind, and lowercases what is left. */
268
+ function link(raw) {
269
+ let url;
270
+ try {
271
+ url = new URL(raw.trim());
272
+ }
273
+ catch {
274
+ return null;
275
+ }
276
+ return url.protocol === 'https:' || url.protocol === 'http:' || url.protocol === 'mailto:'
277
+ ? url.href
278
+ : null;
279
+ }
280
+ function safeDecode(value) {
281
+ try {
282
+ return decodeURIComponent(value);
283
+ }
284
+ catch {
285
+ return value;
286
+ }
287
+ }
288
+ /** The addresses in a CSS value, as the CSSOM serialised it. */
289
+ function addresses(value) {
290
+ const found = [];
291
+ const literal = (text) => text.replace(/\\([0-9a-f]{1,6}\s?|[\s\S])/gi, (_, sequence) => /^[0-9a-f]/i.test(sequence)
292
+ ? String.fromCodePoint(Number.parseInt(sequence, 16) || 0xfffd)
293
+ : sequence);
294
+ for (const match of value.matchAll(/url\(\s*(?:"((?:[^"\\]|\\[\s\S])*)"|'((?:[^'\\]|\\[\s\S])*)'|([^)\s]*))\s*\)/gi)) {
295
+ found.push(literal(match[1] ?? match[2] ?? match[3] ?? ''));
296
+ }
297
+ // `image-set("a.png" 1x)` takes a bare string as an address.
298
+ for (const match of value
299
+ .replace(/url\([^)]*\)/gi, '')
300
+ .matchAll(/"((?:[^"\\]|\\[\s\S])*)"|'((?:[^'\\]|\\[\s\S])*)'/g)) {
301
+ found.push(literal(match[1] ?? match[2] ?? ''));
302
+ }
303
+ return found;
304
+ }
305
+ /**
306
+ * Drops each declaration that fetches something not allowed, or that is one
307
+ * of the old ways to run script from a stylesheet. A value that fetches and
308
+ * whose addresses cannot all be read is dropped, not trusted.
309
+ */
310
+ function cleanDeclarations(style, policy, blocked) {
311
+ for (let index = style.length - 1; index >= 0; index--) {
312
+ const property = style.item(index);
313
+ const value = style.getPropertyValue(property);
314
+ if (HOSTILE_PROPERTY.test(property) || HOSTILE_VALUE.test(value)) {
315
+ style.removeProperty(property);
316
+ continue;
317
+ }
318
+ if (!FETCHES.test(value))
319
+ continue;
320
+ const found = addresses(value);
321
+ const verdicts = found.map((address) => image(address, policy));
322
+ for (const verdict of verdicts) {
323
+ if (typeof verdict === 'object' && 'blocked' in verdict)
324
+ blocked.add(verdict.blocked);
325
+ }
326
+ // A `cid:` in CSS would need rewriting in place, which a declaration
327
+ // read back from the CSSOM cannot be trusted to survive; it is dropped.
328
+ const allowed = found.length > 0 &&
329
+ found.every((address) => !/^\s*cid:/i.test(address)) &&
330
+ verdicts.every((verdict) => typeof verdict === 'object' && 'keep' in verdict);
331
+ if (!allowed)
332
+ style.removeProperty(property);
333
+ }
334
+ }
335
+ const STYLE_RULE = 1;
336
+ const MEDIA_RULE = 4;
337
+ const SUPPORTS_RULE = 12;
338
+ function cleanRules(list, policy, blocked) {
339
+ for (let index = list.cssRules.length - 1; index >= 0; index--) {
340
+ const rule = list.cssRules[index];
341
+ if (!rule)
342
+ continue;
343
+ if (rule.type === STYLE_RULE) {
344
+ cleanDeclarations(rule.style, policy, blocked);
345
+ // A nested rule inside a style rule, where the browser supports nesting.
346
+ if ('cssRules' in rule && 'deleteRule' in rule) {
347
+ cleanRules(rule, policy, blocked);
348
+ }
349
+ }
350
+ else if (rule.type === MEDIA_RULE || rule.type === SUPPORTS_RULE) {
351
+ cleanRules(rule, policy, blocked);
352
+ }
353
+ else {
354
+ list.deleteRule(index);
355
+ }
356
+ }
357
+ }
358
+ /**
359
+ * A stylesheet, read and written back by the browser.
360
+ *
361
+ * The `<` is escaped on the way out because the result is placed inside a
362
+ * `<style>` element, and the CSSOM keeps a string's contents as written: a
363
+ * `content: "</style><img …>"` would otherwise close the element and put the
364
+ * rest into the document as markup that never went past the element list.
365
+ * `\3c ` is the same character to CSS and no character at all to HTML.
366
+ */
367
+ function cleanSheet(css, policy, blocked) {
368
+ if (!css.trim() || typeof CSSStyleSheet !== 'function')
369
+ return '';
370
+ let sheet;
371
+ try {
372
+ sheet = new CSSStyleSheet();
373
+ sheet.replaceSync(css);
374
+ }
375
+ catch {
376
+ return '';
377
+ }
378
+ cleanRules(sheet, policy, blocked);
379
+ return Array.from(sheet.cssRules, (rule) => rule.cssText)
380
+ .join('\n')
381
+ .replace(/</g, '\\3c ');
382
+ }
383
+ function cleanAttributes(element, policy, blocked) {
384
+ const name = element.localName;
385
+ for (const attribute of Array.from(element.attributes)) {
386
+ const key = attribute.name.toLowerCase();
387
+ if (key === 'style') {
388
+ const style = element.style;
389
+ if (!style) {
390
+ element.removeAttribute(attribute.name);
391
+ continue;
392
+ }
393
+ cleanDeclarations(style, policy, blocked);
394
+ const text = style.cssText;
395
+ if (text)
396
+ element.setAttribute('style', text);
397
+ else
398
+ element.removeAttribute('style');
399
+ continue;
400
+ }
401
+ if ((key === 'src' && name === 'img') || key === 'background') {
402
+ const verdict = image(attribute.value, policy);
403
+ if (typeof verdict === 'object' && 'keep' in verdict) {
404
+ element.setAttribute(attribute.name, verdict.keep);
405
+ continue;
406
+ }
407
+ if (typeof verdict === 'object')
408
+ blocked.add(verdict.blocked);
409
+ element.removeAttribute(attribute.name);
410
+ continue;
411
+ }
412
+ if (key === 'href' && name === 'a') {
413
+ const href = link(attribute.value);
414
+ if (href)
415
+ element.setAttribute('href', href);
416
+ else
417
+ element.removeAttribute(attribute.name);
418
+ continue;
419
+ }
420
+ if (!ATTRIBUTES.has(key) && !key.startsWith('aria-'))
421
+ element.removeAttribute(attribute.name);
422
+ }
423
+ if (name === 'a') {
424
+ // Every link leaves the frame for a tab of its own, and takes nothing
425
+ // with it: not a handle back to this window, not this page's address.
426
+ element.setAttribute('target', '_blank');
427
+ element.setAttribute('rel', 'noopener noreferrer');
428
+ }
429
+ }
430
+ /**
431
+ * The walk. Iterative rather than recursive: a message is a stranger's
432
+ * choice of nesting depth, and the stack is not.
433
+ */
434
+ function sweep(root, policy, blocked) {
435
+ cleanAttributes(root, policy, blocked);
436
+ const queue = Array.from(root.childNodes);
437
+ while (queue.length > 0) {
438
+ const node = queue.pop();
439
+ if (node.nodeType === 3)
440
+ continue; // text
441
+ if (node.nodeType !== 1) {
442
+ // Comments (Outlook's conditional ones included), processing
443
+ // instructions, anything else: nothing a reader sees.
444
+ node.parentNode?.removeChild(node);
445
+ continue;
446
+ }
447
+ const element = node;
448
+ const name = element.localName;
449
+ if (element.namespaceURI !== HTML_NS || DISCARD.has(name)) {
450
+ element.remove();
451
+ continue;
452
+ }
453
+ if (!KEEP.has(name)) {
454
+ const children = Array.from(element.childNodes);
455
+ element.replaceWith(...children);
456
+ queue.push(...children);
457
+ continue;
458
+ }
459
+ cleanAttributes(element, policy, blocked);
460
+ queue.push(...Array.from(element.childNodes));
461
+ }
462
+ }
463
+ /**
464
+ * The frame's own content policy, stated in full rather than left to
465
+ * `default-src`: `form-action` and `base-uri` do not fall back to it.
466
+ * Inline styles are allowed because mail is nothing but inline styles, and
467
+ * nothing else is.
468
+ */
469
+ export function contentPolicy(remote) {
470
+ return [
471
+ "default-src 'none'",
472
+ `img-src data:${remote ? ' https: http:' : ''}`,
473
+ "style-src 'unsafe-inline'",
474
+ "font-src 'none'",
475
+ "script-src 'none'",
476
+ "form-action 'none'",
477
+ "base-uri 'none'",
478
+ ].join('; ');
479
+ }
480
+ /**
481
+ * Mail is written for white paper, so it is drawn on white paper in either
482
+ * theme. Inverting a stranger's colours turns their dark text in their pale
483
+ * boxes into dark text on dark, and there is no telling which of their
484
+ * colours were chosen and which were defaults. These come first so the
485
+ * message's own styles win.
486
+ */
487
+ const PAPER = 'html{background:#fff;color:#1f1f1f;font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;overflow-wrap:break-word}' +
488
+ 'img{border:0}';
489
+ /**
490
+ * These come last and win. The frame is sized to its document, so the
491
+ * document must be as tall as its content and no taller: a `height: 100%`
492
+ * would follow the frame, and the frame would follow it. Wide mail scrolls
493
+ * sideways inside the frame rather than being squeezed.
494
+ */
495
+ const FIT = 'html{overflow-x:auto!important;overflow-y:hidden!important;height:auto!important;min-height:0!important}' +
496
+ 'body{height:auto!important;min-height:0!important}';
497
+ /** A message's HTML body as a document for a sandboxed frame. Browser only:
498
+ * it needs `DOMParser`. */
499
+ export function mailDocument(html, policy) {
500
+ const parsed = new DOMParser().parseFromString(html, 'text/html');
501
+ const blocked = new Set();
502
+ const css = Array.from(parsed.querySelectorAll('style'), (style) => {
503
+ const text = style.textContent ?? '';
504
+ style.remove();
505
+ return text;
506
+ }).join('\n');
507
+ // `document.body` is a `<frameset>` when the markup says so. A frameset is
508
+ // not a body, and written into the frame it would replace the one there.
509
+ const body = parsed.body?.localName === 'body' ? parsed.body : parsed.createElement('body');
510
+ sweep(body, policy, blocked);
511
+ const sheet = cleanSheet(css, policy, blocked);
512
+ // The policy first: a `<meta>` policy governs only what comes after it.
513
+ const head = [
514
+ `<meta http-equiv="Content-Security-Policy" content="${contentPolicy(policy.remote)}">`,
515
+ '<meta name="referrer" content="no-referrer">',
516
+ '<meta http-equiv="x-dns-prefetch-control" content="off">',
517
+ '<meta name="color-scheme" content="light">',
518
+ '<base target="_blank">',
519
+ `<style>${PAPER}</style>`,
520
+ sheet ? `<style>${sheet}</style>` : '',
521
+ `<style>${FIT}</style>`,
522
+ ].join('');
523
+ const srcdoc = `<!doctype html><html><head>${head}</head>${body.outerHTML}</html>`;
524
+ return { srcdoc, blocked: policy.remote ? 0 : blocked.size };
525
+ }
526
+ /** Whether an inline part is a picture this will draw from a `data:` URL. */
527
+ export function isInlineImage(type) {
528
+ return RASTER.test(type);
529
+ }
@@ -40,7 +40,18 @@ const BODY_PROPERTIES = [
40
40
  * quoted history should not stall a thread view; anything cut short is
41
41
  * reported as `isTruncated`. */
42
42
  export const DEFAULT_MAX_BODY_BYTES = 512 * 1024;
43
- function joinParts(parts, values) {
43
+ /**
44
+ * The body parts of one type, joined.
45
+ *
46
+ * **Filtered by type because the lists are not.** RFC 8621 §4.1.4 fills
47
+ * `textBody` with a *preference* for `text/plain` and `htmlBody` with one for
48
+ * `text/html`, falling back to whatever the message has: an HTML-only message
49
+ * lists its HTML part in `textBody` too, and a plain one lists its text in
50
+ * `htmlBody`. Joined unfiltered, the first put a stranger's raw markup in the
51
+ * plain-text view and the second sent plain text to be drawn as HTML. A part
52
+ * with no type is `text/plain`, which is MIME's default.
53
+ */
54
+ function joinParts(parts, values, type) {
44
55
  if (!parts || parts.length === 0 || !values)
45
56
  return { text: null, truncated: false };
46
57
  const pieces = [];
@@ -48,6 +59,8 @@ function joinParts(parts, values) {
48
59
  for (const part of parts) {
49
60
  if (part.partId === undefined)
50
61
  continue;
62
+ if ((part.type ?? 'text/plain').toLowerCase() !== type)
63
+ continue;
51
64
  const value = values[part.partId];
52
65
  if (!value)
53
66
  continue;
@@ -62,8 +75,8 @@ function joinParts(parts, values) {
62
75
  /** Turn one `Email/get` result into a `Message`, resolving its bodies and
63
76
  * giving every attachment a download URL. */
64
77
  export function toMessage(raw, downloadUrlFor) {
65
- const text = joinParts(raw.textBody, raw.bodyValues);
66
- const html = joinParts(raw.htmlBody, raw.bodyValues);
78
+ const text = joinParts(raw.textBody, raw.bodyValues, 'text/plain');
79
+ const html = joinParts(raw.htmlBody, raw.bodyValues, 'text/html');
67
80
  const keywords = raw.keywords ?? {};
68
81
  const attachments = (raw.attachments ?? [])
69
82
  // A part with no blob cannot be fetched, so it is not an attachment a
@@ -31,6 +31,13 @@ export type MailSession = {
31
31
  /** True when the account may submit mail, so a composer can be hidden
32
32
  * rather than failing at send. */
33
33
  maySubmit: boolean;
34
+ /** The largest single upload the server accepts, in bytes (RFC 8620
35
+ * §2's `maxSizeUpload`). `null` when the session does not say. */
36
+ maxSizeUpload: number | null;
37
+ /** The most one message's attachments may add up to, in bytes (RFC 8621
38
+ * §1.3.1's `maxSizeAttachmentsPerEmail`). `null` when the account does
39
+ * not say, which RFC 8621 permits. */
40
+ maxSizeAttachmentsPerEmail: number | null;
34
41
  };
35
42
  /** A mailbox with its children, as the tree the server's flat list describes. */
36
43
  export type MailboxNode = {
@@ -182,6 +189,10 @@ export type DraftAttachment = {
182
189
  /** `inline` needs a `cid` the HTML body references. */
183
190
  disposition?: 'inline' | 'attachment';
184
191
  cid?: string;
192
+ /** What it weighs, when known: for a composer to show beside the name and
193
+ * to count against the server's limit. Never sent; the server measured
194
+ * the blob when it was uploaded. */
195
+ size?: number;
185
196
  };
186
197
  /** What `send` reports back. */
187
198
  export type Sent = {
@@ -2,9 +2,11 @@
2
2
  /**
3
3
  * What a browser bundle gets instead of the administration client.
4
4
  *
5
- * This entry reaches a mail server with an administrator credential that, on
6
- * Stalwart 0.16, cannot be scoped and is as powerful as the whole account. It
7
- * must never end up in something a browser downloads.
5
+ * This entry reaches a mail server with an administrative credential. A
6
+ * minted API key can be scoped — `DASHBOARD_PERMISSIONS` is the set a
7
+ * dashboard needs — but nothing obliges a caller to pass a scoped one, and an
8
+ * account password or an `'inherit'` key is as powerful as the whole account.
9
+ * It must never end up in something a browser downloads.
8
10
  *
9
11
  * **Why the `browser` condition and not `server-only`.** `server-only` throws
10
12
  * in any environment without React's `react-server` condition, which includes
@@ -34,6 +34,22 @@ export type StalwartAuth = {
34
34
  };
35
35
  /** API-key secrets are `API_`-prefixed on 0.16, which is how a caller can tell one from an app password. */
36
36
  export declare const API_KEY_PREFIX = "API_";
37
+ /**
38
+ * What a dashboard's mail section needs and nothing more, verified against
39
+ * 0.16.20 on 2026-09-14. This is the default {@link StalwartClient.createApiKey}
40
+ * mints.
41
+ *
42
+ * It covers `loadOverview`, `createMailbox`, `addAlias`, `removeAlias` and
43
+ * `revokeAppPassword` — the five operations the `/email` pages perform. A key
44
+ * holding exactly these is `forbidden` on `Email/query` for every account on
45
+ * the instance, its own included, so it administers mail without being able
46
+ * to read any.
47
+ *
48
+ * `authenticate` is what lets the key be presented at all; the `sys*` names
49
+ * are Stalwart's management vocabulary (`enums.Permission`), which is why the
50
+ * earlier guessed names all failed.
51
+ */
52
+ export declare const DASHBOARD_PERMISSIONS: readonly ["authenticate", "sysAccountQuery", "sysAccountGet", "sysAccountCreate", "sysAccountUpdate", "sysDomainQuery", "sysDomainGet", "sysSystemSettingsGet"];
37
53
  /** Which scheme a secret wants, from its own shape, for a caller holding one opaque string. */
38
54
  export declare function authFor(secret: string, user?: string): StalwartAuth;
39
55
  export declare class StalwartError extends Error {
@@ -70,24 +86,28 @@ export declare class StalwartClient {
70
86
  * Mint an API key for the authenticated account through the self-service
71
87
  * API, and return its secret, which is in the response and nowhere else.
72
88
  *
73
- * **`Inherit`, not a narrower set, and that is a finding rather than a
74
- * shortcut.** `permissions` does take a `{'@type':'Replace', permissions:
75
- * {…}}` form, and an empty one really does restrict — such a key is
76
- * `forbidden` on every management method. But of some sixty candidate
77
- * permission names tried against 0.16.20 on 2026-09-07, only
78
- * `authenticate` and `impersonate` were accepted, and a key holding both
79
- * is still `forbidden` on `x:Account/query`, `x:Domain/query`,
80
- * `x:SystemSettings/get` and `x:ApiKey/query`. There is no name in this
81
- * API's vocabulary that grants management access, so a scoped key cannot
82
- * manage principals at all. `Inherit` is the only value that works.
89
+ * **Scoped by default, because a scoped key does work.** An earlier reading
90
+ * of this API concluded that `Inherit` was the only usable value, from some
91
+ * sixty guessed permission names of which only `authenticate` and
92
+ * `impersonate` were accepted. The guesses were the problem: the vocabulary
93
+ * is `enums.Permission`, and its management names are
94
+ * `sys<Object><Verb>` — `sysAccountQuery`, `sysDomainGet` and so on.
95
+ *
96
+ * {@link DASHBOARD_PERMISSIONS} is the set verified against 0.16.20 on
97
+ * 2026-09-14. A key holding it answers `x:Account/query|get|set`,
98
+ * `x:Domain/query|get` and `x:SystemSettings/get`, which is everything a
99
+ * dashboard's mail section does, and is `forbidden` on `Email/query` for
100
+ * every account including its own. It cannot read anyone's mail.
101
+ *
102
+ * Pass an explicit set to widen or narrow it, or `'inherit'` for a key as
103
+ * powerful as the account itself. Prefer a set: `'inherit'` hands the
104
+ * holder every mailbox on the instance.
83
105
  *
84
- * The key is therefore as powerful as the account it belongs to — the same
85
- * power as its app password — and what it buys is not least privilege but
86
- * two other things: it is typed `ApiKey`, which the `/email` section's revoke
106
+ * Either way the key is typed `ApiKey`, which the `/email` section's revoke
87
107
  * refuses to touch, and it goes as Bearer, so it carries no account name
88
108
  * and cannot be used to sign in to mail as a person.
89
109
  */
90
- createApiKey(description: string): Promise<string>;
110
+ createApiKey(description: string, permissions?: readonly string[] | 'inherit'): Promise<string>;
91
111
  /**
92
112
  * Mint an app password for the authenticated account through the
93
113
  * self-service API. The secret is in the response and nowhere else. An app