@sentropic/artifacts 0.2.18 → 0.2.21

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 (61) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +14 -0
  3. package/dist/adapters/postgres-git-bindings.js +25 -4
  4. package/dist/http.d.ts +3 -0
  5. package/dist/http.js +12 -1
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.js +1 -0
  8. package/dist/live-host/accept.d.ts +30 -0
  9. package/dist/live-host/accept.js +43 -0
  10. package/dist/live-host/api.d.ts +67 -0
  11. package/dist/live-host/api.js +60 -0
  12. package/dist/live-host/candidate.d.ts +21 -0
  13. package/dist/live-host/candidate.js +41 -0
  14. package/dist/live-host/errors.d.ts +9 -0
  15. package/dist/live-host/errors.js +14 -0
  16. package/dist/live-host/handoff.d.ts +63 -0
  17. package/dist/live-host/handoff.js +66 -0
  18. package/dist/live-host/index.d.ts +10 -0
  19. package/dist/live-host/index.js +10 -0
  20. package/dist/live-host/keys.d.ts +14 -0
  21. package/dist/live-host/keys.js +8 -0
  22. package/dist/live-host/live-format.d.ts +70 -0
  23. package/dist/live-host/live-format.js +100 -0
  24. package/dist/live-host/recheck.d.ts +59 -0
  25. package/dist/live-host/recheck.js +45 -0
  26. package/dist/mcp-core.d.ts +1 -1
  27. package/dist/mcp-core.js +4 -1
  28. package/dist/server/build-contract.d.ts +15 -1
  29. package/dist/server/build-contract.js +14 -5
  30. package/dist/server/build-dependencies.d.ts +12 -1
  31. package/dist/server/build-dependencies.js +41 -13
  32. package/dist/server/build-integrity.d.ts +48 -0
  33. package/dist/server/build-integrity.js +70 -0
  34. package/dist/server/build-output.d.ts +22 -0
  35. package/dist/server/build-output.js +40 -0
  36. package/dist/server/build-receipt.d.ts +51 -0
  37. package/dist/server/build-receipt.js +76 -0
  38. package/dist/server/failures.d.ts +2 -2
  39. package/dist/server/failures.js +1 -1
  40. package/dist/server/git-bindings.d.ts +3 -1
  41. package/dist/server/git-bindings.js +26 -1
  42. package/dist/server/git-contracts.d.ts +18 -1
  43. package/dist/server/git-tools-attach.d.ts +8 -0
  44. package/dist/server/git-tools-attach.js +139 -0
  45. package/dist/server/git-tools-contracts.d.ts +59 -0
  46. package/dist/server/git-tools-contracts.js +1 -0
  47. package/dist/server/git-tools-fetch.d.ts +21 -0
  48. package/dist/server/git-tools-fetch.js +65 -0
  49. package/dist/server/git-tools-publish.d.ts +13 -0
  50. package/dist/server/git-tools-publish.js +66 -0
  51. package/dist/server/git-tools.d.ts +4 -0
  52. package/dist/server/git-tools.js +18 -0
  53. package/dist/server/live-mutations.d.ts +1 -1
  54. package/dist/server/live-mutations.js +3 -2
  55. package/dist/server/live-read.d.ts +1 -1
  56. package/dist/server/live-read.js +2 -1
  57. package/dist/server/live-store.d.ts +2 -1
  58. package/dist/server/live-store.js +2 -0
  59. package/dist/server/templates.js +26 -1
  60. package/migrations/0012_git_attach_intents.sql +19 -0
  61. package/package.json +5 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.21
4
+
5
+ - Add the GB1 build validators on `@sentropic/artifacts/server/build-contract`: full dependency
6
+ integrity coverage with a sealed host integrity map (`dependency_integrity_missing`,
7
+ `dependency_integrity_mismatch`), script-package qualification rows, the mandatory
8
+ builder-attested receipt schema and verifier (§8.4 join, served-byte anti-repack), and the
9
+ candidate output ceiling gate (`dist_over_limits`). Tarball-bundled dependencies are exempt
10
+ from the lock closure check. Additive; no new export path.
11
+ - The live runtime record follows A-LIVE Amendment 1: `idleDeadline` is 900 s after the last
12
+ access and the absolute `maximumLifetimeAt` is removed.
13
+ - `@sentropic/artifacts/live-host` is unchanged (HostLedger and AcceptOptions frozen).
14
+ - `ARTIFACTS_PROVIDER_VERSION` is `0.2.21` (it equals the package version). Tool definitions are
15
+ unchanged; the provider manifest digest changes only through `version`.
16
+
17
+ ## 0.2.20
18
+
19
+ - Add the `@sentropic/artifacts/live-host` subpath: single live-host candidate digest with pinned vectors,
20
+ SG4b handoff seal and receipt verification with key rotation, A-LIVE 8.3 publication recheck and
21
+ pending handling shared by `acceptHandoff`, live assertion, control and fence formats, and the host
22
+ build API types with signed job requests. Additive; no existing export changes.
23
+ - Includes the 0.2.19 git-backed tool routing below (never published separately).
24
+
25
+ - Route `artifacts_fetch_app_source`, `artifacts_git_attach` and `artifacts_git_publish`
26
+ through `createHttpArtifactApp` and the MCP executor (G0 v3 §1.3; A-LIVE v2 S03).
27
+ `createGitToolService` composes the injected binding store, registry, code-rights,
28
+ GitPort and build executor ports; a missing port is a closed 503 refusal.
29
+ - `assertArtifactsTransportProfile` admits the three tools. Existing catalogue
30
+ entries are byte-identical; `artifacts_list_app_sources` stays unrouted.
31
+ - `git_attach` checks the current code right on every path before any registry or
32
+ forge call, and admits every executor through the host build port at attach.
33
+ - Additive migration `0012_git_attach_intents.sql`: a durable attach intent written
34
+ before `createBranch` keeps a crash retry deterministic, and the attach event of a
35
+ created branch carries `branchCreated: true` (A-LIVE v2 §5.3.1).
36
+ - The served authoring guide describes the git-backed path and the current caps.
37
+
3
38
  ## 0.2.18
4
39
 
5
40
  - Export the canonical MIME helpers through `server/mime` and the generic
package/README.md CHANGED
@@ -496,6 +496,20 @@ caps may only go below it, and larger listings belong to dedicated listing
496
496
  tools. Hosts must qualify
497
497
  a 2 MiB serialized MCP result budget before selecting this capability.
498
498
 
499
+ `POST /fetch_app_source`, `POST /git_attach` and `POST /git_publish` (G0 v3 §1.3,
500
+ §1.4, §2.6; A-LIVE v2 S03) are dispatched through `deps.gitTools`, built with
501
+ `createGitToolService({ bindings, registry, codeRights, git, authorize, build?,
502
+ outputDir?, journal? })`. Each executor fails closed: no `gitTools` is
503
+ `capability_unavailable` (503); `git_publish` without a `build` port is
504
+ `provider_unavailable` (503); `ci` is `builder_unavailable`, and so is every
505
+ other executor the `build` port does not admit, including the omitted `caller`
506
+ default (without a `build` port only `caller` is admitted). Every `git_attach`
507
+ path, pause/resume/detach included, checks the current code right before any
508
+ registry or forge call. A branch created by attach records an intent first
509
+ (migration `0012_git_attach_intents.sql`) and marks its attach event
510
+ `branchCreated: true`; see `docs/git-bindings.md`.
511
+ `artifacts_list_app_sources` stays unrouted.
512
+
499
513
  `POST /set_access` grants or revokes a named principal's read access, requires a
500
514
  caller `idempotencyKey`, and keeps the artifact private. Bind
501
515
  `isApprovedAccount` to the host's principal policy. `POST /delete` also requires
@@ -1,5 +1,5 @@
1
1
  import { ArtifactOperationError } from '../server/failures.js';
2
- import { gitBindingEvent, gitBindingReceiptKey, validateGitBindingWrite } from '../server/git-bindings.js';
2
+ import { gitBindingEvent, gitBindingReceiptKey, validateGitAttachIntent, validateGitBindingWrite } from '../server/git-bindings.js';
3
3
  const fields = ['artifactId', 'storageScopeId', 'repoId', 'branch', 'channel', 'personalPrincipalId', 'subPath',
4
4
  'baseCommitSha', 'headCommitSha', 'releaseCommitSha', 'autoPublish', 'executor', 'pendingJobId',
5
5
  'pendingCommitSha', 'state', 'stateDetail', 'generation', 'version', 'attachedBy', 'attachedAt', 'updatedAt'];
@@ -10,8 +10,19 @@ function bindingRow(row) {
10
10
  return key === 'stateDetail' && value === null ? [] : [[key, value instanceof Date ? value.toISOString() : value]];
11
11
  }));
12
12
  }
13
+ const intentFields = ['storageScopeId', 'actorId', 'idempotencyKey', 'commandHash', 'artifactId', 'repoId',
14
+ 'branch', 'baseCommitSha', 'createdAt'];
15
+ const intentRow = (row) => Object.fromEntries(intentFields.map(key => {
16
+ const value = row[column(key)];
17
+ return [key, value instanceof Date ? value.toISOString() : value];
18
+ }));
13
19
  /** Injected pool, no import-time I/O/DDL. All mutation work shares one transaction. */
14
20
  export function createPostgresGitBindingStore(pool) {
21
+ const readIntent = async (scope, actorId, key) => {
22
+ const { rows } = await pool.query(`SELECT * FROM artifacts.git_attach_intents
23
+ WHERE storage_scope_id=$1 AND actor_id=$2 AND idempotency_key=$3`, [scope, actorId, key]);
24
+ return rows[0] ? intentRow(rows[0]) : undefined;
25
+ };
15
26
  return {
16
27
  async get(scope, id) {
17
28
  const { rows } = await pool.query('SELECT * FROM artifacts.git_bindings WHERE storage_scope_id=$1 AND artifact_id=$2', [scope, id]);
@@ -28,9 +39,19 @@ export function createPostgresGitBindingStore(pool) {
28
39
  if (row[column(key)] !== null)
29
40
  event[key] = row[column(key)];
30
41
  }
42
+ if (row.branch_created === true)
43
+ event.branchCreated = true;
31
44
  return event;
32
45
  });
33
46
  },
47
+ async reserveAttachIntent(intent) {
48
+ validateGitAttachIntent(intent);
49
+ await pool.query(`INSERT INTO artifacts.git_attach_intents (storage_scope_id,actor_id,idempotency_key,
50
+ command_hash,artifact_id,repo_id,branch,base_commit_sha,created_at)
51
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT DO NOTHING`, intentFields.map(key => intent[key]));
52
+ return (await readIntent(intent.storageScopeId, intent.actorId, intent.idempotencyKey));
53
+ },
54
+ attachIntent: readIntent,
34
55
  async write(input) {
35
56
  const snapshot = structuredClone(input);
36
57
  const binding = snapshot.binding;
@@ -63,10 +84,10 @@ export function createPostgresGitBindingStore(pool) {
63
84
  WHERE git_bindings.storage_scope_id=EXCLUDED.storage_scope_id`, values);
64
85
  const event = gitBindingEvent(snapshot);
65
86
  await client.query(`INSERT INTO artifacts.git_binding_events
66
- (artifact_id,storage_scope_id,actor_id,action,before_sha,after_sha,delivery_id,invocation_id,created_at)
67
- VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`, [binding.artifactId, scope, snapshot.actorId,
87
+ (artifact_id,storage_scope_id,actor_id,action,before_sha,after_sha,delivery_id,invocation_id,created_at,
88
+ branch_created) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, [binding.artifactId, scope, snapshot.actorId,
68
89
  event.action, event.beforeSha ?? null, event.afterSha ?? null,
69
- event.deliveryId ?? null, event.invocationId ?? null, event.createdAt]);
90
+ event.deliveryId ?? null, event.invocationId ?? null, event.createdAt, event.branchCreated ?? null]);
70
91
  await client.query('INSERT INTO artifacts.idempotency_keys(key,params_hash,result) VALUES ($1,$2,$3)', [key, snapshot.commandHash, JSON.stringify(binding)]);
71
92
  await client.query('COMMIT');
72
93
  return { binding, replayed: false };
package/dist/http.d.ts CHANGED
@@ -14,6 +14,7 @@ import { type ArtifactInvocationContext, type ArtifactCommitCoordinator } from '
14
14
  import { type ArtifactOutcome, type ArtifactHostFailureMapper } from './server/failures.js';
15
15
  import { type GitProjectionPorts } from './server/git-projection.js';
16
16
  import type { LiveService } from './server/live-contracts.js';
17
+ import type { GitToolService } from './server/git-tools-contracts.js';
17
18
  import { type ManagementUnit, type ArtifactConfirmationPort } from './server/management.js';
18
19
  import type { FinalizeTxClient } from './server/commit/types.js';
19
20
  import type { SourceStore } from './server/sources.js';
@@ -39,6 +40,8 @@ export declare function errorBody(status: number): {
39
40
  export interface HttpAppDeps {
40
41
  /** AL-T/AL-D: trusted service; absence is a closed capability refusal. */
41
42
  live?: LiveService;
43
+ /** SG3: fetch_app_source, git_attach and git_publish executors; absence is a closed capability refusal. */
44
+ gitTools?: GitToolService;
42
45
  /** SG1: host repository code access, independent of page/source grants. */
43
46
  git?: GitProjectionPorts;
44
47
  /** Trusted mapping of host wrapper errors; causes remain private. Also bind on the coordinator. */
package/dist/http.js CHANGED
@@ -50,11 +50,13 @@ export function assertArtifactsTransportProfile(value) {
50
50
  'artifacts_create_upload', 'artifacts_commit_upload', 'artifacts_publish_bundle',
51
51
  'artifacts_create_upload_page', 'artifacts_list_assets', 'artifacts_publish_bundle_v2',
52
52
  'artifacts_revoke_reader_consent', 'artifacts_git_commit', 'artifacts_live_write',
53
- 'artifacts_live_read', 'artifacts_live_reset', 'artifacts_live_status', 'artifacts_live_control'];
53
+ 'artifacts_live_read', 'artifacts_live_reset', 'artifacts_live_status', 'artifacts_live_control',
54
+ 'artifacts_fetch_app_source', 'artifacts_git_attach', 'artifacts_git_publish'];
54
55
  if (value.selectedCapabilities.some((name) => !supported.includes(name))) {
55
56
  throw new Error('unsupported artifacts transport capability');
56
57
  }
57
58
  }
59
+ const GIT_TOOL_CAPABILITIES = ['artifacts_fetch_app_source', 'artifacts_git_attach', 'artifacts_git_publish'];
58
60
  export function createHttpArtifactApp(deps) {
59
61
  assertArtifactsTransportProfile(deps.profile);
60
62
  if (typeof deps.coordinator?.finalizePrepared !== 'function' || typeof deps.coordinator.replayPrepared !== 'function') {
@@ -540,6 +542,15 @@ export function createHttpArtifactApp(deps) {
540
542
  }
541
543
  }
542
544
  const normalized = profile.validate(capability, args, request.idempotencyKey, { deferPrecondition: true });
545
+ if (GIT_TOOL_CAPABILITIES.includes(capability)) {
546
+ if (!deps.gitTools)
547
+ throw new ArtifactOperationError('capability_unselected');
548
+ phase = 'dispatch';
549
+ const result = await deps.gitTools.execute(operation, normalized, invocation);
550
+ return { ok: true, invocationId: invocation.invocationId,
551
+ commitState: operation === 'fetch_app_source' ? 'not_committed' : 'committed',
552
+ replayed: result.replayed === true, result: { status: 200, body: result } };
553
+ }
543
554
  if (capability.startsWith('artifacts_live_') || capability === 'artifacts_git_commit') {
544
555
  if (!deps.live)
545
556
  throw new ArtifactOperationError('capability_unselected');
package/dist/index.d.ts CHANGED
@@ -41,3 +41,4 @@ export * from './server/live-drafts.js';
41
41
  export * from './server/live-errors.js';
42
42
  export * from './adapters/postgres-live.js';
43
43
  export * from './server/live-body.js';
44
+ export * from './server/git-tools.js';
package/dist/index.js CHANGED
@@ -44,3 +44,4 @@ export * from './server/live-drafts.js';
44
44
  export * from './server/live-errors.js';
45
45
  export * from './adapters/postgres-live.js';
46
46
  export * from './server/live-body.js';
47
+ export * from './server/git-tools.js';
@@ -0,0 +1,30 @@
1
+ import { type CandidateFile } from './candidate.js';
2
+ import { type Handoff, type HandoffClaims, type HandoffReceipt } from './handoff.js';
3
+ import { type KeyResolver, type SigningKey } from './keys.js';
4
+ import { type HostRecheckView } from './recheck.js';
5
+ /** Host persistence. `transaction` runs `work` and stores its receipt under the job key in ONE host transaction, so a
6
+ * failed recheck, release CAS or bytes re-read rolls back the consumption too. A concurrent winner is returned as stored. */
7
+ export interface HostLedger {
8
+ find(jobKey: string): Promise<HandoffReceipt | undefined>;
9
+ transaction(jobKey: string, work: () => Promise<HandoffReceipt>): Promise<HandoffReceipt>;
10
+ }
11
+ export interface AcceptOptions {
12
+ /** Authenticated host scope. */
13
+ scopeId: string;
14
+ /** Builder public keys by kid: old and new during a rotation overlap. */
15
+ builderKeys: KeyResolver;
16
+ /** Current host receipt key; its kid is stamped on the receipt. */
17
+ receiptKey: SigningKey;
18
+ now(): number;
19
+ ledger: HostLedger;
20
+ /** Inside the host transaction, before any write: the locked durable state `publicationRecheck` evaluates. */
21
+ view(claims: HandoffClaims): HostRecheckView | Promise<HostRecheckView>;
22
+ /** Inside the host transaction: store the exact bytes, write release/index/receipt/baseline, re-read stored bytes. */
23
+ publish(claims: HandoffClaims, files: readonly CandidateFile[]): Promise<{
24
+ releaseId: string;
25
+ manifestDigest: string;
26
+ storedDigest: string;
27
+ }>;
28
+ }
29
+ /** A-LIVE §8.4 step 2. Refuses with a closed LiveHostError code; a retry after committed success returns the stored receipt. */
30
+ export declare function acceptHandoff(options: AcceptOptions, handoff: Handoff, files: readonly CandidateFile[]): Promise<HandoffReceipt>;
@@ -0,0 +1,43 @@
1
+ import { candidateDigest } from './candidate.js';
2
+ import { LiveHostError } from './errors.js';
3
+ import { HANDOFF_LIFETIME_MS, handoffAuthentic, handoffEvidence, jobKey, signReceipt, } from './handoff.js';
4
+ import { assertSigner } from './keys.js';
5
+ import { publicationRecheck } from './recheck.js';
6
+ /** A-LIVE §8.4 step 2. Refuses with a closed LiveHostError code; a retry after committed success returns the stored receipt. */
7
+ export async function acceptHandoff(options, handoff, files) {
8
+ assertSigner(options.receiptKey);
9
+ if (!handoffAuthentic(handoff, options.builderKeys))
10
+ throw new LiveHostError('handoff_unauthenticated');
11
+ const { claims } = handoff;
12
+ if (!handoffEvidence(claims))
13
+ throw new LiveHostError('handoff_evidence_missing');
14
+ const job = jobKey(claims);
15
+ const stored = await options.ledger.find(job);
16
+ if (stored) {
17
+ if (stored.nonce !== claims.nonce)
18
+ throw new LiveHostError('handoff_replayed');
19
+ return stored;
20
+ }
21
+ const now = options.now();
22
+ if (now >= claims.expiresAt || claims.expiresAt - claims.sealedAt > HANDOFF_LIFETIME_MS)
23
+ throw new LiveHostError('handoff_expired');
24
+ if (claims.scopeId !== options.scopeId)
25
+ throw new LiveHostError('handoff_mismatch', 'scope_mismatch');
26
+ if (candidateDigest(files) !== claims.candidateDigest)
27
+ throw new LiveHostError('candidate_bytes_mismatch');
28
+ const receipt = await options.ledger.transaction(job, async () => {
29
+ const refusal = publicationRecheck(await options.view(claims), claims);
30
+ if (refusal)
31
+ throw new LiveHostError('handoff_mismatch', refusal);
32
+ const published = await options.publish(claims, files);
33
+ if (published.storedDigest !== claims.candidateDigest)
34
+ throw new LiveHostError('candidate_bytes_mismatch');
35
+ return signReceipt({ v: 1, kid: options.receiptKey.kid, nonce: claims.nonce, scopeId: claims.scopeId,
36
+ artifactId: claims.artifactId, jobId: claims.jobId, runId: claims.runId, attempt: claims.attempt, commitSha: claims.commitSha,
37
+ candidateDigest: claims.candidateDigest, releaseId: published.releaseId, manifestDigest: published.manifestDigest,
38
+ committedAt: options.now() }, options.receiptKey);
39
+ });
40
+ if (receipt.nonce !== claims.nonce)
41
+ throw new LiveHostError('handoff_replayed');
42
+ return receipt;
43
+ }
@@ -0,0 +1,67 @@
1
+ import { type CandidateFile } from './candidate.js';
2
+ import { LiveHostError, type LiveHostErrorCode } from './errors.js';
3
+ import { type Handoff, type HandoffReceipt } from './handoff.js';
4
+ import { type KeyResolver, type SigningKey } from './keys.js';
5
+ import { type AttemptFence, type HostJob, type RecheckRefusal } from './recheck.js';
6
+ /** Host build API (A-LIVE §8.4): the trusted builder calls the content host to resolve its pending job, then to submit
7
+ * the sealed handoff with the exact candidate bytes. JSON bodies; paths are relative to the host-configured base URL. */
8
+ export declare const HOST_BUILD_PATHS: Readonly<{
9
+ job: "/live-host/v1/job";
10
+ handoff: "/live-host/v1/handoff";
11
+ }>;
12
+ export declare const JOB_REQUEST_LIFETIME_MS = 60000;
13
+ /** Signed by the builder key, so no unauthenticated caller can advance the attempt fence. */
14
+ export interface HostJobClaims {
15
+ v: 1;
16
+ kid: string;
17
+ scopeId: string;
18
+ artifactId: string;
19
+ jobId: string;
20
+ fence: AttemptFence;
21
+ iat: number;
22
+ exp: number;
23
+ }
24
+ export interface HostJobRequest {
25
+ claims: HostJobClaims;
26
+ signature: string;
27
+ }
28
+ export interface HostJobResponse {
29
+ v: 1;
30
+ job: HostJob;
31
+ }
32
+ export interface HostCandidateFile {
33
+ path: string;
34
+ base64: string;
35
+ }
36
+ export interface HostHandoffRequest {
37
+ v: 1;
38
+ handoff: Handoff;
39
+ files: HostCandidateFile[];
40
+ }
41
+ export interface HostHandoffResponse {
42
+ v: 1;
43
+ receipt: HandoffReceipt;
44
+ }
45
+ /** Every host refusal body: a closed code, never caller text. Any other failure is a transport failure (unknown outcome). */
46
+ export interface HostBuildRefusal {
47
+ v: 1;
48
+ error: LiveHostErrorCode;
49
+ reason?: RecheckRefusal;
50
+ }
51
+ export declare function sealJobRequest(input: Pick<HostJobClaims, 'scopeId' | 'artifactId' | 'jobId' | 'fence'>, signer: SigningKey, now: number): HostJobRequest;
52
+ /** Host side: authenticated, fresh, for this host scope. The host then runs `resolvePendingJob` on its locked rows. */
53
+ export declare function verifyJobRequest(request: unknown, options: {
54
+ scopeId: string;
55
+ builderKeys: KeyResolver;
56
+ now: number;
57
+ }): HostJobClaims;
58
+ export declare const encodeHandoffRequest: (handoff: Handoff, files: readonly CandidateFile[]) => HostHandoffRequest;
59
+ /** Host side: strict shape and canonical base64 only. acceptHandoff then authenticates and digests the bytes. */
60
+ export declare function parseHandoffRequest(body: unknown): {
61
+ handoff: Handoff;
62
+ files: CandidateFile[];
63
+ };
64
+ /** Host side: the body for a LiveHostError; undefined for any other error (answer a generic failure). */
65
+ export declare const refusalOf: (error: unknown) => HostBuildRefusal | undefined;
66
+ /** Builder side: a host refusal from a closed code set; undefined means no refusal (unknown outcome, resend). */
67
+ export declare function refusalFrom(body: unknown): LiveHostError | undefined;
@@ -0,0 +1,60 @@
1
+ import { CANDIDATE_LIMITS, candidatePath } from './candidate.js';
2
+ import { LIVE_HOST_ERROR_CODES, LiveHostError } from './errors.js';
3
+ import { count, record, signed, text, valid } from './handoff.js';
4
+ import { assertSigner, liveKeyId } from './keys.js';
5
+ import { RECHECK_REFUSALS } from './recheck.js';
6
+ /** Host build API (A-LIVE §8.4): the trusted builder calls the content host to resolve its pending job, then to submit
7
+ * the sealed handoff with the exact candidate bytes. JSON bodies; paths are relative to the host-configured base URL. */
8
+ export const HOST_BUILD_PATHS = Object.freeze({ job: '/live-host/v1/job', handoff: '/live-host/v1/handoff' });
9
+ export const JOB_REQUEST_LIFETIME_MS = 60_000;
10
+ const JOB_SKEW_MS = 5_000;
11
+ const JOB_TAG = 'sentropic.sg4b.job.v1\n';
12
+ export function sealJobRequest(input, signer, now) {
13
+ assertSigner(signer);
14
+ const claims = { v: 1, kid: signer.kid, ...input, iat: now, exp: now + JOB_REQUEST_LIFETIME_MS };
15
+ return { claims, signature: signed(JOB_TAG, claims, signer.key) };
16
+ }
17
+ const invalid = () => { throw new LiveHostError('request_invalid'); };
18
+ /** Host side: authenticated, fresh, for this host scope. The host then runs `resolvePendingJob` on its locked rows. */
19
+ export function verifyJobRequest(request, options) {
20
+ const body = record(request) ? request : undefined;
21
+ const claims = body?.claims;
22
+ if (!record(claims) || claims.v !== 1 || !liveKeyId(claims.kid)
23
+ || !valid(JOB_TAG, claims, body?.signature, options.builderKeys(claims.kid)))
24
+ return invalid();
25
+ const c = claims;
26
+ if (!text(c.scopeId) || !text(c.artifactId) || !text(c.jobId) || !record(c.fence) || !text(c.fence.runId) || !count(c.fence.attempt)
27
+ || !Number.isSafeInteger(c.iat) || !Number.isSafeInteger(c.exp) || c.exp - c.iat > JOB_REQUEST_LIFETIME_MS
28
+ || c.iat > options.now + JOB_SKEW_MS || c.exp <= options.now)
29
+ return invalid();
30
+ if (c.scopeId !== options.scopeId)
31
+ throw new LiveHostError('handoff_mismatch', 'scope_mismatch');
32
+ return c;
33
+ }
34
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
35
+ const MAX_BASE64 = Math.ceil(CANDIDATE_LIMITS.fileBytes / 3) * 4;
36
+ export const encodeHandoffRequest = (handoff, files) => ({ v: 1, handoff, files: files.map(file => ({ path: file.path, base64: Buffer.from(file.bytes).toString('base64') })) });
37
+ /** Host side: strict shape and canonical base64 only. acceptHandoff then authenticates and digests the bytes. */
38
+ export function parseHandoffRequest(body) {
39
+ if (!record(body) || body.v !== 1 || !record(body.handoff) || !Array.isArray(body.files) || body.files.length < 1
40
+ || body.files.length > CANDIDATE_LIMITS.files)
41
+ return invalid();
42
+ const files = body.files.map((file) => {
43
+ if (!record(file) || Object.keys(file).sort().join() !== 'base64,path' || !candidatePath(file.path)
44
+ || typeof file.base64 !== 'string' || file.base64.length > MAX_BASE64 || !BASE64.test(file.base64))
45
+ return invalid();
46
+ const bytes = Buffer.from(file.base64, 'base64');
47
+ return bytes.toString('base64') === file.base64 ? { path: file.path, bytes: new Uint8Array(bytes) } : invalid();
48
+ });
49
+ return { handoff: body.handoff, files };
50
+ }
51
+ /** Host side: the body for a LiveHostError; undefined for any other error (answer a generic failure). */
52
+ export const refusalOf = (error) => error instanceof LiveHostError
53
+ ? { v: 1, error: error.code, ...(error.reason ? { reason: error.reason } : {}) } : undefined;
54
+ /** Builder side: a host refusal from a closed code set; undefined means no refusal (unknown outcome, resend). */
55
+ export function refusalFrom(body) {
56
+ if (!record(body) || body.v !== 1 || !LIVE_HOST_ERROR_CODES.includes(body.error)
57
+ || (body.reason !== undefined && !RECHECK_REFUSALS.includes(body.reason)))
58
+ return undefined;
59
+ return new LiveHostError(body.error, body.reason);
60
+ }
@@ -0,0 +1,21 @@
1
+ /** One output file of a clean build (G0 §2.3 candidate). Modes are not served, so they are not digested. */
2
+ export interface CandidateFile {
3
+ readonly path: string;
4
+ readonly bytes: Uint8Array;
5
+ }
6
+ /** A-LIVE §8.3 stable output snapshot ceilings. */
7
+ export declare const CANDIDATE_LIMITS: Readonly<{
8
+ files: 255;
9
+ fileBytes: 16777216;
10
+ totalBytes: 67108864;
11
+ }>;
12
+ export declare const CANDIDATE_DIGEST_TAG = "sentropic.candidate.v1\n";
13
+ /** Relative, `/`-separated, no empty, `.` or `..` segment, no backslash, control character or lone surrogate. */
14
+ export declare function candidatePath(path: unknown): path is string;
15
+ /**
16
+ * THE canonical candidate digest, shared by the supervisor snapshot, the builder handoff and the host verifier:
17
+ * sha256 hex of `sentropic.candidate.v1\n` + JSON of `[path, byteLength, sha256 hex]` entries sorted by path in
18
+ * UTF-16 code unit order (the JSON is UTF-8 encoded). Refuses with `candidate_invalid` an empty or over-limit set,
19
+ * an unsafe or duplicate path, and a path that is both a file and a directory.
20
+ */
21
+ export declare function candidateDigest(files: readonly CandidateFile[]): string;
@@ -0,0 +1,41 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { LiveHostError } from './errors.js';
3
+ /** A-LIVE §8.3 stable output snapshot ceilings. */
4
+ export const CANDIDATE_LIMITS = Object.freeze({ files: 255, fileBytes: 16_777_216, totalBytes: 67_108_864 });
5
+ export const CANDIDATE_DIGEST_TAG = 'sentropic.candidate.v1\n';
6
+ const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
7
+ const FORBIDDEN = /[\\\u0000-\u001f\u007f]|\p{Cs}/u;
8
+ /** Relative, `/`-separated, no empty, `.` or `..` segment, no backslash, control character or lone surrogate. */
9
+ export function candidatePath(path) {
10
+ return typeof path === 'string' && path.length > 0 && Buffer.byteLength(path) <= 1024 && !FORBIDDEN.test(path)
11
+ && path.split('/').every(segment => segment !== '' && segment !== '.' && segment !== '..');
12
+ }
13
+ const invalid = () => { throw new LiveHostError('candidate_invalid'); };
14
+ /**
15
+ * THE canonical candidate digest, shared by the supervisor snapshot, the builder handoff and the host verifier:
16
+ * sha256 hex of `sentropic.candidate.v1\n` + JSON of `[path, byteLength, sha256 hex]` entries sorted by path in
17
+ * UTF-16 code unit order (the JSON is UTF-8 encoded). Refuses with `candidate_invalid` an empty or over-limit set,
18
+ * an unsafe or duplicate path, and a path that is both a file and a directory.
19
+ */
20
+ export function candidateDigest(files) {
21
+ if (!Array.isArray(files) || files.length < 1 || files.length > CANDIDATE_LIMITS.files)
22
+ invalid();
23
+ const paths = new Set();
24
+ let total = 0;
25
+ const entries = files.map(file => {
26
+ if (!file || !candidatePath(file.path) || paths.has(file.path) || !(file.bytes instanceof Uint8Array)
27
+ || file.bytes.byteLength > CANDIDATE_LIMITS.fileBytes)
28
+ invalid();
29
+ paths.add(file.path);
30
+ total += file.bytes.byteLength;
31
+ return [file.path, file.bytes.byteLength, sha256(file.bytes)];
32
+ }).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
33
+ if (total > CANDIDATE_LIMITS.totalBytes)
34
+ invalid();
35
+ for (const path of paths) {
36
+ for (let at = path.indexOf('/'); at !== -1; at = path.indexOf('/', at + 1))
37
+ if (paths.has(path.slice(0, at)))
38
+ invalid();
39
+ }
40
+ return sha256(CANDIDATE_DIGEST_TAG + JSON.stringify(entries));
41
+ }
@@ -0,0 +1,9 @@
1
+ /** Closed refusal codes of the live host code. A refusal never carries caller text. */
2
+ export declare const LIVE_HOST_ERROR_CODES: readonly ["candidate_invalid", "candidate_bytes_mismatch", "handoff_unauthenticated", "handoff_expired", "handoff_mismatch", "handoff_replayed", "handoff_evidence_missing", "receipt_invalid", "request_invalid"];
3
+ export type LiveHostErrorCode = typeof LIVE_HOST_ERROR_CODES[number];
4
+ export declare class LiveHostError extends Error {
5
+ readonly code: LiveHostErrorCode;
6
+ readonly reason?: "scope_mismatch" | "publication_paused" | "generation_mismatch" | "job_not_pending" | "attempt_fenced" | "policy_refused" | "head_unreachable" | "release_conflict" | "image_not_allowed" | undefined;
7
+ /** `reason` names the failed A-LIVE §8.3 recheck on `handoff_mismatch`. */
8
+ constructor(code: LiveHostErrorCode, reason?: "scope_mismatch" | "publication_paused" | "generation_mismatch" | "job_not_pending" | "attempt_fenced" | "policy_refused" | "head_unreachable" | "release_conflict" | "image_not_allowed" | undefined);
9
+ }
@@ -0,0 +1,14 @@
1
+ /** Closed refusal codes of the live host code. A refusal never carries caller text. */
2
+ export const LIVE_HOST_ERROR_CODES = ['candidate_invalid', 'candidate_bytes_mismatch', 'handoff_unauthenticated', 'handoff_expired',
3
+ 'handoff_mismatch', 'handoff_replayed', 'handoff_evidence_missing', 'receipt_invalid', 'request_invalid'];
4
+ export class LiveHostError extends Error {
5
+ code;
6
+ reason;
7
+ /** `reason` names the failed A-LIVE §8.3 recheck on `handoff_mismatch`. */
8
+ constructor(code, reason) {
9
+ super(code);
10
+ this.code = code;
11
+ this.reason = reason;
12
+ this.name = 'LiveHostError';
13
+ }
14
+ }
@@ -0,0 +1,63 @@
1
+ /// <reference types="node" resolution-mode="require"/>
2
+ import { type KeyObject } from 'node:crypto';
3
+ import type { ArtifactBuildTuple } from '../server/build-contract.js';
4
+ import { type KeyResolver, type SigningKey } from './keys.js';
5
+ /** A-LIVE §8.4 two-step SG4b handoff. Step 1: the trusted builder seals the candidate into a single-use Ed25519
6
+ * authorization. Step 2: the host verifies it, commits release/index/receipt/baseline in ONE transaction and signs a
7
+ * receipt. No private key or publication credential enters a worker pod. */
8
+ export declare const HANDOFF_LIFETIME_MS = 600000;
9
+ export interface HandoffClaims {
10
+ v: 1;
11
+ kid: string;
12
+ scopeId: string;
13
+ artifactId: string;
14
+ jobId: string;
15
+ kind: 'explicit' | 'idle';
16
+ runId: string;
17
+ attempt: number;
18
+ generation: number;
19
+ commitSha: string;
20
+ treeSha: string;
21
+ tuple: ArtifactBuildTuple;
22
+ candidateDigest: string;
23
+ expectedReleaseId: string | null;
24
+ nonce: string;
25
+ sealedAt: number;
26
+ expiresAt: number;
27
+ }
28
+ export type HandoffInput = Omit<HandoffClaims, 'v' | 'kid' | 'nonce' | 'sealedAt' | 'expiresAt'>;
29
+ export interface Handoff {
30
+ claims: HandoffClaims;
31
+ signature: string;
32
+ }
33
+ export interface HandoffReceipt {
34
+ v: 1;
35
+ kid: string;
36
+ nonce: string;
37
+ scopeId: string;
38
+ artifactId: string;
39
+ jobId: string;
40
+ runId: string;
41
+ attempt: number;
42
+ commitSha: string;
43
+ candidateDigest: string;
44
+ releaseId: string;
45
+ manifestDigest: string;
46
+ committedAt: number;
47
+ signature: string;
48
+ }
49
+ export declare const signed: (tag: string, body: object, key: KeyObject) => string;
50
+ export declare function valid(tag: string, body: object, signature: unknown, key: KeyObject | undefined): boolean;
51
+ export declare const record: (value: unknown) => value is Record<string, unknown>;
52
+ export declare const text: (value: unknown) => value is string;
53
+ export declare const count: (value: unknown) => value is number;
54
+ /** Host ledger key: one consumption per job. */
55
+ export declare const jobKey: (c: Pick<HandoffClaims, 'scopeId' | 'artifactId' | 'jobId'>) => string;
56
+ export declare function sealHandoff(input: HandoffInput, signer: SigningKey, now: number): Handoff;
57
+ /** Builder side: the receipt is signed by a known host key (by its kid) and binds this exact handoff. */
58
+ export declare function verifyReceipt(receipt: HandoffReceipt, receiptKeys: KeyResolver, expected: HandoffClaims): void;
59
+ /** Host side (module-internal, not re-exported by the subpath). */
60
+ export declare const handoffAuthentic: (handoff: Handoff, builderKeys: KeyResolver) => boolean;
61
+ /** Mandatory A-LIVE §8.4 evidence join, and a nonce derived from these exact claims. */
62
+ export declare function handoffEvidence(c: HandoffClaims): boolean;
63
+ export declare function signReceipt(body: Omit<HandoffReceipt, 'signature'>, signer: SigningKey): HandoffReceipt;
@@ -0,0 +1,66 @@
1
+ import { createHash, sign, verify } from 'node:crypto';
2
+ import { LiveHostError } from './errors.js';
3
+ import { assertSigner, ed25519, liveKeyId } from './keys.js';
4
+ /** A-LIVE §8.4 two-step SG4b handoff. Step 1: the trusted builder seals the candidate into a single-use Ed25519
5
+ * authorization. Step 2: the host verifies it, commits release/index/receipt/baseline in ONE transaction and signs a
6
+ * receipt. No private key or publication credential enters a worker pod. */
7
+ export const HANDOFF_LIFETIME_MS = 600_000;
8
+ const encode = (value) => Array.isArray(value) ? `[${value.map(encode).join(',')}]`
9
+ : value !== null && typeof value === 'object'
10
+ ? `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${encode(value[key])}`).join(',')}}`
11
+ : JSON.stringify(value);
12
+ /** Sorted-key JSON of the JSON-normalized value, so the signed bytes survive a JSON round trip. */
13
+ const canonical = (value) => encode(JSON.parse(JSON.stringify(value)));
14
+ const sha = (data) => createHash('sha256').update(data).digest('hex');
15
+ const HANDOFF_TAG = 'sentropic.sg4b.handoff.v1\n';
16
+ const RECEIPT_TAG = 'sentropic.sg4b.receipt.v1\n';
17
+ export const signed = (tag, body, key) => sign(null, Buffer.from(tag + canonical(body)), key).toString('base64url');
18
+ export function valid(tag, body, signature, key) {
19
+ try {
20
+ return ed25519(key, 'public') && typeof signature === 'string'
21
+ && verify(null, Buffer.from(tag + canonical(body)), key, Buffer.from(signature, 'base64url'));
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ export const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
28
+ export const text = (value) => typeof value === 'string' && value.length > 0;
29
+ export const count = (value) => Number.isSafeInteger(value) && value >= 1;
30
+ /** Deterministic: a resend for the same attempt reuses the nonce, even under a rotated key, and reads the committed receipt. */
31
+ const nonceOf = (c) => sha(canonical([c.scopeId, c.artifactId, c.jobId, c.runId, c.attempt, c.generation, c.commitSha, c.candidateDigest]));
32
+ /** Host ledger key: one consumption per job. */
33
+ export const jobKey = (c) => sha(canonical([c.scopeId, c.artifactId, c.jobId]));
34
+ export function sealHandoff(input, signer, now) {
35
+ assertSigner(signer);
36
+ const claims = { v: 1, kid: signer.kid, ...input, nonce: nonceOf(input), sealedAt: now, expiresAt: now + HANDOFF_LIFETIME_MS };
37
+ return { claims, signature: signed(HANDOFF_TAG, claims, signer.key) };
38
+ }
39
+ const RECEIPT_FIELDS = ['nonce', 'scopeId', 'artifactId', 'jobId', 'runId', 'attempt', 'commitSha', 'candidateDigest'];
40
+ /** Builder side: the receipt is signed by a known host key (by its kid) and binds this exact handoff. */
41
+ export function verifyReceipt(receipt, receiptKeys, expected) {
42
+ if (!record(receipt) || !liveKeyId(receipt.kid))
43
+ throw new LiveHostError('receipt_invalid');
44
+ const { signature, ...body } = receipt;
45
+ if (!valid(RECEIPT_TAG, body, signature, receiptKeys(receipt.kid)) || receipt.v !== 1 || !text(receipt.releaseId)
46
+ || !text(receipt.manifestDigest) || !Number.isSafeInteger(receipt.committedAt)
47
+ || RECEIPT_FIELDS.some(field => receipt[field] !== expected[field]))
48
+ throw new LiveHostError('receipt_invalid');
49
+ }
50
+ /** Host side (module-internal, not re-exported by the subpath). */
51
+ export const handoffAuthentic = (handoff, builderKeys) => record(handoff) && record(handoff.claims)
52
+ && handoff.claims.v === 1 && liveKeyId(handoff.claims.kid)
53
+ && valid(HANDOFF_TAG, handoff.claims, handoff.signature, builderKeys(handoff.claims.kid));
54
+ const TUPLE = ['commitSha', 'treeSha', 'lockfileDigest', 'descriptorDigest', 'builderImageDigest', 'nodeVersion', 'npmVersion'];
55
+ const TEXT = ['scopeId', 'artifactId', 'jobId', 'runId', 'commitSha', 'treeSha', 'candidateDigest'];
56
+ /** Mandatory A-LIVE §8.4 evidence join, and a nonce derived from these exact claims. */
57
+ export function handoffEvidence(c) {
58
+ const tuple = c.tuple;
59
+ return TEXT.every(field => text(c[field])) && count(c.attempt) && count(c.generation) && (c.kind === 'explicit' || c.kind === 'idle')
60
+ && (c.expectedReleaseId === null || text(c.expectedReleaseId)) && Number.isSafeInteger(c.sealedAt) && Number.isSafeInteger(c.expiresAt)
61
+ && c.nonce === nonceOf(c) && record(tuple) && TUPLE.every(field => text(tuple[field])) && record(tuple.publicEnvHashes)
62
+ && Object.values(tuple.publicEnvHashes).every(text) && tuple.commitSha === c.commitSha && tuple.treeSha === c.treeSha;
63
+ }
64
+ export function signReceipt(body, signer) {
65
+ return { ...body, signature: signed(RECEIPT_TAG, body, signer.key) };
66
+ }
@@ -0,0 +1,10 @@
1
+ /** `@sentropic/artifacts/live-host`: the single home of the code the live host runs or verifies (A-LIVE v2 §8).
2
+ * api, artifact-content and the content host (immo) import it; none re-implements a digest, a signature or a recheck. */
3
+ export { CANDIDATE_DIGEST_TAG, CANDIDATE_LIMITS, candidateDigest, candidatePath, type CandidateFile } from './candidate.js';
4
+ export { LIVE_HOST_ERROR_CODES, LiveHostError, type LiveHostErrorCode } from './errors.js';
5
+ export { LIVE_KEY_ID, liveKeyId, type KeyResolver, type SigningKey } from './keys.js';
6
+ export { HANDOFF_LIFETIME_MS, jobKey, sealHandoff, verifyReceipt, type Handoff, type HandoffClaims, type HandoffInput, type HandoffReceipt, } from './handoff.js';
7
+ export { publicationRecheck, RECHECK_REFUSALS, resolvePendingJob, type AttemptFence, type HostJob, type HostRecheckView, type RecheckRefusal, } from './recheck.js';
8
+ export { acceptHandoff, type AcceptOptions, type HostLedger } from './accept.js';
9
+ export { encodeHandoffRequest, HOST_BUILD_PATHS, JOB_REQUEST_LIFETIME_MS, parseHandoffRequest, refusalFrom, refusalOf, sealJobRequest, verifyJobRequest, type HostBuildRefusal, type HostCandidateFile, type HostHandoffRequest, type HostHandoffResponse, type HostJobClaims, type HostJobRequest, type HostJobResponse, } from './api.js';
10
+ export { ASSERTION_HEADER, CONTROL_HEADER, FENCE_HEADER, MAX_ASSERTION_SECONDS, MAX_CONTROL_SECONDS, MAX_SKEW_SECONDS, MAX_SOURCE_REVISION_LENGTH, MIN_KEY_BYTES, signLiveAssertion, signLiveControl, signLiveFence, verifyLiveAssertion, verifyLiveControl, verifyLiveFence, type LiveAssertionClaims, type LiveControlClaims, type LiveFenceClaims, type VerifyOptions, } from './live-format.js';