@xlinklight/publishing 3.3.0 → 3.4.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.
Files changed (119) hide show
  1. package/README.md +23 -3
  2. package/dist/src/acceptance-delivery-binding.d.ts +20 -0
  3. package/dist/src/acceptance-delivery-binding.js +59 -0
  4. package/dist/src/acceptance.d.ts +49 -0
  5. package/dist/src/acceptance.js +79 -0
  6. package/dist/src/client.d.ts +71 -0
  7. package/dist/src/client.js +146 -0
  8. package/dist/src/index.d.ts +6 -0
  9. package/dist/src/index.js +3 -0
  10. package/dist/src/node/acceptance-delivery.d.ts +34 -0
  11. package/dist/src/node/acceptance-delivery.js +88 -0
  12. package/dist/src/node/activation.d.ts +5 -0
  13. package/dist/src/node/activation.js +3 -0
  14. package/dist/src/node/authorization.d.ts +31 -0
  15. package/dist/src/node/authorization.js +76 -0
  16. package/dist/src/node/cli.d.ts +2 -0
  17. package/dist/src/node/cli.js +22 -0
  18. package/dist/src/node/index.d.ts +20 -0
  19. package/dist/src/node/index.js +11 -0
  20. package/dist/src/node/journal-directory.d.ts +2 -0
  21. package/dist/src/node/journal-directory.js +121 -0
  22. package/dist/src/node/journal.d.ts +49 -0
  23. package/dist/src/node/journal.js +280 -0
  24. package/dist/src/node/local-json-file.d.ts +3 -0
  25. package/dist/src/node/local-json-file.js +49 -0
  26. package/dist/src/node/publishing-command.d.ts +46 -0
  27. package/dist/src/node/publishing-command.js +268 -0
  28. package/dist/src/node/session.d.ts +95 -0
  29. package/dist/src/node/session.js +223 -0
  30. package/dist/src/node/solution-package.d.ts +55 -0
  31. package/dist/src/node/solution-package.js +217 -0
  32. package/dist/src/node/source-error.d.ts +10 -0
  33. package/dist/src/node/source-error.js +15 -0
  34. package/dist/src/node/source-producer.d.ts +5 -0
  35. package/dist/src/node/source-producer.js +145 -0
  36. package/dist/src/node/terminal-network.d.ts +23 -0
  37. package/dist/src/node/terminal-network.js +122 -0
  38. package/dist/src/node/workflow.d.ts +74 -0
  39. package/dist/src/node/workflow.js +467 -0
  40. package/dist/src/package.d.ts +38 -0
  41. package/dist/src/package.js +74 -0
  42. package/dist/src/protocol.d.ts +83 -0
  43. package/dist/src/protocol.js +105 -0
  44. package/dist/src/shared/activation-types.d.ts +37 -0
  45. package/dist/src/shared/activation-types.js +1 -0
  46. package/dist/src/shared/activation.d.ts +17 -0
  47. package/dist/src/shared/activation.js +111 -0
  48. package/dist/src/shared/records.d.ts +10 -0
  49. package/dist/src/shared/records.js +26 -0
  50. package/dist/src/shared/release-version.d.ts +4 -0
  51. package/dist/src/shared/release-version.js +15 -0
  52. package/dist/src/worker/activation.d.ts +12 -0
  53. package/dist/src/worker/activation.js +11 -0
  54. package/dist/src/worker/durable-retention.d.ts +9 -0
  55. package/dist/src/worker/durable-retention.js +96 -0
  56. package/dist/src/worker/index.d.ts +12 -0
  57. package/dist/src/worker/index.js +7 -0
  58. package/dist/src/worker/journal.d.ts +129 -0
  59. package/dist/src/worker/journal.js +328 -0
  60. package/dist/src/worker/package.d.ts +60 -0
  61. package/dist/src/worker/package.js +116 -0
  62. package/dist/src/worker/release-retention.d.ts +34 -0
  63. package/dist/src/worker/release-retention.js +27 -0
  64. package/dist/src/worker/release.d.ts +22 -0
  65. package/dist/src/worker/release.js +59 -0
  66. package/dist/src/worker/runtime.d.ts +47 -0
  67. package/dist/src/worker/runtime.js +98 -0
  68. package/dist/src/worker/service.d.ts +128 -0
  69. package/dist/src/worker/service.js +520 -0
  70. package/package.json +23 -14
  71. package/src/acceptance-delivery-binding.mjs +0 -49
  72. package/src/acceptance.d.mts +0 -24
  73. package/src/acceptance.mjs +0 -67
  74. package/src/client.d.mts +0 -16
  75. package/src/client.mjs +0 -74
  76. package/src/index.d.mts +0 -6
  77. package/src/index.mjs +0 -3
  78. package/src/node/acceptance-delivery.d.mts +0 -11
  79. package/src/node/acceptance-delivery.mjs +0 -70
  80. package/src/node/activation.d.mts +0 -8
  81. package/src/node/activation.mjs +0 -3
  82. package/src/node/authorization.d.mts +0 -8
  83. package/src/node/authorization.mjs +0 -49
  84. package/src/node/cli.mjs +0 -12
  85. package/src/node/index.d.mts +0 -17
  86. package/src/node/index.mjs +0 -9
  87. package/src/node/journal.d.mts +0 -13
  88. package/src/node/journal.mjs +0 -135
  89. package/src/node/publishing-command.d.mts +0 -20
  90. package/src/node/publishing-command.mjs +0 -104
  91. package/src/node/session.d.mts +0 -25
  92. package/src/node/session.mjs +0 -134
  93. package/src/node/solution-package.d.mts +0 -15
  94. package/src/node/solution-package.mjs +0 -113
  95. package/src/node/source-error.d.mts +0 -5
  96. package/src/node/source-error.mjs +0 -9
  97. package/src/node/source-producer.mjs +0 -103
  98. package/src/node/workflow.d.mts +0 -37
  99. package/src/node/workflow.mjs +0 -320
  100. package/src/package.d.mts +0 -11
  101. package/src/package.mjs +0 -36
  102. package/src/protocol.d.mts +0 -27
  103. package/src/protocol.mjs +0 -50
  104. package/src/shared/activation.d.mts +0 -5
  105. package/src/shared/activation.mjs +0 -64
  106. package/src/worker/activation.d.mts +0 -7
  107. package/src/worker/activation.mjs +0 -4
  108. package/src/worker/index.d.mts +0 -6
  109. package/src/worker/index.mjs +0 -6
  110. package/src/worker/journal.d.mts +0 -21
  111. package/src/worker/journal.mjs +0 -151
  112. package/src/worker/package.d.mts +0 -16
  113. package/src/worker/package.mjs +0 -32
  114. package/src/worker/release.d.mts +0 -7
  115. package/src/worker/release.mjs +0 -21
  116. package/src/worker/runtime.d.mts +0 -4
  117. package/src/worker/runtime.mjs +0 -23
  118. package/src/worker/service.d.mts +0 -41
  119. package/src/worker/service.mjs +0 -251
@@ -0,0 +1,83 @@
1
+ import type { JsonValue } from '@xlinklight/contracts';
2
+ import type { SolutionPackageLimits } from './package.js';
3
+ /** Consumer-owned read-only public metadata port. It carries no credentials or
4
+ * command body and does not require the optional platform implementation. */
5
+ export type PublishingMetadataTransport = (address: string, options: {
6
+ timeoutMs?: number;
7
+ signal?: AbortSignal;
8
+ }) => Promise<JsonValue>;
9
+ export interface PublishingConfiguration {
10
+ schemaVersion: 1;
11
+ serviceUrl: string;
12
+ projectId: string;
13
+ coreOrigin: string;
14
+ publisher: {
15
+ publisherId: string;
16
+ keys: {
17
+ keyId: string;
18
+ publicKey: string;
19
+ }[];
20
+ };
21
+ }
22
+ export interface PublishingIntent {
23
+ schemaVersion: 1;
24
+ requestId: string;
25
+ projectId: string;
26
+ policyRevision: number;
27
+ package: {
28
+ solutionId: string;
29
+ publisherId: string;
30
+ packageName: string;
31
+ version: string;
32
+ content: {
33
+ manifestSha256: string;
34
+ };
35
+ fileCount: number;
36
+ totalBytes: number;
37
+ };
38
+ provenance?: {
39
+ gitRevision: string;
40
+ };
41
+ }
42
+ export interface PublishingProject {
43
+ schemaVersion: 1;
44
+ configuration: PublishingConfiguration;
45
+ policyRevision: number;
46
+ solutionId: string;
47
+ packageName: string;
48
+ limits: SolutionPackageLimits;
49
+ }
50
+ export interface PublishingStatus {
51
+ schemaVersion: 1;
52
+ requestId: string;
53
+ projectId: string;
54
+ intentSha256: string;
55
+ state: 'uploading' | 'queued' | 'deploying' | 'registered' | 'awaiting-acceptance' | 'active' | 'failed' | 'unknown' | 'abandoned' | 'superseded';
56
+ sideEffects: 'none' | 'pending' | 'unknown' | 'closed';
57
+ missingFiles: {
58
+ path: string;
59
+ sha256: string;
60
+ byteLength: number;
61
+ receivedBytes: number;
62
+ }[];
63
+ activation?: JsonValue;
64
+ error?: {
65
+ code: string;
66
+ };
67
+ }
68
+ export declare const publishingError: (code: string) => Error & {
69
+ code: string;
70
+ };
71
+ export declare const protocolRecord: <T>(value: T, required: readonly string[], optional?: readonly string[]) => value is T & Record<string, unknown>;
72
+ export declare const publishingIdentifier: (value: unknown) => value is string;
73
+ export declare const publishingDigest: (value: unknown) => value is string;
74
+ export declare const publishingRequestId: (value: unknown) => value is string;
75
+ export declare function parsePublishingConfiguration(value: unknown, { allowLoopback }?: {
76
+ allowLoopback?: boolean;
77
+ }): PublishingConfiguration;
78
+ export declare function parsePublishingIntent(value: unknown): PublishingIntent;
79
+ export declare function parsePublishingProject(value: unknown, { allowLoopback }?: {
80
+ allowLoopback?: boolean;
81
+ }): PublishingProject;
82
+ export declare const publishingIntentBytes: (value: unknown) => Uint8Array;
83
+ export declare function parsePublishingStatus(value: unknown): PublishingStatus;
@@ -0,0 +1,105 @@
1
+ import { validatePortableRelativePath } from '@openge/forge-path-safety';
2
+ import { parseSolutionPackageLimits } from './package.js';
3
+ import { jsonValue } from './shared/records.js';
4
+ export const publishingError = (code) => Object.assign(Error('PUBLISHING_' + code), { code: 'PUBLISHING_' + code });
5
+ const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
6
+ export const protocolRecord = (value, required, optional = []) => record(value) && required.every(key => Object.hasOwn(value, key)) && Object.keys(value).every(key => required.includes(key) || optional.includes(key));
7
+ export const publishingIdentifier = (value) => typeof value === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(value);
8
+ export const publishingDigest = (value) => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
9
+ export const publishingRequestId = (value) => typeof value === 'string' && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(value);
10
+ const integer = (value, min, max) => typeof value === 'number' && Number.isSafeInteger(value) && value >= min && value <= max;
11
+ const member = (value, items) => items.some(item => value === item);
12
+ function origin(value, allowLoopback) {
13
+ if (typeof value !== 'string' || value.length > 2048)
14
+ throw publishingError('CONFIGURATION_INVALID');
15
+ let url;
16
+ try {
17
+ url = new URL(value);
18
+ }
19
+ catch {
20
+ throw publishingError('CONFIGURATION_INVALID');
21
+ }
22
+ if (url.origin !== value || url.username || url.password || url.hash || url.search || !(url.protocol === 'https:' || allowLoopback === true && url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname)))
23
+ throw publishingError('CONFIGURATION_INVALID');
24
+ return value;
25
+ }
26
+ export function parsePublishingConfiguration(value, { allowLoopback = false } = {}) {
27
+ if (!protocolRecord(value, ['schemaVersion', 'serviceUrl', 'projectId', 'coreOrigin', 'publisher']) || value.schemaVersion !== 1 || !publishingIdentifier(value.projectId) || !protocolRecord(value.publisher, ['publisherId', 'keys']) || !publishingIdentifier(value.publisher.publisherId) || !Array.isArray(value.publisher.keys) || value.publisher.keys.length < 1 || value.publisher.keys.length > 8)
28
+ throw publishingError('CONFIGURATION_INVALID');
29
+ const seen = new Set(), keys = value.publisher.keys.map(key => {
30
+ if (!protocolRecord(key, ['keyId', 'publicKey']) || !publishingIdentifier(key.keyId) || seen.has(key.keyId) || typeof key.publicKey !== 'string' || key.publicKey.length > 4096 || !/^-----BEGIN PUBLIC KEY-----\n[A-Za-z0-9+/=\n]+\n-----END PUBLIC KEY-----\n?$/.test(key.publicKey))
31
+ throw publishingError('CONFIGURATION_INVALID');
32
+ seen.add(key.keyId);
33
+ return { keyId: key.keyId, publicKey: key.publicKey };
34
+ });
35
+ return { schemaVersion: 1, serviceUrl: origin(value.serviceUrl, allowLoopback), projectId: value.projectId, coreOrigin: origin(value.coreOrigin, allowLoopback), publisher: { publisherId: value.publisher.publisherId, keys } };
36
+ }
37
+ export function parsePublishingIntent(value) {
38
+ if (!protocolRecord(value, ['schemaVersion', 'requestId', 'projectId', 'policyRevision', 'package'], ['provenance']) || value.schemaVersion !== 1 || !publishingRequestId(value.requestId) || !publishingIdentifier(value.projectId) || !integer(value.policyRevision, 1, Number.MAX_SAFE_INTEGER))
39
+ throw publishingError('INTENT_INVALID');
40
+ const item = value.package;
41
+ if (!protocolRecord(item, ['solutionId', 'publisherId', 'packageName', 'version', 'content', 'fileCount', 'totalBytes']) || !publishingIdentifier(item.solutionId) || !publishingIdentifier(item.publisherId) || typeof item.packageName !== 'string' || !/^@[a-z0-9][a-z0-9.-]{0,63}\/[a-z0-9][a-z0-9.-]{0,63}$/.test(item.packageName) || typeof item.version !== 'string' || !/^\d{1,8}\.\d{1,8}\.\d{1,8}$/.test(item.version) || !protocolRecord(item.content, ['manifestSha256']) || !publishingDigest(item.content.manifestSha256) || !integer(item.fileCount, 1, 10000) || !integer(item.totalBytes, 1, 268435456))
42
+ throw publishingError('INTENT_INVALID');
43
+ let provenance;
44
+ if (value.provenance !== undefined) {
45
+ if (!protocolRecord(value.provenance, ['gitRevision']) || typeof value.provenance.gitRevision !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value.provenance.gitRevision))
46
+ throw publishingError('INTENT_INVALID');
47
+ provenance = { gitRevision: value.provenance.gitRevision };
48
+ }
49
+ return { schemaVersion: 1, requestId: value.requestId, projectId: value.projectId, policyRevision: value.policyRevision, package: { solutionId: item.solutionId, publisherId: item.publisherId, packageName: item.packageName, version: item.version, content: { manifestSha256: item.content.manifestSha256 }, fileCount: item.fileCount, totalBytes: item.totalBytes }, ...(provenance ? { provenance } : {}) };
50
+ }
51
+ export function parsePublishingProject(value, { allowLoopback = false } = {}) {
52
+ if (!protocolRecord(value, ['schemaVersion', 'configuration', 'policyRevision', 'solutionId', 'packageName', 'limits']) || value.schemaVersion !== 1 || !integer(value.policyRevision, 1, Number.MAX_SAFE_INTEGER) || !publishingIdentifier(value.solutionId) || typeof value.packageName !== 'string' || !/^@[a-z0-9][a-z0-9.-]{0,63}\/[a-z0-9][a-z0-9.-]{0,63}$/.test(value.packageName))
53
+ throw publishingError('PROJECT_INVALID');
54
+ let limits;
55
+ try {
56
+ limits = parseSolutionPackageLimits(value.limits);
57
+ }
58
+ catch {
59
+ throw publishingError('PROJECT_INVALID');
60
+ }
61
+ return { schemaVersion: 1, configuration: parsePublishingConfiguration(value.configuration, { allowLoopback }), policyRevision: value.policyRevision, solutionId: value.solutionId, packageName: value.packageName, limits };
62
+ }
63
+ export const publishingIntentBytes = (value) => new TextEncoder().encode(JSON.stringify(parsePublishingIntent(value)));
64
+ export function parsePublishingStatus(value) {
65
+ if (!protocolRecord(value, ['schemaVersion', 'requestId', 'projectId', 'intentSha256', 'state', 'sideEffects', 'missingFiles'], ['activation', 'error']) || value.schemaVersion !== 1 || !publishingRequestId(value.requestId) || !publishingIdentifier(value.projectId) || !publishingDigest(value.intentSha256) || !member(value.state, ['uploading', 'queued', 'deploying', 'registered', 'awaiting-acceptance', 'active', 'failed', 'unknown', 'abandoned', 'superseded']) || !member(value.sideEffects, ['none', 'pending', 'unknown', 'closed']) || !Array.isArray(value.missingFiles) || value.missingFiles.length > 10000)
66
+ throw publishingError('STATUS_INVALID');
67
+ const names = new Set(), missingFiles = value.missingFiles.map(file => {
68
+ if (!protocolRecord(file, ['path', 'sha256', 'byteLength', 'receivedBytes']) || !publishingDigest(file.sha256) || !integer(file.byteLength, 0, 134217728) || !integer(file.receivedBytes, 0, file.byteLength))
69
+ throw publishingError('STATUS_INVALID');
70
+ let relative;
71
+ try {
72
+ if (typeof file.path !== 'string')
73
+ throw publishingError('STATUS_INVALID');
74
+ relative = validatePortableRelativePath(file.path);
75
+ }
76
+ catch {
77
+ throw publishingError('STATUS_INVALID');
78
+ }
79
+ if (names.has(relative))
80
+ throw publishingError('STATUS_INVALID');
81
+ names.add(relative);
82
+ return { path: relative, sha256: file.sha256, byteLength: file.byteLength, receivedBytes: file.receivedBytes };
83
+ });
84
+ if (value.state === 'active' && (!value.activation || value.sideEffects !== 'closed' || missingFiles.length))
85
+ throw publishingError('STATUS_INVALID');
86
+ let activation;
87
+ if (value.activation !== undefined) {
88
+ if (!record(value.activation))
89
+ throw publishingError('STATUS_INVALID');
90
+ const encoded = JSON.stringify(value.activation);
91
+ if (new TextEncoder().encode(encoded).byteLength > 1048576)
92
+ throw publishingError('STATUS_INVALID');
93
+ const cloned = structuredClone(value.activation);
94
+ if (!jsonValue(cloned))
95
+ throw publishingError('STATUS_INVALID');
96
+ activation = cloned;
97
+ }
98
+ let error;
99
+ if (value.error !== undefined) {
100
+ if (!protocolRecord(value.error, ['code']) || typeof value.error.code !== 'string' || !/^[A-Z][A-Z0-9_]{1,95}$/.test(value.error.code))
101
+ throw publishingError('STATUS_INVALID');
102
+ error = { code: value.error.code };
103
+ }
104
+ return { schemaVersion: 1, requestId: value.requestId, projectId: value.projectId, intentSha256: value.intentSha256, state: value.state, sideEffects: value.sideEffects, missingFiles, ...(activation !== undefined ? { activation } : {}), ...(error ? { error } : {}) };
105
+ }
@@ -0,0 +1,37 @@
1
+ import type { Digest, SolutionReleaseManifest } from '@xlinklight/contracts';
2
+ import type { PublishingConfiguration, PublishingIntent, PublishingMetadataTransport } from '../protocol.js';
3
+ export interface PublishingActivation {
4
+ payload: {
5
+ schemaVersion: 1;
6
+ projectId: string;
7
+ requestId: string;
8
+ policyRevision: number;
9
+ configurationSha256: string;
10
+ intentSha256: string;
11
+ releaseDigest: Digest;
12
+ acceptanceReceiptSha256: string;
13
+ };
14
+ manifest: SolutionReleaseManifest;
15
+ signature: {
16
+ keyId: string;
17
+ algorithm: 'Ed25519';
18
+ value: string;
19
+ };
20
+ }
21
+ interface ActivationContext {
22
+ configuration: PublishingConfiguration;
23
+ intent: PublishingIntent;
24
+ allowLoopback?: boolean;
25
+ metadataTransport?: PublishingMetadataTransport;
26
+ signal?: AbortSignal;
27
+ }
28
+ export interface CreateActivationInput extends ActivationContext {
29
+ manifest: SolutionReleaseManifest;
30
+ acceptanceReceiptSha256: string;
31
+ keyId: string;
32
+ privateKey: string;
33
+ }
34
+ export interface VerifyActivationInput extends ActivationContext {
35
+ activation: unknown;
36
+ }
37
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ import type { SolutionReleaseManifest } from '@xlinklight/contracts';
2
+ import type * as Platform from '@xlinklight/platform/worker';
3
+ import type { PublishingMetadataTransport } from '../protocol.js';
4
+ import type { CreateActivationInput, PublishingActivation, VerifyActivationInput } from './activation-types.js';
5
+ type ActivationDomain = Pick<typeof Platform, 'publicPublisherMetadata' | 'verifySolutionRelease' | 'releasePayload' | 'canonicalMetadata' | 'metadataDigest'> & {
6
+ resolveApprovedIndependentRelease(input: Omit<Parameters<typeof Platform.resolveApprovedIndependentRelease>[0], 'transport'> & {
7
+ transport?: PublishingMetadataTransport;
8
+ }): ReturnType<typeof Platform.resolveApprovedIndependentRelease>;
9
+ };
10
+ export declare function createPublishingActivationFunctions(loadDomain: () => Promise<ActivationDomain>): {
11
+ createPublishingActivation: (input: CreateActivationInput) => Promise<PublishingActivation>;
12
+ verifyPublishingActivation: (input: VerifyActivationInput) => Promise<{
13
+ manifest: Readonly<SolutionReleaseManifest>;
14
+ acceptanceReceiptSha256: string;
15
+ }>;
16
+ };
17
+ export {};
@@ -0,0 +1,111 @@
1
+ import { createHash, createPrivateKey, createPublicKey, sign, verify } from 'node:crypto';
2
+ import { parsePublishingConfiguration, parsePublishingIntent, publishingIntentBytes, protocolRecord, publishingDigest, publishingIdentifier, publishingError } from '../protocol.js';
3
+ export function createPublishingActivationFunctions(loadDomain) {
4
+ const fail = (code) => publishingError('ACTIVATION_' + code), hash = (value) => createHash('sha256').update(value).digest('hex');
5
+ const payloadKeys = ['schemaVersion', 'projectId', 'requestId', 'policyRevision', 'configurationSha256', 'intentSha256', 'releaseDigest', 'acceptanceReceiptSha256'];
6
+ const signatureKeys = ['keyId', 'algorithm', 'value'];
7
+ async function domain() {
8
+ let sdk;
9
+ try {
10
+ sdk = await loadDomain();
11
+ }
12
+ catch {
13
+ throw fail('SDK_REQUIRED');
14
+ }
15
+ if (['publicPublisherMetadata', 'verifySolutionRelease', 'releasePayload', 'canonicalMetadata', 'metadataDigest', 'resolveApprovedIndependentRelease'].some(name => typeof sdk[name] !== 'function'))
16
+ throw fail('SDK_REQUIRED');
17
+ return sdk;
18
+ }
19
+ function context(input) {
20
+ const configuration = parsePublishingConfiguration(input.configuration, { allowLoopback: input.allowLoopback === true }), intent = parsePublishingIntent(input.intent);
21
+ if (intent.projectId !== configuration.projectId || intent.package.publisherId !== configuration.publisher.publisherId)
22
+ throw fail('BINDING_INVALID');
23
+ return { configuration, intent };
24
+ }
25
+ function manifestInput(value, sdk, configuration, intent) {
26
+ try {
27
+ if (!value || typeof value !== 'object' || !('server' in value) || !value.server || typeof value.server !== 'object' || !('url' in value.server) || typeof value.server.url !== 'string' || !('ui' in value) || !value.ui || typeof value.ui !== 'object' || !('url' in value.ui) || typeof value.ui.url !== 'string')
28
+ throw Error();
29
+ const publisher = sdk.publicPublisherMetadata({ ...configuration.publisher, enabled: true, serverOrigins: [new URL(value.server.url).origin], uiOrigins: [new URL(value.ui.url).origin] }), manifest = sdk.verifySolutionRelease(value, publisher);
30
+ if (['solutionId', 'publisherId', 'version'].some(name => manifest[name] !== intent.package[name]))
31
+ throw Error();
32
+ return { manifest, publisher };
33
+ }
34
+ catch {
35
+ throw fail('MANIFEST_INVALID');
36
+ }
37
+ }
38
+ function payloadFor(configuration, intent, releaseDigest, acceptanceReceiptSha256) {
39
+ if (!publishingDigest(acceptanceReceiptSha256))
40
+ throw fail('INVALID');
41
+ return { schemaVersion: 1, projectId: intent.projectId, requestId: intent.requestId, policyRevision: intent.policyRevision, configurationSha256: hash(JSON.stringify(configuration)), intentSha256: hash(publishingIntentBytes(intent)), releaseDigest, acceptanceReceiptSha256 };
42
+ }
43
+ const signedBytes = (payload, sdk) => Buffer.from('link-light.publishing.activation.v1\n' + sdk.metadataDigest(payload));
44
+ async function approved({ sdk, configuration, manifest, publisher, metadataTransport, signal }) {
45
+ try {
46
+ return await sdk.resolveApprovedIndependentRelease({ coreOrigin: configuration.coreOrigin, candidate: { payload: sdk.releasePayload(manifest), releaseDigest: manifest.releaseDigest, publisher }, ...(metadataTransport ? { transport: metadataTransport } : {}), signal });
47
+ }
48
+ catch {
49
+ throw fail('ADMISSION_REQUIRED');
50
+ }
51
+ }
52
+ function snapshot(value) {
53
+ try {
54
+ const encoded = JSON.stringify(value);
55
+ if (typeof encoded !== 'string' || encoded.length > 1048576 || Buffer.byteLength(encoded) > 1048576)
56
+ throw Error();
57
+ return JSON.parse(encoded);
58
+ }
59
+ catch {
60
+ throw fail('INVALID');
61
+ }
62
+ }
63
+ /** The signing owner calls this only after actual owned acceptance and closed
64
+ * effects. Its receipt digest binds evidence; the constructor does not run it. */
65
+ async function createPublishingActivation(input) {
66
+ input.signal?.throwIfAborted();
67
+ const { configuration, intent } = context(input), value = snapshot(input.manifest), sdk = await domain(), { manifest, publisher } = manifestInput(value, sdk, configuration, intent), payload = payloadFor(configuration, intent, manifest.releaseDigest, input.acceptanceReceiptSha256);
68
+ const selected = configuration.publisher.keys.find(key => key.keyId === input.keyId);
69
+ let key;
70
+ try {
71
+ if (!selected || typeof input.privateKey !== 'string' || input.privateKey.length > 8192)
72
+ throw Error();
73
+ key = createPrivateKey(input.privateKey);
74
+ if (key.asymmetricKeyType !== 'ed25519' || createPublicKey(key).export({ type: 'spki', format: 'pem' }).toString() !== createPublicKey(selected.publicKey).export({ type: 'spki', format: 'pem' }).toString())
75
+ throw Error();
76
+ }
77
+ catch {
78
+ throw fail('SIGNATURE_INVALID');
79
+ }
80
+ await approved({ sdk, configuration, manifest, publisher, metadataTransport: input.metadataTransport, signal: input.signal });
81
+ input.signal?.throwIfAborted();
82
+ const activation = { payload, manifest, signature: { keyId: input.keyId, algorithm: 'Ed25519', value: sign(null, signedBytes(payload, sdk), key).toString('base64url') } };
83
+ return snapshot(activation);
84
+ }
85
+ /** Authenticate original intent/content/trust, then re-read current Core trust
86
+ * and admission. An earlier signature never substitutes for current approval. */
87
+ async function verifyPublishingActivation(input) {
88
+ input.signal?.throwIfAborted();
89
+ const { configuration, intent } = context(input), activation = snapshot(input.activation);
90
+ if (!protocolRecord(activation, ['payload', 'manifest', 'signature']) || !protocolRecord(activation.payload, payloadKeys) || activation.payload.schemaVersion !== 1 || !protocolRecord(activation.signature, signatureKeys) || !publishingIdentifier(activation.signature.keyId) || activation.signature.algorithm !== 'Ed25519' || typeof activation.signature.value !== 'string' || !/^[A-Za-z0-9_-]{86}$/.test(activation.signature.value))
91
+ throw fail('INVALID');
92
+ const signatureFields = activation.signature, manifestValue = activation.manifest;
93
+ const digest = manifestValue && typeof manifestValue === 'object' && 'releaseDigest' in manifestValue ? manifestValue.releaseDigest : undefined;
94
+ const sdk = await domain(), expected = payloadFor(configuration, intent, digest, activation.payload.acceptanceReceiptSha256);
95
+ if (sdk.canonicalMetadata(expected) !== sdk.canonicalMetadata(activation.payload))
96
+ throw fail('BINDING_INVALID');
97
+ const key = configuration.publisher.keys.find(key => key.keyId === signatureFields.keyId);
98
+ try {
99
+ const signature = Buffer.from(activation.signature.value, 'base64url'), publicKey = key && createPublicKey(key.publicKey);
100
+ if (!publicKey || publicKey.asymmetricKeyType !== 'ed25519' || signature.toString('base64url') !== activation.signature.value || !verify(null, signedBytes(activation.payload, sdk), publicKey, signature))
101
+ throw Error();
102
+ }
103
+ catch {
104
+ throw fail('SIGNATURE_INVALID');
105
+ }
106
+ const { manifest, publisher } = manifestInput(activation.manifest, sdk, configuration, intent), accepted = await approved({ sdk, configuration, manifest, publisher, metadataTransport: input.metadataTransport, signal: input.signal });
107
+ input.signal?.throwIfAborted();
108
+ return { manifest: accepted.manifest, acceptanceReceiptSha256: expected.acceptanceReceiptSha256 };
109
+ }
110
+ return { createPublishingActivation, verifyPublishingActivation };
111
+ }
@@ -0,0 +1,10 @@
1
+ import type { JsonValue } from '@xlinklight/contracts';
2
+ import type { ArtifactOperationRecord } from '@openge/forge-artifact-publish';
3
+ export declare const objectRecord: (value: unknown) => value is Record<string, unknown>;
4
+ export declare function errorCode(value: unknown): string | undefined;
5
+ export declare function jsonSnapshot(value: unknown): JsonValue;
6
+ export declare function jsonValue(value: unknown): value is JsonValue;
7
+ export declare function operationRecord(record: {
8
+ revision: number;
9
+ payload: unknown;
10
+ } | undefined, invalid: () => Error): ArtifactOperationRecord | undefined;
@@ -0,0 +1,26 @@
1
+ export const objectRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
2
+ export function errorCode(value) {
3
+ if (value && typeof value === 'object' && 'code' in value && typeof value.code === 'string')
4
+ return value.code;
5
+ return undefined;
6
+ }
7
+ export function jsonSnapshot(value) {
8
+ return JSON.parse(JSON.stringify(value));
9
+ }
10
+ export function jsonValue(value) {
11
+ if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
12
+ return true;
13
+ if (Array.isArray(value))
14
+ return value.every(jsonValue);
15
+ return objectRecord(value) && (Object.getPrototypeOf(value) === null || Object.getPrototypeOf(value) === Object.prototype) && Object.values(value).every(jsonValue);
16
+ }
17
+ export function operationRecord(record, invalid) {
18
+ if (!record)
19
+ return undefined;
20
+ const value = record.payload;
21
+ if (!value || typeof value !== 'object' || !('revision' in value) || value.revision !== record.revision)
22
+ throw invalid();
23
+ // This journal persists Foundation's opaque record. Foundation verifies its
24
+ // binding, fingerprint, state and ownership on every operation or observation.
25
+ return value;
26
+ }
@@ -0,0 +1,4 @@
1
+ import type { PublishingConfiguration } from '../protocol.js';
2
+ export declare function newerVersion(candidate: string, original: string): boolean;
3
+ /** Stable across authorized workstations and independent of the credential or policy revision. */
4
+ export declare function publishingVersionRequestId(configuration: Pick<PublishingConfiguration, 'serviceUrl' | 'projectId'>, packageName: string, version: string): string;
@@ -0,0 +1,15 @@
1
+ import { createHash } from 'node:crypto';
2
+ export function newerVersion(candidate, original) {
3
+ const parts = candidate.split('.').map(Number), previous = original.split('.').map(Number);
4
+ const index = parts.findIndex((part, n) => part !== previous[n]);
5
+ return index >= 0 && parts[index] > previous[index];
6
+ }
7
+ /** Stable across authorized workstations and independent of the credential or policy revision. */
8
+ export function publishingVersionRequestId(configuration, packageName, version) {
9
+ const identity = ['link-light/project-version/v1', configuration.serviceUrl, configuration.projectId, packageName, version];
10
+ const bytes = createHash('sha256').update(JSON.stringify(identity)).digest().subarray(0, 16);
11
+ bytes[6] = (bytes[6] & 15) | 128;
12
+ bytes[8] = (bytes[8] & 63) | 128;
13
+ const hex = bytes.toString('hex');
14
+ return [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20)].join('-');
15
+ }
@@ -0,0 +1,12 @@
1
+ import type { SolutionReleaseManifest } from '@xlinklight/contracts';
2
+ import type { PublishingMetadataTransport } from '../protocol.js';
3
+ import type { CreateActivationInput, VerifyActivationInput, PublishingActivation } from '../shared/activation-types.js';
4
+ export type { PublishingActivation } from '../shared/activation-types.js';
5
+ type WorkerAdmission = {
6
+ metadataTransport: PublishingMetadataTransport;
7
+ };
8
+ export declare const createPublishingActivation: (input: CreateActivationInput & WorkerAdmission) => Promise<PublishingActivation>;
9
+ export declare const verifyPublishingActivation: (input: VerifyActivationInput & WorkerAdmission) => Promise<{
10
+ manifest: Readonly<SolutionReleaseManifest>;
11
+ acceptanceReceiptSha256: string;
12
+ }>;
@@ -0,0 +1,11 @@
1
+ import { publicPublisherMetadata, verifySolutionRelease, releasePayload, canonicalMetadata, metadataDigest, resolveApprovedIndependentRelease } from '@xlinklight/platform/worker';
2
+ import { createPublishingActivationFunctions } from '../shared/activation.js';
3
+ const helpers = createPublishingActivationFunctions(async () => ({ publicPublisherMetadata, verifySolutionRelease, releasePayload, canonicalMetadata, metadataDigest,
4
+ resolveApprovedIndependentRelease(input) {
5
+ if (!input.transport)
6
+ throw Error('PUBLISHING_ACTIVATION_ADMISSION_REQUIRED');
7
+ return resolveApprovedIndependentRelease({ ...input, transport: input.transport });
8
+ },
9
+ }));
10
+ export const createPublishingActivation = helpers.createPublishingActivation;
11
+ export const verifyPublishingActivation = helpers.verifyPublishingActivation;
@@ -0,0 +1,9 @@
1
+ import type { JsonValue } from '@xlinklight/contracts';
2
+ import type { PublishingClosedRequestReplacement, PublishingDurableStorage } from './journal.js';
3
+ type Sql = PublishingDurableStorage['sql'];
4
+ /** Called inside the same SQLite transaction as the new project revision. */
5
+ export declare function reclaimClosedRecords(sql: Sql, projectId: string, previous: JsonValue, next: JsonValue, retire: PublishingClosedRequestReplacement, now: number, maximumRecords: number): string[];
6
+ /** Keep legacy or opaque bytes with unknown ownership. For owned package bytes,
7
+ * retain every manifest or chunk still required by any project's full request. */
8
+ export declare function reclaimUnreferencedPackageBlobs(sql: Sql, digests: readonly string[]): void;
9
+ export {};
@@ -0,0 +1,96 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { objectRecord } from '../shared/records.js';
4
+ import { parsePublishingIntent, publishingIntentBytes, publishingDigest, publishingRequestId, publishingError } from '../protocol.js';
5
+ import { newerVersion, publishingVersionRequestId } from '../shared/release-version.js';
6
+ import { closedRelease, releaseReceipts } from './release-retention.js';
7
+ const fail = () => publishingError('DURABLE_RETIREMENT_CONFLICT');
8
+ function requests(value, projectId) {
9
+ if (!objectRecord(value) || !objectRecord(value.policy) || !objectRecord(value.policy.configuration) ||
10
+ value.policy.configuration.projectId !== projectId || !objectRecord(value.policy.configuration.publisher) || !Array.isArray(value.requests))
11
+ throw fail();
12
+ for (const row of value.requests) {
13
+ if (!objectRecord(row) || !Array.isArray(row.files) || typeof row.state !== 'string' || typeof row.sideEffects !== 'string')
14
+ throw fail();
15
+ const intent = parsePublishingIntent(row.intent);
16
+ if (intent.projectId !== projectId || intent.package.solutionId !== value.policy.solutionId || intent.package.packageName !== value.policy.packageName ||
17
+ intent.package.publisherId !== value.policy.configuration.publisher.publisherId ||
18
+ createHash('sha256').update(publishingIntentBytes(intent)).digest('hex') !== row.intentSha256)
19
+ throw fail();
20
+ for (const file of row.files) {
21
+ if (!objectRecord(file) || !Array.isArray(file.chunks) || file.chunks.some(chunk => !objectRecord(chunk) || !publishingDigest(chunk.sha256)))
22
+ throw fail();
23
+ }
24
+ }
25
+ return value.requests;
26
+ }
27
+ /** Called inside the same SQLite transaction as the new project revision. */
28
+ export function reclaimClosedRecords(sql, projectId, previous, next, retire, now, maximumRecords) {
29
+ const old = requests(previous, projectId), proposed = requests(next, projectId), created = proposed.at(-1);
30
+ if (!created || created.state !== 'uploading' || created.sideEffects !== 'none' || created.receiptOnly ||
31
+ !old.every(closedRelease) || !isDeepStrictEqual(proposed.slice(0, -1), releaseReceipts(old)) ||
32
+ old.some(row => !newerVersion(created.intent.package.version, row.intent.package.version)))
33
+ throw fail();
34
+ if (!objectRecord(previous) || !objectRecord(previous.policy) || !objectRecord(previous.policy.configuration))
35
+ throw fail();
36
+ const url = previous.policy.configuration.serviceUrl;
37
+ if (typeof url !== 'string' || created.intent.requestId !== publishingVersionRequestId({ serviceUrl: url, projectId }, created.intent.package.packageName, created.intent.package.version))
38
+ throw fail();
39
+ const full = old.filter(item => !item.receiptOnly), ids = full.map(item => item.intent.requestId);
40
+ if (!isDeepStrictEqual(retire.requestIds, ids) || new Set(ids).size !== ids.length || !ids.every(publishingRequestId) ||
41
+ !Array.isArray(retire.auxiliaryRecords) || retire.auxiliaryRecords.length > maximumRecords)
42
+ throw fail();
43
+ if (sql.exec('SELECT project FROM publishing_queue WHERE project=? UNION ALL SELECT project FROM publishing_leases WHERE project=? AND until_ms>? LIMIT 1', projectId, projectId, now).toArray().length)
44
+ throw fail();
45
+ const candidates = new Set();
46
+ for (const item of full) {
47
+ candidates.add(item.intent.package.content.manifestSha256);
48
+ for (const file of item.files)
49
+ for (const part of file.chunks)
50
+ candidates.add(part.sha256);
51
+ }
52
+ if (!ids.length && retire.auxiliaryRecords.length)
53
+ throw fail();
54
+ if (ids.length) {
55
+ if (sql.exec(`SELECT 1 FROM publishing_records AS record,json_each(record.payload,'$.requests') AS item
56
+ WHERE record.key GLOB 'project:*' AND record.key<>? AND json_extract(item.value,'$.intent.requestId') IN (SELECT value FROM json_each(?)) LIMIT 1`, 'project:' + projectId, JSON.stringify(ids)).toArray().length)
57
+ throw fail();
58
+ }
59
+ const auxiliaryKeys = new Set();
60
+ for (const entry of retire.auxiliaryRecords) {
61
+ if (!entry || typeof entry.key !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9:._/-]{0,511}$/.test(entry.key) ||
62
+ /^(project|operation|retirement):/.test(entry.key) || !Number.isSafeInteger(entry.revision) || entry.revision < 1 || auxiliaryKeys.has(entry.key))
63
+ throw fail();
64
+ auxiliaryKeys.add(entry.key);
65
+ const removed = sql.exec('DELETE FROM publishing_records WHERE key=? AND revision=? RETURNING key', entry.key, entry.revision).toArray();
66
+ if (removed.length !== 1)
67
+ throw fail();
68
+ }
69
+ for (const item of full) {
70
+ const id = item.intent.requestId;
71
+ // A lost historical operation never becomes a confirmed outcome through cleanup.
72
+ sql.exec(`DELETE FROM publishing_records WHERE key GLOB ? AND key='operation:'||json_extract(payload,'$.binding.requestId')
73
+ AND json_extract(payload,'$.binding.content.manifestSha256')=?
74
+ AND (json_extract(payload,'$.observation') IN ('succeeded','failed') OR json_extract(payload,'$.writeState')='rejected')`, 'operation:' + id + '.*', item.intent.package.content.manifestSha256);
75
+ }
76
+ return [...candidates];
77
+ }
78
+ /** Keep legacy or opaque bytes with unknown ownership. For owned package bytes,
79
+ * retain every manifest or chunk still required by any project's full request. */
80
+ export function reclaimUnreferencedPackageBlobs(sql, digests) {
81
+ if (!digests.length)
82
+ return;
83
+ const selected = JSON.stringify(digests);
84
+ sql.exec(`WITH full_requests AS MATERIALIZED (
85
+ SELECT item.value AS body FROM publishing_records AS p,json_each(p.payload,'$.requests') AS item
86
+ WHERE p.key GLOB 'project:*' AND json_extract(item.value,'$.receiptOnly') IS NOT 1
87
+ ), retained AS MATERIALIZED (
88
+ SELECT json_extract(body,'$.intent.package.content.manifestSha256') AS digest FROM full_requests
89
+ UNION SELECT json_extract(chunk.value,'$.sha256') FROM full_requests,
90
+ json_each(body,'$.files') AS file,json_each(file.value,'$.chunks') AS chunk
91
+ )
92
+ DELETE FROM publishing_blobs WHERE sha256 IN (
93
+ SELECT owner.sha256 FROM publishing_managed_blobs AS owner JOIN json_each(?) AS candidate ON candidate.value=owner.sha256
94
+ WHERE NOT EXISTS (SELECT 1 FROM retained WHERE retained.digest=owner.sha256)
95
+ )`, selected);
96
+ }
@@ -0,0 +1,12 @@
1
+ export { openPreparedPublishingPackage, publishingChunkBytes, publishingReadFileBytes } from './package.js';
2
+ export type { PublishingContentReader, PreparedPublishingPackage, PublishingPackageRecord } from './package.js';
3
+ export { createPublishingService, configurePublishingProject, createPublishingWorker } from './service.js';
4
+ export type { PublishingProjectPolicy, PublishingServiceLimits, PublishingService, PublishingClosedReleaseRetention, PublishingProjectLease, PublishingDeploymentStage, PublishingWorkerOptions, PublishingWorkerResult, } from './service.js';
5
+ export { openPublishingDurableJournal } from './journal.js';
6
+ export type { PublishingDurableStorage, PublishingDurableLimits, PublishingDispatch, PublishingQueueLease, PublishingMutationAuthority, PublishingRecordIdentity, PublishingClosedRequestReplacement, PublishingDurableJournal, } from './journal.js';
7
+ export { createPublishingDurableRuntime } from './runtime.js';
8
+ export type { PublishingDurableContext } from './runtime.js';
9
+ export { preparePublishingRelease } from './release.js';
10
+ export { createPublishingActivation, verifyPublishingActivation } from './activation.js';
11
+ export type { PublishingActivation } from './activation.js';
12
+ export { publishingVersionRequestId } from '../shared/release-version.js';
@@ -0,0 +1,7 @@
1
+ export { openPreparedPublishingPackage, publishingChunkBytes, publishingReadFileBytes } from './package.js';
2
+ export { createPublishingService, configurePublishingProject, createPublishingWorker } from './service.js';
3
+ export { openPublishingDurableJournal } from './journal.js';
4
+ export { createPublishingDurableRuntime } from './runtime.js';
5
+ export { preparePublishingRelease } from './release.js';
6
+ export { createPublishingActivation, verifyPublishingActivation } from './activation.js';
7
+ export { publishingVersionRequestId } from '../shared/release-version.js';