@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,214 @@
|
|
|
1
|
+
// Internal confirmation capability. prepare remains read-only; apply requires a caller writer mutex.
|
|
2
|
+
// Trusted concurrency excludes raw-ref-type replacement after the last observation;
|
|
3
|
+
// Git old-OID CAS is NOT raw-type CAS (docs/BRANCH-DELETE-RAW-REF-RACE.md). No RPC/UI.
|
|
4
|
+
// Embedded born symbolic HEAD, direct loose target, no packed refs/shared metadata.
|
|
5
|
+
// Observation barriers detect changes, not hostile swaps or mutation-and-restoration.
|
|
6
|
+
import * as fs from 'node:fs/promises';
|
|
7
|
+
import {constants} from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import {readLatestCommit} from './latest-commit.mjs';
|
|
10
|
+
import {deleteLocalBranch} from './git-branch-delete.mjs';
|
|
11
|
+
import {git} from './local-command.mjs';
|
|
12
|
+
import {parseVerifiedCommit} from './src/verified-commit.mjs';
|
|
13
|
+
import {createVerifiedBranchDeletePlan} from './src/verified-branch-delete-plan.mjs';
|
|
14
|
+
import {withOperationBudget,currentOperationBudget} from './src/operation-budget.mjs';
|
|
15
|
+
const capabilities=new WeakMap();
|
|
16
|
+
const BODY=2*1024*1024,TOTAL=16*1024*1024,NODES=10000;
|
|
17
|
+
const fail=message=>Object.assign(new Error(message),{code:'vcs/branch-delete-preview'});
|
|
18
|
+
const check=()=>currentOperationBudget().throwIfExpired();
|
|
19
|
+
const equal=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
|
|
20
|
+
const identity=s=>[s.dev,s.ino,s.birthtimeNs].map(String);
|
|
21
|
+
const version=s=>[...identity(s),s.size,s.mtimeNs,s.ctimeNs,s.mode].map(String);
|
|
22
|
+
const plain=s=>s.isFile()&&!s.isSymbolicLink()&&s.nlink===1n;
|
|
23
|
+
function record(value,keys,label){
|
|
24
|
+
if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw fail('Invalid '+label+' record');
|
|
25
|
+
const out=Object.create(null);for(const key of Reflect.ownKeys(value)){
|
|
26
|
+
if(!keys.includes(key))throw fail('Unsupported '+label+' field');
|
|
27
|
+
const d=Object.getOwnPropertyDescriptor(value,key);
|
|
28
|
+
if(!d||!Object.hasOwn(d,'value'))throw fail(label+' requires own data properties');
|
|
29
|
+
out[key]=d.value;
|
|
30
|
+
}return out;
|
|
31
|
+
}
|
|
32
|
+
function validateName(name){
|
|
33
|
+
if(typeof name!=='string'||!name||Buffer.from(name,'utf8').toString('utf8')!==name||Buffer.byteLength(name,'utf8')>1000||
|
|
34
|
+
name==='@'||name.toUpperCase()==='HEAD'||name.startsWith('-')||name.startsWith('refs/')||/[\x00-\x20\x7f~^:?*\[\\<>"|\p{Cc}\p{Cf}]/u.test(name)||name.includes('..')||name.includes('@{')||
|
|
35
|
+
name.split('/').some(p=>!p||Buffer.byteLength(p,'utf8')>255||p.startsWith('.')||/[. ]$/.test(p)||p.toLowerCase().endsWith('.lock')||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p)))
|
|
36
|
+
throw fail('Safe portable short branch name required');
|
|
37
|
+
}
|
|
38
|
+
async function stat(file){check();try{return await fs.lstat(file,{bigint:true});}catch(error){if(error.code==='ENOENT')return null;throw error;}}
|
|
39
|
+
async function directory(file){
|
|
40
|
+
const s=await stat(file);if(!s||!s.isDirectory()||s.isSymbolicLink()||await fs.realpath(file)!==file)throw fail('Canonical metadata directory required');return s;
|
|
41
|
+
}
|
|
42
|
+
async function raw(file,max){
|
|
43
|
+
check();const before=await stat(file);
|
|
44
|
+
if(!before||!plain(before)||before.size>BigInt(max))throw fail('Bounded single-link metadata file required');
|
|
45
|
+
const handle=await fs.open(file,constants.O_RDONLY|(constants.O_NOFOLLOW||0));
|
|
46
|
+
try{
|
|
47
|
+
const opened=await handle.stat({bigint:true});if(!plain(opened)||!equal(version(before),version(opened)))throw fail('Stale metadata opening');
|
|
48
|
+
const bytes=Buffer.alloc(max+1);let n=0;
|
|
49
|
+
while(n<bytes.length){check();const r=await handle.read(bytes,n,bytes.length-n,n);if(!r.bytesRead)break;n+=r.bytesRead;}
|
|
50
|
+
const after=await handle.stat({bigint:true}),now=await stat(file);
|
|
51
|
+
if(n>max||!now||!plain(now)||!equal(version(opened),version(after))||!equal(version(after),version(now))||BigInt(n)!==after.size)throw fail('Stale metadata reading');
|
|
52
|
+
return [version(after),bytes.subarray(0,n).toString('hex')];
|
|
53
|
+
}finally{await handle.close();}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const forbidden=new Set(['packed-refs','reftable','commondir','gitdir','shallow','config.worktree','MERGE_HEAD','MERGE_MSG','CHERRY_PICK_HEAD','REVERT_HEAD','REBASE_HEAD','BISECT_LOG','BISECT_START','rebase-merge','rebase-apply','sequencer','worktrees','info/sparse-checkout','info/attributes','objects/info/alternates','objects/info/http-alternates'].map(s=>s.toLowerCase()));
|
|
57
|
+
async function metadata(directory){
|
|
58
|
+
const rows=[];let nodes=0;
|
|
59
|
+
async function visit(file,relative){
|
|
60
|
+
check();if(++nodes>20000)throw fail('Metadata inspection limit exceeded');
|
|
61
|
+
const key=relative.toLowerCase();
|
|
62
|
+
if(forbidden.has(key)||key.endsWith('.lock')||key.endsWith('.promisor')||key.startsWith('sharedindex.')||key.startsWith('hooks/')&&!key.endsWith('.sample'))throw fail('Unsupported repository metadata: '+relative);
|
|
63
|
+
const s=await fs.lstat(file,{bigint:true});
|
|
64
|
+
if(s.isSymbolicLink()||(!s.isDirectory()&&!plain(s))||await fs.realpath(file)!==file)throw fail('Linked or special repository metadata');
|
|
65
|
+
rows.push([relative,version(s)]);
|
|
66
|
+
if(s.isDirectory()){const names=await fs.readdir(file);check();if(names.length>20000-nodes)throw fail('Metadata inspection limit exceeded');for(const name of names.sort())await visit(path.join(file,name),relative?relative+'/'+name:name);}
|
|
67
|
+
}
|
|
68
|
+
await visit(directory,'');return rows;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Pin effective system/global/local configuration without expanding includes.
|
|
72
|
+
const effectiveConfig=root=>git(root,['--git-dir='+path.join(root,'.git'),'--work-tree='+root,'config','--no-includes','--null','--list'],256*1024);
|
|
73
|
+
async function capture(root,name){
|
|
74
|
+
check();const rootStat=await directory(root),gitDir=path.join(root,'.git');await directory(gitDir);
|
|
75
|
+
const rows=await metadata(gitDir);
|
|
76
|
+
const entries=await fs.readdir(gitDir);
|
|
77
|
+
for(const expected of ['HEAD','config','refs','logs','objects','hooks'])if(entries.some(n=>n.toLowerCase()===expected.toLowerCase()&&n!==expected))throw fail('Noncanonical metadata spelling');
|
|
78
|
+
let parent=gitDir;const parts=['refs','heads',...name.split('/')];
|
|
79
|
+
for(let i=0;i<parts.length;i++){
|
|
80
|
+
check();const part=parts[i],matches=(await fs.readdir(parent)).filter(n=>n.toLowerCase()===part.toLowerCase());
|
|
81
|
+
if(matches.length!==1||matches[0]!==part)throw fail('Missing target or portable namespace collision');
|
|
82
|
+
const file=path.join(parent,part);
|
|
83
|
+
if(i<parts.length-1)await directory(file);
|
|
84
|
+
parent=file;
|
|
85
|
+
}
|
|
86
|
+
const head=await raw(path.join(gitDir,'HEAD'),4096),config=await raw(path.join(gitDir,'config'),256*1024),target=await raw(parent,65);
|
|
87
|
+
if(!equal(rows,await metadata(gitDir)))throw fail('Stale repository metadata during capture');
|
|
88
|
+
check();return {root:identity(rootStat),rows,head,config,target};
|
|
89
|
+
}
|
|
90
|
+
/** Strict own-data repo {type:'git',root} and options {name,signal?} only.
|
|
91
|
+
* 15s shared budget; <=20k metadata entries/scan, <=10k commits, <=2MiB/body,
|
|
92
|
+
* <=16MiB graph. All parents of BOTH tips must exist and pass strict verification.
|
|
93
|
+
* No worktree or index body opens. No network/lazy fetch. No force operation.
|
|
94
|
+
*/
|
|
95
|
+
export async function prepareBranchDelete(repo,options={}){
|
|
96
|
+
const r=record(repo,['type','root'],'repository'),o=record(options,['name','signal'],'options');
|
|
97
|
+
if(r.type!=='git'||typeof r.root!=='string'||!path.isAbsolute(r.root)||path.resolve(r.root)!==r.root)throw fail('Canonical Git root required');
|
|
98
|
+
validateName(o.name);
|
|
99
|
+
if(o.signal!==undefined){try{Reflect.apply(Object.getOwnPropertyDescriptor(AbortSignal.prototype,'aborted').get,o.signal,[]);}catch{throw fail('Native AbortSignal required');}}
|
|
100
|
+
const name=o.name,ref='refs/heads/'+name;
|
|
101
|
+
return withOperationBudget({signal:o.signal,timeoutMs:15000},async()=>{
|
|
102
|
+
const before=await capture(r.root,name),configBaseline=await effectiveConfig(r.root);
|
|
103
|
+
const first=await readLatestCommit({type:r.type,root:r.root},{signal:o.signal});
|
|
104
|
+
validateName(first.ref.slice(11));
|
|
105
|
+
if(first.ref.toLowerCase()===ref.toLowerCase())throw fail('Cannot delete current branch or case-insensitive alias');
|
|
106
|
+
const text=Buffer.from(before.target[1],'hex').toString('latin1'),width=first.objectFormat==='sha1'?40:64;
|
|
107
|
+
if(!new RegExp('^[0-9a-f]{'+width+'}\\n?$').test(text)||/^0+\n?$/.test(text))throw fail('Target requires direct raw object id');
|
|
108
|
+
const oid=text.replace(/\n$/,''),current={ref:first.ref,oid:first.head},target={ref,oid};
|
|
109
|
+
const currentRaw=await raw(path.join(r.root,'.git',...current.ref.split('/')),65);
|
|
110
|
+
if(![current.oid,current.oid+'\n'].some(value=>Buffer.from(value).toString('hex')===currentRaw[1]))throw fail('Stale direct current ref');
|
|
111
|
+
if(!equal(before,await capture(r.root,name)))throw fail('Stale repository before traversal');
|
|
112
|
+
const queue=[...new Set([current.oid,target.oid])],seen=new Set(queue),objects=[];let total=0;
|
|
113
|
+
for(let i=0;i<queue.length;i++){
|
|
114
|
+
check();const oid=queue[i],body=await git(r.root,['cat-file','commit',oid],Math.min(BODY,TOTAL-total||1));
|
|
115
|
+
check();total+=body.length;if(total>TOTAL)throw fail('Aggregate object body byte limit exceeded');
|
|
116
|
+
const parsed=parseVerifiedCommit(body,{oid,objectFormat:first.objectFormat,signal:currentOperationBudget().signal});
|
|
117
|
+
objects.push({oid,body});
|
|
118
|
+
for(const parent of parsed.parents)if(!seen.has(parent)){
|
|
119
|
+
if(seen.size>=NODES)throw fail('Commit node limit exceeded');seen.add(parent);queue.push(parent);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if(!equal(before,await capture(r.root,name)))throw fail('Stale repository after traversal');
|
|
123
|
+
const last=await readLatestCommit({type:r.type,root:r.root},{signal:o.signal});
|
|
124
|
+
if(!equal(first,last)||!(await effectiveConfig(r.root)).equals(configBaseline)||!equal(currentRaw,await raw(path.join(r.root,'.git',...current.ref.split('/')),65))||!equal(before,await capture(r.root,name)))throw fail('Stale current facts or repository');
|
|
125
|
+
check();const plan=createVerifiedBranchDeletePlan({objectFormat:first.objectFormat,current,target,objects,signal:currentOperationBudget().signal});
|
|
126
|
+
check();const summary=Object.freeze({action:'branch-delete',name,ref,objectFormat:plan.objectFormat,current:plan.current,target:plan.target,merged:true,proof:plan.proof,planId:plan.id});
|
|
127
|
+
capabilities.set(summary,{root:r.root,name,ref,before,configBaseline,currentRaw,current,target,objectFormat:first.objectFormat,planId:plan.id});
|
|
128
|
+
return summary;
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Internal only. Caller MUST hold the repository writer mutex and supply trusted
|
|
133
|
+
* callbacks. Exact summary identity is consumed synchronously, including invalid
|
|
134
|
+
* attempts. No clone, replay, overrides, rollback, checkout or graph recomputation.
|
|
135
|
+
* Full metadata versions pin the already hash-authenticated merged graph; this is
|
|
136
|
+
* observation safety, not hostile swaps/ABA isolation or atomic raw-ref-type CAS.
|
|
137
|
+
*/
|
|
138
|
+
export async function applyBranchDelete(repo,options={}){
|
|
139
|
+
// Burn before record validation or any await; do not invoke a snapshot accessor.
|
|
140
|
+
const descriptor=options&&(typeof options==='object'||typeof options==='function')?Object.getOwnPropertyDescriptor(options,'snapshot'):undefined;
|
|
141
|
+
const snapshot=descriptor&&Object.hasOwn(descriptor,'value')?descriptor.value:undefined;
|
|
142
|
+
const authority=capabilities.get(snapshot);
|
|
143
|
+
if(authority)capabilities.delete(snapshot);
|
|
144
|
+
if(!authority)throw fail('Exact unused branch-delete snapshot required');
|
|
145
|
+
const r=record(repo,['type','root'],'repository');
|
|
146
|
+
const o=record(options,['snapshot','signal','assertAuthorized','onStart'],'options');
|
|
147
|
+
if(r.type!=='git'||r.root!==authority.root||typeof o.assertAuthorized!=='function'||typeof o.onStart!=='function')throw fail('Bound repository and authorization/start callbacks required');
|
|
148
|
+
if(o.signal!==undefined){try{Reflect.apply(Object.getOwnPropertyDescriptor(AbortSignal.prototype,'aborted').get,o.signal,[]);}catch{throw fail('Native AbortSignal required');}}
|
|
149
|
+
const {root,name,ref,before,configBaseline,currentRaw,current,target,objectFormat}=authority;
|
|
150
|
+
const bound={type:'git',root};let started=false;
|
|
151
|
+
async function facts(){
|
|
152
|
+
if(!(await effectiveConfig(root)).equals(configBaseline))throw fail('Effective Git configuration changed');
|
|
153
|
+
// Format/policy were established by the full reader; retain EXACT prepare bytes.
|
|
154
|
+
if(!equal(currentRaw,await raw(path.join(root,'.git',...current.ref.split('/')),65)))throw fail('Original direct current ref changed');
|
|
155
|
+
}
|
|
156
|
+
async function fresh(){
|
|
157
|
+
check();if(!equal(before,await capture(root,name)))throw fail('Stale branch-delete snapshot');
|
|
158
|
+
await facts();
|
|
159
|
+
if(!equal(before,await capture(root,name)))throw fail('Stale authenticated current facts');
|
|
160
|
+
check();
|
|
161
|
+
}
|
|
162
|
+
const removed=new Set([ref,'logs/'+ref]),ancestors=new Set(['']);
|
|
163
|
+
for(const leaf of removed){let p=leaf;while(p.includes('/')){p=p.slice(0,p.lastIndexOf('/'));ancestors.add(p);}}
|
|
164
|
+
const original=new Map(before.rows);
|
|
165
|
+
async function deleted(){
|
|
166
|
+
check();const gitDir=path.join(root,'.git');
|
|
167
|
+
if(!equal(identity(await directory(root)),before.root))throw fail('Repository identity changed');
|
|
168
|
+
await directory(gitDir);const rows=await metadata(gitDir),now=new Map(rows);
|
|
169
|
+
for(const leaf of removed)if(now.has(leaf)||await stat(path.join(gitDir,...leaf.split('/'))))throw fail('Deleted target or reflog reappeared');
|
|
170
|
+
for(const [key,v] of rows){
|
|
171
|
+
const old=original.get(key);if(!old)throw fail('Unrelated metadata added');
|
|
172
|
+
if(ancestors.has(key)){
|
|
173
|
+
// Existing ancestor directories retain identity/type/mode, not size/times.
|
|
174
|
+
if(!equal(v.slice(0,3),old.slice(0,3))||v[6]!==old[6])throw fail('Ancestor directory replaced');
|
|
175
|
+
}else if(!equal(v,old))throw fail('Unrelated metadata changed');
|
|
176
|
+
}
|
|
177
|
+
for(const [key,v] of before.rows)if(!now.has(key)&&!removed.has(key)){
|
|
178
|
+
if(!key||!ancestors.has(key)||(BigInt(v[6])&0o170000n)!==0o040000n)throw fail('Unrelated metadata disappeared');
|
|
179
|
+
// Only ancestors made empty by the exact two removals may be pruned.
|
|
180
|
+
for(const [child] of before.rows)if(child.startsWith(key+'/')&&!removed.has(child)&&!ancestors.has(child))throw fail('Nonempty ancestor disappeared');
|
|
181
|
+
}
|
|
182
|
+
if(!equal(await raw(path.join(gitDir,'HEAD'),4096),before.head)||!equal(await raw(path.join(gitDir,'config'),256*1024),before.config))throw fail('Original HEAD/config changed');
|
|
183
|
+
await facts();
|
|
184
|
+
if(!equal(rows,await metadata(gitDir)))throw fail('Stale post-delete metadata');
|
|
185
|
+
check();
|
|
186
|
+
}
|
|
187
|
+
// Trusted authorization may remain pending. Race only its wait, never continue
|
|
188
|
+
// mutation after cancellation; Promise.race also observes a late rejection.
|
|
189
|
+
const authorization=async()=>{
|
|
190
|
+
check();const signal=currentOperationBudget().signal;let abort;
|
|
191
|
+
const cancelled=new Promise((_,reject)=>{abort=()=>reject(signal.reason);signal.addEventListener('abort',abort,{once:true});if(signal.aborted)abort();});
|
|
192
|
+
try{await Promise.race([Promise.resolve().then(()=>{check();return o.assertAuthorized();}),cancelled]);check();}
|
|
193
|
+
finally{signal.removeEventListener('abort',abort);}
|
|
194
|
+
};
|
|
195
|
+
const authorize=async()=>{
|
|
196
|
+
if(started){await deleted();await authorization();check();await deleted();}
|
|
197
|
+
else{await fresh();await authorization();check();await fresh();}
|
|
198
|
+
};
|
|
199
|
+
try{
|
|
200
|
+
return await withOperationBudget({signal:o.signal,timeoutMs:15000},async()=>{
|
|
201
|
+
// One full policy/hash authentication; every later barrier retains prepare baselines.
|
|
202
|
+
await fresh();
|
|
203
|
+
const latest=await readLatestCommit(bound,{signal:o.signal});
|
|
204
|
+
if(latest.ref!==current.ref||latest.head!==current.oid||latest.objectFormat!==objectFormat)throw fail('Stale authenticated current facts');
|
|
205
|
+
await fresh();
|
|
206
|
+
await deleteLocalBranch(bound,{ref,expectedOid:target.oid,objectFormat,signal:o.signal,assertAuthorized:authorize,onStart:()=>{started=true;return o.onStart();}});
|
|
207
|
+
await deleted();await authorize();await deleted();check();
|
|
208
|
+
return Object.freeze({name,ref,deletedOid:target.oid,currentRef:current.ref,currentOid:current.oid});
|
|
209
|
+
});
|
|
210
|
+
}catch(cause){
|
|
211
|
+
if(started)throw Object.assign(new Error('Branch deletion outcome is unknown; inspect before any further action.',{cause}),{code:'vcs/branch-delete-outcome-unknown',outcomeUnknown:true});
|
|
212
|
+
throw cause;
|
|
213
|
+
}
|
|
214
|
+
}
|
package/branch-switch-host.mjs
CHANGED
|
@@ -1,35 +1,15 @@
|
|
|
1
|
-
//
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
const access=new Map();
|
|
5
|
-
const error=(code,message)=>Object.assign(new Error(message),{code});
|
|
6
|
-
const keyOf=root=>{const key=path.resolve(root);return process.platform==='win32'?key.toLowerCase():key;};
|
|
7
|
-
export function acquireRepositoryAccess(root,write=false){
|
|
8
|
-
const key=keyOf(root),state=access.get(key)||{readers:0,writer:false};
|
|
9
|
-
if(state.writer||(write&&state.readers))throw error('vcs/busy','This repository has an active operation. Wait for it to finish and prepare again.');
|
|
10
|
-
if(write)state.writer=true;else state.readers++;access.set(key,state);let released=false;
|
|
11
|
-
return()=>{if(released)return;released=true;if(write)state.writer=false;else state.readers--;if(!state.writer&&!state.readers)access.delete(key);};
|
|
12
|
-
}
|
|
1
|
+
// Branch-specific adapter: the browser cannot choose the confirmed operation.
|
|
2
|
+
import {createConfirmedOperationCoordinator} from './confirmed-operation.mjs';
|
|
3
|
+
export {acquireRepositoryAccess} from './confirmed-operation.mjs';
|
|
13
4
|
export function createBranchSwitchCoordinator({api,now=Date.now,ttlMs=60000,maxTokens=32}){
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
return {token,expiresAt,current:snapshot.current,target:snapshot.target};
|
|
25
|
-
},
|
|
26
|
-
async confirm(address,{entry,repository,cwd,signal,assertAuthorized}){
|
|
27
|
-
purge();const row=tokens.get(address.token);tokens.delete(address.token);
|
|
28
|
-
if(!row||row.entry!==entry||row.repository!==repository||row.cwd!==cwd||row.sessionId!==address.sessionId||row.repositoryId!==address.repositoryId)throw error('vcs/branch-confirmation-invalid','Confirmation is expired, used, or belongs to a different Session/repository. Prepare again.');
|
|
29
|
-
const release=acquireRepositoryAccess(repository.root,true);let started=false;
|
|
30
|
-
try{await assertAuthorized();signal?.throwIfAborted();const result=await api.switchLocalBranch({...repository},{snapshot:row.snapshot,signal,assertAuthorized,onStart(){started=true;}});await assertAuthorized();signal?.throwIfAborted();return result;}
|
|
31
|
-
catch(failure){if(started)throw error('vcs/branch-outcome-unknown','Branch switching started but its final result could not be confirmed. Refresh the repository and inspect the current branch before preparing another switch.');throw failure;}
|
|
32
|
-
finally{release();}
|
|
33
|
-
},
|
|
34
|
-
};
|
|
5
|
+
return createConfirmedOperationCoordinator({
|
|
6
|
+
operationKind:'branch-switch',now,ttlMs,maxTokens,
|
|
7
|
+
prepare:(repository,{address,signal})=>api.prepareLocalBranchSwitch(repository,{branch:address.branch,signal}),
|
|
8
|
+
execute:(repository,request)=>api.switchLocalBranch(repository,request),
|
|
9
|
+
project:snapshot=>({current:snapshot.current,target:snapshot.target}),
|
|
10
|
+
invalidCode:'vcs/branch-confirmation-invalid',
|
|
11
|
+
invalidMessage:'Confirmation is expired, used, or belongs to a different Session/repository. Prepare again.',
|
|
12
|
+
unknownCode:'vcs/branch-outcome-unknown',
|
|
13
|
+
unknownMessage:'Branch switching started but its final result could not be confirmed. Refresh the repository and inspect the current branch before preparing another switch.',
|
|
14
|
+
});
|
|
35
15
|
}
|
package/commit-host.mjs
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import {createConfirmedOperationCoordinator} from './confirmed-operation.mjs';
|
|
2
|
+
import {encodeGitCommit} from './src/git-commit-object.mjs';
|
|
3
|
+
|
|
4
|
+
const invalid=message=>Object.assign(new Error(message),{code:'vcs/commit-confirmation-invalid'});
|
|
5
|
+
function record(value,keys,label){
|
|
6
|
+
if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw invalid('Invalid '+label+' record.');
|
|
7
|
+
const result={};
|
|
8
|
+
for(const key of Reflect.ownKeys(value)){
|
|
9
|
+
if(!keys.includes(key))throw invalid('Unsupported '+label+' field.');
|
|
10
|
+
const descriptor=Object.getOwnPropertyDescriptor(value,key);
|
|
11
|
+
if(!descriptor||!Object.hasOwn(descriptor,'value'))throw invalid(label+' requires own data properties.');
|
|
12
|
+
result[key]=descriptor.value;
|
|
13
|
+
}
|
|
14
|
+
return result;
|
|
15
|
+
}
|
|
16
|
+
const identityKeys=['name','email','timestamp','timezone'];
|
|
17
|
+
const projectIdentity=value=>Object.fromEntries(identityKeys.map(key=>[key,value[key]]));
|
|
18
|
+
function capture(address){
|
|
19
|
+
const saved=record(address,['sessionId','repositoryId','author','committer','message'],'commit address');
|
|
20
|
+
saved.author=record(saved.author,identityKeys,'author');
|
|
21
|
+
saved.committer=record(saved.committer,identityKeys,'committer');
|
|
22
|
+
if(typeof saved.sessionId!=='string'||!saved.sessionId||typeof saved.repositoryId!=='string'||!saved.repositoryId)throw invalid('Session and repository identifiers are required.');
|
|
23
|
+
if(typeof saved.message!=='string'||Buffer.byteLength(saved.message)>65536||!saved.message.trim()||/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(saved.message.replace(/[\n\t]/g,'')))throw invalid('Bounded plaintext commit message required.');
|
|
24
|
+
// Validate the owned scalar metadata with the same pure bounds as the adapter.
|
|
25
|
+
try{encodeGitCommit({tree:'1'.repeat(40),author:saved.author,committer:saved.committer,message:saved.message});}
|
|
26
|
+
catch{throw invalid('Invalid commit identity or message.');}
|
|
27
|
+
Object.freeze(saved.author);Object.freeze(saved.committer);return Object.freeze(saved);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Internal host adapter: authenticated grants and authorization callbacks remain
|
|
31
|
+
// the caller's responsibility. No raw browser repository paths or execution plans.
|
|
32
|
+
export function createCommitCoordinator({api,now=Date.now,ttlMs=60000,maxTokens=32}){
|
|
33
|
+
const coordinator=createConfirmedOperationCoordinator({
|
|
34
|
+
operationKind:'commit',now,ttlMs,maxTokens,
|
|
35
|
+
prepare:(repository,{address,signal})=>api.prepareCommitPreview({type:repository.type,root:repository.root},{author:address.author,committer:address.committer,message:address.message,signal}),
|
|
36
|
+
execute:(repository,request)=>api.applyCommitPreview({type:repository.type,root:repository.root},request),
|
|
37
|
+
project:snapshot=>({action:'commit',head:snapshot.head,ref:snapshot.ref,objectFormat:snapshot.objectFormat,indexDigest:snapshot.indexDigest,tree:snapshot.tree,commit:{oid:snapshot.commit.oid},author:projectIdentity(snapshot.author),committer:projectIdentity(snapshot.committer),message:snapshot.message}),
|
|
38
|
+
invalidCode:'vcs/commit-confirmation-invalid',
|
|
39
|
+
unknownCode:'vcs/commit-outcome-unknown',
|
|
40
|
+
unknownMessage:'Commit started but its final result could not be confirmed. Append-only object writes may remain. Refresh the repository and inspect HEAD and the index before preparing another commit. Never retry automatically or roll back appended objects.',
|
|
41
|
+
});
|
|
42
|
+
return {
|
|
43
|
+
// Capture before invoking even an asynchronous adapter or authorization callback.
|
|
44
|
+
async prepare(address,binding){return coordinator.prepare(capture(address),binding);},
|
|
45
|
+
confirm:(address,binding)=>coordinator.confirm(address,binding),
|
|
46
|
+
invalidate:entry=>coordinator.invalidate(entry),
|
|
47
|
+
clear:()=>coordinator.clear(),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {TextDecoder} from 'node:util';
|
|
3
|
+
import {storeCapturedObject} from './git-object-store.mjs';
|
|
4
|
+
import {buildIndexTree} from './src/index-tree.mjs';
|
|
5
|
+
import {encodeGitTree} from './src/git-commit-object.mjs';
|
|
6
|
+
import {parseVerifiedCommit} from './src/verified-commit.mjs';
|
|
7
|
+
import {withOperationBudget, currentOperationBudget} from './src/operation-budget.mjs';
|
|
8
|
+
|
|
9
|
+
const MAX_TREES=100001, MAX_TREE_BYTES=8*1024*1024, MAX_COMMIT_BYTES=128*1024;
|
|
10
|
+
const invalid=message=>Object.assign(new Error(message),{code:'vcs/commit-objects-invalid'});
|
|
11
|
+
const utf8=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true});
|
|
12
|
+
function record(value,allowed,required=allowed){
|
|
13
|
+
if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw invalid('Expected own-data record.');
|
|
14
|
+
const descriptors=Object.getOwnPropertyDescriptors(value), out=Object.create(null);
|
|
15
|
+
for(const key of Reflect.ownKeys(descriptors)){
|
|
16
|
+
const d=descriptors[key];
|
|
17
|
+
if(typeof key!=='string'||!allowed.includes(key)||!Object.hasOwn(d,'value'))throw invalid('Unexpected field or accessor.');
|
|
18
|
+
out[key]=d.value;
|
|
19
|
+
}
|
|
20
|
+
for(const key of required)if(!Object.hasOwn(out,key))throw invalid('Missing '+key+'.');
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
function capture(input){
|
|
24
|
+
const options=record(input,['gitDirectory','objectFormat','trees','commit','signal','assertAuthorized','onStart'],['gitDirectory','objectFormat','trees','commit','assertAuthorized','onStart']);
|
|
25
|
+
const list=options.trees;
|
|
26
|
+
if(!Array.isArray(list)||Object.getPrototypeOf(list)!==Array.prototype)throw invalid('trees must be an array.');
|
|
27
|
+
const length=Object.getOwnPropertyDescriptor(list,'length').value;
|
|
28
|
+
if(length<1||length>MAX_TREES)throw invalid('Tree count bound exceeded.');
|
|
29
|
+
const keys=Reflect.ownKeys(list);
|
|
30
|
+
if(keys.length!==length+1)throw invalid('Sparse or extended tree array.');
|
|
31
|
+
const trees=[];let total=0;
|
|
32
|
+
for(let i=0;i<length;i++){
|
|
33
|
+
const descriptor=Object.getOwnPropertyDescriptor(list,String(i));
|
|
34
|
+
if(!descriptor||!Object.hasOwn(descriptor,'value'))throw invalid('Tree array accessors are forbidden.');
|
|
35
|
+
const tree=record(descriptor.value,['path','oid','body']);
|
|
36
|
+
if(!Buffer.isBuffer(tree.body)||tree.body.length>MAX_TREE_BYTES||(total+=tree.body.length)>MAX_TREE_BYTES)throw invalid('Aggregate tree body bound exceeded.');
|
|
37
|
+
trees.push({...tree,body:Buffer.from(tree.body)});
|
|
38
|
+
}
|
|
39
|
+
const commit=record(options.commit,['oid','body']);
|
|
40
|
+
if(!Buffer.isBuffer(commit.body)||commit.body.length>MAX_COMMIT_BYTES)throw invalid('Commit body bound exceeded.');
|
|
41
|
+
return {...options,trees,commit:{...commit,body:Buffer.from(commit.body)}};
|
|
42
|
+
}
|
|
43
|
+
function validate({objectFormat,trees,commit}){
|
|
44
|
+
if(objectFormat!=='sha1'&&objectFormat!=='sha256')throw invalid('Unsupported object format.');
|
|
45
|
+
const width=objectFormat==='sha1'?40:64, byPath=new Map(),used=new Set(),leaves=[];
|
|
46
|
+
const verify=(type,{oid,body})=>{
|
|
47
|
+
if(typeof oid!=='string'||oid.length!==width||/[^0-9a-f]/.test(oid)||/^0+$/.test(oid))throw invalid('Invalid full object id.');
|
|
48
|
+
if(createHash(objectFormat).update(type+' '+body.length+'\0').update(body).digest('hex')!==oid)throw invalid('Object id mismatch.');
|
|
49
|
+
};
|
|
50
|
+
for(let i=0;i<trees.length;i++){
|
|
51
|
+
const tree=trees[i];verify('tree',tree);
|
|
52
|
+
if(typeof tree.path!=='string'||tree.path.length>4096||byPath.has(tree.path)||(tree.path==='')!==(i===trees.length-1))throw invalid('Invalid tree path, root or order.');
|
|
53
|
+
const entries=[];let offset=0;
|
|
54
|
+
while(offset<tree.body.length){
|
|
55
|
+
if(entries.length===100000)throw invalid('Tree record bound exceeded.');
|
|
56
|
+
const space=tree.body.indexOf(32,offset),nul=tree.body.indexOf(0,offset);
|
|
57
|
+
if(space<offset||space-offset>6||nul<space+2||nul-space-1>4096||nul+1+width/2>tree.body.length)throw invalid('Malformed tree record.');
|
|
58
|
+
const mode=tree.body.toString('ascii',offset,space);
|
|
59
|
+
if(!['100644','100755','40000'].includes(mode))throw invalid('Noncanonical tree mode.');
|
|
60
|
+
const name=utf8.decode(tree.body.subarray(space+1,nul));
|
|
61
|
+
const oid=tree.body.subarray(nul+1,nul+1+width/2).toString('hex');
|
|
62
|
+
const childPath=tree.path?tree.path+'/'+name:name;
|
|
63
|
+
if(mode==='40000'){
|
|
64
|
+
const child=byPath.get(childPath);
|
|
65
|
+
if(!child||child.oid!==oid||used.has(childPath))throw invalid('Missing, reused or out-of-order child tree.');
|
|
66
|
+
used.add(childPath);
|
|
67
|
+
}else{
|
|
68
|
+
if(leaves.length===100000)throw invalid('Leaf count bound exceeded.');
|
|
69
|
+
leaves.push({path:childPath,mode,oid});
|
|
70
|
+
}
|
|
71
|
+
entries.push({name,mode,oid});offset=nul+1+width/2;
|
|
72
|
+
}
|
|
73
|
+
if(!encodeGitTree(entries,{objectFormat}).body.equals(tree.body))throw invalid('Noncanonical raw tree ordering or encoding.');
|
|
74
|
+
byPath.set(tree.path,tree);
|
|
75
|
+
}
|
|
76
|
+
if(used.size!==trees.length-1)throw invalid('Unused tree.');
|
|
77
|
+
const rebuilt=buildIndexTree(leaves,{objectFormat});
|
|
78
|
+
if(rebuilt.trees.length!==trees.length||rebuilt.trees.some((t,i)=>t.path!==trees[i].path||t.oid!==trees[i].oid||!t.body.equals(trees[i].body)))throw invalid('Tree graph differs from canonical index graph.');
|
|
79
|
+
verify('commit',commit);
|
|
80
|
+
if(parseVerifiedCommit(commit.body,{oid:commit.oid,objectFormat}).tree!==rebuilt.root)throw invalid('Commit tree differs from root.');
|
|
81
|
+
return rebuilt.root;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Append-only, child-first tree/commit publication; never touches refs or index.
|
|
85
|
+
* All own-data inputs and ALL bodies are captured before callbacks/awaits. A single
|
|
86
|
+
* 15s budget covers the operation (and inherits any shorter enclosing budget).
|
|
87
|
+
* onStart must be synchronous; it runs once immediately before the store's first
|
|
88
|
+
* mutation attempt, never when every object already exists (read-only success).
|
|
89
|
+
* After onStart any failure is outcome-unknown: objects may remain, with no rollback.
|
|
90
|
+
* Blob existence/type and parent existence are the CALLER's responsibility. Graph
|
|
91
|
+
* validation does not consult or authenticate external blob/parent objects.
|
|
92
|
+
*/
|
|
93
|
+
export async function publishCommitObjects(input){
|
|
94
|
+
const captured=capture(input);
|
|
95
|
+
const {gitDirectory,objectFormat,trees,commit,signal,assertAuthorized,onStart}=captured;
|
|
96
|
+
if(typeof assertAuthorized!=='function'||typeof onStart!=='function')throw invalid('Authorization and synchronous start callbacks required.');
|
|
97
|
+
let started=false;
|
|
98
|
+
try{
|
|
99
|
+
return await withOperationBudget({signal,timeoutMs:15000},async()=>{
|
|
100
|
+
const tree=validate(captured);
|
|
101
|
+
const check=()=>currentOperationBudget().throwIfExpired();
|
|
102
|
+
const authorize=async()=>{check();await assertAuthorized();check();};
|
|
103
|
+
const start=()=>{
|
|
104
|
+
if(started)return;
|
|
105
|
+
started=true;
|
|
106
|
+
const value=onStart();
|
|
107
|
+
if(value&&typeof value.then==='function'){Promise.resolve(value).catch(()=>{});throw invalid('onStart must be synchronous.');}
|
|
108
|
+
};
|
|
109
|
+
const created=[];
|
|
110
|
+
for(const [type,object] of [...trees.map(t=>['tree',t]),['commit',commit]]){
|
|
111
|
+
await authorize();
|
|
112
|
+
const stored=await storeCapturedObject({gitDirectory,objectFormat,type,bytes:object.body,signal:currentOperationBudget().signal,assertAuthorized:authorize,onStart:start});
|
|
113
|
+
await authorize();
|
|
114
|
+
if(stored.oid!==object.oid)throw invalid('Stored object id mismatch.');
|
|
115
|
+
if(stored.created)created.push({type,oid:stored.oid});
|
|
116
|
+
}
|
|
117
|
+
return {tree,commit:commit.oid,created};
|
|
118
|
+
});
|
|
119
|
+
}catch(cause){
|
|
120
|
+
if(!started)throw cause;
|
|
121
|
+
throw Object.assign(new Error('Append-only commit object publication started; objects may exist. Never roll back by deletion.',{cause}),{code:'vcs/commit-objects-outcome-unknown',appendOnly:true,outcomeUnknown:true});
|
|
122
|
+
}
|
|
123
|
+
}
|