dsh-plugin-update-doctor 0.5.0 → 0.5.3

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,78 @@
1
+ # Windows支持扩展与公共API边界
2
+
3
+ ## 当前0.5.3与本机状态
4
+
5
+ - 本机更新器0.5.3已安装激活;用户在真实面板完成WSL0.26.2→0.29.0,日志applied、包和代际核验通过,当前16/16Host行active。
6
+ - WSL新候选按公开原包/现代声明契约和实际身份检查,不再仅限固定版本名单;旧根/全部保留原包证明、schema4及未知结果保护见[WSL结构准入](<WSL_STRUCTURAL_0_5_3.md>)。
7
+ - Union常规npm/HMR限制不变;**自0.5.2起另有已审查0.10.24→0.10.25完整依赖本地代际路线**,不是仅靠风险拦截,也不是修改宿主。来源转本地、额外确认、fresh恢复及未知/未审查目标拒绝见[Union代际](<UNION_GENERATION_0_5_2.md>)。
8
+ - Windows x64、Node≥24、宿主服务和.NET Framework4.x检测助手等条件见[运行要求](<WINDOWS_REQUIREMENTS.md>);没有写死本机路径,不代表第二台设备已验证。
9
+ - 本页下方保留的是0.5.1阶段的普通来源/镜像/WSL0.28实验和常规Union故障事实,**不是当前0.5.3全部行为清单**,没有重新执行所有历史实验。
10
+
11
+ ## 0.5.1阶段已实现的路径(历史)
12
+
13
+ - 普通 registry 更新使用公开 `pluginManager.updateBundle`,保留精确 npm 安装规格和官方后续 Versions 资格。
14
+ - 更新器支持固定 npm 官方源及固定公共镜像 `https://registry.npmmirror.com`。镜像旧/新归档必须与官方同版本归档摘要及运行声明一致;需额外用户确认,绑定来源和已披露宿主计划,不修改 profile 配置。官方原有严格无 fallback 路径仍独立保留。
15
+ - 旧普通 Doctor 归档可在无待处理结果、身份与已装字节核验通过后,独立确认**同版本来源迁移**。不接受任意 file/git、自身或 WSL迁移;失败尝试恢复原记录归档,未知不重发。
16
+ - 不再仅因普通插件声明 dependencies 就拒绝。支持不变、可解析、无原生/安装生命周期脚本的 JS 依赖集合;对实际安装依赖包版本、边关系与全文件摘要在准备、替换前及替换后核验。只实现严格 semver 子集,不能解析的范围拒绝。
17
+ - WSL精确增加已审查 `0.28.0` 及原归档SHA256。已有部署归档、实际安装的全文件、根旧资源、保留代际、exports/patch分别核验,并重建已知原包组合;不接受未知代际。查询与预检不执行包代码。
18
+ - 官方插件详情通过公开 `plugins.detail.section` 提供**由更新器提供的独立归档版本检查**和打开更新面板入口。不会改宿主 `update` 字段或伪造内置 Versions。
19
+
20
+ ## 0.5.1阶段实际隔离验证(历史)
21
+
22
+ 均使用已安装 DSH Desktop **0.2.2-rc.5** 的 AppBoot/Cordis/Loader/HMR/PluginManager,自有临时profile/store/cache,禁止模型、用户发行版和真实用户任务;原始结果含本地路径,仅留在忽略目录。
23
+
24
+ ### 普通 npm 与纯 ESM 依赖
25
+
26
+ - 无依赖正常更新和故意激活失败自动恢复,各自同进程通过;新旧来源保持 npm,官方 Versions查询仍可用。
27
+ - 一项纯 ESM依赖、声明不变:新旧实际依赖版本/边关系/文件摘要一致,更新 Host active、代码标记有效、来源 registry。故意目标加载失败由 Host恢复旧版,升级仍为失败。
28
+ - 旧 file来源同版本迁移通过,npm来源和官方 Versions资格恢复;一次测试安装拒绝为明确fixture、没有包命令执行,迁移恢复原归档 applied,原代码及身份恢复。不是声称真实npm网络故障。
29
+
30
+ - 最后冻结核心后复跑上述四组,六项 production源码摘要与当前源码全部一致;各mode自有环境清理,成功/失败不靠重写结果。新旧图与来源的证据只限定这组纯ESMfixture和来源迁移,不扩大为所有社区依赖。
31
+
32
+ 入口脚本(仓库开发材料,不随插件安装):`experiments/registry-preservation-proof-runner.mjs`、`experiments/migration-deps-proof-runner.mjs`。
33
+
34
+ ### 公共镜像自身交接
35
+
36
+ 复制当前production代码的旧/新fixture、固定镜像/官方逻辑元数据及owned loopback传输映射。Host公共操作和真实包管理/卸载/激活/恢复不替换。好组单次交接到新版本、包/来源/YAML2.9.1/Host核验;坏组故意目标apply抛错,Host恢复旧版,失败保留。缺 `confirmPublicMirror`拒绝。每组保持同PID;旧disposer约1ms且不等待自身替换;临时根清理。
37
+
38
+ 该证明不是已经发布的真实旧 `0.5.0` 含镜像功能,也不是现场公共镜像网络安装。并行编辑造成部分client/service/staging摘要不同,原始结果有productionFilesSha256;不能把未匹配文件算作同一快照已验证。
39
+
40
+ 入口脚本(仓库开发材料,不随插件安装):`experiments/mirror-self-proof-runner.mjs`。
41
+
42
+ ### 新版 WSL 与历史根资源
43
+
44
+ - 原public归档 `0.28.0` SHA256:`c137376aba2b3973690ecef93baed9e4de79a22825ab5a50e92ae9ad2881e694`;版本清单、peer键和值、无依赖、客户端声明已审查,新增 `wsl-plugin-update` 是第16个Host条目。
45
+ - 冷0.26.2基线15active→0.28.0 16active→恢复0.26.2 15active,同PID。
46
+ - 复刻原0.24-root部署形态:准备、更新及恢复保留0.24根和24/26/28各自资源;每次749项文件字节核验。
47
+ - 最终实际 production RegistryStager+HTTP prepare-batch票据+commit/runBatch 完整路径通过,同PID,旧/新资源及Host逐项核验;另坏新条目衍生fixture触发实际恢复分支,目标失败、恢复applied分开。
48
+ - 两次前置fixture准备尝试失败保留,未算通过;最终新cold归档基线通过。首轮故意改bareanchor未触发失败,不将其原因写成已确定Host故障。
49
+
50
+ - 冻结核心后再次完整复验:同PID28448,116.418秒,service/staging/wsl-policy/generation前后摘要不变并与最终源码一致;缓存优化仅需4次元数据/3次归档fixture读取,仍严格核验。更新16active、回退15active及两次749项检查通过,临时根清理。不是现场网络可用性证明。
51
+
52
+ 入口脚本(仓库开发材料,不随插件安装):`experiments/wsl-modern-proof-runner.mjs`。传输提供工作区已核验public归档副本,而非现场网络持续可用性;没有真实WSL模型或发行版任务连续性、浏览器交互证明。
53
+
54
+ ## 常规Union npm/HMR故障记录(历史,故障不因新路线而消失)
55
+
56
+ 公开 `0.10.24 → 0.10.25`:
57
+
58
+ - 新进程冷安装 `0.10.25` applied,Host 1/1 active;包16文件与公开归档一致。
59
+ - HMR官方更新:pnpm exit0,但加载 `TypeError: Cannot read properties of undefined (reading 'Element')`;自动恢复旧版也出现同导入错误。
60
+ - 前后29依赖包、2289文件、约14.55MB完全一致;这不是发现依赖版本被替换的证据。circular dependency警告与冷热差异支持运行时重载问题,但没有证明私有缓存内部精确根因。
61
+ - 无HMR、先冷旧基线:更新正确返回 `restart-required/no-hmr`,磁盘新包/来源/依赖字节一致;旧运行行不是新版代码证据。独立cold新版本证明包可加载。
62
+
63
+ DSH公开管理器在HMR下拒绝重复安装已知registry包;关闭bundle不解除它,官方更新仍先移除再安装。未发现合法公共原位npm覆盖入口,不用别名、未知tarball、私有cache或底层profile写操作绕过。因此当时0.5.1的HMR配置中Union更新/来源迁移/恢复被具体标为 `dependency-runtime-reload-unverified`,而不是对所有JS依赖一概拒绝。非HMR真实重启路径保留,但不会自动改用户HMR或强制重启。
64
+
65
+ 入口脚本(仓库开发材料,不随插件安装):`experiments/union-dependency-proof-runner.mjs`。
66
+
67
+ ### 0.5.1对此问题的处理(历史)
68
+
69
+ 当时0.5.1在原版DSH HMR环境中拒绝Union更新、来源迁移和恢复;版本扫描不因拒绝替换而假称没有新版。**拒绝是风险拦截,不是修复。仅安装本更新器无法完整解决该问题。**
70
+
71
+ 此前对Union自身或Node/Electron的独立研究,涉及修改第三方插件或底层运行时,不属于本插件发布功能,也不是原版DSH下的插件验收。本更新器不部署这些补丁、不注入debugger、不强清缓存、不自动重启。需要单独冷启动/重启处理时由用户另行确认和验收;没有保证所有旧版均能热恢复。
72
+
73
+ ## 历史实验保留边界
74
+
75
+ - WSL保存来源仍为代际本地归档;公开详情扩展解决可发现性与操作衔接,**不等于宿主内置Versions认可registry身份**。关闭或卸载更新器后该扩展不在,未来需宿主来源扩展接口。
76
+ - 已装依赖图摘要证明当时已声明dependencies的文件/解析关系,不覆盖完整peer解析身份、不证明全部依赖都来自公共npm或运行模块缓存已换代;root peer声明另行比较,Host再次下载也可能重新解析,所以后验失败不能冒充成功。
77
+ - 独立检查与重复状态重验不是原子CAS,外部管理/CLI仍可并发;不保证恢复成功。
78
+ - 上述历史开发实验未修改用户profile/安装/缓存,不自动批准脚本或豁免;没有扩展Mac。其当时的UI未验收状态不覆盖用户后来提供的0.5.3中文深色截图和实际WSL升级,其他未验证范围见上方当前状态。
@@ -0,0 +1,30 @@
1
+ # v0.5.3:WSL 新版准入修复
2
+
3
+ 本版修复更新器把 WSL 新版仅因不在固定版本名单中而提前拒绝的问题。0.5.2 能发现 0.29.0,却以 `wsl-version-not-yet-verified` 禁止勾选;这不是 WSL 安装故障,也不是兼容性测试失败。
4
+
5
+ ## 新的检查方式
6
+
7
+ - 检查稳定正式版的公开 npm 原包、SHA512、精确包名/版本、宿主兼容性及平台。
8
+ - 对新候选核验现代 WSL 的完整声明契约:16 个既有 Host 行、基础服务抑制、预设及配置表达式、11 个既有 peer 名称、客户端注入图、导出资源和安全路径。声明变化会给出具体契约拒绝原因,而不是“没有测试这个版本号”。
9
+ - 不引入新运行依赖、不批准安装脚本、不复制或修改宿主;已有 Linux agent 原生资源只在受限原路径内保留。
10
+ - “检查全部更新”对候选只读下载/检查,不写 stage、不安装、不停止任务。准备确认时再次下载、绑定候选摘要及实际已装资源,确认后及等待后重验。
11
+ - 新的代际身份保存 root 与全部 retained 原包的版本、SHA256/SHA512 和独立原包证明,重新打开时离线重建整个派生归档。旧身份仍可读,新 WSL 结构身份使用 schema4;不能降级旧更新器继续管理 schema4。
12
+ - 最多保留 8 个原包并受原来的 2,000 项归档和字节上限限制,超过上限提前拒绝,不静默删除旧代。
13
+ - 初次安装、第二次公开 reapply 或恢复回执未知时均不自动恢复或重发。未知恢复身份在准备、已发票据、任务政策前和实际恢复入口拒绝。
14
+
15
+ 旧 0.24.0 / 0.26.2 / 0.28.0 的固定摘要只用于验证既有历史原包和保留根资源,**不再充当新候选版本名单**。
16
+
17
+ ## 本机用户后续升级确认(2026-11-23)
18
+
19
+ 0.5.3完整归档安装完成后,用户在真实面板确认WSL **0.26.2→0.29.0**,日志时间 **22:12:13–22:12:29(Asia/Shanghai)**。操作applied、包命令exit0、generationVerified=true、资源核验通过,当前Host **16/16active**,没有触发旧版恢复。此项是用户真实升级证据,不再仅是隔离实验;不等于发行版任务、全部已有会话或第二台设备已验证。中文深色截图还确认新版本列表和候选可选,完整主题/英文/键盘/窄屏行为仍未覆盖。
20
+
21
+ ## 实际验证与限制
22
+
23
+ - 公开 WSL 0.29.0 的 Host patch、peers、导出与 0.28.0 不变;主要变化为客户端、状态模块和文档。
24
+ - 原版 DSH Desktop 0.2.2-rc.5 隔离 profile 中,保留 0.24 根资源的 0.26.2 基线通过完整生产 HTTP prepare/commit、默认等待、0.29.0 代际更新,Host 15 → 16 active;替换前准备的旧包经公开管理器恢复后 15 active。新旧代和根资源按公开原包逐 byte 核验。
25
+ - 结构专项验证不是未来版本实际安装成功承诺。源码结构保持不变的未来正式版可以进入同一检查流程;变更执行代码仍可能发生加载错误,因此保留结果核验和恢复路径。
26
+ - 实验使用自有临时 profile、公共原包传输 adapter、panel-shaped 请求,没有运行真实 WSL 发行版、模型任务或浏览器点击。预准备旧包的恢复通过不等于每个实际激活失败恢复都验证。
27
+ - 0.5.3打包时回归358项(344通过、14明确跳过、0失败),同一最终归档47文件已核验,冻结生产模块与其摘要一致。后续文档补记不覆盖该归档,不把早期冻结结果冒充最新代码复验。
28
+ - Windows x64并非唯一环境条件;Node/Host及.NET Framework4.x辅助要求、另一台设备未验证的边界见[运行要求](<WINDOWS_REQUIREMENTS.md>)。
29
+ - 安装更新器本身不会自动更新WSL / Union;本机WSL的后续升级由用户另行确认,WSL 来源仍是本地代际归档,不伪造 npm / 内置 Versions 身份。已有会话可能保留旧预设。
30
+ - 本版不扩大 Union 的已审查升级对,不修改 DSH / Node / Electron,不重启或杀进程;仍不代表“任意插件都能更新”。
package/index.js CHANGED
@@ -1,16 +1,18 @@
1
1
  import { join } from 'node:path';
2
2
  import { realpath, readFile } from 'node:fs/promises';
3
+ import { pathToFileURL } from 'node:url';
3
4
  import { createRequire } from 'node:module';
4
5
  import { SelfUpdateCoordinator } from './lib/self-update.js';
5
6
  import { SelfUpdatePreflight } from './lib/self-update-policy.js';
6
7
  import { GithubSelfUpdatePreflight } from './lib/self-update-github.js';
7
8
  import { defineTool } from '@deepseek-ai/dsh-tools';
8
- import { getDshRuntimeVersion, resolveBundleDir, evaluatePluginCompatibility } from '@deepseek-ai/dsh-app-boot';
9
+ import { getDshRuntimeVersion, resolveBundleDir, evaluatePluginCompatibility, resolvePluginResource } from '@deepseek-ai/dsh-app-boot';
9
10
  import { DoctorService } from './lib/service.js';
10
11
  import { probeLocks } from './lib/locks.js';
11
12
  import { createHandler, ROUTE } from './lib/http.js';
12
13
  import { TaskGate } from './lib/task-gate.js';
13
14
  import { RegistryStager } from './lib/staging.js';
15
+ import { UnionGenerationStager } from './lib/union-staging.js';
14
16
 
15
17
  export const name = 'plugin-update-doctor';
16
18
  export const inject = ['pluginManager', 'profileContext', 'agents'];
@@ -24,10 +26,21 @@ export async function apply(ctx) {
24
26
  // Use the public manager Service. Its updateBundle implementation owns package operations
25
27
  // on the manager's providing context; teardown independence is verified by an isolated Host proof.
26
28
  const manager = ctx.get('pluginManager');
29
+ const unionStager = new UnionGenerationStager(join(profile.home,'cache','dsh-plugin-update-doctor',profile.name,'union-staged'),{registryStager:stager});
30
+ const verifyRunningGeneration=async(directory,reference,{enabled}={})=>{
31
+ const entry=[...ctx.loader.entries()].find(value=>value.options.id==='web-search-free'&&value.options.name==='dsh-union-search');
32
+ if(enabled===false)return !entry?.fiber || entry.disabled===true;
33
+ if(!entry?.moduleNamespace)return false;
34
+ const originalEntry=pathToFileURL(join(directory,reference.runtimeGeneration.generation,'lib/index.js')).href;
35
+ const namespace=await import(originalEntry);if(entry.moduleNamespace!==namespace)return false;
36
+ const sharedPath=resolvePluginResource('@deepseek-ai/schemastery',originalEntry),shared=await import(pathToFileURL(sharedPath).href);
37
+ if(sharedPath.includes(reference.runtimeGeneration.generation+'/node_modules/')||sharedPath.includes(reference.runtimeGeneration.generation.replaceAll('/','\\')+'\\node_modules\\'))return false;
38
+ return typeof namespace.Config==='function' && Object.getPrototypeOf(namespace.Config)===shared.default.prototype;
39
+ };
27
40
  const service = new DoctorService({
28
41
  manager, profile, runtimeVersion: getDshRuntimeVersion(),
29
42
  resolvePackage: async packageName => resolveBundleDir('dsh', packageName, profile.installAnchor, profile.dir),
30
- probeLocks, statePath: join(profile.home, 'cache', 'dsh-plugin-update-doctor', profile.name, 'history.json'), taskGate, stager,
43
+ probeLocks, statePath: join(profile.home, 'cache', 'dsh-plugin-update-doctor', profile.name, 'history.json'), taskGate, stager, unionStager, verifyRunningGeneration, hmrAvailable:!!ctx.get('hmr'),
31
44
  });
32
45
  await service.initialize();
33
46
  const selfUpdate = new SelfUpdateCoordinator({ manager, profile, taskGate,
@@ -0,0 +1,89 @@
1
+ import { createRequire } from 'node:module';
2
+ import { createHash } from 'node:crypto';
3
+ import { lstat, realpath, readdir } from 'node:fs/promises';
4
+ import { join, relative, isAbsolute, sep } from 'node:path';
5
+ import { boundedFile } from './file-read.js';
6
+
7
+ const MAX_PACKAGES=64, MAX_FILES=6000, MAX_DIRS=4000, MAX_BYTES=64*1024*1024, MAX_FILE=8*1024*1024;
8
+ const NAME=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
9
+ const UNSAFE=/^(?:@deepseek-ai\/dsh-|dsh-plugin-update-doctor$|electron$|node-pty$|koffi$|ffi-napi$|better-sqlite3$)/;
10
+ const stable=value=>/^\d+\.\d+\.\d+$/.test(value??'');
11
+ function rangeMatches(version,range) {
12
+ if(typeof range!=='string')return false;
13
+ const value=version.split('.').map(Number),compare=(a,b)=>{for(let i=0;i<3;i++)if(a[i]!==b[i])return a[i]-b[i];return 0;};
14
+ return range.split('||').some(branch=>{
15
+ const tokens=branch.trim().match(/(?:\^|~|>=|<=|>|<|=)?\s*(?:\d+(?:\.\d+|\.\*){0,2}|\*)/g);
16
+ if(!tokens||tokens.join('').replace(/\s/g,'')!==branch.replace(/\s/g,''))return false;
17
+ return tokens.every(token=>{const match=/^(\^|~|>=|<=|>|<|=)?\s*(\d+(?:\.\d+|\.\*){0,2}|\*)$/.exec(token);if(!match)return false;if(match[2]==='*')return !match[1];
18
+ const nums=match[2].split('.'),minimum=nums.map(x=>x==='*'?0:Number(x));
19
+ if(match[1]&&(nums.length!==3||nums.includes('*')))return false;
20
+ while(minimum.length<3)minimum.push(0);const c=compare(value,minimum),op=match[1];
21
+ if(op==='>=')return c>=0;if(op==='>')return c>0;if(op==='<=')return c<=0;if(op==='<')return c<0;
22
+ if(op==='^'||op==='~'){let upper=[...minimum];if(op==='~'){upper[1]++;upper[2]=0;}else if(upper[0]){upper[0]++;upper[1]=upper[2]=0;}else if(upper[1]){upper[1]++;upper[2]=0;}else upper[2]++;return c>=0&&compare(value,upper)<0;}
23
+ if(nums.length<3||nums.includes('*'))return nums.every((x,i)=>x==='*'||Number(x)===value[i]);return c===0;
24
+ });
25
+ });
26
+ }
27
+ const dependencies=manifest=>({...manifest.dependencies,...manifest.optionalDependencies});
28
+ const fail=code=>{throw Object.assign(Error(code),{code});};
29
+ const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(key=>[key,canonical(value[key])])):value;
30
+ export function dependencyDeclaration(manifest) { return JSON.stringify(canonical({dependencies:manifest.dependencies??{},optionalDependencies:manifest.optionalDependencies??{}})); }
31
+ export function dependencyPolicyReasons(manifest,{publishedDependency=false}={}) {
32
+ const reasons=[];const deps=dependencies(manifest);
33
+ if(Object.keys(deps).some(name=>UNSAFE.test(name)))reasons.push('host-runtime-dependencies');
34
+ if(Object.values(deps).some(spec=>typeof spec!=='string'||!/^\s*[~^<>=*\d][\d\s.~^<>=*|+-]*$/.test(spec)))reasons.push('dependency-source-unsupported');
35
+ if(Object.keys(manifest.optionalDependencies??{}).length||manifest.bundledDependencies?.length||manifest.bundleDependencies?.length)reasons.push('dependency-graph-update-requires-separate-review');
36
+ for(const key of ['preinstall','install','postinstall',...publishedDependency?[]:['prepare']])if(manifest.scripts?.[key]?.trim())reasons.push('package-install-scripts-require-separate-review');
37
+ return [...new Set(reasons)];
38
+ }
39
+
40
+ /** Bounded installed graph evidence. No code runs, no dependency is installed or approved.
41
+ * Only unchanged reviewed dependency declarations are admitted; graph bytes/versions
42
+ * are compared again after Host installation and independently from package identity.
43
+ */
44
+ export async function inspectDependencyGraph(packageDirectory, manifest, signal) {
45
+ signal=signal?AbortSignal.any([signal,AbortSignal.timeout(60000)]):AbortSignal.timeout(60000);
46
+ const reasons=dependencyPolicyReasons(manifest);if(reasons.length)fail(reasons[0]);
47
+ const root=await realpath(packageDirectory),rootOwner='root:'+manifest.name,pending=[{directory:root,names:Object.keys(dependencies(manifest)),manifest,ownerKey:rootOwner}],seen=new Map(),records=[],edges=[];
48
+ let count=0,total=0,directoryCount=0;
49
+ const readManifest=async dir=>JSON.parse((await boundedFile(join(dir,'package.json'),512*1024)).toString('utf8'));
50
+ while(pending.length){
51
+ signal?.throwIfAborted();const owner=pending.shift(),require=createRequire(join(owner.directory,'package.json'));
52
+ for(const name of owner.names){
53
+ if(!NAME.test(name)||UNSAFE.test(name))fail('dependency-source-unsupported');
54
+ let entry;try{entry=require.resolve(name+'/package.json');}catch{try{entry=require.resolve(name);}catch{fail('dependency-not-resolved');}}
55
+ let directory=entry;
56
+ const {dirname}=await import('node:path');directory=dirname(directory);
57
+ while(true){try{const value=await readManifest(directory);if(value.name===name)break;}catch{}
58
+ const parent=dirname(directory);if(parent===directory)fail('dependency-not-resolved');directory=parent;
59
+ }
60
+ directory=await realpath(directory);const value=await readManifest(directory);
61
+ if(!stable(value.version)||value.name!==name||dependencyPolicyReasons(value,{publishedDependency:true}).length)fail('dependency-graph-update-requires-separate-review');
62
+ if(!rangeMatches(value.version,dependencies(owner.manifest)[name]))fail('dependency-version-range-mismatch');
63
+ const key=name+'@'+value.version;edges.push({owner:owner.ownerKey??owner.manifest.name+'@'+owner.manifest.version,name,resolved:key});
64
+ if(edges.length>256)fail('dependency-graph-limit');
65
+ if(seen.has(directory))continue;seen.set(directory,key);
66
+ if(seen.size>MAX_PACKAGES)fail('dependency-graph-limit');
67
+ const files=[],dirs=[directory];
68
+ while(dirs.length){signal.throwIfAborted();if(++directoryCount>MAX_DIRS)fail('dependency-graph-limit');const dir=dirs.pop();for(const item of await readdir(dir,{withFileTypes:true})){
69
+ if(item.name==='node_modules'||item.name==='.git')continue;
70
+ signal.throwIfAborted();
71
+ const path=join(dir,item.name),rel=relative(directory,path).split(sep).join('/');
72
+ if(isAbsolute(rel)||rel.split('/').includes('..')||/[<>:"\\|?*\x00-\x1f]/.test(rel))fail('dependency-path-unsupported');
73
+ const info=await lstat(path);if(info.isSymbolicLink())fail('dependency-path-unsupported');
74
+ if(info.isDirectory()){dirs.push(path);continue;}if(!info.isFile())fail('dependency-path-unsupported');
75
+ if(/\.(?:node|dll|exe|so|dylib)$/i.test(item.name)||item.name==='binding.gyp')fail('native-or-shared-runtime');
76
+ if(++count>MAX_FILES)fail('dependency-graph-limit');const bytes=await boundedFile(path,MAX_FILE);total+=bytes.length;if(total>MAX_BYTES)fail('dependency-graph-limit');
77
+ files.push([rel,createHash('sha256').update(bytes).digest('hex')]);
78
+ }}
79
+ files.sort((a,b)=>a[0].localeCompare(b[0]));records.push({name,version:value.version,digest:createHash('sha256').update(JSON.stringify(files)).digest('hex'),files:files.length});
80
+ pending.push({directory,names:Object.keys(dependencies(value)),manifest:value});
81
+ }
82
+ }
83
+ records.sort((a,b)=>(a.name+'@'+a.version).localeCompare(b.name+'@'+b.version));
84
+ edges.sort((a,b)=>JSON.stringify(a).localeCompare(JSON.stringify(b)));
85
+ return {schemaVersion:1,declaration:dependencyDeclaration(manifest),packages:records,edges,provenance:'installed file evidence, not public registry provenance',digest:createHash('sha256').update(JSON.stringify({records,edges})).digest('hex'),packageCount:records.length,fileCount:count,totalBytes:total};
86
+ }
87
+ export function assertSameDependencyGraph(previous,next) {
88
+ if(previous?.declaration!==next?.declaration||previous?.digest!==next?.digest)fail('dependency-graph-changed');
89
+ }
package/lib/history.js CHANGED
@@ -11,9 +11,9 @@ const FACTS = new Set(['id', 'batchId', 'package', 'name', 'operation', 'origin'
11
11
  const RECORD_FACTS = ['id', 'batchId', 'package', 'target', 'operation', 'origin', 'phase', 'outcome', 'application',
12
12
  'from', 'to', 'version', 'savedEnabled', 'enabled', 'time', 'startedAt', 'finishedAt', 'taskPolicy', 'confirmCancel'];
13
13
  const ITEM_FACTS = ['name', 'from', 'to', 'version', 'status', 'outcome', 'phase', 'enabled', 'origin', 'archivePath',
14
- 'sourceArchivePath', 'originalSha256', 'sha256', 'integrity', 'runtimePackaging', 'interrupted', 'previousStatus'];
14
+ 'sourceArchivePath', 'originalSha256', 'sha256', 'integrity', 'runtimePackaging', 'installMode', 'sourceMode', 'management', 'registryOutcomeUnknown', 'unionOutcomeUnknown', 'unionDispatchStarted', 'wslOutcomeUnknown', 'wslDispatchStarted', 'interrupted', 'previousStatus'];
15
15
  const RESULT_FACTS = ['application', 'stage', 'target', 'bundle', 'version', 'changed', 'enabled', 'restartReason',
16
- 'generationVerified', 'verifiedVersion', 'id', 'reason', 'time', 'phase', 'errorCode'];
16
+ 'generationVerified', 'verifiedVersion', 'observedApplication', 'id', 'reason', 'time', 'phase', 'errorCode'];
17
17
  const stringify = records => JSON.stringify({ schemaVersion: 1, records });
18
18
  const bytes = text => Buffer.byteLength(text, 'utf8');
19
19
  const scalar = value => value === null || ['string', 'boolean', 'number'].includes(typeof value);
package/lib/http.js CHANGED
@@ -60,6 +60,10 @@ export function createHandler(service) {
60
60
  || body.commit !== undefined && (typeof body.commit !== 'string' || !/^[a-f0-9]{40}$/.test(body.commit))) return json({ error: 'Self-update accepts only its offered exact version and commit.', code: 'invalid-self-update' }, 400);
61
61
  return json(await service.selfUpdate.prepare(body.version, request.signal, { targetCommit: body.commit }));
62
62
  }
63
+ if (body.action === 'prepare-migration') {
64
+ if(Object.keys(body).some(key=>!['action','name'].includes(key)))return json({error:'Migration accepts only an identified package name.',code:'invalid-migration'},400);
65
+ return json(await service.prepareMigration(body.name,request.signal));
66
+ }
63
67
  if (body.action === 'prepare-batch') return json(await service.prepareBatch(body.items, request.signal));
64
68
  if (body.action === 'prepare-restore') {
65
69
  if (Object.keys(body).some(key => !['action', 'name'].includes(key))) return json({ error: 'Recovery accepts only the recorded package name.', code: 'invalid-recovery' }, 400);
@@ -70,7 +74,7 @@ export function createHandler(service) {
70
74
  if (body.action === 'prepare') return json({ error: 'Single-item management bypass is disabled. Use the batch confirmation flow.', code: 'use-batch-flow' }, 400);
71
75
  if (body.action === 'commit') {
72
76
  if (typeof body.ticket !== 'string') return json({ error: 'User confirmation ticket required.' }, 400);
73
- return json(await service.commit(body.ticket, { taskPolicy: body.taskPolicy ?? 'wait-for-idle', confirmCancel: body.confirmCancel === true }));
77
+ return json(await service.commit(body.ticket, { taskPolicy: body.taskPolicy ?? 'wait-for-idle', confirmCancel: body.confirmCancel === true, confirmPublicMirror:body.confirmPublicMirror===true, confirmUnionGeneration:body.confirmUnionGeneration===true }));
74
78
  }
75
79
  return json({ error: 'Unknown user action.', code: 'invalid-action' }, 400);
76
80
  } catch (error) {
package/lib/identity.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { readFile, lstat, mkdir, writeFile, rename, unlink } from 'node:fs/promises';
2
2
  import { dirname } from 'node:path';
3
3
  import { randomUUID } from 'node:crypto';
4
- import { PUBLIC_REGISTRY } from './source.js';
4
+ import { PUBLIC_REGISTRY, approvedPublicRegistry } from './source.js';
5
5
  import { boundedFile } from './file-read.js';
6
+ import { validateUnionReference } from './union-staging.js';
7
+ import {validateWslReference,structuralWsl} from './wsl-proof.js';
6
8
 
7
9
  const NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
8
10
  const VERSION = /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?(?:\+[A-Za-z0-9.-]+)?$/;
@@ -21,15 +23,21 @@ export class IdentityStore {
21
23
  const info = await lstat(this.path);
22
24
  if (!info.isFile() || info.isSymbolicLink() || info.size > this.maxBytes) throw Error('identity-file-untrusted');
23
25
  const parsed = JSON.parse((await boundedFile(this.path, this.maxBytes)).toString('utf8'));
24
- if (parsed.schemaVersion !== 1 || !Array.isArray(parsed.installed) || !Array.isArray(parsed.recoveries)) throw Error('identity-format');
26
+ if (![1,2,3,4].includes(parsed.schemaVersion) || !Array.isArray(parsed.installed) || !Array.isArray(parsed.recoveries)) throw Error('identity-format');
25
27
  if (parsed.installed.length > this.maxPackages || parsed.recoveries.length > this.maxRecoveries) throw Error('identity-count-limit');
26
28
  for (const item of parsed.installed) this.validateInstalled(item);
27
29
  for (const item of parsed.recoveries) this.validateRecovery(item);
30
+ if (parsed.schemaVersion === 1 && parsed.recoveries.some(item=>['registry-spec','registry-migration'].includes(item.installMode))) throw Error('identity-format');
31
+ const references=[...parsed.installed,...parsed.recoveries.flatMap(value=>[value.previous,value.next])];
32
+ if(![3,4].includes(parsed.schemaVersion)&&references.some(item=>item?.runtimeGeneration?.kind==='union-dependency'))throw Error('identity-format');
33
+ if(parsed.schemaVersion!==4&&references.some(structuralWsl))throw Error('identity-format');
28
34
  this.installed = new Map(parsed.installed.map(item => [item.name, item]));
29
35
  this.recoveries = new Map(parsed.recoveries.map(item => [item.name, item]));
30
36
  } catch (error) { if (error.code !== 'ENOENT') this.warning = 'identity-read-failed'; }
31
37
  }
32
38
  validateArchive(value) {
39
+ if(value?.runtimeGeneration?.kind==='union-dependency'){validateUnionReference(value);return;}
40
+ if(structuralWsl(value)){validateWslReference(value);return;}
33
41
  if (!value || !NAME.test(value.name ?? '') || !VERSION.test(value.version ?? '') || value.origin !== PUBLIC_REGISTRY
34
42
  || !KEY.test(value.archiveKey ?? '') || !SHA.test(value.sha256 ?? '') || !SHA.test(value.originalSha256 ?? '')
35
43
  || typeof value.integrity !== 'string' || !value.integrity.startsWith('sha512-')) throw Error('identity-archive-invalid');
@@ -40,13 +48,24 @@ export class IdentityStore {
40
48
  if (!value || !NAME.test(value.name ?? '') || typeof value.id !== 'string' || value.id.length > 128 || typeof value.failedBatchId !== 'string' || value.failedBatchId.length > 128
41
49
  || !VERSION.test(value.from ?? '') || !VERSION.test(value.to ?? '') || typeof value.enabled !== 'boolean'
42
50
  || !['prepared', 'failed', 'unknown'].includes(value.status) || typeof value.expectedFingerprint !== 'string' || value.expectedFingerprint.length > 200_000) throw Error('identity-recovery-invalid');
51
+ if (value.installMode !== undefined && !['archive','registry-spec','registry-migration','union-generation'].includes(value.installMode)) throw Error('identity-recovery-mode-invalid');
52
+ if(value.registry!==undefined&&!approvedPublicRegistry(value.registry))throw Error('identity-recovery-mode-invalid');
53
+ if(value.dependencyGraph!==undefined&&(!SHA.test(value.dependencyGraph.digest??'')||!Array.isArray(value.dependencyGraph.packages)||value.dependencyGraph.packages.length>64||!Array.isArray(value.dependencyGraph.edges)||value.dependencyGraph.edges.length>256))throw Error('identity-recovery-mode-invalid');
54
+ if (value.dispatchStarted !== undefined && typeof value.dispatchStarted !== 'boolean') throw Error('identity-recovery-mode-invalid');
55
+ if (value.installMode === 'registry-spec' && (value.previous.runtimeGeneration || value.next.runtimeGeneration)) throw Error('identity-recovery-mode-invalid');
56
+ if(value.unionOutcomeUnknown!==undefined&&typeof value.unionOutcomeUnknown!=='boolean')throw Error('identity-recovery-mode-invalid');
57
+ if(value.installMode==='union-generation'&&(value.name!=='dsh-union-search'||value.previous?.runtimeGeneration?.kind!=='union-dependency'||value.next?.runtimeGeneration?.kind!=='union-dependency'))throw Error('identity-recovery-mode-invalid');
58
+ if(value.installMode!=='union-generation'&&(value.previous?.runtimeGeneration?.kind==='union-dependency'||value.next?.runtimeGeneration?.kind==='union-dependency'))throw Error('identity-recovery-mode-invalid');
43
59
  this.validateArchive(value.previous); this.validateArchive(value.next);
44
60
  if (value.previous.name !== value.name || value.next.name !== value.name || value.previous.version !== value.from || value.next.version !== value.to) throw Error('identity-recovery-target');
45
61
  }
46
62
  document(installed = this.installed, recoveries = this.recoveries) {
47
- return { schemaVersion: 1, installed: [...installed.values()], recoveries: [...recoveries.values()] };
63
+ const union=[...installed.values(),...[...recoveries.values()].flatMap(value=>[value.previous,value.next])].some(value=>value?.runtimeGeneration?.kind==='union-dependency');
64
+ const wsl=[...installed.values(),...[...recoveries.values()].flatMap(value=>[value.previous,value.next])].some(structuralWsl);
65
+ return { schemaVersion: wsl ? 4 : union ? 3 : 2, installed: [...installed.values()], recoveries: [...recoveries.values()] };
48
66
  }
49
67
  async change(fn) {
68
+ if(this.warning)throw Error('identity-store-unverified');
50
69
  const work = this.chain.then(async () => {
51
70
  const installed = new Map(this.installed), recoveries = new Map(this.recoveries);
52
71
  fn(installed, recoveries);
package/lib/online.js CHANGED
@@ -1,30 +1,57 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { isGenerationSupported } from './wsl-policy.js';
3
- import { PUBLIC_REGISTRY, publicRegistry } from './source.js';
3
+ import { publicRegistry, approvedPublicRegistry, registryOrigin, readRegistryVersions } from './source.js';
4
+ import { dependencyPolicyReasons } from './dependency-policy.js';
4
5
 
5
- /** Query via the official manager; candidate versions are compatible nondeprecated stable bundles. */
6
- export async function scanUpdates(manager, summaries, { signal, concurrency = 3 } = {}) {
6
+ /** Version discovery is independent of installation admission and always scoped to the queried source. */
7
+ export function versionDiscovery(result) {
8
+ if (result?.status !== 'listed' || !Array.isArray(result.versions)) return { versionStatus: 'error', latestVersion: null, latestPublishedVersion: null };
9
+ const versions = result.versions;
10
+ const malformed = versions.some(value => !value || typeof value.version !== 'string' || value.version.length > 128 || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(value.version)
11
+ || !value.version.split(/[.+-]/).slice(0,3).map(Number).every(Number.isSafeInteger));
12
+ const stable = versions.filter(value => /^\d+\.\d+\.\d+$/.test(value?.version ?? '') && !value.prerelease)
13
+ .sort((a,b) => { const aa=a.version.split('.').map(Number),bb=b.version.split('.').map(Number); for (let i=0;i<3;i++) if(aa[i]!==bb[i]) return bb[i]-aa[i]; return 0; });
14
+ const offered = stable.find(value => value.bundle && !value.incompatible && !value.metadataIncomplete && !value.deprecated);
15
+ const incomplete = malformed || stable.some(value => value.metadataIncomplete) || result.queryReasons?.length > 0;
16
+ const versionStatus = incomplete ? 'unknown' : offered ? 'available' : result.omitted > 0 ? 'unknown' : stable.length ? 'no-compatible-version' : 'up-to-date';
17
+ return { versionStatus, latestVersion: offered?.version ?? null, latestPublishedVersion: stable[0]?.version ?? null };
18
+ }
19
+
20
+ /** Query via the official manager; discovery never grants permission to replace a package. */
21
+ export async function scanUpdates(manager, summaries, { signal, concurrency = 3, inspectWslCandidate } = {}) {
7
22
  const items = new Array(summaries.length);
8
23
  let next = 0;
9
24
  await Promise.all(Array.from({ length: Math.min(concurrency, Math.max(1, summaries.length)) }, async () => {
10
25
  while (next < summaries.length) {
11
26
  signal?.throwIfAborted();
12
27
  const index = next++; const bundle = summaries[index];
13
- const queryable = bundle.sourceKind === 'registry' || bundle.canUpdate;
14
- if (!queryable) { items[index] = { ...bundle, latestVersion: null, status: 'blocked', versionChecked:false }; continue; }
28
+ const queryable = bundle.sourceKind === 'registry' || bundle.canUpdate || bundle.unionGeneration;
29
+ if (!queryable) { items[index] = { ...bundle, canUpdate:false, latestVersion:null, latestPublishedVersion:null, status:'blocked', versionStatus:'not-checked', updateStatus:'blocked', versionChecked:false }; continue; }
15
30
  try {
16
- const result = await manager.listVersions(bundle.name, undefined, signal);
17
- if (result.status !== 'listed') { items[index] = { ...bundle, latestVersion: null, canUpdate: false, status: 'error', reasons: [result.problem ?? 'version-query-failed'] }; continue; }
18
- const offered = result.versions.find(version => !version.prerelease && !version.version.includes('-') && version.bundle && !version.incompatible && !version.deprecated);
19
- const sourceAllowed = publicRegistry(result.registry);
20
- const reasons = [...bundle.reasons ?? [], ...sourceAllowed ? [] : [result.registry == null ? 'registry-origin-unverified' : 'registry-origin-unsupported']];
21
- items[index] = { ...bundle, latestVersion: offered?.version ?? null, registry: sourceAllowed ? PUBLIC_REGISTRY : null,
22
- canUpdate: bundle.canUpdate && sourceAllowed && !!offered, versionChecked: true,
23
- status: !bundle.canUpdate || !sourceAllowed ? 'blocked' : offered ? 'available' : result.omitted > 0 ? 'unknown' : 'up-to-date',
24
- reasons: bundle.canUpdate && sourceAllowed && !offered ? (result.omitted > 0 ? ['compatible-version-window-incomplete'] : []) : reasons };
31
+ const result = await readRegistryVersions(manager, bundle.name, signal);
32
+ const discovery = versionDiscovery(result);
33
+ if (discovery.versionStatus === 'error') { items[index] = { ...bundle, ...discovery, canUpdate:false, updateStatus:'blocked', status:'error', versionChecked:false, reasons:[...new Set([...bundle.reasons ?? [], 'version-query-failed'])] }; continue; }
34
+ const sourceAllowed = approvedPublicRegistry(result.registry);
35
+ const reasons = [...bundle.reasons ?? [], ...result.queryReasons ?? [], ...sourceAllowed ? [] : [result.registry == null ? 'registry-origin-unverified' : 'registry-origin-unsupported']];
36
+ let wslPreflight;
37
+ if(bundle.name==='dsh-plugin-wsl-env'&&discovery.latestVersion){
38
+ if(!isGenerationSupported({name:bundle.name,version:discovery.latestVersion}))reasons.push('wsl-version-format-unsupported');
39
+ else if(sourceAllowed&&bundle.canUpdate){
40
+ if(typeof inspectWslCandidate!=='function')reasons.push('wsl-archive-preflight-unavailable');
41
+ else try{wslPreflight=await inspectWslCandidate(discovery.latestVersion,{origin:registryOrigin(result.registry),signal});if(wslPreflight?.status!=='passed'||wslPreflight.version!==discovery.latestVersion||!/^[a-f0-9]{64}$/.test(wslPreflight.originalSha256??''))throw Error('wsl-archive-preflight-failed');}
42
+ catch(error){if(signal?.aborted)throw error;const code=error?.code??error?.message;reasons.push(typeof code==='string'&&/^[a-z-]{1,100}$/.test(code)?code:'wsl-archive-preflight-failed');}
43
+ }
44
+ }
45
+ if (discovery.versionStatus === 'unknown') reasons.push('version-metadata-incomplete');
46
+ const uniqueReasons = [...new Set(reasons)];
47
+ const canUpdate = bundle.canUpdate && sourceAllowed && uniqueReasons.length === 0 && discovery.versionStatus === 'available';
48
+ const updateStatus = canUpdate ? 'available' : uniqueReasons.length || !bundle.canUpdate ? 'blocked' : 'no-update';
49
+ items[index] = { ...bundle, ...discovery, registry:registryOrigin(result.registry), canUpdate, versionChecked:true, updateStatus,
50
+ status:updateStatus === 'blocked' ? 'blocked' : discovery.versionStatus, reasons:uniqueReasons, ...(wslPreflight?{wslPreflight}: {}) };
25
51
  } catch (error) {
26
52
  if (signal?.aborted) throw error;
27
- items[index] = { ...bundle, latestVersion: null, canUpdate: false, status: 'error', reasons: ['version-query-failed'] };
53
+ items[index] = { ...bundle, latestVersion:null, latestPublishedVersion:null, canUpdate:false, status:'error', versionStatus:'error', updateStatus:'blocked', versionChecked:false,
54
+ reasons:[...new Set([...bundle.reasons ?? [], 'version-query-failed'])] };
28
55
  }
29
56
  }
30
57
  }));
@@ -36,9 +63,8 @@ export function onlineSafety(bundle, manifest) {
36
63
  const reasons = [];
37
64
  const dependencies = { ...manifest?.dependencies, ...manifest?.optionalDependencies };
38
65
  const wslGeneration = isGenerationSupported(manifest);
39
- if (bundle.name === 'dsh-plugin-wsl-env' && !wslGeneration) reasons.push('wsl-version-not-yet-verified');
40
- if (Object.keys(dependencies).length) reasons.push('dependency-graph-update-requires-separate-review');
41
- if (Object.keys(dependencies).some(name => name.startsWith('@deepseek-ai/') || name === 'dsh-plugin-update-doctor')) reasons.push('host-runtime-dependencies');
66
+ if (bundle.name === 'dsh-plugin-wsl-env' && !wslGeneration) reasons.push('wsl-version-format-unsupported');
67
+ reasons.push(...dependencyPolicyReasons(manifest ?? {}));
42
68
  if (Object.keys(dependencies).some(name => /(?:node-pty|koffi|ffi-napi|better-sqlite3|electron|sharp)/.test(name))) reasons.push('native-or-shared-runtime');
43
69
  if (!wslGeneration && (bundle.overrides ?? []).some(id => /^(?:subprocess|fs-sandbox|directory-picker|agent-loop|hmr|plugin-manager|storage|session|tool-working-directory)$/.test(id))) reasons.push('core-service-takeover');
44
70
  if (bundle.name === 'dsh-plugin-update-doctor') reasons.push('self-update-blocked');
@@ -4,7 +4,7 @@ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
4
  import { parseDocument } from 'yaml';
5
5
  import { archiveEntries } from './generation.js';
6
6
  import { boundedFile } from './file-read.js';
7
- import { PUBLIC_REGISTRY, publicRegistry } from './source.js';
7
+ import { PUBLIC_REGISTRY, PUBLIC_MIRROR, publicRegistry, approvedPublicRegistry, registryOrigin } from './source.js';
8
8
 
9
9
  export const SELF_UPDATE_PACKAGE = 'dsh-plugin-update-doctor';
10
10
  export const SELF_UPDATE_YAML_VERSION = '2.9.1';
@@ -131,12 +131,26 @@ export function inspectSelfFiles(files, { version, role = 'next', resolvedYamlVe
131
131
  return { manifest, files };
132
132
  }
133
133
 
134
- /** Ensure the official Host cannot fall through to a mirror/private registry during handoff. */
134
+ /** The official path retains its strict no-fallback policy. The fixed mirror path
135
+ * is separate and allows only already-configured, known public npm/mirror sources.
136
+ * Returning normalized public facts permits confirmation to bind the entire plan.
137
+ */
135
138
  export function verifySelfRegistryPlan(registries, queryRegistry) {
136
- required(publicRegistry(queryRegistry), 'self-query-origin-unverified');
137
- required(plain(registries) && Array.isArray(registries.fallbackRegistries) && registries.fallbackRegistries.length === 0
138
- && (registries.registry === null ? publicRegistry(registries.resolved) : publicRegistry(registries.registry))
139
- && (registries.resolved == null || publicRegistry(registries.resolved)), 'self-host-registry-plan-unsupported');
139
+ const query = registryOrigin(queryRegistry);
140
+ required(approvedPublicRegistry(query), 'self-query-origin-unverified');
141
+ if (query !== PUBLIC_MIRROR) {
142
+ required(plain(registries) && Array.isArray(registries.fallbackRegistries) && registries.fallbackRegistries.length === 0
143
+ && (registries.registry === null ? publicRegistry(registries.resolved) : publicRegistry(registries.registry))
144
+ && (registries.resolved == null || publicRegistry(registries.resolved)), 'self-host-registry-plan-unsupported');
145
+ return { queryRegistry: PUBLIC_REGISTRY, registry: registries.registry === null ? null : PUBLIC_REGISTRY,
146
+ resolved: registries.resolved == null ? null : PUBLIC_REGISTRY, fallbackRegistries: [] };
147
+ }
148
+ required(plain(registries) && Array.isArray(registries.fallbackRegistries) && registries.fallbackRegistries.length <= 8
149
+ && approvedPublicRegistry(registries.resolved)
150
+ && (registries.registry === null || approvedPublicRegistry(registries.registry))
151
+ && registries.fallbackRegistries.every(approvedPublicRegistry), 'self-host-registry-plan-unsupported');
152
+ return { queryRegistry: PUBLIC_MIRROR, registry: registries.registry === null ? null : registryOrigin(registries.registry),
153
+ resolved: registryOrigin(registries.resolved), fallbackRegistries: registries.fallbackRegistries.map(registryOrigin) };
140
154
  }
141
155
  function metadataIdentity(metadata, version, inspected) {
142
156
  required(metadata.name === SELF_UPDATE_PACKAGE && metadata.version === version, 'self-registry-identity-mismatch');
@@ -203,43 +217,63 @@ export async function verifyCurrentFiles(currentDirectory, files) {
203
217
  }
204
218
  }
205
219
 
206
- /** Public npm byte preflight only: official updateBundle still installs/restores by registry spec, not these bytes. */
220
+ /** Fixed official/mirror archive preflight only: the Host still installs by registry
221
+ * spec. Mirror bytes must independently equal canonical official archive digests. */
207
222
  export class SelfUpdatePreflight {
208
223
  constructor({ fetcher = fetch, compatibility, helperSha256 = SELF_UPDATE_HELPER_SHA256 } = {}) {
209
224
  Object.assign(this, { fetcher, compatibility, helperSha256 });
210
225
  }
211
- async fetchArchive(version, role, resolvedYamlVersion, signal) {
212
- const options = { signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(90_000)]) : AbortSignal.timeout(90_000), redirect: 'error' };
226
+ async fetchArchive(version, role, resolvedYamlVersion, signal, registry = PUBLIC_REGISTRY) {
227
+ const source = registryOrigin(registry);
228
+ required(approvedPublicRegistry(source) && VERSION.test(version ?? ''), 'self-query-origin-unverified');
229
+ const options = { signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(90_000)]) : AbortSignal.timeout(90_000), redirect: 'error', credentials: 'omit' };
213
230
  options.signal.throwIfAborted();
214
- const metadataResponse = await this.fetcher(`${PUBLIC_REGISTRY}/${SELF_UPDATE_PACKAGE}/${version}`, options);
215
- required(metadataResponse.ok, 'self-registry-metadata-unavailable');
216
- const metadata = json(await body(metadataResponse, MAX_METADATA), 'self-registry-metadata-invalid');
217
- required(metadata.name === SELF_UPDATE_PACKAGE && metadata.version === version, 'self-registry-identity-mismatch');
218
- let url;
219
- try { url = new URL(metadata.dist?.tarball); } catch { refuse('self-tarball-origin-unsupported'); }
220
- required(url.protocol === 'https:' && url.origin === PUBLIC_REGISTRY && !url.username && !url.password && !url.search && !url.hash
221
- && url.pathname === `/${SELF_UPDATE_PACKAGE}/-/${SELF_UPDATE_PACKAGE}-${version}.tgz`, 'self-tarball-origin-unsupported');
222
- const response = await this.fetcher(url, options); required(response.ok, 'self-archive-unavailable');
223
- const bytes = await body(response, MAX_ARCHIVE); verifyIntegrity(bytes, metadata.dist?.integrity);
224
- const inspected = inspectSelfArchive(bytes, { version, role, resolvedYamlVersion, compatibility: this.compatibility, helperSha256: this.helperSha256 });
225
- metadataIdentity(metadata, version, inspected);
226
- return { ...inspected, integrity: metadata.dist.integrity };
231
+ const read = async origin => {
232
+ const metadataURL = `${origin}/${SELF_UPDATE_PACKAGE}/${version}`;
233
+ const metadataResponse = await this.fetcher(metadataURL, options);
234
+ required(metadataResponse.ok, 'self-registry-metadata-unavailable');
235
+ required(!metadataResponse.url || metadataResponse.url === metadataURL, 'self-tarball-origin-unsupported');
236
+ const metadata = json(await body(metadataResponse, MAX_METADATA), 'self-registry-metadata-invalid');
237
+ required(metadata.name === SELF_UPDATE_PACKAGE && metadata.version === version, 'self-registry-identity-mismatch');
238
+ let url;
239
+ try { url = new URL(metadata.dist?.tarball); } catch { refuse('self-tarball-origin-unsupported'); }
240
+ required(url.protocol === 'https:' && (url.origin === origin || origin === PUBLIC_MIRROR && url.origin === PUBLIC_REGISTRY)
241
+ && !url.username && !url.password && !url.search && !url.hash
242
+ && url.pathname === `/${SELF_UPDATE_PACKAGE}/-/${SELF_UPDATE_PACKAGE}-${version}.tgz`, 'self-tarball-origin-unsupported');
243
+ const response = await this.fetcher(url, options); required(response.ok, 'self-archive-unavailable');
244
+ required(!response.url || response.url === url.href, 'self-tarball-origin-unsupported');
245
+ const bytes = await body(response, MAX_ARCHIVE); verifyIntegrity(bytes, metadata.dist?.integrity);
246
+ const inspected = inspectSelfArchive(bytes, { version, role, resolvedYamlVersion, compatibility: this.compatibility, helperSha256: this.helperSha256 });
247
+ metadataIdentity(metadata, version, inspected);
248
+ return { ...inspected, integrity: metadata.dist.integrity, canonicalIntegrity: 'sha512-' + createHash('sha512').update(bytes).digest('base64') };
249
+ };
250
+ const downloaded = await read(source);
251
+ if (source === PUBLIC_MIRROR) {
252
+ const canonical = await read(PUBLIC_REGISTRY);
253
+ required(downloaded.sha256 === canonical.sha256 && downloaded.canonicalIntegrity === canonical.canonicalIntegrity,
254
+ 'self-public-mirror-archive-mismatch');
255
+ return { ...downloaded, integrity: canonical.canonicalIntegrity };
256
+ }
257
+ const { canonicalIntegrity, ...official } = downloaded;
258
+ return official;
227
259
  }
228
260
  async check({ bundle, currentDirectory, targetVersion, resolvedYamlVersion, registries, queryRegistry, signal } = {}) {
229
261
  required(bundle?.name === SELF_UPDATE_PACKAGE && bundle.update === 'registry' && bundle.installed === true && bundle.enabled === true
230
262
  && bundle.removable === true && bundle.availability === 'profile' && !bundle.readOnlyReason && !bundle.error, 'self-installed-source-unsupported');
231
263
  required(stableNewer(targetVersion, bundle.version), 'self-target-version-unsupported');
232
- verifySelfRegistryPlan(registries, queryRegistry);
264
+ const registry = registryOrigin(queryRegistry), publicMirror = registry === PUBLIC_MIRROR;
265
+ const hostRegistryPlan = verifySelfRegistryPlan(registries, queryRegistry);
233
266
  signal?.throwIfAborted();
234
- const previous = await this.fetchArchive(bundle.version, 'previous', resolvedYamlVersion, signal);
267
+ const previous = await this.fetchArchive(bundle.version, 'previous', resolvedYamlVersion, signal, registry);
235
268
  await verifyCurrentFiles(currentDirectory, previous.files);
236
- const next = await this.fetchArchive(targetVersion, 'next', resolvedYamlVersion, signal);
269
+ const next = await this.fetchArchive(targetVersion, 'next', resolvedYamlVersion, signal, registry);
237
270
  for (const key of ['exports', 'peerDependencies', 'engines']) required(equal(previous.manifest[key], next.manifest[key]), 'self-runtime-graph-changed');
238
271
  required(equal(previous.manifest.dsh.client, next.manifest.dsh.client), 'self-runtime-graph-changed');
239
272
  const publicArchive = value => ({ sha256: value.sha256, integrity: value.integrity, manifest: value.manifest,
240
273
  files: Object.fromEntries([...value.files].map(([path, bytes]) => [path, digest(bytes)])) });
241
274
  signal?.throwIfAborted();
242
- return { name: SELF_UPDATE_PACKAGE, from: bundle.version, to: targetVersion, registry: PUBLIC_REGISTRY, currentManifest: previous.manifest,
275
+ return { name: SELF_UPDATE_PACKAGE, from: bundle.version, to: targetVersion, registry, currentManifest: previous.manifest,
276
+ ...(publicMirror ? { sourceMode: 'public-mirror', publicMirror: true, hostRegistryPlan } : {}),
243
277
  previous: publicArchive(previous), next: publicArchive(next) };
244
278
  }
245
279
  /** Verify the recorded original resource hashes locally, independently of version labels and registry queries. */