dsh-plugin-mesh 0.5.5 → 0.5.6

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.
@@ -0,0 +1,88 @@
1
+ /**
2
+ * 「把本机另一个 DSH 引擎的 Web 界面转发出去」——给手机在应用内开面板用。
3
+ *
4
+ * 背景:同一台机器上可能同时跑着两个引擎(桌面 App 一个、CLI/web profile 一个),
5
+ * 而用户要的是**桌面 App 那个**(有历史会话)。它只监听 127.0.0.1,且客户端
6
+ * 会话 cookie 是 SameSite=Strict、token 又是进程级随机 —— 从网络侧直接打不开。
7
+ *
8
+ * 这里的做法:在**我们自己这个引擎**里开一条前缀路由,把请求转发到
9
+ * 127.0.0.1:<desktopPort>,并自己签发一枚该 authority 的会话 cookie。
10
+ *
11
+ * 为什能签:cookie 只是 HMAC 签名,密钥持久化在 <DSH_HOME>/.credentials.yaml 的
12
+ * `client-connection/browser-session` 记录里(同一 DSH_HOME 下的两个引擎共用)。
13
+ * 签名算法:`v1.<b64url(json{version,authority,issuedAt,expiresAt})>.<b64url(hmac-sha256(secretBytes, body))>`,
14
+ * cookie 名是 `dsh-auth-<b64url(sha256(authority))>`,密钥是**解码后的字节**而不是那串 base64。
15
+ *
16
+ * 边界:这是"同一台机器、同一个用户"的自我委托,不是跨用户授权;拿到它等于拿到
17
+ * 该引擎的操作权,所以路由必须连同整条链路一起看成敏感面。
18
+ */
19
+ import { createHmac, createHash } from "node:crypto";
20
+ import { readFileSync, statSync } from "node:fs";
21
+
22
+ /** 凭据文件里那条记录的键。 */
23
+ const AUTH_RECORD_KEY = "client-connection/browser-session";
24
+ /** cookie 名固定前缀(见 dsh-client-connection)。 */
25
+ const COOKIE_PREFIX = "dsh-auth-";
26
+ /** 签出来的 cookie 给多久:对齐上游默认的 30 天。 */
27
+ const COOKIE_MAX_AGE_MS = 30 * 24 * 3600 * 1000;
28
+
29
+ function b64u(buffer) {
30
+ return Buffer.from(buffer).toString("base64").replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
31
+ }
32
+
33
+ function fromB64u(text) {
34
+ const padded = String(text).replaceAll("-", "+").replaceAll("_", "/");
35
+ return Buffer.from(padded + "=".repeat((4 - (padded.length % 4)) % 4), "base64");
36
+ }
37
+
38
+ /**
39
+ * 从凭据 YAML 里抠出 browser-session 的 secret。
40
+ *
41
+ * 用一个只认这种形式的窄解析而不是引入 YAML 依赖:这里读的是本机自己的文件,
42
+ * 结构由 dsh 写死(records → client-connection/browser-session → payload.secret)。
43
+ * @returns {Buffer | undefined} 解码后的密钥字节
44
+ */
45
+ function parseSecret(text) {
46
+ const at = text.indexOf(`${AUTH_RECORD_KEY}:`);
47
+ if (at === -1) return undefined;
48
+ const rest = text.slice(at);
49
+ const match = /secret:\s*(\S+)/.exec(rest);
50
+ if (!match) return undefined;
51
+ const bytes = fromB64u(match[1]);
52
+ return bytes.byteLength > 0 ? bytes : undefined;
53
+ }
54
+
55
+ /**
56
+ * 读(并缓存)浏览器会话密钥;凭据文件改动后自动重读。
57
+ * @param credentialsPath - <DSH_HOME>/.credentials.yaml 的绝对路径
58
+ * @returns {Buffer | undefined}
59
+ */
60
+ export function createSecretReader(credentialsPath) {
61
+ let cache;
62
+ return () => {
63
+ try {
64
+ const st = statSync(credentialsPath);
65
+ if (cache && cache.mtimeMs === st.mtimeMs && cache.size === st.size) return cache.secret;
66
+ const secret = parseSecret(readFileSync(credentialsPath, "utf8"));
67
+ cache = { mtimeMs: st.mtimeMs, size: st.size, secret };
68
+ return secret;
69
+ } catch {
70
+ return undefined;
71
+ }
72
+ };
73
+ }
74
+
75
+ /**
76
+ * 给某个 authority 签一枚会话 cookie。
77
+ * @param secret - 解码后的密钥字节
78
+ * @param authority - 目标 authority,必须与请求的 Host 完全一致(含端口)
79
+ * @returns {{ name: string, header: string }}
80
+ */
81
+ export function signSessionCookie(secret, authority) {
82
+ const name = COOKIE_PREFIX + b64u(createHash("sha256").update(authority).digest());
83
+ const issuedAt = Date.now();
84
+ const payload = { version: 1, authority, issuedAt, expiresAt: issuedAt + COOKIE_MAX_AGE_MS };
85
+ const body = b64u(Buffer.from(JSON.stringify(payload), "utf8"));
86
+ const signature = b64u(createHmac("sha256", secret).update(body).digest());
87
+ return { name, header: `${name}=v1.${body}.${signature}` };
88
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * 前缀反向代理:把 `/mesh/web/...` 转发到本机另一个 DSH 引擎的 Web 界面。
3
+ *
4
+ * 前缀只在**本机之间**用:对端(手机上的代理)把浏览器请求原样带过来,
5
+ * 这里去掉前缀再打给 loopback。浏览器一侧看到的永远是根的绝对路径,
6
+ * 所以对端前端里的 /api、/plugins 不需要任何改写。
7
+ */
8
+ import { request as httpRequest } from "node:http";
9
+ import { connect as netConnect } from "node:net";
10
+ import { signSessionCookie } from "./desktop-auth.js";
11
+
12
+ /** 前缀本身。 */
13
+ export const DESKTOP_WEB_PREFIX = "/mesh/web";
14
+
15
+ /**
16
+ * 客户端的流式载波(WebSocket):`new WebSocket(remoteStreamUrl(...))` 开的就是它。
17
+ * 少了这条 upgrade 转发,前端会永远停在"自动重连中",工作区与会话列表也就不会出现
18
+ * ——POST 请求都能通,所以症状看起来像"只有一部分功能好了"。
19
+ */
20
+ export const DESKTOP_WEB_STREAM_PATH = `${DESKTOP_WEB_PREFIX}/api/remote.mux`;
21
+
22
+ /** 去掉前缀;不是这个前缀下的请求返回 undefined。 */
23
+ function remainder(url) {
24
+ if (url === DESKTOP_WEB_PREFIX || url === `${DESKTOP_WEB_PREFIX}/`) return "/";
25
+ if (!url.startsWith(`${DESKTOP_WEB_PREFIX}/`)) return undefined;
26
+ return url.slice(DESKTOP_WEB_PREFIX.length);
27
+ }
28
+
29
+ /**
30
+ * 造一个转发 handler。
31
+ * @param options - port(目标引擎端口)、secretOf(读密钥的函数)、log、warn
32
+ * @returns {(req, res) => Promise<void>}
33
+ */
34
+ export function createDesktopWebForwarder({ port, secretOf, log = () => {}, warn = () => {} }) {
35
+ const authority = `127.0.0.1:${port}`;
36
+
37
+ function forward(req, res, retried) {
38
+ const secret = secretOf();
39
+ if (!secret) {
40
+ res.writeHead(503, { "content-type": "text/plain; charset=utf-8" });
41
+ res.end("读不到本机的浏览器会话密钥(.credentials.yaml 里没有 browser-session 记录)。\n");
42
+ return;
43
+ }
44
+ const path = remainder(req.url ?? "/");
45
+ if (path === undefined) {
46
+ res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
47
+ res.end("not found\n");
48
+ return;
49
+ }
50
+ // 探针:不转发,直接回答"这条链路在不在"。
51
+ if (path === "/__probe") {
52
+ const body = Buffer.from(JSON.stringify({ ok: true, target: authority }), "utf8");
53
+ res.writeHead(200, { "content-type": "application/json; charset=utf-8", "content-length": String(body.length) });
54
+ res.end(req.method === "HEAD" ? undefined : body);
55
+ return;
56
+ }
57
+
58
+ const headers = { ...req.headers, host: authority, cookie: signSessionCookie(secret, authority).header };
59
+ // 浏览器是从"手机代理的 origin"发起的:Origin 与 Host 不一致会被对端的
60
+ // 同源栅栏拒成 403(而插件自己的路由不过栅栏,所以看起来"一部分能用")。
61
+ // 我们本来就是替浏览器发的,这里把来源改写成目标 authority。
62
+ headers.origin = `http://${authority}`;
63
+ if (headers.referer !== undefined) headers.referer = `http://${authority}/`;
64
+ if (String(headers["sec-fetch-site"] ?? "") === "cross-site") headers["sec-fetch-site"] = "same-origin";
65
+ const up = httpRequest({ host: "127.0.0.1", port, method: req.method, path, headers }, (reply) => {
66
+ // 401 = 密钥换过或算错了:重读一次密钥再试一遍(幂等方法)。
67
+ if (reply.statusCode === 401 && !retried && (req.method === "GET" || req.method === "HEAD")) {
68
+ reply.resume();
69
+ forward(req, res, true);
70
+ return;
71
+ }
72
+ const out = { ...reply.headers };
73
+ // 认证由这里维护,别把对端的 Set-Cookie 泄到上一层。
74
+ delete out["set-cookie"];
75
+ delete out["transfer-encoding"];
76
+ res.writeHead(reply.statusCode ?? 502, out);
77
+ reply.pipe(res);
78
+ });
79
+
80
+ up.on("error", (error) => {
81
+ warn(`桌面引擎转发失败(${authority}):${error?.message ?? error}`);
82
+ if (res.headersSent) {
83
+ res.destroy();
84
+ return;
85
+ }
86
+ res.writeHead(502, { "content-type": "text/plain; charset=utf-8" });
87
+ res.end(`连不上本机 ${authority}:${error?.message ?? error}\n`);
88
+ });
89
+
90
+ if (req.readableEnded) up.end();
91
+ else req.pipe(up);
92
+ }
93
+
94
+ return async function handle(req, res) {
95
+ log(`${req.method ?? "GET"} ${req.url ?? "/"} → ${authority}`);
96
+ forward(req, res, false);
97
+ };
98
+ }
99
+
100
+
101
+ /**
102
+ * 造一个 upgrade 转发器:把流式端点的握手原样转给本机 loopback 引擎。
103
+ * @param options - port、secretOf、log、warn
104
+ * @returns {(req, socket, head) => void}
105
+ */
106
+ export function createDesktopWebUpgrade({ port, secretOf, log = () => {}, warn = () => {} }) {
107
+ const authority = `127.0.0.1:${port}`;
108
+ return function handleUpgrade(req, socket, head) {
109
+ const secret = secretOf();
110
+ if (!secret) {
111
+ warn("读不到会话密钥,无法转发 WebSocket");
112
+ socket.destroy();
113
+ return;
114
+ }
115
+ const url = req.url ?? "/";
116
+ const path = url.startsWith(DESKTOP_WEB_PREFIX) ? url.slice(DESKTOP_WEB_PREFIX.length) || "/" : url;
117
+ try {
118
+ const h = req.headers;
119
+ appendFileSync("/tmp/mesh-web.log", `UPGRADE-REQ ${path} ext=${h["sec-websocket-extensions"] ?? "-"} origin=${h.origin ?? "-"} ua=${String(h["user-agent"] ?? "-").slice(0, 30)}\n`);
120
+ } catch {}
121
+ log(`UPGRADE ${path} → ${authority}`);
122
+ const target = netConnect(port, "127.0.0.1", () => {
123
+ const lines = [`${req.method} ${path} HTTP/1.1`];
124
+ for (const [key, value] of Object.entries(req.headers)) {
125
+ if (value === undefined) continue;
126
+ const name = key.toLowerCase();
127
+ // 这几个由代理改写(见 HTTP 分支同样的理由:同源栅栏 + 认证)。
128
+ if (name === "host" || name === "cookie" || name === "origin" || name === "referer" || name === "sec-fetch-site") continue;
129
+ for (const item of Array.isArray(value) ? value : [value]) lines.push(`${key}: ${item}`);
130
+ }
131
+ lines.push(`host: ${authority}`);
132
+ lines.push(`cookie: ${signSessionCookie(secret, authority).header}`);
133
+ lines.push(`origin: http://${authority}`);
134
+ lines.push("sec-fetch-site: same-origin");
135
+ target.write(`${lines.join("\r\n")}\r\n\r\n`);
136
+ if (head && head.length) target.write(head);
137
+ target.pipe(socket);
138
+ socket.pipe(target);
139
+ });
140
+ target.on("error", (error) => {
141
+ warn(`WebSocket 转发失败:${error?.message ?? error}`);
142
+ socket.destroy();
143
+ });
144
+ socket.on("error", () => target.destroy());
145
+ };
146
+ }