@feng0531/dsh-vcs 0.7.2 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -6
- package/amend-host.mjs +48 -0
- package/branch-create-host.mjs +42 -0
- package/branch-create-preview.mjs +196 -0
- package/branch-delete-preview.mjs +214 -0
- package/branch-switch-host.mjs +13 -33
- package/commit-host.mjs +49 -0
- package/commit-object-publish.mjs +123 -0
- package/commit-preview.mjs +335 -0
- package/confirmed-operation.mjs +50 -0
- package/dist/client.js +2 -2
- package/dist/frontend.json +1 -1
- package/dist/interface.js +2 -2
- package/docs/RELEASING.md +7 -5
- package/git-blob-store.mjs +151 -0
- package/git-branch-create.mjs +156 -0
- package/git-branch-delete.mjs +175 -0
- package/git-lightweight-tag-create.mjs +181 -0
- package/git-object-store.mjs +162 -0
- package/git-ref-cas.mjs +119 -0
- package/git-tag-create.mjs +186 -0
- package/index-change-host.mjs +19 -0
- package/index-change.mjs +418 -0
- package/index-lock.mjs +231 -0
- package/index-stage-host.mjs +19 -0
- package/index.mjs +301 -4
- package/latest-commit.mjs +109 -0
- package/lightweight-tag-host.mjs +42 -0
- package/lightweight-tag-preview.mjs +183 -0
- package/line-index-host.mjs +58 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +48 -3
- package/partial-stage-host.mjs +52 -0
- package/partial-unstage-host.mjs +52 -0
- package/src/amend-plan.mjs +74 -0
- package/src/branch-delete-plan.mjs +113 -0
- package/src/commit-plan.mjs +78 -0
- package/src/git-commit-object.mjs +99 -0
- package/src/git-index.mjs +113 -0
- package/src/git-tag-object.mjs +110 -0
- package/src/index-tree.mjs +77 -0
- package/src/lightweight-tag-plan.mjs +64 -0
- package/src/line-index.mjs +168 -0
- package/src/partial-index.mjs +199 -0
- package/src/reflog.mjs +33 -0
- package/src/settled-reads.mjs +5 -0
- package/src/verified-branch-delete-plan.mjs +95 -0
- package/src/verified-commit-metadata.mjs +57 -0
- package/src/verified-commit-plan.mjs +49 -0
- package/src/verified-commit.mjs +84 -0
- package/src/verified-tag-plan.mjs +72 -0
- package/tag-create-host.mjs +31 -0
- package/tag-create-preview.mjs +215 -0
- package/tag-object-publish.mjs +49 -0
- package/vcs.mjs +29 -0
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Internal only: caller owns the repository mutation mutex and trusted callbacks.
|
|
2
|
+
// No RPC/UI/commit adapter. Hostile concurrent directory replacement is excluded:
|
|
3
|
+
// portable Node path/identity checks cannot provide dirfd-relative isolation.
|
|
4
|
+
// Packed refs, linked/shared metadata, reftable and alternates fail closed.
|
|
5
|
+
// No external global guarantee or hostile directory-swap/ABA isolation is claimed.
|
|
6
|
+
// On supported Git, zero-old --no-deref rejects even dangling symbolic targets;
|
|
7
|
+
// the focused real-Git characterization test guards that version-dependent fact.
|
|
8
|
+
import * as fs from 'node:fs/promises';
|
|
9
|
+
import {constants} from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import {parseVerifiedCommit} from './src/verified-commit.mjs';
|
|
13
|
+
import {git} from './local-command.mjs';
|
|
14
|
+
import {withOperationBudget,currentOperationBudget} from './src/operation-budget.mjs';
|
|
15
|
+
|
|
16
|
+
const fail=(kind,message,cause)=>Object.assign(new Error(message,{cause}),{code:'vcs/lightweight-tag-create-'+kind});
|
|
17
|
+
const same=(a,b)=>a.dev===b.dev&&a.ino===b.ino&&a.birthtimeNs===b.birthtimeNs;
|
|
18
|
+
const plain=s=>s.isFile()&&!s.isSymbolicLink()&&s.nlink===1n;
|
|
19
|
+
const decode=b=>new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(b);
|
|
20
|
+
function validRef(ref,prefix='refs/tags/'){
|
|
21
|
+
const name=typeof ref==='string'&&ref.startsWith(prefix)?ref.slice(prefix.length):'';
|
|
22
|
+
if(!name||Buffer.from(name,'utf8').toString('utf8')!==name||Buffer.byteLength(name)>1000||
|
|
23
|
+
name==='@'||name.toUpperCase()==='HEAD'||name.startsWith('-')||name.startsWith('refs/')||
|
|
24
|
+
/[\x00-\x20\x7f~^:?*\[\\<>"|\p{Cc}\p{Cf}]/u.test(name)||name.includes('..')||name.includes('@{')||
|
|
25
|
+
name.split('/').some(p=>!p||Buffer.byteLength(p)>255||p.startsWith('.')||/[. ]$/.test(p)||p.toLowerCase().endsWith('.lock')||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p)))
|
|
26
|
+
throw fail('invalid','An exact safe portable '+prefix+' name is required.');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Create one absent local tag via Git update-ref --no-deref full-width zero-old CAS.
|
|
30
|
+
* Internal only: the caller MUST hold the repository writer mutex throughout.
|
|
31
|
+
* Existing born symbolic HEAD is pinned as a current fact, never a caller token.
|
|
32
|
+
* Returns {ref,commit}; fixed Dsh audit attribution, not user authorship.
|
|
33
|
+
* Packed refs (even unrelated), linked/shared metadata and locks fail closed.
|
|
34
|
+
* Index bodies are not read: optional index metadata versions are pinned only.
|
|
35
|
+
* No checkout, HEAD/index/worktree/object mutation, signing, network or retry.
|
|
36
|
+
* All failures after synchronous onStart are outcome-unknown. Never roll back,
|
|
37
|
+
* remove a competing ref or Git lock, or retry on the caller's behalf.
|
|
38
|
+
* Trusted callbacks must not mutate filesystem state; onStart must be synchronous.
|
|
39
|
+
* Portable path checks do not isolate hostile concurrent directory replacement.
|
|
40
|
+
*/
|
|
41
|
+
export async function createLightweightTag(repo,{ref,expectedCommitOid,objectFormat,signal,assertAuthorized,onStart}={}){
|
|
42
|
+
const root=repo?.root;
|
|
43
|
+
validRef(ref);
|
|
44
|
+
const oidPattern=objectFormat==='sha1'?/^[0-9a-f]{40}$/:objectFormat==='sha256'?/^[0-9a-f]{64}$/:null;
|
|
45
|
+
if(repo?.type!=='git'||typeof root!=='string'||!path.isAbsolute(root)||path.resolve(root)!==root||
|
|
46
|
+
!oidPattern||typeof expectedCommitOid!=='string'||!oidPattern.test(expectedCommitOid)||/^0+$/.test(expectedCommitOid)||
|
|
47
|
+
typeof assertAuthorized!=='function'||typeof onStart!=='function')throw fail('invalid','Canonical embedded Git root, a full commit OID and callbacks required.');
|
|
48
|
+
let started=false,hooks,owned,headText,headRef,headOid,indexVersion,commitBody,headLogs;
|
|
49
|
+
const directory=path.join(root,'.git'),identities=new Map();
|
|
50
|
+
const check=()=>{signal?.throwIfAborted();currentOperationBudget()?.throwIfExpired();};
|
|
51
|
+
const authorize=async()=>{check();await assertAuthorized();check();};
|
|
52
|
+
async function dir(p){
|
|
53
|
+
check();const s=await fs.lstat(p,{bigint:true});
|
|
54
|
+
if(!s.isDirectory()||s.isSymbolicLink()||await fs.realpath(p)!==p||(identities.has(p)&&!same(identities.get(p),s)))throw fail('unsafe','Noncanonical or replaced directory.');
|
|
55
|
+
identities.set(p,s);return s;
|
|
56
|
+
}
|
|
57
|
+
async function read(p,max=4096){
|
|
58
|
+
check();const before=await fs.lstat(p,{bigint:true});
|
|
59
|
+
if(!plain(before)||before.size>BigInt(max))throw fail('unsafe','Expected bounded single-link metadata.');
|
|
60
|
+
const h=await fs.open(p,constants.O_RDONLY|(constants.O_NOFOLLOW||0));
|
|
61
|
+
try{
|
|
62
|
+
const opened=await h.stat({bigint:true});
|
|
63
|
+
if(!plain(opened)||!same(before,opened))throw fail('unsafe','Metadata replaced.');
|
|
64
|
+
const b=Buffer.alloc(max+1);let n=0;
|
|
65
|
+
while(n<b.length){check();const r=await h.read(b,n,b.length-n,n);if(!r.bytesRead)break;n+=r.bytesRead;}
|
|
66
|
+
const after=await h.stat({bigint:true}),now=await fs.lstat(p,{bigint:true});
|
|
67
|
+
if(n>max||!plain(now)||!same(opened,now)||opened.size!==after.size||opened.mtimeNs!==after.mtimeNs||opened.ctimeNs!==after.ctimeNs||after.size!==now.size||after.mtimeNs!==now.mtimeNs||after.ctimeNs!==now.ctimeNs||BigInt(n)!==after.size)throw fail('unsafe','Metadata changed.');
|
|
68
|
+
return decode(b.subarray(0,n));
|
|
69
|
+
}finally{await h.close();}
|
|
70
|
+
}
|
|
71
|
+
async function metadata(){
|
|
72
|
+
await dir(root);let count=0;
|
|
73
|
+
const forbidden=new Set(['commondir','gitdir','worktrees','reftable','packed-refs','shallow','config.worktree','objects/info/alternates','objects/info/http-alternates','MERGE_HEAD','CHERRY_PICK_HEAD','REVERT_HEAD','rebase-merge','rebase-apply','sequencer'].map(s=>s.toLowerCase()));
|
|
74
|
+
async function visit(p,rel){
|
|
75
|
+
check();if(++count>20000)throw fail('unsupported','Metadata node bound exceeded.');
|
|
76
|
+
const lower=rel.toLowerCase();
|
|
77
|
+
if(forbidden.has(lower)||lower.endsWith('.lock')||lower.endsWith('.promisor')||lower.startsWith('sharedindex.'))throw fail('unsupported','Unsupported metadata or lock: '+rel);
|
|
78
|
+
const s=await fs.lstat(p,{bigint:true});
|
|
79
|
+
if(s.isSymbolicLink()||await fs.realpath(p)!==p)throw fail('unsafe','Linked metadata.');
|
|
80
|
+
if(s.isDirectory()){await dir(p);for(const name of await fs.readdir(p))await visit(path.join(p,name),rel?rel+'/'+name:name);}
|
|
81
|
+
else if(!plain(s))throw fail('unsafe','Shared or special metadata.');
|
|
82
|
+
}
|
|
83
|
+
await visit(directory,'');
|
|
84
|
+
}
|
|
85
|
+
const run=(args,max=16384)=>{check();return git(root,['-c','core.hooksPath='+hooks,'-c','user.name=Dsh','-c','user.email=dsh@localhost','-c','committer.name=Dsh','-c','committer.email=dsh@localhost','--git-dir='+directory,'--work-tree='+root,...args],max,{signal});};
|
|
86
|
+
async function config(){
|
|
87
|
+
// FIRST Git call: never expand include/includeIf (including global/system).
|
|
88
|
+
const rows=decode(await run(['config','--no-includes','--null','--list'],128*1024)).split('\0').filter(Boolean);
|
|
89
|
+
for(const row of rows){const i=row.indexOf('\n'),key=(i<0?row:row.slice(0,i)).toLowerCase(),value=i<0?'':row.slice(i+1).toLowerCase();
|
|
90
|
+
if(key.startsWith('include')||key.startsWith('extensions.')&&key!=='extensions.objectformat'||key==='core.worktree'||key==='core.repositoryformatversion'&&!['0','1'].includes(value)||key==='core.bare'&&value!=='false'||key==='core.sharedrepository'&&!['false','0'].includes(value)||/^remote\..*\.(promisor|partialclonefilter)$/.test(key))throw fail('unsupported','Unsupported configuration: '+key);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
async function indexStat(){
|
|
94
|
+
check();try{
|
|
95
|
+
const s=await fs.lstat(path.join(directory,'index'),{bigint:true});
|
|
96
|
+
if(!plain(s))throw fail('unsafe','Index must be single-link regular metadata.');
|
|
97
|
+
return s;
|
|
98
|
+
}catch(error){if(error.code==='ENOENT')return null;throw error;}
|
|
99
|
+
}
|
|
100
|
+
function sameVersion(a,b){return a===null?b===null:b!==null&&same(a,b)&&a.size===b.size&&a.mtimeNs===b.mtimeNs&&a.ctimeNs===b.ctimeNs;}
|
|
101
|
+
async function absentTarget(){
|
|
102
|
+
// Reject exact, prefix and portable case-fold collisions in both namespaces.
|
|
103
|
+
for(const parts of [ref.split('/'),['logs',...ref.split('/')]]){
|
|
104
|
+
let p=directory;
|
|
105
|
+
for(let i=0;i<parts.length;i++){
|
|
106
|
+
let names;try{names=await fs.readdir(p);}catch(e){if(e.code==='ENOENT')break;throw e;}
|
|
107
|
+
const name=parts[i],matches=names.filter(n=>n.toLowerCase()===name.toLowerCase());
|
|
108
|
+
if(matches.some(n=>n!==name))throw fail('exists','Case-colliding tag namespace.');
|
|
109
|
+
if(!matches.length)break;
|
|
110
|
+
p=path.join(p,name);
|
|
111
|
+
if(i===parts.length-1||(await fs.lstat(p)).isDirectory()===false)throw fail('exists','Target tag, reflog or namespace exists.');
|
|
112
|
+
await dir(p);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async function optionalRead(p,max=2*1024*1024){
|
|
117
|
+
try{return await read(p,max);}catch(e){if(e.code==='ENOENT')return null;throw e;}
|
|
118
|
+
}
|
|
119
|
+
async function verifyObjects(){
|
|
120
|
+
const target=await run(['cat-file','commit',expectedCommitOid],2*1024*1024);
|
|
121
|
+
parseVerifiedCommit(target,{oid:expectedCommitOid,objectFormat,signal});
|
|
122
|
+
if(commitBody!==undefined&&!commitBody.equals(target))throw fail('stale','Original commit content changed.');
|
|
123
|
+
commitBody=target;
|
|
124
|
+
}
|
|
125
|
+
async function state(created=false){
|
|
126
|
+
await metadata();await config();
|
|
127
|
+
const current=await read(path.join(directory,'HEAD'));
|
|
128
|
+
if(headText===undefined){
|
|
129
|
+
if(!current.startsWith('ref: ')||!current.endsWith('\n'))throw fail('stale','Existing born symbolic HEAD required.');
|
|
130
|
+
headRef=current.slice(5,-1);validRef(headRef,'refs/heads/');headText=current;
|
|
131
|
+
headOid=(await read(path.join(directory,...headRef.split('/')))).replace(/\n$/,'');
|
|
132
|
+
if(!oidPattern.test(headOid)||/^0+$/.test(headOid))throw fail('stale','HEAD must name a born direct commit.');
|
|
133
|
+
}
|
|
134
|
+
if(current!==headText||await read(path.join(directory,...headRef.split('/')))!==headOid+'\n')throw fail('stale','Original HEAD changed.');
|
|
135
|
+
const logs=await Promise.all(['logs/HEAD','logs/'+headRef].map(p=>optionalRead(path.join(directory,...p.split('/')))));
|
|
136
|
+
if(headLogs===undefined)headLogs=logs;
|
|
137
|
+
else if(logs.some((v,i)=>v!==headLogs[i]))throw fail('stale','Original HEAD reflogs changed.');
|
|
138
|
+
if(created){
|
|
139
|
+
if(await read(path.join(directory,...ref.split('/')))!==expectedCommitOid+'\n')throw fail('stale','Created tag is no longer the exact direct commit OID.');
|
|
140
|
+
const log=await optionalRead(path.join(directory,'logs',...ref.split('/')));
|
|
141
|
+
if(log!==null){
|
|
142
|
+
const zero='0'.repeat(expectedCommitOid.length);
|
|
143
|
+
const pattern=new RegExp('^'+zero+' '+expectedCommitOid+' Dsh <dsh@localhost> [0-9]+ [+-][0-9]{4}\\tdsh: create lightweight tag\\n$');
|
|
144
|
+
if(!pattern.test(log))throw fail('stale','Unexpected created tag reflog.');
|
|
145
|
+
}
|
|
146
|
+
}else await absentTarget();
|
|
147
|
+
const facts=decode(await run(['rev-parse','--absolute-git-dir','--git-common-dir','--show-toplevel','--is-bare-repository','--show-object-format','--verify','HEAD'])).trimEnd().split('\n');
|
|
148
|
+
if(facts.length!==6||path.resolve(root,facts[0])!==directory||path.resolve(root,facts[1])!==directory||path.resolve(facts[2])!==root||facts[3]!=='false'||facts[4]!==objectFormat||facts[5]!==headOid)throw fail('stale','Git repository facts changed.');
|
|
149
|
+
const now=await indexStat();
|
|
150
|
+
if(indexVersion===undefined)indexVersion=now;
|
|
151
|
+
else if(!sameVersion(indexVersion,now))throw fail('stale','Index metadata version changed.');
|
|
152
|
+
}
|
|
153
|
+
async function verifyHooks(){
|
|
154
|
+
const s=await fs.lstat(hooks,{bigint:true});
|
|
155
|
+
if(!s.isDirectory()||s.isSymbolicLink()||!same(owned,s)||await fs.realpath(hooks)!==hooks||(await fs.readdir(hooks)).length)throw fail('unsafe','Owned hooks directory changed or is not empty.');
|
|
156
|
+
}
|
|
157
|
+
try{
|
|
158
|
+
return await withOperationBudget({signal},async()=>{
|
|
159
|
+
await authorize();await metadata();
|
|
160
|
+
const temp=await fs.realpath(os.tmpdir());
|
|
161
|
+
if(temp===root||temp.startsWith(root+path.sep))throw fail('unsafe','Hooks directory must be outside repository.');
|
|
162
|
+
hooks=await fs.mkdtemp(path.join(temp,'dsh-lightweight-tag-hooks-'+process.pid+'-'));owned=await fs.lstat(hooks,{bigint:true});await verifyHooks();
|
|
163
|
+
await state();
|
|
164
|
+
await verifyObjects();
|
|
165
|
+
if(decode(await run(['cat-file','-t',headOid],1024))!=='commit\n')throw fail('invalid','Expected born branch must name a commit.');
|
|
166
|
+
await authorize();await state();await verifyHooks();await verifyObjects();check();
|
|
167
|
+
started=true;const result=onStart();
|
|
168
|
+
if(result&&typeof result.then==='function'){Promise.resolve(result).catch(()=>{});throw fail('invalid','onStart must be synchronous.');}
|
|
169
|
+
// No asynchronous work between the notification and mutation subprocess.
|
|
170
|
+
await run(['update-ref','--no-deref','-m','dsh: create lightweight tag',ref,expectedCommitOid,'0'.repeat(expectedCommitOid.length)],4096);
|
|
171
|
+
await authorize();await state(true);await authorize();check();
|
|
172
|
+
return {ref,commit:expectedCommitOid};
|
|
173
|
+
});
|
|
174
|
+
}catch(error){
|
|
175
|
+
if(started)throw Object.assign(fail('outcome-unknown','Tag update outcome is unknown; inspect before any further action.',error),{outcomeUnknown:true});
|
|
176
|
+
throw error;
|
|
177
|
+
}finally{
|
|
178
|
+
// Never recursively remove, unlink foreign entries, or delete a replaced path.
|
|
179
|
+
if(hooks&&owned)try{const s=await fs.lstat(hooks,{bigint:true});if(s.isDirectory()&&!s.isSymbolicLink()&&same(owned,s)&&await fs.realpath(hooks)===hooks&&(await fs.readdir(hooks)).length===0)await fs.rmdir(hooks);}catch{}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// Internal append-only primitive. No RPC, subprocess, Index, refs or worktree writes.
|
|
2
|
+
import {constants} from 'node:fs';
|
|
3
|
+
import {lstat, realpath, open, mkdir, link, unlink} from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {createHash, randomUUID} from 'node:crypto';
|
|
6
|
+
import {deflateSync, inflateSync} from 'node:zlib';
|
|
7
|
+
import {currentOperationBudget} from './src/operation-budget.mjs';
|
|
8
|
+
|
|
9
|
+
export const MAX_TREE_BYTES = 8 * 1024 * 1024;
|
|
10
|
+
export const MAX_COMMIT_BYTES = 128 * 1024;
|
|
11
|
+
export const MAX_TAG_BYTES = 128 * 1024;
|
|
12
|
+
const COMPRESSED_OVERHEAD_BYTES = 1024 * 1024;
|
|
13
|
+
const fail = (kind, message, cause) => Object.assign(new Error(message, {cause}), {code:'vcs/object-' + kind});
|
|
14
|
+
const same = (a,b) => a.dev === b.dev && a.ino === b.ino;
|
|
15
|
+
const plain = s => s.isFile() && !s.isSymbolicLink() && s.nlink === 1n;
|
|
16
|
+
const normalized = p => process.platform === 'win32' ? p.toLowerCase() : p;
|
|
17
|
+
const hash = (format, bytes) => createHash(format).update(bytes).digest('hex');
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Capture a Buffer synchronously before the first await, then store its exact Git
|
|
21
|
+
* tree, commit or tag representation. Returns {oid,created}; sha1 and sha256 are the only formats.
|
|
22
|
+
* The caller supplies an already validated embedded canonical .git directory and
|
|
23
|
+
* mandatory authorization and synchronous onStart callbacks. onStart precedes even
|
|
24
|
+
* fanout mkdir; an already-valid existing object returns without onStart (read-only).
|
|
25
|
+
* All errors after that notification are append-only outcome-unknown;
|
|
26
|
+
* a published object is NEVER removed, including after cancellation/revocation.
|
|
27
|
+
* Bodies are opaque: callers validate tree/commit/tag semantics, including referenced
|
|
28
|
+
* object existence/types. Storage checks only exact type/length/header/bytes/hash.
|
|
29
|
+
* Tree bodies are bounded to 8MiB, commits and tags to 128KiB, compressed bytes to the
|
|
30
|
+
* applicable body bound plus 1MiB. No blob API is provided by this module.
|
|
31
|
+
* Existing loose objects must be plain single-link files with bounded compressed
|
|
32
|
+
* and inflated size and exact raw content/hash. Packed-only objects are not read:
|
|
33
|
+
* creating a correct loose duplicate is safe. Alternates are not supported.
|
|
34
|
+
*
|
|
35
|
+
* Requires local filesystem exclusive-create and atomic hardlink NOREPLACE
|
|
36
|
+
* semantics. Unsupported hardlinks fail closed (no rename/copy fallback). Identity
|
|
37
|
+
* checks are conservative, not isolation against malicious concurrent directory
|
|
38
|
+
* replacement; Node has no portable dirfd-relative filesystem transaction. Caller
|
|
39
|
+
* must exclude hostile filesystem mutation. File sync is attempted, but directory
|
|
40
|
+
* fsync/crash durability and network filesystem semantics are NOT guaranteed.
|
|
41
|
+
*/
|
|
42
|
+
export async function storeCapturedObject({gitDirectory, objectFormat, type, bytes, signal, assertAuthorized, onStart} = {}) {
|
|
43
|
+
// Destructured type is an immutable primitive captured before any callback/await.
|
|
44
|
+
if (type !== 'tree' && type !== 'commit' && type !== 'tag') throw fail('invalid','Only explicit tree, commit or tag types are supported.');
|
|
45
|
+
const maxBodyBytes = type === 'tree' ? MAX_TREE_BYTES : type === 'commit' ? MAX_COMMIT_BYTES : MAX_TAG_BYTES;
|
|
46
|
+
const maxLooseBytes = maxBodyBytes + COMPRESSED_OVERHEAD_BYTES;
|
|
47
|
+
if (!Buffer.isBuffer(bytes)) throw fail('invalid','bytes must be a Buffer.');
|
|
48
|
+
if (bytes.length > maxBodyBytes) throw fail('too-large','Object body exceeds its type bound.');
|
|
49
|
+
const captured = Buffer.from(bytes); // Do not move below any await/callback.
|
|
50
|
+
if (!['sha1','sha256'].includes(objectFormat) || typeof gitDirectory !== 'string' ||
|
|
51
|
+
!path.isAbsolute(gitDirectory) || path.basename(gitDirectory) !== '.git' ||
|
|
52
|
+
typeof assertAuthorized !== 'function' || typeof onStart !== 'function') {
|
|
53
|
+
throw fail('invalid','Canonical embedded .git, exact objectFormat and authorization/start callbacks are required.');
|
|
54
|
+
}
|
|
55
|
+
const budget = currentOperationBudget();
|
|
56
|
+
const check = () => { signal?.throwIfAborted(); budget?.throwIfExpired(); };
|
|
57
|
+
const authorize = async () => { check(); await assertAuthorized(); check(); };
|
|
58
|
+
const directory = path.resolve(gitDirectory), objects = path.join(directory,'objects');
|
|
59
|
+
if(normalized(directory) !== normalized(gitDirectory))throw fail('unsafe','gitDirectory must be canonical, not a path alias.');
|
|
60
|
+
const raw = Buffer.concat([Buffer.from(type + ' ' + captured.length + '\0'),captured]);
|
|
61
|
+
const oid = hash(objectFormat,raw), fanout = path.join(objects,oid.slice(0,2)), target = path.join(fanout,oid.slice(2));
|
|
62
|
+
let started = false, handle, owned, temporary;
|
|
63
|
+
const directories = new Map();
|
|
64
|
+
const verifyDirectory = async p => {
|
|
65
|
+
check();
|
|
66
|
+
const s = await lstat(p,{bigint:true});
|
|
67
|
+
if (!s.isDirectory() || s.isSymbolicLink() || normalized(await realpath(p)) !== normalized(p) ||
|
|
68
|
+
(directories.has(p) && !same(directories.get(p),s))) throw fail('unsafe','Noncanonical or changed object directory.');
|
|
69
|
+
directories.set(p,s);
|
|
70
|
+
};
|
|
71
|
+
const absent = async p => {
|
|
72
|
+
try { await lstat(p); } catch(e) { if(e.code === 'ENOENT')return; throw e; }
|
|
73
|
+
throw fail('unsafe','Alternate or shared object storage is unsupported.');
|
|
74
|
+
};
|
|
75
|
+
const verifyStorage = async () => {
|
|
76
|
+
await verifyDirectory(directory); await verifyDirectory(objects);
|
|
77
|
+
await absent(path.join(directory,'commondir'));
|
|
78
|
+
const info = path.join(objects,'info');
|
|
79
|
+
try { await verifyDirectory(info); } catch(e) { if(e.code !== 'ENOENT')throw e; }
|
|
80
|
+
await absent(path.join(info,'alternates')); await absent(path.join(info,'http-alternates'));
|
|
81
|
+
check();
|
|
82
|
+
};
|
|
83
|
+
const validateExisting = async () => {
|
|
84
|
+
await verifyStorage(); await verifyDirectory(fanout);
|
|
85
|
+
let entry;
|
|
86
|
+
try { entry = await lstat(target,{bigint:true}); } catch(e) { if(e.code === 'ENOENT')return false; throw e; }
|
|
87
|
+
if(!plain(entry))throw fail('unsafe','Object must be a plain single-link file.');
|
|
88
|
+
if(entry.size > BigInt(maxLooseBytes))throw fail('corrupt','Compressed object exceeds bound.');
|
|
89
|
+
const file = await open(target,constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
|
|
90
|
+
try {
|
|
91
|
+
const before = await file.stat({bigint:true});
|
|
92
|
+
if(!plain(before) || !same(entry,before))throw fail('unsafe','Object identity changed while opening.');
|
|
93
|
+
if(before.size > BigInt(maxLooseBytes))throw fail('corrupt','Compressed object exceeds bound.');
|
|
94
|
+
const buffer = Buffer.alloc(Number(before.size) + 1); let length = 0;
|
|
95
|
+
while(length < buffer.length) {
|
|
96
|
+
check(); const {bytesRead} = await file.read(buffer,length,buffer.length-length,length);
|
|
97
|
+
if(!bytesRead)break; length += bytesRead;
|
|
98
|
+
}
|
|
99
|
+
const after = await file.stat({bigint:true}), current = await lstat(target,{bigint:true});
|
|
100
|
+
if(!plain(after) || !plain(current) || !same(before,current) || length !== Number(before.size) ||
|
|
101
|
+
before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs)throw fail('unsafe','Object changed while reading.');
|
|
102
|
+
let inflated;
|
|
103
|
+
try { inflated = inflateSync(buffer.subarray(0,length),{maxOutputLength:raw.length,info:true}); }
|
|
104
|
+
catch(e) { throw fail('corrupt','Invalid or oversized loose object.',e); }
|
|
105
|
+
if(inflated.engine.bytesWritten !== length || !inflated.buffer.equals(raw) || hash(objectFormat,inflated.buffer) !== oid)throw fail('corrupt','Loose object content/hash mismatch.');
|
|
106
|
+
await verifyStorage(); await verifyDirectory(fanout); check(); return true;
|
|
107
|
+
} finally { await file.close(); }
|
|
108
|
+
};
|
|
109
|
+
// Cleanup deliberately ignores cancellation but never removes a foreign path or
|
|
110
|
+
// final object. Retain uncertain temp files rather than guessing ownership.
|
|
111
|
+
const cleanup = async () => {
|
|
112
|
+
if(!temporary || !owned)return;
|
|
113
|
+
for(const p of [directory,objects,fanout]) {
|
|
114
|
+
const s = await lstat(p,{bigint:true});
|
|
115
|
+
if(!s.isDirectory() || s.isSymbolicLink() || !same(s,directories.get(p)) || normalized(await realpath(p)) !== normalized(p))throw fail('unsafe','Cannot safely clean changed directory.');
|
|
116
|
+
}
|
|
117
|
+
let current;
|
|
118
|
+
try { current = await lstat(temporary,{bigint:true}); } catch(e) { if(e.code === 'ENOENT'){temporary=undefined;return;} throw e; }
|
|
119
|
+
if(!current.isFile() || current.isSymbolicLink() || !same(current,owned))throw fail('unsafe','Temporary path ownership changed; retained.');
|
|
120
|
+
await unlink(temporary); temporary=undefined;
|
|
121
|
+
};
|
|
122
|
+
try {
|
|
123
|
+
await authorize(); await verifyStorage();
|
|
124
|
+
let hasFanout = true;
|
|
125
|
+
try { await verifyDirectory(fanout); } catch(e) { if(e.code !== 'ENOENT')throw e; hasFanout=false; }
|
|
126
|
+
if(hasFanout && await validateExisting()) { await authorize(); return {oid,created:false}; }
|
|
127
|
+
const compressed = deflateSync(raw); check();
|
|
128
|
+
await authorize(); await verifyStorage();
|
|
129
|
+
if(hasFanout)await verifyDirectory(fanout);
|
|
130
|
+
started=true;
|
|
131
|
+
const notification=onStart();
|
|
132
|
+
if(notification && typeof notification.then === 'function') {
|
|
133
|
+
Promise.resolve(notification).catch(()=>{});
|
|
134
|
+
throw fail('invalid','onStart must be synchronous.');
|
|
135
|
+
}
|
|
136
|
+
check();
|
|
137
|
+
if(!hasFanout) {
|
|
138
|
+
try { await mkdir(fanout); } catch(e) { if(e.code !== 'EEXIST')throw e; }
|
|
139
|
+
}
|
|
140
|
+
await verifyStorage(); await verifyDirectory(fanout); check();
|
|
141
|
+
temporary=path.join(fanout,'.dsh-object-' + randomUUID());
|
|
142
|
+
handle=await open(temporary,constants.O_CREAT|constants.O_EXCL|constants.O_WRONLY|(constants.O_NOFOLLOW||0),0o600);
|
|
143
|
+
owned=await handle.stat({bigint:true});
|
|
144
|
+
if(!plain(owned))throw fail('unsafe','Temporary object is not single-link.');
|
|
145
|
+
await handle.writeFile(compressed); check(); await handle.sync();
|
|
146
|
+
await handle.close(); handle=undefined;
|
|
147
|
+
await authorize(); await verifyStorage(); await verifyDirectory(fanout);
|
|
148
|
+
const temp=await lstat(temporary,{bigint:true});
|
|
149
|
+
if(!plain(temp) || !same(temp,owned) || temp.size !== BigInt(compressed.length))throw fail('unsafe','Temporary object changed.');
|
|
150
|
+
check(); let created=true;
|
|
151
|
+
try { await link(temporary,target); }
|
|
152
|
+
catch(e) { if(e.code !== 'EEXIST')throw e; created=false; }
|
|
153
|
+
await cleanup(); // Drop our second link before validating the final nlink=1.
|
|
154
|
+
if(!await validateExisting())throw fail('corrupt','Published object is missing.');
|
|
155
|
+
await authorize(); return {oid,created};
|
|
156
|
+
} catch(error) {
|
|
157
|
+
try { if(handle){await handle.close();handle=undefined;} await cleanup(); }
|
|
158
|
+
catch(cleanupError) { error = new AggregateError([error,cleanupError],'Object operation and owned-temp cleanup failed.'); }
|
|
159
|
+
if(!started)throw error;
|
|
160
|
+
throw Object.assign(fail('outcome-unknown','Append-only object storage started; object may exist. Never roll back with deletion or GC.',error),{outcomeUnknown:true,appendOnly:true});
|
|
161
|
+
}
|
|
162
|
+
}
|
package/git-ref-cas.mjs
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Internal only: caller owns the repository mutation mutex and trusted callbacks.
|
|
2
|
+
// No RPC/UI/commit adapter. Hostile concurrent directory replacement is excluded:
|
|
3
|
+
// portable Node path/identity checks cannot provide dirfd-relative isolation.
|
|
4
|
+
// Packed refs, linked/shared metadata, reftable and alternates fail closed.
|
|
5
|
+
import * as fs from 'node:fs/promises';
|
|
6
|
+
import {constants} from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import {git} from './local-command.mjs';
|
|
10
|
+
import {withOperationBudget,currentOperationBudget} from './src/operation-budget.mjs';
|
|
11
|
+
|
|
12
|
+
const fail=(kind,message,cause)=>Object.assign(new Error(message,{cause}),{code:'vcs/ref-'+kind});
|
|
13
|
+
const same=(a,b)=>a.dev===b.dev&&a.ino===b.ino&&a.birthtimeNs===b.birthtimeNs;
|
|
14
|
+
const plain=s=>s.isFile()&&!s.isSymbolicLink()&&s.nlink===1n;
|
|
15
|
+
const decode=b=>new TextDecoder('utf-8',{fatal:true}).decode(b);
|
|
16
|
+
function validRef(ref){
|
|
17
|
+
if(typeof ref!=='string'||!ref.startsWith('refs/heads/')||Buffer.byteLength(ref)>1024||
|
|
18
|
+
/[\x00- \x7f~^:?*[\\]/.test(ref)||ref.includes('..')||ref.includes('@{')||ref.endsWith('.')||
|
|
19
|
+
ref.split('/').some(p=>!p||p.startsWith('.')||p.toLowerCase().endsWith('.lock')||/[. ]$/.test(p)||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p)))
|
|
20
|
+
throw fail('invalid','An exact safe refs/heads branch is required.');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Atomically update one born current branch via Git old-OID CAS.
|
|
24
|
+
* Returns {ref,oldOid,newOid}. Reflog uses fixed Dsh <dsh@localhost> machine
|
|
25
|
+
* audit identity, not user attribution. All failures after synchronous onStart
|
|
26
|
+
* (including callback errors/CAS rejection) are outcome-unknown: never retry,
|
|
27
|
+
* reset refs, remove objects or remove Git locks. Authorization must throw on
|
|
28
|
+
* revocation; callbacks must be trusted and must not modify filesystem state.
|
|
29
|
+
* Only Git's normal ref/reflog writes occur. No signing/network/maintenance.
|
|
30
|
+
* No crash/directory durability or hostile filesystem isolation guarantee.
|
|
31
|
+
*/
|
|
32
|
+
export async function compareAndSwapBranch(repo,{ref,expectedOid,newOid,objectFormat,signal,assertAuthorized,onStart}={}){
|
|
33
|
+
const root=repo?.root;
|
|
34
|
+
validRef(ref);
|
|
35
|
+
const oidPattern=objectFormat==='sha1'?/^[0-9a-f]{40}$/:objectFormat==='sha256'?/^[0-9a-f]{64}$/:null;
|
|
36
|
+
if(repo?.type!=='git'||typeof root!=='string'||!path.isAbsolute(root)||path.resolve(root)!==root||
|
|
37
|
+
!oidPattern||![expectedOid,newOid].every(x=>typeof x==='string'&&oidPattern.test(x)&&!/^0+$/.test(x))||expectedOid===newOid||
|
|
38
|
+
typeof assertAuthorized!=='function'||typeof onStart!=='function')throw fail('invalid','Canonical embedded Git root, distinct full OIDs and callbacks required.');
|
|
39
|
+
let started=false,hooks,owned;
|
|
40
|
+
const directory=path.join(root,'.git'),identities=new Map();
|
|
41
|
+
const check=()=>{signal?.throwIfAborted();currentOperationBudget()?.throwIfExpired();};
|
|
42
|
+
const authorize=async()=>{check();await assertAuthorized();check();};
|
|
43
|
+
async function dir(p){
|
|
44
|
+
check();const s=await fs.lstat(p,{bigint:true});
|
|
45
|
+
if(!s.isDirectory()||s.isSymbolicLink()||await fs.realpath(p)!==p||(identities.has(p)&&!same(identities.get(p),s)))throw fail('unsafe','Noncanonical or replaced directory.');
|
|
46
|
+
identities.set(p,s);return s;
|
|
47
|
+
}
|
|
48
|
+
async function read(p,max=4096){
|
|
49
|
+
check();const before=await fs.lstat(p,{bigint:true});
|
|
50
|
+
if(!plain(before)||before.size>BigInt(max))throw fail('unsafe','Expected bounded single-link metadata.');
|
|
51
|
+
const h=await fs.open(p,constants.O_RDONLY|(constants.O_NOFOLLOW||0));
|
|
52
|
+
try{
|
|
53
|
+
const opened=await h.stat({bigint:true});
|
|
54
|
+
if(!plain(opened)||!same(before,opened))throw fail('unsafe','Metadata replaced.');
|
|
55
|
+
const b=Buffer.alloc(max+1);let n=0;
|
|
56
|
+
while(n<b.length){check();const r=await h.read(b,n,b.length-n,n);if(!r.bytesRead)break;n+=r.bytesRead;}
|
|
57
|
+
const after=await h.stat({bigint:true}),now=await fs.lstat(p,{bigint:true});
|
|
58
|
+
if(n>max||!plain(now)||!same(opened,now)||opened.size!==after.size||opened.mtimeNs!==after.mtimeNs||opened.ctimeNs!==after.ctimeNs||after.size!==now.size||after.mtimeNs!==now.mtimeNs||after.ctimeNs!==now.ctimeNs||BigInt(n)!==after.size)throw fail('unsafe','Metadata changed.');
|
|
59
|
+
return decode(b.subarray(0,n));
|
|
60
|
+
}finally{await h.close();}
|
|
61
|
+
}
|
|
62
|
+
async function metadata(){
|
|
63
|
+
await dir(root);let count=0;
|
|
64
|
+
const forbidden=new Set(['commondir','gitdir','worktrees','reftable','packed-refs','shallow','config.worktree','objects/info/alternates','objects/info/http-alternates','MERGE_HEAD','CHERRY_PICK_HEAD','REVERT_HEAD','rebase-merge','rebase-apply','sequencer'].map(s=>s.toLowerCase()));
|
|
65
|
+
async function visit(p,rel){
|
|
66
|
+
check();if(++count>20000)throw fail('unsupported','Metadata node bound exceeded.');
|
|
67
|
+
const lower=rel.toLowerCase();
|
|
68
|
+
if(forbidden.has(lower)||lower.endsWith('.lock')||lower.endsWith('.promisor')||lower.startsWith('sharedindex.'))throw fail('unsupported','Unsupported metadata or lock: '+rel);
|
|
69
|
+
const s=await fs.lstat(p,{bigint:true});
|
|
70
|
+
if(s.isSymbolicLink()||await fs.realpath(p)!==p)throw fail('unsafe','Linked metadata.');
|
|
71
|
+
if(s.isDirectory()){await dir(p);for(const name of await fs.readdir(p))await visit(path.join(p,name),rel?rel+'/'+name:name);}
|
|
72
|
+
else if(!plain(s))throw fail('unsafe','Shared or special metadata.');
|
|
73
|
+
}
|
|
74
|
+
await visit(directory,'');
|
|
75
|
+
}
|
|
76
|
+
const run=(args,max=16384)=>{check();return git(root,['-c','core.hooksPath='+hooks,'-c','user.name=Dsh','-c','user.email=dsh@localhost','-c','committer.name=Dsh','-c','committer.email=dsh@localhost',...args],max,{signal});};
|
|
77
|
+
async function config(){
|
|
78
|
+
// FIRST Git call: never expand include/includeIf (including global/system).
|
|
79
|
+
const rows=decode(await run(['config','--no-includes','--null','--list'],128*1024)).split('\0').filter(Boolean);
|
|
80
|
+
for(const row of rows){const i=row.indexOf('\n'),key=(i<0?row:row.slice(0,i)).toLowerCase(),value=i<0?'':row.slice(i+1).toLowerCase();
|
|
81
|
+
if(key.startsWith('include')||key.startsWith('extensions.')&&key!=='extensions.objectformat'||key==='core.worktree'||key==='core.repositoryformatversion'&&!['0','1'].includes(value)||key==='core.bare'&&value!=='false'||key==='core.sharedrepository'&&!['false','0'].includes(value)||/^remote\..*\.(promisor|partialclonefilter)$/.test(key))throw fail('unsupported','Unsupported configuration: '+key);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
async function state(oid){
|
|
85
|
+
await metadata();await config();
|
|
86
|
+
if(await read(path.join(directory,'HEAD'))!=='ref: '+ref+'\n')throw fail('stale','HEAD must target the exact branch.');
|
|
87
|
+
if(await read(path.join(directory,...ref.split('/')))!==oid+'\n')throw fail('stale','Branch no longer has the expected OID.');
|
|
88
|
+
const facts=decode(await run(['rev-parse','--absolute-git-dir','--git-common-dir','--show-toplevel','--is-bare-repository','--show-object-format','--verify','HEAD'])).trimEnd().split('\n');
|
|
89
|
+
if(facts.length!==6||path.resolve(root,facts[0])!==directory||path.resolve(root,facts[1])!==directory||path.resolve(facts[2])!==root||facts[3]!=='false'||facts[4]!==objectFormat||facts[5]!==oid)throw fail('stale','Git repository facts changed.');
|
|
90
|
+
}
|
|
91
|
+
async function verifyHooks(){
|
|
92
|
+
const s=await fs.lstat(hooks,{bigint:true});
|
|
93
|
+
if(!s.isDirectory()||s.isSymbolicLink()||!same(owned,s)||await fs.realpath(hooks)!==hooks||(await fs.readdir(hooks)).length)throw fail('unsafe','Owned hooks directory changed or is not empty.');
|
|
94
|
+
}
|
|
95
|
+
try{
|
|
96
|
+
return await withOperationBudget({signal},async()=>{
|
|
97
|
+
await authorize();await metadata();
|
|
98
|
+
const temp=await fs.realpath(os.tmpdir());
|
|
99
|
+
if(temp===root||temp.startsWith(root+path.sep))throw fail('unsafe','Hooks directory must be outside repository.');
|
|
100
|
+
hooks=await fs.mkdtemp(path.join(temp,'dsh-ref-hooks-'+process.pid+'-'));owned=await fs.lstat(hooks,{bigint:true});await verifyHooks();
|
|
101
|
+
await state(expectedOid);
|
|
102
|
+
if(decode(await run(['cat-file','-t',newOid],1024))!=='commit\n')throw fail('invalid','newOid must name a real commit object.');
|
|
103
|
+
if(decode(await run(['cat-file','-t',expectedOid],1024))!=='commit\n')throw fail('invalid','Expected born branch must name a commit.');
|
|
104
|
+
await authorize();await state(expectedOid);await verifyHooks();check();
|
|
105
|
+
started=true;const result=onStart();
|
|
106
|
+
if(result&&typeof result.then==='function'){Promise.resolve(result).catch(()=>{});throw fail('invalid','onStart must be synchronous.');}
|
|
107
|
+
// No asynchronous work between the notification and mutation subprocess.
|
|
108
|
+
await run(['update-ref','--no-deref','-m','dsh: branch compare-and-swap',ref,newOid,expectedOid],4096);
|
|
109
|
+
await authorize();await state(newOid);await authorize();check();
|
|
110
|
+
return {ref,oldOid:expectedOid,newOid};
|
|
111
|
+
});
|
|
112
|
+
}catch(error){
|
|
113
|
+
if(started)throw Object.assign(fail('outcome-unknown','Branch update outcome is unknown; inspect before any further action.',error),{outcomeUnknown:true});
|
|
114
|
+
throw error;
|
|
115
|
+
}finally{
|
|
116
|
+
// Never recursively remove, unlink foreign entries, or delete a replaced path.
|
|
117
|
+
if(hooks&&owned)try{const s=await fs.lstat(hooks,{bigint:true});if(s.isDirectory()&&!s.isSymbolicLink()&&same(owned,s)&&await fs.realpath(hooks)===hooks&&(await fs.readdir(hooks)).length===0)await fs.rmdir(hooks);}catch{}
|
|
118
|
+
}
|
|
119
|
+
}
|