ai_co_discuss 0.4.45 → 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.
- package/backend/entry_guard.py +36 -0
- package/backend/server.py +26 -2
- package/package.json +1 -1
- package/runner/account_env.mjs +2 -1
- package/runner/admin_panel.mjs +49 -15
- package/runner/cli_login.mjs +22 -3
- package/runner/discuss.py +19 -3
- package/runner/discussion_local.mjs +25 -5
- package/runner/entry_client.mjs +51 -2
- package/runner/os_users.mjs +101 -20
- package/runner/skill_library.mjs +2 -1
- package/web/admin.css +1 -1
- package/web/admin.js +3 -3
- package/web/modern.js +2 -2
package/backend/entry_guard.py
CHANGED
|
@@ -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,
|
|
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
|
-
|
|
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):
|
package/package.json
CHANGED
package/runner/account_env.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
|
package/runner/admin_panel.mjs
CHANGED
|
@@ -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
|
|
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
|
|
196
|
-
if ((job.restart || []).includes(account.name)) await update_step(steps, `已重启 ${account.name} 的实例`,
|
|
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 } : {}) } });
|
|
@@ -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');
|
|
@@ -665,7 +692,8 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
|
|
|
665
692
|
if (method === 'POST' && action === 'password') return { password: op.reset_password(data, name) };
|
|
666
693
|
if (method === 'POST' && action === 'protect') return op.protect_account(data, name, body.on !== false);
|
|
667
694
|
if (method === 'POST' && (action === 'disable' || action === 'enable')) { op.set_account_disabled(data, name, action === 'disable'); return { disabled: action === 'disable' }; }
|
|
668
|
-
|
|
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) }; }
|
|
669
697
|
// A start is reported only once the instance serves as the account is set (protected or not).
|
|
670
698
|
if (method === 'POST' && action === 'start') { await op.start_verified(data, name); return { ok: true }; }
|
|
671
699
|
if (method === 'POST' && action === 'stop') { await op.run_instance(data, name, action); return { ok: true }; }
|
|
@@ -786,6 +814,12 @@ async function set_entry_mode(data, mode) {
|
|
|
786
814
|
if (!settings.relay_url) throw new Error('还没有入口地址:先用接入码接入');
|
|
787
815
|
}
|
|
788
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
|
+
}
|
|
789
823
|
save_entry_settings(data, { mode });
|
|
790
824
|
if (mode !== 'local' && !(await entry_status(data)).running) { await start_entry(data); save_entry_settings(data, { running: true }); }
|
|
791
825
|
if (mode === 'relay' && !local_status(data).running) await run_owner_service(data, 'start');
|
|
@@ -946,7 +980,7 @@ export async function relay_operator_events(data, send = send_notice, ready = ca
|
|
|
946
980
|
try { marks = JSON.parse(readFileSync(state_file, 'utf8')) || {}; } catch { marks = {}; }
|
|
947
981
|
const notified = [];
|
|
948
982
|
for (const name of Object.keys(read_accounts(data))) {
|
|
949
|
-
const path = join(
|
|
983
|
+
const path = join(plain_instance_home(data, name), OPERATOR_EVENTS_FILE);
|
|
950
984
|
let read = null;
|
|
951
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
|
|
952
986
|
// account replaced with a junction) is not followed, so only a file really inside that folder is read.
|
|
@@ -1111,7 +1145,7 @@ function run_panel(data, port) {
|
|
|
1111
1145
|
const tray = show_tray({ title: '共议', icon_path: existsSync(icon) ? icon : '', window_title: WINDOW_TITLE,
|
|
1112
1146
|
host: join(data, 'launcher', '共议.exe'), on_action: action => {
|
|
1113
1147
|
if (action === 'open') open_panel_window(data, panel_url(state), false);
|
|
1114
|
-
if (action === 'site') open_browser(site_url(data));
|
|
1148
|
+
if (action === 'site') open_browser(signed_site_url(site_url(data), data));
|
|
1115
1149
|
// Restarting and closing take seconds and show nothing of their own, so the icon says what is happening.
|
|
1116
1150
|
if (action === 'restart') {
|
|
1117
1151
|
tray.notify('busy', '正在重启共议服务…');
|
package/runner/cli_login.mjs
CHANGED
|
@@ -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 })
|
|
142
|
-
|
|
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
|
|
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 (
|
|
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
|
}
|
package/runner/entry_client.mjs
CHANGED
|
@@ -10,9 +10,11 @@
|
|
|
10
10
|
* to another, unverified connection; nothing here retries on a new one.
|
|
11
11
|
*/
|
|
12
12
|
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
13
|
-
import { readFileSync } from 'node:fs';
|
|
13
|
+
import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
14
14
|
import http from 'node:http';
|
|
15
15
|
import net from 'node:net';
|
|
16
|
+
import { homedir } from 'node:os';
|
|
17
|
+
import { join } from 'node:path';
|
|
16
18
|
import { Readable } from 'node:stream';
|
|
17
19
|
|
|
18
20
|
export const ENTRY_KEY_PATTERN = /^[0-9a-f]{64}$/;
|
|
@@ -113,6 +115,53 @@ export function entry_access() {
|
|
|
113
115
|
return process.env[KEY_FILE_VARIABLE] ? { entry_key_file: process.env[KEY_FILE_VARIABLE] } : {};
|
|
114
116
|
}
|
|
115
117
|
|
|
118
|
+
// The computer owner's own site is protected while hosting is on (every hosted account's processes share this loopback);
|
|
119
|
+
// its key then sits in the owner's service directory, which no hosted account can open.
|
|
120
|
+
const OWNER_KEY_FILE = join('local', 'site-key.json');
|
|
121
|
+
|
|
122
|
+
/** The owner's site key file in a service directory (it exists only while that site runs protected). */
|
|
123
|
+
export function owner_key_file(home) {
|
|
124
|
+
return join(home, OWNER_KEY_FILE);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Turn the owner site's protection on or off for the next start: on writes a new key file (kept if one is there), off
|
|
129
|
+
* removes it. Returns the key file's path when on, '' when off.
|
|
130
|
+
*/
|
|
131
|
+
export function set_owner_protection(home, on) {
|
|
132
|
+
const path = owner_key_file(home);
|
|
133
|
+
if (!on) { try { unlinkSync(path); } catch { /* already off */ } return ''; }
|
|
134
|
+
if (!existsSync(path)) writeFileSync(path, `${JSON.stringify({ key: randomBytes(32).toString('hex') })}\n`, { mode: 0o600 });
|
|
135
|
+
return path;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The key file a request to `target` proves itself with when the caller's environment names none: the owner's own site
|
|
140
|
+
* key, for the owner's own port only (the owner's command line in a terminal, started outside the service).
|
|
141
|
+
*/
|
|
142
|
+
function default_key_file(target) {
|
|
143
|
+
const home = process.env.DISCUSS_SERVICE_HOME || join(homedir(), '.codiscuss');
|
|
144
|
+
const path = owner_key_file(home);
|
|
145
|
+
if (!existsSync(path)) return '';
|
|
146
|
+
let port = 8765;
|
|
147
|
+
try { port = Number(JSON.parse(readFileSync(join(home, 'local-settings.json'), 'utf8')).port) || 8765; } catch { /* default port */ }
|
|
148
|
+
return Number(target.port || 80) === port ? path : '';
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* A link that opens the owner's protected site in a browser: the site turns it into a cookie (backend/entry_guard.py).
|
|
153
|
+
* The URL is returned unchanged when the site is not protected. A fragment is kept (browsers keep it across the redirect).
|
|
154
|
+
*/
|
|
155
|
+
export function signed_site_url(url, home) {
|
|
156
|
+
const path = owner_key_file(home);
|
|
157
|
+
let key = '';
|
|
158
|
+
try { key = String(JSON.parse(readFileSync(path, 'utf8')).key || ''); } catch { return url; }
|
|
159
|
+
if (!ENTRY_KEY_PATTERN.test(key)) return url;
|
|
160
|
+
const target = new URL(url);
|
|
161
|
+
const at = String(Math.floor(Date.now() / 1000));
|
|
162
|
+
return `${target.origin}/_instance/open?at=${at}&sig=${entry_proof(key, 'open', at)}${target.hash}`;
|
|
163
|
+
}
|
|
164
|
+
|
|
116
165
|
/** The instance key when protection is configured: '' when it is not, an error when it is but unusable. */
|
|
117
166
|
function configured_key(key_file = process.env[KEY_FILE_VARIABLE]) {
|
|
118
167
|
const path = key_file;
|
|
@@ -133,7 +182,7 @@ function configured_key(key_file = process.env[KEY_FILE_VARIABLE]) {
|
|
|
133
182
|
*/
|
|
134
183
|
export async function site_fetch(url, init = {}, { key_file } = {}) {
|
|
135
184
|
const target = new URL(url);
|
|
136
|
-
const key = LOOPBACK_HOSTS.has(target.hostname) ? configured_key(key_file || process.env[KEY_FILE_VARIABLE]) : '';
|
|
185
|
+
const key = LOOPBACK_HOSTS.has(target.hostname) ? configured_key(key_file || process.env[KEY_FILE_VARIABLE] || default_key_file(target)) : '';
|
|
137
186
|
if (!key) return fetch(url, init);
|
|
138
187
|
const port = Number(target.port || 80);
|
|
139
188
|
const { socket, header } = await verified_connection(port, key, { signal: init.signal });
|