@agledger/verify-core 2.1.0 → 4.0.0
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/LICENSE +18 -18
- package/README.md +869 -53
- package/dist/acknowledgements.d.ts +32 -0
- package/dist/acknowledgements.js +88 -0
- package/dist/anchors.d.ts +349 -0
- package/dist/anchors.js +654 -0
- package/dist/attestation.d.ts +98 -0
- package/dist/attestation.js +145 -0
- package/dist/audit-export.d.ts +404 -29
- package/dist/audit-export.js +547 -28
- package/dist/batch-head.d.ts +28 -0
- package/dist/batch-head.js +169 -0
- package/dist/batch.d.ts +69 -0
- package/dist/batch.js +99 -0
- package/dist/bulk-export.d.ts +161 -0
- package/dist/bulk-export.js +711 -0
- package/dist/cbor-strict.d.ts +9 -0
- package/dist/cbor-strict.js +14 -0
- package/dist/chain.d.ts +221 -31
- package/dist/chain.js +339 -65
- package/dist/claim.d.ts +23 -0
- package/dist/claim.js +100 -0
- package/dist/export-anchors.d.ts +84 -0
- package/dist/export-anchors.js +109 -0
- package/dist/export-evidence.d.ts +90 -0
- package/dist/export-evidence.js +186 -0
- package/dist/export-pages.d.ts +476 -0
- package/dist/export-pages.js +586 -0
- package/dist/failures.d.ts +44 -26
- package/dist/failures.js +81 -31
- package/dist/federation-wire.d.ts +106 -20
- package/dist/federation-wire.js +286 -76
- package/dist/history-seal.d.ts +100 -0
- package/dist/history-seal.js +301 -0
- package/dist/index.d.ts +37 -9
- package/dist/index.js +18 -5
- package/dist/instant.d.ts +1 -1
- package/dist/instant.js +1 -1
- package/dist/key-statements.d.ts +160 -11
- package/dist/key-statements.js +261 -60
- package/dist/ml-dsa-kats.d.ts +18 -0
- package/dist/ml-dsa-kats.js +241 -0
- package/dist/options.js +4 -4
- package/dist/primitives.d.ts +287 -47
- package/dist/primitives.js +673 -101
- package/dist/read-log.d.ts +350 -0
- package/dist/read-log.js +816 -0
- package/dist/schema-chain-export.d.ts +82 -0
- package/dist/schema-chain-export.js +474 -0
- package/dist/walk-anchors.d.ts +115 -0
- package/dist/walk-anchors.js +133 -0
- package/dist/walk-checkpoints.d.ts +125 -0
- package/dist/walk-checkpoints.js +118 -0
- package/package.json +9 -5
|
@@ -0,0 +1,586 @@
|
|
|
1
|
+
import { auditVaultExportKind, capVerdict } from './audit-export.js';
|
|
2
|
+
import { BATCH_PENDING_GRACE_SECONDS } from './batch.js';
|
|
3
|
+
import { decodeSignedClaim } from './claim.js';
|
|
4
|
+
import { rfc3339Ms } from './instant.js';
|
|
5
|
+
import { deepEqual, runtimeBelowFloor } from './primitives.js';
|
|
6
|
+
/**
|
|
7
|
+
* Each page's read time: its own `exportMetadata.exportDate`, else
|
|
8
|
+
* `option`, else `fallback` (with `fallbackSource`). A page whose
|
|
9
|
+
* `exportDate` is present and not an RFC 3339 instant states none, and
|
|
10
|
+
* `notes` says so.
|
|
11
|
+
*/
|
|
12
|
+
export function pageReadTimes(pages, option, notes, fallback = null) {
|
|
13
|
+
return pages.map((page, i) => {
|
|
14
|
+
const own = page.exportMetadata.exportDate;
|
|
15
|
+
if (typeof own === 'string' && !Number.isNaN(rfc3339Ms(own)))
|
|
16
|
+
return { exportDate: own, source: 'pages' };
|
|
17
|
+
if (own !== undefined && own !== null)
|
|
18
|
+
notes.push(`Page ${i + 1}'s exportMetadata.exportDate ${JSON.stringify(own)} is not an RFC 3339 instant, so the page was read as stating no read time.`);
|
|
19
|
+
if (option !== undefined)
|
|
20
|
+
return { exportDate: option, source: 'option' };
|
|
21
|
+
return fallback !== null ? { exportDate: fallback.exportDate, source: fallback.source } : { exportDate: null, source: null };
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
/** The latest of some page read times, and where the read times came from. */
|
|
25
|
+
export function latestReadTime(times) {
|
|
26
|
+
let latest = null;
|
|
27
|
+
const sources = new Set();
|
|
28
|
+
for (const t of times) {
|
|
29
|
+
if (t.exportDate === null || t.source === null)
|
|
30
|
+
continue;
|
|
31
|
+
sources.add(t.source);
|
|
32
|
+
if (latest === null || rfc3339Ms(t.exportDate) > rfc3339Ms(latest.exportDate))
|
|
33
|
+
latest = { exportDate: t.exportDate, source: t.source };
|
|
34
|
+
}
|
|
35
|
+
return {
|
|
36
|
+
exportDate: latest?.exportDate ?? null,
|
|
37
|
+
source: sources.size === 0 ? null : sources.size === 1 ? [...sources][0] ?? null : 'mixed',
|
|
38
|
+
latestSource: latest?.source ?? null,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
const PAGE_LEVEL_KEYS = new Set(['kind', 'chainMetadata', 'verificationGuide', 'nextCursor', 'heldBack', 'holdbackSeconds', 'retryAfterSeconds', 'hasMore', 'total', 'bulkExport', 'bulkExports']);
|
|
42
|
+
export function isRecord(value) {
|
|
43
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
44
|
+
}
|
|
45
|
+
/** One NDJSON page: its metadata line and the entry lines after it, in the JSON page's shape. */
|
|
46
|
+
function pageFromNdjson(metadata, rows) {
|
|
47
|
+
const page = {};
|
|
48
|
+
const exportMetadata = {};
|
|
49
|
+
for (const [key, value] of Object.entries(metadata)) {
|
|
50
|
+
if (key === 'kind')
|
|
51
|
+
continue;
|
|
52
|
+
if (PAGE_LEVEL_KEYS.has(key))
|
|
53
|
+
page[key] = value;
|
|
54
|
+
else
|
|
55
|
+
exportMetadata[key] = value;
|
|
56
|
+
}
|
|
57
|
+
page['exportMetadata'] = exportMetadata;
|
|
58
|
+
page['data'] = rows.map(({ kind: _kind, ...row }) => row);
|
|
59
|
+
return page;
|
|
60
|
+
}
|
|
61
|
+
/** The pages in NDJSON text: each `kind: 'metadata'` line opens one, and the entry lines after it are its rows. */
|
|
62
|
+
function ndjsonPages(text, fn) {
|
|
63
|
+
const pages = [];
|
|
64
|
+
let metadata = null;
|
|
65
|
+
let rows = [];
|
|
66
|
+
const lines = text.split(/\r?\n/);
|
|
67
|
+
lines.forEach((line, i) => {
|
|
68
|
+
if (line.trim() === '')
|
|
69
|
+
return;
|
|
70
|
+
let value;
|
|
71
|
+
try {
|
|
72
|
+
value = JSON.parse(line);
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
throw new TypeError(`${fn}: NDJSON line ${i + 1} is not JSON (${err.message}).`, { cause: err });
|
|
76
|
+
}
|
|
77
|
+
if (!isRecord(value) || (value['kind'] !== 'metadata' && value['kind'] !== 'entry')) {
|
|
78
|
+
throw new TypeError(`${fn}: NDJSON line ${i + 1} is neither a kind:"metadata" line nor a kind:"entry" line.`);
|
|
79
|
+
}
|
|
80
|
+
if (value['kind'] === 'metadata') {
|
|
81
|
+
if (metadata !== null)
|
|
82
|
+
pages.push(pageFromNdjson(metadata, rows));
|
|
83
|
+
metadata = value;
|
|
84
|
+
rows = [];
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
if (metadata === null)
|
|
88
|
+
throw new TypeError(`${fn}: NDJSON line ${i + 1} is an entry before any kind:"metadata" line; each page starts with its metadata line.`);
|
|
89
|
+
rows.push(value);
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
if (metadata !== null)
|
|
93
|
+
pages.push(pageFromNdjson(metadata, rows));
|
|
94
|
+
return pages;
|
|
95
|
+
}
|
|
96
|
+
/** The pages one string holds: a JSON page, a JSON array of pages, or NDJSON. */
|
|
97
|
+
function pagesOfText(text, fn) {
|
|
98
|
+
let whole;
|
|
99
|
+
try {
|
|
100
|
+
whole = JSON.parse(text);
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
whole = undefined;
|
|
104
|
+
}
|
|
105
|
+
if (Array.isArray(whole))
|
|
106
|
+
return whole.map((p) => ({ page: p, format: 'json' }));
|
|
107
|
+
if (isRecord(whole) && whole['kind'] !== 'metadata')
|
|
108
|
+
return [{ page: whole, format: 'json' }];
|
|
109
|
+
return ndjsonPages(text, fn).map((page) => ({ page, format: 'ndjson' }));
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The input as pages, each checked to be a page of `kind`. Throws
|
|
113
|
+
* `TypeError` on anything that is not one: a malformed NDJSON line, a page
|
|
114
|
+
* without `data`, `exportMetadata` or `chainMetadata`, or a page of the
|
|
115
|
+
* other export.
|
|
116
|
+
*/
|
|
117
|
+
export function readPages(input, kind, fn) {
|
|
118
|
+
const parts = Array.isArray(input) ? input : [input];
|
|
119
|
+
const pages = [];
|
|
120
|
+
for (const part of parts) {
|
|
121
|
+
if (typeof part === 'string')
|
|
122
|
+
pages.push(...pagesOfText(part, fn));
|
|
123
|
+
else
|
|
124
|
+
pages.push({ page: part, format: 'json' });
|
|
125
|
+
}
|
|
126
|
+
const other = kind === 'bulk' ? 'verifySchemaChainExport' : 'verifyBulkExport';
|
|
127
|
+
pages.forEach(({ page }, i) => {
|
|
128
|
+
const what = `${fn}: page ${i + 1}`;
|
|
129
|
+
if (!isRecord(page) || !Array.isArray(page['data']) || !isRecord(page['exportMetadata']) || !isRecord(page['chainMetadata'])) {
|
|
130
|
+
throw new TypeError(`${what} is not an export page: { data: [...], exportMetadata: {...}, chainMetadata: {...}, nextCursor }, or its NDJSON form.`);
|
|
131
|
+
}
|
|
132
|
+
const found = auditVaultExportKind(page);
|
|
133
|
+
if (found !== kind) {
|
|
134
|
+
throw new TypeError(found === null
|
|
135
|
+
? `${what} is not a page of ${kind === 'bulk' ? 'GET /v1/audit-vault/export' : 'GET /v1/audit-vault/schema-chain/export'}.`
|
|
136
|
+
: `${what} is a page of ${found === 'bulk' ? 'GET /v1/audit-vault/export' : 'GET /v1/audit-vault/schema-chain/export'}; ${other} reads it.`);
|
|
137
|
+
}
|
|
138
|
+
page['data'].forEach((row, j) => {
|
|
139
|
+
if (!isRecord(row))
|
|
140
|
+
throw new TypeError(`${what}: data[${j}] is not an object.`);
|
|
141
|
+
});
|
|
142
|
+
});
|
|
143
|
+
const order = walkOrder(pages.map((p) => p.page), kind);
|
|
144
|
+
return order.map((i) => ({ ...pages[i], given: i }));
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* The walk order of some pages, as indexes into them: by first entry (the
|
|
148
|
+
* bulk export serves rows in ascending entry id, the schema-chain export in
|
|
149
|
+
* ascending position), a page with no entry right after the page whose
|
|
150
|
+
* nextCursor it carries, and a page with no entry and a null nextCursor
|
|
151
|
+
* last. Ties keep the order given. The cursor is compared as a whole string,
|
|
152
|
+
* never decoded.
|
|
153
|
+
*/
|
|
154
|
+
export function walkOrder(pages, kind) {
|
|
155
|
+
const byCursor = cursorOrder(pages);
|
|
156
|
+
if (byCursor !== null)
|
|
157
|
+
return byCursor;
|
|
158
|
+
const firstOf = (page) => {
|
|
159
|
+
const data = page['data'];
|
|
160
|
+
const row = Array.isArray(data) ? data[0] : undefined;
|
|
161
|
+
if (!isRecord(row))
|
|
162
|
+
return null;
|
|
163
|
+
if (kind === 'bulk')
|
|
164
|
+
return typeof row['id'] === 'string' ? row['id'].toLowerCase() : null;
|
|
165
|
+
return Number.isSafeInteger(row['chainPosition']) ? row['chainPosition'] : null;
|
|
166
|
+
};
|
|
167
|
+
const withRows = [];
|
|
168
|
+
const empty = [];
|
|
169
|
+
pages.forEach((p, i) => (firstOf(p) !== null ? withRows : empty).push(i));
|
|
170
|
+
withRows.sort((a, b) => {
|
|
171
|
+
const x = firstOf(pages[a]);
|
|
172
|
+
const y = firstOf(pages[b]);
|
|
173
|
+
return x === y ? a - b : x < y ? -1 : 1;
|
|
174
|
+
});
|
|
175
|
+
const out = [...withRows];
|
|
176
|
+
const trailing = [];
|
|
177
|
+
for (const i of empty) {
|
|
178
|
+
const cursor = pages[i]['nextCursor'];
|
|
179
|
+
if (typeof cursor !== 'string' || cursor === '') {
|
|
180
|
+
trailing.push(i);
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
const after = out.findLastIndex((j) => pages[j]['nextCursor'] === cursor);
|
|
184
|
+
if (after === -1)
|
|
185
|
+
trailing.unshift(i);
|
|
186
|
+
else
|
|
187
|
+
out.splice(after + 1, 0, i);
|
|
188
|
+
}
|
|
189
|
+
return [...out, ...trailing];
|
|
190
|
+
}
|
|
191
|
+
/** The cursor a page states it was requested with: a string, null, or undefined when it states none. */
|
|
192
|
+
export function requestCursor(page) {
|
|
193
|
+
const meta = page['exportMetadata'];
|
|
194
|
+
if (meta === null || typeof meta !== 'object' || Array.isArray(meta) || !('cursor' in meta))
|
|
195
|
+
return undefined;
|
|
196
|
+
const cursor = meta['cursor'];
|
|
197
|
+
return typeof cursor === 'string' && cursor !== '' ? cursor : cursor === null ? null : undefined;
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* The walk order the pages' cursors give, when every page states the cursor
|
|
201
|
+
* it was requested with and they link from the one requested with none,
|
|
202
|
+
* each page's nextCursor naming the next page's cursor, through every page.
|
|
203
|
+
* Null when they do not, so the order falls back to what the pages hold and
|
|
204
|
+
* the break is reported by {@link cursorLinkReasons}.
|
|
205
|
+
*/
|
|
206
|
+
function cursorOrder(pages) {
|
|
207
|
+
const cursors = pages.map(requestCursor);
|
|
208
|
+
if (pages.length === 0 || cursors.some((c) => c === undefined))
|
|
209
|
+
return null;
|
|
210
|
+
const start = cursors.indexOf(null);
|
|
211
|
+
if (start === -1 || cursors.lastIndexOf(null) !== start)
|
|
212
|
+
return null;
|
|
213
|
+
const out = [start];
|
|
214
|
+
const used = new Set(out);
|
|
215
|
+
while (out.length < pages.length) {
|
|
216
|
+
const next = pages[out.at(-1) ?? -1]?.['nextCursor'];
|
|
217
|
+
if (typeof next !== 'string')
|
|
218
|
+
return null;
|
|
219
|
+
// A held-back page hands back the cursor it was sent, so the next page
|
|
220
|
+
// may carry the same cursor as the one before: take the first unused.
|
|
221
|
+
const j = cursors.findIndex((c, k) => c === next && !used.has(k));
|
|
222
|
+
if (j === -1)
|
|
223
|
+
return null;
|
|
224
|
+
out.push(j);
|
|
225
|
+
used.add(j);
|
|
226
|
+
}
|
|
227
|
+
return out;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Each reason the pages, in walk order, do not link by their cursors: the
|
|
231
|
+
* first page requested with a cursor (a page before it is missing), or a page
|
|
232
|
+
* requested with a cursor other than the nextCursor of the page before it.
|
|
233
|
+
* Empty when they link, and when no page states its cursor (one note says so);
|
|
234
|
+
* a walk where only some pages state it gets a reason for each that does not.
|
|
235
|
+
*/
|
|
236
|
+
export function cursorLinkReasons(pages, notes) {
|
|
237
|
+
const cursors = pages.map(requestCursor);
|
|
238
|
+
if (cursors.every((c) => c === undefined)) {
|
|
239
|
+
if (pages.length > 0)
|
|
240
|
+
notes.push('No page states the cursor it was requested with (exportMetadata.cursor, from Server 4.0.0), so a page missing between two given pages is seen only where a chain shows it.');
|
|
241
|
+
return [];
|
|
242
|
+
}
|
|
243
|
+
const reasons = [];
|
|
244
|
+
cursors.forEach((cursor, i) => {
|
|
245
|
+
const n = i + 1;
|
|
246
|
+
if (cursor === undefined) {
|
|
247
|
+
reasons.push(`Page ${n} states no cursor it was requested with, and other pages do: they are not one walk from one Server.`);
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (i === 0) {
|
|
251
|
+
if (cursor !== null)
|
|
252
|
+
reasons.push('The first page was requested with a cursor (exportMetadata.cursor), so the page or pages before it are missing. Add them, starting from the page requested with none.');
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
const before = pages[i - 1]?.['nextCursor'];
|
|
256
|
+
if (cursor === null)
|
|
257
|
+
reasons.push(`Page ${n} was requested with no cursor, so it starts another walk: the pages are not one walk.`);
|
|
258
|
+
else if (cursor !== before)
|
|
259
|
+
reasons.push(`Page ${n} was requested with a cursor other than page ${i}'s nextCursor: a page between them is missing, or the pages are not one walk.`);
|
|
260
|
+
});
|
|
261
|
+
return reasons;
|
|
262
|
+
}
|
|
263
|
+
/** Which of the pages state the cursor they were requested with. */
|
|
264
|
+
export function cursorsStated(pages) {
|
|
265
|
+
const stated = pages.filter((p) => requestCursor(p) !== undefined).length;
|
|
266
|
+
return stated === 0 ? 'none' : stated === pages.length ? 'all' : 'some';
|
|
267
|
+
}
|
|
268
|
+
/** Throw `TypeError` on an `exportDate` that is not a strict RFC 3339 instant. */
|
|
269
|
+
export function assertExportDate(fn, value) {
|
|
270
|
+
if (value === undefined)
|
|
271
|
+
return;
|
|
272
|
+
if (typeof value !== 'string' || Number.isNaN(rfc3339Ms(value))) {
|
|
273
|
+
throw new TypeError(`${fn}: exportDate must be an RFC 3339 instant such as 2026-12-04T10:00:00Z (got ${JSON.stringify(value)}).`);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Merge the key material of every page. A key, a key statement, a batch head
|
|
278
|
+
* or a history seal that two pages carry under one id with different bytes is
|
|
279
|
+
* EXPORT_PAGE_CONFLICT, and the first page's stands. A key's window may close
|
|
280
|
+
* during a walk (a retirement, or a distrust instant added), so a later page's
|
|
281
|
+
* window wins where it only adds those; any other difference is a conflict.
|
|
282
|
+
* New keys and statements on later pages are added. `anchoredFrom` is the last
|
|
283
|
+
* page's: the Server's own key, which can change during a walk.
|
|
284
|
+
*/
|
|
285
|
+
export function mergePageMetadata(pages) {
|
|
286
|
+
const findings = [];
|
|
287
|
+
const keys = {};
|
|
288
|
+
const windows = {};
|
|
289
|
+
const statements = {};
|
|
290
|
+
const statementPage = new Map();
|
|
291
|
+
const heads = new Map();
|
|
292
|
+
const seals = new Map();
|
|
293
|
+
const unsigned = new Set();
|
|
294
|
+
let anchoredFrom;
|
|
295
|
+
let format = null;
|
|
296
|
+
pages.forEach((p, i) => {
|
|
297
|
+
const n = i + 1;
|
|
298
|
+
const m = p.exportMetadata;
|
|
299
|
+
// The walk is read in the first page's format, or in the first other
|
|
300
|
+
// format a later page states, so a page this verifier does not read
|
|
301
|
+
// fails UNSUPPORTED_FORMAT by name.
|
|
302
|
+
const supported = (f) => f.exportFormatVersion === '2.0' && f.canonicalization === 'RFC8949-CDE';
|
|
303
|
+
if (format === null || (supported(format) && !supported(m))) {
|
|
304
|
+
format = { exportFormatVersion: m.exportFormatVersion, canonicalization: m.canonicalization };
|
|
305
|
+
}
|
|
306
|
+
for (const [keyId, spki] of Object.entries(isRecord(m.signingPublicKeys) ? m.signingPublicKeys : {})) {
|
|
307
|
+
if (keys[keyId] === undefined)
|
|
308
|
+
keys[keyId] = spki;
|
|
309
|
+
else if (keys[keyId] !== spki)
|
|
310
|
+
findings.push({ code: 'EXPORT_PAGE_CONFLICT', page: n, detail: `Page ${n} publishes key ${keyId} as different bytes than an earlier page.` });
|
|
311
|
+
}
|
|
312
|
+
for (const [keyId, window] of Object.entries(isRecord(m.signingKeyWindows) ? m.signingKeyWindows : {})) {
|
|
313
|
+
const known = windows[keyId];
|
|
314
|
+
if (known === undefined || !isRecord(window)) {
|
|
315
|
+
if (known === undefined)
|
|
316
|
+
windows[keyId] = window;
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
const closes = known.activatedAt === window.activatedAt
|
|
320
|
+
&& (known.retiredAt === window.retiredAt || known.retiredAt === null)
|
|
321
|
+
&& (known.distrustedFrom === window.distrustedFrom || known.distrustedFrom === undefined);
|
|
322
|
+
if (closes)
|
|
323
|
+
windows[keyId] = window;
|
|
324
|
+
else
|
|
325
|
+
findings.push({ code: 'EXPORT_PAGE_CONFLICT', page: n, detail: `Page ${n} gives key ${keyId} the window ${JSON.stringify(window)}, and an earlier page ${JSON.stringify(known)}: a window only closes during a walk.` });
|
|
326
|
+
}
|
|
327
|
+
for (const [keyId, list] of Object.entries(isRecord(m.signingKeyStatements) ? m.signingKeyStatements : {})) {
|
|
328
|
+
if (!Array.isArray(list)) {
|
|
329
|
+
statements[keyId] ??= list;
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
const into = (statements[keyId] ??= []);
|
|
333
|
+
for (const st of list) {
|
|
334
|
+
const id = isRecord(st) && typeof st['id'] === 'string' ? `${keyId}|${st['id']}` : null;
|
|
335
|
+
const same = into.find((s) => (id !== null && isRecord(s) && `${keyId}|${String(s['id'])}` === id) || deepEqual(s, st));
|
|
336
|
+
if (same === undefined) {
|
|
337
|
+
into.push(st);
|
|
338
|
+
if (id !== null)
|
|
339
|
+
statementPage.set(id, n);
|
|
340
|
+
}
|
|
341
|
+
else if (!deepEqual(same, st)) {
|
|
342
|
+
findings.push({ code: 'EXPORT_PAGE_CONFLICT', page: n, detail: `Page ${n} carries key statement ${String(st['id'])} of key ${keyId} with different content than page ${statementPage.get(id ?? '') ?? 'an earlier one'}.` });
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
for (const head of Array.isArray(m.batchHeads) ? m.batchHeads : []) {
|
|
347
|
+
if (!isRecord(head) || typeof head['id'] !== 'string')
|
|
348
|
+
continue;
|
|
349
|
+
const id = head['id'].toLowerCase();
|
|
350
|
+
const known = heads.get(id);
|
|
351
|
+
if (known === undefined)
|
|
352
|
+
heads.set(id, { head, page: n });
|
|
353
|
+
else if (!deepEqual(known.head, head))
|
|
354
|
+
findings.push({ code: 'EXPORT_PAGE_CONFLICT', page: n, detail: `Page ${n} carries batch head ${head['id']} with different content than page ${known.page}.` });
|
|
355
|
+
}
|
|
356
|
+
for (const seal of Array.isArray(m.historySeals) ? m.historySeals : []) {
|
|
357
|
+
if (!isRecord(seal) || typeof seal['id'] !== 'string')
|
|
358
|
+
continue;
|
|
359
|
+
const id = seal['id'].toLowerCase();
|
|
360
|
+
const known = seals.get(id);
|
|
361
|
+
if (known === undefined)
|
|
362
|
+
seals.set(id, { seal, page: n });
|
|
363
|
+
else if (!deepEqual(known.seal, seal))
|
|
364
|
+
findings.push({ code: 'EXPORT_PAGE_CONFLICT', page: n, detail: `Page ${n} carries history seal ${seal['id']} with different content than page ${known.page}.` });
|
|
365
|
+
}
|
|
366
|
+
if (m.anchoredFrom !== undefined)
|
|
367
|
+
anchoredFrom = m.anchoredFrom;
|
|
368
|
+
for (const f of Array.isArray(p.verificationGuide?.unsignedFields) ? p.verificationGuide.unsignedFields : []) {
|
|
369
|
+
if (typeof f === 'string')
|
|
370
|
+
unsigned.add(f);
|
|
371
|
+
}
|
|
372
|
+
});
|
|
373
|
+
const stated = format ?? {};
|
|
374
|
+
const meta = {
|
|
375
|
+
...(stated.exportFormatVersion !== undefined ? { exportFormatVersion: stated.exportFormatVersion } : {}),
|
|
376
|
+
...(stated.canonicalization !== undefined ? { canonicalization: stated.canonicalization } : {}),
|
|
377
|
+
signingPublicKeys: keys,
|
|
378
|
+
signingKeyWindows: windows,
|
|
379
|
+
signingKeyStatements: statements,
|
|
380
|
+
...(anchoredFrom !== undefined ? { anchoredFrom } : {}),
|
|
381
|
+
...(heads.size > 0 ? { batchHeads: [...heads.values()].map((h) => h.head) } : {}),
|
|
382
|
+
...(seals.size > 0 ? { historySeals: [...seals.values()].map((s) => s.seal) } : {}),
|
|
383
|
+
};
|
|
384
|
+
return { meta, findings, unsignedFields: [...unsigned] };
|
|
385
|
+
}
|
|
386
|
+
/** A page row as the record export's entry shape `verifyAuditExport` reads. */
|
|
387
|
+
export function entryOfRow(row) {
|
|
388
|
+
const entry = {
|
|
389
|
+
integrity: {
|
|
390
|
+
payloadHash: row.payloadHash,
|
|
391
|
+
previousHash: row.previousHash,
|
|
392
|
+
coseSign1: row.coseSign1,
|
|
393
|
+
signingKeyId: row.signingKeyId,
|
|
394
|
+
...(row.batch !== undefined ? { batch: row.batch } : {}),
|
|
395
|
+
},
|
|
396
|
+
};
|
|
397
|
+
const copy = (key) => {
|
|
398
|
+
if (row[key] !== undefined)
|
|
399
|
+
entry[key] = row[key];
|
|
400
|
+
};
|
|
401
|
+
copy('chainPosition');
|
|
402
|
+
copy('createdAt');
|
|
403
|
+
copy('recordId');
|
|
404
|
+
copy('entryType');
|
|
405
|
+
copy('payload');
|
|
406
|
+
copy('actorId');
|
|
407
|
+
copy('actorRole');
|
|
408
|
+
copy('actorOwnerId');
|
|
409
|
+
copy('actorOidcIss');
|
|
410
|
+
copy('actorOidcSub');
|
|
411
|
+
copy('actorOidcSynthesized');
|
|
412
|
+
return entry;
|
|
413
|
+
}
|
|
414
|
+
/** The lowest and highest safe-integer position among `rows`, or null when none carries one. */
|
|
415
|
+
export function positionRange(rows) {
|
|
416
|
+
const positions = rows.map((r) => r.chainPosition).filter((p) => Number.isSafeInteger(p) && p >= 1);
|
|
417
|
+
if (positions.length === 0)
|
|
418
|
+
return null;
|
|
419
|
+
return { first: Math.min(...positions), last: Math.max(...positions) };
|
|
420
|
+
}
|
|
421
|
+
/** The base64url JSON object an opaque cursor decodes to, or null. */
|
|
422
|
+
export function decodeCursor(cursor) {
|
|
423
|
+
if (typeof cursor !== 'string' || cursor === '')
|
|
424
|
+
return null;
|
|
425
|
+
try {
|
|
426
|
+
const value = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
|
|
427
|
+
return isRecord(value) ? value : null;
|
|
428
|
+
}
|
|
429
|
+
catch {
|
|
430
|
+
return null;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
/** Verdicts from worst to best. */
|
|
434
|
+
const VERDICT_ORDER = ['failed', 'unverifiable', 'unanchored', 'trusted'];
|
|
435
|
+
/** The worse of two verdicts. */
|
|
436
|
+
export function worseVerdict(a, b) {
|
|
437
|
+
return VERDICT_ORDER.indexOf(a) <= VERDICT_ORDER.indexOf(b) ? a : b;
|
|
438
|
+
}
|
|
439
|
+
const UNSUPPORTED = 'CHAIN_UNSUPPORTED_ALGORITHM';
|
|
440
|
+
/** BATCH_UNATTESTED's detail when nothing dated the read of an entry's page (verify-core's own wording, in chain.ts). */
|
|
441
|
+
const UNDATED = 'nothing dates when this artifact was cut';
|
|
442
|
+
/**
|
|
443
|
+
* Put the walk's result together from its chains and the findings on its
|
|
444
|
+
* pages. The verdict is the worst chain's, `failed` on any page finding, and
|
|
445
|
+
* null on a walk that holds no entry.
|
|
446
|
+
*/
|
|
447
|
+
export function walkResult(input) {
|
|
448
|
+
const { chains, findings, walk } = input;
|
|
449
|
+
const empty = walk.entries === 0;
|
|
450
|
+
let verdict = null;
|
|
451
|
+
let representative;
|
|
452
|
+
for (const c of chains) {
|
|
453
|
+
if (verdict === null || worseVerdict(c.result.verdict, verdict) !== verdict) {
|
|
454
|
+
verdict = c.result.verdict;
|
|
455
|
+
representative = c;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
if (findings.length > 0 && verdict !== null)
|
|
459
|
+
verdict = 'failed';
|
|
460
|
+
const seen = new Set();
|
|
461
|
+
const capped = [];
|
|
462
|
+
for (const c of [...(input.capped ?? []), ...chains.flatMap((ch) => ch.result.capped)]) {
|
|
463
|
+
if (seen.has(c.detail))
|
|
464
|
+
continue;
|
|
465
|
+
seen.add(c.detail);
|
|
466
|
+
capped.push(c);
|
|
467
|
+
}
|
|
468
|
+
if (verdict !== null)
|
|
469
|
+
verdict = capVerdict(verdict, capped);
|
|
470
|
+
if (empty)
|
|
471
|
+
verdict = null;
|
|
472
|
+
const valid = !empty && findings.length === 0 && chains.every((c) => c.result.valid);
|
|
473
|
+
const firstFailed = chains.find((c) => c.result.verdict === 'failed' && c.result.brokenAt !== undefined)
|
|
474
|
+
?? chains.find((c) => c.result.brokenAt !== undefined);
|
|
475
|
+
const brokenAt = findings[0] !== undefined
|
|
476
|
+
? { chainKey: null, position: 0, code: findings[0].code, detail: findings[0].detail }
|
|
477
|
+
: firstFailed?.result.brokenAt !== undefined
|
|
478
|
+
? { chainKey: firstFailed.chainKey, ...firstFailed.result.brokenAt }
|
|
479
|
+
: undefined;
|
|
480
|
+
// The key statements are the walk's, read once per chain: count their
|
|
481
|
+
// uncomputable checks once, and each chain's entries.
|
|
482
|
+
const entryUnsupported = (r) => r.entries.filter((e) => e.code === UNSUPPORTED).length;
|
|
483
|
+
const rep = representative?.result;
|
|
484
|
+
const algorithms = new Map();
|
|
485
|
+
for (const c of chains)
|
|
486
|
+
for (const a of c.result.uncomputable.algorithms)
|
|
487
|
+
algorithms.set(`${a.algorithm ?? ''}|${a.cause}`, a);
|
|
488
|
+
const uncomputable = rep === undefined
|
|
489
|
+
? { count: 0, algorithms: [], consequences: [] }
|
|
490
|
+
: {
|
|
491
|
+
...rep.uncomputable,
|
|
492
|
+
count: chains.reduce((sum, c) => sum + entryUnsupported(c.result), 0) + Math.max(0, rep.uncomputable.count - entryUnsupported(rep)),
|
|
493
|
+
algorithms: [...algorithms.values()],
|
|
494
|
+
consequences: verdict === 'unverifiable' ? [...new Set(chains.flatMap((c) => c.result.uncomputable.consequences))] : [],
|
|
495
|
+
};
|
|
496
|
+
const undated = chains.flatMap((c) => c.result.entries
|
|
497
|
+
.filter((e) => e.code === 'BATCH_UNATTESTED' && (e.detail ?? '').includes(UNDATED))
|
|
498
|
+
.map((e) => ({ chainKey: c.chainKey, position: e.position })));
|
|
499
|
+
const belowFloor = runtimeBelowFloor();
|
|
500
|
+
return {
|
|
501
|
+
verdict,
|
|
502
|
+
empty,
|
|
503
|
+
valid,
|
|
504
|
+
totalEntries: chains.reduce((sum, c) => sum + c.result.totalEntries, 0),
|
|
505
|
+
verifiedEntries: chains.reduce((sum, c) => sum + c.result.verifiedEntries, 0),
|
|
506
|
+
walk,
|
|
507
|
+
chains,
|
|
508
|
+
findings,
|
|
509
|
+
...(brokenAt !== undefined ? { brokenAt } : {}),
|
|
510
|
+
// Every chain walks the same merged key material; a chain whose entries
|
|
511
|
+
// carry no verified signature (one still waiting for its batch head)
|
|
512
|
+
// reports that about itself, not about the walk's keys.
|
|
513
|
+
keyTrust: (rep?.keyTrust.status === 'no_anchored_signature' ? chains.find((c) => c.result.keyTrust.status === 'walked')?.result.keyTrust : undefined) ?? rep?.keyTrust ?? null,
|
|
514
|
+
uncomputable,
|
|
515
|
+
readTime: {
|
|
516
|
+
...input.readTime,
|
|
517
|
+
undated,
|
|
518
|
+
detail: undated.length === 0
|
|
519
|
+
? null
|
|
520
|
+
: `${undated.length} batched ${undated.length === 1 ? 'entry carries' : 'entries carry'} no inclusion proof on a page that states no read time (exportMetadata.exportDate, which a Server from 4.0.0 writes on every page), and none was given, so each fails BATCH_UNATTESTED, as on an export that states no read time. Give the time the last page was read as exportDate: an entry written within ${BATCH_PENDING_GRACE_SECONDS} seconds before it is read as waiting for its batch head, and one written earlier still fails.`,
|
|
521
|
+
},
|
|
522
|
+
anchors: input.anchors,
|
|
523
|
+
unsignedProjectionFields: input.unsignedFields,
|
|
524
|
+
capped,
|
|
525
|
+
...(belowFloor !== null ? { runtime: belowFloor } : {}),
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
/** Cap a slice's verdict: a run not held to its chain's start or tip is never `trusted`. */
|
|
529
|
+
export function capSlice(result) {
|
|
530
|
+
return result.verdict === 'trusted' ? { ...result, verdict: 'unanchored' } : result;
|
|
531
|
+
}
|
|
532
|
+
/** The options `verifyAuditExport` reads, without the walk's own (the anchor documents go to each chain by its key). */
|
|
533
|
+
export function chainOptions(options) {
|
|
534
|
+
const { exportDate: _date, checkpoints: _checkpoints, anchorDocuments: _documents, acknowledgements: _acknowledgements, ...rest } = options;
|
|
535
|
+
return rest;
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Hold each page's own read time (`exportMetadata.exportDate`) to the signed
|
|
539
|
+
* iat of the entries served on it: a page read before one of its entries was
|
|
540
|
+
* signed states a time that was moved earlier, EXPORT_READ_TIME_INVALID.
|
|
541
|
+
*/
|
|
542
|
+
export function pageReadTimeFindings(pages) {
|
|
543
|
+
const out = [];
|
|
544
|
+
pages.forEach((page, i) => {
|
|
545
|
+
const own = page.exportMetadata.exportDate;
|
|
546
|
+
const ms = typeof own === 'string' ? rfc3339Ms(own) : NaN;
|
|
547
|
+
if (Number.isNaN(ms))
|
|
548
|
+
return;
|
|
549
|
+
for (const row of page.data) {
|
|
550
|
+
const iat = rowIat(row);
|
|
551
|
+
if (iat !== null && iat * 1000 > ms) {
|
|
552
|
+
out.push({ code: 'EXPORT_READ_TIME_INVALID', page: i + 1, detail: `Page ${i + 1} states exportMetadata.exportDate ${String(own)}, and its entry ${String(row.id)} (position ${String(row.chainPosition)}) is signed at iat ${iat} (${new Date(iat * 1000).toISOString()}), later: the page's read time was moved earlier than the read, which can set aside an anchor that shows a cut.` });
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
});
|
|
557
|
+
return out;
|
|
558
|
+
}
|
|
559
|
+
/** The signed iat of a row's envelope, or null. */
|
|
560
|
+
export function rowIat(row) {
|
|
561
|
+
if (typeof row.coseSign1 !== 'string')
|
|
562
|
+
return null;
|
|
563
|
+
const iat = decodeSignedClaim(Buffer.from(row.coseSign1, 'base64'))?.iat;
|
|
564
|
+
return typeof iat === 'number' && Number.isFinite(iat) && Math.abs(iat) < 8.64e12 ? iat : null;
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* Throw `TypeError` when the caller's `exportDate` is earlier than the signed
|
|
568
|
+
* iat of an entry the pages hold: the walk was read after that entry.
|
|
569
|
+
*/
|
|
570
|
+
export function assertWalkReadAfterSigned(fn, exportDate, pages) {
|
|
571
|
+
if (exportDate === undefined)
|
|
572
|
+
return;
|
|
573
|
+
const ms = rfc3339Ms(exportDate);
|
|
574
|
+
for (const page of pages) {
|
|
575
|
+
for (const row of page.data) {
|
|
576
|
+
const iat = rowIat(row);
|
|
577
|
+
if (iat !== null && iat * 1000 > ms) {
|
|
578
|
+
throw new TypeError(`${fn}: exportDate ${exportDate} is earlier than entry ${String(row.id)} (position ${String(row.chainPosition)} of ${row.recordId == null ? 'the schema chain' : `record ${row.recordId}`}), signed at iat ${iat} (${new Date(iat * 1000).toISOString()}): the walk was read after that. Give the time the last page was read.`);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
/** How far a chain is held when no listed checkpoint was given for it. */
|
|
584
|
+
export function heldByPages(lastPosition) {
|
|
585
|
+
return { position: lastPosition, by: 'page_content', checkpoint: null, checkpoints: [], detail: `Held to position ${lastPosition} by the page content.` };
|
|
586
|
+
}
|