ai_co_discuss 0.3.46 → 0.3.49

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 (43) hide show
  1. package/.agents/skills/discuss-host/SKILL.md +1 -0
  2. package/.agents/skills/discuss-host/references/discussion.md +113 -113
  3. package/.agents/skills/discuss-host/references/free.md +36 -34
  4. package/.agents/skills/discuss-host/references/goal.md +35 -0
  5. package/.agents/skills/discuss-participant/SKILL.md +1 -0
  6. package/.agents/skills/workflow-creator/SKILL.md +2 -2
  7. package/README.md +3 -1
  8. package/backend/admin.py +104 -35
  9. package/backend/free_room.py +2170 -2136
  10. package/backend/goal_room.py +358 -0
  11. package/backend/mode_room.py +105 -0
  12. package/backend/schema.sql +1593 -1510
  13. package/backend/server.py +2636 -2555
  14. package/backend/session_room.py +1180 -1148
  15. package/docs/THIRD_PARTY_NOTICES.md +1293 -1264
  16. package/docs/deployment.md +5 -1
  17. package/docs/en/workflow.md +15 -1
  18. package/docs/runner.md +28 -7
  19. package/docs/workflow.md +15 -1
  20. package/package.json +3 -2
  21. package/runner/adapters/api.mjs +333 -313
  22. package/runner/adapters/claude.mjs +12 -16
  23. package/runner/admin_account.mjs +12 -19
  24. package/runner/device_auth.mjs +369 -0
  25. package/runner/discuss.py +1208 -1125
  26. package/runner/discussion_launch.mjs +107 -12
  27. package/runner/discussion_service.mjs +25 -1
  28. package/runner/expert_prompts.mjs +132 -132
  29. package/runner/free_runner.mjs +982 -910
  30. package/runner/pinyin_table.mjs +406 -0
  31. package/runner/project_files.mjs +52 -3
  32. package/runner/relay_channel.mjs +51 -7
  33. package/runner/remote_launch.mjs +221 -235
  34. package/runner/remote_policy.mjs +156 -0
  35. package/runner/scheduler.mjs +459 -429
  36. package/runner/stt.mjs +2 -2
  37. package/runner/tts.mjs +74 -113
  38. package/runner/tts_providers.mjs +205 -0
  39. package/runner/webauthn.mjs +155 -0
  40. package/runner/workflows.mjs +371 -348
  41. package/web/app.js +355 -51
  42. package/web/modern.css +1 -1
  43. package/web/modern.js +5764 -3816
@@ -78,28 +78,24 @@ export function claude_denials(output) {
78
78
  }
79
79
 
80
80
  /**
81
- * Drop variables a hosting Claude session injects, so the spawned CLI uses its own login.
82
- * The host also hides the user's persisted login variables, which are read back on Windows.
81
+ * The environment for one spawned Claude CLI: variables a hosting Claude session injects are dropped, and the user's
82
+ * persisted login variables, read afresh on Windows, override the ones this long-running process inherited at start,
83
+ * so a token switched with setx or the system settings takes effect on the next turn without restarting the runner.
83
84
  */
84
85
  export function standalone_claude_env(env = process.env, persisted = persisted_claude_env) {
85
- if (env.CLAUDECODE !== '1') return env;
86
- const own = Object.entries(env).filter(([key]) =>
87
- !/^(CLAUDECODE|CLAUDE_PID|CLAUDE_EFFORT)$|^(CLAUDE_CODE_|CLAUDE_AGENT_SDK_|CLAUDE_PREVIEW_)/.test(key));
88
- return { ...Object.fromEntries(own), ...persisted() };
86
+ const own = env.CLAUDECODE !== '1' ? env : Object.fromEntries(Object.entries(env).filter(([key]) =>
87
+ !/^(CLAUDECODE|CLAUDE_PID|CLAUDE_EFFORT)$|^(CLAUDE_CODE_|CLAUDE_AGENT_SDK_|CLAUDE_PREVIEW_)/.test(key)));
88
+ return { ...own, ...persisted() };
89
89
  }
90
90
 
91
- let persisted_cache;
92
- /** Read Machine then User persisted ANTHROPIC_/CLAUDE variables once; values stay in memory only. */
91
+ /** Read Machine then User persisted ANTHROPIC_/CLAUDE variables on every call; values stay in memory only. */
93
92
  function persisted_claude_env() {
94
93
  if (process.platform !== 'win32') return {};
95
- if (!persisted_cache) {
96
- const script = "$r=@{}; foreach($s in 'Machine','User'){ $v=[Environment]::GetEnvironmentVariables($s);"
97
- + " foreach($k in $v.Keys){ if($k -match '^(ANTHROPIC_|CLAUDE)'){ $r[$k]=$v[$k] } } }; $r | ConvertTo-Json -Compress";
98
- const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf8', windowsHide: true });
99
- try { persisted_cache = result.status === 0 && result.stdout.trim() ? JSON.parse(result.stdout) : {}; }
100
- catch { persisted_cache = {}; }
101
- }
102
- return persisted_cache;
94
+ const script = "$r=@{}; foreach($s in 'Machine','User'){ $v=[Environment]::GetEnvironmentVariables($s);"
95
+ + " foreach($k in $v.Keys){ if($k -match '^(ANTHROPIC_|CLAUDE)'){ $r[$k]=$v[$k] } } }; $r | ConvertTo-Json -Compress";
96
+ const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf8', windowsHide: true });
97
+ try { return result.status === 0 && result.stdout.trim() ? JSON.parse(result.stdout) : {}; }
98
+ catch { return {}; }
103
99
  }
104
100
 
105
101
  /** Claude permission rules match Windows paths in POSIX form, e.g. C:\a becomes //c/a. */
@@ -1,23 +1,20 @@
1
- /** Site administrator setup from the deploying computer: a one-time registration token and the saved account. */
1
+ /** Site administrator setup from the deploying computer: a one-time registration token. */
2
2
  import { spawnSync } from 'node:child_process';
3
3
  import { createHash, randomBytes } from 'node:crypto';
4
- import { existsSync, mkdirSync, readFileSync } from 'node:fs';
4
+ import { existsSync, rmSync } from 'node:fs';
5
5
  import { join, resolve } from 'node:path';
6
6
  import { parseArgs } from 'node:util';
7
7
 
8
- import { atomic_json } from './files.mjs';
9
- import { service_home } from './discussion_service.mjs';
10
-
11
8
  const DEFAULT_CONFIG = join('.wrangler', 'deploy', 'wrangler.jsonc');
12
- const ACCOUNTS_FILE = 'admin-accounts.json';
9
+ // Older versions kept the administrator password here in plain text; it is deleted and never written again.
10
+ const LEGACY_ACCOUNTS_FILE = 'admin-accounts.json';
13
11
  const TOKEN_BYTES = 32;
14
12
  const HELP = `用法:codiscuss token [--config WRANGLER_CONFIG]
15
13
 
16
14
  生成一次性管理员注册令牌,经 wrangler 把它的哈希写入线上 D1,立即生效。
17
15
  在线上网页左下角注册管理员时填入;注册成功即作废,重新运行会替换旧令牌。
18
16
  需要这台电脑已 wrangler login;--config 默认为当前目录的 ${DEFAULT_CONFIG}。
19
-
20
- 在已用 codiscuss local connect 连上本机服务的网页注册后,账号与密码保存在 ~/.codiscuss/${ACCOUNTS_FILE}。
17
+ 管理员密码只由你自己保管,本机不保存。
21
18
  `;
22
19
 
23
20
  /** Write a fresh token's hash to the deployed D1 and return the token; the raw value is never stored. */
@@ -39,16 +36,12 @@ function run_wrangler(args) {
39
36
  if (result.status !== 0) throw new Error(`wrangler 写入线上数据库失败:${(result.stderr || result.error?.message || '').trim().slice(-800)}`);
40
37
  }
41
38
 
42
- /** Keep the account registered from this computer's browser, one entry per site, in the private service directory. */
43
- export function save_admin_account(home, { site, username, password }) {
44
- if (typeof username !== 'string' || !username.trim() || typeof password !== 'string' || !password) throw new Error('缺少管理员用户名或密码');
45
- const origin = new URL(site).origin;
46
- const path = join(home, ACCOUNTS_FILE);
47
- const accounts = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : { sites: {} };
48
- accounts.sites[origin] = { username: username.trim(), password, saved_at: new Date().toISOString() };
49
- mkdirSync(home, { recursive: true, mode: 0o700 });
50
- atomic_json(path, accounts);
51
- return { saved: path };
39
+ /** Delete the plain-text administrator password an older version saved; returns whether a file was removed. */
40
+ export function remove_legacy_admin_accounts(home) {
41
+ const path = join(home, LEGACY_ACCOUNTS_FILE);
42
+ if (!existsSync(path)) return false;
43
+ rmSync(path, { force: true });
44
+ return true;
52
45
  }
53
46
 
54
47
  /** `codiscuss token [--config FILE]` */
@@ -58,5 +51,5 @@ export function admin_main(args) {
58
51
  } });
59
52
  if (values.help || positionals.length) return process.stdout.write(HELP);
60
53
  const { token } = create_admin_token(values.config);
61
- process.stdout.write(`管理员注册令牌(一次性):\n${token}\n\n在线上网页左下角注册管理员时填入。注册成功后作废;账号密码在已连接本机服务的网页注册时保存到 ${join(service_home(), ACCOUNTS_FILE)}。\n`);
54
+ process.stdout.write(`管理员注册令牌(一次性):\n${token}\n\n在线上网页左下角注册管理员时填入。注册成功后作废;管理员密码只由你自己保管,本机不保存。\n`);
62
55
  }
@@ -0,0 +1,369 @@
1
+ /**
2
+ * Which browsers this computer trusts, decided here alone (see .dev/plans/远程访问安全加固/PROTOCOL.md): pairing by a
3
+ * code shown on a trusted screen, a signature on every relayed command, passkeys kept per device, and per-room write
4
+ * grants. The website only forwards; nothing it stores can add a device or a grant.
5
+ */
6
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
7
+ import { appendFileSync, existsSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+
10
+ import { atomic_json } from './files.mjs';
11
+ import { b64url, from_b64url, joint_challenge, verify_assertion, verify_registration } from './webauthn.mjs';
12
+
13
+ const DEVICES_FILE = 'devices.json';
14
+ // What other devices did here: trust changes and every remote write, never content. Shown in the device list, so an
15
+ // unexpected entry (a device you did not add, a write you did not make) can be noticed and revoked.
16
+ const AUDIT_FILE = 'device-audit.log';
17
+ const AUDIT_MAX_BYTES = 1024 * 1024;
18
+ const AUDIT_SHOWN = 50;
19
+ const LOCK_FILE = 'devices.lock';
20
+ const LOCK_WAIT_MS = 3000;
21
+ const LOCK_STALE_MS = 10000;
22
+ const DAY_MS = 86400000;
23
+ export const DEVICE_DAYS = 30;
24
+ const TEMPORARY_DAYS = 1;
25
+ // An expired device may still renew itself with its passkey for this long; after that it pairs again.
26
+ const RENEW_GRACE_DAYS = 30;
27
+ export const WRITE_GRANT_MS = 12 * 3600000;
28
+ const PAIRING_MS = 120000;
29
+ const PAIRING_ATTEMPTS = 5;
30
+ const CHALLENGE_MS = 120000;
31
+ // A passkey is added only in the minutes after pairing, while the user is at it; later, a script running in the page
32
+ // could otherwise add its own and use it to grant itself writing.
33
+ const PASSKEY_SETUP_MS = 10 * 60000;
34
+ const LABEL_LIMIT = 60;
35
+ // Crockford base32 without I, L, O, U: 12 characters carry 60 random bits.
36
+ const CODE_ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
37
+ const CODE_LENGTH = 12;
38
+ const PAIR_CONTEXT = 'codiscuss-pair-v1';
39
+ // What an expired (not yet removed) device may still ask for: only to renew itself.
40
+ const EXPIRED_ACTIONS = new Set(['passkey-challenge', 'device-renew']);
41
+ // The one action an unpaired browser may send, unsigned: proving it holds a pairing code.
42
+ export const UNSIGNED_ACTIONS = new Set(['device-pair']);
43
+ // Device actions answered by this module rather than the launch entrypoint.
44
+ export const DEVICE_ACTIONS = new Set(['device-pair', 'device-pairing', 'device-list', 'device-revoke', 'passkey-options', 'passkey-register',
45
+ 'passkey-challenge', 'device-renew', 'write-grant', 'write-revoke']);
46
+
47
+ /** Wait briefly for the registry lock: the service and short-lived launch processes both update it. */
48
+ function with_lock(home, task) {
49
+ const path = join(home, LOCK_FILE), deadline = Date.now() + LOCK_WAIT_MS;
50
+ for (;;) {
51
+ try { writeFileSync(path, String(process.pid), { flag: 'wx' }); break; } catch (error) {
52
+ if (error.code !== 'EEXIST') throw error;
53
+ try { if (Date.now() - statSync(path).mtimeMs > LOCK_STALE_MS) { rmSync(path, { force: true }); continue; } } catch { continue; }
54
+ if (Date.now() > deadline) throw new Error('设备登记表正被占用,请稍后重试');
55
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
56
+ }
57
+ }
58
+ try {
59
+ const file = join(home, DEVICES_FILE);
60
+ const registry = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : {};
61
+ registry.devices ||= {}; registry.pairings ||= {}; registry.challenges ||= {}; registry.write_grants ||= {};
62
+ const now = Date.now();
63
+ // Drop what has expired so the file stays small and nothing stale can be used.
64
+ for (const [key, item] of Object.entries(registry.pairings)) if (item.expires_at <= now) delete registry.pairings[key];
65
+ for (const [key, item] of Object.entries(registry.challenges)) if (item.expires_at <= now) delete registry.challenges[key];
66
+ for (const [key, device] of Object.entries(registry.devices)) if (device.expires_at + RENEW_GRACE_DAYS * DAY_MS <= now) delete registry.devices[key];
67
+ for (const [device, rooms] of Object.entries(registry.write_grants)) {
68
+ for (const [room, until] of Object.entries(rooms)) if (until <= now || !registry.devices[device]) delete rooms[room];
69
+ if (!Object.keys(rooms).length) delete registry.write_grants[device];
70
+ }
71
+ // Saved even when the task refuses: a used challenge or a counted failure must not come back.
72
+ try { return task(registry, now); } finally { atomic_json(file, registry); }
73
+ } finally { rmSync(path, { force: true }); }
74
+ }
75
+
76
+ /** Append one audit entry; the log keeps one older generation when it grows past its limit. */
77
+ export function audit(home, entry) {
78
+ const path = join(home, AUDIT_FILE);
79
+ try {
80
+ if (existsSync(path) && statSync(path).size > AUDIT_MAX_BYTES) renameSync(path, `${path}.1`);
81
+ appendFileSync(path, `${JSON.stringify({ at: Date.now(), ...entry })}\n`, { mode: 0o600 });
82
+ } catch { /* An unwritable log never blocks the operation it records. */ }
83
+ }
84
+
85
+ /** The most recent audit entries, newest first. */
86
+ export function recent_audit(home, limit = AUDIT_SHOWN) {
87
+ const path = join(home, AUDIT_FILE);
88
+ if (!existsSync(path)) return [];
89
+ return readFileSync(path, 'utf8').trim().split('\n').filter(Boolean).slice(-limit).reverse()
90
+ .map(line => { try { return JSON.parse(line); } catch { return null; } }).filter(Boolean);
91
+ }
92
+
93
+ /** Read the registry without changing it. */
94
+ function read_registry(home) {
95
+ const file = join(home, DEVICES_FILE);
96
+ const registry = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : {};
97
+ return { devices: registry.devices || {}, write_grants: registry.write_grants || {} };
98
+ }
99
+
100
+ /** The uncompressed P-256 point of a JWK, which names the device. */
101
+ function raw_point(jwk) {
102
+ if (jwk?.kty !== 'EC' || jwk.crv !== 'P-256') throw new Error('设备公钥须为 P-256');
103
+ const x = from_b64url(jwk.x), y = from_b64url(jwk.y);
104
+ if (x.length !== 32 || y.length !== 32) throw new Error('设备公钥格式无效');
105
+ return Uint8Array.from([4, ...x, ...y]);
106
+ }
107
+
108
+ /** A device's id: the first 32 hex characters of SHA-256 of its raw public key. */
109
+ export function device_id_of(jwk) {
110
+ return createHash('sha256').update(raw_point(jwk)).digest('hex').slice(0, 32);
111
+ }
112
+
113
+ /** Keep a short label for the list; it is shown, never trusted. */
114
+ const clean_label = value => String(value || '').replace(/[\u0000-\u001f]/g, ' ').trim().slice(0, LABEL_LIMIT) || '未命名设备';
115
+
116
+ /** Upper-case a typed code and drop separators. */
117
+ const normal_code = value => String(value || '').toUpperCase().replace(/[^0-9A-Z]/g, '');
118
+
119
+ /** The proof a new browser sends: the code authenticates its public key for one computer. */
120
+ export function pairing_proof(code, machine_id, jwk) {
121
+ return createHmac('sha256', normal_code(code)).update(`${PAIR_CONTEXT}\n${machine_id}\n${b64url(raw_point(jwk))}`).digest('base64url');
122
+ }
123
+
124
+ /** Start a pairing from a trusted screen: a 12-character code, valid two minutes, and the link a camera can open. */
125
+ export function start_pairing(home, { site, temporary = false, by = 'computer' }) {
126
+ const bytes = randomBytes(CODE_LENGTH);
127
+ const code = Array.from(bytes, byte => CODE_ALPHABET[byte & 31]).join('');
128
+ audit(home, { event: 'pairing.started', by, temporary: Boolean(temporary) });
129
+ return with_lock(home, (registry, now) => {
130
+ const id = randomBytes(8).toString('hex');
131
+ registry.pairings[id] = { code, temporary: Boolean(temporary), by, expires_at: now + PAIRING_MS, failures: 0 };
132
+ return { code: `${code.slice(0, 4)}-${code.slice(4, 8)}-${code.slice(8)}`, expires_at: now + PAIRING_MS, temporary: Boolean(temporary),
133
+ ...(site ? { url: `${site}/#pair=${code}` } : {}) };
134
+ });
135
+ }
136
+
137
+ /** Record a paired device: thirty days, or one day for a temporary one. */
138
+ function add_device(registry, now, { public_key, label, temporary, by }) {
139
+ const id = device_id_of(public_key);
140
+ registry.devices[id] = { public_key: { kty: 'EC', crv: 'P-256', x: public_key.x, y: public_key.y }, label: clean_label(label), by,
141
+ temporary: Boolean(temporary), created_at: now, expires_at: now + (temporary ? TEMPORARY_DAYS : DEVICE_DAYS) * DAY_MS, passkeys: [] };
142
+ return { device_id: id, expires_at: registry.devices[id].expires_at, temporary: Boolean(temporary) };
143
+ }
144
+
145
+ /** A new browser proves it holds a live code; a wrong proof counts against every waiting code. */
146
+ export function pair_device(home, machine_id, { public_key, label, proof }) {
147
+ if (typeof proof !== 'string' || !proof) throw new Error('缺少配对证明');
148
+ device_id_of(public_key);
149
+ const paired = with_lock(home, (registry, now) => {
150
+ const supplied = Buffer.from(proof);
151
+ for (const [id, pairing] of Object.entries(registry.pairings)) {
152
+ const expected = Buffer.from(pairing_proof(pairing.code, machine_id, public_key));
153
+ if (expected.length === supplied.length && timingSafeEqual(expected, supplied)) {
154
+ delete registry.pairings[id];
155
+ const added = add_device(registry, now, { public_key, label, temporary: pairing.temporary, by: pairing.by });
156
+ audit(home, { event: 'device.paired', device: added.device_id, label: clean_label(label), by: pairing.by, temporary: pairing.temporary });
157
+ return added;
158
+ }
159
+ }
160
+ // The failure is saved before refusing, so guesses stay limited.
161
+ for (const [id, pairing] of Object.entries(registry.pairings)) if (++pairing.failures >= PAIRING_ATTEMPTS) delete registry.pairings[id];
162
+ return null;
163
+ });
164
+ if (!paired) throw new Error('配对码不对或已过期,请在已配对的设备上重新生成');
165
+ return paired;
166
+ }
167
+
168
+ /**
169
+ * Open one relayed request: a paired device's signature over `id + "\n" + body` is checked against its registered key.
170
+ * Returns { request, device_id }; an unsigned request is accepted only for pairing.
171
+ */
172
+ export async function open_signed_request(home, id, sealed, machine_id) {
173
+ if (typeof sealed?.body !== 'string') throw new Error('请更新网页后重试:这台电脑只接受已配对设备签名的请求');
174
+ const request = JSON.parse(sealed.body);
175
+ if (!sealed.device_id) {
176
+ if (!UNSIGNED_ACTIONS.has(request.action)) throw Object.assign(new Error('这台设备还没有与电脑配对'), { need: 'pairing' });
177
+ return { request, device_id: null };
178
+ }
179
+ const device = read_registry(home).devices[sealed.device_id];
180
+ if (!device) throw Object.assign(new Error('这台设备未配对或已被撤销,请重新配对'), { need: 'pairing' });
181
+ const key = await crypto.subtle.importKey('jwk', device.public_key, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']);
182
+ const valid = await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, from_b64url(sealed.signature), new TextEncoder().encode(`${id}\n${sealed.body}`));
183
+ if (!valid) throw new Error('设备签名无效');
184
+ // The signature names the computer it was meant for, so a request cannot be passed on to another paired computer.
185
+ if (request.machine !== machine_id) throw new Error('这条请求是发给另一台电脑的');
186
+ if (device.expires_at <= Date.now() && !EXPIRED_ACTIONS.has(request.action)) {
187
+ throw Object.assign(new Error(device.temporary ? '临时设备授权已到期,请重新配对' : '设备授权已到期,请用通行密钥续期'), { need: device.temporary ? 'pairing' : 'renew' });
188
+ }
189
+ return { request, device_id: sealed.device_id };
190
+ }
191
+
192
+ /** Whether a device holds a live write grant for a room. */
193
+ export function write_allowed(home, device_id, room_id, now = Date.now()) {
194
+ const until = read_registry(home).write_grants[device_id]?.[room_id];
195
+ return Boolean(until && until > now);
196
+ }
197
+
198
+ /** The error that asks the page to confirm remote writing with a passkey, then retry. */
199
+ export function write_needed(room_id) {
200
+ return Object.assign(new Error('这个房间的成员可以改动电脑上的文件;远程操作前需要用通行密钥确认(12 小时有效)'), { need: 'write-grant', room_id });
201
+ }
202
+
203
+ /** List paired devices with their passkeys and write grants, newest first, and the recent audit entries. */
204
+ export function list_devices(home, current = null) {
205
+ const { devices, write_grants } = read_registry(home);
206
+ return { audit: recent_audit(home), devices: Object.entries(devices).map(([id, device]) => ({ id, label: device.label, temporary: device.temporary, created_at: device.created_at,
207
+ expires_at: device.expires_at, passkeys: device.passkeys.length, current: id === current,
208
+ write_rooms: Object.entries(write_grants[id] || {}).map(([room, until]) => ({ room_id: room, until })) }))
209
+ .sort((left, right) => right.created_at - left.created_at) };
210
+ }
211
+
212
+ /**
213
+ * Remove a device with its passkeys and grants; a device may also remove itself. Returns the removed passkey ids so the
214
+ * page can remove the same passkeys from the website's login list.
215
+ */
216
+ export function revoke_device(home, device_id) {
217
+ audit(home, { event: 'device.revoked', device: device_id });
218
+ return with_lock(home, registry => {
219
+ const passkeys = (registry.devices[device_id]?.passkeys || []).map(passkey => passkey.id);
220
+ delete registry.devices[device_id];
221
+ delete registry.write_grants[device_id];
222
+ return { ok: true, passkeys };
223
+ });
224
+ }
225
+
226
+ /** End one device's write grant for one room before it runs out. */
227
+ export function revoke_write(home, device_id, room_id) {
228
+ audit(home, { event: 'write.revoked', device: device_id, room: room_id });
229
+ return with_lock(home, registry => {
230
+ if (registry.write_grants[device_id]) delete registry.write_grants[device_id][room_id];
231
+ return { ok: true };
232
+ });
233
+ }
234
+
235
+ /** The relying party of a site: its exact origin and host name. */
236
+ function relying_party(site) {
237
+ const url = new URL(site);
238
+ return { origin: url.origin, rp_id: url.hostname };
239
+ }
240
+
241
+ /**
242
+ * Hand out a one-time challenge bound to the device, purpose and room. Registration returns creation options; the
243
+ * other purposes return request options listing only this device's passkeys.
244
+ */
245
+ export function passkey_options(home, device_id, site, { purpose, room_id }) {
246
+ if (!['register', 'write', 'renew', 'pair'].includes(purpose)) throw new Error('通行密钥用途无效');
247
+ if (purpose === 'write' && (typeof room_id !== 'string' || !room_id)) throw new Error('须指定要开启可写的房间');
248
+ const { rp_id } = relying_party(site);
249
+ return with_lock(home, (registry, now) => {
250
+ const device = registry.devices[device_id];
251
+ if (!device) throw new Error('这台设备未配对');
252
+ if (purpose !== 'register' && !device.passkeys.length) throw new Error('这台设备还没有通行密钥,请撤销这台设备后重新配对,并在配对后创建');
253
+ if (purpose === 'register' && (device.passkeys.length || now - device.created_at > PASSKEY_SETUP_MS)) {
254
+ throw new Error('通行密钥只能在配对后 10 分钟内创建一次;如需重建,请撤销这台设备后重新配对');
255
+ }
256
+ if (purpose === 'renew' && device.temporary) throw new Error('临时设备不能续期,请重新配对');
257
+ const id = randomBytes(8).toString('hex'), challenge = b64url(randomBytes(32));
258
+ registry.challenges[id] = { device_id, purpose, room_id: room_id || null, challenge, site, expires_at: now + CHALLENGE_MS };
259
+ if (purpose === 'register') {
260
+ // One account entry per device: a synced password manager then keeps each device's passkey instead of replacing it.
261
+ return { challenge_id: id, challenge, rp: { id: rp_id, name: 'AI CoDiscuss' }, user_id: b64url(createHash('sha256').update(`codiscuss:${rp_id}:${device_id}`).digest().subarray(0, 16)),
262
+ user_name: `codiscuss · ${device.label}`, exclude: device.passkeys.map(passkey => passkey.id) };
263
+ }
264
+ return { challenge_id: id, challenge, rp_id, allow: device.passkeys.map(passkey => passkey.id) };
265
+ });
266
+ }
267
+
268
+ /** Take a challenge once, checking it was issued to this device, for this purpose and room. */
269
+ function take_challenge(registry, { challenge_id, device_id, purpose, room_id = null, site }) {
270
+ const item = registry.challenges[challenge_id];
271
+ delete registry.challenges[challenge_id];
272
+ if (!item || item.device_id !== device_id || item.purpose !== purpose || item.room_id !== room_id || item.site !== site) {
273
+ throw new Error('通行密钥确认已过期,请重试');
274
+ }
275
+ return item;
276
+ }
277
+
278
+ /**
279
+ * Keep a passkey created for this device. The browser signed SHA-256 of this computer's challenge and the website's,
280
+ * so one creation registers with both; this computer checks its own part.
281
+ */
282
+ export function register_passkey(home, device_id, site, { challenge_id, website_challenge, credential }) {
283
+ const { origin, rp_id } = relying_party(site);
284
+ return with_lock(home, registry => {
285
+ const item = take_challenge(registry, { challenge_id, device_id, purpose: 'register', site });
286
+ const challenge = website_challenge ? joint_challenge(item.challenge, website_challenge) : item.challenge;
287
+ const passkey = verify_registration(credential, { challenge, origin, rp_id });
288
+ const device = registry.devices[device_id];
289
+ if (!device) throw new Error('这台设备未配对');
290
+ if (device.passkeys.length || Date.now() - device.created_at > PASSKEY_SETUP_MS) throw new Error('通行密钥只能在配对后 10 分钟内创建一次');
291
+ device.passkeys = [...device.passkeys.filter(kept => kept.id !== passkey.id), passkey];
292
+ audit(home, { event: 'passkey.registered', device: device_id });
293
+ return { ok: true, passkeys: device.passkeys.length };
294
+ });
295
+ }
296
+
297
+ /**
298
+ * Check a passkey assertion against this device's own passkeys and the challenge, then, in one locked step, confirm the
299
+ * device and passkey are still there, move the counter only forward, and apply `commit`.
300
+ */
301
+ async function check_assertion(home, device_id, site, { challenge_id, assertion }, purpose, room_id, commit) {
302
+ const { origin, rp_id } = relying_party(site);
303
+ const item = with_lock(home, registry => take_challenge(registry, { challenge_id, device_id, purpose, room_id, site }));
304
+ const passkey = read_registry(home).devices[device_id]?.passkeys.find(kept => kept.id === assertion?.id);
305
+ if (!passkey) throw new Error('这个通行密钥不属于这台设备');
306
+ const count = await verify_assertion(assertion, passkey, { challenge: item.challenge, origin, rp_id });
307
+ return with_lock(home, (registry, now) => {
308
+ const device = registry.devices[device_id];
309
+ const kept = device?.passkeys.find(entry => entry.id === passkey.id);
310
+ if (!kept) throw new Error('这台设备或通行密钥已被撤销');
311
+ // Assertions finishing out of order never move the counter back; a counter that did not grow is refused.
312
+ if ((count || kept.sign_count) && count <= kept.sign_count) throw new Error('通行密钥计数异常,可能被复制,请撤销后重新配对');
313
+ kept.sign_count = count;
314
+ return commit(device, registry, now);
315
+ });
316
+ }
317
+
318
+ /** Grant this device remote writing in one room for twelve hours, never past the device's own expiry. */
319
+ export async function grant_write(home, device_id, site, { challenge_id, assertion, room_id }) {
320
+ return check_assertion(home, device_id, site, { challenge_id, assertion }, 'write', room_id, (device, registry, now) => {
321
+ const until = Math.min(now + WRITE_GRANT_MS, device.expires_at);
322
+ (registry.write_grants[device_id] ||= {})[room_id] = until;
323
+ audit(home, { event: 'write.granted', device: device_id, room: room_id, until });
324
+ return { room_id, until };
325
+ });
326
+ }
327
+
328
+ /** Extend a (possibly just expired) device by another thirty days after a passkey check. */
329
+ export async function renew_device(home, device_id, site, { challenge_id, assertion }) {
330
+ return check_assertion(home, device_id, site, { challenge_id, assertion }, 'renew', null, device => {
331
+ if (device.temporary) throw new Error('这台设备不能续期,请重新配对');
332
+ device.expires_at = Date.now() + DEVICE_DAYS * DAY_MS;
333
+ audit(home, { event: 'device.renewed', device: device_id });
334
+ return { expires_at: device.expires_at };
335
+ });
336
+ }
337
+
338
+ /**
339
+ * Let a paired device show a pairing code only after its passkey confirms it: a new device gains the same trust, so a
340
+ * script using this browser's signing key alone must not be able to add one.
341
+ */
342
+ async function invite_device(home, device_id, site, { challenge_id, assertion, temporary }) {
343
+ await check_assertion(home, device_id, site, { challenge_id, assertion }, 'pair', null, () => true);
344
+ return start_pairing(home, { site, temporary: temporary === true, by: device_id });
345
+ }
346
+
347
+ /**
348
+ * Answer one device action relayed from `site` for `machine_id`, in the website's HTTP shape. `device_id` is the
349
+ * verified sender, or null for an unsigned pairing request.
350
+ */
351
+ export async function device_command(home, { site, machine_id, device_id }, action, payload = {}) {
352
+ try {
353
+ const body = action === 'device-pair' ? pair_device(home, machine_id, payload)
354
+ : action === 'device-pairing' ? await invite_device(home, device_id, site, payload)
355
+ : action === 'device-list' ? list_devices(home, device_id)
356
+ : action === 'device-revoke' ? revoke_device(home, String(payload.device_id || ''))
357
+ : action === 'write-revoke' ? revoke_write(home, String(payload.device_id || device_id), String(payload.room_id || ''))
358
+ : action === 'passkey-options' ? passkey_options(home, device_id, site, { purpose: 'register' })
359
+ : action === 'passkey-register' ? register_passkey(home, device_id, site, payload)
360
+ : action === 'passkey-challenge' ? passkey_options(home, device_id, site, payload)
361
+ : action === 'device-renew' ? await renew_device(home, device_id, site, payload)
362
+ : action === 'write-grant' ? await grant_write(home, device_id, site, payload)
363
+ : null;
364
+ if (!body) return { status: 404, body: { error: '未知的设备操作' } };
365
+ return { status: 200, body };
366
+ } catch (error) {
367
+ return { status: 400, body: { error: error.message, ...(error.need ? { need: error.need } : {}) } };
368
+ }
369
+ }