@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.
Files changed (56) hide show
  1. package/README.md +68 -5
  2. package/amend-host.mjs +48 -0
  3. package/branch-create-host.mjs +42 -0
  4. package/branch-create-preview.mjs +196 -0
  5. package/branch-delete-preview.mjs +214 -0
  6. package/branch-switch-host.mjs +13 -33
  7. package/commit-host.mjs +49 -0
  8. package/commit-object-publish.mjs +123 -0
  9. package/commit-preview.mjs +335 -0
  10. package/confirmed-operation.mjs +50 -0
  11. package/dist/client.js +2 -2
  12. package/dist/frontend.json +1 -1
  13. package/dist/interface.js +2 -2
  14. package/docs/RELEASING.md +2 -0
  15. package/git-blob-store.mjs +151 -0
  16. package/git-branch-create.mjs +156 -0
  17. package/git-branch-delete.mjs +175 -0
  18. package/git-lightweight-tag-create.mjs +181 -0
  19. package/git-object-store.mjs +162 -0
  20. package/git-ref-cas.mjs +119 -0
  21. package/git-tag-create.mjs +186 -0
  22. package/index-change-host.mjs +19 -0
  23. package/index-change.mjs +418 -0
  24. package/index-lock.mjs +231 -0
  25. package/index-stage-host.mjs +19 -0
  26. package/index.mjs +301 -4
  27. package/latest-commit.mjs +109 -0
  28. package/lightweight-tag-host.mjs +42 -0
  29. package/lightweight-tag-preview.mjs +183 -0
  30. package/line-index-host.mjs +58 -0
  31. package/locale/en.json +1 -1
  32. package/locale/zh.json +1 -1
  33. package/package.json +47 -2
  34. package/partial-stage-host.mjs +52 -0
  35. package/partial-unstage-host.mjs +52 -0
  36. package/src/amend-plan.mjs +74 -0
  37. package/src/branch-delete-plan.mjs +113 -0
  38. package/src/commit-plan.mjs +78 -0
  39. package/src/git-commit-object.mjs +99 -0
  40. package/src/git-index.mjs +113 -0
  41. package/src/git-tag-object.mjs +110 -0
  42. package/src/index-tree.mjs +77 -0
  43. package/src/lightweight-tag-plan.mjs +64 -0
  44. package/src/line-index.mjs +168 -0
  45. package/src/partial-index.mjs +199 -0
  46. package/src/reflog.mjs +33 -0
  47. package/src/settled-reads.mjs +5 -0
  48. package/src/verified-branch-delete-plan.mjs +95 -0
  49. package/src/verified-commit-metadata.mjs +57 -0
  50. package/src/verified-commit-plan.mjs +49 -0
  51. package/src/verified-commit.mjs +84 -0
  52. package/src/verified-tag-plan.mjs +72 -0
  53. package/tag-create-host.mjs +31 -0
  54. package/tag-create-preview.mjs +215 -0
  55. package/tag-object-publish.mjs +49 -0
  56. package/vcs.mjs +29 -0
@@ -0,0 +1,78 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {parseGitIndex} from './git-index.mjs';
3
+ import {buildIndexTree} from './index-tree.mjs';
4
+ import {encodeGitCommit} from './git-commit-object.mjs';
5
+
6
+ const MAX_INDEX_BYTES=8*1024*1024;
7
+ const APPROVED_EXTENSIONS=new Set(['TREE','EOIE','IEOT']);
8
+ const sha256=bytes=>createHash('sha256').update(bytes).digest('hex');
9
+ function oid(value,width,label){
10
+ if(typeof value!=='string'||value.length!==width||/[^0-9a-f]/.test(value)||/^0+$/.test(value))throw Error('Invalid Git commit plan '+label+' object id');
11
+ return value;
12
+ }
13
+ function owned(bytes){const copy=Buffer.alloc(bytes.length);bytes.copy(copy);return copy;}
14
+ function dataRecord(value,keys,label){
15
+ if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw Error('Invalid Git commit plan '+label+' record');
16
+ const captured=Object.create(null);
17
+ for(const key of Reflect.ownKeys(value)){
18
+ if(!keys.includes(key))throw Error('Unsupported Git commit plan '+label+' field');
19
+ const descriptor=Object.getOwnPropertyDescriptor(value,key);
20
+ if(!descriptor||!Object.hasOwn(descriptor,'value'))throw Error('Git commit plan '+label+' fields must be own data properties');
21
+ captured[key]=descriptor.value;
22
+ }
23
+ return captured;
24
+ }
25
+ function captureIdentity(value,label){
26
+ const copy=dataRecord(value,['name','email','timestamp','timezone'],label);
27
+ for(const key of ['name','email','timezone'])if(typeof copy[key]!=='string')throw Error('Git identity '+key+' must be a string');
28
+ if(typeof copy.timestamp!=='number')throw Error('Invalid Git identity timestamp');
29
+ return copy;
30
+ }
31
+
32
+ // Pure, synchronous assembly for a born, exactly-one-parent commit. No filesystem,
33
+ // subprocess, worktree, object lookup, refs, ambient cancellation or publication.
34
+ // Copy the <=8 MiB raw index before inspecting options. parseGitIndex verifies its
35
+ // format-specific checksum and stage-0 regular entries. Only opaque, bounded
36
+ // TREE/EOIE/IEOT cache extensions are accepted; trees are rebuilt from entries.
37
+ // Identity, time and message encoding use encodeGitCommit's exact validation.
38
+ // Unlike that primitive, this API rejects trim-empty messages. Nonblank messages
39
+ // retain every byte, including leading/trailing whitespace and newline state.
40
+ // Cancellation is checked around phases, never awaited: an event-loop abort
41
+ // cannot interrupt synchronous execution. No reference/object existence, type or
42
+ // freshness is proven; the supplied parentTree is not resolved from parent.
43
+ // Metadata is frozen; each body is an independent owned *mutable* Buffer. There
44
+ // is no private retained state, no frozen-Buffer claim and no execution capability.
45
+ // Consumers must revalidate bytes/OIDs and fresh repository state before any I/O.
46
+ // id = SHA256(UTF8(JSON.stringify([domain,indexDigest,format,parent,parentTree,
47
+ // root,commitOID]))), where indexDigest is SHA256 of the exact raw index bytes.
48
+ export function createIndexCommitPlan(indexBuffer,inputs={}){
49
+ if(!Buffer.isBuffer(indexBuffer))throw Error('Git index must be a Buffer');
50
+ if(indexBuffer.length>MAX_INDEX_BYTES)throw Error('Git index byte limit exceeded');
51
+ const snapshot=owned(indexBuffer);
52
+ const captured=dataRecord(inputs,['objectFormat','parent','parentTree','author','committer','message','signal'],'input');
53
+ const {objectFormat='sha1',parent,parentTree,message,signal}=captured;
54
+ const author=captureIdentity(captured.author,'author'),committer=captureIdentity(captured.committer,'committer');
55
+ if(Buffer.isBuffer(message)&&message.length>64*1024)throw Error('Git commit message byte limit exceeded');
56
+ const messageSnapshot=Buffer.isBuffer(message)?owned(message):message;
57
+ const check=()=>signal?.throwIfAborted();
58
+ check();
59
+ if(objectFormat!=='sha1'&&objectFormat!=='sha256')throw Error('Unsupported Git commit plan object format');
60
+ const width=objectFormat==='sha1'?40:64;
61
+ oid(parent,width,'parent');oid(parentTree,width,'parent tree');
62
+ const parsed=parseGitIndex(snapshot,{objectFormat});
63
+ if(parsed.extensions.some(extension=>!APPROVED_EXTENSIONS.has(extension.signature)))throw Error('Unsupported semantic Git index extension for commit plan');
64
+ check();
65
+ const built=buildIndexTree(parsed.entries,{objectFormat});
66
+ check();
67
+ if(built.root===parentTree)throw Error('Git commit plan is a no-op: index tree equals parent tree');
68
+ const encoded=encodeGitCommit({tree:built.root,parents:[parent],author,committer,message:messageSnapshot},{objectFormat});
69
+ if(!messageSnapshot.toString().trim())throw Error('Git commit plan message must be nonblank');
70
+ check();
71
+ const indexDigest=sha256(snapshot),tree=built.root;
72
+ const id=sha256(JSON.stringify(['dsh-index-commit-plan-v1',indexDigest,objectFormat,parent,parentTree,tree,encoded.oid]));
73
+ const commit=Object.freeze({oid:encoded.oid,body:owned(encoded.body)});
74
+ const trees=Object.freeze(built.trees.map(value=>Object.freeze({path:value.path,oid:value.oid,body:owned(value.body)})));
75
+ const plan=Object.freeze({id,objectFormat,indexDigest,parent,parentTree,tree,commit,trees});
76
+ check();
77
+ return plan;
78
+ }
@@ -0,0 +1,99 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {TextDecoder} from 'node:util';
3
+
4
+ // Pure object encoding: no filesystem, repository/ref lookup, subprocess or network.
5
+ // OIDs are full lowercase nonzero hex; no existence or referenced-object type check.
6
+ // Modes are canonical octal strings: 100644, 100755, 40000 only. Symlinks
7
+ // (120000), gitlinks (160000), numeric modes and aliases such as 040000 are rejected.
8
+ // Names/messages accept strings or Buffers with strict UTF-8 (no surrogate repair).
9
+ // Names retain spelling/case, except .git is rejected case-insensitively. This is
10
+ // object encoding, not a portable checkout-path validator (backslash is allowed).
11
+ // Limits: 100000 entries, 4096 bytes/name, 8 MiB tree body; 1024 UTF-8 bytes
12
+ // per nonblank identity name/email; 16 unique parents; 64 KiB message (NUL-free).
13
+ // Timestamps are nonnegative safe integers; offsets are +/-HHMM, minutes <60,
14
+ // maximum absolute offset 1400. Messages preserve all bytes/final-newline state.
15
+ // Returned bodies are owned copies, never views of caller buffers or other results.
16
+ const MAX_TREE_BYTES=8*1024*1024,MAX_ENTRIES=100000,MAX_NAME_BYTES=4096;
17
+ const MAX_IDENTITY_BYTES=1024,MAX_MESSAGE_BYTES=64*1024;
18
+ const utf8=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true});
19
+ function formatInfo(objectFormat){
20
+ if(objectFormat!=='sha1'&&objectFormat!=='sha256')throw Error('Unsupported Git object format');
21
+ return objectFormat==='sha1'?40:64;
22
+ }
23
+ function oidText(oid,length){
24
+ if(typeof oid!=='string'||oid.length!==length||/[^0-9a-f]/.test(oid)||/^0+$/.test(oid))throw Error('Invalid Git object id');
25
+ return oid;
26
+ }
27
+ function bytes(value,label,max){
28
+ if(typeof value!=='string'&&!Buffer.isBuffer(value))throw Error(label+' must be a string or Buffer');
29
+ if(value.length>max)throw Error(label+' byte limit exceeded');
30
+ const result=Buffer.from(value);
31
+ if(result.length>max)throw Error(label+' byte limit exceeded');
32
+ let decoded;
33
+ try{decoded=utf8.decode(result);}catch{throw Error(label+' must be strict UTF-8');}
34
+ if(typeof value==='string'&&decoded!==value)throw Error(label+' must be strict UTF-8');
35
+ return {buffer:result,text:decoded};
36
+ }
37
+ function result(type,body,objectFormat){
38
+ const oid=createHash(objectFormat).update(Buffer.from(type+' '+body.length+'\0','ascii')).update(body).digest('hex');
39
+ return {body,oid};
40
+ }
41
+
42
+ export function encodeGitTree(entries,{objectFormat='sha1'}={}){
43
+ const oidLength=formatInfo(objectFormat);
44
+ if(!Array.isArray(entries))throw Error('Git tree entries must be an array');
45
+ if(entries.length>MAX_ENTRIES)throw Error('Git tree entry limit exceeded');
46
+ const seen=new Set(),encoded=[];
47
+ let total=0;
48
+ for(const entry of entries){
49
+ if(!entry||typeof entry!=='object')throw Error('Invalid Git tree entry');
50
+ const {buffer:name,text}=bytes(entry.name,'Git tree name',MAX_NAME_BYTES);
51
+ if(!name.length||text==='.'||text==='..'||text.toLowerCase()==='.git'||/[\0/]/u.test(text))throw Error('Unsafe Git tree name');
52
+ if(seen.has(text))throw Error('Duplicate Git tree name');
53
+ seen.add(text);
54
+ const mode=entry.mode;
55
+ if(mode!=='100644'&&mode!=='100755'&&mode!=='40000')throw Error('Unsupported Git tree mode');
56
+ const oid=oidText(entry.oid,oidLength);
57
+ const header=Buffer.from(mode+' ','ascii');
58
+ total+=header.length+name.length+1+oidLength/2;
59
+ if(total>MAX_TREE_BYTES)throw Error('Git tree byte limit exceeded');
60
+ encoded.push({key:mode==='40000'?Buffer.concat([name,Buffer.from('/')]):name,parts:[header,name,Buffer.from([0]),Buffer.from(oid,'hex')]});
61
+ }
62
+ encoded.sort((a,b)=>Buffer.compare(a.key,b.key));
63
+ const parts=[];
64
+ for(const entry of encoded)parts.push(...entry.parts);
65
+ return result('tree',Buffer.concat(parts,total),objectFormat);
66
+ }
67
+ function identity(value,label){
68
+ if(!value||typeof value!=='object')throw Error('Invalid Git '+label+' identity');
69
+ const fields={};
70
+ for(const key of ['name','email']){
71
+ if(typeof value[key]!=='string')throw Error('Git identity '+key+' must be a string');
72
+ const {text}=bytes(value[key],'Git identity '+key,MAX_IDENTITY_BYTES);
73
+ if(!text.trim()||/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}<>]/u.test(text))throw Error('Unsafe Git identity '+key);
74
+ fields[key]=text;
75
+ }
76
+ const {timestamp,timezone}=value;
77
+ if(!Number.isSafeInteger(timestamp)||timestamp<0)throw Error('Invalid Git identity timestamp');
78
+ if(typeof timezone!=='string'||timezone.length!==5||!/^[-+][0-9]{4}$/.test(timezone))throw Error('Invalid Git identity timezone');
79
+ const hours=Number(timezone.slice(1,3)),minutes=Number(timezone.slice(3));
80
+ if(minutes>59||hours>14||(hours===14&&minutes!==0))throw Error('Invalid Git identity timezone');
81
+ return fields.name+' <'+fields.email+'> '+timestamp+' '+timezone;
82
+ }
83
+
84
+ export function encodeGitCommit(input,{objectFormat='sha1'}={}){
85
+ const oidLength=formatInfo(objectFormat);
86
+ if(!input||typeof input!=='object')throw Error('Invalid Git commit input');
87
+ const tree=oidText(input.tree,oidLength),parents=input.parents===undefined?[]:input.parents;
88
+ if(!Array.isArray(parents)||parents.length>16)throw Error('Git commit parents must be an array of at most 16');
89
+ const seen=new Set(),headers=['tree '+tree];
90
+ for(const parent of parents){
91
+ oidText(parent,oidLength);
92
+ if(seen.has(parent))throw Error('Duplicate Git commit parent');
93
+ seen.add(parent);headers.push('parent '+parent);
94
+ }
95
+ headers.push('author '+identity(input.author,'author'),'committer '+identity(input.committer,'committer'));
96
+ const {buffer:message}=bytes(input.message,'Git commit message',MAX_MESSAGE_BYTES);
97
+ if(message.includes(0))throw Error('Git commit message must not contain NUL');
98
+ return result('commit',Buffer.concat([Buffer.from(headers.join('\n')+'\n\n','utf8'),message]),objectFormat);
99
+ }
@@ -0,0 +1,113 @@
1
+ import {createHash,timingSafeEqual} from 'node:crypto';
2
+ import {TextDecoder} from 'node:util';
3
+
4
+ // Pure Buffer transformations only: no repository, filesystem or subprocess access.
5
+ const MAX_BYTES=8*1024*1024,MAX_ENTRIES=100000;
6
+ const DERIVED_EXTENSIONS=new Set(['TREE','EOIE','IEOT']);
7
+ const utf8=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true});
8
+ function formatInfo(objectFormat){
9
+ if(objectFormat!=='sha1'&&objectFormat!=='sha256')throw Error('Unsupported Git index object format');
10
+ return {objectFormat,hashBytes:objectFormat==='sha1'?20:32};
11
+ }
12
+ function validPath(path){
13
+ if(typeof path!=='string'||!path||/[\u0000-\u001f\u007f\\:<>"|?*]/u.test(path))throw Error('Unsafe Git index path');
14
+ for(const part of path.split('/')){
15
+ if(!part||part==='.'||part==='..'||part.toLowerCase()==='.git'||/[. ]$/.test(part)||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))throw Error('Unsafe Git index path');
16
+ }
17
+ return path;
18
+ }
19
+ function validMode(mode){
20
+ if(mode!=='100644'&&mode!=='100755')throw Error('Unsupported Git index mode');
21
+ return mode;
22
+ }
23
+ function validOid(oid,hashBytes){
24
+ if(typeof oid!=='string'||oid.length!==hashBytes*2||!/^[0-9a-f]+$/.test(oid)||/^0+$/.test(oid))throw Error('Invalid Git index object id');
25
+ return oid;
26
+ }
27
+ function inspect(buffer,objectFormat){
28
+ const {hashBytes}=formatInfo(objectFormat);
29
+ if(!Buffer.isBuffer(buffer))throw Error('Git index must be a Buffer');
30
+ if(buffer.length>MAX_BYTES)throw Error('Git index byte limit exceeded');
31
+ if(buffer.length<12+hashBytes)throw Error('Truncated Git index header');
32
+ const end=buffer.length-hashBytes;
33
+ if(buffer.subarray(end).every(byte=>byte===0))throw Error('Unsupported unverifiable Git index skipHash checksum');
34
+ if(!timingSafeEqual(createHash(objectFormat).update(buffer.subarray(0,end)).digest(),buffer.subarray(end)))throw Error('Git index checksum mismatch');
35
+ if(buffer.toString('ascii',0,4)!=='DIRC'||!buffer.subarray(0,4).equals(Buffer.from('DIRC')))throw Error('Invalid Git index signature');
36
+ const version=buffer.readUInt32BE(4),count=buffer.readUInt32BE(8),fixed=42+hashBytes;
37
+ if(version!==2&&version!==3)throw Error('Unsupported Git index version');
38
+ if(count>MAX_ENTRIES)throw Error('Git index entry limit exceeded');
39
+ if(count>Math.floor((end-12)/(Math.ceil((fixed+2)/8)*8)))throw Error('Truncated Git index entries');
40
+ const entries=[],locations=[],extensions=[],extensionNames=new Set();
41
+ let offset=12,previous=null;
42
+ for(let i=0;i<count;i++){
43
+ const start=offset;
44
+ if(fixed>end-offset)throw Error('Truncated Git index entry');
45
+ const flags=buffer.readUInt16BE(start+40+hashBytes);
46
+ if(flags&0xc000)throw Error('Unsupported Git index assume-valid or extended flags');
47
+ if(flags&0x3000)throw Error('Git index must contain stage 0 entries only');
48
+ const mode=validMode(buffer.readUInt32BE(start+24).toString(8));
49
+ const oid=validOid(buffer.toString('hex',start+40,start+40+hashBytes),hashBytes);
50
+ const pathStart=start+fixed,nul=buffer.indexOf(0,pathStart);
51
+ if(nul<0||nul>=end)throw Error('Missing Git index path NUL');
52
+ const bytes=buffer.subarray(pathStart,nul);
53
+ if((flags&0xfff)!==Math.min(bytes.length,0xfff))throw Error('Git index path length mismatch');
54
+ let path;
55
+ try{path=utf8.decode(bytes);}catch{throw Error('Invalid Git index UTF-8 path');}
56
+ validPath(path);
57
+ if(previous&&Buffer.compare(previous,bytes)>=0)throw Error('Git index paths must be unique and byte ordered');
58
+ previous=bytes;
59
+ offset=start+Math.ceil((nul+1-start)/8)*8;
60
+ if(offset>end)throw Error('Truncated Git index padding');
61
+ for(let p=nul;p<offset;p++)if(buffer[p]!==0)throw Error('Nonzero Git index path padding');
62
+ entries.push({path,oid,mode,flags});locations.push({start,end:offset});
63
+ }
64
+ const entriesEnd=offset;
65
+ while(offset<end){
66
+ if(end-offset<8)throw Error('Truncated Git index extension header');
67
+ const signature=buffer.toString('latin1',offset,offset+4),size=buffer.readUInt32BE(offset+4);
68
+ if(!/^[A-Za-z][A-Za-z0-9 ]{3}$/.test(signature))throw Error('Invalid Git index extension signature');
69
+ if(!/^[A-Z]/.test(signature))throw Error('Unsupported mandatory Git index extension: '+signature);
70
+ if(size>end-offset-8)throw Error('Truncated Git index extension payload');
71
+ if(extensionNames.has(signature))throw Error('Duplicate Git index extension');
72
+ extensionNames.add(signature);
73
+ extensions.push({signature,size,offset});offset+=8+size;
74
+ }
75
+ return {version,entries,extensions,locations,entriesEnd,hashBytes};
76
+ }
77
+
78
+ // Modes are canonical octal strings; paths retain their exact UTF-8 spelling and case.
79
+ // Optional extension payloads are opaque: only their bounded framing is parsed.
80
+ export function parseGitIndex(buffer,{objectFormat='sha1'}={}){
81
+ const {version,entries,extensions}=inspect(buffer,objectFormat);
82
+ return {version,entries,extensions};
83
+ }
84
+
85
+ // Returns an unpublished candidate Buffer. Never adds/removes paths or changes offsets.
86
+ export function replaceGitIndexEntry(buffer,{path,expectedOid,expectedMode,oid,mode,objectFormat='sha1'}){
87
+ const source=inspect(buffer,objectFormat);
88
+ validPath(path);validMode(expectedMode);validMode(mode);
89
+ validOid(expectedOid,source.hashBytes);validOid(oid,source.hashBytes);
90
+ if(source.extensions.some(extension=>!DERIVED_EXTENSIONS.has(extension.signature)))throw Error('Unsupported semantic Git index extension for replacement');
91
+ const selected=source.entries.findIndex(entry=>entry.path===path);
92
+ if(selected<0)throw Error('Selected Git index path does not exist');
93
+ const entry=source.entries[selected];
94
+ if(entry.oid!==expectedOid||entry.mode!==expectedMode)throw Error('Git index expected tuple mismatch');
95
+ const body=Buffer.from(buffer.subarray(0,source.entriesEnd)),start=source.locations[selected].start;
96
+ // Publication advances index mtime: clear every stat cache, including untouched
97
+ // racily-clean entries, without changing their mode/OID/path/flags semantics.
98
+ for(const location of source.locations){
99
+ body.fill(0,location.start,location.start+24);
100
+ body.fill(0,location.start+28,location.start+40);
101
+ }
102
+ body.writeUInt32BE(parseInt(mode,8),start+24);
103
+ Buffer.from(oid,'hex').copy(body,start+40);
104
+ const candidate=Buffer.concat([body,createHash(objectFormat).update(body).digest()]);
105
+ const verified=inspect(candidate,objectFormat);
106
+ if(verified.version!==source.version||verified.entries.length!==source.entries.length||verified.extensions.length)throw Error('Git index candidate structure mismatch');
107
+ for(let i=0;i<source.entries.length;i++){
108
+ const before=source.entries[i],after=verified.entries[i],location=source.locations[i];
109
+ if(after.path!==before.path||after.flags!==before.flags||after.oid!==(i===selected?oid:before.oid)||after.mode!==(i===selected?mode:before.mode)||verified.locations[i].start!==location.start||verified.locations[i].end!==location.end)throw Error('Git index candidate semantic mismatch');
110
+ if(!candidate.subarray(location.start+40,location.end).equals(i===selected?Buffer.concat([Buffer.from(oid,'hex'),buffer.subarray(location.start+40+source.hashBytes,location.end)]):buffer.subarray(location.start+40,location.end)))throw Error('Git index candidate changed path or flags');
111
+ }
112
+ return candidate;
113
+ }
@@ -0,0 +1,110 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {TextDecoder} from 'node:util';
3
+ import {encodeGitCommit} from './git-commit-object.mjs';
4
+
5
+ // Pure unsigned annotated tags targeting commits only. No I/O, ref/object lookup,
6
+ // signing or subprocesses. A claimed commit target is not an existence/type proof.
7
+ // Inputs/options/tagger are exact own-data plain/null-prototype records. Buffers
8
+ // are copied before options or cooperative signal callbacks; no caller getters run.
9
+ // Messages require nonblank strict UTF-8 <=64KiB; CR/LF/TAB and BOM are preserved,
10
+ // other Cc and the exact PGP signature BEGIN marker anywhere are refused.
11
+ // Short tag names follow branch-create's portable 1000/255 UTF-8 byte policy.
12
+ // Parser accepts only this canonical encoder's subset, <=128KiB raw body bytes.
13
+ // messageBytes is a byte COUNT, not a Buffer; returned records are frozen.
14
+ // Signals: native AbortSignal, or an own-data plain record with optional boolean
15
+ // aborted and synchronous throwIfAborted function. Callbacks are trusted but cannot
16
+ // change already captured body/options. No hostile Proxy isolation is promised.
17
+ const MAX_MESSAGE=64*1024,MAX_BODY=128*1024;
18
+ const utf8=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true});
19
+ const nativeAbort=AbortSignal.prototype.throwIfAborted;
20
+ const nativeAborted=Object.getOwnPropertyDescriptor(AbortSignal.prototype,'aborted').get;
21
+ function record(value,keys,required,label){
22
+ if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw Error('Invalid '+label+' record');
23
+ const out=Object.create(null);
24
+ for(const key of Reflect.ownKeys(value)){
25
+ if(typeof key!=='string'||!keys.includes(key))throw Error('Unsupported '+label+' field');
26
+ const d=Object.getOwnPropertyDescriptor(value,key);
27
+ if(!d||!Object.hasOwn(d,'value'))throw Error(label+' requires own data properties');
28
+ out[key]=d.value;
29
+ }
30
+ for(const key of required)if(!Object.hasOwn(out,key))throw Error('Missing '+label+' '+key);
31
+ return out;
32
+ }
33
+ function format(value){
34
+ if(value!=='sha1'&&value!=='sha256')throw Error('Unsupported Git object format');
35
+ return value==='sha1'?40:64;
36
+ }
37
+ function oidText(value,width){
38
+ if(typeof value!=='string'||value.length!==width||/[^0-9a-f]/.test(value)||/^0+$/.test(value))throw Error('Invalid Git object id');
39
+ return value;
40
+ }
41
+ function messageBytes(value){
42
+ if(typeof value!=='string'&&!Buffer.isBuffer(value))throw Error('Git tag message must be a string or Buffer');
43
+ if(value.length>MAX_MESSAGE)throw Error('Git tag message byte limit exceeded');
44
+ const bytes=Buffer.from(value);
45
+ if(bytes.length>MAX_MESSAGE)throw Error('Git tag message byte limit exceeded');
46
+ let text;try{text=utf8.decode(bytes);}catch{throw Error('Git tag message must be strict UTF-8');}
47
+ if(typeof value==='string'&&text!==value)throw Error('Git tag message must be strict UTF-8');
48
+ if(!text.trim()||/[\p{Cc}]/u.test(text.replace(/[\r\n\t]/g,'')))throw Error('Unsafe or blank Git tag message');
49
+ if(text.includes('-----BEGIN PGP SIGNATURE-----'))throw Error('Signed Git tag messages are unsupported');
50
+ return {bytes,text};
51
+ }
52
+ function tagName(name){
53
+ if(typeof name!=='string'||!name||Buffer.from(name,'utf8').toString('utf8')!==name||Buffer.byteLength(name,'utf8')>1000||
54
+ name==='@'||name.toUpperCase()==='HEAD'||name.startsWith('-')||name.startsWith('refs/')||/[\x00-\x20\x7f~^:?*\[\\<>"|\p{Cc}\p{Cf}]/u.test(name)||name.includes('..')||name.includes('@{')||
55
+ 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)))throw Error('Safe portable short tag name required');
56
+ return name;
57
+ }
58
+ function hash(body,objectFormat){return createHash(objectFormat).update(Buffer.from('tag '+body.length+'\0','ascii')).update(body).digest('hex');}
59
+ function capture(input){
60
+ const r=record(input,['object','tag','tagger','message'],['object','tag','tagger','message'],'Git tag input');
61
+ const tagger=record(r.tagger,['name','email','timestamp','timezone'],['name','email','timestamp','timezone'],'Git tagger');
62
+ const message=messageBytes(r.message);
63
+ return {object:r.object,tag:r.tag,tagger,message};
64
+ }
65
+ function encodeCaptured(r,objectFormat){
66
+ const width=format(objectFormat),object=oidText(r.object,width),tag=tagName(r.tag),t=r.tagger;
67
+ // Reuse the commit encoder's established identity validation on owned data only.
68
+ encodeGitCommit({tree:object,author:t,committer:t,message:r.message.bytes},{objectFormat});
69
+ const identity=t.name+' <'+t.email+'> '+t.timestamp+' '+t.timezone;
70
+ const body=Buffer.concat([Buffer.from('object '+object+'\ntype commit\ntag '+tag+'\ntagger '+identity+'\n\n','utf8'),r.message.bytes]);
71
+ return {body,oid:hash(body,objectFormat)};
72
+ }
73
+ export function encodeGitTag(input,options={}){
74
+ const r=capture(input),o=record(options,['objectFormat'],[],'Git tag options');
75
+ return encodeCaptured(r,o.objectFormat===undefined?'sha1':o.objectFormat);
76
+ }
77
+ function abortCheck(signal){
78
+ if(signal===undefined)return ()=>{};
79
+ // Probe brand with the intrinsic, never an overridden method/property.
80
+ let native=false;try{Reflect.apply(nativeAborted,signal,[]);native=true;}catch{}
81
+ if(native)return ()=>Reflect.apply(nativeAbort,signal,[]);
82
+ const s=record(signal,['aborted','throwIfAborted'],[],'Git tag signal');
83
+ if(s.aborted!==undefined&&typeof s.aborted!=='boolean'||s.throwIfAborted!==undefined&&typeof s.throwIfAborted!=='function')throw Error('Invalid Git tag signal');
84
+ return ()=>{if(s.aborted){const e=Error('Git tag verification aborted');e.name='AbortError';throw e;}if(s.throwIfAborted)Reflect.apply(s.throwIfAborted,signal,[]);};
85
+ }
86
+ export function parseVerifiedGitTag(bytes,options={}){
87
+ if(!Buffer.isBuffer(bytes))throw Error('Git tag body must be a Buffer');
88
+ if(bytes.length>MAX_BODY)throw Error('Git tag body byte limit exceeded');
89
+ const body=Buffer.from(bytes);
90
+ const o=record(options,['oid','objectFormat','signal'],['oid'],'Git tag verification options');
91
+ const objectFormat=o.objectFormat===undefined?'sha1':o.objectFormat;
92
+ const width=format(objectFormat),oid=oidText(o.oid,width),check=abortCheck(o.signal);
93
+ check();
94
+ if(hash(body,objectFormat)!==oid)throw Error('Git tag object id mismatch');
95
+ check();
96
+ let text;try{text=utf8.decode(body);}catch{throw Error('Git tag body must be strict UTF-8');}
97
+ const end=text.indexOf('\n\n');
98
+ if(end<0)throw Error('Git tag missing header separator');
99
+ const lines=text.slice(0,end).split('\n');
100
+ if(lines.length!==4||!lines[0].startsWith('object ')||lines[1]!=='type commit'||!lines[2].startsWith('tag ')||!lines[3].startsWith('tagger '))throw Error('Unsupported or out-of-order Git tag headers');
101
+ const match=/^([^<>]+) <([^<>]+)> (0|[1-9][0-9]*) ([-+][0-9]{4})$/.exec(lines[3].slice(7));
102
+ if(!match)throw Error('Invalid Git tagger identity');
103
+ const tagger={name:match[1],email:match[2],timestamp:Number(match[3]),timezone:match[4]};
104
+ const input={object:lines[0].slice(7),tag:lines[2].slice(4),tagger,message:text.slice(end+2)};
105
+ check();
106
+ const canonical=encodeGitTag(input,{objectFormat});
107
+ if(canonical.oid!==oid||!canonical.body.equals(body))throw Error('Noncanonical Git tag body');
108
+ check();
109
+ return Object.freeze({oid,object:input.object,tag:input.tag,tagger:Object.freeze(tagger),message:input.message,messageBytes:Buffer.byteLength(input.message,'utf8')});
110
+ }
@@ -0,0 +1,77 @@
1
+ import {encodeGitTree} from './git-commit-object.mjs';
2
+
3
+ // Pure flat-index -> tree-object assembly: no I/O, object lookup or ref updates.
4
+ // Only canonical regular-file modes are accepted; OIDs are lowercase, nonzero,
5
+ // full-width hex. Referenced blobs need not exist (and are never inspected).
6
+ // Paths must be strict UTF-8 strings, relative, slash-separated and <=4096 bytes.
7
+ // Empty/dot/dotdot/.git components, backslashes, colons and Unicode controls,
8
+ // format characters and line/paragraph separators are rejected.
9
+ // Conservative portable-name policy: sibling names must be distinct under
10
+ // NFC -> Unicode uppercase -> lowercase -> NFC. This deliberately rejects some
11
+ // Git-legal case/normalization aliases (including SS/ß); it is not an assertion
12
+ // of complete filesystem-specific Unicode case folding. Original bytes survive.
13
+ // Limits: 100000 entries; 64 path components (including the filename);
14
+ // 100001 trie nodes INCLUDING root, files and directories; 8 MiB aggregate tree
15
+ // bodies (not object headers). Root path is ''. Trees are deterministic raw-UTF8
16
+ // sibling-sorted postorder (children before parents), with root last, including
17
+ // one canonical empty root for empty input. Each output body owns its memory.
18
+ const MAX_ENTRIES=100000,MAX_PATH_BYTES=4096,MAX_DEPTH=64;
19
+ const MAX_NODES=100001,MAX_TREE_BYTES=8*1024*1024;
20
+ const fold=name=>name.normalize('NFC').toUpperCase().toLowerCase().normalize('NFC');
21
+
22
+ export function buildIndexTree(entries,{objectFormat='sha1'}={}){
23
+ if(objectFormat!=='sha1'&&objectFormat!=='sha256')throw Error('Unsupported Git object format');
24
+ if(!Array.isArray(entries))throw Error('Git index entries must be an array');
25
+ if(entries.length>MAX_ENTRIES)throw Error('Git index entry limit exceeded');
26
+ const oidLength=objectFormat==='sha1'?40:64;
27
+ const root={path:'',children:new Map(),folded:new Map()};
28
+ let nodes=1,totalBytes=0;
29
+ for(const entry of entries){
30
+ if(!entry||typeof entry!=='object')throw Error('Invalid Git index entry');
31
+ const {path,mode,oid}=entry;
32
+ if(typeof path!=='string')throw Error('Git index path must be a string');
33
+ if(path.length>MAX_PATH_BYTES)throw Error('Git index path byte limit exceeded');
34
+ const bytes=Buffer.from(path,'utf8');
35
+ if(bytes.toString('utf8')!==path)throw Error('Git index path must be strict UTF-8');
36
+ if(bytes.length>MAX_PATH_BYTES)throw Error('Git index path byte limit exceeded');
37
+ if(!path||/[\\:\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(path))throw Error('Unsafe Git index path');
38
+ const parts=path.split('/');
39
+ if(parts.length>MAX_DEPTH)throw Error('Git index path depth limit exceeded');
40
+ if(parts.some(part=>!part||part==='.'||part==='..'||fold(part)==='.git'))throw Error('Unsafe Git index path component');
41
+ if(mode!=='100644'&&mode!=='100755')throw Error('Unsupported Git index file mode');
42
+ if(typeof oid!=='string'||oid.length!==oidLength||/[^0-9a-f]/.test(oid)||/^0+$/.test(oid))throw Error('Invalid Git index object id');
43
+ let parent=root;
44
+ for(let i=0;i<parts.length;i++){
45
+ const name=parts[i],last=i===parts.length-1,key=fold(name);
46
+ const alias=parent.folded.get(key);
47
+ if(alias!==undefined&&alias!==name)throw Error('Git index casefold/normalization collision');
48
+ const existing=parent.children.get(name);
49
+ if(existing){
50
+ if(last){
51
+ if(existing.children)throw Error('Git index file-directory prefix collision');
52
+ throw Error('Duplicate Git index path');
53
+ }
54
+ if(!existing.children)throw Error('Git index file-directory prefix collision');
55
+ parent=existing;
56
+ continue;
57
+ }
58
+ if(++nodes>MAX_NODES)throw Error('Git index node limit exceeded');
59
+ const nodeMode=last?mode:'40000';
60
+ totalBytes+=nodeMode.length+2+Buffer.byteLength(name,'utf8')+oidLength/2;
61
+ if(totalBytes>MAX_TREE_BYTES)throw Error('Git index aggregate tree byte limit exceeded');
62
+ const node=last?{mode,oid}:{path:parts.slice(0,i+1).join('/'),children:new Map(),folded:new Map()};
63
+ parent.children.set(name,node);parent.folded.set(key,name);
64
+ parent=node;
65
+ }
66
+ }
67
+ const trees=[];
68
+ function encode(directory){
69
+ const children=[...directory.children].sort((a,b)=>Buffer.compare(Buffer.from(a[0]),Buffer.from(b[0])));
70
+ const encodedEntries=children.map(([name,node])=>({name,mode:node.children?'40000':node.mode,oid:node.children?encode(node):node.oid}));
71
+ const encoded=encodeGitTree(encodedEntries,{objectFormat});
72
+ const body=Buffer.alloc(encoded.body.length);encoded.body.copy(body);
73
+ trees.push({path:directory.path,oid:encoded.oid,body});
74
+ return encoded.oid;
75
+ }
76
+ return {root:encode(root),trees};
77
+ }
@@ -0,0 +1,64 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {parseVerifiedCommit} from './verified-commit.mjs';
3
+
4
+ const MAX_COMMIT_BYTES=2*1024*1024;
5
+ const nativeAborted=Object.getOwnPropertyDescriptor(AbortSignal.prototype,'aborted').get;
6
+ const nativeAbort=AbortSignal.prototype.throwIfAborted;
7
+ function owned(bytes){const copy=Buffer.alloc(bytes.length);Buffer.prototype.copy.call(bytes,copy);return copy;}
8
+ function record(value,keys,required,label){
9
+ if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw Error('Invalid lightweight tag plan '+label+' record');
10
+ const out=Object.create(null);
11
+ for(const key of Reflect.ownKeys(value)){
12
+ if(typeof key!=='string'||!keys.includes(key))throw Error('Unsupported lightweight tag plan '+label+' field');
13
+ const d=Object.getOwnPropertyDescriptor(value,key);
14
+ if(!d||!Object.hasOwn(d,'value'))throw Error('Lightweight tag plan '+label+' requires own data properties');
15
+ out[key]=d.value;
16
+ }
17
+ for(const key of required)if(!Object.hasOwn(out,key))throw Error('Missing lightweight tag plan '+label+' '+key);
18
+ return out;
19
+ }
20
+ function tagName(name){
21
+ if(typeof name!=='string'||!name||Buffer.from(name,'utf8').toString('utf8')!==name||Buffer.byteLength(name,'utf8')>1000||
22
+ name==='@'||name.toUpperCase()==='HEAD'||name.startsWith('-')||name.startsWith('refs/')||/[\x00-\x20\x7f~^:?*\[\\<>"|\p{Cc}\p{Cf}]/u.test(name)||name.includes('..')||name.includes('@{')||
23
+ 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)))throw Error('Safe portable short tag name required');
24
+ return name;
25
+ }
26
+ function abortCheck(signal){
27
+ if(signal===undefined)return ()=>{};
28
+ let native=false;try{Reflect.apply(nativeAborted,signal,[]);native=true;}catch{}
29
+ if(native)return ()=>Reflect.apply(nativeAbort,signal,[]);
30
+ const s=record(signal,['aborted','throwIfAborted'],[],'signal');
31
+ if(s.aborted!==undefined&&typeof s.aborted!=='boolean'||s.throwIfAborted!==undefined&&typeof s.throwIfAborted!=='function')throw Error('Invalid lightweight tag plan signal');
32
+ return ()=>{if(s.aborted){const e=Error('Lightweight tag verification aborted');e.name='AbortError';throw e;}if(s.throwIfAborted)Reflect.apply(s.throwIfAborted,signal,[]);};
33
+ }
34
+
35
+ // Pure synchronous plan over a raw commit BODY, not an object envelope. Capture the
36
+ // bounded Buffer with an intrinsic copy before any input descriptor/prototype traps.
37
+ // Exact own-data plain/null-prototype inputs require target/name; only objectFormat
38
+ // and signal are optional. Local name validation mirrors git-tag-object's portable
39
+ // 1000/255 UTF-8 byte policy without constructing any annotated tag object.
40
+ // All scalars are validated before the first callback. Native signals use captured
41
+ // intrinsics; cooperative own-data signals are snapshotted (no caller getters).
42
+ // Callbacks are trusted; this does not promise hostile Proxy isolation.
43
+ // Authenticates commit syntax/hash only: NOT ref absence, repository authorization,
44
+ // freshness or referenced-object existence. No I/O, object creation or publication.
45
+ // The exact frozen result contains no bodies, Buffers, parents or mutable records.
46
+ export function createVerifiedLightweightTagPlan(commitBody,inputs={}){
47
+ if(!Buffer.isBuffer(commitBody))throw Error('Git commit body must be a Buffer');
48
+ if(commitBody.length>MAX_COMMIT_BYTES)throw Error('Git commit body byte limit exceeded');
49
+ const body=owned(commitBody);
50
+ const r=record(inputs,['objectFormat','target','name','signal'],['target','name'],'input');
51
+ const objectFormat=r.objectFormat===undefined?'sha1':r.objectFormat,target=r.target,name=tagName(r.name);
52
+ if(objectFormat!=='sha1'&&objectFormat!=='sha256')throw Error('Unsupported Git object format');
53
+ const width=objectFormat==='sha1'?40:64;
54
+ if(typeof target!=='string'||target.length!==width||/[^0-9a-f]/.test(target)||/^0+$/.test(target))throw Error('Invalid Git object id');
55
+ const check=abortCheck(r.signal);
56
+ // Adapt the existing parser's legacy aborted read to captured cancellation policy.
57
+ const signal={get aborted(){check();return false;}};
58
+ const verified=parseVerifiedCommit(body,{oid:target,objectFormat,signal});
59
+ check();
60
+ const ref='refs/tags/'+name;
61
+ // JSON tuple framing is unambiguous; authenticated target already binds its tree.
62
+ const id=createHash('sha256').update(JSON.stringify(['dsh-vcs:lightweight-tag-plan:v1',objectFormat,ref,verified.oid]),'utf8').digest('hex');
63
+ return Object.freeze({id,action:'lightweight-tag-create',objectFormat,name,ref,target:verified.oid,targetTree:verified.tree});
64
+ }