@xlinklight/publishing 3.1.0 → 3.3.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 CHANGED
@@ -1,5 +1,13 @@
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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xlinklight/publishing",
3
- "version": "3.1.0",
3
+ "version": "3.3.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.0.0"
51
+ "@xlinklight/platform": "5.1.0"
52
52
  },
53
53
  "peerDependenciesMeta": {
54
54
  "@xlinklight/platform": {
@@ -0,0 +1,49 @@
1
+ import {createPublicKey, verify} from 'node:crypto';
2
+ import {protocolRecord, publishingDigest, publishingError, publishingIdentifier} from './protocol.mjs';
3
+
4
+ export const maximumAcceptanceArchiveBytes = 50 * 1024 ** 2;
5
+ export const deliveryBindingFields = Object.freeze([
6
+ 'projectId', 'solutionId', 'version', 'origin', 'keyId', 'manifestSha256', 'archiveSha256', 'artifactSha256', 'byteLength',
7
+ ]);
8
+ const fail = code => publishingError('ACCEPTANCE_' + code);
9
+ const versionPattern = /^\d{1,8}\.\d{1,8}\.\d{1,8}$/;
10
+
11
+ export function validateDeliveryOrigin(value) {
12
+ const url = typeof value === 'string' ? URL.parse(value) : null;
13
+ if (url?.protocol !== 'https:' || url.origin !== value) throw fail('ORIGIN_INVALID');
14
+ return value;
15
+ }
16
+
17
+ export function deliveryBindingBytes(value) {
18
+ if (!protocolRecord(value,deliveryBindingFields) || ![value.projectId,value.solutionId,value.keyId].every(publishingIdentifier) ||
19
+ !versionPattern.test(value.version) || ![value.manifestSha256,value.archiveSha256,value.artifactSha256].every(publishingDigest) ||
20
+ !Number.isSafeInteger(value.byteLength) || value.byteLength < 1 || value.byteLength > maximumAcceptanceArchiveBytes) throw fail('BINDING_INVALID');
21
+ validateDeliveryOrigin(value.origin);
22
+ return Buffer.from(JSON.stringify(['link-light/owner-acceptance-installation/v1', ...deliveryBindingFields.map(key => value[key])]));
23
+ }
24
+
25
+ export function verifyAcceptanceDelivery(value, signature, publicKey) {
26
+ if (typeof signature !== 'string' || !/^[A-Za-z0-9_-]{86}$/.test(signature)) throw fail('SIGNATURE_INVALID');
27
+ const key = typeof publicKey === 'string' ? createPublicKey(publicKey) : publicKey;
28
+ if (key?.asymmetricKeyType !== 'ed25519' || !verify(null,deliveryBindingBytes(value),key,Buffer.from(signature,'base64url'))) throw fail('SIGNATURE_INVALID');
29
+ }
30
+
31
+ export async function readDeliveryBody(message, limit) {
32
+ const length = message.headers.get('content-length');
33
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > maximumAcceptanceArchiveBytes || !message.body ||
34
+ length !== null && (!/^\d+$/.test(length) || Number(length) > limit)) throw fail('BODY_LIMIT');
35
+ const reader = message.body.getReader(), chunks = [];
36
+ let total = 0;
37
+ try {
38
+ for (;;) {
39
+ const {done,value} = await reader.read();
40
+ if (done) break;
41
+ total += value.byteLength;
42
+ if (total > limit) throw fail('BODY_LIMIT');
43
+ chunks.push(value);
44
+ }
45
+ } finally {
46
+ try { await reader.cancel(); } finally { reader.releaseLock(); }
47
+ }
48
+ return Buffer.concat(chunks,total);
49
+ }
@@ -1,5 +1,7 @@
1
1
  import type {KeyObject} from 'node:crypto';
2
2
  import type {SolutionReleaseManifest} from '@xlinklight/contracts';
3
+ export {maximumAcceptanceArchiveBytes, readDeliveryBody, verifyAcceptanceDelivery} from './node/acceptance-delivery.mjs';
4
+ export type {AcceptanceDeliveryBinding} from './node/acceptance-delivery.mjs';
3
5
 
4
6
  export interface AcceptanceIdentity {
5
7
  projectId:string;requestId:string;intentSha256:string;policyRevision:number;
@@ -1,6 +1,7 @@
1
1
  import {createHash,createPrivateKey,createPublicKey,sign,verify} from 'node:crypto';
2
2
  import {canonicalMetadata} from '@xlinklight/platform/worker';
3
3
  import {protocolRecord,publishingDigest,publishingError,publishingIdentifier,publishingRequestId} from './protocol.mjs';
4
+ export {maximumAcceptanceArchiveBytes, readDeliveryBody, verifyAcceptanceDelivery} from './acceptance-delivery-binding.mjs';
4
5
 
5
6
  const positive=value=>Number.isSafeInteger(value)&&value>0;
6
7
  const identityKeys=['projectId','requestId','intentSha256','policyRevision','releaseDigest','acceptanceArtifactSha256','generation'];
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,70 @@
1
+ import {createHash, createPrivateKey, createPublicKey, sign} from 'node:crypto';
2
+ import {protocolRecord, publishingError, publishingIdentifier} from '../protocol.mjs';
3
+ import {deliveryBindingBytes, deliveryBindingFields, readDeliveryBody, validateDeliveryOrigin} from '../acceptance-delivery-binding.mjs';
4
+ export {maximumAcceptanceArchiveBytes, readDeliveryBody, verifyAcceptanceDelivery} from '../acceptance-delivery-binding.mjs';
5
+
6
+ const fail = code => publishingError('ACCEPTANCE_' + code);
7
+ const hash = bytes => createHash('sha256').update(bytes).digest('hex');
8
+
9
+ export function parseAcceptanceDeliveryCredential(value) {
10
+ if (!protocolRecord(value,['origin','keyId','privateKey']) || !publishingIdentifier(value.keyId) ||
11
+ typeof value.privateKey !== 'string' || value.privateKey.length > 4096) throw fail('CREDENTIAL_INVALID');
12
+ validateDeliveryOrigin(value.origin);
13
+ const key = createPrivateKey(value.privateKey);
14
+ if (key.asymmetricKeyType !== 'ed25519') throw fail('CREDENTIAL_INVALID');
15
+ return {origin:value.origin,keyId:value.keyId,privateKey:key.export({type:'pkcs8',format:'pem'}).toString()};
16
+ }
17
+
18
+ export function acceptanceDeliveryTarget(credential) {
19
+ const {origin,keyId,privateKey}=parseAcceptanceDeliveryCredential(credential);
20
+ return {origin,keyId,publicKeySha256:hash(createPublicKey(privateKey).export({type:'spki',format:'der'}))};
21
+ }
22
+
23
+ export function signAcceptanceDelivery(value, privateKey) {
24
+ return sign(null,deliveryBindingBytes(value),privateKey).toString('base64url');
25
+ }
26
+
27
+ /** Only the dedicated owner's HTTPS origin receives this archive. A read after
28
+ * the immutable PUT also reconciles a lost response without repeating a release. */
29
+ function deliveryTarget({intent,archive,credential,request=fetch,signal}) {
30
+ if (!credential) throw fail('CREDENTIAL_REQUIRED');
31
+ const {origin,keyId,privateKey}=parseAcceptanceDeliveryCredential(credential);
32
+ const expected={projectId:intent.projectId,solutionId:intent.package.solutionId,version:intent.package.version,
33
+ origin,keyId,manifestSha256:intent.package.content.manifestSha256,...archive};
34
+ const url=new URL('/v1/acceptance/installations/'+expected.version,origin);
35
+ const timeout=AbortSignal.timeout(30000);
36
+ const options={redirect:'error',signal:signal?AbortSignal.any([signal,timeout]):timeout};
37
+ async function observed(){
38
+ const response=await request(url,{...options,method:'GET',headers:{accept:'application/json'}});
39
+ if(response.status===404){await response.body?.cancel();return false;}
40
+ if(response.status!==200){await response.body?.cancel();throw fail('DELIVERY_UNKNOWN');}
41
+ const receipt=await readDeliveryBody(response,8192);
42
+ let value;try{value=JSON.parse(receipt.toString('utf8'));}catch{throw fail('DELIVERY_UNKNOWN');}
43
+ if (!protocolRecord(value,deliveryBindingFields))throw fail('DELIVERY_UNKNOWN');
44
+ if (!deliveryBindingBytes(value).equals(deliveryBindingBytes(expected))) throw fail('VERSION_CONFLICT');
45
+ return true;
46
+ }
47
+ return {observed,expected,privateKey,options,url,request};
48
+ }
49
+
50
+ export async function observeAcceptanceDelivery(input) {
51
+ return deliveryTarget(input).observed();
52
+ }
53
+
54
+ export async function deliverAcceptanceArchive(input) {
55
+ const {bytes,archive}=input;
56
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength!==archive.byteLength || hash(bytes)!==archive.archiveSha256) throw fail('ARCHIVE_CHANGED');
57
+ const {observed,expected,privateKey,options,url,request}=deliveryTarget(input);
58
+ if(await observed())return;
59
+ const signature=signAcceptanceDelivery(expected,privateKey);
60
+ let rejection;
61
+ try {
62
+ const response=await request(url,{...options,method:'PUT',headers:{'content-type':'application/octet-stream',
63
+ 'x-link-light-binding':Buffer.from(JSON.stringify(expected)).toString('base64url'),'x-link-light-signature':signature},body:bytes});
64
+ await response.body?.cancel();
65
+ if(response.status===403)rejection='SIGNATURE_INVALID';
66
+ if(response.status===409)rejection='VERSION_CONFLICT';
67
+ if([400,413,415,422].includes(response.status))rejection='DELIVERY_REJECTED';
68
+ } catch(error){if(error?.code?.startsWith('PUBLISHING_ACCEPTANCE_'))throw error;}
69
+ if(!await observed())throw fail(rejection??'DELIVERY_UNKNOWN');
70
+ }
@@ -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');return {configuration,credential:value.credential};
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&&current.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,101 +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 {createLinuxDurableArtifactFilesystem,createWindowsNtfsDurableArtifactFilesystem} from '@openge/forge-generated-artifacts/node';
7
- import {validatePortableRelativePath} from '@openge/forge-path-safety';
8
- import {parsePublishingConfiguration,protocolRecord,publishingError} from '../protocol.mjs';
9
- import {openPublishingJournal} from './journal.mjs';
10
- import {installPublishingAuthorization,loadPublishingAuthorization} from './authorization.mjs';
11
- import {createPublishingWorkflow} from './workflow.mjs';
12
- import {defaultProducer} from './source-producer.mjs';
13
-
14
- const commands=['credentials','check','publish','status','recover','verify','abandon'];
15
- const journalLimits=Object.freeze({maximumBytes:536870912,maximumRecords:256,maximumRecordBytes:1048576,maximumBlobs:12000,maximumBlobBytes:134217728,minimumFreeBytes:67108864});
16
- const fail=code=>publishingError(code);
17
- function parse(args){
18
- if(!Array.isArray(args)||!args.length||args.some(value=>typeof value!=='string'||!value||value.includes('\0')||value.length>4096))throw fail('CLI_ARGUMENT_INVALID');
19
- if(args.length===1&&args[0]==='--help')return {command:'help'};
20
- const command=args[0];if(!commands.includes(command))throw fail('CLI_ARGUMENT_INVALID');
21
- const selected={command},seen=new Set();
22
- for(let index=1;index<args.length;index++){
23
- const flag=args[index];if(seen.has(flag))throw fail('CLI_ARGUMENT_INVALID');seen.add(flag);
24
- if(['--root','--state','--producer'].includes(flag)){
25
- const value=args[++index];if(!value||value.startsWith('--')||flag==='--producer'&&!['check','publish'].includes(command))throw fail('CLI_ARGUMENT_INVALID');selected[flag.slice(2)]=value;
26
- }else if(flag==='--stdin'&&command==='credentials')selected.stdin=true;
27
- else if(flag==='--no-wait'&&command==='publish')selected.waitMs=0;
28
- else if(flag==='--wait-ms'&&command==='publish'){
29
- const value=args[++index];if(!/^[1-9]\d{0,6}$/.test(value??'')||Number(value)>3600000)throw fail('CLI_ARGUMENT_INVALID');selected.waitMs=Number(value);
30
- }
31
- else if(flag==='--replace-credential'&&command==='credentials')selected.replaceCredential=true;
32
- else if(flag==='--new-preparation'&&['check','publish'].includes(command))selected.newPreparation=true;
33
- else throw fail('CLI_ARGUMENT_INVALID');
34
- }
35
- if(command==='credentials'&&!selected.stdin)throw fail('CLI_ARGUMENT_INVALID');
36
- if(seen.has('--no-wait')&&seen.has('--wait-ms'))throw fail('CLI_ARGUMENT_INVALID');
37
- for(const key of ['state','producer'])if(selected[key]!==undefined){try{if(validatePortableRelativePath(selected[key])!==selected[key]||key==='producer'&&!selected[key].endsWith('.mjs'))throw Error();}catch{throw fail('CLI_ARGUMENT_INVALID');}}
38
- return selected;
39
- }
40
- async function credentialInput(stdin,signal,timeoutMilliseconds){
41
- if(!stdin||stdin.isTTY===true||['on','off','destroy','resume'].some(name=>typeof stdin[name]!=='function'))throw fail('CREDENTIAL_INPUT_NON_TTY_REQUIRED');
42
- if(!Number.isSafeInteger(timeoutMilliseconds)||timeoutMilliseconds<1||timeoutMilliseconds>300000)throw fail('CREDENTIAL_INPUT_LIMIT_INVALID');
43
- const chunks=[];let bytes=0,timer,abort,data,end,error,close;
44
- let closedListener;const closed=stdin.closed?Promise.resolve(true):new Promise(resolve=>{closedListener=()=>resolve(true);stdin.once('close',closedListener);});
45
- try{
46
- if(signal?.aborted)throw fail('CREDENTIAL_INPUT_CANCELLED');
47
- await new Promise((resolve,reject)=>{
48
- let settled=false;const rejectOnce=code=>{if(!settled){settled=true;reject(fail(code));}};
49
- data=value=>{if(settled)return;if(!(value instanceof Uint8Array)&&typeof value!=='string')return rejectOnce('CREDENTIAL_INPUT_INVALID');const chunk=Buffer.from(value);bytes+=chunk.byteLength;if(bytes>16384)return rejectOnce('CREDENTIAL_INPUT_BYTE_LIMIT');chunks.push(chunk);};
50
- end=()=>{if(!settled){settled=true;resolve();}};error=()=>rejectOnce('CREDENTIAL_INPUT_INVALID');close=()=>rejectOnce('CREDENTIAL_INPUT_CLOSED');abort=()=>rejectOnce('CREDENTIAL_INPUT_CANCELLED');
51
- stdin.on('data',data);stdin.once('end',end);stdin.once('error',error);stdin.once('close',close);signal?.addEventListener('abort',abort,{once:true});timer=setTimeout(()=>rejectOnce('CREDENTIAL_INPUT_TIMEOUT'),timeoutMilliseconds);stdin.resume();
52
- });
53
- let value;try{value=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks)));}catch{throw fail('CREDENTIAL_INPUT_INVALID');}
54
- if(!protocolRecord(value,['configuration','credential'])||typeof value.credential!=='string'||!/^[A-Za-z0-9_-]{32,4096}$/.test(value.credential))throw fail('CREDENTIAL_INPUT_INVALID');return value;
55
- }catch(error){if(typeof error?.code==='string'&&error.code.startsWith('PUBLISHING_CREDENTIAL_INPUT_'))throw error;throw fail(signal?.aborted?'CREDENTIAL_INPUT_CANCELLED':'CREDENTIAL_INPUT_INVALID');}
56
- finally{
57
- clearTimeout(timer);if(abort)signal?.removeEventListener('abort',abort);
58
- for(const [name,listener]of [['data',data],['end',end],['error',error],['close',close]])if(listener)stdin.off(name,listener);
59
- // Explicit credential input is owned by this call, including blocked pipes.
60
- stdin.destroy();let closureTimer;
61
- try{if(!await Promise.race([closed,new Promise(resolve=>{closureTimer=setTimeout(()=>resolve(false),1000);})]))throw fail('CREDENTIAL_INPUT_CLOSURE_UNKNOWN');}
62
- finally{clearTimeout(closureTimer);if(closedListener)stdin.off('close',closedListener);}
63
- }
64
- }
65
- function diagnostic(error){
66
- const code=typeof error?.code==='string'&&/^PUBLISHING_[A-Z0-9_]{1,96}$/.test(error.code)?error.code:'PUBLISHING_COMMAND_FAILED';return {error:{code}};
67
- }
68
-
69
- /** Bounded one-shot CLI. No token, private producer cause, provider output or
70
- * environment is returned. Callers own private storage ACLs and backup policy. */
71
- async function executeCommand(selected,options){
72
- let journal;
73
- try{
74
- const {signal,allowLoopback=false,request,clientLimits,metadataTransport}=options;
75
- const input=selected.command==='credentials'?await credentialInput(options.stdin??process.stdin,signal,options.credentialInputTimeoutMilliseconds??30000):undefined;
76
- if(input)input.configuration=parsePublishingConfiguration(input.configuration,{allowLoopback});
77
- signal?.throwIfAborted();const root=path.resolve(options.cwd??process.cwd(),selected.root??'.'),info=await fs.lstat(root);
78
- if(!info.isDirectory()||info.isSymbolicLink()||await fs.realpath(root)!==root)throw fail('CLI_ROOT_INVALID');
79
- const filesystem=options.filesystem??await(process.platform==='win32'?createWindowsNtfsDurableArtifactFilesystem():process.platform==='linux'?createLinuxDurableArtifactFilesystem():Promise.reject(fail('CLI_PLATFORM_UNSUPPORTED')));
80
- journal=await openPublishingJournal({root,directory:selected.state??'state/solution-publishing',filesystem,limits:options.journalLimits??journalLimits,signal});
81
- const shared={journal,allowLoopback,...(request?{request}:{}),...(clientLimits?{clientLimits}:{}),signal};
82
- if(input){
83
- const installed=await installPublishingAuthorization({...shared,...input,replaceCredential:selected.replaceCredential===true});
84
- return {exitCode:0,output:{state:installed.status.toLowerCase(),projectId:installed.projectId,policyRevision:installed.policyRevision}};
85
- }
86
- const authorization=await loadPublishingAuthorization(shared);if(!authorization)throw fail('CREDENTIAL_REQUIRED');
87
- const workflow=createPublishingWorkflow({...shared,...authorization,root,...(metadataTransport?{metadataTransport}:{}),...(options.operationLimits?{operationLimits:options.operationLimits}:{})});
88
- const result=await workflow[selected.command]({signal,...(selected.producer?{producer:selected.producer}:{}),...(selected.newPreparation?{newPreparation:true}:{}),...(selected.command==='publish'?{waitMs:selected.waitMs??300000}:{})});
89
- const exitCode=result.state==='active'||['check','abandon'].includes(selected.command)?0:result.state==='failed'?1:3;
90
- return {exitCode,output:result};
91
- }finally{try{journal?.close();}catch{throw fail('JOURNAL_CLOSURE_UNKNOWN');}}
92
- }
93
-
94
- export async function runPublishingCommand(args,options={}){
95
- let selected;try{selected=parse(args);}catch{return {exitCode:2,output:{error:{code:'PUBLISHING_CLI_ARGUMENT_INVALID'}}};}
96
- if(selected.command==='help')return {exitCode:0,output:{commands,sourceProducer:defaultProducer,stateDirectory:'state/solution-publishing',publishWaitMs:300000,publishOptions:['--no-wait','--wait-ms <1..3600000>']}};
97
- try{return await executeCommand(selected,options);}catch(error){return {exitCode:1,output:diagnostic(error)};}
98
- }
4
+ import {runPublishingCommand} from './publishing-command.mjs';
99
5
 
100
6
  async function main(){
101
7
  const controller=new AbortController(),stop=()=>controller.abort();process.once('SIGINT',stop);process.once('SIGTERM',stop);
@@ -103,5 +9,4 @@ async function main(){
103
9
  finally{process.off('SIGINT',stop);process.off('SIGTERM',stop);}
104
10
  }
105
11
 
106
- // A producer can import the same public Node entry while the command is running.
107
12
  if(process.argv[1]&&existsSync(process.argv[1])&&realpathSync(process.argv[1])===realpathSync(fileURLToPath(import.meta.url)))void main();
@@ -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 './cli.mjs';
16
- export {runPublishingCommand} from './cli.mjs';
15
+ export type {PublishingCommandOptions,PublishingCommandResult} from './publishing-command.mjs';
16
+ export {runPublishingCommand} from './publishing-command.mjs';
17
+ export * from './acceptance-delivery.mjs';
@@ -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 {runPublishingCommand} from './cli.mjs';
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
+ }
@@ -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. */
@@ -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){await run(context.signal,async signal=>{status=await(stage==='create'?client.createRequest({intent,manifestBytes,signal}):client.queueRequest({intent,signal}));});return {state:'accepted',reference:intent.requestId};},
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 binding=await bindArtifactOperation({requestId:requestId+'.'+stage,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}]});
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
- const result=await journal.compareAndSet({key:key(intent.requestId),expectedRevision:0,payload:{schemaVersion:1,configuration:config,intent,manifestByteLength:prepared.manifestBytes.byteLength},blobs},{signal});
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'}),
@@ -50,6 +50,21 @@ async function readManifest(file,{checkout=false}={}){
50
50
  }finally{await handle.close();}
51
51
  }
52
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
+
53
68
  function contains(parent,child){
54
69
  const relative=path.relative(parent,child);
55
70
  return relative!==''&&relative!=='..'&&!relative.startsWith('..'+path.sep)&&!path.isAbsolute(relative);
@@ -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 {
@@ -1,16 +1,29 @@
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
6
  import {createPublishingClient} from '../client.mjs';
7
7
  import {parsePublishingConfiguration,parsePublishingProject,parsePublishingIntent,publishingRequestId,protocolRecord,publishingError} from '../protocol.mjs';
8
8
  import {createPublishingSession} from './session.mjs';
9
9
  import {verifyPublishingActivation} from './activation.mjs';
10
10
  import {PublishingSourceError} from './source-error.mjs';
11
- import {selectProducerFile,validateLocalProducer} from './source-producer.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);
@@ -27,16 +40,21 @@ export function createPublishingWorkflow(options){
27
40
  const shared={journal,configuration,credential,allowLoopback,...(request?{request}:{}),...(clientLimits?{clientLimits}:{})};
28
41
  const client=signal=>createPublishingClient({...shared,...(clientLimits?{limits:clientLimits}:{}),verifyActivation:verifier(signal)}),activeKey='active:'+configuration.projectId;
29
42
  const session=(record,signal)=>createPublishingSession({...shared,verifyActivation:verifier(signal),packageLimits:record.payload.project.limits,pathCaseSensitivity:record.payload.pathCaseSensitivity,...(operationLimits?{operationLimits}:{})});
30
- const replace=async(record,phase,signal,failure)=>{
31
- const payload={...record.payload,phase,...(failure?{failure}:{})},result=await journal.compareAndSet({key:sourceKey(payload.requestId),expectedRevision:record.revision,payload},{signal});
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});
32
47
  if(result!=='stored')throw fail('WORKFLOW_CONFLICT');return {revision:record.revision+1,payload};
33
48
  };
34
49
  const current=async signal=>{
35
50
  const active=await journal.load(activeKey,{signal});if(!active)return undefined;
36
51
  if(!protocolRecord(active.payload,['schemaVersion','requestId'])||active.payload.schemaVersion!==1||!publishingRequestId(active.payload.requestId))throw fail('WORKFLOW_STATE_INVALID');
37
52
  let record=await journal.load(sourceKey(active.payload.requestId),{signal});
38
- 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');
39
- if(record.payload.failure!==undefined&&(record.payload.phase!=='failed-closed'||!protocolRecord(record.payload.failure,['code'])||!['PUBLISHING_SOURCE_PACKAGE_BINDING_INVALID','PUBLISHING_SOURCE_PREPARATION_FAILED'].includes(record.payload.failure.code)))throw fail('WORKFLOW_STATE_INVALID');
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');
40
58
  const project=parsePublishingProject(record.payload.project,{allowLoopback});if(JSON.stringify(project.configuration)!==JSON.stringify(configuration))throw fail('CONFIGURATION_CHANGED');
41
59
  // freeze is the atomic authority: losing the outer acknowledgment must never
42
60
  // cause a second import, build, capture or request identity.
@@ -46,51 +64,115 @@ export function createPublishingWorkflow(options){
46
64
  return {active,record};
47
65
  };
48
66
  const result=(record,state,extra={})=>({requestId:record.payload.requestId,state,active:state==='active',...extra});
49
- 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';
50
69
  const prepare=async input=>{
51
- const {producer,newPreparation=false,signal}=sourceOptions(input);let previous=await current(signal);
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
+ }
52
89
  if(previous&&newPreparation&&['remote','completed','failed'].includes(previous.record.payload.phase)){
53
90
  // Observe the original identity and current admission before permitting the
54
91
  // next release. A prior terminal observation never authorizes an unknown,
55
92
  // still-running or currently unverified request to be replaced.
56
93
  const observed=await inspect({signal},true);
57
- if(observed.sideEffects!=='closed'||!['abandoned','active','failed'].includes(observed.state))throw fail('SOURCE_ACTIVE_REQUEST_EXISTS');
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';
58
99
  previous=await current(signal);
59
100
  }
60
101
  if(previous){
61
102
  const phase=previous.record.payload.phase;
62
103
  if(phase==='preparing')throw fail('SOURCE_PREPARATION_UNKNOWN');
63
- if(phase==='frozen'||phase==='remote'){if(newPreparation)throw fail('SOURCE_ACTIVE_REQUEST_EXISTS');return previous.record;}
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
+ }
64
108
  if(!newPreparation)throw fail('SOURCE_NEW_PREPARATION_REQUIRED');
65
109
  }
66
110
  signal?.throwIfAborted();if(await fs.realpath(root)!==root||!(await fs.lstat(root)).isDirectory())throw fail('SOURCE_PATH_INVALID');
67
- const project=await client(signal).getProject({signal}),requestId=randomUUID();
111
+ const project=await client(signal).getProject({signal});
68
112
  let file,selectionFailure;
69
113
  try{file=await selectProducerFile(root,producer);}
70
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
+ }
71
135
  signal?.throwIfAborted();
72
- const payload={schemaVersion:1,requestId,project,pathCaseSensitivity,...(selectionFailure?{phase:'failed-closed',failure:{code:selectionFailure.code}}:{phase:'preparing'})};
73
- if(await journal.compareAndSet({key:sourceKey(requestId),expectedRevision:0,payload},{signal})!=='stored')throw fail('WORKFLOW_CONFLICT');
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');
74
140
  if(await journal.compareAndSet({key:activeKey,expectedRevision:previous?.active.revision??0,payload:{schemaVersion:1,requestId}},{signal})!=='stored')throw fail('WORKFLOW_CONFLICT');
75
141
  if(selectionFailure)throw selectionFailure;
76
- let record={revision:1,payload},prepared,intent,processesClosed=false;
142
+ let record={revision:sourceRevision+1,payload},prepared,intent,acceptanceArchive,processesClosed=false;
77
143
  try{
78
144
  const producerModule=await import(pathToFileURL(file).href+'?publishingRequest='+requestId);
79
145
  if(typeof producerModule.prepare!=='function')throw fail('SOURCE_PORT_INVALID');
80
- const response=await producerModule.prepare({root,project:structuredClone(project),signal,requestId});
81
- 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;
82
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');
83
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
+ }
84
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
+ }
85
162
  }catch(error){
86
- if(processesClosed||error instanceof PublishingSourceError&&error.processesClosed){record=await replace(record,'failed-closed',signal,{code:error.code==='PUBLISHING_SOURCE_PACKAGE_BINDING_INVALID'?error.code:'PUBLISHING_SOURCE_PREPARATION_FAILED'});throw new PublishingSourceError({cause:error,processesClosed:true});}
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
+ }
87
169
  throw new PublishingSourceError({cause:error,processesClosed:false});
88
170
  }
89
171
  // Freeze and its acknowledgment deliberately remain outside the known-closed
90
172
  // source catch: a storage error can mean the original bytes were committed.
91
- 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;
92
174
  };
93
- 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');
94
176
  const observedResult=async(record,status,signal)=>{
95
177
  // The client/session authenticated this exact original intent, and ACTIVE
96
178
  // already passed the real signature and current Core-admission verifier.
@@ -105,13 +187,31 @@ export function createPublishingWorkflow(options){
105
187
  return result(record,status.state,{sideEffects:status.sideEffects});
106
188
  };
107
189
  const inspect=async({signal}={},observe=false,dispatchRecovery=false)=>{
108
- const state=await current(signal);if(!state)return {state:'empty',active:false};const {record}=state;
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
+ }
109
208
  if(!['frozen','remote','completed','failed'].includes(record.payload.phase))return local(record);
110
- const requestId=record.payload.requestId,commit=await operationClaim(requestId,'commit',signal),create=await operationClaim(requestId,'create',signal);
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'}});
111
211
  if(!commit&&!create)return local(record);
112
212
  const selected=session(record,signal);
113
213
  if(observe){
114
- 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');
115
215
  // The control only asks the host to observe an already committed original
116
216
  // operation. Uploading/local preparation never dispatches provider work.
117
217
  const status=dispatchRecovery&&commit&&['queued','deploying','awaiting-acceptance','unknown'].includes(observed.status.state)?await selected.recover({requestId,signal}):observed.status;
@@ -132,17 +232,42 @@ export function createPublishingWorkflow(options){
132
232
  }catch(error){if(timeout.aborted&&!signal?.aborted)return {...latest,timedOut:true};throw error;}
133
233
  };
134
234
  return Object.freeze({
135
- async check(input={}){return local(await prepare(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
+ },
136
241
  async publish(input={}){
137
242
  if(!protocolRecord(input,[],['producer','newPreparation','signal','waitMs','pollMs']))throw fail('WORKFLOW_INPUT_INVALID');
138
243
  const {waitMs=0,pollMs=1000,...source}=input;
139
244
  if(!Number.isSafeInteger(waitMs)||waitMs<0||waitMs>3600000||!Number.isSafeInteger(pollMs)||pollMs<1||pollMs>30000)throw fail('WORKFLOW_INPUT_INVALID');
140
- let record=await prepare(source);const requestId=record.payload.requestId,signal=input.signal,finish=status=>waitFor(record,status,{signal,waitMs,pollMs});
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});
141
248
  // This CAS competes with local abandonment before any remote write. Once
142
249
  // remote publication may start, absence of a later claim is not a closure
143
250
  // proof for an overlapping client.
144
- if(record.payload.phase==='frozen')record=await replace(record,'remote',signal);
145
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
+ }
146
271
  // Never repeat creation, upload or commit after the original commit claim.
147
272
  // A healthy confirmed original may ask the host for its known next step;
148
273
  // unknown requires explicit recovery and cannot perform on publish.
@@ -151,7 +276,23 @@ export function createPublishingWorkflow(options){
151
276
  if(['queued','deploying'].includes(original.state))return finish(await observedResult(record,await selected.resume({requestId,signal}),signal));
152
277
  return finish(original);
153
278
  }
154
- const created=await(await operationClaim(requestId,'create',signal)?selected.observe({requestId,stage:'create',signal}):selected.create({requestId,signal}));
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
+ }
155
296
  if(created.receipt.outcome!=='succeeded')return result(record,'unknown');
156
297
  if(created.status&&created.status.state!=='uploading')return finish(await observedResult(record,created.status,signal));
157
298
  const uploaded=await selected.upload({requestId,signal});if(uploaded.state!=='uploading')return finish(await observedResult(record,uploaded,signal));
@@ -165,7 +306,9 @@ export function createPublishingWorkflow(options){
165
306
  if(record.payload.phase==='preparing')throw fail('SOURCE_PREPARATION_UNKNOWN');if(!['frozen','remote'].includes(record.payload.phase))throw fail('ABANDON_UNSAFE');
166
307
  const requestId=record.payload.requestId;
167
308
  if(await operationClaim(requestId,'commit',signal))throw fail('ABANDON_UNSAFE');
168
- if(await operationClaim(requestId,'create',signal)){
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){
169
312
  const selected=session(record,signal),{intent}=await selected.read({requestId,signal}),status=await client(signal).getStatus({intent,signal});
170
313
  if(status.state==='abandoned'&&status.sideEffects==='closed')return observedResult(record,status,signal);
171
314
  if(status.state!=='uploading'||status.sideEffects!=='none')throw fail('ABANDON_UNSAFE');
@@ -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');