ai_co_discuss 0.4.44 → 0.4.47

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.
@@ -14,6 +14,11 @@ proved the same to it:
14
14
 
15
15
  The key never travels. Protection is on when the environment names a key file (``DISCUSS_ENTRY_KEY_FILE``); a key file
16
16
  that is then missing or unreadable refuses every protected request instead of falling back to no protection.
17
+
18
+ A browser cannot do the handshake. The computer owner's own site (protected once hosting is on, since every hosted
19
+ account's processes share this loopback) is opened in the owner's browser through a signed link that a key holder makes:
20
+ ``GET /_instance/open?at=<unix seconds>&sig=HMAC(K, "open|" + at)``, valid for a few minutes, answers with a cookie
21
+ ``HMAC(K, "browser|site")`` (HttpOnly, SameSite=Strict) that then admits that browser's requests. Changing the key ends it.
17
22
  """
18
23
  import hashlib
19
24
  import hmac
@@ -34,6 +39,10 @@ KEY_PATTERN = re.compile(r"^[0-9a-f]{64}$")
34
39
  HANDSHAKE_SECONDS = 10
35
40
  # Paths any caller may read: the health check and the page's static files carry no data.
36
41
  PUBLIC_PATHS = ("/api/health", "/robots.txt")
42
+ OPEN_PATH = "/_instance/open"
43
+ # How long a signed opening link stays usable, and how long the browser cookie it gives lasts.
44
+ OPEN_LINK_SECONDS = 300
45
+ BROWSER_COOKIE_SECONDS = 30 * 24 * 3600
37
46
 
38
47
 
39
48
  def proof(key, purpose, nonce):
@@ -68,6 +77,33 @@ class EntryPolicy:
68
77
  return value if isinstance(value, str) and KEY_PATTERN.match(value) else None
69
78
 
70
79
 
80
+ def browser_cookie_name(port):
81
+ """The cookie name, per port: cookies are shared by every port of a host."""
82
+ return f"codiscuss_site_{port}"
83
+
84
+
85
+ def open_link_key(policy, at, sig, now):
86
+ """The current key when ``at``/``sig`` are a fresh opening link made with it, else None."""
87
+ key = policy.key()
88
+ if not key or not re.fullmatch(r"\d{1,12}", at or "") or abs(now - int(at)) > OPEN_LINK_SECONDS:
89
+ return None
90
+ return key if hmac.compare_digest(sig or "", proof(key, "open", at)) else None
91
+
92
+
93
+ def browser_admitted(handler, policy):
94
+ """Whether the request carries the browser cookie of the current key."""
95
+ key = policy.key()
96
+ if not key:
97
+ return False
98
+ name = browser_cookie_name(handler.server.server_port)
99
+ expected = proof(key, "browser", "site")
100
+ for part in handler.headers.get("Cookie", "").split(";"):
101
+ label, _, value = part.strip().partition("=")
102
+ if label == name and hmac.compare_digest(value, expected):
103
+ return True
104
+ return False
105
+
106
+
71
107
  def answer_hello(handler, policy):
72
108
  """Prove this instance to a caller and open the connection's single authenticated request.
73
109
 
package/backend/server.py CHANGED
@@ -23,7 +23,8 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
23
23
  from pathlib import Path
24
24
  from urllib.parse import parse_qs, quote, urlsplit
25
25
 
26
- from .entry_guard import HELLO_PATH, PUBLIC_PATHS, EntryPolicy, answer_hello, request_proven
26
+ from .entry_guard import (BROWSER_COOKIE_SECONDS, HELLO_PATH, OPEN_PATH, PUBLIC_PATHS, EntryPolicy, answer_hello, browser_admitted,
27
+ browser_cookie_name, open_link_key, proof, request_proven)
27
28
  from .admin import (AdminError, admin_status, change_password, list_sessions, login_admin, logout_admin, register_admin,
28
29
  revoke_sessions, session_valid, update_profile)
29
30
  from .remote_launch import (COMMAND_WAIT_MAX, claim_machine_commands, finish_machine_command, list_machines, machine_command_status,
@@ -1899,11 +1900,34 @@ class DiscussionHandler(BaseHTTPRequestHandler):
1899
1900
  self.entry_key = request_proven(self, policy)
1900
1901
  if self.entry_key:
1901
1902
  return False
1903
+ if method == "GET" and parsed.path == OPEN_PATH:
1904
+ return self.open_browser_session(policy, parsed)
1905
+ if browser_admitted(self, policy):
1906
+ return False
1902
1907
  if method == "GET" and (parsed.path in ASSETS or parsed.path in PUBLIC_PATHS):
1903
1908
  return False
1904
1909
  self.close_connection = True
1905
1910
  # Sent directly, not through respond(): a refused caller leaves nothing in any room's event log.
1906
- self.send_payload(403, "application/json", json.dumps({"error": "这个工作台只接受经入口的访问"}, ensure_ascii=False).encode("utf-8"))
1911
+ message = "这个工作台只接受经入口的访问;本机管理员请从任务栏图标或桌面“共议”打开"
1912
+ self.send_payload(403, "application/json", json.dumps({"error": message}, ensure_ascii=False).encode("utf-8"))
1913
+ return True
1914
+
1915
+ def open_browser_session(self, policy, parsed):
1916
+ """Turn a fresh signed opening link into the browser cookie and go to the site; refuse anything else."""
1917
+ params = {key: values[-1] for key, values in parse_qs(parsed.query).items()}
1918
+ key = open_link_key(policy, params.get("at"), params.get("sig"), int(time.time()))
1919
+ self.close_connection = True
1920
+ if not key:
1921
+ self.send_payload(403, "text/plain", "链接已失效,请从任务栏图标或桌面“共议”重新打开。".encode("utf-8"))
1922
+ return True
1923
+ self.send_response(302)
1924
+ cookie = f"{browser_cookie_name(self.server.server_port)}={proof(key, 'browser', 'site')}"
1925
+ self.send_header("Set-Cookie", f"{cookie}; Max-Age={BROWSER_COOKIE_SECONDS}; Path=/; HttpOnly; SameSite=Strict")
1926
+ self.send_header("Location", "/")
1927
+ self.send_header("Content-Length", "0")
1928
+ self.send_header("Cache-Control", "no-store")
1929
+ self.send_header("Referrer-Policy", "no-referrer")
1930
+ self.end_headers()
1907
1931
  return True
1908
1932
 
1909
1933
  def end_headers(self):
@@ -169,7 +169,13 @@ npx wrangler deploy --config deploy/updates.wrangler.jsonc
169
169
  npx wrangler deploy --config deploy/entry.wrangler.jsonc
170
170
  ```
171
171
 
172
- 它有自己的 `workers.dev` 地址(如 `https://codiscuss-entry.<账号子域>.workers.dev`),与线上站点不同源,托管账号的网页碰不到你已配对设备的密钥。托管电脑绑定线上站点后,在管理面板“概览 → 托管 → 登录入口”的“外网访问”选“线上中转”,填这个地址;面板给出的链接带电脑编号(`?m=…`),发给使用者即可。使用者的请求经入口 Worker 和中转到达这台电脑的登录入口,登录、会话与入口保护都在电脑上;Cloudflare 能看到这些往来内容(与自有域名隧道相同),每个页面的请求都计入 Workers 免费额度。
172
+ 它有自己的 `workers.dev` 地址(如 `https://codiscuss-entry.<账号子域>.workers.dev`),与线上站点不同源,托管账号的网页碰不到你已配对设备的密钥。把这个地址写进私有配置的 `vars`,重新部署 Pages,线上站点就会把它告诉来接入的托管电脑:
173
+
174
+ ```json
175
+ "vars": { "ENTRY_URL": "https://codiscuss-entry.<账号子域>.workers.dev" }
176
+ ```
177
+
178
+ 接入一台托管电脑:在你(部署线上站点的电脑)的管理面板“概览 → 托管 → 登录入口”选“线上中转”,展开“生成接入码”,填部署配置路径与站点地址后生成(需已登录 wrangler;一次性,再生成会让未用过的作废);把接入码发给托管电脑,粘贴到它的同一个窗口点“接入并切换”,它会绑定站点、取得入口地址、启动所需服务并切换。面板给出的链接带电脑编号(`?m=…`),发给使用者即可。使用者的请求经入口 Worker 和中转到达这台电脑的登录入口,登录、会话与入口保护都在电脑上;Cloudflare 能看到这些往来内容(与自有域名隧道相同),每个页面的请求都计入 Workers 免费额度。
173
179
 
174
180
  ## 常见问题
175
181
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.4.44",
3
+ "version": "0.4.47",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -32,7 +32,8 @@ const OLD_AGY_SKILLS = join(HOME, '.gemini', 'config', 'skills');
32
32
  const PROMPT = join(HOME, '.codex', 'AGENTS.md');
33
33
  const PROMPT_LINKS = [join(HOME, '.claude', 'CLAUDE.md'), join(HOME, '.gemini', 'config', 'AGENTS.md')];
34
34
  const RECORD = 'skills-manifest.json';
35
- const SKILL_NAME = /^[\w.-]{1,64}$/;
35
+ // Starts with a letter, digit or underscore: "." and ".." would name the folder above when joined and removed.
36
+ const SKILL_NAME = /^\w[\w.-]{0,63}$/;
36
37
 
37
38
  // ---- Layout ----
38
39
 
@@ -9,22 +9,22 @@
9
9
  */
10
10
  import { spawn, spawnSync } from 'node:child_process';
11
11
  import { randomBytes } from 'node:crypto';
12
- import { closeSync, copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, openSync, realpathSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
12
+ import { closeSync, copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, realpathSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
13
13
  import http from 'node:http';
14
14
  import { homedir, tmpdir } from 'node:os';
15
15
  import { dirname, extname, join, resolve } from 'node:path';
16
16
  import { fileURLToPath, pathToFileURL } from 'node:url';
17
17
  import { parseArgs } from 'node:util';
18
18
 
19
- import { account_home, add_account, data_home, entry_settings, entry_status, instance_home, read_accounts, remove_account, reset_password, save_entry_settings,
19
+ import { account_home, add_account, data_home, entry_settings, entry_status, instance_home as plain_instance_home, read_accounts, remove_account, reset_password, save_entry_settings,
20
20
  instance_key, set_account_disabled, set_account_protected, start_entry, stop_entry } from '../gateway/gateway.mjs';
21
- import { verified_connection } from './entry_client.mjs';
21
+ import { signed_site_url, verified_connection } from './entry_client.mjs';
22
22
  import { API_PROVIDERS, save_api_key } from './discussion_api.mjs';
23
23
  import { STT_PROVIDERS, TTS_PROVIDERS } from './tts_providers.mjs';
24
24
  import { ensure_tunnel, start_tunnel_setup, tunnel_setup_state, tunnel_status } from './hosting_tunnel.mjs';
25
25
  import { machine_links } from './remote_launch.mjs';
26
26
  import { apply_login, cancel_login, LOGIN_METHODS, login_progress, login_status, logout, start_login, submit_login } from './cli_login.mjs';
27
- import { 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,
27
+ 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,
28
28
  start_instance_as_user } from './os_users.mjs';
29
29
  import { install_workflows, shipped_workflows } from './discussion_skills.mjs';
30
30
  import { list_workflows, workflows_home } from './workflows.mjs';
@@ -188,15 +188,17 @@ async function finish_update(data) {
188
188
  throw new Error('入口没有重新启动,在“概览”页“托管”下点“启动”看原因');
189
189
  });
190
190
  if (hosting_enabled(data)) {
191
+ const accounts = await list_accounts(data);
192
+ // Isolated instances run from the shared copy: they stop before it is replaced, or files in use stay old.
193
+ for (const account of accounts) {
194
+ if (account.os_user && (job.restart || []).includes(account.name)) await update_step(steps, `已停止 ${account.name} 的实例`, () => run_instance(data, account.name, 'stop'));
195
+ }
191
196
  if (installed) await update_step(steps, '已同步隔离账号的程序副本', () => { const result = install_runtime(data); if (result.warnings.length) throw new Error(result.warnings.join(';')); });
192
- for (const account of await list_accounts(data)) {
197
+ for (const account of accounts) {
193
198
  if (installed && account.os_user) await update_step(steps, `已更新 ${account.name} 的技能`, () => prepare_account(data, account.name));
194
199
  // Reported restarted only once it serves again as the account is set (start_verified). Instances run from the
195
- // package were stopped before the install; those running from the shared copy are stopped here.
196
- if ((job.restart || []).includes(account.name)) await update_step(steps, `已重启 ${account.name} 的实例`, async () => {
197
- if (account.os_user) await run_instance(data, account.name, 'stop');
198
- await start_verified(data, account.name);
199
- });
200
+ // package were stopped before the install; those running from the shared copy were stopped above.
201
+ if ((job.restart || []).includes(account.name)) await update_step(steps, `已重启 ${account.name} 的实例`, () => start_verified(data, account.name));
200
202
  }
201
203
  }
202
204
  write_update_job(data, { ...job, status: 'done', ok: installed, steps });
@@ -204,6 +206,22 @@ async function finish_update(data) {
204
206
 
205
207
  // ---- Accounts ----
206
208
 
209
+ /**
210
+ * An account's service directory, for the owner's own reads and writes there. An isolated account may change everything
211
+ * in its folder, including replacing `service` with a link to one of the owner's folders (its keys, its launch settings);
212
+ * a path that does not lead where it says is refused, so the owner's writes cannot be redirected.
213
+ */
214
+ function instance_home(data, name) {
215
+ const path = plain_instance_home(data, name);
216
+ // Node reports a junction as a symbolic link too. The owner writes into the folder and its api-keys folder.
217
+ for (const folder of [path, join(path, 'api-keys')]) {
218
+ let link = false;
219
+ try { link = lstatSync(folder).isSymbolicLink(); } catch { link = false; }
220
+ if (link) throw new Error(`${name} 的服务目录里有指向别处的链接(${folder}),已停止操作`);
221
+ }
222
+ return path;
223
+ }
224
+
207
225
  /** Whether an instance answers on its port. */
208
226
  /** The status of a plain GET /api/rooms: a number when answered, 'down' when the port refuses, 'unknown' otherwise. */
209
227
  function plain_status(port) {
@@ -331,7 +349,7 @@ function install_runtime(data) {
331
349
  */
332
350
  function account_env(data, name, action, request = {}, folders = {}) {
333
351
  const { env_script } = shared_paths();
334
- if (!existsSync(env_script)) throw new Error('还没有安装隔离账号的程序副本,请先在“托管账号”页底部安装');
352
+ if (!existsSync(env_script)) throw new Error('还没有安装隔离账号的程序副本,请先在“概览 → 托管 → 程序副本”中同步');
335
353
  const text = run_as_user(data, name, `& ${ps_quote(process.execPath)} ${ps_quote(env_script)} ${action} $Job`,
336
354
  { files: { 'request.json': JSON.stringify(request) }, folders, timeout: 120_000 });
337
355
  const line = text.split(/\r?\n/).reverse().find(item => item.trim().startsWith('{'));
@@ -482,13 +500,20 @@ function run_instance(data, name, command) {
482
500
  const service = instance_home(data, name);
483
501
  // A protected instance starts knowing its key file; it then serves only callers that prove the key.
484
502
  const key_file = account.protected === true ? instance_key_file(name) : '';
503
+ // An account without its own Windows user runs as the owner and could read everything the owner can; it is not let
504
+ // run while people outside can reach the entry.
505
+ if (command === 'start' && process.platform === 'win32' && !read_os_users(data)[name] && entry_settings(data).mode !== 'local') {
506
+ throw new Error(`外网访问已开启,${name} 未隔离(以你的身份运行),不能启动:请先隔离该账号,或把外网访问改为“仅本机”`);
507
+ }
485
508
  if (command === 'start' && read_os_users(data)[name]) {
486
509
  const { local_script } = shared_paths();
487
- if (!existsSync(local_script)) throw new Error('还没有安装隔离账号的程序副本,请先在“托管账号”页底部安装');
510
+ if (!existsSync(local_script)) throw new Error('还没有安装隔离账号的程序副本,请先在“概览 → 托管 → 程序副本”中同步');
488
511
  // Whatever was set up first, the instance starts on the shared copies its Windows user can run.
489
512
  use_shared_programs(data, name);
490
513
  return start_instance_as_user(data, name, service, local_script, process.execPath, { key_file });
491
514
  }
515
+ // An isolated instance runs as a scheduled task that comes back when the computer starts unless it was stopped here.
516
+ if (command === 'stop' && read_os_users(data)[name]) clear_instance_flag(name);
492
517
  const { DISCUSS_ENTRY_KEY_FILE: _inherited, ...environment } = process.env;
493
518
  const child = spawn(process.execPath, [LOCAL_SCRIPT, command, '--json'], { stdio: 'ignore', windowsHide: true,
494
519
  env: { ...environment, DISCUSS_SERVICE_HOME: service, ...(key_file ? { DISCUSS_ENTRY_KEY_FILE: key_file } : {}) } });
@@ -566,7 +591,7 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
566
591
  const op = { list_accounts, add_account, reset_password, set_account_disabled, remove_account, run_instance, create_os_user, remove_os_user,
567
592
  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,
568
593
  save_api_key, list_keys, remove_key, use_shared_programs, service_overview, run_owner_service, latest_version, begin_update,
569
- autostart_enabled, set_autostart, entry_overview, start_entry, stop_entry, keep_tunnel, start_tunnel_setup, set_entry_mode, set_relay_url, connect_site, protect_account, start_verified, hand_over: () => {}, ...ops };
594
+ autostart_enabled, set_autostart, entry_overview, start_entry, stop_entry, keep_tunnel, start_tunnel_setup, set_entry_mode, set_relay_url, connect_site, make_access_code, join_relay, protect_account, start_verified, hand_over: () => {}, ...ops };
570
595
  const hosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
571
596
 
572
597
  async function api(method, path, body) {
@@ -582,6 +607,8 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
582
607
  : { accounts: [], clis: {}, entry: null }) };
583
608
  }
584
609
  // This computer: the owner's own service, its updates and login autostart.
610
+ // The owner's site opens in the default browser (not the panel's own window), through a signed link while it is protected.
611
+ if (method === 'POST' && section === 'service' && name === 'open') { open_browser(signed_site_url(site_url(data), data)); return { ok: true }; }
585
612
  if (method === 'POST' && section === 'service' && ['start', 'stop', 'restart'].includes(name)) {
586
613
  if (name !== 'start') await op.run_owner_service(data, 'stop');
587
614
  if (name !== 'stop') await op.run_owner_service(data, 'start');
@@ -644,6 +671,10 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
644
671
  if (method === 'POST' && section === 'entry' && name === 'mode') return op.set_entry_mode(data, String(body.mode || ''));
645
672
  if (method === 'POST' && section === 'entry' && name === 'relay') return op.set_relay_url(data, body.url);
646
673
  if (method === 'POST' && section === 'site' && name === 'connect') return op.connect_site(data, body.site, body.setup_key);
674
+ // The access code: made on the computer that deployed the online site, pasted on a hosting computer.
675
+ if (method === 'GET' && section === 'site' && name === 'code') return { ...deploy_settings(data), site: deploy_settings(data).site || bound_site(data)?.site || '' };
676
+ if (method === 'POST' && section === 'site' && name === 'code') return op.make_access_code(data, body);
677
+ if (method === 'POST' && section === 'relay' && name === 'join') return op.join_relay(data, body.code);
647
678
  // The outside address: a Cloudflare tunnel set up by a job of its own (it waits for the owner in the browser).
648
679
  if (section === 'tunnel' && name === 'setup') {
649
680
  if (method === 'GET') return tunnel_setup_state(data);
@@ -661,7 +692,8 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
661
692
  if (method === 'POST' && action === 'password') return { password: op.reset_password(data, name) };
662
693
  if (method === 'POST' && action === 'protect') return op.protect_account(data, name, body.on !== false);
663
694
  if (method === 'POST' && (action === 'disable' || action === 'enable')) { op.set_account_disabled(data, name, action === 'disable'); return { disabled: action === 'disable' }; }
664
- if (method === 'POST' && action === 'remove') { op.remove_account(data, name); return { removed: name, kept: account_home(data, name) }; }
695
+ // The instance stops first: its port goes to the next new account, which must not reach this one's instance.
696
+ 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) }; }
665
697
  // A start is reported only once the instance serves as the account is set (protected or not).
666
698
  if (method === 'POST' && action === 'start') { await op.start_verified(data, name); return { ok: true }; }
667
699
  if (method === 'POST' && action === 'stop') { await op.run_instance(data, name, action); return { ok: true }; }
@@ -749,30 +781,115 @@ async function relay_status(relay_url, machine) {
749
781
  } catch { return { reachable: false, online: false }; }
750
782
  }
751
783
 
784
+ /** What stands between people outside and this computer over the relay, in the order to look at it; '' when nothing. */
785
+ function relay_problem(relay, entry_running, service_running) {
786
+ if (!relay.reachable) return '入口地址连不上:检查网络与代理是否放行 *.workers.dev';
787
+ if (!service_running) return '本机服务没有在运行,电脑连不上线上站点:在上面“本机”里启动共议服务';
788
+ if (!relay.online) return '电脑还没连上线上站点:本机服务刚启动时稍等几秒;持续如此,可能这台电脑绑定的站点与入口不属于同一个 Cloudflare 账号,重新用接入码接入';
789
+ if (!entry_running) return '登录入口没有在运行:点上面的“启动”';
790
+ return '';
791
+ }
792
+
752
793
  async function entry_overview(data) {
753
794
  const { port, public_url, tunnel, mode, relay_url } = entry_settings(data), status = await entry_status(data);
754
795
  const bound = bound_site(data);
755
796
  const relay = { url: relay_url, site: bound?.site || '', link: relay_url && bound ? `${relay_url}/?m=${bound.machine}` : '',
756
797
  ...(mode === 'relay' && relay_url && bound ? await relay_status(relay_url, bound.machine) : {}) };
798
+ if (mode === 'relay') relay.problem = relay_problem(relay, status.running, Boolean(local_status(data).running));
757
799
  // The address people open in the mode in use.
758
800
  const address = mode === 'relay' ? relay.link : mode === 'tunnel' ? public_url : '';
759
801
  return { running: status.running, port: status.running ? status.port : port, public_url, mode, address, relay,
760
802
  tunnel: tunnel ? { host: tunnel.host, name: tunnel.name, ...(await tunnel_status(data)) } : null };
761
803
  }
762
804
 
763
- /** Switch how people outside reach the entry, once what that way needs is there; the tunnel follows at once. */
805
+ /**
806
+ * Switch how people outside reach the entry, once what that way needs is there. Reaching it from outside needs the entry
807
+ * running, and the relay needs this computer's service (which holds the relay connection): both are started here rather
808
+ * than left for the first person to find a broken link. The tunnel follows at once.
809
+ */
764
810
  async function set_entry_mode(data, mode) {
765
811
  const settings = entry_settings(data);
766
812
  if (mode === 'relay') {
767
- if (!bound_site(data)) throw new Error('这台电脑还没有绑定线上站点:先在下面绑定');
768
- if (!settings.relay_url) throw new Error('还没有填写入口地址(入口 Worker 的 workers.dev 地址)');
813
+ if (!bound_site(data)) throw new Error('这台电脑还没有接入线上站点:先用接入码接入');
814
+ if (!settings.relay_url) throw new Error('还没有入口地址:先用接入码接入');
769
815
  }
770
816
  if (mode === 'tunnel' && !settings.tunnel) throw new Error('还没有设好 Cloudflare 隧道:先点“设置”填写你的域名');
817
+ if (mode !== 'local' && process.platform === 'win32') {
818
+ const users = read_os_users(data), accounts = read_accounts(data);
819
+ const exposed = [];
820
+ for (const [name, account] of Object.entries(accounts)) if (!users[name] && await instance_running(account.port)) exposed.push(name);
821
+ if (exposed.length) throw new Error(`未隔离的账号正在运行(${exposed.join('、')}),它们以你的身份运行,开启外网访问前请先停止或隔离`);
822
+ }
771
823
  save_entry_settings(data, { mode });
824
+ if (mode !== 'local' && !(await entry_status(data)).running) { await start_entry(data); save_entry_settings(data, { running: true }); }
825
+ if (mode === 'relay' && !local_status(data).running) await run_owner_service(data, 'start');
772
826
  await keep_tunnel(data);
773
827
  return entry_overview(data);
774
828
  }
775
829
 
830
+ // Where the panel of the computer that deployed the online site remembers its deployment config and the site's address.
831
+ const DEPLOY_FILE = 'panel-deploy.json';
832
+ const BIND_MARK = '#codiscuss-bind=';
833
+
834
+ function deploy_settings(data) {
835
+ try { return JSON.parse(readFileSync(join(data, DEPLOY_FILE), 'utf8')); } catch { return {}; }
836
+ }
837
+
838
+ /** The folder above a deployment config that has wrangler installed, so npx finds it rather than downloading it. */
839
+ function wrangler_folder(config) {
840
+ for (let folder = dirname(config); ; folder = dirname(folder)) {
841
+ if (existsSync(join(folder, 'node_modules', 'wrangler'))) return folder;
842
+ if (dirname(folder) === folder) return dirname(config);
843
+ }
844
+ }
845
+
846
+ /**
847
+ * On the computer that deployed the online site: make an access code for a hosting computer, the site's address with a
848
+ * one-time binding token (`codiscuss token`, written to the site's database through wrangler, in a child process so the
849
+ * panel keeps answering). A new code makes an unused earlier one invalid. The config and site are remembered.
850
+ */
851
+ function make_access_code(data, { config, site }) {
852
+ const saved = deploy_settings(data);
853
+ const path = resolve(String(config || saved.config || '').trim() || '.');
854
+ if (!existsSync(path) || !/\.jsonc?$/.test(path)) throw new Error('找不到线上站点的部署配置:填写源码仓库里 .wrangler\\deploy\\wrangler.jsonc 的完整路径');
855
+ let origin;
856
+ try { origin = new URL(String(site || saved.site || bound_site(data)?.site || '').trim()).origin; } catch { throw new Error('站点地址格式不对,例如 https://xxx.pages.dev'); }
857
+ return new Promise((done, fail) => {
858
+ const child = spawn(process.execPath, [installed_script('codiscuss.mjs'), 'token', '--config', path], { cwd: wrangler_folder(path), windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
859
+ let output = '', errors = '';
860
+ child.stdout.on('data', chunk => { output += chunk; });
861
+ child.stderr.on('data', chunk => { errors += chunk; });
862
+ child.on('error', fail);
863
+ child.on('exit', code => {
864
+ const token = output.match(/^([0-9a-f]{32,})$/m)?.[1];
865
+ if (code !== 0 || !token) return fail(new Error(errors.trim().split(/\r?\n/).pop() || '没有生成绑定令牌'));
866
+ write_settings(join(data, DEPLOY_FILE), { config: path, site: origin });
867
+ done({ code: `${origin}/${BIND_MARK}${token}`, site: origin });
868
+ });
869
+ });
870
+ }
871
+
872
+ /**
873
+ * On a hosting computer: join the online relay with an access code, each step reported. Bind to the site (unless bound
874
+ * already), take the entry address the site gives, then switch to the relay, which starts what it needs.
875
+ */
876
+ async function join_relay(data, text) {
877
+ const value = String(text || '').trim();
878
+ const at = value.indexOf(BIND_MARK);
879
+ if (at < 0) throw new Error('接入码不对:应是部署线上站点的电脑上生成的一整串,形如 https://xxx.pages.dev/#codiscuss-bind=…');
880
+ const site = new URL(value.slice(0, at)).origin, token = value.slice(at + BIND_MARK.length);
881
+ const steps = [];
882
+ if (bound_site(data)?.site === site) steps.push(`已接入 ${site}`);
883
+ else { await connect_site(data, site, token); steps.push(`已接入 ${site}`); }
884
+ const given = await fetch(`${site}/api/entry`, { signal: AbortSignal.timeout(RELAY_CHECK_MS) }).then(answer => answer.json()).catch(() => ({}));
885
+ if (!given.entry_url) throw new Error(`${site} 没有提供入口地址:请部署线上站点的人在部署配置里设置 ENTRY_URL 并重新发布`);
886
+ await set_relay_url(data, given.entry_url);
887
+ steps.push(`入口地址 ${given.entry_url}`);
888
+ const overview = await set_entry_mode(data, 'relay');
889
+ steps.push('已切换到线上中转');
890
+ return { steps, entry: overview };
891
+ }
892
+
776
893
  /** Save the relay's entry address after checking that it answers as one. */
777
894
  async function set_relay_url(data, url) {
778
895
  const origin = String(url || '').trim().replace(/\/+$/, '');
@@ -863,7 +980,7 @@ export async function relay_operator_events(data, send = send_notice, ready = ca
863
980
  try { marks = JSON.parse(readFileSync(state_file, 'utf8')) || {}; } catch { marks = {}; }
864
981
  const notified = [];
865
982
  for (const name of Object.keys(read_accounts(data))) {
866
- const path = join(instance_home(data, name), OPERATOR_EVENTS_FILE);
983
+ const path = join(plain_instance_home(data, name), OPERATOR_EVENTS_FILE);
867
984
  let read = null;
868
985
  // The outbox is in the account's own folder: a link anywhere on its path (the file, or a folder above it that the
869
986
  // account replaced with a junction) is not followed, so only a file really inside that folder is read.
@@ -1028,7 +1145,7 @@ function run_panel(data, port) {
1028
1145
  const tray = show_tray({ title: '共议', icon_path: existsSync(icon) ? icon : '', window_title: WINDOW_TITLE,
1029
1146
  host: join(data, 'launcher', '共议.exe'), on_action: action => {
1030
1147
  if (action === 'open') open_panel_window(data, panel_url(state), false);
1031
- if (action === 'site') open_browser(site_url(data));
1148
+ if (action === 'site') open_browser(signed_site_url(site_url(data), data));
1032
1149
  // Restarting and closing take seconds and show nothing of their own, so the icon says what is happening.
1033
1150
  if (action === 'restart') {
1034
1151
  tray.notify('busy', '正在重启共议服务…');
@@ -16,7 +16,7 @@ import { tmpdir } from 'node:os';
16
16
  import { dirname, join } from 'node:path';
17
17
  import { fileURLToPath } from 'node:url';
18
18
 
19
- import { cli_sources, read_os_users, read_output, run_as_user } from './os_users.mjs';
19
+ import { cli_sources, read_os_users, read_output, run_as_user, run_powershell } from './os_users.mjs';
20
20
 
21
21
  const AGENT = join(dirname(fileURLToPath(import.meta.url)), 'cli_login_agent.mjs');
22
22
  const POWERSHELL = 'powershell.exe';
@@ -138,8 +138,24 @@ function start_agent_login(data, target, cli, args) {
138
138
  return run_as_user(data, target, `& ${quote(process.execPath)} (Join-Path $Job 'agent.mjs') login $Job`, { files, wait: false });
139
139
  }
140
140
  const folder = owner_folder(files);
141
- spawn(process.execPath, [AGENT, 'login', folder], { detached: true, stdio: 'ignore', windowsHide: true }).unref();
142
- return { folder };
141
+ const child = spawn(process.execPath, [AGENT, 'login', folder], { detached: true, stdio: 'ignore', windowsHide: true });
142
+ child.unref();
143
+ return { folder, pid: child.pid || 0 };
144
+ }
145
+
146
+ /**
147
+ * Whether the program listening on Codex's callback port was started by this sign-in (the port is shared by every user
148
+ * of this computer: another hosted account's process could listen there first and receive the authorization code).
149
+ */
150
+ function callback_listener_is(pid) {
151
+ if (!pid) return false;
152
+ return run_powershell(`$listener = (Get-NetTCPConnection -LocalPort 1455 -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1).OwningProcess
153
+ if (-not $listener) { 'none'; exit 0 }
154
+ $parents = @{}
155
+ Get-CimInstance Win32_Process | ForEach-Object { $parents[[int]$_.ProcessId] = [int]$_.ParentProcessId }
156
+ $current = [int]$listener
157
+ for ($step = 0; $step -lt 12 -and $current; $step++) { if ($current -eq ${Number(pid)}) { 'ours'; exit 0 }; $current = $parents[$current] }
158
+ 'other'`) === 'ours';
143
159
  }
144
160
 
145
161
  function start_console(data, target, exe) {
@@ -209,6 +225,9 @@ export async function submit_login(id, text) {
209
225
  if (!['localhost', '127.0.0.1'].includes(address.hostname) || address.port !== '1455' || address.pathname !== '/auth/callback') {
210
226
  throw new Error('这不是 Codex 的登录回调地址:应以 http://localhost:1455/auth/callback 开头');
211
227
  }
228
+ if (process.platform === 'win32' && !callback_listener_is(job.pid)) {
229
+ throw new Error('1455 端口上不是本次登录启动的 Codex(可能被其他程序占用),为防止授权码泄露,已停止;请重新开始登录');
230
+ }
212
231
  const response = await fetch(`${CODEX_CALLBACK}${address.pathname}${address.search}`, { redirect: 'manual', signal: AbortSignal.timeout(20_000) });
213
232
  if (response.status >= 400) throw new Error(`Codex 没有接受这个地址(HTTP ${response.status}),请重新开始登录`);
214
233
  return { ok: true };
package/runner/discuss.py CHANGED
@@ -1137,9 +1137,25 @@ ENTRY_NONCE_PATTERN = re.compile(r"^[0-9a-f]{32}$")
1137
1137
  LOOPBACK_HOSTS = ("127.0.0.1", "localhost", "::1")
1138
1138
 
1139
1139
 
1140
- def entry_key():
1140
+ def owner_key_file(url):
1141
+ """The owner's own site key file for a request to the owner's port, when that site runs protected (hosting on).
1142
+
1143
+ Used only when the environment names no key file: the owner's command line in a terminal (runner/entry_client.mjs).
1144
+ """
1145
+ home = Path(os.getenv("DISCUSS_SERVICE_HOME") or Path.home() / ".codiscuss")
1146
+ path = home / "local" / "site-key.json"
1147
+ if not path.is_file():
1148
+ return ""
1149
+ try:
1150
+ port = int(json.loads((home / "local-settings.json").read_text(encoding="utf-8")).get("port") or 8765)
1151
+ except (OSError, ValueError, TypeError, AttributeError):
1152
+ port = 8765
1153
+ return str(path) if (urlsplit(url).port or 80) == port else ""
1154
+
1155
+
1156
+ def entry_key(url=""):
1141
1157
  """This instance's key when entry protection is configured, '' when it is not; an unusable key stops the request."""
1142
- path = os.getenv(ENTRY_KEY_VARIABLE)
1158
+ path = os.getenv(ENTRY_KEY_VARIABLE) or (owner_key_file(url) if url else "")
1143
1159
  if not path:
1144
1160
  return ""
1145
1161
  try:
@@ -1191,7 +1207,7 @@ def send_request(plan, url, timeout, headers=None):
1191
1207
  "User-Agent": f"AI-CoDiscuss-CLI/{VERSION}", **(headers or {})}
1192
1208
  request = Request(url, data=data, method=plan.method, headers=fields)
1193
1209
  # A protected instance on this computer is reached only through the handshake; nothing falls back to a plain request.
1194
- key = entry_key() if urlsplit(url).hostname in LOOPBACK_HOSTS else ""
1210
+ key = entry_key(url) if urlsplit(url).hostname in LOOPBACK_HOSTS else ""
1195
1211
  deadline = time.monotonic() + REFUSED_RETRY_SECONDS
1196
1212
  while True:
1197
1213
  try:
@@ -14,7 +14,7 @@ import { assert_shared_home, main as service_main, service_home, service_pid, se
14
14
  import { detect_python, local_settings } from './discussion_setup.mjs';
15
15
  import { unlink_machine } from './remote_launch.mjs';
16
16
  import { tone } from './discussion_tui.mjs';
17
- import { site_fetch } from './entry_client.mjs';
17
+ import { set_owner_protection, signed_site_url, site_fetch } from './entry_client.mjs';
18
18
 
19
19
  const SCRIPT = fileURLToPath(import.meta.url);
20
20
  const SERVER = fileURLToPath(new URL('../server.py', import.meta.url));
@@ -68,7 +68,7 @@ async function connect_site(home, site, no_open, setup_key) {
68
68
  const state = await fetch(`${origin}/api/admin`, { redirect: 'error', signal: AbortSignal.timeout(10000) }).then(response => response.json()).catch(() => ({}));
69
69
  if (state.devices) {
70
70
  await bind_machine(home, origin, setup_key);
71
- if (!no_open) open_site(`${local.url}/#settings=devices`);
71
+ if (!no_open) open_site(signed_site_url(`${local.url}/#settings=devices`, home));
72
72
  return { connected: origin, local_url: local.url, url: `${local.url}/#settings=devices`, bound: true };
73
73
  }
74
74
  const token = randomBytes(CONNECTION_TOKEN_BYTES).toString('hex');
@@ -186,10 +186,27 @@ async function requested_service(home, status, owned_service) {
186
186
  // projects root) have neither.
187
187
  const PANEL_SCRIPT = join(dirname(fileURLToPath(import.meta.url)), 'admin_panel.mjs');
188
188
 
189
+ /** Whether this is the computer owner's own Windows instance (not a hosted account's, a test's or a second copy's). */
190
+ function owner_instance(home, settings) {
191
+ return process.platform === 'win32' && !settings.projects_root && resolve(home) === resolve(homedir(), '.codiscuss');
192
+ }
193
+
194
+ /**
195
+ * Whether the owner's site runs protected: while hosting is on, hosted accounts' processes share this loopback and would
196
+ * otherwise reach the owner's site as its implicit administrator. Sets this process's environment, which the website,
197
+ * the discussion service and every member they start inherit, so they all prove themselves.
198
+ */
199
+ function apply_owner_protection(home, settings) {
200
+ if (!owner_instance(home, settings)) return Boolean(process.env.DISCUSS_ENTRY_KEY_FILE);
201
+ const key_file = set_owner_protection(home, settings.hosting === true);
202
+ if (key_file) process.env.DISCUSS_ENTRY_KEY_FILE = key_file; else delete process.env.DISCUSS_ENTRY_KEY_FILE;
203
+ return Boolean(key_file);
204
+ }
205
+
189
206
  /** Start the taskbar icon (and panel) in the background on the owner's Windows instance; it keeps running on its own. */
190
207
  function start_panel_icon(home, settings) {
191
208
  // Only the owner's default service directory: a test or a second copy elsewhere must not put up another icon.
192
- if (process.platform !== 'win32' || settings.projects_root || resolve(home) !== resolve(homedir(), '.codiscuss')) return;
209
+ if (!owner_instance(home, settings)) return;
193
210
  if (!existsSync(PANEL_SCRIPT)) return;
194
211
  const child = spawn(process.execPath, [PANEL_SCRIPT, 'start', '--data', home], { detached: true, stdio: 'ignore', windowsHide: true });
195
212
  child.on('error', () => {});
@@ -208,7 +225,7 @@ async function supervise(home) {
208
225
  const stop_path = join(directory, 'stop.request');
209
226
  const settings = local_settings(home);
210
227
  const url = `http://127.0.0.1:${settings.port || 8765}`;
211
- const status = { pid: process.pid, ready: false, url, version: VERSION };
228
+ const status = { pid: process.pid, ready: false, url, version: VERSION, protected: apply_owner_protection(home, settings) };
212
229
  if (existsSync(stop_path)) unlinkSync(stop_path);
213
230
  atomic_json(status_path, status);
214
231
  let website, owned_service, stopped = false;
@@ -278,6 +295,9 @@ export function restart_reason(home = service_home()) {
278
295
  if (current.url !== url) return `本机网站正在 ${current.url} 运行,端口配置已改为 ${url}`;
279
296
  // A website started with the retired remote entry is restarted without it.
280
297
  if (current.remote_port) return '本机网站仍开着已停用的远程入口';
298
+ if (owner_instance(home, settings) && Boolean(current.protected) !== (settings.hosting === true)) {
299
+ return settings.hosting === true ? '托管已开启,本机网站需要以受保护方式重启' : '托管已关闭,本机网站需要取消保护后重启';
300
+ }
281
301
  if (current.version !== VERSION) return `本机网站正在运行${current.version ? `版本 ${current.version}` : '未记录版本的旧程序'},当前安装为 ${VERSION}`;
282
302
  return null;
283
303
  }
@@ -348,7 +368,7 @@ export async function local_main(args, output) {
348
368
  }
349
369
  if (positionals.length > 1 || values['no-open'] || !['open', 'start', 'status', 'stop'].includes(command)) throw new Error(LOCAL_HELP);
350
370
  const result = command === 'status' ? local_status(home) : command === 'stop' ? await stop_local(home) : await start_local(home);
351
- if (command === 'open') open_site(result.url);
371
+ if (command === 'open') open_site(signed_site_url(result.url, home));
352
372
  report(result, command === 'open');
353
373
  return result;
354
374
  }