@typedstandards/verify-core 0.2.0 → 0.3.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.
- package/dist/asn1.d.ts +36 -0
- package/dist/asn1.js +154 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/rekor-inclusion.js +7 -1
- package/dist/rfc3161.d.ts +41 -0
- package/dist/rfc3161.js +246 -0
- package/dist/verify.d.ts +5 -0
- package/dist/verify.js +18 -7
- package/package.json +3 -2
package/dist/asn1.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export declare class Asn1Error extends Error {
|
|
2
|
+
}
|
|
3
|
+
export interface DerNode {
|
|
4
|
+
/** The identifier octet (e.g. 0x30 SEQUENCE, 0x02 INTEGER, 0xa0 [0]). */
|
|
5
|
+
tag: number;
|
|
6
|
+
constructed: boolean;
|
|
7
|
+
/** Offset of the identifier octet. */
|
|
8
|
+
start: number;
|
|
9
|
+
/** Offset where content begins (just past the length octets). */
|
|
10
|
+
contentStart: number;
|
|
11
|
+
/** Offset one past the last content octet. */
|
|
12
|
+
contentEnd: number;
|
|
13
|
+
/** Offset one past the whole TLV (= contentEnd). */
|
|
14
|
+
end: number;
|
|
15
|
+
}
|
|
16
|
+
/** Parse a single TLV at `pos`, with strict-DER bounds checks. */
|
|
17
|
+
export declare function readNode(buf: Uint8Array, pos: number): DerNode;
|
|
18
|
+
/** Parse every child TLV of a constructed node; require they exactly tile it. */
|
|
19
|
+
export declare function children(buf: Uint8Array, node: DerNode): DerNode[];
|
|
20
|
+
/** The content octets of a node (a view — copy before mutating). */
|
|
21
|
+
export declare function content(buf: Uint8Array, node: DerNode): Uint8Array;
|
|
22
|
+
/** The whole TLV (identifier + length + content) of a node (a view). */
|
|
23
|
+
export declare function rawTlv(buf: Uint8Array, node: DerNode): Uint8Array;
|
|
24
|
+
/** Assert a node's tag, returning it (for fluent parsing). */
|
|
25
|
+
export declare function expectTag(node: DerNode, tag: number, label?: string): DerNode;
|
|
26
|
+
/** Decode an OBJECT IDENTIFIER (tag 0x06) to its dotted-decimal string. */
|
|
27
|
+
export declare function oidToString(buf: Uint8Array, node: DerNode): string;
|
|
28
|
+
/**
|
|
29
|
+
* Decode a UTCTime (0x17) or GeneralizedTime (0x18) to epoch milliseconds. Only
|
|
30
|
+
* the `Z` (UTC) forms RFC 5280 / RFC 3161 mandate are accepted; local-time and
|
|
31
|
+
* offset forms are rejected. UTCTime two-digit years use the RFC 5280 1950–2049
|
|
32
|
+
* window.
|
|
33
|
+
*/
|
|
34
|
+
export declare function readTime(buf: Uint8Array, node: DerNode): number;
|
|
35
|
+
/** First child whose tag matches, or undefined. */
|
|
36
|
+
export declare function findChild(buf: Uint8Array, node: DerNode, tag: number): DerNode | undefined;
|
package/dist/asn1.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// Minimal, bounds-checked DER reader (civic-ai-tools-website#119 P2) — browser-safe.
|
|
2
|
+
//
|
|
3
|
+
// Just enough ASN.1/DER to parse RFC 3161 timestamp tokens (PKCS#7/CMS + TSTInfo)
|
|
4
|
+
// and, later, X.509 certs — NOT a general ASN.1 library. A hand-rolled parser over
|
|
5
|
+
// attacker-supplied bytes is itself an attack surface, so every read is bounds- and
|
|
6
|
+
// shape-checked and the encoding is STRICT DER:
|
|
7
|
+
// - definite lengths only (indefinite `0x80` is rejected — it has no place in DER);
|
|
8
|
+
// - minimal length encoding (no `0x81 0x05`, no leading-zero padding);
|
|
9
|
+
// - lengths may not exceed the buffer; children must exactly tile their parent
|
|
10
|
+
// (no trailing garbage);
|
|
11
|
+
// - high-tag-number form is rejected (none of our structures use it).
|
|
12
|
+
// Malformed input throws `Asn1Error` rather than reading out of bounds or looping.
|
|
13
|
+
// Pure byte logic — no `node:*`, no `Buffer` (browser-safety guard covers this).
|
|
14
|
+
export class Asn1Error extends Error {
|
|
15
|
+
}
|
|
16
|
+
// DER tag classes / numbers we accept in the length/tag header. Context tags used
|
|
17
|
+
// by CMS/X.509 ([0], [1], …) are low-tag-number (0xa0, 0xa1, 0x80, …) so the
|
|
18
|
+
// high-tag-number guard never rejects a well-formed token.
|
|
19
|
+
const HIGH_TAG_NUMBER_MASK = 0x1f;
|
|
20
|
+
const CONSTRUCTED_BIT = 0x20;
|
|
21
|
+
const LONG_FORM_BIT = 0x80;
|
|
22
|
+
/** Parse a single TLV at `pos`, with strict-DER bounds checks. */
|
|
23
|
+
export function readNode(buf, pos) {
|
|
24
|
+
if (pos < 0 || pos + 1 > buf.length)
|
|
25
|
+
throw new Asn1Error('readNode past end of buffer');
|
|
26
|
+
const tag = buf[pos];
|
|
27
|
+
if ((tag & HIGH_TAG_NUMBER_MASK) === HIGH_TAG_NUMBER_MASK) {
|
|
28
|
+
throw new Asn1Error('high-tag-number form unsupported');
|
|
29
|
+
}
|
|
30
|
+
let i = pos + 1;
|
|
31
|
+
if (i >= buf.length)
|
|
32
|
+
throw new Asn1Error('truncated: missing length octet');
|
|
33
|
+
let len = buf[i++];
|
|
34
|
+
if (len & LONG_FORM_BIT) {
|
|
35
|
+
const n = len & 0x7f;
|
|
36
|
+
if (n === 0)
|
|
37
|
+
throw new Asn1Error('indefinite length not allowed in DER');
|
|
38
|
+
if (n > 4)
|
|
39
|
+
throw new Asn1Error('length octet count too large');
|
|
40
|
+
if (i + n > buf.length)
|
|
41
|
+
throw new Asn1Error('truncated long-form length');
|
|
42
|
+
if (buf[i] === 0x00)
|
|
43
|
+
throw new Asn1Error('non-minimal length (leading zero)');
|
|
44
|
+
len = 0;
|
|
45
|
+
for (let k = 0; k < n; k++)
|
|
46
|
+
len = len * 256 + buf[i++]; // *256 avoids 32-bit overflow
|
|
47
|
+
if (len < 0x80)
|
|
48
|
+
throw new Asn1Error('non-minimal length (should be short form)');
|
|
49
|
+
}
|
|
50
|
+
const contentStart = i;
|
|
51
|
+
const contentEnd = i + len;
|
|
52
|
+
if (contentEnd > buf.length)
|
|
53
|
+
throw new Asn1Error('content length exceeds buffer');
|
|
54
|
+
return {
|
|
55
|
+
tag,
|
|
56
|
+
constructed: (tag & CONSTRUCTED_BIT) !== 0,
|
|
57
|
+
start: pos,
|
|
58
|
+
contentStart,
|
|
59
|
+
contentEnd,
|
|
60
|
+
end: contentEnd,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/** Parse every child TLV of a constructed node; require they exactly tile it. */
|
|
64
|
+
export function children(buf, node) {
|
|
65
|
+
if (!node.constructed)
|
|
66
|
+
throw new Asn1Error('children() on a primitive node');
|
|
67
|
+
const out = [];
|
|
68
|
+
let p = node.contentStart;
|
|
69
|
+
while (p < node.contentEnd) {
|
|
70
|
+
const child = readNode(buf, p);
|
|
71
|
+
if (child.end > node.contentEnd)
|
|
72
|
+
throw new Asn1Error('child overruns parent');
|
|
73
|
+
out.push(child);
|
|
74
|
+
p = child.end;
|
|
75
|
+
}
|
|
76
|
+
if (p !== node.contentEnd)
|
|
77
|
+
throw new Asn1Error('trailing bytes in constructed value');
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
/** The content octets of a node (a view — copy before mutating). */
|
|
81
|
+
export function content(buf, node) {
|
|
82
|
+
return buf.subarray(node.contentStart, node.contentEnd);
|
|
83
|
+
}
|
|
84
|
+
/** The whole TLV (identifier + length + content) of a node (a view). */
|
|
85
|
+
export function rawTlv(buf, node) {
|
|
86
|
+
return buf.subarray(node.start, node.end);
|
|
87
|
+
}
|
|
88
|
+
/** Assert a node's tag, returning it (for fluent parsing). */
|
|
89
|
+
export function expectTag(node, tag, label = 'node') {
|
|
90
|
+
if (node.tag !== tag) {
|
|
91
|
+
throw new Asn1Error(`expected ${label} tag 0x${tag.toString(16)}, got 0x${node.tag.toString(16)}`);
|
|
92
|
+
}
|
|
93
|
+
return node;
|
|
94
|
+
}
|
|
95
|
+
/** Decode an OBJECT IDENTIFIER (tag 0x06) to its dotted-decimal string. */
|
|
96
|
+
export function oidToString(buf, node) {
|
|
97
|
+
expectTag(node, 0x06, 'OID');
|
|
98
|
+
const b = content(buf, node);
|
|
99
|
+
if (b.length === 0)
|
|
100
|
+
throw new Asn1Error('empty OID');
|
|
101
|
+
if (b[b.length - 1] & 0x80)
|
|
102
|
+
throw new Asn1Error('truncated OID subidentifier');
|
|
103
|
+
const subids = [];
|
|
104
|
+
let acc = 0;
|
|
105
|
+
for (const byte of b) {
|
|
106
|
+
acc = acc * 128 + (byte & 0x7f);
|
|
107
|
+
if ((byte & 0x80) === 0) {
|
|
108
|
+
subids.push(acc);
|
|
109
|
+
acc = 0;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const first = subids[0];
|
|
113
|
+
const arc0 = Math.min(2, Math.floor(first / 40));
|
|
114
|
+
const arcs = [arc0, first - arc0 * 40, ...subids.slice(1)];
|
|
115
|
+
return arcs.join('.');
|
|
116
|
+
}
|
|
117
|
+
function asciiOf(bytes) {
|
|
118
|
+
let s = '';
|
|
119
|
+
for (const c of bytes) {
|
|
120
|
+
if (c < 0x20 || c > 0x7e)
|
|
121
|
+
throw new Asn1Error('non-ASCII byte in time string');
|
|
122
|
+
s += String.fromCharCode(c);
|
|
123
|
+
}
|
|
124
|
+
return s;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Decode a UTCTime (0x17) or GeneralizedTime (0x18) to epoch milliseconds. Only
|
|
128
|
+
* the `Z` (UTC) forms RFC 5280 / RFC 3161 mandate are accepted; local-time and
|
|
129
|
+
* offset forms are rejected. UTCTime two-digit years use the RFC 5280 1950–2049
|
|
130
|
+
* window.
|
|
131
|
+
*/
|
|
132
|
+
export function readTime(buf, node) {
|
|
133
|
+
const s = asciiOf(content(buf, node));
|
|
134
|
+
if (node.tag === 0x18) {
|
|
135
|
+
const m = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d+)?Z$/.exec(s);
|
|
136
|
+
if (!m)
|
|
137
|
+
throw new Asn1Error('malformed GeneralizedTime');
|
|
138
|
+
const ms = m[7] ? Math.round(parseFloat('0' + m[7]) * 1000) : 0;
|
|
139
|
+
return Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6], ms);
|
|
140
|
+
}
|
|
141
|
+
if (node.tag === 0x17) {
|
|
142
|
+
const m = /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(s);
|
|
143
|
+
if (!m)
|
|
144
|
+
throw new Asn1Error('malformed UTCTime');
|
|
145
|
+
const yy = +m[1];
|
|
146
|
+
const year = yy < 50 ? 2000 + yy : 1900 + yy;
|
|
147
|
+
return Date.UTC(year, +m[2] - 1, +m[3], +m[4], +m[5], +m[6]);
|
|
148
|
+
}
|
|
149
|
+
throw new Asn1Error(`not a time tag: 0x${node.tag.toString(16)}`);
|
|
150
|
+
}
|
|
151
|
+
/** First child whose tag matches, or undefined. */
|
|
152
|
+
export function findChild(buf, node, tag) {
|
|
153
|
+
return children(buf, node).find((c) => c.tag === tag);
|
|
154
|
+
}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
package/dist/rekor-inclusion.js
CHANGED
|
@@ -190,7 +190,13 @@ export function verifyCheckpointSignature(checkpoint, anchors) {
|
|
|
190
190
|
continue;
|
|
191
191
|
try {
|
|
192
192
|
const point = extractP256Point(anchor.publicKeyDer);
|
|
193
|
-
|
|
193
|
+
// `lowS: false`: the log signer may emit a high-S checkpoint signature; low-S
|
|
194
|
+
// is a signing-side malleability convention, not a verification rule, so a
|
|
195
|
+
// verifier must accept both S and n−S (see the rfc3161.ts note — a real high-S
|
|
196
|
+
// TSA token exposed this default). We only ask "did this log key sign this
|
|
197
|
+
// checkpoint". (`@noble` prehashes with the curve hash by default, so the note
|
|
198
|
+
// body is passed as the message.)
|
|
199
|
+
if (p256.verify(sig.sig, checkpoint.signedBody, point, { format: 'der', lowS: false })) {
|
|
194
200
|
return { verified: true, origin: anchor.origin, keyHint: hint };
|
|
195
201
|
}
|
|
196
202
|
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A pinned TSA signing key — the OFFLINE trust anchor for check #7 (spec §10.3).
|
|
3
|
+
* Pinning the SIGNING key (not the long-lived root) is the P2a "acceptable v1":
|
|
4
|
+
* it must be re-pinned if FreeTSA rotates the signing cert. P2b anchors to the RSA
|
|
5
|
+
* root via the token's embedded chain, which removes the re-pin.
|
|
6
|
+
*/
|
|
7
|
+
export interface TsaAnchor {
|
|
8
|
+
name: string;
|
|
9
|
+
/** EC P-384 signing public key, base64 SPKI DER. */
|
|
10
|
+
signingKeyDer: string;
|
|
11
|
+
/** Signing cert validity window (ISO 8601, UTC). genTime must fall inside it. */
|
|
12
|
+
notBefore: string;
|
|
13
|
+
notAfter: string;
|
|
14
|
+
}
|
|
15
|
+
export declare const FREETSA_TSA_ANCHORS: readonly TsaAnchor[];
|
|
16
|
+
export type Rfc3161FailReason = 'parse_error' | 'not_granted' | 'unexpected_content_type' | 'unexpected_algorithm' | 'no_message_digest' | 'content_not_bound' | 'no_anchor' | 'signature_invalid' | 'imprint_mismatch' | 'genTime_outside_validity';
|
|
17
|
+
export interface Rfc3161VerifyResult {
|
|
18
|
+
/** All checks passed: a pinned TSA's signature binds this package hash to genTime. */
|
|
19
|
+
verified: boolean;
|
|
20
|
+
/** messageImprint.hashedMessage == the expected package hash (sha256). */
|
|
21
|
+
imprintMatches: boolean | null;
|
|
22
|
+
/** The TSA ECDSA-P384 signature over SHA-512(signedAttrs) verifies vs the anchor. */
|
|
23
|
+
signatureValid: boolean | null;
|
|
24
|
+
/** signedAttrs.messageDigest == SHA-512(TSTInfo) — the sig is bound to the TSTInfo. */
|
|
25
|
+
contentBound: boolean | null;
|
|
26
|
+
/** genTime within the pinned signing cert's validity window. */
|
|
27
|
+
withinValidity: boolean | null;
|
|
28
|
+
/** RFC 3161 genTime, epoch ms. */
|
|
29
|
+
genTime?: number;
|
|
30
|
+
/** The matched anchor name (when the signature verified). */
|
|
31
|
+
tsa?: string;
|
|
32
|
+
reason?: Rfc3161FailReason;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Verify an RFC 3161 timestamp token (base64) attests `expectedHashHex` (the package
|
|
36
|
+
* SHA-256), against the pinned TSA anchors. Returns a graded verdict; a parse failure
|
|
37
|
+
* or unknown anchor is reported (not thrown) so the caller can render it calmly,
|
|
38
|
+
* while a real cryptographic failure (`signature_invalid` / `imprint_mismatch` /
|
|
39
|
+
* `content_not_bound`) is the alarm signal.
|
|
40
|
+
*/
|
|
41
|
+
export declare function verifyRfc3161Timestamp(tokenB64: string, expectedHashHex: string, anchors?: readonly TsaAnchor[]): Rfc3161VerifyResult;
|
package/dist/rfc3161.js
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
// RFC 3161 timestamp verification (spec §9.2 check #7, deep) — browser-safe.
|
|
2
|
+
//
|
|
3
|
+
// `verifyEvidence` today does PRESENCE for #7 (`!!rfc3161Timestamp`). This closes
|
|
4
|
+
// the cryptographic gap for the FreeTSA profile our producer uses (#119 P2a): it
|
|
5
|
+
// parses the RFC 3161 token (a PKCS#7/CMS SignedData over a TSTInfo) and verifies,
|
|
6
|
+
// OFFLINE, that a trusted TSA attested the package hash at a point in time:
|
|
7
|
+
// 1. messageImprint.hashedMessage == the package hash (sha256), so the token is
|
|
8
|
+
// ABOUT this package;
|
|
9
|
+
// 2. signedAttrs.messageDigest == SHA-512(TSTInfo), so the signature is BOUND to
|
|
10
|
+
// that TSTInfo;
|
|
11
|
+
// 3. the TSA's ECDSA-P384 signature over SHA-512(signedAttrs) verifies against the
|
|
12
|
+
// PINNED FreeTSA signing key (the trust anchor);
|
|
13
|
+
// 4. genTime falls within that signing cert's validity window.
|
|
14
|
+
//
|
|
15
|
+
// SCOPE (P2a): FreeTSA uses an EC P-384 signing cert and `ecdsa-with-SHA512`, so the
|
|
16
|
+
// TSA-signature check is pure `@noble` ECDSA — no WebCrypto/RSA. The anchor is the
|
|
17
|
+
// PINNED signing-cert public key (re-pin on rotation — documented below). P2b adds
|
|
18
|
+
// full embedded-cert chain validation to FreeTSA's RSA root (which removes the
|
|
19
|
+
// re-pin), and generalizes EKU/validity from the certs themselves. The recipe here
|
|
20
|
+
// was validated byte-for-byte against a real freetsa.org token (cross-checked with
|
|
21
|
+
// OpenSSL `ts -verify`) before shipping; `__fixtures__/rfc3161-token.json` is that
|
|
22
|
+
// token and the tests reproduce it offline.
|
|
23
|
+
import { p384 } from '@noble/curves/nist.js';
|
|
24
|
+
import { sha512 } from '@noble/hashes/sha2.js';
|
|
25
|
+
import { base64ToBytes, bytesToHex } from "./primitives.js";
|
|
26
|
+
import { Asn1Error, readNode, children, content, rawTlv, oidToString, readTime, } from "./asn1.js";
|
|
27
|
+
// --- OIDs ------------------------------------------------------------------
|
|
28
|
+
const OID_SIGNED_DATA = '1.2.840.113549.1.7.2';
|
|
29
|
+
const OID_CT_TSTINFO = '1.2.840.113549.1.9.16.1.4';
|
|
30
|
+
const OID_SHA256 = '2.16.840.1.101.3.4.2.1';
|
|
31
|
+
const OID_SHA512 = '2.16.840.1.101.3.4.2.3';
|
|
32
|
+
const OID_ECDSA_SHA512 = '1.2.840.10045.4.3.4';
|
|
33
|
+
const OID_ATTR_MESSAGE_DIGEST = '1.2.840.113549.1.9.4';
|
|
34
|
+
// PROVENANCE (anchor pinning — spec §10.3). FreeTSA's online TSA (`freetsa.org/tsr`)
|
|
35
|
+
// signs with this EC P-384 key (cert serial C2E986160DA8E9CD, OU=TSA, EKU
|
|
36
|
+
// id-kp-timeStamping, valid 2026-02-15 → 2040-02-02). Captured 2026-06-07 from
|
|
37
|
+
// `https://freetsa.org/files/tsa.crt`; a live token verified against it with both
|
|
38
|
+
// `@noble` (here) and OpenSSL `ts -verify` against FreeTSA's published CA. The cert
|
|
39
|
+
// chains to FreeTSA's self-signed RSA-4096 root (OU=Root CA) — pinning that root and
|
|
40
|
+
// validating the embedded chain is P2b.
|
|
41
|
+
export const FREETSA_TSA_ANCHORS = [
|
|
42
|
+
{
|
|
43
|
+
name: 'freetsa.org',
|
|
44
|
+
signingKeyDer: 'MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEohXhobLWy4cYsdKOFALpjUsB1FJTntwwb7PH2LOfNMAA1ufaKhkgsdeW6etU0pl5MC5tSVuPF52yy4sz+mbY3L7IVdx/bs9m0ud7IA14YNcC2yIQLa2gvnxwsrR3rlWr',
|
|
45
|
+
notBefore: '2026-02-15T19:44:22Z',
|
|
46
|
+
notAfter: '2040-02-02T19:44:22Z',
|
|
47
|
+
},
|
|
48
|
+
];
|
|
49
|
+
// EC P-384 SPKI DER is a fixed 120-byte structure: a 23-byte prefix (SEQUENCE →
|
|
50
|
+
// AlgorithmIdentifier{ id-ecPublicKey, secp384r1 } → BIT STRING) then the 97-byte
|
|
51
|
+
// uncompressed point (0x04 ‖ X ‖ Y).
|
|
52
|
+
const EC_P384_SPKI_PREFIX = Uint8Array.from([
|
|
53
|
+
0x30, 0x76, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01,
|
|
54
|
+
0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22, 0x03, 0x62, 0x00,
|
|
55
|
+
]);
|
|
56
|
+
const EC_P384_SPKI_LENGTH = 120;
|
|
57
|
+
function extractP384Point(publicKeyB64Der) {
|
|
58
|
+
const der = base64ToBytes(publicKeyB64Der);
|
|
59
|
+
if (der.length !== EC_P384_SPKI_LENGTH) {
|
|
60
|
+
throw new Asn1Error(`Unexpected P-384 SPKI length ${der.length}`);
|
|
61
|
+
}
|
|
62
|
+
for (let i = 0; i < EC_P384_SPKI_PREFIX.length; i++) {
|
|
63
|
+
if (der[i] !== EC_P384_SPKI_PREFIX[i])
|
|
64
|
+
throw new Asn1Error('Unexpected P-384 SPKI prefix');
|
|
65
|
+
}
|
|
66
|
+
return der.slice(EC_P384_SPKI_LENGTH - 97);
|
|
67
|
+
}
|
|
68
|
+
/** The AlgorithmIdentifier's OID (its first child). */
|
|
69
|
+
function algorithmOid(buf, alg) {
|
|
70
|
+
return oidToString(buf, children(buf, alg)[0]);
|
|
71
|
+
}
|
|
72
|
+
/** Navigate TimeStampResp → ContentInfo → SignedData → { TSTInfo, signerInfo }. */
|
|
73
|
+
function parseToken(buf) {
|
|
74
|
+
const resp = readNode(buf, 0);
|
|
75
|
+
const respKids = children(buf, resp);
|
|
76
|
+
// PKIStatusInfo.status: 0 granted, 1 grantedWithMods; anything else ⇒ no token.
|
|
77
|
+
const status = children(buf, respKids[0])[0];
|
|
78
|
+
const statusVal = content(buf, status);
|
|
79
|
+
if (statusVal.length !== 1 || statusVal[0] > 1)
|
|
80
|
+
throw new Asn1Error('PKIStatus not granted');
|
|
81
|
+
const contentInfo = respKids[1];
|
|
82
|
+
if (!contentInfo)
|
|
83
|
+
throw new Asn1Error('no timeStampToken');
|
|
84
|
+
const ciKids = children(buf, contentInfo);
|
|
85
|
+
if (oidToString(buf, ciKids[0]) !== OID_SIGNED_DATA)
|
|
86
|
+
throw new Asn1Error('not signedData');
|
|
87
|
+
const signedData = children(buf, ciKids[1])[0]; // [0] EXPLICIT → SignedData
|
|
88
|
+
const sd = children(buf, signedData);
|
|
89
|
+
const encap = sd.find((c) => c.tag === 0x30); // first SEQUENCE = encapContentInfo
|
|
90
|
+
const signerInfos = sd.filter((c) => c.tag === 0x31).pop(); // last SET = signerInfos
|
|
91
|
+
if (!encap || !signerInfos)
|
|
92
|
+
throw new Asn1Error('malformed SignedData');
|
|
93
|
+
const encapKids = children(buf, encap);
|
|
94
|
+
if (oidToString(buf, encapKids[0]) !== OID_CT_TSTINFO)
|
|
95
|
+
throw new Asn1Error('eContent not TSTInfo');
|
|
96
|
+
const tstOctet = children(buf, encapKids[1])[0]; // [0] EXPLICIT → OCTET STRING
|
|
97
|
+
if (tstOctet.tag !== 0x04)
|
|
98
|
+
throw new Asn1Error('TSTInfo not an OCTET STRING');
|
|
99
|
+
const tstInfo = buf.slice(tstOctet.contentStart, tstOctet.contentEnd);
|
|
100
|
+
const signerInfo = children(buf, signerInfos)[0];
|
|
101
|
+
const si = children(buf, signerInfo);
|
|
102
|
+
const signedAttrs = si.find((c) => c.tag === 0xa0);
|
|
103
|
+
const signature = si.find((c) => c.tag === 0x04);
|
|
104
|
+
if (!signedAttrs || !signature)
|
|
105
|
+
throw new Asn1Error('signerInfo missing signedAttrs/signature');
|
|
106
|
+
// SignerInfo has three SEQUENCEs: sid (issuerAndSerialNumber), digestAlgorithm,
|
|
107
|
+
// signatureAlgorithm. The digest alg is the LAST 0x30 before signedAttrs (the sid
|
|
108
|
+
// also precedes it); the signature alg is the first 0x30 after.
|
|
109
|
+
const seqs = si.filter((c) => c.tag === 0x30);
|
|
110
|
+
const digestAlg = seqs.filter((c) => c.end <= signedAttrs.start).pop();
|
|
111
|
+
const signatureAlg = seqs.find((c) => c.start >= signedAttrs.end);
|
|
112
|
+
if (!digestAlg || !signatureAlg)
|
|
113
|
+
throw new Asn1Error('signerInfo missing algorithm ids');
|
|
114
|
+
return {
|
|
115
|
+
tstInfo,
|
|
116
|
+
signedAttrs,
|
|
117
|
+
digestAlgOid: algorithmOid(buf, digestAlg),
|
|
118
|
+
signatureAlgOid: algorithmOid(buf, signatureAlg),
|
|
119
|
+
signature: content(buf, signature),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/** The OCTET STRING value of the messageDigest signed attribute. */
|
|
123
|
+
function messageDigestAttr(buf, signedAttrs) {
|
|
124
|
+
for (const attr of children(buf, signedAttrs)) {
|
|
125
|
+
const kids = children(buf, attr);
|
|
126
|
+
if (oidToString(buf, kids[0]) === OID_ATTR_MESSAGE_DIGEST) {
|
|
127
|
+
const value = children(buf, kids[1])[0]; // SET OF → OCTET STRING
|
|
128
|
+
return content(buf, value);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
/** Pull { hashedMessage, hashAlgOid, genTime } out of a TSTInfo. */
|
|
134
|
+
function parseTstInfo(tst) {
|
|
135
|
+
const root = readNode(tst, 0);
|
|
136
|
+
const kids = children(tst, root); // version, policy, messageImprint, serial, genTime, …
|
|
137
|
+
const messageImprint = kids[2];
|
|
138
|
+
const miKids = children(tst, messageImprint);
|
|
139
|
+
const hashAlgOid = algorithmOid(tst, miKids[0]);
|
|
140
|
+
const hashedMessage = content(tst, miKids[1]);
|
|
141
|
+
const genTimeNode = kids.find((c) => c.tag === 0x18);
|
|
142
|
+
if (!genTimeNode)
|
|
143
|
+
throw new Asn1Error('TSTInfo missing genTime');
|
|
144
|
+
return { hashedMessage, hashAlgOid, genTime: readTime(tst, genTimeNode) };
|
|
145
|
+
}
|
|
146
|
+
function bytesEqual(a, b) {
|
|
147
|
+
if (a.length !== b.length)
|
|
148
|
+
return false;
|
|
149
|
+
let diff = 0;
|
|
150
|
+
for (let i = 0; i < a.length; i++)
|
|
151
|
+
diff |= a[i] ^ b[i];
|
|
152
|
+
return diff === 0;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Verify an RFC 3161 timestamp token (base64) attests `expectedHashHex` (the package
|
|
156
|
+
* SHA-256), against the pinned TSA anchors. Returns a graded verdict; a parse failure
|
|
157
|
+
* or unknown anchor is reported (not thrown) so the caller can render it calmly,
|
|
158
|
+
* while a real cryptographic failure (`signature_invalid` / `imprint_mismatch` /
|
|
159
|
+
* `content_not_bound`) is the alarm signal.
|
|
160
|
+
*/
|
|
161
|
+
export function verifyRfc3161Timestamp(tokenB64, expectedHashHex, anchors = FREETSA_TSA_ANCHORS) {
|
|
162
|
+
let buf;
|
|
163
|
+
let token;
|
|
164
|
+
let tst;
|
|
165
|
+
let mdAttr;
|
|
166
|
+
try {
|
|
167
|
+
buf = base64ToBytes(tokenB64);
|
|
168
|
+
token = parseToken(buf);
|
|
169
|
+
tst = parseTstInfo(token.tstInfo);
|
|
170
|
+
mdAttr = messageDigestAttr(buf, token.signedAttrs);
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
return {
|
|
174
|
+
verified: false,
|
|
175
|
+
imprintMatches: null,
|
|
176
|
+
signatureValid: null,
|
|
177
|
+
contentBound: null,
|
|
178
|
+
withinValidity: null,
|
|
179
|
+
reason: 'parse_error',
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
const base = {
|
|
183
|
+
verified: false,
|
|
184
|
+
imprintMatches: null,
|
|
185
|
+
signatureValid: null,
|
|
186
|
+
contentBound: null,
|
|
187
|
+
withinValidity: null,
|
|
188
|
+
genTime: tst.genTime,
|
|
189
|
+
};
|
|
190
|
+
// FreeTSA profile (P2a): SHA-512 digest + ECDSA-with-SHA-512 signature.
|
|
191
|
+
if (token.digestAlgOid !== OID_SHA512 || token.signatureAlgOid !== OID_ECDSA_SHA512) {
|
|
192
|
+
return { ...base, reason: 'unexpected_algorithm' };
|
|
193
|
+
}
|
|
194
|
+
// (1) message imprint is about THIS package (sha256).
|
|
195
|
+
const imprintMatches = tst.hashAlgOid === OID_SHA256 && bytesToHex(tst.hashedMessage) === expectedHashHex.toLowerCase();
|
|
196
|
+
base.imprintMatches = imprintMatches;
|
|
197
|
+
if (!imprintMatches)
|
|
198
|
+
return { ...base, reason: 'imprint_mismatch' };
|
|
199
|
+
// (2) the signature is bound to this TSTInfo via the messageDigest attribute.
|
|
200
|
+
if (!mdAttr)
|
|
201
|
+
return { ...base, reason: 'no_message_digest' };
|
|
202
|
+
const contentBound = bytesEqual(mdAttr, sha512(token.tstInfo));
|
|
203
|
+
base.contentBound = contentBound;
|
|
204
|
+
if (!contentBound)
|
|
205
|
+
return { ...base, reason: 'content_not_bound' };
|
|
206
|
+
// (3) ECDSA-P384 signature over SHA-512(signedAttrs re-tagged [0] → SET) verifies
|
|
207
|
+
// against a pinned anchor key. (`@noble` prehashes with SHA-384 by default, so we
|
|
208
|
+
// hash with SHA-512 ourselves and pass `prehash: false`.)
|
|
209
|
+
const signedBytes = Uint8Array.from(rawTlv(buf, token.signedAttrs));
|
|
210
|
+
signedBytes[0] = 0x31; // [0] IMPLICIT (0xa0) → SET OF (0x31) for the signature input
|
|
211
|
+
const digest = sha512(signedBytes);
|
|
212
|
+
let matched;
|
|
213
|
+
for (const anchor of anchors) {
|
|
214
|
+
try {
|
|
215
|
+
const point = extractP384Point(anchor.signingKeyDer);
|
|
216
|
+
// `lowS: false` is REQUIRED here: low-S is a signature-malleability convention
|
|
217
|
+
// for SIGNING, not a validity rule. A TSA (like FreeTSA) legitimately emits
|
|
218
|
+
// high-S ECDSA signatures (~half of them); `@noble`'s default `lowS: true`
|
|
219
|
+
// would false-negative those (it rejected the real high-S da9246 token —
|
|
220
|
+
// regression-tested). Accepting high-S is correct: both S and n−S are valid
|
|
221
|
+
// signatures by the same key, and we only ask "did this TSA sign this hash".
|
|
222
|
+
if (p384.verify(token.signature, digest, point, { format: 'der', prehash: false, lowS: false })) {
|
|
223
|
+
matched = anchor;
|
|
224
|
+
break;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
// malformed anchor key ⇒ try the next
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
base.signatureValid = !!matched;
|
|
232
|
+
if (!matched) {
|
|
233
|
+
// Distinguish "no pinned key vouches for this token" (calm — unknown TSA) from a
|
|
234
|
+
// signature that fails under a known key. Here, none verified ⇒ no_anchor.
|
|
235
|
+
return { ...base, reason: 'no_anchor' };
|
|
236
|
+
}
|
|
237
|
+
base.tsa = matched.name;
|
|
238
|
+
// (4) genTime within the pinned signing cert's validity window.
|
|
239
|
+
const notBefore = Date.parse(matched.notBefore);
|
|
240
|
+
const notAfter = Date.parse(matched.notAfter);
|
|
241
|
+
const withinValidity = tst.genTime >= notBefore && tst.genTime <= notAfter;
|
|
242
|
+
base.withinValidity = withinValidity;
|
|
243
|
+
if (!withinValidity)
|
|
244
|
+
return { ...base, reason: 'genTime_outside_validity' };
|
|
245
|
+
return { ...base, verified: true };
|
|
246
|
+
}
|
package/dist/verify.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type RekorInclusionProof, type RekorInclusionResult } from './rekor-inclusion.ts';
|
|
2
|
+
import { type Rfc3161VerifyResult } from './rfc3161.ts';
|
|
2
3
|
import { type KeyTrustResult, type TrustRegistry } from './trust-registry.ts';
|
|
3
4
|
import { type ContentCanonicalizationResolution, type ContentHashCheck, type TypeResolution, type SignerIdentityCheck, type CaptureMethodVocabCheck, type BlobRefVerification } from './checks.ts';
|
|
4
5
|
import { type LifecycleResolution } from './lifecycle.ts';
|
|
@@ -90,6 +91,10 @@ export interface VerifyResult {
|
|
|
90
91
|
rekorInclusion: RekorInclusionResult | null;
|
|
91
92
|
hasRekor: boolean;
|
|
92
93
|
hasTimestamp: boolean;
|
|
94
|
+
/** Cryptographic RFC 3161 TSA verdict (#119 P2a): null when no token was present,
|
|
95
|
+
* else the graded result (signature vs pinned TSA anchor, message-imprint match,
|
|
96
|
+
* genTime-in-validity). Additive to `hasTimestamp` (presence). */
|
|
97
|
+
rfc3161: Rfc3161VerifyResult | null;
|
|
93
98
|
keyTrust: KeyTrustResult | null;
|
|
94
99
|
blobRefsVerified: boolean | null;
|
|
95
100
|
blobRefs: BlobRefVerification[];
|
package/dist/verify.js
CHANGED
|
@@ -14,17 +14,20 @@
|
|
|
14
14
|
// sidecar (`buildCommitmentView`) so WS3 can wire sidecar → verifyEvidence with
|
|
15
15
|
// no glue. The server route adapts its DB row to the same shape.
|
|
16
16
|
//
|
|
17
|
-
// Check depth: fully client-side for #1/#2/#3/#4/#5/#6/#9/#12/#13/#14/#15;
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
//
|
|
23
|
-
//
|
|
17
|
+
// Check depth: fully client-side for #1/#2/#3/#4/#5/#6/#9/#12/#13/#14/#15; #7 (RFC
|
|
18
|
+
// 3161) is PRESENCE (`hasTimestamp`) AND, when a token is present, cryptographic TSA
|
|
19
|
+
// verification against the pinned FreeTSA anchor (civic-ai-tools-website#119 P2a —
|
|
20
|
+
// ECDSA-P384 over the signed TSTInfo, message-imprint match, genTime-in-validity);
|
|
21
|
+
// #8 (Rekor) is hash-PARITY AND, when an inclusion proof is available (carried for
|
|
22
|
+
// offline, or on the fetched entry), cryptographic Merkle inclusion against the
|
|
23
|
+
// pinned log key (#119 P1); lifecycle STATE for #10 unless the caller supplies a
|
|
24
|
+
// deeper resolution. Remaining deeper crypto: TSA full cert-chain #7 (#119 P2b),
|
|
25
|
+
// independent lifecycle-chain #10 (#119 P3).
|
|
24
26
|
import { recomputePackageHash } from "./checks.js";
|
|
25
27
|
import { verifySignature } from "./signature.js";
|
|
26
28
|
import { verifyRekorEntry } from "./rekor.js";
|
|
27
29
|
import { verifyRekorInclusion, } from "./rekor-inclusion.js";
|
|
30
|
+
import { verifyRfc3161Timestamp } from "./rfc3161.js";
|
|
28
31
|
import { verifyKeyTrust, legacyEmbeddedKeyTrust, } from "./trust-registry.js";
|
|
29
32
|
import { resolveContentCanonicalization, verifyContentHash, resolvePackageType, checkSignerIdentity, checkCaptureMethodVocab, verifyPackageBlobRefs, } from "./checks.js";
|
|
30
33
|
import { resolveLifecycleFromLegacyColumns, } from "./lifecycle.js";
|
|
@@ -82,6 +85,13 @@ export async function verifyEvidence(input, deps) {
|
|
|
82
85
|
if (input.rekorInclusionProof && input.rekorEntryBody) {
|
|
83
86
|
rekorInclusion = verifyRekorInclusion(input.rekorEntryBody, input.rekorInclusionProof);
|
|
84
87
|
}
|
|
88
|
+
// Step 3c — RFC 3161 timestamp (check #7, deep). Presence is `hasTimestamp`; when a
|
|
89
|
+
// token + package hash are present, cryptographically verify the TSA signature over
|
|
90
|
+
// the timestamped hash against the pinned TSA anchor (#119 P2a). Pure/offline.
|
|
91
|
+
let rfc3161 = null;
|
|
92
|
+
if (input.rfc3161Timestamp && packageHash) {
|
|
93
|
+
rfc3161 = verifyRfc3161Timestamp(input.rfc3161Timestamp, packageHash);
|
|
94
|
+
}
|
|
85
95
|
// Step 3b — blob references embedded in the package (check #9).
|
|
86
96
|
let blobRefs = [];
|
|
87
97
|
let blobRefsVerified = null;
|
|
@@ -134,6 +144,7 @@ export async function verifyEvidence(input, deps) {
|
|
|
134
144
|
rekorInclusion,
|
|
135
145
|
hasRekor: !!input.rekorEntryId,
|
|
136
146
|
hasTimestamp: !!input.rfc3161Timestamp,
|
|
147
|
+
rfc3161,
|
|
137
148
|
keyTrust,
|
|
138
149
|
blobRefsVerified,
|
|
139
150
|
blobRefs,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@typedstandards/verify-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "Portable, browser-safe verification core for Typed Standards evidence packages — the §9.2 check suite, single-sourced so it verifies identically on a server and in the browser.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Nathan Storey",
|
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
"exports": {
|
|
10
10
|
".": {
|
|
11
11
|
"types": "./dist/index.d.ts",
|
|
12
|
-
"import": "./dist/index.js"
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"default": "./dist/index.js"
|
|
13
14
|
},
|
|
14
15
|
"./package.json": "./package.json"
|
|
15
16
|
},
|