@celljs/ta-relay 4.21.0 → 4.23.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.
Files changed (88) hide show
  1. package/esm/common/index.d.ts +3 -0
  2. package/esm/common/index.js +3 -0
  3. package/esm/common/relay-blobs.d.ts +36 -2
  4. package/esm/common/relay-blobs.js +33 -5
  5. package/esm/common/relay-chat-store.d.ts +59 -0
  6. package/esm/common/relay-chat-store.js +40 -0
  7. package/esm/common/relay-hub-charter.d.ts +7 -1
  8. package/esm/common/relay-hub-charter.js +6 -0
  9. package/esm/common/relay-hub-log.d.ts +65 -0
  10. package/esm/common/relay-hub-log.js +147 -0
  11. package/esm/common/relay-hub.d.ts +3 -0
  12. package/esm/common/relay-hub.js +18 -0
  13. package/esm/common/relay-hubs-admins.d.ts +1 -0
  14. package/esm/common/relay-hubs-admins.js +10 -6
  15. package/esm/common/relay-hubs-chats.d.ts +66 -0
  16. package/esm/common/relay-hubs-chats.js +342 -0
  17. package/esm/common/relay-hubs-connection.d.ts +3 -1
  18. package/esm/common/relay-hubs-connection.js +7 -0
  19. package/esm/common/relay-hubs-protocol.d.ts +14 -0
  20. package/esm/common/relay-hubs.d.ts +5 -2
  21. package/esm/common/relay-hubs.js +31 -13
  22. package/esm/common/relay-info.d.ts +23 -1
  23. package/esm/common/relay-info.js +25 -2
  24. package/esm/common/relay-protocol.d.ts +60 -1
  25. package/esm/common/relay-protocol.js +15 -0
  26. package/esm/common/relay-room-app.d.ts +106 -0
  27. package/esm/common/relay-room-app.js +171 -0
  28. package/esm/common/relay-room-chat.d.ts +126 -4
  29. package/esm/common/relay-room-chat.js +230 -6
  30. package/esm/guest/guest-i18n.d.ts +5 -0
  31. package/esm/guest/guest-i18n.js +20 -0
  32. package/esm/guest/guest-style.d.ts +1 -1
  33. package/esm/guest/guest-style.js +11 -0
  34. package/esm/guest/guest.js +84 -11
  35. package/esm/node/index.d.ts +1 -0
  36. package/esm/node/index.js +1 -0
  37. package/esm/node/relay-chat-files.d.ts +46 -0
  38. package/esm/node/relay-chat-files.js +199 -0
  39. package/esm/node/relay-hub-files.d.ts +11 -1
  40. package/esm/node/relay-hub-files.js +8 -1
  41. package/esm/node/relay-server.d.ts +7 -1
  42. package/esm/node/relay-server.js +23 -13
  43. package/lib/common/index.d.ts +3 -0
  44. package/lib/common/index.js +3 -0
  45. package/lib/common/relay-blobs.d.ts +36 -2
  46. package/lib/common/relay-blobs.js +34 -6
  47. package/lib/common/relay-chat-store.d.ts +60 -0
  48. package/lib/common/relay-chat-store.js +44 -0
  49. package/lib/common/relay-hub-charter.d.ts +7 -1
  50. package/lib/common/relay-hub-charter.js +7 -1
  51. package/lib/common/relay-hub-log.d.ts +66 -0
  52. package/lib/common/relay-hub-log.js +151 -0
  53. package/lib/common/relay-hub.d.ts +3 -0
  54. package/lib/common/relay-hub.js +18 -0
  55. package/lib/common/relay-hubs-admins.d.ts +1 -0
  56. package/lib/common/relay-hubs-admins.js +9 -5
  57. package/lib/common/relay-hubs-chats.d.ts +67 -0
  58. package/lib/common/relay-hubs-chats.js +346 -0
  59. package/lib/common/relay-hubs-connection.d.ts +3 -1
  60. package/lib/common/relay-hubs-connection.js +7 -0
  61. package/lib/common/relay-hubs-protocol.d.ts +14 -0
  62. package/lib/common/relay-hubs.d.ts +5 -2
  63. package/lib/common/relay-hubs.js +30 -12
  64. package/lib/common/relay-info.d.ts +23 -1
  65. package/lib/common/relay-info.js +26 -3
  66. package/lib/common/relay-protocol.d.ts +60 -1
  67. package/lib/common/relay-protocol.js +16 -1
  68. package/lib/common/relay-room-app.d.ts +107 -0
  69. package/lib/common/relay-room-app.js +176 -0
  70. package/lib/common/relay-room-chat.d.ts +126 -4
  71. package/lib/common/relay-room-chat.js +231 -7
  72. package/lib/guest/guest-i18n.d.ts +5 -0
  73. package/lib/guest/guest-i18n.js +20 -0
  74. package/lib/guest/guest-style.d.ts +1 -1
  75. package/lib/guest/guest-style.js +11 -0
  76. package/lib/guest/guest.js +83 -10
  77. package/lib/node/index.d.ts +1 -0
  78. package/lib/node/index.js +1 -0
  79. package/lib/node/relay-chat-files.d.ts +47 -0
  80. package/lib/node/relay-chat-files.js +203 -0
  81. package/lib/node/relay-hub-files.d.ts +11 -1
  82. package/lib/node/relay-hub-files.js +8 -1
  83. package/lib/node/relay-server.d.ts +7 -1
  84. package/lib/node/relay-server.js +21 -11
  85. package/package.json +3 -3
  86. package/viewer/join.html +17 -6
  87. package/viewer/page.html +10 -10
  88. package/viewer/room.html +26 -15
@@ -2,7 +2,8 @@ import { FaceUtil } from '../common/relay-faces.js';
2
2
  import { RelayHubUtil } from '../common/relay-hub-util.js';
3
3
  import { RelayHubs } from '../common/relay-hubs.js';
4
4
  import { RelayOpenInTa } from '../common/relay-open-in-ta.js';
5
- import { RelayRoomChat } from '../common/relay-room-chat.js';
5
+ import { RELAY_BOARD_KEY, RelayBoardUtil } from '../common/relay-room-app.js';
6
+ import { RelayRoomChat, RelayRoomChatUtil } from '../common/relay-room-chat.js';
6
7
  import { ViewerMarkdown } from '../viewer/viewer-markdown.js';
7
8
  import { GuestI18n } from './guest-i18n.js';
8
9
  import { GUEST_STYLE } from './guest-style.js';
@@ -93,12 +94,20 @@ class GuestPage {
93
94
  this.screen = '';
94
95
  this.stuck = true;
95
96
  this.connected = false;
97
+ /** The boards of the apps of the room, by key, as its owner writes them (RelayRoomBoard): what a guest sees of them. */
98
+ this.boards = new Map();
96
99
  }
97
100
  start() {
98
101
  this.hubs.onEvent(event => {
99
- var _a;
100
- if (event.type === 'state' && event.room === this.link.room) {
101
- (_a = this.chat) === null || _a === void 0 ? void 0 : _a.heard(event.key, event);
102
+ var _a, _b;
103
+ if (event.type === 'chat' && event.room === this.link.room) {
104
+ (_a = this.chat) === null || _a === void 0 ? void 0 : _a.hear(event);
105
+ }
106
+ else if (event.type === 'state' && event.room === this.link.room) {
107
+ (_b = this.chat) === null || _b === void 0 ? void 0 : _b.heard(event.key, event);
108
+ if (event.key.startsWith(RELAY_BOARD_KEY)) {
109
+ this.heardBoard(event.key, event.value, event.by);
110
+ }
102
111
  }
103
112
  else if (event.type === 'rooms') {
104
113
  this.update();
@@ -261,7 +270,17 @@ class GuestPage {
261
270
  }
262
271
  });
263
272
  const banner = room.view ? [div('banner', t('game'))] : [];
264
- this.frame(top, ...banner, list, div('box', field, send), div('foot', t('secure')));
273
+ this.boardBar = div('boards');
274
+ this.boardBar.hidden = true;
275
+ this.frame(top, ...banner, this.boardBar, list, div('box', field, send), div('foot', t('secure')));
276
+ void this.hubs
277
+ .getState(room.id, RELAY_BOARD_KEY)
278
+ .then(state => {
279
+ for (const [key, value] of Object.entries(state)) {
280
+ this.heardBoard(key, value.value, value.by);
281
+ }
282
+ })
283
+ .catch(() => undefined);
265
284
  this.refresh(room);
266
285
  this.draw();
267
286
  }
@@ -279,7 +298,7 @@ class GuestPage {
279
298
  const sub = el('small', !room.connected ? t('connecting') : online ? t('online', { n: online }) : t('nobody'));
280
299
  sub.className = room.connected && online ? '' : 'quiet';
281
300
  (_b = this.heading) === null || _b === void 0 ? void 0 : _b.replaceChildren(title, sub);
282
- if (this.sheet) {
301
+ if (this.sheet && this.sheetOf === 'members') {
283
302
  this.members();
284
303
  }
285
304
  }
@@ -294,10 +313,8 @@ class GuestPage {
294
313
  const self = (_a = room.members.find(member => member.self)) === null || _a === void 0 ? void 0 : _a.member;
295
314
  const personOf = (line) => { var _a; var _b; return (_b = (_a = room.members.find(member => member.member === line.from)) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : line.name; };
296
315
  // What a double says (docs/design/ta-link.md 4) is its own: `X's double`, a guest having none; an agent's, its name.
297
- const nameOf = (line) => (line.agent ? line.agent.name : line.double ? t('doubleOf').replace('{name}', personOf(line)) : personOf(line));
298
- const tagOf = (line) => [line.agent ? t('agentOf').replace('{name}', personOf(line)) : line.double ? t('double') : '', line.task ? t('task') : '']
299
- .filter(Boolean)
300
- .join(' · ');
316
+ const nameOf = (line) => (line.agent ? line.agent.name : line.double ? t('doubleOf', { name: personOf(line) }) : personOf(line));
317
+ const tagOf = (line) => [line.agent ? t('agentOf', { name: personOf(line) }) : line.double ? t('double') : '', line.task ? t('task') : ''].filter(Boolean).join(' · ');
301
318
  const speaker = (line) => { var _a; var _b; return `${line.from}:${line.double ? 'd' : ''}:${(_b = (_a = line.agent) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : ''}`; };
302
319
  const nodes = [];
303
320
  if (!lines.length) {
@@ -312,7 +329,7 @@ class GuestPage {
312
329
  if (separator) {
313
330
  nodes.push(div('when', GuestI18n.time(line.at)));
314
331
  }
315
- const bubble = div('bubble', ViewerMarkdown.render(line.text));
332
+ const bubble = div('bubble', ViewerMarkdown.render(RelayRoomChatUtil.preview(line, t('picture'), { file: t('file'), voice: t('file'), video: t('file') })));
316
333
  bubble.title = GuestI18n.time(line.at);
317
334
  if (line.from === self && !line.agent) {
318
335
  nodes.push(div('mine', bubble));
@@ -328,6 +345,61 @@ class GuestPage {
328
345
  list.scrollTop = list.scrollHeight;
329
346
  }
330
347
  }
348
+ /** A board of an app of the room changed: kept if its owner wrote it, and drawn over the chat. */
349
+ heardBoard(key, value, by) {
350
+ var _a, _b;
351
+ const owner = (_b = (_a = this.room()) === null || _a === void 0 ? void 0 : _a.members.find(member => member.owner)) === null || _b === void 0 ? void 0 : _b.member;
352
+ const board = RelayBoardUtil.read(key, value, by, owner);
353
+ if (board === null || board === void 0 ? void 0 : board.items.length) {
354
+ this.boards.set(key, board);
355
+ }
356
+ else {
357
+ this.boards.delete(key);
358
+ }
359
+ this.drawBoards();
360
+ }
361
+ /** A chip for each board, how many are in progress and done; a tap opens its items. */
362
+ drawBoards() {
363
+ const bar = this.boardBar;
364
+ if (!bar) {
365
+ return;
366
+ }
367
+ const chips = [...this.boards].map(([key, board]) => {
368
+ const { open, done } = RelayBoardUtil.counts(board);
369
+ const parts = [open ? t('boardOpen', { n: open }) : '', done ? t('boardDone', { n: done }) : ''].filter(Boolean);
370
+ const chip = button('board', [board.title, ...parts].join(' · '), () => this.showBoard(key));
371
+ if (open) {
372
+ chip.prepend(Object.assign(el('span'), { className: 'dot' }));
373
+ }
374
+ return chip;
375
+ });
376
+ bar.replaceChildren(...chips);
377
+ bar.hidden = !chips.length;
378
+ }
379
+ showBoard(key) {
380
+ var _a;
381
+ const board = this.boards.get(key);
382
+ if (!board) {
383
+ return;
384
+ }
385
+ const panel = div('panel', el('h3', board.title));
386
+ for (const item of [...board.items].reverse()) {
387
+ const label = Object.assign(el('span', item.label), { className: `lb ${item.state}` });
388
+ const head = div('hd', Object.assign(el('span', `#${item.n}`), { className: 'n' }), Object.assign(el('span', item.title), { className: 'tt' }), label);
389
+ panel.append(div('item', head, ...(item.people.length ? [div('by', t('boardFrom', { names: item.people.join('、') }))] : [])));
390
+ }
391
+ panel.append(div('sep'), button('row', t('close'), () => this.closeSheet()));
392
+ const sheet = div('sheet', panel);
393
+ sheet.addEventListener('click', event => {
394
+ if (event.target === sheet) {
395
+ this.closeSheet();
396
+ }
397
+ });
398
+ (_a = this.sheet) === null || _a === void 0 ? void 0 : _a.remove();
399
+ document.body.append(sheet);
400
+ this.sheet = sheet;
401
+ this.sheetOf = 'board';
402
+ }
331
403
  /** The members, over the chat: who is online, and the user's name and way out. */
332
404
  members() {
333
405
  var _a;
@@ -335,6 +407,7 @@ class GuestPage {
335
407
  if (!room) {
336
408
  return;
337
409
  }
410
+ this.sheetOf = 'members';
338
411
  const panel = div('panel', Object.assign(el('h3', `${t('members')} (${room.members.length})`)));
339
412
  for (const member of room.members) {
340
413
  const tags = [member.self ? t('you') : '', member.owner ? t('owner') : '', member.guest ? t('guest') : ''].filter(Boolean);
@@ -1,4 +1,5 @@
1
1
  export * from '../common/index.js';
2
+ export * from './relay-chat-files.js';
2
3
  export * from './relay-file-storage.js';
3
4
  export * from './relay-files-host.js';
4
5
  export * from './relay-host.js';
package/esm/node/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from '../common/index.js';
2
+ export * from './relay-chat-files.js';
2
3
  export * from './relay-file-storage.js';
3
4
  export * from './relay-files-host.js';
4
5
  export * from './relay-host.js';
@@ -0,0 +1,46 @@
1
+ import { type RelayChatState, type RelayChatStore } from '../common/relay-chat-store.js';
2
+ import type { RelayChatLine } from '../common/relay-room-chat.js';
3
+ /**
4
+ * The key what is said in the rooms is sealed with on this computer (docs/design/ta-chat-history.md 12): in the
5
+ * keychain of macOS (the service `Ta chats`, an account of the agent directory), elsewhere or with
6
+ * `TA_CHATS_KEY=file` in `chats/.key`, readable by the user alone. Made the first time.
7
+ */
8
+ export declare namespace RelayChatKeys {
9
+ const SERVICE = "Ta chats";
10
+ function local(agentDir: string, env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): () => Promise<Uint8Array>;
11
+ }
12
+ /**
13
+ * What is said in the rooms, kept in `chats/<room>/` of the agent directory (docs/design/ta-chat-history.md 8): a
14
+ * file a month (`2026-11.log`), lines only added, each sealed on its own (AES-256-GCM), so that a line cut short by a
15
+ * crash loses that line alone; and the state of the log (`state`), sealed, written whole. A month goes as a file.
16
+ */
17
+ export declare class RelayChatFiles implements RelayChatStore {
18
+ readonly dir: string;
19
+ protected readonly key: () => Promise<Uint8Array>;
20
+ protected readonly now: () => number;
21
+ /** The lines of each room read, as long as nothing was added that is not in them. */
22
+ protected readonly cache: Map<string, {
23
+ lines: RelayChatLine[];
24
+ months: number;
25
+ all: boolean;
26
+ }>;
27
+ constructor(dir: string, key: () => Promise<Uint8Array>, now?: () => number);
28
+ read(room: string, options: {
29
+ before?: string;
30
+ limit: number;
31
+ }): Promise<{
32
+ lines: RelayChatLine[];
33
+ more: boolean;
34
+ }>;
35
+ append(room: string, lines: RelayChatLine[]): Promise<void>;
36
+ state(room: string): Promise<RelayChatState | undefined>;
37
+ setState(room: string, state: RelayChatState): Promise<void>;
38
+ forget(room: string): Promise<void>;
39
+ protected roomDir(room: string): string;
40
+ /** The months kept of a room, the earliest first. */
41
+ protected months(room: string): string[];
42
+ protected readMonth(room: string, month: string): Promise<RelayChatLine[]>;
43
+ /** base64url of a nonce of 12 bytes, the text sealed and its tag. */
44
+ static seal(key: Uint8Array, text: string): string;
45
+ static open(key: Uint8Array, sealed: string): string | undefined;
46
+ }
@@ -0,0 +1,199 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';
3
+ import { appendFileSync, chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { RelayChatStoreUtil } from '../common/relay-chat-store.js';
6
+ const ROOM = /^[A-Za-z0-9_-]{1,64}$/;
7
+ const MONTH = /^\d{4}-\d{2}\.log$/;
8
+ const STATE = 'state';
9
+ /**
10
+ * The key what is said in the rooms is sealed with on this computer (docs/design/ta-chat-history.md 12): in the
11
+ * keychain of macOS (the service `Ta chats`, an account of the agent directory), elsewhere or with
12
+ * `TA_CHATS_KEY=file` in `chats/.key`, readable by the user alone. Made the first time.
13
+ */
14
+ export var RelayChatKeys;
15
+ (function (RelayChatKeys) {
16
+ RelayChatKeys.SERVICE = 'Ta chats';
17
+ function local(agentDir, env = process.env, platform = process.platform) {
18
+ let key;
19
+ return () => {
20
+ key !== null && key !== void 0 ? key : (key = platform === 'darwin' && env.TA_CHATS_KEY !== 'file' ? keychain(agentDir).catch(() => file(agentDir)) : file(agentDir));
21
+ return key;
22
+ };
23
+ }
24
+ RelayChatKeys.local = local;
25
+ async function keychain(agentDir) {
26
+ const account = createHash('sha256').update(agentDir).digest('base64url').slice(0, 16);
27
+ const found = await run('security', ['find-generic-password', '-s', RelayChatKeys.SERVICE, '-a', account, '-w']);
28
+ const kept = found.code === 0 ? Buffer.from(found.stdout.trim(), 'base64') : undefined;
29
+ if ((kept === null || kept === void 0 ? void 0 : kept.length) === 32) {
30
+ return kept;
31
+ }
32
+ const made = randomBytes(32);
33
+ // Through the input of `security -i`: a key never goes in the arguments, which `ps` shows.
34
+ await run('security', ['-i'], `add-generic-password -U -s "${RelayChatKeys.SERVICE}" -a "${account}" -l "${RelayChatKeys.SERVICE}" -w "${made.toString('base64')}"\n`);
35
+ const again = await run('security', ['find-generic-password', '-s', RelayChatKeys.SERVICE, '-a', account, '-w']);
36
+ if (again.code !== 0 || Buffer.from(again.stdout.trim(), 'base64').length !== 32) {
37
+ throw new Error('The keychain did not keep the key of the chats.');
38
+ }
39
+ return Buffer.from(again.stdout.trim(), 'base64');
40
+ }
41
+ async function file(agentDir) {
42
+ const dir = join(agentDir, 'chats');
43
+ const path = join(dir, '.key');
44
+ if (existsSync(path)) {
45
+ const kept = Buffer.from(readFileSync(path, 'utf8').trim(), 'base64');
46
+ if (kept.length === 32) {
47
+ return kept;
48
+ }
49
+ }
50
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
51
+ const made = randomBytes(32);
52
+ writeFileSync(path, `${made.toString('base64')}\n`, { mode: 0o600 });
53
+ chmodSync(path, 0o600);
54
+ return made;
55
+ }
56
+ function run(command, args, input) {
57
+ return new Promise(resolve => {
58
+ const child = spawn(command, args, { stdio: ['pipe', 'pipe', 'ignore'] });
59
+ let stdout = '';
60
+ child.stdout.on('data', chunk => {
61
+ stdout += chunk;
62
+ });
63
+ child.on('error', () => resolve({ code: -1, stdout }));
64
+ child.on('close', code => resolve({ code: code !== null && code !== void 0 ? code : -1, stdout }));
65
+ child.stdin.end(input !== null && input !== void 0 ? input : '');
66
+ });
67
+ }
68
+ })(RelayChatKeys || (RelayChatKeys = {}));
69
+ /**
70
+ * What is said in the rooms, kept in `chats/<room>/` of the agent directory (docs/design/ta-chat-history.md 8): a
71
+ * file a month (`2026-11.log`), lines only added, each sealed on its own (AES-256-GCM), so that a line cut short by a
72
+ * crash loses that line alone; and the state of the log (`state`), sealed, written whole. A month goes as a file.
73
+ */
74
+ export class RelayChatFiles {
75
+ constructor(dir, key, now = Date.now) {
76
+ this.dir = dir;
77
+ this.key = key;
78
+ this.now = now;
79
+ /** The lines of each room read, as long as nothing was added that is not in them. */
80
+ this.cache = new Map();
81
+ }
82
+ async read(room, options) {
83
+ const months = this.months(room);
84
+ const cached = this.cache.get(room);
85
+ let read = cached !== null && cached !== void 0 ? cached : { lines: [], months: 0, all: months.length === 0 };
86
+ const enough = () => {
87
+ const end = options.before === undefined ? read.lines.length : read.lines.findIndex(line => line.id === options.before);
88
+ return end >= 0 && end - options.limit > 0;
89
+ };
90
+ while (!read.all && !enough()) {
91
+ const month = months[months.length - 1 - read.months];
92
+ const lines = await this.readMonth(room, month);
93
+ read = { lines: [...lines, ...read.lines], months: read.months + 1, all: read.months + 1 >= months.length };
94
+ }
95
+ this.cache.set(room, read);
96
+ const page = RelayChatStoreUtil.page(read.lines, options);
97
+ return { lines: page.lines, more: page.more || !read.all };
98
+ }
99
+ async append(room, lines) {
100
+ if (!lines.length) {
101
+ return;
102
+ }
103
+ const key = await this.key();
104
+ const dir = this.roomDir(room);
105
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
106
+ const date = new Date(this.now());
107
+ const month = `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}.log`;
108
+ const path = join(dir, month);
109
+ const fresh = !existsSync(path);
110
+ appendFileSync(path, lines.map(line => `${RelayChatFiles.seal(key, JSON.stringify(line))}\n`).join(''), { mode: 0o600 });
111
+ const cached = this.cache.get(room);
112
+ if (cached) {
113
+ cached.lines.push(...lines);
114
+ if (fresh) {
115
+ cached.months++;
116
+ }
117
+ }
118
+ }
119
+ async state(room) {
120
+ const path = join(this.roomDir(room), STATE);
121
+ if (!existsSync(path)) {
122
+ return undefined;
123
+ }
124
+ const opened = RelayChatFiles.open(await this.key(), readFileSync(path, 'utf8').trim());
125
+ if (!opened) {
126
+ return undefined;
127
+ }
128
+ const state = JSON.parse(opened);
129
+ return { ...state, seq: Number(state.seq) || 0, outbox: Array.isArray(state.outbox) ? state.outbox : [] };
130
+ }
131
+ async setState(room, state) {
132
+ const key = await this.key();
133
+ const dir = this.roomDir(room);
134
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
135
+ const path = join(dir, STATE);
136
+ const temporary = `${path}.${process.pid}.tmp`;
137
+ writeFileSync(temporary, `${RelayChatFiles.seal(key, JSON.stringify(state))}\n`, { mode: 0o600 });
138
+ renameSync(temporary, path);
139
+ }
140
+ async forget(room) {
141
+ this.cache.delete(room);
142
+ rmSync(this.roomDir(room), { recursive: true, force: true });
143
+ }
144
+ roomDir(room) {
145
+ if (!ROOM.test(room)) {
146
+ throw new Error('Not a room.');
147
+ }
148
+ return join(this.dir, room);
149
+ }
150
+ /** The months kept of a room, the earliest first. */
151
+ months(room) {
152
+ try {
153
+ return readdirSync(this.roomDir(room))
154
+ .filter(name => MONTH.test(name))
155
+ .sort();
156
+ }
157
+ catch (_a) {
158
+ return [];
159
+ }
160
+ }
161
+ async readMonth(room, month) {
162
+ const key = await this.key();
163
+ const lines = [];
164
+ for (const sealed of readFileSync(join(this.roomDir(room), month), 'utf8').split('\n')) {
165
+ const opened = sealed && RelayChatFiles.open(key, sealed);
166
+ if (opened) {
167
+ try {
168
+ lines.push(JSON.parse(opened));
169
+ }
170
+ catch (_a) {
171
+ // A line cut short: that line alone is lost.
172
+ }
173
+ }
174
+ }
175
+ return lines;
176
+ }
177
+ /** base64url of a nonce of 12 bytes, the text sealed and its tag. */
178
+ static seal(key, text) {
179
+ const iv = randomBytes(12);
180
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
181
+ const sealed = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
182
+ return Buffer.concat([iv, sealed, cipher.getAuthTag()]).toString('base64url');
183
+ }
184
+ static open(key, sealed) {
185
+ try {
186
+ const bytes = Buffer.from(sealed, 'base64url');
187
+ if (bytes.length < 28) {
188
+ return undefined;
189
+ }
190
+ const decipher = createDecipheriv('aes-256-gcm', key, bytes.subarray(0, 12));
191
+ decipher.setAuthTag(bytes.subarray(bytes.length - 16));
192
+ return Buffer.concat([decipher.update(bytes.subarray(12, bytes.length - 16)), decipher.final()]).toString('utf8');
193
+ }
194
+ catch (_a) {
195
+ return undefined;
196
+ }
197
+ }
198
+ }
199
+ //# sourceMappingURL=relay-chat-files.js.map
@@ -1,8 +1,18 @@
1
+ import type { RelayChatStore } from '../common/relay-chat-store.js';
1
2
  import type { RelayHubsStore, RelayHubsStoreName } from '../common/relay-hubs-protocol.js';
2
3
  /** What the rooms of a Ta keep, as files of its agent directory readable by the user alone: `identity.json`, `rooms.json`, `friends.json`. */
3
4
  export declare class RelayHubFiles implements RelayHubsStore {
4
5
  readonly agentDir: string;
5
- constructor(agentDir: string);
6
+ /** What is said in the rooms is kept in `chats/`, sealed with the key of the keychain (RelayChatKeys); else in memory. */
7
+ protected readonly options: {
8
+ chats?: boolean;
9
+ };
10
+ constructor(agentDir: string,
11
+ /** What is said in the rooms is kept in `chats/`, sealed with the key of the keychain (RelayChatKeys); else in memory. */
12
+ options?: {
13
+ chats?: boolean;
14
+ });
15
+ chats(): RelayChatStore | undefined;
6
16
  file(name: RelayHubsStoreName): string;
7
17
  read<T>(name: RelayHubsStoreName): T | undefined;
8
18
  /** Written whole, then renamed over the file, readable by the user alone: it holds keys. */
@@ -1,10 +1,17 @@
1
1
  import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
2
  import { userInfo } from 'node:os';
3
3
  import { dirname, join } from 'node:path';
4
+ import { RelayChatFiles, RelayChatKeys } from './relay-chat-files.js';
4
5
  /** What the rooms of a Ta keep, as files of its agent directory readable by the user alone: `identity.json`, `rooms.json`, `friends.json`. */
5
6
  export class RelayHubFiles {
6
- constructor(agentDir) {
7
+ constructor(agentDir,
8
+ /** What is said in the rooms is kept in `chats/`, sealed with the key of the keychain (RelayChatKeys); else in memory. */
9
+ options = {}) {
7
10
  this.agentDir = agentDir;
11
+ this.options = options;
12
+ }
13
+ chats() {
14
+ return this.options.chats ? new RelayChatFiles(join(this.agentDir, 'chats'), RelayChatKeys.local(this.agentDir)) : undefined;
8
15
  }
9
16
  file(name) {
10
17
  return join(this.agentDir, `${name}.json`);
@@ -5,6 +5,7 @@ import { type TaDeploymentEnv } from '@celljs/ta-protocol/lib/common/deployment-
5
5
  import type { RelayAccountProvider } from '../common/relay-accounts.js';
6
6
  import { RelayBlobs } from '../common/relay-blobs.js';
7
7
  import { RelayHub, type RelayHubWho } from '../common/relay-hub.js';
8
+ import { type RelayMedia } from '../common/relay-info.js';
8
9
  import { RelayRoom } from '../common/relay-room.js';
9
10
  import { RelaySpot, type RelaySpotSocket, type RelaySpotWho } from '../common/relay-spot.js';
10
11
  import { FileRelayStorage } from './relay-file-storage.js';
@@ -33,6 +34,11 @@ export interface RelayServerOptions {
33
34
  version?: string;
34
35
  /** The ways to sign in to accounts (docs/design/ta-account.md): GitHub with Ta's own app, unless given. */
35
36
  accounts?: RelayAccountProvider[];
37
+ /**
38
+ * Sealed copies of the pictures of chats it keeps (RELAY_MEDIA_PATH, docs/design/ta-chat-history.md 7), as its
39
+ * operator set it (`ta relay` reads TA_MEDIA_DAYS and TA_MEDIA_MAX_MB, a day by default, none with 0); none here unless given.
40
+ */
41
+ media?: RelayMedia;
36
42
  }
37
43
  interface Room {
38
44
  secretHash: string;
@@ -84,7 +90,7 @@ export declare class RelayServer {
84
90
  protected web(path: string, response: ServerResponse): void;
85
91
  close(): Promise<void>;
86
92
  /** A copy of content (RelayBlobs), kept in memory for as long as the relay runs. */
87
- protected blob(id: string, request: IncomingMessage, response: ServerResponse): Promise<void>;
93
+ protected blob(id: string, request: IncomingMessage, response: ServerResponse, media?: RelayMedia): Promise<void>;
88
94
  protected blobCopy(id: string): {
89
95
  blobs: RelayBlobs;
90
96
  storage: MemoryBlobStorage | FileRelayStorage;
@@ -5,10 +5,10 @@ import { join } from 'node:path';
5
5
  import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
6
6
  import { TA_WELL_KNOWN_PATH, TaDeploymentUtil } from '@celljs/ta-protocol/lib/common/deployment-protocol';
7
7
  import { RELAY_ACCOUNT_PATH } from '../common/relay-account.js';
8
- import { RelayBlobs } from '../common/relay-blobs.js';
8
+ import { RelayBlobs, RelayBlobsUtil } from '../common/relay-blobs.js';
9
9
  import { RelayHub } from '../common/relay-hub.js';
10
10
  import { RELAY_INFO_PATH, RelayInfoUtil } from '../common/relay-info.js';
11
- import { RELAY_BLOB_PATH, RELAY_CONNECT_PATH, RELAY_CONTENT_PATH, RELAY_FRAME_HEADER_CSP, RELAY_FRAME_PATH, RELAY_HOST_PATH, RELAY_HUB_PATH, RELAY_ID, RELAY_PAIR_PAGE, RELAY_PAIR_PATH, RELAY_ROOM_PATH, RELAY_SHARE_PAGE, RELAY_SHARE_PATH, RELAY_VIEWER_HEADERS, RelayCloseCode, } from '../common/relay-protocol.js';
11
+ import { RELAY_BLOB_PATH, RELAY_CONNECT_PATH, RELAY_CONTENT_PATH, RELAY_FRAME_HEADER_CSP, RELAY_FRAME_PATH, RELAY_HOST_PATH, RELAY_HUB_PATH, RELAY_ID, RELAY_MEDIA_PATH, RELAY_PAIR_PAGE, RELAY_PAIR_PATH, RELAY_ROOM_PATH, RELAY_SHARE_PAGE, RELAY_SHARE_PATH, RELAY_VIEWER_HEADERS, RelayCloseCode, } from '../common/relay-protocol.js';
12
12
  import { RelayRoom } from '../common/relay-room.js';
13
13
  import { RELAY_SPOT_PATH, RelaySpot, RelaySpotCloseCode, RelaySpotTries } from '../common/relay-spot.js';
14
14
  import { RELAY_JOIN_PATH, RELAY_WEB_PATH } from '../common/relay-team.js';
@@ -93,7 +93,7 @@ export class RelayServer {
93
93
  }
94
94
  if (path === RELAY_INFO_PATH) {
95
95
  // Without a directory for its data, rooms and copies live in memory: gone when the relay restarts.
96
- const info = RelayInfoUtil.of(!!this.options.data);
96
+ const info = RelayInfoUtil.of(!!this.options.data, this.options.media);
97
97
  response.writeHead(200, { 'content-type': 'application/json', 'access-control-allow-origin': '*', 'cache-control': 'no-store' });
98
98
  response.end(JSON.stringify(info));
99
99
  return;
@@ -102,8 +102,15 @@ export class RelayServer {
102
102
  this.accounts.serve(request, response);
103
103
  return;
104
104
  }
105
- if (path.startsWith(RELAY_BLOB_PATH)) {
106
- this.blob(path.slice(RELAY_BLOB_PATH.length), request, response).catch(() => {
105
+ const media = path.startsWith(RELAY_MEDIA_PATH);
106
+ if (media && !this.options.media) {
107
+ // Its operator lets it keep no pictures of chats.
108
+ response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }).end('Not found.\n');
109
+ return;
110
+ }
111
+ if (path.startsWith(RELAY_BLOB_PATH) || media) {
112
+ const id = path.slice((media ? RELAY_MEDIA_PATH : RELAY_BLOB_PATH).length);
113
+ this.blob(id, request, response, media ? this.options.media : undefined).catch(() => {
107
114
  // A request aborted or that failed: an unhandled rejection would end the relay.
108
115
  if (!response.headersSent) {
109
116
  response.writeHead(400);
@@ -194,37 +201,40 @@ export class RelayServer {
194
201
  return new Promise(resolve => (this.server ? this.server.close(() => resolve()) : resolve()));
195
202
  }
196
203
  /** A copy of content (RelayBlobs), kept in memory for as long as the relay runs. */
197
- async blob(id, request, response) {
198
- var _a;
204
+ async blob(id, request, response, media) {
205
+ var _a, _b;
199
206
  if (!RELAY_ID.test(id)) {
200
207
  response.writeHead(404).end();
201
208
  return;
202
209
  }
203
- const read = await RelayServer.body(request, RelayBlobs.MAX_BYTES);
210
+ const limits = media && RelayBlobsUtil.limitsOf(media);
211
+ const read = await RelayServer.body(request, (_a = limits === null || limits === void 0 ? void 0 : limits.bytes) !== null && _a !== void 0 ? _a : RelayBlobs.MAX_BYTES);
204
212
  if (!read) {
205
213
  // Refused before it is all in memory, whatever its content-length said.
206
214
  response.writeHead(413, { connection: 'close' }).end('Too large.\n');
207
215
  return;
208
216
  }
209
217
  // Kept only while it holds a copy: requests for ids of no copy leave nothing behind.
210
- const copy = this.blobCopy(id);
218
+ const key = media ? `media-${id}` : id;
219
+ const copy = this.blobCopy(key);
211
220
  const headers = new Headers();
212
221
  for (const [name, value] of Object.entries(request.headers)) {
213
222
  if (typeof value === 'string') {
214
223
  headers.set(name, value);
215
224
  }
216
225
  }
217
- const method = (_a = request.method) !== null && _a !== void 0 ? _a : 'GET';
226
+ const method = (_b = request.method) !== null && _b !== void 0 ? _b : 'GET';
218
227
  const body = read.length && method !== 'GET' && method !== 'HEAD' ? read : undefined;
219
228
  copy.pending++;
220
229
  let answer;
221
230
  try {
222
- answer = await copy.blobs.handle(new Request(`http://relay${request.url}`, { method, headers, body }));
231
+ headers.delete(RelayBlobsUtil.LIMITS_HEADER);
232
+ answer = await copy.blobs.handle(new Request(`http://relay${request.url}`, { method, headers, body }), limits);
223
233
  }
224
234
  finally {
225
235
  copy.pending--;
226
- if (copy.pending === 0 && copy.storage.empty && this.blobs.get(id) === copy) {
227
- this.blobs.delete(id);
236
+ if (copy.pending === 0 && copy.storage.empty && this.blobs.get(key) === copy) {
237
+ this.blobs.delete(key);
228
238
  }
229
239
  }
230
240
  response.writeHead(answer.status, Object.fromEntries(answer.headers));
@@ -5,6 +5,7 @@ export * from './relay-accounts';
5
5
  export * from './relay-blobs';
6
6
  export * from './relay-bytes';
7
7
  export * from './relay-card';
8
+ export * from './relay-chat-store';
8
9
  export * from './relay-cipher';
9
10
  export * from './relay-content';
10
11
  export * from './relay-conversation';
@@ -15,6 +16,7 @@ export * from './relay-group-invites';
15
16
  export * from './relay-host-calls';
16
17
  export * from './relay-hub';
17
18
  export * from './relay-hub-charter';
19
+ export * from './relay-hub-log';
18
20
  export * from './relay-hub-util';
19
21
  export * from './relay-hubs';
20
22
  export * from './relay-hubs-protocol';
@@ -24,6 +26,7 @@ export * from './relay-info';
24
26
  export * from './relay-pairing';
25
27
  export * from './relay-protocol';
26
28
  export * from './relay-room';
29
+ export * from './relay-room-app';
27
30
  export * from './relay-room-chat';
28
31
  export * from './relay-share';
29
32
  export * from './relay-socket';
@@ -21,6 +21,7 @@ __exportStar(require("./relay-accounts"), exports);
21
21
  __exportStar(require("./relay-blobs"), exports);
22
22
  __exportStar(require("./relay-bytes"), exports);
23
23
  __exportStar(require("./relay-card"), exports);
24
+ __exportStar(require("./relay-chat-store"), exports);
24
25
  __exportStar(require("./relay-cipher"), exports);
25
26
  __exportStar(require("./relay-content"), exports);
26
27
  __exportStar(require("./relay-conversation"), exports);
@@ -31,6 +32,7 @@ __exportStar(require("./relay-group-invites"), exports);
31
32
  __exportStar(require("./relay-host-calls"), exports);
32
33
  __exportStar(require("./relay-hub"), exports);
33
34
  __exportStar(require("./relay-hub-charter"), exports);
35
+ __exportStar(require("./relay-hub-log"), exports);
34
36
  __exportStar(require("./relay-hub-util"), exports);
35
37
  __exportStar(require("./relay-hubs"), exports);
36
38
  __exportStar(require("./relay-hubs-protocol"), exports);
@@ -40,6 +42,7 @@ __exportStar(require("./relay-info"), exports);
40
42
  __exportStar(require("./relay-pairing"), exports);
41
43
  __exportStar(require("./relay-protocol"), exports);
42
44
  __exportStar(require("./relay-room"), exports);
45
+ __exportStar(require("./relay-room-app"), exports);
43
46
  __exportStar(require("./relay-room-chat"), exports);
44
47
  __exportStar(require("./relay-share"), exports);
45
48
  __exportStar(require("./relay-socket"), exports);