@xlinklight/publishing 3.2.0 → 3.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +1 -1
  2. package/dist/src/acceptance-delivery-binding.js +59 -0
  3. package/dist/src/acceptance.js +79 -0
  4. package/dist/src/client.js +146 -0
  5. package/dist/src/index.js +3 -0
  6. package/dist/src/node/acceptance-delivery.js +88 -0
  7. package/dist/src/node/activation.js +3 -0
  8. package/dist/src/node/authorization.js +76 -0
  9. package/dist/src/node/cli.js +20 -0
  10. package/dist/src/node/index.js +9 -0
  11. package/dist/src/node/journal.js +282 -0
  12. package/dist/src/node/publishing-command.js +220 -0
  13. package/dist/src/node/session.js +223 -0
  14. package/dist/src/node/solution-package.js +217 -0
  15. package/dist/src/node/source-error.js +15 -0
  16. package/dist/src/node/source-producer.js +145 -0
  17. package/dist/src/node/workflow.js +455 -0
  18. package/dist/src/package.js +74 -0
  19. package/dist/src/protocol.js +105 -0
  20. package/dist/src/shared/activation.js +111 -0
  21. package/dist/src/shared/records.js +26 -0
  22. package/dist/src/worker/activation.js +10 -0
  23. package/dist/src/worker/index.js +6 -0
  24. package/dist/src/worker/journal.js +301 -0
  25. package/dist/src/worker/package.js +116 -0
  26. package/dist/src/worker/release.js +59 -0
  27. package/dist/src/worker/runtime.js +98 -0
  28. package/dist/src/worker/service.js +494 -0
  29. package/package.json +17 -14
  30. package/{src/acceptance.d.mts → types/acceptance.d.ts} +2 -0
  31. package/{src/client.d.mts → types/client.d.ts} +1 -1
  32. package/{src/index.d.mts → types/index.d.ts} +6 -6
  33. package/{src/node/acceptance-delivery.d.mts → types/node/acceptance-delivery.d.ts} +1 -1
  34. package/{src/node/activation.d.mts → types/node/activation.d.ts} +4 -4
  35. package/{src/node/authorization.d.mts → types/node/authorization.d.ts} +4 -4
  36. package/types/node/index.d.ts +17 -0
  37. package/{src/node/publishing-command.d.mts → types/node/publishing-command.d.ts} +4 -4
  38. package/{src/node/session.d.mts → types/node/session.d.ts} +7 -7
  39. package/{src/node/solution-package.d.mts → types/node/solution-package.d.ts} +2 -2
  40. package/{src/node/workflow.d.mts → types/node/workflow.d.ts} +7 -7
  41. package/{src/protocol.d.mts → types/protocol.d.ts} +1 -1
  42. package/{src/worker/activation.d.mts → types/worker/activation.d.ts} +3 -3
  43. package/types/worker/index.d.ts +6 -0
  44. package/{src/worker/package.d.mts → types/worker/package.d.ts} +2 -2
  45. package/{src/worker/release.d.mts → types/worker/release.d.ts} +3 -3
  46. package/{src/worker/runtime.d.mts → types/worker/runtime.d.ts} +2 -2
  47. package/{src/worker/service.d.mts → types/worker/service.d.ts} +7 -7
  48. package/src/acceptance.mjs +0 -66
  49. package/src/client.mjs +0 -74
  50. package/src/index.mjs +0 -3
  51. package/src/node/acceptance-delivery.mjs +0 -109
  52. package/src/node/activation.mjs +0 -3
  53. package/src/node/authorization.mjs +0 -49
  54. package/src/node/cli.mjs +0 -12
  55. package/src/node/index.d.mts +0 -17
  56. package/src/node/index.mjs +0 -9
  57. package/src/node/journal.mjs +0 -135
  58. package/src/node/publishing-command.mjs +0 -104
  59. package/src/node/session.mjs +0 -134
  60. package/src/node/solution-package.mjs +0 -113
  61. package/src/node/source-error.mjs +0 -9
  62. package/src/node/source-producer.mjs +0 -103
  63. package/src/node/workflow.mjs +0 -320
  64. package/src/package.mjs +0 -36
  65. package/src/protocol.mjs +0 -50
  66. package/src/shared/activation.mjs +0 -64
  67. package/src/worker/activation.mjs +0 -4
  68. package/src/worker/index.d.mts +0 -6
  69. package/src/worker/index.mjs +0 -6
  70. package/src/worker/journal.mjs +0 -151
  71. package/src/worker/package.mjs +0 -32
  72. package/src/worker/release.mjs +0 -21
  73. package/src/worker/runtime.mjs +0 -23
  74. package/src/worker/service.mjs +0 -251
  75. /package/{src/node/journal.d.mts → types/node/journal.d.ts} +0 -0
  76. /package/{src/node/source-error.d.mts → types/node/source-error.d.ts} +0 -0
  77. /package/{src/package.d.mts → types/package.d.ts} +0 -0
  78. /package/{src/shared/activation.d.mts → types/shared/activation.d.ts} +0 -0
  79. /package/{src/worker/journal.d.mts → types/worker/journal.d.ts} +0 -0
package/README.md CHANGED
@@ -17,7 +17,7 @@ Solution publishing binds declarative metadata, an opaque Worker module closure
17
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
18
 
19
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.
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 a regular ESM file within that installed package. It may be a `.mjs` file, or a `.js` file whose nearest `package.json` declares `"type":"module"`. The package can expose its ESM entry through the `default` condition. pnpm links to packages inside the checkout's `node_modules` are supported.
21
21
  3. `deployment/publishing.mjs` when the metadata field is absent.
22
22
 
23
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.
@@ -0,0 +1,59 @@
1
+ import { createPublicKey, verify } from 'node:crypto';
2
+ import { protocolRecord, publishingDigest, publishingError, publishingIdentifier } from './protocol.js';
3
+ export const maximumAcceptanceArchiveBytes = 50 * 1024 ** 2;
4
+ export const deliveryBindingFields = Object.freeze([
5
+ 'projectId', 'solutionId', 'version', 'origin', 'keyId', 'manifestSha256', 'archiveSha256', 'artifactSha256', 'byteLength',
6
+ ]);
7
+ const fail = (code) => publishingError('ACCEPTANCE_' + code);
8
+ const versionPattern = /^\d{1,8}\.\d{1,8}\.\d{1,8}$/;
9
+ export function validateDeliveryOrigin(value) {
10
+ if (typeof value !== 'string')
11
+ throw fail('ORIGIN_INVALID');
12
+ const url = URL.parse(value);
13
+ if (url?.protocol !== 'https:' || url.origin !== value)
14
+ throw fail('ORIGIN_INVALID');
15
+ return value;
16
+ }
17
+ export function deliveryBindingBytes(value) {
18
+ if (!protocolRecord(value, deliveryBindingFields) || ![value.projectId, value.solutionId, value.keyId].every(publishingIdentifier) ||
19
+ typeof value.version !== 'string' || !versionPattern.test(value.version) || ![value.manifestSha256, value.archiveSha256, value.artifactSha256].every(publishingDigest) ||
20
+ typeof value.byteLength !== 'number' || !Number.isSafeInteger(value.byteLength) || value.byteLength < 1 || value.byteLength > maximumAcceptanceArchiveBytes)
21
+ throw fail('BINDING_INVALID');
22
+ validateDeliveryOrigin(value.origin);
23
+ return Buffer.from(JSON.stringify(['link-light/owner-acceptance-installation/v1', ...deliveryBindingFields.map(key => value[key])]));
24
+ }
25
+ export function verifyAcceptanceDelivery(value, signature, publicKey) {
26
+ if (typeof signature !== 'string' || !/^[A-Za-z0-9_-]{86}$/.test(signature))
27
+ throw fail('SIGNATURE_INVALID');
28
+ const key = typeof publicKey === 'string' ? createPublicKey(publicKey) : publicKey;
29
+ if (key?.asymmetricKeyType !== 'ed25519' || !verify(null, deliveryBindingBytes(value), key, Buffer.from(signature, 'base64url')))
30
+ throw fail('SIGNATURE_INVALID');
31
+ }
32
+ export async function readDeliveryBody(message, limit) {
33
+ const length = message.headers.get('content-length');
34
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > maximumAcceptanceArchiveBytes || !message.body ||
35
+ length !== null && (!/^\d+$/.test(length) || Number(length) > limit))
36
+ throw fail('BODY_LIMIT');
37
+ const reader = message.body.getReader(), chunks = [];
38
+ let total = 0;
39
+ try {
40
+ for (;;) {
41
+ const { done, value } = await reader.read();
42
+ if (done)
43
+ break;
44
+ total += value.byteLength;
45
+ if (total > limit)
46
+ throw fail('BODY_LIMIT');
47
+ chunks.push(value);
48
+ }
49
+ }
50
+ finally {
51
+ try {
52
+ await reader.cancel();
53
+ }
54
+ finally {
55
+ reader.releaseLock();
56
+ }
57
+ }
58
+ return Buffer.concat(chunks, total);
59
+ }
@@ -0,0 +1,79 @@
1
+ import { createHash, createPrivateKey, createPublicKey, sign, verify } from 'node:crypto';
2
+ import { canonicalMetadata } from '@xlinklight/platform/worker';
3
+ import { protocolRecord, publishingDigest, publishingError, publishingIdentifier, publishingRequestId } from './protocol.js';
4
+ export { maximumAcceptanceArchiveBytes, readDeliveryBody, verifyAcceptanceDelivery } from './acceptance-delivery-binding.js';
5
+ const positive = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
6
+ const object = (value) => value !== null && typeof value === 'object';
7
+ const identityKeys = ['projectId', 'requestId', 'intentSha256', 'policyRevision', 'releaseDigest', 'acceptanceArtifactSha256', 'generation'];
8
+ const bindingKeys = ['schemaVersion', 'jobId', ...identityKeys];
9
+ const invalid = (part) => publishingError('ACCEPTANCE_' + part + '_INVALID');
10
+ function validIdentity(value) {
11
+ return object(value) && publishingIdentifier(value.projectId) && publishingRequestId(value.requestId)
12
+ && publishingDigest(value.intentSha256) && positive(value.policyRevision) && typeof value.releaseDigest === 'string'
13
+ && /^sha256:[a-f0-9]{64}$/.test(value.releaseDigest) && publishingDigest(value.acceptanceArtifactSha256) && positive(value.generation);
14
+ }
15
+ export function acceptanceJobId(identity) {
16
+ if (!validIdentity(identity))
17
+ throw invalid('JOB');
18
+ const binding = Object.fromEntries(identityKeys.map(key => [key, identity[key]]));
19
+ return createHash('sha256').update('link-light/acceptance-job-id/v1\n').update(canonicalMetadata(binding)).digest('hex');
20
+ }
21
+ function checkBinding(payload, kind) {
22
+ try {
23
+ return payload.schemaVersion === 1 && validIdentity(payload) && payload.jobId === acceptanceJobId(payload);
24
+ }
25
+ catch {
26
+ throw invalid(kind);
27
+ }
28
+ }
29
+ function assertJob(payload) {
30
+ if (!protocolRecord(payload, [...bindingKeys, 'manifest']) || !checkBinding(payload, 'JOB')
31
+ || !object(payload.manifest) || payload.manifest.releaseDigest !== payload.releaseDigest || !publishingIdentifier(payload.manifest.solutionId)
32
+ || typeof payload.manifest.version !== 'string' || !/^\d{1,8}\.\d{1,8}\.\d{1,8}$/.test(payload.manifest.version))
33
+ throw invalid('JOB');
34
+ }
35
+ function jobPayload(payload) {
36
+ assertJob(payload);
37
+ return payload;
38
+ }
39
+ function assertReceipt(payload) {
40
+ if (!protocolRecord(payload, [...bindingKeys, 'status', 'proof']) || !checkBinding(payload, 'RECEIPT') || payload.status !== 'PASS'
41
+ || !protocolRecord(payload.proof, ['syntheticInstancesCreated', 'syntheticInstancesDisabled', 'closure']))
42
+ throw invalid('RECEIPT');
43
+ const { syntheticInstancesCreated, syntheticInstancesDisabled, closure } = payload.proof;
44
+ if (!positive(syntheticInstancesCreated) || syntheticInstancesCreated < 2 || syntheticInstancesCreated > 1024
45
+ || syntheticInstancesCreated !== syntheticInstancesDisabled || !protocolRecord(closure, ['status', 'activeRequests'])
46
+ || closure.status !== 'closed' || closure.activeRequests !== 0)
47
+ throw invalid('RECEIPT');
48
+ }
49
+ function receiptPayload(payload) {
50
+ assertReceipt(payload);
51
+ return payload;
52
+ }
53
+ function message(kind, payload) {
54
+ const canonical = canonicalMetadata(payload);
55
+ if (Buffer.byteLength(canonical) > 65536)
56
+ throw invalid(kind);
57
+ return Buffer.from('link-light/acceptance-' + kind.toLowerCase() + '/v1\n' + canonical);
58
+ }
59
+ function signEnvelope(payload, kind, { keyId, privateKey }) {
60
+ const key = typeof privateKey === 'string' ? createPrivateKey(privateKey) : privateKey;
61
+ if (!publishingIdentifier(keyId) || key?.type !== 'private' || key.asymmetricKeyType !== 'ed25519')
62
+ throw invalid('SIGNATURE');
63
+ return { payload: structuredClone(payload), keyId, signature: sign(null, message(kind, payload), key).toString('base64url') };
64
+ }
65
+ function verifyEnvelope(envelope, kind, parse, { keyId, publicKey }) {
66
+ if (!protocolRecord(envelope, ['payload', 'keyId', 'signature']) || !publishingIdentifier(keyId) || envelope.keyId !== keyId
67
+ || typeof envelope.signature !== 'string' || !/^[A-Za-z0-9_-]{86}$/.test(envelope.signature))
68
+ throw invalid('SIGNATURE');
69
+ const payload = parse(envelope.payload), bytes = Buffer.from(envelope.signature, 'base64url');
70
+ const key = typeof publicKey === 'string' ? createPublicKey(publicKey) : publicKey;
71
+ if (key?.type !== 'public' || key.asymmetricKeyType !== 'ed25519' || bytes.toString('base64url') !== envelope.signature
72
+ || !verify(null, message(kind, payload), key, bytes))
73
+ throw invalid('SIGNATURE');
74
+ return structuredClone(payload);
75
+ }
76
+ export const signAcceptanceJob = (job, options) => signEnvelope(jobPayload(job), 'JOB', options);
77
+ export const verifyAcceptanceJob = (envelope, options) => verifyEnvelope(envelope, 'JOB', jobPayload, options);
78
+ export const signAcceptanceReceipt = (receipt, options) => signEnvelope(receiptPayload(receipt), 'RECEIPT', options);
79
+ export const verifyAcceptanceReceipt = (envelope, options) => verifyEnvelope(envelope, 'RECEIPT', receiptPayload, options);
@@ -0,0 +1,146 @@
1
+ import { calculateBytesIntegrity } from '@openge/forge-artifact-integrity';
2
+ import { createArtifactContentManifest } from '@openge/forge-artifact-publish';
3
+ import { parsePublishingConfiguration, parsePublishingProject, parsePublishingIntent, parsePublishingStatus, publishingIntentBytes, publishingError, publishingRequestId, publishingDigest, protocolRecord } from './protocol.js';
4
+ const defaults = Object.freeze({ requestMs: 30000, maximumResponseBytes: 1048576, maximumChunkBytes: 262144 });
5
+ const serviceErrors = new Set(['NOT_AUTHORIZED', 'PROJECT_DISABLED', 'POLICY_CHANGED', 'CONFLICT', 'REQUEST_NOT_FOUND', 'QUOTA_PAUSED', 'INVALID_INPUT', 'UNKNOWN_EFFECTS', 'BUSY', 'NOT_READY']);
6
+ function boundedLimits(value) {
7
+ if (!protocolRecord(value, ['requestMs', 'maximumResponseBytes', 'maximumChunkBytes']) || Object.values(value).some(item => typeof item !== 'number' || !Number.isSafeInteger(item) || item < 1) || value.requestMs > 300000 || value.maximumResponseBytes > 2097152 || value.maximumChunkBytes > 1048576)
8
+ throw publishingError('CLIENT_LIMIT_INVALID');
9
+ return { ...value };
10
+ }
11
+ async function responseJson(response, maximum, signal) {
12
+ const declared = response.headers.get('content-length');
13
+ if (declared !== null && (!/^\d+$/.test(declared) || Number(declared) > maximum)) {
14
+ await response.body?.cancel();
15
+ throw publishingError('RESPONSE_BYTE_LIMIT');
16
+ }
17
+ if (!response.body)
18
+ throw publishingError('RESPONSE_INVALID');
19
+ const reader = response.body.getReader(), chunks = [];
20
+ let total = 0;
21
+ try {
22
+ for (;;) {
23
+ signal.throwIfAborted();
24
+ const { done, value } = await reader.read();
25
+ if (done)
26
+ break;
27
+ total += value.byteLength;
28
+ if (total > maximum)
29
+ throw publishingError('RESPONSE_BYTE_LIMIT');
30
+ chunks.push(value);
31
+ }
32
+ }
33
+ catch (error) {
34
+ try {
35
+ await reader.cancel();
36
+ }
37
+ catch { }
38
+ throw error;
39
+ }
40
+ finally {
41
+ reader.releaseLock();
42
+ }
43
+ const bytes = new Uint8Array(total);
44
+ let offset = 0;
45
+ for (const chunk of chunks) {
46
+ bytes.set(chunk, offset);
47
+ offset += chunk.byteLength;
48
+ }
49
+ try {
50
+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
51
+ }
52
+ catch {
53
+ throw publishingError('RESPONSE_INVALID');
54
+ }
55
+ }
56
+ /** All writes are explicit. Recovery reads the original request; there is no retry loop. */
57
+ export function createPublishingClient({ configuration, credential, allowLoopback = false, request = fetch, limits = defaults, verifyActivation }) {
58
+ const config = parsePublishingConfiguration(configuration, { allowLoopback }), selected = boundedLimits(limits);
59
+ if (typeof credential !== 'string' || !/^[A-Za-z0-9_-]{32,4096}$/.test(credential) || typeof request !== 'function' || verifyActivation !== undefined && typeof verifyActivation !== 'function')
60
+ throw publishingError('CREDENTIAL_INVALID');
61
+ const send = async (method, relative, body, signal, contentType = 'application/json') => {
62
+ signal?.throwIfAborted();
63
+ const timeout = AbortSignal.timeout(selected.requestMs), active = signal ? AbortSignal.any([signal, timeout]) : timeout;
64
+ let response;
65
+ try {
66
+ response = await request(config.serviceUrl + relative, { method, headers: { authorization: 'Bearer ' + credential, 'x-link-light-project-id': config.projectId, ...(body === undefined ? {} : { 'content-type': contentType }) }, body, redirect: 'error', credentials: 'omit', cache: 'no-store', signal: active });
67
+ }
68
+ catch {
69
+ active.throwIfAborted();
70
+ throw publishingError('SERVICE_UNREACHABLE');
71
+ }
72
+ active.throwIfAborted();
73
+ const value = await responseJson(response, selected.maximumResponseBytes, active);
74
+ if (!response.ok) {
75
+ const error = value && typeof value === 'object' && 'error' in value ? value.error : undefined;
76
+ const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;
77
+ throw publishingError(typeof code === 'string' && serviceErrors.has(code) ? code : 'SERVICE_REQUEST_FAILED');
78
+ }
79
+ return value;
80
+ };
81
+ const boundStatus = async (value, intent) => {
82
+ const status = parsePublishingStatus(value), identity = await calculateBytesIntegrity(publishingIntentBytes(intent));
83
+ if (intent.projectId !== config.projectId || intent.package.publisherId !== config.publisher.publisherId || status.projectId !== config.projectId || status.requestId !== intent.requestId || status.intentSha256 !== identity.sha256 || status.missingFiles.length > intent.package.fileCount || status.missingFiles.reduce((sum, file) => sum + file.byteLength, 0) > intent.package.totalBytes)
84
+ throw publishingError('STATUS_BINDING_INVALID');
85
+ if (status.activation !== undefined) {
86
+ if (typeof verifyActivation !== 'function')
87
+ throw publishingError('ACTIVATION_VERIFIER_REQUIRED');
88
+ await verifyActivation({ activation: status.activation, intent, configuration: structuredClone(config) });
89
+ }
90
+ return status;
91
+ };
92
+ const checkedIntent = (value) => { const intent = parsePublishingIntent(value); if (intent.projectId !== config.projectId || intent.package.publisherId !== config.publisher.publisherId)
93
+ throw publishingError('INTENT_BINDING_INVALID'); return intent; };
94
+ return Object.freeze({
95
+ async getProject({ signal } = {}) {
96
+ const project = parsePublishingProject(await send('GET', '/v1/project', undefined, signal), { allowLoopback });
97
+ if (JSON.stringify(project.configuration) !== JSON.stringify(config))
98
+ throw publishingError('PROJECT_BINDING_INVALID');
99
+ return project;
100
+ },
101
+ async getLatestRelease({ signal } = {}) {
102
+ const value = await send('GET', '/v1/project/release', undefined, signal);
103
+ if (!protocolRecord(value, ['schemaVersion', 'intent']) || value.schemaVersion !== 1)
104
+ throw publishingError('PROJECT_BINDING_INVALID');
105
+ if (value.intent === null)
106
+ return undefined;
107
+ const intent = checkedIntent(value.intent);
108
+ try {
109
+ return { intent, status: await boundStatus(await send('GET', '/v1/requests/' + intent.requestId, undefined, signal), intent) };
110
+ }
111
+ catch (error) {
112
+ if (error && typeof error === 'object')
113
+ Object.assign(error, { requestId: intent.requestId });
114
+ throw error;
115
+ }
116
+ },
117
+ async createRequest({ intent: input, manifestBytes, signal }) {
118
+ const intent = checkedIntent(input);
119
+ if (!(manifestBytes instanceof Uint8Array) || manifestBytes.byteLength > 1048576)
120
+ throw publishingError('MANIFEST_INVALID');
121
+ let prepared;
122
+ try {
123
+ prepared = await createArtifactContentManifest(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(manifestBytes)));
124
+ }
125
+ catch {
126
+ throw publishingError('MANIFEST_INVALID');
127
+ }
128
+ if (prepared.content.manifestSha256 !== intent.package.content.manifestSha256 || prepared.bytes.byteLength !== manifestBytes.byteLength || prepared.bytes.some((byte, index) => byte !== manifestBytes[index]) || prepared.manifest.files.length !== intent.package.fileCount || prepared.manifest.files.reduce((sum, file) => sum + file.byteLength, 0) !== intent.package.totalBytes)
129
+ throw publishingError('MANIFEST_BINDING_INVALID');
130
+ return boundStatus(await send('POST', '/v1/requests', JSON.stringify({ intent, manifest: prepared.manifest }), signal), intent);
131
+ },
132
+ async getStatus({ intent: input, signal }) { const intent = checkedIntent(input); return boundStatus(await send('GET', '/v1/requests/' + intent.requestId, undefined, signal), intent); },
133
+ async resumeRequest({ intent: input, signal }) { const intent = checkedIntent(input); return boundStatus(await send('POST', '/v1/requests/' + intent.requestId + '/resume', JSON.stringify({ intent }), signal), intent); },
134
+ async recoverRequest({ intent: input, signal }) { const intent = checkedIntent(input); return boundStatus(await send('POST', '/v1/requests/' + intent.requestId + '/recover', JSON.stringify({ intent }), signal), intent); },
135
+ async queueRequest({ intent: input, signal }) { const intent = checkedIntent(input); return boundStatus(await send('POST', '/v1/requests/' + intent.requestId + '/commit', JSON.stringify({ intent }), signal), intent); },
136
+ async abandonRequest({ intent: input, signal }) { const intent = checkedIntent(input); return boundStatus(await send('POST', '/v1/requests/' + intent.requestId + '/abandon', '{}', signal), intent); },
137
+ async uploadChunk({ requestId, file, offset, bytes, signal }) {
138
+ if (!publishingRequestId(requestId) || !file || !publishingDigest(file.sha256) || !Number.isSafeInteger(file.byteLength) || file.byteLength < 0 || file.byteLength > 134217728 || !Number.isSafeInteger(offset) || offset < 0 || !(bytes instanceof Uint8Array) || bytes.byteLength < 1 || bytes.byteLength > selected.maximumChunkBytes || offset + bytes.byteLength > file.byteLength)
139
+ throw publishingError('CHUNK_INVALID');
140
+ const snapshot = new Uint8Array(bytes), value = await send('PUT', '/v1/requests/' + requestId + '/files/' + file.sha256 + '?offset=' + offset, snapshot, signal, 'application/octet-stream');
141
+ if (!protocolRecord(value, ['schemaVersion', 'sha256', 'receivedBytes']) || value.schemaVersion !== 1 || value.sha256 !== file.sha256 || value.receivedBytes !== offset + snapshot.byteLength)
142
+ throw publishingError('CHUNK_RESPONSE_INVALID');
143
+ return { schemaVersion: 1, sha256: file.sha256, receivedBytes: offset + snapshot.byteLength };
144
+ },
145
+ });
146
+ }
@@ -0,0 +1,3 @@
1
+ export { parseSolutionPackageDescriptor, parseSolutionPackageLimits } from './package.js';
2
+ export { parsePublishingConfiguration, parsePublishingProject, parsePublishingIntent, parsePublishingStatus, publishingIntentBytes } from './protocol.js';
3
+ export { createPublishingClient } from './client.js';
@@ -0,0 +1,88 @@
1
+ import { createHash, createPrivateKey, createPublicKey, sign } from 'node:crypto';
2
+ import { protocolRecord, publishingError, publishingIdentifier } from '../protocol.js';
3
+ import { deliveryBindingBytes, deliveryBindingFields, readDeliveryBody, validateDeliveryOrigin } from '../acceptance-delivery-binding.js';
4
+ export { maximumAcceptanceArchiveBytes, readDeliveryBody, verifyAcceptanceDelivery } from '../acceptance-delivery-binding.js';
5
+ const fail = (code) => publishingError('ACCEPTANCE_' + code);
6
+ const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
7
+ export function parseAcceptanceDeliveryCredential(value) {
8
+ if (!protocolRecord(value, ['origin', 'keyId', 'privateKey']) || !publishingIdentifier(value.keyId) ||
9
+ typeof value.privateKey !== 'string' || value.privateKey.length > 4096)
10
+ throw fail('CREDENTIAL_INVALID');
11
+ const origin = validateDeliveryOrigin(value.origin);
12
+ const key = createPrivateKey(value.privateKey);
13
+ if (key.asymmetricKeyType !== 'ed25519')
14
+ throw fail('CREDENTIAL_INVALID');
15
+ return { origin, keyId: value.keyId, privateKey: key.export({ type: 'pkcs8', format: 'pem' }).toString() };
16
+ }
17
+ export function acceptanceDeliveryTarget(credential) {
18
+ const { origin, keyId, privateKey } = parseAcceptanceDeliveryCredential(credential);
19
+ return { origin, keyId, publicKeySha256: hash(createPublicKey(privateKey).export({ type: 'spki', format: 'der' })) };
20
+ }
21
+ export function signAcceptanceDelivery(value, privateKey) {
22
+ return sign(null, deliveryBindingBytes(value), privateKey).toString('base64url');
23
+ }
24
+ function deliveryTarget({ intent, archive, credential, request = fetch, signal }) {
25
+ if (!credential)
26
+ throw fail('CREDENTIAL_REQUIRED');
27
+ const { origin, keyId, privateKey } = parseAcceptanceDeliveryCredential(credential);
28
+ const expected = { projectId: intent.projectId, solutionId: intent.package.solutionId, version: intent.package.version,
29
+ origin, keyId, manifestSha256: intent.package.content.manifestSha256, ...archive };
30
+ const url = new URL('/v1/acceptance/installations/' + expected.version, origin);
31
+ const timeout = AbortSignal.timeout(30000);
32
+ const options = { redirect: 'error', signal: signal ? AbortSignal.any([signal, timeout]) : timeout };
33
+ async function observed() {
34
+ const response = await request(url, { ...options, method: 'GET', headers: { accept: 'application/json' } });
35
+ if (response.status === 404) {
36
+ await response.body?.cancel();
37
+ return false;
38
+ }
39
+ if (response.status !== 200) {
40
+ await response.body?.cancel();
41
+ throw fail('DELIVERY_UNKNOWN');
42
+ }
43
+ const receipt = await readDeliveryBody(response, 8192);
44
+ let value;
45
+ try {
46
+ value = JSON.parse(receipt.toString('utf8'));
47
+ }
48
+ catch {
49
+ throw fail('DELIVERY_UNKNOWN');
50
+ }
51
+ if (!protocolRecord(value, deliveryBindingFields))
52
+ throw fail('DELIVERY_UNKNOWN');
53
+ if (!deliveryBindingBytes(value).equals(deliveryBindingBytes(expected)))
54
+ throw fail('VERSION_CONFLICT');
55
+ return true;
56
+ }
57
+ return { observed, expected, privateKey, options, url, request };
58
+ }
59
+ export async function observeAcceptanceDelivery(input) {
60
+ return deliveryTarget(input).observed();
61
+ }
62
+ export async function deliverAcceptanceArchive(input) {
63
+ const { bytes, archive } = input;
64
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength !== archive.byteLength || hash(bytes) !== archive.archiveSha256)
65
+ throw fail('ARCHIVE_CHANGED');
66
+ const { observed, expected, privateKey, options, url, request } = deliveryTarget(input);
67
+ if (await observed())
68
+ return;
69
+ const signature = signAcceptanceDelivery(expected, privateKey);
70
+ let rejection;
71
+ try {
72
+ const response = await request(url, { ...options, method: 'PUT', headers: { 'content-type': 'application/octet-stream',
73
+ 'x-link-light-binding': Buffer.from(JSON.stringify(expected)).toString('base64url'), 'x-link-light-signature': signature }, body: new Uint8Array(bytes) });
74
+ await response.body?.cancel();
75
+ if (response.status === 403)
76
+ rejection = 'SIGNATURE_INVALID';
77
+ if (response.status === 409)
78
+ rejection = 'VERSION_CONFLICT';
79
+ if ([400, 413, 415, 422].includes(response.status))
80
+ rejection = 'DELIVERY_REJECTED';
81
+ }
82
+ catch (error) {
83
+ if (error && typeof error === 'object' && 'code' in error && typeof error.code === 'string' && error.code.startsWith('PUBLISHING_ACCEPTANCE_'))
84
+ throw error;
85
+ }
86
+ if (!await observed())
87
+ throw fail(rejection ?? 'DELIVERY_UNKNOWN');
88
+ }
@@ -0,0 +1,3 @@
1
+ import { createPublishingActivationFunctions } from '../shared/activation.js';
2
+ const helpers = createPublishingActivationFunctions(() => import('@xlinklight/platform/server'));
3
+ export const { createPublishingActivation, verifyPublishingActivation } = helpers;
@@ -0,0 +1,76 @@
1
+ import { createHash, createPublicKey } from 'node:crypto';
2
+ import { parseAcceptanceDeliveryCredential } from './acceptance-delivery.js';
3
+ import { createPublishingClient } from '../client.js';
4
+ import { parsePublishingConfiguration, protocolRecord, publishingError } from '../protocol.js';
5
+ const key = 'client-authorization', hash = (value) => createHash('sha256').update(value).digest('hex'), fail = (code) => publishingError('CREDENTIAL_' + code);
6
+ const credentialValid = (value) => typeof value === 'string' && /^[A-Za-z0-9_-]{32,4096}$/.test(value);
7
+ function saved(record, allowLoopback) {
8
+ if (!record)
9
+ return undefined;
10
+ const value = record.payload;
11
+ if (!protocolRecord(value, ['schemaVersion', 'configuration', 'configurationSha256', 'credential', 'credentialSha256'], ['acceptanceDelivery']) || value.schemaVersion !== 1 || !credentialValid(value.credential))
12
+ throw fail('INVALID');
13
+ let configuration;
14
+ try {
15
+ configuration = parsePublishingConfiguration(value.configuration, { allowLoopback });
16
+ }
17
+ catch {
18
+ throw fail('INVALID');
19
+ }
20
+ if (hash(JSON.stringify(configuration)) !== value.configurationSha256 || hash(value.credential) !== value.credentialSha256)
21
+ throw fail('INVALID');
22
+ return { configuration, credential: value.credential, ...(value.acceptanceDelivery ? { acceptanceDelivery: parseAcceptanceDeliveryCredential(value.acceptanceDelivery) } : {}) };
23
+ }
24
+ function store(journal) { if (!journal || typeof journal.load !== 'function' || typeof journal.compareAndSet !== 'function')
25
+ throw fail('STORE_INVALID'); return journal; }
26
+ /** The caller supplies private persistent storage, including access controls and
27
+ * backup policy. No provider credential or process/global setting is stored. */
28
+ export async function loadPublishingAuthorization({ journal, allowLoopback = false, signal }) {
29
+ signal?.throwIfAborted();
30
+ return saved(await store(journal).load(key, { signal }), allowLoopback);
31
+ }
32
+ /** Validate installed trust and current project access before atomic install.
33
+ * A changed service/publisher trust never adopts an existing recovery journal. */
34
+ export async function installPublishingAuthorization({ journal, configuration: input, credential, acceptanceDelivery, replaceCredential = false, allowLoopback = false, request, clientLimits, signal }) {
35
+ store(journal);
36
+ signal?.throwIfAborted();
37
+ const configuration = parsePublishingConfiguration(input, { allowLoopback });
38
+ if (!credentialValid(credential) || typeof replaceCredential !== 'boolean')
39
+ throw fail('INVALID');
40
+ const previous = await journal.load(key, { signal }), current = saved(previous, allowLoopback), configurationSha256 = hash(JSON.stringify(configuration)), credentialSha256 = hash(credential);
41
+ if (current && JSON.stringify(current.configuration) !== JSON.stringify(configuration))
42
+ throw fail('TRUST_CHANGED');
43
+ if (current && current.credential !== credential && !replaceCredential)
44
+ throw fail('REPLACEMENT_REQUIRED');
45
+ const delivery = acceptanceDelivery === undefined ? current?.acceptanceDelivery : parseAcceptanceDeliveryCredential(acceptanceDelivery);
46
+ if (delivery) {
47
+ const publicBytes = (key) => createPublicKey(key).export({ type: 'spki', format: 'der' });
48
+ if (configuration.publisher.keys.some(key => publicBytes(key.publicKey).equals(publicBytes(delivery.privateKey))))
49
+ throw fail('TRUST_CHANGED');
50
+ if (current?.acceptanceDelivery && (delivery.origin !== current.acceptanceDelivery.origin || delivery.keyId !== current.acceptanceDelivery.keyId ||
51
+ !publicBytes(delivery.privateKey).equals(publicBytes(current.acceptanceDelivery.privateKey))))
52
+ throw fail('TRUST_CHANGED');
53
+ if (current?.acceptanceDelivery && JSON.stringify(current.acceptanceDelivery) !== JSON.stringify(delivery) && !replaceCredential)
54
+ throw fail('REPLACEMENT_REQUIRED');
55
+ }
56
+ const client = createPublishingClient({ configuration, credential, allowLoopback, ...(request ? { request } : {}), ...(clientLimits ? { limits: clientLimits } : {}) }), project = await client.getProject({ signal });
57
+ if (current?.credential === credential && JSON.stringify(current.acceptanceDelivery) === JSON.stringify(delivery)) {
58
+ const latest = await journal.load(key, { signal });
59
+ if (!previous || latest?.revision !== previous.revision)
60
+ throw fail('CONFLICT');
61
+ saved(latest, allowLoopback);
62
+ return { status: 'VERIFIED', projectId: configuration.projectId, credentialSha256, policyRevision: project.policyRevision };
63
+ }
64
+ let result;
65
+ try {
66
+ result = await journal.compareAndSet({ key, expectedRevision: previous?.revision ?? 0, payload: { schemaVersion: 1, configuration: { ...configuration }, configurationSha256, credential, credentialSha256, ...(delivery ? { acceptanceDelivery: { ...delivery } } : {}) } }, { signal });
67
+ }
68
+ catch {
69
+ throw fail('PERSISTENCE_UNKNOWN');
70
+ }
71
+ if (result === 'conflict')
72
+ throw fail('CONFLICT');
73
+ if (result !== 'stored')
74
+ throw fail('PERSISTENCE_UNKNOWN');
75
+ return { status: previous ? 'REPLACED' : 'CONFIGURED', projectId: configuration.projectId, credentialSha256, policyRevision: project.policyRevision };
76
+ }
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, realpathSync } from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { runPublishingCommand } from './publishing-command.js';
5
+ async function main() {
6
+ const controller = new AbortController(), stop = () => controller.abort();
7
+ process.once('SIGINT', stop);
8
+ process.once('SIGTERM', stop);
9
+ try {
10
+ const result = await runPublishingCommand(process.argv.slice(2), { signal: controller.signal });
11
+ process.stdout.write(JSON.stringify(result.output) + '\n');
12
+ process.exitCode = result.exitCode;
13
+ }
14
+ finally {
15
+ process.off('SIGINT', stop);
16
+ process.off('SIGTERM', stop);
17
+ }
18
+ }
19
+ if (process.argv[1] && existsSync(process.argv[1]) && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)))
20
+ void main();
@@ -0,0 +1,9 @@
1
+ export { prepareSolutionPackage, prepareSolutionPackageBytes, verifySolutionPackage, verifySolutionPackageBytes } from './solution-package.js';
2
+ export { openPublishingJournal } from './journal.js';
3
+ export { createPublishingSession } from './session.js';
4
+ export { installPublishingAuthorization, loadPublishingAuthorization } from './authorization.js';
5
+ export { createPublishingActivation, verifyPublishingActivation } from './activation.js';
6
+ export { PublishingSourceError } from './source-error.js';
7
+ export { createPublishingWorkflow } from './workflow.js';
8
+ export { deliverAcceptanceArchive, signAcceptanceDelivery, maximumAcceptanceArchiveBytes, readDeliveryBody, verifyAcceptanceDelivery } from './acceptance-delivery.js';
9
+ export { runPublishingCommand } from './publishing-command.js';