@xlinklight/publishing 3.3.1 → 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 (76) hide show
  1. package/README.md +22 -2
  2. package/dist/src/acceptance-delivery-binding.d.ts +20 -0
  3. package/dist/src/acceptance.d.ts +49 -0
  4. package/dist/src/client.d.ts +71 -0
  5. package/dist/src/index.d.ts +6 -0
  6. package/dist/src/node/acceptance-delivery.d.ts +34 -0
  7. package/dist/src/node/activation.d.ts +5 -0
  8. package/dist/src/node/authorization.d.ts +31 -0
  9. package/dist/src/node/cli.d.ts +2 -0
  10. package/dist/src/node/cli.js +4 -2
  11. package/dist/src/node/index.d.ts +20 -0
  12. package/dist/src/node/index.js +2 -0
  13. package/dist/src/node/journal-directory.d.ts +2 -0
  14. package/dist/src/node/journal-directory.js +121 -0
  15. package/dist/src/node/journal.d.ts +49 -0
  16. package/dist/src/node/journal.js +6 -8
  17. package/dist/src/node/local-json-file.d.ts +3 -0
  18. package/dist/src/node/local-json-file.js +49 -0
  19. package/dist/src/node/publishing-command.d.ts +46 -0
  20. package/dist/src/node/publishing-command.js +64 -16
  21. package/dist/src/node/session.d.ts +95 -0
  22. package/dist/src/node/solution-package.d.ts +55 -0
  23. package/dist/src/node/source-error.d.ts +10 -0
  24. package/dist/src/node/source-producer.d.ts +5 -0
  25. package/dist/src/node/terminal-network.d.ts +23 -0
  26. package/dist/src/node/terminal-network.js +122 -0
  27. package/dist/src/node/workflow.d.ts +74 -0
  28. package/dist/src/node/workflow.js +46 -34
  29. package/dist/src/package.d.ts +38 -0
  30. package/dist/src/protocol.d.ts +83 -0
  31. package/dist/src/protocol.js +1 -1
  32. package/dist/src/shared/activation-types.d.ts +37 -0
  33. package/dist/src/shared/activation-types.js +1 -0
  34. package/dist/src/shared/activation.d.ts +17 -0
  35. package/dist/src/shared/records.d.ts +10 -0
  36. package/dist/src/shared/release-version.d.ts +4 -0
  37. package/dist/src/shared/release-version.js +15 -0
  38. package/dist/src/worker/activation.d.ts +12 -0
  39. package/dist/src/worker/activation.js +2 -1
  40. package/dist/src/worker/durable-retention.d.ts +9 -0
  41. package/dist/src/worker/durable-retention.js +96 -0
  42. package/dist/src/worker/index.d.ts +12 -0
  43. package/dist/src/worker/index.js +1 -0
  44. package/dist/src/worker/journal.d.ts +129 -0
  45. package/dist/src/worker/journal.js +33 -6
  46. package/dist/src/worker/package.d.ts +60 -0
  47. package/dist/src/worker/release-retention.d.ts +34 -0
  48. package/dist/src/worker/release-retention.js +27 -0
  49. package/dist/src/worker/release.d.ts +22 -0
  50. package/dist/src/worker/runtime.d.ts +47 -0
  51. package/dist/src/worker/service.d.ts +128 -0
  52. package/dist/src/worker/service.js +38 -12
  53. package/package.json +13 -7
  54. package/types/acceptance.d.ts +0 -24
  55. package/types/client.d.ts +0 -16
  56. package/types/index.d.ts +0 -6
  57. package/types/node/acceptance-delivery.d.ts +0 -11
  58. package/types/node/activation.d.ts +0 -8
  59. package/types/node/authorization.d.ts +0 -8
  60. package/types/node/index.d.ts +0 -17
  61. package/types/node/journal.d.ts +0 -13
  62. package/types/node/publishing-command.d.ts +0 -20
  63. package/types/node/session.d.ts +0 -25
  64. package/types/node/solution-package.d.ts +0 -15
  65. package/types/node/source-error.d.ts +0 -5
  66. package/types/node/workflow.d.ts +0 -37
  67. package/types/package.d.ts +0 -11
  68. package/types/protocol.d.ts +0 -27
  69. package/types/shared/activation.d.ts +0 -5
  70. package/types/worker/activation.d.ts +0 -7
  71. package/types/worker/index.d.ts +0 -6
  72. package/types/worker/journal.d.ts +0 -21
  73. package/types/worker/package.d.ts +0 -16
  74. package/types/worker/release.d.ts +0 -7
  75. package/types/worker/runtime.d.ts +0 -4
  76. package/types/worker/service.d.ts +0 -41
package/README.md CHANGED
@@ -2,12 +2,28 @@
2
2
 
3
3
  ## Publishing from an owner checkout
4
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"`.
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 the input and backups with OS access controls. The owner's public `package.json` declares `linkLight.acceptanceDelivery` as `"required"`.
6
+
7
+ New client journals restrict access to the owner on Linux, and to the current user, SYSTEM and local Administrators on Windows. Credential installation checks the existing journal directory and its database and marker before storing a bearer or delivery key. A shared target returns `PUBLISHING_JOURNAL_PRIVATE_REQUIRED` and keeps its original permissions. Use the same dedicated journal for later release commands.
8
+
9
+ For split enrollment, the administrator pipes `{configuration,credential}` into `pnpm release:credentials --delivery-credential-file <absolute-local-path>` on the owner workstation. The script runs `link-light-release credentials --stdin`. The named owner secret file holds `{origin,keyId,privateKey}` as UTF-8 JSON, up to 16 KiB. The CLI reads a regular file with a single link from its canonical local path and verifies the project before installation. Supply the delivery credential once, either in stdin or in the owner file. Subsequent verification of the same installed project preserves its delivery credential when stdin contains only the project authorization.
6
10
 
7
11
  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
12
 
9
13
  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
14
 
15
+ ### Workstation proxy
16
+
17
+ On Windows, `pnpm release:credentials`, `pnpm release`, `pnpm release:status` and `pnpm release:verify` automatically use the system proxy and bypass rules for the registered Publisher, Core and acceptance origins. This works on the first enrollment and with existing authorization. A selected loopback HTTP proxy uses the optional `@openge/forge-http-transport@0.1.0` development peer included in the independent solution template. Other platforms use their ordinary Node transport by default.
18
+
19
+ To select a loopback HTTP proxy for one CLI process on any platform, set `LINK_LIGHT_PUBLISHING_PROXY` to an origin such as `http://127.0.0.1:8080` or `http://[::1]:8080`. The release CLI consumes this variable before loading the owner producer.
20
+
21
+ Publisher credentials travel inside TLS to the registered Publisher. Core metadata uses a separate GET after validating every DNS answer. The tunnel connects to the selected public IP and TLS verifies the original hostname. An unavailable system proxy lookup returns `PUBLISHING_NETWORK_SYSTEM_PROXY_UNAVAILABLE`. Invalid overrides return `PUBLISHING_NETWORK_CONFIG_INVALID`.
22
+
23
+ Node tools can import `discoverWindowsProxyRoutes` from `@xlinklight/publishing/node` to resolve one to sixteen canonical HTTPS origins in one Windows settings lookup. Results follow the input order. Each entry is a loopback HTTP proxy origin or `null` for a system bypass. The optional second argument is an `AbortSignal`.
24
+
25
+ Trusted clients can also call `openPublishingTerminalNetwork({serviceUrl,coreOrigin,deliveryOrigin}, {signal,proxy})` from the Node entry. The delivery origin and options are optional. Pass the returned `request` and `metadataTransport` to the client and await `close()` when finished. An `undefined` result selects the usual direct transports.
26
+
11
27
  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.
12
28
 
13
29
  ## Local preparation and client
@@ -20,12 +36,16 @@ The `link-light-release` executable provides `credentials`, `check`, `publish`,
20
36
  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
37
  3. `deployment/publishing.mjs` when the metadata field is absent.
22
38
 
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.
39
+ 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.
24
40
 
25
41
  The client never automatically repeats request creation. `publish` reuses frozen original bytes and an explicit request identity. CLI publish waits up to 300000 ms; `--no-wait` submits without waiting and `--wait-ms <1..3600000>` selects a finite wait. Programmatic `workflow.publish` defaults to one observation. Waiting uses GET only. Queued, pending or timed-out work exits 3; a closed failure exits 1; verified ACTIVE exits 0. Recovery observes the original operation without advancing its next stage. Resume may advance only after a known pending operation is observed successfully. Neither operation rebuilds, uploads or re-commits the package. Status and verification never dispatch work.
26
42
 
27
43
  ## Durable Object composition
28
44
 
45
+ A host with one active release per project can enable `replaceClosedReleases` when creating the publishing service. The Node CLI already derives a stable request ID per version. Direct clients can call `publishingVersionRequestId(configuration, packageName, version)` from the Node or Worker entry. A higher version can use the same request slot once the previous operations have closed. The service retains the signed active receipt while verifying its successor. A failed candidate leaves the previous active release available.
46
+
47
+ The SQLite journal reclaims unreferenced package chunks and settled operation records in the new request transaction. Hosts that keep private records can supply `recordsForRequest` and return exact keys and revisions after checking ownership. A conflicting revision rolls back the replacement. Blobs shared by another request and records with unresolved ownership remain available.
48
+
29
49
  Use the public Worker entry with Cloudflare `nodejs_compat`; mature crypto and async-context primitives are shared with the Node client. The server graph imports no filesystem, Node HTTP, DNS, subprocess or UI implementation. The application owns one singleton SQLite Durable Object and its trusted configuration, provider credentials and lifecycle:
30
50
 
31
51
  1. `openPublishingDurableJournal({storage: ctx.storage, identity, limits, leaseMs})` binds a durable identity and exact storage limits. `configurePublishingProject` installs a project policy and credential through the trusted composition, never an uploaded module.
@@ -0,0 +1,20 @@
1
+ import type { KeyObject } from 'node:crypto';
2
+ export interface AcceptanceArchiveIdentity {
3
+ archiveSha256: string;
4
+ artifactSha256: string;
5
+ byteLength: number;
6
+ }
7
+ export interface AcceptanceDeliveryBinding extends AcceptanceArchiveIdentity {
8
+ projectId: string;
9
+ solutionId: string;
10
+ version: string;
11
+ origin: string;
12
+ keyId: string;
13
+ manifestSha256: string;
14
+ }
15
+ export declare const maximumAcceptanceArchiveBytes: number;
16
+ export declare const deliveryBindingFields: readonly ["projectId", "solutionId", "version", "origin", "keyId", "manifestSha256", "archiveSha256", "artifactSha256", "byteLength"];
17
+ export declare function validateDeliveryOrigin(value: unknown): string;
18
+ export declare function deliveryBindingBytes(value: unknown): Buffer<ArrayBuffer>;
19
+ export declare function verifyAcceptanceDelivery(value: AcceptanceDeliveryBinding, signature: string, publicKey: string | KeyObject): void;
20
+ export declare function readDeliveryBody(message: Request | Response, limit: number): Promise<Buffer>;
@@ -0,0 +1,49 @@
1
+ export { maximumAcceptanceArchiveBytes, readDeliveryBody, verifyAcceptanceDelivery } from './acceptance-delivery-binding.js';
2
+ import type { KeyObject } from 'node:crypto';
3
+ import type { SolutionReleaseManifest } from '@xlinklight/contracts';
4
+ export type { AcceptanceDeliveryBinding } from './acceptance-delivery-binding.js';
5
+ export interface AcceptanceIdentity {
6
+ projectId: string;
7
+ requestId: string;
8
+ intentSha256: string;
9
+ policyRevision: number;
10
+ releaseDigest: string;
11
+ acceptanceArtifactSha256: string;
12
+ generation: number;
13
+ }
14
+ export interface AcceptanceJob extends AcceptanceIdentity {
15
+ schemaVersion: 1;
16
+ jobId: string;
17
+ manifest: Readonly<SolutionReleaseManifest>;
18
+ }
19
+ export interface AcceptanceReceipt extends AcceptanceIdentity {
20
+ schemaVersion: 1;
21
+ jobId: string;
22
+ status: 'PASS';
23
+ proof: {
24
+ syntheticInstancesCreated: number;
25
+ syntheticInstancesDisabled: number;
26
+ closure: {
27
+ status: 'closed';
28
+ activeRequests: 0;
29
+ };
30
+ };
31
+ }
32
+ export interface AcceptanceEnvelope<Payload> {
33
+ payload: Payload;
34
+ keyId: string;
35
+ signature: string;
36
+ }
37
+ export interface AcceptanceSigner {
38
+ keyId: string;
39
+ privateKey: string | KeyObject;
40
+ }
41
+ export interface AcceptanceVerifier {
42
+ keyId: string;
43
+ publicKey: string | KeyObject;
44
+ }
45
+ export declare function acceptanceJobId(identity: AcceptanceIdentity): string;
46
+ export declare const signAcceptanceJob: (job: AcceptanceJob, options: AcceptanceSigner) => AcceptanceEnvelope<AcceptanceJob>;
47
+ export declare const verifyAcceptanceJob: (envelope: unknown, options: AcceptanceVerifier) => AcceptanceJob;
48
+ export declare const signAcceptanceReceipt: (receipt: AcceptanceReceipt, options: AcceptanceSigner) => AcceptanceEnvelope<AcceptanceReceipt>;
49
+ export declare const verifyAcceptanceReceipt: (envelope: unknown, options: AcceptanceVerifier) => AcceptanceReceipt;
@@ -0,0 +1,71 @@
1
+ import type { PublishingConfiguration, PublishingIntent, PublishingProject, PublishingStatus } from './protocol.js';
2
+ import type { JsonValue } from '@xlinklight/contracts';
3
+ export interface PublishingClientLimits {
4
+ requestMs: number;
5
+ maximumResponseBytes: number;
6
+ maximumChunkBytes: number;
7
+ }
8
+ export interface PublishingClient {
9
+ getProject(input?: {
10
+ signal?: AbortSignal;
11
+ }): Promise<PublishingProject>;
12
+ getLatestRelease(input?: {
13
+ signal?: AbortSignal;
14
+ }): Promise<{
15
+ intent: PublishingIntent;
16
+ status: PublishingStatus;
17
+ } | undefined>;
18
+ createRequest(input: {
19
+ intent: PublishingIntent;
20
+ manifestBytes: Uint8Array;
21
+ signal?: AbortSignal;
22
+ }): Promise<PublishingStatus>;
23
+ getStatus(input: {
24
+ intent: PublishingIntent;
25
+ signal?: AbortSignal;
26
+ }): Promise<PublishingStatus>;
27
+ resumeRequest(input: {
28
+ intent: PublishingIntent;
29
+ signal?: AbortSignal;
30
+ }): Promise<PublishingStatus>;
31
+ recoverRequest(input: {
32
+ intent: PublishingIntent;
33
+ signal?: AbortSignal;
34
+ }): Promise<PublishingStatus>;
35
+ queueRequest(input: {
36
+ intent: PublishingIntent;
37
+ signal?: AbortSignal;
38
+ }): Promise<PublishingStatus>;
39
+ abandonRequest(input: {
40
+ intent: PublishingIntent;
41
+ signal?: AbortSignal;
42
+ }): Promise<PublishingStatus>;
43
+ uploadChunk(input: {
44
+ requestId: string;
45
+ file: {
46
+ sha256: string;
47
+ byteLength: number;
48
+ };
49
+ offset: number;
50
+ bytes: Uint8Array;
51
+ signal?: AbortSignal;
52
+ }): Promise<{
53
+ schemaVersion: 1;
54
+ sha256: string;
55
+ receivedBytes: number;
56
+ }>;
57
+ }
58
+ export interface PublishingClientOptions {
59
+ configuration: PublishingConfiguration;
60
+ credential: string;
61
+ allowLoopback?: boolean;
62
+ request?: typeof fetch;
63
+ limits?: PublishingClientLimits;
64
+ verifyActivation?: (input: {
65
+ activation: JsonValue;
66
+ intent: PublishingIntent;
67
+ configuration: PublishingConfiguration;
68
+ }) => Promise<void> | void;
69
+ }
70
+ /** All writes are explicit. Recovery reads the original request; there is no retry loop. */
71
+ export declare function createPublishingClient({ configuration, credential, allowLoopback, request, limits, verifyActivation }: PublishingClientOptions): PublishingClient;
@@ -0,0 +1,6 @@
1
+ export type { SolutionPackageDescriptor, SolutionPackageLimits } from './package.js';
2
+ export type { PublishingConfiguration, PublishingProject, PublishingIntent, PublishingStatus, PublishingMetadataTransport } from './protocol.js';
3
+ export type { PublishingClient, PublishingClientLimits, PublishingClientOptions } from './client.js';
4
+ export { parseSolutionPackageDescriptor, parseSolutionPackageLimits } from './package.js';
5
+ export { parsePublishingConfiguration, parsePublishingProject, parsePublishingIntent, parsePublishingStatus, publishingIntentBytes } from './protocol.js';
6
+ export { createPublishingClient } from './client.js';
@@ -0,0 +1,34 @@
1
+ import type { KeyObject } from 'node:crypto';
2
+ import type { PublishingIntent } from '../protocol.js';
3
+ export { maximumAcceptanceArchiveBytes, readDeliveryBody, verifyAcceptanceDelivery } from '../acceptance-delivery-binding.js';
4
+ import type { AcceptanceArchiveIdentity, AcceptanceDeliveryBinding } from '../acceptance-delivery-binding.js';
5
+ export type { AcceptanceArchiveIdentity, AcceptanceDeliveryBinding } from '../acceptance-delivery-binding.js';
6
+ export interface AcceptanceDeliveryCredential {
7
+ origin: string;
8
+ keyId: string;
9
+ privateKey: string;
10
+ }
11
+ export interface AcceptanceArchive {
12
+ bytes: Uint8Array;
13
+ artifactSha256: string;
14
+ }
15
+ export declare function parseAcceptanceDeliveryCredential(value: unknown): AcceptanceDeliveryCredential;
16
+ export declare function acceptanceDeliveryTarget(credential: unknown): {
17
+ origin: string;
18
+ keyId: string;
19
+ publicKeySha256: string;
20
+ };
21
+ export declare function signAcceptanceDelivery(value: AcceptanceDeliveryBinding, privateKey: string | KeyObject): string;
22
+ /** Only the dedicated owner's HTTPS origin receives this archive. A read after
23
+ * the immutable PUT also reconciles a lost response without repeating a release. */
24
+ interface DeliveryInput {
25
+ intent: PublishingIntent;
26
+ archive: AcceptanceArchiveIdentity;
27
+ credential: AcceptanceDeliveryCredential;
28
+ request?: typeof fetch;
29
+ signal?: AbortSignal;
30
+ }
31
+ export declare function observeAcceptanceDelivery(input: DeliveryInput): Promise<boolean>;
32
+ export declare function deliverAcceptanceArchive(input: DeliveryInput & {
33
+ bytes: Uint8Array;
34
+ }): Promise<void>;
@@ -0,0 +1,5 @@
1
+ export type { PublishingActivation } from '../shared/activation-types.js';
2
+ export declare const createPublishingActivation: (input: import("../shared/activation-types.js").CreateActivationInput) => Promise<import("../shared/activation-types.js").PublishingActivation>, verifyPublishingActivation: (input: import("../shared/activation-types.js").VerifyActivationInput) => Promise<{
3
+ manifest: Readonly<import("@xlinklight/contracts").SolutionReleaseManifest>;
4
+ acceptanceReceiptSha256: string;
5
+ }>;
@@ -0,0 +1,31 @@
1
+ import type { PublishingJournal } from './journal.js';
2
+ import type { AcceptanceDeliveryCredential } from './acceptance-delivery.js';
3
+ import type { PublishingConfiguration } from '../protocol.js';
4
+ import type { PublishingClientLimits } from '../client.js';
5
+ export interface PublishingAuthorization {
6
+ configuration: PublishingConfiguration;
7
+ credential: string;
8
+ acceptanceDelivery?: AcceptanceDeliveryCredential;
9
+ }
10
+ /** The caller supplies private persistent storage, including access controls and
11
+ * backup policy. No provider credential or process/global setting is stored. */
12
+ export declare function loadPublishingAuthorization({ journal, allowLoopback, signal }: {
13
+ journal: Pick<PublishingJournal, 'load' | 'compareAndSet'>;
14
+ allowLoopback?: boolean;
15
+ signal?: AbortSignal;
16
+ }): Promise<PublishingAuthorization | undefined>;
17
+ /** Validate installed trust and current project access before atomic install.
18
+ * A changed service/publisher trust never adopts an existing recovery journal. */
19
+ export declare function installPublishingAuthorization({ journal, configuration: input, credential, acceptanceDelivery, replaceCredential, allowLoopback, request, clientLimits, signal }: PublishingAuthorization & {
20
+ journal: Pick<PublishingJournal, 'load' | 'compareAndSet'>;
21
+ replaceCredential?: boolean;
22
+ allowLoopback?: boolean;
23
+ request?: typeof fetch;
24
+ clientLimits?: PublishingClientLimits;
25
+ signal?: AbortSignal;
26
+ }): Promise<{
27
+ status: 'CONFIGURED' | 'VERIFIED' | 'REPLACED';
28
+ projectId: string;
29
+ credentialSha256: string;
30
+ policyRevision: number;
31
+ }>;
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -1,13 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import { existsSync, realpathSync } from 'node:fs';
3
3
  import { fileURLToPath } from 'node:url';
4
- import { runPublishingCommand } from './publishing-command.js';
4
+ import { runPublishingTerminalCommand } from './publishing-command.js';
5
5
  async function main() {
6
+ const proxy = process.env.LINK_LIGHT_PUBLISHING_PROXY;
7
+ delete process.env.LINK_LIGHT_PUBLISHING_PROXY;
6
8
  const controller = new AbortController(), stop = () => controller.abort();
7
9
  process.once('SIGINT', stop);
8
10
  process.once('SIGTERM', stop);
9
11
  try {
10
- const result = await runPublishingCommand(process.argv.slice(2), { signal: controller.signal });
12
+ const result = await runPublishingTerminalCommand(process.argv.slice(2), controller.signal, proxy);
11
13
  process.stdout.write(JSON.stringify(result.output) + '\n');
12
14
  process.exitCode = result.exitCode;
13
15
  }
@@ -0,0 +1,20 @@
1
+ export type { SolutionPackageLimits, SolutionPackageFilePlan, PreparedSolutionPackage } from './solution-package.js';
2
+ export type { PublishingMetadataTransport } from '../protocol.js';
3
+ export type { PublishingJournal, PublishingJournalRecord, PublishingJournalLimits } from './journal.js';
4
+ export type { PublishingSession, PublishingSessionResult } from './session.js';
5
+ export type { PublishingAuthorization } from './authorization.js';
6
+ export type { PublishingActivation } from './activation.js';
7
+ export type { PublishingSourceProducer, PublishingWorkflowOptions, PublishingSourceOptions, PublishingPublishOptions, PublishingWorkflowResult, PublishingWorkflow } from './workflow.js';
8
+ export type { PublishingCommandOptions, PublishingCommandResult } from './publishing-command.js';
9
+ export type { AcceptanceArchive, AcceptanceArchiveIdentity, AcceptanceDeliveryBinding, AcceptanceDeliveryCredential } from './acceptance-delivery.js';
10
+ export { prepareSolutionPackage, prepareSolutionPackageBytes, verifySolutionPackage, verifySolutionPackageBytes } from './solution-package.js';
11
+ export { openPublishingJournal } from './journal.js';
12
+ export { createPublishingSession } from './session.js';
13
+ export { installPublishingAuthorization, loadPublishingAuthorization } from './authorization.js';
14
+ export { createPublishingActivation, verifyPublishingActivation } from './activation.js';
15
+ export { PublishingSourceError } from './source-error.js';
16
+ export { createPublishingWorkflow } from './workflow.js';
17
+ export { publishingVersionRequestId } from '../shared/release-version.js';
18
+ export { discoverWindowsProxyRoutes, openPublishingTerminalNetwork } from './terminal-network.js';
19
+ export { deliverAcceptanceArchive, signAcceptanceDelivery, maximumAcceptanceArchiveBytes, readDeliveryBody, verifyAcceptanceDelivery } from './acceptance-delivery.js';
20
+ export { runPublishingCommand } from './publishing-command.js';
@@ -5,5 +5,7 @@ export { installPublishingAuthorization, loadPublishingAuthorization } from './a
5
5
  export { createPublishingActivation, verifyPublishingActivation } from './activation.js';
6
6
  export { PublishingSourceError } from './source-error.js';
7
7
  export { createPublishingWorkflow } from './workflow.js';
8
+ export { publishingVersionRequestId } from '../shared/release-version.js';
9
+ export { discoverWindowsProxyRoutes, openPublishingTerminalNetwork } from './terminal-network.js';
8
10
  export { deliverAcceptanceArchive, signAcceptanceDelivery, maximumAcceptanceArchiveBytes, readDeliveryBody, verifyAcceptanceDelivery } from './acceptance-delivery.js';
9
11
  export { runPublishingCommand } from './publishing-command.js';
@@ -0,0 +1,2 @@
1
+ import type { DurableArtifactFilesystem } from '@openge/forge-generated-artifacts/node';
2
+ export declare function ensurePublishingJournalDirectory(root: string, relative: string, filesystem: DurableArtifactFilesystem, credential: boolean, signal?: AbortSignal): Promise<string>;
@@ -0,0 +1,121 @@
1
+ import { execFile } from 'node:child_process';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { promisify } from 'node:util';
5
+ import { publishingError } from '../protocol.js';
6
+ const execute = promisify(execFile);
7
+ const privateRequired = () => publishingError('JOURNAL_PRIVATE_REQUIRED');
8
+ const boundary = () => publishingError('JOURNAL_BOUNDARY');
9
+ const journalFiles = ['owner.json', 'journal.sqlite', 'journal.sqlite-journal'];
10
+ const missing = (err) => err instanceof Error && 'code' in err && err.code === 'ENOENT';
11
+ // CreateDirectory's security descriptor applies when Windows creates the object.
12
+ // An existing directory keeps its ACL and must already grant private access.
13
+ const windowsSecurity = `$ErrorActionPreference='Stop'
14
+ try {
15
+ $target=$env:PUBLISHING_JOURNAL_DIRECTORY
16
+ $sidType=[Security.Principal.SecurityIdentifier]
17
+ $user=[Security.Principal.WindowsIdentity]::GetCurrent().User
18
+ $allowed=@($user.Value,'S-1-5-18','S-1-5-32-544')
19
+ $dir=[IO.DirectoryInfo]::new($target)
20
+ if(!$dir.Exists){
21
+ if($env:PUBLISHING_JOURNAL_CREATE -ne '1' -or !$dir.Parent.Exists){exit 1}
22
+ $acl=[Security.AccessControl.DirectorySecurity]::new()
23
+ $acl.SetAccessRuleProtection($true,$false)
24
+ $acl.SetOwner($user)
25
+ foreach($id in $allowed){
26
+ $account=[Security.Principal.SecurityIdentifier]::new($id)
27
+ $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($account,'FullControl','ContainerInherit,ObjectInherit','None','Allow'))
28
+ }
29
+ $dir=[IO.Directory]::CreateDirectory($target,$acl)
30
+ }
31
+ function Assert-Private($item,$directory){
32
+ if(($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0){exit 1}
33
+ $security=$item.GetAccessControl()
34
+ $raw=[Security.AccessControl.RawSecurityDescriptor]::new($security.GetSecurityDescriptorBinaryForm(),0)
35
+ if($null -eq $raw.DiscretionaryAcl -or $allowed -notcontains $raw.Owner.Value){exit 1}
36
+ $inherits=$false
37
+ foreach($ace in $raw.DiscretionaryAcl){
38
+ if($ace.AceType -eq 'AccessDenied'){continue}
39
+ if($ace.AceType -ne 'AccessAllowed' -or $allowed -notcontains $ace.SecurityIdentifier.Value){exit 1}
40
+ if(([int]$ace.AceFlags -band [int][Security.AccessControl.AceFlags]::ObjectInherit) -ne 0){$inherits=$true}
41
+ }
42
+ if($directory -and !$inherits){exit 1}
43
+ }
44
+ Assert-Private $dir $true
45
+ foreach($leaf in @('owner.json','journal.sqlite','journal.sqlite-journal')){
46
+ $file=[IO.FileInfo]::new([IO.Path]::Combine($target,$leaf))
47
+ if($file.Exists){Assert-Private $file $false}
48
+ }
49
+ }catch{exit 1}`;
50
+ async function windowsDirectory(directory, create, signal) {
51
+ const system = process.env.SystemRoot;
52
+ if (!system || !path.isAbsolute(system))
53
+ throw privateRequired();
54
+ try {
55
+ await execute(path.join(system, 'System32/WindowsPowerShell/v1.0/powershell.exe'), ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(windowsSecurity, 'utf16le').toString('base64')], { env: { SystemRoot: system, WINDIR: system, PUBLISHING_JOURNAL_DIRECTORY: directory, PUBLISHING_JOURNAL_CREATE: create ? '1' : '0' },
56
+ windowsHide: true, timeout: 10000, maxBuffer: 4096, signal });
57
+ }
58
+ catch {
59
+ throw privateRequired();
60
+ }
61
+ }
62
+ async function directoryIdentity(directory) {
63
+ const info = await fs.lstat(directory, { bigint: true });
64
+ if (!info.isDirectory() || info.isSymbolicLink() || await fs.realpath(directory) !== directory)
65
+ throw boundary();
66
+ return info;
67
+ }
68
+ async function syncDirectory(filesystem, root, relative) {
69
+ try {
70
+ await filesystem.ensureDirectory(root, relative);
71
+ }
72
+ catch {
73
+ throw publishingError('JOURNAL_PERSISTENCE_UNKNOWN');
74
+ }
75
+ }
76
+ async function privatePosixFiles(directory) {
77
+ const uid = process.geteuid?.();
78
+ if (uid === undefined)
79
+ throw privateRequired();
80
+ const parent = await directoryIdentity(directory);
81
+ if (parent.uid !== BigInt(uid) || (parent.mode & 63n) !== 0n)
82
+ throw privateRequired();
83
+ for (const name of journalFiles) {
84
+ const file = path.join(directory, name), info = await fs.lstat(file).catch((err) => { if (missing(err))
85
+ return; throw err; });
86
+ if (info && (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.uid !== uid || (info.mode & 0o077) !== 0))
87
+ throw privateRequired();
88
+ }
89
+ }
90
+ export async function ensurePublishingJournalDirectory(root, relative, filesystem, credential, signal) {
91
+ const directory = path.join(root, ...relative.split('/')), parent = path.dirname(directory);
92
+ if (process.platform !== 'win32') {
93
+ await syncDirectory(filesystem, root, relative);
94
+ if (credential)
95
+ await privatePosixFiles(directory);
96
+ return directory;
97
+ }
98
+ const before = await directoryIdentity(directory).catch((err) => { if (missing(err))
99
+ return; throw err; });
100
+ if (before && !credential) {
101
+ await syncDirectory(filesystem, root, relative);
102
+ const current = await directoryIdentity(directory);
103
+ if (current.dev !== before.dev || current.ino !== before.ino)
104
+ throw boundary();
105
+ return directory;
106
+ }
107
+ // Foundation verifies the ancestry and synchronizes new parents. Only the journal leaf receives the private descriptor.
108
+ const relativeParent = path.posix.dirname(relative);
109
+ await syncDirectory(filesystem, root, relativeParent === '.' ? '' : relativeParent);
110
+ const beforeParent = await directoryIdentity(parent);
111
+ await windowsDirectory(directory, !before, signal);
112
+ const expected = await directoryIdentity(directory);
113
+ if (before && (before.dev !== expected.dev || before.ino !== expected.ino))
114
+ throw boundary();
115
+ await syncDirectory(filesystem, root, relative);
116
+ const identity = await directoryIdentity(directory), afterParent = await directoryIdentity(parent);
117
+ if (beforeParent.dev !== afterParent.dev || beforeParent.ino !== afterParent.ino ||
118
+ expected.dev !== identity.dev || expected.ino !== identity.ino)
119
+ throw boundary();
120
+ return directory;
121
+ }
@@ -0,0 +1,49 @@
1
+ import type { JsonValue } from '@xlinklight/contracts';
2
+ import type { ArtifactOperationJournal } from '@openge/forge-artifact-publish';
3
+ import type { DurableArtifactFilesystem } from '@openge/forge-generated-artifacts/node';
4
+ export interface PublishingJournalLimits {
5
+ maximumBytes: number;
6
+ maximumRecords: number;
7
+ maximumRecordBytes: number;
8
+ maximumBlobs: number;
9
+ maximumBlobBytes: number;
10
+ minimumFreeBytes: number;
11
+ }
12
+ export interface PublishingJournalRecord {
13
+ revision: number;
14
+ payload: JsonValue;
15
+ }
16
+ export interface PublishingJournal {
17
+ load(key: string, options?: {
18
+ signal?: AbortSignal;
19
+ }): Promise<PublishingJournalRecord | undefined>;
20
+ readBlob(input: {
21
+ sha256: string;
22
+ byteLength: number;
23
+ }, options?: {
24
+ signal?: AbortSignal;
25
+ }): Promise<Uint8Array | undefined>;
26
+ compareAndSet(input: {
27
+ key: string;
28
+ expectedRevision: number;
29
+ payload: JsonValue;
30
+ blobs?: readonly {
31
+ sha256: string;
32
+ bytes: Uint8Array;
33
+ }[];
34
+ }, options?: {
35
+ signal?: AbortSignal;
36
+ }): Promise<'stored' | 'conflict'>;
37
+ operationJournal(): ArtifactOperationJournal;
38
+ close(): void;
39
+ }
40
+ type JournalInput = {
41
+ root: string;
42
+ directory: string;
43
+ filesystem: DurableArtifactFilesystem;
44
+ limits: PublishingJournalLimits;
45
+ signal?: AbortSignal;
46
+ };
47
+ export declare function openPublishingJournal(input: JournalInput): Promise<PublishingJournal>;
48
+ export declare function openPublishingCredentialJournal(input: JournalInput): Promise<PublishingJournal>;
49
+ export {};
@@ -7,6 +7,7 @@ import { validatePortableRelativePath } from '@openge/forge-path-safety';
7
7
  import { GeneratedArtifactError, generatedArtifactErrorCodes } from '@openge/forge-generated-artifacts';
8
8
  import { publishingError, protocolRecord, publishingRequestId, publishingDigest } from '../protocol.js';
9
9
  import { jsonSnapshot, operationRecord } from '../shared/records.js';
10
+ import { ensurePublishingJournalDirectory } from './journal-directory.js';
10
11
  const fail = (code) => publishingError('JOURNAL_' + code);
11
12
  const keyValid = (value) => typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,191}$/.test(value);
12
13
  const recordBytes = (key, revision, payload) => Buffer.byteLength('{"key":' + JSON.stringify(key) + ',"revision":' + revision + ',"payload":' + payload + '}');
@@ -42,8 +43,10 @@ async function markerBytes(file) {
42
43
  throw fail('OWNERSHIP_INVALID');
43
44
  }
44
45
  }
46
+ export function openPublishingJournal(input) { return openJournal(input, false); }
47
+ export function openPublishingCredentialJournal(input) { return openJournal(input, true); }
45
48
  /** SQLite owns CAS; Foundation owns durable publication of the directory/owner bytes. */
46
- export async function openPublishingJournal({ root, directory, filesystem, limits, signal }) {
49
+ async function openJournal({ root, directory, filesystem, limits, signal }, credential) {
47
50
  signal?.throwIfAborted();
48
51
  limits = checkedLimits(limits);
49
52
  if (typeof root !== 'string' || !path.isAbsolute(root) || !filesystem || typeof filesystem.ensureDirectory !== 'function' || typeof filesystem.publishBytes !== 'function')
@@ -60,13 +63,8 @@ export async function openPublishingJournal({ root, directory, filesystem, limit
60
63
  }
61
64
  await capacity(root, limits);
62
65
  signal?.throwIfAborted();
63
- try {
64
- await filesystem.ensureDirectory(root, directory);
65
- }
66
- catch {
67
- throw fail('PERSISTENCE_UNKNOWN');
68
- }
69
- const absolute = path.join(root, ...directory.split('/')), markerFile = path.join(absolute, 'owner.json'), databaseFile = path.join(absolute, 'journal.sqlite');
66
+ const absolute = await ensurePublishingJournalDirectory(root, directory, filesystem, credential, signal);
67
+ const markerFile = path.join(absolute, 'owner.json'), databaseFile = path.join(absolute, 'journal.sqlite');
70
68
  const context = { schemaVersion: 1, root: { dev: String(rootInfo.dev), ino: String(rootInfo.ino) }, directory, limits };
71
69
  let marker;
72
70
  try {
@@ -0,0 +1,3 @@
1
+ export declare function isAbsoluteLocalFile(value: string): boolean;
2
+ /** Read the named regular file once. A link, replacement or size change never selects a different JSON document. */
3
+ export declare function readLocalJsonFile(file: string, maximumBytes: number, signal?: AbortSignal): Promise<unknown>;
@@ -0,0 +1,49 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ export function isAbsoluteLocalFile(value) {
4
+ if (!path.isAbsolute(value) || value.length > 4096 || /[\x00-\x1f]/.test(value))
5
+ return false;
6
+ if (process.platform === 'win32') {
7
+ if (!/^[A-Za-z]:[\\/]/.test(value) || value.slice(2).includes(':'))
8
+ return false;
9
+ }
10
+ else if (value.startsWith('//'))
11
+ return false;
12
+ return !value.split(path.sep === '\\' ? /[\\/]/ : '/').some(part => part === '.' || part === '..');
13
+ }
14
+ const invalid = () => Error('LOCAL_JSON_FILE_INVALID');
15
+ const sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs && b.nlink === 1n;
16
+ /** Read the named regular file once. A link, replacement or size change never selects a different JSON document. */
17
+ export async function readLocalJsonFile(file, maximumBytes, signal) {
18
+ signal?.throwIfAborted();
19
+ if (!isAbsoluteLocalFile(file))
20
+ throw invalid();
21
+ const canonical = path.resolve(file), before = await fs.lstat(canonical, { bigint: true });
22
+ if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1n || before.size > BigInt(maximumBytes) ||
23
+ path.relative(canonical, await fs.realpath(canonical)) !== '')
24
+ throw invalid();
25
+ const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
26
+ const handle = await fs.open(canonical, flags);
27
+ const buffer = Buffer.alloc(Number(before.size) + 1);
28
+ try {
29
+ if (!sameFile(before, await handle.stat({ bigint: true })))
30
+ throw invalid();
31
+ let offset = 0;
32
+ while (offset < buffer.length) {
33
+ signal?.throwIfAborted();
34
+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset);
35
+ if (!bytesRead)
36
+ break;
37
+ offset += bytesRead;
38
+ }
39
+ if (offset !== Number(before.size) || !sameFile(before, await handle.stat({ bigint: true })) ||
40
+ !sameFile(before, await fs.lstat(canonical, { bigint: true })) || path.relative(canonical, await fs.realpath(canonical)) !== '')
41
+ throw invalid();
42
+ signal?.throwIfAborted();
43
+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, offset)));
44
+ }
45
+ finally {
46
+ buffer.fill(0);
47
+ await handle.close();
48
+ }
49
+ }