@artenx/dshb 0.1.52 → 0.1.54
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/lib/auth/decorate-webserver.js +4 -4
- package/lib/auth/decorate-webserver.js.map +1 -1
- package/lib/auth/gate.d.ts +11 -3
- package/lib/auth/gate.js +14 -2
- package/lib/auth/gate.js.map +1 -1
- package/lib/auth/index.js +21 -2
- package/lib/auth/index.js.map +1 -1
- package/lib/auth/webserver.js +4 -4
- package/lib/auth/webserver.js.map +1 -1
- package/lib/client.js +285 -0
- package/lib/client.js.map +1 -1
- package/lib/core/index.js +2 -198
- package/lib/core/index.js.map +1 -1
- package/lib/core/node-registry.js +1 -1
- package/lib/relay-auth-CtwES4Xn.js +240 -0
- package/lib/relay-auth-CtwES4Xn.js.map +1 -0
- package/package.json +1 -1
|
@@ -38,8 +38,8 @@ function decorateWebServer(webServer, store, gate = new AuthGate(store)) {
|
|
|
38
38
|
wrapped.__dshbGated = true;
|
|
39
39
|
fallbackServer.fallback = wrapped;
|
|
40
40
|
}
|
|
41
|
-
function guarded(route, req, res) {
|
|
42
|
-
const decision = gate.decide(req);
|
|
41
|
+
async function guarded(route, req, res) {
|
|
42
|
+
const decision = await gate.decide(req);
|
|
43
43
|
if (decision === "allow") {
|
|
44
44
|
rewriteToLoopback(req, webServer.port);
|
|
45
45
|
return route.handler(req, res);
|
|
@@ -64,8 +64,8 @@ function decorateWebServer(webServer, store, gate = new AuthGate(store)) {
|
|
|
64
64
|
error: "unauthorized"
|
|
65
65
|
}));
|
|
66
66
|
}
|
|
67
|
-
function guardedUpgrade(route, req, socket, head) {
|
|
68
|
-
const decision = gate.decide(req);
|
|
67
|
+
async function guardedUpgrade(route, req, socket, head) {
|
|
68
|
+
const decision = await gate.decide(req);
|
|
69
69
|
if (decision === "allow" || decision === "exempt") {
|
|
70
70
|
if (decision === "allow") rewriteToLoopback(req, webServer.port);
|
|
71
71
|
return route.handler(req, socket, head);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decorate-webserver.js","names":[],"sources":["../../src/auth/decorate-webserver.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Duplex } from 'node:stream'\nimport type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'\nimport type WebServer from '@deepseek-ai/dsh-host-webserver'\nimport { AuthGate, rewriteToLoopback } from './gate.js'\nimport type { CredentialStore } from './credentials.js'\n\ntype ResourceFallback = { resource: unknown }\ntype CompatibleFallback = WebRoute['handler'] | ResourceFallback\n\nfunction isResourceFallback(fallback: CompatibleFallback): fallback is ResourceFallback {\n return typeof fallback === 'object'\n && fallback !== null\n && 'resource' in fallback\n && typeof fallback.resource === 'function'\n}\n\nexport function decorateWebServer(\n webServer: WebServer,\n store: CredentialStore,\n gate = new AuthGate(store),\n): () => void {\n const origRegister = webServer.register.bind(webServer)\n const fallbackServer = webServer as unknown as {\n registerFallback: (fallback: CompatibleFallback) => () => void\n fallback?: CompatibleFallback & { __dshbGated?: true }\n }\n const origRegisterFallback = fallbackServer.registerFallback.bind(webServer)\n const origRegisterUpgrade = webServer.registerUpgrade.bind(webServer)\n\n webServer.register = (route: WebRoute): (() => void) => {\n return origRegister({\n ...route,\n handler: (req, res) => guarded(route, req, res),\n })\n }\n\n fallbackServer.registerFallback = (handler: CompatibleFallback): (() => void) => {\n // Newer DSH releases register SPA fallbacks as resources. Their resource\n // callback owns index authorization and must keep its original contract.\n if (isResourceFallback(handler)) return origRegisterFallback(handler)\n return origRegisterFallback((req, res) =>\n guarded({ kind: 'exact', path: '/', handler }, req, res),\n )\n }\n\n webServer.registerUpgrade = (route: WebUpgradeRoute): (() => void) => {\n return origRegisterUpgrade({\n ...route,\n handler: (req, socket, head) => guardedUpgrade(route, req, socket, head),\n })\n }\n\n // DSH 0.1.5+: the frontend-static plugin may have claimed the fallback seat\n // *before* this decoration runs (plugin apply order is not guaranteed). The\n // registerFallback wrap above only gates fallbacks registered later, so also\n // wrap an already-claimed seat in place. Idempotent via the __dshbGated mark.\n const origFallback = fallbackServer.fallback\n if (typeof origFallback === 'function' && !origFallback.__dshbGated) {\n const wrapped: WebRoute['handler'] & { __dshbGated?: true } = (req, res) =>\n guarded({ kind: 'exact', path: '/', handler: origFallback }, req, res)\n wrapped.__dshbGated = true\n fallbackServer.fallback = wrapped\n }\n\n function guarded(\n route: WebRoute,\n req: IncomingMessage,\n res: ServerResponse,\n ):
|
|
1
|
+
{"version":3,"file":"decorate-webserver.js","names":[],"sources":["../../src/auth/decorate-webserver.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Duplex } from 'node:stream'\nimport type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'\nimport type WebServer from '@deepseek-ai/dsh-host-webserver'\nimport { AuthGate, rewriteToLoopback } from './gate.js'\nimport type { CredentialStore } from './credentials.js'\n\ntype ResourceFallback = { resource: unknown }\ntype CompatibleFallback = WebRoute['handler'] | ResourceFallback\n\nfunction isResourceFallback(fallback: CompatibleFallback): fallback is ResourceFallback {\n return typeof fallback === 'object'\n && fallback !== null\n && 'resource' in fallback\n && typeof fallback.resource === 'function'\n}\n\nexport function decorateWebServer(\n webServer: WebServer,\n store: CredentialStore,\n gate = new AuthGate(store),\n): () => void {\n const origRegister = webServer.register.bind(webServer)\n const fallbackServer = webServer as unknown as {\n registerFallback: (fallback: CompatibleFallback) => () => void\n fallback?: CompatibleFallback & { __dshbGated?: true }\n }\n const origRegisterFallback = fallbackServer.registerFallback.bind(webServer)\n const origRegisterUpgrade = webServer.registerUpgrade.bind(webServer)\n\n webServer.register = (route: WebRoute): (() => void) => {\n return origRegister({\n ...route,\n handler: (req, res) => guarded(route, req, res),\n })\n }\n\n fallbackServer.registerFallback = (handler: CompatibleFallback): (() => void) => {\n // Newer DSH releases register SPA fallbacks as resources. Their resource\n // callback owns index authorization and must keep its original contract.\n if (isResourceFallback(handler)) return origRegisterFallback(handler)\n return origRegisterFallback((req, res) =>\n guarded({ kind: 'exact', path: '/', handler }, req, res),\n )\n }\n\n webServer.registerUpgrade = (route: WebUpgradeRoute): (() => void) => {\n return origRegisterUpgrade({\n ...route,\n handler: (req, socket, head) => guardedUpgrade(route, req, socket, head),\n })\n }\n\n // DSH 0.1.5+: the frontend-static plugin may have claimed the fallback seat\n // *before* this decoration runs (plugin apply order is not guaranteed). The\n // registerFallback wrap above only gates fallbacks registered later, so also\n // wrap an already-claimed seat in place. Idempotent via the __dshbGated mark.\n const origFallback = fallbackServer.fallback\n if (typeof origFallback === 'function' && !origFallback.__dshbGated) {\n const wrapped: WebRoute['handler'] & { __dshbGated?: true } = (req, res) =>\n guarded({ kind: 'exact', path: '/', handler: origFallback }, req, res)\n wrapped.__dshbGated = true\n fallbackServer.fallback = wrapped\n }\n\n async function guarded(\n route: WebRoute,\n req: IncomingMessage,\n res: ServerResponse,\n ): Promise<void> {\n const decision = await gate.decide(req)\n if (decision === 'allow') {\n rewriteToLoopback(req, webServer.port)\n return route.handler(req, res)\n }\n if (decision === 'exempt') {\n return route.handler(req, res)\n }\n if (decision === 'redirect-login') {\n res.writeHead(302, { location: '/login' })\n res.end()\n return\n }\n if (decision === 'forbidden') {\n res.writeHead(403, { 'content-type': 'application/json' })\n res.end(JSON.stringify({ ok: false, error: 'forbidden' }))\n return\n }\n res.writeHead(401, { 'content-type': 'application/json' })\n res.end(JSON.stringify({ ok: false, error: 'unauthorized' }))\n }\n\n async function guardedUpgrade(\n route: WebUpgradeRoute,\n req: IncomingMessage,\n socket: Duplex,\n head: Buffer,\n ): Promise<void> {\n const decision = await gate.decide(req)\n if (decision === 'allow' || decision === 'exempt') {\n if (decision === 'allow') rewriteToLoopback(req, webServer.port)\n return route.handler(req, socket, head)\n }\n socket.write(decision === 'forbidden'\n ? 'HTTP/1.1 403 Forbidden\\r\\nConnection: close\\r\\n\\r\\n'\n : 'HTTP/1.1 401 Unauthorized\\r\\nConnection: close\\r\\n\\r\\n')\n socket.destroy()\n }\n\n return () => {\n webServer.register = origRegister\n fallbackServer.registerFallback = origRegisterFallback\n webServer.registerUpgrade = origRegisterUpgrade\n fallbackServer.fallback = origFallback\n }\n}\n"],"mappings":";;AAUA,SAAS,mBAAmB,UAA4D;CACtF,OAAO,OAAO,aAAa,YACtB,aAAa,QACb,cAAc,YACd,OAAO,SAAS,aAAa;AACpC;AAEA,SAAgB,kBACd,WACA,OACA,OAAO,IAAI,SAAS,KAAK,GACb;CACZ,MAAM,eAAe,UAAU,SAAS,KAAK,SAAS;CACtD,MAAM,iBAAiB;CAIvB,MAAM,uBAAuB,eAAe,iBAAiB,KAAK,SAAS;CAC3E,MAAM,sBAAsB,UAAU,gBAAgB,KAAK,SAAS;CAEpE,UAAU,YAAY,UAAkC;EACtD,OAAO,aAAa;GAClB,GAAG;GACH,UAAU,KAAK,QAAQ,QAAQ,OAAO,KAAK,GAAG;EAChD,CAAC;CACH;CAEA,eAAe,oBAAoB,YAA8C;EAG/E,IAAI,mBAAmB,OAAO,GAAG,OAAO,qBAAqB,OAAO;EACpE,OAAO,sBAAsB,KAAK,QAChC,QAAQ;GAAE,MAAM;GAAS,MAAM;GAAK;EAAQ,GAAG,KAAK,GAAG,CACzD;CACF;CAEA,UAAU,mBAAmB,UAAyC;EACpE,OAAO,oBAAoB;GACzB,GAAG;GACH,UAAU,KAAK,QAAQ,SAAS,eAAe,OAAO,KAAK,QAAQ,IAAI;EACzE,CAAC;CACH;CAMA,MAAM,eAAe,eAAe;CACpC,IAAI,OAAO,iBAAiB,cAAc,CAAC,aAAa,aAAa;EACnE,MAAM,WAAyD,KAAK,QAClE,QAAQ;GAAE,MAAM;GAAS,MAAM;GAAK,SAAS;EAAa,GAAG,KAAK,GAAG;EACvE,QAAQ,cAAc;EACtB,eAAe,WAAW;CAC5B;CAEA,eAAe,QACb,OACA,KACA,KACe;EACf,MAAM,WAAW,MAAM,KAAK,OAAO,GAAG;EACtC,IAAI,aAAa,SAAS;GACxB,kBAAkB,KAAK,UAAU,IAAI;GACrC,OAAO,MAAM,QAAQ,KAAK,GAAG;EAC/B;EACA,IAAI,aAAa,UACf,OAAO,MAAM,QAAQ,KAAK,GAAG;EAE/B,IAAI,aAAa,kBAAkB;GACjC,IAAI,UAAU,KAAK,EAAE,UAAU,SAAS,CAAC;GACzC,IAAI,IAAI;GACR;EACF;EACA,IAAI,aAAa,aAAa;GAC5B,IAAI,UAAU,KAAK,EAAE,gBAAgB,mBAAmB,CAAC;GACzD,IAAI,IAAI,KAAK,UAAU;IAAE,IAAI;IAAO,OAAO;GAAY,CAAC,CAAC;GACzD;EACF;EACA,IAAI,UAAU,KAAK,EAAE,gBAAgB,mBAAmB,CAAC;EACzD,IAAI,IAAI,KAAK,UAAU;GAAE,IAAI;GAAO,OAAO;EAAe,CAAC,CAAC;CAC9D;CAEA,eAAe,eACb,OACA,KACA,QACA,MACe;EACf,MAAM,WAAW,MAAM,KAAK,OAAO,GAAG;EACtC,IAAI,aAAa,WAAW,aAAa,UAAU;GACjD,IAAI,aAAa,SAAS,kBAAkB,KAAK,UAAU,IAAI;GAC/D,OAAO,MAAM,QAAQ,KAAK,QAAQ,IAAI;EACxC;EACA,OAAO,MAAM,aAAa,cACtB,wDACA,wDAAwD;EAC5D,OAAO,QAAQ;CACjB;CAEA,aAAa;EACX,UAAU,WAAW;EACrB,eAAe,mBAAmB;EAClC,UAAU,kBAAkB;EAC5B,eAAe,WAAW;CAC5B;AACF"}
|
package/lib/auth/gate.d.ts
CHANGED
|
@@ -2,6 +2,8 @@ import { CredentialStore } from "./credentials.js";
|
|
|
2
2
|
import { IncomingMessage } from "node:http";
|
|
3
3
|
//#region src/auth/gate.d.ts
|
|
4
4
|
type GateDecision = 'allow' | 'exempt' | 'redirect-login' | 'reject' | 'forbidden';
|
|
5
|
+
/** 提供本机 dsh browser-session 签名密钥(relay cookie 校验依赖)。 */
|
|
6
|
+
type BrowserSessionSecretProvider = () => Promise<Buffer | undefined>;
|
|
5
7
|
/**
|
|
6
8
|
* 认证路由(登录/状态)的可信来源判定。
|
|
7
9
|
* - remoteAddress 必须回环:直连本机,或经可信反代(部署方边界)转发。
|
|
@@ -13,12 +15,18 @@ declare function isTrustedAuthRequest(req: IncomingMessage): boolean;
|
|
|
13
15
|
declare class AuthGate {
|
|
14
16
|
private readonly store;
|
|
15
17
|
private isTrustedAuthRequest;
|
|
16
|
-
|
|
18
|
+
private readonly browserSecretProvider;
|
|
19
|
+
constructor(store: CredentialStore, browserSecretProvider?: BrowserSessionSecretProvider);
|
|
17
20
|
setAuthRequestTrustCheck(check: (req: IncomingMessage) => boolean): void;
|
|
18
|
-
|
|
21
|
+
/**
|
|
22
|
+
* relay cookie 校验是 decide 中唯一的异步步骤(需读 credentials)。
|
|
23
|
+
* 返回 Promise<GateDecision>;调用方(guarded/guardedUpgrade)已支持
|
|
24
|
+
* 返回 Promise。未配置 provider 或 secret 不可用时跳过,回退到既有判定。
|
|
25
|
+
*/
|
|
26
|
+
decide(req: IncomingMessage): Promise<GateDecision>;
|
|
19
27
|
private isPageRequest;
|
|
20
28
|
}
|
|
21
29
|
declare function rewriteToLoopback(req: IncomingMessage, port?: number): void;
|
|
22
30
|
//#endregion
|
|
23
|
-
export { AuthGate, GateDecision, isTrustedAuthRequest, rewriteToLoopback };
|
|
31
|
+
export { AuthGate, BrowserSessionSecretProvider, GateDecision, isTrustedAuthRequest, rewriteToLoopback };
|
|
24
32
|
//# sourceMappingURL=gate.d.ts.map
|
package/lib/auth/gate.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { isLoopbackAddress, isLoopbackRequest } from "./loopback.js";
|
|
2
2
|
import { SESSION_COOKIE, readCookie, verifySession } from "./session.js";
|
|
3
|
+
import { a as requestHasValidRelayCookie } from "../relay-auth-CtwES4Xn.js";
|
|
3
4
|
//#region src/auth/gate.ts
|
|
4
5
|
/**
|
|
5
6
|
* 认证路由(登录/状态)的可信来源判定。
|
|
@@ -23,13 +24,20 @@ function isTrustedAuthRequest(req) {
|
|
|
23
24
|
var AuthGate = class {
|
|
24
25
|
store;
|
|
25
26
|
isTrustedAuthRequest;
|
|
26
|
-
|
|
27
|
+
browserSecretProvider;
|
|
28
|
+
constructor(store, browserSecretProvider) {
|
|
27
29
|
this.store = store;
|
|
30
|
+
this.browserSecretProvider = browserSecretProvider ?? (() => Promise.resolve(void 0));
|
|
28
31
|
}
|
|
29
32
|
setAuthRequestTrustCheck(check) {
|
|
30
33
|
this.isTrustedAuthRequest = check;
|
|
31
34
|
}
|
|
32
|
-
|
|
35
|
+
/**
|
|
36
|
+
* relay cookie 校验是 decide 中唯一的异步步骤(需读 credentials)。
|
|
37
|
+
* 返回 Promise<GateDecision>;调用方(guarded/guardedUpgrade)已支持
|
|
38
|
+
* 返回 Promise。未配置 provider 或 secret 不可用时跳过,回退到既有判定。
|
|
39
|
+
*/
|
|
40
|
+
async decide(req) {
|
|
33
41
|
const path = new URL(req.url ?? "/", "http://x").pathname;
|
|
34
42
|
if (path === "/login") return "exempt";
|
|
35
43
|
if (path === "/api/auth" || path.startsWith("/api/auth/")) return (this.isTrustedAuthRequest ? this.isTrustedAuthRequest(req) : isTrustedAuthRequest(req)) ? "exempt" : "forbidden";
|
|
@@ -40,6 +48,10 @@ var AuthGate = class {
|
|
|
40
48
|
const value = readCookie(req.headers.cookie, SESSION_COOKIE);
|
|
41
49
|
if (verifySession(value, secret, username)) return "allow";
|
|
42
50
|
}
|
|
51
|
+
try {
|
|
52
|
+
const browserSecret = await this.browserSecretProvider();
|
|
53
|
+
if (browserSecret && requestHasValidRelayCookie(req.headers.cookie, browserSecret, req.headers.host, Date.now())) return "allow";
|
|
54
|
+
} catch {}
|
|
43
55
|
if (this.isPageRequest(req)) return "redirect-login";
|
|
44
56
|
return "reject";
|
|
45
57
|
}
|
package/lib/auth/gate.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gate.js","names":[],"sources":["../../src/auth/gate.ts"],"sourcesContent":["import type { IncomingMessage } from 'node:http'\nimport { isLoopbackAddress, isLoopbackRequest } from './loopback.js'\nimport { readCookie, SESSION_COOKIE, verifySession } from './session.js'\nimport type { CredentialStore } from './credentials.js'\n\nexport type GateDecision = 'allow' | 'exempt' | 'redirect-login' | 'reject' | 'forbidden'\n\n/**\n * 认证路由(登录/状态)的可信来源判定。\n * - remoteAddress 必须回环:直连本机,或经可信反代(部署方边界)转发。\n * - 跨站浏览器请求一律拒绝(sec-fetch-site / Origin 与 Host 一致性)。\n * Host 头允许外部域名:预览反代会保留原始 Host,回环校验由\n * remoteAddress 与反代信任承担,登录后再经 rewriteToLoopback 归一。\n */\nexport function isTrustedAuthRequest(req: IncomingMessage): boolean {\n if (!isLoopbackAddress(req.socket.remoteAddress)) return false\n if (req.headers['sec-fetch-site'] === 'cross-site') return false\n const origin = req.headers.origin\n if (origin === undefined) return true\n if (typeof origin !== 'string' || !req.headers.host) return false\n try {\n return new URL(origin).host === new URL(`http://${req.headers.host}`).host\n } catch {\n return false\n }\n}\n\nexport class AuthGate {\n private isTrustedAuthRequest: ((req: IncomingMessage) => boolean) | undefined\n\n constructor(private readonly store: CredentialStore) {}\n\n setAuthRequestTrustCheck(check: (req: IncomingMessage) => boolean): void {\n this.isTrustedAuthRequest = check\n }\n\n decide(req: IncomingMessage): GateDecision {\n const path = new URL(req.url ?? '/', 'http://x').pathname\n if (path === '/login') return 'exempt'\n if (path === '/api/auth' || path.startsWith('/api/auth/')) {\n const trusted = this.isTrustedAuthRequest\n ? this.isTrustedAuthRequest(req)\n : isTrustedAuthRequest(req)\n return trusted ? 'exempt' : 'forbidden'\n }\n if (isLoopbackRequest(req.socket.remoteAddress, req.headers.host)) return 'allow'\n const secret = this.store.sessionSecret\n const username = this.store.username\n if (secret && username) {\n const value = readCookie(req.headers.cookie, SESSION_COOKIE)\n if (verifySession(value, secret, username)) return 'allow'\n }\n if (this.isPageRequest(req)) return 'redirect-login'\n return 'reject'\n }\n\n private isPageRequest(req: IncomingMessage): boolean {\n if (req.method !== 'GET' && req.method !== 'HEAD') return false\n const path = new URL(req.url ?? '/', 'http://x').pathname\n if (path.startsWith('/api/')) return false\n const accept = req.headers.accept ?? ''\n return accept.includes('text/html') || accept.includes('*/*')\n }\n}\n\nexport function rewriteToLoopback(req: IncomingMessage, port?: number): void {\n const localPort = port ?? req.socket.localPort\n if (typeof localPort !== 'number') return\n const authority = `127.0.0.1:${localPort}`\n req.headers.host = authority\n for (const name of ['origin', 'referer'] as const) {\n const value = req.headers[name]\n if (typeof value !== 'string') continue\n try {\n const url = new URL(value)\n url.host = authority\n req.headers[name] = url.toString()\n } catch {}\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"gate.js","names":[],"sources":["../../src/auth/gate.ts"],"sourcesContent":["import type { IncomingMessage } from 'node:http'\nimport { isLoopbackAddress, isLoopbackRequest } from './loopback.js'\nimport { readCookie, SESSION_COOKIE, verifySession } from './session.js'\nimport type { CredentialStore } from './credentials.js'\nimport { requestHasValidRelayCookie } from '../core/sync/relay-auth.js'\n\nexport type GateDecision = 'allow' | 'exempt' | 'redirect-login' | 'reject' | 'forbidden'\n\n/** 提供本机 dsh browser-session 签名密钥(relay cookie 校验依赖)。 */\nexport type BrowserSessionSecretProvider = () => Promise<Buffer | undefined>\n\n/**\n * 认证路由(登录/状态)的可信来源判定。\n * - remoteAddress 必须回环:直连本机,或经可信反代(部署方边界)转发。\n * - 跨站浏览器请求一律拒绝(sec-fetch-site / Origin 与 Host 一致性)。\n * Host 头允许外部域名:预览反代会保留原始 Host,回环校验由\n * remoteAddress 与反代信任承担,登录后再经 rewriteToLoopback 归一。\n */\nexport function isTrustedAuthRequest(req: IncomingMessage): boolean {\n if (!isLoopbackAddress(req.socket.remoteAddress)) return false\n if (req.headers['sec-fetch-site'] === 'cross-site') return false\n const origin = req.headers.origin\n if (origin === undefined) return true\n if (typeof origin !== 'string' || !req.headers.host) return false\n try {\n return new URL(origin).host === new URL(`http://${req.headers.host}`).host\n } catch {\n return false\n }\n}\n\nexport class AuthGate {\n private isTrustedAuthRequest: ((req: IncomingMessage) => boolean) | undefined\n private readonly browserSecretProvider: BrowserSessionSecretProvider\n\n constructor(\n private readonly store: CredentialStore,\n browserSecretProvider?: BrowserSessionSecretProvider,\n ) {\n this.browserSecretProvider = browserSecretProvider ?? (() => Promise.resolve(undefined))\n }\n\n setAuthRequestTrustCheck(check: (req: IncomingMessage) => boolean): void {\n this.isTrustedAuthRequest = check\n }\n\n /**\n * relay cookie 校验是 decide 中唯一的异步步骤(需读 credentials)。\n * 返回 Promise<GateDecision>;调用方(guarded/guardedUpgrade)已支持\n * 返回 Promise。未配置 provider 或 secret 不可用时跳过,回退到既有判定。\n */\n async decide(req: IncomingMessage): Promise<GateDecision> {\n const path = new URL(req.url ?? '/', 'http://x').pathname\n if (path === '/login') return 'exempt'\n if (path === '/api/auth' || path.startsWith('/api/auth/')) {\n const trusted = this.isTrustedAuthRequest\n ? this.isTrustedAuthRequest(req)\n : isTrustedAuthRequest(req)\n return trusted ? 'exempt' : 'forbidden'\n }\n if (isLoopbackRequest(req.socket.remoteAddress, req.headers.host)) return 'allow'\n const secret = this.store.sessionSecret\n const username = this.store.username\n if (secret && username) {\n const value = readCookie(req.headers.cookie, SESSION_COOKIE)\n if (verifySession(value, secret, username)) return 'allow'\n }\n // relay cookie(dsh browser-auth 格式):远端经 SSH 回环铸的短时效签名\n // cookie,HMAC 用本机 browser-session 密钥。让同步 relay 反代请求绕过\n // 登录门直接访问远端 SPA(元数据同步的「打开远端会话」链路)。\n try {\n const browserSecret = await this.browserSecretProvider()\n if (browserSecret && requestHasValidRelayCookie(req.headers.cookie, browserSecret, req.headers.host, Date.now())) {\n return 'allow'\n }\n } catch {}\n if (this.isPageRequest(req)) return 'redirect-login'\n return 'reject'\n }\n\n private isPageRequest(req: IncomingMessage): boolean {\n if (req.method !== 'GET' && req.method !== 'HEAD') return false\n const path = new URL(req.url ?? '/', 'http://x').pathname\n if (path.startsWith('/api/')) return false\n const accept = req.headers.accept ?? ''\n return accept.includes('text/html') || accept.includes('*/*')\n }\n}\n\nexport function rewriteToLoopback(req: IncomingMessage, port?: number): void {\n const localPort = port ?? req.socket.localPort\n if (typeof localPort !== 'number') return\n const authority = `127.0.0.1:${localPort}`\n req.headers.host = authority\n for (const name of ['origin', 'referer'] as const) {\n const value = req.headers[name]\n if (typeof value !== 'string') continue\n try {\n const url = new URL(value)\n url.host = authority\n req.headers[name] = url.toString()\n } catch {}\n }\n}\n"],"mappings":";;;;;;;;;;;AAkBA,SAAgB,qBAAqB,KAA+B;CAClE,IAAI,CAAC,kBAAkB,IAAI,OAAO,aAAa,GAAG,OAAO;CACzD,IAAI,IAAI,QAAQ,sBAAsB,cAAc,OAAO;CAC3D,MAAM,SAAS,IAAI,QAAQ;CAC3B,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,IAAI,OAAO,WAAW,YAAY,CAAC,IAAI,QAAQ,MAAM,OAAO;CAC5D,IAAI;EACF,OAAO,IAAI,IAAI,MAAM,CAAC,CAAC,SAAS,IAAI,IAAI,UAAU,IAAI,QAAQ,MAAM,CAAC,CAAC;CACxE,QAAQ;EACN,OAAO;CACT;AACF;AAEA,IAAa,WAAb,MAAsB;CAKD;CAJnB;CACA;CAEA,YACE,OACA,uBACA;EAFiB,KAAA,QAAA;EAGjB,KAAK,wBAAwB,gCAAgC,QAAQ,QAAQ,KAAA,CAAS;CACxF;CAEA,yBAAyB,OAAgD;EACvE,KAAK,uBAAuB;CAC9B;;;;;;CAOA,MAAM,OAAO,KAA6C;EACxD,MAAM,OAAO,IAAI,IAAI,IAAI,OAAO,KAAK,UAAU,CAAC,CAAC;EACjD,IAAI,SAAS,UAAU,OAAO;EAC9B,IAAI,SAAS,eAAe,KAAK,WAAW,YAAY,GAItD,QAHgB,KAAK,uBACjB,KAAK,qBAAqB,GAAG,IAC7B,qBAAqB,GAAG,KACX,WAAW;EAE9B,IAAI,kBAAkB,IAAI,OAAO,eAAe,IAAI,QAAQ,IAAI,GAAG,OAA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CtwES4Xn.js";
|
|
2
3
|
import { AuthGate, isTrustedAuthRequest } from "./gate.js";
|
|
3
4
|
import { decorateWebServer } from "./decorate-webserver.js";
|
|
4
5
|
import { installLoopbackCompat } from "./loopback-compat.js";
|
|
@@ -8,9 +9,10 @@ import { createRequire } from "node:module";
|
|
|
8
9
|
import { readFileSync, readdirSync, realpathSync } from "node:fs";
|
|
9
10
|
import { basename, dirname, join } from "node:path";
|
|
10
11
|
import { fileURLToPath } from "node:url";
|
|
12
|
+
import { credentialKey } from "@deepseek-ai/dsh-credentials";
|
|
11
13
|
//#region src/auth/index.ts
|
|
12
14
|
const name = "dshb-auth";
|
|
13
|
-
const inject = ["webServer"];
|
|
15
|
+
const inject = ["webServer", "credentials"];
|
|
14
16
|
/**
|
|
15
17
|
* 定位 dshb 实际安装所在 profile 的 node_modules。
|
|
16
18
|
* link 安装(开发预览)下 ESM 真实路径解析会把 import.meta.url 指向仓库源码,
|
|
@@ -75,7 +77,24 @@ function registerFrontendBootRaceWorkaround(ctx) {
|
|
|
75
77
|
}
|
|
76
78
|
function apply(ctx) {
|
|
77
79
|
const store = sharedCredentialStore();
|
|
78
|
-
|
|
80
|
+
let cachedBrowserSecret;
|
|
81
|
+
let browserSecretFetchInFlight = false;
|
|
82
|
+
const credentialsLike = ctx.credentials;
|
|
83
|
+
const browserSecretProvider = async () => {
|
|
84
|
+
if (cachedBrowserSecret !== void 0) return cachedBrowserSecret ?? void 0;
|
|
85
|
+
if (!credentialsLike || browserSecretFetchInFlight) return void 0;
|
|
86
|
+
browserSecretFetchInFlight = true;
|
|
87
|
+
try {
|
|
88
|
+
const record = await credentialsLike.readRecord(credentialKey("client-connection", "browser-session"));
|
|
89
|
+
cachedBrowserSecret = browserSessionSecret(record) ?? null;
|
|
90
|
+
} catch {
|
|
91
|
+
cachedBrowserSecret = null;
|
|
92
|
+
} finally {
|
|
93
|
+
browserSecretFetchInFlight = false;
|
|
94
|
+
}
|
|
95
|
+
return cachedBrowserSecret ?? void 0;
|
|
96
|
+
};
|
|
97
|
+
const gate = new AuthGate(store, browserSecretProvider);
|
|
79
98
|
ctx.effect(() => decorateWebServer(ctx.webServer, store, gate));
|
|
80
99
|
registerFrontendBootRaceWorkaround(ctx);
|
|
81
100
|
ctx.effect(() => ctx.webServer.tapIndex(installLoopbackCompat));
|
package/lib/auth/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/auth/index.ts"],"sourcesContent":["import { readFileSync, readdirSync, realpathSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport type { IncomingMessage } from 'node:http'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { sharedCredentialStore } from './credentials.js'\nimport { decorateWebServer } from './decorate-webserver.js'\nimport { AuthGate, isTrustedAuthRequest } from './gate.js'\nimport { installLoopbackCompat } from './loopback-compat.js'\nimport { LoginRateLimiter } from './ratelimit.js'\nimport { registerAuthRoutes } from './routes.js'\n\nexport const name = 'dshb-auth'\n\nexport const inject = ['webServer']\n\n/**\n * 定位 dshb 实际安装所在 profile 的 node_modules。\n * link 安装(开发预览)下 ESM 真实路径解析会把 import.meta.url 指向仓库源码,\n * 由此向上 resolve 会命中仓库工作区的 @deepseek-ai/dsh-web-app 副本;服务器\n * 实际服务的却是 profile 内那份。通过 DSH_HOME/profiles 扫描 realpath 匹配\n * 找回安装位置;常规安装(真实文件就在 profile 内)时现有解析本就正确。\n */\nfunction profileNodeModulesFor(realSelfPath: string): string | undefined {\n const home = process.env.DSH_HOME\n if (!home) return undefined\n const profilesDir = join(home, 'profiles')\n let names: string[]\n try {\n names = readdirSync(profilesDir)\n } catch {\n return undefined\n }\n for (const name of names) {\n const installed = join(profilesDir, name, 'node_modules', '@artenx', 'dshb')\n try {\n const realInstalled = realpathSync(installed)\n if (realInstalled === realSelfPath || realSelfPath.startsWith(`${realInstalled}/`)) {\n return join(profilesDir, name, 'node_modules')\n }\n } catch {\n /* profile without this package */\n }\n }\n return undefined\n}\n\nfunction registerFrontendBootRaceWorkaround(ctx: Context): void {\n try {\n // Resolve the frontend through the same runtime package tree the webserver\n // loads, so the patched hashed asset is the one the static fallback serves.\n // A linked plugin profile may contain only @artenx/dshb; its DSH executable\n // supplies the actual @deepseek-ai bundle tree.\n const resolver = createRequire(import.meta.url)\n const realSelf = realpathSync(fileURLToPath(import.meta.url))\n const profileModules = profileNodeModulesFor(realSelf)\n const webAppResolvers: Array<() => string> = []\n if (profileModules) {\n webAppResolvers.push(() => resolver.resolve('@deepseek-ai/dsh-web-app/package.json', { paths: [profileModules] }))\n }\n if (process.argv[1]) {\n webAppResolvers.push(() => createRequire(realpathSync(process.argv[1]!)).resolve('@deepseek-ai/dsh-web-app/package.json'))\n }\n webAppResolvers.push(() => resolver.resolve('@deepseek-ai/dsh-web-app/package.json'))\n let webAppManifest: string | undefined\n for (const resolveWebApp of webAppResolvers) {\n try {\n webAppManifest = resolveWebApp()\n break\n } catch {\n // Try the next runtime-owned package tree.\n }\n }\n let manifestPath: string\n if (webAppManifest) {\n manifestPath = createRequire(webAppManifest).resolve('@deepseek-ai/dsh-web-frontend/package.json')\n } else {\n manifestPath = resolver.resolve('@deepseek-ai/dsh-web-frontend/package.json', {\n paths: [process.cwd()],\n })\n }\n const assetDir = join(dirname(manifestPath), 'dist', 'assets')\n const assetName = readdirSync(assetDir).find((name) => /^index-.*\\.js$/.test(name))\n if (!assetName) return\n\n const assetPath = join(assetDir, assetName)\n const source = readFileSync(assetPath, 'utf8')\n // DSH asserts before api-remotes' dynamic remote namespace fibers settle.\n // Delay the assertion so mountApp sees the complete client graph; real\n // activation failures still throw after the bounded wait. The minified\n // identifiers vary between builds, and 0.1.7 moved the assertion into nE.\n const legacyPatch = source.replace(\n /await ([A-Za-z_$][\\w$]*)\\.await\\(\\),this\\.assertEntriesActive\\(([A-Za-z_$][\\w$]*)\\)/,\n 'await $1.await(),await new Promise(r=>setTimeout(r,8000)),this.assertEntriesActive($2)',\n )\n const patched = legacyPatch !== source\n ? legacyPatch\n : source.replace(\n /await ([A-Za-z_$][\\w$]*)\\.await\\(\\),([A-Za-z_$][\\w$]*)\\(([A-Za-z_$][\\w$]*),([A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*)\\)/,\n 'await $1.await(),await new Promise(r=>setTimeout(r,8000)),$2($3,$4)',\n )\n if (patched === source) return\n\n ctx.effect(() =>\n ctx.webServer.register({\n kind: 'exact',\n path: `/assets/${basename(assetPath)}`,\n handler: (_req, res) => {\n res.writeHead(200, {\n 'cache-control': 'no-store',\n 'content-type': 'application/javascript; charset=utf-8',\n })\n res.end(patched)\n },\n }),\n )\n } catch {\n // Upstream assets are optional from DSHB's perspective. A missing or changed\n // frontend layout simply skips this version-specific workaround.\n }\n}\n\nexport function apply(ctx: Context): void {\n const store = sharedCredentialStore()\n const gate = new AuthGate(store)\n ctx.effect(() => decorateWebServer(ctx.webServer, store, gate))\n registerFrontendBootRaceWorkaround(ctx)\n ctx.effect(() => ctx.webServer.tapIndex(installLoopbackCompat))\n registerAuthRoutes(ctx, store, new LoginRateLimiter())\n\n // DSH 0.1.5 introduced a browser-auth fence on the connection package: the SPA\n // fallback calls connection.authorizeIndex() on \"/\" (mints/checks DSH's own\n // launch-token cookie), and /api routes run requestRejection() which 401s when\n // that DSH cookie is absent. DSHB uses its own session cookie and must stay the\n // sole auth gate (DSH 0.1.1 had no such connection fence, so DSHB worked there).\n // Neutralize the connection's browserAuth.isAuthenticated check so DSH's fence\n // never rejects a DSHB-authenticated (or loopback) request; DSHB's gate still\n // rejects unauthenticated access to gated routes. Property is read at request\n // time, so installing it once after connection is ready suffices.\n ctx.inject(['connection'], (connCtx: Context) => {\n connCtx.effect(() => {\n const conn = (connCtx as unknown as {\n connection?: {\n browserAuth?: { isAuthenticated?: (...a: unknown[]) => unknown; __dshbNeutralized?: true }\n requestRejection?: (request: IncomingMessage) => number | undefined\n }\n }).connection\n const auth = conn?.browserAuth\n const originalIsAuthenticated = auth?.isAuthenticated\n const neutralizedIsAuthenticated = () => true\n let installedNeutralizer = false\n if (auth && typeof originalIsAuthenticated === 'function' && !auth.__dshbNeutralized) {\n auth.isAuthenticated = neutralizedIsAuthenticated\n auth.__dshbNeutralized = true\n installedNeutralizer = true\n }\n if (conn && typeof conn.requestRejection === 'function') {\n gate.setAuthRequestTrustCheck((req) => {\n const rejection = conn.requestRejection!(req)\n // DSH 401 is its browser-cookie gate; DSHB owns that check for these routes.\n if (rejection === undefined || rejection === 401) return true\n // DSH fence rejects non-loopback authorities (403). Preview reverse\n // proxies keep the external Host header, so DSHB falls back to its own\n // source checks (loopback peer address + cross-site protection); the\n // session gate still owns every authenticated route after login.\n return isTrustedAuthRequest(req)\n })\n }\n return () => {\n if (!auth || !installedNeutralizer) return\n if (auth.isAuthenticated === neutralizedIsAuthenticated && originalIsAuthenticated) {\n auth.isAuthenticated = originalIsAuthenticated\n }\n delete auth.__dshbNeutralized\n }\n })\n })\n}\n"],"mappings":";;;;;;;;;;;AAaA,MAAa,OAAO;AAEpB,MAAa,SAAS,CAAC,WAAW;;;;;;;;AASlC,SAAS,sBAAsB,cAA0C;CACvE,MAAM,OAAO,QAAQ,IAAI;CACzB,IAAI,CAAC,MAAM,OAAO,KAAA;CAClB,MAAM,cAAc,KAAK,MAAM,UAAU;CACzC,IAAI;CACJ,IAAI;EACF,QAAQ,YAAY,WAAW;CACjC,QAAQ;EACN;CACF;CACA,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,YAAY,KAAK,aAAa,MAAM,gBAAgB,WAAW,MAAM;EAC3E,IAAI;GACF,MAAM,gBAAgB,aAAa,SAAS;GAC5C,IAAI,kBAAkB,gBAAgB,aAAa,WAAW,GAAG,cAAc,EAAE,GAC/E,OAAO,KAAK,aAAa,MAAM,cAAc;EAEjD,QAAQ,CAER;CACF;AAEF;AAEA,SAAS,mCAAmC,KAAoB;CAC9D,IAAI;EAKF,MAAM,WAA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AAEA,SAAgB,MAAM,KAAoB;CACxC,MAAM,QAAQ,sBAAsB;CACpC,MAAM,OAAO,IAAI,SAAS,KAAK;CAC/B,IAAI,aAAa,kBAAkB,IAAI,WAAW,OAAO,IAAI,CAAC;CAC9D,mCAAmC,GAAG;CACtC,IAAI,aAAa,IAAI,UAAU,SAAS,qBAAqB,CAAC;CAC9D,mBAAmB,KAAK,OAAO,IAAI,iBAAiB,CAAC;CAWrD,IAAI,OAAO,CAAC,YAAY,IAAI,YAAqB;EAC/C,QAAQ,aAAa;GACnB,MAAM,OAAQ,QAKX;GACH,MAAM,OAAO,MAAM;GACnB,MAAM,0BAA0B,MAAM;GACtC,MAAM,mCAAmC;GACzC,IAAI,uBAAuB;GAC3B,IAAI,QAAQ,OAAO,4BAA4B,cAAc,CAAC,KAAK,mBAAmB;IACpF,KAAK,kBAAkB;IACvB,KAAK,oBAAoB;IACzB,uBAAuB;GACzB;GACA,IAAI,QAAQ,OAAO,KAAK,qBAAqB,YAC3C,KAAK,0BAA0B,QAAQ;IACrC,MAAM,YAAY,KAAK,iBAAkB,GAAG;IAE5C,IAAI,cAAc,KAAA,KAAa,cAAc,KAAK,OAAO;IAKzD,OAAO,qBAAqB,GAAG;GACjC,CAAC;GAEH,aAAa;IACX,IAAI,CAAC,QAAQ,CAAC,sBAAsB;IACpC,IAAI,KAAK,oBAAoB,8BAA8B,yBACzD,KAAK,kBAAkB;IAEzB,OAAO,KAAK;GACd;EACF,CAAC;CACH,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/auth/index.ts"],"sourcesContent":["import { readFileSync, readdirSync, realpathSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport type { IncomingMessage } from 'node:http'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { credentialKey } from '@deepseek-ai/dsh-credentials'\nimport { sharedCredentialStore } from './credentials.js'\nimport { decorateWebServer } from './decorate-webserver.js'\nimport { AuthGate, isTrustedAuthRequest, type BrowserSessionSecretProvider } from './gate.js'\nimport { installLoopbackCompat } from './loopback-compat.js'\nimport { LoginRateLimiter } from './ratelimit.js'\nimport { registerAuthRoutes } from './routes.js'\nimport { browserSessionSecret } from '../core/sync/relay-auth.js'\n\nexport const name = 'dshb-auth'\n\nexport const inject = ['webServer', 'credentials']\n\n/**\n * 定位 dshb 实际安装所在 profile 的 node_modules。\n * link 安装(开发预览)下 ESM 真实路径解析会把 import.meta.url 指向仓库源码,\n * 由此向上 resolve 会命中仓库工作区的 @deepseek-ai/dsh-web-app 副本;服务器\n * 实际服务的却是 profile 内那份。通过 DSH_HOME/profiles 扫描 realpath 匹配\n * 找回安装位置;常规安装(真实文件就在 profile 内)时现有解析本就正确。\n */\nfunction profileNodeModulesFor(realSelfPath: string): string | undefined {\n const home = process.env.DSH_HOME\n if (!home) return undefined\n const profilesDir = join(home, 'profiles')\n let names: string[]\n try {\n names = readdirSync(profilesDir)\n } catch {\n return undefined\n }\n for (const name of names) {\n const installed = join(profilesDir, name, 'node_modules', '@artenx', 'dshb')\n try {\n const realInstalled = realpathSync(installed)\n if (realInstalled === realSelfPath || realSelfPath.startsWith(`${realInstalled}/`)) {\n return join(profilesDir, name, 'node_modules')\n }\n } catch {\n /* profile without this package */\n }\n }\n return undefined\n}\n\nfunction registerFrontendBootRaceWorkaround(ctx: Context): void {\n try {\n // Resolve the frontend through the same runtime package tree the webserver\n // loads, so the patched hashed asset is the one the static fallback serves.\n // A linked plugin profile may contain only @artenx/dshb; its DSH executable\n // supplies the actual @deepseek-ai bundle tree.\n const resolver = createRequire(import.meta.url)\n const realSelf = realpathSync(fileURLToPath(import.meta.url))\n const profileModules = profileNodeModulesFor(realSelf)\n const webAppResolvers: Array<() => string> = []\n if (profileModules) {\n webAppResolvers.push(() => resolver.resolve('@deepseek-ai/dsh-web-app/package.json', { paths: [profileModules] }))\n }\n if (process.argv[1]) {\n webAppResolvers.push(() => createRequire(realpathSync(process.argv[1]!)).resolve('@deepseek-ai/dsh-web-app/package.json'))\n }\n webAppResolvers.push(() => resolver.resolve('@deepseek-ai/dsh-web-app/package.json'))\n let webAppManifest: string | undefined\n for (const resolveWebApp of webAppResolvers) {\n try {\n webAppManifest = resolveWebApp()\n break\n } catch {\n // Try the next runtime-owned package tree.\n }\n }\n let manifestPath: string\n if (webAppManifest) {\n manifestPath = createRequire(webAppManifest).resolve('@deepseek-ai/dsh-web-frontend/package.json')\n } else {\n manifestPath = resolver.resolve('@deepseek-ai/dsh-web-frontend/package.json', {\n paths: [process.cwd()],\n })\n }\n const assetDir = join(dirname(manifestPath), 'dist', 'assets')\n const assetName = readdirSync(assetDir).find((name) => /^index-.*\\.js$/.test(name))\n if (!assetName) return\n\n const assetPath = join(assetDir, assetName)\n const source = readFileSync(assetPath, 'utf8')\n // DSH asserts before api-remotes' dynamic remote namespace fibers settle.\n // Delay the assertion so mountApp sees the complete client graph; real\n // activation failures still throw after the bounded wait. The minified\n // identifiers vary between builds, and 0.1.7 moved the assertion into nE.\n const legacyPatch = source.replace(\n /await ([A-Za-z_$][\\w$]*)\\.await\\(\\),this\\.assertEntriesActive\\(([A-Za-z_$][\\w$]*)\\)/,\n 'await $1.await(),await new Promise(r=>setTimeout(r,8000)),this.assertEntriesActive($2)',\n )\n const patched = legacyPatch !== source\n ? legacyPatch\n : source.replace(\n /await ([A-Za-z_$][\\w$]*)\\.await\\(\\),([A-Za-z_$][\\w$]*)\\(([A-Za-z_$][\\w$]*),([A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*)\\)/,\n 'await $1.await(),await new Promise(r=>setTimeout(r,8000)),$2($3,$4)',\n )\n if (patched === source) return\n\n ctx.effect(() =>\n ctx.webServer.register({\n kind: 'exact',\n path: `/assets/${basename(assetPath)}`,\n handler: (_req, res) => {\n res.writeHead(200, {\n 'cache-control': 'no-store',\n 'content-type': 'application/javascript; charset=utf-8',\n })\n res.end(patched)\n },\n }),\n )\n } catch {\n // Upstream assets are optional from DSHB's perspective. A missing or changed\n // frontend layout simply skips this version-specific workaround.\n }\n}\n\nexport function apply(ctx: Context): void {\n const store = sharedCredentialStore()\n // relay cookie 校验需读 dsh browser-session 密钥;credentials 可能晚于\n // auth 插件就绪,provider 每次按需读取并缓存(密钥仅在凭据重置时变化)。\n let cachedBrowserSecret: Buffer | null | undefined\n let browserSecretFetchInFlight = false\n const credentialsLike = (ctx as unknown as { credentials?: { readRecord: (key: unknown) => Promise<unknown> } }).credentials\n const browserSecretProvider: BrowserSessionSecretProvider = async () => {\n if (cachedBrowserSecret !== undefined) return cachedBrowserSecret ?? undefined\n if (!credentialsLike || browserSecretFetchInFlight) return undefined\n browserSecretFetchInFlight = true\n try {\n const record = await credentialsLike.readRecord(credentialKey('client-connection', 'browser-session'))\n cachedBrowserSecret = browserSessionSecret(record) ?? null\n } catch {\n cachedBrowserSecret = null\n } finally {\n browserSecretFetchInFlight = false\n }\n return cachedBrowserSecret ?? undefined\n }\n const gate = new AuthGate(store, browserSecretProvider)\n ctx.effect(() => decorateWebServer(ctx.webServer, store, gate))\n registerFrontendBootRaceWorkaround(ctx)\n ctx.effect(() => ctx.webServer.tapIndex(installLoopbackCompat))\n registerAuthRoutes(ctx, store, new LoginRateLimiter())\n\n // DSH 0.1.5 introduced a browser-auth fence on the connection package: the SPA\n // fallback calls connection.authorizeIndex() on \"/\" (mints/checks DSH's own\n // launch-token cookie), and /api routes run requestRejection() which 401s when\n // that DSH cookie is absent. DSHB uses its own session cookie and must stay the\n // sole auth gate (DSH 0.1.1 had no such connection fence, so DSHB worked there).\n // Neutralize the connection's browserAuth.isAuthenticated check so DSH's fence\n // never rejects a DSHB-authenticated (or loopback) request; DSHB's gate still\n // rejects unauthenticated access to gated routes. Property is read at request\n // time, so installing it once after connection is ready suffices.\n ctx.inject(['connection'], (connCtx: Context) => {\n connCtx.effect(() => {\n const conn = (connCtx as unknown as {\n connection?: {\n browserAuth?: { isAuthenticated?: (...a: unknown[]) => unknown; __dshbNeutralized?: true }\n requestRejection?: (request: IncomingMessage) => number | undefined\n }\n }).connection\n const auth = conn?.browserAuth\n const originalIsAuthenticated = auth?.isAuthenticated\n const neutralizedIsAuthenticated = () => true\n let installedNeutralizer = false\n if (auth && typeof originalIsAuthenticated === 'function' && !auth.__dshbNeutralized) {\n auth.isAuthenticated = neutralizedIsAuthenticated\n auth.__dshbNeutralized = true\n installedNeutralizer = true\n }\n if (conn && typeof conn.requestRejection === 'function') {\n gate.setAuthRequestTrustCheck((req) => {\n const rejection = conn.requestRejection!(req)\n // DSH 401 is its browser-cookie gate; DSHB owns that check for these routes.\n if (rejection === undefined || rejection === 401) return true\n // DSH fence rejects non-loopback authorities (403). Preview reverse\n // proxies keep the external Host header, so DSHB falls back to its own\n // source checks (loopback peer address + cross-site protection); the\n // session gate still owns every authenticated route after login.\n return isTrustedAuthRequest(req)\n })\n }\n return () => {\n if (!auth || !installedNeutralizer) return\n if (auth.isAuthenticated === neutralizedIsAuthenticated && originalIsAuthenticated) {\n auth.isAuthenticated = originalIsAuthenticated\n }\n delete auth.__dshbNeutralized\n }\n })\n })\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,MAAa,OAAO;AAEpB,MAAa,SAAS,CAAC,aAAa,aAAa;;;;;;;;AASjD,SAAS,sBAAsB,cAA0C;CACvE,MAAM,OAAO,QAAQ,IAAI;CACzB,IAAI,CAAC,MAAM,OAAO,KAAA;CAClB,MAAM,cAAc,KAAK,MAAM,UAAU;CACzC,IAAI;CACJ,IAAI;EACF,QAAQ,YAAY,WAAW;CACjC,QAAQ;EACN;CACF;CACA,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,YAAY,KAAK,aAAa,MAAM,gBAAgB,WAAW,MAAM;EAC3E,IAAI;GACF,MAAM,gBAAgB,aAAa,SAAS;GAC5C,IAAI,kBAAkB,gBAAgB,aAAa,WAAW,GAAG,cAAc,EAAE,GAC/E,OAAO,KAAK,aAAa,MAAM,cAAc;EAEjD,QAAQ,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B,GAAG;GACjC,CAAC;GAEH,aAAa;IACX,IAAI,CAAC,QAAQ,CAAC,sBAAsB;IACpC,IAAI,KAAK,oBAAoB,8BAA8B,yBACzD,KAAK,kBAAkB;IAEzB,OAAO,KAAK;GACd;EACF,CAAC;CACH,CAAC;AACH"}
|
package/lib/auth/webserver.js
CHANGED
|
@@ -27,8 +27,8 @@ var AuthedWebServer = class extends WebServer {
|
|
|
27
27
|
handler: (req, socket, head) => this.guardedUpgrade(route, req, socket, head)
|
|
28
28
|
});
|
|
29
29
|
}
|
|
30
|
-
guarded(route, req, res) {
|
|
31
|
-
const decision = this.gate.decide(req);
|
|
30
|
+
async guarded(route, req, res) {
|
|
31
|
+
const decision = await this.gate.decide(req);
|
|
32
32
|
if (decision === "allow") {
|
|
33
33
|
rewriteToLoopback(req, this.port);
|
|
34
34
|
return route.handler(req, res);
|
|
@@ -53,8 +53,8 @@ var AuthedWebServer = class extends WebServer {
|
|
|
53
53
|
error: "unauthorized"
|
|
54
54
|
}));
|
|
55
55
|
}
|
|
56
|
-
guardedUpgrade(route, req, socket, head) {
|
|
57
|
-
const decision = this.gate.decide(req);
|
|
56
|
+
async guardedUpgrade(route, req, socket, head) {
|
|
57
|
+
const decision = await this.gate.decide(req);
|
|
58
58
|
if (decision === "allow" || decision === "exempt") {
|
|
59
59
|
if (decision === "allow") rewriteToLoopback(req, this.port);
|
|
60
60
|
return route.handler(req, socket, head);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webserver.js","names":[],"sources":["../../src/auth/webserver.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Duplex } from 'node:stream'\nimport WebServer from '@deepseek-ai/dsh-host-webserver'\nimport type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { sharedCredentialStore } from './credentials.js'\nimport { AuthGate, rewriteToLoopback } from './gate.js'\n\nexport default class AuthedWebServer extends WebServer {\n private readonly gate = new AuthGate(sharedCredentialStore())\n\n constructor(ctx: Context, config: { host: string; port: number }) {\n super(ctx, config)\n }\n\n override register(route: WebRoute): () => void {\n return super.register({ ...route, handler: (req, res) => this.guarded(route, req, res) })\n }\n\n override registerFallback(handler: WebRoute['handler'] | { resource: unknown }): () => void {\n if (typeof handler === 'object'\n && handler !== null\n && 'resource' in handler\n && typeof handler.resource === 'function') {\n return super.registerFallback(handler as unknown as WebRoute['handler'])\n }\n return super.registerFallback((req, res) =>\n this.guarded({ kind: 'exact', path: '/', handler: handler as WebRoute['handler'] }, req, res),\n )\n }\n\n override registerUpgrade(route: WebUpgradeRoute): () => void {\n return super.registerUpgrade({\n ...route,\n handler: (req, socket, head) => this.guardedUpgrade(route, req, socket, head),\n })\n }\n\n private guarded(route: WebRoute, req: IncomingMessage, res: ServerResponse):
|
|
1
|
+
{"version":3,"file":"webserver.js","names":[],"sources":["../../src/auth/webserver.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Duplex } from 'node:stream'\nimport WebServer from '@deepseek-ai/dsh-host-webserver'\nimport type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { sharedCredentialStore } from './credentials.js'\nimport { AuthGate, rewriteToLoopback } from './gate.js'\n\nexport default class AuthedWebServer extends WebServer {\n private readonly gate = new AuthGate(sharedCredentialStore())\n\n constructor(ctx: Context, config: { host: string; port: number }) {\n super(ctx, config)\n }\n\n override register(route: WebRoute): () => void {\n return super.register({ ...route, handler: (req, res) => this.guarded(route, req, res) })\n }\n\n override registerFallback(handler: WebRoute['handler'] | { resource: unknown }): () => void {\n if (typeof handler === 'object'\n && handler !== null\n && 'resource' in handler\n && typeof handler.resource === 'function') {\n return super.registerFallback(handler as unknown as WebRoute['handler'])\n }\n return super.registerFallback((req, res) =>\n this.guarded({ kind: 'exact', path: '/', handler: handler as WebRoute['handler'] }, req, res),\n )\n }\n\n override registerUpgrade(route: WebUpgradeRoute): () => void {\n return super.registerUpgrade({\n ...route,\n handler: (req, socket, head) => this.guardedUpgrade(route, req, socket, head),\n })\n }\n\n private async guarded(route: WebRoute, req: IncomingMessage, res: ServerResponse): Promise<void> {\n const decision = await this.gate.decide(req)\n if (decision === 'allow') {\n rewriteToLoopback(req, this.port)\n return route.handler(req, res)\n }\n if (decision === 'exempt') {\n return route.handler(req, res)\n }\n if (decision === 'redirect-login') {\n res.writeHead(302, { location: '/login' })\n res.end()\n return\n }\n if (decision === 'forbidden') {\n res.writeHead(403, { 'content-type': 'application/json' })\n res.end(JSON.stringify({ ok: false, error: 'forbidden' }))\n return\n }\n res.writeHead(401, { 'content-type': 'application/json' })\n res.end(JSON.stringify({ ok: false, error: 'unauthorized' }))\n }\n\n private async guardedUpgrade(\n route: WebUpgradeRoute,\n req: IncomingMessage,\n socket: Duplex,\n head: Buffer,\n ): Promise<void> {\n const decision = await this.gate.decide(req)\n if (decision === 'allow' || decision === 'exempt') {\n if (decision === 'allow') rewriteToLoopback(req, this.port)\n return route.handler(req, socket, head)\n }\n socket.write(decision === 'forbidden'\n ? 'HTTP/1.1 403 Forbidden\\r\\nConnection: close\\r\\n\\r\\n'\n : 'HTTP/1.1 401 Unauthorized\\r\\nConnection: close\\r\\n\\r\\n')\n socket.destroy()\n }\n}\n"],"mappings":";;;;AAQA,IAAqB,kBAArB,cAA6C,UAAU;CACrD,OAAwB,IAAI,SAAS,sBAAsB,CAAC;CAE5D,YAAY,KAAc,QAAwC;EAChE,MAAM,KAAK,MAAM;CACnB;CAEA,SAAkB,OAA6B;EAC7C,OAAO,MAAM,SAAS;GAAE,GAAG;GAAO,UAAU,KAAK,QAAQ,KAAK,QAAQ,OAAO,KAAK,GAAG;EAAE,CAAC;CAC1F;CAEA,iBAA0B,SAAkE;EAC1F,IAAI,OAAO,YAAY,YAClB,YAAY,QACZ,cAAc,WACd,OAAO,QAAQ,aAAa,YAC/B,OAAO,MAAM,iBAAiB,OAAyC;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@@ -2291,6 +2291,45 @@ window.__ModuleLoader__.load({
|
|
|
2291
2291
|
[data-dshb-remote-overlay] > header { display: flex; align-items: center; gap: 8px; padding: 6px 10px; border-bottom: 1px solid color-mix(in srgb, currentColor 12%, transparent); font-size: 12px; opacity: .85; }
|
|
2292
2292
|
[data-dshb-remote-overlay] > header button { cursor: pointer; }
|
|
2293
2293
|
[data-dshb-remote-overlay] > iframe { flex: 1; width: 100%; border: 0; background: transparent; }
|
|
2294
|
+
`;
|
|
2295
|
+
const REMOTE_CATALOG_PANEL_STYLE = `
|
|
2296
|
+
[data-dshb-remote-catalog="open"] {
|
|
2297
|
+
display: inline-flex; align-items: center; justify-content: center;
|
|
2298
|
+
width: 32px; height: 32px; border: none; border-radius: 8px; background: none;
|
|
2299
|
+
color: inherit; cursor: pointer; opacity: .7; padding: 0;
|
|
2300
|
+
}
|
|
2301
|
+
[data-dshb-remote-catalog="open"]:hover { opacity: 1; background: var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,.18)); }
|
|
2302
|
+
[data-dshb-remote-catalog-panel] {
|
|
2303
|
+
position: fixed; left: 0; top: 0; bottom: 0; width: min(340px, 92vw); z-index: 2147482900;
|
|
2304
|
+
background: var(--dsw-alias-bg-layer-1, #15171b); color: var(--dsw-alias-label-primary, #e8eaed);
|
|
2305
|
+
border-right: 1px solid var(--dsw-alias-border-l2, rgba(255,255,255,.08));
|
|
2306
|
+
box-shadow: 8px 0 28px rgba(0,0,0,.35); display: flex; flex-direction: column;
|
|
2307
|
+
font-size: 13px; overflow: hidden;
|
|
2308
|
+
}
|
|
2309
|
+
[data-dshb-remote-catalog-panel] > header {
|
|
2310
|
+
display: flex; align-items: center; gap: 8px; padding: 10px 12px;
|
|
2311
|
+
border-bottom: 1px solid var(--dsw-alias-border-l2, rgba(255,255,255,.08)); flex: none;
|
|
2312
|
+
}
|
|
2313
|
+
[data-dshb-remote-catalog-panel] > header .title { font-weight: 600; flex: 1; }
|
|
2314
|
+
[data-dshb-remote-catalog-panel] > header button { cursor: pointer; background: none; border: none; color: inherit; padding: 4px; }
|
|
2315
|
+
[data-dshb-remote-catalog-body] { flex: 1; overflow-y: auto; padding: 8px 6px 16px; }
|
|
2316
|
+
[data-dshb-remote-catalog-body] .peer { margin: 6px 4px 12px; }
|
|
2317
|
+
[data-dshb-remote-catalog-body] .peer-name { font-weight: 600; padding: 4px 8px; display: flex; align-items: center; gap: 6px; }
|
|
2318
|
+
[data-dshb-remote-catalog-body] .peer-meta { opacity: .55; font-size: 11px; font-weight: 400; }
|
|
2319
|
+
[data-dshb-remote-catalog-body] .ws { margin: 2px 0 2px 10px; }
|
|
2320
|
+
[data-dshb-remote-catalog-body] .ws-title { padding: 4px 8px; opacity: .8; display: flex; gap: 6px; align-items: baseline; }
|
|
2321
|
+
[data-dshb-remote-catalog-body] .ws-path { font-size: 11px; opacity: .5; font-family: ui-monospace, Menlo, Consolas, monospace; }
|
|
2322
|
+
[data-dshb-remote-catalog-body] .sess {
|
|
2323
|
+
display: flex; align-items: center; gap: 8px; width: calc(100% - 18px); margin: 1px 0 1px 18px;
|
|
2324
|
+
padding: 5px 8px; border: none; border-radius: 8px; background: none; color: inherit;
|
|
2325
|
+
text-align: left; cursor: pointer; font-size: 13px;
|
|
2326
|
+
}
|
|
2327
|
+
[data-dshb-remote-catalog-body] .sess:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(255,255,255,.08)); }
|
|
2328
|
+
[data-dshb-remote-catalog-body] .sess .s-title { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
2329
|
+
[data-dshb-remote-catalog-body] .sess .s-size { font-size: 11px; opacity: .45; flex: none; }
|
|
2330
|
+
[data-dshb-remote-catalog-body] .empty { padding: 8px 12px; opacity: .55; }
|
|
2331
|
+
[data-dshb-remote-catalog-body] .err { padding: 6px 10px; margin: 4px 8px; border-radius: 8px; background: var(--dsw-alias-state-error-tertiary, rgba(220,60,60,.15)); font-size: 12px; }
|
|
2332
|
+
[data-dshb-remote-catalog-backdrop] { position: fixed; inset: 0; z-index: 2147482800; background: rgba(0,0,0,.32); }
|
|
2294
2333
|
`;
|
|
2295
2334
|
function RemoteSessionOverlay({ peerId, onClose }) {
|
|
2296
2335
|
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
|
@@ -2337,6 +2376,251 @@ window.__ModuleLoader__.load({
|
|
|
2337
2376
|
}, RemoteSessionRowAction));
|
|
2338
2377
|
}
|
|
2339
2378
|
//#endregion
|
|
2379
|
+
//#region src/client/remote-catalog.tsx
|
|
2380
|
+
function formatSize(bytes) {
|
|
2381
|
+
if (bytes === void 0 || !Number.isFinite(bytes)) return "";
|
|
2382
|
+
if (bytes < 1024) return `${bytes}B`;
|
|
2383
|
+
if (bytes < 1048576) return `${(bytes / 1024).toFixed(0)}K`;
|
|
2384
|
+
return `${(bytes / 1024 / 1024).toFixed(1)}M`;
|
|
2385
|
+
}
|
|
2386
|
+
function wsKey(origin) {
|
|
2387
|
+
return origin ? `${origin.originInstanceId}/${origin.originEntityId}` : "";
|
|
2388
|
+
}
|
|
2389
|
+
async function fetchPeerCatalog(peerId) {
|
|
2390
|
+
const res = await fetch(`/api/dshb/sync/peers/${encodeURIComponent(peerId)}/catalog`, { cache: "no-store" });
|
|
2391
|
+
const body = await res.json().catch(() => void 0);
|
|
2392
|
+
if (!res.ok || !body?.catalog) throw new Error(body?.code ? `${body.code}${body.error ? `:${body.error}` : ""}` : `HTTP ${res.status}`);
|
|
2393
|
+
return body.catalog;
|
|
2394
|
+
}
|
|
2395
|
+
function CatalogPanel({ peers, onClose }) {
|
|
2396
|
+
const [entries, setEntries] = (0, react.useState)(void 0);
|
|
2397
|
+
const [openSession, setOpenSession] = (0, react.useState)(void 0);
|
|
2398
|
+
const [reloadKey, setReloadKey] = (0, react.useState)(0);
|
|
2399
|
+
(0, react.useEffect)(() => {
|
|
2400
|
+
let cancelled = false;
|
|
2401
|
+
setEntries(void 0);
|
|
2402
|
+
const targets = peers.filter((peer) => peer.enabled);
|
|
2403
|
+
Promise.all(targets.map(async (peer) => {
|
|
2404
|
+
try {
|
|
2405
|
+
return {
|
|
2406
|
+
peer,
|
|
2407
|
+
catalog: await fetchPeerCatalog(peer.id)
|
|
2408
|
+
};
|
|
2409
|
+
} catch (error) {
|
|
2410
|
+
return {
|
|
2411
|
+
peer,
|
|
2412
|
+
error: error instanceof Error ? error.message : String(error)
|
|
2413
|
+
};
|
|
2414
|
+
}
|
|
2415
|
+
})).then((result) => {
|
|
2416
|
+
if (!cancelled) setEntries(result);
|
|
2417
|
+
});
|
|
2418
|
+
return () => {
|
|
2419
|
+
cancelled = true;
|
|
2420
|
+
};
|
|
2421
|
+
}, [peers, reloadKey]);
|
|
2422
|
+
if (openSession) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RemoteSessionOverlay, {
|
|
2423
|
+
peerId: openSession.peerId,
|
|
2424
|
+
onClose: () => setOpenSession(void 0)
|
|
2425
|
+
});
|
|
2426
|
+
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
|
|
2427
|
+
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("style", { children: REMOTE_CATALOG_PANEL_STYLE }),
|
|
2428
|
+
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
|
|
2429
|
+
"data-dshb-remote-catalog-backdrop": true,
|
|
2430
|
+
onClick: onClose
|
|
2431
|
+
}),
|
|
2432
|
+
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
|
2433
|
+
"data-dshb-remote-catalog-panel": true,
|
|
2434
|
+
role: "dialog",
|
|
2435
|
+
"aria-label": "远端目录",
|
|
2436
|
+
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("header", { children: [
|
|
2437
|
+
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
|
|
2438
|
+
className: "title",
|
|
2439
|
+
children: "远端目录"
|
|
2440
|
+
}),
|
|
2441
|
+
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
|
|
2442
|
+
type: "button",
|
|
2443
|
+
"aria-label": "刷新",
|
|
2444
|
+
title: "重新拉取目录",
|
|
2445
|
+
onClick: () => setReloadKey((k) => k + 1),
|
|
2446
|
+
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
|
|
2447
|
+
width: "14",
|
|
2448
|
+
height: "14",
|
|
2449
|
+
viewBox: "0 0 16 16",
|
|
2450
|
+
fill: "none",
|
|
2451
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
2452
|
+
"aria-hidden": "true",
|
|
2453
|
+
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
|
|
2454
|
+
d: "M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 2.5V6h-3.5",
|
|
2455
|
+
stroke: "currentColor",
|
|
2456
|
+
strokeWidth: "1.5",
|
|
2457
|
+
strokeLinecap: "round",
|
|
2458
|
+
strokeLinejoin: "round"
|
|
2459
|
+
})
|
|
2460
|
+
})
|
|
2461
|
+
}),
|
|
2462
|
+
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
|
|
2463
|
+
type: "button",
|
|
2464
|
+
"aria-label": "关闭",
|
|
2465
|
+
title: "关闭",
|
|
2466
|
+
onClick: onClose,
|
|
2467
|
+
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("svg", {
|
|
2468
|
+
width: "14",
|
|
2469
|
+
height: "14",
|
|
2470
|
+
viewBox: "0 0 16 16",
|
|
2471
|
+
fill: "none",
|
|
2472
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
2473
|
+
"aria-hidden": "true",
|
|
2474
|
+
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
|
|
2475
|
+
d: "M4 4l8 8M12 4l-8 8",
|
|
2476
|
+
stroke: "currentColor",
|
|
2477
|
+
strokeWidth: "1.5",
|
|
2478
|
+
strokeLinecap: "round"
|
|
2479
|
+
})
|
|
2480
|
+
})
|
|
2481
|
+
})
|
|
2482
|
+
] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
|
2483
|
+
"data-dshb-remote-catalog-body": true,
|
|
2484
|
+
children: [
|
|
2485
|
+
entries === void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
|
|
2486
|
+
className: "empty",
|
|
2487
|
+
children: "正在拉取远端目录…"
|
|
2488
|
+
}) : null,
|
|
2489
|
+
entries?.map((entry) => {
|
|
2490
|
+
const sessions = (entry.catalog?.sessions ?? []).filter((session) => !session.deleted);
|
|
2491
|
+
const workspaces = entry.catalog?.workspaces ?? [];
|
|
2492
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
2493
|
+
for (const workspace of workspaces) grouped.set(wsKey(workspace.origin), {
|
|
2494
|
+
title: workspace.title || workspace.remotePath,
|
|
2495
|
+
remotePath: workspace.remotePath,
|
|
2496
|
+
sessions: []
|
|
2497
|
+
});
|
|
2498
|
+
for (const session of sessions) {
|
|
2499
|
+
const key = wsKey(session.workspaceOrigin);
|
|
2500
|
+
const bucket = grouped.get(key);
|
|
2501
|
+
if (bucket) bucket.sessions.push(session);
|
|
2502
|
+
else grouped.set(key, {
|
|
2503
|
+
title: session.workspaceRemotePath || "未分组",
|
|
2504
|
+
remotePath: session.workspaceRemotePath ?? "",
|
|
2505
|
+
sessions: [session]
|
|
2506
|
+
});
|
|
2507
|
+
}
|
|
2508
|
+
const orphanKey = wsKey(void 0);
|
|
2509
|
+
const orphan = grouped.get(orphanKey);
|
|
2510
|
+
if (orphan && orphan.sessions.length === 0) grouped.delete(orphanKey);
|
|
2511
|
+
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
|
2512
|
+
className: "peer",
|
|
2513
|
+
children: [
|
|
2514
|
+
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
|
2515
|
+
className: "peer-name",
|
|
2516
|
+
children: [entry.peer.name || entry.peer.id, /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
|
|
2517
|
+
className: "peer-meta",
|
|
2518
|
+
children: entry.catalog ? `${workspaces.length} 工作区 · ${sessions.length} 会话` : ""
|
|
2519
|
+
})]
|
|
2520
|
+
}),
|
|
2521
|
+
entry.error ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
|
|
2522
|
+
className: "err",
|
|
2523
|
+
children: entry.error
|
|
2524
|
+
}) : null,
|
|
2525
|
+
entry.catalog && grouped.size === 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
|
|
2526
|
+
className: "empty",
|
|
2527
|
+
children: "远端暂无工作区或会话"
|
|
2528
|
+
}) : null,
|
|
2529
|
+
[...grouped.entries()].map(([key, group]) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
|
2530
|
+
className: "ws",
|
|
2531
|
+
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
|
2532
|
+
className: "ws-title",
|
|
2533
|
+
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: group.title }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
|
|
2534
|
+
className: "ws-path",
|
|
2535
|
+
children: group.remotePath
|
|
2536
|
+
})]
|
|
2537
|
+
}), group.sessions.map((session) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
|
|
2538
|
+
type: "button",
|
|
2539
|
+
className: "sess",
|
|
2540
|
+
title: `打开远端会话(实时操作 ${entry.peer.name})`,
|
|
2541
|
+
onClick: () => setOpenSession({
|
|
2542
|
+
peerId: entry.peer.id,
|
|
2543
|
+
title: session.title ?? session.sessionId
|
|
2544
|
+
}),
|
|
2545
|
+
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
|
|
2546
|
+
className: "s-title",
|
|
2547
|
+
children: session.title || session.sessionId
|
|
2548
|
+
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
|
|
2549
|
+
className: "s-size",
|
|
2550
|
+
children: formatSize(session.sizeBytes)
|
|
2551
|
+
})]
|
|
2552
|
+
}, session.origin.originEntityId || session.sessionId))]
|
|
2553
|
+
}, key))
|
|
2554
|
+
]
|
|
2555
|
+
}, entry.peer.id);
|
|
2556
|
+
}),
|
|
2557
|
+
entries !== void 0 && entries.length === 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
|
|
2558
|
+
className: "empty",
|
|
2559
|
+
children: "尚无已启用的同步节点"
|
|
2560
|
+
}) : null
|
|
2561
|
+
]
|
|
2562
|
+
})]
|
|
2563
|
+
})
|
|
2564
|
+
] });
|
|
2565
|
+
}
|
|
2566
|
+
/** 侧栏 footer 的「远端」按钮:打开远端目录浮层。 */
|
|
2567
|
+
function RemoteCatalogButton() {
|
|
2568
|
+
const [open, setOpen] = (0, react.useState)(false);
|
|
2569
|
+
const [peers, setPeers] = (0, react.useState)([]);
|
|
2570
|
+
const loadPeers = (0, react.useCallback)(async () => {
|
|
2571
|
+
try {
|
|
2572
|
+
const body = await (await fetch("/api/dshb/sync/peers", { cache: "no-store" })).json().catch(() => void 0);
|
|
2573
|
+
if (body?.peers) setPeers(body.peers);
|
|
2574
|
+
} catch {}
|
|
2575
|
+
}, []);
|
|
2576
|
+
(0, react.useEffect)(() => {
|
|
2577
|
+
if (open) loadPeers();
|
|
2578
|
+
}, [open, loadPeers]);
|
|
2579
|
+
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
|
|
2580
|
+
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("style", { children: REMOTE_CATALOG_PANEL_STYLE }),
|
|
2581
|
+
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
|
|
2582
|
+
type: "button",
|
|
2583
|
+
"data-dshb-remote-catalog": "open",
|
|
2584
|
+
"aria-label": "远端目录",
|
|
2585
|
+
title: "远端目录(浏览同步节点的远端工作区与会话)",
|
|
2586
|
+
onClick: () => setOpen(true),
|
|
2587
|
+
children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
|
|
2588
|
+
width: "15",
|
|
2589
|
+
height: "15",
|
|
2590
|
+
viewBox: "0 0 16 16",
|
|
2591
|
+
fill: "none",
|
|
2592
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
2593
|
+
"aria-hidden": "true",
|
|
2594
|
+
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
|
|
2595
|
+
cx: "8",
|
|
2596
|
+
cy: "8",
|
|
2597
|
+
r: "6.25",
|
|
2598
|
+
stroke: "currentColor",
|
|
2599
|
+
strokeWidth: "1.4"
|
|
2600
|
+
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
|
|
2601
|
+
d: "M2 6.5h12M2 9.5h12M8 1.9c-1.8 1.7-2.8 3.8-2.8 6.1s1 4.4 2.8 6.1c1.8-1.7 2.8-3.8 2.8-6.1s-1-4.4-2.8-6.1Z",
|
|
2602
|
+
stroke: "currentColor",
|
|
2603
|
+
strokeWidth: "1.2"
|
|
2604
|
+
})]
|
|
2605
|
+
})
|
|
2606
|
+
}),
|
|
2607
|
+
open ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CatalogPanel, {
|
|
2608
|
+
peers,
|
|
2609
|
+
onClose: () => setOpen(false)
|
|
2610
|
+
}) : null
|
|
2611
|
+
] });
|
|
2612
|
+
}
|
|
2613
|
+
/** 注册侧栏远端目录入口(footer 操作区)。 */
|
|
2614
|
+
function installRemoteCatalogEntry(ctx) {
|
|
2615
|
+
const slots = ctx.slots;
|
|
2616
|
+
if (!slots) return;
|
|
2617
|
+
slots.inject("sidebar.footer.action", () => slots.register({
|
|
2618
|
+
name: "sidebar.footer.action",
|
|
2619
|
+
id: "dshb-remote-catalog",
|
|
2620
|
+
order: 40
|
|
2621
|
+
}, RemoteCatalogButton));
|
|
2622
|
+
}
|
|
2623
|
+
//#endregion
|
|
2340
2624
|
//#region src/client/sync-selection-picker.tsx
|
|
2341
2625
|
function originKey(origin) {
|
|
2342
2626
|
return JSON.stringify([origin.originInstanceId, origin.originEntityId]);
|
|
@@ -5349,6 +5633,7 @@ window.__ModuleLoader__.load({
|
|
|
5349
5633
|
priority: -10
|
|
5350
5634
|
}, DirectoryFlowOccupant));
|
|
5351
5635
|
installRemoteSessionEntry(sub);
|
|
5636
|
+
installRemoteCatalogEntry(sub);
|
|
5352
5637
|
}
|
|
5353
5638
|
});
|
|
5354
5639
|
const ICON_SVG = {
|