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,223 @@
1
+ /**
2
+ * Compatibility generations for the DSH BrowserAuth replacement.
3
+ *
4
+ * A profile is the unit of compatibility: a complete runtime/connection
5
+ * version pair plus the host/client implementation generation that knows how
6
+ * to serve it. Do not replace this table with independent version `includes`
7
+ * checks: a runtime from one generation and a connection package from another
8
+ * generation must never activate together.
9
+ */
10
+ export const COMPATIBILITY_PROFILES = [
11
+ {
12
+ id: 'legacy-web-v1',
13
+ pairs: [{ runtime: '0.1.2-rc.1', connection: '0.1.2-rc.1' }],
14
+ hostAdapter: 'legacy-web',
15
+ clientVariant: 'rc12',
16
+ requiresRecoveryGlobal: false,
17
+ browserAuthSemantics: 'root',
18
+ hostProfiles: ['web'],
19
+ status: 'active',
20
+ },
21
+ {
22
+ id: 'carrier-neutral-v2',
23
+ // 0.1.5-rc.2 joined this generation after a byte-level audit: every anchor
24
+ // package the gate probes (@deepseek-ai/dsh, dsh-client-connection,
25
+ // dsh-host-webserver, dsh-web-app) ships rc.1-identical code and only bumps
26
+ // manifest versions/dependency ranges. See docs/COMPATIBILITY.md §6.
27
+ pairs: [
28
+ { runtime: '0.1.5-rc.1', connection: '0.1.5-rc.1' },
29
+ { runtime: '0.1.5-rc.2', connection: '0.1.5-rc.2' },
30
+ ],
31
+ hostAdapter: 'carrier-neutral',
32
+ clientVariant: 'rc15',
33
+ requiresRecoveryGlobal: true,
34
+ browserAuthSemantics: 'root',
35
+ hostProfiles: ['web'],
36
+ // Promoted after the carrier-neutral host/client adapter and fixture path
37
+ // are implemented; real deployment validation remains documented separately.
38
+ status: 'active',
39
+ },
40
+ {
41
+ // 0.1.7 is a real contract change from 0.1.5, not a republish: the shared /api
42
+ // route admits through the new OperatorPeer (`admit()`) and wraps the
43
+ // bridge in the `connection/request` waterfall; BrowserAuth consumption
44
+ // becomes mount-preserving; the browser client bundle is rewritten. Audited
45
+ // package-by-package in docs/COMPATIBILITY.md §5.4.
46
+ //
47
+ // 0.1.7-rc.1 joined this generation after a byte-level audit (§5.5): every
48
+ // package the replacement touches (dsh-client-connection lib/+client/,
49
+ // dsh-host-webserver, dsh-scope, dsh-host-frontend-static) ships rc.2-identical
50
+ // code, the web-app patch's connection row is field-identical, and the runtime
51
+ // diff is chunk-hash renames plus diagnostics-only boot changes. The rc17
52
+ // client variant therefore serves both pairs, selected by this one profile id.
53
+ //
54
+ // 0.2.0-rc.1 joined for the same reason (§5.6): despite the minor bump it is
55
+ // a dependency-alignment republish on every surface the replacement probes
56
+ // or serves — lib/+client/ byte-identical in all anchor packages, the
57
+ // official patch's connection row field-identical, and the only code diffs
58
+ // (dsh-app-boot OPTIONAL_BUNDLES, web-app patch telemetry/schedule rows)
59
+ // never intersect the connection contract. No second 0.1.x-line build input
60
+ // is introduced: the rc17 client variant keeps anchoring at 0.1.7-rc.2.
61
+ //
62
+ // 0.2.0-rc.2 joined for the same reason (§5.7): another dependency-alignment
63
+ // republish on the contract face — lib/+client/ byte-identical in all anchor
64
+ // packages (web-app's whole diff is package.json, so cordis.patch.yml and its
65
+ // connection row are byte-identical too) — plus unrelated Desktop-only
66
+ // plugin-management CLI changes in the runtime (bin.js, lib/types/*.d.ts) and
67
+ // a ModuleLoader chunk-hash rename whose 34 changed lines all sit in that CLI
68
+ // area with resolveSync usage line-identical. rc17 keeps anchoring at
69
+ // 0.1.7-rc.2; no second 0.2.x-line build input is introduced.
70
+ //
71
+ // 0.2.1-rc.1 does NOT join this generation (§5.8): unlike every rc.2-style
72
+ // republish it is a real contract change on the replacement face —
73
+ // OperatorPeer reworked into per-request Peer instances with principals,
74
+ // the shared-route bridge threading admission.peer into fetch, a new
75
+ // /connect exact channel (authorizeConnect), the client bundle split into
76
+ // browser/node entries, and the official patch's connection row moving
77
+ // from the webRuntime to the webStartup service. It therefore starts the
78
+ // carrier-neutral-v4 generation below (docs/COMPATIBILITY.md §5.2/§5.9).
79
+ id: 'carrier-neutral-v3',
80
+ pairs: [
81
+ { runtime: '0.1.7-rc.1', connection: '0.1.7-rc.1' },
82
+ { runtime: '0.1.7-rc.2', connection: '0.1.7-rc.2' },
83
+ { runtime: '0.2.0-rc.1', connection: '0.2.0-rc.1' },
84
+ { runtime: '0.2.0-rc.2', connection: '0.2.0-rc.2' },
85
+ ],
86
+ hostAdapter: 'carrier-neutral-017',
87
+ clientVariant: 'rc17',
88
+ requiresRecoveryGlobal: true,
89
+ browserAuthSemantics: 'mount-preserving',
90
+ hostProfiles: ['web'],
91
+ // Promoted together with the adapter/client implementation; the fixture
92
+ // composition suite and the real 0.1.7-rc.2 deployment checklist are the
93
+ // promotion evidence (docs/COMPATIBILITY.md §5.4, docs/DESIGN.md).
94
+ status: 'active',
95
+ },
96
+ {
97
+ // 0.2.1-rc.1 starts its own generation (§5.8 audit → §5.2 new generation):
98
+ // the official apply wiring it must replicate is admit() → waterfall →
99
+ // bridge(req, res, fetchHandler, admission.peer, maxRequestBodyBytes) plus
100
+ // the new exact /connect route (connection.authorizeConnect). The
101
+ // HostConnectionService constructor (ctx, trustedHosts, browserAuth) is
102
+ // unchanged, but the patch row serving this generation reads trustedHosts
103
+ // from the webStartup service (webRuntime is gone upstream; the official
104
+ // 0.2.1 patch row made the same move and narrows trustedHosts to the
105
+ // explicit invocation authorities). The rc21 client variant anchors at the
106
+ // official browser entry lib/client.browser.js of 0.2.1-rc.1 — no other
107
+ // generation shares this build input.
108
+ //
109
+ // 0.2.1-rc.2 joined this generation after a tarball audit (§5.10): another
110
+ // rc.2-style republish on the contract face — connection/webserver/scope/
111
+ // frontend-static/app-boot/runtime ship manifest-only bumps, invariants
112
+ // remains unpublished on both sides, and web-app's whole patch diff is one
113
+ // ADDED row (ui-deepseek-model-label-1017) with the connection row
114
+ // field-identical. rc21 keeps anchoring at 0.2.1-rc.1; no second 0.2.1-line
115
+ // build input is introduced.
116
+ //
117
+ // 0.2.1-rc.3 joined this generation after a tarball audit (§5.11): another
118
+ // rc.2-style republish on the contract face — connection/webserver/scope/
119
+ // frontend-static/app-boot/runtime ship manifest-only bumps, invariants
120
+ // remains unpublished on both sides, and web-app's whole patch diff is one
121
+ // ADDED row (entry-customization) with the connection row field-identical
122
+ // and presets/ byte-identical. rc21 keeps anchoring at 0.2.1-rc.1; no
123
+ // second 0.2.1-line build input is introduced.
124
+ //
125
+ // 0.2.1-rc.4 joined this generation after a tarball audit (§5.12): a pure
126
+ // rc.2-style republish on the contract face — every anchor package
127
+ // (connection/webserver/scope/frontend-static/app-boot/web-app/runtime)
128
+ // ships manifest-only bumps, invariants remains unpublished on both sides,
129
+ // and web-app's patch diff is empty for the first time in the 0.2.1 line
130
+ // (no ADDED rows at all, connection row field-identical). rc21 keeps
131
+ // anchoring at 0.2.1-rc.1; no second 0.2.1-line build input is introduced.
132
+ //
133
+ // 0.2.1-rc.5 joined this generation after a tarball audit (§5.13): another
134
+ // pure rc.2-style republish on the contract face — every anchor package
135
+ // (connection/webserver/scope/frontend-static/app-boot/web-app/runtime)
136
+ // ships manifest-only bumps, invariants remains unpublished on both sides,
137
+ // and web-app's patch diff stays empty for a second consecutive round
138
+ // (connection row field-identical). rc21 keeps anchoring at 0.2.1-rc.1;
139
+ // no second 0.2.1-line build input is introduced.
140
+ //
141
+ // 0.2.2-rc.1 joined this generation after a per-dimension tarball audit
142
+ // (§5.14): the mechanical grader returned CONTRACT-CHANGED (unpaired locale
143
+ // files plus real webserver/frontend-static/app-boot diffs), but every
144
+ // §5.1 admission condition holds on the replacement face — connection
145
+ // lib/index.js and lib/client.browser.js are byte-identical (client types
146
+ // add an optional resolveAsset? only), the official patch's connection row
147
+ // is field-identical, and the surrounding diffs are additive or
148
+ // internal-only: the webserver keeps handler-route dispatch line-identical
149
+ // (resource routes are a new parallel path), frontend-static still drives
150
+ // the same authorizeIndex(request, res-shim) truthy/falsy contract against
151
+ // the official browserPeer the replacement instantiates, app-boot's new
152
+ // dsh.bundle.platforms field is optional (omission allows every platform),
153
+ // and the runtime diff is chunk-hash renames with the loader resolveSync
154
+ // seam line-identical. The real 0.2.2-rc.1 fixture composition exercises
155
+ // the new webserver/frontend-static packages directly (§5.14 item 5).
156
+ //
157
+ // 0.2.2-rc.2 and 0.2.2-rc.3 joined this generation after a per-dimension
158
+ // tarball audit (§5.15): both are republish-grade bumps on the
159
+ // replacement face. connection lib/index.js and lib/client.node.js are
160
+ // byte-identical to rc.1 and to each other; the bundled browser client
161
+ // differs only by minification (same 78 function names, same declaration
162
+ // order, byte-identical package bytes for rc.2 vs rc.3) while keeping the
163
+ // same module id, the same five exports (apply / inject /
164
+ // installConnection / RpcId / transportError) and the same
165
+ // __DSH_TRANSPORT__ / __DSH_CONNECTION_RECOVERY__ globals. The official
166
+ // patch's connection row stays field-identical (same id, same
167
+ // @deepseek-ai/dsh-client-connection, inject [webStartup], trustedHosts
168
+ // !!js ctx.webStartup.trustedHosts), and dsh-host-webserver /
169
+ // dsh-web-app ship no non-map, non-manifest change against rc.2/rc.3.
170
+ // rc21 keeps anchoring at 0.2.1-rc.1; no second build input is introduced.
171
+ id: 'carrier-neutral-v4',
172
+ pairs: [
173
+ { runtime: '0.2.1-rc.1', connection: '0.2.1-rc.1' },
174
+ { runtime: '0.2.1-rc.2', connection: '0.2.1-rc.2' },
175
+ { runtime: '0.2.1-rc.3', connection: '0.2.1-rc.3' },
176
+ { runtime: '0.2.1-rc.4', connection: '0.2.1-rc.4' },
177
+ { runtime: '0.2.1-rc.5', connection: '0.2.1-rc.5' },
178
+ { runtime: '0.2.2-rc.1', connection: '0.2.2-rc.1' },
179
+ { runtime: '0.2.2-rc.2', connection: '0.2.2-rc.2' },
180
+ { runtime: '0.2.2-rc.3', connection: '0.2.2-rc.3' },
181
+ ],
182
+ hostAdapter: 'carrier-neutral-021',
183
+ clientVariant: 'rc21',
184
+ requiresRecoveryGlobal: true,
185
+ browserAuthSemantics: 'mount-preserving',
186
+ hostProfiles: ['web'],
187
+ status: 'active',
188
+ },
189
+ ];
190
+ /**
191
+ * The §5.9 generation id: the only profile whose bundle patch row injects the
192
+ * `webStartup` service (upstream renamed webRuntime → webStartup in 0.2.1).
193
+ * The row-binding expressions in gate.ts partition the active profile ids by
194
+ * this constant so exactly one inserted row can activate per host generation.
195
+ */
196
+ export const CARRIER_NEUTRAL_V4_PROFILE_ID = 'carrier-neutral-v4';
197
+ /** All exact versions represented by profiles, for diagnostics and fixtures. */
198
+ export const GATE_VERSIONS = [...new Set(COMPATIBILITY_PROFILES.flatMap((profile) => profile.pairs.flatMap((pair) => [pair.runtime, pair.connection])))];
199
+ /** Backward-compatible internal alias for the original 0.1.2 build/test pin. */
200
+ export const GATE_VERSION = GATE_VERSIONS[0];
201
+ /** Profile ids whose host/client implementations are currently safe to activate. */
202
+ export const ACTIVE_COMPATIBILITY_PROFILE_IDS = COMPATIBILITY_PROFILES
203
+ .filter((profile) => profile.status === 'active')
204
+ .map((profile) => profile.id);
205
+ /** Resolve a complete runtime/connection pair, including candidate profiles. */
206
+ export function resolveCompatibilityProfile(runtimeVersion, connectionVersion) {
207
+ if (typeof runtimeVersion !== 'string' || typeof connectionVersion !== 'string')
208
+ return undefined;
209
+ return COMPATIBILITY_PROFILES.find((profile) => profile.pairs.some((pair) => pair.runtime === runtimeVersion && pair.connection === connectionVersion));
210
+ }
211
+ /** Resolve only a profile whose implementation is promoted to active AND whose
212
+ * hostProfiles admit the given host profile(未知宿主形态一律无匹配,fail-closed)。 */
213
+ export function resolveActiveCompatibilityProfile(runtimeVersion, connectionVersion, hostProfile) {
214
+ const profile = resolveCompatibilityProfile(runtimeVersion, connectionVersion);
215
+ return profile?.status === 'active' && profile.hostProfiles.includes(hostProfile)
216
+ ? profile
217
+ : undefined;
218
+ }
219
+ export function isActiveCompatibilityProfileId(value) {
220
+ return typeof value === 'string' && ACTIVE_COMPATIBILITY_PROFILE_IDS.includes(value);
221
+ }
222
+ /** Small JSON-safe table embedded into the Loader `!!js` expression. */
223
+ export const GATE_PROFILE_TABLE = COMPATIBILITY_PROFILES.map(({ id, pairs, hostProfiles }) => ({ id, pairs, hostProfiles }));
@@ -0,0 +1,63 @@
1
+ /** Runtime connection module loader used by compatibility adapters. */
2
+ import { CONNECTION_PACKAGE } from './gate.js';
3
+ function isRuntimeConnectionModule(value) {
4
+ if (typeof value !== 'object' || value === null)
5
+ return false;
6
+ const candidate = value;
7
+ return typeof candidate.HostConnectionService === 'function'
8
+ && typeof candidate.API_PATH === 'string';
9
+ }
10
+ function describeError(error) {
11
+ return error instanceof Error ? error.message : String(error);
12
+ }
13
+ /**
14
+ * Resolve the connection module from the active product loader.
15
+ *
16
+ * 产品组合必须消费宿主自己的 connection module 实例:有 loader 服务时
17
+ * internal.import 缺失或调用失败都 fail loud——绝不静默回退到插件自带的
18
+ * pinned dev 副本(那会重演 2026-09-05「探针自我满足」一类代际错配)。
19
+ * pinned 副本只允许出现在完全没有 loader 服务的直接单元测试上下文。
20
+ */
21
+ export async function loadRuntimeConnectionModule(ctx) {
22
+ const loader = ctx.get('loader');
23
+ if (loader !== undefined) {
24
+ const importer = loader.internal?.import;
25
+ if (typeof importer !== 'function') {
26
+ throw new Error('dsh-plugin-reverse-proxy: product loader is present but loader.internal.import is unavailable; refusing to fall back to the pinned dev copy');
27
+ }
28
+ const baseUrl = ctx.baseUrl;
29
+ if (typeof baseUrl !== 'string' || baseUrl === '') {
30
+ throw new Error('dsh-plugin-reverse-proxy: loader.internal.import requires the plugin context baseUrl (profile directory URL); refusing to import without it');
31
+ }
32
+ let loaded;
33
+ try {
34
+ // 必须以 loader.internal 为接收者调用(bound call)。把方法摘下来
35
+ // detached 调用会丢失 this,Node 内部 ESM loader 在 getOrCreateModuleJob
36
+ // 前即抛 "Cannot read properties of undefined"(2026-09-10 崩溃循环根因)。
37
+ loaded = await importer.call(loader.internal, CONNECTION_PACKAGE, baseUrl, {});
38
+ }
39
+ catch (error) {
40
+ throw new Error(`dsh-plugin-reverse-proxy: failed to import runtime module ${CONNECTION_PACKAGE} via loader.internal.import(name, baseUrl, options): ${describeError(error)}`);
41
+ }
42
+ if (!isRuntimeConnectionModule(loaded)) {
43
+ throw new Error(`dsh-plugin-reverse-proxy: runtime module ${CONNECTION_PACKAGE} has an incompatible export shape`);
44
+ }
45
+ return loaded;
46
+ }
47
+ return importPinnedConnectionModule();
48
+ }
49
+ /**
50
+ * Pinned dev 副本惰性加载(审计修复 2026-09-28):只允许在完全没有 loader
51
+ * 服务的直接单元测试上下文执行。禁止顶层静态 import——那会让 0.1.2 旧模块
52
+ * 图在产品环境随插件加载被求值,且 bare specifier 绑定随安装布局漂移(dev
53
+ * 树内嵌时遮蔽命中 pinned 副本,净装则经 pnpm hoist 命中宿主副本)。动态
54
+ * import() 把模块解析推迟到实际调用点,产品路径(loader 恒在)永不触碰该
55
+ * 副本。不变量由 tests/manifest.test.mjs 的 lazy-load 断言锁定。
56
+ */
57
+ async function importPinnedConnectionModule() {
58
+ const pinned = (await import('@deepseek-ai/dsh-client-connection'));
59
+ if (typeof pinned?.HostConnectionService !== 'function' || typeof pinned?.API_PATH !== 'string') {
60
+ throw new Error(`dsh-plugin-reverse-proxy: pinned dev module ${CONNECTION_PACKAGE} has an incompatible export shape`);
61
+ }
62
+ return pinned;
63
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * 版本探针与行绑定表达式的单一事实源(组合期激活判据)。
3
+ *
4
+ * 两个表达式都跑在 Loader 的 `!!js` 求值环境里(`with (ctx) + eval`,
5
+ * 见 vendor/loader/src/config/utils.ts),失败一律落入 dormant(fail-closed)。
6
+ * sibling 解析走 Symbol.for('cordis.entry') 当前 entry 所属子树,
7
+ * 不依赖根 Loader 的 resolve——业务行位于 Include 子树,根上看不到。
8
+ *
9
+ * 探针解析基准(2026-09-05 事故修正):锚定宿主 runtime 本体,而不是
10
+ * connection 包自身。`ctx.baseUrl` 是 profile 目录,Node 解析自 profile
11
+ * 向上走 node_modules;旧版插件把 connection 包声明进 dependencies,发布
12
+ * 安装(profile `nodeLinker: hoisted`)把 0.1.2-rc.1 副本抬升进 profile
13
+ * node_modules,遮蔽 `~/.dsh/profiles/node_modules/` 下
14
+ * healProfilesModuleFallback 维护的 runtime fallback 符号链——探针随之
15
+ * 「自我满足」,在不兼容宿主上误激活(正是本次事故)。因此:
16
+ * 1. 第一锚点是 `@deepseek-ai/dsh/package.json`(runtime 应用包本体)。
17
+ * 它只可能来自 runtime fallback,不可能被任何 profile 插件的依赖
18
+ * 抬升污染;其版本即宿主 runtime 版本。
19
+ * 2. 第二锚点仍是官方 connection 包(被替换对象本体);双锚点必须同时
20
+ * 命中同一个 active compatibility profile pair,任一解析失败、混合版本或版本漂移一律 dormant。
21
+ * 配套必要条件:本插件的 dependencies 不得声明任何 `@deepseek-ai` 运行时
22
+ * 包(connection 仅作 devDependency 供编译期类型与构建锚点),由
23
+ * tests/manifest.test.mjs 作为不变量看护。
24
+ *
25
+ * 单锚点版本判定(2026-09-05 第二修正,npm 扁平布局):
26
+ * 1. pnpm store 路径段(快路径):URL 含 `+包名@版本[_/]` 段即取段值。
27
+ * 保留既有文档化行为——「段真、manifest 版本漂移」时探针仍放行,
28
+ * 由 apply 内 backstop 读 manifest 兜底 fail loud。
29
+ * 2. manifest 回退:URL 为 `file:` 且无版本段(npm 扁平布局,如 dshm
30
+ * 安装)时,经 `process.getBuiltinModule('node:fs'/'node:url')` 同步读
31
+ * manifest 比对精确版本(Node ≥22.3,插件 engines 覆盖;`!!js` 求值
32
+ * 环境无 require/模块导入,这是唯一受支持的同步内建模块获取方式)。
33
+ * 两分支都拿不到精确版本 → dormant。任何异常一律 dormant(组合期绝不
34
+ * fail loud;最后防线在 apply 内 backstop)。
35
+ *
36
+ * 宿主 profile 门控(2026-10-07,web-only / desktop 休眠;2026-10-08 0.3.8 信号修订)。
37
+ * 设计公理(0.3.6 desktop 事故后的 default-deny):**激活需要正向 web 证明,
38
+ * 休眠不需要理由**——伤害不对称已被实证(误激活 desktop ⇒ 宿主不可启动;
39
+ * 误休眠 web ⇒ 回到 token 输入,可一分钟定位)。
40
+ * 表达式在版本对判定之前先做宿主形态判别,desktop 否决两条 + web 证明一条:
41
+ * ① desktop 信号包(DESKTOP_HOST_PACKAGE)自 ctx.baseUrl 可解析且得合法
42
+ * {url: string}——app.asar 内置形态的判别;
43
+ * ② 宿主进程 process.argv 含 `dsh-desktop-host`——desktop 宿主以
44
+ * `[execPath, dsh-desktop-host/lib/index.js, <dsh>, <profileDir>, …]` 启动
45
+ * (Electron under ELECTRON_RUN_AS_NODE),与 DSH 官方 dsh-plugin-manager
46
+ * 的 isPackagedDesktopArgv 同款判别:launcher 事实独立于 profile 布局,
47
+ * 不可被依赖抬升污染;
48
+ * ②′ desktop 槽位判别:ctx.baseUrl 目录基名 === 'desktop'——desktop 客户端
49
+ * 恒以 profiles/desktop 槽位启动 loader(官方 desktopProfileDirFromArgv 按
50
+ * profiles 树定位),构造性事实、与进程树形状无关。0.3.8 的事态(宿主以
51
+ * 纯 node 子进程跑 loader,argv/execPath 双双落空)由本信号兜底;
52
+ * ③ web 正向证明:宿主二进制 process.execPath 基名(大小写归一)∈
53
+ * {node, node.exe, nodejs, nodejs.exe}——Windows/macOS/Linux 的 web 全形态
54
+ * (systemd/docker/nvm/fnm/volta/mise/直接 node)经解释器 exec 后 execPath
55
+ * 恒为 node 系二进制;desktop 宿主(Electron run-as-node)恒非 node 系。
56
+ * 非 node 系二进制 ⇒ 非 web ⇒ 休眠(unknown-variant 兜底)。
57
+ * 三者关系:任一 desktop 信号命中,或 web 证明不成立 ⇒ desktop(休眠)。
58
+ * 判 desktop ⇒ 由白名单表条目的 hostProfiles: ['web'] 条件统一拒绝(休眠,
59
+ * 策略单一来源 src/compatibility.ts);全否 ⇒ web 继续;resolver 缺失仍走
60
+ * 原有 null 分支。检测异常的 fail-closed 兜底是版本对判定本身(真异常时
61
+ * 双锚点同样解析失败 ⇒ null)。
62
+ * 信号修订缘由(2026-10-07 desktop 事故):desktop profile 为 hoisted 物化布局,
63
+ * dsh-desktop-host 只在 app.asar 内、自 ctx.baseUrl 不可达 ⇒ 0.3.6 仅凭信号①
64
+ * 误判 web ⇒ 版本对命中 v3 ⇒ Replacement 在 desktop 激活 ⇒ "Desktop Host
65
+ * authentication failed" 崩溃循环(0.3.6 已从 desktop 撤出;事故记录
66
+ * docs/COMPATIBILITY.md §7.4/§7.6)。Node 侧镜像见 detectHostProfile;
67
+ * 语义、事故记录与解冻条件见 docs/COMPATIBILITY.md §7。
68
+ */
69
+ import { ACTIVE_COMPATIBILITY_PROFILE_IDS, CARRIER_NEUTRAL_V4_PROFILE_ID, GATE_PROFILE_TABLE, } from './compatibility.js';
70
+ export { ACTIVE_COMPATIBILITY_PROFILE_IDS, COMPATIBILITY_PROFILES, GATE_VERSION, GATE_VERSIONS, isActiveCompatibilityProfileId, resolveActiveCompatibilityProfile, resolveCompatibilityProfile, } from './compatibility.js';
71
+ export const CONNECTION_PACKAGE = '@deepseek-ai/dsh-client-connection';
72
+ /** 宿主 runtime 本体包:探针的第一锚点,版本即宿主 dsh 版本。 */
73
+ export const GATE_RUNTIME_PACKAGE = '@deepseek-ai/dsh';
74
+ /** 探针锚点(顺序即求值顺序):宿主 runtime 本体在前,被替换对象在后。 */
75
+ export const GATE_ANCHOR_PACKAGES = [GATE_RUNTIME_PACKAGE, CONNECTION_PACKAGE];
76
+ /** desktop 宿主信号包:仅在 app.asar 内置形态存在(profile 布局下常不可达,见 0.3.8 事故记录);可解析即判定 desktop。 */
77
+ export const DESKTOP_HOST_PACKAGE = '@deepseek-ai/dsh-desktop-host';
78
+ /** desktop 宿主 argv 判别子串:desktop 宿主入口脚本为 `dsh-desktop-host/lib/index.js`(官方 isPackagedDesktopArgv 同款)。 */
79
+ export const DESKTOP_HOST_ARGV_MARKER = 'dsh-desktop-host';
80
+ /** desktop 安装槽位名:desktop 客户端恒以 profiles/desktop 槽位启动 loader(官方 desktopProfileDirFromArgv 契约)。 */
81
+ export const DESKTOP_HOST_SLOT_NAME = 'desktop';
82
+ /**
83
+ * 从已解析 URL 提取 pnpm store 版本段的正则源(`+name@VER_` / `+name@VER/`)。
84
+ * 探针表达式内嵌的正则由此单一实现生成;仅匹配 pnpm 布局,非 pnpm 布局
85
+ * 落入 manifest 回退分支。
86
+ */
87
+ export function versionSegmentPatternSource(pkg) {
88
+ const shortName = pkg.slice(pkg.indexOf('/') + 1).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
89
+ return `[+]${shortName}@([^/_]+)[_/]`;
90
+ }
91
+ /** 探针内嵌的锚点表:`[包名, 版本段正则源]` 对,全部由上方常量派生。 */
92
+ const GATE_ANCHOR_TABLE = GATE_ANCHOR_PACKAGES.map((pkg) => [pkg, versionSegmentPatternSource(pkg)]);
93
+ // Profile probe:单行;生成 cordis.patch.yml 的 profile-aware disabled 表达式。
94
+ // 逐锚点解析 `锚点包/package.json`,返回完整 runtime/connection pair 对应的
95
+ // profile id;candidate profile 也可被识别,是否允许激活由下方 boolean probe
96
+ // 根据 profile status 决定。解析失败、未知 pair 或混合 pair 一律返回 null。
97
+ export const GATE_PROFILE_EXPRESSION = `(() => { try { const internal = ctx.loader && ctx.loader.internal; if (!internal || typeof internal.resolveSync !== 'function') return null; const desktopSpecifier = ${JSON.stringify(DESKTOP_HOST_PACKAGE)} + '/package.json'; let hostProfile = 'web'; let hostProcess = null; try { if (typeof process === 'object' && process !== null) hostProcess = process; } catch (sigError0) { } let slot = ''; let desktopBySlot = false; try { const decodedBase = decodeURIComponent(typeof ctx.baseUrl === 'string' ? ctx.baseUrl : ''); const trimmedBase = decodedBase.endsWith('/') ? decodedBase.slice(0, -1) : decodedBase; slot = trimmedBase.slice(trimmedBase.lastIndexOf('/') + 1).toLowerCase(); desktopBySlot = slot === ${JSON.stringify(DESKTOP_HOST_SLOT_NAME)}; } catch (sigError1) { } let desktopByArgv = false; try { if (hostProcess !== null && typeof hostProcess === 'object' && Array.isArray(hostProcess.argv)) desktopByArgv = hostProcess.argv.some((arg) => typeof arg === 'string' && arg.indexOf(${JSON.stringify(DESKTOP_HOST_ARGV_MARKER)}) !== -1); } catch (sigError2) { } let webByBinary = false; try { if (hostProcess !== null && typeof hostProcess === 'object' && typeof hostProcess.execPath === 'string') { const execBase = hostProcess.execPath.slice(Math.max(hostProcess.execPath.lastIndexOf('/'), hostProcess.execPath.lastIndexOf('\\\\')) + 1).toLowerCase(); webByBinary = execBase === 'node' || execBase === 'node.exe' || execBase === 'nodejs' || execBase === 'nodejs.exe'; } } catch (sigError3) { } let desktopByPackage = false; try { const desktopResolved = internal.version === 'v2' ? internal.resolveSync(ctx.baseUrl, { specifier: desktopSpecifier, attributes: {} }) : internal.resolveSync(desktopSpecifier, ctx.baseUrl, {}); const desktopUrl = desktopResolved === null || typeof desktopResolved !== 'object' ? undefined : desktopResolved.url; desktopByPackage = typeof desktopUrl === 'string'; } catch (sigError4) { } hostProfile = desktopByArgv || desktopBySlot || desktopByPackage || !webByBinary ? 'desktop' : 'web'; const versionOfUrl = (url, patternSource) => { if (typeof url !== 'string') return null; const decoded = decodeURIComponent(url); const segmented = decoded.match(new RegExp(patternSource)); if (segmented !== null) return segmented[1]; if (decoded.slice(0, 5) === 'file:') { const processRef = globalThis.process; if (processRef === null || typeof processRef !== 'object' || typeof processRef.getBuiltinModule !== 'function') return null; const fsModule = processRef.getBuiltinModule('node:fs'); const urlModule = processRef.getBuiltinModule('node:url'); if (!fsModule || typeof fsModule.readFileSync !== 'function' || !urlModule || typeof urlModule.fileURLToPath !== 'function') return null; const manifest = JSON.parse(fsModule.readFileSync(urlModule.fileURLToPath(url), 'utf8')); return manifest !== null && typeof manifest === 'object' && typeof manifest.version === 'string' ? manifest.version : null; } return null; }; const anchors = ${JSON.stringify(GATE_ANCHOR_TABLE)}; const versions = []; for (const [anchorPackage, patternSource] of anchors) { const specifier = anchorPackage + '/package.json'; let url; try { url = internal.version === 'v2' ? internal.resolveSync(ctx.baseUrl, { specifier, attributes: {} }).url : internal.resolveSync(specifier, ctx.baseUrl, {}).url; } catch (gateError) { return null; } let anchorVersion; try { anchorVersion = versionOfUrl(url, patternSource); } catch (gateError) { return null; } if (anchorVersion === null) return null; versions.push(anchorVersion); } const profiles = ${JSON.stringify(GATE_PROFILE_TABLE)}; for (const profile of profiles) { if (profile.hostProfiles.includes(hostProfile) && profile.pairs.some((pair) => pair.runtime === versions[0] && pair.connection === versions[1])) return profile.id; } return null; } catch (gateError) { return null; } })()`;
98
+ // Boolean activation probe: only active profiles disable the official row.
99
+ // A known candidate profile remains dormant until its host/client adapter is
100
+ // promoted, while the profile expression still exposes its exact pair id.
101
+ export const GATE_PROBE_EXPRESSION = `(() => { try { const profile = (${GATE_PROFILE_EXPRESSION}); return profile !== null && ${JSON.stringify(ACTIVE_COMPATIBILITY_PROFILE_IDS)}.includes(profile); } catch (gateError) { return false; } })()`;
102
+ // 行绑定放行表达式源(0.4.0 起按代际拆分):自身探针解析出的 profile 落在
103
+ // allowedProfileIds 内 + 同组 sibling 存在且名字匹配且其 effective disabled 为真。
104
+ // sibling 必须从当前 entry(Symbol.for('cordis.entry'))所属子树解析,
105
+ // 根 Loader 的 resolve 看不到 Include 子树内的行。
106
+ //
107
+ // 为什么按代际拆分(§5.9):bundle patch 现在插入两行(webRuntime 行服务
108
+ // ≤0.2.0 代际、webStartup 行服务 0.2.1+ 代际),两个 id 集合必须互斥——否则
109
+ // 新代际宿主上旧行也会放行(其 inject 的 webRuntime 服务在上游已不存在)。
110
+ // 两个集合由 compatibility.ts 单表派生,不会漂移。
111
+ function rowAllowedExpressionSource(allowedProfileIds) {
112
+ return `(() => { try { const self = ctx[Symbol.for('cordis.entry')]; if (!self || !self.parent || !self.parent.tree) return false; const official = self.parent.tree.resolve('connection'); if (!official || official.parent !== self.parent) return false; if (official.options.id !== 'connection' || official.options.name !== '${CONNECTION_PACKAGE}') return false; const profile = (${GATE_PROFILE_EXPRESSION}); if (profile === null || !${JSON.stringify(allowedProfileIds)}.includes(profile)) return false; return official.disabled === true; } catch (gateError) { return false; } })()`;
113
+ }
114
+ /** ≤0.2.0 代际的行绑定(webRuntime 行):active 集合排除 v4。 */
115
+ export const GATE_ROW_ALLOWED_EXPRESSION = rowAllowedExpressionSource(ACTIVE_COMPATIBILITY_PROFILE_IDS.filter((id) => id !== CARRIER_NEUTRAL_V4_PROFILE_ID));
116
+ /** 0.2.1+ 代际(carrier-neutral-v4)的行绑定(webStartup 行):仅 v4。 */
117
+ export const GATE_ROW_ALLOWED_EXPRESSION_V4 = rowAllowedExpressionSource([CARRIER_NEUTRAL_V4_PROFILE_ID]);
118
+ /**
119
+ * Evaluate the activation probe against a loader context scope.
120
+ * @param ctx - the `!!js` evaluation scope (same object the Loader passes).
121
+ * @returns true only when both gate anchors resolve to one active compatibility profile pair.
122
+ */
123
+ export function evaluateGate(ctx) {
124
+ // 与 vendor/loader/src/config/utils.ts 的 evaluate 同语义:with(ctx) + eval。
125
+ return new Function('ctx', 'expr', 'with (ctx) { return eval(expr) }')(ctx, GATE_PROBE_EXPRESSION);
126
+ }
127
+ /**
128
+ * Node 侧宿主形态检测(apply backstop 镜像 + apply 前置判别共用):与
129
+ * GATE_PROFILE_EXPRESSION 内联检测同语义,desktop 信号取或——① desktop 信号包自
130
+ * baseUrl 解析出合法 {url: string}(抛错/空值/url 非字符串视为不可达,继续②);
131
+ * ② 宿主进程 process.argv 含 `dsh-desktop-host`(与官方 isPackagedDesktopArgv
132
+ * 同款)。两信号皆否 ⇒ 'web'(fail-closed 兜底是后续版本对判定)。
133
+ * resolver 允许为 undefined(0.3.12 起 apply 在 presence 检查之前先调用本函数做
134
+ * 前置判别):信号① 对 undefined 的访问在自身 try/catch 内消化,其余信号不依赖
135
+ * resolver——undefined 一律按「信号①不可达」处理,语义不变。
136
+ */
137
+ export function detectHostProfile(internal, baseUrl) {
138
+ const specifier = `${DESKTOP_HOST_PACKAGE}/package.json`;
139
+ // resolver 缺省 ⇒ 信号①按「不可达」处理(与原 try/catch 消化 TypeError 等价)。
140
+ if (internal !== undefined) {
141
+ try {
142
+ const resolved = internal.version === 'v2'
143
+ ? internal.resolveSync(baseUrl, { specifier, attributes: {} })
144
+ : internal.resolveSync(specifier, baseUrl, {});
145
+ const url = resolved?.url;
146
+ if (typeof url === 'string')
147
+ return 'desktop';
148
+ }
149
+ catch {
150
+ // 信号包不可达/解析异常 ⇒ 落到宿主进程 argv 判别
151
+ }
152
+ }
153
+ let slot = '';
154
+ try {
155
+ const trimmedBase = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
156
+ const slotIndex = Math.max(trimmedBase.lastIndexOf('/'), trimmedBase.lastIndexOf('\\'));
157
+ slot = trimmedBase.slice(slotIndex + 1).toLowerCase();
158
+ }
159
+ catch {
160
+ slot = '';
161
+ }
162
+ if (slot === 'desktop')
163
+ return 'desktop';
164
+ const hostProcess = globalThis.process;
165
+ if (hostProcess !== undefined && hostProcess !== null && Array.isArray(hostProcess.argv)) {
166
+ const desktopByArgv = hostProcess.argv.some((arg) => typeof arg === 'string' && arg.includes(DESKTOP_HOST_ARGV_MARKER));
167
+ if (desktopByArgv)
168
+ return 'desktop';
169
+ const execPath = typeof hostProcess.execPath === 'string' ? hostProcess.execPath : '';
170
+ const execBase = execPath.slice(Math.max(execPath.lastIndexOf('/'), execPath.lastIndexOf('\\')) + 1).toLowerCase();
171
+ const webByBinary = execBase === 'node' || execBase === 'node.exe' || execBase === 'nodejs' || execBase === 'nodejs.exe';
172
+ if (!webByBinary)
173
+ return 'desktop';
174
+ }
175
+ return 'web';
176
+ }