@xlinklight/publishing 3.3.0 → 3.3.1

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 (80) hide show
  1. package/README.md +1 -1
  2. package/dist/src/acceptance-delivery-binding.js +59 -0
  3. package/dist/src/acceptance.js +79 -0
  4. package/dist/src/client.js +146 -0
  5. package/dist/src/index.js +3 -0
  6. package/dist/src/node/acceptance-delivery.js +88 -0
  7. package/dist/src/node/activation.js +3 -0
  8. package/dist/src/node/authorization.js +76 -0
  9. package/dist/src/node/cli.js +20 -0
  10. package/dist/src/node/index.js +9 -0
  11. package/dist/src/node/journal.js +282 -0
  12. package/dist/src/node/publishing-command.js +220 -0
  13. package/dist/src/node/session.js +223 -0
  14. package/dist/src/node/solution-package.js +217 -0
  15. package/dist/src/node/source-error.js +15 -0
  16. package/dist/src/node/source-producer.js +145 -0
  17. package/dist/src/node/workflow.js +455 -0
  18. package/dist/src/package.js +74 -0
  19. package/dist/src/protocol.js +105 -0
  20. package/dist/src/shared/activation.js +111 -0
  21. package/dist/src/shared/records.js +26 -0
  22. package/dist/src/worker/activation.js +10 -0
  23. package/dist/src/worker/index.js +6 -0
  24. package/dist/src/worker/journal.js +301 -0
  25. package/dist/src/worker/package.js +116 -0
  26. package/dist/src/worker/release.js +59 -0
  27. package/dist/src/worker/runtime.js +98 -0
  28. package/dist/src/worker/service.js +494 -0
  29. package/package.json +17 -14
  30. package/{src/acceptance.d.mts → types/acceptance.d.ts} +2 -2
  31. package/{src/client.d.mts → types/client.d.ts} +1 -1
  32. package/{src/index.d.mts → types/index.d.ts} +6 -6
  33. package/{src/node/acceptance-delivery.d.mts → types/node/acceptance-delivery.d.ts} +1 -1
  34. package/{src/node/activation.d.mts → types/node/activation.d.ts} +4 -4
  35. package/{src/node/authorization.d.mts → types/node/authorization.d.ts} +4 -4
  36. package/types/node/index.d.ts +17 -0
  37. package/{src/node/publishing-command.d.mts → types/node/publishing-command.d.ts} +4 -4
  38. package/{src/node/session.d.mts → types/node/session.d.ts} +7 -7
  39. package/{src/node/solution-package.d.mts → types/node/solution-package.d.ts} +2 -2
  40. package/{src/node/workflow.d.mts → types/node/workflow.d.ts} +7 -7
  41. package/{src/protocol.d.mts → types/protocol.d.ts} +1 -1
  42. package/{src/worker/activation.d.mts → types/worker/activation.d.ts} +3 -3
  43. package/types/worker/index.d.ts +6 -0
  44. package/{src/worker/package.d.mts → types/worker/package.d.ts} +2 -2
  45. package/{src/worker/release.d.mts → types/worker/release.d.ts} +3 -3
  46. package/{src/worker/runtime.d.mts → types/worker/runtime.d.ts} +2 -2
  47. package/{src/worker/service.d.mts → types/worker/service.d.ts} +7 -7
  48. package/src/acceptance-delivery-binding.mjs +0 -49
  49. package/src/acceptance.mjs +0 -67
  50. package/src/client.mjs +0 -74
  51. package/src/index.mjs +0 -3
  52. package/src/node/acceptance-delivery.mjs +0 -70
  53. package/src/node/activation.mjs +0 -3
  54. package/src/node/authorization.mjs +0 -49
  55. package/src/node/cli.mjs +0 -12
  56. package/src/node/index.d.mts +0 -17
  57. package/src/node/index.mjs +0 -9
  58. package/src/node/journal.mjs +0 -135
  59. package/src/node/publishing-command.mjs +0 -104
  60. package/src/node/session.mjs +0 -134
  61. package/src/node/solution-package.mjs +0 -113
  62. package/src/node/source-error.mjs +0 -9
  63. package/src/node/source-producer.mjs +0 -103
  64. package/src/node/workflow.mjs +0 -320
  65. package/src/package.mjs +0 -36
  66. package/src/protocol.mjs +0 -50
  67. package/src/shared/activation.mjs +0 -64
  68. package/src/worker/activation.mjs +0 -4
  69. package/src/worker/index.d.mts +0 -6
  70. package/src/worker/index.mjs +0 -6
  71. package/src/worker/journal.mjs +0 -151
  72. package/src/worker/package.mjs +0 -32
  73. package/src/worker/release.mjs +0 -21
  74. package/src/worker/runtime.mjs +0 -23
  75. package/src/worker/service.mjs +0 -251
  76. /package/{src/node/journal.d.mts → types/node/journal.d.ts} +0 -0
  77. /package/{src/node/source-error.d.mts → types/node/source-error.d.ts} +0 -0
  78. /package/{src/package.d.mts → types/package.d.ts} +0 -0
  79. /package/{src/shared/activation.d.mts → types/shared/activation.d.ts} +0 -0
  80. /package/{src/worker/journal.d.mts → types/worker/journal.d.ts} +0 -0
@@ -1,135 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import path from 'node:path';
3
- import {randomUUID,createHash} from 'node:crypto';
4
- import {isDeepStrictEqual} from 'node:util';
5
- import {DatabaseSync} from 'node:sqlite';
6
- import {validatePortableRelativePath} from '@openge/forge-path-safety';
7
- import {GeneratedArtifactError,generatedArtifactErrorCodes} from '@openge/forge-generated-artifacts';
8
- import {publishingError,protocolRecord,publishingRequestId,publishingDigest} from '../protocol.mjs';
9
-
10
- const fail=code=>publishingError('JOURNAL_'+code);
11
- const keyValid=value=>typeof value==='string'&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,191}$/.test(value);
12
- const recordBytes=(key,revision,payload)=>Buffer.byteLength('{"key":'+JSON.stringify(key)+',"revision":'+revision+',"payload":'+payload+'}');
13
- function storageFailure(error){
14
- if(typeof error?.code==='string'&&error.code.startsWith('PUBLISHING_'))throw error;
15
- throw fail([5,6].includes(error?.errcode)?'BUSY':'STORAGE_UNKNOWN');
16
- }
17
- function checkedLimits(value){
18
- if(!protocolRecord(value,['maximumBytes','maximumRecords','maximumRecordBytes','maximumBlobs','maximumBlobBytes','minimumFreeBytes'])||!Object.values(value).every(Number.isSafeInteger)||value.maximumBytes<65536||value.maximumBytes>1073741824||value.maximumRecords<1||value.maximumRecords>4096||value.maximumRecordBytes<1||value.maximumRecordBytes>1048576||value.maximumBlobs<1||value.maximumBlobs>32768||value.maximumBlobBytes<1||value.maximumBlobBytes>134217728||value.minimumFreeBytes<0)throw fail('LIMIT_INVALID');return {...value};
19
- }
20
- const occupied=error=>error instanceof GeneratedArtifactError&&error.code===generatedArtifactErrorCodes.destinationOccupied&&error.details.cleanupFailed!==true;
21
- async function capacity(root,limits){
22
- const info=await fs.statfs(root,{bigint:true});
23
- if(info.bavail*info.bsize<BigInt(limits.minimumFreeBytes)+BigInt(limits.maximumBytes)*2n+65536n)throw fail('CAPACITY_REQUIRED');
24
- }
25
- async function markerBytes(file){
26
- const before=await fs.lstat(file,{bigint:true});
27
- if(!before.isFile()||before.isSymbolicLink()||before.nlink!==1n||before.size>4096n||await fs.realpath(file)!==file)throw fail('OWNERSHIP_INVALID');
28
- const body=await fs.readFile(file),after=await fs.lstat(file,{bigint:true});
29
- if(body.byteLength>4096||['dev','ino','size','mtimeNs','ctimeNs'].some(key=>before[key]!==after[key]))throw fail('OWNERSHIP_INVALID');
30
- try{return JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(body));}catch{throw fail('OWNERSHIP_INVALID');}
31
- }
32
-
33
- /** SQLite owns CAS; Foundation owns durable publication of the directory/owner bytes. */
34
- export async function openPublishingJournal({root,directory,filesystem,limits,signal}){
35
- signal?.throwIfAborted();limits=checkedLimits(limits);
36
- if(typeof root!=='string'||!path.isAbsolute(root)||!filesystem||typeof filesystem.ensureDirectory!=='function'||typeof filesystem.publishBytes!=='function')throw fail('INPUT_INVALID');
37
- root=path.resolve(root);const rootInfo=await fs.lstat(root,{bigint:true});
38
- if(!rootInfo.isDirectory()||rootInfo.isSymbolicLink()||await fs.realpath(root)!==root)throw fail('BOUNDARY');
39
- try{directory=validatePortableRelativePath(directory);}catch{throw fail('BOUNDARY');}
40
- await capacity(root,limits);signal?.throwIfAborted();
41
- try{await filesystem.ensureDirectory(root,directory);}catch{throw fail('PERSISTENCE_UNKNOWN');}
42
- const absolute=path.join(root,...directory.split('/')),markerFile=path.join(absolute,'owner.json'),databaseFile=path.join(absolute,'journal.sqlite');
43
- const context={schemaVersion:1,root:{dev:String(rootInfo.dev),ino:String(rootInfo.ino)},directory,limits};
44
- let marker;
45
- try{marker=await markerBytes(markerFile);}catch(error){
46
- if(error.code!=='ENOENT')throw error;
47
- if((await fs.readdir(absolute)).length)throw fail('OCCUPIED');
48
- const value={...context,ownerId:randomUUID()};
49
- try{await filesystem.publishBytes(root,directory+'/owner.json',new TextEncoder().encode(JSON.stringify(value)+'\n'),{mode:'exclusive'});}
50
- catch(error){if(!occupied(error))throw fail('PERSISTENCE_UNKNOWN');}
51
- marker=await markerBytes(markerFile);
52
- }
53
- if(!protocolRecord(marker,['schemaVersion','root','directory','limits','ownerId'])||!publishingRequestId(marker.ownerId)||!isDeepStrictEqual({...marker,ownerId:undefined},{...context,ownerId:undefined}))throw fail('CONTEXT_CHANGED');
54
- const allowed=new Set(['owner.json','journal.sqlite','journal.sqlite-journal']);let retained=0;
55
- for(const name of await fs.readdir(absolute)){
56
- if(!allowed.has(name))throw fail('OCCUPIED');const file=path.join(absolute,name),info=await fs.lstat(file);
57
- if(!info.isFile()||info.isSymbolicLink()||info.nlink!==1||await fs.realpath(file)!==file)throw fail('BOUNDARY');retained+=info.size;
58
- }
59
- if(retained>limits.maximumBytes*2+65536)throw fail('BYTE_LIMIT');
60
- try{await fs.lstat(databaseFile);}catch(error){
61
- if(error.code!=='ENOENT')throw error;
62
- try{await filesystem.publishBytes(root,directory+'/journal.sqlite',new Uint8Array(),{mode:'exclusive'});}
63
- catch(error){if(!occupied(error))throw fail('PERSISTENCE_UNKNOWN');}
64
- }
65
- signal?.throwIfAborted();let database;
66
- try{
67
- database=new DatabaseSync(databaseFile,{enableForeignKeyConstraints:true,enableDoubleQuotedStringLiterals:false,allowExtension:false});
68
- const tables=database.prepare("SELECT name FROM sqlite_schema WHERE type='table' AND substr(name,1,7)<>'sqlite_' ORDER BY name").all().map(row=>row.name);
69
- if(tables.length===0){
70
- database.exec('PRAGMA journal_mode=DELETE;PRAGMA synchronous=FULL;PRAGMA temp_store=MEMORY;');
71
- database.exec('BEGIN IMMEDIATE');
72
- try{
73
- database.exec('CREATE TABLE journal_metadata (id INTEGER PRIMARY KEY CHECK(id=1),payload TEXT NOT NULL) STRICT;CREATE TABLE journal_records (key TEXT PRIMARY KEY,revision INTEGER NOT NULL CHECK(revision>0),payload TEXT NOT NULL) STRICT;CREATE TABLE journal_blobs (sha256 TEXT PRIMARY KEY,byte_length INTEGER NOT NULL CHECK(byte_length>=0),bytes BLOB NOT NULL) STRICT;');
74
- database.prepare('INSERT INTO journal_metadata(id,payload) VALUES(1,?)').run(JSON.stringify(marker));database.exec('COMMIT');
75
- }catch(error){try{database.exec('ROLLBACK');}catch{}throw error;}
76
- }else if(tables.join(',')!=='journal_blobs,journal_metadata,journal_records')throw fail('OWNERSHIP_INVALID');
77
- const stored=database.prepare('SELECT payload FROM journal_metadata WHERE id=1').get();
78
- if(!stored||!isDeepStrictEqual(JSON.parse(stored.payload),marker))throw fail('OWNERSHIP_INVALID');
79
- database.exec('PRAGMA journal_mode=DELETE;PRAGMA synchronous=FULL;PRAGMA foreign_keys=ON;PRAGMA trusted_schema=OFF;PRAGMA temp_store=MEMORY;PRAGMA busy_timeout=0;');
80
- const pages=Math.floor(limits.maximumBytes/4096);database.exec('PRAGMA max_page_count='+pages);
81
- if(Number(database.prepare('PRAGMA page_size').get().page_size)!==4096||Number(database.prepare('PRAGMA max_page_count').get().max_page_count)!==pages)throw fail('BYTE_LIMIT');
82
- await filesystem.ensureDirectory(root,directory);signal?.throwIfAborted();
83
- }catch(error){try{database?.close();}catch{}storageFailure(error);}
84
- let closed=false;
85
- const ready=()=>{if(closed)throw fail('CLOSED');};
86
- const load=async(key,{signal}={})=>{
87
- ready();signal?.throwIfAborted();if(!keyValid(key))throw fail('KEY_INVALID');
88
- const row=database.prepare('SELECT revision,payload FROM journal_records WHERE key=?').get(key);
89
- if(!row)return undefined;
90
- if(!Number.isSafeInteger(row.revision)||row.revision<1||recordBytes(key,row.revision,row.payload)>limits.maximumRecordBytes)throw fail('RECORD_INVALID');
91
- let payload;try{payload=JSON.parse(row.payload);}catch{throw fail('RECORD_INVALID');}
92
- return {revision:row.revision,payload};
93
- };
94
- const readBlob=async({sha256,byteLength},{signal}={})=>{
95
- ready();signal?.throwIfAborted();if(!publishingDigest(sha256)||!Number.isSafeInteger(byteLength)||byteLength<0||byteLength>limits.maximumBlobBytes)throw fail('BLOB_INVALID');
96
- const row=database.prepare('SELECT byte_length,bytes FROM journal_blobs WHERE sha256=?').get(sha256);
97
- if(!row)return undefined;
98
- if(row.byte_length!==byteLength||row.bytes.byteLength!==byteLength||createHash('sha256').update(row.bytes).digest('hex')!==sha256)throw fail('BLOB_INVALID');return new Uint8Array(row.bytes);
99
- };
100
- const compareAndSet=async({key,expectedRevision,payload,blobs=[]},{signal}={})=>{
101
- ready();signal?.throwIfAborted();if(!keyValid(key)||!Number.isSafeInteger(expectedRevision)||expectedRevision<0||expectedRevision===Number.MAX_SAFE_INTEGER)throw fail('RECORD_INVALID');
102
- let encoded;try{encoded=JSON.stringify(payload);}catch{throw fail('RECORD_INVALID');}
103
- if(typeof encoded!=='string')throw fail('RECORD_INVALID');if(recordBytes(key,expectedRevision+1,encoded)>limits.maximumRecordBytes)throw fail('BYTE_LIMIT');
104
- if(!Array.isArray(blobs)||blobs.length>limits.maximumBlobs)throw fail('BLOB_LIMIT');
105
- const snapshots=[];let blobBytes=0;
106
- for(const blob of blobs){
107
- if(!protocolRecord(blob,['sha256','bytes'])||!publishingDigest(blob.sha256)||!(blob.bytes instanceof Uint8Array)||blob.bytes.byteLength>limits.maximumBlobBytes)throw fail('BLOB_INVALID');
108
- blobBytes+=blob.bytes.byteLength;if(blobBytes>limits.maximumBytes)throw fail('BYTE_LIMIT');
109
- const bytes=new Uint8Array(blob.bytes);if(createHash('sha256').update(bytes).digest('hex')!==blob.sha256)throw fail('BLOB_INVALID');snapshots.push({sha256:blob.sha256,bytes});
110
- }
111
- await capacity(root,limits);ready();signal?.throwIfAborted();
112
- try{database.exec('BEGIN IMMEDIATE');}catch(error){storageFailure(error);}
113
- try{
114
- const row=database.prepare('SELECT revision FROM journal_records WHERE key=?').get(key);
115
- if((row?.revision??0)!==expectedRevision){database.exec('ROLLBACK');return 'conflict';}
116
- if(!row&&Number(database.prepare('SELECT count(*) AS amount FROM journal_records').get().amount)>=limits.maximumRecords)throw fail('RECORD_LIMIT');
117
- for(const blob of snapshots){
118
- const existing=database.prepare('SELECT byte_length,bytes FROM journal_blobs WHERE sha256=?').get(blob.sha256);
119
- if(existing){if(existing.byte_length!==blob.bytes.byteLength||!Buffer.from(existing.bytes).equals(blob.bytes))throw fail('BLOB_INVALID');}
120
- else database.prepare('INSERT INTO journal_blobs(sha256,byte_length,bytes) VALUES(?,?,?)').run(blob.sha256,blob.bytes.byteLength,blob.bytes);
121
- }
122
- if(Number(database.prepare('SELECT count(*) AS amount FROM journal_blobs').get().amount)>limits.maximumBlobs)throw fail('BLOB_LIMIT');
123
- database.prepare('INSERT INTO journal_records(key,revision,payload) VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET revision=excluded.revision,payload=excluded.payload').run(key,expectedRevision+1,encoded);
124
- database.exec('COMMIT');return 'stored';
125
- }catch(error){try{database.exec('ROLLBACK');}catch{}storageFailure(error);}
126
- };
127
- return Object.freeze({
128
- load,readBlob,compareAndSet,
129
- operationJournal(){return {
130
- async load(requestId,context){if(!keyValid(requestId))throw fail('KEY_INVALID');const record=await load('operation:'+requestId,context);if(record&&record.payload?.revision!==record.revision)throw fail('RECORD_INVALID');return record?.payload;},
131
- async compareAndSet({expectedRevision,next},context){if(!next?.binding||!keyValid(next.binding.requestId)||next.revision!==expectedRevision+1)throw fail('RECORD_INVALID');return compareAndSet({key:'operation:'+next.binding.requestId,expectedRevision,payload:next},context);},
132
- };},
133
- close(){if(!closed){database.close();closed=true;}},
134
- });
135
- }
@@ -1,104 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import path from 'node:path';
3
- import {createLinuxDurableArtifactFilesystem,createWindowsNtfsDurableArtifactFilesystem} from '@openge/forge-generated-artifacts/node';
4
- import {validatePortableRelativePath} from '@openge/forge-path-safety';
5
- import {parsePublishingConfiguration,protocolRecord,publishingError,publishingRequestId} from '../protocol.mjs';
6
- import {openPublishingJournal} from './journal.mjs';
7
- import {installPublishingAuthorization,loadPublishingAuthorization} from './authorization.mjs';
8
- import {createPublishingWorkflow} from './workflow.mjs';
9
- import {defaultProducer} from './source-producer.mjs';
10
-
11
- const commands=['credentials','check','publish','status','recover','verify','abandon'];
12
- const journalLimits=Object.freeze({maximumBytes:536870912,maximumRecords:256,maximumRecordBytes:1048576,maximumBlobs:12000,maximumBlobBytes:134217728,minimumFreeBytes:67108864});
13
- const fail=code=>publishingError(code);
14
- function parse(args){
15
- if(!Array.isArray(args)||!args.length||args.some(value=>typeof value!=='string'||!value||value.includes('\0')||value.length>4096))throw fail('CLI_ARGUMENT_INVALID');
16
- if(args.length===1&&args[0]==='--help')return {command:'help'};
17
- const command=args[0];if(!commands.includes(command))throw fail('CLI_ARGUMENT_INVALID');
18
- const selected={command},seen=new Set();
19
- for(let index=1;index<args.length;index++){
20
- const flag=args[index];if(seen.has(flag))throw fail('CLI_ARGUMENT_INVALID');seen.add(flag);
21
- if(['--root','--state','--producer'].includes(flag)){
22
- const value=args[++index];if(!value||value.startsWith('--')||flag==='--producer'&&!['check','publish'].includes(command))throw fail('CLI_ARGUMENT_INVALID');selected[flag.slice(2)]=value;
23
- }else if(flag==='--stdin'&&command==='credentials')selected.stdin=true;
24
- else if(flag==='--no-wait'&&command==='publish')selected.waitMs=0;
25
- else if(flag==='--wait-ms'&&command==='publish'){
26
- const value=args[++index];if(!/^[1-9]\d{0,6}$/.test(value??'')||Number(value)>3600000)throw fail('CLI_ARGUMENT_INVALID');selected.waitMs=Number(value);
27
- }
28
- else if(flag==='--replace-credential'&&command==='credentials')selected.replaceCredential=true;
29
- else if(flag==='--new-preparation'&&['check','publish'].includes(command))selected.newPreparation=true;
30
- else throw fail('CLI_ARGUMENT_INVALID');
31
- }
32
- if(command==='credentials'&&!selected.stdin)throw fail('CLI_ARGUMENT_INVALID');
33
- if(seen.has('--no-wait')&&seen.has('--wait-ms'))throw fail('CLI_ARGUMENT_INVALID');
34
- for(const key of ['state','producer'])if(selected[key]!==undefined){try{if(validatePortableRelativePath(selected[key])!==selected[key]||key==='producer'&&!selected[key].endsWith('.mjs'))throw Error();}catch{throw fail('CLI_ARGUMENT_INVALID');}}
35
- return selected;
36
- }
37
- async function credentialInput(stdin,signal,timeoutMilliseconds){
38
- if(!stdin||stdin.isTTY===true||['on','off','destroy','resume'].some(name=>typeof stdin[name]!=='function'))throw fail('CREDENTIAL_INPUT_NON_TTY_REQUIRED');
39
- if(!Number.isSafeInteger(timeoutMilliseconds)||timeoutMilliseconds<1||timeoutMilliseconds>300000)throw fail('CREDENTIAL_INPUT_LIMIT_INVALID');
40
- const chunks=[];let bytes=0,timer,abort,data,end,error,close;
41
- let closedListener;const closed=stdin.closed?Promise.resolve(true):new Promise(resolve=>{closedListener=()=>resolve(true);stdin.once('close',closedListener);});
42
- try{
43
- if(signal?.aborted)throw fail('CREDENTIAL_INPUT_CANCELLED');
44
- await new Promise((resolve,reject)=>{
45
- let settled=false;const rejectOnce=code=>{if(!settled){settled=true;reject(fail(code));}};
46
- data=value=>{if(settled)return;if(!(value instanceof Uint8Array)&&typeof value!=='string')return rejectOnce('CREDENTIAL_INPUT_INVALID');const chunk=Buffer.from(value);bytes+=chunk.byteLength;if(bytes>16384)return rejectOnce('CREDENTIAL_INPUT_BYTE_LIMIT');chunks.push(chunk);};
47
- end=()=>{if(!settled){settled=true;resolve();}};error=()=>rejectOnce('CREDENTIAL_INPUT_INVALID');close=()=>rejectOnce('CREDENTIAL_INPUT_CLOSED');abort=()=>rejectOnce('CREDENTIAL_INPUT_CANCELLED');
48
- stdin.on('data',data);stdin.once('end',end);stdin.once('error',error);stdin.once('close',close);signal?.addEventListener('abort',abort,{once:true});timer=setTimeout(()=>rejectOnce('CREDENTIAL_INPUT_TIMEOUT'),timeoutMilliseconds);stdin.resume();
49
- });
50
- let value;try{value=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks)));}catch{throw fail('CREDENTIAL_INPUT_INVALID');}
51
- if(!protocolRecord(value,['configuration','credential'],['acceptanceDelivery'])||typeof value.credential!=='string'||!/^[A-Za-z0-9_-]{32,4096}$/.test(value.credential))throw fail('CREDENTIAL_INPUT_INVALID');return value;
52
- }catch(error){if(typeof error?.code==='string'&&error.code.startsWith('PUBLISHING_CREDENTIAL_INPUT_'))throw error;throw fail(signal?.aborted?'CREDENTIAL_INPUT_CANCELLED':'CREDENTIAL_INPUT_INVALID');}
53
- finally{
54
- clearTimeout(timer);if(abort)signal?.removeEventListener('abort',abort);
55
- for(const [name,listener]of [['data',data],['end',end],['error',error],['close',close]])if(listener)stdin.off(name,listener);
56
- // Explicit credential input is owned by this call, including blocked pipes.
57
- stdin.destroy();let closureTimer;
58
- try{if(!await Promise.race([closed,new Promise(resolve=>{closureTimer=setTimeout(()=>resolve(false),1000);})]))throw fail('CREDENTIAL_INPUT_CLOSURE_UNKNOWN');}
59
- finally{clearTimeout(closureTimer);if(closedListener)stdin.off('close',closedListener);}
60
- }
61
- }
62
- function diagnostic(error){
63
- const code=typeof error?.code==='string'&&/^PUBLISHING_[A-Z0-9_]{1,96}$/.test(error.code)?error.code:'PUBLISHING_COMMAND_FAILED';return {error:{code}};
64
- }
65
-
66
- /** Bounded one-shot CLI. No token, private producer cause, provider output or
67
- * environment is returned. Callers own private storage ACLs and backup policy. */
68
- async function executeCommand(selected,options){
69
- let journal;
70
- try{
71
- const {signal,allowLoopback=false,request,clientLimits,metadataTransport}=options;
72
- const input=selected.command==='credentials'?await credentialInput(options.stdin??process.stdin,signal,options.credentialInputTimeoutMilliseconds??30000):undefined;
73
- if(input)input.configuration=parsePublishingConfiguration(input.configuration,{allowLoopback});
74
- signal?.throwIfAborted();const root=path.resolve(options.cwd??process.cwd(),selected.root??'.'),info=await fs.lstat(root);
75
- if(!info.isDirectory()||info.isSymbolicLink()||await fs.realpath(root)!==root)throw fail('CLI_ROOT_INVALID');
76
- const filesystem=options.filesystem??await(process.platform==='win32'?createWindowsNtfsDurableArtifactFilesystem():process.platform==='linux'?createLinuxDurableArtifactFilesystem():Promise.reject(fail('CLI_PLATFORM_UNSUPPORTED')));
77
- journal=await openPublishingJournal({root,directory:selected.state??'state/solution-publishing',filesystem,limits:options.journalLimits??journalLimits,signal});
78
- const shared={journal,allowLoopback,...(request?{request}:{}),...(clientLimits?{clientLimits}:{}),signal};
79
- if(input){
80
- const installed=await installPublishingAuthorization({...shared,...input,replaceCredential:selected.replaceCredential===true});
81
- return {exitCode:0,output:{state:installed.status.toLowerCase(),projectId:installed.projectId,policyRevision:installed.policyRevision}};
82
- }
83
- const authorization=await loadPublishingAuthorization(shared);if(!authorization)throw fail('CREDENTIAL_REQUIRED');
84
- const workflow=createPublishingWorkflow({...shared,...authorization,root,...(metadataTransport?{metadataTransport}:{}),...(options.operationLimits?{operationLimits:options.operationLimits}:{})});
85
- let result;
86
- try{
87
- result=await workflow[selected.command]({signal,...(selected.producer?{producer:selected.producer}:{}),...(selected.newPreparation?{newPreparation:true}:{}),...(selected.command==='publish'?{waitMs:selected.waitMs??300000}:{})});
88
- }catch(error){
89
- const code=diagnostic(error).error.code;
90
- const ambiguous=code.endsWith('_UNKNOWN')||['PUBLISHING_SERVICE_UNREACHABLE','PUBLISHING_PROVIDER_FAILED','PUBLISHING_BUSY'].includes(code)||error?.name==='TimeoutError';
91
- const requestId=error?.requestId??(await journal.load('active:'+authorization.configuration.projectId))?.payload?.requestId;
92
- if(!publishingRequestId(requestId))throw error;
93
- return {exitCode:ambiguous?3:1,output:{...(ambiguous?{state:'unknown',active:false}:{}),requestId,error:{code}}};
94
- }
95
- const exitCode=result.state==='active'||selected.command==='check'&&result.state==='checked'||selected.command==='abandon'&&result.state==='abandoned'?0:result.state==='failed'?1:3;
96
- return {exitCode,output:result};
97
- }finally{try{journal?.close();}catch{throw fail('JOURNAL_CLOSURE_UNKNOWN');}}
98
- }
99
-
100
- export async function runPublishingCommand(args,options={}){
101
- let selected;try{selected=parse(args);}catch{return {exitCode:2,output:{error:{code:'PUBLISHING_CLI_ARGUMENT_INVALID'}}};}
102
- if(selected.command==='help')return {exitCode:0,output:{commands,sourceProducer:defaultProducer,stateDirectory:'state/solution-publishing',publishWaitMs:300000,publishOptions:['--no-wait','--wait-ms <1..3600000>']}};
103
- try{return await executeCommand(selected,options);}catch(error){return {exitCode:1,output:diagnostic(error)};}
104
- }
@@ -1,134 +0,0 @@
1
- import {createHash} from 'node:crypto';
2
- import {bindArtifactOperation,performArtifactOperation,observeArtifactOperation} from '@openge/forge-artifact-publish';
3
- import {createPublishingClient} from '../client.mjs';
4
- import {parsePublishingConfiguration,parsePublishingIntent,publishingIntentBytes,publishingRequestId,protocolRecord,publishingError} from '../protocol.mjs';
5
- import {verifySolutionPackageBytes} from './solution-package.mjs';
6
- import {maximumAcceptanceArchiveBytes} from './acceptance-delivery.mjs';
7
- import {publishingDigest} from '../protocol.mjs';
8
-
9
- const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
10
- const encoded=value=>new TextEncoder().encode(JSON.stringify(value));
11
- const fail=code=>publishingError(code);
12
- function validAcceptanceTarget(target){
13
- if(!protocolRecord(target,['origin','keyId','publicKeySha256'])||typeof target.origin!=='string'||!publishingDigest(target.publicKeySha256)||
14
- typeof target.keyId!=='string'||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(target.keyId))return false;
15
- const origin=URL.parse(target.origin);return origin?.protocol==='https:'&&origin.origin===target.origin;
16
- }
17
- const operationDefaults={timeoutMilliseconds:30000,closeTimeoutMilliseconds:2000};
18
- function checkBinding(intent,prepared,configuration){
19
- const item=intent.package,descriptor=prepared.descriptor;
20
- if(intent.projectId!==configuration.projectId||item.publisherId!==configuration.publisher.publisherId||['solutionId','publisherId','packageName','version'].some(key=>item[key]!==descriptor[key])||item.fileCount!==prepared.files.length||item.totalBytes!==prepared.payloadBytes||item.content.manifestSha256!==prepared.content.manifestSha256)throw fail('PACKAGE_BINDING_INVALID');
21
- }
22
- function transportFor({client,intent,manifestBytes,target,configurationSha256,stage}){
23
- const pending=new Set(),controller=new AbortController();let status,closed=false;
24
- const run=(signal,execute)=>{
25
- if(closed)throw fail('TRANSPORT_CLOSED');
26
- const promise=Promise.resolve().then(()=>execute(AbortSignal.any([signal,controller.signal])));pending.add(promise);const settled=()=>pending.delete(promise);promise.then(settled,settled);return promise;
27
- };
28
- return {transport:{
29
- target,capability:stage==='create'?'artifact-upload':'deployment-create',configurationSha256,
30
- async execute(_binding,context){
31
- try{await run(context.signal,async signal=>{status=await(stage==='create'?client.createRequest({intent,manifestBytes,signal}):client.queueRequest({intent,signal}));});}
32
- catch(error){if(stage==='create'&&error?.code==='PUBLISHING_CONFLICT')return {state:'rejected',code:'CONFLICT'};throw error;}
33
- return {state:'accepted',reference:intent.requestId};
34
- },
35
- async observe(binding,_reference,context){
36
- try{await run(context.signal,async signal=>{status=await client.getStatus({intent,signal});});}
37
- catch(error){if(error.code==='PUBLISHING_REQUEST_NOT_FOUND')return {state:'absent',fingerprint:binding.fingerprint};throw error;}
38
- const state=stage==='create'?'succeeded':status.state==='uploading'?'pending':status.state==='unknown'?'unknown':['failed','abandoned','superseded'].includes(status.state)?'failed':'succeeded';
39
- return {state,fingerprint:binding.fingerprint,reference:intent.requestId};
40
- },
41
- async close({timeoutMilliseconds}){
42
- closed=true;controller.abort();let timer;
43
- try{await Promise.race([Promise.allSettled([...pending]),new Promise(resolve=>{timer=setTimeout(resolve,timeoutMilliseconds);})]);}
44
- finally{clearTimeout(timer);}
45
- return {status:pending.size?'unconfirmed':'closed',activeRequests:pending.size};
46
- },
47
- },status:()=>status};
48
- }
49
-
50
- /** A project session holds no deployment-provider credential and never evaluates payloads. */
51
- export function createPublishingSession({journal,configuration,credential,allowLoopback=false,request,clientLimits,verifyActivation,packageLimits,pathCaseSensitivity,operationLimits=operationDefaults}){
52
- const config=parsePublishingConfiguration(configuration,{allowLoopback}),configurationSha256=hash(encoded(config)),selectedLimits={...packageLimits},selectedOperations={...operationLimits},selectedClientLimits=clientLimits?{...clientLimits}:undefined;
53
- if(!journal||['load','compareAndSet','readBlob','operationJournal'].some(name=>typeof journal[name]!=='function')||!['case-sensitive','case-insensitive'].includes(pathCaseSensitivity))throw fail('SESSION_INPUT_INVALID');
54
- const client=createPublishingClient({configuration:config,credential,allowLoopback,...(request?{request}:{}),...(selectedClientLimits?{limits:selectedClientLimits}:{}),...(verifyActivation?{verifyActivation}:{})});
55
- const key=requestId=>{if(!publishingRequestId(requestId))throw fail('REQUEST_ID_INVALID');return 'request:'+requestId;};
56
- const metadata=async({requestId,signal})=>{
57
- const record=await journal.load(key(requestId),{signal});if(!record)throw fail('FROZEN_REQUEST_MISSING');const saved=record.payload;
58
- if(record.revision!==1||!protocolRecord(saved,['schemaVersion','configuration','intent','manifestByteLength'],['acceptanceArchive','acceptanceTarget'])||saved.schemaVersion!==1||!Number.isSafeInteger(saved.manifestByteLength)||saved.manifestByteLength<1||saved.manifestByteLength>1048576)throw fail('FROZEN_REQUEST_INVALID');
59
- const archive=saved.acceptanceArchive;
60
- if(archive!==undefined&&!validAcceptanceTarget(saved.acceptanceTarget)||archive===undefined&&saved.acceptanceTarget!==undefined)throw fail('FROZEN_REQUEST_INVALID');
61
- if(archive!==undefined&&(!protocolRecord(archive,['archiveSha256','artifactSha256','byteLength'])||![archive.archiveSha256,archive.artifactSha256].every(publishingDigest)||!Number.isSafeInteger(archive.byteLength)||archive.byteLength<1||archive.byteLength>maximumAcceptanceArchiveBytes))throw fail('FROZEN_REQUEST_INVALID');
62
- if(hash(encoded(parsePublishingConfiguration(saved.configuration,{allowLoopback})))!==configurationSha256)throw fail('CONFIGURATION_CHANGED');
63
- const intent=parsePublishingIntent(saved.intent);if(intent.requestId!==requestId||intent.projectId!==config.projectId||intent.package.publisherId!==config.publisher.publisherId)throw fail('FROZEN_REQUEST_INVALID');return {intent,saved};
64
- };
65
- const read=async({requestId,signal})=>{
66
- const {intent,saved}=await metadata({requestId,signal});
67
- const manifestBytes=await journal.readBlob({sha256:intent.package.content.manifestSha256,byteLength:saved.manifestByteLength},{signal});if(!manifestBytes)throw fail('FROZEN_BYTES_MISSING');
68
- let manifest;try{manifest=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(manifestBytes));}catch{throw fail('FROZEN_REQUEST_INVALID');}
69
- if(!Array.isArray(manifest?.files)||manifest.files.length!==intent.package.fileCount)throw fail('FROZEN_REQUEST_INVALID');
70
- const files=[];
71
- for(const file of manifest.files){const bytes=await journal.readBlob({sha256:file.sha256,byteLength:file.byteLength},{signal});if(!bytes)throw fail('FROZEN_BYTES_MISSING');files.push({path:file.path,bytes});}
72
- const prepared=await verifySolutionPackageBytes({files,manifestBytes,expectedContent:intent.package.content,pathCaseSensitivity,limits:selectedLimits,signal});checkBinding(intent,prepared,config);return {intent,prepared};
73
- };
74
- const operation=async(mode,{requestId,signal,stage='create',attempt=0})=>{
75
- if(!['create','commit'].includes(stage)||!Number.isSafeInteger(attempt)||attempt<0||attempt>64||stage==='commit'&&attempt!==0)throw fail('SESSION_INPUT_INVALID');
76
- const {intent,saved}=await metadata({requestId,signal}),frozen=mode==='create'?await read({requestId,signal}):undefined,intentBytes=publishingIntentBytes(intent);
77
- const target={provider:'link-light-publishing',namespace:config.projectId,endpoint:config.serviceUrl};
78
- const operationId=requestId+'.'+stage+(attempt?'.'+attempt:'');
79
- const binding=await bindArtifactOperation({requestId:operationId,content:intent.package.content,...(intent.provenance?{provenance:intent.provenance}:{}),target,capability:stage==='create'?'artifact-upload':'deployment-create',configurationSha256,inputs:[{name:'intent.json',sha256:hash(intentBytes),byteLength:intentBytes.byteLength},{name:'content-manifest.json',sha256:intent.package.content.manifestSha256,byteLength:saved.manifestByteLength}]});
80
- const current=transportFor({client,intent,manifestBytes:frozen?.prepared.manifestBytes,target,configurationSha256,stage});
81
- const receipt=await(mode==='create'?performArtifactOperation:observeArtifactOperation)(current.transport,binding,journal.operationJournal(),{...selectedOperations,signal});
82
- return {receipt,...(current.status()?{status:current.status()}:{})};
83
- };
84
- return Object.freeze({
85
- async freeze({intent:input,prepared:inputPackage,acceptanceArchive,acceptanceTarget,signal}){
86
- const intent=parsePublishingIntent(input);key(intent.requestId);
87
- if(await journal.load(key(intent.requestId),{signal}))throw fail('REQUEST_EXISTS');
88
- const prepared=await verifySolutionPackageBytes({files:inputPackage.files,manifestBytes:inputPackage.manifestBytes,expectedContent:intent.package.content,pathCaseSensitivity,limits:selectedLimits,signal});checkBinding(intent,prepared,config);
89
- const files=new Map(prepared.manifest.files.map(file=>[file.path,file]));
90
- const blobs=[{sha256:prepared.content.manifestSha256,bytes:prepared.manifestBytes},...prepared.files.map(file=>({sha256:files.get(file.path).sha256,bytes:file.bytes}))];
91
- let archive;
92
- if(acceptanceArchive!==undefined){
93
- const {bytes,artifactSha256}=acceptanceArchive;
94
- if(!(bytes instanceof Uint8Array)||bytes.byteLength<1||bytes.byteLength>maximumAcceptanceArchiveBytes||!publishingDigest(artifactSha256)||!validAcceptanceTarget(acceptanceTarget))throw fail('ACCEPTANCE_ARCHIVE_INVALID');
95
- archive={archiveSha256:hash(bytes),artifactSha256,byteLength:bytes.byteLength};
96
- blobs.push({sha256:archive.archiveSha256,bytes});
97
- }
98
- const result=await journal.compareAndSet({key:key(intent.requestId),expectedRevision:0,payload:{schemaVersion:1,configuration:config,intent,manifestByteLength:prepared.manifestBytes.byteLength,...(archive?{acceptanceArchive:archive,acceptanceTarget}:{})},blobs},{signal});
99
- if(result!=='stored')throw fail('REQUEST_EXISTS');return {requestId:intent.requestId,content:prepared.content};
100
- },
101
- read,
102
- async acceptanceMetadata({requestId,signal}){
103
- const {saved,intent}=await metadata({requestId,signal});
104
- return saved.acceptanceArchive?{intent,archive:saved.acceptanceArchive,target:saved.acceptanceTarget}:undefined;
105
- },
106
- async readAcceptanceArchive({requestId,signal}){
107
- const {saved,intent}=await metadata({requestId,signal}),archive=saved.acceptanceArchive;
108
- if(!archive)return undefined;
109
- const bytes=await journal.readBlob({sha256:archive.archiveSha256,byteLength:archive.byteLength},{signal});
110
- if(!bytes||hash(bytes)!==archive.archiveSha256)throw fail('FROZEN_BYTES_MISSING');
111
- return {archive,bytes,intent,target:saved.acceptanceTarget};
112
- },
113
- create:input=>operation('create',{...input,stage:'create'}),
114
- observe:input=>operation('observe',input),
115
- queue:input=>operation('create',{...input,stage:'commit'}),
116
- async status({requestId,signal}){const {intent}=await metadata({requestId,signal});return client.getStatus({intent,signal});},
117
- async resume({requestId,signal}){const {intent}=await metadata({requestId,signal});return client.resumeRequest({intent,signal});},
118
- async recover({requestId,signal}){const {intent}=await metadata({requestId,signal});return client.recoverRequest({intent,signal});},
119
- async upload({requestId,signal}){
120
- const {intent,prepared}=await read({requestId,signal}),manifest=new Map(prepared.manifest.files.map(file=>[file.path,file])),bodies=new Map(prepared.files.map(file=>[file.path,file.bytes]));
121
- const checked=async()=>{
122
- const status=await client.getStatus({intent,signal}),seen=new Map();
123
- for(const file of status.missingFiles){const original=manifest.get(file.path);if(!original||original.sha256!==file.sha256||original.byteLength!==file.byteLength||file.receivedBytes>=file.byteLength||seen.has(file.sha256)&&seen.get(file.sha256)!==file.receivedBytes)throw fail('STATUS_BINDING_INVALID');seen.set(file.sha256,file.receivedBytes);}return status;
124
- };
125
- const status=await checked();if(status.state!=='uploading')return status;const done=new Set(),chunkBytes=selectedClientLimits?.maximumChunkBytes??262144;
126
- for(const file of status.missingFiles){
127
- if(done.has(file.sha256))continue;done.add(file.sha256);const bytes=bodies.get(file.path);
128
- for(let offset=file.receivedBytes;offset<file.byteLength;offset+=chunkBytes)await client.uploadChunk({requestId,file,offset,bytes:bytes.subarray(offset,Math.min(offset+chunkBytes,file.byteLength)),signal});
129
- }
130
- return checked();
131
- },
132
- async abandon({requestId,signal}){const {intent}=await metadata({requestId,signal});return client.abandonRequest({intent,signal});},
133
- });
134
- }
@@ -1,113 +0,0 @@
1
- import path from 'node:path';
2
- import {createHash} from 'node:crypto';
3
- import {calculateBytesIntegrity} from '@openge/forge-artifact-integrity';
4
- import {createArtifactContentManifest} from '@openge/forge-artifact-publish';
5
- import {captureArtifactFiles,verifyArtifactFiles} from '@openge/forge-artifact-publish/node';
6
- import {parseSolutionPackageDescriptor,parseSolutionPackageLimits} from '../package.mjs';
7
-
8
- const failure=code=>Error('PUBLISHING_PACKAGE_'+code);
9
- const compare=(a,b)=>a<b?-1:a>b?1:0;
10
- const check=signal=>signal.throwIfAborted();
11
- function runtimeClosure(descriptor,files,pathCaseSensitivity){
12
- const names=new Set(files),links=new Map(),fold=value=>pathCaseSensitivity==='case-insensitive'?value.toLowerCase():value;
13
- const overlaps=(first,second)=>first===second||first.startsWith(second+'/')||second.startsWith(first+'/');
14
- for(const link of descriptor.runtime.links){
15
- const name=fold(link.path);
16
- if(files.some(file=>overlaps(fold(file),name))||[...links.keys()].some(file=>overlaps(fold(file),name)))throw failure('RUNTIME_LINK_INVALID');
17
- links.set(link.path,link.target);
18
- }
19
- const resolve=(input,visited=new Set())=>{
20
- if(visited.size>64||visited.has(input))throw failure('RUNTIME_LINK_INVALID');visited.add(input);
21
- const match=[...links.keys()].filter(name=>input===name||input.startsWith(name+'/')).sort((a,b)=>b.length-a.length)[0];
22
- if(match){const target=path.posix.normalize(path.posix.join(path.posix.dirname(match),links.get(match),input.slice(match.length)));if(!target.startsWith('server/'))throw failure('RUNTIME_LINK_INVALID');return resolve(target,visited);}
23
- if(!names.has(input)&&!files.some(name=>name.startsWith(input+'/')))throw failure('RUNTIME_LINK_INVALID');return input;
24
- };
25
- for(const name of links.keys())resolve(name);
26
- if(!names.has(descriptor.runtime.entry)||!names.has(descriptor.ui.entry))throw failure('ENTRY_MISSING');
27
- }
28
- function packageNames(files,pathCaseSensitivity){
29
- if(!['case-sensitive','case-insensitive'].includes(pathCaseSensitivity))throw failure('INPUT_INVALID');
30
- const names=files.map(file=>file.path),folded=names.map(name=>pathCaseSensitivity==='case-insensitive'?name.toLowerCase():name);
31
- const paths=new Set(folded),collision=folded.some(name=>{for(let slash=name.lastIndexOf('/');slash>=0;slash=name.lastIndexOf('/',slash-1))if(paths.has(name.slice(0,slash)))return true;return false;});
32
- if(paths.size!==folded.length||collision||names.some(name=>name.split('/').some(part=>part.startsWith('.env')||['.git','.npmrc','.ssh','release-private'].includes(part)))||files.find(file=>file.path==='solution.json')?.role!=='control')throw failure('PLAN_INVALID');return names;
33
- }
34
- function completed(prepared,captured,pathCaseSensitivity,total){
35
- let descriptor;try{descriptor=parseSolutionPackageDescriptor(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(captured.find(file=>file.path==='solution.json').bytes)));}catch{throw failure('DESCRIPTOR_INVALID');}
36
- runtimeClosure(descriptor,packageNames(prepared.manifest.files,pathCaseSensitivity),pathCaseSensitivity);
37
- const files=captured.sort((a,b)=>compare(a.path,b.path));
38
- const streamFile=async function*(path,{signal}={}){const file=files.find(file=>file.path===path),declared=prepared.manifest.files.find(file=>file.path===path);if(!file||!declared)throw failure('CLOSURE');const digest=createHash('sha256');let count=0;for(let offset=0;offset<file.bytes.length;offset+=1048576){signal?.throwIfAborted();const bytes=new Uint8Array(file.bytes.subarray(offset,Math.min(offset+1048576,file.bytes.length)));digest.update(bytes);count+=bytes.length;yield bytes;}if(count!==declared.byteLength||digest.digest('hex')!==declared.sha256)throw failure('CHANGED');};
39
- const readFile=async(path,{maximumBytes,signal}={})=>{const declared=prepared.manifest.files.find(file=>file.path===path);if(!Number.isSafeInteger(maximumBytes)||maximumBytes<0||maximumBytes>16777216||!declared||declared.byteLength>maximumBytes)throw failure('BYTE_LIMIT');const bytes=new Uint8Array(declared.byteLength);let offset=0;for await(const part of streamFile(path,{signal})){bytes.set(part,offset);offset+=part.length;}return bytes;};
40
- return {descriptor,content:prepared.content,manifest:prepared.manifest,manifestBytes:prepared.bytes,files,payloadBytes:total,streamFile,readFile};
41
- }
42
- async function capturedPackage(declared,captured,pathCaseSensitivity,selected,current,total){
43
- const byPath=new Map(captured.map(file=>[file.path,file])),manifestFiles=[];
44
- if(byPath.size!==captured.length||declared.length!==captured.length)throw failure('CLOSURE');
45
- for(const file of declared){const capturedFile=byPath.get(file.path);if(!capturedFile)throw failure('CLOSURE');const bytes=capturedFile.bytes,integrity=await calculateBytesIntegrity(bytes);check(current);manifestFiles.push({...file,byteLength:bytes.byteLength,sha256:integrity.sha256});}
46
- const prepared=await createArtifactContentManifest({schemaVersion:1,files:manifestFiles});check(current);
47
- if(prepared.bytes.byteLength>selected.maximumManifestBytes||total+prepared.bytes.byteLength>selected.maximumTotalBytes)throw failure('BYTE_LIMIT');return completed(prepared,captured,pathCaseSensitivity,total);
48
- }
49
- async function canonicalManifest(manifestBytes,expectedContent,limits){
50
- if(!(manifestBytes instanceof Uint8Array)||manifestBytes.byteLength>limits.maximumManifestBytes||!expectedContent||Object.keys(expectedContent).join(',')!=='manifestSha256'||!/^[a-f0-9]{64}$/.test(expectedContent.manifestSha256??''))throw failure('MANIFEST_INVALID');
51
- const snapshot=new Uint8Array(manifestBytes);let manifest;
52
- try{manifest=await createArtifactContentManifest(JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(snapshot)));}catch{throw failure('MANIFEST_INVALID');}
53
- if(manifest.content.manifestSha256!==expectedContent.manifestSha256||manifest.bytes.byteLength!==snapshot.byteLength||manifest.bytes.some((byte,index)=>byte!==snapshot[index]))throw failure('MANIFEST_CHANGED');return manifest;
54
- }
55
- /** Capture exact artifact bytes, independently of source control or a deployment. */
56
- export async function prepareSolutionPackage({root,files,pathCaseSensitivity,limits,signal}){
57
- signal?.throwIfAborted();const selected=parseSolutionPackageLimits(limits);
58
- if(typeof root!=='string'||!path.isAbsolute(root)||!['case-sensitive','case-insensitive'].includes(pathCaseSensitivity)||!Array.isArray(files)||!files.length||files.length>selected.maximumFiles)throw failure('INPUT_INVALID');
59
- let declared;
60
- try{declared=(await createArtifactContentManifest({schemaVersion:1,files:files.map(file=>({...file,byteLength:0,sha256:'0'.repeat(64)}))})).manifest.files;}catch{throw failure('PLAN_INVALID');}
61
- if(files.some(file=>Object.keys(file).sort().join(',')!==(file.role==='asset'?'path,responseHeaders,role':'path,role')))throw failure('PLAN_INVALID');
62
- packageNames(declared,pathCaseSensitivity);
63
- return captureSolution({root,files,pathCaseSensitivity,selected,signal});
64
- }
65
-
66
- async function captureSolution({root,files,pathCaseSensitivity,selected,signal,manifestBytes,expectedContent}){
67
- const options={sources:[{rootDirectory:root,closure:'exact',files:files.map(file=>({...file,sourcePath:file.path}))}],pathCaseSensitivity,maxFiles:selected.maximumFiles,maxEntries:selected.maximumFiles*8,maxFileBytes:selected.maximumFileBytes,maxTotalBytes:selected.maximumTotalBytes,maxManifestBytes:selected.maximumManifestBytes,timeoutMilliseconds:selected.timeoutMs,...(signal?{signal}:{})};
68
- let captured;
69
- try{captured=await(manifestBytes?verifyArtifactFiles({...options,manifestBytes,expectedContent}):captureArtifactFiles(options));}
70
- catch(error){signal?.throwIfAborted();throw failure(({INVALID_PLAN:'PLAN_INVALID',INVALID_SOURCE:'CLOSURE',INTEGRITY_MISMATCH:'CHANGED',BUDGET_EXCEEDED:'BYTE_LIMIT',CLOSURE_UNCONFIRMED:'CLOSE_FAILED'})[error.code]??'CAPTURE_FAILED');}
71
- return completed({manifest:captured.manifest,content:captured.content,bytes:captured.manifestBytes},captured.manifest.files.map(file=>({path:file.path,bytes:captured.readFile(file.path)})),pathCaseSensitivity,captured.payloadByteLength);
72
- }
73
-
74
- /** Compose already-captured components without staging a second directory tree. */
75
- export async function prepareSolutionPackageBytes({files,pathCaseSensitivity,limits,signal}){
76
- signal?.throwIfAborted();const selected=parseSolutionPackageLimits(limits),deadline=AbortSignal.timeout(selected.timeoutMs),current=signal?AbortSignal.any([signal,deadline]):deadline;
77
- if(!Array.isArray(files)||!files.length||files.length>selected.maximumFiles)throw failure('INPUT_INVALID');
78
- const captured=[],plan=[];let total=0;
79
- for(const file of files){
80
- if(!file||!(file.bytes instanceof Uint8Array)||Object.keys(file).sort().join(',')!==(file.role==='asset'?'bytes,path,responseHeaders,role':'bytes,path,role'))throw failure('PLAN_INVALID');
81
- if(file.bytes.byteLength>selected.maximumFileBytes)throw failure('BYTE_LIMIT');total+=file.bytes.byteLength;if(total>selected.maximumTotalBytes)throw failure('BYTE_LIMIT');
82
- captured.push({path:file.path,bytes:new Uint8Array(file.bytes)});const {bytes,...declaration}=file;void bytes;plan.push({...declaration,byteLength:0,sha256:'0'.repeat(64)});
83
- }
84
- let declared;try{declared=(await createArtifactContentManifest({schemaVersion:1,files:plan})).manifest.files;}catch{throw failure('PLAN_INVALID');}
85
- packageNames(declared,pathCaseSensitivity);return capturedPackage(declared,captured,pathCaseSensitivity,selected,current,total);
86
- }
87
-
88
- export async function verifySolutionPackage({root,manifestBytes,expectedContent,pathCaseSensitivity,limits,signal}){
89
- const selected=parseSolutionPackageLimits(limits),manifest=await canonicalManifest(manifestBytes,expectedContent,selected);
90
- packageNames(manifest.manifest.files,pathCaseSensitivity);
91
- return captureSolution({root,files:manifest.manifest.files.map(({path,role,responseHeaders})=>({path,role,...(role==='asset'?{responseHeaders}:{})})),pathCaseSensitivity,selected,signal,manifestBytes:manifest.bytes,expectedContent});
92
- }
93
-
94
- /** Validate opaque received bytes without importing or executing the payload. */
95
- export async function verifySolutionPackageBytes({files,manifestBytes,expectedContent,pathCaseSensitivity,limits,signal}){
96
- signal?.throwIfAborted();const selected=parseSolutionPackageLimits(limits),deadline=AbortSignal.timeout(selected.timeoutMs),current=signal?AbortSignal.any([signal,deadline]):deadline;
97
- if(!Array.isArray(files)||files.length<1||files.length>selected.maximumFiles)throw failure('CLOSURE');
98
- const captured=[],seen=new Set();let total=0;
99
- for(const file of files){
100
- if(!file||Object.keys(file).sort().join(',')!=='bytes,path'||typeof file.path!=='string'||!(file.bytes instanceof Uint8Array)||seen.has(file.path))throw failure('CLOSURE');
101
- if(file.bytes.byteLength>selected.maximumFileBytes)throw failure('BYTE_LIMIT');total+=file.bytes.byteLength;if(total>selected.maximumTotalBytes)throw failure('BYTE_LIMIT');
102
- seen.add(file.path);captured.push({path:file.path,bytes:new Uint8Array(file.bytes)});
103
- }
104
- const prepared=await canonicalManifest(manifestBytes,expectedContent,selected);check(current);
105
- if(total+prepared.bytes.byteLength>selected.maximumTotalBytes)throw failure('BYTE_LIMIT');
106
- if(prepared.manifest.files.length!==captured.length)throw failure('CLOSURE');
107
- const byPath=new Map(captured.map(file=>[file.path,file]));
108
- for(const declared of prepared.manifest.files){
109
- const file=byPath.get(declared.path);if(!file)throw failure('CLOSURE');
110
- if(file.bytes.byteLength!==declared.byteLength||(await calculateBytesIntegrity(file.bytes)).sha256!==declared.sha256)throw failure('CHANGED');check(current);
111
- }
112
- return completed(prepared,captured,pathCaseSensitivity,total);
113
- }
@@ -1,9 +0,0 @@
1
- /** Only a source owner that observed its process lifecycle may assert closure.
2
- * The original cause stays private; CLI diagnostics emit only the stable code. */
3
- export class PublishingSourceError extends Error {
4
- constructor({cause,processesClosed}){
5
- if(typeof processesClosed!=='boolean')throw TypeError('PUBLISHING_SOURCE_CLOSURE_REQUIRED');
6
- const code='PUBLISHING_SOURCE_PREPARATION_'+(processesClosed?'FAILED':'UNKNOWN');
7
- super(code,{cause});this.name='PublishingSourceError';this.code=code;this.processesClosed=processesClosed;
8
- }
9
- }
@@ -1,103 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import path from 'node:path';
3
- import {createRequire} from 'node:module';
4
- import {validatePortableRelativePath} from '@openge/forge-path-safety';
5
- import {protocolRecord,publishingError} from '../protocol.mjs';
6
-
7
- export const defaultProducer='deployment/publishing.mjs';
8
- const maximumSourceBytes=65536n;
9
- const fail=code=>publishingError('SOURCE_'+code);
10
- const record=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
11
- const sameFile=(before,after)=>['dev','ino','size','mtimeNs','ctimeNs'].every(key=>before[key]===after[key]);
12
- const readOnlyFlags=fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0)|(fs.constants.O_NONBLOCK??0);
13
-
14
- export function validateLocalProducer(relative){
15
- try{
16
- if(validatePortableRelativePath(relative)===relative&&relative.endsWith('.mjs'))return relative;
17
- }catch{
18
- throw fail('PATH_INVALID');
19
- }
20
- throw fail('PATH_INVALID');
21
- }
22
-
23
- async function localProducerFile(root,relative){
24
- const parts=relative.split('/');let current=root;
25
- for(const [index,part] of parts.entries()){
26
- current=path.join(current,part);const info=await fs.lstat(current,{bigint:true});
27
- if(info.isSymbolicLink()||await fs.realpath(current)!==current||(index===parts.length-1?!info.isFile()||info.nlink!==1n||info.size>maximumSourceBytes:!info.isDirectory()))throw fail('PATH_INVALID');
28
- }
29
- return current;
30
- }
31
-
32
- async function readManifest(file,{checkout=false}={}){
33
- let before;
34
- try{before=await fs.lstat(file,{bigint:true});}
35
- catch(error){if(checkout&&error.code==='ENOENT')return undefined;throw error;}
36
- if(!before.isFile()||before.size>maximumSourceBytes||checkout&&before.nlink!==1n)throw fail('METADATA_INVALID');
37
- const handle=await fs.open(file,readOnlyFlags);
38
- try{
39
- if(!sameFile(before,await handle.stat({bigint:true})))throw fail('METADATA_INVALID');
40
- const bytes=Buffer.alloc(Number(before.size)+1);let offset=0;
41
- while(offset<bytes.length){
42
- const {bytesRead}=await handle.read(bytes,offset,bytes.length-offset,offset);
43
- if(bytesRead===0)break;
44
- offset+=bytesRead;
45
- }
46
- if(offset!==Number(before.size)||!sameFile(before,await handle.stat({bigint:true}))||!sameFile(before,await fs.lstat(file,{bigint:true})))throw fail('METADATA_INVALID');
47
- const value=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes.subarray(0,offset)));
48
- if(!record(value))throw fail('METADATA_INVALID');
49
- return value;
50
- }finally{await handle.close();}
51
- }
52
-
53
- export async function checkoutReleaseVersion(root, packageName) {
54
- const manifest=await readManifest(path.join(root,'package.json'),{checkout:true});
55
- if(!manifest || manifest.name===undefined && manifest.version===undefined)return undefined;
56
- if(manifest.name!==packageName || typeof manifest.version!=='string' ||
57
- !/^(?:0|[1-9]\d{0,7})(?:\.(?:0|[1-9]\d{0,7})){2}$/.test(manifest.version))throw fail('PACKAGE_BINDING_INVALID');
58
- return manifest.version;
59
- }
60
-
61
- export async function checkoutRequiresAcceptanceDelivery(root) {
62
- const manifest=await readManifest(path.join(root,'package.json'),{checkout:true});
63
- const mode=manifest?.linkLight?.acceptanceDelivery;
64
- if(mode!==undefined&&mode!=='required')throw fail('METADATA_INVALID');
65
- return mode==='required';
66
- }
67
-
68
- function contains(parent,child){
69
- const relative=path.relative(parent,child);
70
- return relative!==''&&relative!=='..'&&!relative.startsWith('..'+path.sep)&&!path.isAbsolute(relative);
71
- }
72
-
73
- async function packageProducerFile(root,manifest,checkout,selection){
74
- if(!protocolRecord(selection,['module'])||typeof selection.module!=='string'||selection.module.length>512)throw fail('METADATA_INVALID');
75
- const specifier=selection.module;
76
- const match=/^((?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*)(\/[A-Za-z0-9_-][A-Za-z0-9._-]*)+$/.exec(specifier);
77
- if(match?.[0]!==specifier)throw fail('METADATA_INVALID');
78
- const packageName=match[1];
79
- if(![checkout.dependencies,checkout.devDependencies].some(group=>record(group)&&Object.hasOwn(group,packageName)&&typeof group[packageName]==='string'&&group[packageName].trim()))throw fail('PACKAGE_UNDECLARED');
80
-
81
- const modules=path.join(root,'node_modules');
82
- if(await fs.realpath(modules)!==modules)throw fail('PATH_INVALID');
83
- const installed=await fs.realpath(path.join(modules,...packageName.split('/')));
84
- if(!contains(modules,installed))throw fail('PATH_INVALID');
85
- const dependency=await readManifest(path.join(installed,'package.json'));
86
- if(dependency.name!==packageName||dependency.exports==null)throw fail('PACKAGE_EXPORT_INVALID');
87
- const file=await fs.realpath(createRequire(manifest).resolve(specifier));
88
- if(!contains(installed,file)||!file.endsWith('.mjs'))throw fail('PATH_INVALID');
89
- const info=await fs.lstat(file,{bigint:true});
90
- if(!info.isFile()||info.size>maximumSourceBytes)throw fail('PATH_INVALID');
91
- return file;
92
- }
93
-
94
- export async function selectProducerFile(root,explicit){
95
- if(explicit!==undefined)return localProducerFile(root,explicit);
96
- const manifest=path.join(root,'package.json'),checkout=await readManifest(manifest,{checkout:true});
97
- const metadata=checkout?.linkLight;
98
- if(metadata!==undefined&&!record(metadata))throw fail('METADATA_INVALID');
99
- const selection=metadata?.publishingProducer;
100
- if(selection===undefined)return localProducerFile(root,defaultProducer);
101
- if(typeof selection==='string')return localProducerFile(root,validateLocalProducer(selection));
102
- return packageProducerFile(root,manifest,checkout,selection);
103
- }