@sentropic/artifacts 0.2.20 → 0.2.22

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 (39) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/adapters/postgres-live.js +41 -0
  3. package/dist/git-tool-definitions.d.ts +168 -1
  4. package/dist/git-tool-definitions.js +11 -1
  5. package/dist/http.js +3 -2
  6. package/dist/mcp-core.d.ts +3 -3
  7. package/dist/mcp-core.js +5 -1
  8. package/dist/profile/contracts.d.ts +1 -1
  9. package/dist/profile/contracts.js +3 -0
  10. package/dist/profile/index.js +4 -2
  11. package/dist/profile/schemas.js +3 -0
  12. package/dist/profile/validation.js +2 -1
  13. package/dist/server/build-contract.d.ts +15 -1
  14. package/dist/server/build-contract.js +14 -5
  15. package/dist/server/build-dependencies.d.ts +12 -1
  16. package/dist/server/build-dependencies.js +41 -13
  17. package/dist/server/build-integrity.d.ts +48 -0
  18. package/dist/server/build-integrity.js +70 -0
  19. package/dist/server/build-output.d.ts +22 -0
  20. package/dist/server/build-output.js +40 -0
  21. package/dist/server/build-receipt.d.ts +51 -0
  22. package/dist/server/build-receipt.js +76 -0
  23. package/dist/server/failures.d.ts +2 -2
  24. package/dist/server/failures.js +1 -1
  25. package/dist/server/live-contracts.d.ts +37 -0
  26. package/dist/server/live-invitation-state.d.ts +9 -0
  27. package/dist/server/live-invitation-state.js +44 -0
  28. package/dist/server/live-invitations.d.ts +5 -0
  29. package/dist/server/live-invitations.js +178 -0
  30. package/dist/server/live-mutations.d.ts +1 -1
  31. package/dist/server/live-mutations.js +3 -2
  32. package/dist/server/live-read.d.ts +1 -1
  33. package/dist/server/live-read.js +2 -1
  34. package/dist/server/live-service.d.ts +5 -2
  35. package/dist/server/live-service.js +11 -1
  36. package/dist/server/live-store.d.ts +29 -1
  37. package/dist/server/live-store.js +36 -0
  38. package/migrations/0013_live_invitations.sql +101 -0
  39. package/package.json +1 -1
@@ -1,7 +1,9 @@
1
1
  import { ArtifactOperationError } from './failures.js';
2
2
  import { buildJson, buildPath, buildRecord } from './build-contract.js';
3
+ import { dependencyIntegrity } from './build-integrity.js';
3
4
  const sections = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'];
4
5
  function refuse() { throw new ArtifactOperationError('dep_outside_lock'); }
6
+ const SEMVER = /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?(?:\+[A-Za-z0-9.-]+)?$/;
5
7
  function registryUrl(value, registries) {
6
8
  if (typeof value !== 'string')
7
9
  return false;
@@ -25,7 +27,7 @@ function registrySpec(value) {
25
27
  return /^[A-Za-z0-9~^*<>=| .+-]+$/.test(alias ? alias[1] : value);
26
28
  }
27
29
  /** Validate the lock-indexed install closure, including host-owned lifecycle permissions. */
28
- export function validateBuildDependencies(snapshot, lock, installDirectory) {
30
+ export function validateBuildDependencies(snapshot, lock, installDirectory, lockfileDigest) {
29
31
  if ((lock.lockfileVersion !== 2 && lock.lockfileVersion !== 3) || !buildRecord(lock.packages)
30
32
  || !buildRecord(lock.packages['']))
31
33
  throw new ArtifactOperationError('build_descriptor_invalid');
@@ -42,7 +44,10 @@ export function validateBuildDependencies(snapshot, lock, installDirectory) {
42
44
  };
43
45
  const registries = snapshot.allowedRegistries ?? ['https://registry.npmjs.org/'];
44
46
  const allowlist = snapshot.postinstallAllowlist ?? [];
47
+ const qualified = snapshot.scriptQualification ?? [];
45
48
  const postinstall = [];
49
+ const scriptQualification = [];
50
+ const lockName = (path, raw) => typeof raw.name === 'string' ? raw.name : path.split('node_modules/').at(-1);
46
51
  const repositoryPath = (path) => installDirectory ? `${installDirectory}/${path}` : path;
47
52
  const workspaceTargets = new Set();
48
53
  for (const [path, raw] of Object.entries(packages)) {
@@ -60,18 +65,33 @@ export function validateBuildDependencies(snapshot, lock, installDirectory) {
60
65
  refuse();
61
66
  }
62
67
  }
68
+ const remote = [];
69
+ for (const [path, raw] of Object.entries(packages)) {
70
+ if (!buildRecord(raw) || raw.link === true || path === '' || workspaceTargets.has(path))
71
+ continue;
72
+ const name = lockName(path, raw);
73
+ if ((raw.resolved !== undefined && !registryUrl(raw.resolved, registries)) || typeof name !== 'string'
74
+ || typeof raw.version !== 'string' || !SEMVER.test(raw.version))
75
+ refuse();
76
+ remote.push({ path, name, version: raw.version, resolved: raw.resolved, integrity: raw.integrity });
77
+ }
78
+ // Every remote byte sequence is covered before any dependency or script rule admits the lock.
79
+ const integrity = dependencyIntegrity(remote, lockfileDigest, snapshot.integrityMap, value => registryUrl(value, registries));
80
+ const evidence = new Map(integrity.entries.map(entry => [entry.path, entry]));
63
81
  for (const [path, raw] of Object.entries(packages)) {
64
82
  if (!buildRecord(raw))
65
83
  refuse();
66
84
  if (raw.link === true)
67
85
  continue;
68
86
  const local = path === '' || workspaceTargets.has(path);
69
- if (!local && (!registryUrl(raw.resolved, registries) || typeof raw.version !== 'string'
70
- || !/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?(?:\+[A-Za-z0-9.-]+)?$/.test(raw.version)
71
- || typeof raw.integrity !== 'string' || !raw.integrity))
72
- refuse();
73
87
  const manifestPath = repositoryPath(path ? `${path}/package.json` : 'package.json');
74
88
  const manifest = local ? buildJson(snapshot.files[manifestPath]) : raw;
89
+ // Bundled dependencies ship inside the locked tarball, whose verified integrity covers their bytes.
90
+ const bundle = local ? undefined : raw.bundleDependencies;
91
+ if (bundle !== undefined && bundle !== true
92
+ && (!Array.isArray(bundle) || bundle.some(name => typeof name !== 'string')))
93
+ refuse();
94
+ const bundled = (name) => bundle === true || (Array.isArray(bundle) && bundle.includes(name));
75
95
  for (const source of [raw, manifest]) {
76
96
  for (const section of sections) {
77
97
  const dependencies = source[section];
@@ -83,7 +103,7 @@ export function validateBuildDependencies(snapshot, lock, installDirectory) {
83
103
  if (!registrySpec(spec) || !/^(?:@[A-Za-z0-9._-]+\/)?[A-Za-z0-9._-]+$/.test(name))
84
104
  refuse();
85
105
  if ((section === 'dependencies' || (local && section === 'devDependencies'))
86
- && !lockedPackage(path, name))
106
+ && !(section === 'dependencies' && bundled(name)) && !lockedPackage(path, name))
87
107
  refuse();
88
108
  }
89
109
  }
@@ -106,17 +126,25 @@ export function validateBuildDependencies(snapshot, lock, installDirectory) {
106
126
  || ['preinstall', 'install', 'postinstall', 'prepare'].some(name => Object.hasOwn(scripts, name));
107
127
  if (!hasScript)
108
128
  continue;
109
- const name = typeof raw.name === 'string' ? raw.name : path.split('node_modules/').at(-1);
110
- const entry = { package: local ? manifest.name : name, version: raw.version, integrity: raw.integrity };
111
- if (typeof entry.package !== 'string' || typeof entry.version !== 'string' || typeof entry.integrity !== 'string'
112
- || !entry.integrity || !allowlist.some(allowed => allowed.package === entry.package
113
- && allowed.version === entry.version && allowed.integrity === entry.integrity)) {
129
+ // Only a literal lockfile SRI can close the exact G0 triple; a host-map value never qualifies (A-LIVE §7.3).
130
+ const record = evidence.get(path);
131
+ const entry = { package: local ? manifest.name : lockName(path, raw), version: raw.version,
132
+ integrity: record?.source === 'lockfile' ? record.integrity : undefined };
133
+ if (typeof entry.package !== 'string' || typeof entry.version !== 'string' || entry.integrity === undefined) {
114
134
  throw new ArtifactOperationError('install_script_not_allowlisted');
115
135
  }
116
- postinstall.push({ package: entry.package, version: entry.version, integrity: entry.integrity });
136
+ const triple = { package: entry.package, version: entry.version, integrity: entry.integrity };
137
+ const same = (row) => row.package === triple.package
138
+ && row.version === triple.version && row.integrity === triple.integrity;
139
+ const execution = allowlist.some(same) ? 'allowlisted' : qualified.some(same) ? 'disabled' : undefined;
140
+ if (execution === undefined)
141
+ throw new ArtifactOperationError('install_script_not_allowlisted');
142
+ if (execution === 'allowlisted')
143
+ postinstall.push(triple);
144
+ scriptQualification.push({ ...triple, source: 'lockfile', execution });
117
145
  }
118
146
  const scriptKey = snapshot.subPath.slice(installDirectory ? installDirectory.length + 1 : 0);
119
147
  if (scriptKey && !workspaceTargets.has(scriptKey))
120
148
  refuse();
121
- return postinstall;
149
+ return { postinstall, scriptQualification, integrity };
122
150
  }
@@ -0,0 +1,48 @@
1
+ /** A-LIVE §7.2: host-sealed value for one lock entry; never supplied by the branch or the cache. */
2
+ export interface HostIntegrityMapEntry {
3
+ readonly path: string;
4
+ readonly name: string;
5
+ readonly version: string;
6
+ readonly registryUrl: string;
7
+ readonly integrity: string;
8
+ }
9
+ /** Immutable host map tied to the exact lock bytes; the host authenticates its seal before use. */
10
+ export interface HostIntegrityMap {
11
+ readonly lockfileDigest: string;
12
+ readonly entries: readonly HostIntegrityMapEntry[];
13
+ }
14
+ /** Remote lock entry fields the coverage rule reads; `resolved` is already an approved URL. */
15
+ export interface RemoteLockEntry {
16
+ readonly path: string;
17
+ readonly name: string;
18
+ readonly version: string;
19
+ readonly resolved?: string;
20
+ readonly integrity?: unknown;
21
+ }
22
+ export interface DependencyIntegrityRecord {
23
+ readonly path: string;
24
+ readonly name: string;
25
+ readonly version: string;
26
+ readonly registryUrl: string;
27
+ readonly integrity: string;
28
+ readonly source: 'lockfile' | 'host_map';
29
+ }
30
+ /** Complete remote-package inventory; `mapDigest` binds the approved map into cache and build receipts. */
31
+ export interface DependencyIntegrityInventory {
32
+ readonly mapDigest: string | null;
33
+ readonly lockfileSri: number;
34
+ readonly hostMap: number;
35
+ readonly entries: readonly DependencyIntegrityRecord[];
36
+ }
37
+ export declare const sha256Hex: (text: string) => string;
38
+ /** SHA-256 of the exact lockfile text read at the pinned commit. */
39
+ export declare const lockfileSha256: (lockText: string) => string;
40
+ /** npm SRI carrying at least one SHA-256-or-stronger digest; SHA-1-only or malformed values never qualify. */
41
+ export declare function approvedIntegrity(value: unknown): value is string;
42
+ /** Canonical map digest: entries ordered by path, fixed field order. */
43
+ export declare function hostIntegrityMapDigest(map: HostIntegrityMap): string;
44
+ /**
45
+ * Cover every remote lock entry by literal lockfile SRI or the sealed host map, before any fetch.
46
+ * No trust on first use, no reuse across versions or paths, no SHA-1-only pin, no contradicting value.
47
+ */
48
+ export declare function dependencyIntegrity(remote: readonly RemoteLockEntry[], lockfileDigest: string, map: HostIntegrityMap | undefined, approvedRegistryUrl: (url: unknown) => boolean): DependencyIntegrityInventory;
@@ -0,0 +1,70 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { ArtifactOperationError } from './failures.js';
3
+ export const sha256Hex = (text) => createHash('sha256').update(text, 'utf8').digest('hex');
4
+ /** SHA-256 of the exact lockfile text read at the pinned commit. */
5
+ export const lockfileSha256 = (lockText) => sha256Hex(lockText);
6
+ const SRI_BYTES = { sha256: 32, sha384: 48, sha512: 64 };
7
+ /** npm SRI carrying at least one SHA-256-or-stronger digest; SHA-1-only or malformed values never qualify. */
8
+ export function approvedIntegrity(value) {
9
+ if (typeof value !== 'string' || value.length > 1024)
10
+ return false;
11
+ let strong = false;
12
+ for (const token of value.split(' ')) {
13
+ const match = /^(sha1|sha256|sha384|sha512)-([A-Za-z0-9+/]+={0,2})$/.exec(token);
14
+ if (!match)
15
+ return false;
16
+ const bytes = SRI_BYTES[match[1]];
17
+ if (bytes === undefined)
18
+ continue;
19
+ if (match[2].length !== Math.ceil(bytes / 3) * 4 || Buffer.from(match[2], 'base64').length !== bytes)
20
+ return false;
21
+ strong = true;
22
+ }
23
+ return strong;
24
+ }
25
+ /** Canonical map digest: entries ordered by path, fixed field order. */
26
+ export function hostIntegrityMapDigest(map) {
27
+ const rows = map.entries.map(entry => [entry.path, entry.name, entry.version, entry.registryUrl, entry.integrity]);
28
+ rows.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
29
+ return sha256Hex(JSON.stringify(['sentropic.integrity-map/v1', map.lockfileDigest, rows]));
30
+ }
31
+ /**
32
+ * Cover every remote lock entry by literal lockfile SRI or the sealed host map, before any fetch.
33
+ * No trust on first use, no reuse across versions or paths, no SHA-1-only pin, no contradicting value.
34
+ */
35
+ export function dependencyIntegrity(remote, lockfileDigest, map, approvedRegistryUrl) {
36
+ const mismatch = () => { throw new ArtifactOperationError('dependency_integrity_mismatch'); };
37
+ const mapped = new Map();
38
+ if (map !== undefined) {
39
+ if (map?.lockfileDigest !== lockfileDigest || !Array.isArray(map.entries))
40
+ mismatch();
41
+ const locked = new Map(remote.map(entry => [entry.path, entry]));
42
+ for (const entry of map.entries) {
43
+ const lock = locked.get(entry?.path);
44
+ if (lock === undefined || mapped.has(entry.path) || entry.name !== lock.name || entry.version !== lock.version
45
+ || !approvedRegistryUrl(entry.registryUrl) || !approvedIntegrity(entry.integrity)
46
+ || (lock.resolved !== undefined && lock.resolved !== entry.registryUrl)
47
+ || (approvedIntegrity(lock.integrity) && lock.integrity !== entry.integrity))
48
+ mismatch();
49
+ mapped.set(entry.path, entry);
50
+ }
51
+ }
52
+ const entries = remote.map((lock) => {
53
+ const host = mapped.get(lock.path);
54
+ const literal = approvedIntegrity(lock.integrity) ? lock.integrity : undefined;
55
+ if (literal === undefined && host === undefined)
56
+ throw new ArtifactOperationError('dependency_integrity_missing');
57
+ const registryUrl = lock.resolved ?? host?.registryUrl;
58
+ // A literal pin without a locked URL names no approved registry location.
59
+ if (registryUrl === undefined)
60
+ throw new ArtifactOperationError('dep_outside_lock');
61
+ const base = { path: lock.path, name: lock.name, version: lock.version, registryUrl };
62
+ return literal !== undefined ? { ...base, integrity: literal, source: 'lockfile' }
63
+ : { ...base, integrity: host.integrity, source: 'host_map' };
64
+ });
65
+ const lockfileSri = entries.filter(entry => entry.source === 'lockfile').length;
66
+ return {
67
+ mapDigest: map === undefined ? null : hostIntegrityMapDigest(map),
68
+ lockfileSri, hostMap: entries.length - lockfileSri, entries,
69
+ };
70
+ }
@@ -0,0 +1,22 @@
1
+ import { type PublicationLimits } from './publication-limits.js';
2
+ /** One entry of the stable output snapshot, relative to the descriptor outputDir; directories are implicit. */
3
+ export interface BuildOutputEntry {
4
+ readonly path: string;
5
+ readonly kind: 'file' | 'symlink' | 'other';
6
+ readonly bytes: number;
7
+ }
8
+ export interface AdmittedOutputFile {
9
+ readonly path: string;
10
+ readonly bytes: number;
11
+ readonly mimeType: string;
12
+ }
13
+ /**
14
+ * A-LIVE §8.3 / G0 §4.1 pre-flight on the supervisor's inventory, after build processes ended and before
15
+ * hashing or upload: regular files only, canonical unique paths, a mapped MIME type, the descriptor entry
16
+ * present, and the stricter of profile and server ceilings (255 files, 16 MiB per file, 64 MiB in total).
17
+ * Structural faults are verification_failed; ceiling overflow is dist_over_limits; nothing is uploaded.
18
+ */
19
+ export declare function validateBuildOutput(entries: readonly BuildOutputEntry[], options?: {
20
+ entry?: string;
21
+ limits?: Partial<PublicationLimits>;
22
+ }): readonly AdmittedOutputFile[];
@@ -0,0 +1,40 @@
1
+ import { ArtifactOperationError } from './failures.js';
2
+ import { isWithinMimeCeiling, mimeTypeForPath } from './mime.js';
3
+ import { publicationLimits } from './publication-limits.js';
4
+ const outputPath = (value) => typeof value === 'string' && Buffer.byteLength(value) <= 1024
5
+ && !/[\\%?#:\u0000-\u001f\u007f]/.test(value) && value.split('/').every(part => part !== '' && part !== '.' && part !== '..');
6
+ /**
7
+ * A-LIVE §8.3 / G0 §4.1 pre-flight on the supervisor's inventory, after build processes ended and before
8
+ * hashing or upload: regular files only, canonical unique paths, a mapped MIME type, the descriptor entry
9
+ * present, and the stricter of profile and server ceilings (255 files, 16 MiB per file, 64 MiB in total).
10
+ * Structural faults are verification_failed; ceiling overflow is dist_over_limits; nothing is uploaded.
11
+ */
12
+ export function validateBuildOutput(entries, options = {}) {
13
+ const limits = publicationLimits(options.limits);
14
+ const invalid = () => { throw new ArtifactOperationError('verification_failed'); };
15
+ const over = () => { throw new ArtifactOperationError('dist_over_limits'); };
16
+ if (!Array.isArray(entries) || entries.length === 0)
17
+ invalid();
18
+ if (entries.length > limits.maxFiles)
19
+ over();
20
+ const seen = new Set();
21
+ let total = 0;
22
+ const files = entries.map((entry) => {
23
+ if (entry?.kind !== 'file' || !outputPath(entry.path) || seen.has(entry.path)
24
+ || !Number.isSafeInteger(entry.bytes) || entry.bytes < 0)
25
+ invalid();
26
+ seen.add(entry.path);
27
+ const mimeType = mimeTypeForPath(entry.path);
28
+ if (mimeType === undefined || !isWithinMimeCeiling(mimeType))
29
+ return invalid();
30
+ if (entry.bytes > limits.maxFileBytes)
31
+ over();
32
+ total += entry.bytes;
33
+ if (total > limits.maxTotalBytes)
34
+ over();
35
+ return { path: entry.path, bytes: entry.bytes, mimeType };
36
+ });
37
+ if (options.entry !== undefined && !seen.has(options.entry))
38
+ invalid();
39
+ return files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
40
+ }
@@ -0,0 +1,51 @@
1
+ /** One candidate output file as hashed by the trusted supervisor from the stable output snapshot. */
2
+ export interface CandidateFileDigest {
3
+ readonly path: string;
4
+ readonly bytes: number;
5
+ readonly sha256: string;
6
+ }
7
+ /**
8
+ * A-LIVE §8.4 builder-attested evidence, sealed outside repository code. Every field is mandatory;
9
+ * unknown fields are additive and ignored. releaseId/manifestDigest stay null until publication.
10
+ */
11
+ export interface BuilderAttestedEvidence {
12
+ readonly storageScopeId: string;
13
+ readonly artifactId: string;
14
+ readonly bindingGeneration: number;
15
+ readonly jobId: string;
16
+ readonly runId: string;
17
+ readonly attempt: number;
18
+ readonly commitSha: string;
19
+ readonly treeSha: string;
20
+ readonly descriptorDigest: string;
21
+ readonly lockfileDigest: string;
22
+ /** Digest of the integrity-map/cache receipt that admitted the dependency closure. */
23
+ readonly integrityReceiptDigest: string;
24
+ readonly builderImageDigest: string;
25
+ readonly platform: string;
26
+ readonly nodeVersion: string;
27
+ readonly npmVersion: string;
28
+ readonly publicEnvHashes: Readonly<Record<string, string>>;
29
+ readonly stagingPolicy: string;
30
+ readonly stagingDigest: string;
31
+ readonly candidateDigest: string;
32
+ readonly candidateFiles: readonly CandidateFileDigest[];
33
+ readonly releaseId: string | null;
34
+ readonly manifestDigest: string | null;
35
+ }
36
+ /** Server-resolved job, sealed handoff and admitted inputs the evidence must join exactly. */
37
+ export type BuilderReceiptExpectation = Pick<BuilderAttestedEvidence, typeof JOINS[number][0]>;
38
+ /** Closed `git_build_job_mismatch` reasons; no foreign job, scope or digest value is disclosed. */
39
+ export type BuilderReceiptMismatch = 'scope' | 'job' | 'source' | 'inputs' | 'candidate';
40
+ declare const JOINS: readonly [readonly ["storageScopeId", "scope"], readonly ["artifactId", "scope"], readonly ["bindingGeneration", "scope"], readonly ["jobId", "job"], readonly ["runId", "job"], readonly ["attempt", "job"], readonly ["commitSha", "source"], readonly ["treeSha", "source"], readonly ["descriptorDigest", "inputs"], readonly ["lockfileDigest", "inputs"], readonly ["integrityReceiptDigest", "inputs"], readonly ["builderImageDigest", "inputs"], readonly ["platform", "inputs"], readonly ["publicEnvHashes", "inputs"], readonly ["stagingPolicy", "inputs"], readonly ["stagingDigest", "inputs"], readonly ["candidateDigest", "candidate"]];
41
+ /** Canonical candidate manifest digest over every file (path, size, SHA-256); file order is irrelevant. */
42
+ export declare function candidateInventoryDigest(files: readonly CandidateFileDigest[]): string;
43
+ /**
44
+ * Pure verdict (BR-82 pattern, G0 §4.3): mandatory schema, candidate digest recomputed from the complete
45
+ * file inventory, then the exact join against server evidence. Authentication, single use and expiry of
46
+ * the supervisor handoff belong to the SG4b handoff, not to this function.
47
+ */
48
+ export declare function verifyBuilderReceipt(evidence: unknown, expected: BuilderReceiptExpectation): BuilderAttestedEvidence;
49
+ /** Anti-repack: the re-read uploaded bytes must hash to the sealed candidate digest. */
50
+ export declare function verifyServedCandidate(evidence: BuilderAttestedEvidence, served: readonly CandidateFileDigest[]): void;
51
+ export {};
@@ -0,0 +1,76 @@
1
+ import { sha256Hex } from './build-integrity.js';
2
+ import { ArtifactOperationError } from './failures.js';
3
+ import { isGitSha } from './git-port-policy.js';
4
+ import { SERVER_MAX_FILES_PER_RELEASE, SERVER_MAX_FILE_BYTES } from './publication-limits.js';
5
+ const JOINS = [
6
+ ['storageScopeId', 'scope'], ['artifactId', 'scope'], ['bindingGeneration', 'scope'],
7
+ ['jobId', 'job'], ['runId', 'job'], ['attempt', 'job'], ['commitSha', 'source'], ['treeSha', 'source'],
8
+ ['descriptorDigest', 'inputs'], ['lockfileDigest', 'inputs'], ['integrityReceiptDigest', 'inputs'],
9
+ ['builderImageDigest', 'inputs'], ['platform', 'inputs'], ['publicEnvHashes', 'inputs'],
10
+ ['stagingPolicy', 'inputs'], ['stagingDigest', 'inputs'], ['candidateDigest', 'candidate'],
11
+ ];
12
+ const HEX = /^[a-f0-9]{64}$/;
13
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
14
+ const VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
15
+ const id = (value) => typeof value === 'string' && value.length > 0 && value.length <= 256
16
+ && value.trim() === value && !/[\u0000-\u001f\u007f]/.test(value);
17
+ const count = (value, min) => Number.isSafeInteger(value) && value >= min;
18
+ const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
19
+ const path = (value) => typeof value === 'string' && Buffer.byteLength(value) <= 1024
20
+ && !/[\\%?#:\u0000-\u001f\u007f]/.test(value) && value.split('/').every(part => part !== '' && part !== '.' && part !== '..');
21
+ const canonicalEnv = (hashes) => JSON.stringify(Object.entries(hashes).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
22
+ /** Canonical candidate manifest digest over every file (path, size, SHA-256); file order is irrelevant. */
23
+ export function candidateInventoryDigest(files) {
24
+ const rows = files.map(file => [file.path, file.bytes, file.sha256]);
25
+ rows.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
26
+ return sha256Hex(JSON.stringify(['sentropic.build-candidate/v1', rows]));
27
+ }
28
+ function schema(value) {
29
+ if (!record(value))
30
+ return false;
31
+ const files = value.candidateFiles;
32
+ const env = value.publicEnvHashes;
33
+ return id(value.storageScopeId) && typeof value.artifactId === 'string' && UUID.test(value.artifactId)
34
+ && count(value.bindingGeneration, 1) && id(value.jobId) && id(value.runId) && count(value.attempt, 1)
35
+ && typeof value.commitSha === 'string' && isGitSha(value.commitSha)
36
+ && typeof value.treeSha === 'string' && isGitSha(value.treeSha)
37
+ && [value.descriptorDigest, value.lockfileDigest, value.integrityReceiptDigest, value.stagingDigest,
38
+ value.candidateDigest].every(digest => typeof digest === 'string' && HEX.test(digest))
39
+ && typeof value.builderImageDigest === 'string' && /^sha256:[a-f0-9]{64}$/.test(value.builderImageDigest)
40
+ && typeof value.platform === 'string' && /^[a-z0-9]+\/[a-z0-9_]+(?:\/[a-z0-9]+)?$/.test(value.platform)
41
+ && typeof value.nodeVersion === 'string' && VERSION.test(value.nodeVersion)
42
+ && typeof value.npmVersion === 'string' && VERSION.test(value.npmVersion)
43
+ && record(env) && Object.entries(env).every(([name, hash]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(name)
44
+ && typeof hash === 'string' && HEX.test(hash))
45
+ && id(value.stagingPolicy)
46
+ && (value.releaseId === null || (typeof value.releaseId === 'string' && UUID.test(value.releaseId)))
47
+ && (value.manifestDigest === null || (typeof value.manifestDigest === 'string' && HEX.test(value.manifestDigest)))
48
+ && Array.isArray(files) && files.length > 0 && files.length <= SERVER_MAX_FILES_PER_RELEASE
49
+ && new Set(files.map(file => file?.path)).size === files.length
50
+ && files.every(file => record(file) && path(file.path) && count(file.bytes, 0)
51
+ && file.bytes <= SERVER_MAX_FILE_BYTES && typeof file.sha256 === 'string' && HEX.test(file.sha256));
52
+ }
53
+ /**
54
+ * Pure verdict (BR-82 pattern, G0 §4.3): mandatory schema, candidate digest recomputed from the complete
55
+ * file inventory, then the exact join against server evidence. Authentication, single use and expiry of
56
+ * the supervisor handoff belong to the SG4b handoff, not to this function.
57
+ */
58
+ export function verifyBuilderReceipt(evidence, expected) {
59
+ if (!schema(evidence) || candidateInventoryDigest(evidence.candidateFiles) !== evidence.candidateDigest) {
60
+ throw new ArtifactOperationError('verification_failed');
61
+ }
62
+ for (const [key, reason] of JOINS) {
63
+ const same = key === 'publicEnvHashes'
64
+ ? record(expected.publicEnvHashes) && canonicalEnv(evidence.publicEnvHashes) === canonicalEnv(expected.publicEnvHashes)
65
+ : evidence[key] === expected[key];
66
+ if (!same)
67
+ throw new ArtifactOperationError('git_build_job_mismatch', { publicDetails: { reason } });
68
+ }
69
+ return Object.freeze({ ...evidence });
70
+ }
71
+ /** Anti-repack: the re-read uploaded bytes must hash to the sealed candidate digest. */
72
+ export function verifyServedCandidate(evidence, served) {
73
+ if (!Array.isArray(served) || candidateInventoryDigest(served) !== evidence.candidateDigest) {
74
+ throw new ArtifactOperationError('verification_failed');
75
+ }
76
+ }
@@ -5,7 +5,7 @@ export type ArtifactCommitState = 'not_committed' | 'committed' | 'unknown';
5
5
  export type ArtifactInternalKey = string & {
6
6
  readonly __brand: 'internal-key';
7
7
  };
8
- export type ArtifactErrorKind = LiveErrorCode | 'provider_unavailable' | 'command_conflict' | 'pointer_conflict' | 'unauthorized_at_commit' | 'capability_unselected' | 'admission_unavailable' | 'invalid_request' | 'anonymous' | 'access_denied' | 'not_found' | 'gone' | 'release_unavailable' | 'limit_exceeded' | 'unprocessable' | 'verification_failed' | 'edit_mismatch' | 'precondition_required' | 'git_binding_conflict' | 'git_repo_not_registered' | 'git_ref_not_allowed' | 'git_head_moved' | 'git_path_refused' | 'git_branch_missing' | 'build_descriptor_invalid' | 'build_script_missing' | 'lock_missing' | 'dep_outside_lock' | 'install_script_not_allowlisted';
8
+ export type ArtifactErrorKind = LiveErrorCode | 'provider_unavailable' | 'command_conflict' | 'pointer_conflict' | 'unauthorized_at_commit' | 'capability_unselected' | 'admission_unavailable' | 'invalid_request' | 'anonymous' | 'access_denied' | 'not_found' | 'gone' | 'release_unavailable' | 'limit_exceeded' | 'unprocessable' | 'verification_failed' | 'edit_mismatch' | 'precondition_required' | 'git_binding_conflict' | 'git_repo_not_registered' | 'git_ref_not_allowed' | 'git_head_moved' | 'git_path_refused' | 'git_branch_missing' | 'build_descriptor_invalid' | 'build_script_missing' | 'lock_missing' | 'dep_outside_lock' | 'install_script_not_allowlisted' | 'dist_over_limits';
9
9
  /** Optimistic-concurrency payload: the caller re-reads and merges against this. */
10
10
  export interface ArtifactConflictDetails {
11
11
  readonly artifactId?: string;
@@ -49,7 +49,7 @@ export interface ArtifactOperationalFailure extends ArtifactFailureFields {
49
49
  }
50
50
  export interface ArtifactOrdinaryFailure extends Omit<ArtifactFailureFields, 'variant' | 'retriable'> {
51
51
  readonly kind: 'ordinary';
52
- readonly category: 'invalid_request' | 'not_found' | 'gone' | 'release_unavailable' | 'limit_exceeded' | LiveErrorCode | 'unprocessable' | 'verification_failed' | 'edit_mismatch' | 'precondition_required' | 'build_descriptor_invalid' | 'build_script_missing' | 'lock_missing' | 'dep_outside_lock' | 'install_script_not_allowlisted' | 'git_path_refused' | 'git_branch_missing' | 'git_ref_not_allowed' | 'git_repo_not_registered';
52
+ readonly category: 'invalid_request' | 'not_found' | 'gone' | 'release_unavailable' | 'limit_exceeded' | LiveErrorCode | 'unprocessable' | 'verification_failed' | 'edit_mismatch' | 'precondition_required' | 'build_descriptor_invalid' | 'build_script_missing' | 'lock_missing' | 'dep_outside_lock' | 'install_script_not_allowlisted' | 'dist_over_limits' | 'git_path_refused' | 'git_branch_missing' | 'git_ref_not_allowed' | 'git_repo_not_registered';
53
53
  readonly retriable: false;
54
54
  }
55
55
  /** Entry authority outcomes are separate from ordinary and operational failures. */
@@ -32,7 +32,7 @@ const DOMAIN_STATUS = {
32
32
  not_found: 404, gone: 410, release_unavailable: 410, limit_exceeded: 413, unprocessable: 422, verification_failed: 422, edit_mismatch: 422,
33
33
  precondition_required: 428,
34
34
  build_descriptor_invalid: 422, build_script_missing: 422, lock_missing: 422,
35
- dep_outside_lock: 422, install_script_not_allowlisted: 422,
35
+ dep_outside_lock: 422, install_script_not_allowlisted: 422, dist_over_limits: 422,
36
36
  git_path_refused: 422, git_branch_missing: 422, git_ref_not_allowed: 422, git_repo_not_registered: 422,
37
37
  };
38
38
  function field(value, name) {
@@ -2,6 +2,7 @@ import type { GitBinding } from './git-contracts.js';
2
2
  import type { GitPort, GitPortRepository, GitPortTarget } from './git-port.js';
3
3
  import type { LiveKeyPort } from './live-crypto.js';
4
4
  import type { LiveDraftRecord, LiveIdentity, LiveStore, LiveTransaction } from './live-store.js';
5
+ import type { PrincipalDirectoryPort } from './ports.js';
5
6
  export interface LiveInvocation {
6
7
  actorId: string;
7
8
  storageScopeId: string;
@@ -33,6 +34,36 @@ export interface LiveWorkerPort {
33
34
  leaseEpoch: number;
34
35
  }): Promise<void>;
35
36
  }
37
+ export interface LiveInvitationRevoked {
38
+ storageScopeId: string;
39
+ artifactId: string;
40
+ liveSessionId: string;
41
+ bindingGeneration: number;
42
+ invitationId: string;
43
+ epoch: number;
44
+ }
45
+ /** Host invitation port. Invited live readers stay opt-in: `qualified !== true` keeps live owner-only. */
46
+ export interface LiveInvitationPort extends Pick<PrincipalDirectoryPort, 'resolvePrincipal' | 'describePrincipal'> {
47
+ qualified: boolean;
48
+ /** Called once after the revocation commit: close the proxied sockets, then push c1 revoke_invitation.
49
+ * Idempotent; the host retries the push until 204. */
50
+ onRevoked(e: LiveInvitationRevoked): Promise<void>;
51
+ }
52
+ /** The `invitation` object of the reconcile and grant bodies; `expiresAt` is the latest active expiry (ms). */
53
+ export interface LiveInvitationState {
54
+ epoch: number;
55
+ expiresAt: number | null;
56
+ }
57
+ export type LiveViewer = {
58
+ role: 'binding_owner';
59
+ } | {
60
+ role: 'invitee';
61
+ invitation: {
62
+ id: string;
63
+ epoch: number;
64
+ expiresAt: number;
65
+ };
66
+ } | null;
36
67
  export interface LiveServiceDeps {
37
68
  store: LiveStore;
38
69
  keys: LiveKeyPort;
@@ -45,10 +76,16 @@ export interface LiveServiceDeps {
45
76
  commitBytesMax?: number;
46
77
  gitMessageMaxUnits?: number;
47
78
  idempotencyKeyMaxUnits?: number;
79
+ invitations?: LiveInvitationPort;
48
80
  }
49
81
  export interface LiveService {
50
82
  execute(operation: string, args: Record<string, unknown>, invocation: LiveInvocation): Promise<Record<string, any>>;
51
83
  }
84
+ /** Session state exports for the host reconcile, grant and live proxy paths. */
85
+ export interface LiveSessionService extends LiveService {
86
+ liveInvitationState(identity: LiveIdentity): Promise<LiveInvitationState>;
87
+ liveViewer(identity: LiveIdentity, principalId: string): Promise<LiveViewer>;
88
+ }
52
89
  export declare function liveResponse(record: LiveDraftRecord, currentHeadSha: string, now?: number): Record<string, unknown>;
53
90
  export type LiveSessionTransaction = LiveTransaction;
54
91
  export type LiveSnapshot = {
@@ -0,0 +1,9 @@
1
+ import type { LiveServiceDeps, LiveSessionService } from './live-contracts.js';
2
+ import type { LiveDraftRecord, LiveIdentity, LiveInvitationRecord, LiveTransaction } from './live-store.js';
3
+ export declare const isOpenInvitation: (row: LiveInvitationRecord) => boolean;
4
+ /** The session an invitation binds: the binding generation's current runtime, never a stopped (DORMANT) one. */
5
+ export declare const currentLiveSession: (record: LiveDraftRecord | undefined) => string | null;
6
+ /** Projects ceased (other session or generation) and expired invitations; writers persist the transitions. */
7
+ export declare function sweepInvitations(tx: LiveTransaction, identity: LiveIdentity, now: number, persist: boolean): Promise<LiveInvitationRecord[]>;
8
+ /** `liveInvitationState` and `liveViewer` read the committed state; they never write. */
9
+ export declare function liveInvitationViews(deps: LiveServiceDeps): Omit<LiveSessionService, 'execute'>;
@@ -0,0 +1,44 @@
1
+ export const isOpenInvitation = (row) => row.status === 'pending' || row.status === 'active';
2
+ /** The session an invitation binds: the binding generation's current runtime, never a stopped (DORMANT) one. */
3
+ export const currentLiveSession = (record) => record?.runtime && record.runtime.phase !== 'DORMANT' ? record.runtime.liveSessionId : null;
4
+ /** Projects ceased (other session or generation) and expired invitations; writers persist the transitions. */
5
+ export async function sweepInvitations(tx, identity, now, persist) {
6
+ const rows = (await tx.invitations.list()).sort((a, b) => a.createdAt.localeCompare(b.createdAt) ||
7
+ a.invitationId.localeCompare(b.invitationId));
8
+ for (const row of rows) {
9
+ if (!isOpenInvitation(row))
10
+ continue;
11
+ const status = row.bindingGeneration !== identity.bindingGeneration || row.liveSessionId !== currentLiveSession(tx.record)
12
+ ? 'ceased' : Date.parse(row.expiresAt) <= now ? 'expired' : row.status;
13
+ if (status === row.status)
14
+ continue;
15
+ Object.assign(row, { status, rowVersion: row.rowVersion + 1 });
16
+ if (persist)
17
+ await tx.invitations.save(row);
18
+ }
19
+ return rows;
20
+ }
21
+ /** `liveInvitationState` and `liveViewer` read the committed state; they never write. */
22
+ export function liveInvitationViews(deps) {
23
+ const qualified = () => deps.invitations?.qualified === true;
24
+ const read = (identity, empty, action) => deps.store.transaction(identity, async (tx) => {
25
+ const session = currentLiveSession(tx.record);
26
+ if (!session)
27
+ return empty;
28
+ return action(qualified() && tx.invitations ? await sweepInvitations(tx, identity, (deps.now ?? Date.now)(), false) : [], session, tx);
29
+ });
30
+ return {
31
+ liveInvitationState: identity => read(identity, { epoch: 0, expiresAt: null }, async (rows, session, tx) => {
32
+ const active = rows.filter(row => row.liveSessionId === session && row.status === 'active').map(row => Date.parse(row.expiresAt));
33
+ return { epoch: qualified() && tx.invitations ? await tx.invitations.epoch(identity.bindingGeneration, session) : 0,
34
+ expiresAt: active.length ? Math.max(...active) : null };
35
+ }),
36
+ liveViewer: (identity, principalId) => read(identity, null, async (rows, session, tx) => {
37
+ if (principalId === tx.record.runtime.ownerId)
38
+ return { role: 'binding_owner' };
39
+ const row = rows.find(entry => entry.liveSessionId === session && entry.principalId === principalId && entry.status === 'active');
40
+ return row ? { role: 'invitee', invitation: { id: row.invitationId, epoch: row.epoch,
41
+ expiresAt: Date.parse(row.expiresAt) } } : null;
42
+ }),
43
+ };
44
+ }
@@ -0,0 +1,5 @@
1
+ import type { LiveInvocation, LiveServiceDeps } from './live-contracts.js';
2
+ /** Generic live invitations (A-LIVE v2 §8.2, §9; contract 2026-11-07). Viewing only: no edit, publication or release grant. */
3
+ export declare const LIVE_INVITATION_OPERATIONS: readonly ["live_invite", "live_accept_invitation", "live_revoke_invitation", "live_invitations"];
4
+ export declare const LIVE_INVITATIONS_OPEN_MAX = 16;
5
+ export declare function executeLiveInvitation(deps: LiveServiceDeps, operation: string, args: Record<string, any>, invocation: LiveInvocation): Promise<Record<string, any>>;