@runeditrun/rer 0.2.85 → 0.2.86
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.
- package/README.md +138 -29
- package/cli/README.md +61 -1
- package/cli/agent-door.mjs +149 -0
- package/cli/agent-fixtures.mjs +16 -0
- package/cli/agent-mail.mjs +54 -0
- package/cli/agent-network.mjs +64 -0
- package/cli/agent-reviewers.mjs +110 -0
- package/cli/agent-secrets.mjs +23 -0
- package/cli/agent-sponsors.mjs +43 -0
- package/cli/agent-surface.mjs +34 -0
- package/cli/agent-webhooks.mjs +19 -0
- package/cli/authoring.mjs +2 -1
- package/cli/business/archive-task.mjs +32 -0
- package/cli/business/carry.mjs +3 -1
- package/cli/business/catchup-task.mjs +42 -0
- package/cli/business/choices.mjs +97 -0
- package/cli/business/command.mjs +23 -5
- package/cli/business/connect.mjs +19 -7
- package/cli/business/detector.mjs +4 -1
- package/cli/business/device.mjs +13 -0
- package/cli/business/export-inputs.mjs +69 -0
- package/cli/business/export-task.mjs +17 -0
- package/cli/business/invocation.mjs +8 -1
- package/cli/business/keychain.mjs +8 -1
- package/cli/business/lease.mjs +11 -1
- package/cli/business/local-commands.mjs +79 -31
- package/cli/business/outbound.mjs +9 -4
- package/cli/business/parsers-config.mjs +8 -7
- package/cli/business/parsers-syntax.mjs +7 -3
- package/cli/business/permissions.mjs +2 -0
- package/cli/business/questions.mjs +89 -9
- package/cli/business/setup-command.mjs +49 -0
- package/cli/business/setup-company.json +15 -0
- package/cli/business/setup-demo.mjs +95 -0
- package/cli/business/state.mjs +44 -10
- package/cli/business/supervisor.mjs +94 -35
- package/cli/business/vendor-door.mjs +230 -0
- package/cli/business/vendors/README.md +29 -3
- package/cli/business/vendors/common.mjs +8 -6
- package/cli/business/vendors/index.mjs +22 -11
- package/cli/business/vendors/sorry.mjs +106 -0
- package/cli/contract.mjs +2 -2
- package/cli/demo-deploy-error.mjs +14 -0
- package/cli/demo-native.mjs +4 -1
- package/cli/deploy-config.mjs +1 -1
- package/cli/deploy-owner-input.mjs +3 -1
- package/cli/deploy-variables.mjs +58 -0
- package/cli/door-clauses.mjs +157 -0
- package/cli/export.mjs +16 -4
- package/cli/hosted-output.mjs +17 -7
- package/cli/inspect.mjs +4 -0
- package/cli/jsonc.mjs +8 -4
- package/cli/lifecycle.mjs +3 -1
- package/cli/main.mjs +1 -0
- package/cli/managed-data-schema.mjs +14 -1
- package/cli/portability-empty.mjs +6 -0
- package/cli/portability-migrations.mjs +26 -4
- package/cli/production-auth.mjs +1 -1
- package/cli/production-mail.mjs +8 -2
- package/edition-authoring/archive-source.mjs +59 -0
- package/edition-authoring/base-copies.mjs +92 -18
- package/edition-authoring/cli.mjs +1 -1
- package/edition-authoring/edition-migrations.mjs +7 -3
- package/edition-authoring/module-closure.mjs +2 -16
- package/edition-authoring/workflow-copies.mjs +1 -1
- package/edition-authoring/workflow-scripts.mjs +12 -3
- package/foundation/runtime/contract-docs.mjs +215 -32
- package/foundation/runtime/contract-prose-patterns.mjs +14 -0
- package/foundation/runtime/contract-prose.mjs +88 -0
- package/global/CHANGELOG.md +93 -0
- package/global/README.md +138 -29
- package/global/door/command.mjs +3 -1
- package/global/main.mjs +1 -1
- package/modules/agent-door/CLAUSES.md +215 -0
- package/modules/agent-door/conformance/audit.mjs +66 -0
- package/modules/agent-door/conformance/authority.d.mts +2 -0
- package/modules/agent-door/conformance/authority.mjs +17 -0
- package/modules/agent-door/conformance/crypto.mjs +36 -0
- package/modules/agent-door/conformance/discovery.mjs +61 -0
- package/modules/agent-door/conformance/index.mjs +41 -0
- package/modules/agent-door/conformance/invocation.mjs +32 -0
- package/modules/agent-door/conformance/journey.mjs +112 -0
- package/modules/agent-door/conformance/narrowing.d.mts +1 -0
- package/modules/agent-door/conformance/narrowing.mjs +21 -0
- package/modules/agent-door/conformance/negative.mjs +47 -0
- package/modules/agent-door/conformance/network-modules.mjs +86 -0
- package/modules/agent-door/conformance/network-runtime.mjs +46 -0
- package/modules/agent-door/conformance/policy-phases.mjs +75 -0
- package/modules/agent-door/conformance/protocol.mjs +145 -0
- package/modules/agent-door/conformance/replay.mjs +38 -0
- package/modules/agent-door/conformance/schema.mjs +71 -0
- package/modules/agent-door/conformance/security.mjs +33 -0
- package/modules/agent-door/conformance/sponsors.mjs +68 -0
- package/modules/agent-door/conformance/surface.mjs +89 -0
- package/modules/agent-door/conformance/target.mjs +18 -0
- package/modules/agent-door/conformance/tool-name.d.mts +1 -0
- package/modules/agent-door/conformance/tool-name.mjs +7 -0
- package/modules/agent-door/conformance/webhooks.mjs +30 -0
- package/modules/container/image-variables.mjs +8 -2
- package/modules/demo-host/README.md +6 -0
- package/modules/demo-host/ownership.mjs +39 -0
- package/modules/demo-host/plan.mjs +2 -1
- package/modules/demo-host/remove.mjs +6 -1
- package/modules/import-kit/schema/importer-verification-receipt.schema.json +171 -0
- package/modules/import-kit/schema/importers.schema.json +107 -0
- package/modules/import-kit/src/door/ADOPTING.md +20 -0
- package/modules/import-kit/src/door/README.md +2 -1
- package/modules/import-kit/src/door/admission.ts +5 -3
- package/modules/import-kit/src/door/archive.ts +5 -2
- package/modules/import-kit/src/door/authority.ts +1 -0
- package/modules/import-kit/src/door/grants.ts +1 -1
- package/modules/import-kit/src/door/handler.ts +14 -8
- package/modules/import-kit/src/door/index.ts +1 -1
- package/modules/import-kit/src/door/jobs.ts +40 -0
- package/modules/import-kit/src/door/operator.ts +3 -3
- package/modules/import-kit/src/door/planning.ts +10 -6
- package/modules/import-kit/src/door/protocol.ts +2 -2
- package/modules/import-kit/src/door/raw.ts +25 -0
- package/modules/import-kit/src/door/refusals.ts +1 -0
- package/modules/import-kit/src/door/types.ts +26 -6
- package/modules/import-kit/src/receipt/encoding.ts +37 -0
- package/modules/import-kit/src/receipt/index.ts +69 -0
- package/modules/import-kit/src/receipt/policy.ts +24 -0
- package/modules/import-kit/src/receipt/types.ts +64 -0
- package/modules/import-kit/src/receipt/uri.ts +45 -0
- package/modules/import-kit/src/receipt/validation.ts +87 -0
- package/modules/import-kit/src/status/encoding.ts +13 -0
- package/modules/import-kit/src/status/evidence.ts +218 -0
- package/modules/import-kit/src/status/index.ts +56 -0
- package/modules/import-kit/src/status/schema.ts +208 -0
- package/modules/import-kit/src/status/types.ts +86 -0
- package/modules/operator-auth/accounts/delegated.mjs +48 -0
- package/modules/operator-auth/index.d.mts +7 -0
- package/modules/operator-auth/service.mjs +2 -0
- package/modules/portability/README.md +32 -11
- package/modules/portability/bridge.mjs +22 -2
- package/modules/portability/copies.mjs +8 -1
- package/modules/portability/derived.mjs +33 -0
- package/modules/portability/http-errors.mjs +1 -1
- package/modules/portability/import.mjs +14 -7
- package/package.json +4 -2
- package/scripts/publish-check/copy_identities.py +3 -1
- package/scripts/publish-check/github_refs.py +32 -13
- package/cli/business/opt-ins.mjs +0 -37
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { readRawSource } from './raw.ts';
|
|
1
2
|
import { randomUUID } from 'node:crypto';
|
|
2
3
|
import { canonicalJson, sha256 } from '../provenance/identity.ts';
|
|
3
4
|
import { readFileSource } from '../readers/file.ts';
|
|
@@ -13,9 +14,9 @@ import { bundleBytes, text, uploadRow, type UploadRow } from './uploads.ts';
|
|
|
13
14
|
import { sourceRefusal } from './refusals.ts';
|
|
14
15
|
import { intakeState } from './intake-policy.ts';
|
|
15
16
|
|
|
16
|
-
export function preview(snapshot: DoorSnapshot) {
|
|
17
|
+
export function preview(snapshot: DoorSnapshot, created: boolean) {
|
|
17
18
|
const {plan,differences} = snapshot;
|
|
18
|
-
return {planId:snapshot.id,fingerprint:plan.fingerprint,bundleSha256:snapshot.bundleSha256,
|
|
19
|
+
return {planId:snapshot.id,fingerprint:plan.fingerprint,bundleSha256:snapshot.bundleSha256,created,
|
|
19
20
|
summary:{sourceRecords:snapshot.sourceCount,created:differences.additions.length,updated:differences.replacements.length,unchanged:differences.unchanged.length,gone:differences.gone.length},
|
|
20
21
|
counts:plan.counts,rejected:plan.entries.filter(e=>e.rejection).map(e=>({kind:e.source.kind,sourceId:e.source.sourceId,reason:e.rejection})),
|
|
21
22
|
diagnostics:plan.diagnostics,differences};
|
|
@@ -67,7 +68,7 @@ async function planUpload(request: DoorRequest, input: Record<string, unknown>,
|
|
|
67
68
|
if (snapshot.plan.mappingVersion !== request.options.mapping.version) throw new DoorError('snapshot_mapping_changed_use_new_namespace',409);
|
|
68
69
|
if (request.access.catchup === 'bounded' && (!snapshot.standingApproval || snapshot.standingApproval.id !== request.access.approvalRecordId || snapshot.standingApproval.at !== request.access.approvedAt)) throw new DoorError('standing_approval_mismatch');
|
|
69
70
|
await dropCredentialBytes(request,snapshot,upload);
|
|
70
|
-
return preview(snapshot);
|
|
71
|
+
return preview(snapshot,false);
|
|
71
72
|
}
|
|
72
73
|
if (current.pending_id) throw new DoorError('namespace_has_pending_import',409);
|
|
73
74
|
// An erasure withdrew the live import's snapshot, so nothing can be compared
|
|
@@ -138,7 +139,7 @@ async function planUpload(request: DoorRequest, input: Record<string, unknown>,
|
|
|
138
139
|
if (retired) await retire(request,retired,snapshot.plan);
|
|
139
140
|
await saveSnapshot(request,snapshot,upload,retainedFrom);
|
|
140
141
|
await dropCredentialBytes(request,snapshot,upload);
|
|
141
|
-
return preview(snapshot);
|
|
142
|
+
return preview(snapshot,true);
|
|
142
143
|
}
|
|
143
144
|
/** Retire an erasure-withdrawn live import as the namespace's baseline. The kit
|
|
144
145
|
* never lets a new import write a record another live import holds, so while an
|
|
@@ -173,8 +174,11 @@ async function readUpload(request: DoorRequest, upload: UploadRow, planId: strin
|
|
|
173
174
|
const retained = await retainedSource(request,upload);
|
|
174
175
|
if (retained) return {kitNamespace,retainedFrom:retained.planId,source:{...retained.source,records:retained.source.records.map(record=>({...record,namespace:kitNamespace}))}};
|
|
175
176
|
// Credential values are removed per record, never imported, and never refuse a record.
|
|
176
|
-
const
|
|
177
|
-
|
|
177
|
+
const bytes = await bundleBytes(request,upload);
|
|
178
|
+
const limits = {...options.limits,maxBytes:Math.min(options.limits?.maxBytes ?? request.access.maxBytes,request.access.maxBytes),maxRecords:Math.min(options.limits?.maxRecords ?? request.access.maxRecords,request.access.maxRecords)};
|
|
179
|
+
const source = options.format === 'raw'
|
|
180
|
+
? await readRawSource(options,upload,bytes,kitNamespace,limits)
|
|
181
|
+
: await readFileSource({namespace:kitNamespace,name:upload.name,bytes,format:intake ? 'ndjson' : options.format,parse:options.parse,credentials:'remove'},limits);
|
|
178
182
|
if (intake) source.intake = intake;
|
|
179
183
|
return {kitNamespace,source,retainedFrom:undefined};
|
|
180
184
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export type DoorAction = 'uploads' | 'plan' | 'apply' | 'status' | 'reconcile' | 'undo' | 'archive' | 'restore-check';
|
|
1
|
+
export type DoorAction = 'uploads' | 'plan' | 'apply' | 'status' | 'reconcile' | 'undo' | 'cancel' | 'archive' | 'restore-check';
|
|
2
2
|
/** Grant-only actions: the owner-session mount answers them 404. */
|
|
3
|
-
export const GRANT_ONLY_ACTIONS: readonly DoorAction[] = ['archive', 'restore-check'];
|
|
3
|
+
export const GRANT_ONLY_ACTIONS: readonly DoorAction[] = ['cancel', 'archive', 'restore-check'];
|
|
4
4
|
|
|
5
5
|
export interface DoorGrant {
|
|
6
6
|
v: 1;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
import type { ParsedRecord, ReaderLimits, SourceBundle } from '../types.ts';
|
|
3
|
+
import { limitsFor, RecordCollector, safeValue, textId } from '../readers/records.ts';
|
|
4
|
+
import { fail } from '../readers/errors.ts';
|
|
5
|
+
import type { ImportDoorRawRuntimeOptions } from './types.ts';
|
|
6
|
+
import type { UploadRow } from './uploads.ts';
|
|
7
|
+
|
|
8
|
+
/** Upload custody is already verified. Never decode it before the seed reads it. */
|
|
9
|
+
export async function readRawSource(options: ImportDoorRawRuntimeOptions, upload: Pick<UploadRow, 'name' | 'bundle_sha256' | 'total_bytes'>,
|
|
10
|
+
bytes: Uint8Array, namespace: string, limits: ReaderLimits): Promise<SourceBundle> {
|
|
11
|
+
const bounded = limitsFor(limits), location = {artifact: upload.name};
|
|
12
|
+
textId(upload.name); safeValue(upload.name);
|
|
13
|
+
if (bytes.byteLength > bounded.maxBytes) fail('SOURCE_BYTE_LIMIT',location);
|
|
14
|
+
// Snapshot custody before the callback, whose working buffer may be mutated.
|
|
15
|
+
const base64 = Buffer.from(bytes).toString('base64');
|
|
16
|
+
let records: ParsedRecord[];
|
|
17
|
+
try {
|
|
18
|
+
records = await options.readRaw({bytes:Uint8Array.from(bytes),name:upload.name,sha256:upload.bundle_sha256,size:upload.total_bytes},Object.freeze({...bounded}));
|
|
19
|
+
} catch { fail('SOURCE_RAW_READER_FAILED',location); }
|
|
20
|
+
const collector = new RecordCollector(namespace,bounded,[]);
|
|
21
|
+
collector.add(records,location,upload.bundle_sha256);
|
|
22
|
+
collector.bundle.artifacts.push({name:upload.name,sha256:upload.bundle_sha256,size:upload.total_bytes,
|
|
23
|
+
original:{status:'available',base64}});
|
|
24
|
+
return collector.bundle;
|
|
25
|
+
}
|
|
@@ -8,6 +8,7 @@ const reasons: Record<string, string> = {
|
|
|
8
8
|
MALFORMED_JSON: 'The upload is not valid JSON in the declared format.',
|
|
9
9
|
MALFORMED_UTF8: 'The upload is not valid UTF-8.',
|
|
10
10
|
INVALID_OR_CREDENTIAL_SOURCE_DATA: 'A source value is not plain JSON data, holds a URL that cannot be parsed, or is encoded too deeply to inspect for credentials.',
|
|
11
|
+
SOURCE_RAW_READER_FAILED: "The seed's reader refused the raw upload. Check the archive format and contents.",
|
|
11
12
|
SOURCE_PARSER_FAILED: "The seed's parser refused a source value.",
|
|
12
13
|
SOURCE_OBJECT_DROPPED: "The seed's parser returned no record for a source value.",
|
|
13
14
|
INVALID_PARSED_RECORDS: "The seed's parser returned an invalid record list.",
|
|
@@ -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
|
-
/**
|
|
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
|
-
| (
|
|
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):
|
|
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:
|
|
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
|
+
}
|