@tnunamak/dalan 0.9.8 → 0.9.11
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/CHANGELOG.md +8 -0
- package/bin/dot-acp-agent.mjs +145 -28
- package/bin/dot-worker.mjs +17 -4
- package/docs/design/target-architecture-v2.md +58 -2
- package/docs/design/target-architecture-v3.md +151 -0
- package/docs/local-agent-requester.md +52 -0
- package/docs/pull-workers.md +5 -1
- package/package.json +1 -1
- package/src/acp-bridge.mjs +23 -11
- package/src/as-files.mjs +6 -3
- package/src/cli-help.mjs +4 -2
- package/src/get-summary.mjs +5 -0
- package/src/local-attachment-authority.mjs +174 -0
- package/src/local-attachment-capture.mjs +136 -0
- package/src/local-attachment-cli.mjs +46 -0
- package/src/local-attachment-gateway.mjs +93 -0
- package/src/local-attachment-owner-verify.mjs +152 -0
- package/src/local-attachment-result.mjs +64 -0
- package/src/local-attachment-snapshot.mjs +142 -0
- package/src/mcp-stdio.mjs +189 -7
- package/src/patch-apply.mjs +28 -6
- package/src/publication-authority.mjs +1 -0
- package/src/pull-pacing.mjs +10 -0
- package/src/requester-local-context.mjs +113 -0
- package/src/server.mjs +53 -16
- package/src/store.mjs +199 -15
- package/src/tool-registry.mjs +15 -4
- package/src/work-recovery.mjs +143 -0
- package/src/worker-runs.mjs +25 -0
- package/src/workspace.mjs +17 -10
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { canonicalJson } from '../packages/job-core/protocol/canonical.mjs';
|
|
3
|
+
|
|
4
|
+
const id = v => typeof v==='string'&&v.length>0&&v.length<=512&&!/[\x00-\x1f\x7f]/.test(v);
|
|
5
|
+
const digest = v => typeof v==='string'&&/^[a-f0-9]{64}$/.test(v);
|
|
6
|
+
const tree = v => typeof v==='string'&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(v);
|
|
7
|
+
const fail = code => { throw Object.assign(new Error(code),{code}); };
|
|
8
|
+
const audience = v => {
|
|
9
|
+
if(!v||!['relationship_side','principal','route','adapter_binding','address'].every(k=>id(v[k]))) fail('attachment_invalid_audience');
|
|
10
|
+
return Object.fromEntries(['relationship_side','principal','route','adapter_binding','address'].map(k=>[k,v[k]]));
|
|
11
|
+
};
|
|
12
|
+
const identity = v => createHash('sha256').update(canonicalJson(v)).digest('hex');
|
|
13
|
+
const epoch = v => Number.isSafeInteger(v)&&v>=1;
|
|
14
|
+
const ordinary = v => typeof v==='string'&&v.length>0&&v.length<=512;
|
|
15
|
+
|
|
16
|
+
// Invoke migration and each state-changing method inside the authoritative Store transaction.
|
|
17
|
+
export function migrateLocalAttachments(db) {
|
|
18
|
+
if(!db.isTransaction) fail('transaction_required');
|
|
19
|
+
db.exec(`CREATE TABLE IF NOT EXISTS local_attachment_bindings(
|
|
20
|
+
work TEXT PRIMARY KEY, identity TEXT NOT NULL, binding TEXT NOT NULL,
|
|
21
|
+
first_served_at INTEGER, last_served_at INTEGER, revoked_at INTEGER, finished TEXT
|
|
22
|
+
);
|
|
23
|
+
CREATE TABLE IF NOT EXISTS local_attachment_receipts(
|
|
24
|
+
work TEXT NOT NULL, kind TEXT NOT NULL, receipt_key TEXT NOT NULL,
|
|
25
|
+
intent TEXT NOT NULL, reply TEXT NOT NULL,
|
|
26
|
+
PRIMARY KEY(work,kind)
|
|
27
|
+
);`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// This store never persists bytes or credentials. Callbacks are trusted adapters over the current
|
|
31
|
+
// Store, scoped sealed artifacts, and owner-verification receipts, not caller-supplied claims.
|
|
32
|
+
export function localAttachmentAuthority({db,now,ownerHasAuthority,workerHasAuthority,findSealedArtifact,
|
|
33
|
+
verifyOwnerResult,parentsForWork,retentionMs}) {
|
|
34
|
+
if([now,ownerHasAuthority,workerHasAuthority,findSealedArtifact,verifyOwnerResult,parentsForWork].some(f=>typeof f!=='function')||
|
|
35
|
+
!Number.isSafeInteger(retentionMs)||retentionMs<1) fail('attachment_adapters_required');
|
|
36
|
+
const tx = () => {if(!db.isTransaction) fail('transaction_required');};
|
|
37
|
+
const clock = () => {const t=now();if(!Number.isSafeInteger(t)||t<0)fail('attachment_clock_unavailable');return t;};
|
|
38
|
+
const row = work => db.prepare('SELECT * FROM local_attachment_bindings WHERE work=?').get(work);
|
|
39
|
+
const required = work => {const r=row(work);if(!r)fail('attachment_missing');return [r,JSON.parse(r.binding)];};
|
|
40
|
+
const owner = (work,capability) => {if(ownerHasAuthority(work,capability)!==true)fail('attachment_owner_required');};
|
|
41
|
+
function seal({work,capability,recipient,repo,published_base,published_tree,input_tree,manifest_sha256,artifact_id,patch_sha256,expires_at}) {
|
|
42
|
+
tx();owner(work,capability);
|
|
43
|
+
if(!id(work)||!id(artifact_id)||typeof repo!=='string'||!/^[\w.-]+\/[\w.-]+$/.test(repo)||
|
|
44
|
+
![published_base,published_tree,input_tree].every(tree)||!digest(manifest_sha256)||!digest(patch_sha256)||!Number.isSafeInteger(expires_at))
|
|
45
|
+
fail('attachment_invalid_binding');
|
|
46
|
+
const binding={work,recipient:audience(recipient),repo,published_base,published_tree,input_tree,manifest_sha256,artifact_id,patch_sha256,expires_at};
|
|
47
|
+
const key=identity(binding),prev=row(work);
|
|
48
|
+
if(prev){if(prev.identity!==key)fail('attachment_binding_conflict');return {binding_sha256:key,expires_at};}
|
|
49
|
+
const t=clock();
|
|
50
|
+
if(expires_at<=t||expires_at-t>retentionMs)fail('attachment_invalid_expiry');
|
|
51
|
+
const artifact=findSealedArtifact({work,artifact_id,mode:'metadata'});
|
|
52
|
+
if(artifact?.work!==work||artifact?.sealed!==true||artifact?.patch_sha256!==patch_sha256||artifact?.expires_at<expires_at||!Number.isSafeInteger(artifact?.expires_at))
|
|
53
|
+
fail('attachment_artifact_mismatch');
|
|
54
|
+
db.prepare('INSERT INTO local_attachment_bindings(work,identity,binding) VALUES(?,?,?)').run(work,key,canonicalJson(binding));
|
|
55
|
+
return {binding_sha256:key,expires_at};
|
|
56
|
+
}
|
|
57
|
+
function admit({work,recipient}) {
|
|
58
|
+
const [r,b]=required(work);
|
|
59
|
+
if(identity(audience(recipient))!==identity(b.recipient))fail('attachment_audience_mismatch');
|
|
60
|
+
if(r.revoked_at!==null)fail('attachment_revoked');
|
|
61
|
+
if(clock()>=b.expires_at)fail('attachment_expired');
|
|
62
|
+
if(r.finished!==null)fail('attachment_terminal');
|
|
63
|
+
return {binding_sha256:r.identity,expires_at:b.expires_at};
|
|
64
|
+
}
|
|
65
|
+
function worker(request,mode) {
|
|
66
|
+
const [r,b]=required(request.work);
|
|
67
|
+
if(!id(request.claim_id)||!epoch(request.epoch)||identity(audience(request.recipient))!==identity(b.recipient)||
|
|
68
|
+
workerHasAuthority({work:request.work,claim_id:request.claim_id,epoch:request.epoch,recipient:b.recipient,mode})!==true)
|
|
69
|
+
fail('attachment_claim_mismatch');
|
|
70
|
+
return [r,b];
|
|
71
|
+
}
|
|
72
|
+
function live(r,b,t) {
|
|
73
|
+
if(r.revoked_at!==null)fail('attachment_revoked');
|
|
74
|
+
if(t>=b.expires_at)fail('attachment_expired');
|
|
75
|
+
if(r.finished!==null)fail('attachment_terminal');
|
|
76
|
+
}
|
|
77
|
+
function bytes(b) {
|
|
78
|
+
const item=findSealedArtifact({work:b.work,artifact_id:b.artifact_id,mode:'bytes'});
|
|
79
|
+
if(item?.work!==b.work||item.sealed!==true||item.patch_sha256!==b.patch_sha256||!Buffer.isBuffer(item.bytes)||
|
|
80
|
+
createHash('sha256').update(item.bytes).digest('hex')!==b.patch_sha256) fail('attachment_artifact_mismatch');
|
|
81
|
+
return Buffer.from(item.bytes);
|
|
82
|
+
}
|
|
83
|
+
function assertLiveWorker(request) {
|
|
84
|
+
tx();
|
|
85
|
+
const [r,b]=worker(request,'live');
|
|
86
|
+
live(r,b,clock());
|
|
87
|
+
}
|
|
88
|
+
function read(request) {
|
|
89
|
+
tx();
|
|
90
|
+
const [r,b]=worker(request,'live'),t=clock();
|
|
91
|
+
live(r,b,t);const data=bytes(b);
|
|
92
|
+
live(r,b,clock());
|
|
93
|
+
// “Served” means the bridge made bytes available, not that the worker observed them.
|
|
94
|
+
db.prepare('UPDATE local_attachment_bindings SET first_served_at=coalesce(first_served_at,?),last_served_at=? WHERE work=?').run(t,t,b.work);
|
|
95
|
+
return {binding_sha256:r.identity,patch_sha256:b.patch_sha256,bytes:data};
|
|
96
|
+
}
|
|
97
|
+
function receipt(work,kind,key,intent) {
|
|
98
|
+
const found=db.prepare('SELECT * FROM local_attachment_receipts WHERE work=? AND kind=?').get(work,kind);
|
|
99
|
+
if(!found)return null;
|
|
100
|
+
if(found.receipt_key!==key||found.intent!==intent)fail('attachment_receipt_conflict');
|
|
101
|
+
return JSON.parse(found.reply);
|
|
102
|
+
}
|
|
103
|
+
function save(work,kind,key,intent,reply) {
|
|
104
|
+
db.prepare('INSERT INTO local_attachment_receipts VALUES(?,?,?,?,?)').run(work,kind,key,intent,canonicalJson(reply));
|
|
105
|
+
return JSON.parse(canonicalJson(reply));
|
|
106
|
+
}
|
|
107
|
+
function finish(request) {
|
|
108
|
+
tx();
|
|
109
|
+
const {work,key,input_tree,output_tree,result_sha256}=request;
|
|
110
|
+
if(!ordinary(key)||!tree(input_tree)||!tree(output_tree)||!digest(result_sha256))fail('attachment_invalid_finish');
|
|
111
|
+
const [r,b]=worker(request,rMode(work));
|
|
112
|
+
if(input_tree!==b.input_tree)fail('attachment_result_basis_mismatch');
|
|
113
|
+
const intent=identity({input_tree,output_tree,result_sha256,claim:request.claim_id,epoch:request.epoch});
|
|
114
|
+
const prior=receipt(work,'finish',key,intent);
|
|
115
|
+
if(prior)return prior;
|
|
116
|
+
const t=clock(),authoritative=r.revoked_at===null&&t<b.expires_at;
|
|
117
|
+
const reply={at:t,authoritative,input_tree,output_tree,result_sha256};
|
|
118
|
+
if(authoritative)db.prepare('UPDATE local_attachment_bindings SET finished=? WHERE work=?').run(canonicalJson(reply),work);
|
|
119
|
+
return save(work,'finish',key,intent,reply);
|
|
120
|
+
}
|
|
121
|
+
function rMode(work) {
|
|
122
|
+
return db.prepare("SELECT 1 FROM local_attachment_receipts WHERE work=? AND kind='finish'").get(work)?'receipt':'live';
|
|
123
|
+
}
|
|
124
|
+
function accept({work,capability,key,verification_id,result_sha256}) {
|
|
125
|
+
tx();owner(work,capability);
|
|
126
|
+
if(!ordinary(key)||!id(verification_id)||!digest(result_sha256))fail('attachment_invalid_acceptance');
|
|
127
|
+
const intent=identity({verification_id,result_sha256}),prior=receipt(work,'accept',key,intent);
|
|
128
|
+
if(prior)return prior;
|
|
129
|
+
const [r,b]=required(work);
|
|
130
|
+
const liveAcceptance=()=>{
|
|
131
|
+
if(r.revoked_at!==null)fail('attachment_revoked');
|
|
132
|
+
const t=clock();
|
|
133
|
+
if(t>=b.expires_at)fail('attachment_expired');
|
|
134
|
+
return t;
|
|
135
|
+
};
|
|
136
|
+
liveAcceptance();
|
|
137
|
+
const finished=r.finished&&JSON.parse(r.finished);
|
|
138
|
+
if(!finished||finished.result_sha256!==result_sha256||
|
|
139
|
+
verifyOwnerResult({work,verification_id,binding_sha256:r.identity,input_tree:b.input_tree,
|
|
140
|
+
output_tree:finished.output_tree,result_sha256})!==true)fail('attachment_result_unverified');
|
|
141
|
+
const acceptedAt=liveAcceptance();
|
|
142
|
+
return save(work,'accept',key,intent,{accepted:true,at:acceptedAt,result_sha256,input_tree:b.input_tree,output_tree:finished.output_tree});
|
|
143
|
+
}
|
|
144
|
+
function revoke({work,capability}) {
|
|
145
|
+
tx();owner(work,capability);
|
|
146
|
+
const [r]=required(work),t=r.revoked_at??clock();
|
|
147
|
+
if(r.revoked_at===null)db.prepare('UPDATE local_attachment_bindings SET revoked_at=? WHERE work=?').run(t,work);
|
|
148
|
+
return {revoked_at:t};
|
|
149
|
+
}
|
|
150
|
+
function reopen({work,capability,includeBytes=false}) {
|
|
151
|
+
owner(work,capability);
|
|
152
|
+
const [r,b]=required(work);
|
|
153
|
+
const data=includeBytes&&clock()<b.expires_at?bytes(b):null;
|
|
154
|
+
return {binding_sha256:r.identity,recipient:b.recipient,manifest_sha256:b.manifest_sha256,
|
|
155
|
+
expires_at:b.expires_at,revoked_at:r.revoked_at,first_served_at:r.first_served_at,last_served_at:r.last_served_at,
|
|
156
|
+
worker_access:false,...(data&&clock()<b.expires_at?{bytes:data}:{})};
|
|
157
|
+
}
|
|
158
|
+
function assertStandingPublicationAllowed(work) {
|
|
159
|
+
const visited=new Set(),stack=[work];
|
|
160
|
+
while(stack.length){
|
|
161
|
+
const current=stack.pop();
|
|
162
|
+
if(!id(current)||visited.size>=1024)fail('attachment_lineage_unverified');
|
|
163
|
+
if(visited.has(current))continue;
|
|
164
|
+
visited.add(current);
|
|
165
|
+
if(row(current))fail('attachment_standing_publication_forbidden');
|
|
166
|
+
const parents=parentsForWork(current);
|
|
167
|
+
if(!Array.isArray(parents)||parents.length>1024)fail('attachment_lineage_unverified');
|
|
168
|
+
stack.push(...parents);
|
|
169
|
+
}
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
return {seal,admit,read,finish,accept,revoke,reopen,assertStandingPublicationAllowed,
|
|
173
|
+
assertLiveWorker,assertOwner:(work,capability)=>owner(work,capability)};
|
|
174
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { gitEnv } from './git-env.mjs';
|
|
7
|
+
import { canonicalJson } from '../packages/job-core/protocol/canonical.mjs';
|
|
8
|
+
import { isLiteralScopePath, withheldRepoPath, matchesCredentialPathTerm } from './submission-policy.mjs';
|
|
9
|
+
import { artifactSecretRule, hasSecretContent, hasCredentialFieldText } from './redaction.mjs';
|
|
10
|
+
|
|
11
|
+
const maxFile = 1024 * 1024, maxPatch = 4 * maxFile, maxSelection = 128;
|
|
12
|
+
const oid = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
|
|
13
|
+
const digest = data => createHash('sha256').update(data).digest('hex');
|
|
14
|
+
const fail = code => { throw Object.assign(new Error(code), { code }); };
|
|
15
|
+
const text = data => new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(data);
|
|
16
|
+
const sameFile = (a,b) => a?.dev===b?.dev && a?.ino===b?.ino && a?.size===b?.size &&
|
|
17
|
+
a?.mode===b?.mode && a?.mtimeNs===b?.mtimeNs && a?.ctimeNs===b?.ctimeNs;
|
|
18
|
+
const secret = bytes => artifactSecretRule(bytes) || hasSecretContent(text(bytes)) || hasCredentialFieldText(text(bytes));
|
|
19
|
+
const stockGit = gitEnv();
|
|
20
|
+
|
|
21
|
+
function git(cwd,args,{env=stockGit,input,ok=[0],buffer=maxPatch+maxFile}={}) {
|
|
22
|
+
const r=spawnSync('git',args,{cwd,env:{...env,GIT_TERMINAL_PROMPT:'0'},input,maxBuffer:buffer,timeout:15000});
|
|
23
|
+
if(!ok.includes(r.status)) fail('attachment_git_read_failed');
|
|
24
|
+
return r;
|
|
25
|
+
}
|
|
26
|
+
function entry(root,sha,rel) {
|
|
27
|
+
const v=text(git(root,['--literal-pathspecs','ls-tree','-z',sha,'--',rel]).stdout);
|
|
28
|
+
if(!v) return null;
|
|
29
|
+
const m=/^(\d+) (\S+) ([a-f0-9]+)\t([^\0]+)\0$/.exec(v);
|
|
30
|
+
if(!m||m[4]!==rel) fail('attachment_invalid_base_entry');
|
|
31
|
+
return {mode:m[1],type:m[2],oid:m[3]};
|
|
32
|
+
}
|
|
33
|
+
function current(root,rel) {
|
|
34
|
+
const parts=rel.split('/');
|
|
35
|
+
let at=root;
|
|
36
|
+
for(const [i,part] of parts.entries()) {
|
|
37
|
+
at=path.join(at,part);
|
|
38
|
+
const s=fs.lstatSync(at,{throwIfNoEntry:false,bigint:true});
|
|
39
|
+
if(!s) return {bytes:null};
|
|
40
|
+
if(s.isSymbolicLink()) return {omit:'symbolic_path'};
|
|
41
|
+
if(i<parts.length-1&&!s.isDirectory()) return {omit:'unsupported_path'};
|
|
42
|
+
if(i<parts.length-1) continue;
|
|
43
|
+
if(!s.isFile()) return {omit:'unsupported_file'};
|
|
44
|
+
if(s.size>BigInt(maxFile)) return {omit:'file_too_large'};
|
|
45
|
+
const fd=fs.openSync(at,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW|fs.constants.O_NONBLOCK);
|
|
46
|
+
try {
|
|
47
|
+
const before=fs.fstatSync(fd,{bigint:true});
|
|
48
|
+
if(!sameFile(s,before)||fs.realpathSync(at)!==at) fail('attachment_capture_changed');
|
|
49
|
+
const bytes=Buffer.alloc(Number(before.size)+1);
|
|
50
|
+
let n=0;
|
|
51
|
+
while(n<bytes.length) {
|
|
52
|
+
const got=fs.readSync(fd,bytes,n,bytes.length-n,null);
|
|
53
|
+
if(!got) break;
|
|
54
|
+
n+=got;
|
|
55
|
+
}
|
|
56
|
+
if(n!==Number(before.size)||!sameFile(before,fs.fstatSync(fd,{bigint:true}))||!sameFile(before,fs.lstatSync(at,{bigint:true}))) fail('attachment_capture_changed');
|
|
57
|
+
return {bytes:bytes.subarray(0,n),mode:(before.mode&0o100n)?'100755':'100644'};
|
|
58
|
+
} finally { fs.closeSync(fd); }
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function validText(b) {
|
|
62
|
+
if(!b) return true;
|
|
63
|
+
try { const value=text(b);return !/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value); }
|
|
64
|
+
catch {return false;}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// The caller supplies a published commit that it verified through its existing anchor policy;
|
|
68
|
+
// ancestry is checked locally. This helper never contacts a forge or reads an unselected worktree file.
|
|
69
|
+
export function captureLocalAttachment({checkout,repo,publishedBase,paths,policy}) {
|
|
70
|
+
if(!path.isAbsolute(checkout??'')||!/^[\w.-]+\/[\w.-]+$/.test(repo??'')||!oid.test(publishedBase??'')||
|
|
71
|
+
!Array.isArray(paths)||!paths.length||paths.length>maxSelection||
|
|
72
|
+
paths.some(p=>typeof p!=='string'||!isLiteralScopePath(p)||p.split('/').some(x=>x.toLowerCase()==='.git')||/[\x00-\x1f\x7f]/.test(p))) fail('invalid_attachment_selection');
|
|
73
|
+
if(!policy||policy.error||!Array.isArray(policy.excludedPaths)||!Array.isArray(policy.credentialPathTerms)||
|
|
74
|
+
[...policy.excludedPaths,...policy.credentialPathTerms].some(s=>typeof s!=='string'||!s)) fail('attachment_policy_unavailable');
|
|
75
|
+
if(new Set(paths.map(p=>p.normalize('NFC').toLowerCase())).size!==paths.length) fail('ambiguous_attachment_selection');
|
|
76
|
+
const selection=[...paths].sort(),root=fs.realpathSync(checkout);
|
|
77
|
+
const query=(...args)=>text(git(root,args).stdout).trimEnd();
|
|
78
|
+
if(query('rev-parse','--show-toplevel')!==root||query('rev-parse',publishedBase+'^{commit}')!==publishedBase||
|
|
79
|
+
git(root,['merge-base','--is-ancestor',publishedBase,'HEAD'],{ok:[0,1]}).status!==0) fail('invalid_attachment_anchor');
|
|
80
|
+
const tip=query('rev-parse','HEAD'), publishedTree=query('rev-parse',publishedBase+'^{tree}');
|
|
81
|
+
const objects=query('rev-parse','--path-format=absolute','--git-path','objects');
|
|
82
|
+
const format=query('rev-parse','--show-object-format');
|
|
83
|
+
const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'dalan-local-capture-'));
|
|
84
|
+
try {
|
|
85
|
+
git(scratch,['init','--quiet','--bare','--object-format='+format,'repo']);
|
|
86
|
+
const env={...stockGit,GIT_ALTERNATE_OBJECT_DIRECTORIES:JSON.stringify(objects),GIT_INDEX_FILE:path.join(scratch,'index')};
|
|
87
|
+
const pgit=(args,input)=>git(scratch,['--git-dir='+path.join(scratch,'repo'),...args],{env,input}).stdout;
|
|
88
|
+
pgit(['read-tree',publishedTree]);
|
|
89
|
+
const entries=[], omissions=[], reads=[];
|
|
90
|
+
let total=0;
|
|
91
|
+
for(const rel of selection) {
|
|
92
|
+
const omit=reason=>omissions.push({path:rel,reason});
|
|
93
|
+
if(secret(Buffer.from(rel))) fail('attachment_selection_contains_sensitive_value');
|
|
94
|
+
if(withheldRepoPath(rel,policy.excludedPaths)||matchesCredentialPathTerm(rel,policy.credentialPathTerms)) {omit('withheld_path');continue;}
|
|
95
|
+
const old=entry(root,publishedTree,rel);
|
|
96
|
+
if(old&&(old.type!=='blob'||!['100644','100755'].includes(old.mode))) {omit('unsupported_base_entry');continue;}
|
|
97
|
+
const head=old?null:entry(root,tip,rel);
|
|
98
|
+
const indexed=!old&&!head&&git(root,['--literal-pathspecs','ls-files','--stage','-z','--',rel]).stdout.length>0;
|
|
99
|
+
if(!old&&!head&&!indexed&&git(root,['check-ignore','-q','--',rel],{ok:[0,1]}).status===0) {omit('ignored');continue;}
|
|
100
|
+
const snap=current(root,rel);
|
|
101
|
+
if(snap.omit) {omit(snap.omit);continue;}
|
|
102
|
+
reads.push([rel,snap]);
|
|
103
|
+
if(!old&&!snap.bytes) {omit('not_present');continue;}
|
|
104
|
+
if(old&&Number(query('cat-file','-s',old.oid))>maxFile) {omit('file_too_large');continue;}
|
|
105
|
+
const before=old?git(root,['cat-file','blob',old.oid]).stdout:null;
|
|
106
|
+
const after=snap.bytes;
|
|
107
|
+
if(before&&after&&before.equals(after)&&old.mode===snap.mode) continue;
|
|
108
|
+
if(!validText(before)||!validText(after)) {omit('non_text');continue;}
|
|
109
|
+
if((before&&secret(before))||(after&&secret(after))) {omit('credential_content');continue;}
|
|
110
|
+
total+=(before?.length??0)+(after?.length??0);
|
|
111
|
+
if(total>maxPatch) fail('attachment_too_large');
|
|
112
|
+
const mode=after?snap.mode:'0';
|
|
113
|
+
const hash=after?text(pgit(['hash-object','--no-filters','-w','--stdin'],after)).trim():publishedBase.replace(/./g,'0');
|
|
114
|
+
pgit(['update-index','-z','--index-info'],Buffer.from(`${mode} ${hash}\t${rel}\0`));
|
|
115
|
+
entries.push({path:rel,disposition:!before?'added':!after?'deleted':'modified',
|
|
116
|
+
before_sha256:before?digest(before):null,after_sha256:after?digest(after):null,
|
|
117
|
+
before_mode:old?.mode??null,after_mode:after?snap.mode:null});
|
|
118
|
+
}
|
|
119
|
+
const inputTree=text(pgit(['write-tree'])).trim();
|
|
120
|
+
const patch=pgit(['diff-tree','--no-commit-id','--full-index','--no-ext-diff','--no-textconv',
|
|
121
|
+
'--no-renames','--text','--no-color','--diff-algorithm=myers','--src-prefix=a/','--dst-prefix=b/','-r','-p',publishedTree,inputTree]);
|
|
122
|
+
if(patch.length>maxPatch) fail('attachment_too_large');
|
|
123
|
+
if(!validText(patch)||secret(patch)) fail('attachment_patch_withheld');
|
|
124
|
+
for(const [rel,snap] of reads) {
|
|
125
|
+
const next=current(root,rel);
|
|
126
|
+
if(next.omit||next.mode!==snap.mode||(next.bytes===null)!==(snap.bytes===null)||
|
|
127
|
+
(next.bytes&&!next.bytes.equals(snap.bytes))) fail('attachment_capture_changed');
|
|
128
|
+
}
|
|
129
|
+
if(query('rev-parse','HEAD')!==tip) fail('attachment_capture_changed');
|
|
130
|
+
const manifest={version:1,repo,published_base:publishedBase,published_tree:publishedTree,input_tree:inputTree,patch_sha256:digest(patch),entries,omissions};
|
|
131
|
+
return {patch,manifest,manifest_sha256:digest(Buffer.from(canonicalJson(manifest)))};
|
|
132
|
+
} catch(error) {
|
|
133
|
+
if(error.code==='ENOENT'||error.code==='ELOOP'||error.code==='ENOTDIR') fail('attachment_capture_changed');
|
|
134
|
+
throw error;
|
|
135
|
+
} finally { fs.rmSync(scratch,{recursive:true,force:true}); }
|
|
136
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { captureLocalAttachment } from './local-attachment-capture.mjs';
|
|
3
|
+
import { sensitivePolicyPaths } from './submission-policy.mjs';
|
|
4
|
+
|
|
5
|
+
const oid=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
|
|
6
|
+
const digest=/^[a-f0-9]{64}$/;
|
|
7
|
+
const repo=/^[a-zA-Z0-9][a-zA-Z0-9_.-]*\/[a-zA-Z0-9][a-zA-Z0-9_.-]*$/;
|
|
8
|
+
const fail=(local_code,message)=>{throw Object.assign(new Error(message),{local_code});};
|
|
9
|
+
const invalid=()=>fail('invalid_attachment_arguments','use attachment preview --repo OWNER/REPO --base SHA --path FILE [--path FILE ...], or attachment send --work ID --confirm-manifest SHA256');
|
|
10
|
+
export function localAttachmentCommand(argv,{cwd=process.cwd(),capture=captureLocalAttachment,readPolicy=sensitivePolicyPaths}={}) {
|
|
11
|
+
const [action,...args]=argv;
|
|
12
|
+
if(!['preview','send'].includes(action))invalid();
|
|
13
|
+
const options=new Map(),paths=[];
|
|
14
|
+
const allowed=action==='preview'?['--repo','--base','--dir','--path']:['--work','--confirm-manifest'];
|
|
15
|
+
for(let i=0;i<args.length;i++){
|
|
16
|
+
const flag=args[i];
|
|
17
|
+
if(flag==='--json'){if(options.has(flag))invalid();options.set(flag,true);continue;}
|
|
18
|
+
if(!allowed.includes(flag)||options.has(flag))invalid();
|
|
19
|
+
const value=args[++i];
|
|
20
|
+
if(!value||value.startsWith('-')||/[\x00-\x1f\x7f]/.test(value))invalid();
|
|
21
|
+
if(flag==='--path'){paths.push(value);continue;}
|
|
22
|
+
options.set(flag,value);
|
|
23
|
+
}
|
|
24
|
+
if(action==='send'){
|
|
25
|
+
if(!/^[-\w]{8,128}$/.test(options.get('--work')??'')||!digest.test(options.get('--confirm-manifest')??''))invalid();
|
|
26
|
+
// No compatible owner/recipient route is advertised in this build. Never turn this into normal submit.
|
|
27
|
+
fail('local_attachment_send_unavailable','This bridge does not support sending local attachments. Nothing was read or sent.');
|
|
28
|
+
}
|
|
29
|
+
const publishedBase=options.get('--base'),name=options.get('--repo');
|
|
30
|
+
if(!oid.test(publishedBase??'')||!repo.test(name??'')||!paths.length)invalid();
|
|
31
|
+
const policy=readPolicy();
|
|
32
|
+
if(!policy||policy.error||!Array.isArray(policy.paths))fail('local_attachment_policy_unavailable','The local attachment policy could not be read. Nothing was sent.');
|
|
33
|
+
let prepared;
|
|
34
|
+
try {
|
|
35
|
+
prepared=capture({checkout:path.resolve(cwd,options.get('--dir')??'.'),repo:name,publishedBase,paths,
|
|
36
|
+
policy:{excludedPaths:policy.paths,credentialPathTerms:[]}});
|
|
37
|
+
} catch(e) {
|
|
38
|
+
fail(/^attachment_[a-z_]+$/.test(e.code??'')?e.code:'local_attachment_preview_failed','Could not freeze the selected local changes. Nothing was sent.');
|
|
39
|
+
}
|
|
40
|
+
const {manifest,manifest_sha256}=prepared;
|
|
41
|
+
// Deliberately return an explicit metadata projection; do not print the patch or the local filesystem root.
|
|
42
|
+
return {status:'preview',sent:false,send_available:false,repo:name,published_base:publishedBase,
|
|
43
|
+
manifest_sha256,patch_bytes:prepared.patch.length,
|
|
44
|
+
selected:manifest.entries.map(({path,disposition})=>({path,disposition})),
|
|
45
|
+
omitted:manifest.omissions.map(({path,reason})=>({path,reason}))};
|
|
46
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {canonicalJson} from '../packages/job-core/protocol/canonical.mjs';
|
|
3
|
+
import {createArtifactDownloadGuard} from './protocol-artifact-commands.mjs';
|
|
4
|
+
|
|
5
|
+
const bindingFields=['relationship_side','principal','route','adapter_binding','address'];
|
|
6
|
+
const invalid=code=>{throw Object.assign(new Error(code),{code});};
|
|
7
|
+
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
8
|
+
const digest=value=>typeof value==='string'&&/^[a-f0-9]{64}$/.test(value);
|
|
9
|
+
const chunkSize=18*1024;
|
|
10
|
+
function exact(value) {
|
|
11
|
+
if(!value||!bindingFields.every(key=>typeof value[key]==='string'&&value[key]&&value[key].length<=512&&
|
|
12
|
+
!/[\x00-\x1f\x7f]/.test(value[key])))invalid('attachment_recipient_unavailable');
|
|
13
|
+
return Object.fromEntries(bindingFields.map(k=>[k,value[k]]));
|
|
14
|
+
}
|
|
15
|
+
// No route constructor can self-attest. Both callbacks look up independent trusted facts;
|
|
16
|
+
// do not use request bodies or a requester result-delivery address for either lookup.
|
|
17
|
+
// The private owner artifact adapter must not expose its staged bytes on a public artifact URL.
|
|
18
|
+
export function createLocalAttachmentArtifactGateway({
|
|
19
|
+
transaction,snapshots,registeredDestination,authenticatedDestination,
|
|
20
|
+
downloadGuard=createArtifactDownloadGuard(),
|
|
21
|
+
}) {
|
|
22
|
+
function configured() {
|
|
23
|
+
if([transaction,registeredDestination,authenticatedDestination,downloadGuard,
|
|
24
|
+
snapshots?.seal,snapshots?.read,snapshots?.authorizeRead,snapshots?.verify].some(f=>typeof f!=='function'))
|
|
25
|
+
invalid('attachment_recipient_unavailable');
|
|
26
|
+
}
|
|
27
|
+
function route(work) {
|
|
28
|
+
if(typeof work!=='string'||!work)invalid('attachment_recipient_unavailable');
|
|
29
|
+
return exact(registeredDestination(work));
|
|
30
|
+
}
|
|
31
|
+
function match(actual,expected) {
|
|
32
|
+
if(canonicalJson(exact(actual))!==canonicalJson(expected))invalid('attachment_audience_mismatch');
|
|
33
|
+
}
|
|
34
|
+
function seal(options) {
|
|
35
|
+
configured();
|
|
36
|
+
return transaction(()=>{
|
|
37
|
+
const registered=route(options.work);
|
|
38
|
+
match(options.approval?.recipient,registered); // no checkout read or upload for unsupported routes
|
|
39
|
+
const receipt=snapshots.seal(options);
|
|
40
|
+
match(route(options.work),registered);
|
|
41
|
+
return receipt;
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
function read({work,actor,claim_id,epoch,binding_sha256,offset=0,patch_sha256}) {
|
|
45
|
+
configured();
|
|
46
|
+
if(!digest(binding_sha256)||!Number.isSafeInteger(offset)||offset<0||offset%chunkSize!==0||
|
|
47
|
+
(offset!==0&&!digest(patch_sha256))||(patch_sha256!==undefined&&!digest(patch_sha256)))
|
|
48
|
+
invalid('attachment_invalid_artifact_read');
|
|
49
|
+
return transaction(()=>{
|
|
50
|
+
const expected=route(work);
|
|
51
|
+
const context={work,actor,claim_id,epoch};
|
|
52
|
+
const recheck=()=>{
|
|
53
|
+
match(route(work),expected);
|
|
54
|
+
match(authenticatedDestination(context),expected);
|
|
55
|
+
const current=snapshots.authorizeRead(context);
|
|
56
|
+
if(current.binding_sha256!==binding_sha256)invalid('attachment_artifact_mismatch');
|
|
57
|
+
};
|
|
58
|
+
recheck();
|
|
59
|
+
const selected=snapshots.read(context);
|
|
60
|
+
if(selected.binding_sha256!==binding_sha256||
|
|
61
|
+
(patch_sha256!==undefined&&patch_sha256!==selected.manifest.patch_sha256))
|
|
62
|
+
invalid('attachment_artifact_mismatch');
|
|
63
|
+
const bytes=selected.bytes, patchHash=selected.manifest.patch_sha256;
|
|
64
|
+
downloadGuard({bytes,sha256:patchHash,id:binding_sha256,requestId:work});
|
|
65
|
+
if(offset>bytes.length||(offset===bytes.length&&offset>0))invalid('attachment_invalid_artifact_read');
|
|
66
|
+
const end=Math.min(offset+chunkSize,bytes.length);
|
|
67
|
+
// Omitted names are owner-only; publish just the count with a separately
|
|
68
|
+
// identified worker manifest. The receipt still binds the exact owner manifest.
|
|
69
|
+
const {omissions,...visible}=selected.manifest;
|
|
70
|
+
const manifest={...visible,omitted_count:omissions.length};
|
|
71
|
+
const metadata=Buffer.from(canonicalJson(manifest));
|
|
72
|
+
const manifestHash=sha(metadata);
|
|
73
|
+
downloadGuard({bytes:metadata,sha256:manifestHash,id:binding_sha256,requestId:work});
|
|
74
|
+
recheck(); // after storage/scanner work, before releasing even metadata
|
|
75
|
+
return {binding_sha256,manifest,manifest_sha256:manifestHash,
|
|
76
|
+
owner_manifest_sha256:sha(Buffer.from(canonicalJson(selected.manifest))),sha256:patchHash,
|
|
77
|
+
size:bytes.length,offset,next_offset:end===bytes.length?null:end,data_base64:bytes.subarray(offset,end).toString('base64')};
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
function verify(options) {
|
|
81
|
+
configured();
|
|
82
|
+
return transaction(()=>{
|
|
83
|
+
const expected=route(options.work);
|
|
84
|
+
const receipt=snapshots.verify(options);
|
|
85
|
+
match(route(options.work),expected);
|
|
86
|
+
return {...receipt,assertCallerUnchanged(){
|
|
87
|
+
match(route(options.work),expected);
|
|
88
|
+
return receipt.assertCallerUnchanged();
|
|
89
|
+
}};
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
return {seal,read,verify};
|
|
93
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { gitEnv } from './git-env.mjs';
|
|
7
|
+
import { canonicalJson } from '../packages/job-core/protocol/canonical.mjs';
|
|
8
|
+
|
|
9
|
+
const oid = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
|
|
10
|
+
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
11
|
+
const decode = bytes => new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes);
|
|
12
|
+
const error = code => Object.assign(new Error(code),{code});
|
|
13
|
+
const maxBytes = 4 * 1024 * 1024;
|
|
14
|
+
const env = {...gitEnv(),GIT_TERMINAL_PROMPT:'0'};
|
|
15
|
+
const git = (cwd,args,{input,override=env}={})=>{
|
|
16
|
+
const r=spawnSync('git',args,{cwd,env:override,input,maxBuffer:16*1024*1024,timeout:15000});
|
|
17
|
+
if(r.status!==0) throw error('attachment_verification_git_failed');
|
|
18
|
+
return r.stdout;
|
|
19
|
+
};
|
|
20
|
+
function rows(bytes) {
|
|
21
|
+
return decode(bytes).split('\0').filter(Boolean).map(row=>{
|
|
22
|
+
const m=/^(\d+) (\S+) ([a-f0-9]+)\t(.+)$/.exec(row);
|
|
23
|
+
if(!m) throw error('attachment_unsupported_tree_entry');
|
|
24
|
+
return {mode:m[1],type:m[2],oid:m[3],path:m[4]};
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
function sealedBytes(data) {
|
|
28
|
+
if(!Buffer.isBuffer(data)||data.length>maxBytes) throw error('attachment_invalid_patch');
|
|
29
|
+
return Buffer.from(data);
|
|
30
|
+
}
|
|
31
|
+
function unchanged(a,b) {
|
|
32
|
+
return a.dev===b.dev&&a.ino===b.ino&&a.mode===b.mode&&a.size===b.size&&
|
|
33
|
+
a.mtimeNs===b.mtimeNs&&a.ctimeNs===b.ctimeNs;
|
|
34
|
+
}
|
|
35
|
+
function liveFile(cwd,rel,expectedMode,expectedOid,format) {
|
|
36
|
+
let file=cwd;
|
|
37
|
+
for(const part of rel.split('/')) {
|
|
38
|
+
if(!part||part==='.'||part==='..'||part.toLowerCase()==='.git') return false;
|
|
39
|
+
file=path.join(file,part);
|
|
40
|
+
const s=fs.lstatSync(file,{bigint:true,throwIfNoEntry:false});
|
|
41
|
+
if(!s||s.isSymbolicLink()) return false;
|
|
42
|
+
}
|
|
43
|
+
const fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW|fs.constants.O_NONBLOCK);
|
|
44
|
+
try {
|
|
45
|
+
const before=fs.fstatSync(fd,{bigint:true});
|
|
46
|
+
if(!before.isFile()||fs.realpathSync(file)!==file||(before.mode&0o100n?'100755':'100644')!==expectedMode) return false;
|
|
47
|
+
const hasher=createHash(format).update(`blob ${before.size}\0`);
|
|
48
|
+
const data=Buffer.alloc(65536);
|
|
49
|
+
let bytes=0n;
|
|
50
|
+
for(;;) {
|
|
51
|
+
const n=fs.readSync(fd,data,0,data.length,null);
|
|
52
|
+
if(!n) break;
|
|
53
|
+
bytes+=BigInt(n);
|
|
54
|
+
if(bytes>before.size) return false;
|
|
55
|
+
hasher.update(data.subarray(0,n));
|
|
56
|
+
}
|
|
57
|
+
return bytes===before.size&&unchanged(before,fs.fstatSync(fd,{bigint:true}))&&
|
|
58
|
+
unchanged(before,fs.lstatSync(file,{bigint:true}))&&hasher.digest('hex')===expectedOid;
|
|
59
|
+
} finally {fs.closeSync(fd);}
|
|
60
|
+
}
|
|
61
|
+
function existsOrHasUnsafeAncestor(cwd,rel) {
|
|
62
|
+
let file=cwd;
|
|
63
|
+
const parts=rel.split('/');
|
|
64
|
+
for(const [i,part] of parts.entries()){
|
|
65
|
+
if(!part||part==='..'||part==='.'||part.toLowerCase()==='.git') return true;
|
|
66
|
+
file=path.join(file,part);
|
|
67
|
+
const s=fs.lstatSync(file,{throwIfNoEntry:false});
|
|
68
|
+
if(!s) return false;
|
|
69
|
+
if(i===parts.length-1||!s.isDirectory()||s.isSymbolicLink()) return true;
|
|
70
|
+
}
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Returns a proof and a fresh guard, not permission or a live apply operation.
|
|
75
|
+
// The integration must serialize the final guard with the apply it controls.
|
|
76
|
+
export function verifyLocalAttachmentResult({
|
|
77
|
+
checkout, repo, manifest, manifestSha256, sealedPatch, expectedInputTree,
|
|
78
|
+
outputDelta, deltaBase, expectedOutputTree, expiresAtMs, now=Date.now,
|
|
79
|
+
}) {
|
|
80
|
+
const fresh=()=>{
|
|
81
|
+
if(!Number.isSafeInteger(expiresAtMs)||now()>=expiresAtMs) throw error('attachment_input_expired');
|
|
82
|
+
};
|
|
83
|
+
fresh();
|
|
84
|
+
if(!path.isAbsolute(checkout??'') || typeof repo!=='string' || manifest?.version!==1 || manifest.repo!==repo ||
|
|
85
|
+
![manifest.published_base,manifest.published_tree,manifest.input_tree,deltaBase,expectedOutputTree].every(v=>oid.test(v??'')) ||
|
|
86
|
+
manifest.input_tree!==expectedInputTree || deltaBase!==expectedInputTree ||
|
|
87
|
+
sha(Buffer.from(canonicalJson(manifest)))!==manifestSha256) throw error('attachment_result_binding_mismatch');
|
|
88
|
+
const patch=sealedBytes(sealedPatch), delta=sealedBytes(outputDelta);
|
|
89
|
+
if(sha(patch)!==manifest.patch_sha256) throw error('attachment_patch_digest_mismatch');
|
|
90
|
+
const root=fs.realpathSync(checkout);
|
|
91
|
+
const q=(...args)=>decode(git(root,args)).trimEnd();
|
|
92
|
+
if(q('rev-parse','--show-toplevel')!==root||q('rev-parse',manifest.published_base+'^{commit}')!==manifest.published_base||
|
|
93
|
+
q('rev-parse',manifest.published_base+'^{tree}')!==manifest.published_tree) throw error('attachment_published_tree_mismatch');
|
|
94
|
+
const format=q('rev-parse','--show-object-format'), objects=q('rev-parse','--path-format=absolute','--git-path','objects');
|
|
95
|
+
const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'dalan-local-verify-'));
|
|
96
|
+
let inputRows, publishedPaths, additions;
|
|
97
|
+
try {
|
|
98
|
+
git(scratch,['init','--quiet','--bare','--object-format='+format,'repo']);
|
|
99
|
+
const override={...env,GIT_ALTERNATE_OBJECT_DIRECTORIES:JSON.stringify(objects),GIT_INDEX_FILE:path.join(scratch,'index')};
|
|
100
|
+
const privateGit=(args,input)=>git(scratch,['--git-dir='+path.join(scratch,'repo'),...args],{input,override});
|
|
101
|
+
privateGit(['read-tree',manifest.published_tree]);
|
|
102
|
+
if(patch.length) privateGit(['apply','--cached','--whitespace=nowarn','-'],patch);
|
|
103
|
+
if(decode(privateGit(['write-tree'])).trim()!==expectedInputTree) throw error('attachment_input_tree_mismatch');
|
|
104
|
+
inputRows=rows(privateGit(['ls-tree','-r','-z',expectedInputTree]));
|
|
105
|
+
const originRows=rows(privateGit(['ls-tree','-r','-z',manifest.published_tree]));
|
|
106
|
+
const origin=new Map(originRows.map(e=>[e.path,e])),input=new Map(inputRows.map(e=>[e.path,e]));
|
|
107
|
+
publishedPaths=[...origin.keys()];
|
|
108
|
+
const changed=[...new Set([...origin.keys(),...input.keys()])].sort().filter(p=>
|
|
109
|
+
origin.get(p)?.oid!==input.get(p)?.oid||origin.get(p)?.mode!==input.get(p)?.mode);
|
|
110
|
+
if(!Array.isArray(manifest.entries)||manifest.entries.length!==changed.length||!Array.isArray(manifest.omissions)||
|
|
111
|
+
manifest.omissions.some(e=>!e||typeof e.path!=='string'||changed.includes(e.path)))
|
|
112
|
+
throw error('attachment_manifest_entries_mismatch');
|
|
113
|
+
const observed=(e)=>e?sha(privateGit(['cat-file','blob',e.oid])):null;
|
|
114
|
+
for(const [i,p] of changed.entries()){
|
|
115
|
+
const a=origin.get(p),b=input.get(p),e=manifest.entries[i];
|
|
116
|
+
if(!e||e.path!==p||e.disposition!==(!a?'added':!b?'deleted':'modified')||
|
|
117
|
+
e.before_mode!==(a?.mode??null)||e.after_mode!==(b?.mode??null)||
|
|
118
|
+
e.before_sha256!==observed(a)||e.after_sha256!==observed(b)) throw error('attachment_manifest_entries_mismatch');
|
|
119
|
+
}
|
|
120
|
+
if(delta.length) privateGit(['apply','--cached','--whitespace=nowarn','-'],delta);
|
|
121
|
+
if(decode(privateGit(['write-tree'])).trim()!==expectedOutputTree) throw error('attachment_output_tree_mismatch');
|
|
122
|
+
const before=new Map(inputRows.map(e=>[e.path,e]));
|
|
123
|
+
const outputRows=rows(privateGit(['ls-tree','-r','-z',expectedOutputTree]));
|
|
124
|
+
additions=outputRows.filter(e=>!before.has(e.path)).map(e=>e.path);
|
|
125
|
+
if([...inputRows,...outputRows].some(e=>e.type!=='blob'||!['100644','100755'].includes(e.mode))) throw error('attachment_unsupported_tree_entry');
|
|
126
|
+
} finally {fs.rmSync(scratch,{recursive:true,force:true});}
|
|
127
|
+
const assertCallerUnchanged=()=>{
|
|
128
|
+
fresh();
|
|
129
|
+
const beforeHead=q('rev-parse','HEAD');
|
|
130
|
+
try {
|
|
131
|
+
const actualIndex=decode(git(root,['ls-files','-z','--cached'])).split('\0').filter(Boolean);
|
|
132
|
+
const expectedPaths=new Set(inputRows.map(e=>e.path));
|
|
133
|
+
// Extra staged tracked files (including a selected deletion still present in the old index)
|
|
134
|
+
// cannot stand in for actual worktree identity; allow only those whose bytes are absent.
|
|
135
|
+
const extra=[...new Set([...actualIndex,...publishedPaths])].filter(rel=>!expectedPaths.has(rel));
|
|
136
|
+
if(inputRows.some(e=>!liveFile(root,e.path,e.mode,e.oid,format))||
|
|
137
|
+
[...extra,...additions].some(rel=>existsOrHasUnsafeAncestor(root,rel))||
|
|
138
|
+
q('rev-parse','HEAD')!==beforeHead) throw error('attachment_caller_conflict');
|
|
139
|
+
} catch(e) {
|
|
140
|
+
if(['ENOENT','ENOTDIR','ELOOP'].includes(e.code)) throw error('attachment_caller_conflict');
|
|
141
|
+
throw e;
|
|
142
|
+
}
|
|
143
|
+
fresh();
|
|
144
|
+
return true;
|
|
145
|
+
};
|
|
146
|
+
fresh();
|
|
147
|
+
let callerMatches;
|
|
148
|
+
try {callerMatches=assertCallerUnchanged();}
|
|
149
|
+
catch(e) {if(e.code!=='attachment_caller_conflict')throw e;callerMatches=false;}
|
|
150
|
+
return {input_tree:expectedInputTree,output_tree:expectedOutputTree,output_delta_sha256:sha(delta),
|
|
151
|
+
caller_matches:callerMatches,apply_conflict:callerMatches?null:'attachment_caller_conflict',assertCallerUnchanged};
|
|
152
|
+
}
|