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.
package/lib/source.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { relative, resolve, isAbsolute, sep } from 'node:path';
2
2
 
3
3
  export const PUBLIC_REGISTRY = 'https://registry.npmjs.org';
4
+ export const PUBLIC_MIRROR = 'https://registry.npmmirror.com';
5
+ export function approvedPublicRegistry(value) { const origin=registryOrigin(value);return origin===PUBLIC_REGISTRY||origin===PUBLIC_MIRROR; }
4
6
 
5
7
  /** Public npm only. A missing, private or mirror origin never silently becomes npm. */
6
8
  export function registryOrigin(value) {
@@ -12,6 +14,33 @@ export function registryOrigin(value) {
12
14
  }
13
15
  export function publicRegistry(value) { return registryOrigin(value) === PUBLIC_REGISTRY; }
14
16
 
17
+ /** Host null means pnpm's configured registry, not a missing or implicitly public origin.
18
+ * Resolve it only when the public before/after snapshots agree. Never expose raw registry plans.
19
+ */
20
+ export async function readRegistryVersions(manager, name, signal) {
21
+ const snapshot = async () => {
22
+ if (typeof manager.registries !== 'function') return null;
23
+ try { return await manager.registries(); }
24
+ catch (error) { if (signal?.aborted) throw error; return null; }
25
+ };
26
+ signal?.throwIfAborted();
27
+ const before = await snapshot();
28
+ signal?.throwIfAborted();
29
+ const answer = await manager.listVersions(name, undefined, signal);
30
+ signal?.throwIfAborted();
31
+ if (answer?.status !== 'listed') return { status:'refused', problem:['not-updatable','not-found','network','unknown'].includes(answer?.problem) ? answer.problem : 'unknown' };
32
+ let registry = registryOrigin(answer.registry), queryReasons = [];
33
+ if (answer.registry === null) {
34
+ const after = await snapshot();
35
+ signal?.throwIfAborted();
36
+ const first = registryOrigin(before?.resolved), last = registryOrigin(after?.resolved);
37
+ if (first && first === last) registry = first;
38
+ else queryReasons = [first && last && first !== last ? 'registry-origin-changed' : 'registry-origin-unverified'];
39
+ }
40
+ if (!registry && !queryReasons.length) queryReasons = ['registry-origin-unverified'];
41
+ return { status:'listed', installed:answer.installed, versions:answer.versions, omitted:answer.omitted, registry, queryReasons };
42
+ }
43
+
15
44
  /** Store package-owned archive references relative to the staging root, not user paths. */
16
45
  export function archiveKey(root, filename) {
17
46
  if (typeof filename !== 'string') return null;
package/lib/staging.js CHANGED
@@ -4,8 +4,10 @@ import { join, basename, dirname, resolve } from 'node:path';
4
4
  import { gunzipSync } from 'node:zlib';
5
5
  import { inspectPatches } from './patch-safety.js';
6
6
  import { archiveEntries, generationArchive } from './generation.js';
7
- import { isGenerationSupported, inspectWslPatches } from './wsl-policy.js';
8
- import { PUBLIC_REGISTRY, registryOrigin, archiveKey, archivePath } from './source.js';
7
+ import { isGenerationSupported, inspectWslPatches, inspectWslArchivePolicy, WSL_NAME, WSL_LEGACY_ORIGINALS } from './wsl-policy.js';
8
+ import { structuralWsl, annotateWslStage, preserveWslProofPair, verifyWslProofInventory } from './wsl-proof.js';
9
+ import { PUBLIC_REGISTRY, PUBLIC_MIRROR, approvedPublicRegistry, registryOrigin, archiveKey, archivePath } from './source.js';
10
+ import { dependencyPolicyReasons } from './dependency-policy.js';
9
11
  import { boundedFile } from './file-read.js';
10
12
 
11
13
  const MAX_ARCHIVE = 64 * 1024 * 1024;
@@ -14,19 +16,42 @@ const abortSignal = signal => signal ? AbortSignal.any([signal, AbortSignal.time
14
16
 
15
17
  /** Stage registry bytes before touching the installed version. Never executes staged code. */
16
18
  export class RegistryStager {
17
- constructor(root, { fetcher = fetch, registry = 'https://registry.npmjs.org', compatibility = () => undefined } = {}) { this.root = root; this.fetcher = fetcher; this.registry = registry; this.compatibility = compatibility; }
19
+ constructor(root, { fetcher = fetch, registry = 'https://registry.npmjs.org', compatibility = () => undefined } = {}) { this.root = root; this.fetcher = fetcher; this.registry = registry; this.compatibility = compatibility; this.verifiedWslOriginals=new Map(); }
18
20
  async listVersions(name, current, signal) {
19
21
  if (!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(name)) throw new Error('invalid-registry-package');
20
- const response = await this.fetcher(new URL(encodeURIComponent(name), this.registry + '/'), { signal: abortSignal(signal), redirect: 'error', headers: { accept: 'application/vnd.npm.install-v1+json' } });
22
+ if (registryOrigin(this.registry) !== PUBLIC_REGISTRY) throw new Error('registry-origin-unsupported');
23
+ const parts = value => /^\d+\.\d+\.\d+$/.test(value ?? '') ? value.split('.').map(Number) : [];
24
+ const currentParts = parts(current);
25
+ if (currentParts.length !== 3 || !currentParts.every(Number.isSafeInteger)) throw new Error('invalid-installed-version');
26
+ signal?.throwIfAborted();
27
+ const response = await this.fetcher(new URL(encodeURIComponent(name), PUBLIC_REGISTRY + '/'), {
28
+ signal: abortSignal(signal), redirect: 'error', credentials: 'omit', headers: { accept: 'application/json' },
29
+ });
21
30
  if (!response.ok) throw new Error('registry-versions-unavailable');
22
31
  const data = JSON.parse((await boundedBody(response, 10 * 1024 * 1024)).toString('utf8'));
23
- const compare = (a,b) => { const aa=a.split('.').map(Number),bb=b.split('.').map(Number); for(let i=0;i<3;i++) if(aa[i]!==bb[i]) return aa[i]-bb[i]; return 0; };
24
- const versions = Object.values(data.versions ?? {}).filter(manifest => /^\d+\.\d+\.\d+$/.test(manifest.version) && compare(manifest.version,current)>0 && manifest.dsh?.bundle?.patch)
25
- .sort((a,b)=>compare(b.version,a.version)).slice(0,20).map(manifest => ({ version:manifest.version, bundle:true, prerelease:false, deprecated:manifest.deprecated, incompatible:this.compatibility(manifest) }));
26
- return { status:'listed', installed:current, versions, registry:this.registry };
32
+ if (!data || data.name !== name || !data.versions || typeof data.versions !== 'object' || Array.isArray(data.versions)
33
+ || !Object.hasOwn(data.versions,current)) throw new Error('registry-versions-invalid');
34
+ const compare = (a,b) => { const aa=parts(a),bb=parts(b); for(let i=0;i<3;i++) if(aa[i]!==bb[i]) return aa[i]-bb[i]; return 0; };
35
+ const newer = [];
36
+ for (const [version, manifest] of Object.entries(data.versions)) {
37
+ const numbers = parts(version);
38
+ if (!numbers.length) continue;
39
+ if (!numbers.every(Number.isSafeInteger) || !manifest || typeof manifest !== 'object' || Array.isArray(manifest)
40
+ || manifest.name !== name || manifest.version !== version) throw new Error('registry-version-identity-invalid');
41
+ if (compare(version,current) > 0) newer.push(manifest);
42
+ }
43
+ newer.sort((a,b)=>compare(b.version,a.version));
44
+ const versions = newer.slice(0,20).map(manifest => {
45
+ const patch = manifest.dsh?.bundle?.patch;
46
+ const bundle = typeof patch === 'string' && !!patch || Array.isArray(patch) && patch.length > 0 && patch.every(value => typeof value === 'string' && !!value);
47
+ return { version:manifest.version, bundle, prerelease:false, deprecated:manifest.deprecated,
48
+ incompatible:this.compatibility(manifest), metadataIncomplete: !bundle };
49
+ });
50
+ // Missing custom metadata cannot turn a visible newer version into "up to date".
51
+ return { status:'listed', installed:current, versions, omitted:newer.length-versions.length, registry:PUBLIC_REGISTRY };
27
52
  }
28
- async stage(name, version, { signal, origin = PUBLIC_REGISTRY } = {}) {
29
- if (origin !== PUBLIC_REGISTRY || registryOrigin(this.registry) !== PUBLIC_REGISTRY) throw new Error('registry-origin-unsupported');
53
+ async stage(name, version, { signal, origin = PUBLIC_REGISTRY, inspectOnly = false } = {}) {
54
+ if (!approvedPublicRegistry(origin) || registryOrigin(this.registry) !== PUBLIC_REGISTRY) throw new Error('registry-origin-unsupported');
30
55
  if (!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(name) || !/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?(?:\+[A-Za-z0-9.-]+)?$/.test(version)) throw new Error('invalid-staging-target');
31
56
  const url = new URL(encodeURIComponent(name) + '/' + encodeURIComponent(version), this.registry.endsWith('/') ? this.registry : this.registry + '/');
32
57
  if (url.protocol !== 'https:') throw new Error('insecure-registry');
@@ -37,7 +62,8 @@ export class RegistryStager {
37
62
  if (manifest.name !== name || manifest.version !== version || !manifest.dsh?.bundle?.patch) throw new Error('unexpected-staged-package');
38
63
  const tarball = new URL(manifest.dist?.tarball ?? '');
39
64
  // Only same-registry HTTPS resources; do not forward cookies or discover private URLs.
40
- if (tarball.protocol !== 'https:' || tarball.origin !== url.origin || tarball.username || tarball.password) throw new Error('untrusted-tarball-origin');
65
+ if (tarball.protocol !== 'https:' || tarball.origin !== url.origin || tarball.username || tarball.password || tarball.search || tarball.hash
66
+ || tarball.pathname!==`/${name}/-/${name.split('/').at(-1)}-${version}.tgz`) throw new Error('untrusted-tarball-origin');
41
67
  const fetched = await this.fetcher(tarball, { signal: abortSignal(signal), redirect: 'error' });
42
68
  if (!fetched.ok) throw new Error('archive-unavailable');
43
69
  const bytes = await boundedBody(fetched, MAX_ARCHIVE);
@@ -51,12 +77,22 @@ export class RegistryStager {
51
77
  contents={manifest:JSON.parse(manifestEntry.bytes.toString('utf8')),files:new Map(entries.map(entry=>[entry.name,entry.bytes]))};
52
78
  } else contents = readPackedContents(bytes);
53
79
  const packed = contents.manifest;
54
- if (generationAllowed && !isGenerationSupported(packed)) throw new Error('wsl-version-not-yet-verified');
55
- if (generationAllowed) {
56
- const knownDigests={'0.24.0':'1d03208d3e58596d155b052c8a0e9eab7a539ac45def89ad53052fa1746104b7','0.26.2':'0761e085453faa1b32ef8b44e8099bc938b62662b11b74e23f7946f4ef75fe98'};
57
- if(knownDigests[version]!==originalSha256) throw new Error('wsl-archive-requires-new-review');
58
- }
80
+ if (generationAllowed && !isGenerationSupported(packed)) throw new Error('wsl-version-format-unsupported');
81
+ if (generationAllowed && WSL_LEGACY_ORIGINALS[version] && WSL_LEGACY_ORIGINALS[version]!==originalSha256) throw new Error('wsl-legacy-original-changed');
59
82
  if (this.compatibility(packed)) throw new Error('staged-version-incompatible');
83
+ if (origin === PUBLIC_MIRROR) {
84
+ const mirroredMetadata=await this.fetcher(`${PUBLIC_MIRROR}/${encodeURIComponent(name)}/${encodeURIComponent(version)}`,{signal:abortSignal(signal),redirect:'error',credentials:'omit'});
85
+ if(!mirroredMetadata.ok)throw new Error('mirror-version-unavailable');
86
+ const mirrorManifest=JSON.parse((await boundedBody(mirroredMetadata,2*1024*1024)).toString('utf8'));
87
+ if(mirrorManifest.name!==name||mirrorManifest.version!==version)throw new Error('mirror-version-identity-mismatch');
88
+ 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;
89
+ for(const key of ['name','version','type','main','exports','imports','dsh','engines','dependencies','optionalDependencies','peerDependencies','peerDependenciesMeta','scripts','overrides','resolutions','pnpm','bundledDependencies','bundleDependencies','bin','gypfile','packageManager','os','cpu','libc'])if(JSON.stringify(canonical(mirrorManifest[key]))!==JSON.stringify(canonical(packed[key])))throw new Error('mirror-runtime-metadata-mismatch');
90
+ const mirrorURL=new URL(mirrorManifest.dist?.tarball??'');
91
+ if(!approvedPublicRegistry(mirrorURL.origin)||mirrorURL.username||mirrorURL.password||mirrorURL.search||mirrorURL.hash||mirrorURL.pathname!==`/${name}/-/${name.split('/').at(-1)}-${version}.tgz`)throw new Error('mirror-tarball-origin-unsupported');
92
+ const mirrorResponse=await this.fetcher(mirrorURL,{signal:abortSignal(signal),redirect:'error',credentials:'omit'});if(!mirrorResponse.ok)throw new Error('mirror-archive-unavailable');
93
+ const mirrorBytes=await boundedBody(mirrorResponse,MAX_ARCHIVE);verifyIntegrity(mirrorBytes,mirrorManifest.dist.integrity);
94
+ if(createHash('sha256').update(mirrorBytes).digest('hex')!==originalSha256)throw new Error('mirror-archive-mismatch');
95
+ }
60
96
  if (packed.dsh.bundle.platforms && !packed.dsh.bundle.platforms.includes(process.platform)) throw new Error('staged-platform-unsupported');
61
97
  const patches = typeof packed.dsh?.bundle?.patch === 'string' ? [packed.dsh.bundle.patch] : packed.dsh?.bundle?.patch;
62
98
  if (!Array.isArray(patches) || !patches.length || patches.length > 8) throw new Error('invalid-bundle-patch-list');
@@ -69,31 +105,92 @@ export class RegistryStager {
69
105
  const footprint = generationAllowed ? inspectWslPatches(patchTexts,packed) : { rows:inspectPatches(patchTexts,name), overrides:[] };
70
106
  const rows = footprint.rows;
71
107
  if (packed.name !== name || packed.version !== version || !packed.dsh?.bundle?.patch) throw new Error('archive-manifest-mismatch');
72
- if (Object.keys({ ...packed.dependencies, ...packed.optionalDependencies, ...packed.bundledDependencies }).length) throw new Error('dependency-graph-update-requires-separate-review');
108
+ const dependencyReasons=dependencyPolicyReasons(packed);if(dependencyReasons.length)throw new Error(dependencyReasons[0]);
73
109
  const scripts = packed.scripts ?? {};
74
110
  if (['preinstall', 'install', 'postinstall', 'prepare'].some(key => typeof scripts[key] === 'string' && scripts[key].trim())) throw new Error('package-install-scripts-require-separate-review');
111
+ if(generationAllowed)inspectWslArchivePolicy(packed,archiveEntries(bytes));
112
+ if(inspectOnly){if(!generationAllowed)throw Error('archive-inspection-not-supported');return {name,version,originalSha256,integrity:manifest.dist.integrity,rows,overrides:footprint.overrides,contractDigest:footprint.contractDigest,origin:PUBLIC_REGISTRY};}
75
113
  const directory = join(this.root, randomUUID()); await mkdir(directory, { recursive: true, mode: 0o700 });
76
114
  const sourceArchivePath=join(directory,'source-package.tgz');await writeFile(sourceArchivePath,bytes,{mode:0o600});
77
115
  const transformed=generationAllowed ? generationArchive(bytes) : null;
78
116
  const installBytes=transformed?.bytes ?? bytes;
79
117
  const archivePath = join(directory, 'package.tgz'); await writeFile(archivePath, installBytes, { mode: 0o600 });
80
- return { name, version, origin: PUBLIC_REGISTRY, archivePath, sourceArchivePath, manifest: packed, rows, overrides:footprint.overrides,
118
+ const staged={ name, version, origin: PUBLIC_REGISTRY, queryRegistry:registryOrigin(origin), archivePath, sourceArchivePath, manifest: packed, rows, overrides:footprint.overrides,
81
119
  runtimeGeneration: transformed ? { generation:transformed.generation, moduleAliases:transformed.moduleAliases, originalRuntimeBytesPreserved:true } : null,
82
120
  originalSha256, sha256: createHash('sha256').update(installBytes).digest('hex'), integrity: manifest.dist.integrity, size: installBytes.length };
121
+ if(generationAllowed)await annotateWslStage(this,staged);return staged;
83
122
  }
84
- async preserveGenerationPair(next, previous) {
123
+ async inspectWslCandidate(version,{signal,origin=PUBLIC_REGISTRY}={}) {
124
+ const inspected=await this.stage(WSL_NAME,version,{signal,origin,inspectOnly:true});
125
+ return {status:'passed',version,originalSha256:inspected.originalSha256,integrity:inspected.integrity,contractDigest:inspected.contractDigest,source:'canonical-public-archive-and-declarative-contract',runtimeInstallationTested:false};
126
+ }
127
+ async preserveGenerationPair(next, previous, deployedReference) {
128
+ if(structuralWsl(next)&&structuralWsl(previous))return preserveWslProofPair(this,next,previous,deployedReference);
85
129
  if(!next.runtimeGeneration || !previous.runtimeGeneration)return;
86
- const latest=await boundedFile(next.sourceArchivePath, MAX_ARCHIVE), legacy=await boundedFile(previous.sourceArchivePath, MAX_ARCHIVE);
87
- if(createHash('sha256').update(latest).digest('hex')!==next.originalSha256 || createHash('sha256').update(legacy).digest('hex')!==previous.originalSha256)throw new Error('verified-source-archive-changed');
130
+ const latest=await boundedFile(next.sourceArchivePath,MAX_ARCHIVE),legacy=await boundedFile(previous.sourceArchivePath,MAX_ARCHIVE);
131
+ if(createHash('sha256').update(latest).digest('hex')!==next.originalSha256||createHash('sha256').update(legacy).digest('hex')!==previous.originalSha256)throw new Error('verified-source-archive-changed');
88
132
  verifyIntegrity(latest,next.integrity);verifyIntegrity(legacy,previous.integrity);
89
- for(const [staged,source,retained] of [[next,latest,[legacy]],[previous,legacy,[latest]]]){
90
- const transformed=generationArchive(source,{legacyOriginal:legacy,retainedOriginal:retained});
91
- await writeFile(staged.archivePath,transformed.bytes,{mode:0o600});
92
- staged.sha256=createHash('sha256').update(transformed.bytes).digest('hex');
93
- staged.runtimeGeneration={generation:transformed.generation,moduleAliases:transformed.moduleAliases,originalRuntimeBytesPreserved:true,legacyRootResourcesPreserved:true};
133
+ const originals=new Map([[next.originalSha256,latest],[previous.originalSha256,legacy]]);
134
+ let rootOriginal=legacy;
135
+ if(deployedReference){
136
+ const deployed=await this.reopen(deployedReference),installed=await boundedFile(deployed.archivePath,MAX_CONTENT);
137
+ const deployedEntries=new Map(archiveEntries(installed).map(entry=>[entry.name,entry.bytes]));
138
+ const reviewed={'0.24.0':'1d03208d3e58596d155b052c8a0e9eab7a539ac45def89ad53052fa1746104b7','0.26.2':'0761e085453faa1b32ef8b44e8099bc938b62662b11b74e23f7946f4ef75fe98','0.28.0':'c137376aba2b3973690ecef93baed9e4de79a22825ab5a50e92ae9ad2881e694'};
139
+ for(const [version,digest]of Object.entries(reviewed))if([...deployedEntries.keys()].some(path=>path.startsWith('package/g/'+digest.slice(0,12)+'/'))||version==='0.24.0'){
140
+ if(!originals.has(digest))originals.set(digest,await this.reviewedWslOriginal(version,digest));
141
+ }
142
+ const deployedManifest=JSON.parse(deployedEntries.get('package/package.json').toString('utf8'));
143
+ const patchPaths=new Set((Array.isArray(deployedManifest.dsh.bundle.patch)?deployedManifest.dsh.bundle.patch:[deployedManifest.dsh.bundle.patch]).map(path=>'package/'+path.replace(/^\.\//,'')));
144
+ const matches=[...originals.values()].filter(bytes=>archiveEntries(bytes).filter(entry=>entry.name!=='package/package.json'&&!patchPaths.has(entry.name)).every(entry=>deployedEntries.get(entry.name)?.equals(entry.bytes)));
145
+ if(!matches.length)throw Error('wsl-root-generation-unverified');rootOriginal=matches[0];
146
+ await this.verifyWslGenerationInventory(deployed.sourceArchivePath,deployedReference,installed);
147
+ }
148
+ for(const [staged,source]of [[next,latest],[previous,legacy]]){
149
+ const transformed=generationArchive(source,{legacyOriginal:rootOriginal,retainedOriginal:[...originals.values()]});
150
+ await writeFile(staged.archivePath,transformed.bytes,{mode:0o600});staged.sha256=createHash('sha256').update(transformed.bytes).digest('hex');
151
+ staged.runtimeGeneration={generation:transformed.generation,moduleAliases:transformed.moduleAliases,originalRuntimeBytesPreserved:true,legacyRootResourcesPreserved:true,
152
+ rootOriginalSha256:createHash('sha256').update(rootOriginal).digest('hex'),retainedOriginalSha256:[...originals.keys()].sort()};
94
153
  }
95
154
  }
155
+ async reviewedWslOriginal(version,digest) {
156
+ const cached=this.verifiedWslOriginals.get(digest);
157
+ if(cached&&createHash('sha256').update(cached).digest('hex')===digest)return Buffer.from(cached);
158
+ const fetched=await this.stage('dsh-plugin-wsl-env',version),bytes=await boundedFile(fetched.sourceArchivePath,MAX_ARCHIVE);
159
+ if(createHash('sha256').update(bytes).digest('hex')!==digest)throw Error('unverified-retained-wsl-original');return bytes;
160
+ }
161
+ async verifyWslGenerationInventory(sourcePath,reference,installed) {
162
+ if(structuralWsl(reference))return verifyWslProofInventory(this,sourcePath,reference,installed);
163
+ const source=await boundedFile(sourcePath,MAX_ARCHIVE),deployed=new Map(archiveEntries(installed).map(entry=>[entry.name,entry.bytes]));
164
+ // Always use the source belonging to this deployed reference, not a newer prepared source.
165
+ if(createHash('sha256').update(source).digest('hex')!==reference.originalSha256)throw Error('verified-source-archive-changed');
166
+ const reviewed={'0.24.0':'1d03208d3e58596d155b052c8a0e9eab7a539ac45def89ad53052fa1746104b7','0.26.2':'0761e085453faa1b32ef8b44e8099bc938b62662b11b74e23f7946f4ef75fe98','0.28.0':'c137376aba2b3973690ecef93baed9e4de79a22825ab5a50e92ae9ad2881e694'};
167
+ const originals=new Map([[createHash('sha256').update(source).digest('hex'),source]]),ids=new Set([...deployed.keys()].filter(path=>path.startsWith('package/g/')).map(path=>path.split('/')[2]));
168
+ for(const id of ids){const pair=Object.entries(reviewed).find(([,digest])=>digest.slice(0,12)===id);if(!pair)throw Error('unverified-retained-wsl-original');if(!originals.has(pair[1]))originals.set(pair[1],await this.reviewedWslOriginal(pair[0],pair[1]));}
169
+ if(!originals.has(reviewed['0.24.0']))originals.set(reviewed['0.24.0'],await this.reviewedWslOriginal('0.24.0',reviewed['0.24.0']));
170
+ const manifest=JSON.parse(deployed.get('package/package.json').toString('utf8')),patchPaths=new Set((Array.isArray(manifest.dsh.bundle.patch)?manifest.dsh.bundle.patch:[manifest.dsh.bundle.patch]).map(path=>'package/'+path.replace(/^\.\//,'')));
171
+ const legacy=[...originals.values()].find(bytes=>archiveEntries(bytes).filter(entry=>entry.name!=='package/package.json'&&!patchPaths.has(entry.name)).every(entry=>deployed.get(entry.name)?.equals(entry.bytes)));
172
+ if(!legacy)throw Error('wsl-root-generation-unverified');
173
+ const retained=[...originals].filter(([digest])=>ids.has(digest.slice(0,12))).map(([,bytes])=>bytes);
174
+ const transformed=generationArchive(source,{legacyOriginal:legacy,retainedOriginal:retained}),expected=new Map(archiveEntries(transformed.bytes).map(entry=>[entry.name,entry.bytes]));
175
+ 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;
176
+ const same=(path,left,right)=>path==='package/package.json'?JSON.stringify(canonical(JSON.parse(left.toString('utf8'))))===JSON.stringify(canonical(JSON.parse(right.toString('utf8')))):left.equals(right);
177
+ if(expected.size!==deployed.size||[...expected].some(([path,bytes])=>!deployed.get(path)||!same(path,bytes,deployed.get(path))))throw Error('retained-wsl-inventory-changed');
178
+ const rootSha=createHash('sha256').update(legacy).digest('hex'),retainedSha=retained.map(bytes=>createHash('sha256').update(bytes).digest('hex')).sort();
179
+ if(reference.runtimeGeneration?.rootOriginalSha256&&reference.runtimeGeneration.rootOriginalSha256!==rootSha)throw Error('identity-generation-changed');
180
+ if(reference.runtimeGeneration?.retainedOriginalSha256&&JSON.stringify(reference.runtimeGeneration.retainedOriginalSha256)!==JSON.stringify(retainedSha))throw Error('identity-generation-changed');
181
+ return {rootOriginalSha256:rootSha,retainedOriginalSha256:retainedSha};
182
+ }
183
+ async verifyInstalledArchive(reference,packageDirectory) {
184
+ const staged=await this.reopen(reference),bytes=await boundedFile(staged.archivePath,MAX_CONTENT),entries=archiveEntries(bytes);
185
+ const rootInfo=await lstat(packageDirectory);if(!rootInfo.isDirectory()||rootInfo.isSymbolicLink())throw Error('installed-original-unverified');
186
+ const root=await realpath(packageDirectory);
187
+ for(const entry of entries){let path=root;for(const part of entry.name.slice(8).split('/')){path=join(path,part);const info=await lstat(path);if(info.isSymbolicLink()||!info.isDirectory()&&!info.isFile())throw Error('installed-generation-unverified');}
188
+ if(!(await boundedFile(path,MAX_CONTENT)).equals(entry.bytes))throw Error('installed-generation-unverified');}
189
+ return {verified:true,files:entries.length};
190
+ }
96
191
  async verifyInstalledOriginal(staged, packageDirectory) {
192
+ const rootInfo=await lstat(packageDirectory);
193
+ if(!rootInfo.isDirectory()||rootInfo.isSymbolicLink())throw new Error('installed-original-unverified');
97
194
  const root = await realpath(packageDirectory);
98
195
  const entries = archiveEntries(await boundedFile(staged.sourceArchivePath, MAX_ARCHIVE));
99
196
  for (const entry of entries) {
@@ -118,7 +215,7 @@ export class RegistryStager {
118
215
  const bytes = await boundedFile(sourcePath, MAX_ARCHIVE), installed = await boundedFile(installedPath, MAX_CONTENT);
119
216
  const originalSha256 = createHash('sha256').update(bytes).digest('hex');
120
217
  if (name === 'dsh-plugin-wsl-env') {
121
- const known = { '0.24.0':'1d03208d3e58596d155b052c8a0e9eab7a539ac45def89ad53052fa1746104b7', '0.26.2':'0761e085453faa1b32ef8b44e8099bc938b62662b11b74e23f7946f4ef75fe98' };
218
+ const known = { '0.28.0':'c137376aba2b3973690ecef93baed9e4de79a22825ab5a50e92ae9ad2881e694', '0.24.0':'1d03208d3e58596d155b052c8a0e9eab7a539ac45def89ad53052fa1746104b7', '0.26.2':'0761e085453faa1b32ef8b44e8099bc938b62662b11b74e23f7946f4ef75fe98' };
122
219
  if (known[version] !== originalSha256 || expectedOriginalSha256 !== originalSha256) throw new Error('wsl-archive-requires-new-review');
123
220
  } else { if (!bytes.equals(installed)) throw new Error('source-identity-unverified'); readPackedContents(bytes); }
124
221
  const entries = archiveEntries(bytes), manifest = JSON.parse(entries.find(entry => entry.name === 'package/package.json').bytes.toString('utf8'));
@@ -173,14 +270,15 @@ export class RegistryStager {
173
270
  if (!wsl) { readPackedContents(source); if (reference.runtimeGeneration != null) throw new Error('identity-generation-changed'); }
174
271
  const footprint = wsl ? inspectWslPatches(texts, manifest) : { rows: inspectPatches(texts, manifest.name), overrides: [] };
175
272
  if (JSON.stringify(manifest) !== JSON.stringify(reference.manifest) || JSON.stringify(footprint.rows) !== JSON.stringify(reference.rows) || JSON.stringify(footprint.overrides) !== JSON.stringify(reference.overrides)) throw new Error('identity-metadata-changed');
176
- if (Object.keys({ ...manifest.dependencies, ...manifest.optionalDependencies, ...manifest.bundledDependencies }).length || ['preinstall', 'install', 'postinstall', 'prepare'].some(key => manifest.scripts?.[key]?.trim())) throw new Error('staged-package-policy-changed');
273
+ if (dependencyPolicyReasons(manifest).length) throw new Error('staged-package-policy-changed');
177
274
  if (this.compatibility(manifest)) throw new Error('staged-version-incompatible');
178
275
  if (manifest.name !== reference.name || manifest.version !== reference.version) throw new Error('archive-manifest-mismatch');
179
276
  const install = await boundedFile(staged.archivePath, MAX_CONTENT);
180
277
  if (!wsl && !source.equals(install)) throw new Error('source-identity-unverified');
181
278
  if (wsl) {
182
- const verified = await this.adoptLegacy(reference.name, reference.version, staged.archivePath, reference.originalSha256);
183
- if (JSON.stringify(verified.runtimeGeneration?.moduleAliases) !== JSON.stringify(reference.runtimeGeneration?.moduleAliases) || verified.runtimeGeneration?.generation !== reference.runtimeGeneration?.generation) throw new Error('identity-generation-changed');
279
+ await this.verifyWslGenerationInventory(staged.sourceArchivePath,reference,install);
280
+ if(!structuralWsl(reference)){const verified = await this.adoptLegacy(reference.name, reference.version, staged.archivePath, reference.originalSha256);
281
+ if (JSON.stringify(verified.runtimeGeneration?.moduleAliases) !== JSON.stringify(reference.runtimeGeneration?.moduleAliases) || verified.runtimeGeneration?.generation !== reference.runtimeGeneration?.generation) throw new Error('identity-generation-changed');}
184
282
  }
185
283
  return staged;
186
284
  }