@xlinklight/publishing 3.0.0-rc.0 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +7 -1
- package/package.json +3 -3
- package/src/node/cli.mjs +107 -106
- package/src/node/source-producer.mjs +88 -0
- package/src/node/workflow.mjs +11 -12
- package/src/worker/journal.d.mts +21 -21
- package/src/worker/journal.mjs +151 -151
- package/src/worker/service.mjs +247 -247
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 zopenge
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 zopenge
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -6,7 +6,13 @@ Solution publishing binds declarative metadata, an opaque Worker module closure
|
|
|
6
6
|
|
|
7
7
|
`prepareSolutionPackage` captures an explicit file/response-policy plan with declared path case semantics and file, byte and time limits. It rejects links, escapes, missing/extra files, collisions and changing bytes. `prepareSolutionPackageBytes` composes already captured snapshots without another filesystem staging tree. Both preserve binary bytes, BOMs, line endings and response headers. Their snapshots expose bounded `readFile(path, {maximumBytes, signal})` and `streamFile(path, {signal})`; the Node snapshot also retains its owned file bytes for local freezing. These results establish byte identity, not provider deployment or business acceptance.
|
|
8
8
|
|
|
9
|
-
The `link-light-release` executable provides `credentials`, `check`, `publish`, `status`, `recover`, `verify` and `abandon`. `credentials --stdin` installs
|
|
9
|
+
The `link-light-release` executable provides `credentials`, `check`, `publish`, `status`, `recover`, `verify` and `abandon`. `credentials --stdin` installs a pinned project configuration and token. A fresh `check` or `publish` selects an owner-installed producer in this order.
|
|
10
|
+
|
|
11
|
+
1. An explicit `--producer` portable checkout-relative `.mjs` path.
|
|
12
|
+
2. The checkout's `package.json` field `linkLight.publishingProducer`. Use a portable checkout-relative `.mjs` string or an object with a single `module` key naming a bare public package subpath, such as `{"module":"@example/owner-tools/deployment-producer"}`. Declare the package in the checkout's `dependencies` or `devDependencies` and install it under the checkout's `node_modules`. Node's `createRequire(...).resolve()` must find the export as a regular `.mjs` file within that installed package. The package can expose its ESM entry through the `default` condition. pnpm links to packages inside the checkout's `node_modules` are supported.
|
|
13
|
+
3. `deployment/publishing.mjs` when the metadata field is absent.
|
|
14
|
+
|
|
15
|
+
The checkout manifest, installed producer's package manifest and producer entry each have a 64 KiB limit. Invalid selection fails closed before producer code runs. Correct the selection and use `--new-preparation` to retry a closed failure. Each durable preparation invokes the producer once and requires its `prepare` result to confirm `processesClosed: true`. Unknown producer closure requires recovery. Frozen requests retain their original bytes and can be resumed after the selection or its files change. The default private client state is `state/solution-publishing`, separate from disposable build outputs. The caller owns filesystem access controls and backup policy for this secret-bearing journal.
|
|
10
16
|
|
|
11
17
|
The client never automatically repeats request creation. `publish` reuses frozen original bytes and an explicit request identity. CLI publish waits up to 300000 ms; `--no-wait` submits without waiting and `--wait-ms <1..3600000>` selects a finite wait. Programmatic `workflow.publish` defaults to one observation. Waiting uses GET only. Queued, pending or timed-out work exits 3; a closed failure exits 1; verified ACTIVE exits 0. Recovery observes the original operation without advancing its next stage. Resume may advance only after a known pending operation is observed successfully. Neither operation rebuilds, uploads or re-commits the package. Status and verification never dispatch work.
|
|
12
18
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xlinklight/publishing",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.1.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -45,10 +45,10 @@
|
|
|
45
45
|
"@openge/forge-artifact-publish": "0.4.1",
|
|
46
46
|
"@openge/forge-generated-artifacts": "0.2.0",
|
|
47
47
|
"@openge/forge-path-safety": "0.1.0",
|
|
48
|
-
"@xlinklight/contracts": "3.0.0
|
|
48
|
+
"@xlinklight/contracts": "3.0.0"
|
|
49
49
|
},
|
|
50
50
|
"peerDependencies": {
|
|
51
|
-
"@xlinklight/platform": "5.0.0
|
|
51
|
+
"@xlinklight/platform": "5.0.0"
|
|
52
52
|
},
|
|
53
53
|
"peerDependenciesMeta": {
|
|
54
54
|
"@xlinklight/platform": {
|
package/src/node/cli.mjs
CHANGED
|
@@ -1,106 +1,107 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import fs from 'node:fs/promises';
|
|
3
|
-
import {existsSync,realpathSync} from 'node:fs';
|
|
4
|
-
import path from 'node:path';
|
|
5
|
-
import {fileURLToPath} from 'node:url';
|
|
6
|
-
import {createLinuxDurableArtifactFilesystem,createWindowsNtfsDurableArtifactFilesystem} from '@openge/forge-generated-artifacts/node';
|
|
7
|
-
import {validatePortableRelativePath} from '@openge/forge-path-safety';
|
|
8
|
-
import {parsePublishingConfiguration,protocolRecord,publishingError} from '../protocol.mjs';
|
|
9
|
-
import {openPublishingJournal} from './journal.mjs';
|
|
10
|
-
import {installPublishingAuthorization,loadPublishingAuthorization} from './authorization.mjs';
|
|
11
|
-
import {createPublishingWorkflow} from './workflow.mjs';
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
const
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
if(args.length
|
|
19
|
-
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
if(
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
else if(flag==='--
|
|
27
|
-
else if(flag==='--wait
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
else if(flag==='--
|
|
32
|
-
else
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
if(
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
if(!
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
const
|
|
87
|
-
const
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import {existsSync,realpathSync} from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {fileURLToPath} from 'node:url';
|
|
6
|
+
import {createLinuxDurableArtifactFilesystem,createWindowsNtfsDurableArtifactFilesystem} from '@openge/forge-generated-artifacts/node';
|
|
7
|
+
import {validatePortableRelativePath} from '@openge/forge-path-safety';
|
|
8
|
+
import {parsePublishingConfiguration,protocolRecord,publishingError} from '../protocol.mjs';
|
|
9
|
+
import {openPublishingJournal} from './journal.mjs';
|
|
10
|
+
import {installPublishingAuthorization,loadPublishingAuthorization} from './authorization.mjs';
|
|
11
|
+
import {createPublishingWorkflow} from './workflow.mjs';
|
|
12
|
+
import {defaultProducer} from './source-producer.mjs';
|
|
13
|
+
|
|
14
|
+
const commands=['credentials','check','publish','status','recover','verify','abandon'];
|
|
15
|
+
const journalLimits=Object.freeze({maximumBytes:536870912,maximumRecords:256,maximumRecordBytes:1048576,maximumBlobs:12000,maximumBlobBytes:134217728,minimumFreeBytes:67108864});
|
|
16
|
+
const fail=code=>publishingError(code);
|
|
17
|
+
function parse(args){
|
|
18
|
+
if(!Array.isArray(args)||!args.length||args.some(value=>typeof value!=='string'||!value||value.includes('\0')||value.length>4096))throw fail('CLI_ARGUMENT_INVALID');
|
|
19
|
+
if(args.length===1&&args[0]==='--help')return {command:'help'};
|
|
20
|
+
const command=args[0];if(!commands.includes(command))throw fail('CLI_ARGUMENT_INVALID');
|
|
21
|
+
const selected={command},seen=new Set();
|
|
22
|
+
for(let index=1;index<args.length;index++){
|
|
23
|
+
const flag=args[index];if(seen.has(flag))throw fail('CLI_ARGUMENT_INVALID');seen.add(flag);
|
|
24
|
+
if(['--root','--state','--producer'].includes(flag)){
|
|
25
|
+
const value=args[++index];if(!value||value.startsWith('--')||flag==='--producer'&&!['check','publish'].includes(command))throw fail('CLI_ARGUMENT_INVALID');selected[flag.slice(2)]=value;
|
|
26
|
+
}else if(flag==='--stdin'&&command==='credentials')selected.stdin=true;
|
|
27
|
+
else if(flag==='--no-wait'&&command==='publish')selected.waitMs=0;
|
|
28
|
+
else if(flag==='--wait-ms'&&command==='publish'){
|
|
29
|
+
const value=args[++index];if(!/^[1-9]\d{0,6}$/.test(value??'')||Number(value)>3600000)throw fail('CLI_ARGUMENT_INVALID');selected.waitMs=Number(value);
|
|
30
|
+
}
|
|
31
|
+
else if(flag==='--replace-credential'&&command==='credentials')selected.replaceCredential=true;
|
|
32
|
+
else if(flag==='--new-preparation'&&['check','publish'].includes(command))selected.newPreparation=true;
|
|
33
|
+
else throw fail('CLI_ARGUMENT_INVALID');
|
|
34
|
+
}
|
|
35
|
+
if(command==='credentials'&&!selected.stdin)throw fail('CLI_ARGUMENT_INVALID');
|
|
36
|
+
if(seen.has('--no-wait')&&seen.has('--wait-ms'))throw fail('CLI_ARGUMENT_INVALID');
|
|
37
|
+
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');}}
|
|
38
|
+
return selected;
|
|
39
|
+
}
|
|
40
|
+
async function credentialInput(stdin,signal,timeoutMilliseconds){
|
|
41
|
+
if(!stdin||stdin.isTTY===true||['on','off','destroy','resume'].some(name=>typeof stdin[name]!=='function'))throw fail('CREDENTIAL_INPUT_NON_TTY_REQUIRED');
|
|
42
|
+
if(!Number.isSafeInteger(timeoutMilliseconds)||timeoutMilliseconds<1||timeoutMilliseconds>300000)throw fail('CREDENTIAL_INPUT_LIMIT_INVALID');
|
|
43
|
+
const chunks=[];let bytes=0,timer,abort,data,end,error,close;
|
|
44
|
+
let closedListener;const closed=stdin.closed?Promise.resolve(true):new Promise(resolve=>{closedListener=()=>resolve(true);stdin.once('close',closedListener);});
|
|
45
|
+
try{
|
|
46
|
+
if(signal?.aborted)throw fail('CREDENTIAL_INPUT_CANCELLED');
|
|
47
|
+
await new Promise((resolve,reject)=>{
|
|
48
|
+
let settled=false;const rejectOnce=code=>{if(!settled){settled=true;reject(fail(code));}};
|
|
49
|
+
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);};
|
|
50
|
+
end=()=>{if(!settled){settled=true;resolve();}};error=()=>rejectOnce('CREDENTIAL_INPUT_INVALID');close=()=>rejectOnce('CREDENTIAL_INPUT_CLOSED');abort=()=>rejectOnce('CREDENTIAL_INPUT_CANCELLED');
|
|
51
|
+
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();
|
|
52
|
+
});
|
|
53
|
+
let value;try{value=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks)));}catch{throw fail('CREDENTIAL_INPUT_INVALID');}
|
|
54
|
+
if(!protocolRecord(value,['configuration','credential'])||typeof value.credential!=='string'||!/^[A-Za-z0-9_-]{32,4096}$/.test(value.credential))throw fail('CREDENTIAL_INPUT_INVALID');return value;
|
|
55
|
+
}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');}
|
|
56
|
+
finally{
|
|
57
|
+
clearTimeout(timer);if(abort)signal?.removeEventListener('abort',abort);
|
|
58
|
+
for(const [name,listener]of [['data',data],['end',end],['error',error],['close',close]])if(listener)stdin.off(name,listener);
|
|
59
|
+
// Explicit credential input is owned by this call, including blocked pipes.
|
|
60
|
+
stdin.destroy();let closureTimer;
|
|
61
|
+
try{if(!await Promise.race([closed,new Promise(resolve=>{closureTimer=setTimeout(()=>resolve(false),1000);})]))throw fail('CREDENTIAL_INPUT_CLOSURE_UNKNOWN');}
|
|
62
|
+
finally{clearTimeout(closureTimer);if(closedListener)stdin.off('close',closedListener);}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function diagnostic(error){
|
|
66
|
+
const code=typeof error?.code==='string'&&/^PUBLISHING_[A-Z0-9_]{1,96}$/.test(error.code)?error.code:'PUBLISHING_COMMAND_FAILED';return {error:{code}};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Bounded one-shot CLI. No token, private producer cause, provider output or
|
|
70
|
+
* environment is returned. Callers own private storage ACLs and backup policy. */
|
|
71
|
+
async function executeCommand(selected,options){
|
|
72
|
+
let journal;
|
|
73
|
+
try{
|
|
74
|
+
const {signal,allowLoopback=false,request,clientLimits,metadataTransport}=options;
|
|
75
|
+
const input=selected.command==='credentials'?await credentialInput(options.stdin??process.stdin,signal,options.credentialInputTimeoutMilliseconds??30000):undefined;
|
|
76
|
+
if(input)input.configuration=parsePublishingConfiguration(input.configuration,{allowLoopback});
|
|
77
|
+
signal?.throwIfAborted();const root=path.resolve(options.cwd??process.cwd(),selected.root??'.'),info=await fs.lstat(root);
|
|
78
|
+
if(!info.isDirectory()||info.isSymbolicLink()||await fs.realpath(root)!==root)throw fail('CLI_ROOT_INVALID');
|
|
79
|
+
const filesystem=options.filesystem??await(process.platform==='win32'?createWindowsNtfsDurableArtifactFilesystem():process.platform==='linux'?createLinuxDurableArtifactFilesystem():Promise.reject(fail('CLI_PLATFORM_UNSUPPORTED')));
|
|
80
|
+
journal=await openPublishingJournal({root,directory:selected.state??'state/solution-publishing',filesystem,limits:options.journalLimits??journalLimits,signal});
|
|
81
|
+
const shared={journal,allowLoopback,...(request?{request}:{}),...(clientLimits?{clientLimits}:{}),signal};
|
|
82
|
+
if(input){
|
|
83
|
+
const installed=await installPublishingAuthorization({...shared,...input,replaceCredential:selected.replaceCredential===true});
|
|
84
|
+
return {exitCode:0,output:{state:installed.status.toLowerCase(),projectId:installed.projectId,policyRevision:installed.policyRevision}};
|
|
85
|
+
}
|
|
86
|
+
const authorization=await loadPublishingAuthorization(shared);if(!authorization)throw fail('CREDENTIAL_REQUIRED');
|
|
87
|
+
const workflow=createPublishingWorkflow({...shared,...authorization,root,...(metadataTransport?{metadataTransport}:{}),...(options.operationLimits?{operationLimits:options.operationLimits}:{})});
|
|
88
|
+
const result=await workflow[selected.command]({signal,...(selected.producer?{producer:selected.producer}:{}),...(selected.newPreparation?{newPreparation:true}:{}),...(selected.command==='publish'?{waitMs:selected.waitMs??300000}:{})});
|
|
89
|
+
const exitCode=result.state==='active'||['check','abandon'].includes(selected.command)?0:result.state==='failed'?1:3;
|
|
90
|
+
return {exitCode,output:result};
|
|
91
|
+
}finally{try{journal?.close();}catch{throw fail('JOURNAL_CLOSURE_UNKNOWN');}}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function runPublishingCommand(args,options={}){
|
|
95
|
+
let selected;try{selected=parse(args);}catch{return {exitCode:2,output:{error:{code:'PUBLISHING_CLI_ARGUMENT_INVALID'}}};}
|
|
96
|
+
if(selected.command==='help')return {exitCode:0,output:{commands,sourceProducer:defaultProducer,stateDirectory:'state/solution-publishing',publishWaitMs:300000,publishOptions:['--no-wait','--wait-ms <1..3600000>']}};
|
|
97
|
+
try{return await executeCommand(selected,options);}catch(error){return {exitCode:1,output:diagnostic(error)};}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function main(){
|
|
101
|
+
const controller=new AbortController(),stop=()=>controller.abort();process.once('SIGINT',stop);process.once('SIGTERM',stop);
|
|
102
|
+
try{const result=await runPublishingCommand(process.argv.slice(2),{signal:controller.signal});process.stdout.write(JSON.stringify(result.output)+'\n');process.exitCode=result.exitCode;}
|
|
103
|
+
finally{process.off('SIGINT',stop);process.off('SIGTERM',stop);}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// A producer can import the same public Node entry while the command is running.
|
|
107
|
+
if(process.argv[1]&&existsSync(process.argv[1])&&realpathSync(process.argv[1])===realpathSync(fileURLToPath(import.meta.url)))void main();
|
|
@@ -0,0 +1,88 @@
|
|
|
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
|
+
function contains(parent,child){
|
|
54
|
+
const relative=path.relative(parent,child);
|
|
55
|
+
return relative!==''&&relative!=='..'&&!relative.startsWith('..'+path.sep)&&!path.isAbsolute(relative);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function packageProducerFile(root,manifest,checkout,selection){
|
|
59
|
+
if(!protocolRecord(selection,['module'])||typeof selection.module!=='string'||selection.module.length>512)throw fail('METADATA_INVALID');
|
|
60
|
+
const specifier=selection.module;
|
|
61
|
+
const match=/^((?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*)(\/[A-Za-z0-9_-][A-Za-z0-9._-]*)+$/.exec(specifier);
|
|
62
|
+
if(match?.[0]!==specifier)throw fail('METADATA_INVALID');
|
|
63
|
+
const packageName=match[1];
|
|
64
|
+
if(![checkout.dependencies,checkout.devDependencies].some(group=>record(group)&&Object.hasOwn(group,packageName)&&typeof group[packageName]==='string'&&group[packageName].trim()))throw fail('PACKAGE_UNDECLARED');
|
|
65
|
+
|
|
66
|
+
const modules=path.join(root,'node_modules');
|
|
67
|
+
if(await fs.realpath(modules)!==modules)throw fail('PATH_INVALID');
|
|
68
|
+
const installed=await fs.realpath(path.join(modules,...packageName.split('/')));
|
|
69
|
+
if(!contains(modules,installed))throw fail('PATH_INVALID');
|
|
70
|
+
const dependency=await readManifest(path.join(installed,'package.json'));
|
|
71
|
+
if(dependency.name!==packageName||dependency.exports==null)throw fail('PACKAGE_EXPORT_INVALID');
|
|
72
|
+
const file=await fs.realpath(createRequire(manifest).resolve(specifier));
|
|
73
|
+
if(!contains(installed,file)||!file.endsWith('.mjs'))throw fail('PATH_INVALID');
|
|
74
|
+
const info=await fs.lstat(file,{bigint:true});
|
|
75
|
+
if(!info.isFile()||info.size>maximumSourceBytes)throw fail('PATH_INVALID');
|
|
76
|
+
return file;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function selectProducerFile(root,explicit){
|
|
80
|
+
if(explicit!==undefined)return localProducerFile(root,explicit);
|
|
81
|
+
const manifest=path.join(root,'package.json'),checkout=await readManifest(manifest,{checkout:true});
|
|
82
|
+
const metadata=checkout?.linkLight;
|
|
83
|
+
if(metadata!==undefined&&!record(metadata))throw fail('METADATA_INVALID');
|
|
84
|
+
const selection=metadata?.publishingProducer;
|
|
85
|
+
if(selection===undefined)return localProducerFile(root,defaultProducer);
|
|
86
|
+
if(typeof selection==='string')return localProducerFile(root,validateLocalProducer(selection));
|
|
87
|
+
return packageProducerFile(root,manifest,checkout,selection);
|
|
88
|
+
}
|
package/src/node/workflow.mjs
CHANGED
|
@@ -3,26 +3,19 @@ import path from 'node:path';
|
|
|
3
3
|
import {pathToFileURL} from 'node:url';
|
|
4
4
|
import {randomUUID} from 'node:crypto';
|
|
5
5
|
import {setTimeout as delay} from 'node:timers/promises';
|
|
6
|
-
import {validatePortableRelativePath} from '@openge/forge-path-safety';
|
|
7
6
|
import {createPublishingClient} from '../client.mjs';
|
|
8
7
|
import {parsePublishingConfiguration,parsePublishingProject,parsePublishingIntent,publishingRequestId,protocolRecord,publishingError} from '../protocol.mjs';
|
|
9
8
|
import {createPublishingSession} from './session.mjs';
|
|
10
9
|
import {verifyPublishingActivation} from './activation.mjs';
|
|
11
10
|
import {PublishingSourceError} from './source-error.mjs';
|
|
11
|
+
import {selectProducerFile,validateLocalProducer} from './source-producer.mjs';
|
|
12
12
|
|
|
13
13
|
const fail=code=>publishingError(code),sourceKey=id=>'source:'+id;
|
|
14
14
|
const sourceOptions=input=>{
|
|
15
15
|
if(!protocolRecord(input,[],['producer','newPreparation','signal'])||input.newPreparation!==undefined&&typeof input.newPreparation!=='boolean')throw fail('WORKFLOW_INPUT_INVALID');
|
|
16
|
-
|
|
16
|
+
if(input.producer!==undefined)validateLocalProducer(input.producer);
|
|
17
|
+
return input;
|
|
17
18
|
};
|
|
18
|
-
async function producerFile(root,relative){
|
|
19
|
-
const selected=path.join(root,...relative.split('/'));let current=root;
|
|
20
|
-
for(const [index,part]of relative.split('/').entries()){
|
|
21
|
-
current=path.join(current,part);const info=await fs.lstat(current,{bigint:true});
|
|
22
|
-
if(info.isSymbolicLink()||await fs.realpath(current)!==current||(index===relative.split('/').length-1? !info.isFile()||info.nlink!==1n||info.size>65536n:!info.isDirectory()))throw fail('SOURCE_PATH_INVALID');
|
|
23
|
-
}
|
|
24
|
-
return selected;
|
|
25
|
-
}
|
|
26
19
|
|
|
27
20
|
/** One active request per project/client journal. Recovery never imports source
|
|
28
21
|
* or performs an operation whose durable Foundation claim already exists. */
|
|
@@ -71,12 +64,18 @@ export function createPublishingWorkflow(options){
|
|
|
71
64
|
if(!newPreparation)throw fail('SOURCE_NEW_PREPARATION_REQUIRED');
|
|
72
65
|
}
|
|
73
66
|
signal?.throwIfAborted();if(await fs.realpath(root)!==root||!(await fs.lstat(root)).isDirectory())throw fail('SOURCE_PATH_INVALID');
|
|
74
|
-
const project=await client(signal).getProject({signal}),requestId=randomUUID()
|
|
67
|
+
const project=await client(signal).getProject({signal}),requestId=randomUUID();
|
|
68
|
+
let file,selectionFailure;
|
|
69
|
+
try{file=await selectProducerFile(root,producer);}
|
|
70
|
+
catch(cause){selectionFailure=new PublishingSourceError({cause,processesClosed:true});}
|
|
71
|
+
signal?.throwIfAborted();
|
|
72
|
+
const payload={schemaVersion:1,requestId,project,pathCaseSensitivity,...(selectionFailure?{phase:'failed-closed',failure:{code:selectionFailure.code}}:{phase:'preparing'})};
|
|
75
73
|
if(await journal.compareAndSet({key:sourceKey(requestId),expectedRevision:0,payload},{signal})!=='stored')throw fail('WORKFLOW_CONFLICT');
|
|
76
74
|
if(await journal.compareAndSet({key:activeKey,expectedRevision:previous?.active.revision??0,payload:{schemaVersion:1,requestId}},{signal})!=='stored')throw fail('WORKFLOW_CONFLICT');
|
|
75
|
+
if(selectionFailure)throw selectionFailure;
|
|
77
76
|
let record={revision:1,payload},prepared,intent,processesClosed=false;
|
|
78
77
|
try{
|
|
79
|
-
const
|
|
78
|
+
const producerModule=await import(pathToFileURL(file).href+'?publishingRequest='+requestId);
|
|
80
79
|
if(typeof producerModule.prepare!=='function')throw fail('SOURCE_PORT_INVALID');
|
|
81
80
|
const response=await producerModule.prepare({root,project:structuredClone(project),signal,requestId});
|
|
82
81
|
if(!protocolRecord(response,['prepared','processesClosed'])||response.processesClosed!==true)throw fail('SOURCE_PROCESS_CLOSURE_UNKNOWN');processesClosed=true;prepared=response.prepared;
|
package/src/worker/journal.d.mts
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import type {JsonValue} from '@xlinklight/contracts';
|
|
2
|
-
import type {ArtifactOperationJournal,ArtifactTransportClosure} from '@openge/forge-artifact-publish';
|
|
3
|
-
export interface PublishingDurableStorage {readonly sql:{readonly databaseSize:number;exec(query:string,...values:(string|number|ArrayBuffer|null)[]):{toArray():Record<string,unknown>[]}};transactionSync<T>(work:()=>T):T;sync():Promise<void>}
|
|
4
|
-
export interface PublishingDurableLimits {maximumBytes:number;maximumRecords:number;maximumRecordBytes:number;maximumBlobs:number;maximumBlobBytes:number;recoveryReserveBytes:number}
|
|
5
|
-
export interface PublishingDispatch {projectId:string;requestId:string;mode:'perform'|'observe';continue:boolean;acceptanceReceipt?:true}
|
|
6
|
-
export interface PublishingQueueLease extends PublishingDispatch {revision:number;observations:number}
|
|
7
|
-
export interface PublishingMutationAuthority {kind:'configure'|'request'|'worker';projectId:string;requestId?:string;policyRevision?:number;credentialSha256?:string;revision?:number;owner?:string;mode?:'perform'|'observe'}
|
|
8
|
-
export interface PublishingDurableJournal {
|
|
9
|
-
recordCapacity():{used:number;maximum:number};
|
|
10
|
-
load(key:string,options?:{signal?:AbortSignal}):Promise<{revision:number;payload:JsonValue}|undefined>;
|
|
11
|
-
readBlob(input:{sha256:string;byteLength:number},options?:{signal?:AbortSignal}):Promise<Uint8Array|undefined>;
|
|
12
|
-
compareAndSet(input:{key:string;expectedRevision:number;payload:JsonValue;blobs?:readonly {sha256:string;bytes:Uint8Array}[]},options?:{signal?:AbortSignal;authority?:PublishingMutationAuthority;dispatch?:PublishingDispatch}):Promise<'stored'|'conflict'>;
|
|
13
|
-
operationJournal():ArtifactOperationJournal;
|
|
14
|
-
enqueue(input:PublishingDispatch,options?:{signal?:AbortSignal;authority?:PublishingMutationAuthority}):Promise<void>;
|
|
15
|
-
nextWake():number|null;take():Promise<PublishingQueueLease|null>;
|
|
16
|
-
finish(job:PublishingQueueLease,options?:{again?:boolean;delayMs?:number;mode?:'perform'|'observe';advance?:boolean;observations?:number}):Promise<void>;
|
|
17
|
-
withIngress<T>(work:()=>Promise<T>):Promise<T>;
|
|
18
|
-
withProjectLock<T>(input:{projectId:string;requestId:string;mode?:'perform'|'observe';signal?:AbortSignal},work:(lease:{signal:AbortSignal;assertHeld():Promise<void>;beginOperation():void;confirmClosure(closure:ArtifactTransportClosure|undefined):void})=>Promise<T>):Promise<T>;
|
|
19
|
-
readonly blocked:boolean;readonly running:boolean;close():void;
|
|
20
|
-
}
|
|
21
|
-
export function openPublishingDurableJournal(input:{storage:PublishingDurableStorage;identity:string;limits:PublishingDurableLimits;now?:()=>number;leaseMs?:number;increaseMaximumRecordsTo?:number}):Promise<PublishingDurableJournal>;
|
|
1
|
+
import type {JsonValue} from '@xlinklight/contracts';
|
|
2
|
+
import type {ArtifactOperationJournal,ArtifactTransportClosure} from '@openge/forge-artifact-publish';
|
|
3
|
+
export interface PublishingDurableStorage {readonly sql:{readonly databaseSize:number;exec(query:string,...values:(string|number|ArrayBuffer|null)[]):{toArray():Record<string,unknown>[]}};transactionSync<T>(work:()=>T):T;sync():Promise<void>}
|
|
4
|
+
export interface PublishingDurableLimits {maximumBytes:number;maximumRecords:number;maximumRecordBytes:number;maximumBlobs:number;maximumBlobBytes:number;recoveryReserveBytes:number}
|
|
5
|
+
export interface PublishingDispatch {projectId:string;requestId:string;mode:'perform'|'observe';continue:boolean;acceptanceReceipt?:true}
|
|
6
|
+
export interface PublishingQueueLease extends PublishingDispatch {revision:number;observations:number}
|
|
7
|
+
export interface PublishingMutationAuthority {kind:'configure'|'request'|'worker';projectId:string;requestId?:string;policyRevision?:number;credentialSha256?:string;revision?:number;owner?:string;mode?:'perform'|'observe'}
|
|
8
|
+
export interface PublishingDurableJournal {
|
|
9
|
+
recordCapacity():{used:number;maximum:number};
|
|
10
|
+
load(key:string,options?:{signal?:AbortSignal}):Promise<{revision:number;payload:JsonValue}|undefined>;
|
|
11
|
+
readBlob(input:{sha256:string;byteLength:number},options?:{signal?:AbortSignal}):Promise<Uint8Array|undefined>;
|
|
12
|
+
compareAndSet(input:{key:string;expectedRevision:number;payload:JsonValue;blobs?:readonly {sha256:string;bytes:Uint8Array}[]},options?:{signal?:AbortSignal;authority?:PublishingMutationAuthority;dispatch?:PublishingDispatch}):Promise<'stored'|'conflict'>;
|
|
13
|
+
operationJournal():ArtifactOperationJournal;
|
|
14
|
+
enqueue(input:PublishingDispatch,options?:{signal?:AbortSignal;authority?:PublishingMutationAuthority}):Promise<void>;
|
|
15
|
+
nextWake():number|null;take():Promise<PublishingQueueLease|null>;
|
|
16
|
+
finish(job:PublishingQueueLease,options?:{again?:boolean;delayMs?:number;mode?:'perform'|'observe';advance?:boolean;observations?:number}):Promise<void>;
|
|
17
|
+
withIngress<T>(work:()=>Promise<T>):Promise<T>;
|
|
18
|
+
withProjectLock<T>(input:{projectId:string;requestId:string;mode?:'perform'|'observe';signal?:AbortSignal},work:(lease:{signal:AbortSignal;assertHeld():Promise<void>;beginOperation():void;confirmClosure(closure:ArtifactTransportClosure|undefined):void})=>Promise<T>):Promise<T>;
|
|
19
|
+
readonly blocked:boolean;readonly running:boolean;close():void;
|
|
20
|
+
}
|
|
21
|
+
export function openPublishingDurableJournal(input:{storage:PublishingDurableStorage;identity:string;limits:PublishingDurableLimits;now?:()=>number;leaseMs?:number;increaseMaximumRecordsTo?:number}):Promise<PublishingDurableJournal>;
|