clavarium 0.2.159-beta.1 → 0.2.160-beta.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,19 +1,19 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.159-beta.1",
3
+ "version": "0.2.160-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.159-beta.1",
9
+ "version": "0.2.160-beta.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
13
13
  "@xterm/xterm": "^6.0.0",
14
14
  "clavarium-binder": "0.1.60-next.1",
15
15
  "clavarium-docket": "0.1.2-next.2",
16
- "clavarium-parley": "0.17.67-next.1",
16
+ "clavarium-parley": "0.17.68-next.1",
17
17
  "clavarium-tether": "0.1.0-next.49",
18
18
  "mammoth": "1.13.0",
19
19
  "mermaid": "11.17.2",
@@ -787,9 +787,9 @@
787
787
  }
788
788
  },
789
789
  "node_modules/clavarium-parley": {
790
- "version": "0.17.67-next.1",
791
- "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.67-next.1.tgz",
792
- "integrity": "sha512-6dQaElIA0BJi8ruT6uS8k+eRstjnBqVbwKLWZxsJwH6PVtr1CVQ7/9KzUuKabc5+PN+v8oBFFE8iZh4HHYq3qQ==",
790
+ "version": "0.17.68-next.1",
791
+ "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.68-next.1.tgz",
792
+ "integrity": "sha512-KnnRFm0Qd1ckzqkf2NdzQEVewblOyLYPmwAwhM99uRHGLDNgPN4Rpm+YDC8d6TWbL+pBFoSX8WORr9G27FYbgw==",
793
793
  "license": "MIT",
794
794
  "bin": {
795
795
  "parley": "bin/parley.mjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.159-beta.1",
3
+ "version": "0.2.160-beta.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.",
@@ -46,7 +46,7 @@
46
46
  "@xterm/xterm": "^6.0.0",
47
47
  "clavarium-binder": "0.1.60-next.1",
48
48
  "clavarium-docket": "0.1.2-next.2",
49
- "clavarium-parley": "0.17.67-next.1",
49
+ "clavarium-parley": "0.17.68-next.1",
50
50
  "clavarium-tether": "0.1.0-next.49",
51
51
  "mammoth": "1.13.0",
52
52
  "mermaid": "11.17.2",
package/server/api.mjs CHANGED
@@ -152,10 +152,11 @@ 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';
159
+ import { demandeView } from './demandes.mjs';
159
160
 
160
161
  const BODY_MAX = 16 * 1024;
161
162
  /* A setup file travels inside the JSON of a request: room for it, escaped. */
@@ -242,6 +243,14 @@ export async function handleApi(request, response, conversations, headers, resou
242
243
  file.stream.pipe(response);
243
244
  return true;
244
245
  }
246
+ if (request.method === 'GET' && pathname === '/api/files/mail') {
247
+ /* A mail with its remote pictures (asked for, never on opening): as a page is, not for a conversation that is offline. */
248
+ if (conversations.list().find((x) => x.name === query.get('c'))?.offline === true) throw new Refusal(403, 'This conversation is offline: remote pictures stay blocked.');
249
+ const shown = mailPage(await mailFile(attached(), query.get('p') ?? ''));
250
+ response.writeHead(200, shown.headers);
251
+ response.end(shown.body);
252
+ return true;
253
+ }
245
254
  if (request.method === 'GET' && pathname === '/api/files/download') {
246
255
  const file = await download(attached(), query.get('p') ?? '');
247
256
  response.writeHead(200, { ...headers, 'content-type': 'application/octet-stream', 'content-length': file.size,
@@ -289,7 +298,13 @@ export async function handleApi(request, response, conversations, headers, resou
289
298
  if (pathname === '/api/accounts' && accounts) return send(200, { supported: accounts.supported() }), true;
290
299
  /* Assets > Access: the targets, who was given each at which level, the
291
300
  calls waiting, and the recent journal -- all the page needs to read. */
292
- if (pathname === '/api/tether' && tethers) { const r = await tethers.act('state', { agent: query.get('agent') ?? undefined }, ''); return send(200, { given: tethers.given(), changes: tethers.changes(), ...(r.data ?? {}) }), true; }
301
+ /* Each call waiting carries `view`: the card Parley draws for it (demandes.mjs), the same as in the thread. */
302
+ if (pathname === '/api/tether' && tethers) {
303
+ const r = await tethers.act('state', { agent: query.get('agent') ?? undefined }, '');
304
+ const data = r.data ?? {};
305
+ const approvals = Array.isArray(data.approvals) ? data.approvals.map((q) => { try { return { ...q, view: demandeView(q) }; } catch { return q; } }) : data.approvals;
306
+ return send(200, { given: tethers.given(), changes: tethers.changes(), ...data, ...(approvals ? { approvals } : {}) }), true;
307
+ }
293
308
  /* Every device, each with all it was given. */
294
309
  if (pathname === '/api/devices' && sharing) return send(200, sharing.devices.all()), true;
295
310
  if (pathname === '/api/git-keys' && gitAccess) return send(200, gitAccess.keys()), true;
@@ -0,0 +1,140 @@
1
+ /* A TETHER CALL WAITING FOR THE OWNER, AS PLAIN DATA FOR PARLEY'S REQUEST CARD (05-11, "B enrichie").
2
+ *
3
+ * One sentence that says what will happen ("Send “Quote” to sales@example.com"), one or two key
4
+ * facts, what should make one think (someone outside, a time already taken, administrator
5
+ * rights), and, unfolded, the facts, before -> after, the first lines of the text. Parley draws it
6
+ * (requestCard, docs/protocol.md "A request, as a card") wherever it is shown: in the thread
7
+ * (tethers.mjs puts it on the line that asks) and in Assets › Demandes (GET /api/tether gives it
8
+ * with each call). Built from `q.card`, the facts Tether attaches (server/cards.mjs), and
9
+ * `q.card.about`, what the act is about when its connector can tell (the event before a change).
10
+ *
11
+ * IRREVERSIBLE (an amber edge, unfolded when newest, never in "Accept all"): a mail that leaves
12
+ * the owner's domain (not a draft), any delete, a change or delete of an event others are invited
13
+ * to, a command run on a machine. The accept waits HOLD_S seconds with Undo before it is sent to
14
+ * Tether (the page holds it; Tether has no undo once decided). */
15
+ export const HOLD_S = 5;
16
+ const KINDS = new Set(['mail', 'calendar', 'contacts', 'files', 'terminal', 'browser', 'screen', 'device']);
17
+
18
+ const hhmm = (when) => /[T ](\d{2}:\d{2})/.exec(String(when ?? ''))?.[1] ?? '';
19
+ const dayWords = (when) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(when ?? '')); return m ? new Date(Date.UTC(+m[1], +m[2] - 1, +m[3], 12)).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' }) : String(when ?? ''); };
20
+ const span = (from, to) => [hhmm(from), hhmm(to)].filter(Boolean).join('–');
21
+ const whenWords = (from, to) => [dayWords(from), span(from, to)].filter(Boolean).join(' · ');
22
+ const nameOfAddr = (a) => { const m = /^\s*"?([^"<]*?)"?\s*<([^>]+)>/.exec(String(a ?? '')); return m && m[1] ? m[1] : String(a ?? '').split('@')[0]; };
23
+ const subj = (s) => (s ? `“${s}”` : 'a message');
24
+ const sizeOf = (kb) => (kb >= 1024 ? `${(kb / 1024).toFixed(1)} MB` : `${kb} KB`);
25
+ const filesLine = (files) => (files?.length ? files.map((f) => `${f.name}${f.kb ? ` (${sizeOf(f.kb)})` : ''}`).join(', ') : '');
26
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
27
+ /* Whom: the first, and how many more. */
28
+ const whom = (list) => (list.length ? `${list[0]}${list.length > 1 ? ` +${list.length - 1}` : ''}` : '');
29
+ /* The body as it will read: the Markdown marks taken off. */
30
+ const plain = (body) => String(body ?? '').replace(/\*\*(\S[^*\n]*?)\*\*/g, '$1').replace(/__(\S[^_\n]*?)__/g, '$1').replace(/(^|[^*\w])\*(\S[^*\n]*?)\*(?!\w)/g, '$1$2')
31
+ .replace(/\[([^\]\n]+)\]\(([^)\s]+)\)/g, '$1 ($2)').replace(/^#{1,6}\s+/gm, '');
32
+
33
+ export function demandeView(q) {
34
+ const c = q?.card ?? {}; const about = c.about ?? {};
35
+ const kind = KINDS.has(c.kind) ? c.kind : 'other';
36
+ const own = String(c.self ?? '').split('@')[1] ?? '';
37
+ const outside = (list) => (own ? (list ?? []).filter((x) => !String(x).toLowerCase().endsWith(`@${own}`)) : []);
38
+ const chips = (list, ext = []) => (list ?? []).map((x) => ({ text: String(x), ...(ext.includes(x) ? { ext: true } : {}) }));
39
+ const where = q?.target?.title ?? '';
40
+ const v = { kind, title: '', sub: '', risk: [], facts: [], irreversible: false, yes: 'Accept' };
41
+ const sub = [];
42
+ if (c.kind === 'mail') {
43
+ const recipients = [...(c.to ?? []), ...(c.cc ?? []), ...(c.bcc ?? [])];
44
+ const ext = outside(recipients);
45
+ const sending = ['send', 'reply', 'forward'].includes(c.action);
46
+ if (sending && ext.length) v.risk.push('Goes outside your domain');
47
+ const sendWord = c.draft ? 'Save draft' : c.at ? 'Schedule' : 'Send';
48
+ const to = whom(c.to ?? []);
49
+ if (c.action === 'send') { v.title = c.draft ? `Draft ${subj(c.subject)}${to ? ` to ${to}` : ''}` : `${sendWord} ${subj(c.subject)}${to ? ` to ${to}` : ''}`; v.yes = sendWord; }
50
+ else if (c.action === 'reply') { v.title = `${c.all ? 'Reply to all on' : 'Reply to'} ${about.from ? nameOfAddr(about.from) : 'a message'}${about.subject ? ` on “${about.subject}”` : ''}`; v.yes = sendWord; }
51
+ else if (c.action === 'forward') {
52
+ v.title = `Forward ${subj(about.subject)}${to ? ` to ${to}` : ''}`; v.yes = c.draft ? 'Save draft' : 'Forward';
53
+ const k = String(c.keep ?? 'all').toLowerCase();
54
+ v.facts.push(['Keeps', /^(none|false|no)$/.test(k) ? 'without its files' : /^(all|true|yes|)$/.test(k) ? (about.files?.length ? filesLine(about.files) : 'its files') : String(c.keep)]);
55
+ } else if (c.action === 'move') { v.title = `Move ${subj(about.subject)} to ${c.mailbox ?? 'a folder'}`; v.yes = 'Move'; }
56
+ else if (c.action === 'flag') { v.title = `Mark ${subj(about.subject)} ${c.flag ?? ''}`.trim(); v.yes = 'Mark'; }
57
+ else if (c.action === 'delete') { v.title = `Delete ${subj(about.subject)}`; v.yes = 'Delete'; v.irreversible = true; }
58
+ else v.title = `${c.action ?? 'mail'} ${q?.detail ?? ''}`.trim();
59
+ if (sending && !c.draft && ext.length) v.irreversible = true;
60
+ if (about.from && c.action !== 'reply') v.facts.push(['From', String(about.from)]);
61
+ if (about.date && !sending) v.facts.push(['Date', String(about.date)]);
62
+ if (c.to?.length) v.facts.push(['To', chips(c.to, ext)]);
63
+ if (c.cc?.length) v.facts.push(['Cc', chips(c.cc, ext)]);
64
+ if (c.bcc?.length) v.facts.push(['Bcc', chips(c.bcc, ext)]);
65
+ if (c.files?.length) v.facts.push(['Joined', filesLine(c.files)]);
66
+ if (c.at) v.facts.push(['Leaves', `${whenWords(c.at)} (waits in Drafts)`]);
67
+ if (where) sub.push(where);
68
+ if (c.body) { const lines = String(c.body).split('\n').length; sub.push(plural(lines, 'line')); v.quote = plain(c.body); }
69
+ if (c.files?.length) sub.push(plural(c.files.length, 'attachment'));
70
+ } else if (c.kind === 'calendar') {
71
+ const answer = { accept: 'Accept', yes: 'Accept', decline: 'Decline', no: 'Decline', refuse: 'Decline', tentative: 'Maybe', maybe: 'Maybe' }[String(c.answer ?? '').toLowerCase()] ?? '';
72
+ const was = c.action === 'create' ? null : about;
73
+ const ev = c.action === 'create' ? c : { ...about, ...Object.fromEntries(Object.entries(c).filter(([k]) => ['title', 'start', 'end', 'where'].includes(k))) };
74
+ const name = was?.title || c.title || 'an event';
75
+ const guests = c.action === 'create' || c.action === 'update' ? (c.with?.length ? c.with : (about.attendees ?? [])) : (about.attendees ?? []);
76
+ const ext = outside(c.with ?? []);
77
+ if (c.action === 'respond') v.title = `${answer || 'Answer'} “${about.title || 'an invitation'}”${about.start ? ` (${whenWords(about.start, about.end)})` : ''}`;
78
+ else if (c.action === 'create') v.title = `Create “${c.title ?? 'New event'}”${c.start ? ` ${whenWords(c.start, c.end)}` : ''}`;
79
+ else if (c.action === 'delete') v.title = `Delete “${name}”${about.start ? ` (${whenWords(about.start, about.end)})` : ''}`;
80
+ else if (c.action === 'update') v.title = (c.start && c.start !== about.start) ? `Move “${name}” to ${whenWords(c.start, c.end ?? about.end)}` : `Change “${name}”`;
81
+ else if (c.action === 'attach') v.title = `Attach ${filesLine(c.files)} to “${name}”`;
82
+ else v.title = `${c.action ?? 'calendar'} ${q?.detail ?? ''}`.trim();
83
+ /* Before -> after: what changes of a change, and the event itself otherwise. */
84
+ if (c.action === 'update' && was?.start) {
85
+ v.before = [whenWords(was.start, was.end), was.where].filter(Boolean);
86
+ v.after = [whenWords(ev.start, ev.end), ev.where].filter(Boolean);
87
+ sub.push(`was ${whenWords(was.start, was.end)}`);
88
+ } else if (ev.start) { if (c.action !== 'respond' && c.action !== 'delete' && c.action !== 'create') sub.push(whenWords(ev.start, ev.end)); if (ev.where) v.facts.push(['Where', String(ev.where)]); }
89
+ if (guests.length && ['update', 'delete'].includes(c.action)) { sub.push(`${plural(guests.length, 'guest')} told`); v.irreversible = true; }
90
+ if (about.clashes?.length) v.risk.push(`Clashes with ${about.clashes.join(', ')}`);
91
+ if (ext.length) v.risk.push('Invites someone outside your domain');
92
+ if (about.organizer && c.action === 'respond') v.facts.push(['From', String(about.organizer)]);
93
+ if (guests.length) v.facts.push(['Guests', chips(guests, ext)]);
94
+ if (c.online === 'teams' || (c.action === 'create' && (c.with ?? []).length && !c.online)) v.facts.push(['Online', 'Teams meeting']);
95
+ if (where) sub.unshift(where);
96
+ if (c.notes) v.quote = String(c.notes);
97
+ v.yes = c.action === 'respond' ? (answer || 'Answer') : c.action === 'create' ? ((c.with ?? []).length ? 'Create and invite' : 'Create') : c.action === 'delete' ? 'Delete' : c.action === 'update' ? (v.before ? 'Move' : 'Change') : 'Accept';
98
+ if (c.action === 'delete') v.irreversible = true;
99
+ } else if (c.kind === 'contacts') {
100
+ v.title = c.action === 'create' ? `Add ${c.name || c.email || 'a contact'}` : c.action === 'update' ? `Update ${c.name || 'a contact'}` : c.action === 'delete' ? `Delete ${c.name || 'a contact'}` : c.action === 'attach' ? `Set ${c.name ? `${c.name}'s` : 'a contact\'s'} photo` : `${c.action ?? 'contacts'} ${q?.detail ?? ''}`.trim();
101
+ if (c.name && c.action !== 'create') v.facts.push(['Name', String(c.name)]);
102
+ if (c.email) v.facts.push(['Email', String(c.email)]);
103
+ if (c.phone) v.facts.push(['Phone', String(c.phone)]);
104
+ if (where) sub.push(where);
105
+ if (c.email && c.action === 'create') sub.push(String(c.email));
106
+ v.yes = c.action === 'create' ? 'Add' : c.action === 'delete' ? 'Delete' : 'Update';
107
+ if (c.action === 'delete') v.irreversible = true;
108
+ } else if (c.kind === 'terminal') {
109
+ const on = where || 'a machine';
110
+ v.title = c.action === 'run' ? `Run a command on ${on}` : c.action === 'type' ? `Type into a terminal on ${on}` : `Open a terminal on ${on}`;
111
+ if (/^\s*sudo\b/.test(c.command ?? '')) v.risk.push('As administrator');
112
+ if (c.command || c.text) { v.code = String(c.command ?? c.text); sub.push(v.code.split('\n')[0].slice(0, 60)); }
113
+ v.yes = c.action === 'run' ? 'Run' : c.action === 'type' ? 'Type' : 'Open';
114
+ if (c.action === 'run') v.irreversible = true;
115
+ } else if (c.kind === 'files') {
116
+ v.title = c.action === 'write' ? `Write ${c.path}` : c.action === 'delete' ? `Delete ${c.path}` : c.action === 'move' ? `Move ${c.from} → ${c.to}` : `${c.action ?? 'files'} ${c.path ?? ''}`.trim();
117
+ if (where) sub.push(where);
118
+ if (c.bytes !== undefined) { const size = c.bytes >= 1024 ? `${Math.round(c.bytes / 1024)} KB` : `${c.bytes} bytes`; sub.push(size); v.facts.push(['Size', size]); }
119
+ if (c.action === 'move') { v.before = [String(c.from ?? '')]; v.after = [String(c.to ?? '')]; }
120
+ else if (c.path) v.facts.push(['Path', String(c.path)]);
121
+ v.yes = c.action === 'delete' ? 'Delete' : c.action === 'move' ? 'Move' : 'Write';
122
+ if (c.action === 'delete') { v.irreversible = true; v.risk.push('Cannot be undone'); }
123
+ } else if (c.kind === 'browser' && c.action === 'open') { v.title = `Open ${c.url}`; v.yes = 'Open'; if (where) sub.push(where); }
124
+ else { v.title = `${q?.verb ?? 'action'}${q?.detail ? ` ${q.detail}` : ''}`; if (where) sub.push(where); }
125
+ const id = String(q?.id ?? '');
126
+ return {
127
+ kind, title: v.title || String(q?.verb ?? 'A request'), sub: sub.filter(Boolean).slice(0, 3).join(' · '),
128
+ ...(v.risk.length ? { risk: v.risk } : {}), ...(v.facts.length ? { facts: v.facts } : {}),
129
+ ...(v.before ? { before: v.before, after: v.after } : {}),
130
+ ...(v.quote ? { quote: v.quote } : {}), ...(v.code ? { code: v.code } : {}),
131
+ ...(q?.why ? { why: String(q.why) } : {}),
132
+ /* The technical line, in "See all" only. */
133
+ detail: [q?.verb, q?.detail].filter(Boolean).join(' — '),
134
+ irreversible: v.irreversible,
135
+ yes: { id: `allow:${id}`, label: v.yes }, no: { id: `deny:${id}`, label: 'Refuse' },
136
+ /* "Always allow ...": behind "⋯", as before. */
137
+ ...(q?.rule ? { others: [{ id: `always:${id}`, label: `Always allow ${q.rule.value ?? 'this'}` }] } : {}),
138
+ hold: HOLD_S,
139
+ };
140
+ }
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/server/talk.mjs CHANGED
@@ -174,6 +174,8 @@ const TOPIC_MAX = 40;
174
174
  const BRIEF_MAX = 60;
175
175
  const ACTIONS_MAX = 4;
176
176
  const ACTION = /^[a-z]{1,20}(:[a-z0-9][a-z0-9._-]{0,63})?$/;
177
+ const REQUEST_MAX = 8000;
178
+ const OUTCOMES = ['yes', 'always', 'no', 'timeout', 'withdrawn', 'stopped'];
177
179
  /* Where the person's files go, in the bridge folder; one folder per file, named by an id. */
178
180
  const FILES = 'files';
179
181
  const ATTACHED = new RegExp(`^/work/\\${FOLDER}/${FILES}/([0-9a-f-]{36})/([^/]+)$`);
@@ -574,7 +576,7 @@ export class Talk {
574
576
  Only where the chat is on; never counted as unread (the page counts
575
577
  the tool's messages only); at most SYSTEM_MAX kept. Resolves with the
576
578
  line kept, or null. `actions`: ids the page maps to buttons. */
577
- event(name, { kind, text, level, tone, topic, brief, actions = [] } = {}) {
579
+ event(name, { kind, text, level, tone, topic, brief, actions = [], request, outcome } = {}) {
578
580
  if (!Object.hasOwn(EVENT_LEVELS, kind)) throw new RangeError(`No such kind of event: ${kind}`);
579
581
  const said = String(text ?? '').trim();
580
582
  if (!said) return null;
@@ -589,6 +591,10 @@ export class Talk {
589
591
  ...(topic ? { topic: String(topic).slice(0, TOPIC_MAX) } : {}),
590
592
  ...(brief ? { brief: String(brief).slice(0, BRIEF_MAX) } : {}),
591
593
  actions: (Array.isArray(actions) ? actions : []).filter((a) => typeof a === 'string' && ACTION.test(a)).slice(0, ACTIONS_MAX),
594
+ /* A request's card, as Parley draws it (demandes.mjs): plain data, bounded. */
595
+ ...(request && typeof request === 'object' && !Array.isArray(request) && JSON.stringify(request).length <= REQUEST_MAX ? { request } : {}),
596
+ /* How the call a line closes ended (tether-done): yes, always, no, timeout, withdrawn, stopped. */
597
+ ...(OUTCOMES.includes(outcome) ? { outcome } : {}),
592
598
  };
593
599
  return this.#line(name, line);
594
600
  }
@@ -22,6 +22,7 @@
22
22
  import { mkdirSync, lstatSync } from 'node:fs';
23
23
  import { keeper } from 'clavarium-tether/host';
24
24
  import { JsonFile } from './store.mjs';
25
+ import { demandeView } from './demandes.mjs';
25
26
 
26
27
  export const FOLDER = '.tether';
27
28
  /* The keeper takes what the agents asked, this often. */
@@ -30,7 +31,7 @@ const AGENT = 'conversation:';
30
31
  export const USB_DEVICE = 'usb-device';
31
32
 
32
33
  export class Tethers {
33
- #keeper; #resources; #conversations; #secrets; #timers = []; #changes = 0; #seen = new Map(); #offered;
34
+ #keeper; #resources; #conversations; #secrets; #timers = []; #changes = 0; #seen = new Map(); #offered; #ended = new Map();
34
35
  /* Set by the server once the thread is ready (main.mjs): (name, event) => talk.event(...).
35
36
  A call waiting for the owner is said in its conversation's thread when there is one. */
36
37
  announce = null;
@@ -44,7 +45,12 @@ export class Tethers {
44
45
  /* Every change a page shows -- a new approval waiting, one decided, the targets,
45
46
  the journal -- bumps the counter the client watches, so the approvals screen
46
47
  sees them all at once, not only when a store change happens to wake it. */
47
- this.#keeper.onChange(() => { this.#changes++; this.#tellNew(); });
48
+ this.#keeper.onChange((what) => {
49
+ /* How a call ended (yes, always, no, timeout, withdrawn, stopped): said on the line that closes its card. */
50
+ const end = what?.approvals;
51
+ if (end?.op === 'end' && end.id) this.#ended.set(end.id, String(end.decision ?? ''));
52
+ this.#changes++; this.#tellNew();
53
+ });
48
54
  /* A device plugged into the owner's computer: one target, always there, flashed from the
49
55
  owner's browser (Tether's device connector). The owner gives it to a conversation as any other. */
50
56
  try {
@@ -70,7 +76,10 @@ export class Tethers {
70
76
  this.#seen.set(r.id, { name, verb: r.verb ?? 'action' });
71
77
  const what = [r.verb ?? 'action', r.detail].filter(Boolean).join(' ');
72
78
  const text = [what, r.target?.title ? `(${r.target.title})` : '', r.why ? `-- ${r.why}` : ''].filter(Boolean).join(' ');
73
- try { this.announce(name, { kind: 'tether-demande', text: text || (r.verb ?? 'A Tether call'), topic: 'Demande', tone: 'warn', actions: [`allow:${r.id}`, `deny:${r.id}`] }); } catch { /* its chat is off */ }
79
+ /* `request`: the card Parley draws (demandes.mjs); the text and its buttons stay for an older screen. */
80
+ let request;
81
+ try { request = demandeView(r); } catch { request = undefined; }
82
+ try { this.announce(name, { kind: 'tether-demande', text: text || (r.verb ?? 'A Tether call'), topic: 'Demande', tone: 'warn', actions: [`allow:${r.id}`, `deny:${r.id}`], ...(request ? { request } : {}) }); } catch { /* its chat is off */ }
74
83
  }
75
84
  /* An approved call only the owner's browser can do (a device to flash): said once, with where to do it. */
76
85
  let jobs = [];
@@ -87,8 +96,11 @@ export class Tethers {
87
96
  for (const [id, info] of [...this.#seen]) {
88
97
  if (live.has(id)) continue;
89
98
  this.#seen.delete(id);
90
- try { this.announce(info.name, { kind: 'tether-done', text: `Request handled: ${info.verb}`, topic: 'Demande', brief: id }); } catch { /* its chat is off */ }
99
+ const outcome = this.#ended.get(id) ?? '';
100
+ this.#ended.delete(id);
101
+ try { this.announce(info.name, { kind: 'tether-done', text: `Request handled: ${info.verb}${outcome ? ` (${outcome})` : ''}`, topic: 'Demande', brief: id, ...(outcome ? { outcome } : {}) }); } catch { /* its chat is off */ }
91
102
  }
103
+ for (const id of [...this.#ended.keys()]) if (!this.#seen.has(id)) this.#ended.delete(id);
92
104
  }
93
105
 
94
106
  /* A secret's value for a connector, by name, from this server's vault; never seen by the agent.