@xlinklight/publishing 3.0.0 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -1
- package/package.json +2 -2
- package/src/client.d.mts +1 -0
- package/src/client.mjs +8 -0
- package/src/node/acceptance-delivery.d.mts +11 -0
- package/src/node/acceptance-delivery.mjs +109 -0
- package/src/node/authorization.d.mts +1 -1
- package/src/node/authorization.mjs +16 -6
- package/src/node/cli.mjs +1 -95
- package/src/node/index.d.mts +3 -2
- package/src/node/index.mjs +2 -1
- package/src/node/publishing-command.mjs +104 -0
- package/src/node/session.d.mts +5 -3
- package/src/node/session.mjs +40 -7
- package/src/node/source-producer.mjs +103 -0
- package/src/node/workflow.d.mts +3 -1
- package/src/node/workflow.mjs +178 -36
- package/src/worker/service.mjs +4 -0
- /package/src/node/{cli.d.mts → publishing-command.d.mts} +0 -0
package/README.md
CHANGED
|
@@ -1,12 +1,26 @@
|
|
|
1
1
|
# Link Light solution publishing
|
|
2
2
|
|
|
3
|
+
## Publishing from an owner checkout
|
|
4
|
+
|
|
5
|
+
The project administrator enrolls the owner with Publisher. Install the project authorization on each trusted workstation with `pnpm release:credentials` using a non-interactive stdin pipe. A delivery-enabled authorization contains `configuration`, `credential` and `acceptanceDelivery`. The last object contains the owner runner's exact HTTPS `origin`, its deployment `keyId` and the project-specific Ed25519 PKCS8 `privateKey`. Protect that file and the client journal with OS access controls. The owner's public `package.json` declares `linkLight.acceptanceDelivery` as `"required"`.
|
|
6
|
+
|
|
7
|
+
Set the intended version in the owner's manifest and run `pnpm release`. A fresh request freezes the prepared solution and owner acceptance archive in a single journal transaction. The client retains its original destination and bytes through interruption. It observes the authenticated project's last request before starting the next version, and requires current Core admission to accept an active receipt. Another authorized machine verifies the existing intent and uses the same identity for identical version content.
|
|
8
|
+
|
|
9
|
+
Use `pnpm release:status` to inspect, `pnpm release:recover` to reconcile the original effects and `pnpm release:verify` to verify activation again. A bounded timeout or unknown response returns the request ID and a nonzero exit. A closed source preparation failure can be corrected and retried with `pnpm release --new-preparation`. Independent clients need project authorization and an installed Node toolchain.
|
|
10
|
+
|
|
3
11
|
Solution publishing binds declarative metadata, an opaque Worker module closure and separately served static UI bytes to Foundation's canonical content manifest. The publisher never discovers or executes code from an uploaded package. The root entry parses the portable envelope. `@xlinklight/publishing/node` owns local capture, the CLI, credentials and the client SQLite journal. `@xlinklight/publishing/worker` owns the service, durable queue and finite deployment stages for a SQLite Durable Object. There is one cloud execution path: Cloudflare Workers and Durable Objects, with explicit provider adapters for immutable Workers and Pages deployments.
|
|
4
12
|
|
|
5
13
|
## Local preparation and client
|
|
6
14
|
|
|
7
15
|
`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
16
|
|
|
9
|
-
The `link-light-release` executable provides `credentials`, `check`, `publish`, `status`, `recover`, `verify` and `abandon`. `credentials --stdin` installs
|
|
17
|
+
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.
|
|
18
|
+
|
|
19
|
+
1. An explicit `--producer` portable checkout-relative `.mjs` path.
|
|
20
|
+
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.
|
|
21
|
+
3. `deployment/publishing.mjs` when the metadata field is absent.
|
|
22
|
+
|
|
23
|
+
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
24
|
|
|
11
25
|
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
26
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xlinklight/publishing",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.2.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"@xlinklight/contracts": "3.0.0"
|
|
49
49
|
},
|
|
50
50
|
"peerDependencies": {
|
|
51
|
-
"@xlinklight/platform": "5.
|
|
51
|
+
"@xlinklight/platform": "5.1.0"
|
|
52
52
|
},
|
|
53
53
|
"peerDependenciesMeta": {
|
|
54
54
|
"@xlinklight/platform": {
|
package/src/client.d.mts
CHANGED
|
@@ -3,6 +3,7 @@ import type {PublishingConfiguration,PublishingProject,PublishingIntent,Publishi
|
|
|
3
3
|
export interface PublishingClientLimits {requestMs:number;maximumResponseBytes:number;maximumChunkBytes:number}
|
|
4
4
|
export interface PublishingClient {
|
|
5
5
|
getProject(input?:{signal?:AbortSignal}):Promise<PublishingProject>;
|
|
6
|
+
getLatestRelease(input?:{signal?:AbortSignal}):Promise<{intent:PublishingIntent;status:PublishingStatus}|undefined>;
|
|
6
7
|
createRequest(input:{intent:PublishingIntent;manifestBytes:Uint8Array;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
7
8
|
getStatus(input:{intent:PublishingIntent;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
8
9
|
resumeRequest(input:{intent:PublishingIntent;signal?:AbortSignal}):Promise<PublishingStatus>;
|
package/src/client.mjs
CHANGED
|
@@ -45,6 +45,14 @@ export function createPublishingClient({configuration,credential,allowLoopback=f
|
|
|
45
45
|
const project=parsePublishingProject(await send('GET','/v1/project',undefined,signal),{allowLoopback});
|
|
46
46
|
if(JSON.stringify(project.configuration)!==JSON.stringify(config))throw publishingError('PROJECT_BINDING_INVALID');return project;
|
|
47
47
|
},
|
|
48
|
+
async getLatestRelease({signal}={}){
|
|
49
|
+
const value=await send('GET','/v1/project/release',undefined,signal);
|
|
50
|
+
if(!protocolRecord(value,['schemaVersion','intent'])||value.schemaVersion!==1)throw publishingError('PROJECT_BINDING_INVALID');
|
|
51
|
+
if(value.intent===null)return undefined;
|
|
52
|
+
const intent=checkedIntent(value.intent);
|
|
53
|
+
try{return {intent,status:await boundStatus(await send('GET','/v1/requests/'+intent.requestId,undefined,signal),intent)};}
|
|
54
|
+
catch(error){error.requestId=intent.requestId;throw error;}
|
|
55
|
+
},
|
|
48
56
|
async createRequest({intent:input,manifestBytes,signal}){
|
|
49
57
|
const intent=checkedIntent(input);
|
|
50
58
|
if(!(manifestBytes instanceof Uint8Array)||manifestBytes.byteLength>1048576)throw publishingError('MANIFEST_INVALID');
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface AcceptanceDeliveryCredential {origin:string;keyId:string;privateKey:string}
|
|
2
|
+
export interface AcceptanceArchive {bytes:Uint8Array;artifactSha256:string}
|
|
3
|
+
export interface AcceptanceArchiveIdentity {archiveSha256:string;artifactSha256:string;byteLength:number}
|
|
4
|
+
export interface AcceptanceDeliveryBinding extends AcceptanceArchiveIdentity {
|
|
5
|
+
projectId:string;solutionId:string;version:string;origin:string;keyId:string;manifestSha256:string;
|
|
6
|
+
}
|
|
7
|
+
export const maximumAcceptanceArchiveBytes:number;
|
|
8
|
+
export function signAcceptanceDelivery(binding:AcceptanceDeliveryBinding,privateKey:string|import('node:crypto').KeyObject):string;
|
|
9
|
+
export function deliverAcceptanceArchive(input:{intent:import('../protocol.mjs').PublishingIntent;archive:AcceptanceArchiveIdentity;bytes:Uint8Array;credential:AcceptanceDeliveryCredential;request?:typeof fetch;signal?:AbortSignal}):Promise<void>;
|
|
10
|
+
export function verifyAcceptanceDelivery(binding:AcceptanceDeliveryBinding,signature:string,publicKey:string|import('node:crypto').KeyObject):void;
|
|
11
|
+
export function readDeliveryBody(message:Request|Response,limit:number):Promise<Buffer>;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import {createHash, createPrivateKey, createPublicKey, sign, verify} from 'node:crypto';
|
|
2
|
+
import {protocolRecord, publishingDigest, publishingError, publishingIdentifier} from '../protocol.mjs';
|
|
3
|
+
|
|
4
|
+
export const maximumAcceptanceArchiveBytes = 50 * 1024 ** 2;
|
|
5
|
+
const fail = code => publishingError('ACCEPTANCE_' + code);
|
|
6
|
+
const versionPattern = /^\d{1,8}\.\d{1,8}\.\d{1,8}$/;
|
|
7
|
+
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
8
|
+
const fields = ['projectId','solutionId','version','origin','keyId','manifestSha256','archiveSha256','artifactSha256','byteLength'];
|
|
9
|
+
|
|
10
|
+
function validateOrigin(value) {
|
|
11
|
+
const url = typeof value === 'string' ? URL.parse(value) : null;
|
|
12
|
+
if (url?.protocol !== 'https:' || url.origin !== value) throw fail('ORIGIN_INVALID');
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function parseAcceptanceDeliveryCredential(value) {
|
|
17
|
+
if (!protocolRecord(value,['origin','keyId','privateKey']) || !publishingIdentifier(value.keyId) ||
|
|
18
|
+
typeof value.privateKey !== 'string' || value.privateKey.length > 4096) throw fail('CREDENTIAL_INVALID');
|
|
19
|
+
validateOrigin(value.origin);
|
|
20
|
+
const key = createPrivateKey(value.privateKey);
|
|
21
|
+
if (key.asymmetricKeyType !== 'ed25519') throw fail('CREDENTIAL_INVALID');
|
|
22
|
+
return {origin:value.origin,keyId:value.keyId,privateKey:key.export({type:'pkcs8',format:'pem'}).toString()};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function acceptanceDeliveryTarget(credential) {
|
|
26
|
+
const {origin,keyId,privateKey}=parseAcceptanceDeliveryCredential(credential);
|
|
27
|
+
return {origin,keyId,publicKeySha256:hash(createPublicKey(privateKey).export({type:'spki',format:'der'}))};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function binding(value) {
|
|
31
|
+
if (!protocolRecord(value,fields) || ![value.projectId,value.solutionId,value.keyId].every(publishingIdentifier) ||
|
|
32
|
+
!versionPattern.test(value.version) || ![value.manifestSha256,value.archiveSha256,value.artifactSha256].every(publishingDigest) ||
|
|
33
|
+
!Number.isSafeInteger(value.byteLength) || value.byteLength < 1 || value.byteLength > maximumAcceptanceArchiveBytes) throw fail('BINDING_INVALID');
|
|
34
|
+
validateOrigin(value.origin);
|
|
35
|
+
return Buffer.from(JSON.stringify(['link-light/owner-acceptance-installation/v1', ...fields.map(key => value[key])]));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function signAcceptanceDelivery(value, privateKey) {
|
|
39
|
+
return sign(null,binding(value),privateKey).toString('base64url');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function verifyAcceptanceDelivery(value, signature, publicKey) {
|
|
43
|
+
if (typeof signature !== 'string' || !/^[A-Za-z0-9_-]{86}$/.test(signature)) throw fail('SIGNATURE_INVALID');
|
|
44
|
+
const key = typeof publicKey === 'string' ? createPublicKey(publicKey) : publicKey;
|
|
45
|
+
if (key?.asymmetricKeyType !== 'ed25519' || !verify(null,binding(value),key,Buffer.from(signature,'base64url'))) throw fail('SIGNATURE_INVALID');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Only the dedicated owner's HTTPS origin receives this archive. A read after
|
|
49
|
+
* the immutable PUT also reconciles a lost response without repeating a release. */
|
|
50
|
+
function deliveryTarget({intent,archive,credential,request=fetch,signal}) {
|
|
51
|
+
if (!credential) throw fail('CREDENTIAL_REQUIRED');
|
|
52
|
+
const {origin,keyId,privateKey}=parseAcceptanceDeliveryCredential(credential);
|
|
53
|
+
const expected={projectId:intent.projectId,solutionId:intent.package.solutionId,version:intent.package.version,
|
|
54
|
+
origin,keyId,manifestSha256:intent.package.content.manifestSha256,...archive};
|
|
55
|
+
const url=new URL('/v1/acceptance/installations/'+expected.version,origin);
|
|
56
|
+
const timeout=AbortSignal.timeout(30000);
|
|
57
|
+
const options={redirect:'error',signal:signal?AbortSignal.any([signal,timeout]):timeout};
|
|
58
|
+
async function observed(){
|
|
59
|
+
const response=await request(url,{...options,method:'GET',headers:{accept:'application/json'}});
|
|
60
|
+
if(response.status===404){await response.body?.cancel();return false;}
|
|
61
|
+
if(response.status!==200){await response.body?.cancel();throw fail('DELIVERY_UNKNOWN');}
|
|
62
|
+
const receipt=await readDeliveryBody(response,8192);
|
|
63
|
+
let value;try{value=JSON.parse(receipt.toString('utf8'));}catch{throw fail('DELIVERY_UNKNOWN');}
|
|
64
|
+
if (!protocolRecord(value,fields))throw fail('DELIVERY_UNKNOWN');
|
|
65
|
+
if (!binding(value).equals(binding(expected))) throw fail('VERSION_CONFLICT');
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
return {observed,expected,privateKey,options,url,request};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function observeAcceptanceDelivery(input) {
|
|
72
|
+
return deliveryTarget(input).observed();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function deliverAcceptanceArchive(input) {
|
|
76
|
+
const {bytes,archive}=input;
|
|
77
|
+
if (!(bytes instanceof Uint8Array) || bytes.byteLength!==archive.byteLength || hash(bytes)!==archive.archiveSha256) throw fail('ARCHIVE_CHANGED');
|
|
78
|
+
const {observed,expected,privateKey,options,url,request}=deliveryTarget(input);
|
|
79
|
+
if(await observed())return;
|
|
80
|
+
const signature=signAcceptanceDelivery(expected,privateKey);
|
|
81
|
+
let rejection;
|
|
82
|
+
try {
|
|
83
|
+
const response=await request(url,{...options,method:'PUT',headers:{'content-type':'application/octet-stream',
|
|
84
|
+
'x-link-light-binding':Buffer.from(JSON.stringify(expected)).toString('base64url'),'x-link-light-signature':signature},body:bytes});
|
|
85
|
+
await response.body?.cancel();
|
|
86
|
+
if(response.status===403)rejection='SIGNATURE_INVALID';
|
|
87
|
+
if(response.status===409)rejection='VERSION_CONFLICT';
|
|
88
|
+
if([400,413,415,422].includes(response.status))rejection='DELIVERY_REJECTED';
|
|
89
|
+
} catch(error){if(error?.code?.startsWith('PUBLISHING_ACCEPTANCE_'))throw error;}
|
|
90
|
+
if(!await observed())throw fail(rejection??'DELIVERY_UNKNOWN');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function readDeliveryBody(message,limit) {
|
|
94
|
+
const length=message.headers.get('content-length');
|
|
95
|
+
if(!Number.isSafeInteger(limit)||limit<1||limit>maximumAcceptanceArchiveBytes||!message.body||
|
|
96
|
+
length!==null&&(!/^\d+$/.test(length)||Number(length)>limit))throw fail('BODY_LIMIT');
|
|
97
|
+
const reader=message.body.getReader(),chunks=[];
|
|
98
|
+
let total=0;
|
|
99
|
+
try {
|
|
100
|
+
for(;;){
|
|
101
|
+
const {done,value}=await reader.read();
|
|
102
|
+
if(done)break;
|
|
103
|
+
total+=value.byteLength;
|
|
104
|
+
if(total>limit)throw fail('BODY_LIMIT');
|
|
105
|
+
chunks.push(value);
|
|
106
|
+
}
|
|
107
|
+
} finally {try{await reader.cancel();}finally{reader.releaseLock();}}
|
|
108
|
+
return Buffer.concat(chunks,total);
|
|
109
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type {PublishingConfiguration} from '../protocol.mjs';
|
|
2
2
|
import type {PublishingClientLimits} from '../client.mjs';
|
|
3
3
|
import type {PublishingJournal} from './journal.mjs';
|
|
4
|
-
export interface PublishingAuthorization {configuration:PublishingConfiguration;credential:string}
|
|
4
|
+
export interface PublishingAuthorization {configuration:PublishingConfiguration;credential:string;acceptanceDelivery?:import('./acceptance-delivery.mjs').AcceptanceDeliveryCredential}
|
|
5
5
|
export function loadPublishingAuthorization(input:{journal:Pick<PublishingJournal,'load'|'compareAndSet'>;allowLoopback?:boolean;signal?:AbortSignal}):Promise<PublishingAuthorization|undefined>;
|
|
6
6
|
export function installPublishingAuthorization(input:PublishingAuthorization&{
|
|
7
7
|
journal:Pick<PublishingJournal,'load'|'compareAndSet'>;replaceCredential?:boolean;allowLoopback?:boolean;request?:typeof fetch;clientLimits?:PublishingClientLimits;signal?:AbortSignal;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {createHash} from 'node:crypto';
|
|
1
|
+
import {createHash,createPublicKey} from 'node:crypto';
|
|
2
|
+
import {parseAcceptanceDeliveryCredential} from './acceptance-delivery.mjs';
|
|
2
3
|
import {createPublishingClient} from '../client.mjs';
|
|
3
4
|
import {parsePublishingConfiguration,protocolRecord,publishingError} from '../protocol.mjs';
|
|
4
5
|
|
|
@@ -6,9 +7,10 @@ const key='client-authorization',hash=value=>createHash('sha256').update(value).
|
|
|
6
7
|
const credentialValid=value=>typeof value==='string'&&/^[A-Za-z0-9_-]{32,4096}$/.test(value);
|
|
7
8
|
function saved(record,allowLoopback){
|
|
8
9
|
if(!record)return undefined;const value=record.payload;
|
|
9
|
-
if(!protocolRecord(value,['schemaVersion','configuration','configurationSha256','credential','credentialSha256'])||value.schemaVersion!==1||!credentialValid(value.credential))throw fail('INVALID');
|
|
10
|
+
if(!protocolRecord(value,['schemaVersion','configuration','configurationSha256','credential','credentialSha256'],['acceptanceDelivery'])||value.schemaVersion!==1||!credentialValid(value.credential))throw fail('INVALID');
|
|
10
11
|
let configuration;try{configuration=parsePublishingConfiguration(value.configuration,{allowLoopback});}catch{throw fail('INVALID');}
|
|
11
|
-
if(hash(JSON.stringify(configuration))!==value.configurationSha256||hash(value.credential)!==value.credentialSha256)throw fail('INVALID');
|
|
12
|
+
if(hash(JSON.stringify(configuration))!==value.configurationSha256||hash(value.credential)!==value.credentialSha256)throw fail('INVALID');
|
|
13
|
+
return {configuration,credential:value.credential,...(value.acceptanceDelivery?{acceptanceDelivery:parseAcceptanceDeliveryCredential(value.acceptanceDelivery)}:{})};
|
|
12
14
|
}
|
|
13
15
|
function store(journal){if(!journal||typeof journal.load!=='function'||typeof journal.compareAndSet!=='function')throw fail('STORE_INVALID');return journal;}
|
|
14
16
|
|
|
@@ -20,19 +22,27 @@ export async function loadPublishingAuthorization({journal,allowLoopback=false,s
|
|
|
20
22
|
|
|
21
23
|
/** Validate installed trust and current project access before atomic install.
|
|
22
24
|
* A changed service/publisher trust never adopts an existing recovery journal. */
|
|
23
|
-
export async function installPublishingAuthorization({journal,configuration:input,credential,replaceCredential=false,allowLoopback=false,request,clientLimits,signal}){
|
|
25
|
+
export async function installPublishingAuthorization({journal,configuration:input,credential,acceptanceDelivery,replaceCredential=false,allowLoopback=false,request,clientLimits,signal}){
|
|
24
26
|
store(journal);signal?.throwIfAborted();const configuration=parsePublishingConfiguration(input,{allowLoopback});
|
|
25
27
|
if(!credentialValid(credential)||typeof replaceCredential!=='boolean')throw fail('INVALID');
|
|
26
28
|
const previous=await journal.load(key,{signal}),current=saved(previous,allowLoopback),configurationSha256=hash(JSON.stringify(configuration)),credentialSha256=hash(credential);
|
|
27
29
|
if(current&&JSON.stringify(current.configuration)!==JSON.stringify(configuration))throw fail('TRUST_CHANGED');
|
|
28
30
|
if(current&¤t.credential!==credential&&!replaceCredential)throw fail('REPLACEMENT_REQUIRED');
|
|
31
|
+
const delivery=acceptanceDelivery===undefined?current?.acceptanceDelivery:parseAcceptanceDeliveryCredential(acceptanceDelivery);
|
|
32
|
+
if(delivery){
|
|
33
|
+
const publicBytes=key=>createPublicKey(key).export({type:'spki',format:'der'});
|
|
34
|
+
if(configuration.publisher.keys.some(key=>publicBytes(key.publicKey).equals(publicBytes(delivery.privateKey))))throw fail('TRUST_CHANGED');
|
|
35
|
+
if(current?.acceptanceDelivery&&(delivery.origin!==current.acceptanceDelivery.origin||delivery.keyId!==current.acceptanceDelivery.keyId||
|
|
36
|
+
!publicBytes(delivery.privateKey).equals(publicBytes(current.acceptanceDelivery.privateKey))))throw fail('TRUST_CHANGED');
|
|
37
|
+
if(current?.acceptanceDelivery&&JSON.stringify(current.acceptanceDelivery)!==JSON.stringify(delivery)&&!replaceCredential)throw fail('REPLACEMENT_REQUIRED');
|
|
38
|
+
}
|
|
29
39
|
const client=createPublishingClient({configuration,credential,allowLoopback,...(request?{request}:{}),...(clientLimits?{limits:clientLimits}:{})}),project=await client.getProject({signal});
|
|
30
|
-
if(current?.credential===credential){
|
|
40
|
+
if(current?.credential===credential&&JSON.stringify(current.acceptanceDelivery)===JSON.stringify(delivery)){
|
|
31
41
|
const latest=await journal.load(key,{signal});if(latest?.revision!==previous.revision)throw fail('CONFLICT');saved(latest,allowLoopback);
|
|
32
42
|
return {status:'VERIFIED',projectId:configuration.projectId,credentialSha256,policyRevision:project.policyRevision};
|
|
33
43
|
}
|
|
34
44
|
let result;
|
|
35
|
-
try{result=await journal.compareAndSet({key,expectedRevision:previous?.revision??0,payload:{schemaVersion:1,configuration,configurationSha256,credential,credentialSha256}},{signal});}
|
|
45
|
+
try{result=await journal.compareAndSet({key,expectedRevision:previous?.revision??0,payload:{schemaVersion:1,configuration,configurationSha256,credential,credentialSha256,...(delivery?{acceptanceDelivery:delivery}:{})}},{signal});}
|
|
36
46
|
catch{throw fail('PERSISTENCE_UNKNOWN');}
|
|
37
47
|
if(result==='conflict')throw fail('CONFLICT');if(result!=='stored')throw fail('PERSISTENCE_UNKNOWN');
|
|
38
48
|
return {status:previous?'REPLACED':'CONFIGURED',projectId:configuration.projectId,credentialSha256,policyRevision:project.policyRevision};
|
package/src/node/cli.mjs
CHANGED
|
@@ -1,100 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import fs from 'node:fs/promises';
|
|
3
2
|
import {existsSync,realpathSync} from 'node:fs';
|
|
4
|
-
import path from 'node:path';
|
|
5
3
|
import {fileURLToPath} from 'node:url';
|
|
6
|
-
import {
|
|
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
|
-
const commands=['credentials','check','publish','status','recover','verify','abandon'];
|
|
14
|
-
const journalLimits=Object.freeze({maximumBytes:536870912,maximumRecords:256,maximumRecordBytes:1048576,maximumBlobs:12000,maximumBlobBytes:134217728,minimumFreeBytes:67108864});
|
|
15
|
-
const fail=code=>publishingError(code);
|
|
16
|
-
function parse(args){
|
|
17
|
-
if(!Array.isArray(args)||!args.length||args.some(value=>typeof value!=='string'||!value||value.includes('\0')||value.length>4096))throw fail('CLI_ARGUMENT_INVALID');
|
|
18
|
-
if(args.length===1&&args[0]==='--help')return {command:'help'};
|
|
19
|
-
const command=args[0];if(!commands.includes(command))throw fail('CLI_ARGUMENT_INVALID');
|
|
20
|
-
const selected={command},seen=new Set();
|
|
21
|
-
for(let index=1;index<args.length;index++){
|
|
22
|
-
const flag=args[index];if(seen.has(flag))throw fail('CLI_ARGUMENT_INVALID');seen.add(flag);
|
|
23
|
-
if(['--root','--state','--producer'].includes(flag)){
|
|
24
|
-
const value=args[++index];if(!value||value.startsWith('--')||flag==='--producer'&&!['check','publish'].includes(command))throw fail('CLI_ARGUMENT_INVALID');selected[flag.slice(2)]=value;
|
|
25
|
-
}else if(flag==='--stdin'&&command==='credentials')selected.stdin=true;
|
|
26
|
-
else if(flag==='--no-wait'&&command==='publish')selected.waitMs=0;
|
|
27
|
-
else if(flag==='--wait-ms'&&command==='publish'){
|
|
28
|
-
const value=args[++index];if(!/^[1-9]\d{0,6}$/.test(value??'')||Number(value)>3600000)throw fail('CLI_ARGUMENT_INVALID');selected.waitMs=Number(value);
|
|
29
|
-
}
|
|
30
|
-
else if(flag==='--replace-credential'&&command==='credentials')selected.replaceCredential=true;
|
|
31
|
-
else if(flag==='--new-preparation'&&['check','publish'].includes(command))selected.newPreparation=true;
|
|
32
|
-
else throw fail('CLI_ARGUMENT_INVALID');
|
|
33
|
-
}
|
|
34
|
-
if(command==='credentials'&&!selected.stdin)throw fail('CLI_ARGUMENT_INVALID');
|
|
35
|
-
if(seen.has('--no-wait')&&seen.has('--wait-ms'))throw fail('CLI_ARGUMENT_INVALID');
|
|
36
|
-
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');}}
|
|
37
|
-
return selected;
|
|
38
|
-
}
|
|
39
|
-
async function credentialInput(stdin,signal,timeoutMilliseconds){
|
|
40
|
-
if(!stdin||stdin.isTTY===true||['on','off','destroy','resume'].some(name=>typeof stdin[name]!=='function'))throw fail('CREDENTIAL_INPUT_NON_TTY_REQUIRED');
|
|
41
|
-
if(!Number.isSafeInteger(timeoutMilliseconds)||timeoutMilliseconds<1||timeoutMilliseconds>300000)throw fail('CREDENTIAL_INPUT_LIMIT_INVALID');
|
|
42
|
-
const chunks=[];let bytes=0,timer,abort,data,end,error,close;
|
|
43
|
-
let closedListener;const closed=stdin.closed?Promise.resolve(true):new Promise(resolve=>{closedListener=()=>resolve(true);stdin.once('close',closedListener);});
|
|
44
|
-
try{
|
|
45
|
-
if(signal?.aborted)throw fail('CREDENTIAL_INPUT_CANCELLED');
|
|
46
|
-
await new Promise((resolve,reject)=>{
|
|
47
|
-
let settled=false;const rejectOnce=code=>{if(!settled){settled=true;reject(fail(code));}};
|
|
48
|
-
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);};
|
|
49
|
-
end=()=>{if(!settled){settled=true;resolve();}};error=()=>rejectOnce('CREDENTIAL_INPUT_INVALID');close=()=>rejectOnce('CREDENTIAL_INPUT_CLOSED');abort=()=>rejectOnce('CREDENTIAL_INPUT_CANCELLED');
|
|
50
|
-
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();
|
|
51
|
-
});
|
|
52
|
-
let value;try{value=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks)));}catch{throw fail('CREDENTIAL_INPUT_INVALID');}
|
|
53
|
-
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;
|
|
54
|
-
}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');}
|
|
55
|
-
finally{
|
|
56
|
-
clearTimeout(timer);if(abort)signal?.removeEventListener('abort',abort);
|
|
57
|
-
for(const [name,listener]of [['data',data],['end',end],['error',error],['close',close]])if(listener)stdin.off(name,listener);
|
|
58
|
-
// Explicit credential input is owned by this call, including blocked pipes.
|
|
59
|
-
stdin.destroy();let closureTimer;
|
|
60
|
-
try{if(!await Promise.race([closed,new Promise(resolve=>{closureTimer=setTimeout(()=>resolve(false),1000);})]))throw fail('CREDENTIAL_INPUT_CLOSURE_UNKNOWN');}
|
|
61
|
-
finally{clearTimeout(closureTimer);if(closedListener)stdin.off('close',closedListener);}
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
function diagnostic(error){
|
|
65
|
-
const code=typeof error?.code==='string'&&/^PUBLISHING_[A-Z0-9_]{1,96}$/.test(error.code)?error.code:'PUBLISHING_COMMAND_FAILED';return {error:{code}};
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/** Bounded one-shot CLI. No token, private producer cause, provider output or
|
|
69
|
-
* environment is returned. Callers own private storage ACLs and backup policy. */
|
|
70
|
-
async function executeCommand(selected,options){
|
|
71
|
-
let journal;
|
|
72
|
-
try{
|
|
73
|
-
const {signal,allowLoopback=false,request,clientLimits,metadataTransport}=options;
|
|
74
|
-
const input=selected.command==='credentials'?await credentialInput(options.stdin??process.stdin,signal,options.credentialInputTimeoutMilliseconds??30000):undefined;
|
|
75
|
-
if(input)input.configuration=parsePublishingConfiguration(input.configuration,{allowLoopback});
|
|
76
|
-
signal?.throwIfAborted();const root=path.resolve(options.cwd??process.cwd(),selected.root??'.'),info=await fs.lstat(root);
|
|
77
|
-
if(!info.isDirectory()||info.isSymbolicLink()||await fs.realpath(root)!==root)throw fail('CLI_ROOT_INVALID');
|
|
78
|
-
const filesystem=options.filesystem??await(process.platform==='win32'?createWindowsNtfsDurableArtifactFilesystem():process.platform==='linux'?createLinuxDurableArtifactFilesystem():Promise.reject(fail('CLI_PLATFORM_UNSUPPORTED')));
|
|
79
|
-
journal=await openPublishingJournal({root,directory:selected.state??'state/solution-publishing',filesystem,limits:options.journalLimits??journalLimits,signal});
|
|
80
|
-
const shared={journal,allowLoopback,...(request?{request}:{}),...(clientLimits?{clientLimits}:{}),signal};
|
|
81
|
-
if(input){
|
|
82
|
-
const installed=await installPublishingAuthorization({...shared,...input,replaceCredential:selected.replaceCredential===true});
|
|
83
|
-
return {exitCode:0,output:{state:installed.status.toLowerCase(),projectId:installed.projectId,policyRevision:installed.policyRevision}};
|
|
84
|
-
}
|
|
85
|
-
const authorization=await loadPublishingAuthorization(shared);if(!authorization)throw fail('CREDENTIAL_REQUIRED');
|
|
86
|
-
const workflow=createPublishingWorkflow({...shared,...authorization,root,...(metadataTransport?{metadataTransport}:{}),...(options.operationLimits?{operationLimits:options.operationLimits}:{})});
|
|
87
|
-
const result=await workflow[selected.command]({signal,...(selected.producer?{producer:selected.producer}:{}),...(selected.newPreparation?{newPreparation:true}:{}),...(selected.command==='publish'?{waitMs:selected.waitMs??300000}:{})});
|
|
88
|
-
const exitCode=result.state==='active'||['check','abandon'].includes(selected.command)?0:result.state==='failed'?1:3;
|
|
89
|
-
return {exitCode,output:result};
|
|
90
|
-
}finally{try{journal?.close();}catch{throw fail('JOURNAL_CLOSURE_UNKNOWN');}}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
export async function runPublishingCommand(args,options={}){
|
|
94
|
-
let selected;try{selected=parse(args);}catch{return {exitCode:2,output:{error:{code:'PUBLISHING_CLI_ARGUMENT_INVALID'}}};}
|
|
95
|
-
if(selected.command==='help')return {exitCode:0,output:{commands,sourceProducer:'deployment/publishing.mjs',stateDirectory:'state/solution-publishing',publishWaitMs:300000,publishOptions:['--no-wait','--wait-ms <1..3600000>']}};
|
|
96
|
-
try{return await executeCommand(selected,options);}catch(error){return {exitCode:1,output:diagnostic(error)};}
|
|
97
|
-
}
|
|
4
|
+
import {runPublishingCommand} from './publishing-command.mjs';
|
|
98
5
|
|
|
99
6
|
async function main(){
|
|
100
7
|
const controller=new AbortController(),stop=()=>controller.abort();process.once('SIGINT',stop);process.once('SIGTERM',stop);
|
|
@@ -102,5 +9,4 @@ async function main(){
|
|
|
102
9
|
finally{process.off('SIGINT',stop);process.off('SIGTERM',stop);}
|
|
103
10
|
}
|
|
104
11
|
|
|
105
|
-
// A producer can import the same public Node entry while the command is running.
|
|
106
12
|
if(process.argv[1]&&existsSync(process.argv[1])&&realpathSync(process.argv[1])===realpathSync(fileURLToPath(import.meta.url)))void main();
|
package/src/node/index.d.mts
CHANGED
|
@@ -12,5 +12,6 @@ export {createPublishingActivation,verifyPublishingActivation} from './activatio
|
|
|
12
12
|
export {PublishingSourceError} from './source-error.mjs';
|
|
13
13
|
export type {PublishingSourceProducer,PublishingWorkflowOptions,PublishingSourceOptions,PublishingPublishOptions,PublishingWorkflowResult,PublishingWorkflow} from './workflow.mjs';
|
|
14
14
|
export {createPublishingWorkflow} from './workflow.mjs';
|
|
15
|
-
export type {PublishingCommandOptions,PublishingCommandResult} from './
|
|
16
|
-
export {runPublishingCommand} from './
|
|
15
|
+
export type {PublishingCommandOptions,PublishingCommandResult} from './publishing-command.mjs';
|
|
16
|
+
export {runPublishingCommand} from './publishing-command.mjs';
|
|
17
|
+
export * from './acceptance-delivery.mjs';
|
package/src/node/index.mjs
CHANGED
|
@@ -5,4 +5,5 @@ export {installPublishingAuthorization,loadPublishingAuthorization} from './auth
|
|
|
5
5
|
export {createPublishingActivation,verifyPublishingActivation} from './activation.mjs';
|
|
6
6
|
export {PublishingSourceError} from './source-error.mjs';
|
|
7
7
|
export {createPublishingWorkflow} from './workflow.mjs';
|
|
8
|
-
export {
|
|
8
|
+
export {deliverAcceptanceArchive,signAcceptanceDelivery,maximumAcceptanceArchiveBytes,readDeliveryBody,verifyAcceptanceDelivery} from './acceptance-delivery.mjs';
|
|
9
|
+
export {runPublishingCommand} from './publishing-command.mjs';
|
|
@@ -0,0 +1,104 @@
|
|
|
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
|
+
}
|
package/src/node/session.d.mts
CHANGED
|
@@ -5,10 +5,12 @@ import type {PublishingJournal} from './journal.mjs';
|
|
|
5
5
|
import type {PreparedSolutionPackage,SolutionPackageLimits} from './solution-package.mjs';
|
|
6
6
|
export interface PublishingSessionResult {receipt:ArtifactOperationReceipt;status?:PublishingStatus}
|
|
7
7
|
export interface PublishingSession {
|
|
8
|
-
freeze(input:{intent:PublishingIntent;prepared:Pick<PreparedSolutionPackage,'files'|'manifestBytes'>;signal?:AbortSignal}):Promise<{requestId:string;content:{manifestSha256:string}}>;
|
|
8
|
+
freeze(input:{intent:PublishingIntent;prepared:Pick<PreparedSolutionPackage,'files'|'manifestBytes'>;acceptanceArchive?:import('./acceptance-delivery.mjs').AcceptanceArchive;acceptanceTarget?:{origin:string;keyId:string;publicKeySha256:string};signal?:AbortSignal}):Promise<{requestId:string;content:{manifestSha256:string}}>;
|
|
9
|
+
readAcceptanceArchive(input:{requestId:string;signal?:AbortSignal}):Promise<{intent:PublishingIntent;archive:import('./acceptance-delivery.mjs').AcceptanceArchiveIdentity;bytes:Uint8Array}|undefined>;
|
|
10
|
+
acceptanceMetadata(input:{requestId:string;signal?:AbortSignal}):Promise<{intent:PublishingIntent;archive:import('./acceptance-delivery.mjs').AcceptanceArchiveIdentity}|undefined>;
|
|
9
11
|
read(input:{requestId:string;signal?:AbortSignal}):Promise<{intent:PublishingIntent;prepared:PreparedSolutionPackage}>;
|
|
10
|
-
create(input:{requestId:string;signal?:AbortSignal}):Promise<PublishingSessionResult>;
|
|
11
|
-
observe(input:{requestId:string;stage?:'create'|'commit';signal?:AbortSignal}):Promise<PublishingSessionResult>;
|
|
12
|
+
create(input:{requestId:string;attempt?:number;signal?:AbortSignal}):Promise<PublishingSessionResult>;
|
|
13
|
+
observe(input:{requestId:string;stage?:'create'|'commit';attempt?:number;signal?:AbortSignal}):Promise<PublishingSessionResult>;
|
|
12
14
|
upload(input:{requestId:string;signal?:AbortSignal}):Promise<PublishingStatus>;
|
|
13
15
|
queue(input:{requestId:string;signal?:AbortSignal}):Promise<PublishingSessionResult>;
|
|
14
16
|
/** Source-free controls use the immutable original intent, without reading payload blobs. */
|
package/src/node/session.mjs
CHANGED
|
@@ -3,10 +3,17 @@ import {bindArtifactOperation,performArtifactOperation,observeArtifactOperation}
|
|
|
3
3
|
import {createPublishingClient} from '../client.mjs';
|
|
4
4
|
import {parsePublishingConfiguration,parsePublishingIntent,publishingIntentBytes,publishingRequestId,protocolRecord,publishingError} from '../protocol.mjs';
|
|
5
5
|
import {verifySolutionPackageBytes} from './solution-package.mjs';
|
|
6
|
+
import {maximumAcceptanceArchiveBytes} from './acceptance-delivery.mjs';
|
|
7
|
+
import {publishingDigest} from '../protocol.mjs';
|
|
6
8
|
|
|
7
9
|
const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
8
10
|
const encoded=value=>new TextEncoder().encode(JSON.stringify(value));
|
|
9
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
|
+
}
|
|
10
17
|
const operationDefaults={timeoutMilliseconds:30000,closeTimeoutMilliseconds:2000};
|
|
11
18
|
function checkBinding(intent,prepared,configuration){
|
|
12
19
|
const item=intent.package,descriptor=prepared.descriptor;
|
|
@@ -20,7 +27,11 @@ function transportFor({client,intent,manifestBytes,target,configurationSha256,st
|
|
|
20
27
|
};
|
|
21
28
|
return {transport:{
|
|
22
29
|
target,capability:stage==='create'?'artifact-upload':'deployment-create',configurationSha256,
|
|
23
|
-
async execute(_binding,context){
|
|
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
|
+
},
|
|
24
35
|
async observe(binding,_reference,context){
|
|
25
36
|
try{await run(context.signal,async signal=>{status=await client.getStatus({intent,signal});});}
|
|
26
37
|
catch(error){if(error.code==='PUBLISHING_REQUEST_NOT_FOUND')return {state:'absent',fingerprint:binding.fingerprint};throw error;}
|
|
@@ -44,7 +55,10 @@ export function createPublishingSession({journal,configuration,credential,allowL
|
|
|
44
55
|
const key=requestId=>{if(!publishingRequestId(requestId))throw fail('REQUEST_ID_INVALID');return 'request:'+requestId;};
|
|
45
56
|
const metadata=async({requestId,signal})=>{
|
|
46
57
|
const record=await journal.load(key(requestId),{signal});if(!record)throw fail('FROZEN_REQUEST_MISSING');const saved=record.payload;
|
|
47
|
-
if(record.revision!==1||!protocolRecord(saved,['schemaVersion','configuration','intent','manifestByteLength'])||saved.schemaVersion!==1||!Number.isSafeInteger(saved.manifestByteLength)||saved.manifestByteLength<1||saved.manifestByteLength>1048576)throw fail('FROZEN_REQUEST_INVALID');
|
|
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');
|
|
48
62
|
if(hash(encoded(parsePublishingConfiguration(saved.configuration,{allowLoopback})))!==configurationSha256)throw fail('CONFIGURATION_CHANGED');
|
|
49
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};
|
|
50
64
|
};
|
|
@@ -57,26 +71,45 @@ export function createPublishingSession({journal,configuration,credential,allowL
|
|
|
57
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});}
|
|
58
72
|
const prepared=await verifySolutionPackageBytes({files,manifestBytes,expectedContent:intent.package.content,pathCaseSensitivity,limits:selectedLimits,signal});checkBinding(intent,prepared,config);return {intent,prepared};
|
|
59
73
|
};
|
|
60
|
-
const operation=async(mode,{requestId,signal,stage='create'})=>{
|
|
61
|
-
if(!['create','commit'].includes(stage))throw fail('SESSION_INPUT_INVALID');
|
|
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');
|
|
62
76
|
const {intent,saved}=await metadata({requestId,signal}),frozen=mode==='create'?await read({requestId,signal}):undefined,intentBytes=publishingIntentBytes(intent);
|
|
63
77
|
const target={provider:'link-light-publishing',namespace:config.projectId,endpoint:config.serviceUrl};
|
|
64
|
-
const
|
|
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}]});
|
|
65
80
|
const current=transportFor({client,intent,manifestBytes:frozen?.prepared.manifestBytes,target,configurationSha256,stage});
|
|
66
81
|
const receipt=await(mode==='create'?performArtifactOperation:observeArtifactOperation)(current.transport,binding,journal.operationJournal(),{...selectedOperations,signal});
|
|
67
82
|
return {receipt,...(current.status()?{status:current.status()}:{})};
|
|
68
83
|
};
|
|
69
84
|
return Object.freeze({
|
|
70
|
-
async freeze({intent:input,prepared:inputPackage,signal}){
|
|
85
|
+
async freeze({intent:input,prepared:inputPackage,acceptanceArchive,acceptanceTarget,signal}){
|
|
71
86
|
const intent=parsePublishingIntent(input);key(intent.requestId);
|
|
72
87
|
if(await journal.load(key(intent.requestId),{signal}))throw fail('REQUEST_EXISTS');
|
|
73
88
|
const prepared=await verifySolutionPackageBytes({files:inputPackage.files,manifestBytes:inputPackage.manifestBytes,expectedContent:intent.package.content,pathCaseSensitivity,limits:selectedLimits,signal});checkBinding(intent,prepared,config);
|
|
74
89
|
const files=new Map(prepared.manifest.files.map(file=>[file.path,file]));
|
|
75
90
|
const blobs=[{sha256:prepared.content.manifestSha256,bytes:prepared.manifestBytes},...prepared.files.map(file=>({sha256:files.get(file.path).sha256,bytes:file.bytes}))];
|
|
76
|
-
|
|
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});
|
|
77
99
|
if(result!=='stored')throw fail('REQUEST_EXISTS');return {requestId:intent.requestId,content:prepared.content};
|
|
78
100
|
},
|
|
79
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
|
+
},
|
|
80
113
|
create:input=>operation('create',{...input,stage:'create'}),
|
|
81
114
|
observe:input=>operation('observe',input),
|
|
82
115
|
queue:input=>operation('create',{...input,stage:'commit'}),
|
|
@@ -0,0 +1,103 @@
|
|
|
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
|
+
}
|
package/src/node/workflow.d.mts
CHANGED
|
@@ -4,10 +4,11 @@ import type {PublishingJournal} from './journal.mjs';
|
|
|
4
4
|
import type {PreparedSolutionPackage} from './solution-package.mjs';
|
|
5
5
|
import type {PublishingMetadataTransport as ReleaseMetadataTransport} from '../protocol.mjs';
|
|
6
6
|
export interface PublishingSourceProducer {
|
|
7
|
-
prepare(input:{root:string;project:PublishingProject;signal?:AbortSignal;requestId:string}):Promise<{prepared:PreparedSolutionPackage;processesClosed:true}>;
|
|
7
|
+
prepare(input:{root:string;project:PublishingProject;signal?:AbortSignal;requestId:string;includeAcceptanceArchive?:boolean}):Promise<{prepared:PreparedSolutionPackage;acceptanceArchive?:import('./acceptance-delivery.mjs').AcceptanceArchive;processesClosed:true}>;
|
|
8
8
|
}
|
|
9
9
|
export interface PublishingWorkflowOptions {
|
|
10
10
|
root:string;journal:PublishingJournal;configuration:PublishingConfiguration;credential:string;
|
|
11
|
+
acceptanceDelivery?:import('./acceptance-delivery.mjs').AcceptanceDeliveryCredential;
|
|
11
12
|
allowLoopback?:boolean;request?:typeof fetch;clientLimits?:PublishingClientLimits;
|
|
12
13
|
pathCaseSensitivity?:'case-sensitive'|'case-insensitive';metadataTransport?:ReleaseMetadataTransport;
|
|
13
14
|
operationLimits?:{timeoutMilliseconds:number;closeTimeoutMilliseconds:number};
|
|
@@ -16,6 +17,7 @@ export interface PublishingWorkflowResult {
|
|
|
16
17
|
requestId?:string;
|
|
17
18
|
state:'empty'|'checked'|'preparation-unknown'|'preparation-failed'|'uploading'|'queued'|'deploying'|'registered'|'awaiting-acceptance'|'active'|'failed'|'unknown'|'abandoned'|'superseded';
|
|
18
19
|
active:boolean;sideEffects?:'none'|'pending'|'unknown'|'closed';timedOut?:true;
|
|
20
|
+
error?:{code:string};
|
|
19
21
|
}
|
|
20
22
|
export interface PublishingSourceOptions {producer?:string;newPreparation?:boolean;signal?:AbortSignal}
|
|
21
23
|
export interface PublishingPublishOptions extends PublishingSourceOptions {
|
package/src/node/workflow.mjs
CHANGED
|
@@ -1,28 +1,34 @@
|
|
|
1
1
|
import fs from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import {pathToFileURL} from 'node:url';
|
|
4
|
-
import {randomUUID} from 'node:crypto';
|
|
4
|
+
import {createHash,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 {checkoutReleaseVersion,checkoutRequiresAcceptanceDelivery,selectProducerFile,validateLocalProducer} from './source-producer.mjs';
|
|
12
|
+
import {acceptanceDeliveryTarget,deliverAcceptanceArchive,maximumAcceptanceArchiveBytes,observeAcceptanceDelivery} from './acceptance-delivery.mjs';
|
|
12
13
|
|
|
13
14
|
const fail=code=>publishingError(code),sourceKey=id=>'source:'+id;
|
|
15
|
+
const rejectedDelivery=new Set(['PUBLISHING_ACCEPTANCE_VERSION_CONFLICT','PUBLISHING_ACCEPTANCE_SIGNATURE_INVALID','PUBLISHING_ACCEPTANCE_DELIVERY_REJECTED']);
|
|
16
|
+
function newerVersion(candidate,original){
|
|
17
|
+
const parts=candidate.split('.').map(Number),previous=original.split('.').map(Number);
|
|
18
|
+
const index=parts.findIndex((part,n)=>part!==previous[n]);
|
|
19
|
+
return index>=0&&parts[index]>previous[index];
|
|
20
|
+
}
|
|
21
|
+
function versionRequestId(configuration,packageName,version){
|
|
22
|
+
const bytes=createHash('sha256').update(JSON.stringify(['link-light/project-version/v1',configuration.serviceUrl,configuration.projectId,packageName,version])).digest().subarray(0,16);
|
|
23
|
+
bytes[6]=(bytes[6]&15)|128;bytes[8]=(bytes[8]&63)|128;
|
|
24
|
+
const hex=bytes.toString('hex');
|
|
25
|
+
return [hex.slice(0,8),hex.slice(8,12),hex.slice(12,16),hex.slice(16,20),hex.slice(20)].join('-');
|
|
26
|
+
}
|
|
14
27
|
const sourceOptions=input=>{
|
|
15
28
|
if(!protocolRecord(input,[],['producer','newPreparation','signal'])||input.newPreparation!==undefined&&typeof input.newPreparation!=='boolean')throw fail('WORKFLOW_INPUT_INVALID');
|
|
16
|
-
|
|
29
|
+
if(input.producer!==undefined)validateLocalProducer(input.producer);
|
|
30
|
+
return input;
|
|
17
31
|
};
|
|
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
32
|
|
|
27
33
|
/** One active request per project/client journal. Recovery never imports source
|
|
28
34
|
* or performs an operation whose durable Foundation claim already exists. */
|
|
@@ -34,16 +40,21 @@ export function createPublishingWorkflow(options){
|
|
|
34
40
|
const shared={journal,configuration,credential,allowLoopback,...(request?{request}:{}),...(clientLimits?{clientLimits}:{})};
|
|
35
41
|
const client=signal=>createPublishingClient({...shared,...(clientLimits?{limits:clientLimits}:{}),verifyActivation:verifier(signal)}),activeKey='active:'+configuration.projectId;
|
|
36
42
|
const session=(record,signal)=>createPublishingSession({...shared,verifyActivation:verifier(signal),packageLimits:record.payload.project.limits,pathCaseSensitivity:record.payload.pathCaseSensitivity,...(operationLimits?{operationLimits}:{})});
|
|
37
|
-
const replace=async(record,phase,signal,failure)=>{
|
|
38
|
-
const payload={...record.payload,phase,...(
|
|
43
|
+
const replace=async(record,phase,signal,failure,createAttempt=record.payload.createAttempt)=>{
|
|
44
|
+
const payload={...record.payload,phase,...(createAttempt?{createAttempt}:{})};delete payload.failure;
|
|
45
|
+
if(failure)payload.failure=failure;
|
|
46
|
+
const result=await journal.compareAndSet({key:sourceKey(payload.requestId),expectedRevision:record.revision,payload},{signal});
|
|
39
47
|
if(result!=='stored')throw fail('WORKFLOW_CONFLICT');return {revision:record.revision+1,payload};
|
|
40
48
|
};
|
|
41
49
|
const current=async signal=>{
|
|
42
50
|
const active=await journal.load(activeKey,{signal});if(!active)return undefined;
|
|
43
51
|
if(!protocolRecord(active.payload,['schemaVersion','requestId'])||active.payload.schemaVersion!==1||!publishingRequestId(active.payload.requestId))throw fail('WORKFLOW_STATE_INVALID');
|
|
44
52
|
let record=await journal.load(sourceKey(active.payload.requestId),{signal});
|
|
45
|
-
if(!record||!protocolRecord(record.payload,['schemaVersion','requestId','phase','project','pathCaseSensitivity'],['failure'])||record.payload.schemaVersion!==1||record.payload.requestId!==active.payload.requestId||!['preparing','failed-closed','frozen','remote','abandoned','completed','failed'].includes(record.payload.phase)||!['case-sensitive','case-insensitive'].includes(record.payload.pathCaseSensitivity))throw fail('WORKFLOW_STATE_INVALID');
|
|
46
|
-
if(record.payload.
|
|
53
|
+
if(!record||!protocolRecord(record.payload,['schemaVersion','requestId','phase','project','pathCaseSensitivity'],['failure','selectedVersion','createAttempt'])||record.payload.schemaVersion!==1||record.payload.requestId!==active.payload.requestId||!['preparing','failed-closed','frozen','delivering','delivery-rejected','remote','abandoned','completed','failed'].includes(record.payload.phase)||!['case-sensitive','case-insensitive'].includes(record.payload.pathCaseSensitivity))throw fail('WORKFLOW_STATE_INVALID');
|
|
54
|
+
if(record.payload.createAttempt!==undefined&&(!Number.isSafeInteger(record.payload.createAttempt)||record.payload.createAttempt<1||record.payload.createAttempt>64))throw fail('WORKFLOW_STATE_INVALID');
|
|
55
|
+
if(record.payload.failure!==undefined&&(!protocolRecord(record.payload.failure,['code'])||
|
|
56
|
+
!(record.payload.phase==='failed-closed'&&['PUBLISHING_SOURCE_PACKAGE_BINDING_INVALID','PUBLISHING_SOURCE_PREPARATION_FAILED','PUBLISHING_ACCEPTANCE_VERSION_CONFLICT'].includes(record.payload.failure.code)||
|
|
57
|
+
record.payload.phase==='delivery-rejected'&&rejectedDelivery.has(record.payload.failure.code))))throw fail('WORKFLOW_STATE_INVALID');
|
|
47
58
|
const project=parsePublishingProject(record.payload.project,{allowLoopback});if(JSON.stringify(project.configuration)!==JSON.stringify(configuration))throw fail('CONFIGURATION_CHANGED');
|
|
48
59
|
// freeze is the atomic authority: losing the outer acknowledgment must never
|
|
49
60
|
// cause a second import, build, capture or request identity.
|
|
@@ -53,45 +64,115 @@ export function createPublishingWorkflow(options){
|
|
|
53
64
|
return {active,record};
|
|
54
65
|
};
|
|
55
66
|
const result=(record,state,extra={})=>({requestId:record.payload.requestId,state,active:state==='active',...extra});
|
|
56
|
-
const operationClaim=(id,stage,signal)=>journal.load('operation:'+id+'.'+stage,{signal});
|
|
67
|
+
const operationClaim=(id,stage,signal,attempt=0)=>journal.load('operation:'+id+'.'+stage+(attempt?'.'+attempt:''),{signal});
|
|
68
|
+
const rejectedCreate=claim=>claim?.payload?.writeState==='rejected'&&claim.payload.attemptFailure==='CONFLICT';
|
|
57
69
|
const prepare=async input=>{
|
|
58
|
-
const {producer,
|
|
70
|
+
const {producer,signal}=sourceOptions(input);let {newPreparation=false}=input;
|
|
71
|
+
let previous=await current(signal),automatic=false,previousCreateRejected=false;
|
|
72
|
+
if(previous?.record.payload.phase==='failed-closed'&&previous.record.payload.selectedVersion&&!newPreparation){
|
|
73
|
+
const version=await checkoutReleaseVersion(root,previous.record.payload.project.packageName);
|
|
74
|
+
newPreparation=Boolean(version&&newerVersion(version,previous.record.payload.selectedVersion));
|
|
75
|
+
}
|
|
76
|
+
if(previous&&!newPreparation&&['remote','completed','failed','abandoned','delivery-rejected'].includes(previous.record.payload.phase)){
|
|
77
|
+
const original=await journal.load('request:'+previous.record.payload.requestId,{signal});
|
|
78
|
+
const originalPackage=original?.payload?.intent?.package;
|
|
79
|
+
if(originalPackage){
|
|
80
|
+
// A checkout is optional when resuming. Only a valid, explicitly higher owner
|
|
81
|
+
// version can select another identity. Its producer is loaded after closure.
|
|
82
|
+
const version=await checkoutReleaseVersion(root,originalPackage.packageName).catch(()=>undefined);
|
|
83
|
+
if((version===undefined||version===originalPackage.version)&&['completed','failed','delivery-rejected'].includes(previous.record.payload.phase))return previous.record;
|
|
84
|
+
if(version&&version!==originalPackage.version){
|
|
85
|
+
if(newerVersion(version,originalPackage.version)){automatic=true;newPreparation=true;}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
59
89
|
if(previous&&newPreparation&&['remote','completed','failed'].includes(previous.record.payload.phase)){
|
|
60
90
|
// Observe the original identity and current admission before permitting the
|
|
61
91
|
// next release. A prior terminal observation never authorizes an unknown,
|
|
62
92
|
// still-running or currently unverified request to be replaced.
|
|
63
93
|
const observed=await inspect({signal},true);
|
|
64
|
-
if(observed.sideEffects!=='closed'||!['abandoned','active','failed'].includes(observed.state))
|
|
94
|
+
if(observed.sideEffects!=='closed'||!['abandoned','active','failed'].includes(observed.state)){
|
|
95
|
+
if(automatic)return {observed:{...observed,active:false}};
|
|
96
|
+
throw fail('SOURCE_ACTIVE_REQUEST_EXISTS');
|
|
97
|
+
}
|
|
98
|
+
previousCreateRejected=observed.error?.code==='PUBLISHING_CONFLICT'&&observed.sideEffects==='closed';
|
|
65
99
|
previous=await current(signal);
|
|
66
100
|
}
|
|
67
101
|
if(previous){
|
|
68
102
|
const phase=previous.record.payload.phase;
|
|
69
103
|
if(phase==='preparing')throw fail('SOURCE_PREPARATION_UNKNOWN');
|
|
70
|
-
if(
|
|
104
|
+
if(['frozen','delivering','remote'].includes(phase)){
|
|
105
|
+
if(!newPreparation)return previous.record;
|
|
106
|
+
if(phase!=='remote'||!previousCreateRejected)throw fail('SOURCE_ACTIVE_REQUEST_EXISTS');
|
|
107
|
+
}
|
|
71
108
|
if(!newPreparation)throw fail('SOURCE_NEW_PREPARATION_REQUIRED');
|
|
72
109
|
}
|
|
73
110
|
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})
|
|
75
|
-
|
|
111
|
+
const project=await client(signal).getProject({signal});
|
|
112
|
+
let file,selectionFailure;
|
|
113
|
+
try{file=await selectProducerFile(root,producer);}
|
|
114
|
+
catch(cause){selectionFailure=new PublishingSourceError({cause,processesClosed:true});}
|
|
115
|
+
const deliver=Boolean(options.acceptanceDelivery);
|
|
116
|
+
if(!selectionFailure&&!producer&&await checkoutRequiresAcceptanceDelivery(root)&&!deliver)throw fail('ACCEPTANCE_CREDENTIAL_REQUIRED');
|
|
117
|
+
let inherited,selectedVersion,requestId=randomUUID();
|
|
118
|
+
if(deliver){
|
|
119
|
+
const version=await checkoutReleaseVersion(root,project.packageName);
|
|
120
|
+
if(!version)throw fail('SOURCE_PACKAGE_BINDING_INVALID');
|
|
121
|
+
selectedVersion=version;
|
|
122
|
+
const latest=await client(signal).getLatestRelease({signal});
|
|
123
|
+
if(latest&&(latest.intent.package.packageName!==project.packageName||latest.intent.package.solutionId!==project.solutionId))throw fail('PROJECT_BINDING_INVALID');
|
|
124
|
+
if(latest?.intent.package.version===version){
|
|
125
|
+
inherited=latest.intent;
|
|
126
|
+
requestId=inherited.requestId;
|
|
127
|
+
}else{
|
|
128
|
+
if(latest&&(!['active','failed','superseded'].includes(latest.status.state)||latest.status.sideEffects!=='closed')){
|
|
129
|
+
return {observed:{requestId:latest.intent.requestId,state:latest.status.state,sideEffects:latest.status.sideEffects,active:false}};
|
|
130
|
+
}
|
|
131
|
+
if(latest&&!newerVersion(version,latest.intent.package.version))throw fail('SOURCE_VERSION_NOT_NEWER');
|
|
132
|
+
requestId=versionRequestId(configuration,project.packageName,version);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
signal?.throwIfAborted();
|
|
136
|
+
const payload={schemaVersion:1,requestId,project,pathCaseSensitivity,...(selectedVersion?{selectedVersion}:{}),...(selectionFailure?{phase:'failed-closed',failure:{code:selectionFailure.code}}:{phase:'preparing'})};
|
|
137
|
+
const retry=previous?.record.payload.requestId===requestId&&previous.record.payload.phase==='failed-closed'&&newPreparation;
|
|
138
|
+
const sourceRevision=retry?previous.record.revision:0;
|
|
139
|
+
if(await journal.compareAndSet({key:sourceKey(requestId),expectedRevision:sourceRevision,payload},{signal})!=='stored')throw fail('WORKFLOW_CONFLICT');
|
|
76
140
|
if(await journal.compareAndSet({key:activeKey,expectedRevision:previous?.active.revision??0,payload:{schemaVersion:1,requestId}},{signal})!=='stored')throw fail('WORKFLOW_CONFLICT');
|
|
77
|
-
|
|
141
|
+
if(selectionFailure)throw selectionFailure;
|
|
142
|
+
let record={revision:sourceRevision+1,payload},prepared,intent,acceptanceArchive,processesClosed=false;
|
|
78
143
|
try{
|
|
79
|
-
const
|
|
144
|
+
const producerModule=await import(pathToFileURL(file).href+'?publishingRequest='+requestId);
|
|
80
145
|
if(typeof producerModule.prepare!=='function')throw fail('SOURCE_PORT_INVALID');
|
|
81
|
-
const response=await producerModule.prepare({root,project:structuredClone(project),signal,requestId});
|
|
82
|
-
if(!protocolRecord(response,['prepared','processesClosed'])||response.processesClosed!==true)throw fail('SOURCE_PROCESS_CLOSURE_UNKNOWN');processesClosed=true;prepared=response.prepared;
|
|
146
|
+
const response=await producerModule.prepare({root,project:structuredClone(project),signal,requestId,...(deliver?{includeAcceptanceArchive:true}:{})});
|
|
147
|
+
if(!protocolRecord(response,['prepared','processesClosed'],['acceptanceArchive'])||response.processesClosed!==true)throw fail('SOURCE_PROCESS_CLOSURE_UNKNOWN');processesClosed=true;prepared=response.prepared;acceptanceArchive=response.acceptanceArchive;
|
|
83
148
|
const item=prepared?.descriptor;
|
|
149
|
+
if(deliver&&(!acceptanceArchive||!(acceptanceArchive.bytes instanceof Uint8Array)||!acceptanceArchive.bytes.length||
|
|
150
|
+
acceptanceArchive.bytes.length>maximumAcceptanceArchiveBytes||!/^[a-f0-9]{64}$/.test(acceptanceArchive.artifactSha256)))throw fail('SOURCE_PACKAGE_BINDING_INVALID');
|
|
151
|
+
if(!deliver&&acceptanceArchive)throw fail('SOURCE_PACKAGE_BINDING_INVALID');
|
|
84
152
|
if(!item||item.solutionId!==project.solutionId||item.packageName!==project.packageName||item.publisherId!==configuration.publisher.publisherId)throw fail('SOURCE_PACKAGE_BINDING_INVALID');
|
|
153
|
+
if(!producer){
|
|
154
|
+
const expected=await checkoutReleaseVersion(root,project.packageName);
|
|
155
|
+
if(expected!==undefined&&item.version!==expected)throw fail('SOURCE_PACKAGE_BINDING_INVALID');
|
|
156
|
+
}
|
|
85
157
|
intent=parsePublishingIntent({schemaVersion:1,requestId,projectId:configuration.projectId,policyRevision:project.policyRevision,package:{solutionId:item.solutionId,publisherId:item.publisherId,packageName:item.packageName,version:item.version,content:prepared.content,fileCount:prepared.files.length,totalBytes:prepared.payloadBytes}});
|
|
158
|
+
if(inherited){
|
|
159
|
+
if(JSON.stringify(intent.package)!==JSON.stringify(inherited.package))throw fail('ACCEPTANCE_VERSION_CONFLICT');
|
|
160
|
+
intent=inherited;
|
|
161
|
+
}
|
|
86
162
|
}catch(error){
|
|
87
|
-
if(processesClosed||error instanceof PublishingSourceError&&error.processesClosed){
|
|
163
|
+
if(processesClosed||error instanceof PublishingSourceError&&error.processesClosed){
|
|
164
|
+
const code=['PUBLISHING_SOURCE_PACKAGE_BINDING_INVALID','PUBLISHING_ACCEPTANCE_VERSION_CONFLICT'].includes(error.code)?error.code:'PUBLISHING_SOURCE_PREPARATION_FAILED';
|
|
165
|
+
await replace(record,'failed-closed',signal,{code});
|
|
166
|
+
if(code==='PUBLISHING_ACCEPTANCE_VERSION_CONFLICT')throw error;
|
|
167
|
+
throw new PublishingSourceError({cause:error,processesClosed:true});
|
|
168
|
+
}
|
|
88
169
|
throw new PublishingSourceError({cause:error,processesClosed:false});
|
|
89
170
|
}
|
|
90
171
|
// Freeze and its acknowledgment deliberately remain outside the known-closed
|
|
91
172
|
// source catch: a storage error can mean the original bytes were committed.
|
|
92
|
-
await session(record,signal).freeze({intent,prepared,signal});record=await replace(record,'frozen',signal);return record;
|
|
173
|
+
await session(record,signal).freeze({intent,prepared,acceptanceArchive,acceptanceTarget:deliver?acceptanceDeliveryTarget(options.acceptanceDelivery):undefined,signal});record=await replace(record,'frozen',signal);return record;
|
|
93
174
|
};
|
|
94
|
-
const local=record=>result(record,['frozen','remote'].includes(record.payload.phase)?'checked':record.payload.phase==='preparing'?'preparation-unknown':record.payload.phase==='failed-closed'?'preparation-failed':record.payload.phase==='abandoned'?'abandoned':'unknown');
|
|
175
|
+
const local=record=>result(record,['frozen','remote','completed','failed'].includes(record.payload.phase)?'checked':record.payload.phase==='preparing'?'preparation-unknown':record.payload.phase==='failed-closed'?'preparation-failed':record.payload.phase==='abandoned'?'abandoned':'unknown');
|
|
95
176
|
const observedResult=async(record,status,signal)=>{
|
|
96
177
|
// The client/session authenticated this exact original intent, and ACTIVE
|
|
97
178
|
// already passed the real signature and current Core-admission verifier.
|
|
@@ -106,13 +187,31 @@ export function createPublishingWorkflow(options){
|
|
|
106
187
|
return result(record,status.state,{sideEffects:status.sideEffects});
|
|
107
188
|
};
|
|
108
189
|
const inspect=async({signal}={},observe=false,dispatchRecovery=false)=>{
|
|
109
|
-
const state=await current(signal);
|
|
190
|
+
const state=await current(signal);
|
|
191
|
+
if(!state){
|
|
192
|
+
const latest=options.acceptanceDelivery?await client(signal).getLatestRelease({signal}):undefined;
|
|
193
|
+
return latest?{requestId:latest.intent.requestId,state:latest.status.state,sideEffects:latest.status.sideEffects,active:latest.status.state==='active'}:{state:'empty',active:false};
|
|
194
|
+
}
|
|
195
|
+
const {record}=state;
|
|
196
|
+
if(record.payload.phase==='delivery-rejected')return result(record,'failed',{sideEffects:'closed',error:record.payload.failure});
|
|
197
|
+
if(record.payload.phase==='delivering'){
|
|
198
|
+
const bundle=await session(record,signal).acceptanceMetadata({requestId:record.payload.requestId,signal});
|
|
199
|
+
try{
|
|
200
|
+
if(!bundle||JSON.stringify(bundle.target)!==JSON.stringify(acceptanceDeliveryTarget(options.acceptanceDelivery)))throw fail('ACCEPTANCE_TRUST_CHANGED');
|
|
201
|
+
if(await observeAcceptanceDelivery({...bundle,credential:options.acceptanceDelivery,request,signal}))return result(record,'checked');
|
|
202
|
+
}catch(error){if(error?.code==='PUBLISHING_ACCEPTANCE_VERSION_CONFLICT'){
|
|
203
|
+
await replace(record,'delivery-rejected',signal,{code:error.code});
|
|
204
|
+
return result(record,'failed',{sideEffects:'closed',error:{code:error.code}});
|
|
205
|
+
}}
|
|
206
|
+
return result(record,'unknown');
|
|
207
|
+
}
|
|
110
208
|
if(!['frozen','remote','completed','failed'].includes(record.payload.phase))return local(record);
|
|
111
|
-
const requestId=record.payload
|
|
209
|
+
const {requestId,createAttempt:attempt=0}=record.payload,commit=await operationClaim(requestId,'commit',signal),create=await operationClaim(requestId,'create',signal,attempt);
|
|
210
|
+
if(!commit&&rejectedCreate(create))return result(record,'failed',{sideEffects:'closed',error:{code:'PUBLISHING_CONFLICT'}});
|
|
112
211
|
if(!commit&&!create)return local(record);
|
|
113
212
|
const selected=session(record,signal);
|
|
114
213
|
if(observe){
|
|
115
|
-
const observed=await selected.observe({requestId,stage:commit?'commit':'create',signal});if(!observed.status)return result(record,'unknown');
|
|
214
|
+
const observed=await selected.observe({requestId,stage:commit?'commit':'create',attempt:commit?0:attempt,signal});if(!observed.status)return result(record,'unknown');
|
|
116
215
|
// The control only asks the host to observe an already committed original
|
|
117
216
|
// operation. Uploading/local preparation never dispatches provider work.
|
|
118
217
|
const status=dispatchRecovery&&commit&&['queued','deploying','awaiting-acceptance','unknown'].includes(observed.status.state)?await selected.recover({requestId,signal}):observed.status;
|
|
@@ -133,17 +232,42 @@ export function createPublishingWorkflow(options){
|
|
|
133
232
|
}catch(error){if(timeout.aborted&&!signal?.aborted)return {...latest,timedOut:true};throw error;}
|
|
134
233
|
};
|
|
135
234
|
return Object.freeze({
|
|
136
|
-
async check(input={}){
|
|
235
|
+
async check(input={}){
|
|
236
|
+
const record=await prepare(input);
|
|
237
|
+
if(record.observed)return record.observed;
|
|
238
|
+
if(['delivering','delivery-rejected'].includes(record.payload.phase))return inspect({signal:input.signal},true);
|
|
239
|
+
return local(record);
|
|
240
|
+
},
|
|
137
241
|
async publish(input={}){
|
|
138
242
|
if(!protocolRecord(input,[],['producer','newPreparation','signal','waitMs','pollMs']))throw fail('WORKFLOW_INPUT_INVALID');
|
|
139
243
|
const {waitMs=0,pollMs=1000,...source}=input;
|
|
140
244
|
if(!Number.isSafeInteger(waitMs)||waitMs<0||waitMs>3600000||!Number.isSafeInteger(pollMs)||pollMs<1||pollMs>30000)throw fail('WORKFLOW_INPUT_INVALID');
|
|
141
|
-
let record=await prepare(source);
|
|
245
|
+
let record=await prepare(source);
|
|
246
|
+
if(record.observed)return record.observed;
|
|
247
|
+
const requestId=record.payload.requestId,signal=input.signal,finish=status=>waitFor(record,status,{signal,waitMs,pollMs});
|
|
142
248
|
// This CAS competes with local abandonment before any remote write. Once
|
|
143
249
|
// remote publication may start, absence of a later claim is not a closure
|
|
144
250
|
// proof for an overlapping client.
|
|
145
|
-
if(record.payload.phase==='frozen')record=await replace(record,'remote',signal);
|
|
146
251
|
const selected=session(record,signal);
|
|
252
|
+
// Delivery is an immutable owner-side installation. Keep the original
|
|
253
|
+
// request frozen until its exact version and both digests can be read back.
|
|
254
|
+
if(['frozen','delivering','delivery-rejected'].includes(record.payload.phase)){
|
|
255
|
+
const bundle=await selected.readAcceptanceArchive({requestId,signal});
|
|
256
|
+
if(bundle){
|
|
257
|
+
if(!options.acceptanceDelivery||JSON.stringify(bundle.target)!==JSON.stringify(acceptanceDeliveryTarget(options.acceptanceDelivery)))return result(record,'failed',{error:{code:'PUBLISHING_ACCEPTANCE_TRUST_CHANGED'}});
|
|
258
|
+
if(record.payload.phase!=='delivering')record=await replace(record,'delivering',signal);
|
|
259
|
+
try{await deliverAcceptanceArchive({...bundle,credential:options.acceptanceDelivery,request,signal});}
|
|
260
|
+
catch(error){
|
|
261
|
+
const code=error?.code;
|
|
262
|
+
if(rejectedDelivery.has(code)){
|
|
263
|
+
await replace(record,'delivery-rejected',signal,{code});
|
|
264
|
+
return result(record,'failed',{sideEffects:'closed',error:{code}});
|
|
265
|
+
}
|
|
266
|
+
return result(record,'unknown',{error:{code:'PUBLISHING_ACCEPTANCE_DELIVERY_UNKNOWN'}});
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
record=await replace(record,'remote',signal);
|
|
270
|
+
}
|
|
147
271
|
// Never repeat creation, upload or commit after the original commit claim.
|
|
148
272
|
// A healthy confirmed original may ask the host for its known next step;
|
|
149
273
|
// unknown requires explicit recovery and cannot perform on publish.
|
|
@@ -152,7 +276,23 @@ export function createPublishingWorkflow(options){
|
|
|
152
276
|
if(['queued','deploying'].includes(original.state))return finish(await observedResult(record,await selected.resume({requestId,signal}),signal));
|
|
153
277
|
return finish(original);
|
|
154
278
|
}
|
|
155
|
-
|
|
279
|
+
let attempt=record.payload.createAttempt??0,createClaim=await operationClaim(requestId,'create',signal,attempt);
|
|
280
|
+
if(rejectedCreate(createClaim)){
|
|
281
|
+
const latest=await client(signal).getLatestRelease({signal});
|
|
282
|
+
if(latest&&latest.status.sideEffects!=='closed')return {requestId:latest.intent.requestId,state:latest.status.state,sideEffects:latest.status.sideEffects,active:false};
|
|
283
|
+
const version=record.payload.selectedVersion??(await journal.load('request:'+requestId,{signal})).payload.intent.package.version;
|
|
284
|
+
if(latest&&latest.intent.package.version===version||attempt>=64)return result(record,'failed',{sideEffects:'closed',error:{code:'PUBLISHING_CONFLICT'}});
|
|
285
|
+
// An authenticated rejection is durable. Advance only after observing
|
|
286
|
+
// closure. Unknown create acknowledgements always use the original claim.
|
|
287
|
+
record=await replace(record,'remote',signal,undefined,++attempt);
|
|
288
|
+
createClaim=undefined;
|
|
289
|
+
}
|
|
290
|
+
let created;
|
|
291
|
+
try{created=await(createClaim?selected.observe({requestId,stage:'create',attempt,signal}):selected.create({requestId,attempt,signal}));}
|
|
292
|
+
catch(error){
|
|
293
|
+
if(rejectedCreate(await operationClaim(requestId,'create',signal,attempt)))return result(record,'failed',{sideEffects:'closed',error:{code:'PUBLISHING_CONFLICT'}});
|
|
294
|
+
throw error;
|
|
295
|
+
}
|
|
156
296
|
if(created.receipt.outcome!=='succeeded')return result(record,'unknown');
|
|
157
297
|
if(created.status&&created.status.state!=='uploading')return finish(await observedResult(record,created.status,signal));
|
|
158
298
|
const uploaded=await selected.upload({requestId,signal});if(uploaded.state!=='uploading')return finish(await observedResult(record,uploaded,signal));
|
|
@@ -166,7 +306,9 @@ export function createPublishingWorkflow(options){
|
|
|
166
306
|
if(record.payload.phase==='preparing')throw fail('SOURCE_PREPARATION_UNKNOWN');if(!['frozen','remote'].includes(record.payload.phase))throw fail('ABANDON_UNSAFE');
|
|
167
307
|
const requestId=record.payload.requestId;
|
|
168
308
|
if(await operationClaim(requestId,'commit',signal))throw fail('ABANDON_UNSAFE');
|
|
169
|
-
|
|
309
|
+
const creation=await operationClaim(requestId,'create',signal,record.payload.createAttempt);
|
|
310
|
+
if(rejectedCreate(creation))return local(await replace(record,'abandoned',signal));
|
|
311
|
+
if(creation){
|
|
170
312
|
const selected=session(record,signal),{intent}=await selected.read({requestId,signal}),status=await client(signal).getStatus({intent,signal});
|
|
171
313
|
if(status.state==='abandoned'&&status.sideEffects==='closed')return observedResult(record,status,signal);
|
|
172
314
|
if(status.state!=='uploading'||status.sideEffects!=='none')throw fail('ABANDON_UNSAFE');
|
package/src/worker/service.mjs
CHANGED
|
@@ -84,6 +84,10 @@ export function createPublishingService({journal,allowLoopback=false,limits=defa
|
|
|
84
84
|
try{
|
|
85
85
|
const current=await authorize(request,signal),{state}=current,{policy}=state,url=new URL(request.url);
|
|
86
86
|
if(request.method==='GET'&&url.pathname==='/v1/project'&&!url.search)return json({schemaVersion:1,configuration:policy.configuration,policyRevision:policy.policyRevision,solutionId:policy.solutionId,packageName:policy.packageName,limits:policy.limits});
|
|
87
|
+
if(request.method==='GET'&&url.pathname==='/v1/project/release'&&!url.search){
|
|
88
|
+
const selected=state.requests.find(blocking)??state.requests.findLast(item=>item.state!=='abandoned');
|
|
89
|
+
return json({schemaVersion:1,intent:selected?.intent??null});
|
|
90
|
+
}
|
|
87
91
|
if(request.method==='POST'&&url.pathname==='/v1/requests'&&!url.search){
|
|
88
92
|
const body=await jsonBody(request,signal);if(!protocolRecord(body,['intent','manifest']))throw fail('INVALID_INPUT');const intent=parsePublishingIntent(body.intent),item=intent.package;
|
|
89
93
|
if(intent.projectId!==policy.configuration.projectId||item.publisherId!==policy.configuration.publisher.publisherId||item.solutionId!==policy.solutionId||item.packageName!==policy.packageName)throw fail('NOT_AUTHORIZED');
|
|
File without changes
|