ai_co_discuss 0.4.89 → 0.4.91

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.
@@ -24,6 +24,7 @@ import { API_PROVIDERS, save_api_key } from './discussion_api.mjs';
24
24
  import { STT_PROVIDERS, TTS_PROVIDERS } from './tts_providers.mjs';
25
25
  import { ensure_tunnel, start_tunnel_setup, tunnel_setup_state, tunnel_status } from './hosting_tunnel.mjs';
26
26
  import { machine_links } from './remote_launch.mjs';
27
+ import { DIRECT_ACCOUNTS_FILE } from '../gateway/direct.mjs';
27
28
  import { apply_login, cancel_login, LOGIN_METHODS, login_progress, login_status, logout, start_login, submit_login } from './cli_login.mjs';
28
29
  import { clear_instance_flag, create_os_user, install_shared_runtime, instance_key_file, place_instance_key, read_os_users, remove_os_user, run_as_user, shared_cli_state, shared_executables, shared_paths,
29
30
  start_instance_as_user } from './os_users.mjs';
@@ -362,7 +363,8 @@ async function list_accounts(data) {
362
363
  return Promise.all(Object.entries(read_accounts(data)).map(async ([name, account]) => ({ name, port: account.port, home: account_home(data, name), disabled: Boolean(account.disabled), protected: account.protected === true,
363
364
  os_user: users[name]?.user || '', running: await instance_running(account.port), keys: list_keys(instance_home(data, name)).length,
364
365
  // The AI environment is set up once account_env.mjs has run for its Windows user (it records skills in the service home).
365
- skills: Boolean(users[name]) && existsSync(join(instance_home(data, name), SKILL_RECORD)) })));
366
+ skills: Boolean(users[name]) && existsSync(join(instance_home(data, name), SKILL_RECORD)),
367
+ external: Boolean(read_account_sites(data)[name]) })));
366
368
  }
367
369
 
368
370
  function write_settings(path, value) {
@@ -654,7 +656,7 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
654
656
  const op = { list_accounts, add_account, reset_password, set_account_disabled, remove_account, run_instance, create_os_user, remove_os_user,
655
657
  login_status, apply_login, logout, start_login, login_progress, submit_login, cancel_login, install_runtime, prepare_account, account_env, account_skills, account_workflows, owner_env, owner_skills, owner_prompts, save_owner_prompt, shared_cli_state,
656
658
  save_api_key, list_keys, remove_key, use_shared_programs, service_overview, run_owner_service, latest_version, check_package, begin_update,
657
- autostart_enabled, set_autostart, entry_overview, start_entry, stop_entry, keep_tunnel, start_tunnel_setup, set_entry_way, set_relay_url, connect_site, make_access_code, join_relay, protect_account, start_verified, hand_over: () => {}, ...ops };
659
+ set_account_external, autostart_enabled, set_autostart, entry_overview, start_entry, stop_entry, keep_tunnel, start_tunnel_setup, set_entry_way, set_relay_url, connect_site, make_access_code, join_relay, protect_account, start_verified, hand_over: () => {}, ...ops };
658
660
  const hosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
659
661
 
660
662
  async function api(method, path, body) {
@@ -740,7 +742,10 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
740
742
  return op.entry_overview(data);
741
743
  }
742
744
  // How people outside reach the entry, the relay's entry address, and binding this computer to an online site.
743
- if (method === 'POST' && section === 'entry' && name === 'way') return op.set_entry_way(data, String(body.way || ''), body.enabled === true);
745
+ if (method === 'POST' && section === 'entry' && name === 'way') {
746
+ if (body.way === 'tunnel' && body.enabled !== true) keep_direct_domain(data);
747
+ return op.set_entry_way(data, String(body.way || ''), body.enabled === true);
748
+ }
744
749
  if (method === 'POST' && section === 'entry' && name === 'relay') return op.set_relay_url(data, body.url);
745
750
  // The access code: made on the computer that deployed the online site, pasted on a hosting computer.
746
751
  if (method === 'GET' && section === 'site' && name === 'code') return { ...deploy_settings(data), site: deploy_settings(data).site || bound_site(data)?.site || '' };
@@ -749,6 +754,8 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
749
754
  // The outside address: a Cloudflare tunnel set up by a job of its own (it waits for the owner in the browser).
750
755
  if (section === 'tunnel' && name === 'setup') {
751
756
  if (method === 'GET') return tunnel_setup_state(data);
757
+ // Another domain would leave the accounts reached through this one with invites to the old address.
758
+ if (method === 'POST' && String(body.host || '').toLowerCase() !== String(entry_settings(data).tunnel?.host || '').toLowerCase()) keep_direct_domain(data);
752
759
  if (method === 'POST') return op.start_tunnel_setup(data, body.host, body.name);
753
760
  }
754
761
  if (method === 'POST' && section === 'entry' && name === 'settings') { save_entry_settings(data, { public_url: body.public_url }); return op.entry_overview(data); }
@@ -764,10 +771,19 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
764
771
  if (method === 'POST' && action === 'protect') return op.protect_account(data, name, body.on !== false);
765
772
  if (method === 'POST' && (action === 'disable' || action === 'enable')) { op.set_account_disabled(data, name, action === 'disable'); return { disabled: action === 'disable' }; }
766
773
  // The instance stops first: its port goes to the next new account, which must not reach this one's instance.
767
- if (method === 'POST' && action === 'remove') { await op.run_instance(data, name, 'stop'); op.remove_account(data, name); return { removed: name, kept: account_home(data, name) }; }
774
+ if (method === 'POST' && action === 'remove') {
775
+ await op.run_instance(data, name, 'stop');
776
+ // Its online-site binding goes first, or the owner could never unbind the computer afterwards.
777
+ await op.set_account_external(data, name, false, undefined, { removing: true }).catch(() => {});
778
+ op.remove_account(data, name);
779
+ return { removed: name, kept: account_home(data, name) };
780
+ }
781
+ if (method === 'POST' && action === 'external') return op.set_account_external(data, name, body.on !== false);
768
782
  // A start is reported only once the instance serves as the account is set (protected or not).
769
783
  if (method === 'POST' && action === 'start') { await op.start_verified(data, name); return { ok: true }; }
770
784
  if (method === 'POST' && action === 'stop') { await op.run_instance(data, name, action); return { ok: true }; }
785
+ // Its binding file is sealed for whichever Windows user wrote it: changing that user would leave it unreadable.
786
+ if (method === 'POST' && action === 'os-user' && read_account_sites(data)[name]) throw panel_error('请先关闭该账号的“允许邀请外部专家”,再更改隔离');
771
787
  if (method === 'POST' && action === 'os-user' && extra === 'remove') { op.remove_os_user(data, name); return { ok: true }; }
772
788
  if (method === 'POST' && action === 'os-user') {
773
789
  const result = op.create_os_user(data, name, account_home(data, name));
@@ -1033,10 +1049,134 @@ function disconnect_site(data) {
1033
1049
  const bound = bound_site(data);
1034
1050
  if (!bound) return { disconnected: '' };
1035
1051
  if (entry_settings(data).relay_enabled) throw panel_error('托管账号入口的线上网站还开着,请先关闭它');
1052
+ // Accounts reached on the owner's domain do not use the online site; only the ones bound to it hold it (#5617).
1053
+ if (Object.values(read_account_sites(data)).some(record => !record.direct)) throw panel_error('还有托管账号开着“允许邀请外部专家”,请先在“账号”页关闭');
1036
1054
  save_site_connection(data, bound.site);
1037
1055
  return { disconnected: bound.site };
1038
1056
  }
1039
1057
 
1058
+ // ---- Hosted accounts on the online site (#5494) ----
1059
+
1060
+ const ACCOUNT_SITES_FILE = 'account-sites.json';
1061
+
1062
+ /** The accounts this panel bound to the online site: { name: { site, machine, at } }; their own files are sealed for them. */
1063
+ function read_account_sites(data) {
1064
+ try { return JSON.parse(readFileSync(join(data, ACCOUNT_SITES_FILE), 'utf8')); } catch { return {}; }
1065
+ }
1066
+
1067
+ /**
1068
+ * Let a hosted account invite external experts, or stop. On: this computer, bound to the online site, asks it for a
1069
+ * one-time child token and binds the account's own service home with it, so the account is a computer of its own there
1070
+ * and every external-member protection works as for the owner. Off: the site releases that computer first (its slot
1071
+ * under the cap comes back; a failure stops here for a retry), then the account's own binding is removed. An account
1072
+ * being removed lets go of the record whatever happens. Off by default.
1073
+ */
1074
+ async function set_account_external(data, name, on, bind = bind_account_site, { removing = false, direct = direct_account_site } = {}) {
1075
+ const sites = read_account_sites(data);
1076
+ const save = () => write_settings(join(data, ACCOUNT_SITES_FILE), sites);
1077
+ if (!on) {
1078
+ const record = sites[name];
1079
+ if (!record) return { external: false };
1080
+ if (record.direct) {
1081
+ // Reached on the owner's domain: the entry stops answering for it first, then its direct identity goes.
1082
+ write_direct_accounts(data, Object.fromEntries(Object.entries(read_direct_accounts(data)).filter(([, account]) => account !== name)));
1083
+ try { await direct(data, name, { site: record.site, remove: true }); } catch (error) { if (!removing) throw error; }
1084
+ delete sites[name];
1085
+ save();
1086
+ return { external: false };
1087
+ }
1088
+ // The site's slot first: a failure stops here so it can be retried, never leaving a slot held with nothing bound.
1089
+ // An account being removed lets go of the record whatever happens, or the owner could never unbind afterwards.
1090
+ try { await release_account_site(data, record); } catch (error) { if (!removing) throw error; }
1091
+ try { await bind(data, name, { site: record.site, unbind: true }); } catch (error) { if (!removing) throw error; }
1092
+ delete sites[name];
1093
+ save();
1094
+ return { external: false };
1095
+ }
1096
+ // With the owner's domain on, external members reach the account through it, never the online relay (#5588).
1097
+ const settings = entry_settings(data);
1098
+ const wants_direct = Boolean(settings.tunnel_enabled && settings.tunnel?.host);
1099
+ // Already on: the same way stays; the other way is turned off first, so no slot or identity is left behind (#5617).
1100
+ if (sites[name]) {
1101
+ if (Boolean(sites[name].direct) === wants_direct) return { external: true, site: sites[name].site };
1102
+ await set_account_external(data, name, false, bind, { direct });
1103
+ delete sites[name];
1104
+ }
1105
+ if (wants_direct) {
1106
+ const site = `https://${settings.tunnel.host}`;
1107
+ const result = await direct(data, name, { site });
1108
+ if (!/^[0-9a-f]{32}$/.test(String(result.machine || ''))) throw panel_error('没有建立直连身份');
1109
+ write_direct_accounts(data, { ...Object.fromEntries(Object.entries(read_direct_accounts(data)).filter(([, account]) => account !== name)), [result.machine]: name });
1110
+ sites[name] = { site, machine: result.machine, direct: true, at: Date.now() };
1111
+ save();
1112
+ return { external: true, site };
1113
+ }
1114
+ const bound = bound_site(data);
1115
+ if (!bound) throw panel_error('这台电脑未绑定线上网站,请在管理面板“本机 → 线上网站”处绑定');
1116
+ const answer = await fetch_outside(`${bound.site}/api/machines/${bound.machine}/setup`, OUTSIDE_TIMEOUT_MS,
1117
+ { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Machine-Token': machine_links(data).sites[bound.site].token }, body: '{}' });
1118
+ const given = await answer.json().catch(() => ({}));
1119
+ if (answer.status === 404) throw panel_error('{value1} 的线上网站版本过旧,请部署方更新线上网站后再试', { value1: bound.site });
1120
+ if (!answer.ok || !given.setup_key) throw panel_error('线上网站没有签发绑定令牌:{value1}', { value1: given.error || answer.status });
1121
+ let result;
1122
+ try { result = await bind(data, name, { site: bound.site, setup_key: given.setup_key }); }
1123
+ catch (error) {
1124
+ // The website words a used or expired token for someone running codiscuss token by hand.
1125
+ if (String(error.message).includes('绑定令牌错误或已用过')) throw panel_error('绑定令牌已过期,请重试');
1126
+ throw error;
1127
+ }
1128
+ sites[name] = { site: bound.site, machine: result.machine || '', at: Date.now() };
1129
+ save();
1130
+ return { external: true, site: bound.site };
1131
+ }
1132
+
1133
+ /** Refuse a change to the owner's domain while accounts are reached through it: their members would be cut off (#5617). */
1134
+ function keep_direct_domain(data) {
1135
+ if (Object.values(read_account_sites(data)).some(record => record.direct)) {
1136
+ throw panel_error('还有托管账号经自有域名邀请外部专家,请先在“账号”页关闭它们的“允许邀请外部专家”');
1137
+ }
1138
+ }
1139
+
1140
+ /** Which computer id is which account on the owner's domain, for the sign-in entry (gateway/direct.mjs). */
1141
+ function read_direct_accounts(data) {
1142
+ try { return JSON.parse(readFileSync(join(data, DIRECT_ACCOUNTS_FILE), 'utf8')); } catch { return {}; }
1143
+ }
1144
+ function write_direct_accounts(data, mapping) {
1145
+ write_settings(join(data, DIRECT_ACCOUNTS_FILE), mapping);
1146
+ }
1147
+
1148
+ /** Create or remove an account's direct identity, as its own Windows user when it has one (the identity is sealed for it). */
1149
+ async function direct_account_site(data, name, { site, remove = false }) {
1150
+ const home = instance_home(data, name);
1151
+ if (read_os_users(data)[name]) return account_env(data, name, 'direct', { home, site, remove });
1152
+ const { create_direct_link, remove_direct_link } = await import('./remote_launch.mjs');
1153
+ if (remove) { remove_direct_link(home); return { ok: true }; }
1154
+ return { machine: create_direct_link(home, site).id };
1155
+ }
1156
+
1157
+ /** Ask the online site to let go of an account's computer; a site without this (older) or without it any more is done. */
1158
+ async function release_account_site(data, record) {
1159
+ const owner = machine_links(data).sites[record.site];
1160
+ if (!owner?.token || !record.machine) return;
1161
+ const answer = await fetch_outside(`${record.site}/api/machines/${owner.id}/release`, OUTSIDE_TIMEOUT_MS,
1162
+ { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Machine-Token': owner.token }, body: JSON.stringify({ machine: record.machine }) });
1163
+ if (answer.ok || answer.status === 404) return;
1164
+ const given = await answer.json().catch(() => ({}));
1165
+ throw panel_error('线上网站没有释放这个账号:{value1}', { value1: given.error || answer.status });
1166
+ }
1167
+
1168
+ /**
1169
+ * Bind or unbind one account's service home without starting anything (its instance re-reads bindings by itself), as
1170
+ * the account's own Windows user when it has one: the binding file is sealed for whoever writes it.
1171
+ */
1172
+ async function bind_account_site(data, name, { site, setup_key = '', unbind = false }) {
1173
+ const home = instance_home(data, name);
1174
+ if (read_os_users(data)[name]) return account_env(data, name, 'site', { home, site, setup_key, unbind });
1175
+ if (unbind) { save_site_connection(home, site); return { ok: true }; }
1176
+ const { bind_machine } = await import('./discussion_local.mjs');
1177
+ return { machine: await bind_machine(home, site, setup_key) };
1178
+ }
1179
+
1040
1180
  // ---- Hosted accounts' failures, to the owner's Weixin ----
1041
1181
 
1042
1182
  /** Whether two paths name the same place, as written (Windows paths compare without regard to case). */
@@ -241,14 +241,25 @@ export async function open_signed_request(home, id, sealed, machine_id) {
241
241
  */
242
242
  export async function signed_device_list(home, link, now = Date.now(), externals = []) {
243
243
  const { devices } = read_registry(home);
244
- const body = JSON.stringify({ machine: link.id, issued_at: now, devices: [...Object.entries(devices)
244
+ const listed = [...Object.entries(devices)
245
245
  .map(([id, device]) => ({ id, x: device.public_key.x, y: device.public_key.y, expires_at: device.expires_at,
246
246
  ...(renewable(device) ? { renew_until: device.expires_at + RENEW_GRACE_DAYS * DAY_MS } : {}) })),
247
- ...externals.map(({ id, x, y, room, expires_at }) => ({ id, x, y, kind: 'external', room, expires_at }))] });
247
+ ...externals.map(({ id, x, y, room, expires_at }) => ({ id, x, y, kind: 'external', room, expires_at }))];
248
+ // An unchanged list keeps its signature and issued_at, so the heartbeat that carries it is the same each time and
249
+ // the website neither rewrites it nor wakes the relay (2026-11-19, #5500); issued_at is when the content last changed.
250
+ const content = JSON.stringify({ machine: link.id, devices: listed });
251
+ const cache_key = [home, link.id, link.sign_private_key?.x || ''].join('|');
252
+ const cached = signed_lists.get(cache_key);
253
+ if (cached?.content === content) return cached.signed;
254
+ const body = JSON.stringify({ machine: link.id, issued_at: Math.max(now, (cached?.issued_at || 0) + 1), devices: listed });
248
255
  const key = await crypto.subtle.importKey('jwk', link.sign_private_key, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign']);
249
256
  const signature = await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, new TextEncoder().encode(body));
250
- return { body, signature: b64url(new Uint8Array(signature)) };
257
+ const signed = { body, signature: b64url(new Uint8Array(signature)) };
258
+ signed_lists.set(cache_key, { content, issued_at: JSON.parse(body).issued_at, signed });
259
+ return signed;
251
260
  }
261
+ // The last list signed per service directory and computer: { content, issued_at, signed }.
262
+ const signed_lists = new Map();
252
263
 
253
264
  /** List paired devices with their passkey counts and unlock times, newest first, and the recent audit entries. */
254
265
  export function list_devices(home, current = null) {
@@ -0,0 +1,164 @@
1
+ /**
2
+ * The direct receiver of a hosted account reached on its owner's domain (user 2026-11-19, #5588, #5599): instead of the
3
+ * online relay, the sign-in entry (gateway/gateway.mjs) hands it the three requests an external member's computer sends
4
+ * (`/api/machines/<id>/pair` and `/relay`; the key list is the entry's own). It runs inside the account's own discussion
5
+ * service, the only process that can open the account's sealed direct identity (runner/remote_launch.mjs `direct_link`).
6
+ *
7
+ * What it takes and what it never does:
8
+ * - only external members' requests, the branch of runner/relay_channel.mjs `answer_request` that goes to
9
+ * `answer_external`: a paired device's signed command is refused here whatever its signature, so nothing that reaches
10
+ * this from outside can run a local operation;
11
+ * - a relayed request's `X-CoDiscuss-Device` credential is checked against the members this account registered before
12
+ * anything is decrypted, as the online site does for the relay, so unregistered senders cost no decryption;
13
+ * - it listens on loopback only, under a random token kept with its port in `local/direct.json` for the entry; the
14
+ * token is compared in constant time, a request with an Origin is refused, and a few requests at a time are served.
15
+ */
16
+ import http from 'node:http';
17
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
18
+ import { mkdirSync, rmSync } from 'node:fs';
19
+ import { dirname, join } from 'node:path';
20
+
21
+ import { atomic_json } from './files.mjs';
22
+ import { answer_external, is_external_request, read_registry } from './external_gateway.mjs';
23
+ import { direct_link, relay_cipher, unseal } from './remote_launch.mjs';
24
+ import { seal_compressed } from './relay_channel.mjs';
25
+
26
+ export const DIRECT_FILE = join('local', 'direct.json');
27
+ export const DIRECT_PATH = '/direct';
28
+ export const DIRECT_TOKEN_HEADER = 'x-codiscuss-direct';
29
+ const BODY_MAX = 600 * 1024;
30
+ const READ_TIMEOUT_MS = 15_000;
31
+ const CONCURRENT_MAX = 6;
32
+ // The same window the online site allows a member's request credential (worker.mjs DEVICE_CLOCK_SECONDS).
33
+ const CLOCK_SECONDS = 300;
34
+ const ID_PATTERN = /^[A-Za-z0-9_-]{16,80}$/;
35
+ const KINDS = new Set(['pair', 'relay']);
36
+ const ECDSA = { name: 'ECDSA', namedCurve: 'P-256' }, SIGNED = { name: 'ECDSA', hash: 'SHA-256' };
37
+
38
+ /**
39
+ * The registered member a relayed request's credential names, or null: `<machine>.<member>.<seconds>.<signature>` over
40
+ * `POST\n<path>\n<seconds>`, by a member whose key this account registered for its direct address and has not expired.
41
+ */
42
+ export async function direct_member(home, link, credential, path, now = Date.now()) {
43
+ const [machine, member, time, signature] = String(credential || '').split('.');
44
+ if (machine !== link.id || !/^[0-9a-f]{32}$/.test(member || '') || !/^\d{10}$/.test(time || '') || !signature) return null;
45
+ if (Math.abs(Math.floor(now / 1000) - Number(time)) > CLOCK_SECONDS) return null;
46
+ const entry = read_registry(home).externals[member];
47
+ if (!entry || !(entry.key_expires_at > now) || (entry.site && entry.site !== link.site)) return null;
48
+ try {
49
+ const key = await crypto.subtle.importKey('jwk', { kty: 'EC', crv: 'P-256', x: entry.public_key.x, y: entry.public_key.y }, ECDSA, false, ['verify']);
50
+ const valid = await crypto.subtle.verify(SIGNED, key, Buffer.from(signature, 'base64url'), new TextEncoder().encode(`POST\n${path}\n${time}`));
51
+ return valid ? member : null;
52
+ } catch { return null; }
53
+ }
54
+
55
+ /** An envelope as the relay accepts one: an ephemeral public key and the sealed bytes. */
56
+ function valid_envelope(envelope) {
57
+ return envelope && typeof envelope === 'object' && envelope.key && typeof envelope.key === 'object'
58
+ && typeof envelope.iv === 'string' && typeof envelope.data === 'string';
59
+ }
60
+
61
+ /**
62
+ * Answer one request the entry handed over: `{ kind, path, credential, id, envelope }`. Returns `{ status, body }`,
63
+ * the body for 200 being the relay's answer `{ id, status: 'done', response }` with the reply sealed for the sender.
64
+ */
65
+ export async function answer_direct(home, request, { now = Date.now(), fetcher } = {}) {
66
+ const link = direct_link(home);
67
+ if (!link) return { status: 404, body: { error: '这个账号没有开启邀请外部专家' } };
68
+ const { kind, path, credential, id, envelope } = request || {};
69
+ if (!KINDS.has(kind) || typeof id !== 'string' || !ID_PATTERN.test(id) || !valid_envelope(envelope)) return { status: 400, body: { error: '请求格式无效' } };
70
+ if (path !== `/api/machines/${link.id}/${kind}`) return { status: 404, body: { error: '地址不存在' } };
71
+ let member = null;
72
+ if (kind === 'relay') {
73
+ member = await direct_member(home, link, credential, path, now);
74
+ if (!member) return { status: 401, body: { error: '外部成员未登记或凭据已失效' } };
75
+ }
76
+ let key, sealed;
77
+ try {
78
+ key = await relay_cipher(link.private_key, envelope.key);
79
+ sealed = await unseal(key, envelope, id);
80
+ } catch { return { status: 400, body: { error: '无法解开请求' } }; }
81
+ // Only an external member's request: a redemption on `pair`, the member the credential named on `relay`.
82
+ if (!is_external_request(sealed) || (kind === 'pair' ? sealed.external_id !== undefined : sealed.external_id !== member)) {
83
+ return { status: 403, body: { error: '这个入口只接受外部成员的请求' } };
84
+ }
85
+ const { response } = await answer_external(home, { machine_id: link.id, link, fetcher }, id, sealed);
86
+ return { status: 200, body: { id, status: 'done', response: await seal_compressed(key, response, `${id}:response`) } };
87
+ }
88
+
89
+ function reply(response, status, body) {
90
+ const text = JSON.stringify(body);
91
+ response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(text), 'Cache-Control': 'no-store' });
92
+ response.end(text);
93
+ }
94
+
95
+ /** Read a JSON body up to BODY_MAX within READ_TIMEOUT_MS. */
96
+ function read_body(request) {
97
+ return new Promise((done, fail) => {
98
+ const parts = [];
99
+ let size = 0;
100
+ const timer = setTimeout(() => { request.destroy(); fail(Object.assign(new Error('读取超时'), { status: 408 })); }, READ_TIMEOUT_MS);
101
+ request.on('data', part => {
102
+ size += part.length;
103
+ if (size > BODY_MAX) { clearTimeout(timer); request.destroy(); fail(Object.assign(new Error('请求过大'), { status: 413 })); return; }
104
+ parts.push(part);
105
+ });
106
+ request.on('end', () => { clearTimeout(timer); try { done(JSON.parse(Buffer.concat(parts).toString('utf8'))); } catch { fail(Object.assign(new Error('请求格式无效'), { status: 400 })); } });
107
+ request.on('error', error => { clearTimeout(timer); fail(error); });
108
+ });
109
+ }
110
+
111
+ /**
112
+ * Keep the receiver in step with the direct identity: listening while the account has one, gone when it has none.
113
+ * `refresh()` is called from the service loop; `close()` stops it and removes `local/direct.json`.
114
+ */
115
+ export function direct_receiver(home, { log = () => {}, fetcher } = {}) {
116
+ const file = join(home, DIRECT_FILE);
117
+ let server = null, token = '', machine = '', active = 0, starting = false;
118
+ const same = (given) => {
119
+ const expected = Buffer.from(token), supplied = Buffer.from(String(given || ''));
120
+ return expected.length === supplied.length && timingSafeEqual(expected, supplied);
121
+ };
122
+ const handle = async (request, response) => {
123
+ if (request.method !== 'POST' || request.url !== DIRECT_PATH || request.headers.origin || !same(request.headers[DIRECT_TOKEN_HEADER])) {
124
+ request.resume();
125
+ return reply(response, 404, { error: '地址不存在' });
126
+ }
127
+ if (active >= CONCURRENT_MAX) { request.resume(); return reply(response, 503, { error: '请求过多,请稍后再试' }); }
128
+ active += 1;
129
+ try {
130
+ const body = await read_body(request);
131
+ const answer = await answer_direct(home, body, { fetcher });
132
+ reply(response, answer.status, answer.body);
133
+ } catch (error) { if (!response.headersSent) reply(response, error.status || 400, { error: error.message }); }
134
+ finally { active -= 1; }
135
+ };
136
+ const stop = () => {
137
+ if (server) { server.close(); server = null; }
138
+ rmSync(file, { force: true });
139
+ };
140
+ return {
141
+ refresh() {
142
+ let link;
143
+ try { link = direct_link(home); } catch (error) { log(`读取直连身份失败:${error.message}`); return; }
144
+ if (!link) { if (server) { stop(); log('已关闭外部专家直连入口'); } return; }
145
+ if (server && machine === link.id) return;
146
+ if (starting) return;
147
+ if (server) stop();
148
+ starting = true;
149
+ token = randomBytes(32).toString('hex');
150
+ machine = link.id;
151
+ const created = http.createServer((request, response) => { handle(request, response).catch(() => { if (!response.headersSent) reply(response, 500, { error: '处理失败' }); }); });
152
+ created.listen(0, '127.0.0.1', () => {
153
+ server = created;
154
+ starting = false;
155
+ mkdirSync(dirname(file), { recursive: true });
156
+ atomic_json(file, { port: created.address().port, token, machine: link.id, site: link.site,
157
+ public_key: link.public_key, sign_key: link.sign_public_key, name: link.name });
158
+ log(`外部专家直连入口已开启:${link.site}`);
159
+ });
160
+ created.on('error', error => { starting = false; log(`外部专家直连入口启动失败:${error.message}`); });
161
+ },
162
+ close: stop,
163
+ };
164
+ }
@@ -2445,7 +2445,7 @@ export async function launch_main(args = process.argv.slice(2), input_text) {
2445
2445
  // The QR code opens the paired website and carries this computer's key fingerprint for the new device to check.
2446
2446
  const { keyed_links } = await import('./remote_launch.mjs');
2447
2447
  const [site, link] = Object.entries(keyed_links(home).sites).find(([origin]) => !input?.site || origin === input.site) || [];
2448
- if (!link) throw new Error('这台电脑未绑定线上网站,请在管理面板“线上网站”处绑定');
2448
+ if (!link) throw new Error('这台电脑未绑定线上网站,请在管理面板“本机 → 线上网站”处绑定');
2449
2449
  result = start_pairing(home, { site, fingerprint: machine_fingerprint(link), temporary: input?.temporary === true, without_passkey: input?.without_passkey === true });
2450
2450
  }
2451
2451
  else if (positionals[0] === 'devices' && !values.remote) {
@@ -84,7 +84,7 @@ async function connect_site(home, site, no_open, setup_key) {
84
84
  * Register this computer with an online website using a one-time setup token, then publish its keys and signed device
85
85
  * list. Without a token given, the deploying computer creates one through wrangler, as `codiscuss token` does.
86
86
  */
87
- async function bind_machine(home, origin, setup_key) {
87
+ export async function bind_machine(home, origin, setup_key) {
88
88
  const { machine_link, sync_remote_launches } = await import('./remote_launch.mjs');
89
89
  let key = setup_key;
90
90
  if (!key) {
@@ -99,6 +99,7 @@ async function bind_machine(home, origin, setup_key) {
99
99
  // From now on this website reaches the local one only as the relay's bridge, never with a browser connection credential.
100
100
  (await import('./relay_channel.mjs')).bridge_token(home, origin);
101
101
  await sync_remote_launches(home);
102
+ return link.id;
102
103
  }
103
104
 
104
105
  /** Read the website supervisor's lock and last startup receipt. */
@@ -742,7 +742,7 @@ export async function run_service(home, output = () => {}) {
742
742
  service.push = true;
743
743
  const stop_path = join(home, 'stop.request');
744
744
  if (existsSync(stop_path)) unlinkSync(stop_path);
745
- let stopped = false, syncing = null, relaying = null, channels = null, receiving = null, updating_pi = null, pi_checked = false;
745
+ let stopped = false, syncing = null, relaying = null, channels = null, direct = null, receiving = null, updating_pi = null, pi_checked = false;
746
746
  const relay_stop = new AbortController();
747
747
  const stop = () => { stopped = true; relay_stop.abort(); };
748
748
  process.once('SIGINT', stop);
@@ -756,6 +756,9 @@ export async function run_service(home, output = () => {}) {
756
756
  const { start_relay_channels } = await import('./relay_channel.mjs');
757
757
  if ((await import('./admin_account.mjs')).remove_legacy_admin_accounts(home)) log_line('已删除旧版本明文保存的管理员密码文件 admin-accounts.json');
758
758
  channels = start_relay_channels(home, { log: log_line, signal: relay_stop.signal });
759
+ // A hosted account reached on its owner's domain answers external members here instead of over the relay (#5588).
760
+ direct = (await import('./direct_entry.mjs')).direct_receiver(home, { log: log_line });
761
+ direct.refresh();
759
762
  // Rooms on other computers this one was invited to: pull the requests named for its AI (runner/external_client.mjs).
760
763
  (await import('./external_client.mjs')).start_external_client(home, { log: log_line, signal: relay_stop.signal });
761
764
  // The owner's Weixin replies come back here and go to the room their notice came from.
@@ -791,7 +794,8 @@ export async function run_service(home, output = () => {}) {
791
794
  if (!syncing && Date.now() - synced_at >= REMOTE_SYNC_MS) {
792
795
  synced_at = Date.now();
793
796
  channels.refresh();
794
- syncing = sync_remote_launches(home, { log: log_line }).catch(error => log_line(`远程启动检查失败:${error.message}`))
797
+ direct.refresh();
798
+ syncing = sync_remote_launches(home, { log: log_line, throttle: true }).catch(error => log_line(`远程启动检查失败:${error.message}`))
795
799
  .finally(() => { syncing = null; });
796
800
  }
797
801
  if (!relaying && Date.now() - relay_failed_at >= REMOTE_SYNC_MS) start_relay();
@@ -806,6 +810,7 @@ export async function run_service(home, output = () => {}) {
806
810
  }
807
811
  } finally {
808
812
  relay_stop.abort();
813
+ direct?.close();
809
814
  await Promise.all([syncing, relaying, channels?.done(), receiving, updating_pi]);
810
815
  await service.close();
811
816
  if (existsSync(stop_path)) unlinkSync(stop_path);
@@ -192,7 +192,7 @@ export function free_task_text({ name, discussion, discussion_request, profile,
192
192
  const quick = `问候、致谢等简单消息可跳过技能:${cli} message view 上面的消息编号${access} 看原文,${cli} message post --body "回答"${access} 回复(${INLINE_BODY_RULE})。`;
193
193
  const opening = `${wake_opening(requests, name, discussion)},对应消息 ${messages}。`;
194
194
  // Choosing a sub-workflow was left to the host's memory and got skipped, so every host task now asks for it (#4487).
195
- const route = workflow ? '本房间启用了工作流:派活或改文件之前,先读 workflow.skill_path,把这次请求对照主线和 workflow.sub_workflows 每一项的 description;命中就读它的 SKILL.md 并照做,不问要不要用,回答开头写明走的哪条;都不命中就写明按普通请求处理。' : '';
195
+ const route = workflow ? '本房间启用了工作流:派活或改文件之前,先读 workflow.skill_path,把这次请求对照主线和 workflow.sub_workflows 每一项的 description;命中就读它的 SKILL.md 并照做,不问要不要用,回答开头用一句话写明走的哪条;都不命中就按普通请求处理,回答里不必说明。' : '';
196
196
  // A message with files is never a mere greeting: the quick path would skip them (2026-11-14, #3143); nor is a
197
197
  // hand-back, notice, Goal or host assignment, so the shortcut only goes with a user's own message (#3145 四.5).
198
198
  const prompt = files || !from_user(requests)
@@ -290,8 +290,10 @@ export async function machine_keys(site, machine, { fetcher = fetch, retry_delay
290
290
  }, { repeatable: true, delays: retry_delays });
291
291
  const body = await response.json().catch(() => ({}));
292
292
  const list = (Array.isArray(body) ? body : body.machines || []).filter(item => item?.public_key && item?.sign_key);
293
- if (!machine && list.length > 1) throw failure('machine_required', '对方站点连着多台电脑,请用 --machine 指定电脑编号:{ids}', { ids: list.map(item => `${item.id}(${item.name || ''})`).join('、') });
294
- const found = machine ? list.find(item => item.id === machine) : list[0];
293
+ // Hosted accounts' computers (`parent`) are reached by id only; without one the site's own computers are meant (#5494).
294
+ const owners = list.filter(item => !item.parent);
295
+ if (!machine && owners.length > 1) throw failure('machine_required', '对方站点连着多台电脑,请用 --machine 指定电脑编号:{ids}', { ids: owners.map(item => `${item.id}(${item.name || ''})`).join('、') });
296
+ const found = machine ? list.find(item => item.id === machine) : owners[0];
295
297
  if (!found) throw failure('machine_not_found', '对方站点上找不到这台电脑,或它还没有连接中转');
296
298
  return { id: found.id, public_key: found.public_key, sign_key: found.sign_key, name: String(found.name || ''), fingerprint: fingerprint_of(found.public_key, found.sign_key) };
297
299
  }
@@ -81,7 +81,7 @@ function with_registry(home, task) {
81
81
  }
82
82
 
83
83
  /** Read the registry without changing it. */
84
- function read_registry(home) {
84
+ export function read_registry(home) {
85
85
  const file = join(home, REGISTRY_FILE);
86
86
  const registry = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : {};
87
87
  registry.invites ||= {}; registry.externals ||= {};
@@ -180,13 +180,18 @@ function membership_end(duration, now) {
180
180
  return Math.floor((now + HOUR_MS) / 1000);
181
181
  }
182
182
 
183
- /** Pick the online site an invite names: the one asked for, or the only one this computer is bound to. */
183
+ /**
184
+ * Pick the site an invite names: the one asked for, else this account's own domain when it is reached directly (#5588),
185
+ * else the only online site this computer is bound to.
186
+ */
184
187
  async function invite_site(home, site_url) {
185
- const { keyed_links } = await import('./remote_launch.mjs');
188
+ const { direct_link, keyed_links } = await import('./remote_launch.mjs');
189
+ const direct = direct_link(home);
190
+ if (direct && (!site_url || site_url === direct.site)) return { site: direct.site, link: direct };
186
191
  const sites = Object.entries(keyed_links(home).sites);
187
192
  const found = site_url ? sites.find(([origin]) => origin === site_url) : sites.length === 1 ? sites[0] : null;
188
193
  if (!found) throw sites.length ? new GatewayError(400, '这台电脑绑定了多个线上网站,请指定邀请使用的网站', {}, 'site_required')
189
- : new GatewayError(400, '这台电脑未绑定线上网站,请在管理面板“线上网站”处绑定', {}, 'site_missing');
194
+ : new GatewayError(400, '这台电脑未绑定线上网站,请在管理面板“本机 → 线上网站”处绑定', {}, 'site_missing');
190
195
  return { site: found[0], link: found[1] };
191
196
  }
192
197
 
@@ -360,6 +365,8 @@ async function redeem(home, ctx, id, sealed, request) {
360
365
  let external_id;
361
366
  try { external_id = device_id_of(public_key); } catch { throw new GatewayError(400, '外部成员公钥须为 P-256'); }
362
367
  if (!await verify_signature(public_key, sealed.signature, `${id}\n${sealed.body}`)) throw new GatewayError(400, '外部成员签名无效', {}, 'bad_signature');
368
+ // Only a signed redemption is remembered against replay: unsigned ones, which anyone can make, never grow that record.
369
+ claim_relayed_command(home, id, request.sent_at);
363
370
  if (typeof platform !== 'string' || !/^[A-Za-z]{2,20}$/.test(platform)) throw new GatewayError(400, '请说明派来的是哪个 AI');
364
371
  const previous = read_registry(home).externals[external_id];
365
372
  if (previous) {
@@ -527,7 +534,6 @@ export async function answer_external(home, ctx, id, sealed) {
527
534
  request = JSON.parse(sealed.body);
528
535
  if (request.action !== 'external-redeem') throw new GatewayError(403, '该操作不对外部成员开放', {}, 'action_forbidden');
529
536
  if (request.machine !== ctx.machine_id) throw new GatewayError(403, '这条请求是发给另一台电脑的', {}, 'wrong_machine');
530
- claim_relayed_command(home, id, request.sent_at);
531
537
  response = await redeem(home, ctx, id, sealed, request);
532
538
  } else {
533
539
  const opened = await open_external(home, id, sealed, ctx.machine_id);
@@ -5,7 +5,7 @@
5
5
  * check that the entry answers here and outside. Safe to run again: what is already done is kept.
6
6
  */
7
7
  import { spawnSync } from 'node:child_process';
8
- import { existsSync } from 'node:fs';
8
+ import { existsSync, readFileSync } from 'node:fs';
9
9
  import { homedir } from 'node:os';
10
10
  import { dirname, join } from 'node:path';
11
11
  import { fileURLToPath } from 'node:url';
@@ -81,6 +81,11 @@ export async function configure_hosting(home, options, { interactive = Boolean(p
81
81
  if (options['public-host']) {
82
82
  try {
83
83
  const host = tunnel_host(options['public-host']);
84
+ // As the panel refuses (#5625): accounts reached on the current domain would keep inviting to the old address.
85
+ const current = String(entry_settings(home).tunnel?.host || '').toLowerCase();
86
+ let direct = false;
87
+ try { direct = Object.values(JSON.parse(readFileSync(join(home, 'account-sites.json'), 'utf8'))).some(record => record?.direct); } catch { direct = false; }
88
+ if (direct && current && current !== host.toLowerCase()) throw new Error(t('还有托管账号经自有域名邀请外部专家,请先在“账号”页关闭它们的“允许邀请外部专家”'));
84
89
  const tunnel = await prepare_tunnel({ host, name: options['tunnel-name'], interactive, say });
85
90
  Object.assign(changes, { public_url: `https://${host}`, tunnel, tunnel_enabled: true });
86
91
  lines.push(t('外网地址 https://{value1},经 Cloudflare 隧道 {value2} 转到登录入口;隧道独立运行,由管理面板按设置维持', { value1: host, value2: tunnel.name }));