@intellectual-frontiers/grc 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,164 @@
1
+ import { type ResourceDescriptor, type Statement } from "@intellectual-frontiers/crypto/dsse";
2
+ import { type Assessment, type Instant } from "./grc.js";
3
+ import { type Sha256 } from "@intellectual-frontiers/crypto/sha256";
4
+ import { type Uuid } from "@intellectual-frontiers/crypto/uuid";
5
+ /** A CycloneDX 1.6 component type. */
6
+ export type CdxComponentType = "application" | "framework" | "library" | "container" | "platform" | "operating-system" | "device" | "device-driver" | "firmware" | "file" | "machine-learning-model" | "data" | "cryptographic-asset";
7
+ /** A requirement of a standard. */
8
+ export type CdxRequirement = {
9
+ readonly "bom-ref": string;
10
+ readonly identifier: string;
11
+ readonly title?: string;
12
+ readonly text?: string;
13
+ };
14
+ /** A standard (`definitions.standards`): its requirements, and what is known of it. */
15
+ export type CdxStandard = {
16
+ readonly "bom-ref": string;
17
+ readonly name: string;
18
+ readonly version?: string;
19
+ readonly description?: string;
20
+ readonly owner?: string;
21
+ readonly requirements: readonly CdxRequirement[];
22
+ };
23
+ /** An assessor. */
24
+ export type CdxAssessor = {
25
+ readonly "bom-ref": string;
26
+ readonly thirdParty: boolean;
27
+ readonly organization: {
28
+ readonly name: string;
29
+ };
30
+ };
31
+ /** How far a requirement is met: a score from 0 to 1 and why. */
32
+ export type CdxConformance = {
33
+ readonly score: number;
34
+ readonly rationale: string;
35
+ };
36
+ /** One requirement of an attestation, with the claims and counter-claims that bear on it. */
37
+ export type CdxAttestationMapItem = {
38
+ readonly requirement: string;
39
+ readonly claims: readonly string[];
40
+ readonly counterClaims?: readonly string[];
41
+ readonly conformance: CdxConformance;
42
+ };
43
+ /** An attestation: an assessor's map of requirements to claims. */
44
+ export type CdxAttestation = {
45
+ readonly summary: string;
46
+ readonly assessor: string;
47
+ readonly map: readonly CdxAttestationMapItem[];
48
+ };
49
+ /** A claim about a target, with the evidence for it and against it. */
50
+ export type CdxClaim = {
51
+ readonly "bom-ref": string;
52
+ readonly target: string;
53
+ readonly predicate: string;
54
+ readonly reasoning: string;
55
+ readonly evidence?: readonly string[];
56
+ readonly counterEvidence?: readonly string[];
57
+ };
58
+ /** A piece of evidence: what it is, when it was made, and where its data is. */
59
+ export type CdxEvidence = {
60
+ readonly "bom-ref": string;
61
+ readonly description: string;
62
+ readonly data?: readonly {
63
+ readonly name: string;
64
+ readonly contents: {
65
+ readonly url: string;
66
+ };
67
+ }[];
68
+ readonly created: Instant;
69
+ };
70
+ /** A component claims are about. */
71
+ export type CdxTargetComponent = {
72
+ readonly "bom-ref": string;
73
+ readonly type: CdxComponentType;
74
+ readonly name: string;
75
+ readonly version?: string;
76
+ };
77
+ /** CycloneDX 1.6 declarations. */
78
+ export type CdxDeclarations = {
79
+ readonly assessors: readonly CdxAssessor[];
80
+ readonly attestations: readonly CdxAttestation[];
81
+ readonly claims: readonly CdxClaim[];
82
+ readonly evidence: readonly CdxEvidence[];
83
+ readonly targets: {
84
+ readonly components: readonly CdxTargetComponent[];
85
+ };
86
+ };
87
+ /** A tool that made a BOM. */
88
+ export type CdxTool = {
89
+ readonly type: "application";
90
+ readonly name: string;
91
+ readonly version: string;
92
+ };
93
+ /** A minimal CycloneDX 1.6 BOM that carries declarations. */
94
+ export type CdxBom = {
95
+ readonly bomFormat: "CycloneDX";
96
+ readonly specVersion: "1.6";
97
+ readonly serialNumber: `urn:uuid:${string}`;
98
+ readonly version: 1;
99
+ readonly metadata: {
100
+ readonly timestamp: Instant;
101
+ readonly tools?: {
102
+ readonly components: readonly CdxTool[];
103
+ };
104
+ };
105
+ readonly definitions: {
106
+ readonly standards: readonly CdxStandard[];
107
+ };
108
+ readonly declarations: CdxDeclarations;
109
+ };
110
+ /** What an attestation needs beyond the assessment. */
111
+ export type AttestOptions = {
112
+ /** The namespace of the BOM's serial number and of its evidence's UUIDs. */
113
+ readonly namespace: Uuid;
114
+ readonly assessor: {
115
+ readonly name: string;
116
+ readonly thirdParty: boolean;
117
+ };
118
+ /** What the claims are about. */
119
+ readonly target: {
120
+ readonly name: string;
121
+ readonly type?: CdxComponentType;
122
+ readonly version?: string;
123
+ };
124
+ readonly tool?: {
125
+ readonly name: string;
126
+ readonly version: string;
127
+ };
128
+ /** What is known of each catalog, by its id. */
129
+ readonly standards?: Readonly<Record<string, {
130
+ readonly name?: string;
131
+ readonly version?: string;
132
+ readonly owner?: string;
133
+ readonly description?: string;
134
+ }>>;
135
+ readonly summary?: string;
136
+ };
137
+ /** An RFC 6920 Named Information URI of a SHA-256: `ni:///sha-256;` and the digest in base64url without padding. */
138
+ export declare function niUri(digest: Sha256): string;
139
+ /** An assessment's declarations, and the standards their requirements are of. */
140
+ export declare function declarations(a: Assessment, o: AttestOptions): Promise<{
141
+ readonly standards: readonly CdxStandard[];
142
+ readonly declarations: CdxDeclarations;
143
+ }>;
144
+ /** An assessment as a CycloneDX 1.6 BOM of its declarations: the serial number a version 5 UUID of the pack and time in the namespace. */
145
+ export declare function cyclonedxBom(a: Assessment, o: AttestOptions): Promise<CdxBom>;
146
+ /** The in-toto predicate type of a CycloneDX BOM. */
147
+ export declare const CYCLONEDX_PREDICATE_TYPE = "https://cyclonedx.org/bom";
148
+ /** A statement's subject named by its SHA-256. */
149
+ export type DigestSubject = ResourceDescriptor & {
150
+ readonly digest: {
151
+ readonly sha256: Sha256;
152
+ };
153
+ };
154
+ /** An in-toto Statement v1 whose predicate type is `T` and predicate `P`, its subjects named by their SHA-256: a `Statement<P>` for DSSE. */
155
+ export type TypedStatement<T extends string, P> = Statement<P> & {
156
+ readonly predicateType: T;
157
+ readonly subject: readonly DigestSubject[];
158
+ };
159
+ /** A subject: the name and the SHA-256 of the bytes. */
160
+ export declare function digestSubject(name: string, bytes: Uint8Array): Promise<DigestSubject>;
161
+ /** An in-toto Statement v1 of a predicate of the type named about the subjects. */
162
+ export declare function intotoStatement<const T extends string, P>(subjects: readonly DigestSubject[], predicateType: T, predicate: P): TypedStatement<T, P>;
163
+ /** A CycloneDX BOM as the predicate of an in-toto statement about the subjects. */
164
+ export declare function bomStatement(bom: CdxBom, subjects: readonly DigestSubject[]): TypedStatement<typeof CYCLONEDX_PREDICATE_TYPE, CdxBom>;
package/dist/attest.js ADDED
@@ -0,0 +1,213 @@
1
+ // Spec: 0001-grc-engineering FR-018
2
+ /**
3
+ * Attestations (commons 0001-grc-engineering FR-018): an assessment as CycloneDX 1.6 `declarations` (assessors, attestations, claims, evidence and
4
+ * targets) in a minimal CycloneDX 1.6 BOM, and in-toto Statements v1 with a predicate type the caller names, ready for a DSSE envelope
5
+ * (`crypto/dsse`, 0005-typescript-runtime FR-045).
6
+ *
7
+ * - `definitions.standards`: one standard per catalog the assessment's controls implement (a control that implements none stands as a
8
+ * requirement of a standard named after the pack), each catalog control a requirement.
9
+ * - `declarations.evidence`: one entry per finding, its digests as RFC 6920 `ni:///sha-256;...` URIs.
10
+ * - `declarations.claims`: for each requirement, a claim that its controls meet it, with the evidence of the passing findings and, as
11
+ * counter-evidence, of the others; and where some newest finding does not pass, a counter-claim that it is not met.
12
+ * - `declarations.attestations`: the assessor maps each requirement to its claim, its counter-claim if any, and a conformance score, the
13
+ * share of applicable newest findings that pass (0 where none).
14
+ *
15
+ * Every list is in an order of its own and the serial number is a version 5 UUID of a namespace the caller gives and the pack and time,
16
+ * so the same assessment gives the same BOM. The in-toto statement is built by `crypto/dsse`'s `statement` and keeps the predicate's
17
+ * type in its own type, so `signStatement` and `verifyStatement` take it as it is.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { CYCLONEDX_PREDICATE_TYPE, digestSubject, intotoStatement } from "./attest.ts";
22
+ * const s = intotoStatement([await digestSubject("report.json", new TextEncoder().encode("{}"))], CYCLONEDX_PREDICATE_TYPE, { bomFormat: "CycloneDX" });
23
+ * s.predicateType; // "https://cyclonedx.org/bom", as a literal type
24
+ * ```
25
+ *
26
+ * @module
27
+ */
28
+ import { newestFindings } from "./assess.js";
29
+ import { toBase64Url } from "@intellectual-frontiers/formats/base64";
30
+ import { statement } from "@intellectual-frontiers/crypto/dsse";
31
+ import { canonicalize } from "./evidence.js";
32
+ import { findingKey } from "./grc.js";
33
+ import { fromHex } from "@intellectual-frontiers/formats/hex";
34
+ import { sha256 } from "@intellectual-frontiers/crypto/sha256";
35
+ import { uuidUrn, uuidV5Of } from "@intellectual-frontiers/crypto/uuid";
36
+ // ---------------------------------------------------------------------------------------------------------------------------- declarations
37
+ const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
38
+ const ref = (kind, ...parts) => `${kind}:${parts.map(encodeURIComponent).join("/")}`;
39
+ function stableText(value) {
40
+ const c = canonicalize(value);
41
+ return c.kind === "ok" ? c.value : String(value);
42
+ }
43
+ /** An RFC 6920 Named Information URI of a SHA-256: `ni:///sha-256;` and the digest in base64url without padding. */
44
+ export function niUri(digest) {
45
+ return `ni:///sha-256;${toBase64Url(fromHex(digest) ?? new Uint8Array(0))}`;
46
+ }
47
+ function requirementsOf(controls, pack) {
48
+ const map = new Map();
49
+ const add = (standard, id, control, title) => {
50
+ const k = JSON.stringify([standard, id]);
51
+ const r = map.get(k) ?? { standard, id, ...(title === undefined ? {} : { title }), controls: new Set() };
52
+ r.controls.add(control);
53
+ map.set(k, r);
54
+ };
55
+ for (const c of controls) {
56
+ if (c.implements.length === 0)
57
+ add(pack, c.id, c.id, c.title);
58
+ for (const r of c.implements)
59
+ add(r.catalog, r.id, c.id);
60
+ }
61
+ return [...map.entries()]
62
+ .sort(([a], [b]) => byText(a, b))
63
+ .map(([, r]) => ({
64
+ standard: r.standard,
65
+ id: r.id,
66
+ ...(r.title === undefined ? {} : { title: r.title }),
67
+ controls: [...r.controls].sort(byText),
68
+ }));
69
+ }
70
+ const PASSING = new Set(["pass"]);
71
+ /** An assessment's declarations, and the standards their requirements are of. */
72
+ export async function declarations(a, o) {
73
+ const controls = new Map();
74
+ for (const c of [...a.controls, ...a.findings.map((f) => f.control)])
75
+ if (!controls.has(c.id))
76
+ controls.set(c.id, c);
77
+ const requirements = requirementsOf([...controls.values()], a.pack.id);
78
+ const keyed = a.findings.map((f) => ({ f, key: findingKey(f), text: stableText(f) }));
79
+ keyed.sort((x, y) => byText(x.key, y.key) || byText(x.text, y.text));
80
+ const count = new Map();
81
+ const evidenceRef = new Map();
82
+ const evidence = [];
83
+ for (const { f, key } of keyed) {
84
+ const n = count.get(key) ?? 0;
85
+ count.set(key, n + 1);
86
+ const uuid = await uuidV5Of(o.namespace, ["evidence", a.pack.id, a.at, key, String(n)]);
87
+ const bomRef = `evidence:${uuid}`;
88
+ evidenceRef.set(f, bomRef);
89
+ const digests = [...new Set(f.evidence)].sort(byText);
90
+ evidence.push({
91
+ "bom-ref": bomRef,
92
+ description: `${f.control.id} on ${f.subject.kind} ${f.subject.id}: ${f.outcome}${f.detail === "" ? "" : `: ${f.detail}`}`,
93
+ ...(digests.length === 0 ? {} : { data: digests.map((d) => ({ name: `sha256:${d}`, contents: { url: niUri(d) } })) }),
94
+ created: f.at,
95
+ });
96
+ }
97
+ const newest = new Set(newestFindings(a.findings));
98
+ const target = ref("target", o.target.name);
99
+ const assessor = ref("assessor", o.assessor.name);
100
+ const claims = [];
101
+ const map = [];
102
+ for (const r of requirements) {
103
+ const label = `${r.standard} ${r.id}`;
104
+ const mine = keyed.map(({ f }) => f).filter((f) => r.controls.includes(f.control.id));
105
+ const refsOf = (fs) => fs.flatMap((f) => evidenceRef.get(f) ?? []);
106
+ const passing = mine.filter((f) => PASSING.has(f.outcome));
107
+ const failing = mine.filter((f) => f.outcome !== "pass" && f.outcome !== "not-applicable");
108
+ const current = mine.filter((f) => newest.has(f) && f.outcome !== "not-applicable");
109
+ const currentPass = current.filter((f) => f.outcome === "pass").length;
110
+ const accepted = current.filter((f) => f.outcome === "accepted").length;
111
+ const open = current.filter((f) => f.outcome !== "pass" && f.outcome !== "accepted");
112
+ const claim = ref("claim", r.standard, r.id);
113
+ claims.push({
114
+ "bom-ref": claim,
115
+ target,
116
+ predicate: `${label} is met by ${r.controls.join(", ")}`,
117
+ reasoning: current.length === 0
118
+ ? "no applicable finding yet"
119
+ : `${currentPass} of ${current.length} applicable findings pass${accepted === 0 ? "" : `, ${accepted} accepted under a waiver`}`,
120
+ ...(passing.length === 0 ? {} : { evidence: refsOf(passing) }),
121
+ ...(failing.length === 0 ? {} : { counterEvidence: refsOf(failing) }),
122
+ });
123
+ const counter = ref("counter-claim", r.standard, r.id);
124
+ if (open.length > 0 || accepted > 0) {
125
+ const against = current.filter((f) => f.outcome !== "pass");
126
+ claims.push({
127
+ "bom-ref": counter,
128
+ target,
129
+ predicate: `${label} is not met for ${[...new Set(against.map((f) => `${f.subject.kind} ${f.subject.id}`))].sort(byText).join(", ")}`,
130
+ reasoning: [...new Set(against.map((f) => f.outcome))].sort(byText).join(", "),
131
+ evidence: refsOf(against),
132
+ });
133
+ }
134
+ const score = current.length === 0 ? 0 : Math.round((currentPass / current.length) * 1000) / 1000;
135
+ map.push({
136
+ requirement: ref("requirement", r.standard, r.id),
137
+ claims: [claim],
138
+ ...(open.length > 0 || accepted > 0 ? { counterClaims: [counter] } : {}),
139
+ conformance: {
140
+ score,
141
+ rationale: current.length === 0 ? "no applicable finding" : `${currentPass} of ${current.length} applicable newest findings pass`,
142
+ },
143
+ });
144
+ }
145
+ const standardIds = [...new Set(requirements.map((r) => r.standard))].sort(byText);
146
+ const standards = standardIds.map((s) => {
147
+ const known = o.standards?.[s];
148
+ return {
149
+ "bom-ref": ref("standard", s),
150
+ name: known?.name ?? s,
151
+ ...(known?.version === undefined ? {} : { version: known.version }),
152
+ ...(known?.description === undefined ? {} : { description: known.description }),
153
+ ...(known?.owner === undefined ? {} : { owner: known.owner }),
154
+ requirements: requirements
155
+ .filter((r) => r.standard === s)
156
+ .map((r) => ({
157
+ "bom-ref": ref("requirement", r.standard, r.id),
158
+ identifier: r.id,
159
+ ...(r.title === undefined ? {} : { title: r.title }),
160
+ })),
161
+ };
162
+ });
163
+ return {
164
+ standards,
165
+ declarations: {
166
+ assessors: [{ "bom-ref": assessor, thirdParty: o.assessor.thirdParty, organization: { name: o.assessor.name } }],
167
+ attestations: [{ summary: o.summary ?? `${a.pack.title}: the findings of ${a.at}, by requirement`, assessor, map }],
168
+ claims,
169
+ evidence,
170
+ targets: {
171
+ components: [
172
+ {
173
+ "bom-ref": target,
174
+ type: o.target.type ?? "platform",
175
+ name: o.target.name,
176
+ ...(o.target.version === undefined ? {} : { version: o.target.version }),
177
+ },
178
+ ],
179
+ },
180
+ },
181
+ };
182
+ }
183
+ /** An assessment as a CycloneDX 1.6 BOM of its declarations: the serial number a version 5 UUID of the pack and time in the namespace. */
184
+ export async function cyclonedxBom(a, o) {
185
+ const d = await declarations(a, o);
186
+ return {
187
+ bomFormat: "CycloneDX",
188
+ specVersion: "1.6",
189
+ serialNumber: uuidUrn(await uuidV5Of(o.namespace, ["cyclonedx-bom", a.pack.id, a.at])),
190
+ version: 1,
191
+ metadata: {
192
+ timestamp: a.at,
193
+ ...(o.tool === undefined ? {} : { tools: { components: [{ type: "application", name: o.tool.name, version: o.tool.version }] } }),
194
+ },
195
+ definitions: { standards: d.standards },
196
+ declarations: d.declarations,
197
+ };
198
+ }
199
+ // ---------------------------------------------------------------------------------------------------------------------------- in-toto
200
+ /** The in-toto predicate type of a CycloneDX BOM. */
201
+ export const CYCLONEDX_PREDICATE_TYPE = "https://cyclonedx.org/bom";
202
+ /** A subject: the name and the SHA-256 of the bytes. */
203
+ export async function digestSubject(name, bytes) {
204
+ return { name, digest: { sha256: await sha256(bytes) } };
205
+ }
206
+ /** An in-toto Statement v1 of a predicate of the type named about the subjects. */
207
+ export function intotoStatement(subjects, predicateType, predicate) {
208
+ return { ...statement(subjects, predicateType, predicate), subject: subjects, predicateType };
209
+ }
210
+ /** A CycloneDX BOM as the predicate of an in-toto statement about the subjects. */
211
+ export function bomStatement(bom, subjects) {
212
+ return intotoStatement(subjects, CYCLONEDX_PREDICATE_TYPE, bom);
213
+ }
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Evidence: JSON's canonical form and the digest it gives, a hash-chained ledger, a manifest of files and a deterministic bundle (commons
3
+ * 0001-grc-engineering FR-006 to FR-009). The kernel holds no key: a manifest's signature is made and checked by functions the caller gives.
4
+ *
5
+ * - `canonicalize` writes RFC 8785's JSON Canonicalization Scheme: object members sorted by the UTF-16 code units of their names, numbers
6
+ * as ECMAScript writes them, strings with JSON's minimal escapes, no white space; `evidenceDigest` is the SHA-256 of its UTF-8 (FR-006).
7
+ * - A ledger is append-only and hash-chained: entry `seq` (from 1) holds the digest of the entry before (64 zeros for the first), its time,
8
+ * kind, subject and evidence digest, and its own `digest`, the SHA-256 of the canonical form of the rest. It is written as JSON lines,
9
+ * and `verifyLedger` names the first entry that was changed, removed, inserted or reordered (FR-007). Removing the last entries leaves a
10
+ * valid chain, so a signature covers a head (`LedgerHead`) that `verifyLedger` is then given.
11
+ * - A manifest lists files by path, size and SHA-256 in the byte order of their paths; `verifyManifest` names each file missing, extra or
12
+ * different, and `verifyManifestSignature` checks its bytes with a `VerifySignature` the caller gives (FR-008).
13
+ * - A bundle is a gzip of a ustar archive whose first entry is the manifest (then its signature, if any), the same bytes every time for the
14
+ * same files; `readBundle` gives the files back only where the manifest (and the signature, if a verifier is given) holds (FR-009).
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * import { canonicalize, evidenceDigest } from "./evidence.js";
19
+ * canonicalize({ b: 1, a: 2.0 }); // { kind: "ok", value: '{"a":2,"b":1}' }
20
+ * await evidenceDigest({ a: 2, b: 1 }); // the same digest as for { b: 1, a: 2.0 }
21
+ * ```
22
+ *
23
+ * @module
24
+ */
25
+ import { type Decoder, type DecodeError, type Result } from "@intellectual-frontiers/core";
26
+ import { type ArchiveError, type Files } from "@intellectual-frontiers/formats/archive";
27
+ import { type Instant, type SubjectRef } from "./grc.js";
28
+ import { type Sha256 } from "@intellectual-frontiers/crypto/sha256";
29
+ /** Why a value has no canonical JSON form: where it is (`$.a[2]`) and what it is. */
30
+ export type CanonicalError = {
31
+ readonly kind: "canonical";
32
+ readonly path: string;
33
+ readonly reason: string;
34
+ };
35
+ /**
36
+ * A value's canonical JSON text (RFC 8785): plain objects, arrays, strings, finite numbers, booleans and `null`. An object member whose
37
+ * value is `undefined` is left out, as `JSON.stringify` leaves it; anything else that is not JSON (a non-finite number, a lone surrogate,
38
+ * a `Date`, a class instance, a cycle, a hole) is an error naming where it is.
39
+ */
40
+ export declare function canonicalize(value: unknown): Result<string, CanonicalError>;
41
+ /** A value's canonical JSON as UTF-8 bytes. */
42
+ export declare function canonicalBytes(value: unknown): Result<Uint8Array, CanonicalError>;
43
+ /** The address of a piece of evidence: the SHA-256 of its canonical JSON, the same on every runtime. */
44
+ export declare function evidenceDigest(value: unknown): Promise<Result<Sha256, CanonicalError>>;
45
+ /** The digest the first entry of a ledger names as the one before it: 64 zeros. */
46
+ export declare const GENESIS: Sha256;
47
+ /** What is appended to a ledger: when, what kind of record (`observation`, `assessment`), about what, and the digest of the evidence. */
48
+ export type LedgerRecord = {
49
+ readonly at: Instant;
50
+ readonly kind: string;
51
+ readonly subject: SubjectRef;
52
+ readonly evidence: Sha256;
53
+ };
54
+ /** One entry of a ledger: a record with its place, the digest of the entry before it and its own digest. */
55
+ export type LedgerEntry = LedgerRecord & {
56
+ readonly seq: number;
57
+ readonly prev: Sha256;
58
+ readonly digest: Sha256;
59
+ };
60
+ /** The last entry a ledger is known to have reached (what a signature covers): `{ seq: 0, digest: GENESIS }` for an empty one. */
61
+ export type LedgerHead = {
62
+ readonly seq: number;
63
+ readonly digest: Sha256;
64
+ };
65
+ /** The digest an entry must carry: the SHA-256 of the canonical JSON of every field but `digest`. */
66
+ export declare function entryDigest(e: Omit<LedgerEntry, "digest">): Promise<Result<Sha256, CanonicalError>>;
67
+ /** The head of a ledger: its last entry's place and digest. */
68
+ export declare function ledgerHead(entries: readonly LedgerEntry[]): LedgerHead;
69
+ /** The ledger with one record appended; an error where the record has no canonical form (a lone surrogate in its kind or subject). */
70
+ export declare function appendEntry(entries: readonly LedgerEntry[], record: LedgerRecord): Promise<Result<readonly LedgerEntry[], CanonicalError>>;
71
+ /** A ledger as JSON lines: each entry's canonical JSON and a line feed. */
72
+ export declare function ledgerLines(entries: readonly LedgerEntry[]): string;
73
+ /** A ledger entry as its JSON holds it. */
74
+ export declare const ledgerEntryDecoder: Decoder<LedgerEntry>;
75
+ /** Why the text of a ledger could not be read: the line (from 1) and what is wrong there. */
76
+ export type LedgerParseError = {
77
+ readonly kind: "ledger-line";
78
+ readonly line: number;
79
+ readonly error: DecodeError;
80
+ };
81
+ /** A ledger parse error as one sentence. */
82
+ export declare function formatLedgerParseError(e: LedgerParseError): string;
83
+ /** A ledger from its JSON lines (blank lines skipped), each decoded; the chain is checked by `verifyLedger`. */
84
+ export declare function parseLedger(text: string): Result<readonly LedgerEntry[], LedgerParseError>;
85
+ /** The kind of tampering a broken ledger shows. */
86
+ export type Tampering = "changed" | "removed" | "inserted" | "reordered";
87
+ /** Where a ledger breaks: the place (from 1) of the first entry that was changed, removed, inserted or reordered, and why that is said. */
88
+ export type LedgerBreak = {
89
+ readonly kind: Tampering;
90
+ readonly seq: number;
91
+ readonly reason: string;
92
+ };
93
+ /** A ledger break as one sentence. */
94
+ export declare function formatLedgerBreak(b: LedgerBreak): string;
95
+ /**
96
+ * The ledger's head where every entry's digest is the digest of its content, its `seq` its place and its `prev` the digest of the entry
97
+ * before it (and, where a `head` is given, the ledger reaches it with that digest); else the first break. Entry N edited in place is
98
+ * `changed` at N (edited and re-hashed, it is found at N + 1's link and still named N); entry N gone is `removed` at N; a forged entry
99
+ * slipped in at N is `inserted` at N; two entries swapped are `reordered` at the first of them.
100
+ */
101
+ export declare function verifyLedger(entries: readonly LedgerEntry[], head?: LedgerHead): Promise<Result<LedgerHead, LedgerBreak>>;
102
+ /** One file of a manifest. */
103
+ export type ManifestEntry = {
104
+ readonly path: string;
105
+ readonly size: number;
106
+ readonly sha256: Sha256;
107
+ };
108
+ /** Files by path, size and SHA-256, in the byte order of their UTF-8 paths. */
109
+ export type Manifest = {
110
+ readonly files: readonly ManifestEntry[];
111
+ };
112
+ /** The manifest of some files. */
113
+ export declare function manifestOf(files: Files): Promise<Manifest>;
114
+ /** A manifest's bytes: its canonical JSON (RFC 8785) and a line feed. These are the bytes a signature covers. */
115
+ export declare function manifestBytes(m: Manifest): Uint8Array;
116
+ /** Why a manifest could not be read. */
117
+ export type ManifestError = {
118
+ readonly kind: "manifest-decode";
119
+ readonly error: DecodeError;
120
+ } | {
121
+ readonly kind: "manifest-order";
122
+ readonly path: string;
123
+ } | {
124
+ readonly kind: "manifest-unsafe-path";
125
+ readonly path: string;
126
+ };
127
+ /** A manifest error as one sentence. */
128
+ export declare function formatManifestError(e: ManifestError): string;
129
+ /** A manifest from its bytes (or text), each path checked safe and the list checked in strict byte order. */
130
+ export declare function parseManifest(input: Uint8Array | string): Result<Manifest, ManifestError>;
131
+ /** One way files differ from their manifest. */
132
+ export type ManifestMismatch = {
133
+ readonly kind: "missing";
134
+ readonly path: string;
135
+ } | {
136
+ readonly kind: "extra";
137
+ readonly path: string;
138
+ } | {
139
+ readonly kind: "different";
140
+ readonly path: string;
141
+ readonly expected: {
142
+ readonly size: number;
143
+ readonly sha256: Sha256;
144
+ };
145
+ readonly actual: {
146
+ readonly size: number;
147
+ readonly sha256: Sha256;
148
+ };
149
+ };
150
+ /** A mismatch as one sentence. */
151
+ export declare function formatManifestMismatch(m: ManifestMismatch): string;
152
+ /** Whether files are exactly what the manifest lists; else every file missing, extra or different, in the byte order of their paths. */
153
+ export declare function verifyManifest(m: Manifest, files: Files): Promise<Result<Manifest, readonly ManifestMismatch[]>>;
154
+ /** A check of a signature over a message, with a key the caller holds (an in-toto/DSSE verifier, `ssh-keygen -Y verify`, ...). */
155
+ export type VerifySignature = (message: Uint8Array, signature: Uint8Array) => boolean | Promise<boolean>;
156
+ /** A signer of a message, with a key the caller holds. */
157
+ export type Sign = (message: Uint8Array) => Uint8Array | Promise<Uint8Array>;
158
+ /** Why a signed manifest is refused. */
159
+ export type SignatureError = {
160
+ readonly kind: "unsigned";
161
+ } | {
162
+ readonly kind: "bad-signature";
163
+ readonly reason: string;
164
+ } | ManifestError;
165
+ /** The manifest its bytes hold, where the signature over those exact bytes verifies; a verifier that throws is a bad signature. */
166
+ export declare function verifyManifestSignature(bytes: Uint8Array, signature: Uint8Array, verify: VerifySignature): Promise<Result<Manifest, SignatureError>>;
167
+ /** The path of a bundle's manifest, its first entry. */
168
+ export declare const BUNDLE_MANIFEST = "MANIFEST.json";
169
+ /** The path of a bundle manifest's signature, its second entry where there is one. */
170
+ export declare const BUNDLE_SIGNATURE = "MANIFEST.json.sig";
171
+ /** What a bundle read back holds: its manifest, its files (the manifest and signature left out), and whether its signature verified. */
172
+ export type Bundle = {
173
+ readonly manifest: Manifest;
174
+ readonly files: Files;
175
+ readonly signature: {
176
+ readonly kind: "none";
177
+ } | {
178
+ readonly kind: "verified";
179
+ } | {
180
+ readonly kind: "unverified";
181
+ readonly bytes: Uint8Array;
182
+ };
183
+ };
184
+ /** Why a bundle could not be written or read. */
185
+ export type BundleError = {
186
+ readonly kind: "archive";
187
+ readonly error: ArchiveError;
188
+ } | {
189
+ readonly kind: "reserved-path";
190
+ readonly path: string;
191
+ } | {
192
+ readonly kind: "no-manifest";
193
+ } | {
194
+ readonly kind: "mismatch";
195
+ readonly mismatches: readonly ManifestMismatch[];
196
+ } | SignatureError;
197
+ /** A bundle error as one sentence. */
198
+ export declare function formatBundleError(e: BundleError): string;
199
+ /**
200
+ * A bundle of files: a gzip of a ustar archive whose first entry is the manifest, then its signature where a signer is given, then the
201
+ * files (their folders first) in byte order, every time and date fixed, so the same files (and a deterministic signer) give the same bytes.
202
+ */
203
+ export declare function writeBundle(files: Files, options?: {
204
+ readonly sign?: Sign;
205
+ }): Promise<Result<Uint8Array, BundleError>>;
206
+ /**
207
+ * A bundle's files, where its first entry is a manifest the files match exactly (one added, removed or changed is named); with `verify`,
208
+ * also where its signature verifies over the manifest's bytes (a bundle with none is then refused as unsigned).
209
+ */
210
+ export declare function readBundle(data: Uint8Array, options?: {
211
+ readonly verify?: VerifySignature;
212
+ }): Promise<Result<Bundle, BundleError>>;