clavarium 0.2.321-next.1 → 0.2.323-next.1

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,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.321-next.1",
3
+ "version": "0.2.323-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.321-next.1",
9
+ "version": "0.2.323-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.321-next.1",
3
+ "version": "0.2.323-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
package/server/api.mjs CHANGED
@@ -152,7 +152,7 @@ import { suggest } from './suggest.mjs';
152
152
  import { sameOrigin } from './bridge.mjs';
153
153
  import { Refusal, DISK_GB } from './conversations.mjs';
154
154
  import { VmUnknown } from './vm.mjs';
155
- import { list, download, importFile, page, PAGE_HEADERS, changeRoute, IMAGE_HEADERS } from './files.mjs';
155
+ import { list, download, importFile, page, PAGE_HEADERS, changeRoute, IMAGE_HEADERS, mailFile, mailPage } from './files.mjs';
156
156
  import { WORK_TAB } from './resources.mjs';
157
157
  import { transcribe, AUDIO_MAX } from './voice.mjs';
158
158
  import { FILE_MAX } from './setup.mjs';
@@ -242,6 +242,14 @@ export async function handleApi(request, response, conversations, headers, resou
242
242
  file.stream.pipe(response);
243
243
  return true;
244
244
  }
245
+ if (request.method === 'GET' && pathname === '/api/files/mail') {
246
+ /* A mail with its remote pictures (asked for, never on opening): as a page is, not for a conversation that is offline. */
247
+ if (conversations.list().find((x) => x.name === query.get('c'))?.offline === true) throw new Refusal(403, 'This conversation is offline: remote pictures stay blocked.');
248
+ const shown = mailPage(await mailFile(attached(), query.get('p') ?? ''));
249
+ response.writeHead(200, shown.headers);
250
+ response.end(shown.body);
251
+ return true;
252
+ }
245
253
  if (request.method === 'GET' && pathname === '/api/files/download') {
246
254
  const file = await download(attached(), query.get('p') ?? '');
247
255
  response.writeHead(200, { ...headers, 'content-type': 'application/octet-stream', 'content-length': file.size,
package/server/door.mjs CHANGED
@@ -48,7 +48,7 @@
48
48
  import { Refusal } from './conversations.mjs';
49
49
  import { readCookie, sessionCookie, cookieNameOf, isPairingId } from './devices.mjs';
50
50
  import { WORK_TAB } from './resources.mjs';
51
- import { list, download, importFile, page, PAGE_HEADERS, changeRoute, CHANGE_ROUTES, IMAGE_HEADERS } from './files.mjs';
51
+ import { list, download, importFile, page, PAGE_HEADERS, changeRoute, CHANGE_ROUTES, IMAGE_HEADERS, mailFile, mailPage } from './files.mjs';
52
52
  import { transcribe, AUDIO_MAX } from './voice.mjs';
53
53
 
54
54
  const BODY_MAX = 16 * 1024;
@@ -155,7 +155,7 @@ export async function handleDoor(request, response, { devices, conversations, re
155
155
  return send(200, { ...about, conversations: names.filter((n) => conversations.list().some((c) => c.name === n)), shared: own });
156
156
  }
157
157
  /* The files a device was given for itself need no conversation; everything else does. */
158
- const forFiles = route === '/files' || route === '/files/download' || route === '/files/page' || route === '/files/import' || CHANGE_ROUTES.includes(route) || route === '/leave';
158
+ const forFiles = route === '/files' || route === '/files/download' || route === '/files/page' || route === '/files/mail' || route === '/files/import' || CHANGE_ROUTES.includes(route) || route === '/leave';
159
159
  if (!mine && !forFiles) return send(404, { error: 'This device was given no conversation.' });
160
160
  /* Shortcuts are typed into the terminal, or are the ready answers of the chat: one of the two must be its to write in. */
161
161
  if (request.method === 'GET' && route === '/shortcuts') { need(part.terminal || part.chat === 'write', 'the terminal or the chat'); return send(200, shortcuts.list()); }
@@ -208,6 +208,13 @@ export async function handleDoor(request, response, { devices, conversations, re
208
208
  file.stream.pipe(response);
209
209
  return true;
210
210
  }
211
+ if (request.method === 'GET' && route === '/files/mail') {
212
+ if (mine?.offline === true) throw new Refusal(403, 'This conversation is offline: remote pictures stay blocked.');
213
+ const shown = mailPage(await mailFile(attached('read', 'open'), url.searchParams.get('p') ?? ''));
214
+ response.writeHead(200, shown.headers);
215
+ response.end(shown.body);
216
+ return true;
217
+ }
211
218
  if (request.method === 'GET' && route === '/files/download') {
212
219
  const file = await download(attached('read', 'open'), url.searchParams.get('p') ?? '');
213
220
  response.writeHead(200, { ...headers, 'content-type': 'application/octet-stream', 'content-length': file.size,
package/server/files.mjs CHANGED
@@ -13,7 +13,7 @@
13
13
  * saves it, it never opens it as a page of this site.
14
14
  */
15
15
  import { lstat, readdir, realpath, open, rename, unlink, mkdir, rm } from 'node:fs/promises';
16
- import { createReadStream, constants } from 'node:fs';
16
+ import { createReadStream, constants, readFileSync } from 'node:fs';
17
17
  import { randomBytes } from 'node:crypto';
18
18
  import { join, sep } from 'node:path';
19
19
  import { Refusal } from './conversations.mjs';
@@ -106,6 +106,41 @@ export async function page(root, relative) {
106
106
  return file;
107
107
  }
108
108
 
109
+ /* A MAIL FILE'S PAGE WITH ITS REMOTE PICTURES (05-11): only when the reader asks for them ("Show them").
110
+ * The page reads the mail itself (web/mail-view.js) and draws it in a frame whose rules are the page's
111
+ * own: nothing remote can load there. So this answer, the same mail made harmless by the same code,
112
+ * carries rules of its own -- pictures from anywhere, and still no script, no form, no same-origin
113
+ * (sandbox), shown only inside this site's window. Read whole: an .eml up to PREVIEW_MAX. */
114
+ export const MAIL_MAX = 25 * 1024 * 1024;
115
+ let mailCode = null;
116
+ const mailReader = () => {
117
+ if (!mailCode) { const holder = {}; new Function('window', readFileSync(new URL('../web/mail-view.js', import.meta.url), 'utf8'))(holder); mailCode = holder.clavariumMail; }
118
+ return mailCode;
119
+ };
120
+ export const MAIL_HEADERS = Object.freeze({
121
+ 'content-type': 'text/html; charset=utf-8',
122
+ 'content-security-policy': "sandbox allow-popups allow-popups-to-escape-sandbox; default-src 'none'; img-src data: https: http:; style-src 'unsafe-inline'; font-src data:; form-action 'none'; base-uri 'none'; frame-ancestors 'self'",
123
+ 'x-content-type-options': 'nosniff',
124
+ 'referrer-policy': 'no-referrer',
125
+ 'cache-control': 'no-store',
126
+ 'cross-origin-resource-policy': 'same-origin',
127
+ });
128
+ export function mailPage(bytes) {
129
+ const reader = mailReader();
130
+ const body = reader.pageOf(reader.parse(bytes), { remote: true }).html;
131
+ return { body, headers: { ...MAIL_HEADERS, 'content-length': Buffer.byteLength(body) } };
132
+ }
133
+ /* The bytes of a mail file of a folder, for mailPage. */
134
+ export async function mailFile(root, relative) {
135
+ const file = await download(root, relative);
136
+ file.stream.on('error', () => {});
137
+ if (!/\.eml$/i.test(file.name)) { file.stream.destroy(); throw new Refusal(400, 'Only a mail file (.eml) is shown as a mail.'); }
138
+ if (file.size > MAIL_MAX) { file.stream.destroy(); throw new Refusal(413, 'This mail is too large to be shown here. Download it.'); }
139
+ const chunks = [];
140
+ for await (const chunk of file.stream) chunks.push(chunk);
141
+ return new Uint8Array(Buffer.concat(chunks));
142
+ }
143
+
109
144
  /* Writes an imported file under `relative` (a folder). By default it never
110
145
  overwrites: a taken name becomes "name (2).ext". Returns the name it was given.
111
146
  `exists`: 'keep' (both kept, the default), 'replace' (a FILE of that name
package/server/main.mjs CHANGED
@@ -102,6 +102,8 @@ export const FILES = {
102
102
  '/links.js': ['web/links.js', 'text/javascript; charset=utf-8'],
103
103
  '/features.js': ['web/features.js', 'text/javascript; charset=utf-8'],
104
104
  '/kit.js': ['web/kit.js', 'text/javascript; charset=utf-8'],
105
+ /* A mail file (.eml) read as a mail program shows it (the file viewer, app.js showMail). */
106
+ '/mail-view.js': ['web/mail-view.js', 'text/javascript; charset=utf-8'],
105
107
  '/gitgraph.js': ['web/gitgraph.js', 'text/javascript; charset=utf-8'],
106
108
  /* The page shown while an update stops this server (app.js goes to it); the front serves the same file while it is down. */
107
109
  '/maintenance.html': [MAINTENANCE, 'text/html; charset=utf-8'],
@@ -43,5 +43,10 @@ export const SETTINGS_WORDS_FR = {
43
43
  'set-na-speaks': 'Parlera dans {name}', 'set-na-room': 'salon', 'set-na-box-plug': 'Branchez-le sur le secteur.',
44
44
  'set-na-box-flash': 'Non flashé : sa conversation le flashe (Tether).', 'set-na-box-waiting': 'En attente de sa réponse…',
45
45
  'set-na-box-made': '{name} répond dans {where}',
46
+ /* A mail file (.eml) in the viewer (app.js showMail). */
47
+ 'set-mail-message': 'Message', 'set-mail-source': 'Source', 'set-mail-to': 'À', 'set-mail-cc': 'Cc', 'set-mail-date': 'Date',
48
+ 'set-mail-details': 'Afficher les détails', 'set-mail-hide-details': 'Masquer les détails', 'set-mail-no-subject': '(sans objet)',
49
+ 'set-mail-remote': 'Images distantes bloquées', 'set-mail-show-remote': 'Les afficher', 'set-mail-empty': 'Ce mail n\'a pas de texte.',
50
+ 'set-mail-file': '1 pièce jointe', 'set-mail-files': '{n} pièces jointes', 'set-mail-download': 'Télécharger', 'set-mail-of': 'Pièce jointe de {name}',
46
51
  };
47
52
  export const settingsWords = (lang) => (String(lang ?? '').toLowerCase().split('-')[0] === 'fr' ? { ...SETTINGS_WORDS_FR } : {});
package/web/app.js CHANGED
@@ -9323,8 +9323,11 @@
9323
9323
  }
9324
9324
  /* `tab`, `inner`: its place in a folder kept here. `from`: an address to
9325
9325
  read it at instead (a file of the machine's own disk). */
9326
- async function preview(tab, inner, name, size, from) {
9326
+ /* `opts.own`: a blob address of the page's own (an attachment of a mail), let go with the window; `opts.within`: the mail it came from;
9327
+ `opts.bytes`: its bytes, already read. */
9328
+ async function preview(tab, inner, name, size, from, opts = {}) {
9327
9329
  closePreview();
9330
+ if (opts.own) mdUrls.add(opts.own);
9328
9331
  const address = from ?? `${API}/files/download?${new URLSearchParams({ c: current, r: tab, p: inner })}`;
9329
9332
  $('preview-name').textContent = name;
9330
9333
  $('preview-download').href = address; $('preview-download').setAttribute('download', name);
@@ -9356,7 +9359,7 @@
9356
9359
  $('preview-full').onclick = () => full(!$('viewer').classList.contains('viewer-full'));
9357
9360
  $('preview-attach').onclick = () => void attachToCard({ kind: 'file', ref: tab === 'work' ? `/work/${inner}` : `/resources/${tab}/${inner}`, title: name });
9358
9361
  /* A file read from the machine's disk says so, whatever else is said. */
9359
- const origin = from ? 'Read from the disk of the machine: this file is not kept here, and goes with the machine.' : '';
9362
+ const origin = opts.within ? uiSaid('set-mail-of', 'An attachment of {name}', { name: opts.within }) : from ? 'Read from the disk of the machine: this file is not kept here, and goes with the machine.' : '';
9360
9363
  const note = (text) => { const all = [text, text === 'Loading...' ? '' : origin].filter(Boolean).join(' '); $('preview-note').textContent = all; $('preview-note').hidden = !all; };
9361
9364
  /* NOTHING TO SHOW (02-11): not an empty frame, but a file, why, and a Download button that is seen. */
9362
9365
  const cannot = (why) => {
@@ -9369,6 +9372,13 @@
9369
9372
  box.append(icon, el('b', 'preview-cannot-name', name), el('p', 'hint', why), get);
9370
9373
  $('preview-body').replaceChildren(box); note('');
9371
9374
  };
9375
+ /* Its bytes: read from the server, or already here (an attachment of a mail: this page's rules fetch no blob:). */
9376
+ const readIt = async () => {
9377
+ if (opts.bytes) return opts.bytes.buffer.slice(opts.bytes.byteOffset, opts.bytes.byteOffset + opts.bytes.byteLength);
9378
+ const r = await fetch(address);
9379
+ if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || 'The file could not be read.');
9380
+ return r.arrayBuffer();
9381
+ };
9372
9382
  const kind = name.includes('.') ? name.split('.').pop().toLowerCase() : '';
9373
9383
  if (MEDIA[kind]) {
9374
9384
  const video = MEDIA[kind].startsWith('video/');
@@ -9379,11 +9389,7 @@
9379
9389
  if (size && size > MEDIA_MAX) { player.src = address; $('preview-body').replaceChildren(player); note(''); return; }
9380
9390
  note('Loading...');
9381
9391
  let got;
9382
- try {
9383
- const r = await fetch(address);
9384
- if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || 'The file could not be read.');
9385
- got = await r.arrayBuffer();
9386
- } catch (error) { cannot(error.message); return; }
9392
+ try { got = await readIt(); } catch (error) { cannot(error.message); return; }
9387
9393
  if ($('viewer').hidden || $('preview-name').textContent !== name) return;
9388
9394
  shownUrl = URL.createObjectURL(new Blob([got], { type: MEDIA[kind] }));
9389
9395
  player.src = shownUrl; $('preview-body').replaceChildren(player); note('');
@@ -9391,14 +9397,10 @@
9391
9397
  }
9392
9398
  const known = PICTURES[kind] || kind === 'pdf' || TEXTS.includes(kind) || SHEETS.includes(kind) || kind === 'docx';
9393
9399
  if (!known) { cannot(`${size ? `${sizeOf(size)} · ` : ''}This kind of file cannot be shown here.`); return; }
9394
- if (size > (TEXTS.includes(kind) ? TEXT_MAX : PREVIEW_MAX)) { cannot(`${sizeOf(size)} · Too large to be shown here.`); return; }
9400
+ if (size > (TEXTS.includes(kind) && kind !== 'eml' ? TEXT_MAX : PREVIEW_MAX)) { cannot(`${sizeOf(size)} · Too large to be shown here.`); return; }
9395
9401
  note('Loading...');
9396
9402
  let bytes;
9397
- try {
9398
- const r = await fetch(address);
9399
- if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || 'The file could not be read.');
9400
- bytes = await r.arrayBuffer();
9401
- } catch (error) { cannot(error.message); return; }
9403
+ try { bytes = await readIt(); } catch (error) { cannot(error.message); return; }
9402
9404
  if ($('viewer').hidden || $('preview-name').textContent !== name) return; /* closed meanwhile */
9403
9405
  const body = $('preview-body');
9404
9406
  if (PICTURES[kind]) {
@@ -9464,6 +9466,8 @@
9464
9466
  }
9465
9467
  note(doc.numPages > pages ? `The first ${pages} pages of ${doc.numPages}. Download the file to read the rest.` : `${doc.numPages} page${doc.numPages > 1 ? 's' : ''}.`);
9466
9468
  } catch { cannot('This PDF could not be shown here.'); }
9469
+ } else if (kind === 'eml') {
9470
+ showMail({ bytes, name, tab, inner, from, note });
9467
9471
  } else {
9468
9472
  const text = new TextDecoder('utf-8', { fatal: false }).decode(bytes);
9469
9473
  const source = () => { const pre = document.createElement('pre'); pre.className = 'source'; pre.textContent = text; return pre; };
@@ -9525,6 +9529,95 @@
9525
9529
  } else { body.append(source()); note(offline && (kind === 'html' || kind === 'htm') ? 'This conversation is offline: its page is shown as text, not run.' : ''); }
9526
9530
  }
9527
9531
  }
9532
+ /* A MAIL FILE (.eml), as a mail program shows it (05-11): subject, who, when, its words, its
9533
+ attachments; its source one tap away (Copy, Download, Full screen: the file as it is). Read by
9534
+ web/mail-view.js, here, in the page. Its HTML, which a stranger wrote, is drawn in a frame that
9535
+ runs nothing (sandbox: no scripts, no same-origin; its own rules: nothing fetched), made harmless
9536
+ first; remote pictures blocked till asked for -- then the server's page of it (files.mjs mailPage),
9537
+ still no script. Nothing is fetched on opening. */
9538
+ function showMail({ bytes, name, tab, inner, from, note }) {
9539
+ const body = $('preview-body');
9540
+ const M = window.clavariumMail;
9541
+ /* Its source: the first megabyte of a large one (Download for all of it). */
9542
+ const raw = new TextDecoder('utf-8', { fatal: false }).decode(bytes.byteLength > TEXT_MAX ? bytes.slice(0, TEXT_MAX) : bytes) + (bytes.byteLength > TEXT_MAX ? '\n…' : '');
9543
+ const source = el('pre', 'source', raw);
9544
+ offerCopy({ text: raw }, { select: () => { show('source'); return selectAll(source); } });
9545
+ let mail = null;
9546
+ try { mail = M.parse(new Uint8Array(bytes)); } catch { mail = null; }
9547
+ if (!mail || (!mail.headers.length && mail.html === null && mail.text === null)) { body.append(source); note(''); return; }
9548
+ const view = el('div', 'mail-view');
9549
+ /* Who, to whom, when. */
9550
+ const head = el('div', 'mail-head');
9551
+ head.append(el('h2', 'mail-subject', mail.subject || uiSaid('set-mail-no-subject', '(no subject)')));
9552
+ const who = (list) => { const span = el('span', 'mail-who'); list.forEach((a, i) => { if (i) span.append(', '); if (a.name) { span.append(el('b', '', a.name), ' '); span.append(el('span', 'hint mail-addr', `<${a.address}>`)); } else span.append(el('b', '', a.address)); }); return span; };
9553
+ if (mail.from.length) { const line = el('div', 'mail-from'); line.append(who(mail.from)); head.append(line); }
9554
+ const row = (label, value) => { const line = el('div', 'mail-line'); line.append(el('span', 'mail-label', label), value); head.append(line); };
9555
+ if (mail.to.length) row(uiSaid('set-mail-to', 'To'), who(mail.to));
9556
+ if (mail.cc.length) row(uiSaid('set-mail-cc', 'Cc'), who(mail.cc));
9557
+ if (mail.date) row(uiSaid('set-mail-date', 'Date'), el('span', '', mail.date.toLocaleString(undefined, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })));
9558
+ const details = el('button', 'quiet mail-details', uiSaid('set-mail-details', 'Show details')); details.type = 'button'; details.setAttribute('aria-expanded', 'false');
9559
+ const all = el('pre', 'mail-headers', mail.head); all.hidden = true;
9560
+ details.addEventListener('click', () => { all.hidden = !all.hidden; details.setAttribute('aria-expanded', String(!all.hidden)); details.textContent = all.hidden ? uiSaid('set-mail-details', 'Show details') : uiSaid('set-mail-hide-details', 'Hide details'); });
9561
+ head.append(details, all);
9562
+ view.append(head);
9563
+ /* Its words: the HTML in a frame that runs nothing, or the plain words with their links. */
9564
+ const offline = conversations.find((x) => x.name === current)?.offline === true;
9565
+ const frameOf = () => { const f = document.createElement('iframe'); f.className = 'mail-frame'; f.setAttribute('sandbox', 'allow-popups allow-popups-to-escape-sandbox'); f.setAttribute('referrerpolicy', 'no-referrer'); f.title = mail.subject || name; return f; };
9566
+ if (mail.html !== null) {
9567
+ const page = M.pageOf(mail);
9568
+ let frame = frameOf(); frame.srcdoc = page.html;
9569
+ if (page.blocked) {
9570
+ const bar = el('div', 'mail-remote'); bar.setAttribute('role', 'status');
9571
+ bar.append(el('span', '', uiSaid('set-mail-remote', 'Remote pictures blocked')));
9572
+ /* Shown by the server's page of the same file: one of a folder kept here, a conversation not cut off. */
9573
+ if (!from && !offline) {
9574
+ const go = el('button', 'quiet mail-remote-show', uiSaid('set-mail-show-remote', 'Show them')); go.type = 'button';
9575
+ go.addEventListener('click', () => { const f = frameOf(); f.src = `${API}/files/mail?${new URLSearchParams({ c: current, r: tab, p: inner })}`; frame.replaceWith(f); frame = f; bar.remove(); });
9576
+ bar.append(' · ', go);
9577
+ }
9578
+ view.append(bar);
9579
+ }
9580
+ view.append(frame);
9581
+ } else if (mail.text !== null && mail.text.trim()) {
9582
+ const words = el('div', 'mail-text');
9583
+ for (const piece of M.linkify(mail.text)) {
9584
+ if (!piece.href) { words.append(piece.text); continue; }
9585
+ const a = el('a', '', piece.text); a.href = piece.href; a.target = '_blank'; a.rel = 'noopener noreferrer'; words.append(a);
9586
+ }
9587
+ view.append(words);
9588
+ } else view.append(el('p', 'hint mail-empty', uiSaid('set-mail-empty', 'This mail has no text.')));
9589
+ /* Its attachments: each opens in this same window (or offers its download), as a file of a folder does. */
9590
+ if (mail.attachments.length) {
9591
+ const list = el('ul', 'mail-files');
9592
+ list.setAttribute('aria-label', mail.attachments.length === 1 ? uiSaid('set-mail-file', '1 attachment') : uiSaid('set-mail-files', '{n} attachments', { n: mail.attachments.length }));
9593
+ for (const a of mail.attachments) {
9594
+ const li = el('li', 'mail-file');
9595
+ const open = el('button', 'quiet mail-file-open'); open.type = 'button';
9596
+ const ext = a.name.includes('.') ? a.name.split('.').pop().toUpperCase().slice(0, 4) : '';
9597
+ open.append(el('span', 'kind', ext || '?'), el('b', '', a.name), el('small', '', `${sizeOf(a.size)} · ${a.type}`));
9598
+ open.addEventListener('click', () => { const url = URL.createObjectURL(new Blob([a.bytes], { type: a.type })); void preview(tab, inner, a.name, a.size, url, { own: url, within: name, bytes: a.bytes }); });
9599
+ const get = el('a', 'mail-file-get'); get.setAttribute('download', a.name); get.title = uiSaid('set-mail-download', 'Download'); get.setAttribute('aria-label', `${get.title} ${a.name}`);
9600
+ get.innerHTML = '<svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4v11"/><path d="m7 11 5 5 5-5"/><path d="M5 20h14"/></svg>';
9601
+ /* Its address let go with the window. */
9602
+ { const url = URL.createObjectURL(new Blob([a.bytes], { type: a.type })); mdUrls.add(url); get.href = url; }
9603
+ li.append(open, get); list.append(li);
9604
+ }
9605
+ view.append(list);
9606
+ }
9607
+ /* Message, or its source. */
9608
+ const switcher = el('div', 'md-switch'); switcher.setAttribute('role', 'group'); switcher.setAttribute('aria-label', 'Show');
9609
+ const choice = (label, what) => { const b = el('button', '', label); b.type = 'button'; b.dataset.show = what; b.addEventListener('click', () => show(what)); return b; };
9610
+ const asMail = choice(uiSaid('set-mail-message', 'Message'), 'mail'); const asSource = choice(uiSaid('set-mail-source', 'Source'), 'source');
9611
+ switcher.append(asMail, asSource);
9612
+ function show(what) {
9613
+ asMail.setAttribute('aria-pressed', String(what === 'mail')); asSource.setAttribute('aria-pressed', String(what === 'source'));
9614
+ /* The frame is kept as it is (moved, not made again): hidden, not removed. */
9615
+ if (!view.isConnected) body.replaceChildren(switcher, view, source);
9616
+ view.hidden = what !== 'mail'; source.hidden = what !== 'source';
9617
+ }
9618
+ show('mail');
9619
+ note('');
9620
+ }
9528
9621
  $('preview-close').addEventListener('click', () => leavePreview());
9529
9622
  /* Outside the window, or Escape: closed too -- unless what is edited is not saved. */
9530
9623
  $('viewer').addEventListener('click', (event) => { if (event.target === $('viewer')) leavePreview(); });
package/web/device.html CHANGED
@@ -145,6 +145,7 @@
145
145
  <script src="vendor/fit.js"></script>
146
146
  <script src="device.js"></script>
147
147
  <script src="kit.js"></script>
148
+ <script src="mail-view.js"></script>
148
149
  <script src="app.js"></script>
149
150
  <script type="module" src="voice.js"></script>
150
151
  <script type="module" src="icons.js"></script>
package/web/index.html CHANGED
@@ -1351,6 +1351,7 @@
1351
1351
  <script src="/links.js"></script>
1352
1352
  <script src="/features.js"></script>
1353
1353
  <script src="/kit.js"></script>
1354
+ <script src="/mail-view.js"></script>
1354
1355
  <script src="/app.js"></script>
1355
1356
  <script type="module" src="/voice.js"></script>
1356
1357
  <script type="module" src="/icons.js"></script>
package/web/kit.js CHANGED
@@ -125,12 +125,20 @@
125
125
  const main = node('span', 'kit-conv-main');
126
126
  const head = node('span', 'kit-conv-head');
127
127
  head.append(node('b', '', m.title ?? ''));
128
+ /* A row (05-11, the designers' review): its unread count beside its time, its marks as small words on
129
+ the line below, beside its last words -- one line less than pills. */
130
+ const counts = size === 'row' ? (m.chips ?? []).filter((c) => c && !c.wide && c.tone === 'count') : [];
131
+ const countChips = Chips(counts);
132
+ if (countChips) head.append(countChips);
128
133
  if (m.when) head.append(node('small', 'when', m.when));
129
134
  main.append(head);
130
135
  const lines = [];
131
136
  if (size === 'row') {
132
- if (m.last) lines.push(node('small', 'last', m.last));
133
- if (m.now) lines.push(node('small', 'kit-conv-now', m.now));
137
+ const marks = Chips((m.chips ?? []).filter((c) => c && !c.wide && c.tone !== 'count'));
138
+ const sub = [m.last ? node('small', 'last', m.last) : null, m.now ? node('small', 'kit-conv-now', m.now) : null].filter(Boolean);
139
+ if (marks && sub.length) { const line = node('span', 'kit-conv-sub'); line.append(sub[0], marks); lines.push(line, ...sub.slice(1)); }
140
+ else if (marks) lines.push(marks);
141
+ else lines.push(...sub);
134
142
  } else if (size === 'card') {
135
143
  if (m.last) lines.push(node('small', 'last', m.last));
136
144
  const what = [m.now, m.who].filter(Boolean).join(' · ');
@@ -141,7 +149,7 @@
141
149
  }
142
150
  main.append(...lines);
143
151
  /* Its chips by place: all on a card; a row leaves out the wide ones; a member only what waits for you. */
144
- const chips = Chips((m.chips ?? []).filter((c) => c && (size === 'card' || (size === 'row' ? !c.wide : c.tone === 'need' || c.tone === 'count'))));
152
+ const chips = size === 'row' ? null : Chips((m.chips ?? []).filter((c) => c && (size === 'card' || c.tone === 'need' || c.tone === 'count')));
145
153
  if (chips) main.append(chips);
146
154
  root.append(main);
147
155
  if (actions.length) { const acts = node('span', 'kit-conv-acts'); acts.append(...actions.filter(Boolean)); root.append(acts); }
@@ -0,0 +1,386 @@
1
+ /* A MAIL FILE (.eml), read as a mail program shows it (05-11): its subject, who wrote to whom and when,
2
+ * its words, its attachments -- and its source one tap away.
3
+ *
4
+ * parse(bytes) RFC 822 / MIME: headers (RFC 2047 words, RFC 2231 names), multipart
5
+ * alternative / mixed / related, quoted-printable, base64, charsets.
6
+ * sanitize(html, opts) the HTML of a mail, which a stranger wrote: kept are the tags and the
7
+ * attributes that draw a page, nothing that runs, submits or frames;
8
+ * remote pictures and styles blocked unless `remote`; `cid:` pictures
9
+ * drawn from the mail itself.
10
+ * pageOf(mail, opts) the document the viewer's frame shows (srcdoc), its own rules in it.
11
+ * linkify(text) plain words cut into text and links (http, https, mailto), for the page to draw.
12
+ *
13
+ * Pure: no DOM, no network. The page (app.js) draws it in a frame that runs nothing (sandbox without
14
+ * scripts or same-origin); the server (files.mjs) uses the same code when remote pictures are asked for.
15
+ * Loaded as a classic script (index.html, device.html): window.clavariumMail. */
16
+ (function (root) {
17
+ /* ---------- bytes and words ---------- */
18
+ const latin = (bytes) => {
19
+ let s = '';
20
+ for (let i = 0; i < bytes.length; i += 8192) s += String.fromCharCode.apply(null, bytes.subarray(i, i + 8192));
21
+ return s;
22
+ };
23
+ const bytesOf = (binary) => { const b = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) b[i] = binary.charCodeAt(i) & 255; return b; };
24
+ const ALIASES = { 'utf8': 'utf-8', 'latin1': 'iso-8859-1', 'latin-1': 'iso-8859-1', 'cp1252': 'windows-1252', 'us-ascii': 'utf-8', 'ascii': 'utf-8', 'ansi_x3.4-1968': 'utf-8', 'unknown-8bit': 'windows-1252', 'x-unknown': 'windows-1252' };
25
+ /* Bytes in a charset; one a browser does not know is read as UTF-8, and failing that as Windows-1252. */
26
+ function decode(bytes, charset) {
27
+ let label = String(charset || 'utf-8').trim().toLowerCase().replace(/^["']|["']$/g, '');
28
+ label = ALIASES[label] || label;
29
+ try { return new TextDecoder(label, { fatal: label === 'utf-8' }).decode(bytes); } catch { /* unknown, or not UTF-8 after all */ }
30
+ try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { /* 8-bit */ }
31
+ try { return new TextDecoder('windows-1252').decode(bytes); } catch { return latin(bytes); }
32
+ }
33
+ function fromBase64(text) {
34
+ const clean = String(text).replace(/[^A-Za-z0-9+/]/g, '');
35
+ const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
36
+ const at = (c) => { const n = c.charCodeAt(0); return n >= 97 ? n - 71 : n >= 65 ? n - 65 : n >= 48 ? n + 4 : n === 43 ? 62 : 63; };
37
+ let o = 0;
38
+ for (let i = 0; i + 1 < clean.length; i += 4) {
39
+ const a = at(clean[i]); const b = at(clean[i + 1]); const c = i + 2 < clean.length ? at(clean[i + 2]) : -1; const d = i + 3 < clean.length ? at(clean[i + 3]) : -1;
40
+ out[o++] = (a << 2) | (b >> 4);
41
+ if (c >= 0) out[o++] = ((b & 15) << 4) | (c >> 2);
42
+ if (d >= 0) out[o++] = ((c & 3) << 6) | d;
43
+ }
44
+ return out.subarray(0, o);
45
+ }
46
+ const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
47
+ function toBase64(bytes) {
48
+ let s = '';
49
+ for (let i = 0; i < bytes.length; i += 3) {
50
+ const n = (bytes[i] << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);
51
+ s += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + (i + 1 < bytes.length ? B64[(n >> 6) & 63] : '=') + (i + 2 < bytes.length ? B64[n & 63] : '=');
52
+ }
53
+ return s;
54
+ }
55
+ /* Quoted-printable, on the binary string: "=XX" a byte, "=" at a line's end a soft break. */
56
+ function fromQuotedPrintable(binary, header = false) {
57
+ let s = String(binary).replace(/[ \t]+(\r?\n)/g, '$1').replace(/=\r?\n/g, '');
58
+ if (header) s = s.replace(/_/g, ' ');
59
+ const out = [];
60
+ for (let i = 0; i < s.length; i++) {
61
+ if (s[i] === '=' && /^[0-9A-Fa-f]{2}$/.test(s.slice(i + 1, i + 3))) { out.push(parseInt(s.slice(i + 1, i + 3), 16)); i += 2; } else out.push(s.charCodeAt(i) & 255);
62
+ }
63
+ return Uint8Array.from(out);
64
+ }
65
+ /* RFC 2047: "=?UTF-8?Q?caf=C3=A9?=" -- words side by side are one; the rest, 8-bit, read as UTF-8. */
66
+ function words(value) {
67
+ const raw = String(value ?? '');
68
+ const re = /=\?([^?\s]+)\?([QqBb])\?([^?\s]*)\?=/g;
69
+ let out = ''; let last = 0; let wasWord = false; let m;
70
+ while ((m = re.exec(raw))) {
71
+ const between = raw.slice(last, m.index);
72
+ if (!(wasWord && /^\s*$/.test(between))) out += decode(bytesOf(between), 'utf-8');
73
+ const charset = m[1].split('*')[0];
74
+ const bytes = m[2].toUpperCase() === 'B' ? fromBase64(m[3]) : fromQuotedPrintable(m[3], true);
75
+ out += decode(bytes, charset);
76
+ last = re.lastIndex; wasWord = true;
77
+ }
78
+ out += decode(bytesOf(raw.slice(last)), 'utf-8');
79
+ return out;
80
+ }
81
+
82
+ /* ---------- an entity: its headers, its body ---------- */
83
+ function split(binary) {
84
+ const m = /\r?\n\r?\n/.exec(binary);
85
+ const head = m ? binary.slice(0, m.index) : binary;
86
+ const body = m ? binary.slice(m.index + m[0].length) : '';
87
+ /* A message that starts with its body (no header at all) has no "name:" first. */
88
+ if (!/^[!-9;-~]+:/.test(head)) return { head: '', body: binary, headers: [] };
89
+ const headers = [];
90
+ for (const line of head.split(/\r?\n/)) {
91
+ if (/^[ \t]/.test(line) && headers.length) headers[headers.length - 1][1] += ` ${line.trim()}`;
92
+ else { const at = line.indexOf(':'); if (at > 0) headers.push([line.slice(0, at).trim(), line.slice(at + 1).trim()]); }
93
+ }
94
+ return { head, body, headers };
95
+ }
96
+ const first = (headers, name) => { const h = headers.find(([k]) => k.toLowerCase() === name); return h ? h[1] : ''; };
97
+ /* "text/html; charset=\"utf-8\"; name*=utf-8''r%C3%A9sum%C3%A9.pdf" -> { value, params } (RFC 2231 names and pieces). */
98
+ function params(value) {
99
+ const parts = []; let cur = ''; let quoted = false;
100
+ for (const ch of String(value ?? '')) {
101
+ if (ch === '"') quoted = !quoted;
102
+ if (ch === ';' && !quoted) { parts.push(cur); cur = ''; } else cur += ch;
103
+ }
104
+ parts.push(cur);
105
+ const out = {}; const pieces = {};
106
+ for (const p of parts.slice(1)) {
107
+ const at = p.indexOf('='); if (at < 0) continue;
108
+ const key = p.slice(0, at).trim().toLowerCase();
109
+ let val = p.slice(at + 1).trim();
110
+ if (val.startsWith('"')) val = val.replace(/^"|"$/g, '').replace(/\\(.)/g, '$1');
111
+ const piece = /^([^*]+)\*(\d+)?(\*)?$/.exec(key);
112
+ if (piece) { (pieces[piece[1]] ??= []).push({ n: Number(piece[2] ?? 0), val, enc: Boolean(piece[3]) || (piece[2] === undefined) }); } else out[key] = val;
113
+ }
114
+ for (const [key, list] of Object.entries(pieces)) {
115
+ list.sort((a, b) => a.n - b.n);
116
+ let charset = 'utf-8'; let bin = '';
117
+ list.forEach((p, i) => {
118
+ let v = p.val;
119
+ if (p.enc && i === 0) { const m = /^([^']*)'[^']*'(.*)$/.exec(v); if (m) { charset = m[1] || charset; v = m[2]; } }
120
+ bin += p.enc ? v.replace(/%([0-9A-Fa-f]{2})/g, (a, h) => String.fromCharCode(parseInt(h, 16))) : v;
121
+ });
122
+ out[key] = decode(bytesOf(bin), charset);
123
+ }
124
+ for (const k of Object.keys(out)) if (!(k in pieces)) out[k] = words(out[k]);
125
+ return { value: parts[0].trim().toLowerCase(), params: out };
126
+ }
127
+ function bodyBytes(binary, encoding) {
128
+ const e = String(encoding || '').trim().toLowerCase();
129
+ if (e === 'base64') return fromBase64(binary);
130
+ if (e === 'quoted-printable') return fromQuotedPrintable(binary);
131
+ return bytesOf(binary);
132
+ }
133
+ function entity(binary, depth = 0, parentType = '') {
134
+ const { head, body, headers } = split(binary);
135
+ const ct = params(first(headers, 'content-type') || (parentType === 'multipart/digest' ? 'message/rfc822' : 'text/plain; charset=us-ascii'));
136
+ const cd = params(first(headers, 'content-disposition'));
137
+ const node = {
138
+ head, headers, type: ct.value || 'text/plain', params: ct.params,
139
+ disposition: cd.value, filename: cd.params.filename || ct.params.name || '',
140
+ cid: first(headers, 'content-id').replace(/^\s*<|>\s*$/g, ''),
141
+ encoding: first(headers, 'content-transfer-encoding'), raw: body, parts: [],
142
+ };
143
+ const boundary = ct.params.boundary;
144
+ if (node.type.startsWith('multipart/') && boundary && depth < 20) {
145
+ const mark = `--${boundary}`;
146
+ const lines = body.split(/\r?\n/);
147
+ let cur = null;
148
+ for (const line of lines) {
149
+ const t = line.replace(/[ \t]+$/, '');
150
+ if (t === mark || t === `${mark}--`) {
151
+ if (cur) node.parts.push(entity(cur.join('\r\n'), depth + 1, node.type));
152
+ cur = t === mark ? [] : null;
153
+ if (t !== mark) break;
154
+ } else if (cur) cur.push(line);
155
+ }
156
+ if (cur && cur.length) node.parts.push(entity(cur.join('\r\n'), depth + 1, node.type));
157
+ }
158
+ return node;
159
+ }
160
+ const contentOf = (node) => bodyBytes(node.raw, node.encoding);
161
+ const textOf = (node) => decode(contentOf(node), node.params.charset);
162
+
163
+ /* "Ann Example <ann@example.com>, \"Doe, Bo\" <bo@example.org>" -> [{ name, address }]. */
164
+ function addresses(value) {
165
+ const text = words(value);
166
+ const out = []; let cur = ''; let quoted = false; let angle = false;
167
+ for (const ch of text) {
168
+ if (ch === '"') quoted = !quoted;
169
+ else if (ch === '<' && !quoted) angle = true;
170
+ else if (ch === '>' && !quoted) angle = false;
171
+ if (ch === ',' && !quoted && !angle) { out.push(cur); cur = ''; } else cur += ch;
172
+ }
173
+ out.push(cur);
174
+ return out.map((one) => {
175
+ const m = /^(.*?)<([^>]*)>\s*$/.exec(one.trim());
176
+ if (m) return { name: m[1].trim().replace(/^"|"$/g, '').replace(/\\(.)/g, '$1').trim(), address: m[2].trim() };
177
+ const bare = one.trim().replace(/\s*\(([^)]*)\)\s*$/, '');
178
+ const note = /\(([^)]*)\)\s*$/.exec(one.trim());
179
+ return { name: note ? note[1].trim() : '', address: bare };
180
+ }).filter((a) => a.address || a.name);
181
+ }
182
+
183
+ /* ---------- the mail ---------- */
184
+ function parse(input) {
185
+ const bytes = input instanceof Uint8Array ? input : new Uint8Array(input ?? []);
186
+ const top = entity(latin(bytes));
187
+ const mail = {
188
+ headers: top.headers.map(([k, v]) => [k, words(v)]), head: top.head,
189
+ subject: words(first(top.headers, 'subject')).trim(),
190
+ from: addresses(first(top.headers, 'from')), to: addresses(first(top.headers, 'to')), cc: addresses(first(top.headers, 'cc')),
191
+ replyTo: addresses(first(top.headers, 'reply-to')),
192
+ date: null, html: null, text: null, attachments: [], cids: {},
193
+ };
194
+ const d = Date.parse(first(top.headers, 'date').replace(/\s*\([^)]*\)\s*$/, ''));
195
+ mail.date = Number.isNaN(d) ? null : new Date(d);
196
+ const attach = (node, inline) => {
197
+ const content = contentOf(node);
198
+ let name = node.filename;
199
+ if (!name && node.type === 'message/rfc822') name = `${(words(first(split(node.raw).headers, 'subject')).trim() || 'message').replace(/[\\/:*?"<>|\u0000-\u001f]+/g, ' ').slice(0, 80)}.eml`;
200
+ if (!name) name = `part-${mail.attachments.length + 1}${EXT[node.type] ?? ''}`;
201
+ const one = { name: name.replace(/[\\/]+/g, '_'), type: node.type, size: content.length, bytes: content, cid: node.cid, inline: Boolean(inline) };
202
+ mail.attachments.push(one);
203
+ return one;
204
+ };
205
+ const isAttachment = (node) => node.disposition === 'attachment' || (Boolean(node.filename) && !/^text\/(plain|html)$/.test(node.type));
206
+ const hasHtml = (node) => node.type === 'text/html' || node.parts.some(hasHtml);
207
+ /* `body`: may this part be the mail's words, or only beside them. */
208
+ const walk = (node, body) => {
209
+ if (node.type === 'multipart/alternative') {
210
+ const best = [...node.parts].reverse().find((p) => hasHtml(p) && !isAttachment(p)) ?? [...node.parts].reverse().find((p) => p.type === 'text/plain') ?? node.parts[0];
211
+ if (best) walk(best, body);
212
+ return;
213
+ }
214
+ if (node.type === 'multipart/related') {
215
+ const start = node.params.start ? node.params.start.replace(/^<|>$/g, '') : '';
216
+ const main = node.parts.find((p) => start && p.cid === start) ?? node.parts[0];
217
+ for (const p of node.parts) {
218
+ if (p === main) continue;
219
+ if (p.cid && p.parts.length === 0) { const one = attach(p, true); mail.cids[p.cid] = one; } else walk(p, false);
220
+ }
221
+ if (main) walk(main, body);
222
+ return;
223
+ }
224
+ if (node.type.startsWith('multipart/')) { for (const p of node.parts) walk(p, body); return; }
225
+ if (!isAttachment(node) && (node.type === 'text/html' || node.type === 'text/plain') && body && mail.html === null && mail.text === null) {
226
+ if (node.type === 'text/html') mail.html = textOf(node); else mail.text = textOf(node);
227
+ return;
228
+ }
229
+ const one = attach(node, false);
230
+ if (node.cid && node.type.startsWith('image/')) mail.cids[node.cid] = one;
231
+ };
232
+ walk(top, true);
233
+ /* A picture of the page drawn in it is not one more attachment; one it never shows is. */
234
+ if (mail.html !== null) {
235
+ const used = new Set([...mail.html.matchAll(/cid:([^"'\s)>]+)/gi)].map((m) => decodeURIComponentSafe(m[1])));
236
+ mail.attachments = mail.attachments.filter((a) => !(a.cid && used.has(a.cid)));
237
+ }
238
+ for (const a of mail.attachments) delete a.inline;
239
+ return mail;
240
+ }
241
+ const decodeURIComponentSafe = (s) => { try { return decodeURIComponent(s); } catch { return s; } };
242
+ const EXT = { 'text/plain': '.txt', 'text/html': '.html', 'image/png': '.png', 'image/jpeg': '.jpg', 'image/gif': '.gif', 'application/pdf': '.pdf', 'text/calendar': '.ics' };
243
+
244
+ /* ---------- its HTML, made harmless ---------- */
245
+ /* Tags kept (the page they draw); any other tag is dropped, its words kept. */
246
+ const KEEP = new Set(('a abbr address article aside b bdi bdo big blockquote br caption center cite code col colgroup dd del details dfn div dl dt em '
247
+ + 'figcaption figure font footer h1 h2 h3 h4 h5 h6 header hr i img ins kbd li main mark nav ol p pre q s samp section small span strike strong '
248
+ + 'style sub summary sup table tbody td tfoot th thead tr tt u ul var wbr').split(' '));
249
+ /* Dropped with all that is in them. */
250
+ const DROP = new Set('script noscript template iframe frame frameset object embed applet svg math title select textarea option button audio video canvas map xml'.split(' '));
251
+ const RAW = new Set(['script', 'style', 'textarea', 'title', 'xmp', 'iframe', 'noembed', 'noframes', 'noscript', 'plaintext']);
252
+ const VOID = new Set(['br', 'hr', 'img', 'col', 'wbr', 'area', 'base', 'link', 'meta', 'input', 'source', 'track', 'param', 'embed', 'keygen']);
253
+ const ATTRS = new Set(('href src alt title width height style class id align valign bgcolor color face size border cellpadding cellspacing colspan rowspan '
254
+ + 'dir lang start type span background nowrap hspace vspace summary scope headers abbr reversed open cite datetime').split(' '));
255
+ const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: '\u00a0', colon: ':', tab: '\t', newline: '\n', lpar: '(', rpar: ')', sol: '/', bsol: '\\', period: '.', comma: ',' };
256
+ const unescape = (s) => String(s).replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);?/gi, (all, e) => {
257
+ if (e[0] === '#') { const n = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10); return n > 0 && n < 0x110000 ? String.fromCodePoint(n) : ''; }
258
+ return ENTITIES[e.toLowerCase()] ?? all;
259
+ });
260
+ const escape = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
261
+ const SAFE_LINK = /^(https?:|mailto:|tel:|#)/i;
262
+ const REMOTE = /^(https?:)?\/\//i;
263
+ /* An address as a browser reads it: no blanks or controls anywhere in it ("java\tscript:"). */
264
+ const squeezed = (v) => unescape(v).replace(/[\u0000-\u0020\u007f-\u00a0\u00ad\u200b-\u200f\u2028\u2029\ufeff]+/g, '');
265
+ function sanitize(html, opts = {}) {
266
+ const remote = Boolean(opts.remote); const cids = opts.cids || {};
267
+ let blocked = 0;
268
+ const picture = (value) => {
269
+ const v = squeezed(value);
270
+ if (/^cid:/i.test(v)) { const one = cids[decodeURIComponentSafe(v.slice(4))]; return one && /^image\//.test(one.type) ? `data:${one.type};base64,${toBase64(one.bytes)}` : null; }
271
+ if (/^data:image\/(png|jpe?g|gif|webp|bmp);base64,[a-z0-9+/=\s]*$/i.test(v)) return v;
272
+ if (REMOTE.test(v)) { if (remote) return v.startsWith('//') ? `https:${v}` : v; blocked++; return null; }
273
+ return null;
274
+ };
275
+ /* CSS: nothing that runs or binds, no @import; a url() kept only as a picture is. */
276
+ const cssOnce = (text) => unescape(String(text)).replace(/\\/g, '')
277
+ .replace(/expression\s*\(|behaviou?r\s*:|-moz-binding|javascript:|vbscript:/gi, 'x-')
278
+ .replace(/@import[^;]*;?/gi, '')
279
+ .replace(/url\(\s*(['"]?)(.*?)\1\s*\)/gi, (all, q, v) => { const p = picture(v); return p ? `url("${p.replace(/"/g, '%22')}")` : 'none'; })
280
+ ;
281
+ const css = (text) => { let t = cssOnce(text); for (let n = 0; n < 5 && /<\/?\s*style/i.test(t); n++) t = t.replace(/<\/?\s*style/gi, ''); return t.replace(/<\/?\s*style/gi, '').replace(/</g, ' '); };
282
+ let out = ''; let i = 0; const s = String(html ?? '');
283
+ let skip = null; let depth = 0; let bodyOpen = false;
284
+ while (i < s.length) {
285
+ const lt = s.indexOf('<', i);
286
+ if (lt < 0) { if (!skip) out += textOut(s.slice(i)); break; }
287
+ if (!skip) out += textOut(s.slice(i, lt));
288
+ i = lt;
289
+ if (s.startsWith('<!--', i)) { const end = s.indexOf('-->', i + 4); i = end < 0 ? s.length : end + 3; continue; }
290
+ if (s[i + 1] === '!' || s[i + 1] === '?') { const end = s.indexOf('>', i); i = end < 0 ? s.length : end + 1; continue; }
291
+ const closing = s[i + 1] === '/';
292
+ const nm = /^[a-zA-Z][a-zA-Z0-9:-]*/.exec(s.slice(i + (closing ? 2 : 1), i + 80));
293
+ if (!nm) { if (!skip) out += '&lt;'; i += 1; continue; }
294
+ const name = nm[0].toLowerCase();
295
+ /* The attributes, quotes kept whole ("a>b" inside one does not end the tag). */
296
+ let j = i + (closing ? 2 : 1) + nm[0].length; const attrs = [];
297
+ while (j < s.length && s[j] !== '>') {
298
+ if (/[\s/]/.test(s[j])) { j++; continue; }
299
+ const an = /^[^\s/>=]+/.exec(s.slice(j)); if (!an) { j++; continue; }
300
+ j += an[0].length;
301
+ let k = j; while (/\s/.test(s[k] ?? '')) k++;
302
+ let value = '';
303
+ if (s[k] === '=') {
304
+ k++; while (/\s/.test(s[k] ?? '')) k++;
305
+ if (s[k] === '"' || s[k] === "'") { const end = s.indexOf(s[k], k + 1); value = s.slice(k + 1, end < 0 ? s.length : end); j = end < 0 ? s.length : end + 1; } else { const v = /^[^\s>]*/.exec(s.slice(k))[0]; value = v; j = k + v.length; }
306
+ }
307
+ attrs.push([an[0].toLowerCase(), value]);
308
+ }
309
+ i = j + 1;
310
+ if (skip) {
311
+ if (name === skip) { if (closing) { depth--; if (depth === 0) skip = null; } else if (!RAW.has(name)) depth++; }
312
+ continue;
313
+ }
314
+ if (RAW.has(name) && !closing && name !== 'style' && !KEEP.has(name)) {
315
+ /* Raw text (a script's, a textarea's): to its own end tag, nothing in it read as markup. */
316
+ const end = s.toLowerCase().indexOf(`</${name}`, i);
317
+ i = end < 0 ? s.length : (s.indexOf('>', end) < 0 ? s.length : s.indexOf('>', end) + 1);
318
+ continue;
319
+ }
320
+ if (name === 'style' && !closing) {
321
+ const end = s.toLowerCase().indexOf('</style', i);
322
+ const content = s.slice(i, end < 0 ? s.length : end);
323
+ i = end < 0 ? s.length : (s.indexOf('>', end) < 0 ? s.length : s.indexOf('>', end) + 1);
324
+ out += `<style>${css(content)}</style>`;
325
+ continue;
326
+ }
327
+ if (DROP.has(name)) { if (!closing && !VOID.has(name)) { skip = name; depth = 1; } continue; }
328
+ if (name === 'body' && !closing) {
329
+ /* The body's colour and its background colour, kept on a box of their own. */
330
+ const bg = attrs.find(([k]) => k === 'bgcolor'); const st = attrs.find(([k]) => k === 'style');
331
+ const style = [bg && /^#?[\w]+$/.test(bg[1]) ? `background-color:${bg[1]}` : '', st ? css(st[1]) : ''].filter(Boolean).join(';');
332
+ out += `<div class="mail-body"${style ? ` style="${escape(style)}"` : ''}>`; bodyOpen = true; continue;
333
+ }
334
+ if (name === 'body' && closing) { if (bodyOpen) { out += '</div>'; bodyOpen = false; } continue; }
335
+ if (!KEEP.has(name)) continue;
336
+ if (closing) { if (!VOID.has(name)) out += `</${name}>`; continue; }
337
+ let tag = `<${name}`;
338
+ for (const [k, raw] of attrs) {
339
+ if (k.startsWith('on') || !ATTRS.has(k)) continue;
340
+ let v = raw;
341
+ if (k === 'href') { const u = squeezed(v); if (!SAFE_LINK.test(u)) continue; v = u; }
342
+ else if (k === 'src') { if (name !== 'img') continue; const p = picture(v); if (!p) { tag += ' data-blocked=""'; continue; } v = p; }
343
+ else if (k === 'background') { const p = picture(v); if (!p) continue; v = p; }
344
+ else if (k === 'style') v = css(v);
345
+ else if (k === 'cite') continue;
346
+ else v = unescape(v);
347
+ tag += ` ${k}="${escape(v)}"`;
348
+ }
349
+ if (name === 'a') tag += ' target="_blank" rel="noopener noreferrer"';
350
+ out += `${tag}>`;
351
+ }
352
+ if (bodyOpen) out += '</div>';
353
+ return { html: out, blocked };
354
+ function textOut(t) { return t.replace(/</g, '&lt;').replace(/>/g, '&gt;'); }
355
+ }
356
+
357
+ /* The frame's document: its own rules first (no script, nothing fetched but what `remote` allows),
358
+ links to a new tab; a mail is drawn on white as it was written for, whatever the page's theme. */
359
+ function pageOf(mail, opts = {}) {
360
+ const { html, blocked } = sanitize(mail.html ?? '', { remote: opts.remote, cids: mail.cids });
361
+ const img = opts.remote ? "data: https: http:" : 'data:';
362
+ const rules = `default-src 'none'; img-src ${img}; style-src 'unsafe-inline'; font-src data:; form-action 'none'; base-uri 'none'`;
363
+ const doc = `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${rules}">`
364
+ + '<meta name="referrer" content="no-referrer"><base target="_blank">'
365
+ + '<style>html{background:#fff;color:#17202b}body{margin:0;padding:16px;font:15px/1.5 system-ui,sans-serif;overflow-wrap:anywhere}img{max-width:100%;height:auto}img[data-blocked]{display:none}pre{white-space:pre-wrap}</style>'
366
+ + `</head><body>${html}</body></html>`;
367
+ return { html: doc, blocked };
368
+ }
369
+
370
+ /* Words and links, for the page to draw as text and <a> (never as markup). */
371
+ function linkify(text) {
372
+ const out = []; const re = /\b(https?:\/\/[^\s<>"']+|mailto:[^\s<>"']+|[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})/g;
373
+ let last = 0; let m;
374
+ const t = String(text ?? '');
375
+ while ((m = re.exec(t))) {
376
+ let link = m[0]; const trail = /[.,;:!?)\]]+$/.exec(link); if (trail) link = link.slice(0, -trail[0].length);
377
+ if (m.index > last) out.push({ text: t.slice(last, m.index) });
378
+ out.push({ text: link, href: /^(https?|mailto):/i.test(link) ? link : `mailto:${link}` });
379
+ last = m.index + link.length; re.lastIndex = last;
380
+ }
381
+ if (last < t.length) out.push({ text: t.slice(last) });
382
+ return out;
383
+ }
384
+
385
+ root.clavariumMail = { parse, sanitize, pageOf, linkify, words, decode, addresses };
386
+ })(typeof window !== 'undefined' ? window : globalThis);
package/web/style.css CHANGED
@@ -2253,6 +2253,31 @@ body.as-dragging #assets-rows .as-row { touch-action: none; }
2253
2253
  .sheet-table thead th { top: 0; z-index: 1; } .sheet-table tbody th { left: 0; }
2254
2254
  .doc-frame { width: 100%; min-height: 70vh; border: 0; border-radius: 8px; background: transparent; }
2255
2255
 
2256
+ /* A MAIL FILE (.eml), as a mail program shows it (app.js showMail): its head, its words, its attachments. */
2257
+ .mail-view { display: flex; flex-direction: column; gap: 10px; min-width: 0; }
2258
+ .mail-head { display: flex; flex-direction: column; gap: 4px; padding: 4px 2px 10px; border-bottom: 1px solid var(--line); min-width: 0; }
2259
+ .mail-subject { margin: 0 0 4px; font-size: 1.25rem; line-height: 1.3; color: var(--ink); overflow-wrap: anywhere; }
2260
+ .mail-from, .mail-line { font-size: .875rem; color: var(--ink); overflow-wrap: anywhere; }
2261
+ .mail-line { display: flex; gap: 8px; }
2262
+ .mail-label { flex: 0 0 3.2em; color: var(--ink2); }
2263
+ .mail-addr { font-size: .8125rem; }
2264
+ #viewer .mail-details { align-self: flex-start; min-height: 32px; padding: 0 2px; border: 0; font-size: .8125rem; text-decoration: underline; }
2265
+ #preview-body pre.mail-headers { padding: 8px; background: var(--bg); border: 1px solid var(--line); border-radius: 6px; font-size: .75rem; max-height: 40vh; overflow: auto; }
2266
+ .mail-remote { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; padding: 4px 10px; font-size: .8125rem; color: var(--ink2); background: var(--bar); border: 1px solid var(--line); border-radius: 6px; }
2267
+ #viewer .mail-remote-show { min-height: 32px; padding: 0 4px; border: 0; color: var(--brass-ink); font-weight: 600; text-decoration: underline; }
2268
+ #preview-body iframe.mail-frame { flex: 0 0 auto; height: min(70vh, 900px); border: 1px solid var(--line); }
2269
+ .mail-text { white-space: pre-wrap; overflow-wrap: anywhere; font-size: .9375rem; line-height: 1.5; color: var(--ink); padding: 4px 2px; }
2270
+ .mail-text a { color: var(--brass-ink); }
2271
+ .mail-files { list-style: none; margin: 0; padding: 8px 0 0; border-top: 1px solid var(--line); display: flex; flex-wrap: wrap; gap: 6px; }
2272
+ .mail-file { display: flex; align-items: stretch; min-width: 0; max-width: 100%; border: 1px solid var(--line); border-radius: 8px; }
2273
+ #viewer .mail-file-open { display: flex; align-items: center; gap: 8px; min-width: 0; padding: 4px 10px; border: 0; color: var(--ink); text-align: left; }
2274
+ .mail-file-open b { font-weight: 600; font-size: .8125rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
2275
+ .mail-file-open small { color: var(--ink2); font-size: .75rem; white-space: nowrap; }
2276
+ .mail-file-open .kind { flex: 0 0 34px; font-size: .6875rem; font-weight: 600; text-align: center; padding: 3px 0; border: 1px solid var(--line); border-radius: 5px; color: var(--ink2); }
2277
+ .mail-file-get { display: flex; align-items: center; justify-content: center; width: 40px; border-left: 1px solid var(--line); color: var(--ink2); }
2278
+ .mail-file-get .ic { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
2279
+ @media (max-width: 560px) { .mail-file-open small { display: none; } .mail-file { flex: 1 1 100%; } }
2280
+
2256
2281
  /* THE CONVERSATIONS AS CARDS (02-11): playing cards, one per conversation, and one to add. */
2257
2282
  #list-title { cursor: pointer; }
2258
2283
  #deck { overflow-y: auto; }
@@ -2706,3 +2731,13 @@ button.kit-switch[aria-checked="true"]::after { left: 18px; background: var(--ok
2706
2731
  .kit-conv-member .kit-conv-main > small { font-size: .75rem; }
2707
2732
  .salon-host-box > .kit-conv-member { flex: 1; padding: 0; --kc-ring: color-mix(in srgb, var(--brass) 10%, var(--panel)); }
2708
2733
  @media (max-width: 520px) { .kit-conv-card { --kc-av: 30px; column-gap: 8px; padding: 10px; } }
2734
+
2735
+ /* THE ROW, compact (05-11, designers' review): a smaller initial, a bigger ringed point, the marks as small
2736
+ coloured words beside the last words (not pills), the unread count beside the time. */
2737
+ .kit-conv-row { --kc-av: 24px; padding: 6px 10px; }
2738
+ .kit-conv-row > .state-dot { width: 10px; height: 10px; margin: calc(var(--kc-av) - 8px) -4px 0 0; box-shadow: 0 0 0 2px var(--kc-ring); }
2739
+ .kit-conv-row .kit-conv-head > .kit-chips { flex: none; margin: 0; }
2740
+ .kit-conv-sub { display: flex; align-items: baseline; gap: 6px; min-width: 0; }
2741
+ .kit-conv-sub > small { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--ink2); }
2742
+ .kit-conv-row .kit-conv-main > .kit-chips, .kit-conv-sub > .kit-chips { flex: none; margin: 0; gap: 6px; flex-wrap: nowrap; }
2743
+ .kit-conv-row .kit-conv-main .kit-chip:not([data-tone="count"]) { border: 0; padding: 0; background: none; line-height: inherit; font-size: .75rem; }