ai_co_discuss 0.4.43 → 0.4.45
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/docs/deployment.md +16 -0
- package/gateway/gateway.mjs +17 -3
- package/package.json +1 -1
- package/runner/admin_panel.mjs +150 -5
- package/runner/hosting_setup.mjs +1 -1
- package/runner/hosting_tunnel.mjs +1 -1
- package/runner/relay_channel.mjs +75 -0
- package/web/admin.css +1 -1
- package/web/admin.js +2 -2
- package/web/modern.js +1 -1
package/docs/deployment.md
CHANGED
|
@@ -161,6 +161,22 @@ 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`),与线上站点不同源,托管账号的网页碰不到你已配对设备的密钥。把这个地址写进私有配置的 `vars`,重新部署 Pages,线上站点就会把它告诉来接入的托管电脑:
|
|
173
|
+
|
|
174
|
+
```json
|
|
175
|
+
"vars": { "ENTRY_URL": "https://codiscuss-entry.<账号子域>.workers.dev" }
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
接入一台托管电脑:在你(部署线上站点的电脑)的管理面板“概览 → 托管 → 登录入口”选“线上中转”,展开“生成接入码”,填部署配置路径与站点地址后生成(需已登录 wrangler;一次性,再生成会让未用过的作废);把接入码发给托管电脑,粘贴到它的同一个窗口点“接入并切换”,它会绑定站点、取得入口地址、启动所需服务并切换。面板给出的链接带电脑编号(`?m=…`),发给使用者即可。使用者的请求经入口 Worker 和中转到达这台电脑的登录入口,登录、会话与入口保护都在电脑上;Cloudflare 能看到这些往来内容(与自有域名隧道相同),每个页面的请求都计入 Workers 免费额度。
|
|
179
|
+
|
|
164
180
|
## 常见问题
|
|
165
181
|
|
|
166
182
|
- **`no such table`**:所连接的数据库尚未执行 schema,先核对配置文件指向的数据库。
|
package/gateway/gateway.mjs
CHANGED
|
@@ -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
|
-
|
|
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
package/runner/admin_panel.mjs
CHANGED
|
@@ -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, make_access_code, join_relay, 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,14 @@ 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);
|
|
647
|
+
// The access code: made on the computer that deployed the online site, pasted on a hosting computer.
|
|
648
|
+
if (method === 'GET' && section === 'site' && name === 'code') return { ...deploy_settings(data), site: deploy_settings(data).site || bound_site(data)?.site || '' };
|
|
649
|
+
if (method === 'POST' && section === 'site' && name === 'code') return op.make_access_code(data, body);
|
|
650
|
+
if (method === 'POST' && section === 'relay' && name === 'join') return op.join_relay(data, body.code);
|
|
640
651
|
// The outside address: a Cloudflare tunnel set up by a job of its own (it waits for the owner in the browser).
|
|
641
652
|
if (section === 'tunnel' && name === 'setup') {
|
|
642
653
|
if (method === 'GET') return tunnel_setup_state(data);
|
|
@@ -723,16 +734,150 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
|
|
|
723
734
|
/** The account entry as the hosting page shows it: whether it runs, its loopback port and the address customers open. */
|
|
724
735
|
/** Keep the entry's tunnel as the settings say: running while hosting is on and the entry is meant to run. */
|
|
725
736
|
function keep_tunnel(data) {
|
|
726
|
-
const { tunnel, port, running } = entry_settings(data);
|
|
727
|
-
return ensure_tunnel(data, hosting_enabled(data) ? tunnel : null, port, running);
|
|
737
|
+
const { tunnel, port, running, mode } = entry_settings(data);
|
|
738
|
+
return ensure_tunnel(data, hosting_enabled(data) && mode === 'tunnel' ? tunnel : null, port, running);
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/** The online site this computer is bound to (`codiscuss local connect`) and its id there, or null. */
|
|
742
|
+
function bound_site(data) {
|
|
743
|
+
const [site, link] = Object.entries(machine_links(data).sites || {}).find(([, item]) => item?.id && item?.private_key) || [];
|
|
744
|
+
return site ? { site, machine: link.id } : null;
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/** Ask the relay's entry Worker whether it is one and whether this computer is connected to it. */
|
|
748
|
+
async function relay_status(relay_url, machine) {
|
|
749
|
+
try {
|
|
750
|
+
const answer = await fetch(`${relay_url}/_codiscuss/status?machine=${machine || '0'.repeat(32)}`, { signal: AbortSignal.timeout(RELAY_CHECK_MS) });
|
|
751
|
+
const result = await answer.json();
|
|
752
|
+
return result.service === 'codiscuss-entry' ? { reachable: true, online: Boolean(result.online) } : { reachable: false, online: false };
|
|
753
|
+
} catch { return { reachable: false, online: false }; }
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/** What stands between people outside and this computer over the relay, in the order to look at it; '' when nothing. */
|
|
757
|
+
function relay_problem(relay, entry_running, service_running) {
|
|
758
|
+
if (!relay.reachable) return '入口地址连不上:检查网络与代理是否放行 *.workers.dev';
|
|
759
|
+
if (!service_running) return '本机服务没有在运行,电脑连不上线上站点:在上面“本机”里启动共议服务';
|
|
760
|
+
if (!relay.online) return '电脑还没连上线上站点:本机服务刚启动时稍等几秒;持续如此,可能这台电脑绑定的站点与入口不属于同一个 Cloudflare 账号,重新用接入码接入';
|
|
761
|
+
if (!entry_running) return '登录入口没有在运行:点上面的“启动”';
|
|
762
|
+
return '';
|
|
728
763
|
}
|
|
729
764
|
|
|
730
765
|
async function entry_overview(data) {
|
|
731
|
-
const { port, public_url, tunnel } = entry_settings(data), status = await entry_status(data);
|
|
732
|
-
|
|
766
|
+
const { port, public_url, tunnel, mode, relay_url } = entry_settings(data), status = await entry_status(data);
|
|
767
|
+
const bound = bound_site(data);
|
|
768
|
+
const relay = { url: relay_url, site: bound?.site || '', link: relay_url && bound ? `${relay_url}/?m=${bound.machine}` : '',
|
|
769
|
+
...(mode === 'relay' && relay_url && bound ? await relay_status(relay_url, bound.machine) : {}) };
|
|
770
|
+
if (mode === 'relay') relay.problem = relay_problem(relay, status.running, Boolean(local_status(data).running));
|
|
771
|
+
// The address people open in the mode in use.
|
|
772
|
+
const address = mode === 'relay' ? relay.link : mode === 'tunnel' ? public_url : '';
|
|
773
|
+
return { running: status.running, port: status.running ? status.port : port, public_url, mode, address, relay,
|
|
733
774
|
tunnel: tunnel ? { host: tunnel.host, name: tunnel.name, ...(await tunnel_status(data)) } : null };
|
|
734
775
|
}
|
|
735
776
|
|
|
777
|
+
/**
|
|
778
|
+
* Switch how people outside reach the entry, once what that way needs is there. Reaching it from outside needs the entry
|
|
779
|
+
* running, and the relay needs this computer's service (which holds the relay connection): both are started here rather
|
|
780
|
+
* than left for the first person to find a broken link. The tunnel follows at once.
|
|
781
|
+
*/
|
|
782
|
+
async function set_entry_mode(data, mode) {
|
|
783
|
+
const settings = entry_settings(data);
|
|
784
|
+
if (mode === 'relay') {
|
|
785
|
+
if (!bound_site(data)) throw new Error('这台电脑还没有接入线上站点:先用接入码接入');
|
|
786
|
+
if (!settings.relay_url) throw new Error('还没有入口地址:先用接入码接入');
|
|
787
|
+
}
|
|
788
|
+
if (mode === 'tunnel' && !settings.tunnel) throw new Error('还没有设好 Cloudflare 隧道:先点“设置”填写你的域名');
|
|
789
|
+
save_entry_settings(data, { mode });
|
|
790
|
+
if (mode !== 'local' && !(await entry_status(data)).running) { await start_entry(data); save_entry_settings(data, { running: true }); }
|
|
791
|
+
if (mode === 'relay' && !local_status(data).running) await run_owner_service(data, 'start');
|
|
792
|
+
await keep_tunnel(data);
|
|
793
|
+
return entry_overview(data);
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
// Where the panel of the computer that deployed the online site remembers its deployment config and the site's address.
|
|
797
|
+
const DEPLOY_FILE = 'panel-deploy.json';
|
|
798
|
+
const BIND_MARK = '#codiscuss-bind=';
|
|
799
|
+
|
|
800
|
+
function deploy_settings(data) {
|
|
801
|
+
try { return JSON.parse(readFileSync(join(data, DEPLOY_FILE), 'utf8')); } catch { return {}; }
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/** The folder above a deployment config that has wrangler installed, so npx finds it rather than downloading it. */
|
|
805
|
+
function wrangler_folder(config) {
|
|
806
|
+
for (let folder = dirname(config); ; folder = dirname(folder)) {
|
|
807
|
+
if (existsSync(join(folder, 'node_modules', 'wrangler'))) return folder;
|
|
808
|
+
if (dirname(folder) === folder) return dirname(config);
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/**
|
|
813
|
+
* On the computer that deployed the online site: make an access code for a hosting computer, the site's address with a
|
|
814
|
+
* one-time binding token (`codiscuss token`, written to the site's database through wrangler, in a child process so the
|
|
815
|
+
* panel keeps answering). A new code makes an unused earlier one invalid. The config and site are remembered.
|
|
816
|
+
*/
|
|
817
|
+
function make_access_code(data, { config, site }) {
|
|
818
|
+
const saved = deploy_settings(data);
|
|
819
|
+
const path = resolve(String(config || saved.config || '').trim() || '.');
|
|
820
|
+
if (!existsSync(path) || !/\.jsonc?$/.test(path)) throw new Error('找不到线上站点的部署配置:填写源码仓库里 .wrangler\\deploy\\wrangler.jsonc 的完整路径');
|
|
821
|
+
let origin;
|
|
822
|
+
try { origin = new URL(String(site || saved.site || bound_site(data)?.site || '').trim()).origin; } catch { throw new Error('站点地址格式不对,例如 https://xxx.pages.dev'); }
|
|
823
|
+
return new Promise((done, fail) => {
|
|
824
|
+
const child = spawn(process.execPath, [installed_script('codiscuss.mjs'), 'token', '--config', path], { cwd: wrangler_folder(path), windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
825
|
+
let output = '', errors = '';
|
|
826
|
+
child.stdout.on('data', chunk => { output += chunk; });
|
|
827
|
+
child.stderr.on('data', chunk => { errors += chunk; });
|
|
828
|
+
child.on('error', fail);
|
|
829
|
+
child.on('exit', code => {
|
|
830
|
+
const token = output.match(/^([0-9a-f]{32,})$/m)?.[1];
|
|
831
|
+
if (code !== 0 || !token) return fail(new Error(errors.trim().split(/\r?\n/).pop() || '没有生成绑定令牌'));
|
|
832
|
+
write_settings(join(data, DEPLOY_FILE), { config: path, site: origin });
|
|
833
|
+
done({ code: `${origin}/${BIND_MARK}${token}`, site: origin });
|
|
834
|
+
});
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
/**
|
|
839
|
+
* On a hosting computer: join the online relay with an access code, each step reported. Bind to the site (unless bound
|
|
840
|
+
* already), take the entry address the site gives, then switch to the relay, which starts what it needs.
|
|
841
|
+
*/
|
|
842
|
+
async function join_relay(data, text) {
|
|
843
|
+
const value = String(text || '').trim();
|
|
844
|
+
const at = value.indexOf(BIND_MARK);
|
|
845
|
+
if (at < 0) throw new Error('接入码不对:应是部署线上站点的电脑上生成的一整串,形如 https://xxx.pages.dev/#codiscuss-bind=…');
|
|
846
|
+
const site = new URL(value.slice(0, at)).origin, token = value.slice(at + BIND_MARK.length);
|
|
847
|
+
const steps = [];
|
|
848
|
+
if (bound_site(data)?.site === site) steps.push(`已接入 ${site}`);
|
|
849
|
+
else { await connect_site(data, site, token); steps.push(`已接入 ${site}`); }
|
|
850
|
+
const given = await fetch(`${site}/api/entry`, { signal: AbortSignal.timeout(RELAY_CHECK_MS) }).then(answer => answer.json()).catch(() => ({}));
|
|
851
|
+
if (!given.entry_url) throw new Error(`${site} 没有提供入口地址:请部署线上站点的人在部署配置里设置 ENTRY_URL 并重新发布`);
|
|
852
|
+
await set_relay_url(data, given.entry_url);
|
|
853
|
+
steps.push(`入口地址 ${given.entry_url}`);
|
|
854
|
+
const overview = await set_entry_mode(data, 'relay');
|
|
855
|
+
steps.push('已切换到线上中转');
|
|
856
|
+
return { steps, entry: overview };
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
/** Save the relay's entry address after checking that it answers as one. */
|
|
860
|
+
async function set_relay_url(data, url) {
|
|
861
|
+
const origin = String(url || '').trim().replace(/\/+$/, '');
|
|
862
|
+
const checked = await relay_status(origin, bound_site(data)?.machine);
|
|
863
|
+
if (!checked.reachable) throw new Error(`${origin} 不是共议的入口 Worker,或现在连不上`);
|
|
864
|
+
save_entry_settings(data, { relay_url: origin });
|
|
865
|
+
return entry_overview(data);
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
/** Bind this computer to an online site with a one-time token, as `codiscuss local connect` does. */
|
|
869
|
+
function connect_site(data, site, setup_key) {
|
|
870
|
+
return new Promise((done, fail) => {
|
|
871
|
+
const child = spawn(process.execPath, [installed_script('discussion_local.mjs'), 'connect', String(site || '').trim(), '--setup-key', String(setup_key || '').trim(), '--no-open', '--json'],
|
|
872
|
+
{ cwd: data, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, DISCUSS_SERVICE_HOME: data } });
|
|
873
|
+
let output = '', errors = '';
|
|
874
|
+
child.stdout.on('data', chunk => { output += chunk; });
|
|
875
|
+
child.stderr.on('data', chunk => { errors += chunk; });
|
|
876
|
+
child.on('error', fail);
|
|
877
|
+
child.on('exit', code => (code === 0 ? done(bound_site(data)) : fail(new Error(errors.trim().split(/\r?\n/).pop() || `绑定失败(退出码 ${code})`))));
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
|
|
736
881
|
// ---- Hosted accounts' failures, to the owner's Weixin ----
|
|
737
882
|
|
|
738
883
|
/** Whether two paths name the same place, as written (Windows paths compare without regard to case). */
|
package/runner/hosting_setup.mjs
CHANGED
|
@@ -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 });
|
package/runner/relay_channel.mjs
CHANGED
|
@@ -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];
|