dsh-plugin-update-doctor 0.5.0 → 0.5.4
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/README.md +65 -65
- package/client.js +337 -32
- package/docs/DETAIL.md +65 -22
- package/docs/PUBLICATION.md +36 -15
- package/docs/RELEASE_NOTES_0_5_1.md +80 -0
- package/docs/RELEASE_REVIEW_0_5_1.md +54 -0
- package/docs/SELF_UPDATE.md +7 -1
- package/docs/UNION_GENERATION_0_5_2.md +32 -0
- package/docs/V0_3_DESIGN.md +2 -0
- package/docs/VERIFICATION.md +168 -81
- package/docs/WINDOWS_REQUIREMENTS.md +48 -0
- package/docs/WINDOWS_SUPPORT.md +82 -0
- package/docs/WSL_STRUCTURAL_0_5_3.md +30 -0
- package/index.js +15 -2
- package/lib/dependency-policy.js +89 -0
- package/lib/history.js +2 -2
- package/lib/http.js +5 -1
- package/lib/identity.js +22 -3
- package/lib/online.js +44 -18
- package/lib/self-update-policy.js +90 -25
- package/lib/self-update-store.js +25 -9
- package/lib/self-update.js +92 -29
- package/lib/service.js +437 -58
- package/lib/source.js +29 -0
- package/lib/staging.js +128 -30
- package/lib/union-generation.js +376 -0
- package/lib/union-service.js +83 -0
- package/lib/union-staging.js +325 -0
- package/lib/wsl-outcome.js +15 -0
- package/lib/wsl-policy.js +71 -5
- package/lib/wsl-proof.js +85 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +1 -1
|
@@ -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
|
|
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
|
-
|
|
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 {
|
|
3
|
+
import { publicRegistry, approvedPublicRegistry, registryOrigin, readRegistryVersions } from './source.js';
|
|
4
|
+
import { dependencyPolicyReasons } from './dependency-policy.js';
|
|
4
5
|
|
|
5
|
-
/**
|
|
6
|
-
export
|
|
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
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const sourceAllowed =
|
|
20
|
-
const reasons = [...bundle.reasons ?? [], ...sourceAllowed ? [] : [result.registry == null ? 'registry-origin-unverified' : 'registry-origin-unsupported']];
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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:
|
|
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-
|
|
40
|
-
|
|
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,29 @@ export function inspectSelfFiles(files, { version, role = 'next', resolvedYamlVe
|
|
|
131
131
|
return { manifest, files };
|
|
132
132
|
}
|
|
133
133
|
|
|
134
|
-
/**
|
|
134
|
+
/** Only the two fixed public origins are admitted. The legacy official-only path
|
|
135
|
+
* remains narrow; public fallback plans are independently disclosed and bound.
|
|
136
|
+
* No registry configuration is written and no private source is promoted.
|
|
137
|
+
*/
|
|
135
138
|
export function verifySelfRegistryPlan(registries, queryRegistry) {
|
|
136
|
-
|
|
137
|
-
required(
|
|
139
|
+
const query = registryOrigin(queryRegistry);
|
|
140
|
+
required(approvedPublicRegistry(query), 'self-query-origin-unverified');
|
|
141
|
+
required(plain(registries) && Array.isArray(registries.fallbackRegistries) && registries.fallbackRegistries.length <= 8,
|
|
142
|
+
'self-host-registry-plan-unsupported');
|
|
143
|
+
const legacyOfficial = query === PUBLIC_REGISTRY && registries.fallbackRegistries.length === 0
|
|
138
144
|
&& (registries.registry === null ? publicRegistry(registries.resolved) : publicRegistry(registries.registry))
|
|
139
|
-
&& (registries.resolved == null || publicRegistry(registries.resolved))
|
|
145
|
+
&& (registries.resolved == null || publicRegistry(registries.resolved));
|
|
146
|
+
if (!legacyOfficial) required(approvedPublicRegistry(registries.resolved)
|
|
147
|
+
&& (registries.registry === null || approvedPublicRegistry(registries.registry))
|
|
148
|
+
&& registries.fallbackRegistries.every(approvedPublicRegistry), 'self-host-registry-plan-unsupported');
|
|
149
|
+
return { queryRegistry: query, registry: registries.registry === null ? null : registryOrigin(registries.registry),
|
|
150
|
+
resolved: registries.resolved == null ? null : registryOrigin(registries.resolved),
|
|
151
|
+
fallbackRegistries: registries.fallbackRegistries.map(registryOrigin) };
|
|
152
|
+
}
|
|
153
|
+
export function selfRegistrySourceMode(plan) {
|
|
154
|
+
if (plan.queryRegistry === PUBLIC_MIRROR) return 'public-mirror';
|
|
155
|
+
return plan.fallbackRegistries.length || plan.registry === PUBLIC_MIRROR || plan.resolved === PUBLIC_MIRROR
|
|
156
|
+
? 'public-fallback' : 'official';
|
|
140
157
|
}
|
|
141
158
|
function metadataIdentity(metadata, version, inspected) {
|
|
142
159
|
required(metadata.name === SELF_UPDATE_PACKAGE && metadata.version === version, 'self-registry-identity-mismatch');
|
|
@@ -203,43 +220,91 @@ export async function verifyCurrentFiles(currentDirectory, files) {
|
|
|
203
220
|
}
|
|
204
221
|
}
|
|
205
222
|
|
|
206
|
-
/**
|
|
223
|
+
/** Fixed official/mirror archive preflight only: the Host still installs by registry
|
|
224
|
+
* spec. Mirror bytes must independently equal canonical official archive digests. */
|
|
207
225
|
export class SelfUpdatePreflight {
|
|
208
226
|
constructor({ fetcher = fetch, compatibility, helperSha256 = SELF_UPDATE_HELPER_SHA256 } = {}) {
|
|
209
227
|
Object.assign(this, { fetcher, compatibility, helperSha256 });
|
|
210
228
|
}
|
|
211
|
-
async
|
|
212
|
-
|
|
229
|
+
async downloadArchive(url, options, version) {
|
|
230
|
+
// npmmirror's public tarball route uses one redirect to its fixed CDN.
|
|
231
|
+
// Follow only this exact package/version path, never automatic redirects.
|
|
232
|
+
const mirror = url.origin === PUBLIC_MIRROR;
|
|
233
|
+
let response = await this.fetcher(url, mirror ? { ...options, redirect: 'manual' } : options);
|
|
234
|
+
required(!response.url || response.url === url.href, 'self-tarball-origin-unsupported');
|
|
235
|
+
if (mirror && [301,302,303,307,308].includes(response.status)) {
|
|
236
|
+
const location = response.headers.get('location');
|
|
237
|
+
await response.body?.cancel();
|
|
238
|
+
const expected = `https://cdn.npmmirror.com/packages/${SELF_UPDATE_PACKAGE}/${version}/${SELF_UPDATE_PACKAGE}-${version}.tgz`;
|
|
239
|
+
required(location === expected, 'self-tarball-origin-unsupported');
|
|
240
|
+
options.signal.throwIfAborted();
|
|
241
|
+
response = await this.fetcher(expected, { ...options, redirect: 'manual' });
|
|
242
|
+
required(!response.url || response.url === expected, 'self-tarball-origin-unsupported');
|
|
243
|
+
if ([301,302,303,307,308].includes(response.status)) {
|
|
244
|
+
await response.body?.cancel();
|
|
245
|
+
refuse('self-tarball-origin-unsupported');
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
required(response.ok, 'self-archive-unavailable');
|
|
249
|
+
return response;
|
|
250
|
+
}
|
|
251
|
+
async fetchArchive(version, role, resolvedYamlVersion, signal, registry = PUBLIC_REGISTRY) {
|
|
252
|
+
const source = registryOrigin(registry);
|
|
253
|
+
required(approvedPublicRegistry(source) && VERSION.test(version ?? ''), 'self-query-origin-unverified');
|
|
254
|
+
const options = { signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(90_000)]) : AbortSignal.timeout(90_000), redirect: 'error', credentials: 'omit' };
|
|
213
255
|
options.signal.throwIfAborted();
|
|
214
|
-
const
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
256
|
+
const read = async origin => {
|
|
257
|
+
const metadataURL = `${origin}/${SELF_UPDATE_PACKAGE}/${version}`;
|
|
258
|
+
const metadataResponse = await this.fetcher(metadataURL, options);
|
|
259
|
+
required(metadataResponse.ok, 'self-registry-metadata-unavailable');
|
|
260
|
+
required(!metadataResponse.url || metadataResponse.url === metadataURL, 'self-tarball-origin-unsupported');
|
|
261
|
+
const metadata = json(await body(metadataResponse, MAX_METADATA), 'self-registry-metadata-invalid');
|
|
262
|
+
required(metadata.name === SELF_UPDATE_PACKAGE && metadata.version === version, 'self-registry-identity-mismatch');
|
|
263
|
+
let url;
|
|
264
|
+
try { url = new URL(metadata.dist?.tarball); } catch { refuse('self-tarball-origin-unsupported'); }
|
|
265
|
+
required(url.protocol === 'https:' && (url.origin === origin || origin === PUBLIC_MIRROR && url.origin === PUBLIC_REGISTRY)
|
|
266
|
+
&& !url.username && !url.password && !url.search && !url.hash
|
|
267
|
+
&& url.pathname === `/${SELF_UPDATE_PACKAGE}/-/${SELF_UPDATE_PACKAGE}-${version}.tgz`, 'self-tarball-origin-unsupported');
|
|
268
|
+
const response = await this.downloadArchive(url, options, version);
|
|
269
|
+
const bytes = await body(response, MAX_ARCHIVE); verifyIntegrity(bytes, metadata.dist?.integrity);
|
|
270
|
+
const inspected = inspectSelfArchive(bytes, { version, role, resolvedYamlVersion, compatibility: this.compatibility, helperSha256: this.helperSha256 });
|
|
271
|
+
metadataIdentity(metadata, version, inspected);
|
|
272
|
+
return { ...inspected, integrity: metadata.dist.integrity, canonicalIntegrity: 'sha512-' + createHash('sha512').update(bytes).digest('base64') };
|
|
273
|
+
};
|
|
274
|
+
const downloaded = await read(source);
|
|
275
|
+
if (source === PUBLIC_MIRROR) {
|
|
276
|
+
const canonical = await read(PUBLIC_REGISTRY);
|
|
277
|
+
required(downloaded.sha256 === canonical.sha256 && downloaded.canonicalIntegrity === canonical.canonicalIntegrity,
|
|
278
|
+
'self-public-mirror-archive-mismatch');
|
|
279
|
+
return { ...downloaded, integrity: canonical.canonicalIntegrity };
|
|
280
|
+
}
|
|
281
|
+
const { canonicalIntegrity, ...official } = downloaded;
|
|
282
|
+
return official;
|
|
227
283
|
}
|
|
228
284
|
async check({ bundle, currentDirectory, targetVersion, resolvedYamlVersion, registries, queryRegistry, signal } = {}) {
|
|
229
285
|
required(bundle?.name === SELF_UPDATE_PACKAGE && bundle.update === 'registry' && bundle.installed === true && bundle.enabled === true
|
|
230
286
|
&& bundle.removable === true && bundle.availability === 'profile' && !bundle.readOnlyReason && !bundle.error, 'self-installed-source-unsupported');
|
|
231
287
|
required(stableNewer(targetVersion, bundle.version), 'self-target-version-unsupported');
|
|
232
|
-
|
|
288
|
+
const registry = registryOrigin(queryRegistry);
|
|
289
|
+
const hostRegistryPlan = verifySelfRegistryPlan(registries, queryRegistry);
|
|
290
|
+
const sourceMode = selfRegistrySourceMode(hostRegistryPlan), publicMirror = sourceMode === 'public-mirror', publicFallback = sourceMode === 'public-fallback';
|
|
233
291
|
signal?.throwIfAborted();
|
|
234
|
-
const previous = await this.fetchArchive(bundle.version, 'previous', resolvedYamlVersion, signal);
|
|
292
|
+
const previous = await this.fetchArchive(bundle.version, 'previous', resolvedYamlVersion, signal, registry);
|
|
235
293
|
await verifyCurrentFiles(currentDirectory, previous.files);
|
|
236
|
-
const next = await this.fetchArchive(targetVersion, 'next', resolvedYamlVersion, signal);
|
|
294
|
+
const next = await this.fetchArchive(targetVersion, 'next', resolvedYamlVersion, signal, registry);
|
|
295
|
+
if (publicFallback && [hostRegistryPlan.registry, hostRegistryPlan.resolved, ...hostRegistryPlan.fallbackRegistries].includes(PUBLIC_MIRROR)) {
|
|
296
|
+
const mirrorPrevious = await this.fetchArchive(bundle.version, 'previous', resolvedYamlVersion, signal, PUBLIC_MIRROR);
|
|
297
|
+
const mirrorNext = await this.fetchArchive(targetVersion, 'next', resolvedYamlVersion, signal, PUBLIC_MIRROR);
|
|
298
|
+
required(mirrorPrevious.sha256 === previous.sha256 && mirrorNext.sha256 === next.sha256, 'self-public-mirror-archive-mismatch');
|
|
299
|
+
}
|
|
237
300
|
for (const key of ['exports', 'peerDependencies', 'engines']) required(equal(previous.manifest[key], next.manifest[key]), 'self-runtime-graph-changed');
|
|
238
301
|
required(equal(previous.manifest.dsh.client, next.manifest.dsh.client), 'self-runtime-graph-changed');
|
|
239
302
|
const publicArchive = value => ({ sha256: value.sha256, integrity: value.integrity, manifest: value.manifest,
|
|
240
303
|
files: Object.fromEntries([...value.files].map(([path, bytes]) => [path, digest(bytes)])) });
|
|
241
304
|
signal?.throwIfAborted();
|
|
242
|
-
return { name: SELF_UPDATE_PACKAGE, from: bundle.version, to: targetVersion, registry
|
|
305
|
+
return { name: SELF_UPDATE_PACKAGE, from: bundle.version, to: targetVersion, registry, currentManifest: previous.manifest,
|
|
306
|
+
...(publicMirror ? { sourceMode: 'public-mirror', publicMirror: true, hostRegistryPlan }
|
|
307
|
+
: publicFallback ? { sourceMode: 'public-fallback', publicFallback: true, hostRegistryPlan } : {}),
|
|
243
308
|
previous: publicArchive(previous), next: publicArchive(next) };
|
|
244
309
|
}
|
|
245
310
|
/** Verify the recorded original resource hashes locally, independently of version labels and registry queries. */
|
package/lib/self-update-store.js
CHANGED
|
@@ -2,8 +2,9 @@ import { open, mkdir, lstat, realpath, opendir, link, unlink, rmdir } from 'node
|
|
|
2
2
|
import { resolve, join, dirname, basename, parse, sep } from 'node:path';
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
4
|
import { boundedFile } from './file-read.js';
|
|
5
|
-
import { PUBLIC_REGISTRY, registryOrigin } from './source.js';
|
|
5
|
+
import { PUBLIC_REGISTRY, PUBLIC_MIRROR, approvedPublicRegistry, registryOrigin } from './source.js';
|
|
6
6
|
import { parseSelfGithubSource, SELF_UPDATE_GITHUB_REPOSITORY } from './self-update-github.js';
|
|
7
|
+
import { verifySelfRegistryPlan, selfRegistrySourceMode } from './self-update-policy.js';
|
|
7
8
|
|
|
8
9
|
const SELF = 'dsh-plugin-update-doctor';
|
|
9
10
|
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
@@ -12,7 +13,7 @@ const SHA = /^[a-f0-9]{64}$/;
|
|
|
12
13
|
const APPLICATION = new Set(['applied', 'failed', 'cancelled', 'restart-required', 'overridden']);
|
|
13
14
|
const STAGES = new Set(['install', 'enable', 'remove']);
|
|
14
15
|
const RESTART = new Set(['no-hmr', 'package-moved', 'host-module', 'unmanaged-plugin', 'module-comparison']);
|
|
15
|
-
const ATTEMPT_KEYS = new Set(['schemaVersion', 'id', 'name', 'from', 'to', 'registry', 'sourceKind', 'repository', 'fromCommit', 'toCommit', 'pid', 'startedAt', 'taskPolicy', 'confirmCancel', 'previousSha256', 'nextSha256', 'previousFiles', 'nextFiles']);
|
|
16
|
+
const ATTEMPT_KEYS = new Set(['schemaVersion', 'id', 'name', 'from', 'to', 'registry', 'sourceKind', 'sourceMode', 'publicMirror', 'publicFallback', 'confirmPublicMirror', 'hostRegistryPlan', 'repository', 'fromCommit', 'toCommit', 'pid', 'startedAt', 'taskPolicy', 'confirmCancel', 'previousSha256', 'nextSha256', 'previousFiles', 'nextFiles']);
|
|
16
17
|
const RESULT_KEYS = new Set(['schemaVersion', 'id', 'finishedAt', 'official', 'outcome', 'error', 'truncated']);
|
|
17
18
|
const HANDOFF_KEYS = new Set(['schemaVersion', 'id', 'handedOffAt']);
|
|
18
19
|
const object = value => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
@@ -34,28 +35,43 @@ export class SelfUpdateStore {
|
|
|
34
35
|
if (!object(value)) fail('self-update-attempt-invalid');
|
|
35
36
|
if (reading) {
|
|
36
37
|
exactKeys(value, ATTEMPT_KEYS);
|
|
37
|
-
if (value.schemaVersion
|
|
38
|
+
if (![1,2,3].includes(value.schemaVersion) || value.name !== SELF || ['id', 'from', 'to', 'pid', 'startedAt', 'taskPolicy', 'confirmCancel'].some(key => !Object.hasOwn(value, key))) fail('self-update-record-format');
|
|
38
39
|
if (!Number.isSafeInteger(value.pid) || value.pid < 1 || typeof value.confirmCancel !== 'boolean' || !['wait-for-idle', 'cancel-active'].includes(value.taskPolicy)) fail('self-update-record-format');
|
|
39
40
|
timestamp(value.startedAt);
|
|
40
41
|
}
|
|
41
42
|
const id = identifier(value.id ?? randomUUID());
|
|
42
43
|
if (!VERSION.test(value.from ?? '') || !VERSION.test(value.to ?? '') || value.from === value.to) fail('self-update-attempt-target');
|
|
43
|
-
const git = value.sourceKind === 'git';
|
|
44
|
+
const git = value.sourceKind === 'git', publicMirror = registryOrigin(value.registry) === PUBLIC_MIRROR, publicFallback = value.sourceMode === 'public-fallback';
|
|
44
45
|
let source;
|
|
45
46
|
if (git) {
|
|
46
|
-
if (value.registry !== undefined || value.repository !== SELF_UPDATE_GITHUB_REPOSITORY || value.fromCommit === value.toCommit) fail('self-update-attempt-target');
|
|
47
|
+
if (value.registry !== undefined || ['sourceMode','publicMirror','publicFallback','confirmPublicMirror','hostRegistryPlan'].some(key=>value[key]!==undefined) || value.repository !== SELF_UPDATE_GITHUB_REPOSITORY || value.fromCommit === value.toCommit) fail('self-update-attempt-target');
|
|
47
48
|
const previous = parseSelfGithubSource('github:' + value.repository + '#' + value.fromCommit), next = parseSelfGithubSource('github:' + value.repository + '#' + value.toCommit);
|
|
48
49
|
source = { sourceKind: 'git', repository: SELF_UPDATE_GITHUB_REPOSITORY, fromCommit: previous.commit, toCommit: next.commit };
|
|
49
50
|
} else {
|
|
50
|
-
if (value.sourceKind !== undefined && value.sourceKind !== 'registry' ||
|
|
51
|
+
if (value.sourceKind !== undefined && value.sourceKind !== 'registry' || !approvedPublicRegistry(value.registry)
|
|
51
52
|
|| ['repository', 'fromCommit', 'toCommit'].some(key => value[key] !== undefined)) fail('self-update-attempt-target');
|
|
52
|
-
|
|
53
|
+
if (publicMirror || publicFallback) {
|
|
54
|
+
const mode = publicMirror ? 'public-mirror' : 'public-fallback';
|
|
55
|
+
if (value.sourceMode !== mode || value.confirmPublicMirror !== true
|
|
56
|
+
|| publicMirror && (value.publicMirror !== true || value.publicFallback !== undefined)
|
|
57
|
+
|| publicFallback && (registryOrigin(value.registry) !== PUBLIC_REGISTRY || value.publicFallback !== true || value.publicMirror !== undefined)
|
|
58
|
+
|| reading && value.schemaVersion !== (publicFallback ? 3 : 2)) fail('self-update-attempt-target');
|
|
59
|
+
exactKeys(value.hostRegistryPlan,new Set(['queryRegistry','registry','resolved','fallbackRegistries']));
|
|
60
|
+
const registry = publicMirror ? PUBLIC_MIRROR : PUBLIC_REGISTRY;
|
|
61
|
+
const plan=verifySelfRegistryPlan(value.hostRegistryPlan,registry);
|
|
62
|
+
if(value.hostRegistryPlan.queryRegistry!==registry || selfRegistrySourceMode(plan)!==mode)fail('self-update-attempt-target');
|
|
63
|
+
source = { registry, sourceMode:mode, ...(publicMirror ? {publicMirror:true} : {publicFallback:true}), confirmPublicMirror:true, hostRegistryPlan:plan };
|
|
64
|
+
} else {
|
|
65
|
+
if (['sourceMode','publicMirror','publicFallback','confirmPublicMirror','hostRegistryPlan'].some(key=>value[key]!==undefined) || reading && value.schemaVersion !== 1) fail('self-update-attempt-target');
|
|
66
|
+
source = { registry: PUBLIC_REGISTRY };
|
|
67
|
+
}
|
|
53
68
|
}
|
|
54
69
|
const pid = value.pid ?? this.pid;
|
|
55
70
|
if (!Number.isSafeInteger(pid) || pid < 1 || !reading && pid !== this.pid) fail('self-update-attempt-pid');
|
|
56
71
|
const taskPolicy = value.taskPolicy ?? 'wait-for-idle', confirmCancel = value.confirmCancel ?? false;
|
|
57
72
|
if (!['wait-for-idle', 'cancel-active'].includes(taskPolicy) || typeof confirmCancel !== 'boolean' || taskPolicy === 'cancel-active' && !confirmCancel || taskPolicy === 'wait-for-idle' && confirmCancel) fail('self-update-task-policy');
|
|
58
|
-
|
|
73
|
+
if (git && reading && value.schemaVersion !== 1) fail('self-update-attempt-target');
|
|
74
|
+
const result = { schemaVersion: publicFallback ? 3 : publicMirror ? 2 : 1, id, name: SELF, from: value.from, to: value.to, ...source, pid, startedAt: timestamp(value.startedAt ?? this.time()), taskPolicy, confirmCancel };
|
|
59
75
|
for (const key of ['previousSha256', 'nextSha256']) if (value[key] !== undefined) { if (!SHA.test(value[key])) fail('self-update-digest-invalid'); result[key] = value[key]; }
|
|
60
76
|
for (const key of ['previousFiles', 'nextFiles']) if (value[key] !== undefined) {
|
|
61
77
|
if (!object(value[key]) || Object.keys(value[key]).length === 0 || Object.keys(value[key]).length > 128) fail('self-update-files-invalid');
|
|
@@ -107,7 +123,7 @@ export class SelfUpdateStore {
|
|
|
107
123
|
if (typeof source.timedOut === 'boolean') result.packageResult.timedOut = source.timedOut;
|
|
108
124
|
if (typeof source.kind === 'string') result.packageResult.kind = this.text(source.kind, 64);
|
|
109
125
|
}
|
|
110
|
-
if (Array.isArray(value.registries)) result.registries = value.registries.slice(0, 8).map(registry => registry === null ? null :
|
|
126
|
+
if (Array.isArray(value.registries)) result.registries = value.registries.slice(0, 8).map(registry => registry === null ? null : approvedPublicRegistry(registry) ? registryOrigin(registry) : '<unsupported-registry>');
|
|
111
127
|
if (['registry', 'spec-host'].includes(value.failedAt)) result.failedAt = value.failedAt;
|
|
112
128
|
return result;
|
|
113
129
|
}
|