@celljs/ta-relay 4.22.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 (80) hide show
  1. package/esm/common/index.d.ts +2 -0
  2. package/esm/common/index.js +2 -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 +2 -0
  8. package/esm/common/relay-hub-charter.js +3 -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 +2 -2
  21. package/esm/common/relay-hubs.js +13 -11
  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-chat.d.ts +126 -4
  27. package/esm/common/relay-room-chat.js +230 -6
  28. package/esm/guest/guest-i18n.d.ts +2 -0
  29. package/esm/guest/guest-i18n.js +8 -0
  30. package/esm/guest/guest.js +8 -5
  31. package/esm/node/index.d.ts +1 -0
  32. package/esm/node/index.js +1 -0
  33. package/esm/node/relay-chat-files.d.ts +46 -0
  34. package/esm/node/relay-chat-files.js +199 -0
  35. package/esm/node/relay-hub-files.d.ts +11 -1
  36. package/esm/node/relay-hub-files.js +8 -1
  37. package/esm/node/relay-server.d.ts +7 -1
  38. package/esm/node/relay-server.js +23 -13
  39. package/lib/common/index.d.ts +2 -0
  40. package/lib/common/index.js +2 -0
  41. package/lib/common/relay-blobs.d.ts +36 -2
  42. package/lib/common/relay-blobs.js +34 -6
  43. package/lib/common/relay-chat-store.d.ts +60 -0
  44. package/lib/common/relay-chat-store.js +44 -0
  45. package/lib/common/relay-hub-charter.d.ts +2 -0
  46. package/lib/common/relay-hub-charter.js +3 -0
  47. package/lib/common/relay-hub-log.d.ts +66 -0
  48. package/lib/common/relay-hub-log.js +151 -0
  49. package/lib/common/relay-hub.d.ts +3 -0
  50. package/lib/common/relay-hub.js +18 -0
  51. package/lib/common/relay-hubs-admins.d.ts +1 -0
  52. package/lib/common/relay-hubs-admins.js +9 -5
  53. package/lib/common/relay-hubs-chats.d.ts +67 -0
  54. package/lib/common/relay-hubs-chats.js +346 -0
  55. package/lib/common/relay-hubs-connection.d.ts +3 -1
  56. package/lib/common/relay-hubs-connection.js +7 -0
  57. package/lib/common/relay-hubs-protocol.d.ts +14 -0
  58. package/lib/common/relay-hubs.d.ts +2 -2
  59. package/lib/common/relay-hubs.js +13 -11
  60. package/lib/common/relay-info.d.ts +23 -1
  61. package/lib/common/relay-info.js +26 -3
  62. package/lib/common/relay-protocol.d.ts +60 -1
  63. package/lib/common/relay-protocol.js +16 -1
  64. package/lib/common/relay-room-chat.d.ts +126 -4
  65. package/lib/common/relay-room-chat.js +231 -7
  66. package/lib/guest/guest-i18n.d.ts +2 -0
  67. package/lib/guest/guest-i18n.js +8 -0
  68. package/lib/guest/guest.js +7 -4
  69. package/lib/node/index.d.ts +1 -0
  70. package/lib/node/index.js +1 -0
  71. package/lib/node/relay-chat-files.d.ts +47 -0
  72. package/lib/node/relay-chat-files.js +203 -0
  73. package/lib/node/relay-hub-files.d.ts +11 -1
  74. package/lib/node/relay-hub-files.js +8 -1
  75. package/lib/node/relay-server.d.ts +7 -1
  76. package/lib/node/relay-server.js +21 -11
  77. package/package.json +3 -3
  78. package/viewer/join.html +4 -4
  79. package/viewer/page.html +10 -10
  80. package/viewer/room.html +15 -15
@@ -13,6 +13,8 @@ const zh = {
13
13
  namePlaceholder: '大家看到的名字',
14
14
  join: '申请加入',
15
15
  joining: '正在申请…',
16
+ picture: '[图片,在 Ta 里看]',
17
+ file: '[文件、语音或视频,在 Ta 里看]',
16
18
  keep: '你的名字和一把只属于这个浏览器的钥匙保存在本机;清除浏览器数据后要重新申请。',
17
19
  haveTa: '装了 Ta?在 Ta 应用里扫码或粘贴这个链接,还能一起玩小镇等游戏。',
18
20
  waiting: '已向{by}申请',
@@ -61,6 +63,8 @@ const zhTw = {
61
63
  namePlaceholder: '大家看到的名字',
62
64
  join: '申請加入',
63
65
  joining: '正在申請…',
66
+ picture: '[圖片,在 Ta 裡看]',
67
+ file: '[檔案、語音或影片,在 Ta 裡看]',
64
68
  keep: '你的名字和一把只屬於這個瀏覽器的鑰匙儲存在本機;清除瀏覽器資料後要重新申請。',
65
69
  haveTa: '裝了 Ta?在 Ta 應用裡掃碼或貼上這個連結,還能一起玩小鎮等遊戲。',
66
70
  waiting: '已向{by}申請',
@@ -109,6 +113,8 @@ const en = {
109
113
  namePlaceholder: 'What everyone sees',
110
114
  join: 'Ask to join',
111
115
  joining: 'Asking…',
116
+ picture: '[Picture: see it in Ta]',
117
+ file: '[File, voice or video: see it in Ta]',
112
118
  keep: 'Your name and a key of this browser alone are kept on this device; clear its data and you ask again.',
113
119
  haveTa: 'Have Ta? Scan this link in the Ta app or paste it there, to play the Town and other games together too.',
114
120
  waiting: 'Asked {by}',
@@ -157,6 +163,8 @@ const ja = {
157
163
  namePlaceholder: 'みんなに見える名前',
158
164
  join: '参加をリクエスト',
159
165
  joining: 'リクエスト中…',
166
+ picture: '[画像:Ta で表示]',
167
+ file: '[ファイル・ボイス・動画:Ta で表示]',
160
168
  keep: 'あなたの名前とこのブラウザ専用のキーはこのデバイスに保存されます。ブラウザデータをクリアすると再度リクエストが必要です。',
161
169
  haveTa: 'Ta をインストール済みですか?Ta アプリでこのリンクをスキャンするかペーストして、タウンなどのゲームも一緒にプレイできます。',
162
170
  waiting: '{by}さんにリクエスト済み',
@@ -101,9 +101,12 @@ class GuestPage {
101
101
  }
102
102
  start() {
103
103
  this.hubs.onEvent(event => {
104
- var _a;
105
- if (event.type === 'state' && event.room === this.link.room) {
106
- (_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);
107
110
  if (event.key.startsWith(relay_room_app_1.RELAY_BOARD_KEY)) {
108
111
  this.heardBoard(event.key, event.value, event.by);
109
112
  }
@@ -328,7 +331,7 @@ class GuestPage {
328
331
  if (separator) {
329
332
  nodes.push(div('when', guest_i18n_1.GuestI18n.time(line.at)));
330
333
  }
331
- 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') })));
332
335
  bubble.title = guest_i18n_1.GuestI18n.time(line.at);
333
336
  if (line.from === self && !line.agent) {
334
337
  nodes.push(div('mine', bubble));
@@ -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.22.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.22.0",
34
- "@celljs/ta-protocol": "4.22.0"
33
+ "@celljs/rpc": "4.23.0",
34
+ "@celljs/ta-protocol": "4.23.0"
35
35
  },
36
36
  "publishConfig": {
37
37
  "access": "public"