ai_co_discuss 0.4.43 → 0.4.44

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.
@@ -161,6 +161,16 @@ npx wrangler deploy --config deploy/updates.wrangler.jsonc
161
161
 
162
162
  旧版还提供推送对象 `DiscussionUpdates`(绑定名 `UPDATES`),新版已删除:私有配置里有 `UPDATES` 绑定时,先删掉它并重新部署 Pages,再部署中转 Worker,否则 Worker 删除该对象时 Pages 会失去绑定。
163
163
 
164
+ ### 托管账号的入口(可选)
165
+
166
+ 开了托管管理、想让托管账号的使用者不用自有域名就能从外网登录时,再部署入口 Worker(在中转之后部署,它使用中转的 Durable Object):
167
+
168
+ ```sh
169
+ npx wrangler deploy --config deploy/entry.wrangler.jsonc
170
+ ```
171
+
172
+ 它有自己的 `workers.dev` 地址(如 `https://codiscuss-entry.<账号子域>.workers.dev`),与线上站点不同源,托管账号的网页碰不到你已配对设备的密钥。托管电脑绑定线上站点后,在管理面板“概览 → 托管 → 登录入口”的“外网访问”选“线上中转”,填这个地址;面板给出的链接带电脑编号(`?m=…`),发给使用者即可。使用者的请求经入口 Worker 和中转到达这台电脑的登录入口,登录、会话与入口保护都在电脑上;Cloudflare 能看到这些往来内容(与自有域名隧道相同),每个页面的请求都计入 Workers 免费额度。
173
+
164
174
  ## 常见问题
165
175
 
166
176
  - **`no such table`**:所连接的数据库尚未执行 schema,先核对配置文件指向的数据库。
@@ -503,12 +503,20 @@ function run_instance(data, name, command) {
503
503
 
504
504
  // ---- The entry as a background process the panel starts and stops ----
505
505
 
506
- /** The entry's saved settings: the loopback port it listens on and the public address customers open. */
506
+ // How people outside reach the entry: this computer only, the online relay (no domain needed), or a Cloudflare tunnel
507
+ // from the owner's own domain.
508
+ export const ENTRY_MODES = ['local', 'relay', 'tunnel'];
509
+
510
+ /**
511
+ * The entry's saved settings: the loopback port it listens on, the public address customers open, and how they reach it
512
+ * (`mode`). Settings from before the mode was chosen read as the way they set up: the tunnel when one is, else local.
513
+ */
507
514
  export function entry_settings(data) {
508
515
  const saved = read_json(join(data, ENTRY_SETTINGS_FILE));
509
516
  const tunnel = saved.tunnel && typeof saved.tunnel === 'object' && ['name', 'host', 'id', 'credentials'].every(key => saved.tunnel[key]) ? saved.tunnel : null;
517
+ const mode = ENTRY_MODES.includes(saved.mode) ? saved.mode : tunnel ? 'tunnel' : 'local';
510
518
  return { port: Number.isInteger(saved.port) ? saved.port : DEFAULT_ENTRY_PORT, public_url: typeof saved.public_url === 'string' ? saved.public_url : '',
511
- running: saved.running === true, tunnel };
519
+ running: saved.running === true, tunnel, mode, relay_url: typeof saved.relay_url === 'string' ? saved.relay_url : '' };
512
520
  }
513
521
 
514
522
  /**
@@ -517,13 +525,19 @@ export function entry_settings(data) {
517
525
  * Args:
518
526
  * changes: `port` (1–65535), `public_url` (an https address, kept as its origin; empty clears it), `running`, the
519
527
  * state the panel restores when it starts again, and `tunnel`, the Cloudflare tunnel the panel runs for the outside
520
- * address ({ name, host, id, credentials } from hosting_tunnel.mjs, or null for none).
528
+ * address ({ name, host, id, credentials } from hosting_tunnel.mjs, or null for none), `mode` (one of ENTRY_MODES)
529
+ * and `relay_url`, the address of the relay's entry Worker (an https origin; empty clears it).
521
530
  *
522
531
  * Returns:
523
532
  * The settings as saved.
524
533
  */
525
534
  export function save_entry_settings(data, changes) {
526
535
  const next = { ...entry_settings(data) };
536
+ if (changes.mode !== undefined) {
537
+ if (!ENTRY_MODES.includes(changes.mode)) throw new Error(`未知的外网访问方式:${changes.mode}`);
538
+ next.mode = changes.mode;
539
+ }
540
+ if (changes.relay_url !== undefined) next.relay_url = public_origin(changes.relay_url);
527
541
  if (changes.port !== undefined) {
528
542
  const port = Number(changes.port);
529
543
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('入口端口须为 1–65535 的整数');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.4.43",
3
+ "version": "0.4.44",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -22,6 +22,7 @@ import { 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
+ import { machine_links } from './remote_launch.mjs';
25
26
  import { apply_login, cancel_login, LOGIN_METHODS, login_progress, login_status, logout, start_login, submit_login } from './cli_login.mjs';
26
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
28
  start_instance_as_user } from './os_users.mjs';
@@ -52,6 +53,8 @@ const OWNER_ENV_TIMEOUT_MS = 120_000;
52
53
  // How often the panel makes sure the entry's tunnel runs as set, and how long an update waits for the entry to be back.
53
54
  const TUNNEL_CHECK_MS = 60_000;
54
55
  const ENTRY_BACK_MS = 15_000;
56
+ // How long the panel waits for the relay's entry Worker to answer whether it is reachable.
57
+ const RELAY_CHECK_MS = 5000;
55
58
  // Hosted accounts' failures, relayed to the owner's Weixin: how often, how far each account's outbox was read, and limits
56
59
  // on what one notice carries (the outbox is in the account's own folder, so its text is the account's, not ours).
57
60
  const RELAY_MS = 30_000;
@@ -563,7 +566,7 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
563
566
  const op = { list_accounts, add_account, reset_password, set_account_disabled, remove_account, run_instance, create_os_user, remove_os_user,
564
567
  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,
565
568
  save_api_key, list_keys, remove_key, use_shared_programs, service_overview, run_owner_service, latest_version, begin_update,
566
- autostart_enabled, set_autostart, entry_overview, start_entry, stop_entry, keep_tunnel, start_tunnel_setup, protect_account, start_verified, hand_over: () => {}, ...ops };
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 };
567
570
  const hosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
568
571
 
569
572
  async function api(method, path, body) {
@@ -637,6 +640,10 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
637
640
  await op.keep_tunnel(data);
638
641
  return op.entry_overview(data);
639
642
  }
643
+ // How people outside reach the entry, the relay's entry address, and binding this computer to an online site.
644
+ if (method === 'POST' && section === 'entry' && name === 'mode') return op.set_entry_mode(data, String(body.mode || ''));
645
+ if (method === 'POST' && section === 'entry' && name === 'relay') return op.set_relay_url(data, body.url);
646
+ if (method === 'POST' && section === 'site' && name === 'connect') return op.connect_site(data, body.site, body.setup_key);
640
647
  // The outside address: a Cloudflare tunnel set up by a job of its own (it waits for the owner in the browser).
641
648
  if (section === 'tunnel' && name === 'setup') {
642
649
  if (method === 'GET') return tunnel_setup_state(data);
@@ -723,16 +730,71 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
723
730
  /** The account entry as the hosting page shows it: whether it runs, its loopback port and the address customers open. */
724
731
  /** Keep the entry's tunnel as the settings say: running while hosting is on and the entry is meant to run. */
725
732
  function keep_tunnel(data) {
726
- const { tunnel, port, running } = entry_settings(data);
727
- return ensure_tunnel(data, hosting_enabled(data) ? tunnel : null, port, running);
733
+ const { tunnel, port, running, mode } = entry_settings(data);
734
+ return ensure_tunnel(data, hosting_enabled(data) && mode === 'tunnel' ? tunnel : null, port, running);
735
+ }
736
+
737
+ /** The online site this computer is bound to (`codiscuss local connect`) and its id there, or null. */
738
+ function bound_site(data) {
739
+ const [site, link] = Object.entries(machine_links(data).sites || {}).find(([, item]) => item?.id && item?.private_key) || [];
740
+ return site ? { site, machine: link.id } : null;
741
+ }
742
+
743
+ /** Ask the relay's entry Worker whether it is one and whether this computer is connected to it. */
744
+ async function relay_status(relay_url, machine) {
745
+ try {
746
+ const answer = await fetch(`${relay_url}/_codiscuss/status?machine=${machine || '0'.repeat(32)}`, { signal: AbortSignal.timeout(RELAY_CHECK_MS) });
747
+ const result = await answer.json();
748
+ return result.service === 'codiscuss-entry' ? { reachable: true, online: Boolean(result.online) } : { reachable: false, online: false };
749
+ } catch { return { reachable: false, online: false }; }
728
750
  }
729
751
 
730
752
  async function entry_overview(data) {
731
- const { port, public_url, tunnel } = entry_settings(data), status = await entry_status(data);
732
- return { running: status.running, port: status.running ? status.port : port, public_url,
753
+ const { port, public_url, tunnel, mode, relay_url } = entry_settings(data), status = await entry_status(data);
754
+ const bound = bound_site(data);
755
+ const relay = { url: relay_url, site: bound?.site || '', link: relay_url && bound ? `${relay_url}/?m=${bound.machine}` : '',
756
+ ...(mode === 'relay' && relay_url && bound ? await relay_status(relay_url, bound.machine) : {}) };
757
+ // The address people open in the mode in use.
758
+ const address = mode === 'relay' ? relay.link : mode === 'tunnel' ? public_url : '';
759
+ return { running: status.running, port: status.running ? status.port : port, public_url, mode, address, relay,
733
760
  tunnel: tunnel ? { host: tunnel.host, name: tunnel.name, ...(await tunnel_status(data)) } : null };
734
761
  }
735
762
 
763
+ /** Switch how people outside reach the entry, once what that way needs is there; the tunnel follows at once. */
764
+ async function set_entry_mode(data, mode) {
765
+ const settings = entry_settings(data);
766
+ if (mode === 'relay') {
767
+ if (!bound_site(data)) throw new Error('这台电脑还没有绑定线上站点:先在下面绑定');
768
+ if (!settings.relay_url) throw new Error('还没有填写入口地址(入口 Worker 的 workers.dev 地址)');
769
+ }
770
+ if (mode === 'tunnel' && !settings.tunnel) throw new Error('还没有设好 Cloudflare 隧道:先点“设置”填写你的域名');
771
+ save_entry_settings(data, { mode });
772
+ await keep_tunnel(data);
773
+ return entry_overview(data);
774
+ }
775
+
776
+ /** Save the relay's entry address after checking that it answers as one. */
777
+ async function set_relay_url(data, url) {
778
+ const origin = String(url || '').trim().replace(/\/+$/, '');
779
+ const checked = await relay_status(origin, bound_site(data)?.machine);
780
+ if (!checked.reachable) throw new Error(`${origin} 不是共议的入口 Worker,或现在连不上`);
781
+ save_entry_settings(data, { relay_url: origin });
782
+ return entry_overview(data);
783
+ }
784
+
785
+ /** Bind this computer to an online site with a one-time token, as `codiscuss local connect` does. */
786
+ function connect_site(data, site, setup_key) {
787
+ return new Promise((done, fail) => {
788
+ const child = spawn(process.execPath, [installed_script('discussion_local.mjs'), 'connect', String(site || '').trim(), '--setup-key', String(setup_key || '').trim(), '--no-open', '--json'],
789
+ { cwd: data, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, DISCUSS_SERVICE_HOME: data } });
790
+ let output = '', errors = '';
791
+ child.stdout.on('data', chunk => { output += chunk; });
792
+ child.stderr.on('data', chunk => { errors += chunk; });
793
+ child.on('error', fail);
794
+ child.on('exit', code => (code === 0 ? done(bound_site(data)) : fail(new Error(errors.trim().split(/\r?\n/).pop() || `绑定失败(退出码 ${code})`))));
795
+ });
796
+ }
797
+
736
798
  // ---- Hosted accounts' failures, to the owner's Weixin ----
737
799
 
738
800
  /** Whether two paths name the same place, as written (Windows paths compare without regard to case). */
@@ -81,7 +81,7 @@ export async function configure_hosting(home, options, { interactive = Boolean(p
81
81
  try {
82
82
  const host = tunnel_host(options['public-host']);
83
83
  const tunnel = await prepare_tunnel({ host, name: options['tunnel-name'], interactive, say });
84
- Object.assign(changes, { public_url: `https://${host}`, tunnel });
84
+ Object.assign(changes, { public_url: `https://${host}`, tunnel, mode: 'tunnel' });
85
85
  lines.push(`外网地址 https://${host},经 Cloudflare 隧道 ${tunnel.name} 转到登录入口;隧道独立运行,由管理面板按设置维持`);
86
86
  if (remove_legacy_tunnel_start()) lines.push('已移除旧的“CoDiscuss Tunnel”开机任务,改由管理面板运行隧道');
87
87
  // cert.pem manages the whole Cloudflare site, while the running tunnel needs only its own credentials.
@@ -263,7 +263,7 @@ async function prepare_job(data, host, name) {
263
263
  try {
264
264
  const tunnel = await prepare_tunnel({ host, name, shown: false, progress: step => save({ step }), on_url: url => save({ url }), say: note => save({ note }) });
265
265
  save({ step: '启动隧道', url: '' });
266
- const settings = save_entry_settings(data, { public_url: `https://${tunnel.host}`, tunnel });
266
+ const settings = save_entry_settings(data, { public_url: `https://${tunnel.host}`, tunnel, mode: 'tunnel' });
267
267
  remove_legacy_tunnel_start();
268
268
  await ensure_tunnel(data, tunnel, settings.port, settings.running);
269
269
  save({ status: 'done', step: '', host: tunnel.host });
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { createHash, randomBytes } from 'node:crypto';
7
7
  import { existsSync, readFileSync } from 'node:fs';
8
+ import http from 'node:http';
8
9
  import { join } from 'node:path';
9
10
  import { setTimeout as sleep } from 'node:timers/promises';
10
11
  import { gzipSync } from 'node:zlib';
@@ -17,6 +18,7 @@ import { machine_links, relay_cipher, save_machine_links, relayed_command, ROOM_
17
18
  import { claim_relayed_command } from './remote_policy.mjs';
18
19
  import { audit, DEVICE_ACTIONS, device_command, open_signed_request } from './device_auth.mjs';
19
20
  import { site_fetch } from './entry_client.mjs';
21
+ import { entry_settings } from '../gateway/gateway.mjs';
20
22
 
21
23
  const RELAY_PROTOCOL = 'codiscuss-relay';
22
24
  const BRIDGE_TOKEN_BYTES = 32;
@@ -37,6 +39,14 @@ const UPLOAD_PATH = /^\/api\/rooms\/[A-Za-z0-9_-]+\/attachments(\/[A-Za-z0-9_-]+
37
39
  const UPLOAD_MAX_BYTES = 20 * 1024 * 1024;
38
40
  const UPLOAD_TTL_MS = 10 * 60 * 1000;
39
41
  const uploads = new Map();
42
+ // The hosted accounts' entry over the relay (backend/entry_worker.mjs): answer parts per frame (sent as base64 within the
43
+ // 1 MiB frame), the largest request taken, and when to pause reading an answer the connection has not sent on yet.
44
+ const ENTRY_PART_BYTES = 512 * 1024;
45
+ const ENTRY_BODY_MAX_BYTES = 45 * 1024 * 1024;
46
+ const ENTRY_BUFFER_HIGH = 4 * 1024 * 1024;
47
+ const ENTRY_BUFFER_CHECK_MS = 50;
48
+ const ENTRY_HOP_HEADERS = new Set(['connection', 'keep-alive', 'transfer-encoding', 'upgrade', 'proxy-connection', 'te', 'trailer', 'content-length',
49
+ 'x-forwarded-proto', 'x-forwarded-for', 'x-forwarded-host', 'x-real-ip']);
40
50
 
41
51
  /** The bridge token for one website, created on first use; the local website keeps only its hash, next to the connection. */
42
52
  export function bridge_token(home, site) {
@@ -229,6 +239,67 @@ async function forward_changes(home, socket, signal) {
229
239
  }
230
240
  }
231
241
 
242
+ /**
243
+ * Answer the hosted accounts' entry traffic the relay hands over (`entry` frames, apart from the administrator's signed
244
+ * requests). Each request goes only to this computer's sign-in entry on loopback, never anywhere the frame names, and
245
+ * only while its owner chose this way in the panel (entry settings `mode: 'relay'`), so a tampered website cannot open
246
+ * the channel on its own. The entry treats it like traffic from a tunnel: HTTPS outside, the browser's own Host.
247
+ * Returns the frame handler; `send` puts a frame on the connection, `buffered` says how much it holds unsent.
248
+ */
249
+ export function entry_proxy(home, { send, buffered = () => 0 }) {
250
+ const open = new Map();
251
+ const head = (id, status, headers = []) => send({ type: 'entry-head', id, status, headers });
252
+ const refuse = (id, status, text) => {
253
+ head(id, status, [['content-type', 'text/plain; charset=utf-8'], ['cache-control', 'no-store']]);
254
+ send({ type: 'entry-data', id, data: Buffer.from(text).toString('base64') });
255
+ send({ type: 'entry-end', id });
256
+ };
257
+ const forward = id => {
258
+ const entry = open.get(id);
259
+ const settings = entry_settings(home);
260
+ if (settings.mode !== 'relay') { open.delete(id); return refuse(id, 503, '这台电脑没有开启线上中转'); }
261
+ const body = Buffer.concat(entry.parts);
262
+ const headers = {};
263
+ for (const [name, value] of Array.isArray(entry.headers) ? entry.headers : []) {
264
+ const key = String(name).toLowerCase();
265
+ if (ENTRY_HOP_HEADERS.has(key)) continue;
266
+ headers[key] = headers[key] === undefined ? String(value) : `${headers[key]}, ${value}`;
267
+ }
268
+ Object.assign(headers, { 'x-forwarded-proto': 'https', 'content-length': String(body.length) });
269
+ const path = typeof entry.path === 'string' && entry.path.startsWith('/') && !entry.path.startsWith('//') ? entry.path : '/';
270
+ const request = http.request({ host: '127.0.0.1', port: settings.port, method: String(entry.method || 'GET'), path, headers }, reply => {
271
+ const kept = [];
272
+ for (let index = 0; index < reply.rawHeaders.length; index += 2) {
273
+ if (!ENTRY_HOP_HEADERS.has(reply.rawHeaders[index].toLowerCase())) kept.push([reply.rawHeaders[index], reply.rawHeaders[index + 1]]);
274
+ }
275
+ head(id, reply.statusCode, kept);
276
+ // Hold the answer while the connection is behind, so a large file is not read into memory ahead of it.
277
+ const drain = () => { if (buffered() > ENTRY_BUFFER_HIGH) { reply.pause(); setTimeout(() => { reply.resume(); drain(); }, ENTRY_BUFFER_CHECK_MS); } };
278
+ reply.on('data', chunk => {
279
+ for (let offset = 0; offset < chunk.length; offset += ENTRY_PART_BYTES) send({ type: 'entry-data', id, data: chunk.subarray(offset, offset + ENTRY_PART_BYTES).toString('base64') });
280
+ drain();
281
+ });
282
+ reply.on('end', () => { open.delete(id); send({ type: 'entry-end', id }); });
283
+ reply.on('error', () => { open.delete(id); send({ type: 'entry-end', id }); });
284
+ });
285
+ entry.request = request;
286
+ request.on('error', () => { if (open.delete(id)) refuse(id, 502, '登录入口没有在运行'); });
287
+ request.end(body);
288
+ };
289
+ return frame => {
290
+ const id = frame.id;
291
+ if (typeof id !== 'string') return;
292
+ if (frame.type === 'entry-cancel') { open.get(id)?.request?.destroy(); open.delete(id); return; }
293
+ const part = Buffer.from(String(frame.body || ''), 'base64');
294
+ if (frame.type === 'entry') open.set(id, { method: frame.method, path: frame.path, headers: frame.headers, parts: [part], size: part.length });
295
+ else if (frame.type === 'entry-body' && open.has(id)) { const entry = open.get(id); entry.parts.push(part); entry.size += part.length; }
296
+ else return;
297
+ const entry = open.get(id);
298
+ if (entry.size > ENTRY_BODY_MAX_BYTES) { open.delete(id); return refuse(id, 413, '请求太大'); }
299
+ if (!frame.more) forward(id);
300
+ };
301
+ }
302
+
232
303
  /** Hold one website's relay connection, reconnecting with backoff; `connected` tracks which websites are live. */
233
304
  async function hold_channel(home, site, { connected, log, signal }) {
234
305
  let delay = RETRY_MIN_MS;
@@ -242,6 +313,9 @@ async function hold_channel(home, site, { connected, log, signal }) {
242
313
  try { socket = new WebSocket(url, [RELAY_PROTOCOL, `m.${link.token}`]); } catch { return resolve(false); }
243
314
  const events = new AbortController();
244
315
  let ping, finished = false;
316
+ // The hosted accounts' entry traffic on this connection (entry_proxy).
317
+ const entry = entry_proxy(home, { send: frame => { if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(frame)); },
318
+ buffered: () => socket.bufferedAmount || 0 });
245
319
  // Only the first finish counts: a stalled socket may report its close long after its replacement connected.
246
320
  const finish = opened => {
247
321
  if (finished) return;
@@ -275,6 +349,7 @@ async function hold_channel(home, site, { connected, log, signal }) {
275
349
  if (typeof event.data !== 'string') return;
276
350
  let frame;
277
351
  try { frame = JSON.parse(event.data); } catch { return; }
352
+ if (typeof frame.type === 'string' && frame.type.startsWith('entry')) return entry(frame);
278
353
  if (frame.type !== 'request' || typeof frame.id !== 'string' || !frame.envelope) return;
279
354
  // Disconnecting or re-pairing the website ends this connection at once, not at its next reconnect.
280
355
  const current = machine_links(home).sites[site];