dsh-plugin-reverse-proxy 0.0.0-stage → 0.4.2

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,212 @@
1
+ /**
2
+ * dsh-plugin-reverse-proxy host half:trusted-network Connection Replacement。
3
+ *
4
+ * 兼容性按 profile 分代:0.1.2 使用 legacy-web adapter,0.1.5 使用
5
+ * carrier-neutral adapter,0.1.7–0.2.0 使用 carrier-neutral-017 adapter,
6
+ * 0.2.1 起使用 carrier-neutral-021 adapter。公共 apply
7
+ * 只负责 profile/backstop、信任配置、生命周期和固定 warning;版本差异藏在
8
+ * adapter 与 runtime connection loader。
9
+ */
10
+ import { readFileSync } from 'node:fs';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { CONNECTION_PACKAGE, DESKTOP_HOST_PACKAGE, detectHostProfile, GATE_ANCHOR_PACKAGES, GATE_VERSIONS, isActiveCompatibilityProfileId, resolveActiveCompatibilityProfile, } from './gate.js';
13
+ import { COMPATIBILITY_PROFILES } from './compatibility.js';
14
+ import { loadRuntimeConnectionModule } from './connection-runtime.js';
15
+ import { createLegacyWebRuntime } from './adapters/legacy-web.js';
16
+ import { createCarrierNeutralRuntime } from './adapters/carrier-neutral.js';
17
+ import { createCarrierNeutral017Runtime } from './adapters/carrier-neutral-017.js';
18
+ import { createCarrierNeutral021Runtime } from './adapters/carrier-neutral-021.js';
19
+ import { assertTrustedAuthority } from './trust-fence.js';
20
+ import { createTrustedAuth } from './trusted-auth.js';
21
+ import { DEFAULT_MAX_REQUEST_BODY_BYTES } from './bridge.js';
22
+ /** Stable Cordis plugin name. */
23
+ export const name = 'dsh-plugin-reverse-proxy';
24
+ /** The replacement owns a web carrier so dedicated RPC channels have a route owner. */
25
+ export const inject = ['webServer'];
26
+ /** 启动警告固定文案(全局约束:Replacement 激活时逐字输出)。 */
27
+ const SKIP_WARNING = 'dsh-plugin-reverse-proxy: BrowserAuth has been skipped. DSH Web is using the trusted-network behavior; this plugin does not verify any upstream proxy.';
28
+ /** desktop 休眠通知固定文案(0.3.12 起 apply 前置判别休眠时逐字输出;可 grep)。 */
29
+ const DESKTOP_DORMANT_NOTICE = 'dsh-plugin-reverse-proxy: desktop host detected — dormant by design (web-only plugin); official connection untouched. Safe to uninstall.';
30
+ /** Headroom for RPC JSON fields around aggregate base64 image payloads. */
31
+ const REQUEST_ENVELOPE_HEADROOM_BYTES = 1024 * 1024;
32
+ const PROFILE_GLOBAL = '__DSH_SKIP_BROWSER_AUTH_PROFILE__';
33
+ const RECOVERY_GLOBAL = '__DSH_CONNECTION_RECOVERY__';
34
+ const WHITELIST_TEXT = `[${GATE_VERSIONS.map((version) => `'${version}'`).join(', ')}]`;
35
+ function assertImageBodyCapacity(ctx, maxRequestBodyBytes) {
36
+ const attachments = ctx.get('attachments');
37
+ if (attachments === undefined)
38
+ return;
39
+ const requiredImageBodyBytes = Math.ceil(attachments.imageLimits.maxMessageImageBytes * 4 / 3) + REQUEST_ENVELOPE_HEADROOM_BYTES;
40
+ if (maxRequestBodyBytes < requiredImageBodyBytes) {
41
+ throw new Error(`dsh-plugin-reverse-proxy maxRequestBodyBytes (${String(maxRequestBodyBytes)}) must be at least `
42
+ + `${String(requiredImageBodyBytes)} for the configured aggregate image limit`);
43
+ }
44
+ }
45
+ function profileById(value) {
46
+ if (!isActiveCompatibilityProfileId(value))
47
+ return undefined;
48
+ return COMPATIBILITY_PROFILES.find((profile) => profile.id === value && profile.status === 'active');
49
+ }
50
+ /**
51
+ * direct(无 loader/fiber entry)上下文的 profile 兜底:仅纯单测/dev 树可达。
52
+ * 宿主形态按 'web' 处理(dev 树即 web)——apply 的前置宿主判别(0.3.12)凭
53
+ * 槽位/argv/execPath 信号即可判 desktop,真 desktop 上必然先静默休眠,不会走到
54
+ * 这里;resolver 缺失不影响该判别(信号①自行消化 undefined)。
55
+ */
56
+ function directProfile(requestedProfile) {
57
+ if (requestedProfile !== undefined) {
58
+ const requested = profileById(requestedProfile);
59
+ if (requested !== undefined)
60
+ return requested;
61
+ throw new Error(`dsh-plugin-reverse-proxy: compatibility profile ${String(requestedProfile)} is not active; refusing to run`);
62
+ }
63
+ const legacy = profileById('legacy-web-v1');
64
+ if (legacy === undefined) {
65
+ throw new Error('dsh-plugin-reverse-proxy: no active compatibility profile is available for direct context');
66
+ }
67
+ return legacy;
68
+ }
69
+ /**
70
+ * apply 内 backstop(最后防线,fail loud):版本 pair 读取全部门控锚点的
71
+ * manifest,并解析到 active compatibility profile;绑定断言确认当前 entry
72
+ * 子树内的官方 connection 行确实被本插件禁用、同组同名且无活跃 fiber。
73
+ *
74
+ * 产品组合中 loader / internal / current 任一缺失都意味着最后防线无法执行,
75
+ * 必须在创建 Connection 服务与注册 /api 之前 fail loud。没有 loader 与 entry
76
+ * 的直接单元测试上下文才跳过本 backstop。
77
+ *
78
+ * 0.3.12 起 desktop 分支由 apply 的前置宿主判别承接(静默休眠,见 apply),
79
+ * 本函数内的 desktop throw 正常不可达,保留为纵深防御(防未来调用路径回退);
80
+ * 本 backstop 实际只在 web 路径运行,四类契约破坏(锚点解析失败、版本对不在
81
+ * 白名单、profile mismatch、binding violated)照旧 fail loud。
82
+ */
83
+ function assertGateBackstop(ctx, requestedProfile) {
84
+ const loader = ctx.get('loader');
85
+ const current = ctx.fiber?.entry;
86
+ if (loader === undefined && current === undefined)
87
+ return undefined;
88
+ if (loader === undefined) {
89
+ throw new Error('dsh-plugin-reverse-proxy: gate backstop unavailable: loader service is missing');
90
+ }
91
+ if (loader.internal === undefined) {
92
+ throw new Error('dsh-plugin-reverse-proxy: gate backstop unavailable: loader internal resolver is missing');
93
+ }
94
+ if (current === undefined) {
95
+ throw new Error('dsh-plugin-reverse-proxy: gate backstop unavailable: current loader entry is missing');
96
+ }
97
+ const baseUrl = ctx.baseUrl ?? '';
98
+ const internal = loader.internal;
99
+ // 宿主 profile 镜像检测(2026-10-07 web-only 门控,纵深防御层):desktop 信号在
100
+ // 场 ⇒ fail loud。0.3.12 起 apply 的前置判别已在 desktop 上静默休眠返回,此分支
101
+ // 正常不可达,保留为纵深防御(防未来重排序/调用路径回退)。语义与
102
+ // detectHostProfile/表达式层一致(docs/COMPATIBILITY.md §7/§7.8)。
103
+ const hostProfile = detectHostProfile(internal, baseUrl);
104
+ if (hostProfile === 'desktop') {
105
+ throw new Error(`dsh-plugin-reverse-proxy: desktop profile not supported; disable or uninstall the plugin (${DESKTOP_HOST_PACKAGE} present)`);
106
+ }
107
+ const versions = [];
108
+ for (const anchorPackage of GATE_ANCHOR_PACKAGES) {
109
+ const specifier = `${anchorPackage}/package.json`;
110
+ const resolved = internal.version === 'v2'
111
+ ? internal.resolveSync(baseUrl, { specifier, attributes: {} })
112
+ : internal.resolveSync(specifier, baseUrl, {});
113
+ const manifestUrl = resolved?.url;
114
+ if (typeof manifestUrl !== 'string') {
115
+ throw new Error(`dsh-plugin-reverse-proxy: gate anchor ${anchorPackage} did not resolve; whitelist is ${WHITELIST_TEXT}; disable or uninstall the plugin`);
116
+ }
117
+ const manifest = JSON.parse(readFileSync(fileURLToPath(manifestUrl), 'utf8'));
118
+ if (typeof manifest.version !== 'string') {
119
+ throw new Error(`dsh-plugin-reverse-proxy: gate anchor ${anchorPackage} manifest has no version, whitelist is ${WHITELIST_TEXT}; disable or uninstall the plugin`);
120
+ }
121
+ versions.push(manifest.version);
122
+ }
123
+ const profile = resolveActiveCompatibilityProfile(versions[0], versions[1], hostProfile);
124
+ if (profile === undefined) {
125
+ throw new Error(`dsh-plugin-reverse-proxy: gate anchors ${GATE_ANCHOR_PACKAGES[0]}=${String(versions[0])}, ${GATE_ANCHOR_PACKAGES[1]}=${String(versions[1])} do not resolve to one active compatibility profile; whitelist is ${WHITELIST_TEXT}; disable or uninstall the plugin`);
126
+ }
127
+ if (requestedProfile !== undefined && requestedProfile !== profile.id) {
128
+ throw new Error(`dsh-plugin-reverse-proxy: compatibility profile mismatch: patch selected ${String(requestedProfile)}, anchors selected ${profile.id}; refusing to run`);
129
+ }
130
+ const official = current.parent.tree.resolve('connection');
131
+ if (official.parent !== current.parent
132
+ || official.options?.id !== 'connection'
133
+ || official.options?.name !== CONNECTION_PACKAGE
134
+ || official.disabled !== true
135
+ || official.fiber !== undefined) {
136
+ throw new Error('dsh-plugin-reverse-proxy: gate binding violated; refusing to run');
137
+ }
138
+ return profile;
139
+ }
140
+ function installBrowserGlobals(ctx, profile) {
141
+ ctx.inject(['webServer'], (webCtx) => {
142
+ const carrier = webCtx;
143
+ if (typeof carrier.on !== 'function')
144
+ return;
145
+ carrier.on('webserver/index-inject', (table) => {
146
+ table.push({ kind: 'global', name: PROFILE_GLOBAL, value: profile.id });
147
+ if (profile.requiresRecoveryGlobal) {
148
+ table.push({ kind: 'global', name: RECOVERY_GLOBAL, value: {} });
149
+ }
150
+ });
151
+ });
152
+ }
153
+ function createHostRuntime(profile, input) {
154
+ switch (profile.hostAdapter) {
155
+ case 'legacy-web':
156
+ return createLegacyWebRuntime(input);
157
+ case 'carrier-neutral':
158
+ return createCarrierNeutralRuntime(input);
159
+ case 'carrier-neutral-017':
160
+ return createCarrierNeutral017Runtime(input);
161
+ case 'carrier-neutral-021':
162
+ return createCarrierNeutral021Runtime(input);
163
+ default:
164
+ throw new Error('dsh-plugin-reverse-proxy: unsupported host adapter');
165
+ }
166
+ }
167
+ /**
168
+ * Mounts the trusted-network Connection replacement under the profile's Web
169
+ * carrier. Every request passes the Host/Origin browser-trust fence; no
170
+ * identity layer exists beyond it.
171
+ */
172
+ export async function apply(ctx, config) {
173
+ // 宿主形态判别最前置(0.3.12,运行时权威休眠):desktop ⇒ 静默休眠,无条件
174
+ // 先于一切配置校验与副作用。背景:用户层 patch 可按行 id 合法覆盖本插件
175
+ // patch 的 !!js disabled 表达式(dsh-m 插件开关 / `dsh plugin add` enable
176
+ // 通道的标准产物,2026-10-11 实录),组合期门控因此不承担语义;apply 内判定
177
+ // 是唯一权威。§7.4 教训(任何半区的 throw 都可能炸宿主):休眠路径零 throw、
178
+ // 零副作用,仅留一行可 grep 的通知;「激活需要正向 web 证明」的 default-deny
179
+ // 语义不变。resolver 缺失不阻碍判别(信号①自行消化 undefined)。
180
+ const earlyLoader = ctx.get('loader');
181
+ const earlyBaseUrl = ctx.baseUrl ?? '';
182
+ if (detectHostProfile(earlyLoader?.internal, earlyBaseUrl) === 'desktop') {
183
+ console.warn(DESKTOP_DORMANT_NOTICE);
184
+ return;
185
+ }
186
+ const trustedHosts = config?.trustedHosts ?? [];
187
+ const maxRequestBodyBytes = config?.maxRequestBodyBytes ?? DEFAULT_MAX_REQUEST_BODY_BYTES;
188
+ for (const entry of trustedHosts)
189
+ assertTrustedAuthority(entry);
190
+ assertImageBodyCapacity(ctx, maxRequestBodyBytes);
191
+ const profile = assertGateBackstop(ctx, config?.compatibilityProfile) ?? directProfile(config?.compatibilityProfile);
192
+ const module = await loadRuntimeConnectionModule(ctx);
193
+ const auth = createTrustedAuth(trustedHosts, profile.browserAuthSemantics);
194
+ const runtime = createHostRuntime(profile, {
195
+ ctx,
196
+ module,
197
+ trustedHosts,
198
+ auth,
199
+ maxRequestBodyBytes,
200
+ profileId: profile.id,
201
+ });
202
+ ctx.effect(() => ctx.webServer.register(runtime.route), `dsh-plugin-reverse-proxy: ${runtime.adapterId} ${runtime.route.path} route`);
203
+ // 代际附加路由(官方 apply 注册顺序照抄):0.2.1 的 /connect exact 通道。
204
+ for (const additionalRoute of runtime.additionalRoutes ?? []) {
205
+ ctx.effect(() => ctx.webServer.register(additionalRoute), `dsh-plugin-reverse-proxy: ${runtime.adapterId} ${additionalRoute.path} route`);
206
+ }
207
+ installBrowserGlobals(ctx, profile);
208
+ ctx.inject(['attachments'], (attachmentCtx) => {
209
+ assertImageBodyCapacity(attachmentCtx, maxRequestBodyBytes);
210
+ });
211
+ console.warn(SKIP_WARNING);
212
+ }
@@ -0,0 +1,141 @@
1
+ /**
2
+ * 多窗口共存:每个标签页自己的身份 ⇒ 每个标签页自己的 Peer。
3
+ *
4
+ * 官方 ConnectionService 的身份模型是「一个浏览器 cookie = 一个 Peer」:同一
5
+ * 浏览器的所有标签共享 cookie,于是第二块窗口和第一块抢同一个 Peer;而官方一个
6
+ * Peer 只认一条事件流(能回答 waterfall 的那条),第二块窗口的首屏请求等不到
7
+ * 回答,就一直转圈。
8
+ *
9
+ * 免 Token 模式更麻烦一层:官方 `admit()` 里 `isAuthenticated()` 恒真,于是所有
10
+ * 普通请求都直接落到共享的 `browserPeer`;事件流(waterfall)要求「回答来自持有
11
+ * 该流的同一份 Peer」,browserPeer 手上没有 socket,请求就永远没人应答。
12
+ *
13
+ * 所以这里同时接管两处:
14
+ * · `admit(request)` —— 带标签身份的请求发给该标签的 Peer(普通请求与事件流同一份);
15
+ * · `admitConnection(req)`—— mux 建立时把 socket 挂到该标签的 Peer 上,引用计数归零才回收。
16
+ * 认不到标签 id 时完全退回官方行为。
17
+ */
18
+
19
+ const TAB_HEADER = 'x-dsh-tab'
20
+ const TAB_QUERY = 'tab'
21
+ const TAB_PATTERN = /^[A-Za-z0-9._-]{8,64}$/
22
+
23
+ /** 从请求里认领标签 id:优先请求头,其次 mux URL 的 ?tab=。 */
24
+ function tabIdOf(request) {
25
+ try {
26
+ const header = request?.headers?.[TAB_HEADER]
27
+ const value = Array.isArray(header) ? header[0] : header
28
+ if (typeof value === 'string' && TAB_PATTERN.test(value)) return value
29
+ const url = new URL(request?.url ?? '/', 'http://dsh.invalid')
30
+ const query = url.searchParams.get(TAB_QUERY)
31
+ if (typeof query === 'string' && TAB_PATTERN.test(query)) return query
32
+ }
33
+ catch {
34
+ // 请求形态异常一律当作「没有标签身份」,走官方路径
35
+ }
36
+ return undefined
37
+ }
38
+
39
+ function pathOf(request) {
40
+ try { return new URL(request?.url ?? '/', 'http://dsh.invalid').pathname }
41
+ catch { return '?' }
42
+ }
43
+
44
+ /**
45
+ * 在 ConnectionService 实例上安装 per-tab Peer 行为。
46
+ * @param connection - 官方 HostConnectionService 实例(已由适配器创建)
47
+ * @returns 是否安装成功
48
+ */
49
+ export function installPerSocketPeers(connection) {
50
+ const peers = connection.peers
51
+ const publishPeer = connection.publishPeer
52
+ if (!(peers instanceof Map) || typeof publishPeer !== 'function') return false
53
+ if (typeof connection.admit !== 'function' || typeof connection.admitConnection !== 'function') return false
54
+
55
+ const originalAdmit = connection.admit.bind(connection)
56
+ const originalAdmitConnection = connection.admitConnection.bind(connection)
57
+
58
+ /** tab → { record, sockets } ;sockets 是该标签当前挂着的 mux 数。 */
59
+ const tabs = new Map()
60
+ const seen = new Map()
61
+ const logOnce = (key, line) => {
62
+ const bucket = Math.floor(Date.now() / 60000)
63
+ const k = `${key}:${bucket}`
64
+ if (seen.has(k)) return
65
+ seen.set(k, true)
66
+ if (seen.size > 400) seen.clear()
67
+ console.log(line)
68
+ }
69
+
70
+ function mint(key, interactions) {
71
+ const id = publishPeer.call(connection, interactions ?? 'answer')
72
+ const record = peers.get(id)
73
+ if (record === undefined) return undefined
74
+ if (key !== id) {
75
+ peers.delete(id)
76
+ peers.set(key, record)
77
+ }
78
+ // 让 record 自己知道它挂在哪个 key 下,回收时才能找到自己
79
+ record.__reproxyKey = key
80
+ return record
81
+ }
82
+
83
+ function ensure(tab) {
84
+ let entry = tabs.get(tab)
85
+ if (entry !== undefined && entry.record?.peer !== undefined) return entry
86
+ const record = mint(tab, 'answer')
87
+ if (record === undefined) return undefined
88
+ entry = { record, sockets: 0 }
89
+ tabs.set(tab, entry)
90
+ return entry
91
+ }
92
+
93
+ // ① 普通请求:官方在免 Token 模式下把所有人都塞给 browserPeer,
94
+ // 这里先把标签认出来,再交给该标签自己的 Peer。
95
+ connection.admit = function admitPerTab(request) {
96
+ const base = originalAdmit(request)
97
+ if (base !== undefined && base !== null && 'rejection' in base) return base
98
+ const tab = tabIdOf(request)
99
+ if (tab === undefined) return base
100
+ const entry = ensure(tab)
101
+ if (entry === undefined) return base
102
+ logOnce(`http:${tab}`, `[reproxy-lan] http tab ${tab.slice(0, 8)} ${pathOf(request)}`)
103
+ return { peer: entry.record.peer }
104
+ }
105
+
106
+ // ② mux:socket 挂到同一份 Peer 上,引用计数归零才 dispose。
107
+ connection.admitConnection = function admitConnectionPerTab(request) {
108
+ const tab = tabIdOf(request)
109
+ if (tab === undefined) return originalAdmitConnection(request)
110
+ const base = originalAdmit(request)
111
+ if (base !== undefined && base !== null && 'rejection' in base) {
112
+ logOnce(`muxrej:${tab}`, `[reproxy-lan] mux 被拒 ${tab.slice(0, 8)} → ${base.rejection}`)
113
+ return base
114
+ }
115
+ const entry = ensure(tab)
116
+ if (entry === undefined) return originalAdmitConnection(request)
117
+ entry.sockets += 1
118
+ entry.record.ownsSocket = true
119
+ let released
120
+ console.log('[reproxy-lan] mux admit', tab.slice(0, 8), '| 该标签 socket 数:', entry.sockets, '| 活跃 Peer:', peers.size)
121
+ return {
122
+ peer: entry.record.peer,
123
+ release: () => {
124
+ if (released !== undefined) return released
125
+ entry.sockets = Math.max(0, entry.sockets - 1)
126
+ let disposed
127
+ if (entry.sockets === 0) {
128
+ if (peers.get(tab) === entry.record) peers.delete(tab)
129
+ else if (entry.record.peer !== undefined && peers.get(entry.record.peer.id) === entry.record) peers.delete(entry.record.peer.id)
130
+ tabs.delete(tab)
131
+ disposed = entry.record.peer.dispose()
132
+ }
133
+ else disposed = Promise.resolve()
134
+ console.log('[reproxy-lan] mux release', tab.slice(0, 8), '| 该标签 socket 数:', entry.sockets, '| 剩余 Peer:', peers.size)
135
+ released = disposed
136
+ return released
137
+ },
138
+ }
139
+ }
140
+ return true
141
+ }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Browser-trust fence for every /api request. Defends the two confused-deputy
3
+ * paths a browser opens against a local HTTP API — DNS rebinding (Host names
4
+ * the attacker's domain while the socket reaches this server) and cross-site
5
+ * requests fired from a malicious page. The Host fence binds every request,
6
+ * browser-looking or not: over plain HTTP a browser attaches neither Origin
7
+ * nor Fetch-Metadata to reads (images and navigations — those
8
+ * headers go only to trustworthy destinations), so an unmarked request may
9
+ * still be a rebound browser read and Host is the one header rebinding cannot
10
+ * forge. Non-browser and remote clients pass the same fence via loopback,
11
+ * deployment-derived LAN IP literals, or a declared `trustedHosts` authority.
12
+ * Network reachability and authentication stay out of scope: binding policy
13
+ * belongs to the webserver config, and this fence is not an auth layer.
14
+ *
15
+ * 移植自官方 packages/client/connection/src/api-request-trust.ts(rc.1),
16
+ * 语义照抄;isLoopbackHostname 与 ConnectionTrustRequest 类型就地局部化。
17
+ */
18
+ /**
19
+ * Whether a normalized URL hostname names the local loopback authority.
20
+ * @param hostname - WHATWG URL hostname (IPv6 literals retain brackets).
21
+ * @returns true for localhost, IPv6 loopback, or any IPv4 address in 127/8.
22
+ */
23
+ function isLoopbackHostname(hostname) {
24
+ if (hostname === 'localhost' || hostname === '[::1]')
25
+ return true;
26
+ const parts = hostname.split('.');
27
+ return parts.length === 4
28
+ && parts[0] === '127'
29
+ && parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255);
30
+ }
31
+ function header(headers, name) {
32
+ if (headers instanceof Headers)
33
+ return headers.get(name) ?? undefined;
34
+ const value = headers[name];
35
+ return typeof value === 'string' ? value : undefined;
36
+ }
37
+ /** Normalized URL of a Host-header authority (hostname lowercased, default port stripped, IPv6 bracketed), or undefined when unparsable. */
38
+ function parseAuthority(authority) {
39
+ try {
40
+ // http: is a WHATWG "special scheme": parsing yields a non-empty hostname or throws.
41
+ return new URL(`http://${authority}`);
42
+ }
43
+ catch {
44
+ return undefined;
45
+ }
46
+ }
47
+ /**
48
+ * Assert one configured `trustedHosts` entry is a bare authority (`host` or
49
+ * `host:port`) in canonical form: it must survive WHATWG parsing unchanged
50
+ * (case aside). Anything parsing would silently rewrite is refused as a typo
51
+ * that must fail the load loudly instead of being ignored until requests 403
52
+ * or quietly changing the grant: URL parts beyond the authority
53
+ * (`harness.internal/path`, `user@harness.internal` — which would authorize
54
+ * the embedded hostname), stripped whitespace, a dangling colon or
55
+ * zero-padded port (which would broaden an intended exact-port grant to every
56
+ * port), and non-canonical host spellings (`0x7f.0.0.1`, percent-encoding,
57
+ * unbracketed IPv6; IDN hosts are declared in punycode, the form the wire
58
+ * carries).
59
+ * @param entry - the configured value, verbatim.
60
+ */
61
+ export function assertTrustedAuthority(entry) {
62
+ const entryUrl = parseAuthority(entry);
63
+ if (entryUrl !== undefined && canonicalAuthority(entry, entryUrl) === entry.toLowerCase())
64
+ return;
65
+ throw new Error(`dsh-plugin-reverse-proxy: trustedHosts entry ${JSON.stringify(entry)} is not a bare host[:port] authority`);
66
+ }
67
+ /**
68
+ * Canonical form of a parsed authority: `hostname` when no port was written,
69
+ * else `hostname:port`. The port is judged from URL parses under both special
70
+ * schemes (their default ports differ, so `:80` and `:443` still count as
71
+ * explicit), never from the raw string, where WHATWG trimming would misread
72
+ * shapes like `host:port ` as port-less.
73
+ */
74
+ function canonicalAuthority(entry, entryUrl) {
75
+ // An authority that parsed under http cannot fail under https.
76
+ const port = entryUrl.port !== '' ? entryUrl.port : new URL(`https://${entry}`).port;
77
+ return port === '' ? entryUrl.hostname : `${entryUrl.hostname}:${port}`;
78
+ }
79
+ /**
80
+ * Whether the request authority matches a `trustedHosts` entry. An entry with
81
+ * an explicit port matches that exact authority; a port-less entry matches the
82
+ * hostname on any port (the shape the CLI derives for IP-literal LAN serving,
83
+ * where the bound port may be OS-assigned). Both sides compare through WHATWG
84
+ * normalization, so case and a redundant `:80` never decide trust.
85
+ */
86
+ function isTrustedAuthority(hostUrl, trustedHosts) {
87
+ return trustedHosts.some((entry) => {
88
+ const entryUrl = parseAuthority(entry);
89
+ if (entryUrl === undefined)
90
+ return false;
91
+ return canonicalAuthority(entry, entryUrl) === entryUrl.hostname
92
+ ? entryUrl.hostname === hostUrl.hostname
93
+ : entryUrl.host === hostUrl.host;
94
+ });
95
+ }
96
+ /**
97
+ * Decide whether one /api request may reach the RPC bridge.
98
+ * @param request - Node HTTP or Fetch request facts (headers).
99
+ * @param trustedHosts - non-loopback authorities this deployment serves: exact `host:port`, or port-less `host` matching any port.
100
+ * @returns true when the Host is ours (loopback or trusted) and any attached browser markers are same-origin.
101
+ */
102
+ export function isTrustedApiRequest(request, trustedHosts) {
103
+ // Host fence (DNS-rebinding defense), applied to every request: the browser
104
+ // fills Host from the URL it believes it is talking to, so a rebound page
105
+ // carries the attacker's domain here even though the socket lands on this
106
+ // server. There is no marker shortcut — a browser read over plain HTTP
107
+ // (images and navigations) arrives with neither Origin nor
108
+ // Fetch-Metadata, indistinguishable from curl, and its response is readable
109
+ // by the rebound page.
110
+ const host = header(request.headers, 'host');
111
+ if (host === undefined)
112
+ return false;
113
+ const hostUrl = parseAuthority(host);
114
+ if (hostUrl === undefined)
115
+ return false;
116
+ if (!isLoopbackHostname(hostUrl.hostname) && !isTrustedAuthority(hostUrl, trustedHosts))
117
+ return false;
118
+ // Cross-site fence: modern browsers label the initiator relationship on
119
+ // every fetch; an explicit cross-site marker is refused regardless of Origin.
120
+ if (header(request.headers, 'sec-fetch-site') === 'cross-site')
121
+ return false;
122
+ // Origin fence: when a browser attaches an Origin it must be exactly this
123
+ // authority (compared through the same normalization as the Host). Absent
124
+ // Origin is fine — the Host fence above already bound the request. The
125
+ // literal "null" (sandboxed iframes, file: pages) is an opaque origin, refused.
126
+ const origin = header(request.headers, 'origin');
127
+ if (origin === undefined)
128
+ return true;
129
+ try {
130
+ return new URL(origin).host === hostUrl.host;
131
+ }
132
+ catch {
133
+ return false;
134
+ }
135
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Trusted-network replacement for the official BrowserAuth stub.
3
+ *
4
+ * 官方 HostConnectionService 对认证的全部依赖(0.2.1 起)只有四个方法:
5
+ * isAuthenticated / authorizeIndex / authenticatedUrl / authorizeConnect。
6
+ * 本模块以 trusted-network 语义提供四方法 stub:请求信任栅栏(Host/Origin/
7
+ * Fetch Metadata/trustedHosts)承担全部访问判定,身份层不存在。
8
+ * 首页 fence 与 /api fence 消费同一个 trustedHosts 列表。
9
+ */
10
+ import { isTrustedApiRequest } from './trust-fence.js';
11
+ const TOKEN_QUERY = 'token';
12
+ /**
13
+ * Create the three-method stub consumed by the official HostConnectionService.
14
+ * @param trustedHosts - non-loopback authorities this deployment serves: exact `host:port`, or port-less `host` matching any port.
15
+ * @param semantics - the host generation's BrowserAuth URL contract: `root`
16
+ * (0.1.2/0.1.5, app at `/`) or `mount-preserving` (0.1.7, app may mount at a
17
+ * sub-path). Selected by the compatibility profile, never guessed.
18
+ * @returns authentication owner with trusted-network semantics for all three methods.
19
+ */
20
+ export function createTrustedAuth(trustedHosts, semantics = 'root') {
21
+ // mount-preserving:官方 0.1.7 的清理重定向目标是目录相对 `./`,
22
+ // 应用可以挂在子路径上;root:官方 0.1.2/0.1.5 一律回到 `/`。
23
+ const cleanLocation = semantics === 'mount-preserving' ? './' : '/';
24
+ return {
25
+ // 请求已通过 /api 侧的 requestRejection/admit 信任栅栏;此处恒真,
26
+ // 使官方 service 不再叠加 401 身份层。
27
+ isAuthenticated(_request) {
28
+ return true;
29
+ },
30
+ // 首页请求先过与 /api 相同的信任栅栏(不可信 → 403);
31
+ // 可信的 GET / 带 token 时以 303 清理 URL(无身份层,无需交换 cookie),
32
+ // 其余可信请求直接放行交付 index.html。
33
+ authorizeIndex(req, res) {
34
+ if (!isTrustedApiRequest(req, trustedHosts)) {
35
+ res.writeHead(403, {
36
+ 'cache-control': 'no-store',
37
+ 'content-type': 'text/plain; charset=utf-8',
38
+ });
39
+ res.end(req.method === 'HEAD' ? undefined : 'forbidden\n');
40
+ return false;
41
+ }
42
+ const url = new URL(req.url ?? '/', 'http://dsh.invalid');
43
+ if (url.searchParams.has(TOKEN_QUERY) && req.method === 'GET' && url.pathname === '/') {
44
+ res.writeHead(303, {
45
+ 'cache-control': 'no-store',
46
+ 'location': cleanLocation,
47
+ 'referrer-policy': 'no-referrer',
48
+ });
49
+ res.end();
50
+ return false;
51
+ }
52
+ return true;
53
+ },
54
+ // 无身份层:返回干净的应用 URL,不附加任何 token。
55
+ // root:官方 0.1.2/0.1.5 语义,重写到应用根 `/`;
56
+ // mount-preserving:官方 0.1.7 语义,保留调用方的 mount,仅去掉 query/hash。
57
+ authenticatedUrl(baseUrl) {
58
+ const url = new URL(baseUrl);
59
+ if (semantics !== 'mount-preserving')
60
+ url.pathname = '/';
61
+ url.search = '';
62
+ url.hash = '';
63
+ return url.href;
64
+ },
65
+ // 0.2.1 /connect 交换(trusted-network 语义):
66
+ // - interactions 声明校验逐字对齐官方(客户端协议契约,400 兜底);
67
+ // - 官方成功路径 = mint operator cookie + 302 ./api/remote.mux;本 stub
68
+ // 省略 cookie 与 operator 记录(无身份可铸造;publish 不调用,避免
69
+ // 生成无 cookie 引用的孤儿 operator 台账),其余响应形态逐字对齐。
70
+ // 后续 /api 请求由 admit() 恒准为 owner-principal browserPeer,mux
71
+ // 连接不依赖该 cookie。
72
+ // - 服务层已在 authorizeConnect 入口做过 isTrusted(evil host ⇒ 403,
73
+ // 不达本 stub);身份/token 校验路径在本模式恒通过(isAuthenticated
74
+ // 恒真),token 缺失不再 401。
75
+ authorizeConnect(req, res, _secure, _publish) {
76
+ const url = new URL(req.url ?? '/', 'http://dsh.invalid');
77
+ const declarations = url.searchParams.getAll('interactions');
78
+ const interactions = declarations[0] ?? 'none';
79
+ if (declarations.length > 1 || (interactions !== 'answer' && interactions !== 'none')) {
80
+ res.writeHead(400, {
81
+ 'cache-control': 'no-store',
82
+ 'content-type': 'text/plain; charset=utf-8',
83
+ });
84
+ res.end('interactions must be declared once as answer or none\n');
85
+ return;
86
+ }
87
+ res.writeHead(302, {
88
+ 'cache-control': 'no-store',
89
+ 'location': './api/remote.mux',
90
+ 'referrer-policy': 'no-referrer',
91
+ });
92
+ res.end();
93
+ },
94
+ };
95
+ }