@feng0531/dsh-vcs 0.7.3 → 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 +68 -5
- 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 +2 -0
- 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 +47 -2
- 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
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
|
+
}
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
// Internal preview capabilities and caller-serialized commit transaction.
|
|
2
|
+
import * as fs from 'node:fs/promises';
|
|
3
|
+
import {constants} from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import {settledReads} from './src/settled-reads.mjs';
|
|
7
|
+
import {createHash} from 'node:crypto';
|
|
8
|
+
import {git} from './local-command.mjs';
|
|
9
|
+
import {inflateSync} from 'node:zlib';
|
|
10
|
+
import {publishCommitObjects} from './commit-object-publish.mjs';
|
|
11
|
+
import {compareAndSwapBranch} from './git-ref-cas.mjs';
|
|
12
|
+
import {withOperationBudget,currentOperationBudget} from './src/operation-budget.mjs';
|
|
13
|
+
import {parseGitIndex} from './src/git-index.mjs';
|
|
14
|
+
import {encodeGitCommit} from './src/git-commit-object.mjs';
|
|
15
|
+
import {createVerifiedIndexCommitPlan} from './src/verified-commit-plan.mjs';
|
|
16
|
+
import {createAmendPlan} from './src/amend-plan.mjs';
|
|
17
|
+
|
|
18
|
+
const INDEX=8*1024*1024,PARENT=2*1024*1024,CONFIG=256*1024;
|
|
19
|
+
// Only the exact issued public summary is a key; private plans never leave this module.
|
|
20
|
+
const previews=new WeakMap();
|
|
21
|
+
// Amend capabilities are deliberately unusable by normal commit consumers.
|
|
22
|
+
const amendPreviews=new WeakMap();
|
|
23
|
+
const hash=b=>createHash('sha256').update(b).digest('hex');
|
|
24
|
+
const decode=b=>new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(b);
|
|
25
|
+
const check=()=>currentOperationBudget().throwIfExpired();
|
|
26
|
+
const fail=message=>Object.assign(new Error(message),{code:'vcs/commit-preview'});
|
|
27
|
+
const identity=s=>[s.dev,s.ino,s.birthtimeNs].map(String);
|
|
28
|
+
const version=s=>[...identity(s),s.size,s.mtimeNs,s.ctimeNs,s.mode].map(String);
|
|
29
|
+
const equal=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
|
|
30
|
+
const plain=s=>s.isFile()&&!s.isSymbolicLink()&&s.nlink===1n;
|
|
31
|
+
function record(value,keys,label){
|
|
32
|
+
if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw fail('Invalid '+label+' record');
|
|
33
|
+
const out={};for(const key of Reflect.ownKeys(value)){
|
|
34
|
+
if(!keys.includes(key))throw fail('Unsupported '+label+' field');
|
|
35
|
+
const d=Object.getOwnPropertyDescriptor(value,key);
|
|
36
|
+
if(!d||!Object.hasOwn(d,'value'))throw fail(label+' requires own data properties');
|
|
37
|
+
out[key]=d.value;
|
|
38
|
+
}return out;
|
|
39
|
+
}
|
|
40
|
+
async function readPlain(file,max){
|
|
41
|
+
check();const before=await fs.lstat(file,{bigint:true});
|
|
42
|
+
if(!plain(before)||before.size>BigInt(max))throw fail('Expected bounded single-link regular file: '+file);
|
|
43
|
+
const handle=await fs.open(file,constants.O_RDONLY|(constants.O_NOFOLLOW||0));
|
|
44
|
+
try{
|
|
45
|
+
const opened=await handle.stat({bigint:true});
|
|
46
|
+
if(!plain(opened)||!equal(version(before),version(opened)))throw fail('Stale file opening');
|
|
47
|
+
const bytes=Buffer.alloc(max+1);let length=0;
|
|
48
|
+
while(length<bytes.length){check();const r=await handle.read(bytes,length,bytes.length-length,length);if(!r.bytesRead)break;length+=r.bytesRead;}
|
|
49
|
+
const after=await handle.stat({bigint:true}),current=await fs.lstat(file,{bigint:true});
|
|
50
|
+
if(length>max||!plain(current)||!equal(version(opened),version(after))||!equal(version(after),version(current))||BigInt(length)!==after.size)throw fail('Stale or oversized file reading');
|
|
51
|
+
return {bytes:Buffer.from(bytes.subarray(0,length)),version:version(after)};
|
|
52
|
+
}finally{await handle.close();}
|
|
53
|
+
}
|
|
54
|
+
async function exists(file){try{await fs.lstat(file);return true;}catch(e){if(e.code==='ENOENT')return false;throw e;}}
|
|
55
|
+
const forbidden=new Set(['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()));
|
|
56
|
+
async function metadata(directory){
|
|
57
|
+
const rows=[];let nodes=0;
|
|
58
|
+
async function visit(file,relative){
|
|
59
|
+
check();if(++nodes>20000)throw fail('Metadata inspection limit exceeded');
|
|
60
|
+
const key=relative.toLowerCase();
|
|
61
|
+
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);
|
|
62
|
+
const s=await fs.lstat(file,{bigint:true});
|
|
63
|
+
if(s.isSymbolicLink()||(!s.isDirectory()&&!plain(s))||await fs.realpath(file)!==file)throw fail('Linked or special repository metadata');
|
|
64
|
+
rows.push([relative,s.isDirectory()?identity(s):version(s)]);
|
|
65
|
+
if(s.isDirectory()){
|
|
66
|
+
const names=await fs.readdir(file);check();
|
|
67
|
+
if(names.length>20000-nodes)throw fail('Metadata inspection limit exceeded');
|
|
68
|
+
for(const name of names.sort())await visit(path.join(file,name),relative?relative+'/'+name:name);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
await visit(directory,'');return rows;
|
|
72
|
+
}
|
|
73
|
+
// Inspect names/types only, never read working file contents (including attributes).
|
|
74
|
+
async function workPolicy(root){
|
|
75
|
+
let nodes=0;const rows=[];
|
|
76
|
+
async function visit(dir,relative){
|
|
77
|
+
check();if(++nodes>20000)throw fail('Working directory inspection limit exceeded');
|
|
78
|
+
const s=await fs.lstat(dir,{bigint:true});
|
|
79
|
+
if(!s.isDirectory()||s.isSymbolicLink()||await fs.realpath(dir)!==dir)throw fail('Linked working directory');
|
|
80
|
+
rows.push([relative,identity(s)]);
|
|
81
|
+
const names=(await fs.readdir(dir)).filter(name=>relative||name!=='.git');check();
|
|
82
|
+
if(names.length>20000-nodes)throw fail('Working directory inspection limit exceeded');
|
|
83
|
+
for(const name of names.sort()){
|
|
84
|
+
if(['.gitattributes','.gitmodules','.git'].includes(name.toLowerCase()))throw fail('Attributes, nested repositories or submodules unsupported');
|
|
85
|
+
const file=path.join(dir,name),stat=await fs.lstat(file,{bigint:true});
|
|
86
|
+
if(stat.isDirectory()&&!stat.isSymbolicLink())await visit(file,relative+'/'+name);
|
|
87
|
+
else if(++nodes>20000||!plain(stat))throw fail('Linked or special working file');
|
|
88
|
+
}
|
|
89
|
+
}await visit(root,'');return rows;
|
|
90
|
+
}
|
|
91
|
+
function validateConfig(bytes){
|
|
92
|
+
for(const row of decode(bytes).split('\0').filter(Boolean)){
|
|
93
|
+
const i=row.indexOf('\n'),key=(i<0?row:row.slice(0,i)).toLowerCase(),value=(i<0?'':row.slice(i+1)).toLowerCase();
|
|
94
|
+
if(/^(filter|hook|include|submodule|gpg)\./.test(key)||key.startsWith('includeif.')||key.startsWith('extensions.')&&key!=='extensions.objectformat'||['core.worktree','core.hookspath','core.attributesfile','core.sshcommand','core.gitproxy','core.sharedrepository','core.sparsecheckout','core.sparsecheckoutcone','core.splitindex','core.untrackedcache','index.sparse','commit.gpgsign','tag.gpgsign','user.signingkey','commit.template','i18n.commitencoding'].includes(key)||/^remote\..*\.(promisor|partialclonefilter)$/.test(key))throw fail('Unsupported repository configuration: '+key);
|
|
95
|
+
if(['core.autocrlf','core.safecrlf','core.fsmonitor'].includes(key)&&!['false','no','0'].includes(value))throw fail('Content conversions unsupported');
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async function capture(root){
|
|
99
|
+
check();if(await fs.realpath(root)!==root)throw fail('Canonical root required');
|
|
100
|
+
const rootStat=await fs.lstat(root,{bigint:true});if(!rootStat.isDirectory()||rootStat.isSymbolicLink())throw fail('Directory root required');
|
|
101
|
+
const directory=path.join(root,'.git');
|
|
102
|
+
const [meta,work]=await settledReads([()=>metadata(directory),()=>workPolicy(root)]);
|
|
103
|
+
for(const file of [path.join(process.env.XDG_CONFIG_HOME||path.join(os.homedir(),'.config'),'git','attributes'),path.join(os.homedir(),'.gitattributes'),...(process.platform==='win32'?[]:['/etc/gitattributes','/usr/local/etc/gitattributes'])])if(await exists(file))throw fail('Global attributes unsupported');
|
|
104
|
+
const localConfig=await readPlain(path.join(directory,'config'),CONFIG);
|
|
105
|
+
const config=await git(root,['--git-dir='+directory,'--work-tree='+root,'config','--no-includes','--null','--list'],CONFIG);validateConfig(config);
|
|
106
|
+
const facts=decode(await git(root,['rev-parse','--absolute-git-dir','--git-common-dir','--show-toplevel','--is-bare-repository','--show-object-format','--verify','HEAD^{commit}'],16384)).split('\n');
|
|
107
|
+
if(facts.length!==7||facts[6]!==''||facts.slice(0,3).some(s=>!s||/[\r\0]/.test(s))||path.resolve(root,facts[0])!==directory||path.resolve(root,facts[1])!==directory||path.resolve(facts[2])!==root||facts[3]!=='false')throw fail('Born embedded non-bare Git repository required');
|
|
108
|
+
const objectFormat=facts[4],head=facts[5];
|
|
109
|
+
if(!['sha1','sha256'].includes(objectFormat)||!(objectFormat==='sha1'?/^[a-f0-9]{40}$/:/^[a-f0-9]{64}$/).test(head))throw fail('Invalid fixed HEAD');
|
|
110
|
+
const headFile=await readPlain(path.join(directory,'HEAD'),4096),text=decode(headFile.bytes);
|
|
111
|
+
if(!/^ref: refs\/heads\/[^\r\n]+\n?$/.test(text))throw fail('Born symbolic HEAD required');
|
|
112
|
+
const ref=text.replace(/\n$/,'').slice(5);await git(root,['check-ref-format',ref],4096);
|
|
113
|
+
const index=await readPlain(path.join(directory,'index'),INDEX),parsed=parseGitIndex(index.bytes,{objectFormat});
|
|
114
|
+
if(parsed.extensions.some(e=>!['TREE','EOIE','IEOT'].includes(e.signature)))throw fail('Unsupported Index extension');
|
|
115
|
+
const folded=new Set();for(const e of parsed.entries){
|
|
116
|
+
const key=e.path.toLowerCase();if(folded.has(key)||e.path.split('/').some(p=>['.gitattributes','.gitmodules'].includes(p.toLowerCase())))throw fail('Ambiguous Index paths or tracked attributes unsupported');folded.add(key);
|
|
117
|
+
}
|
|
118
|
+
// Close each capture with a metadata barrier as well: changes late in the
|
|
119
|
+
// second capture must not escape merely because HEAD was read earlier.
|
|
120
|
+
if(!equal(meta,await metadata(directory))||!equal(identity(rootStat),identity(await fs.lstat(root,{bigint:true})))||await fs.realpath(root)!==root)throw fail('Stale repository metadata during capture');
|
|
121
|
+
return {bytes:index.bytes,entries:parsed.entries,head,ref,objectFormat,fingerprint:{root:identity(rootStat),meta,work,config:hash(config),localConfig:[localConfig.version,hash(localConfig.bytes)],headFile:[headFile.version,hash(headFile.bytes)],index:[index.version,hash(index.bytes)],head,ref,objectFormat}};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function readFixedHead(root,state){
|
|
125
|
+
// All capture policy guards precede fixed reads; never resolve moving HEAD.
|
|
126
|
+
// Cached attributes avoid opening working content.
|
|
127
|
+
for(let i=0;i<state.entries.length;i+=128){
|
|
128
|
+
if((await git(root,['check-attr','--cached','--all','-z','--',...state.entries.slice(i,i+128).map(e=>e.path)],CONFIG)).length)throw fail('Git attributes unsupported');
|
|
129
|
+
}
|
|
130
|
+
return git(root,['cat-file','commit',state.head],PARENT);
|
|
131
|
+
}
|
|
132
|
+
async function verifyFixedBlobs(root,state){
|
|
133
|
+
for(const oid of new Set(state.entries.map(e=>e.oid))){check();if(decode(await git(root,['cat-file','-t',oid],128))!=='blob\n')throw fail('Index entry is not an existing blob');}
|
|
134
|
+
}
|
|
135
|
+
async function rebuild(root,state,{author,committer,message}){
|
|
136
|
+
const body=await readFixedHead(root,state);
|
|
137
|
+
const plan=createVerifiedIndexCommitPlan(state.bytes,body,{objectFormat:state.objectFormat,parent:state.head,author,committer,message,signal:currentOperationBudget().signal});
|
|
138
|
+
await verifyFixedBlobs(root,state);
|
|
139
|
+
return plan;
|
|
140
|
+
}
|
|
141
|
+
function safeSummary(state,plan,{author,committer,message}){
|
|
142
|
+
return Object.freeze({head:state.head,ref:state.ref,objectFormat:state.objectFormat,indexDigest:plan.indexDigest,tree:plan.tree,commit:Object.freeze({oid:plan.commit.oid}),author,committer,message});
|
|
143
|
+
}
|
|
144
|
+
async function authorize(callback){
|
|
145
|
+
check();const {signal}=currentOperationBudget();
|
|
146
|
+
// A stalled external authorization callback cannot defeat the shared deadline.
|
|
147
|
+
let abort;const canceled=new Promise((_,reject)=>{abort=()=>reject(signal.reason);signal.addEventListener('abort',abort,{once:true});});
|
|
148
|
+
try{await Promise.race([Promise.resolve().then(callback),canceled]);check();}
|
|
149
|
+
finally{signal.removeEventListener('abort',abort);}
|
|
150
|
+
}
|
|
151
|
+
/** Single-use, read-only revalidation; not an execution/publication API.
|
|
152
|
+
* The retained plan is reserved for future internal composition and discarded here.
|
|
153
|
+
* Work content is neither read nor pinned: the existing fingerprint records directory
|
|
154
|
+
* identities only, while workPolicy still rejects special files/attributes/nested Git.
|
|
155
|
+
* No global filesystem atomicity is promised by these observation barriers.
|
|
156
|
+
*/
|
|
157
|
+
export async function consumeCommitPreview(repo,options={}){
|
|
158
|
+
// Burn an own-data snapshot BEFORE validating any other metadata or callbacks,
|
|
159
|
+
// including malformed options and a wrong repository. Never invoke a getter.
|
|
160
|
+
const descriptor=options&&Object.getOwnPropertyDescriptor(options,'snapshot');
|
|
161
|
+
const snapshot=descriptor&&Object.hasOwn(descriptor,'value')?descriptor.value:undefined;
|
|
162
|
+
const saved=previews.get(snapshot);previews.delete(snapshot);
|
|
163
|
+
const r=record(repo,['type','root'],'repository'),o=record(options,['snapshot','signal','assertAuthorized'],'options');
|
|
164
|
+
if(!saved)throw fail('A single-use server-issued commit preview is required');
|
|
165
|
+
if(r.type!=='git'||typeof r.root!=='string'||!path.isAbsolute(r.root)||path.resolve(r.root)!==r.root||r.root!==saved.root)throw fail('Same canonical Git root required');
|
|
166
|
+
if(typeof o.assertAuthorized!=='function')throw fail('Authorization callback required');
|
|
167
|
+
return withOperationBudget({signal:o.signal},async()=>{
|
|
168
|
+
await authorize(o.assertAuthorized);
|
|
169
|
+
const first=await capture(r.root);
|
|
170
|
+
if(!equal(saved.fingerprint,first.fingerprint))throw fail('Stale repository changed since commit preview');
|
|
171
|
+
const plan=await rebuild(r.root,first,snapshot);
|
|
172
|
+
if(plan.id!==saved.plan.id)throw fail('Stale rebuilt commit plan');
|
|
173
|
+
await authorize(o.assertAuthorized);
|
|
174
|
+
// Must follow the LAST external callback, which may itself mutate the repository.
|
|
175
|
+
const final=await capture(r.root);
|
|
176
|
+
if(!equal(saved.fingerprint,final.fingerprint))throw fail('Stale repository changed during commit preview consumption');
|
|
177
|
+
check();return safeSummary(final,plan,snapshot);
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Internal commit transaction. CALLER MUST hold the shared repository writer mutex
|
|
182
|
+
* across prepare/apply (at least the entire apply). No Host/UI integration.
|
|
183
|
+
* Observation barriers are not hostile-external-process isolation: no index lock is
|
|
184
|
+
* held, so index edits between the final check and ref CAS can only be diagnosed
|
|
185
|
+
* afterwards. No work content reads/writes, rollback, or crash-durability promise.
|
|
186
|
+
* Requires a loose born branch and existing HEAD/branch reflogs; no log creation.
|
|
187
|
+
* Publisher authorization is raw while its owned temporary file exists; full
|
|
188
|
+
* original+verified-created-object barriers follow publication and precede CAS.
|
|
189
|
+
*/
|
|
190
|
+
export async function applyCommitPreview(repo,options={}){
|
|
191
|
+
const descriptor=options&&Object.getOwnPropertyDescriptor(options,'snapshot');
|
|
192
|
+
const snapshot=descriptor&&Object.hasOwn(descriptor,'value')?descriptor.value:undefined;
|
|
193
|
+
const saved=previews.get(snapshot);previews.delete(snapshot);
|
|
194
|
+
return executeSnapshot(repo,options,saved,'commit');
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Internal amend transaction; the same caller-held writer mutex is required.
|
|
198
|
+
* Only this entrypoint can consume amend capabilities. No public mode flag. */
|
|
199
|
+
export async function applyAmendPreview(repo,options={}){
|
|
200
|
+
const descriptor=options&&Object.getOwnPropertyDescriptor(options,'snapshot');
|
|
201
|
+
const snapshot=descriptor&&Object.hasOwn(descriptor,'value')?descriptor.value:undefined;
|
|
202
|
+
const saved=amendPreviews.get(snapshot);amendPreviews.delete(snapshot);
|
|
203
|
+
return executeSnapshot(repo,options,saved,'amend');
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function executeSnapshot(repo,options,saved,kind){
|
|
207
|
+
const r=record(repo,['type','root'],'repository'),o=record(options,['snapshot','signal','assertAuthorized','onStart'],'options');
|
|
208
|
+
const snapshot=kind==='amend'?saved?.plan:o.snapshot;
|
|
209
|
+
if(!saved)throw fail('A single-use server-issued '+kind+' preview is required');
|
|
210
|
+
if(r.type!=='git'||typeof r.root!=='string'||!path.isAbsolute(r.root)||path.resolve(r.root)!==r.root||r.root!==saved.root)throw fail('Same canonical Git root required');
|
|
211
|
+
if(typeof o.assertAuthorized!=='function'||typeof o.onStart!=='function')throw fail('Authorization and synchronous start callbacks required');
|
|
212
|
+
let started=false;
|
|
213
|
+
try{return await withOperationBudget({signal:o.signal,timeoutMs:15000},async()=>{
|
|
214
|
+
const original=saved.fingerprint,plan=saved.plan,directory=path.join(r.root,'.git');
|
|
215
|
+
const rawAuth=()=>authorize(o.assertAuthorized);
|
|
216
|
+
const start=()=>{
|
|
217
|
+
check();if(started)return;started=true;
|
|
218
|
+
const value=o.onStart();
|
|
219
|
+
if(value&&typeof value.then==='function'){Promise.resolve(value).catch(()=>{});throw fail('onStart must be synchronous');}
|
|
220
|
+
check();
|
|
221
|
+
};
|
|
222
|
+
const exact=state=>{if(!equal(original,state.fingerprint))throw fail('Stale repository changed since commit preview');};
|
|
223
|
+
await rawAuth();const first=await capture(r.root);exact(first);
|
|
224
|
+
const rebuilt=kind==='amend'
|
|
225
|
+
?createAmendPlan(first.bytes,await readFixedHead(r.root,first),{head:first.head,objectFormat:first.objectFormat,committer:snapshot.committer,message:snapshot.message,signal:currentOperationBudget().signal})
|
|
226
|
+
:await rebuild(r.root,first,snapshot);
|
|
227
|
+
if(kind==='amend')await verifyFixedBlobs(r.root,first);
|
|
228
|
+
if(rebuilt.id!==plan.id)throw fail('Stale rebuilt '+kind+' plan');
|
|
229
|
+
const ref=original.ref,mutable=new Set([ref,'logs/HEAD','logs/'+ref]);
|
|
230
|
+
const baseline=new Map(original.meta),logs=new Map();
|
|
231
|
+
for(const name of mutable){
|
|
232
|
+
if(!baseline.has(name)||baseline.get(name).length!==7)throw fail('Existing loose branch and reflogs required');
|
|
233
|
+
const file=await readPlain(path.join(directory,...name.split('/')),1024*1024);
|
|
234
|
+
if(!equal(file.version,baseline.get(name)))throw fail('Stale branch or reflog');
|
|
235
|
+
if(name===ref){if(decode(file.bytes)!==original.head+'\n')throw fail('Exact loose branch required');}
|
|
236
|
+
else logs.set(name,file.bytes);
|
|
237
|
+
}
|
|
238
|
+
await rawAuth();exact(await capture(r.root));check();
|
|
239
|
+
const published=await publishCommitObjects({gitDirectory:directory,objectFormat:original.objectFormat,trees:plan.trees,commit:plan.commit,signal:currentOperationBudget().signal,assertAuthorized:rawAuth,onStart:start});
|
|
240
|
+
// Only the publisher's actual newly-created list grants additions. Existing
|
|
241
|
+
// object rows must remain byte-version-identical, even when candidates match.
|
|
242
|
+
const owned=new Map(),allowed=new Set();
|
|
243
|
+
for(const {type,oid} of published.created){
|
|
244
|
+
const object=type==='commit'?plan.commit:plan.trees.find(t=>t.oid===oid);
|
|
245
|
+
if(!object||object.oid!==oid)throw fail('Unexpected published object');
|
|
246
|
+
const name='objects/'+oid.slice(0,2)+'/'+oid.slice(2),fanout='objects/'+oid.slice(0,2);
|
|
247
|
+
if(baseline.has(name))throw fail('Publisher changed a preexisting object');
|
|
248
|
+
allowed.add(name);if(!baseline.has(fanout))allowed.add(fanout);
|
|
249
|
+
const stored=await readPlain(path.join(directory,...name.split('/')),object.body.length+1024*1024);
|
|
250
|
+
const inflated=inflateSync(stored.bytes,{maxOutputLength:object.body.length+128,info:true});check();
|
|
251
|
+
const raw=inflated.buffer,expected=Buffer.concat([Buffer.from(type+' '+object.body.length+'\0'),object.body]);
|
|
252
|
+
if(inflated.engine.bytesWritten!==stored.bytes.length||!raw.equals(expected)||createHash(original.objectFormat).update(raw).digest('hex')!==oid)throw fail('Stored object differs from saved plan');
|
|
253
|
+
owned.set(name,stored.version);
|
|
254
|
+
}
|
|
255
|
+
let ownedRows;
|
|
256
|
+
const barrier=async(post=false)=>{
|
|
257
|
+
const current=await capture(r.root),fp=current.fingerprint,rows=new Map(fp.meta);
|
|
258
|
+
for(const [name,row] of baseline){
|
|
259
|
+
if(!rows.has(name)||(!post||!mutable.has(name))&&!equal(row,rows.get(name)))throw fail('Stale original metadata: '+name);
|
|
260
|
+
}
|
|
261
|
+
for(const [name,row] of rows)if(!baseline.has(name)){
|
|
262
|
+
if(!allowed.has(name)||owned.has(name)&&!equal(owned.get(name),row))throw fail('Foreign or changed object metadata: '+name);
|
|
263
|
+
}
|
|
264
|
+
const additions=fp.meta.filter(([name])=>!baseline.has(name));
|
|
265
|
+
if(additions.length!==allowed.size||ownedRows&&!equal(ownedRows,additions))throw fail('Owned object metadata changed');
|
|
266
|
+
if(!ownedRows)ownedRows=additions;
|
|
267
|
+
const normalized={...fp,meta:original.meta,head:post?original.head:fp.head};
|
|
268
|
+
if(!equal(normalized,original)||post&&fp.head!==plan.commit.oid)throw fail('Stale repository fingerprint');
|
|
269
|
+
if(!current.bytes.equals(first.bytes))throw fail('Index bytes changed');
|
|
270
|
+
return current;
|
|
271
|
+
};
|
|
272
|
+
await barrier();
|
|
273
|
+
let refStarted=false;
|
|
274
|
+
await compareAndSwapBranch(r,{ref,expectedOid:original.head,newOid:plan.commit.oid,objectFormat:original.objectFormat,signal:currentOperationBudget().signal,
|
|
275
|
+
assertAuthorized:async()=>{await rawAuth();if(!refStarted)await barrier();},
|
|
276
|
+
onStart:()=>{check();refStarted=true;start();check();}});
|
|
277
|
+
await barrier(true);
|
|
278
|
+
for(const [name,before] of logs){
|
|
279
|
+
const after=(await readPlain(path.join(directory,...name.split('/')),1024*1024)).bytes;
|
|
280
|
+
const tail=after.subarray(before.length);
|
|
281
|
+
if(!after.subarray(0,before.length).equals(before)||!decode(tail).startsWith(original.head+' '+plan.commit.oid+' ')||decode(tail).split('\n').length!==2)throw fail('Unexpected reflog change');
|
|
282
|
+
}
|
|
283
|
+
if(decode((await readPlain(path.join(directory,...ref.split('/')),4096)).bytes)!==plan.commit.oid+'\n')throw fail('Unexpected branch tip');
|
|
284
|
+
check();return Object.freeze({head:plan.commit.oid,ref,tree:plan.tree,indexDigest:plan.indexDigest});
|
|
285
|
+
});}catch(cause){
|
|
286
|
+
if(!started)throw cause;
|
|
287
|
+
throw Object.assign(new Error((kind==='amend'?'Amend':'Commit')+' started; outcome unknown. Inspect repository; never roll back appended objects or retry automatically.',{cause}),{code:'vcs/'+kind+'-outcome-unknown',appendOnly:true,outcomeUnknown:true});
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Read-only, conservative two-capture preview; private retained plan.
|
|
292
|
+
* Repeated observations are stale barriers, not global filesystem atomicity.
|
|
293
|
+
* Only regular stage-zero Index entries; no hooks/signing/attributes/conversions,
|
|
294
|
+
* linked/shared/alternate/shallow repositories, active operations or locks.
|
|
295
|
+
*/
|
|
296
|
+
export async function prepareCommitPreview(repo,options={}){
|
|
297
|
+
// Strict metadata snapshots and validation happen synchronously before the first await.
|
|
298
|
+
const r=record(repo,['type','root'],'repository'),o=record(options,['author','committer','message','signal'],'options');
|
|
299
|
+
if(r.type!=='git'||typeof r.root!=='string'||!path.isAbsolute(r.root)||path.resolve(r.root)!==r.root)throw fail('Absolute canonical Git root required');
|
|
300
|
+
const author=record(o.author,['name','email','timestamp','timezone'],'author'),committer=record(o.committer,['name','email','timestamp','timezone'],'committer');
|
|
301
|
+
if(typeof o.message!=='string'||Buffer.byteLength(o.message)>65536||!o.message.trim()||/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(o.message.replace(/[\n\t]/g,'')))throw fail('Bounded plaintext commit message required');
|
|
302
|
+
const message=o.message;
|
|
303
|
+
// Reuse the pure encoder to reject all invalid identities before repository I/O.
|
|
304
|
+
encodeGitCommit({tree:'1'.repeat(40),parents:[],author,committer,message});
|
|
305
|
+
Object.freeze(author);Object.freeze(committer);
|
|
306
|
+
return withOperationBudget({signal:o.signal},async()=>{
|
|
307
|
+
const first=await capture(r.root);check();
|
|
308
|
+
const plan=await rebuild(r.root,first,{author,committer,message});
|
|
309
|
+
const second=await capture(r.root);
|
|
310
|
+
if(!equal(first.fingerprint,second.fingerprint))throw fail('Stale repository changed during commit preview');
|
|
311
|
+
check();const summary=safeSummary(first,plan,{author,committer,message});
|
|
312
|
+
previews.set(summary,{root:r.root,fingerprint:first.fingerprint,plan});return summary;
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
/** Read-only amend preview; its separate capability is consumed only by applyAmendPreview. */
|
|
316
|
+
export async function prepareAmendPreview(repo,options={}){
|
|
317
|
+
// Snapshot strict own-data metadata before the first await, just like commit preview.
|
|
318
|
+
const r=record(repo,['type','root'],'repository'),o=record(options,['committer','message','signal'],'options');
|
|
319
|
+
if(r.type!=='git'||typeof r.root!=='string'||!path.isAbsolute(r.root)||path.resolve(r.root)!==r.root)throw fail('Absolute canonical Git root required');
|
|
320
|
+
const committer=record(o.committer,['name','email','timestamp','timezone'],'committer');
|
|
321
|
+
if(typeof o.message!=='string'||Buffer.byteLength(o.message)>65536||!o.message.trim()||/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(o.message.replace(/[\n\t]/g,'')))throw fail('Bounded plaintext commit message required');
|
|
322
|
+
const message=o.message;
|
|
323
|
+
encodeGitCommit({tree:'1'.repeat(40),parents:[],author:committer,committer,message});
|
|
324
|
+
Object.freeze(committer);
|
|
325
|
+
return withOperationBudget({signal:o.signal},async()=>{
|
|
326
|
+
const first=await capture(r.root);check();
|
|
327
|
+
const body=await readFixedHead(r.root,first);
|
|
328
|
+
const plan=createAmendPlan(first.bytes,body,{head:first.head,objectFormat:first.objectFormat,committer,message,signal:currentOperationBudget().signal});
|
|
329
|
+
await verifyFixedBlobs(r.root,first);
|
|
330
|
+
const second=await capture(r.root);
|
|
331
|
+
if(!equal(first.fingerprint,second.fingerprint))throw fail('Stale repository changed during amend preview');
|
|
332
|
+
check();const summary=Object.freeze({action:'amend',head:first.head,ref:first.ref,objectFormat:first.objectFormat,indexDigest:plan.indexDigest,previousTree:plan.previousTree,parents:plan.parents,author:plan.author,committer:plan.committer,message:plan.message,tree:plan.tree,commit:Object.freeze({oid:plan.commit.oid})});
|
|
333
|
+
amendPreviews.set(summary,{root:r.root,fingerprint:first.fingerprint,plan});return summary;
|
|
334
|
+
});
|
|
335
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Server-owned, single-use confirmation and process-shared repository exclusion.
|
|
2
|
+
import {randomBytes} from 'node:crypto';
|
|
3
|
+
import path from 'node:path';
|
|
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
|
+
}
|
|
13
|
+
|
|
14
|
+
// operationKind and callbacks are selected by the host, never by a browser address.
|
|
15
|
+
// prepare(repository, {address, signal}) retains its entire result on the server.
|
|
16
|
+
// Only explicitly projected public fields cross the confirmation boundary.
|
|
17
|
+
export function createConfirmedOperationCoordinator({
|
|
18
|
+
operationKind,api,prepare=api?.prepare,execute=api?.execute,project=()=>({}),
|
|
19
|
+
now=Date.now,ttlMs=60000,maxTokens=32,
|
|
20
|
+
invalidCode='vcs/confirmation-invalid',
|
|
21
|
+
invalidMessage='Confirmation is expired, used, or belongs to a different Session/repository. Prepare again.',
|
|
22
|
+
unknownCode='vcs/outcome-unknown',
|
|
23
|
+
unknownMessage='The operation started but its final result could not be confirmed. Refresh the repository before preparing another operation.',
|
|
24
|
+
}){
|
|
25
|
+
if(typeof operationKind!=='string'||!operationKind.trim())throw new TypeError('A server-selected operationKind is required.');
|
|
26
|
+
if(typeof prepare!=='function'||typeof execute!=='function'||typeof project!=='function')throw new TypeError('Confirmation prepare, execute and project callbacks must be functions.');
|
|
27
|
+
if(!Number.isFinite(ttlMs)||ttlMs<=0||!Number.isSafeInteger(maxTokens)||maxTokens<=0)throw new TypeError('Confirmation ttlMs and maxTokens must be positive.');
|
|
28
|
+
const tokens=new Map();
|
|
29
|
+
const purge=()=>{for(const [token,row]of tokens)if(row.expiresAt<=now())tokens.delete(token);};
|
|
30
|
+
return {
|
|
31
|
+
invalidate(entry){for(const [token,row]of tokens)if(row.entry===entry)tokens.delete(token);},
|
|
32
|
+
clear(){tokens.clear();},
|
|
33
|
+
async prepare(address,{entry,repository,cwd,signal,assertAuthorized}){
|
|
34
|
+
const snapshot=await prepare.call(api,{...repository},{address,signal});await assertAuthorized();signal?.throwIfAborted();purge();
|
|
35
|
+
while(tokens.size>=maxTokens)tokens.delete(tokens.keys().next().value);
|
|
36
|
+
const token=randomBytes(32).toString('hex'),expiresAt=now()+ttlMs;
|
|
37
|
+
const publicFields=project(snapshot);
|
|
38
|
+
tokens.set(token,{snapshot,expiresAt,entry,repository,cwd,sessionId:address.sessionId,repositoryId:address.repositoryId,operationKind});
|
|
39
|
+
return {...publicFields,token,expiresAt};
|
|
40
|
+
},
|
|
41
|
+
async confirm(address,{entry,repository,cwd,signal,assertAuthorized}){
|
|
42
|
+
purge();const row=tokens.get(address.token);tokens.delete(address.token);
|
|
43
|
+
if(!row||row.operationKind!==operationKind||row.entry!==entry||row.repository!==repository||row.cwd!==cwd||row.sessionId!==address.sessionId||row.repositoryId!==address.repositoryId)throw error(invalidCode,invalidMessage);
|
|
44
|
+
const release=acquireRepositoryAccess(repository.root,true);let started=false;
|
|
45
|
+
try{await assertAuthorized();signal?.throwIfAborted();const result=await execute.call(api,{...repository},{snapshot:row.snapshot,signal,assertAuthorized,onStart(){started=true;}});await assertAuthorized();signal?.throwIfAborted();return result;}
|
|
46
|
+
catch(failure){if(started)throw error(unknownCode,unknownMessage);throw failure;}
|
|
47
|
+
finally{release();}
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|