@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
@@ -47,6 +47,17 @@ input.text:focus{border-color:var(--accent)}
47
47
  @media (prefers-color-scheme:dark){.face[data-face="11"] .ta-face-body>g>circle{fill:#4a4a52}}
48
48
  .face i{position:absolute;right:-1px;bottom:-1px;width:28%;height:28%;min-width:7px;min-height:7px;border-radius:50%;border:2px solid var(--bg);background:var(--faint)}
49
49
  .face i.on{background:var(--accent)}
50
+ .boards{flex:none;display:flex;gap:6px;overflow-x:auto;margin:10px 14px 0;scrollbar-width:none}
51
+ .boards::-webkit-scrollbar{display:none}
52
+ .board{flex:none;display:flex;align-items:center;gap:6px;border:0;padding:7px 12px;border-radius:12px;background:var(--soft);color:var(--fg);font-size:12.5px;line-height:1.4;white-space:nowrap}
53
+ .board .dot{width:6px;height:6px;border-radius:50%;background:var(--accent)}
54
+ .item{display:flex;flex-direction:column;gap:2px;padding:9px 14px}
55
+ .item .hd{display:flex;align-items:center;gap:8px;font-size:14.5px}
56
+ .item .n{color:var(--muted);font-variant-numeric:tabular-nums}
57
+ .item .tt{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
58
+ .item .lb{flex:none;font-size:12px;color:var(--muted)}
59
+ .item .lb.doing,.item .lb.waiting{color:var(--accent)}
60
+ .item .by{font-size:12px;color:var(--muted);padding-left:2px}
50
61
  .banner{flex:none;margin:10px 14px 0;padding:8px 12px;border-radius:12px;background:var(--soft);color:var(--muted);font-size:12.5px;line-height:1.5}
51
62
  .list{flex:1;min-height:0;overflow-y:auto;overflow-x:hidden;overscroll-behavior:none;padding:10px 14px 12px;display:flex;flex-direction:column;gap:4px}
52
63
  .empty{margin:14vh auto 0;max-width:300px;text-align:center;color:var(--muted);font-size:13px}
@@ -4,6 +4,7 @@ const relay_faces_1 = require("../common/relay-faces");
4
4
  const relay_hub_util_1 = require("../common/relay-hub-util");
5
5
  const relay_hubs_1 = require("../common/relay-hubs");
6
6
  const relay_open_in_ta_1 = require("../common/relay-open-in-ta");
7
+ const relay_room_app_1 = require("../common/relay-room-app");
7
8
  const relay_room_chat_1 = require("../common/relay-room-chat");
8
9
  const viewer_markdown_1 = require("../viewer/viewer-markdown");
9
10
  const guest_i18n_1 = require("./guest-i18n");
@@ -95,12 +96,20 @@ class GuestPage {
95
96
  this.screen = '';
96
97
  this.stuck = true;
97
98
  this.connected = false;
99
+ /** The boards of the apps of the room, by key, as its owner writes them (RelayRoomBoard): what a guest sees of them. */
100
+ this.boards = new Map();
98
101
  }
99
102
  start() {
100
103
  this.hubs.onEvent(event => {
101
- var _a;
102
- if (event.type === 'state' && event.room === this.link.room) {
103
- (_a = this.chat) === null || _a === void 0 ? void 0 : _a.heard(event.key, event);
104
+ var _a, _b;
105
+ if (event.type === 'chat' && event.room === this.link.room) {
106
+ (_a = this.chat) === null || _a === void 0 ? void 0 : _a.hear(event);
107
+ }
108
+ else if (event.type === 'state' && event.room === this.link.room) {
109
+ (_b = this.chat) === null || _b === void 0 ? void 0 : _b.heard(event.key, event);
110
+ if (event.key.startsWith(relay_room_app_1.RELAY_BOARD_KEY)) {
111
+ this.heardBoard(event.key, event.value, event.by);
112
+ }
104
113
  }
105
114
  else if (event.type === 'rooms') {
106
115
  this.update();
@@ -263,7 +272,17 @@ class GuestPage {
263
272
  }
264
273
  });
265
274
  const banner = room.view ? [div('banner', t('game'))] : [];
266
- this.frame(top, ...banner, list, div('box', field, send), div('foot', t('secure')));
275
+ this.boardBar = div('boards');
276
+ this.boardBar.hidden = true;
277
+ this.frame(top, ...banner, this.boardBar, list, div('box', field, send), div('foot', t('secure')));
278
+ void this.hubs
279
+ .getState(room.id, relay_room_app_1.RELAY_BOARD_KEY)
280
+ .then(state => {
281
+ for (const [key, value] of Object.entries(state)) {
282
+ this.heardBoard(key, value.value, value.by);
283
+ }
284
+ })
285
+ .catch(() => undefined);
267
286
  this.refresh(room);
268
287
  this.draw();
269
288
  }
@@ -281,7 +300,7 @@ class GuestPage {
281
300
  const sub = el('small', !room.connected ? t('connecting') : online ? t('online', { n: online }) : t('nobody'));
282
301
  sub.className = room.connected && online ? '' : 'quiet';
283
302
  (_b = this.heading) === null || _b === void 0 ? void 0 : _b.replaceChildren(title, sub);
284
- if (this.sheet) {
303
+ if (this.sheet && this.sheetOf === 'members') {
285
304
  this.members();
286
305
  }
287
306
  }
@@ -296,10 +315,8 @@ class GuestPage {
296
315
  const self = (_a = room.members.find(member => member.self)) === null || _a === void 0 ? void 0 : _a.member;
297
316
  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; };
298
317
  // 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.
299
- const nameOf = (line) => (line.agent ? line.agent.name : line.double ? t('doubleOf').replace('{name}', personOf(line)) : personOf(line));
300
- const tagOf = (line) => [line.agent ? t('agentOf').replace('{name}', personOf(line)) : line.double ? t('double') : '', line.task ? t('task') : '']
301
- .filter(Boolean)
302
- .join(' · ');
318
+ const nameOf = (line) => (line.agent ? line.agent.name : line.double ? t('doubleOf', { name: personOf(line) }) : personOf(line));
319
+ const tagOf = (line) => [line.agent ? t('agentOf', { name: personOf(line) }) : line.double ? t('double') : '', line.task ? t('task') : ''].filter(Boolean).join(' · ');
303
320
  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 : ''}`; };
304
321
  const nodes = [];
305
322
  if (!lines.length) {
@@ -314,7 +331,7 @@ class GuestPage {
314
331
  if (separator) {
315
332
  nodes.push(div('when', guest_i18n_1.GuestI18n.time(line.at)));
316
333
  }
317
- const bubble = div('bubble', viewer_markdown_1.ViewerMarkdown.render(line.text));
334
+ const bubble = div('bubble', viewer_markdown_1.ViewerMarkdown.render(relay_room_chat_1.RelayRoomChatUtil.preview(line, t('picture'), { file: t('file'), voice: t('file'), video: t('file') })));
318
335
  bubble.title = guest_i18n_1.GuestI18n.time(line.at);
319
336
  if (line.from === self && !line.agent) {
320
337
  nodes.push(div('mine', bubble));
@@ -330,6 +347,61 @@ class GuestPage {
330
347
  list.scrollTop = list.scrollHeight;
331
348
  }
332
349
  }
350
+ /** A board of an app of the room changed: kept if its owner wrote it, and drawn over the chat. */
351
+ heardBoard(key, value, by) {
352
+ var _a, _b;
353
+ 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;
354
+ const board = relay_room_app_1.RelayBoardUtil.read(key, value, by, owner);
355
+ if (board === null || board === void 0 ? void 0 : board.items.length) {
356
+ this.boards.set(key, board);
357
+ }
358
+ else {
359
+ this.boards.delete(key);
360
+ }
361
+ this.drawBoards();
362
+ }
363
+ /** A chip for each board, how many are in progress and done; a tap opens its items. */
364
+ drawBoards() {
365
+ const bar = this.boardBar;
366
+ if (!bar) {
367
+ return;
368
+ }
369
+ const chips = [...this.boards].map(([key, board]) => {
370
+ const { open, done } = relay_room_app_1.RelayBoardUtil.counts(board);
371
+ const parts = [open ? t('boardOpen', { n: open }) : '', done ? t('boardDone', { n: done }) : ''].filter(Boolean);
372
+ const chip = button('board', [board.title, ...parts].join(' · '), () => this.showBoard(key));
373
+ if (open) {
374
+ chip.prepend(Object.assign(el('span'), { className: 'dot' }));
375
+ }
376
+ return chip;
377
+ });
378
+ bar.replaceChildren(...chips);
379
+ bar.hidden = !chips.length;
380
+ }
381
+ showBoard(key) {
382
+ var _a;
383
+ const board = this.boards.get(key);
384
+ if (!board) {
385
+ return;
386
+ }
387
+ const panel = div('panel', el('h3', board.title));
388
+ for (const item of [...board.items].reverse()) {
389
+ const label = Object.assign(el('span', item.label), { className: `lb ${item.state}` });
390
+ const head = div('hd', Object.assign(el('span', `#${item.n}`), { className: 'n' }), Object.assign(el('span', item.title), { className: 'tt' }), label);
391
+ panel.append(div('item', head, ...(item.people.length ? [div('by', t('boardFrom', { names: item.people.join('、') }))] : [])));
392
+ }
393
+ panel.append(div('sep'), button('row', t('close'), () => this.closeSheet()));
394
+ const sheet = div('sheet', panel);
395
+ sheet.addEventListener('click', event => {
396
+ if (event.target === sheet) {
397
+ this.closeSheet();
398
+ }
399
+ });
400
+ (_a = this.sheet) === null || _a === void 0 ? void 0 : _a.remove();
401
+ document.body.append(sheet);
402
+ this.sheet = sheet;
403
+ this.sheetOf = 'board';
404
+ }
333
405
  /** The members, over the chat: who is online, and the user's name and way out. */
334
406
  members() {
335
407
  var _a;
@@ -337,6 +409,7 @@ class GuestPage {
337
409
  if (!room) {
338
410
  return;
339
411
  }
412
+ this.sheetOf = 'members';
340
413
  const panel = div('panel', Object.assign(el('h3', `${t('members')} (${room.members.length})`)));
341
414
  for (const member of room.members) {
342
415
  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';
2
+ export * from './relay-chat-files';
2
3
  export * from './relay-file-storage';
3
4
  export * from './relay-files-host';
4
5
  export * from './relay-host';
package/lib/node/index.js CHANGED
@@ -15,6 +15,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("../common"), exports);
18
+ __exportStar(require("./relay-chat-files"), exports);
18
19
  __exportStar(require("./relay-file-storage"), exports);
19
20
  __exportStar(require("./relay-files-host"), exports);
20
21
  __exportStar(require("./relay-host"), exports);
@@ -0,0 +1,47 @@
1
+ import { type RelayChatState, type RelayChatStore } from '../common/relay-chat-store';
2
+ import type { RelayChatLine } from '../common/relay-room-chat';
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
+ }
47
+ //# sourceMappingURL=relay-chat-files.d.ts.map
@@ -0,0 +1,203 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RelayChatFiles = exports.RelayChatKeys = void 0;
4
+ const node_child_process_1 = require("node:child_process");
5
+ const node_crypto_1 = require("node:crypto");
6
+ const node_fs_1 = require("node:fs");
7
+ const node_path_1 = require("node:path");
8
+ const relay_chat_store_1 = require("../common/relay-chat-store");
9
+ const ROOM = /^[A-Za-z0-9_-]{1,64}$/;
10
+ const MONTH = /^\d{4}-\d{2}\.log$/;
11
+ const STATE = 'state';
12
+ /**
13
+ * The key what is said in the rooms is sealed with on this computer (docs/design/ta-chat-history.md 12): in the
14
+ * keychain of macOS (the service `Ta chats`, an account of the agent directory), elsewhere or with
15
+ * `TA_CHATS_KEY=file` in `chats/.key`, readable by the user alone. Made the first time.
16
+ */
17
+ var RelayChatKeys;
18
+ (function (RelayChatKeys) {
19
+ RelayChatKeys.SERVICE = 'Ta chats';
20
+ function local(agentDir, env = process.env, platform = process.platform) {
21
+ let key;
22
+ return () => {
23
+ key !== null && key !== void 0 ? key : (key = platform === 'darwin' && env.TA_CHATS_KEY !== 'file' ? keychain(agentDir).catch(() => file(agentDir)) : file(agentDir));
24
+ return key;
25
+ };
26
+ }
27
+ RelayChatKeys.local = local;
28
+ async function keychain(agentDir) {
29
+ const account = (0, node_crypto_1.createHash)('sha256').update(agentDir).digest('base64url').slice(0, 16);
30
+ const found = await run('security', ['find-generic-password', '-s', RelayChatKeys.SERVICE, '-a', account, '-w']);
31
+ const kept = found.code === 0 ? Buffer.from(found.stdout.trim(), 'base64') : undefined;
32
+ if ((kept === null || kept === void 0 ? void 0 : kept.length) === 32) {
33
+ return kept;
34
+ }
35
+ const made = (0, node_crypto_1.randomBytes)(32);
36
+ // Through the input of `security -i`: a key never goes in the arguments, which `ps` shows.
37
+ await run('security', ['-i'], `add-generic-password -U -s "${RelayChatKeys.SERVICE}" -a "${account}" -l "${RelayChatKeys.SERVICE}" -w "${made.toString('base64')}"\n`);
38
+ const again = await run('security', ['find-generic-password', '-s', RelayChatKeys.SERVICE, '-a', account, '-w']);
39
+ if (again.code !== 0 || Buffer.from(again.stdout.trim(), 'base64').length !== 32) {
40
+ throw new Error('The keychain did not keep the key of the chats.');
41
+ }
42
+ return Buffer.from(again.stdout.trim(), 'base64');
43
+ }
44
+ async function file(agentDir) {
45
+ const dir = (0, node_path_1.join)(agentDir, 'chats');
46
+ const path = (0, node_path_1.join)(dir, '.key');
47
+ if ((0, node_fs_1.existsSync)(path)) {
48
+ const kept = Buffer.from((0, node_fs_1.readFileSync)(path, 'utf8').trim(), 'base64');
49
+ if (kept.length === 32) {
50
+ return kept;
51
+ }
52
+ }
53
+ (0, node_fs_1.mkdirSync)(dir, { recursive: true, mode: 0o700 });
54
+ const made = (0, node_crypto_1.randomBytes)(32);
55
+ (0, node_fs_1.writeFileSync)(path, `${made.toString('base64')}\n`, { mode: 0o600 });
56
+ (0, node_fs_1.chmodSync)(path, 0o600);
57
+ return made;
58
+ }
59
+ function run(command, args, input) {
60
+ return new Promise(resolve => {
61
+ const child = (0, node_child_process_1.spawn)(command, args, { stdio: ['pipe', 'pipe', 'ignore'] });
62
+ let stdout = '';
63
+ child.stdout.on('data', chunk => {
64
+ stdout += chunk;
65
+ });
66
+ child.on('error', () => resolve({ code: -1, stdout }));
67
+ child.on('close', code => resolve({ code: code !== null && code !== void 0 ? code : -1, stdout }));
68
+ child.stdin.end(input !== null && input !== void 0 ? input : '');
69
+ });
70
+ }
71
+ })(RelayChatKeys || (exports.RelayChatKeys = RelayChatKeys = {}));
72
+ /**
73
+ * What is said in the rooms, kept in `chats/<room>/` of the agent directory (docs/design/ta-chat-history.md 8): a
74
+ * 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
75
+ * crash loses that line alone; and the state of the log (`state`), sealed, written whole. A month goes as a file.
76
+ */
77
+ class RelayChatFiles {
78
+ constructor(dir, key, now = Date.now) {
79
+ this.dir = dir;
80
+ this.key = key;
81
+ this.now = now;
82
+ /** The lines of each room read, as long as nothing was added that is not in them. */
83
+ this.cache = new Map();
84
+ }
85
+ async read(room, options) {
86
+ const months = this.months(room);
87
+ const cached = this.cache.get(room);
88
+ let read = cached !== null && cached !== void 0 ? cached : { lines: [], months: 0, all: months.length === 0 };
89
+ const enough = () => {
90
+ const end = options.before === undefined ? read.lines.length : read.lines.findIndex(line => line.id === options.before);
91
+ return end >= 0 && end - options.limit > 0;
92
+ };
93
+ while (!read.all && !enough()) {
94
+ const month = months[months.length - 1 - read.months];
95
+ const lines = await this.readMonth(room, month);
96
+ read = { lines: [...lines, ...read.lines], months: read.months + 1, all: read.months + 1 >= months.length };
97
+ }
98
+ this.cache.set(room, read);
99
+ const page = relay_chat_store_1.RelayChatStoreUtil.page(read.lines, options);
100
+ return { lines: page.lines, more: page.more || !read.all };
101
+ }
102
+ async append(room, lines) {
103
+ if (!lines.length) {
104
+ return;
105
+ }
106
+ const key = await this.key();
107
+ const dir = this.roomDir(room);
108
+ (0, node_fs_1.mkdirSync)(dir, { recursive: true, mode: 0o700 });
109
+ const date = new Date(this.now());
110
+ const month = `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}.log`;
111
+ const path = (0, node_path_1.join)(dir, month);
112
+ const fresh = !(0, node_fs_1.existsSync)(path);
113
+ (0, node_fs_1.appendFileSync)(path, lines.map(line => `${RelayChatFiles.seal(key, JSON.stringify(line))}\n`).join(''), { mode: 0o600 });
114
+ const cached = this.cache.get(room);
115
+ if (cached) {
116
+ cached.lines.push(...lines);
117
+ if (fresh) {
118
+ cached.months++;
119
+ }
120
+ }
121
+ }
122
+ async state(room) {
123
+ const path = (0, node_path_1.join)(this.roomDir(room), STATE);
124
+ if (!(0, node_fs_1.existsSync)(path)) {
125
+ return undefined;
126
+ }
127
+ const opened = RelayChatFiles.open(await this.key(), (0, node_fs_1.readFileSync)(path, 'utf8').trim());
128
+ if (!opened) {
129
+ return undefined;
130
+ }
131
+ const state = JSON.parse(opened);
132
+ return { ...state, seq: Number(state.seq) || 0, outbox: Array.isArray(state.outbox) ? state.outbox : [] };
133
+ }
134
+ async setState(room, state) {
135
+ const key = await this.key();
136
+ const dir = this.roomDir(room);
137
+ (0, node_fs_1.mkdirSync)(dir, { recursive: true, mode: 0o700 });
138
+ const path = (0, node_path_1.join)(dir, STATE);
139
+ const temporary = `${path}.${process.pid}.tmp`;
140
+ (0, node_fs_1.writeFileSync)(temporary, `${RelayChatFiles.seal(key, JSON.stringify(state))}\n`, { mode: 0o600 });
141
+ (0, node_fs_1.renameSync)(temporary, path);
142
+ }
143
+ async forget(room) {
144
+ this.cache.delete(room);
145
+ (0, node_fs_1.rmSync)(this.roomDir(room), { recursive: true, force: true });
146
+ }
147
+ roomDir(room) {
148
+ if (!ROOM.test(room)) {
149
+ throw new Error('Not a room.');
150
+ }
151
+ return (0, node_path_1.join)(this.dir, room);
152
+ }
153
+ /** The months kept of a room, the earliest first. */
154
+ months(room) {
155
+ try {
156
+ return (0, node_fs_1.readdirSync)(this.roomDir(room))
157
+ .filter(name => MONTH.test(name))
158
+ .sort();
159
+ }
160
+ catch (_a) {
161
+ return [];
162
+ }
163
+ }
164
+ async readMonth(room, month) {
165
+ const key = await this.key();
166
+ const lines = [];
167
+ for (const sealed of (0, node_fs_1.readFileSync)((0, node_path_1.join)(this.roomDir(room), month), 'utf8').split('\n')) {
168
+ const opened = sealed && RelayChatFiles.open(key, sealed);
169
+ if (opened) {
170
+ try {
171
+ lines.push(JSON.parse(opened));
172
+ }
173
+ catch (_a) {
174
+ // A line cut short: that line alone is lost.
175
+ }
176
+ }
177
+ }
178
+ return lines;
179
+ }
180
+ /** base64url of a nonce of 12 bytes, the text sealed and its tag. */
181
+ static seal(key, text) {
182
+ const iv = (0, node_crypto_1.randomBytes)(12);
183
+ const cipher = (0, node_crypto_1.createCipheriv)('aes-256-gcm', key, iv);
184
+ const sealed = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
185
+ return Buffer.concat([iv, sealed, cipher.getAuthTag()]).toString('base64url');
186
+ }
187
+ static open(key, sealed) {
188
+ try {
189
+ const bytes = Buffer.from(sealed, 'base64url');
190
+ if (bytes.length < 28) {
191
+ return undefined;
192
+ }
193
+ const decipher = (0, node_crypto_1.createDecipheriv)('aes-256-gcm', key, bytes.subarray(0, 12));
194
+ decipher.setAuthTag(bytes.subarray(bytes.length - 16));
195
+ return Buffer.concat([decipher.update(bytes.subarray(12, bytes.length - 16)), decipher.final()]).toString('utf8');
196
+ }
197
+ catch (_a) {
198
+ return undefined;
199
+ }
200
+ }
201
+ }
202
+ exports.RelayChatFiles = RelayChatFiles;
203
+ //# sourceMappingURL=relay-chat-files.js.map
@@ -1,8 +1,18 @@
1
+ import type { RelayChatStore } from '../common/relay-chat-store';
1
2
  import type { RelayHubsStore, RelayHubsStoreName } from '../common/relay-hubs-protocol';
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. */
@@ -4,10 +4,17 @@ exports.RelayHubFiles = void 0;
4
4
  const node_fs_1 = require("node:fs");
5
5
  const node_os_1 = require("node:os");
6
6
  const node_path_1 = require("node:path");
7
+ const relay_chat_files_1 = require("./relay-chat-files");
7
8
  /** What the rooms of a Ta keep, as files of its agent directory readable by the user alone: `identity.json`, `rooms.json`, `friends.json`. */
8
9
  class RelayHubFiles {
9
- constructor(agentDir) {
10
+ constructor(agentDir,
11
+ /** What is said in the rooms is kept in `chats/`, sealed with the key of the keychain (RelayChatKeys); else in memory. */
12
+ options = {}) {
10
13
  this.agentDir = agentDir;
14
+ this.options = options;
15
+ }
16
+ chats() {
17
+ return this.options.chats ? new relay_chat_files_1.RelayChatFiles((0, node_path_1.join)(this.agentDir, 'chats'), relay_chat_files_1.RelayChatKeys.local(this.agentDir)) : undefined;
11
18
  }
12
19
  file(name) {
13
20
  return (0, node_path_1.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';
6
6
  import { RelayBlobs } from '../common/relay-blobs';
7
7
  import { RelayHub, type RelayHubWho } from '../common/relay-hub';
8
+ import { type RelayMedia } from '../common/relay-info';
8
9
  import { RelayRoom } from '../common/relay-room';
9
10
  import { RelaySpot, type RelaySpotSocket, type RelaySpotWho } from '../common/relay-spot';
10
11
  import { FileRelayStorage } from './relay-file-storage';
@@ -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;
@@ -96,7 +96,7 @@ class RelayServer {
96
96
  }
97
97
  if (path === relay_info_1.RELAY_INFO_PATH) {
98
98
  // Without a directory for its data, rooms and copies live in memory: gone when the relay restarts.
99
- const info = relay_info_1.RelayInfoUtil.of(!!this.options.data);
99
+ const info = relay_info_1.RelayInfoUtil.of(!!this.options.data, this.options.media);
100
100
  response.writeHead(200, { 'content-type': 'application/json', 'access-control-allow-origin': '*', 'cache-control': 'no-store' });
101
101
  response.end(JSON.stringify(info));
102
102
  return;
@@ -105,8 +105,15 @@ class RelayServer {
105
105
  this.accounts.serve(request, response);
106
106
  return;
107
107
  }
108
- if (path.startsWith(relay_protocol_1.RELAY_BLOB_PATH)) {
109
- this.blob(path.slice(relay_protocol_1.RELAY_BLOB_PATH.length), request, response).catch(() => {
108
+ const media = path.startsWith(relay_protocol_1.RELAY_MEDIA_PATH);
109
+ if (media && !this.options.media) {
110
+ // Its operator lets it keep no pictures of chats.
111
+ response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }).end('Not found.\n');
112
+ return;
113
+ }
114
+ if (path.startsWith(relay_protocol_1.RELAY_BLOB_PATH) || media) {
115
+ const id = path.slice((media ? relay_protocol_1.RELAY_MEDIA_PATH : relay_protocol_1.RELAY_BLOB_PATH).length);
116
+ this.blob(id, request, response, media ? this.options.media : undefined).catch(() => {
110
117
  // A request aborted or that failed: an unhandled rejection would end the relay.
111
118
  if (!response.headersSent) {
112
119
  response.writeHead(400);
@@ -197,37 +204,40 @@ class RelayServer {
197
204
  return new Promise(resolve => (this.server ? this.server.close(() => resolve()) : resolve()));
198
205
  }
199
206
  /** A copy of content (RelayBlobs), kept in memory for as long as the relay runs. */
200
- async blob(id, request, response) {
201
- var _a;
207
+ async blob(id, request, response, media) {
208
+ var _a, _b;
202
209
  if (!relay_protocol_1.RELAY_ID.test(id)) {
203
210
  response.writeHead(404).end();
204
211
  return;
205
212
  }
206
- const read = await RelayServer.body(request, relay_blobs_1.RelayBlobs.MAX_BYTES);
213
+ const limits = media && relay_blobs_1.RelayBlobsUtil.limitsOf(media);
214
+ const read = await RelayServer.body(request, (_a = limits === null || limits === void 0 ? void 0 : limits.bytes) !== null && _a !== void 0 ? _a : relay_blobs_1.RelayBlobs.MAX_BYTES);
207
215
  if (!read) {
208
216
  // Refused before it is all in memory, whatever its content-length said.
209
217
  response.writeHead(413, { connection: 'close' }).end('Too large.\n');
210
218
  return;
211
219
  }
212
220
  // Kept only while it holds a copy: requests for ids of no copy leave nothing behind.
213
- const copy = this.blobCopy(id);
221
+ const key = media ? `media-${id}` : id;
222
+ const copy = this.blobCopy(key);
214
223
  const headers = new Headers();
215
224
  for (const [name, value] of Object.entries(request.headers)) {
216
225
  if (typeof value === 'string') {
217
226
  headers.set(name, value);
218
227
  }
219
228
  }
220
- const method = (_a = request.method) !== null && _a !== void 0 ? _a : 'GET';
229
+ const method = (_b = request.method) !== null && _b !== void 0 ? _b : 'GET';
221
230
  const body = read.length && method !== 'GET' && method !== 'HEAD' ? read : undefined;
222
231
  copy.pending++;
223
232
  let answer;
224
233
  try {
225
- answer = await copy.blobs.handle(new Request(`http://relay${request.url}`, { method, headers, body }));
234
+ headers.delete(relay_blobs_1.RelayBlobsUtil.LIMITS_HEADER);
235
+ answer = await copy.blobs.handle(new Request(`http://relay${request.url}`, { method, headers, body }), limits);
226
236
  }
227
237
  finally {
228
238
  copy.pending--;
229
- if (copy.pending === 0 && copy.storage.empty && this.blobs.get(id) === copy) {
230
- this.blobs.delete(id);
239
+ if (copy.pending === 0 && copy.storage.empty && this.blobs.get(key) === copy) {
240
+ this.blobs.delete(key);
231
241
  }
232
242
  }
233
243
  response.writeHead(answer.status, Object.fromEntries(answer.headers));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/ta-relay",
3
- "version": "4.21.0",
3
+ "version": "4.23.0",
4
4
  "description": "Ta from anywhere: a relay that only forwards, and end-to-end encryption between a paired device and ta serve",
5
5
  "homepage": "https://github.com/cellbang/ta",
6
6
  "bugs": {
@@ -30,8 +30,8 @@
30
30
  "watch": "tsc -b -w --preserveWatchOutput"
31
31
  },
32
32
  "dependencies": {
33
- "@celljs/rpc": "4.21.0",
34
- "@celljs/ta-protocol": "4.21.0"
33
+ "@celljs/rpc": "4.23.0",
34
+ "@celljs/ta-protocol": "4.23.0"
35
35
  },
36
36
  "publishConfig": {
37
37
  "access": "public"