@wtfalch/email 0.7.0 → 0.8.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.
@@ -1,6 +1,21 @@
1
1
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Button, Field, Icon, Identity, Input, Select, Textarea } from '@wtfalch/design';
3
- import { useState } from 'react';
3
+ import { useEffect, useRef, useState } from 'react';
4
+ import { bytes } from "./ThreadView.js";
5
+ /**
6
+ * The sentence for a file the limits rule out, or `null` when it may go.
7
+ * `pending` is what the draft's attachments and the uploads already under
8
+ * way weigh, so two 30 MB files picked together are measured together.
9
+ */
10
+ export function refusal(file, pending, limits = {}) {
11
+ if (limits.file !== undefined && file.size > limits.file) {
12
+ return `Too large to attach: ${bytes(file.size)}, and this server takes files up to ${bytes(limits.file)}.`;
13
+ }
14
+ if (limits.message !== undefined && pending + file.size > limits.message) {
15
+ return `This would bring the attachments to ${bytes(pending + file.size)}, over the ${bytes(limits.message)} one message may carry.`;
16
+ }
17
+ return null;
18
+ }
4
19
  /** Split what somebody typed into addresses. Commas and semicolons both
5
20
  * separate, because both get typed and both get pasted. */
6
21
  export function parseAddresses(text) {
@@ -19,11 +34,122 @@ export function parseAddresses(text) {
19
34
  return { email: part };
20
35
  });
21
36
  }
22
- export function Composer({ draft, onChange, onSend, onCancel, identities, sending = false, error, className, }) {
37
+ export function Composer({ draft, onChange, onSend, onCancel, identities, onAttach, limits, sending = false, error, className, }) {
23
38
  const [showCopies, setShowCopies] = useState((draft.cc?.length ?? 0) > 0 || (draft.bcc?.length ?? 0) > 0);
24
- const set = (patch) => onChange({ ...draft, ...patch });
25
- const canSend = draft.to.length > 0 && !sending;
26
- return (_jsxs("form", { className: `composer${className ? ` ${className}` : ''}`, onSubmit: (event) => {
39
+ const [uploads, setUploads] = useState([]);
40
+ const [dropping, setDropping] = useState(false);
41
+ const picker = useRef(null);
42
+ const controllers = useRef(new Map());
43
+ const counter = useRef(0);
44
+ /* dragenter and dragleave fire for every child the pointer crosses, so
45
+ "is something over the composer" is a count, not the last event seen. */
46
+ const depth = useRef(0);
47
+ /* The draft as of the last change this component made or was handed. An
48
+ upload resolves long after the render that started it, and merging its
49
+ attachment into *that* render's `draft` would put back whatever has been
50
+ typed since. It is written on every change as well as read, so two
51
+ uploads that finish in the same tick each add to the other rather than
52
+ both to the draft they started from. `onChange` is read the same way, so
53
+ a late upload does not call a handler from three renders ago. */
54
+ const latest = useRef(draft);
55
+ const given = useRef(draft);
56
+ if (given.current !== draft) {
57
+ given.current = draft;
58
+ latest.current = draft;
59
+ }
60
+ const change = useRef(onChange);
61
+ change.current = onChange;
62
+ const commit = (next) => {
63
+ latest.current = next;
64
+ change.current(next);
65
+ };
66
+ const set = (patch) => commit({ ...latest.current, ...patch });
67
+ /* Closing the composer stops whatever is still uploading: the bytes are
68
+ going to a draft that no longer exists. */
69
+ useEffect(() => {
70
+ const live = controllers.current;
71
+ return () => {
72
+ for (const controller of live.values())
73
+ controller.abort();
74
+ live.clear();
75
+ };
76
+ }, []);
77
+ const start = (key, file) => {
78
+ if (!onAttach)
79
+ return;
80
+ const controller = new AbortController();
81
+ controllers.current.set(key, controller);
82
+ onAttach(file, controller.signal).then((attachment) => {
83
+ if (controller.signal.aborted)
84
+ return;
85
+ controllers.current.delete(key);
86
+ setUploads((all) => all.filter((upload) => upload.key !== key));
87
+ commit({
88
+ ...latest.current,
89
+ attachments: [...(latest.current.attachments ?? []), attachment],
90
+ });
91
+ }, (thrown) => {
92
+ if (controller.signal.aborted)
93
+ return;
94
+ controllers.current.delete(key);
95
+ const detail = thrown instanceof Error ? thrown.message : '';
96
+ setUploads((all) => all.map((upload) => upload.key === key
97
+ ? {
98
+ ...upload,
99
+ state: 'failed',
100
+ reason: detail ? `Did not upload: ${detail}.` : 'Did not upload.',
101
+ }
102
+ : upload));
103
+ });
104
+ };
105
+ /* Nothing is added while a send is in flight: that send has already taken
106
+ the draft it is sending, and a file attached now would be on neither it
107
+ nor anything else once it lands and the composer closes. */
108
+ const accepting = Boolean(onAttach) && !sending;
109
+ const add = (files) => {
110
+ if (!accepting || files.length === 0)
111
+ return;
112
+ let pending = (latest.current.attachments ?? []).reduce((sum, file) => sum + (file.size ?? 0), 0) +
113
+ uploads
114
+ .filter((upload) => upload.state === 'uploading')
115
+ .reduce((sum, upload) => sum + upload.file.size, 0);
116
+ const added = [];
117
+ for (const file of files) {
118
+ const key = `upload-${++counter.current}`;
119
+ const reason = refusal(file, pending, limits);
120
+ if (reason) {
121
+ added.push({ key, file, state: 'refused', reason });
122
+ continue;
123
+ }
124
+ pending += file.size;
125
+ added.push({ key, file, state: 'uploading' });
126
+ }
127
+ setUploads((all) => [...all, ...added]);
128
+ for (const upload of added)
129
+ if (upload.state === 'uploading')
130
+ start(upload.key, upload.file);
131
+ };
132
+ const remove = (key) => {
133
+ controllers.current.get(key)?.abort();
134
+ controllers.current.delete(key);
135
+ setUploads((all) => all.filter((upload) => upload.key !== key));
136
+ };
137
+ const retry = (key) => {
138
+ const upload = uploads.find((one) => one.key === key);
139
+ if (!upload || !accepting)
140
+ return;
141
+ setUploads((all) => all.map((one) => (one.key === key ? { key, file: one.file, state: 'uploading' } : one)));
142
+ start(key, upload.file);
143
+ };
144
+ const waiting = uploads.filter((upload) => upload.state === 'uploading').length;
145
+ const stuck = uploads.length - waiting;
146
+ const canSend = draft.to.length > 0 && !sending && uploads.length === 0;
147
+ /* Any drag carrying files is caught, whether or not this can take them.
148
+ A file let fall onto a page that does not want it is opened by the
149
+ browser in place of the page -- and the page here is somebody's
150
+ half-written message. Text dragged into the body is left alone. */
151
+ const carriesFiles = (event) => Array.from(event.dataTransfer?.types ?? []).includes('Files');
152
+ return (_jsxs("form", { className: `composer${dropping ? ' is-dropping' : ''}${className ? ` ${className}` : ''}`, onSubmit: (event) => {
27
153
  event.preventDefault();
28
154
  if (canSend)
29
155
  void onSend();
@@ -36,7 +162,40 @@ export function Composer({ draft, onChange, onSend, onCancel, identities, sendin
36
162
  event.preventDefault();
37
163
  if (canSend)
38
164
  void onSend();
39
- }, children: [identities.length > 1 && (_jsx(Field, { label: "From", children: (field) => (_jsx(Select, { id: field.id, block: true, value: draft.identityId, onChange: (event) => set({ identityId: event.target.value }), children: identities.map((identity) => (_jsx("option", { value: identity.id, children: identity.name ? `${identity.name} <${identity.email}>` : identity.email }, identity.id))) })) })), _jsx(AddressField, { label: "To", people: draft.to, onChange: (to) => set({ to }), trail: !showCopies && (_jsx(Button, { kind: "ghost", size: "sm", onClick: () => setShowCopies(true), type: "button", children: "Cc / Bcc" })) }), showCopies && (_jsxs(_Fragment, { children: [_jsx(AddressField, { label: "Cc", people: draft.cc ?? [], onChange: (cc) => set({ cc }) }), _jsx(AddressField, { label: "Bcc", people: draft.bcc ?? [], onChange: (bcc) => set({ bcc }) })] })), _jsx(Field, { label: "Subject", children: (field) => (_jsx(Input, { ...field, block: true, value: draft.subject, onChange: (event) => set({ subject: event.target.value }) })) }), _jsx(Field, { label: "Message", children: (field) => (_jsx(Textarea, { ...field, rows: 12, value: draft.text ?? '', onChange: (event) => set({ text: event.target.value }) })) }), (draft.attachments?.length ?? 0) > 0 && (_jsx("ul", { className: "composer-files", children: draft.attachments?.map((file) => (_jsxs("li", { children: [_jsx("span", { className: "composer-file", children: file.name }), _jsx(Button, { kind: "ghost", size: "sm", type: "button", onClick: () => set({ attachments: draft.attachments?.filter((f) => f.blobId !== file.blobId) }), "aria-label": `Remove ${file.name}`, children: "Remove" })] }, file.blobId))) })), error && (_jsx("p", { className: "composer-error", role: "alert", children: error })), _jsxs("div", { className: "composer-actions", children: [_jsxs(Button, { kind: "primary", type: "submit", disabled: !canSend, busy: sending, children: [_jsx(Icon, { name: "send", size: 15 }), " ", sending ? 'Sending…' : 'Send'] }), onCancel && (_jsx(Button, { kind: "ghost", type: "button", onClick: onCancel, disabled: sending, children: "Discard" })), _jsx("span", { className: "composer-hint", children: draft.to.length === 0 ? ('Add a recipient to send.') : (_jsxs(_Fragment, { children: [_jsx("kbd", { children: "\u2318" }), _jsx("kbd", { children: "\u21B5" }), " to send"] })) })] })] }));
165
+ }, onDragEnter: (event) => {
166
+ if (!carriesFiles(event))
167
+ return;
168
+ event.preventDefault();
169
+ depth.current += 1;
170
+ if (accepting)
171
+ setDropping(true);
172
+ }, onDragOver: (event) => {
173
+ if (!carriesFiles(event))
174
+ return;
175
+ event.preventDefault();
176
+ event.dataTransfer.dropEffect = accepting ? 'copy' : 'none';
177
+ }, onDragLeave: (event) => {
178
+ if (!carriesFiles(event))
179
+ return;
180
+ depth.current = Math.max(0, depth.current - 1);
181
+ if (depth.current === 0)
182
+ setDropping(false);
183
+ }, onDrop: (event) => {
184
+ if (!carriesFiles(event))
185
+ return;
186
+ event.preventDefault();
187
+ depth.current = 0;
188
+ setDropping(false);
189
+ add(Array.from(event.dataTransfer.files));
190
+ }, children: [identities.length > 1 && (_jsx(Field, { label: "From", children: (field) => (_jsx(Select, { id: field.id, block: true, value: draft.identityId, onChange: (event) => set({ identityId: event.target.value }), children: identities.map((identity) => (_jsx("option", { value: identity.id, children: identity.name ? `${identity.name} <${identity.email}>` : identity.email }, identity.id))) })) })), _jsx(AddressField, { label: "To", people: draft.to, onChange: (to) => set({ to }), trail: !showCopies && (_jsx(Button, { kind: "ghost", size: "sm", onClick: () => setShowCopies(true), type: "button", children: "Cc / Bcc" })) }), showCopies && (_jsxs(_Fragment, { children: [_jsx(AddressField, { label: "Cc", people: draft.cc ?? [], onChange: (cc) => set({ cc }) }), _jsx(AddressField, { label: "Bcc", people: draft.bcc ?? [], onChange: (bcc) => set({ bcc }) })] })), _jsx(Field, { label: "Subject", children: (field) => (_jsx(Input, { ...field, block: true, value: draft.subject, onChange: (event) => set({ subject: event.target.value }) })) }), _jsx(Field, { label: "Message", children: (field) => (_jsx(Textarea, { ...field, rows: 12, value: draft.text ?? '', onChange: (event) => set({ text: event.target.value }) })) }), ((draft.attachments?.length ?? 0) > 0 || uploads.length > 0) && (_jsxs("ul", { className: "composer-files", children: [draft.attachments?.map((file, index) => (_jsxs("li", { children: [_jsx(Icon, { name: "paperclip", size: 14, className: "composer-file-icon" }), _jsx("span", { className: "composer-file", children: file.name }), file.size !== undefined && (_jsx("span", { className: "composer-file-size", children: bytes(file.size) })), _jsx(Button, { kind: "ghost", size: "sm", type: "button", onClick: () => set({
191
+ attachments: latest.current.attachments?.filter((_, at) => at !== index),
192
+ }), "aria-label": `Remove ${file.name}`, children: "Remove" })] }, `${file.blobId}:${index}`))), uploads.map((upload) => {
193
+ const busy = upload.state === 'uploading';
194
+ return (_jsxs("li", { className: busy ? 'is-uploading' : 'is-stuck', "aria-busy": busy || undefined, children: [_jsx(Icon, { name: busy ? 'spinner' : 'warning', size: 14, className: `composer-file-icon${busy ? ' spin' : ''}` }), _jsx("span", { className: "composer-file", children: upload.file.name }), _jsx("span", { className: "composer-file-size", children: busy ? `Uploading ${bytes(upload.file.size)}…` : bytes(upload.file.size) }), upload.state === 'failed' && (_jsx(Button, { kind: "ghost", size: "sm", type: "button", onClick: () => retry(upload.key), disabled: !accepting, "aria-label": `Try ${upload.file.name} again`, children: "Try again" })), _jsx(Button, { kind: "ghost", size: "sm", type: "button", onClick: () => remove(upload.key), "aria-label": `${busy ? 'Stop uploading' : 'Remove'} ${upload.file.name}`, children: busy ? 'Stop' : 'Remove' }), upload.reason && (_jsx("p", { className: "composer-file-problem", role: "alert", children: upload.reason }))] }, upload.key));
195
+ })] })), error && (_jsx("p", { className: "composer-error", role: "alert", children: error })), onAttach && (_jsx("input", { ref: picker, type: "file", multiple: true, hidden: true, onChange: (event) => {
196
+ add(Array.from(event.target.files ?? []));
197
+ event.target.value = '';
198
+ } })), _jsxs("div", { className: "composer-actions", children: [_jsxs(Button, { kind: "primary", type: "submit", disabled: !canSend, busy: sending, children: [_jsx(Icon, { name: "send", size: 15 }), " ", sending ? 'Sending…' : 'Send'] }), onAttach && (_jsxs(Button, { kind: "ghost", type: "button", onClick: () => picker.current?.click(), disabled: !accepting, children: [_jsx(Icon, { name: "paperclip", size: 15 }), " Attach"] })), onCancel && (_jsx(Button, { kind: "ghost", type: "button", onClick: onCancel, disabled: sending, children: "Discard" })), _jsx("span", { className: "composer-hint", children: draft.to.length === 0 ? ('Add a recipient to send.') : waiting > 0 ? (`Waiting for ${waiting === 1 ? 'a file' : `${waiting} files`} to upload.`) : stuck > 0 ? (`${stuck === 1 ? 'A file' : `${stuck} files`} did not attach; remove ${stuck === 1 ? 'it' : 'them'} to send.`) : (_jsxs(_Fragment, { children: [_jsx("kbd", { children: "\u2318" }), _jsx("kbd", { children: "\u21B5" }), " to send"] })) })] })] }));
40
199
  }
41
200
  function AddressField({ label, people, onChange, trail, }) {
42
201
  const [typed, setTyped] = useState('');
@@ -0,0 +1,63 @@
1
+ import type { Attachment } from '../types.ts';
2
+ /**
3
+ * A message's HTML, drawn where it cannot reach the page around it.
4
+ *
5
+ * **Three walls, and each stands if the other two fall.** The markup arrives
6
+ * from strangers, and a client that puts it into its own document has a
7
+ * cross-site scripting hole in the one place attackers reliably look. So it
8
+ * is never put there:
9
+ *
10
+ * 1. *The frame.* It is a `srcdoc` iframe whose `sandbox` has no
11
+ * `allow-scripts`, so nothing in it runs — not a script element, not an
12
+ * `onerror`, not a `javascript:` link. Without `allow-forms` nothing in it
13
+ * submits, and without `allow-top-navigation` nothing in it replaces this
14
+ * page. Links open a tab of their own through
15
+ * `allow-popups-to-escape-sandbox`: a page opened from a mail is an
16
+ * ordinary page, and should not inherit a sandbox it would break under.
17
+ * 2. *Its content policy.* The document carries its own
18
+ * `Content-Security-Policy`: `default-src 'none'`, so no script, font,
19
+ * frame, fetch or media; inline styles and nothing else; `form-action` and
20
+ * `base-uri` closed, because neither falls back to the default; images
21
+ * from `data:` only, until the reader allows more.
22
+ * 3. *The sanitiser.* `sanitise.ts` walks the markup against an allowlist
23
+ * before any of it reaches the frame, for the things the first two do not
24
+ * stop: a `<meta>` refresh, a `<base>`, a `ping`, a relative address that
25
+ * would fetch from this application.
26
+ *
27
+ * **`allow-same-origin`, deliberately.** It is what lets this component read
28
+ * the frame's height, so a message reads as part of the conversation rather
29
+ * than as a box with its own scrollbar inside a scrolling pane. It is safe
30
+ * because nothing in the frame can run: same origin is the power to reach
31
+ * this page *from script*, and there is none. The pairing never to ship is
32
+ * `allow-scripts` with `allow-same-origin`, which lets a frame remove its own
33
+ * sandbox; this has one of the two, and `FRAME_SANDBOX` is pinned by a test.
34
+ *
35
+ * **Remote images wait to be asked for.** An image on the sender's server is
36
+ * a request the sender sees: that the message was opened, when, and from
37
+ * where. They are withheld — by the sanitiser, and again by the policy — and
38
+ * the reader is told how many, with a button that allows them for this
39
+ * message.
40
+ *
41
+ * **Inline images are fetched, not linked.** A `cid:` picture is a part of
42
+ * the message, on this account's own server, behind the same credential as
43
+ * everything else — so `fetchInline` fetches it and it goes in as a `data:`
44
+ * URL. Only raster types: the part's declared type is the sender's claim, and
45
+ * a picture is the only thing it is allowed to claim.
46
+ *
47
+ * **The frame is drawn after the page is.** The sanitiser needs `DOMParser`,
48
+ * which a server render does not have, so the server and the first client
49
+ * render agree on drawing nothing and the frame arrives with the second.
50
+ */
51
+ /** The frame's permissions, in full. Adding `allow-scripts` to this makes the
52
+ * other two walls the only ones, and with `allow-same-origin` beside it not
53
+ * even those. */
54
+ export declare const FRAME_SANDBOX = "allow-same-origin allow-popups allow-popups-to-escape-sandbox";
55
+ export type HtmlBodyProps = {
56
+ html: string;
57
+ /** The message's parts, for the inline pictures its HTML refers to. */
58
+ attachments: readonly Attachment[];
59
+ /** Fetches an inline part's bytes. Without it, `cid:` pictures are left
60
+ * out rather than requested without a credential. */
61
+ fetchInline?: (attachment: Attachment) => Promise<Blob>;
62
+ };
63
+ export declare function HtmlBody({ html, attachments, fetchInline }: HtmlBodyProps): import("react").JSX.Element;
@@ -0,0 +1,168 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Button } from '@wtfalch/design';
3
+ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
4
+ import { isInlineImage, mailDocument } from "./sanitise.js";
5
+ /**
6
+ * A message's HTML, drawn where it cannot reach the page around it.
7
+ *
8
+ * **Three walls, and each stands if the other two fall.** The markup arrives
9
+ * from strangers, and a client that puts it into its own document has a
10
+ * cross-site scripting hole in the one place attackers reliably look. So it
11
+ * is never put there:
12
+ *
13
+ * 1. *The frame.* It is a `srcdoc` iframe whose `sandbox` has no
14
+ * `allow-scripts`, so nothing in it runs — not a script element, not an
15
+ * `onerror`, not a `javascript:` link. Without `allow-forms` nothing in it
16
+ * submits, and without `allow-top-navigation` nothing in it replaces this
17
+ * page. Links open a tab of their own through
18
+ * `allow-popups-to-escape-sandbox`: a page opened from a mail is an
19
+ * ordinary page, and should not inherit a sandbox it would break under.
20
+ * 2. *Its content policy.* The document carries its own
21
+ * `Content-Security-Policy`: `default-src 'none'`, so no script, font,
22
+ * frame, fetch or media; inline styles and nothing else; `form-action` and
23
+ * `base-uri` closed, because neither falls back to the default; images
24
+ * from `data:` only, until the reader allows more.
25
+ * 3. *The sanitiser.* `sanitise.ts` walks the markup against an allowlist
26
+ * before any of it reaches the frame, for the things the first two do not
27
+ * stop: a `<meta>` refresh, a `<base>`, a `ping`, a relative address that
28
+ * would fetch from this application.
29
+ *
30
+ * **`allow-same-origin`, deliberately.** It is what lets this component read
31
+ * the frame's height, so a message reads as part of the conversation rather
32
+ * than as a box with its own scrollbar inside a scrolling pane. It is safe
33
+ * because nothing in the frame can run: same origin is the power to reach
34
+ * this page *from script*, and there is none. The pairing never to ship is
35
+ * `allow-scripts` with `allow-same-origin`, which lets a frame remove its own
36
+ * sandbox; this has one of the two, and `FRAME_SANDBOX` is pinned by a test.
37
+ *
38
+ * **Remote images wait to be asked for.** An image on the sender's server is
39
+ * a request the sender sees: that the message was opened, when, and from
40
+ * where. They are withheld — by the sanitiser, and again by the policy — and
41
+ * the reader is told how many, with a button that allows them for this
42
+ * message.
43
+ *
44
+ * **Inline images are fetched, not linked.** A `cid:` picture is a part of
45
+ * the message, on this account's own server, behind the same credential as
46
+ * everything else — so `fetchInline` fetches it and it goes in as a `data:`
47
+ * URL. Only raster types: the part's declared type is the sender's claim, and
48
+ * a picture is the only thing it is allowed to claim.
49
+ *
50
+ * **The frame is drawn after the page is.** The sanitiser needs `DOMParser`,
51
+ * which a server render does not have, so the server and the first client
52
+ * render agree on drawing nothing and the frame arrives with the second.
53
+ */
54
+ /** The frame's permissions, in full. Adding `allow-scripts` to this makes the
55
+ * other two walls the only ones, and with `allow-same-origin` beside it not
56
+ * even those. */
57
+ export const FRAME_SANDBOX = 'allow-same-origin allow-popups allow-popups-to-escape-sandbox';
58
+ const never = () => () => { };
59
+ /** True once this is a browser render, false on the server and during
60
+ * hydration, so the two never disagree about the markup. */
61
+ function useBrowser() {
62
+ return useSyncExternalStore(never, () => typeof DOMParser === 'function', () => false);
63
+ }
64
+ const NONE = new Map();
65
+ /**
66
+ * The inline pictures the HTML refers to, as `data:` URLs by Content-ID.
67
+ *
68
+ * The fetcher is held in a ref, as `usePush` holds its handler: a caller
69
+ * that passes an inline arrow would otherwise refetch every picture on every
70
+ * render, and each result would cause the next render.
71
+ */
72
+ function useInlineImages(html, attachments, fetchInline) {
73
+ const [found, setFound] = useState(NONE);
74
+ const fetcher = useRef(fetchInline);
75
+ fetcher.current = fetchInline;
76
+ const able = fetchInline !== undefined;
77
+ useEffect(() => {
78
+ const fetch = fetcher.current;
79
+ if (!able || !fetch)
80
+ return;
81
+ const wanted = attachments.filter((file) => file.cid !== null && isInlineImage(file.type) && html.includes(file.cid));
82
+ if (wanted.length === 0)
83
+ return;
84
+ let live = true;
85
+ void Promise.all(wanted.map(async (file) => {
86
+ try {
87
+ return [file.cid, await asDataUrl(await fetch(file), file.type)];
88
+ }
89
+ catch {
90
+ // A picture that will not come is a gap in the message, not a
91
+ // reason to lose the ones that did.
92
+ return null;
93
+ }
94
+ })).then((pairs) => {
95
+ if (live)
96
+ setFound(new Map(pairs.filter((pair) => pair !== null)));
97
+ });
98
+ return () => {
99
+ live = false;
100
+ };
101
+ }, [html, attachments, able]);
102
+ return found;
103
+ }
104
+ /** Bytes as a `data:` URL of the type the message declared, which the
105
+ * caller has already checked is a picture. */
106
+ async function asDataUrl(blob, type) {
107
+ const bytes = new Uint8Array(await blob.arrayBuffer());
108
+ let binary = '';
109
+ for (let at = 0; at < bytes.length; at += 0x8000) {
110
+ binary += String.fromCharCode(...bytes.subarray(at, at + 0x8000));
111
+ }
112
+ return `data:${type.toLowerCase()};base64,${btoa(binary)}`;
113
+ }
114
+ export function HtmlBody({ html, attachments, fetchInline }) {
115
+ const browser = useBrowser();
116
+ const [remote, setRemote] = useState(false);
117
+ const [source, setSource] = useState(false);
118
+ const inline = useInlineImages(html, attachments, fetchInline);
119
+ /* A sanitiser that throws has not sanitised anything, so a failure draws
120
+ no frame at all -- and says so, rather than taking the conversation
121
+ down with it through the error boundary. */
122
+ const made = useMemo(() => {
123
+ if (!browser)
124
+ return null;
125
+ try {
126
+ return mailDocument(html, {
127
+ remote,
128
+ inline,
129
+ origin: typeof location === 'undefined' ? undefined : location.origin,
130
+ });
131
+ }
132
+ catch {
133
+ return 'failed';
134
+ }
135
+ }, [browser, html, remote, inline]);
136
+ const frame = useRef(null);
137
+ /* The document's own height, plus the sideways scrollbar when a wide
138
+ message has one. Read on load, which waits for its pictures, and again
139
+ when the pane changes width, which reflows it. Not on a change of
140
+ height: the frame's height is what this sets, and a message whose
141
+ content follows the frame's height would chase it for ever. */
142
+ const fit = useCallback(() => {
143
+ const node = frame.current;
144
+ const root = node?.contentDocument?.documentElement;
145
+ const view = node?.contentWindow;
146
+ if (!node || !root || !view)
147
+ return;
148
+ const height = Math.ceil(root.getBoundingClientRect().height);
149
+ const scrollbar = Math.max(0, view.innerHeight - root.clientHeight);
150
+ node.style.height = `${height + scrollbar}px`;
151
+ }, []);
152
+ const drawn = made !== null && made !== 'failed';
153
+ useEffect(() => {
154
+ const node = frame.current;
155
+ if (!drawn || !node || typeof ResizeObserver !== 'function')
156
+ return;
157
+ let width = node.clientWidth;
158
+ const observer = new ResizeObserver(() => {
159
+ if (node.clientWidth === width)
160
+ return;
161
+ width = node.clientWidth;
162
+ fit();
163
+ });
164
+ observer.observe(node);
165
+ return () => observer.disconnect();
166
+ }, [drawn, fit]);
167
+ return (_jsxs("div", { className: "message-html", children: [made === 'failed' && (_jsx("p", { className: "message-quiet", children: "This message's formatting could not be made safe to draw, so it is not drawn. The source is below." })), drawn && made.blocked > 0 && (_jsxs("p", { className: "message-images", children: [_jsxs("span", { children: [made.blocked === 1 ? 'One remote image is' : `${made.blocked} remote images are`, ' ', "hidden, so the sender cannot see when this was opened."] }), _jsx(Button, { kind: "ghost", size: "sm", onClick: () => setRemote(true), children: "Show images" })] })), drawn && (_jsx("iframe", { ref: frame, className: "message-frame", title: "The message, as its sender formatted it", sandbox: FRAME_SANDBOX, referrerPolicy: "no-referrer", srcDoc: made.srcdoc, onLoad: fit })), _jsx(Button, { kind: "ghost", size: "sm", onClick: () => setSource((was) => !was), children: source ? 'Hide the source' : 'Show the source' }), source && _jsx("pre", { className: "message-source", children: html })] }));
168
+ }
@@ -1,6 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Button, Command, Icon, Modal, SplitPane } from '@wtfalch/design';
3
3
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
4
+ import { attach } from "../attach.js";
4
5
  import { downloadAttachment } from "../download.js";
5
6
  import { forwardDraft, replyDraft } from "../drafts.js";
6
7
  import { findRole } from "../mailboxes.js";
@@ -44,6 +45,9 @@ import { saveBlob } from "./save.js";
44
45
  * focus, or `c` could never be typed into a subject.
45
46
  */
46
47
  const PAGE = 50;
48
+ /** A logo or a signature is kilobytes; five megabytes is a photograph, and
49
+ * past that it is an attachment wearing a `cid:`. */
50
+ const INLINE_MAX_BYTES = 5 * 1024 * 1024;
47
51
  export function Mail({ client, location, onNavigate, account, onError, now, className, }) {
48
52
  const [ownMailboxId, setOwnMailboxId] = useState(null);
49
53
  const [ownThreadId, setOwnThreadId] = useState(null);
@@ -68,6 +72,12 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
68
72
  const [query, setQuery] = useState('');
69
73
  const [text, setText] = useState('');
70
74
  const [draft, setDraft] = useState(null);
75
+ /* Which draft this is, as a key for the composer. Starting a reply while
76
+ another draft is open replaces the draft without closing the modal, and
77
+ the composer's own state -- the uploads under way above all -- belongs
78
+ to the draft it was opened for: without a new key, a file still uploading
79
+ for one message would land on the next. */
80
+ const [drafted, setDrafted] = useState(0);
71
81
  const [sending, setSending] = useState(false);
72
82
  const [sendError, setSendError] = useState();
73
83
  const [paletteOpen, setPaletteOpen] = useState(false);
@@ -82,6 +92,33 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
82
92
  const searchField = useRef(null);
83
93
  const boxes = useMailboxes(client);
84
94
  const identities = useIdentities(client);
95
+ /* What the server will take, for the composer to refuse an oversize file
96
+ in a sentence instead of after uploading it. Read each time a composer
97
+ opens rather than once, so a session that failed at first -- or came
98
+ back under a new token -- is read again; it is the connection the
99
+ client already holds, not a request. A failure is left alone: the hooks
100
+ above report a connection that does not work, and without limits the
101
+ server is still the one that refuses. */
102
+ const [limits, setLimits] = useState({});
103
+ const composing = draft !== null;
104
+ useEffect(() => {
105
+ if (!composing)
106
+ return;
107
+ let live = true;
108
+ client.session().then((session) => {
109
+ if (!live)
110
+ return;
111
+ setLimits({
112
+ ...(session.maxSizeUpload !== null ? { file: session.maxSizeUpload } : {}),
113
+ ...(session.maxSizeAttachmentsPerEmail !== null
114
+ ? { message: session.maxSizeAttachmentsPerEmail }
115
+ : {}),
116
+ });
117
+ }, () => { });
118
+ return () => {
119
+ live = false;
120
+ };
121
+ }, [client, composing]);
85
122
  /* The inbox, once, when the mailboxes first arrive. Not in an effect that
86
123
  depends on `boxes.data`, which would fight a person who has since picked
87
124
  another mailbox: it only fires while nothing is selected. */
@@ -156,18 +193,21 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
156
193
  if (!identity)
157
194
  return;
158
195
  setSendError(undefined);
196
+ setDrafted((n) => n + 1);
159
197
  setDraft(replyDraft(message, { identity, all }));
160
198
  }, [identity]);
161
199
  const startForward = useCallback((message) => {
162
200
  if (!identity)
163
201
  return;
164
202
  setSendError(undefined);
203
+ setDrafted((n) => n + 1);
165
204
  setDraft(forwardDraft(message, { identity }));
166
205
  }, [identity]);
167
206
  const startNew = useCallback(() => {
168
207
  if (!identity)
169
208
  return;
170
209
  setSendError(undefined);
210
+ setDrafted((n) => n + 1);
171
211
  setDraft({ identityId: identity.id, to: [], subject: '', text: '' });
172
212
  }, [identity]);
173
213
  const doSend = async () => {
@@ -262,6 +302,10 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
262
302
  });
263
303
  }
264
304
  }, [client]);
305
+ /** An inline picture for an HTML body, behind the same credential as the
306
+ * rest, and capped well below an attachment: it is going into a document
307
+ * as a `data:` URL, not onto the disk. */
308
+ const fetchInline = useCallback((file) => downloadAttachment(client, file, { maxBytes: INLINE_MAX_BYTES }), [client]);
265
309
  const flag = useCallback((next) => {
266
310
  if (!threadId)
267
311
  return;
@@ -438,8 +482,8 @@ export function Mail({ client, location, onNavigate, account, onError, now, clas
438
482
  setQuery('');
439
483
  }, "aria-label": "Clear the search", children: _jsx(Icon, { name: "close", size: 13 }) })) : (_jsx("span", { className: "mail-search-key", "aria-hidden": "true", children: "/" }))] }));
440
484
  const list = (_jsx(ThreadList, { page: threads.data, selectedId: threadId, onSelect: openThread, onPage: (threads.data?.total ?? 0) > PAGE ? setPosition : undefined, limit: PAGE, loading: threads.loading, now: now, title: query ? `Results for “${query}”` : current?.name, empty: query ? _jsxs("p", { className: "threads-quiet", children: ["Nothing matches \u201C", query, "\u201D."] }) : undefined }));
441
- const reader = (_jsx(ThreadView, { thread: thread.data, loading: thread.loading, onReply: startReply, onForward: startForward, onArchive: archiveBox ? archive : undefined, onTrash: trashBox ? trash : undefined, onMarkUnread: markUnread, onFlag: flag, onDownload: (file) => void download(file), downloading: downloading, flagged: summary?.isFlagged ?? false, busy: acting, onBack: panes === 'narrow' ? () => setThreadId(null) : undefined }));
442
- return (_jsxs("div", { className: `mail is-${panes}${className ? ` ${className}` : ''}`, children: [_jsxs("header", { className: "mail-bar", children: [_jsxs("div", { className: "mail-bar-start", children: [panes === 'narrow' && (_jsx(Button, { kind: "ghost", iconOnly: true, onClick: () => setDrawerOpen(true), "aria-label": "Mailboxes", children: _jsx(Icon, { name: "menu" }) })), _jsx("span", { className: "mail-wordmark", children: "Mail" })] }), searchBox, _jsxs("div", { className: "mail-bar-end", children: [_jsxs(Button, { kind: "primary", size: "sm", onClick: startNew, disabled: !identity, children: [_jsx(Icon, { name: "pen", size: 15 }), " ", _jsx("span", { className: "mail-compose-word", children: "Compose" })] }), account] })] }), panes === 'wide' && (_jsxs(SplitPane, { className: "mail-panes", label: "Mailbox list width", defaultSize: 15, min: 11, max: 28, storageKey: "mail-sidebar", children: [_jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading }), _jsxs(SplitPane, { label: "Conversation list width", defaultSize: 36, min: 26, max: 55, storageKey: "mail-list", children: [list, reader] })] })), panes === 'medium' && (_jsxs("div", { className: "mail-panes", children: [_jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading, rail: true }), _jsxs(SplitPane, { className: "mail-panes-split", label: "Conversation list width", defaultSize: 40, min: 28, max: 60, storageKey: "mail-list", children: [list, reader] })] })), panes === 'narrow' && _jsx("div", { className: "mail-panes", children: reading ? reader : list }), drawerOpen && (_jsx(Modal, { title: "Mailboxes", width: "20rem", onClose: () => setDrawerOpen(false), children: _jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading }) })), _jsx(Command, { open: paletteOpen, onOpenChange: setPaletteOpen, groups: paletteGroups }), helpOpen && (_jsx(Modal, { title: "Keyboard shortcuts", width: "26rem", onClose: () => setHelpOpen(false), children: _jsx(Shortcuts, {}) })), draft && (_jsx(Modal, { title: draft.subject ? draft.subject : 'New message', width: "46rem", onClose: sending ? undefined : () => setDraft(null), closeDisabled: sending, children: _jsx(Composer, { draft: draft, onChange: setDraft, onSend: doSend, onCancel: () => setDraft(null), identities: identities.data ?? [], sending: sending, error: sendError }) })), _jsx(Note, { said: note, onDone: () => setNote(null) })] }));
485
+ const reader = (_jsx(ThreadView, { thread: thread.data, loading: thread.loading, onReply: startReply, onForward: startForward, onArchive: archiveBox ? archive : undefined, onTrash: trashBox ? trash : undefined, onMarkUnread: markUnread, onFlag: flag, onDownload: (file) => void download(file), downloading: downloading, fetchInline: fetchInline, flagged: summary?.isFlagged ?? false, busy: acting, onBack: panes === 'narrow' ? () => setThreadId(null) : undefined }));
486
+ return (_jsxs("div", { className: `mail is-${panes}${className ? ` ${className}` : ''}`, children: [_jsxs("header", { className: "mail-bar", children: [_jsxs("div", { className: "mail-bar-start", children: [panes === 'narrow' && (_jsx(Button, { kind: "ghost", iconOnly: true, onClick: () => setDrawerOpen(true), "aria-label": "Mailboxes", children: _jsx(Icon, { name: "menu" }) })), _jsx("span", { className: "mail-wordmark", children: "Mail" })] }), searchBox, _jsxs("div", { className: "mail-bar-end", children: [_jsxs(Button, { kind: "primary", size: "sm", onClick: startNew, disabled: !identity, children: [_jsx(Icon, { name: "pen", size: 15 }), " ", _jsx("span", { className: "mail-compose-word", children: "Compose" })] }), account] })] }), panes === 'wide' && (_jsxs(SplitPane, { className: "mail-panes", label: "Mailbox list width", defaultSize: 15, min: 11, max: 28, storageKey: "mail-sidebar", children: [_jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading }), _jsxs(SplitPane, { label: "Conversation list width", defaultSize: 36, min: 26, max: 55, storageKey: "mail-list", children: [list, reader] })] })), panes === 'medium' && (_jsxs("div", { className: "mail-panes", children: [_jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading, rail: true }), _jsxs(SplitPane, { className: "mail-panes-split", label: "Conversation list width", defaultSize: 40, min: 28, max: 60, storageKey: "mail-list", children: [list, reader] })] })), panes === 'narrow' && _jsx("div", { className: "mail-panes", children: reading ? reader : list }), drawerOpen && (_jsx(Modal, { title: "Mailboxes", width: "20rem", onClose: () => setDrawerOpen(false), children: _jsx(MailboxTree, { mailboxes: boxes.data ?? [], selectedId: mailboxId, onSelect: go, loading: boxes.loading }) })), _jsx(Command, { open: paletteOpen, onOpenChange: setPaletteOpen, groups: paletteGroups }), helpOpen && (_jsx(Modal, { title: "Keyboard shortcuts", width: "26rem", onClose: () => setHelpOpen(false), children: _jsx(Shortcuts, {}) })), draft && (_jsx(Modal, { title: draft.subject ? draft.subject : 'New message', width: "46rem", onClose: sending ? undefined : () => setDraft(null), closeDisabled: sending, children: _jsx(Composer, { draft: draft, onChange: setDraft, onSend: doSend, onCancel: () => setDraft(null), identities: identities.data ?? [], onAttach: (file, signal) => attach(client, file, { signal }), limits: limits, sending: sending, error: sendError }, drafted) })), _jsx(Note, { said: note, onDone: () => setNote(null) })] }));
443
487
  }
444
488
  /**
445
489
  * What just happened, said once and then gone.
@@ -17,13 +17,18 @@ import type { Attachment, Message, ThreadDetail } from '../types.ts';
17
17
  * is the one you came to read. A thread view that opens everything makes you
18
18
  * scroll past mail you have already seen to reach the mail you have not.
19
19
  *
20
- * **The HTML body is not rendered.** It arrives from strangers, and a mail
21
- * client that injects it into its own document is a mail client with a
22
- * cross-site scripting hole in the one place attackers reliably look. Text is
23
- * shown; where a message has only HTML, this says so and offers the raw
24
- * source rather than silently showing nothing. Rendering it safely means a
25
- * sandboxed frame with a sanitiser and a content policy, which is its own
26
- * piece of work.
20
+ * **The HTML body is drawn in a frame it cannot climb out of.** It arrives
21
+ * from strangers, and a mail client that injects it into its own document is
22
+ * a mail client with a cross-site scripting hole in the one place attackers
23
+ * reliably look. `HtmlBody` puts it in a sandboxed frame with no script,
24
+ * under a content policy of its own, after a sanitiser has been over it —
25
+ * three walls, each of which holds alone. Its docblock says what each stops.
26
+ *
27
+ * **Plain text first, where there is a choice.** A message with both is
28
+ * shown as its text, with the formatted version a button away. The text is
29
+ * what the sender wrote rather than how they dressed it, it reflows to any
30
+ * pane, and it asks the reader nothing about images; the frame is for mail
31
+ * that has nothing else.
27
32
  *
28
33
  * **A truncated body says it is truncated.** `core` fetches the first half
29
34
  * megabyte of each part; a message longer than that would otherwise appear to
@@ -53,10 +58,13 @@ export type ThreadViewProps = ThreadActions & {
53
58
  * A set rather than a boolean: four files on one message download
54
59
  * independently and one spinner for all of them lies about three. */
55
60
  downloading?: ReadonlySet<string>;
61
+ /** Fetches an inline picture's bytes, for a `cid:` reference in an HTML
62
+ * body. Without it those pictures are left out. */
63
+ fetchInline?: (attachment: Attachment) => Promise<Blob>;
56
64
  /** Back to the list, on a window too narrow to show both. */
57
65
  onBack?: () => void;
58
66
  className?: string;
59
67
  };
60
- export declare function ThreadView({ thread, loading, onReply, onForward, onArchive, onTrash, onMarkUnread, onFlag, flagged, busy, onDownload, downloading, onBack, className, }: ThreadViewProps): import("react").JSX.Element;
68
+ export declare function ThreadView({ thread, loading, onReply, onForward, onArchive, onTrash, onMarkUnread, onFlag, flagged, busy, onDownload, downloading, fetchInline, onBack, className, }: ThreadViewProps): import("react").JSX.Element;
61
69
  /** Bytes, the way a mail client says them. */
62
70
  export declare function bytes(size: number): string;