@mogragsigma/dsh-dual-host-plugin 0.0.0-stage → 0.33.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +58 -0
- package/LICENSE.en.md +94 -0
- package/README.md +88 -2
- package/bundle/ASSET_NOTICE.md +19 -0
- package/bundle/LICENSE +58 -0
- package/bundle/LICENSE.en.md +94 -0
- package/bundle/README.md +75 -0
- package/bundle/THIRD_PARTY_NOTICES.md +94 -0
- package/bundle/a2a-dispatches.js +38 -0
- package/bundle/a2a-endpoint.js +112 -0
- package/bundle/a2a-tools.js +11 -0
- package/bundle/a2a-worker.js +63 -0
- package/bundle/approval-auth.js +5 -0
- package/bundle/approval-chat.js +150 -0
- package/bundle/approval-feishu.js +52 -0
- package/bundle/approval-guidance.js +68 -0
- package/bundle/approval-http.js +8 -0
- package/bundle/approval-ledger.js +142 -0
- package/bundle/approval-local-relay.js +86 -0
- package/bundle/approval-receipts.js +62 -0
- package/bundle/approval-reference.js +33 -0
- package/bundle/approval-semantic-model.js +26 -0
- package/bundle/approval-semantics.js +51 -0
- package/bundle/approval-ui/app.js +1 -0
- package/bundle/approval-ui/index.html +1 -0
- package/bundle/approval-ui/style.css +1 -0
- package/bundle/approval-workbench.js +45 -0
- package/bundle/artifact-media.js +34 -0
- package/bundle/bounded-text.js +44 -0
- package/bundle/compatibility.json +980 -0
- package/bundle/cordis.patch.yml +5 -0
- package/bundle/delivery-approval.js +133 -0
- package/bundle/delivery-artifacts.js +52 -0
- package/bundle/delivery-commit.js +125 -0
- package/bundle/delivery-contract.js +42 -0
- package/bundle/delivery-git-read.js +217 -0
- package/bundle/delivery-index.js +23 -0
- package/bundle/delivery-journal.js +207 -0
- package/bundle/delivery-object-plan.js +138 -0
- package/bundle/delivery-preview.js +153 -0
- package/bundle/delivery-process-receipts.js +90 -0
- package/bundle/delivery-process.js +46 -0
- package/bundle/delivery-process.py +228 -0
- package/bundle/delivery-push-approval.js +89 -0
- package/bundle/delivery-push-plan.js +98 -0
- package/bundle/delivery-push-recovery.js +32 -0
- package/bundle/delivery-push.js +83 -0
- package/bundle/delivery-recovery.js +143 -0
- package/bundle/delivery-runtime.js +182 -0
- package/bundle/delivery-ssh.js +64 -0
- package/bundle/delivery-state.js +106 -0
- package/bundle/development-attention.js +35 -0
- package/bundle/development-bridge.js +136 -0
- package/bundle/development-command-review.js +110 -0
- package/bundle/development-container.js +110 -0
- package/bundle/development-contract.js +17 -0
- package/bundle/development-files.js +101 -0
- package/bundle/development-gate.js +236 -0
- package/bundle/development-model-budget.js +48 -0
- package/bundle/development-peer.js +155 -0
- package/bundle/development-plan.js +43 -0
- package/bundle/development-reconciliation.js +62 -0
- package/bundle/development-review.js +81 -0
- package/bundle/development-rules/AGENTS.md +51 -0
- package/bundle/development-runtime.js +68 -0
- package/bundle/development-source.js +48 -0
- package/bundle/development-test-runner.js +13 -0
- package/bundle/development-tools.js +45 -0
- package/bundle/development-worker-review.js +110 -0
- package/bundle/development-worker.js +68 -0
- package/bundle/development-workspace.js +54 -0
- package/bundle/diagnostics.js +78 -0
- package/bundle/distribution-lock.json +773 -0
- package/bundle/drained-process.js +26 -0
- package/bundle/durable-inbox.js +294 -0
- package/bundle/feishu-policy.js +24 -0
- package/bundle/gateway-maintenance.js +55 -0
- package/bundle/global-rules/AGENTS.md +83 -0
- package/bundle/im-delivery.js +60 -0
- package/bundle/index.js +445 -0
- package/bundle/intervention-actions.js +135 -0
- package/bundle/intervention-job-control.js +28 -0
- package/bundle/intervention-state.js +43 -0
- package/bundle/job-version.js +15 -0
- package/bundle/legacy-feishu-adapter.js +89 -0
- package/bundle/link-contract.js +80 -0
- package/bundle/maintenance-process-identity.js +93 -0
- package/bundle/model-selection.js +71 -0
- package/bundle/native-context.js +14 -0
- package/bundle/native-entry-admission.js +2 -0
- package/bundle/native-entry.js +58 -0
- package/bundle/native-file-reference.js +32 -0
- package/bundle/native-owner-origin.js +12 -0
- package/bundle/native-rules/AGENTS.md +199 -0
- package/bundle/native-tools.js +108 -0
- package/bundle/notification-artifacts.js +70 -0
- package/bundle/notification-contract.js +29 -0
- package/bundle/notification-defaults.js +81 -0
- package/bundle/notification-discovery.js +65 -0
- package/bundle/notification-endpoint.js +54 -0
- package/bundle/notification-feishu.js +51 -0
- package/bundle/notification-media-endpoint.js +94 -0
- package/bundle/notification-review.js +27 -0
- package/bundle/notification-targets.js +54 -0
- package/bundle/onboarding-activity.js +66 -0
- package/bundle/onboarding-agent-hold.js +94 -0
- package/bundle/onboarding-boundary.js +20 -0
- package/bundle/onboarding-cloud-contract.js +29 -0
- package/bundle/onboarding-cloud-file-review.js +58 -0
- package/bundle/onboarding-cloud-files.js +100 -0
- package/bundle/onboarding-cloud-im.js +34 -0
- package/bundle/onboarding-cloud-model-probe.js +53 -0
- package/bundle/onboarding-cloud-models.js +68 -0
- package/bundle/onboarding-cloud-operation.js +276 -0
- package/bundle/onboarding-cloud-package.js +38 -0
- package/bundle/onboarding-cloud-repositories.js +89 -0
- package/bundle/onboarding-cloud-retirement.js +59 -0
- package/bundle/onboarding-cloud-task-runtime.js +90 -0
- package/bundle/onboarding-cloud-web.js +85 -0
- package/bundle/onboarding-cloud.js +110 -0
- package/bundle/onboarding-coordinated-hold.js +94 -0
- package/bundle/onboarding-exclusive-rename.js +16 -0
- package/bundle/onboarding-existing-host.js +63 -0
- package/bundle/onboarding-existing-setup.js +123 -0
- package/bundle/onboarding-file-contract.js +31 -0
- package/bundle/onboarding-file-review-contract.js +38 -0
- package/bundle/onboarding-file-transfer.js +133 -0
- package/bundle/onboarding-handoff-remote.js +98 -0
- package/bundle/onboarding-handoff.js +112 -0
- package/bundle/onboarding-host-stop-observation.js +44 -0
- package/bundle/onboarding-host.js +254 -0
- package/bundle/onboarding-identity.js +9 -0
- package/bundle/onboarding-im-maintenance-native.js +30 -0
- package/bundle/onboarding-im-maintenance.js +70 -0
- package/bundle/onboarding-im.js +31 -0
- package/bundle/onboarding-inspection-guard.js +15 -0
- package/bundle/onboarding-install-fs.js +58 -0
- package/bundle/onboarding-installer.js +157 -0
- package/bundle/onboarding-local-pair-native.js +21 -0
- package/bundle/onboarding-local-pair.js +99 -0
- package/bundle/onboarding-maintenance-fs.js +69 -0
- package/bundle/onboarding-maintenance-plan.js +213 -0
- package/bundle/onboarding-maintenance-record.js +169 -0
- package/bundle/onboarding-maintenance.js +163 -0
- package/bundle/onboarding-model-probe.js +119 -0
- package/bundle/onboarding-models.js +107 -0
- package/bundle/onboarding-native-host.js +101 -0
- package/bundle/onboarding-native-probe.js +56 -0
- package/bundle/onboarding-native-runner.js +29 -0
- package/bundle/onboarding-node-bootstrap.py +678 -0
- package/bundle/onboarding-node.js +77 -0
- package/bundle/onboarding-notification-defaults.js +93 -0
- package/bundle/onboarding-package-source.js +33 -0
- package/bundle/onboarding-paths.js +58 -0
- package/bundle/onboarding-peer-binding.js +61 -0
- package/bundle/onboarding-peer-contract.js +12 -0
- package/bundle/onboarding-plugin-repair.js +116 -0
- package/bundle/onboarding-plugin-version.js +143 -0
- package/bundle/onboarding-remote-control.js +140 -0
- package/bundle/onboarding-remote-probe.js +40 -0
- package/bundle/onboarding-repositories.js +88 -0
- package/bundle/onboarding-repository.js +49 -0
- package/bundle/onboarding-runtime-activation.js +83 -0
- package/bundle/onboarding-runtime-artifacts-client.js +87 -0
- package/bundle/onboarding-runtime-artifacts.js +126 -0
- package/bundle/onboarding-runtime-extension.js +400 -0
- package/bundle/onboarding-runtime-inventory.js +88 -0
- package/bundle/onboarding-runtime-program.js +42 -0
- package/bundle/onboarding-runtime-reclaim-client.js +94 -0
- package/bundle/onboarding-runtime-reclaim-worker.js +63 -0
- package/bundle/onboarding-runtime-reclaim.js +132 -0
- package/bundle/onboarding-runtime-repair-client.js +50 -0
- package/bundle/onboarding-runtime-repair.js +88 -0
- package/bundle/onboarding-runtime-stop.js +90 -0
- package/bundle/onboarding-runtime-uninstall-client.js +88 -0
- package/bundle/onboarding-runtime-uninstall.js +167 -0
- package/bundle/onboarding-runtime-version-client.js +138 -0
- package/bundle/onboarding-runtime-version.js +145 -0
- package/bundle/onboarding-schema.js +42 -0
- package/bundle/onboarding-self-disable.js +3 -0
- package/bundle/onboarding-self-lifecycle.js +95 -0
- package/bundle/onboarding-self-maintenance.js +52 -0
- package/bundle/onboarding-self-remove.js +3 -0
- package/bundle/onboarding-self-stop.js +85 -0
- package/bundle/onboarding-ssh-forward.js +48 -0
- package/bundle/onboarding-ssh.js +105 -0
- package/bundle/onboarding-state.js +95 -0
- package/bundle/onboarding-task-runtime-contract.js +38 -0
- package/bundle/onboarding-task-runtime-native.js +80 -0
- package/bundle/onboarding-task-runtime.js +66 -0
- package/bundle/onboarding-token-plan.js +52 -0
- package/bundle/onboarding-version-activation-client.js +48 -0
- package/bundle/onboarding-version-candidate.js +96 -0
- package/bundle/onboarding-version-repair.js +128 -0
- package/bundle/package-lock.json +773 -0
- package/bundle/package.json +99 -0
- package/bundle/peer-file-fs.js +62 -0
- package/bundle/peer-file-migration.js +59 -0
- package/bundle/peer-file-review.js +107 -0
- package/bundle/peer-files.js +157 -0
- package/bundle/peer-mailbox.js +75 -0
- package/bundle/protocol.js +17 -0
- package/bundle/recovery.js +40 -0
- package/bundle/repository-catalog.js +85 -0
- package/bundle/repository-gitee.js +76 -0
- package/bundle/repository-managed.js +46 -0
- package/bundle/repository-writer.js +43 -0
- package/bundle/rules/AGENTS.md +22 -0
- package/bundle/runtime-im-lock.json +11577 -0
- package/bundle/runtime-im-package.json +18 -0
- package/bundle/runtime-lock.json +10152 -0
- package/bundle/runtime-package.json +17 -0
- package/bundle/scheduler-migration.js +45 -0
- package/bundle/search-contract.js +19 -0
- package/bundle/skills/dsh-dual-end/SKILL.md +12 -0
- package/bundle/skills/task-a2a/SKILL.md +55 -0
- package/bundle/skills/task-a2a-worker/SKILL.md +23 -0
- package/bundle/skills/task-approval/SKILL.md +128 -0
- package/bundle/skills/task-artifacts/SKILL.md +46 -0
- package/bundle/skills/task-development/SKILL.md +144 -0
- package/bundle/skills/task-diagnostics/SKILL.md +41 -0
- package/bundle/skills/task-direct-link/SKILL.md +143 -0
- package/bundle/skills/task-file-transfer/SKILL.md +107 -0
- package/bundle/skills/task-handoff/SKILL.md +23 -0
- package/bundle/skills/task-intake/SKILL.md +13 -0
- package/bundle/skills/task-notify/SKILL.md +102 -0
- package/bundle/skills/task-onboarding/SKILL.md +708 -0
- package/bundle/skills/task-recovery/SKILL.md +54 -0
- package/bundle/skills/task-repository/SKILL.md +145 -0
- package/bundle/skills/task-research/SKILL.md +43 -0
- package/bundle/skills/task-schedule/SKILL.md +79 -0
- package/bundle/skills/task-sidebar/SKILL.md +122 -0
- package/bundle/skills/task-workbench/SKILL.md +30 -0
- package/bundle/skills/task-worker/SKILL.md +88 -0
- package/bundle/source-search.js +89 -0
- package/bundle/source-web.js +17 -0
- package/bundle/ssh-connector.js +24 -0
- package/bundle/store.js +102 -0
- package/bundle/task-a2a.js +298 -0
- package/bundle/task-artifacts.js +179 -0
- package/bundle/task-board-a2a.js +55 -0
- package/bundle/task-board-development.js +83 -0
- package/bundle/task-board-planning.js +84 -0
- package/bundle/task-board.js +132 -0
- package/bundle/task-branch.js +2 -0
- package/bundle/task-catalog.js +77 -0
- package/bundle/task-context.js +40 -0
- package/bundle/task-envelope.js +96 -0
- package/bundle/task-interventions.js +54 -0
- package/bundle/task-jobs.js +156 -0
- package/bundle/task-notifications.js +132 -0
- package/bundle/task-results.js +16 -0
- package/bundle/task-scheduler.js +77 -0
- package/bundle/task-sources.js +101 -0
- package/bundle/task-trigger-time.js +46 -0
- package/bundle/task-triggers.js +157 -0
- package/bundle/task-worker.js +73 -0
- package/bundle/task-workflows.js +117 -0
- package/bundle/tools.js +13 -0
- package/bundle/workbench-assets/asset-provenance.json +26 -0
- package/bundle/workbench-assets/whale-ui-states.png +0 -0
- package/bundle/workbench-client.js +811 -0
- package/bundle/workbench-decisions.js +48 -0
- package/bundle/workbench-host.js +122 -0
- package/bundle/workbench-im-identity.js +51 -0
- package/bundle/workbench-proxy.js +127 -0
- package/bundle/worker-rules/AGENTS.md +84 -0
- package/bundle/worker-tools.js +13 -0
- package/compatibility.json +980 -0
- package/cordis.patch.yml +3 -0
- package/package.json +57 -4
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// Internal offline version transaction. The original installer must explicitly
|
|
2
|
+
// provide this contract, its original inventory, an exclusive lock and stop proof.
|
|
3
|
+
// No arbitrary path, network fetch, Host startup or rules installation is exposed.
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {randomUUID,createHmac,timingSafeEqual} from 'node:crypto';
|
|
6
|
+
import {fs,hash as sha,bytes,snapshot,sameIdentity,syncWrite,atomicState,ancestors} from './onboarding-install-fs.js';
|
|
7
|
+
import {statMaybe,syncDirectory} from './onboarding-maintenance-fs.js';
|
|
8
|
+
import {renameExclusive} from './onboarding-exclusive-rename.js';
|
|
9
|
+
import {createVersionRepair} from './onboarding-version-repair.js';
|
|
10
|
+
const hash=x=>sha(JSON.stringify(x)),fail=c=>{throw Error('ONBOARDING_PLUGIN_VERSION_'+c);};
|
|
11
|
+
const exact=(x,k)=>x&&typeof x==='object'&&!Array.isArray(x)&&Object.keys(x).sort().join()===k.slice().sort().join();
|
|
12
|
+
const uuid=x=>typeof x==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(x);
|
|
13
|
+
const digest=x=>typeof x==='string'&&/^[a-f0-9]{64}$/.test(x);
|
|
14
|
+
const version=x=>typeof x==='string'&&x.length<100&&/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(x);
|
|
15
|
+
const relative=x=>typeof x==='string'&&x.length<=240&&/^[A-Za-z0-9_./-]+$/.test(x)&&x.split('/').every(p=>p&&p!=='.'&&p!=='..'&&p!=='node_modules'&&p!=='.control');
|
|
16
|
+
const id=s=>({dev:s.dev,ino:s.ino,uid:s.uid,mode:s.mode&0o777});
|
|
17
|
+
const terminal=j=>['committed','rolled_back'].includes(j.state);
|
|
18
|
+
const stateView=j=>({contract:1,id:j.id,state:j.state,fromVersion:j.before.version,toVersion:j.after.version,scope:'stopped_owned_plugin_image_only',hostStarted:false,activationVerified:false,globalRulesChanged:false,credentialsChanged:false,backupsRetained:true,recoveryRequired:!terminal(j)});
|
|
19
|
+
function manifest(value){
|
|
20
|
+
if(!Array.isArray(value)||!value.length||value.length>512)fail('MANIFEST');
|
|
21
|
+
const seen=new Set(),dirs=new Set(['']);
|
|
22
|
+
for(const f of value){if(!exact(f,['path','sha256'])||!relative(f.path)||!digest(f.sha256)||seen.has(f.path.toLowerCase()))fail('MANIFEST');seen.add(f.path.toLowerCase());let p=path.posix.dirname(f.path);while(p!=='.'){dirs.add(p);p=path.posix.dirname(p);}}
|
|
23
|
+
if(dirs.size>2048||[...dirs].some(p=>seen.has(p.toLowerCase()))||new Set([...dirs].map(p=>p.toLowerCase())).size!==dirs.size||!value.some(f=>f.path==='package.json'))fail('MANIFEST');
|
|
24
|
+
return {files:value.map(f=>({...f})).sort((a,b)=>a.path.localeCompare(b.path,'en')),dirs:[...dirs].sort()};
|
|
25
|
+
}
|
|
26
|
+
function release(value){
|
|
27
|
+
if(!exact(value,['version','manifest','image'])||!version(value.version)||!Array.isArray(value.image))fail('INVENTORY');
|
|
28
|
+
const m=manifest(value.manifest),expected=new Map([...m.dirs.map(p=>[p,null]),...m.files.map(f=>[f.path,f.sha256])]);
|
|
29
|
+
const seen=new Set();for(const e of value.image){
|
|
30
|
+
if(!e||!expected.has(e.path)||seen.has(e.path)||!['dev','ino','uid','mode'].every(k=>Number.isSafeInteger(e[k])&&e[k]>=0))fail('INVENTORY');seen.add(e.path);
|
|
31
|
+
if(expected.get(e.path)===null){if(!exact(e,['path','kind','dev','ino','uid','mode'])||e.kind!=='directory'||e.mode!==0o700)fail('INVENTORY');}
|
|
32
|
+
else if(!exact(e,['path','kind','dev','ino','uid','mode','bytes','sha256'])||e.kind!=='file'||e.mode!==0o600||e.sha256!==expected.get(e.path)||!Number.isSafeInteger(e.bytes)||e.bytes<0||e.bytes>4194304)fail('INVENTORY');
|
|
33
|
+
}
|
|
34
|
+
if(seen.size!==expected.size)fail('INVENTORY');return {version:value.version,manifest:m.files,image:structuredClone(value.image).sort((a,b)=>a.path.localeCompare(b.path,'en'))};
|
|
35
|
+
}
|
|
36
|
+
export function createPluginVersion({root,operationId,runtimeId,proof,initial,exclusive,verifyOwnedStopped,moveImage=renameExclusive,now=Date.now,hook,verifyRepairCandidate}){
|
|
37
|
+
if(!path.isAbsolute(root)||path.resolve(root)!==root||!uuid(operationId)||!uuid(runtimeId)||!digest(proof)||typeof exclusive!=='function'||typeof verifyOwnedStopped!=='function'||typeof moveImage!=='function'||typeof process.getuid!=='function')fail('CONTRACT');
|
|
38
|
+
const original=release(initial),binding=hash({root,operationId,runtimeId,initial:original});
|
|
39
|
+
const control=path.join(root,'.control/runtime'),folder=path.join(control,'plugin-versions'),target=path.join(root,'runtime/plugin'),planFile=path.join(control,'plugin-version-plan.json');
|
|
40
|
+
const txn=id=>path.join(folder,id),journal=id=>path.join(txn(id),'journal.json');
|
|
41
|
+
const seal=body=>({...body,signature:createHmac('sha256',proof).update(JSON.stringify(body)).digest('hex')});
|
|
42
|
+
function unseal(v){if(!v||!digest(v.signature))fail('JOURNAL_REVIEW');const{signature,...body}=v;if(!timingSafeEqual(Buffer.from(signature,'hex'),Buffer.from(seal(body).signature,'hex')))fail('JOURNAL_REVIEW');return body;}
|
|
43
|
+
async function signedFile(p){const s=await snapshot(p,33554432);if(s.missing)fail('NOT_FOUND');if(s.mode!==0o600)fail('JOURNAL_REVIEW');try{return unseal(JSON.parse(bytes(s)));}catch{fail('JOURNAL_REVIEW');}}
|
|
44
|
+
async function privateDir(p){await ancestors(p);const s=await fs.lstat(p);if(!s.isDirectory()||s.isSymbolicLink()||s.uid!==process.getuid()||(s.mode&0o777)!==0o700)fail('DIRECTORY_REVIEW');return id(s);}
|
|
45
|
+
async function guard(){const p=await verifyOwnedStopped();if(!exact(p,['operationId','runtimeId','stopped','ownershipVerified'])||p.operationId!==operationId||p.runtimeId!==runtimeId||p.stopped!==true||p.ownershipVerified!==true)fail('STOP_OR_OWNERSHIP_REQUIRED');await privateDir(control);}
|
|
46
|
+
async function image(p){
|
|
47
|
+
await ancestors(path.dirname(p));if(!await statMaybe(p))return null;
|
|
48
|
+
const rows=[];let total=0;
|
|
49
|
+
async function walk(dir,name){
|
|
50
|
+
const s=await fs.lstat(dir);if(rows.length>=4096||s.isSymbolicLink()||s.uid!==process.getuid())fail('UNSAFE_IMAGE');
|
|
51
|
+
if(s.isDirectory()){if((s.mode&0o777)!==0o700)fail('MODE_REVIEW');rows.push({path:name,kind:'directory',...id(s)});for(const child of (await fs.readdir(dir)).sort()){const rel=name?name+'/'+child:child;if(!relative(rel))fail('UNSAFE_IMAGE');await walk(path.join(dir,child),rel);}if(!sameIdentity(await fs.lstat(dir),s))fail('IMAGE_DRIFT');}
|
|
52
|
+
else if(s.isFile()&&s.nlink===1){const b=await snapshot(dir,4194304);if(!sameIdentity(s,b)||b.mode!==0o600)fail('IMAGE_DRIFT');total+=b.size;if(total>16777216)fail('SIZE_LIMIT');rows.push({path:name,kind:'file',...id(s),bytes:b.size,sha256:b.sha256});}
|
|
53
|
+
else fail('UNSAFE_IMAGE');
|
|
54
|
+
}
|
|
55
|
+
await walk(p,'');return rows.sort((a,b)=>a.path.localeCompare(b.path,'en'));
|
|
56
|
+
}
|
|
57
|
+
const matches=async(p,expected)=>hash(await image(p))===hash(expected);
|
|
58
|
+
async function verifyImage(p,expected){if(!await matches(p,expected))fail('IMAGE_DRIFT');}
|
|
59
|
+
async function readAll(){
|
|
60
|
+
if(!await statMaybe(folder))return [];await privateDir(folder);const names=await fs.readdir(folder);if(names.length>128||names.some(n=>!uuid(n)))fail('JOURNAL_REVIEW');
|
|
61
|
+
const rows=[];for(const name of names){const j=await signedFile(journal(name));
|
|
62
|
+
if(j.binding!==binding||j.id!==name||j.schema!==1||!Number.isSafeInteger(j.sequence)||j.sequence<1||!digest(j.planHash)||!digest(j.parentHash)||!['preparing','applying','committed','rolling_back','rolled_back','needs_review'].includes(j.state)||!uuid(j.candidateId))fail('JOURNAL_REVIEW');
|
|
63
|
+
if(hash(await privateDir(txn(name)))!==hash(j.directoryIdentity)||hash(release(j.before))!==hash(j.before)||!version(j.after?.version)||j.after.version===j.before.version||hash(manifest(j.after.manifest).files)!==hash(j.after.manifest))fail('JOURNAL_REVIEW');
|
|
64
|
+
if(j.stage!==null&&hash(release({...j.after,image:j.stage}))!==hash({...j.after,image:j.stage}))fail('JOURNAL_REVIEW');
|
|
65
|
+
if(['applying','committed','rolling_back'].includes(j.state)&&!j.stage)fail('JOURNAL_REVIEW');
|
|
66
|
+
if((await fs.readdir(txn(name))).some(n=>!['journal.json','stage','backup','discarded','repairs'].includes(n)))fail('JOURNAL_REVIEW');await repair.validate(j);rows.push(j);
|
|
67
|
+
}
|
|
68
|
+
rows.sort((a,b)=>a.sequence-b.sequence);let current=original,parent=binding;
|
|
69
|
+
for(let n=0;n<rows.length;n++){const j=rows[n];if(j.sequence!==n+1||j.parentHash!==parent||hash(j.before)!==hash(current)||n<rows.length-1&&!terminal(j))fail('JOURNAL_REVIEW');if(terminal(j)&&n<rows.length-1)current=repair.current(j);parent=hash(j);}
|
|
70
|
+
return rows;
|
|
71
|
+
}
|
|
72
|
+
function active(rows){const j=rows.at(-1);if(j&&!terminal(j))fail('RECOVERY_REQUIRED');return j?repair.current(j):original;}
|
|
73
|
+
async function loadPlan(){const p=await signedFile(planFile);if(p.binding!==binding||!uuid(p.id)||!['switch','rollback'].includes(p.kind)||hash({...p,fingerprint:undefined})!==p.fingerprint)fail('PLAN_DRIFT');return p;}
|
|
74
|
+
async function savePlan(p){if(await statMaybe(planFile))await loadPlan();const value={...p,binding,id:randomUUID(),expiresAt:now()+300000};value.fingerprint=hash(value);await atomicState(planFile,seal(value));return value;}
|
|
75
|
+
async function save(j){if(Buffer.byteLength(JSON.stringify(j))>33554432)fail('SIZE_LIMIT');await atomicState(journal(j.id),seal(j));}
|
|
76
|
+
async function candidate(a){
|
|
77
|
+
if(!exact(a,['candidateId','version','manifest'])||!uuid(a.candidateId)||!version(a.version))fail('ARGUMENTS');
|
|
78
|
+
const m=manifest(a.manifest),source=path.join(control,'plugin-candidates',a.candidateId,'plugin'),observed=await image(source);if(!observed)fail('CANDIDATE_MISSING');
|
|
79
|
+
const r=release({version:a.version,manifest:m.files,image:observed}),pkg=JSON.parse(bytes(await snapshot(path.join(source,'package.json'),262144)));
|
|
80
|
+
if(pkg.name!=='@mogragsigma/dsh-dual-host-plugin'||pkg.version!==r.version)fail('PACKAGE_MISMATCH');return {candidateId:a.candidateId,source,release:r};
|
|
81
|
+
}
|
|
82
|
+
async function verifyCurrent(current){await verifyImage(target,current.image);const pkg=JSON.parse(bytes(await snapshot(path.join(target,'package.json'),262144)));if(pkg.name!=='@mogragsigma/dsh-dual-host-plugin'||pkg.version!==current.version)fail('PACKAGE_MISMATCH');const dev=(await fs.lstat(control)).dev;if(current.image.some(x=>x.dev!==dev))fail('CROSS_DEVICE');}
|
|
83
|
+
async function preview(a){return exclusive(async()=>{
|
|
84
|
+
await guard();const rows=await readAll(),current=active(rows);await verifyCurrent(current);const c=await candidate(a),dev=(await fs.lstat(control)).dev;if(c.release.version===current.version)fail('SAME_VERSION');if(c.release.image.some(x=>x.dev!==dev))fail('CROSS_DEVICE');
|
|
85
|
+
const p=await savePlan({kind:'switch',before:current,candidate:c.release,candidateId:c.candidateId,parentHash:rows.length?hash(rows.at(-1)):binding,sequence:rows.length+1});
|
|
86
|
+
const old=new Map(current.manifest.map(f=>[f.path,f.sha256])),next=new Map(c.release.manifest.map(f=>[f.path,f.sha256]));
|
|
87
|
+
return {id:p.id,fingerprint:p.fingerprint,expiresAt:p.expiresAt,fromVersion:current.version,toVersion:c.release.version,scope:'stopped_owned_plugin_image_only',changes:[...new Set([...old.keys(),...next.keys()])].sort().filter(n=>old.get(n)!==next.get(n)).map(n=>({path:n,action:!old.has(n)?'add':!next.has(n)?'remove':'replace'})),hostStarted:false,activationVerified:false,globalRulesChanged:false,credentialsChanged:false,backupsRetained:true};
|
|
88
|
+
});}
|
|
89
|
+
async function move(from,to){await moveImage(from,to);await syncDirectory(path.dirname(from));if(path.dirname(from)!==path.dirname(to))await syncDirectory(path.dirname(to));}
|
|
90
|
+
async function restore(j){
|
|
91
|
+
await guard();const dir=txn(j.id),backup=path.join(dir,'backup'),discarded=path.join(dir,'discarded');
|
|
92
|
+
try{
|
|
93
|
+
if(await matches(target,j.before.image)&&!await statMaybe(backup)){j.state='rolled_back';await save(j);return stateView(j);}
|
|
94
|
+
await verifyImage(backup,j.before.image);
|
|
95
|
+
if(await statMaybe(target)){if(!j.stage)fail('IMAGE_DRIFT');await verifyImage(target,repair.after(j));await guard();await move(target,discarded);await hook?.('after_rollback_capture');}
|
|
96
|
+
else if(await statMaybe(discarded)){if(!j.stage)fail('IMAGE_DRIFT');await verifyImage(discarded,repair.after(j));}
|
|
97
|
+
await guard();await verifyImage(backup,j.before.image);await move(backup,target);await hook?.('after_restore');await verifyImage(target,j.before.image);
|
|
98
|
+
j.state='rolled_back';await save(j);return stateView(j);
|
|
99
|
+
}catch(e){j.state='needs_review';j.review='changed_or_unverified_image_preserved';await save(j);return stateView(j);}
|
|
100
|
+
}
|
|
101
|
+
async function apply(a){return exclusive(async()=>{
|
|
102
|
+
if(!exact(a,['id','fingerprint','confirm'])||!uuid(a.id)||!digest(a.fingerprint)||a.confirm!==true)fail('CONFIRMATION_REQUIRED');await guard();const rows=await readAll(),prior=rows.find(x=>x.id===a.id);if(prior){if(prior.planHash!==a.fingerprint)fail('PLAN_DRIFT');return {...stateView(prior),notResent:true};}
|
|
103
|
+
const current=active(rows),p=await loadPlan();if(p.kind!=='switch'||p.id!==a.id||p.fingerprint!==a.fingerprint||p.expiresAt<=now()||p.sequence!==rows.length+1||p.parentHash!==(rows.length?hash(rows.at(-1)):binding)||hash(p.before)!==hash(current))fail('PLAN_DRIFT');
|
|
104
|
+
await verifyCurrent(current);const c=await candidate({candidateId:p.candidateId,version:p.candidate.version,manifest:p.candidate.manifest});if(hash(c.release)!==hash(p.candidate))fail('PLAN_DRIFT');if(rows.length>=128)fail('HISTORY_FULL');
|
|
105
|
+
if(!await statMaybe(folder)){await fs.mkdir(folder,{mode:0o700});await syncDirectory(control);}await privateDir(folder);
|
|
106
|
+
const dir=txn(p.id);await fs.mkdir(dir,{mode:0o700});await syncDirectory(folder);
|
|
107
|
+
const j={schema:1,id:p.id,binding,sequence:p.sequence,parentHash:p.parentHash,planHash:p.fingerprint,before:current,after:{version:c.release.version,manifest:c.release.manifest},candidateId:p.candidateId,state:'preparing',stage:null,directoryIdentity:await privateDir(dir)};await save(j);
|
|
108
|
+
try{
|
|
109
|
+
const stage=path.join(dir,'stage');for(const name of manifest(c.release.manifest).dirs.sort((a,b)=>a.split('/').length-b.split('/').length||a.localeCompare(b)))await fs.mkdir(path.join(stage,name),{mode:0o700});
|
|
110
|
+
await hook?.('stage_created');for(const f of c.release.manifest){await guard();const s=await snapshot(path.join(c.source,f.path),4194304);if(s.sha256!==f.sha256)fail('CANDIDATE_DRIFT');await syncWrite(path.join(stage,f.path),bytes(s));}
|
|
111
|
+
for(const name of manifest(c.release.manifest).dirs.sort((a,b)=>b.length-a.length))await syncDirectory(path.join(stage,name));await syncDirectory(dir);
|
|
112
|
+
j.stage=(await candidateImage(stage,c.release)).image;j.state='applying';await save(j);await hook?.('stage_ready');
|
|
113
|
+
await guard();await verifyImage(target,j.before.image);await hook?.('before_capture');await move(target,path.join(dir,'backup'));await hook?.('after_capture');await verifyImage(path.join(dir,'backup'),j.before.image);
|
|
114
|
+
await guard();await verifyImage(stage,j.stage);await move(stage,target);await hook?.('after_publish');await verifyImage(target,j.stage);await verifyImage(path.join(dir,'backup'),j.before.image);await guard();
|
|
115
|
+
j.state='committed';await save(j);await hook?.('after_commit');return stateView(j);
|
|
116
|
+
}catch(e){if(j.state==='committed')throw e;j.state='needs_review';j.review='operation_interrupted';await save(j);return stateView(j);}
|
|
117
|
+
});}
|
|
118
|
+
async function candidateImage(p,r){return release({version:r.version,manifest:r.manifest,image:await image(p)});}
|
|
119
|
+
async function latest(id){if(!uuid(id))fail('ARGUMENTS');const rows=await readAll(),j=rows.at(-1);if(!j||j.id!==id)fail('NOT_LATEST');return j;}
|
|
120
|
+
async function previewRollback(a){return exclusive(async()=>{
|
|
121
|
+
if(!exact(a,['id']))fail('ARGUMENTS');await guard();const j=await latest(a.id);if(j.state!=='committed')fail('NOT_COMMITTED');repair.settled(j);await verifyImage(target,repair.after(j));await verifyImage(path.join(txn(j.id),'backup'),j.before.image);
|
|
122
|
+
const p=await savePlan({kind:'rollback',transactionId:j.id,journalHash:hash(j)});return {id:p.id,transactionId:j.id,fingerprint:p.fingerprint,expiresAt:p.expiresAt,fromVersion:j.after.version,toVersion:j.before.version,scope:'stopped_owned_plugin_image_only',hostStarted:false,activationVerified:false,backupsRetained:true};
|
|
123
|
+
});}
|
|
124
|
+
async function rollback(a){return exclusive(async()=>{
|
|
125
|
+
if(!exact(a,['id','planId','fingerprint','confirm'])||!uuid(a.planId)||!digest(a.fingerprint)||a.confirm!==true)fail('CONFIRMATION_REQUIRED');await guard();const j=await latest(a.id),p=await loadPlan();
|
|
126
|
+
if(j.state!=='committed'||p.kind!=='rollback'||p.id!==a.planId||p.transactionId!==j.id||p.fingerprint!==a.fingerprint||p.expiresAt<=now()||p.journalHash!==hash(j))fail('PLAN_DRIFT');
|
|
127
|
+
repair.settled(j);await verifyImage(target,repair.after(j));await verifyImage(path.join(txn(j.id),'backup'),j.before.image);j.state='rolling_back';await save(j);return restore(j);
|
|
128
|
+
});}
|
|
129
|
+
async function recover(a){return exclusive(async()=>{if(!exact(a,['id','confirm'])||a.confirm!==true)fail('CONFIRMATION_REQUIRED');await guard();const j=await latest(a.id);repair.settled(j);if(terminal(j))return {...stateView(j),notResent:true};if(j.stage){j.state='rolling_back';await save(j);}return restore(j);});}
|
|
130
|
+
async function status(a){return exclusive(async()=>{if(!exact(a,['id'])||!uuid(a.id))fail('ARGUMENTS');const j=(await readAll()).find(j=>j.id===a.id);if(!j)fail('NOT_FOUND');return {...stateView(j),historical:true};});}
|
|
131
|
+
async function ownership(){return exclusive(async()=>{await guard();const rows=await readAll(),current=active(rows);await verifyCurrent(current);return structuredClone(current);});}
|
|
132
|
+
// Read-only signed identity for runtime admission. This does not certify a
|
|
133
|
+
// stopped Host, authorize a move, or infer loaded code from files on disk.
|
|
134
|
+
async function effective(){return exclusive(async()=>{await privateDir(control);const current=active(await readAll());await verifyCurrent(current);return structuredClone(current);});}
|
|
135
|
+
// Signed release identity, not a disk-to-ledger rebase or a repair operation.
|
|
136
|
+
async function activationBinding(){return exclusive(async()=>{
|
|
137
|
+
await privateDir(control);const rows=await readAll(),current=active(rows),j=rows.at(-1);
|
|
138
|
+
if(!j)fail('ACTIVATION_VERSION_REQUIRED');repair.settled(j);
|
|
139
|
+
return {transactionId:j.id,state:j.state,historyHash:hash(j),release:structuredClone(current)};
|
|
140
|
+
});}
|
|
141
|
+
const repair=createVersionRepair({root,operationId,runtimeId,proof,original,readAll,save,guard,privateDir,verifyImage,readImage:image,now,hook,verifyRepairCandidate});
|
|
142
|
+
return {preview,apply,previewRollback,rollback,recover,status,ownership,effective,activationBinding,repair:(name,args)=>exclusive(()=>repair.action(name,args)),repairBinding:()=>exclusive(()=>repair.binding())};
|
|
143
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// Fixed private SSH program. No network listener, model tool or arbitrary command interface.
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import {constants} from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import {createHash,createHmac,randomUUID,timingSafeEqual} from 'node:crypto';
|
|
7
|
+
const OWNER='dsh-dual-host-onboarding';
|
|
8
|
+
const hash=x=>createHash('sha256').update(typeof x==='string'||Buffer.isBuffer(x)?x:JSON.stringify(x)).digest('hex');
|
|
9
|
+
const fail=code=>{throw Error('ONBOARDING_CLOUD_'+code);};
|
|
10
|
+
const uuid=x=>typeof x==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(x);
|
|
11
|
+
const hex=x=>typeof x==='string'&&/^[a-f0-9]{64}$/.test(x);
|
|
12
|
+
const sign=(body,proof)=>createHmac('sha256',proof).update(JSON.stringify(body)).digest('hex');
|
|
13
|
+
const signed=(body,proof)=>({...body,signature:sign(body,proof)});
|
|
14
|
+
function verified(value,proof){if(!value||!hex(value.signature))fail('JOURNAL_REVIEW');const {signature,...body}=value;if(!timingSafeEqual(Buffer.from(signature,'hex'),Buffer.from(sign(body,proof),'hex')))fail('JOURNAL_REVIEW');return body;}
|
|
15
|
+
const exact=(x,keys)=>x&&typeof x==='object'&&!Array.isArray(x)&&Object.keys(x).sort().join()===keys.sort().join();
|
|
16
|
+
const identity=s=>({dev:s.dev,ino:s.ino,uid:s.uid,mode:s.mode&0o777});
|
|
17
|
+
const same=(a,b)=>a.dev===b.dev&&a.ino===b.ino&&a.uid===b.uid&&a.mode===b.mode;
|
|
18
|
+
const relative=p=>typeof p==='string'&&p.length<=256&&p.startsWith('plugin/')&&p.split('/').every(s=>s&&s!=='.'&&s!=='..'&&s!=='node_modules'&&!/[\x00-\x1f\x7f\\]/.test(s));
|
|
19
|
+
async function stat(p){try{return await fs.lstat(p);}catch(e){if(e.code==='ENOENT')return null;throw e;}}
|
|
20
|
+
async function regular(p,limit=8388608){
|
|
21
|
+
const s=await stat(p);if(!s)return null;
|
|
22
|
+
if(!s.isFile()||s.isSymbolicLink()||s.nlink!==1||s.size>limit)fail('FILE_REVIEW');
|
|
23
|
+
const h=await fs.open(p,constants.O_RDONLY|constants.O_NOFOLLOW);
|
|
24
|
+
try{const a=await h.stat();if(!same(identity(a),identity(s)))fail('FILE_REVIEW');const data=await h.readFile();const b=await h.stat();if(a.mtimeMs!==b.mtimeMs||a.size!==b.size)fail('FILE_REVIEW');return {data,identity:identity(s),sha256:hash(data)};}finally{await h.close();}
|
|
25
|
+
}
|
|
26
|
+
async function writeNew(p,data){const h=await fs.open(p,'wx',0o600);try{await h.writeFile(data);await h.sync();}finally{await h.close();}}
|
|
27
|
+
async function syncDir(p){const h=await fs.open(p,'r');try{await h.sync();}finally{await h.close();}}
|
|
28
|
+
async function atomicJSON(p,value){
|
|
29
|
+
const temp=p+'.'+randomUUID()+'.tmp';
|
|
30
|
+
try{await writeNew(temp,JSON.stringify(value));await fs.rename(temp,p);await syncDir(path.dirname(p));}finally{await fs.unlink(temp).catch(e=>{if(e.code!=='ENOENT')throw e;});}
|
|
31
|
+
}
|
|
32
|
+
async function processInfo(pid=process.pid){
|
|
33
|
+
if(process.platform!=='linux')return {platform:process.platform,pid,start:null,boot:null};
|
|
34
|
+
const raw=await fs.readFile('/proc/'+pid+'/stat','utf8'),start=raw.slice(raw.lastIndexOf(')')+2).split(' ')[19];
|
|
35
|
+
return {platform:'linux',pid,start,boot:(await fs.readFile('/proc/sys/kernel/random/boot_id','utf8')).trim()};
|
|
36
|
+
}
|
|
37
|
+
async function processActive(p){
|
|
38
|
+
if(!p)return false;if(!Number.isSafeInteger(p.pid)||p.pid<1)fail('JOURNAL_REVIEW');
|
|
39
|
+
try{if(p.platform==='linux'){const now=await processInfo(p.pid);return now.start===p.start&&now.boot===p.boot;}process.kill(p.pid,0);return true;}
|
|
40
|
+
catch(e){if(['ENOENT','ESRCH'].includes(e.code))return false;fail('PROCESS_REVIEW');}
|
|
41
|
+
}
|
|
42
|
+
function base(q){
|
|
43
|
+
if(!q||!uuid(q.operationId)||!uuid(q.installationId)||!hex(q.proof)||!hex(q.planHash)||typeof q.root!=='string'||q.root.length>700||q.root.split(path.sep).length>64||!path.isAbsolute(q.root)||path.normalize(q.root)!==q.root||/[\x00-\x1f\x7f]/.test(q.root)||path.basename(q.root)!=='host-'+q.installationId)fail('ARGUMENTS');
|
|
44
|
+
if(q.root===os.homedir()||path.dirname(q.root)==='/')fail('UNSAFE_ROOT');
|
|
45
|
+
return {owner:path.join(q.root,'.dsh-onboarding-owner.json'),journal:path.join(q.root,'.control/journal.json')};
|
|
46
|
+
}
|
|
47
|
+
function manifest(files,withData){
|
|
48
|
+
if(!Array.isArray(files)||!files.length||files.length>512)fail('SOURCE_REVIEW');
|
|
49
|
+
let total=0,last='';const result=[];
|
|
50
|
+
for(const f of files){
|
|
51
|
+
if(!exact(f,withData?['path','bytes','sha256','mode','data']:['path','bytes','sha256','mode'])||!relative(f.path)||f.path<=last||!Number.isSafeInteger(f.bytes)||f.bytes<0||f.bytes>4194304||!hex(f.sha256)||f.mode!==0o600)fail('SOURCE_REVIEW');
|
|
52
|
+
if(withData){if(typeof f.data!=='string'||f.data.length>5592408)fail('SOURCE_REVIEW');const b=Buffer.from(f.data,'base64');if(b.toString('base64')!==f.data||b.length!==f.bytes||hash(b)!==f.sha256)fail('SOURCE_REVIEW');}
|
|
53
|
+
total+=f.bytes;if(total>8388608)fail('SOURCE_REVIEW');last=f.path;result.push({path:f.path,bytes:f.bytes,sha256:f.sha256,mode:f.mode});
|
|
54
|
+
}
|
|
55
|
+
if(!result.some(x=>x.path==='plugin/package.json')||Buffer.byteLength(JSON.stringify(result))>65536)fail('SOURCE_REVIEW');return result;
|
|
56
|
+
}
|
|
57
|
+
async function checkAncestors(root,expected=null){
|
|
58
|
+
let p=path.parse(root).root;const names=[p];for(const x of root.split(path.sep).filter(Boolean)){p=path.join(p,x);names.push(p);}
|
|
59
|
+
if(expected&&(!Array.isArray(expected)||expected.length!==names.length||expected.some((x,i)=>x.path!==names[i])))fail('BASELINE_DRIFT');
|
|
60
|
+
const result=[];
|
|
61
|
+
for(let i=0;i<names.length;i++){
|
|
62
|
+
const s=await stat(names[i]);if(s&&(s.isSymbolicLink()||!s.isDirectory()))fail('UNSAFE_PATH');
|
|
63
|
+
if(expected){const e=expected[i];if(e.missing?s!==null:!s||!same(e,identity(s)))fail('BASELINE_DRIFT');}
|
|
64
|
+
result.push(s?{path:names[i],...identity(s)}:{path:names[i],missing:true});
|
|
65
|
+
}
|
|
66
|
+
return result;
|
|
67
|
+
}
|
|
68
|
+
async function load(q){
|
|
69
|
+
const files=base(q);await checkAncestors(q.root);
|
|
70
|
+
const s=await stat(q.root);if(!s)return {state:'absent'};
|
|
71
|
+
const stored=await regular(files.owner,131072);if(!stored||stored.identity.mode!==0o600||stored.identity.uid!==s.uid)fail('OWNER_REVIEW');
|
|
72
|
+
let owner;try{owner=verified(JSON.parse(stored.data),q.proof);}catch{fail('OWNER_REVIEW');}
|
|
73
|
+
if(!exact(owner,['owner','schema','installationId','operationId','planHash','proofHash','root','identity','parents','manifest','manifestHash','creator'])||owner.owner!==OWNER||owner.schema!==1||owner.root!==q.root||owner.operationId!==q.operationId||owner.installationId!==q.installationId||owner.planHash!==q.planHash||!hex(owner.proofHash)||!timingSafeEqual(Buffer.from(owner.proofHash,'hex'),Buffer.from(hash(q.proof),'hex'))||!same(identity(s),owner.identity))fail('OWNER_REVIEW');
|
|
74
|
+
manifest(owner.manifest,false);if(hash(owner.manifest)!==owner.manifestHash||!Array.isArray(owner.parents))fail('OWNER_REVIEW');
|
|
75
|
+
for(const a of owner.parents)if(!a||typeof a.path!=='string'||a.path==='/'||!q.root.startsWith(a.path+path.sep)||!Number.isSafeInteger(a.dev)||!Number.isSafeInteger(a.ino))fail('OWNER_REVIEW');
|
|
76
|
+
const j=await regular(files.journal,131072);let journal=null;
|
|
77
|
+
if(j){if(j.identity.mode!==0o600||j.identity.uid!==s.uid)fail('JOURNAL_REVIEW');try{journal=verified(JSON.parse(j.data),q.proof);}catch{fail('JOURNAL_REVIEW');}if(!exact(journal,['owner','schema','operationId','planHash','revision','state','written','error','process'])||journal.owner!==OWNER||journal.schema!==1||journal.operationId!==q.operationId||journal.planHash!==q.planHash||!Number.isSafeInteger(journal.revision)||!['preparing','prepared','rolling_back','needs_review'].includes(journal.state)||!Array.isArray(journal.written)||journal.written.some(x=>!owner.manifest.some(f=>f.path===x)))fail('JOURNAL_REVIEW');}
|
|
78
|
+
const active=await processActive(journal?journal.process:owner.creator);
|
|
79
|
+
return {state:journal?.state==='preparing'&&!active?'needs_review':journal?.state??(active?'preparing':'needs_review'),active,owner,ownerSnapshot:stored,journal,journalSnapshot:j,files};
|
|
80
|
+
}
|
|
81
|
+
const publicState=s=>({state:s.state,active:s.active??false,operationId:s.owner?.operationId??null,manifestHash:s.owner?.manifestHash??null,written:s.journal?.written.length??0,files:s.owner?.manifest.length??0,initialization:false,hostStarted:false});
|
|
82
|
+
export async function remoteControl(q,runtime={}){
|
|
83
|
+
const names=['action','root','operationId','installationId','proof','planHash'];
|
|
84
|
+
if(!['prepare','status','rollback'].includes(q?.action)||!exact(q,q.action==='prepare'?[...names,'baseline','files','manifestHash']:names))fail('ARGUMENTS');
|
|
85
|
+
base(q);
|
|
86
|
+
if(q.action==='status'){
|
|
87
|
+
const s=await load(q);if(s.state==='absent')return publicState(s);
|
|
88
|
+
const changed=[];for(const f of s.owner.manifest){const r=await regular(path.join(q.root,f.path));if(r&&(r.sha256!==f.sha256||r.identity.mode!==f.mode||r.identity.uid!==s.owner.identity.uid)||!r&&s.state==='prepared')changed.push(f.path);}
|
|
89
|
+
return {...publicState(s),state:changed.length?'needs_review':s.state,changed};
|
|
90
|
+
}
|
|
91
|
+
if(q.action==='prepare'){
|
|
92
|
+
const rows=manifest(q.files,true);if(!hex(q.manifestHash)||hash(rows)!==q.manifestHash)fail('SOURCE_REVIEW');
|
|
93
|
+
if(await stat(q.root)){
|
|
94
|
+
const s=await load(q);if(s.owner.manifestHash!==q.manifestHash)fail('SOURCE_CHANGED');
|
|
95
|
+
if(s.state==='prepared'){for(const f of rows){const r=await regular(path.join(q.root,f.path));if(!r||r.sha256!==f.sha256||r.identity.mode!==f.mode||r.identity.uid!==s.owner.identity.uid)fail('FILE_CHANGED');}return {...publicState(s),idempotent:true};}
|
|
96
|
+
fail('RECOVERY_REQUIRED');
|
|
97
|
+
}
|
|
98
|
+
const b=q.baseline;if(!b||b.root!==q.root||b.rootExists!==false||b.uid!==os.userInfo().uid||b.platform!==process.platform||b.arch!==process.arch||!b.node)fail('BASELINE_DRIFT');
|
|
99
|
+
const node=await fs.stat(process.execPath);if(b.node.path!==process.execPath||b.node.version!==process.versions.node||b.node.dev!==node.dev||b.node.ino!==node.ino||b.node.size!==node.size||b.node.mtime!==node.mtimeMs)fail('BASELINE_DRIFT');
|
|
100
|
+
const ancestors=await checkAncestors(q.root,b.ancestors),created=[];
|
|
101
|
+
for(const a of ancestors.filter(x=>x.missing)){
|
|
102
|
+
// Recheck the complete parent chain immediately before each exclusive mkdir.
|
|
103
|
+
await checkAncestors(path.dirname(a.path));await fs.mkdir(a.path,{mode:0o700});const s=await fs.lstat(a.path);created.push({path:a.path,...identity(s)});
|
|
104
|
+
}
|
|
105
|
+
const rootStat=await fs.lstat(q.root),files=base(q),owner={owner:OWNER,schema:1,installationId:q.installationId,operationId:q.operationId,planHash:q.planHash,proofHash:hash(q.proof),root:q.root,identity:identity(rootStat),parents:created.filter(x=>x.path!==q.root),manifest:rows,manifestHash:q.manifestHash,creator:await processInfo()};
|
|
106
|
+
await writeNew(files.owner,JSON.stringify(signed(owner,q.proof)));await syncDir(q.root);
|
|
107
|
+
await runtime.afterOwner?.();
|
|
108
|
+
await fs.mkdir(path.dirname(files.journal),{mode:0o700});
|
|
109
|
+
const j={owner:OWNER,schema:1,operationId:q.operationId,planHash:q.planHash,revision:1,state:'preparing',written:[],error:null,process:await processInfo()};await atomicJSON(files.journal,signed(j,q.proof));
|
|
110
|
+
try{
|
|
111
|
+
for(const f of q.files){
|
|
112
|
+
const p=path.join(q.root,f.path);let parent=q.root;
|
|
113
|
+
for(const part of f.path.split('/').slice(0,-1)){parent=path.join(parent,part);const s=await stat(parent);if(!s)await fs.mkdir(parent,{mode:0o700});else if(!s.isDirectory()||s.isSymbolicLink())fail('UNSAFE_PATH');}
|
|
114
|
+
if(await stat(p))fail('FILE_CHANGED');await writeNew(p,Buffer.from(f.data,'base64'));
|
|
115
|
+
await runtime.afterFile?.(f.path,j.written.length+1);
|
|
116
|
+
j.written.push(f.path);j.revision++;await atomicJSON(files.journal,signed(j,q.proof));
|
|
117
|
+
}
|
|
118
|
+
j.state='prepared';j.process=null;j.revision++;await atomicJSON(files.journal,signed(j,q.proof));return publicState(await load(q));
|
|
119
|
+
}catch(e){j.state='needs_review';j.process=null;j.error=/^ONBOARDING_CLOUD_[A-Z_]+$/.test(e.message)?e.message:'ONBOARDING_CLOUD_PREPARATION_FAILED';j.revision++;await atomicJSON(files.journal,signed(j,q.proof));throw e;}
|
|
120
|
+
}
|
|
121
|
+
const s=await load(q);if(s.state==='absent')return {state:'absent',initialization:false,hostStarted:false};
|
|
122
|
+
if(s.active)fail('PROCESS_ACTIVE');
|
|
123
|
+
// Full preflight before deletion: unknown content is preserved, never claimed by a directory prefix.
|
|
124
|
+
const allowed=new Map(s.owner.manifest.map(f=>[f.path,f.sha256]));allowed.set('.dsh-onboarding-owner.json',s.ownerSnapshot.sha256);
|
|
125
|
+
if(s.journalSnapshot)allowed.set('.control/journal.json',s.journalSnapshot.sha256);
|
|
126
|
+
const allowedDirs=new Set(['.control']);for(const name of allowed.keys()){let d=path.dirname(name);while(d!=='.'){allowedDirs.add(d);d=path.dirname(d);}}
|
|
127
|
+
const files=[],dirs=[];async function walk(dir){for(const name of await fs.readdir(dir)){const p=path.join(dir,name),rel=path.relative(q.root,p),a=await fs.lstat(p);if(a.isSymbolicLink())fail('ROLLBACK_REVIEW');if(a.isDirectory()){if(!allowedDirs.has(rel)||(a.mode&0o777)!==0o700||a.uid!==s.owner.identity.uid)fail('ROLLBACK_REVIEW');dirs.push({path:p,identity:identity(a)});await walk(p);}else{const f=await regular(p);if(!allowed.has(rel)||f.sha256!==allowed.get(rel)||f.identity.mode!==0o600||f.identity.uid!==s.owner.identity.uid)fail('ROLLBACK_REVIEW');files.push({path:p,...f});}}}
|
|
128
|
+
await walk(q.root);
|
|
129
|
+
// Filesystem may change after preflight: recheck each item immediately, retain any divergence.
|
|
130
|
+
for(const f of files.filter(x=>x.path!==s.files.owner)){const current=await regular(f.path);if(!current||current.sha256!==f.sha256||!same(current.identity,f.identity))fail('ROLLBACK_REVIEW');await fs.unlink(f.path);}
|
|
131
|
+
for(const d of dirs.sort((a,b)=>b.path.length-a.path.length)){const current=await fs.lstat(d.path);if(!same(identity(current),d.identity))fail('ROLLBACK_REVIEW');await fs.rmdir(d.path);}
|
|
132
|
+
const last=await fs.lstat(q.root),owner=await regular(s.files.owner);if(!same(identity(last),s.owner.identity)||!owner||owner.sha256!==s.ownerSnapshot.sha256||(await fs.readdir(q.root)).join()!=='.dsh-onboarding-owner.json')fail('OWNER_REVIEW');await fs.unlink(s.files.owner);await fs.rmdir(q.root);
|
|
133
|
+
const retainedParents=[];
|
|
134
|
+
for(const p of [...s.owner.parents].reverse())try{const current=await fs.lstat(p.path);if(!same(identity(current),p)){retainedParents.push(p.path);continue;}await fs.rmdir(p.path);}catch{retainedParents.push(p.path);}
|
|
135
|
+
return {state:'rolled_back',operationId:q.operationId,retainedParents,initialization:false,hostStarted:false};
|
|
136
|
+
}
|
|
137
|
+
export async function remoteControlCLI(){
|
|
138
|
+
try{let size=0,parts=[];for await(const c of process.stdin){size+=c.length;if(size>12582912)fail('INPUT_LIMIT');parts.push(c);}const r=await remoteControl(JSON.parse(Buffer.concat(parts)));console.log(JSON.stringify({ok:true,value:r}));}
|
|
139
|
+
catch(e){console.log(JSON.stringify({ok:false,error:/^ONBOARDING_CLOUD_[A-Z_]+$/.test(e.message)?e.message:'ONBOARDING_CLOUD_CONTROL_FAILED'}));}
|
|
140
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// This file is sent as fixed program text over authenticated SSH. Read-only.
|
|
2
|
+
// It does not read model/IM credentials, process environments, or user rule bodies.
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import {constants} from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import {createHash} from 'node:crypto';
|
|
8
|
+
const hash=x=>createHash('sha256').update(JSON.stringify(x)).digest('hex');
|
|
9
|
+
const fail=code=>{throw Error(code);};
|
|
10
|
+
try{
|
|
11
|
+
let size=0,parts=[];for await(const chunk of process.stdin){size+=chunk.length;if(size>8192)fail('INPUT_LIMIT');parts.push(chunk);}
|
|
12
|
+
const input=JSON.parse(Buffer.concat(parts).toString());
|
|
13
|
+
if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).sort().join()!=='installationId,parent'||!/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(input.installationId))fail('INPUT_INVALID');
|
|
14
|
+
const user=os.userInfo(),parent=input.parent??path.join(user.homedir,'.local/share/dsh-dual-host/instances');
|
|
15
|
+
if(typeof parent!=='string'||!path.isAbsolute(parent)||path.normalize(parent)!==parent||parent.length>600||/[\x00-\x1f\x7f]/.test(parent)||['/',user.homedir].includes(parent))fail('PATH_INVALID');
|
|
16
|
+
const root=path.join(parent,'host-'+input.installationId),ancestors=[];let cursor=path.parse(root).root,missing=false;
|
|
17
|
+
const top=await fs.lstat(cursor);ancestors.push({path:cursor,dev:top.dev,ino:top.ino,mode:top.mode&0o777,uid:top.uid});
|
|
18
|
+
for(const part of root.split(path.sep).filter(Boolean)){
|
|
19
|
+
cursor=path.join(cursor,part);let s;try{s=await fs.lstat(cursor);}catch(e){if(e.code!=='ENOENT')throw e;missing=true;ancestors.push({path:cursor,missing:true});continue;}
|
|
20
|
+
if(missing||s.isSymbolicLink()||!s.isDirectory())fail('UNSAFE_PATH');
|
|
21
|
+
ancestors.push({path:cursor,dev:s.dev,ino:s.ino,mode:s.mode&0o777,uid:s.uid});
|
|
22
|
+
}
|
|
23
|
+
const anchor=ancestors.filter(x=>!x.missing).at(-1),rootExists=!ancestors.at(-1).missing;
|
|
24
|
+
let writable=false;try{await fs.access(anchor.path,constants.W_OK|constants.X_OK);writable=true;}catch{}
|
|
25
|
+
let freeBytes=null;try{const s=await fs.statfs(anchor.path);freeBytes=s.bavail*s.bsize;}catch{}
|
|
26
|
+
let owner=null;
|
|
27
|
+
if(rootExists){
|
|
28
|
+
const file=path.join(root,'.dsh-onboarding-owner.json');
|
|
29
|
+
try{const s=await fs.lstat(file);if(s.isSymbolicLink()||!s.isFile()||s.nlink!==1||s.size>131072)fail('OWNER_REVIEW');const h=await fs.open(file,constants.O_RDONLY|constants.O_NOFOLLOW);try{const a=await h.stat();if(a.ino!==s.ino||a.dev!==s.dev)fail('OWNER_REVIEW');const data=Buffer.alloc(131073);let used=0;while(used<data.length){const n=(await h.read(data,used,data.length-used,used)).bytesRead;if(!n)break;used+=n;}const after=await h.stat();if(used>131072||used!==s.size||after.size!==s.size||after.mtimeMs!==s.mtimeMs)fail('OWNER_REVIEW');const p=JSON.parse(data.subarray(0,used).toString('utf8'));owner={sha256:hash(p),matches:p.installationId===input.installationId&&p.owner==='dsh-dual-host-onboarding'};}finally{await h.close();}}catch(e){if(e.code!=='ENOENT')fail('OWNER_REVIEW');}
|
|
30
|
+
}
|
|
31
|
+
const protectedHomes=[];for(const p of [path.join(user.homedir,'.dsh'),path.join(user.homedir,'.agents')]){let exists=false;try{await fs.lstat(p);exists=true;}catch{}protectedHomes.push({path:p,exists,read:false,modified:false});}
|
|
32
|
+
const possibleHosts=[];
|
|
33
|
+
if(process.platform==='linux')for(const pid of (await fs.readdir('/proc')).filter(x=>/^\d+$/.test(x)).slice(0,8192)){
|
|
34
|
+
if(+pid===process.pid)continue;
|
|
35
|
+
try{const c=await fs.readFile('/proc/'+pid+'/cmdline');if(c.length<65536&&c.toString().split('\0').some(x=>x.endsWith('/@deepseek-ai/dsh/lib/bin.js')))possibleHosts.push({pid:+pid,classification:'possible_dsh_cli',configurationRead:false});}catch{}
|
|
36
|
+
}
|
|
37
|
+
const nodeStat=await fs.stat(process.execPath),node={path:process.execPath,version:process.versions.node,dev:nodeStat.dev,ino:nodeStat.ino,size:nodeStat.size,mtime:nodeStat.mtimeMs};
|
|
38
|
+
const baseline={platform:process.platform,arch:process.arch,uid:user.uid,user:user.username,home:user.homedir,parent,root,ancestors,rootExists,owner,node};
|
|
39
|
+
console.log(JSON.stringify({ok:true,contract:1,...baseline,baselineHash:hash(baseline),writable,freeBytes,protectedHomes,possibleHosts,servicePathsVerified:false,remoteWrites:0}));
|
|
40
|
+
}catch(e){console.log(JSON.stringify({ok:false,code:['INPUT_INVALID','INPUT_LIMIT','PATH_INVALID','UNSAFE_PATH','OWNER_REVIEW'].includes(e.message)?e.message:'PROBE_FAILED'}));process.exitCode=0;}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Confirmed repository configuration, not a task association or write grant.
|
|
2
|
+
// Only the official credential store owns persistence/locking. Drafts never activate it.
|
|
3
|
+
import {credentialKey} from '@deepseek-ai/dsh-credentials';
|
|
4
|
+
import {randomUUID} from 'node:crypto';
|
|
5
|
+
import {digest} from './onboarding-ssh.js';
|
|
6
|
+
import {repositoryURL} from './repository-gitee.js';
|
|
7
|
+
import {onboardingIdentity} from './onboarding-identity.js';
|
|
8
|
+
const KEY=credentialKey('dsh-task-gateway','onboarding-repositories-v1'),OWNER='dsh-dual-host-onboarding';
|
|
9
|
+
const exact=(x,ks)=>x&&typeof x==='object'&&!Array.isArray(x)&&Object.keys(x).sort().join()===ks.slice().sort().join();
|
|
10
|
+
const revision=x=>Number.isSafeInteger(x)&&x>=0&&x<Number.MAX_SAFE_INTEGER-1;
|
|
11
|
+
const uuid=x=>typeof x==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(x);
|
|
12
|
+
const hex=x=>typeof x==='string'&&/^[a-f0-9]{64}$/.test(x);
|
|
13
|
+
const fail=c=>{throw Error('ONBOARDING_REPOSITORY_'+c);};
|
|
14
|
+
export const repositoryAlias=x=>typeof x==='string'?x.normalize('NFKC').trim().toLowerCase():'';
|
|
15
|
+
export function repositoryRegistrationInput(a){
|
|
16
|
+
if(!exact(a,['url','alias','authentication','enabled'])||typeof a.alias!=='string'||!repositoryAlias(a.alias)||a.alias.length>120||/[\x00-\x1f\x7f]/.test(a.alias)||/^(?:https:|git@)/i.test(a.alias.normalize('NFKC').trim())||!['anonymous','managed'].includes(a.authentication)||typeof a.enabled!=='boolean')fail('REGISTRY_ARGUMENTS');
|
|
17
|
+
let url;try{url=repositoryURL(a.url).url;}catch{fail('REGISTRY_ARGUMENTS');}
|
|
18
|
+
return {url,alias:a.alias.trim(),authentication:a.authentication,enabled:a.enabled};
|
|
19
|
+
}
|
|
20
|
+
function entry(a){
|
|
21
|
+
if(!exact(a,['url','alias','authentication','enabled','repositoryId','verifiedAt'])||!Number.isSafeInteger(a.repositoryId)||a.repositoryId<1||!Number.isSafeInteger(a.verifiedAt)||a.verifiedAt<0)fail('REGISTRY_REVIEW');
|
|
22
|
+
const v=repositoryRegistrationInput({url:a.url,alias:a.alias,authentication:a.authentication,enabled:a.enabled});if(v.url!==a.url||v.alias!==a.alias)fail('REGISTRY_REVIEW');return a;
|
|
23
|
+
}
|
|
24
|
+
function identity(t){
|
|
25
|
+
if(!exact(t,['role','name','source','platform'])||!['local','cloud','unassigned'].includes(t.role)||!['darwin','linux','win32'].includes(t.platform)||!['setup_configuration','gateway_configuration','unassigned'].includes(t.source)||typeof t.name!=='string'||t.name.length>80)fail('REGISTRY_REVIEW');return t;
|
|
26
|
+
}
|
|
27
|
+
export function repositoryRegistryStatus(v){
|
|
28
|
+
if(!exact(v,['contract','scope','target','revision','appliedOperation','appliedPlanHash','updatedAt','entries','runtimeConfigured','taskBound','writeAuthorized'])||v.contract!==2||v.scope!=='current_host_only'||!revision(v.revision)||typeof v.runtimeConfigured!=='boolean'||v.taskBound!==false||v.writeAuthorized!==false)fail('REGISTRY_REVIEW');
|
|
29
|
+
identity(v.target);
|
|
30
|
+
if(v.revision===0){if(v.appliedOperation!==null||v.appliedPlanHash!==null||v.updatedAt!==null||!Array.isArray(v.entries)||v.entries.length)fail('REGISTRY_REVIEW');}
|
|
31
|
+
else record({kind:'grant',payload:{owner:OWNER,schema:1,revision:v.revision,operation:v.appliedOperation,planHash:v.appliedPlanHash,updatedAt:v.updatedAt,entries:v.entries}});
|
|
32
|
+
return structuredClone(v);
|
|
33
|
+
}
|
|
34
|
+
export function repositoryRegistryPlan(v){
|
|
35
|
+
if(!exact(v,['id','target','entry','registryRevision','credentialRevision','expiresAt','fingerprint','scope','taskBound','writeAuthorized'])||!uuid(v.id)||!hex(v.fingerprint)||!revision(v.registryRevision)||!revision(v.credentialRevision)||!Number.isSafeInteger(v.expiresAt)||v.expiresAt<0||v.scope!=='current_host_only'||v.taskBound!==false||v.writeAuthorized!==false)fail('REGISTRY_REVIEW');
|
|
36
|
+
identity(v.target);entry(v.entry);const {scope,taskBound,writeAuthorized,fingerprint,...body}=v;if(digest(body)!==fingerprint)fail('REGISTRY_REVIEW');
|
|
37
|
+
if(v.entry.enabled&&v.entry.authentication==='managed'?!v.credentialRevision:v.credentialRevision!==0)fail('REGISTRY_REVIEW');return structuredClone(v);
|
|
38
|
+
}
|
|
39
|
+
function record(r){
|
|
40
|
+
if(!r)return null;const p=r.payload;
|
|
41
|
+
if(r.kind!=='grant'||!exact(p,['owner','schema','revision','operation','planHash','updatedAt','entries'])||p.owner!==OWNER||p.schema!==1||!revision(p.revision)||!p.revision||!uuid(p.operation)||!hex(p.planHash)||!Number.isSafeInteger(p.updatedAt)||!Array.isArray(p.entries)||p.entries.length>100)fail('REGISTRY_REVIEW');
|
|
42
|
+
p.entries.forEach(entry);
|
|
43
|
+
if(new Set(p.entries.map(e=>e.url.toLowerCase())).size!==p.entries.length||new Set(p.entries.filter(e=>e.enabled).map(e=>repositoryAlias(e.alias))).size!==p.entries.filter(e=>e.enabled).length)fail('REGISTRY_REVIEW');
|
|
44
|
+
return p;
|
|
45
|
+
}
|
|
46
|
+
export function createOnboardingRepositories({state,credentials,repository,config={},runtime={},now=Date.now}){
|
|
47
|
+
let pending=null,busy=false;
|
|
48
|
+
const target={...onboardingIdentity(config),platform:runtime.platform??process.platform};
|
|
49
|
+
const available=()=>state.available()&&!!credentials();
|
|
50
|
+
const ready=()=>{if(!available())fail('REGISTRY_UNAVAILABLE');return credentials();};
|
|
51
|
+
async function read(){return record(await ready().readRecord(KEY));}
|
|
52
|
+
function view(p){return {contract:2,scope:'current_host_only',target,revision:p?.revision??0,appliedOperation:p?.operation??null,appliedPlanHash:p?.planHash??null,updatedAt:p?.updatedAt??null,entries:structuredClone(p?.entries??[]),runtimeConfigured:runtime.repositoryRuntime===true||config.role==='cloud'&&config.repositoryAccess?.managedOnboarding===true,taskBound:false,writeAuthorized:false};}
|
|
53
|
+
async function run(fn){if(busy)fail('BUSY');busy=true;try{return await fn();}finally{busy=false;}}
|
|
54
|
+
async function status(a){if(!exact(a,[]))fail('REGISTRY_ARGUMENTS');return view(await read());}
|
|
55
|
+
async function preview(raw){return run(async()=>{
|
|
56
|
+
pending=null;const a=repositoryRegistrationInput(raw),old=await read(),entries=old?.entries??[],previous=entries.find(e=>e.url.toLowerCase()===a.url.toLowerCase());
|
|
57
|
+
if(a.enabled&&entries.some(e=>e.enabled&&e!==previous&&repositoryAlias(e.alias)===repositoryAlias(a.alias)))fail('ALIAS_CONFLICT');
|
|
58
|
+
if(!previous&&entries.length>=100)fail('REGISTRY_LIMIT');
|
|
59
|
+
let e,credentialRevision=0;
|
|
60
|
+
if(a.enabled){const check=await repository.inspect({url:a.url,branch:'',authentication:a.authentication});credentialRevision=check.credentialRevision;e={...a,url:check.repository.url,repositoryId:check.repository.repository_id,verifiedAt:check.observedAt};}
|
|
61
|
+
else {if(!previous||previous.alias!==a.alias||previous.authentication!==a.authentication)fail('REGISTRATION_NOT_FOUND');e={...previous,enabled:false};}
|
|
62
|
+
if((await read())?.revision!==old?.revision)fail('REGISTRY_CONFLICT');
|
|
63
|
+
const body={id:randomUUID(),target,entry:e,registryRevision:old?.revision??0,credentialRevision,expiresAt:now()+300000};
|
|
64
|
+
pending={...body,fingerprint:digest(body)};
|
|
65
|
+
return {...pending,scope:'current_host_only',taskBound:false,writeAuthorized:false};
|
|
66
|
+
});}
|
|
67
|
+
async function apply(a){return run(async()=>{
|
|
68
|
+
if(!exact(a,['id','fingerprint','confirm'])||!uuid(a.id)||!hex(a.fingerprint)||a.confirm!==true)fail('CONFIRMATION_REQUIRED');
|
|
69
|
+
const p=pending;if(!p||p.id!==a.id||p.fingerprint!==a.fingerprint||p.expiresAt<=now())fail('PLAN_EXPIRED');
|
|
70
|
+
// Consume before the write; after an unknown result use status, never replay.
|
|
71
|
+
pending=null;
|
|
72
|
+
if(p.entry.enabled&&p.entry.authentication==='managed'){const s=await state.readManagedSecret('gitee');if(!s.value||s.revision!==p.credentialRevision)fail('CREDENTIAL_CHANGED');}
|
|
73
|
+
await ready().modifyRecord(KEY,old=>{
|
|
74
|
+
const r=record(old);if((r?.revision??0)!==p.registryRevision)fail('REGISTRY_CONFLICT');
|
|
75
|
+
const entries=[...(r?.entries??[])],i=entries.findIndex(e=>e.url.toLowerCase()===p.entry.url.toLowerCase());
|
|
76
|
+
if(i<0)entries.push(p.entry);else entries[i]=p.entry;
|
|
77
|
+
return {kind:'grant',payload:{owner:OWNER,schema:1,revision:p.registryRevision+1,operation:p.id,planHash:p.fingerprint,updatedAt:now(),entries}};
|
|
78
|
+
});return status({});
|
|
79
|
+
});}
|
|
80
|
+
async function fence(a){return run(async()=>{
|
|
81
|
+
if(!exact(a,['operation','expectedRevision','confirm'])||!uuid(a.operation)||!revision(a.expectedRevision)||a.confirm!==true)fail('CONFIRMATION_REQUIRED');
|
|
82
|
+
// Preserve entries while advancing the CAS generation. A delayed old apply
|
|
83
|
+
// can no longer win; never clear configuration to resolve an unknown outcome.
|
|
84
|
+
await ready().modifyRecord(KEY,old=>{const p=record(old);if((p?.revision??0)!==a.expectedRevision)fail('REGISTRY_CONFLICT');return {kind:'grant',payload:{owner:OWNER,schema:1,revision:a.expectedRevision+1,operation:a.operation,planHash:digest(a),updatedAt:now(),entries:p?.entries??[]}};});
|
|
85
|
+
return status({});
|
|
86
|
+
});}
|
|
87
|
+
return {available,status,preview,apply,fence};
|
|
88
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Manual metadata checks only. No clone, key generation, task binding or Git writes.
|
|
2
|
+
import {GiteeReadOnly,repositoryURL,repositoryBranch} from './repository-gitee.js';
|
|
3
|
+
import {onboardingIdentity} from './onboarding-identity.js';
|
|
4
|
+
import {handoffTarget} from './onboarding-handoff.js';
|
|
5
|
+
const exact=(v,keys)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join()===keys.sort().join();
|
|
6
|
+
const fail=code=>{throw Error('ONBOARDING_REPOSITORY_'+code);};
|
|
7
|
+
export function repositoryCheckArgs(a){
|
|
8
|
+
if(!exact(a,['url','branch','authentication'])||!['anonymous','managed'].includes(a.authentication)||typeof a.branch!=='string')fail('ARGUMENTS');
|
|
9
|
+
try{return {url:repositoryURL(a.url).url,branch:a.branch?repositoryBranch(a.branch):'',authentication:a.authentication};}catch{fail('ARGUMENTS');}
|
|
10
|
+
}
|
|
11
|
+
export function repositoryCheckResult(v,a){
|
|
12
|
+
if(!exact(v,['contract','scope','target','observedAt','repository','authentication','credentialRevision','taskBound','writeAuthorized'])||v.contract!==1||v.scope!=='current_host'||!Number.isSafeInteger(v.observedAt)||v.observedAt<0||v.authentication!==a.authentication||!Number.isSafeInteger(v.credentialRevision)||v.credentialRevision<0||a.authentication==='managed'&&v.credentialRevision<1||a.authentication==='anonymous'&&v.credentialRevision!==0||v.taskBound!==false||v.writeAuthorized!==false)fail('RESPONSE_REVIEW');
|
|
13
|
+
const t=v.target,r=v.repository;
|
|
14
|
+
if(!exact(t,['role','name','source','platform'])||!['local','cloud','unassigned'].includes(t.role)||!['darwin','linux','win32'].includes(t.platform)||typeof t.name!=='string'||t.name.length>80||!['setup_configuration','gateway_configuration','unassigned'].includes(t.source))fail('RESPONSE_REVIEW');
|
|
15
|
+
if(!exact(r,['provider','repository_id','url','branch','base_sha','private','workspace'])||r.provider!=='gitee'||!Number.isSafeInteger(r.repository_id)||r.repository_id<1||typeof r.private!=='boolean'||r.workspace!==null||typeof r.base_sha!=='string'||!/^[a-f0-9]{40}$/.test(r.base_sha))fail('RESPONSE_REVIEW');
|
|
16
|
+
try{if(repositoryURL(r.url).url!==r.url||r.url.toLowerCase()!==a.url.toLowerCase()||repositoryBranch(r.branch)!==r.branch||a.branch&&r.branch!==a.branch)fail('RESPONSE_REVIEW');}catch{fail('RESPONSE_REVIEW');}
|
|
17
|
+
return structuredClone(v);
|
|
18
|
+
}
|
|
19
|
+
const providerErrors=new Set(['REPOSITORY_DEFAULT_BRANCH_REQUIRED','REPOSITORY_NOT_FOUND_OR_PRIVATE','REPOSITORY_ACCESS_DENIED','REPOSITORY_RATE_LIMIT','REPOSITORY_PROVIDER_UNAVAILABLE','REPOSITORY_RESPONSE_TOO_LARGE','REPOSITORY_RESPONSE_INVALID','REPOSITORY_IDENTITY_MISMATCH','REPOSITORY_BRANCH_RESPONSE_INVALID']);
|
|
20
|
+
export function createOnboardingRepository({state,config={},runtime={},now=Date.now}){
|
|
21
|
+
let busy=false;
|
|
22
|
+
async function inspect(raw){
|
|
23
|
+
const a=repositoryCheckArgs(raw);if(busy)fail('BUSY');busy=true;
|
|
24
|
+
try{
|
|
25
|
+
const credential=a.authentication==='managed'?await state.readManagedSecret('gitee'):null;
|
|
26
|
+
if(credential&&!credential.value)fail('CREDENTIAL_REQUIRED');
|
|
27
|
+
let provider;
|
|
28
|
+
try{provider=new GiteeReadOnly({}, {fetch:runtime.repositoryFetch,...(credential?{token:credential.value}:{})});}catch{fail('CREDENTIAL_INVALID');}
|
|
29
|
+
const repository=await provider.inspect(a.url,a.branch||undefined);
|
|
30
|
+
if(credential&&(await state.readManagedSecret('gitee')).revision!==credential.revision)fail('CREDENTIAL_CHANGED');
|
|
31
|
+
return repositoryCheckResult({contract:1,scope:'current_host',target:{...onboardingIdentity(config),platform:runtime.platform??process.platform},observedAt:now(),repository,authentication:a.authentication,credentialRevision:credential?.revision??0,taskBound:false,writeAuthorized:false},a);
|
|
32
|
+
}catch(e){if(providerErrors.has(e.message))throw Error('ONBOARDING_'+e.message);if(/^ONBOARDING_(REPOSITORY|PERSISTENCE|STATE)_/.test(e.message))throw e;fail('RESPONSE_REVIEW');}
|
|
33
|
+
finally{busy=false;}
|
|
34
|
+
}
|
|
35
|
+
return {inspect};
|
|
36
|
+
}
|
|
37
|
+
export function createOnboardingCloudRepository({remote,enabled,now=Date.now}){
|
|
38
|
+
let busy=false;
|
|
39
|
+
async function inspect(raw){
|
|
40
|
+
const a=repositoryCheckArgs(raw);if(!enabled())fail('CLOUD_DISABLED');if(busy)fail('BUSY');busy=true;
|
|
41
|
+
try{
|
|
42
|
+
const r=await remote('repository_inspect',a);if(!exact(r,['target','value']))fail('RESPONSE_REVIEW');
|
|
43
|
+
const remoteTarget=handoffTarget(r.target),v=repositoryCheckResult(r.value,a);
|
|
44
|
+
if(v.target.role!=='cloud'||v.target.platform!=='linux'||v.target.name!=='云端大肥鱼')fail('IDENTITY_REVIEW');
|
|
45
|
+
return {...v,scope:'managed_cloud_only',remoteTarget,checkedAt:now()};
|
|
46
|
+
}finally{busy=false;}
|
|
47
|
+
}
|
|
48
|
+
return {available:()=>enabled(),inspect};
|
|
49
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// A manual, point-in-time observation, not a restart authority or a live monitor.
|
|
2
|
+
// Loaded only from the original archive. Repair publication and activation stay separate.
|
|
3
|
+
import {observeRuntimeHost} from './onboarding-host-stop-observation.js';
|
|
4
|
+
export function createRuntimeActivation(api,q,j,{repair,inventory,source,compat,versionContext,versionSubject}){
|
|
5
|
+
const {fs,path,hash,fail,regular,verified,signed,atomicJSON,runtimeRecord,runtimeAlive}=api;
|
|
6
|
+
const normal=!!versionSubject;
|
|
7
|
+
const file=path.join(q.root,'.control/runtime',normal?'plugin-release-activation.json':versionContext?'plugin-version-activation.json':'plugin-activation.json'),schema=normal?3:versionContext?2:1;
|
|
8
|
+
const exact=(v,k)=>v&&Object.keys(v).sort().join()===k.slice().sort().join();
|
|
9
|
+
const hex=v=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v);
|
|
10
|
+
const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(v);
|
|
11
|
+
const version=v=>typeof v==='string'&&v.length<100&&/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(v);
|
|
12
|
+
if(versionContext&&(!exact(versionContext,['version','imageHash','transactionId','artifactsReady'])||!version(versionContext.version)||!hex(versionContext.imageHash)||!uuid(versionContext.transactionId)||typeof versionContext.artifactsReady!=='function'))fail('RUNTIME_ACTIVATION_CONTRACT_REVIEW');
|
|
13
|
+
if(normal&&(!versionContext||repair||!exact(versionSubject,['state','historyHash','stillCurrent'])||!['committed','rolled_back'].includes(versionSubject.state)||!hex(versionSubject.historyHash)||typeof versionSubject.stillCurrent!=='function'))fail('RUNTIME_ACTIVATION_CONTRACT_REVIEW');
|
|
14
|
+
const scope=normal?'maintained_plugin_version_observed':'same_version_repaired_plugin_observed';
|
|
15
|
+
const subjectFields=normal?['transactionState','historyHash']:['repairId','fingerprint','repairUpdatedAt'];
|
|
16
|
+
async function read(){
|
|
17
|
+
const f=await regular(file,1048576);if(!f)return [];
|
|
18
|
+
if(f.identity.uid!==process.getuid()||f.identity.mode!==0o600)fail('RUNTIME_ACTIVATION_LEDGER_REVIEW');
|
|
19
|
+
const d=verified(JSON.parse(f.data),q.proof);
|
|
20
|
+
if(!exact(d,['schema','operationId','runtimeId','records'])||d.schema!==schema||d.operationId!==q.operationId||d.runtimeId!==j.id||!Array.isArray(d.records)||d.records.length>128)fail('RUNTIME_ACTIVATION_LEDGER_REVIEW');
|
|
21
|
+
for(const r of d.records)if(!exact(r,[...subjectFields,'restartId','nativeNonce','hostHash','sourceHash','observedAt','installationId',...(versionContext?['pluginVersion','versionTransactionId','imageHash']:[])])||![r.restartId,r.nativeNonce,r.installationId].every(uuid)||![r.hostHash,r.sourceHash].every(hex)||!Number.isSafeInteger(r.observedAt)||r.observedAt<=0||(normal?(!['committed','rolled_back'].includes(r.transactionState)||!hex(r.historyHash)):(!uuid(r.repairId)||!hex(r.fingerprint)||!Number.isSafeInteger(r.repairUpdatedAt)||r.observedAt<r.repairUpdatedAt))||versionContext&&(!version(r.pluginVersion)||!uuid(r.versionTransactionId)||!hex(r.imageHash)))fail('RUNTIME_ACTIVATION_LEDGER_REVIEW');
|
|
22
|
+
return d.records;
|
|
23
|
+
}
|
|
24
|
+
function view(r,fresh=false){
|
|
25
|
+
const sameRelease=!versionContext||!!r&&r.pluginVersion===versionContext.version&&r.versionTransactionId===versionContext.transactionId&&r.imageHash===versionContext.imageHash&&(!normal||r.historyHash===versionSubject.historyHash&&r.transactionState===versionSubject.state);
|
|
26
|
+
return {contract:1,scope,activationVerified:fresh,cached:!fresh,liveStateVerified:false,observedAt:r?.observedAt??null,restartId:r?.restartId??null,sameRecordedHost:!!r&&r.hostHash===hash(j.host??null)&&r.nativeNonce===j.nativeNonce,automaticRestart:false,
|
|
27
|
+
...(normal?{versionMaintenance:true,transactionState:r?.transactionState??null}:{repairId:r?.repairId??null,sameRecordedRepair:sameRelease&&!!r&&r.repairId===repair?.id&&r.fingerprint===repair.fingerprint&&r.repairUpdatedAt===repair.updatedAt,versionUpgrade:false}),
|
|
28
|
+
...(versionContext?{pluginVersion:r?.pluginVersion??null,versionTransactionId:r?.versionTransactionId??null,sameRecordedRelease:sameRelease}:{})};
|
|
29
|
+
}
|
|
30
|
+
async function unchanged(){
|
|
31
|
+
const current=await runtimeRecord(q);
|
|
32
|
+
if(!current||hash(current)!==hash(j)||!await runtimeAlive(j.host)||normal&&!await versionSubject.stillCurrent())fail('RUNTIME_ACTIVATION_HOST_CHANGED');
|
|
33
|
+
}
|
|
34
|
+
async function ownFiles(){
|
|
35
|
+
await api.checkAncestors(path.join(q.root,'runtime/plugin'));
|
|
36
|
+
const items=inventory.filter(x=>x.path==='runtime/plugin'||x.path.startsWith('runtime/plugin/'));
|
|
37
|
+
if(!items.some(x=>x.path==='runtime/plugin'&&x.kind==='directory'))fail('RUNTIME_ACTIVATION_OWNERSHIP_REVIEW');
|
|
38
|
+
for(const x of items){
|
|
39
|
+
const p=path.join(q.root,x.path),s=await fs.lstat(p);
|
|
40
|
+
if(s.isSymbolicLink()||s.dev!==x.dev||s.ino!==x.ino||s.uid!==x.uid||(s.mode&0o777)!==x.mode)fail('RUNTIME_ACTIVATION_OWNERSHIP_REVIEW');
|
|
41
|
+
if(x.kind==='directory'){
|
|
42
|
+
if(!s.isDirectory())fail('RUNTIME_ACTIVATION_OWNERSHIP_REVIEW');
|
|
43
|
+
const expected=items.filter(y=>path.posix.dirname(y.path)===x.path).map(y=>path.posix.basename(y.path)).sort();
|
|
44
|
+
if(hash((await fs.readdir(p)).sort())!==hash(expected))fail('RUNTIME_ACTIVATION_OWNERSHIP_REVIEW');
|
|
45
|
+
}else{
|
|
46
|
+
const f=await regular(p);if(!f||f.sha256!==x.sha256||f.data.length!==x.bytes||f.identity.dev!==x.dev||f.identity.ino!==x.ino)fail('RUNTIME_ACTIVATION_OWNERSHIP_REVIEW');
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function admission(){
|
|
51
|
+
const r=j.restart,n=j.nativeReceipt,rows=n?.rows;
|
|
52
|
+
if((normal?!['committed','rolled_back'].includes(versionSubject.state):!repair||repair.state!=='committed')||!uuid(r?.id)||r.state!=='ready'||r.nativeResumeAcknowledged!==true||r.consentContract!==1||!Number.isSafeInteger(r.createdAt)||!normal&&r.createdAt<repair.updatedAt||!Number.isSafeInteger(r.completedAt)||r.completedAt<r.createdAt||hash(r.host??null)!==hash(j.host??null)||r.nonce!==j.nativeNonce||j.state!=='host_ready'||n?.ok!==true||n.pid!==j.host?.pid||n.nonce!==j.nativeNonce||n.hostVersion!==compat.hostBaseline||n.modelAttempts!==0||n.modelAttemptScope!=='inspection_agents_only')fail('RUNTIME_ACTIVATION_RESTART_REQUIRED');
|
|
53
|
+
if(!Array.isArray(rows)||rows.length!==4||new Set(rows.map(x=>x.preset)).size!==4)fail('RUNTIME_ACTIVATION_ADMISSION_REVIEW');
|
|
54
|
+
if(versionContext&&n.pluginVersion!==versionContext.version)fail('RUNTIME_ACTIVATION_VERSION_REVIEW');
|
|
55
|
+
for(const preset of ['standard','ptc','cordis','minimal']){
|
|
56
|
+
const row=rows.find(x=>x.preset===preset);
|
|
57
|
+
if(!row||row.valid!==true||row.catalogComplete!==true||row.idle!==true||(preset==='minimal'?row.globalSkillCount!==0||row.globalRuleLoaded!==false:row.globalSkillPathsVerified!==true||row.globalRuleLoaded!==true||row.skillBodyLoaded!==true||row.globalSkillCount!==compat.globalSkills.length))fail('RUNTIME_ACTIVATION_ADMISSION_REVIEW');
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async function verify(id){
|
|
61
|
+
if(id!==(normal?versionContext.transactionId:repair?.id))fail(normal?'RUNTIME_ACTIVATION_VERSION_CHANGED':'RUNTIME_ACTIVATION_REPAIR_CHANGED');
|
|
62
|
+
const records=await read();admission();await unchanged();
|
|
63
|
+
for(const p of [j.worker,j.child,j.restart.launcher])if(await runtimeAlive(p))fail('RUNTIME_ACTIVATION_LAUNCH_PENDING');
|
|
64
|
+
await ownFiles();
|
|
65
|
+
if(versionContext&&!await versionContext.artifactsReady())fail('RUNTIME_ACTIVATION_ARTIFACTS_REVIEW');
|
|
66
|
+
const observation=await observeRuntimeHost(api,q,j,{installation:true,versionIdentity:!!versionContext}),installed=observation.installation;
|
|
67
|
+
if(versionContext&&observation.pluginVersion!==versionContext.version)fail('RUNTIME_ACTIVATION_VERSION_REVIEW');
|
|
68
|
+
const expected=[path.join(q.root,'runtime/native-home/dsh/AGENTS.md'),...compat.globalSkills.map(n=>path.join(q.root,'runtime/native-home/dsh/skills',n,'SKILL.md'))].sort();
|
|
69
|
+
const legacy=installed?.state==='committed'&&installed.canRecover===false&&uuid(installed.id)&&!installed.review?.length;
|
|
70
|
+
const maintained=!!versionContext&&installed?.state==='inspected'&&installed.contract===2&&installed.action==='inspect'&&installed.planReady===true&&installed.canApply===false&&installed.installedVersion===versionContext.version&&installed.targetVersion===versionContext.version&&uuid(installed.installationId)&&Array.isArray(installed.conflicts)&&!installed.conflicts.length&&Array.isArray(installed.changes)&&!installed.changes.length&&installed.lastReceipt?.id===installed.installationId&&installed.lastReceipt?.state==='committed'&&installed.lastReceipt?.canRecover===false&&!installed.lastReceipt?.review?.length&&installed.lastReceipt?.version===versionContext.version&&installed.files?.every(x=>x.state==='unchanged');
|
|
71
|
+
if(!(legacy||maintained)||!Array.isArray(installed.files)||hash(installed.files.map(x=>x.path).sort())!==hash(expected))fail('RUNTIME_ACTIVATION_INSTALLATION_REVIEW');
|
|
72
|
+
await ownFiles();await unchanged();
|
|
73
|
+
if(versionContext&&!await versionContext.artifactsReady())fail('RUNTIME_ACTIVATION_ARTIFACTS_REVIEW');
|
|
74
|
+
const receipt={...(normal?{transactionState:versionSubject.state,historyHash:versionSubject.historyHash}:{repairId:repair.id,fingerprint:repair.fingerprint,repairUpdatedAt:repair.updatedAt}),restartId:j.restart.id,nativeNonce:j.nativeNonce,hostHash:hash(j.host),sourceHash:hash(source.owner.manifest),observedAt:Date.now(),installationId:legacy?installed.id:installed.installationId,...(versionContext?{pluginVersion:versionContext.version,versionTransactionId:versionContext.transactionId,imageHash:versionContext.imageHash}:{})};
|
|
75
|
+
// Repeated checks of the same binding replace its latest diagnostic observation,
|
|
76
|
+
// never a repair/approval record. Different bindings retain their history.
|
|
77
|
+
const last=records.at(-1),same=last&&Object.keys(receipt).filter(k=>k!=='observedAt').every(k=>receipt[k]===last[k]);
|
|
78
|
+
if(same)records[records.length-1]=receipt;else{if(records.length>=128)fail('RUNTIME_ACTIVATION_HISTORY_LIMIT');records.push(receipt);}
|
|
79
|
+
await atomicJSON(file,signed({schema,operationId:q.operationId,runtimeId:j.id,records},q.proof));
|
|
80
|
+
return view(receipt,true);
|
|
81
|
+
}
|
|
82
|
+
return {verify,status:async()=>view((await read()).at(-1))};
|
|
83
|
+
}
|