@runeditrun/rer 0.2.85 → 0.2.87

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 (162) hide show
  1. package/README.md +138 -29
  2. package/cli/README.md +61 -1
  3. package/cli/agent-bindings.mjs +25 -0
  4. package/cli/agent-door.mjs +145 -0
  5. package/cli/agent-fixtures.mjs +16 -0
  6. package/cli/agent-journey-fixtures.mjs +17 -0
  7. package/cli/agent-mail.mjs +54 -0
  8. package/cli/agent-network.mjs +64 -0
  9. package/cli/agent-reviewers.mjs +110 -0
  10. package/cli/agent-rpc.mjs +23 -0
  11. package/cli/agent-secrets.mjs +23 -0
  12. package/cli/agent-sponsors.mjs +43 -0
  13. package/cli/agent-surface.mjs +34 -0
  14. package/cli/agent-verifier.mjs +31 -0
  15. package/cli/agent-webhooks.mjs +19 -0
  16. package/cli/authoring.mjs +2 -1
  17. package/cli/business/archive-task.mjs +32 -0
  18. package/cli/business/carry.mjs +3 -1
  19. package/cli/business/catchup-task.mjs +42 -0
  20. package/cli/business/choices.mjs +97 -0
  21. package/cli/business/command.mjs +23 -5
  22. package/cli/business/connect.mjs +19 -7
  23. package/cli/business/detector.mjs +4 -1
  24. package/cli/business/device.mjs +13 -0
  25. package/cli/business/export-inputs.mjs +69 -0
  26. package/cli/business/export-task.mjs +17 -0
  27. package/cli/business/invocation.mjs +8 -1
  28. package/cli/business/keychain.mjs +8 -1
  29. package/cli/business/lease.mjs +11 -1
  30. package/cli/business/local-commands.mjs +79 -31
  31. package/cli/business/outbound.mjs +9 -4
  32. package/cli/business/parsers-config.mjs +8 -7
  33. package/cli/business/parsers-syntax.mjs +7 -3
  34. package/cli/business/permissions.mjs +2 -0
  35. package/cli/business/questions.mjs +89 -9
  36. package/cli/business/setup-command.mjs +49 -0
  37. package/cli/business/setup-company.json +15 -0
  38. package/cli/business/setup-demo.mjs +95 -0
  39. package/cli/business/state.mjs +44 -10
  40. package/cli/business/supervisor.mjs +94 -35
  41. package/cli/business/vendor-door.mjs +230 -0
  42. package/cli/business/vendors/README.md +29 -3
  43. package/cli/business/vendors/common.mjs +8 -6
  44. package/cli/business/vendors/index.mjs +22 -11
  45. package/cli/business/vendors/sorry.mjs +106 -0
  46. package/cli/contract.mjs +2 -2
  47. package/cli/demo-deploy-error.mjs +14 -0
  48. package/cli/demo-native.mjs +4 -1
  49. package/cli/deploy-config.mjs +1 -1
  50. package/cli/deploy-owner-input.mjs +3 -1
  51. package/cli/deploy-variables.mjs +89 -0
  52. package/cli/door-clauses.mjs +157 -0
  53. package/cli/export.mjs +17 -4
  54. package/cli/hosted-output.mjs +31 -8
  55. package/cli/inspect.mjs +4 -0
  56. package/cli/jsonc.mjs +8 -4
  57. package/cli/lifecycle.mjs +3 -1
  58. package/cli/main.mjs +1 -0
  59. package/cli/managed-data-schema.mjs +14 -1
  60. package/cli/managed-data.mjs +8 -4
  61. package/cli/portability-empty.mjs +6 -0
  62. package/cli/portability-migrations.mjs +26 -4
  63. package/cli/portability-worker.mjs +2 -1
  64. package/cli/portability.mjs +1 -0
  65. package/cli/production-auth.mjs +2 -2
  66. package/cli/production-mail.mjs +19 -3
  67. package/cli/server-registry.mjs +2 -0
  68. package/edition-authoring/archive-source.mjs +65 -0
  69. package/edition-authoring/base-copies.mjs +108 -21
  70. package/edition-authoring/cli.mjs +1 -1
  71. package/edition-authoring/copy-namespaces.mjs +28 -0
  72. package/edition-authoring/edition-migrations.mjs +7 -3
  73. package/edition-authoring/files.mjs +2 -1
  74. package/edition-authoring/module-closure.mjs +58 -27
  75. package/edition-authoring/module-edges.mjs +13 -2
  76. package/edition-authoring/workflow-copies.mjs +1 -1
  77. package/edition-authoring/workflow-scripts.mjs +12 -3
  78. package/foundation/runtime/contract-docs.mjs +220 -32
  79. package/foundation/runtime/contract-prose-patterns.mjs +14 -0
  80. package/foundation/runtime/contract-prose.mjs +88 -0
  81. package/global/CHANGELOG.md +151 -0
  82. package/global/README.md +138 -29
  83. package/global/door/command.mjs +3 -1
  84. package/global/main.mjs +1 -1
  85. package/modules/agent-door/CLAUSES.md +215 -0
  86. package/modules/agent-door/conformance/audit-pages.mjs +11 -0
  87. package/modules/agent-door/conformance/audit-rows.mjs +20 -0
  88. package/modules/agent-door/conformance/audit.mjs +63 -0
  89. package/modules/agent-door/conformance/authority.d.mts +2 -0
  90. package/modules/agent-door/conformance/authority.mjs +17 -0
  91. package/modules/agent-door/conformance/crypto.mjs +36 -0
  92. package/modules/agent-door/conformance/discovery.mjs +61 -0
  93. package/modules/agent-door/conformance/fixtures.mjs +41 -0
  94. package/modules/agent-door/conformance/index.mjs +41 -0
  95. package/modules/agent-door/conformance/injection.mjs +24 -0
  96. package/modules/agent-door/conformance/invocation.mjs +33 -0
  97. package/modules/agent-door/conformance/journey.mjs +117 -0
  98. package/modules/agent-door/conformance/narrowing.d.mts +2 -0
  99. package/modules/agent-door/conformance/narrowing.mjs +29 -0
  100. package/modules/agent-door/conformance/negative.mjs +48 -0
  101. package/modules/agent-door/conformance/network-modules.mjs +86 -0
  102. package/modules/agent-door/conformance/network-runtime.mjs +46 -0
  103. package/modules/agent-door/conformance/policy-phases.mjs +83 -0
  104. package/modules/agent-door/conformance/protocol.mjs +153 -0
  105. package/modules/agent-door/conformance/replay.mjs +39 -0
  106. package/modules/agent-door/conformance/schema.mjs +71 -0
  107. package/modules/agent-door/conformance/security.mjs +34 -0
  108. package/modules/agent-door/conformance/sponsors.mjs +68 -0
  109. package/modules/agent-door/conformance/step-hooks.mjs +4 -0
  110. package/modules/agent-door/conformance/surface.mjs +92 -0
  111. package/modules/agent-door/conformance/target.mjs +19 -0
  112. package/modules/agent-door/conformance/tool-name.d.mts +1 -0
  113. package/modules/agent-door/conformance/tool-name.mjs +7 -0
  114. package/modules/agent-door/conformance/webhooks.mjs +31 -0
  115. package/modules/container/image-variables.mjs +8 -2
  116. package/modules/delivery-producer/mail.mjs +20 -0
  117. package/modules/demo-host/README.md +6 -0
  118. package/modules/demo-host/ownership.mjs +39 -0
  119. package/modules/demo-host/plan.mjs +2 -1
  120. package/modules/demo-host/remove.mjs +6 -1
  121. package/modules/import-kit/schema/importer-verification-receipt.schema.json +171 -0
  122. package/modules/import-kit/schema/importers.schema.json +107 -0
  123. package/modules/import-kit/src/door/ADOPTING.md +20 -0
  124. package/modules/import-kit/src/door/README.md +2 -1
  125. package/modules/import-kit/src/door/admission.ts +5 -3
  126. package/modules/import-kit/src/door/archive.ts +5 -2
  127. package/modules/import-kit/src/door/authority.ts +1 -0
  128. package/modules/import-kit/src/door/grants.ts +1 -1
  129. package/modules/import-kit/src/door/handler.ts +14 -8
  130. package/modules/import-kit/src/door/index.ts +1 -1
  131. package/modules/import-kit/src/door/jobs.ts +40 -0
  132. package/modules/import-kit/src/door/operator.ts +3 -3
  133. package/modules/import-kit/src/door/planning.ts +10 -6
  134. package/modules/import-kit/src/door/protocol.ts +2 -2
  135. package/modules/import-kit/src/door/raw.ts +25 -0
  136. package/modules/import-kit/src/door/refusals.ts +1 -0
  137. package/modules/import-kit/src/door/types.ts +26 -6
  138. package/modules/import-kit/src/receipt/encoding.ts +37 -0
  139. package/modules/import-kit/src/receipt/index.ts +69 -0
  140. package/modules/import-kit/src/receipt/policy.ts +24 -0
  141. package/modules/import-kit/src/receipt/types.ts +64 -0
  142. package/modules/import-kit/src/receipt/uri.ts +45 -0
  143. package/modules/import-kit/src/receipt/validation.ts +87 -0
  144. package/modules/import-kit/src/status/encoding.ts +13 -0
  145. package/modules/import-kit/src/status/evidence.ts +218 -0
  146. package/modules/import-kit/src/status/index.ts +56 -0
  147. package/modules/import-kit/src/status/schema.ts +208 -0
  148. package/modules/import-kit/src/status/types.ts +86 -0
  149. package/modules/operator-auth/accounts/delegated.mjs +48 -0
  150. package/modules/operator-auth/index.d.mts +7 -0
  151. package/modules/operator-auth/service.mjs +2 -0
  152. package/modules/portability/README.md +37 -13
  153. package/modules/portability/bridge.mjs +22 -2
  154. package/modules/portability/catalogue.mjs +12 -2
  155. package/modules/portability/copies.mjs +8 -1
  156. package/modules/portability/derived.mjs +33 -0
  157. package/modules/portability/http-errors.mjs +1 -1
  158. package/modules/portability/import.mjs +14 -7
  159. package/package.json +4 -2
  160. package/scripts/publish-check/copy_identities.py +3 -1
  161. package/scripts/publish-check/github_refs.py +32 -13
  162. package/cli/business/opt-ins.mjs +0 -37
@@ -5,14 +5,30 @@ import type { DoorGrant } from './protocol.ts';
5
5
  import type { ImportDoorIntake } from './intake/types.ts';
6
6
  export type { ImportDoorIntake, IntakeFormat } from './intake/types.ts';
7
7
 
8
- /** One import source: its parser and mapping, and optionally its own owner principal. */
8
+ /** Verified upload custody passed to the seed's archive or binary reader. */
9
+ export interface ImportDoorRawUpload {
10
+ readonly bytes: Uint8Array;
11
+ readonly name: string;
12
+ readonly sha256: string;
13
+ readonly size: number;
14
+ }
15
+ /** One decoded source; existing adapters may keep the mount's format. */
9
16
  export interface ImportDoorSource {
10
17
  mapping: ImportMapping;
11
18
  parse(value: Json, index: number): ParsedRecord | ParsedRecord[];
12
19
  ownerPrincipalId?: string;
20
+ format?: 'json' | 'ndjson';
13
21
  /** Project declared fields before the first persistent byte. Shared by both mounts. */
14
22
  intake?: ImportDoorIntake;
15
23
  }
24
+ export interface ImportDoorRawSource extends Omit<ImportDoorSource, 'format' | 'parse' | 'intake'> {
25
+ format: 'raw';
26
+ /** Bound archive expansion while reading; return inert source records. */
27
+ readRaw(upload: ImportDoorRawUpload, limits: Readonly<Required<ReaderLimits>>): ParsedRecord[] | Promise<ParsedRecord[]>;
28
+ parse?: undefined;
29
+ intake?: undefined;
30
+ }
31
+ export type ImportDoorResolvedSource = ImportDoorSource | ImportDoorRawSource;
16
32
  export interface ImportDoorRuntimeOptions extends ImportDoorSource {
17
33
  database: D1Database;
18
34
  targets: D1TargetAdapter;
@@ -26,6 +42,8 @@ export interface ImportDoorRuntimeOptions extends ImportDoorSource {
26
42
  * 'strict'. Existing jobs always keep the policy they were created with. */
27
43
  reversalPolicy?: D1ReversalPolicy;
28
44
  }
45
+ export type ImportDoorRawRuntimeOptions = Omit<ImportDoorRuntimeOptions, 'format' | 'parse' | 'intake'> & ImportDoorRawSource;
46
+ export type ImportDoorRuntime = ImportDoorRuntimeOptions | ImportDoorRawRuntimeOptions;
29
47
  /** Structurally identical to owner-claim's server-owned trust configuration. */
30
48
  export interface ImportDoorClaimConfig {
31
49
  issuer: string;
@@ -34,7 +52,8 @@ export interface ImportDoorClaimConfig {
34
52
  expectedEmail: string;
35
53
  publicKeys: Record<string, JsonWebKey>;
36
54
  }
37
- interface ImportDoorMountOptions extends Omit<ImportDoorRuntimeOptions, 'parse' | 'mapping'> {
55
+ interface ImportDoorMountOptions extends Omit<ImportDoorRuntimeOptions, 'parse' | 'mapping' | 'format'> {
56
+ format: 'json' | 'ndjson' | 'raw';
38
57
  claim: ImportDoorClaimConfig;
39
58
  /** Permanent door key for settings, lineage and history. Defaults to
40
59
  * `claim.installationId`. Set it to the operator mount's `installationId`
@@ -44,13 +63,13 @@ interface ImportDoorMountOptions extends Omit<ImportDoorRuntimeOptions, 'parse'
44
63
  /** A grant mount takes one source's `parse`/`mapping`, or a `source` resolver
45
64
  * for a seed with several sources. */
46
65
  export type ImportDoorOptions = ImportDoorMountOptions & (
47
- | (Pick<ImportDoorRuntimeOptions, 'parse' | 'mapping'> & { source?: undefined })
66
+ | (ImportDoorResolvedSource & { source?: undefined })
48
67
  | {
49
68
  /** The seed's server-owned allow-list, shared with its owner-session mount.
50
69
  * Called with the verified grant's namespace before any grant row is written;
51
70
  * null refuses the grant with 403 `unknown_import_source`. */
52
- source(namespace: string): ImportDoorSource | null | Promise<ImportDoorSource | null>;
53
- parse?: undefined; mapping?: undefined;
71
+ source(namespace: string): ImportDoorResolvedSource | null | Promise<ImportDoorResolvedSource | null>;
72
+ parse?: undefined; mapping?: undefined; readRaw?: undefined;
54
73
  });
55
74
  export type DoorAccess = Pick<DoorGrant, 'action' | 'installationId' | 'email' | 'namespace'
56
75
  | 'maxBytes' | 'maxChunks' | 'maxRecords' | 'fingerprint' | 'approvalRecordId' | 'approvedAt' | 'catchup'>;
@@ -63,6 +82,7 @@ export interface ImportOperatorOptions extends ImportDoorRuntimeOptions {
63
82
  * Check the seed's normal CSRF policy here as well. Null denies access. */
64
83
  authorize(request: Request, action: DoorAccess['action']): Promise<D1Sql | null>;
65
84
  }
85
+ export type ImportRawOperatorOptions = Omit<ImportOperatorOptions, 'format' | 'parse' | 'intake'> & ImportDoorRawSource;
66
86
  export interface DoorHistoryEntry {
67
87
  planId: string; jobId: string; namespace: string; fingerprint: string; state: string;
68
88
  owner: string; approvedAt: string; approvalRecordId: string; reviewer: string; caption: string;
@@ -90,7 +110,7 @@ export interface DoorPlanRow {
90
110
  complete: number; snapshot_hash: string;
91
111
  }
92
112
  export interface DoorRequest {
93
- options: ImportDoorRuntimeOptions; access: Readonly<DoorAccess>;
113
+ options: ImportDoorRuntime; access: Readonly<DoorAccess>;
94
114
  via: 'grant' | 'operator';
95
115
  authority: D1Sql;
96
116
  /** The destination's erasure journal rows when the request was admitted. */
@@ -0,0 +1,37 @@
1
+ /** Recursive UTF-16 key ordering, JSON scalar escaping, and unchanged array order. */
2
+ export function canonicalReceiptJson(value: unknown): string {
3
+ const active = new WeakSet<object>();
4
+ const visit = (item: unknown): string => {
5
+ if (item === null || typeof item === 'string' || typeof item === 'boolean') return JSON.stringify(item);
6
+ if (typeof item === 'number' && Number.isFinite(item)) return JSON.stringify(item);
7
+ if (typeof item !== 'object' || !item || active.has(item)) throw new TypeError('Receipt must contain finite, acyclic JSON data.');
8
+ active.add(item);
9
+ try {
10
+ if (Array.isArray(item)) return `[${Array.from({ length: item.length }, (_, index) => visit(item[index])).join(',')}]`;
11
+ if (Object.getPrototypeOf(item) !== Object.prototype && Object.getPrototypeOf(item) !== null) {
12
+ throw new TypeError('Receipt objects must be plain JSON objects.');
13
+ }
14
+ const object = item as Record<string, unknown>;
15
+ return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${visit(object[key])}`).join(',')}}`;
16
+ } finally {
17
+ active.delete(item);
18
+ }
19
+ };
20
+ return visit(value);
21
+ }
22
+
23
+ export async function receiptSha256(value: string | Uint8Array): Promise<string> {
24
+ const bytes = typeof value === 'string' ? new TextEncoder().encode(value) : new Uint8Array(value);
25
+ const hash = await crypto.subtle.digest('SHA-256', bytes);
26
+ return Array.from(new Uint8Array(hash), (byte) => byte.toString(16).padStart(2, '0')).join('');
27
+ }
28
+
29
+ export function base64(bytes: Uint8Array): string {
30
+ return btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(''));
31
+ }
32
+
33
+ export function unbase64(value: string): Uint8Array<ArrayBuffer> {
34
+ const bytes = Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
35
+ if (base64(bytes) !== value) throw new TypeError('Expected canonical padded base64.');
36
+ return bytes;
37
+ }
@@ -0,0 +1,69 @@
1
+ import { validateReceiptDocumentSchema } from '../status/schema.ts';
2
+ import { base64, canonicalReceiptJson, unbase64 } from './encoding.ts';
3
+ import { assertReceiptKey, receiptPublicKey } from './policy.ts';
4
+ import { validateReceiptPayload } from './validation.ts';
5
+ import type { ImporterReceiptTrustPolicy, ImporterReceiptVerificationResult, ImporterVerificationReceipt } from './types.ts';
6
+
7
+ export { canonicalReceiptJson } from './encoding.ts';
8
+ export { createReceiptEvidencePort } from './policy.ts';
9
+ export type * from './types.ts';
10
+
11
+ /** The caller owns key custody and the truth of the schema-valid claims it signs. */
12
+ export async function signImporterVerificationReceipt(
13
+ payload: unknown,
14
+ keyId: string,
15
+ privateKey: CryptoKey,
16
+ ): Promise<ImporterVerificationReceipt> {
17
+ const canonical = canonicalReceiptJson(payload);
18
+ const receipt = {
19
+ schemaVersion: 1, type: 'runeditrun.importer-verification-receipt', algorithm: 'Ed25519',
20
+ keyId, payload: JSON.parse(canonical), signature: 'AA==',
21
+ } as ImporterVerificationReceipt;
22
+ const issues = validateReceiptDocumentSchema(receipt, '$');
23
+ if (issues.length) throw new TypeError(`Invalid receipt: ${issues.map((issue) => `${issue.code} at ${issue.path}`).join(', ')}`);
24
+ assertReceiptKey(privateKey, 'sign');
25
+ const signature = await crypto.subtle.sign('Ed25519', privateKey, new TextEncoder().encode(canonical));
26
+ receipt.signature = base64(new Uint8Array(signature));
27
+ return receipt;
28
+ }
29
+
30
+ /** Unknown, malformed, synthetic, disallowed and incorrectly signed receipts fail closed. */
31
+ export async function verifyImporterVerificationReceipt(
32
+ document: unknown,
33
+ policy: ImporterReceiptTrustPolicy,
34
+ path = '$',
35
+ ): Promise<ImporterReceiptVerificationResult> {
36
+ let receipt: ImporterVerificationReceipt;
37
+ try {
38
+ // Snapshot before the first await: the verified bytes cannot change underneath us.
39
+ receipt = JSON.parse(canonicalReceiptJson(document));
40
+ } catch {
41
+ return { valid: false, issues: [{ code: 'RECEIPT_NOT_JSON', path, message: 'Verification receipt must be JSON data.' }] };
42
+ }
43
+ const issues = validateReceiptDocumentSchema(receipt, `${path}.receipt`);
44
+ if (issues.length) return { valid: false, issues };
45
+
46
+ const trusted = policy?.keys && Object.hasOwn(policy.keys, receipt.keyId) ? policy.keys[receipt.keyId] : undefined;
47
+ // Only an omitted list is unrestricted; any value other than an array naming the environment refuses the key.
48
+ const environments: unknown = trusted?.environments;
49
+ if (!trusted || typeof policy.environment !== 'string' || !policy.environment
50
+ || (environments !== undefined && !(Array.isArray(environments) && environments.includes(policy.environment)))) {
51
+ return { valid: false, issues: [{ code: 'RECEIPT_KEY_UNTRUSTED', path: `${path}.receipt.keyId`, message: 'The issuer key is not allowed in this consumer environment.' }] };
52
+ }
53
+ let validSignature = false;
54
+ try {
55
+ const key = await receiptPublicKey(trusted.publicKey);
56
+ assertReceiptKey(key, 'verify');
57
+ const signature = unbase64(receipt.signature);
58
+ validSignature = signature.byteLength === 64 && await crypto.subtle.verify(
59
+ 'Ed25519', key, signature, new TextEncoder().encode(canonicalReceiptJson(receipt.payload)),
60
+ );
61
+ } catch {
62
+ validSignature = false;
63
+ }
64
+ if (!validSignature) {
65
+ return { valid: false, issues: [{ code: 'RECEIPT_SIGNATURE_INVALID', path: `${path}.receipt.signature`, message: 'The receipt is not signed by the pinned Ed25519 issuer key.' }] };
66
+ }
67
+ issues.push(...await validateReceiptPayload(receipt.payload, path));
68
+ return { valid: issues.length === 0, issues };
69
+ }
@@ -0,0 +1,24 @@
1
+ import type { ImporterEvidencePort } from '../status/types.ts';
2
+ import type { ImporterReceiptTrustPolicy } from './types.ts';
3
+ import { unbase64 } from './encoding.ts';
4
+
5
+ /** Bind a consumer's resolver and host pins to its public-key/environment policy. */
6
+ export function createReceiptEvidencePort(
7
+ evidence: Pick<ImporterEvidencePort, 'resolve' | 'trustedHosts'>,
8
+ policy: ImporterReceiptTrustPolicy,
9
+ ): ImporterEvidencePort {
10
+ return { resolve: evidence.resolve, trustedHosts: evidence.trustedHosts, receiptTrustPolicy: policy };
11
+ }
12
+
13
+ export async function receiptPublicKey(key: CryptoKey | string): Promise<CryptoKey> {
14
+ if (typeof key !== 'string') return key;
15
+ const match = key.trim().match(/^-----BEGIN PUBLIC KEY-----\s+([A-Za-z0-9+/=\s]+)\s+-----END PUBLIC KEY-----$/);
16
+ if (!match) throw new TypeError('Expected an Ed25519 SPKI public key in PEM format.');
17
+ return crypto.subtle.importKey('spki', unbase64(match[1]!.replace(/\s/g, '')), 'Ed25519', false, ['verify']);
18
+ }
19
+
20
+ export function assertReceiptKey(key: CryptoKey, usage: 'sign' | 'verify'): void {
21
+ if (key.algorithm.name !== 'Ed25519' || key.type !== (usage === 'sign' ? 'private' : 'public') || !key.usages.includes(usage)) {
22
+ throw new TypeError(`Expected an Ed25519 ${usage} key.`);
23
+ }
24
+ }
@@ -0,0 +1,64 @@
1
+ import type { ImporterValidationIssue } from '../status/types.ts';
2
+
3
+ export interface ImporterVerificationCounts {
4
+ input: number;
5
+ unique: number;
6
+ duplicates: number;
7
+ mapped: number;
8
+ unmapped: number;
9
+ rejected: number;
10
+ effects: number;
11
+ byKind: Record<string, number>;
12
+ }
13
+
14
+ export interface ImporterManifestComparison {
15
+ sourceCount: number;
16
+ targetCount: number;
17
+ sourceManifestSha256: string;
18
+ targetManifestSha256: string;
19
+ }
20
+
21
+ export interface ImporterVerificationPayload {
22
+ incumbent: string;
23
+ product: string;
24
+ synthetic: false;
25
+ source: {
26
+ classification: 'authorized-real-export'; origin: string; exportedAt: string;
27
+ format: string; version: string; sha256: string; size: number;
28
+ };
29
+ candidate: { repository: string; revision: string };
30
+ adapter: { repository: string; revision: string };
31
+ mapping: { version: string; policy: string; policySha256: string };
32
+ command: string;
33
+ runs: { dryRun: ImporterVerificationCounts; apply: ImporterVerificationCounts };
34
+ reconciliation: { rows: ImporterManifestComparison; provenance: ImporterManifestComparison; attachments: ImporterManifestComparison };
35
+ unmapped: {
36
+ count: number; itemManifestSha256: string;
37
+ items: Array<{ sourceIdentitySha256: string; sourceKind: string; fields: string[] }>;
38
+ };
39
+ research: { state: 'finished'; sha256: string };
40
+ review: { reviewer: string; reviewedAt: string; result: 'passed' };
41
+ }
42
+
43
+ export interface ImporterVerificationReceipt {
44
+ schemaVersion: 1;
45
+ type: 'runeditrun.importer-verification-receipt';
46
+ algorithm: 'Ed25519';
47
+ keyId: string;
48
+ payload: ImporterVerificationPayload;
49
+ signature: string;
50
+ }
51
+
52
+ /** Public keys only. An omitted environment restriction means all environments. */
53
+ export interface ImporterReceiptTrustPolicy {
54
+ environment: string;
55
+ keys: Readonly<Record<string, {
56
+ publicKey: CryptoKey | string;
57
+ environments?: readonly string[];
58
+ }>>;
59
+ }
60
+
61
+ export interface ImporterReceiptVerificationResult {
62
+ valid: boolean;
63
+ issues: ImporterValidationIssue[];
64
+ }
@@ -0,0 +1,45 @@
1
+ // URIs are split and their hosts checked by fixed ASCII grammars, never by the runtime URL parser: WHATWG host parsing
2
+ // applies UTS #46 IDNA tables that differ between Node and workerd releases, so one string could parse on one runtime
3
+ // and fail on another. The patterns carry no flags, so only their explicit ASCII ranges decide letter case.
4
+ const uriParts = /^([A-Za-z][A-Za-z0-9+.-]*):(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#([^]*))?$/;
5
+ const hostAndPort = /^([^:]*)(?::([1-9][0-9]{0,4}))?$/;
6
+ const dottedQuad = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$/;
7
+ const ldhLabel = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;
8
+ // A last label WHATWG would read as an IPv4 number.
9
+ const numericLabel = /^(?:[0-9]+|0[Xx][0-9A-Fa-f]*)$/;
10
+
11
+ export interface UriParts {
12
+ /** Lower case. */
13
+ scheme: string;
14
+ authority?: string;
15
+ path: string;
16
+ query?: string;
17
+ fragment?: string;
18
+ }
19
+
20
+ /** RFC 3986 appendix B on a string that starts with a scheme; callers check each part's characters. */
21
+ export function splitUri(text: string): UriParts | undefined {
22
+ const parts = uriParts.exec(text);
23
+ if (!parts) return undefined;
24
+ const [, scheme, authority, path, query, fragment] = parts;
25
+ // The scheme is ASCII, where toLowerCase folds only A-Z.
26
+ return { scheme: scheme!.toLowerCase(), authority, path: path!, query, fragment };
27
+ }
28
+
29
+ /** `[userinfo "@"] host [":" port]`; a port is 1 to 65535 without leading zeros. */
30
+ export function splitAuthority(authority: string): { userinfo?: string; host: string } | undefined {
31
+ const at = authority.lastIndexOf('@');
32
+ const address = hostAndPort.exec(authority.slice(at + 1));
33
+ if (!address || Number(address[2] ?? 1) > 65535) return undefined;
34
+ return at < 0 ? { host: address[1]! } : { userinfo: authority.slice(0, at), host: address[1]! };
35
+ }
36
+
37
+ /**
38
+ * Letter-digit-hyphen labels (an IDN only as its xn-- labels, which are not decoded) with an optional final dot and a
39
+ * last label that is not numeric, or a dotted-quad IPv4 address without leading zeros.
40
+ */
41
+ export function isAsciiHostname(host: string): boolean {
42
+ if (dottedQuad.test(host)) return true;
43
+ const labels = (host.endsWith('.') ? host.slice(0, -1) : host).split('.');
44
+ return labels.every((label) => ldhLabel.test(label)) && !numericLabel.test(labels[labels.length - 1]!);
45
+ }
@@ -0,0 +1,87 @@
1
+ import { canonicalReceiptJson as canonicalJson, receiptSha256 as sha256 } from './encoding.ts';
2
+ import type { ImporterValidationIssue } from '../status/types.ts';
3
+ import type { ImporterVerificationPayload } from './types.ts';
4
+ import { isAsciiHostname, splitAuthority, splitUri } from './uri.ts';
5
+
6
+ // One class with `%` plus a stray-`%` check, not a group like (?:[chars]|%XX)*: V8 pushes a backtrack entry per group
7
+ // iteration, so such a pattern throws RangeError near 2^23 characters, at a length that differs between V8 releases.
8
+ const originPath = /^[A-Za-z0-9._~!$&'()*+,;=:@/%-]*$/;
9
+ const strayPercent = /%(?![0-9A-Fa-f]{2})/;
10
+ // Only test() runs it, which needs just eight token characters: an unbounded counted repeat such as {8,} also pushes a
11
+ // V8 backtrack entry per character and threw RangeError past about 5.6M characters.
12
+ const unsafeCredentialText = /(?:bearer\s+[a-z0-9._~+\/-]{8}|--(?:token|password|secret|api[_-]?key)(?:\s+|=)\S+|\b(?:token|password|secret|api[_-]?key)\s*[:=]\s*\S+)/i;
13
+
14
+ /** Checks signed claims for internal consistency; source capture remains the signer's responsibility. */
15
+ export async function validateReceiptPayload(payload: ImporterVerificationPayload, path: string): Promise<ImporterValidationIssue[]> {
16
+ const issues: ImporterValidationIssue[] = [];
17
+ if (await sha256(payload.mapping.policy) !== payload.mapping.policySha256) {
18
+ issues.push({ code: 'RECEIPT_MAPPING_HASH_MISMATCH', path: `${path}.receipt.payload.mapping.policySha256`, message: 'The mapping policy hash does not match its text.' });
19
+ }
20
+ validateRunCounts(payload.runs, path, issues);
21
+ await validateReconciliation(payload.reconciliation, payload.runs.apply.effects, path, issues);
22
+ await validateUnmapped(payload.unmapped, payload.runs.dryRun.unmapped, path, issues);
23
+ if (payload.review.reviewer.includes('@') || unsafeCredentialText.test(payload.command) || unsafeCredentialText.test(payload.mapping.policy)) {
24
+ issues.push({ code: 'RECEIPT_UNSAFE_TEXT', path: `${path}.receipt.payload`, message: 'Receipt metadata must omit personal addresses and credential values.' });
25
+ }
26
+ validateExportOrigin(payload.source.origin, path, issues);
27
+ return issues;
28
+ }
29
+
30
+ /** `https://` host [":" port] and an RFC 3986 path over ASCII; no userinfo, query or fragment. */
31
+ function validateExportOrigin(originValue: string, path: string, issues: ImporterValidationIssue[]): void {
32
+ const origin = splitUri(originValue);
33
+ const address = origin?.authority === undefined ? undefined : splitAuthority(origin.authority);
34
+ if (!origin || origin.scheme !== 'https' || !address || address.userinfo !== undefined || !isAsciiHostname(address.host)
35
+ || !originPath.test(origin.path) || strayPercent.test(origin.path) || origin.query !== undefined || origin.fragment !== undefined) {
36
+ issues.push({ code: 'RECEIPT_ORIGIN_INVALID', path: `${path}.receipt.payload.source.origin`, message: 'Export origin must be an ASCII HTTPS URL (IDN hosts as xn-- labels) without credentials, query parameters, or fragments.' });
37
+ }
38
+ }
39
+
40
+ function validateRunCounts(runs: ImporterVerificationPayload['runs'], path: string, issues: ImporterValidationIssue[]): void {
41
+ const dryRun = runs.dryRun;
42
+ const apply = runs.apply;
43
+ if (dryRun.input !== dryRun.unique + dryRun.duplicates) {
44
+ issues.push({ code: 'RUN_INPUT_COUNT_INCONSISTENT', path: `${path}.receipt.payload.runs.dryRun`, message: 'Input count must equal unique records plus exact duplicates.' });
45
+ }
46
+ if (dryRun.input === 0 || dryRun.unique === 0 || dryRun.effects === 0) {
47
+ issues.push({ code: 'RUN_HAS_NO_IMPORT', path: `${path}.receipt.payload.runs`, message: 'A verified receipt must show at least one source record and target effect.' });
48
+ }
49
+ if (dryRun.rejected !== 0 || apply.rejected !== 0) {
50
+ issues.push({ code: 'RUN_HAS_REJECTED_ROWS', path: `${path}.receipt.payload.runs`, message: 'A verified import cannot leave source rows rejected.' });
51
+ }
52
+ for (const key of ['input', 'unique', 'duplicates', 'mapped', 'unmapped', 'rejected', 'effects'] as const) {
53
+ if (dryRun[key] !== apply[key]) {
54
+ issues.push({ code: 'RUN_COUNT_MISMATCH', path: `${path}.receipt.payload.runs.apply.${key}`, message: `Dry-run and apply ${key} counts differ.` });
55
+ }
56
+ }
57
+ if (canonicalJson(dryRun.byKind) !== canonicalJson(apply.byKind)) {
58
+ issues.push({ code: 'RUN_KIND_COUNTS_MISMATCH', path: `${path}.receipt.payload.runs.apply.byKind`, message: 'Dry-run and apply source-kind counts differ.' });
59
+ }
60
+ }
61
+
62
+ async function validateReconciliation(reconciliation: ImporterVerificationPayload['reconciliation'], appliedEffects: number, path: string, issues: ImporterValidationIssue[]): Promise<void> {
63
+ const emptyManifestSha256 = await sha256('[]');
64
+ for (const kind of ['rows', 'provenance', 'attachments'] as const) {
65
+ const comparison = reconciliation[kind];
66
+ if (comparison.sourceCount !== comparison.targetCount || comparison.sourceManifestSha256 !== comparison.targetManifestSha256) {
67
+ issues.push({ code: 'RECONCILIATION_MISMATCH', path: `${path}.receipt.payload.reconciliation.${kind}`, message: `${kind} source and persisted identity manifests differ.` });
68
+ }
69
+ if (comparison.sourceCount === 0 && comparison.sourceManifestSha256 !== emptyManifestSha256) {
70
+ issues.push({ code: 'EMPTY_MANIFEST_HASH_MISMATCH', path: `${path}.receipt.payload.reconciliation.${kind}`, message: `An empty ${kind} set must use the SHA-256 of the canonical empty manifest.` });
71
+ }
72
+ }
73
+ if (reconciliation.rows.sourceCount !== appliedEffects || reconciliation.provenance.sourceCount !== appliedEffects) {
74
+ issues.push({ code: 'ROW_PROVENANCE_COUNT_MISMATCH', path: `${path}.receipt.payload.reconciliation`, message: 'Applied target rows and provenance must reconcile one-to-one with published effects.' });
75
+ }
76
+ }
77
+
78
+ async function validateUnmapped(unmapped: ImporterVerificationPayload['unmapped'], expectedCount: number, path: string, issues: ImporterValidationIssue[]): Promise<void> {
79
+ const items = unmapped.items;
80
+ const identities = items.map((item) => item.sourceIdentitySha256);
81
+ // The default sort is UTF-16 code-unit order, as for canonical keys, never the host locale's collation.
82
+ const ordered = [...identities].sort();
83
+ if (unmapped.count !== expectedCount || unmapped.count !== items.length || new Set(identities).size !== identities.length
84
+ || canonicalJson(identities) !== canonicalJson(ordered) || unmapped.itemManifestSha256 !== await sha256(canonicalJson(items))) {
85
+ issues.push({ code: 'UNMAPPED_MANIFEST_MISMATCH', path: `${path}.receipt.payload.unmapped`, message: 'Unmapped count, ordered distinct source identities, and item manifest do not agree.' });
86
+ }
87
+ }
@@ -0,0 +1,13 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ export function canonicalJson(value: unknown): string {
4
+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';
5
+ if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(',')}]`;
6
+ const object = value as Record<string, unknown>;
7
+ const entries = Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(object[key])}`);
8
+ return `{${entries.join(',')}}`;
9
+ }
10
+
11
+ export function sha256(bytes: string | Uint8Array): string {
12
+ return createHash('sha256').update(bytes).digest('hex');
13
+ }
@@ -0,0 +1,218 @@
1
+ import { receiptSha256 as sha256 } from '../receipt/encoding.ts';
2
+ import { verifyImporterVerificationReceipt } from '../receipt/index.ts';
3
+ import type { ImporterVerificationReceipt } from '../receipt/types.ts';
4
+ import { isAsciiHostname, splitAuthority, splitUri } from '../receipt/uri.ts';
5
+ import type {
6
+ ImporterEvidenceArtifact,
7
+ ImporterEvidencePort,
8
+ ImporterRecord,
9
+ ImporterValidationIssue,
10
+ ImporterValidationResult,
11
+ VerifiedImporter,
12
+ } from './types.ts';
13
+
14
+ interface ImporterEvidenceReference extends ImporterEvidenceArtifact {
15
+ research?: ImporterEvidenceArtifact;
16
+ }
17
+
18
+ const maximumEvidenceBytes = 8 * 1024 * 1024;
19
+ // One class with `%` and a stray-`%` check, as for the export origin's path (receipt/validation.ts), so no host length
20
+ // overflows V8's regexp backtrack stack.
21
+ const registeredName = /^[A-Za-z0-9._~!$&'()*+,;=%-]*$/;
22
+ const strayPercent = /%(?![0-9A-Fa-f]{2})/;
23
+ const nonAscii = /[^\x00-\x7f]/;
24
+
25
+ export async function validateImporterEvidence(
26
+ records: ImporterRecord[],
27
+ evidence: ImporterEvidencePort | undefined,
28
+ issues: ImporterValidationIssue[],
29
+ ): Promise<ImporterValidationResult['evidence']> {
30
+ const counters: ImporterValidationResult['evidence'] = { required: 0, resolved: 0, verifiedReceipts: 0 };
31
+ if (!evidence || typeof evidence.resolve !== 'function' || !Array.isArray(evidence.trustedHosts)
32
+ || !evidence.trustedHosts.every((host) => typeof host === 'string' && host.length > 0 && host.trim() === host)) {
33
+ issues.push({ code: 'EVIDENCE_PORT_REQUIRED', path: '$', message: 'Supply a resolver for linked artifact bytes and trusted publisher hosts.' });
34
+ return counters;
35
+ }
36
+
37
+ for (let index = 0; index < records.length; index += 1) {
38
+ const record = records[index]!;
39
+ const path = `$.importers[${index}]`;
40
+ const reference = record.evidence as ImporterEvidenceReference;
41
+ const receipt = await resolveAndCheckArtifact(reference, evidence, `${path}.evidence`, issues, counters);
42
+ if (!receipt) continue;
43
+
44
+ if (record.status === 'verified') {
45
+ const research = await resolveAndCheckArtifact(reference.research!, evidence, `${path}.evidence.research`, issues, counters);
46
+ if (!research) continue;
47
+ if (await verifyReceipt(receipt.bytes, research.bytes, record, evidence, path, issues)) counters.verifiedReceipts += 1;
48
+ }
49
+ }
50
+
51
+ return counters;
52
+ }
53
+
54
+ async function resolveAndCheckArtifact(
55
+ reference: ImporterEvidenceArtifact,
56
+ evidence: ImporterEvidencePort,
57
+ path: string,
58
+ issues: ImporterValidationIssue[],
59
+ counters: ImporterValidationResult['evidence'],
60
+ ): Promise<{ url: string; bytes: Uint8Array } | undefined> {
61
+ counters.required += 1;
62
+ if (reference.link.trim() !== reference.link || reference.link.length === 0) {
63
+ issues.push({ code: 'EVIDENCE_LINK_INVALID', path: `${path}.link`, message: 'Evidence links must be non-empty and trimmed.' });
64
+ return undefined;
65
+ }
66
+
67
+ const link = readLink(reference.link);
68
+ if (!link) {
69
+ issues.push({ code: 'EVIDENCE_LINK_INVALID', path: `${path}.link`, message: 'Evidence link must be an absolute HTTPS (ASCII host; IDN as xn-- labels) or evidence URL without spaces or controls.' });
70
+ return undefined;
71
+ }
72
+ if (link.scheme !== 'https' && link.scheme !== 'evidence') {
73
+ issues.push({ code: 'EVIDENCE_LINK_SCHEME', path: `${path}.link`, message: 'Evidence links must use HTTPS or the consumer evidence scheme.' });
74
+ return undefined;
75
+ }
76
+ if (link.userinfo !== undefined || queryKeys(link.query ?? '').some((key) => /token|password|secret|api[_-]?key|authorization/i.test(key))) {
77
+ issues.push({ code: 'EVIDENCE_LINK_CREDENTIALS', path: `${path}.link`, message: 'Evidence links cannot embed credentials.' });
78
+ return undefined;
79
+ }
80
+ if (link.scheme === 'https' && !isTrustedHost(link.host!, evidence.trustedHosts)) {
81
+ issues.push({ code: 'EVIDENCE_PUBLISHER_UNTRUSTED', path: `${path}.link`, message: 'The evidence host is not pinned by the consumer.' });
82
+ return undefined;
83
+ }
84
+
85
+ let resolved: { url: string; bytes: Uint8Array } | undefined;
86
+ try {
87
+ resolved = await evidence.resolve(reference.link);
88
+ } catch {
89
+ issues.push({ code: 'EVIDENCE_RESOLUTION_FAILED', path: `${path}.link`, message: 'The evidence resolver could not resolve this link.' });
90
+ return undefined;
91
+ }
92
+ if (!resolved) {
93
+ issues.push({ code: 'EVIDENCE_NOT_FOUND', path: `${path}.link`, message: 'The linked evidence artifact was not found.' });
94
+ return undefined;
95
+ }
96
+ if (resolved.url !== reference.link) {
97
+ issues.push({ code: 'EVIDENCE_URL_MISMATCH', path: `${path}.link`, message: 'Resolved evidence URL differs from the requested link.' });
98
+ return undefined;
99
+ }
100
+ if (!(resolved.bytes instanceof Uint8Array) || resolved.bytes.byteLength < 1 || resolved.bytes.byteLength > maximumEvidenceBytes) {
101
+ issues.push({ code: 'EVIDENCE_BYTES_INVALID', path: `${path}.link`, message: `Evidence bytes must be between 1 and ${maximumEvidenceBytes} bytes.` });
102
+ return undefined;
103
+ }
104
+
105
+ const snapshot = new Uint8Array(resolved.bytes);
106
+ counters.resolved += 1;
107
+ if (snapshot.byteLength !== reference.size) {
108
+ issues.push({ code: 'EVIDENCE_SIZE_MISMATCH', path: `${path}.size`, message: 'Resolved bytes do not match the declared evidence size.' });
109
+ return undefined;
110
+ }
111
+ if (await sha256(snapshot) !== reference.sha256) {
112
+ issues.push({ code: 'EVIDENCE_HASH_MISMATCH', path: `${path}.sha256`, message: 'Resolved bytes do not match the declared SHA-256.' });
113
+ return undefined;
114
+ }
115
+ return { url: resolved.url, bytes: snapshot };
116
+ }
117
+
118
+ /**
119
+ * Scheme, userinfo, host and port by the module's ASCII grammar: an https host must be an ASCII hostname, another
120
+ * scheme's host an RFC 3986 registered name. Path, query and fragment reach the resolver as written.
121
+ */
122
+ function readLink(text: string): { scheme: string; userinfo?: string; host?: string; query?: string } | undefined {
123
+ const link = splitUri(text);
124
+ if (!link || /[\u0000-\u0020\u007f-\u009f]/.test(text)) return undefined;
125
+ if (link.authority === undefined) return link.scheme === 'https' ? undefined : link;
126
+ const address = splitAuthority(link.authority);
127
+ if (!address || !(link.scheme === 'https' ? isAsciiHostname(address.host) : registeredName.test(address.host) && !strayPercent.test(address.host))) return undefined;
128
+ return { ...link, ...address };
129
+ }
130
+
131
+ /** Names as URL searchParams decodes them (application/x-www-form-urlencoded): `+` is a space, then UTF-8 `%XX` bytes. */
132
+ function queryKeys(query: string): string[] {
133
+ const decoder = new TextDecoder('utf-8', { ignoreBOM: true });
134
+ return query.split('&').filter(Boolean).map((pair) => {
135
+ const name = pair.split('=', 1)[0]!;
136
+ return name.includes('%') || name.includes('+') ? decodeUtf8(decoder, formDecode(name)) : name;
137
+ });
138
+ }
139
+
140
+ /** One TextDecoder call per 16 MiB with streaming state: workerd's decoder refuses one input above about 170 MB. */
141
+ function decodeUtf8(decoder: TextDecoder, bytes: Uint8Array): string {
142
+ const chunk = 16 * 1024 * 1024;
143
+ let text = '';
144
+ for (let start = 0; start < bytes.length; start += chunk) {
145
+ text += decoder.decode(bytes.subarray(start, start + chunk), { stream: start + chunk < bytes.length });
146
+ }
147
+ return text;
148
+ }
149
+
150
+ /**
151
+ * The URL Standard's form decoding of the text's UTF-8 bytes in one pass: `+` becomes a space, `%` and two hex digits
152
+ * that byte. String replaces build their result from one piece per match: a global replace with a callback first lists
153
+ * every match, and V8 aborts the process once that list outgrows 2^26 entries (it did at 25,000,000 matches);
154
+ * replaceAll('+', ' ') ended the workerd process at 75,000,000 characters.
155
+ */
156
+ function formDecode(text: string): Uint8Array {
157
+ const bytes = new TextEncoder().encode(text);
158
+ let length = 0;
159
+ for (let index = 0; index < bytes.length; index += 1) {
160
+ const high = bytes[index] === 0x25 ? hexValue(bytes[index + 1]) : -1;
161
+ const low = high < 0 ? -1 : hexValue(bytes[index + 2]);
162
+ if (low >= 0) { bytes[length++] = high * 16 + low; index += 2; }
163
+ else bytes[length++] = bytes[index] === 0x2b ? 0x20 : bytes[index]!;
164
+ }
165
+ return bytes.subarray(0, length);
166
+ }
167
+
168
+ /** 0-15 for the byte of an ASCII hex digit, otherwise -1. */
169
+ function hexValue(byte: number | undefined): number {
170
+ if (byte === undefined) return -1;
171
+ if (byte >= 0x30 && byte <= 0x39) return byte - 0x30;
172
+ const lower = byte | 0x20;
173
+ return lower >= 0x61 && lower <= 0x66 ? lower - 0x57 : -1;
174
+ }
175
+
176
+ /** `host` is an ASCII hostname, where toLowerCase folds only A-Z; a pin with a non-ASCII character never equals it. */
177
+ function isTrustedHost(host: string, trustedHosts: readonly string[]): boolean {
178
+ const normalized = host.toLowerCase();
179
+ // Checked before toLowerCase, which would fold a pin's U+212A KELVIN SIGN to "k".
180
+ return trustedHosts.some((trusted) => !nonAscii.test(trusted) && trusted.toLowerCase() === normalized);
181
+ }
182
+
183
+ async function verifyReceipt(
184
+ receiptBytes: Uint8Array,
185
+ researchBytes: Uint8Array,
186
+ importer: VerifiedImporter,
187
+ evidence: ImporterEvidencePort,
188
+ path: string,
189
+ issues: ImporterValidationIssue[],
190
+ ): Promise<boolean> {
191
+ const firstIssue = issues.length;
192
+ let parsed: unknown;
193
+ try {
194
+ parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(receiptBytes));
195
+ } catch {
196
+ issues.push({ code: 'RECEIPT_NOT_JSON', path: `${path}.evidence.link`, message: 'The linked verification receipt is not valid UTF-8 JSON.' });
197
+ return false;
198
+ }
199
+
200
+ const policy = evidence.receiptTrustPolicy ?? {
201
+ environment: 'unrestricted',
202
+ keys: Object.fromEntries(Object.entries(evidence.receiptPublicKeys ?? {}).map(([keyId, publicKey]) => [keyId, { publicKey }])),
203
+ };
204
+ const verified = await verifyImporterVerificationReceipt(parsed, policy, path);
205
+ issues.push(...verified.issues);
206
+ if (!verified.valid) return false;
207
+ const receipt = parsed as ImporterVerificationReceipt;
208
+
209
+ const payload = receipt.payload;
210
+ if (payload.incumbent !== importer.incumbent || payload.product !== importer.product) {
211
+ issues.push({ code: 'RECEIPT_PAIR_MISMATCH', path: `${path}.receipt.payload`, message: 'Receipt incumbent and product do not match the catalog row.' });
212
+ }
213
+ if (await sha256(researchBytes) !== payload.research.sha256 || payload.research.sha256 !== importer.evidence.research.sha256) {
214
+ issues.push({ code: 'RESEARCH_HASH_MISMATCH', path: `${path}.receipt.payload.research.sha256`, message: 'The finished research artifact does not match the signed receipt.' });
215
+ }
216
+
217
+ return issues.length === firstIssue;
218
+ }