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,376 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { gzipSync, gunzipSync } from 'node:zlib';
3
+ import { lstat, realpath, opendir } from 'node:fs/promises';
4
+ import { dirname, join, relative, resolve, sep } from 'node:path';
5
+ import { boundedFile } from './file-read.js';
6
+ import { PUBLIC_REGISTRY } from './source.js';
7
+
8
+ /** This reader deliberately does not use generation.archiveEntries (its 2,000-file
9
+ * cap is too small). Nothing in this module extracts or executes archive code. */
10
+ export const UNION_LIMITS = Object.freeze({ compressed:64*1024*1024, archive:128*1024*1024,
11
+ files:18000, file:8*1024*1024, packages:64, dependencyFiles:6000,
12
+ directories:4000, dependencyBytes:64*1024*1024, edges:512, oldGenerations:5 });
13
+ export const UNION_RELEASE_HASHES = Object.freeze({
14
+ '0.10.24':'b1e412d69fb79de5b96de50268df640de27d01d0f89f41886ef3a16029cd0f47',
15
+ '0.10.25':'9de39d37a1594b10f3a074b7289232b29089d46fa18f674632f30ba1a24c2926',
16
+ });
17
+ export const unionHash = bytes => createHash('sha256').update(bytes).digest('hex');
18
+ export const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value==='object'
19
+ ? Object.fromEntries(Object.keys(value).sort().map(key=>[key,canonical(value[key])])) : value;
20
+ export const unionDigest = value => unionHash(Buffer.from(JSON.stringify(canonical(value))));
21
+ const fail = code => { throw Object.assign(Error(code),{code}); };
22
+ const check = (condition,code) => { if (!condition) fail(code); };
23
+ const cmp = (a,b) => a<b ? -1 : a>b ? 1 : 0;
24
+ const NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
25
+ const VERSION = /^\d+\.\d+\.\d+$/;
26
+ const HOST_SHARED = '@deepseek-ai/schemastery';
27
+ const NATIVE = /(?:\.(?:node|dll|exe|so|dylib)|(?:^|\/)binding\.gyp)$/i;
28
+ export const canAdmitUnion = (name,from,to) => name==='dsh-union-search' && Object.hasOwn(UNION_RELEASE_HASHES,from) && Object.hasOwn(UNION_RELEASE_HASHES,to);
29
+ export function unionDeadline(signal, milliseconds=120000) {
30
+ return signal ? AbortSignal.any([signal,AbortSignal.timeout(milliseconds)]) : AbortSignal.timeout(milliseconds);
31
+ }
32
+ export function safeWinArchivePath(name,{directory=false}={}) {
33
+ check(typeof name==='string' && Buffer.byteLength(name)<=1024 && name.normalize('NFC')===name,'union-unsafe-archive-path');
34
+ if (directory && name.endsWith('/')) name=name.slice(0,-1);
35
+ const parts=name.split('/');
36
+ check(parts[0]==='package' && (directory || parts.length>1) && parts.length<128,'union-unsafe-archive-path');
37
+ for (const part of parts) check(part && part!=='.' && part!=='..' && Buffer.byteLength(part)<=255
38
+ && !/[<>:"\\|?*\x00-\x1f\x7f]/.test(part) && !/[. ]$/.test(part)
39
+ && !/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part),'union-unsafe-archive-path');
40
+ return name.toLowerCase();
41
+ }
42
+ function pathSet() {
43
+ const files=new Set(), directories=new Set(), explicit=new Set();
44
+ return (name,directory=false) => {
45
+ const key=safeWinArchivePath(name,{directory});
46
+ check(!explicit.has(key),'union-duplicate-archive-path'); explicit.add(key);
47
+ if (directory) check(!files.has(key),'union-prefix-collision');
48
+ else check(!files.has(key) && !directories.has(key),'union-prefix-collision');
49
+ const parts=key.split('/');
50
+ for(let i=1;i<parts.length;i++) {
51
+ const parent=parts.slice(0,i).join('/'); check(!files.has(parent),'union-prefix-collision'); directories.add(parent);
52
+ }
53
+ (directory?directories:files).add(key);
54
+ };
55
+ }
56
+ function field(header,start,length) {
57
+ const value=header.subarray(start,start+length), zero=value.indexOf(0);
58
+ if(zero>=0) check(value.subarray(zero).every(b=>b===0),'union-invalid-tar-field');
59
+ try { return new TextDecoder('utf-8',{fatal:true}).decode(zero<0?value:value.subarray(0,zero)); }
60
+ catch { fail('union-invalid-tar-field'); }
61
+ }
62
+ function octal(header,start,length) {
63
+ const value=header.subarray(start,start+length).toString('ascii');
64
+ check(/^[ 0-7]+[\0 ]*$/.test(value),'union-invalid-tar-number');
65
+ const result=parseInt(value.replace(/\0/g,'').trim(),8);
66
+ check(Number.isSafeInteger(result) && result>=0,'union-invalid-tar-number'); return result;
67
+ }
68
+ export function inspectUnionArchive(compressed) {
69
+ check(Buffer.isBuffer(compressed) && compressed.length>0 && compressed.length<=UNION_LIMITS.compressed,'union-compressed-bound');
70
+ let data; try { data=gunzipSync(compressed,{maxOutputLength:UNION_LIMITS.archive}); } catch { fail('union-invalid-or-unbounded-gzip'); }
71
+ check(data.length<=UNION_LIMITS.archive && data.length%512===0,'union-archive-bound');
72
+ const entries=[],addPath=pathSet(); let offset=0,count=0,directoryCount=0;
73
+ while(offset+512<=data.length) {
74
+ const h=data.subarray(offset,offset+512); if(h.every(b=>b===0)) break;
75
+ const sum=[...h].reduce((s,b,i)=>s+(i>=148&&i<156?32:b),0);
76
+ check(octal(h,148,8)===sum,'union-invalid-tar-checksum');
77
+ const leaf=field(h,0,100),prefix=field(h,345,155),name=prefix?prefix+'/'+leaf:leaf;
78
+ const size=octal(h,124,12),mode=octal(h,100,8),type=h[156];
79
+ check([0,48,53].includes(type),'union-archive-links-or-extensions');
80
+ check(mode<=0o777 && size<=UNION_LIMITS.file && offset+512+size<=data.length,'union-invalid-tar-range');
81
+ check(++count<=UNION_LIMITS.files+UNION_LIMITS.directories,'union-archive-entry-bound');
82
+ check(!NATIVE.test(name),'union-native-resource'); addPath(name,type===53);
83
+ if(type===53) check(size===0 && ++directoryCount<=UNION_LIMITS.directories,'union-directory-content-or-bound');
84
+ else { check(entries.length<UNION_LIMITS.files,'union-archive-file-bound');
85
+ entries.push({name,bytes:Buffer.from(data.subarray(offset+512,offset+512+size)),mode:mode.toString(8)}); }
86
+ const next=offset+512+Math.ceil(size/512)*512;
87
+ check(next<=data.length && data.subarray(offset+512+size,next).every(b=>b===0),'union-invalid-tar-padding'); offset=next;
88
+ }
89
+ check(offset+1024<=data.length && data.subarray(offset).every(b=>b===0),'union-invalid-tar-terminator');
90
+ return entries;
91
+ }
92
+ export function packUnionArchive(entries) {
93
+ check(Array.isArray(entries) && entries.length<=UNION_LIMITS.files,'union-archive-file-bound');
94
+ const parts=[],addPath=pathSet(); let total=1024;
95
+ for(const entry of entries) {
96
+ addPath(entry.name); check(Buffer.isBuffer(entry.bytes) && entry.bytes.length<=UNION_LIMITS.file,'union-file-bound');
97
+ check(!NATIVE.test(entry.name),'union-native-resource');
98
+ total+=512+Math.ceil(entry.bytes.length/512)*512; check(total<=UNION_LIMITS.archive,'union-archive-bound');
99
+ const h=Buffer.alloc(512); let name=entry.name,prefix='';
100
+ if(Buffer.byteLength(name)>100) {
101
+ let cut=name.lastIndexOf('/');
102
+ while(cut>0 && (Buffer.byteLength(name.slice(cut+1))>100 || Buffer.byteLength(name.slice(0,cut))>155)) cut=name.lastIndexOf('/',cut-1);
103
+ check(cut>0,'union-tar-path-bound'); prefix=name.slice(0,cut);name=name.slice(cut+1);
104
+ }
105
+ const mode=entry.mode??'644'; check(/^[0-7]{1,3}$/.test(mode),'union-invalid-mode');
106
+ h.write(name,0,100);h.write(mode.padStart(7,'0')+'\0',100,8);h.write('0000000\0',108,8);h.write('0000000\0',116,8);
107
+ h.write(entry.bytes.length.toString(8).padStart(11,'0')+'\0',124,12);h.fill(32,148,156);h[156]=48;
108
+ h.write('ustar\0',257,6);h.write('00',263,2);if(prefix)h.write(prefix,345,155);
109
+ h.write([...h].reduce((a,b)=>a+b,0).toString(8).padStart(6,'0')+'\0 ',148,8);
110
+ parts.push(h,entry.bytes,Buffer.alloc((512-entry.bytes.length%512)%512));
111
+ }
112
+ const bytes=gzipSync(Buffer.concat([...parts,Buffer.alloc(1024)]));
113
+ check(bytes.length<=UNION_LIMITS.compressed,'union-compressed-bound'); return bytes;
114
+ }
115
+ export function unionManifest(entries) {
116
+ const item=entries.find(e=>e.name==='package/package.json'); check(item && item.bytes.length<=512*1024,'union-manifest-missing-or-bound');
117
+ let manifest;try { manifest=JSON.parse(item.bytes.toString('utf8')); } catch { fail('union-manifest-invalid'); }
118
+ check(manifest && typeof manifest==='object' && !Array.isArray(manifest),'union-manifest-invalid'); return manifest;
119
+ }
120
+ export function unionInventory(entries) {
121
+ return entries.map(e=>[e.name,unionHash(e.bytes),e.bytes.length]).sort((a,b)=>cmp(a[0],b[0]));
122
+ }
123
+ export function unionRangeMatches(version,range) {
124
+ if(!VERSION.test(version??'') || typeof range!=='string' || range.length>256) return false;
125
+ 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;};
126
+ if(!value.every(Number.isSafeInteger)) return false;
127
+ return range.split('||').some(branch=> {
128
+ const tokens=branch.trim().match(/(?:\^|~|>=|<=|>|<|=)?\s*(?:\d+(?:\.\d+|\.\*){0,2}|\*)/g);
129
+ if(!tokens || tokens.join('').replace(/\s/g,'')!==branch.replace(/\s/g,''))return false;
130
+ return tokens.every(token=> {
131
+ const m=/^(\^|~|>=|<=|>|<|=)?\s*(\d+(?:\.\d+|\.\*){0,2}|\*)$/.exec(token);if(!m)return false;
132
+ if(m[2]==='*')return !m[1]; const nums=m[2].split('.'),min=nums.map(x=>x==='*'?0:Number(x));
133
+ if(!min.every(Number.isSafeInteger) || m[1]&&(nums.length!==3||nums.includes('*')))return false;
134
+ while(min.length<3)min.push(0);const c=compare(value,min),op=m[1];
135
+ if(op==='>=')return c>=0;if(op==='>')return c>0;if(op==='<=')return c<=0;if(op==='<')return c<0;
136
+ if(op==='^'||op==='~') { const upper=[...min];if(op==='~'){upper[1]++;upper[2]=0;}
137
+ else if(upper[0]){upper[0]++;upper[1]=upper[2]=0;}else if(upper[1]){upper[1]++;upper[2]=0;}else upper[2]++;
138
+ return c>=0&&compare(value,upper)<0; }
139
+ return nums.length<3||nums.includes('*')?nums.every((x,i)=>x==='*'||Number(x)===value[i]):c===0;
140
+ });
141
+ });
142
+ }
143
+ export function assertUnionDependencyPolicy(manifest,{root=false}={}) {
144
+ check(NAME.test(manifest.name??'') && VERSION.test(manifest.version??''),'union-dependency-identity');
145
+ for(const key of ['optionalDependencies','bundledDependencies','bundleDependencies','overrides','resolutions'])
146
+ check(!manifest[key] || typeof manifest[key]==='object' && Object.keys(manifest[key]).length===0,'union-dependency-source');
147
+ check(!manifest.gypfile,'union-native-resource');
148
+ for(const key of ['preinstall','install','postinstall',...(root?['prepare']:[])])
149
+ check(!manifest.scripts?.[key],'union-lifecycle-script');
150
+ const deps=manifest.dependencies??{};check(deps && typeof deps==='object' && !Array.isArray(deps) && Object.keys(deps).length<=64,'union-dependency-source');
151
+ for(const [name,range] of Object.entries(deps)) check(NAME.test(name) && !name.split('/').some(x=>x==='.'||x==='..')
152
+ && (name===HOST_SHARED || !name.startsWith('@deepseek-ai/') && !['react','electron','node-pty','koffi','ffi-napi','better-sqlite3'].includes(name))
153
+ && typeof range==='string' && range.length<=256 && /^\s*[~^<>=*\d][\d\s.~^<>=*|]*$/.test(range),'union-dependency-source');
154
+ }
155
+ /** Reject directory junctions/symlinks as well as leaf links before realpath. */
156
+ export async function unionPlainDirectory(directory) {
157
+ const absolute=resolve(directory); let cursor=absolute;
158
+ while(true) {
159
+ const info=await lstat(cursor);check(info.isDirectory()&&!info.isSymbolicLink(),'union-directory-untrusted');
160
+ const parent=dirname(cursor);if(parent===cursor)break;cursor=parent;
161
+ }
162
+ check(await realpath(absolute)===absolute,'union-directory-untrusted');return absolute;
163
+ }
164
+ async function locateDependency(owner,name,signal) {
165
+ let cursor=owner;
166
+ while(true) {
167
+ signal.throwIfAborted();const candidate=join(cursor,'node_modules',...name.split('/'));
168
+ let info;try { info=await lstat(candidate); } catch(error) { if(!['ENOENT','ENOTDIR'].includes(error.code))throw error; }
169
+ if(info) { check(info.isDirectory()&&!info.isSymbolicLink(),'union-dependency-link');return unionPlainDirectory(candidate); }
170
+ const parent=dirname(cursor);if(parent===cursor)fail('union-dependency-unresolved');cursor=parent;
171
+ }
172
+ }
173
+ async function packageContents(directory,state,signal) {
174
+ const files=[],dirs=[directory],addPath=pathSet();
175
+ while(dirs.length) {
176
+ signal.throwIfAborted();check(++state.directories<=UNION_LIMITS.directories,'union-dependency-directory-bound');
177
+ const dir=dirs.pop();
178
+ for await(const item of await opendir(dir)) {
179
+ signal.throwIfAborted();const path=join(dir,item.name),info=await lstat(path);
180
+ check(!info.isSymbolicLink(),'union-dependency-link');
181
+ const rel=relative(directory,path).split(sep).join('/');
182
+ // A dependency's own installed dependencies are resolved independently.
183
+ if(item.name==='node_modules') { check(info.isDirectory(),'union-dependency-link');continue; }
184
+ check(item.name!=='.git','union-dependency-inventory');
185
+ addPath('package/'+rel,info.isDirectory());
186
+ if(info.isDirectory()) {check(state.directories+dirs.length<UNION_LIMITS.directories,'union-dependency-directory-bound');dirs.push(path);continue;}
187
+ check(info.isFile()&&!NATIVE.test(rel),'union-native-resource');
188
+ const bytes=await boundedFile(path,UNION_LIMITS.file);signal.throwIfAborted();state.bytes+=bytes.length;
189
+ check(++state.files<=UNION_LIMITS.dependencyFiles && state.bytes<=UNION_LIMITS.dependencyBytes,'union-dependency-file-bound');
190
+ files.push({name:rel,bytes});
191
+ }
192
+ }
193
+ return files.sort((a,b)=>cmp(a.name,b.name));
194
+ }
195
+ /** Complete physical dependency snapshots, each owner independently resolved. Local
196
+ * paths and buffers are ephemeral and are never included in the persisted evidence. */
197
+ export async function unionDependencySnapshot(packageDirectory,manifest,{signal}={}) {
198
+ signal=unionDeadline(signal,60000);assertUnionDependencyPolicy(manifest,{root:true});
199
+ const root=await unionPlainDirectory(packageDirectory),seen=new Map(),packages=[],pending=[],state={files:0,bytes:0,directories:0};
200
+ const top=[],allEdges=[];
201
+ async function visit(owner,ownerManifest,edges,ownerKey) {
202
+ for(const [name,range] of Object.entries(ownerManifest.dependencies??{}).sort(([a],[b])=>cmp(a,b))) {
203
+ signal.throwIfAborted();check(allEdges.length<UNION_LIMITS.edges,'union-dependency-edge-bound');
204
+ if(name===HOST_SHARED) {const e={name,range,external:true};edges.push(e);allEdges.push({owner:ownerKey,...e});continue;}
205
+ const directory=await locateDependency(owner,name,signal);
206
+ const current=unionManifest([{name:'package/package.json',bytes:await boundedFile(join(directory,'package.json'),512*1024)}]);
207
+ assertUnionDependencyPolicy(current);check(current.name===name && unionRangeMatches(current.version,range),'union-dependency-range');
208
+ const key=name+'@'+current.version,e={name,range,target:key};edges.push(e);allEdges.push({owner:ownerKey,...e});
209
+ if(seen.has(directory)) {check(seen.get(directory).key===key,'union-dependency-changed');continue;}
210
+ check(packages.length<UNION_LIMITS.packages,'union-dependency-package-bound');
211
+ const record={name,version:current.version,key,manifest:current,directory,files:await packageContents(directory,state,signal),edges:[]};
212
+ seen.set(directory,record);packages.push(record);pending.push(record);
213
+ }
214
+ }
215
+ await visit(root,manifest,top,'root:'+manifest.name+'@'+manifest.version);
216
+ while(pending.length) {const pkg=pending.shift();await visit(pkg.directory,pkg.manifest,pkg.edges,pkg.key);}
217
+ const identities=new Map(),unique=[];
218
+ for(const pkg of packages) {
219
+ const identity=unionDigest({files:unionInventory(pkg.files),edges:pkg.edges});
220
+ if(identities.has(pkg.key)) check(identities.get(pkg.key)===identity,'union-same-version-bytes-or-edges');
221
+ else {identities.set(pkg.key,identity);unique.push(pkg);}pkg.identity=identity;
222
+ }
223
+ // Validate each physical copy against public npm, including same-version copies.
224
+ const snapshot={manifest,packages,unique,top,edges:allEdges,fileCount:state.files,totalBytes:state.bytes,
225
+ externalShared:[HOST_SHARED]};
226
+ const layout=unionPortableLayout(snapshot);Object.assign(snapshot,layout);
227
+ snapshot.digest=unionDigest(unionSnapshotGraph(snapshot));return snapshot;
228
+ }
229
+ export function unionSnapshotGraph(snapshot) {
230
+ const packages=(snapshot.unique??snapshot.packages).map(p=>({name:p.name,version:p.version,
231
+ files:unionInventory(p.files),edges:p.edges})).sort((a,b)=>cmp(a.name+'@'+a.version,b.name+'@'+b.version));
232
+ return {declaration:snapshot.manifest.dependencies??{},top:snapshot.top,packages,layout:snapshot.layout};
233
+ }
234
+ export function unionPortableLayout(snapshot) {
235
+ const unique=[...(snapshot.unique??snapshot.packages)].sort((a,b)=>cmp(a.name+'@'+a.version,b.name+'@'+b.version)),byKey=new Map(unique.map(p=>[p.key??p.name+'@'+p.version,p]));
236
+ const baseline=new Map();for(const edge of snapshot.top)if(!edge.external)baseline.set(edge.name,edge.target);
237
+ for(const pkg of unique)if(!baseline.has(pkg.name))baseline.set(pkg.name,pkg.key??pkg.name+'@'+pkg.version);
238
+ const portableFiles=[],layout=[];let bytes=0;
239
+ function copy(key,prefix,visible=new Map(baseline),ancestors=[]) {
240
+ check(!ancestors.includes(key),'union-dependency-cycle');const pkg=byKey.get(key);check(pkg,'union-layout-target');
241
+ layout.push({path:prefix,key,edges:pkg.edges});
242
+ for(const file of pkg.files) {bytes+=file.bytes.length;check(portableFiles.length<16000 && bytes<=96*1024*1024,'union-layout-bound');
243
+ portableFiles.push({name:prefix+'/'+file.name,bytes:file.bytes});}
244
+ const corrections=pkg.edges.filter(e=>!e.external && visible.get(e.name)!==e.target),next=new Map(visible);
245
+ for(const edge of corrections)next.set(edge.name,edge.target);
246
+ for(const edge of corrections)copy(edge.target,prefix+'/node_modules/'+edge.name,next,[...ancestors,key]);
247
+ }
248
+ for(const [name,key] of baseline)copy(key,'node_modules/'+name);
249
+ layout.sort((a,b)=>cmp(a.path,b.path));const layoutDigest=unionDigest({top:snapshot.top,layout,files:unionInventory(portableFiles)});
250
+ return {portableFiles,layout,layoutDigest};
251
+ }
252
+ async function boundedBody(response,max,signal) {
253
+ check(response.ok && response.body,'union-public-download');const reader=response.body.getReader(),parts=[];let size=0;
254
+ try {while(true) {signal.throwIfAborted();const {done,value}=await reader.read();if(done)break;size+=value.length;
255
+ check(size<=max,'union-public-download-bound');parts.push(Buffer.from(value));}}
256
+ finally {await reader.cancel().catch(()=>{});reader.releaseLock();}return Buffer.concat(parts);
257
+ }
258
+ export function verifyUnionSRI(bytes,integrity) {
259
+ check(typeof integrity==='string' && integrity.length<=256 && /^sha512-[A-Za-z0-9+/]+={0,2}$/.test(integrity),'union-public-integrity');
260
+ check('sha512-'+createHash('sha512').update(bytes).digest('base64')===integrity,'union-public-integrity');
261
+ }
262
+ export async function verifyUnionPublicSnapshot(snapshot,{fetcher=fetch,signal}={}) {
263
+ signal=unionDeadline(signal);const proofs=[],cache=new Map(),publicArchives=new Map();let archiveBytes=0;
264
+ for(const pkg of snapshot.packages) {
265
+ signal.throwIfAborted();const key=pkg.name+'@'+pkg.version;let publicRecord=cache.get(key);
266
+ if(!publicRecord) {
267
+ const url=PUBLIC_REGISTRY+'/'+encodeURIComponent(pkg.name)+'/'+pkg.version;
268
+ const metadata=JSON.parse((await boundedBody(await fetcher(url,{signal,redirect:'error',credentials:'omit'}),2*1024*1024,signal)).toString('utf8'));
269
+ check(metadata.name===pkg.name && metadata.version===pkg.version,'union-public-identity');
270
+ let archive;try {archive=new URL(metadata.dist?.tarball);}catch {fail('union-public-source');}
271
+ check(archive.origin===PUBLIC_REGISTRY && !archive.username && !archive.password && !archive.search && !archive.hash
272
+ && archive.pathname==='/'+pkg.name+'/-/'+pkg.name.split('/').at(-1)+'-'+pkg.version+'.tgz','union-public-source');
273
+ const bytes=await boundedBody(await fetcher(archive,{signal,redirect:'error',credentials:'omit'}),16*1024*1024,signal);
274
+ verifyUnionSRI(bytes,metadata.dist.integrity);const entries=inspectUnionArchive(bytes);
275
+ const manifest=unionManifest(entries);assertUnionDependencyPolicy(manifest);
276
+ check(manifest.name===pkg.name && manifest.version===pkg.version,'union-public-identity');
277
+ check(!entries.some(e=>e.name.split('/').includes('node_modules')),'union-public-vendored');
278
+ publicRecord={entries,proof:{name:pkg.name,version:pkg.version,sha256:unionHash(bytes),integrity:metadata.dist.integrity,
279
+ files:entries.length,inventoryDigest:unionDigest(unionInventory(entries.map(e=>({...e,name:e.name.slice(8)})))),installedOriginalBytes:true}};
280
+ cache.set(key,publicRecord);proofs.push(publicRecord.proof);
281
+ archiveBytes+=bytes.length;check(archiveBytes<=UNION_LIMITS.dependencyBytes,'union-public-archive-total-bound');
282
+ publicArchives.set(publicRecord.proof.sha256,bytes);
283
+ }
284
+ check(unionDigest(unionInventory(pkg.files))===publicRecord.proof.inventoryDigest,'union-public-exact-inventory');
285
+ const publicFiles=new Map(publicRecord.entries.map(e=>[e.name.slice(8),e.bytes]));
286
+ check(pkg.files.length===publicFiles.size && pkg.files.every(f=>publicFiles.get(f.name)?.equals(f.bytes)),'union-public-original-bytes');
287
+ }
288
+ proofs.sort((a,b)=>cmp(a.name+'@'+a.version,b.name+'@'+b.version));
289
+ // Canonical public archive bytes remain ephemeral, not JSON/reference content.
290
+ snapshot.publicArchives=publicArchives;
291
+ return {canonical:true,registry:PUBLIC_REGISTRY,packages:proofs,graphDigest:snapshot.digest,layoutDigest:snapshot.layoutDigest,
292
+ digest:unionDigest({root:snapshot.manifest.dependencies??{},top:snapshot.top,graph:snapshot.digest,layout:snapshot.layoutDigest,proofs})};
293
+ }
294
+ /** Serializable file-owned evidence: hashes only, never buffers or filesystem paths. */
295
+ export function unionSnapshotEvidence(snapshot,proof) {
296
+ check(proof?.canonical===true && proof.graphDigest===snapshot.digest && proof.layoutDigest===snapshot.layoutDigest,'union-public-proof-binding');
297
+ const graph=unionSnapshotGraph(snapshot);
298
+ for(const pkg of graph.packages) {
299
+ const publicProof=proof.packages.find(p=>p.name===pkg.name&&p.version===pkg.version);
300
+ check(publicProof && publicProof.inventoryDigest===unionDigest(pkg.files),'union-public-proof-binding');
301
+ }
302
+ return {schemaVersion:1,graph,graphDigest:snapshot.digest,layoutDigest:snapshot.layoutDigest,
303
+ portableInventory:unionInventory(snapshot.portableFiles),proof,fileCount:snapshot.fileCount,totalBytes:snapshot.totalBytes,
304
+ externalShared:snapshot.externalShared};
305
+ }
306
+ export function validateUnionEvidence(evidence) {
307
+ check(evidence?.schemaVersion===1 && evidence.graph && evidence.proof?.canonical===true,'union-evidence-invalid');
308
+ const graph=evidence.graph,proof=evidence.proof;
309
+ check(Array.isArray(graph.packages) && graph.packages.length<=UNION_LIMITS.packages && Array.isArray(graph.top)
310
+ && Array.isArray(graph.layout) && graph.layout.length<=UNION_LIMITS.files && Array.isArray(evidence.portableInventory)
311
+ && evidence.portableInventory.length<=16000 && Array.isArray(proof.packages) && proof.packages.length===graph.packages.length,'union-evidence-bound');
312
+ check(unionDigest(graph)===evidence.graphDigest && proof.graphDigest===evidence.graphDigest
313
+ && proof.layoutDigest===evidence.layoutDigest && proof.registry===PUBLIC_REGISTRY,'union-evidence-binding');
314
+ check(unionDigest({top:graph.top,layout:graph.layout,files:evidence.portableInventory})===evidence.layoutDigest,'union-layout-binding');
315
+ check(proof.digest===unionDigest({root:graph.declaration,top:graph.top,graph:evidence.graphDigest,layout:evidence.layoutDigest,proofs:proof.packages}),'union-public-proof-binding');
316
+ let fileCount=0;const names=new Set();
317
+ for(const pkg of graph.packages) {
318
+ const key=pkg.name+'@'+pkg.version;check(NAME.test(pkg.name)&&VERSION.test(pkg.version)&&!names.has(key),'union-evidence-package');names.add(key);
319
+ check(Array.isArray(pkg.files)&&Array.isArray(pkg.edges)&&pkg.edges.length<=64,'union-evidence-package');fileCount+=pkg.files.length;
320
+ const publicProof=proof.packages.find(p=>p.name===pkg.name&&p.version===pkg.version);
321
+ check(publicProof && publicProof.files===pkg.files.length && publicProof.inventoryDigest===unionDigest(pkg.files)
322
+ && /^[a-f0-9]{64}$/.test(publicProof.sha256) && /^sha512-[A-Za-z0-9+/]+={0,2}$/.test(publicProof.integrity),'union-public-proof-binding');
323
+ }
324
+ check(fileCount<=UNION_LIMITS.dependencyFiles,'union-evidence-bound');return evidence;
325
+ }
326
+ export function unionRoutedManifest(manifest,generation) {
327
+ check(/^g\/[a-f0-9]{32}$/.test(generation),'union-generation-token');
328
+ const rewrite=value=>typeof value==='string' ? (check(value.startsWith('./'),'union-export-route'), './'+generation+'/'+value.slice(2))
329
+ : Array.isArray(value)?value.map(rewrite):value&&typeof value==='object'?Object.fromEntries(Object.entries(value).map(([k,v])=>[k,rewrite(v)])):value;
330
+ check(manifest.exports && typeof manifest.exports==='object' && !Array.isArray(manifest.exports) && typeof manifest.main==='string','union-manifest-route');
331
+ const exports=Object.fromEntries(Object.entries(manifest.exports).map(([key,value])=>[key,/locale|package\.json|icon/.test(key)?value:rewrite(value)]));
332
+ const main=manifest.main.replace(/^\.\//,'');safeWinArchivePath('package/'+main);
333
+ return {...manifest,exports,main:generation+'/'+main};
334
+ }
335
+ /** Pure builder. Admission to production occurs ONLY in UnionGenerationStager,
336
+ * never through a caller-supplied hash/policy override in these safety functions. */
337
+ export function buildUnionGeneration(sourceBytes,snapshot,{rootBytes=sourceBytes,retained=[],generation='g/'+randomUUID().replaceAll('-','')}={}) {
338
+ check(Array.isArray(retained)&&retained.length<=UNION_LIMITS.oldGenerations,'union-retention-limit');
339
+ const source=inspectUnionArchive(sourceBytes),root=inspectUnionArchive(rootBytes),manifest=unionManifest(source),routed=unionRoutedManifest(manifest,generation);
340
+ check(manifest.name==='dsh-union-search' && unionManifest(root).name===manifest.name,'union-generation-package');
341
+ check(!source.some(e=>e.name.split('/')[1]==='g'||e.name.split('/').includes('node_modules')),'union-source-layout');
342
+ const entries=[...root.map(e=>e.name==='package/package.json'?{...e,bytes:Buffer.from(JSON.stringify(routed,null,2))}:e),
343
+ ...source.map(e=>({...e,name:'package/'+generation+'/'+e.name.slice(8)})),
344
+ ...snapshot.portableFiles.map(f=>({name:'package/'+generation+'/'+f.name,bytes:f.bytes}))];
345
+ const generations=new Set([generation]);
346
+ for(const old of retained) {
347
+ check(/^g\/[a-f0-9]{32}$/.test(old.generation)&&!generations.has(old.generation),'union-retained-token');generations.add(old.generation);
348
+ check(Array.isArray(old.entries) && old.entries.length>0 && old.entries.every(e=>e.name.startsWith('package/'+old.generation+'/')),'union-retained-scope');
349
+ entries.push(...old.entries);
350
+ }
351
+ const bytes=packUnionArchive(entries);return {bytes,generation,manifest:routed,originalSha256:unionHash(sourceBytes),
352
+ sha256:unionHash(bytes),files:entries.length,inventoryDigest:unionDigest(unionInventory(entries)),originalJsUnchanged:true};
353
+ }
354
+ /** Full installed inventory; only the top-level Host-managed node_modules tree is
355
+ * outside this archive. Every generation subtree is inventoried and hashed. */
356
+ export async function verifyUnionInstalledEntries(entries,packageDirectory,{signal}={}) {
357
+ signal=unionDeadline(signal,60000);const root=await unionPlainDirectory(packageDirectory),expected=new Map(entries.map(e=>[e.name.slice(8),e]));
358
+ const dirs=[root],actual=[],state={directories:0,bytes:0},addPath=pathSet();
359
+ while(dirs.length) {
360
+ signal.throwIfAborted();check(++state.directories<=UNION_LIMITS.files,'union-installed-directory-bound');const dir=dirs.pop();
361
+ for await(const item of await opendir(dir)) {
362
+ signal.throwIfAborted();const path=join(dir,item.name),rel=relative(root,path).split(sep).join('/'),info=await lstat(path);
363
+ check(!info.isSymbolicLink(),'union-installed-link');
364
+ if(rel==='node_modules') {check(info.isDirectory(),'union-installed-link');continue;}
365
+ addPath('package/'+rel,info.isDirectory());
366
+ if(info.isDirectory()) {check([...expected.keys()].some(key=>key.startsWith(rel+'/')),'union-installed-extra-directory');
367
+ check(state.directories+dirs.length<UNION_LIMITS.files,'union-installed-directory-bound');dirs.push(path);continue;}
368
+ check(info.isFile()&&expected.has(rel),'union-installed-extra-file');
369
+ const bytes=await boundedFile(path,UNION_LIMITS.file);state.bytes+=bytes.length;
370
+ check(actual.length<UNION_LIMITS.files && state.bytes<=UNION_LIMITS.archive,'union-installed-bound');
371
+ check(bytes.equals(expected.get(rel).bytes),'union-installed-bytes');actual.push(rel);
372
+ }
373
+ }
374
+ check(actual.length===expected.size,'union-installed-inventory');
375
+ return {verified:true,files:actual.length,inventoryDigest:unionDigest(unionInventory(entries))};
376
+ }
@@ -0,0 +1,83 @@
1
+ export async function verifyUnionGeneration(service,item,reference,result,field='verification') {
2
+ const {bundles,rows}=await service.snapshot(),bundle=bundles.find(value=>value.name===item.name);
3
+ const root=service.unionStager?.root,expectedSource=root&&service.archiveRoot(bundle,reference);
4
+ let source=false,bytes=false,runtime=false;
5
+ if(bundle?.installed && bundle.version===reference.version && bundle.enabled===item.enabled && root===expectedSource){
6
+ const {archiveKey}=await import('./source.js');source=archiveKey(root,bundle.source)===reference.archiveKey && bundle.update!=='registry';
7
+ }
8
+ if(source)try{await service.unionStager.verifyInstalledArchive(reference,await service.resolvePackage(item.name));bytes=true;}catch{}
9
+ const host=service.expectedHostState(bundle,rows,reference.rows);
10
+ if(source&&bytes&&host.verified)try{runtime=await service.verifyRunningGeneration(await service.resolvePackage(item.name),reference,{enabled:item.enabled})===true;}catch{}
11
+ item[field]={package:{status:bytes?'verified':'failed',version:bundle?.version??null,expectedVersion:reference.version},
12
+ source:{status:source?'verified':'failed',expectedKind:'derived-local-union-generation',kind:source?'local':bundle?.update??'unknown',officialVersionCheckEligible:false},
13
+ host:{status:host.verified?host.status:'unknown',activeRows:host.activeRows,totalRows:host.totalRows},
14
+ runtime:{status:runtime?(item.enabled?'verified':'disabled'):'unknown',generation:reference.runtimeGeneration.generation,executed:item.enabled===true&&runtime,originalJsUnchanged:true}};
15
+ if(result.application==='applied'&&(!source||!bytes||!host.verified||!runtime))return {...result,observedApplication:'applied',application:'unknown',error:{code:'union-generation-state-unverified',diagnostic:'Derived source, original bytes, expected Host state and exact running generation were not all verified.'}};
16
+ return result;
17
+ }
18
+ const complete=result=>result&&['applied','failed','cancelled','restart-required','overridden'].includes(result.application);
19
+ const unknown=(item,error)=>{item.status='unknown';item.unionOutcomeUnknown=true;return {application:'unknown',error:{code:'union-generation-outcome-unknown',diagnostic:String(error?.message??error??'Missing Host result')}};};
20
+
21
+ export async function performUnionGeneration(service,job,item,next,previous) {
22
+ if(item.name!=='dsh-union-search'||!service.unionStager||typeof service.verifyRunningGeneration!=='function')throw Error('union-generation-unavailable');
23
+ const current=(await service.snapshot()).bundles.find(value=>value.name===item.name);
24
+ if(!service.unionPair(current,item.to)||service.fingerprint(current)!==item.fingerprint)throw Error('union-generation-state-changed');
25
+ await service.unionStager.verifyBaseline(item.baseline,await service.resolvePackage(item.name),job.controller.signal);
26
+ await service.unionStager.verify(next);await service.unionStager.verify(previous);
27
+ const recovery=service.recoveryFor(item.name);await service.identities.prepare({...recovery,dispatchStarted:true});
28
+ if(service.fingerprint((await service.snapshot()).bundles.find(value=>value.name===item.name))!==item.fingerprint)throw Error('union-generation-state-changed');
29
+ job.activeInstall={name:item.name,requestId:job.id,recovery:false};
30
+ item.unionDispatchStarted=true;let removed;try{removed=await service.manager.removeBundle(item.name);}catch(error){item.result=unknown(item,error);return;}
31
+ if(!complete(removed)){item.result=unknown(item);return;}
32
+ if(removed.application!=='applied'){item.result=await service.completeResult(removed);item.status=removed.application==='restart-required'?'restart-required':'failed';item.unionUntouched=service.fingerprint((await service.snapshot()).bundles.find(value=>value.name===item.name))===item.fingerprint;return;}
33
+ if((await service.snapshot()).bundles.find(value=>value.name===item.name)?.installed){item.result=unknown(item,'External target appeared after removal');return;}
34
+ let installed;try{installed=await service.manager.installBundle(next.archivePath,{registry:item.registry,enabled:item.enabled,saveExact:true,expected:{name:item.name,version:item.to},requestId:job.id});}catch(error){item.result=unknown(item,error);return;}
35
+ if(!complete(installed)){item.result=unknown(item);return;}
36
+ item.origin='derived-local-generation';item.archivePath=next.archivePath;item.originalSha256=next.originalSha256;
37
+ item.result=await service.completeResult(await verifyUnionGeneration(service,item,item.nextReference,installed));
38
+ item.status=item.result.application==='applied'?'updated':item.result.application==='restart-required'?'restart-required':item.result.application==='unknown'?'unknown':'failed';
39
+ if(item.status==='unknown'){item.unionOutcomeUnknown=true;return;}
40
+ if(item.status!=='failed')return;
41
+ const after=(await service.snapshot()).bundles.find(value=>value.name===item.name);
42
+ if(after?.installed){
43
+ if(!await service.ownedTarget(item)){item.unionOutcomeUnknown=true;item.restore={application:'unknown',error:{code:'external-target-not-restored'}};return;}
44
+ try{await service.unionStager.verifyInstalledArchive(item.nextReference,await service.resolvePackage(item.name));}catch{item.unionOutcomeUnknown=true;item.restore={application:'unknown',error:{code:'external-target-not-restored'}};return;}
45
+ let cleanup;try{cleanup=await service.manager.removeBundle(item.name);}catch(error){item.restore=unknown(item,error);return;}
46
+ if(!complete(cleanup)){item.restore=unknown(item);return;}
47
+ if(cleanup.application!=='applied'){item.restore=await service.completeResult(cleanup);return;}
48
+ }
49
+ if((await service.snapshot()).bundles.find(value=>value.name===item.name)?.installed){item.unionOutcomeUnknown=true;item.restore={application:'unknown',error:{code:'external-target-not-restored'}};return;}
50
+ await service.unionStager.verify(previous);job.activeInstall={name:item.name,requestId:job.id+'-restore',recovery:true};
51
+ let restored;try{restored=await service.manager.installBundle(previous.archivePath,{registry:item.registry,enabled:item.enabled,saveExact:true,expected:{name:item.name,version:item.from},requestId:job.activeInstall.requestId});}catch(error){item.restore=unknown(item,error);return;}
52
+ if(!complete(restored)){item.restore=unknown(item);return;}
53
+ item.restore=await service.completeResult(await verifyUnionGeneration(service,item,item.previousReference,restored,'restoreVerification'));
54
+ if(item.restore.application==='unknown')item.unionOutcomeUnknown=true;
55
+ }
56
+
57
+ export async function performUnionRecovery(service,job,item,staged,current,recovery){
58
+ if(item.name!=='dsh-union-search'||recovery.status!=='failed'||recovery.id!==item.recoveryId||service.fingerprint(current)!==item.fingerprint)throw Error('union-generation-recovery-state-changed');
59
+ if(!current?.installed||!item.currentReference)throw Error('union-generation-recovery-unavailable');
60
+ await service.unionStager.verifyInstalledArchive(item.currentReference,await service.resolvePackage(item.name));await service.unionStager.verify(staged);
61
+ await service.identities.prepare({...recovery,status:'prepared',dispatchStarted:true});
62
+ if(service.fingerprint((await service.snapshot()).bundles.find(value=>value.name===item.name))!==item.fingerprint)throw Error('union-generation-recovery-state-changed');
63
+ item.unionDispatchStarted=true;let removed;try{removed=await service.manager.removeBundle(item.name);}catch(error){item.result=unknown(item,error);return;}
64
+ if(!complete(removed)){item.result=unknown(item);return;}if(removed.application!=='applied'){item.result=await service.completeResult(removed);item.status=removed.application==='restart-required'?'restart-required':'failed';item.unionUntouched=service.fingerprint((await service.snapshot()).bundles.find(value=>value.name===item.name))===item.fingerprint;return;}
65
+ if((await service.snapshot()).bundles.find(value=>value.name===item.name)?.installed){item.result=unknown(item,'External target appeared');return;}
66
+ job.activeInstall={name:item.name,requestId:job.id,recovery:true};let result;try{result=await service.manager.installBundle(staged.archivePath,{registry:item.registry,enabled:item.enabled,saveExact:true,expected:{name:item.name,version:item.to},requestId:job.id});}catch(error){item.result=unknown(item,error);return;}
67
+ if(!complete(result)){item.result=unknown(item);return;}item.result=await service.completeResult(await verifyUnionGeneration(service,item,item.nextReference,result));item.status=item.result.application==='applied'?'restored':item.result.application==='restart-required'?'restart-required':item.result.application==='unknown'?'unknown':'failed';if(item.status==='unknown')item.unionOutcomeUnknown=true;
68
+ }
69
+
70
+ export async function persistUnionOutcome(service,job,item,bundle,recovery) {
71
+ const {archiveKey}=await import('./source.js');
72
+ if(item.unionOutcomeUnknown||item.status==='unknown'){await service.identities.settle(item.name,null,{...recovery,status:'unknown',expectedFingerprint:service.fingerprint(bundle)});delete item.recoveryId;delete item.restoreVersion;return;}
73
+ if(['preparing','waiting','skipped'].includes(item.status)||item.unionUntouched){await service.identities.settle(item.name,service.lineageOf(bundle),job.record.operation==='batch-restore'?{...recovery,status:'failed',dispatchStarted:false}:null);delete item.recoveryId;delete item.restoreVersion;return;}
74
+ const reference=[item.nextReference,item.previousReference].find(value=>value?.version===bundle?.version&&archiveKey(service.unionStager.root,bundle.source)===value.archiveKey);
75
+ let installed=null;if(reference)try{await service.unionStager.verifyInstalledArchive(reference,await service.resolvePackage(item.name));installed=reference;}catch{}
76
+ const runtimeVerified=verification=>verification?.runtime.status==='verified'||item.enabled===false&&verification?.runtime.status==='disabled';
77
+ const restored=item.status==='restored'||item.restore?.application==='applied'&&item.restoreVerification?.package.status==='verified'&&runtimeVerified(item.restoreVerification);
78
+ const succeeded=item.status==='updated'&&item.verification?.package.status==='verified'&&runtimeVerified(item.verification)||restored;
79
+ if(succeeded&&installed){await service.identities.settle(item.name,installed,null);delete item.recoveryId;delete item.restoreVersion;return;}
80
+ const ours=!bundle?.installed||installed||service.fingerprint(bundle)===item.fingerprint;
81
+ await service.identities.settle(item.name,installed,ours?{...recovery,status:'failed',expectedFingerprint:service.fingerprint(bundle)}:null);
82
+ if(ours){item.recoveryId=recovery.id;item.restoreVersion=recovery.from;}else{delete item.recoveryId;delete item.restoreVersion;}
83
+ }