@ocap/chain-node 1.32.1 → 1.32.3
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/esm/access-log.d.mts +5 -2
- package/esm/access-log.mjs +5 -3
- package/esm/config-consistency.mjs +38 -2
- package/esm/did-tls.d.mts +192 -0
- package/esm/did-tls.mjs +1606 -0
- package/esm/env.d.mts +17 -2
- package/esm/env.mjs +126 -1
- package/esm/follower-config.d.mts +3 -2
- package/esm/follower-config.mjs +30 -4
- package/esm/index.d.mts +6 -4
- package/esm/index.mjs +5 -3
- package/esm/mesh-egress.d.mts +30 -0
- package/esm/mesh-egress.mjs +152 -0
- package/esm/start-chain-node.d.mts +6 -1
- package/esm/start-chain-node.mjs +822 -49
- package/esm/types.d.mts +68 -2
- package/lib/access-log.cjs +4 -2
- package/lib/access-log.d.cts +5 -2
- package/lib/config-consistency.cjs +38 -2
- package/lib/did-tls.cjs +1628 -0
- package/lib/did-tls.d.cts +192 -0
- package/lib/env.cjs +131 -1
- package/lib/env.d.cts +17 -2
- package/lib/follower-config.cjs +30 -3
- package/lib/follower-config.d.cts +3 -2
- package/lib/index.cjs +30 -1
- package/lib/index.d.cts +6 -4
- package/lib/mesh-egress.cjs +155 -0
- package/lib/mesh-egress.d.cts +30 -0
- package/lib/start-chain-node.cjs +824 -48
- package/lib/start-chain-node.d.cts +6 -1
- package/lib/types.d.cts +67 -1
- package/package.json +16 -16
package/lib/did-tls.cjs
ADDED
|
@@ -0,0 +1,1628 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
|
+
let node_crypto = require("node:crypto");
|
|
3
|
+
node_crypto = require_rolldown_runtime.__toESM(node_crypto);
|
|
4
|
+
let _arcblock_did = require("@arcblock/did");
|
|
5
|
+
let _ocap_util = require("@ocap/util");
|
|
6
|
+
|
|
7
|
+
//#region src/did-tls.ts
|
|
8
|
+
/**
|
|
9
|
+
* Zero-CA X.509v3 DID-TLS certificate issuer, strict bounded ASN.1 DER parser,
|
|
10
|
+
* and fail-closed peer verifier (`@ocap/chain-node`, #2025).
|
|
11
|
+
*
|
|
12
|
+
* Wire-compatible 1:1 with `arc` DID-TLS (`OID 1.3.101.112` Ed25519 and
|
|
13
|
+
* `OID 1.3.6.1.4.1.59489.1.1` P-256 `DIDBindingProof` Cloudflare mTLS bridge).
|
|
14
|
+
* Uses `node:crypto` + `@arcblock/did` with zero `openssl` CLI subprocesses.
|
|
15
|
+
*/
|
|
16
|
+
/** Hard upper bound on accepted DER certificate size (16 KiB). */
|
|
17
|
+
const MAX_CERT_BYTES = 16384;
|
|
18
|
+
const MAX_DID_TLS_CERT_BYTES = MAX_CERT_BYTES;
|
|
19
|
+
/** Hard upper bound on PEM string input length before base64 decoding. */
|
|
20
|
+
const MAX_DID_TLS_PEM_CHARS = 32768;
|
|
21
|
+
/** Hard upper bound on DID length inside X.509 Subject/Issuer/SAN. */
|
|
22
|
+
const MAX_DID_TLS_DID_LENGTH = 512;
|
|
23
|
+
/** Maximum ASN.1 nesting depth accepted by the strict DER parser. */
|
|
24
|
+
const MAX_ASN1_DEPTH = 16;
|
|
25
|
+
/** Private Enterprise Number extension OID for ARC DID-TLS P-256 binding proof. */
|
|
26
|
+
const DID_TLS_BINDING_PROOF_OID = "1.3.6.1.4.1.59489.1.1";
|
|
27
|
+
/** Domain separation tag for Ed25519 DID-TLS P-256 binding signatures. */
|
|
28
|
+
const DID_TLS_BINDING_DOMAIN = "ARC-DID-TLS-BINDING-V1";
|
|
29
|
+
/** HKDF-SHA256 salt for deterministic P-256 key derivation from a 32-byte DID seed. */
|
|
30
|
+
const DID_TLS_P256_HKDF_SALT = "arc-did-tls-p256-salt-v1";
|
|
31
|
+
/** HKDF-SHA256 info prefix for deterministic P-256 key derivation. */
|
|
32
|
+
const DID_TLS_P256_HKDF_INFO_PREFIX = "arc-did-tls-p256-key-v1:";
|
|
33
|
+
/** Default clock skew tolerance in seconds for certificate validity checks. */
|
|
34
|
+
const DEFAULT_DID_TLS_CLOCK_SKEW_SECONDS = 60;
|
|
35
|
+
const OID_COMMON_NAME = "2.5.4.3";
|
|
36
|
+
const OID_ED25519 = "1.3.101.112";
|
|
37
|
+
const OID_ECDSA_WITH_SHA256 = "1.2.840.10045.4.3.2";
|
|
38
|
+
const OID_EC_PUBLIC_KEY = "1.2.840.10045.2.1";
|
|
39
|
+
const OID_PRIME256V1 = "1.2.840.10045.3.1.7";
|
|
40
|
+
const OID_EXT_SUBJECT_KEY_ID = "2.5.29.14";
|
|
41
|
+
const OID_EXT_KEY_USAGE = "2.5.29.15";
|
|
42
|
+
const OID_EXT_SUBJECT_ALT_NAME = "2.5.29.17";
|
|
43
|
+
const OID_EXT_BASIC_CONSTRAINTS = "2.5.29.19";
|
|
44
|
+
const OID_EXT_AUTHORITY_KEY_ID = "2.5.29.35";
|
|
45
|
+
const OID_EXT_EXTENDED_KEY_USAGE = "2.5.29.37";
|
|
46
|
+
const OID_KP_SERVER_AUTH = "1.3.6.1.5.5.7.3.1";
|
|
47
|
+
const OID_KP_CLIENT_AUTH = "1.3.6.1.5.5.7.3.2";
|
|
48
|
+
const KNOWN_EXTENSION_OIDS = new Set([
|
|
49
|
+
OID_EXT_SUBJECT_KEY_ID,
|
|
50
|
+
OID_EXT_KEY_USAGE,
|
|
51
|
+
OID_EXT_SUBJECT_ALT_NAME,
|
|
52
|
+
OID_EXT_BASIC_CONSTRAINTS,
|
|
53
|
+
OID_EXT_AUTHORITY_KEY_ID,
|
|
54
|
+
OID_EXT_EXTENDED_KEY_USAGE,
|
|
55
|
+
DID_TLS_BINDING_PROOF_OID
|
|
56
|
+
]);
|
|
57
|
+
const P256_P = 115792089210356248762697446949407573530086143415290314195533631308867097853951n;
|
|
58
|
+
const P256_A = 115792089210356248762697446949407573530086143415290314195533631308867097853948n;
|
|
59
|
+
const P256_B = 41058363725152142129326129780047268409114441015993725554835256314039467401291n;
|
|
60
|
+
const P256_N = 115792089210356248762697446949407573529996955224135760342422259061068512044369n;
|
|
61
|
+
const P256_GX = 48439561293906451759052585252797914202762949526041747995844080717082404635286n;
|
|
62
|
+
const P256_GY = 36134250956749795798585127919587881956611106672985015071877198253568414405109n;
|
|
63
|
+
var DidTlsParseError = class extends Error {
|
|
64
|
+
constructor(reason, detail) {
|
|
65
|
+
super(detail);
|
|
66
|
+
this.name = "DidTlsParseError";
|
|
67
|
+
this.reason = reason;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
const TEXT_ENCODER = new TextEncoder();
|
|
71
|
+
const TEXT_DECODER = new TextDecoder("utf-8", { fatal: true });
|
|
72
|
+
const HEX_TABLE = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
73
|
+
function didTlsBytesToHex(bytes) {
|
|
74
|
+
let out = "";
|
|
75
|
+
for (let i = 0; i < bytes.length; i++) out += HEX_TABLE[bytes[i]];
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
function didTlsHexToBytes(input, expectedLength) {
|
|
79
|
+
if (typeof input !== "string") throw new Error("Expected hex string");
|
|
80
|
+
const trimmed = input.trim();
|
|
81
|
+
const clean = trimmed.startsWith("0x") || trimmed.startsWith("0X") ? trimmed.slice(2) : trimmed;
|
|
82
|
+
if (clean.length === 0 || clean.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(clean)) throw new Error("Invalid hex encoding");
|
|
83
|
+
const out = new Uint8Array(clean.length / 2);
|
|
84
|
+
for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);
|
|
85
|
+
if (expectedLength !== void 0 && out.length !== expectedLength) throw new Error(`Expected ${expectedLength} bytes, got ${out.length}`);
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
function concatBytes(...chunks) {
|
|
89
|
+
let total = 0;
|
|
90
|
+
for (const c of chunks) total += c.byteLength;
|
|
91
|
+
const out = new Uint8Array(total);
|
|
92
|
+
let offset = 0;
|
|
93
|
+
for (const c of chunks) {
|
|
94
|
+
out.set(c, offset);
|
|
95
|
+
offset += c.byteLength;
|
|
96
|
+
}
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
function constantTimeEqual(a, b) {
|
|
100
|
+
if (a.byteLength !== b.byteLength) return false;
|
|
101
|
+
return node_crypto.default.timingSafeEqual(a, b);
|
|
102
|
+
}
|
|
103
|
+
function sha256Bytes(data) {
|
|
104
|
+
return new Uint8Array(node_crypto.default.createHash("sha256").update(data).digest());
|
|
105
|
+
}
|
|
106
|
+
const B64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
107
|
+
function bytesToBase64(bytes) {
|
|
108
|
+
return Buffer.from(bytes).toString("base64");
|
|
109
|
+
}
|
|
110
|
+
function base64ToBytesStrict(b64) {
|
|
111
|
+
const stripped = b64.replace(/[ \t\r\n]/g, "");
|
|
112
|
+
if (stripped.length === 0 || stripped.length % 4 !== 0) throw new DidTlsParseError("malformed-cert", "Invalid base64 length in PEM block");
|
|
113
|
+
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(stripped)) throw new DidTlsParseError("malformed-cert", "Invalid base64 characters in PEM block");
|
|
114
|
+
const pad = stripped.endsWith("==") ? 2 : stripped.endsWith("=") ? 1 : 0;
|
|
115
|
+
const outLen = stripped.length / 4 * 3 - pad;
|
|
116
|
+
const out = new Uint8Array(outLen);
|
|
117
|
+
let outIdx = 0;
|
|
118
|
+
for (let i = 0; i < stripped.length; i += 4) {
|
|
119
|
+
const c0 = B64_ALPHABET.indexOf(stripped[i]);
|
|
120
|
+
const c1 = B64_ALPHABET.indexOf(stripped[i + 1]);
|
|
121
|
+
const c2 = stripped[i + 2] === "=" ? 0 : B64_ALPHABET.indexOf(stripped[i + 2]);
|
|
122
|
+
const c3 = stripped[i + 3] === "=" ? 0 : B64_ALPHABET.indexOf(stripped[i + 3]);
|
|
123
|
+
const triple = c0 << 18 | c1 << 12 | c2 << 6 | c3;
|
|
124
|
+
out[outIdx++] = triple >> 16 & 255;
|
|
125
|
+
if (outIdx < outLen) out[outIdx++] = triple >> 8 & 255;
|
|
126
|
+
if (outIdx < outLen) out[outIdx++] = triple & 255;
|
|
127
|
+
}
|
|
128
|
+
if (pad === 2) {
|
|
129
|
+
if ((B64_ALPHABET.indexOf(stripped[stripped.length - 3]) & 15) !== 0) throw new DidTlsParseError("malformed-cert", "Non-canonical base64 padding bits");
|
|
130
|
+
} else if (pad === 1) {
|
|
131
|
+
if ((B64_ALPHABET.indexOf(stripped[stripped.length - 2]) & 3) !== 0) throw new DidTlsParseError("malformed-cert", "Non-canonical base64 padding bits");
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
function encodePem(label, der) {
|
|
136
|
+
const b64 = bytesToBase64(der);
|
|
137
|
+
const lines = [`-----BEGIN ${label}-----`];
|
|
138
|
+
for (let i = 0; i < b64.length; i += 64) lines.push(b64.slice(i, i + 64));
|
|
139
|
+
lines.push(`-----END ${label}-----`, "");
|
|
140
|
+
return lines.join("\n");
|
|
141
|
+
}
|
|
142
|
+
function extractCertDer(certDerOrPem) {
|
|
143
|
+
if (typeof certDerOrPem === "string") {
|
|
144
|
+
if (certDerOrPem.length > MAX_DID_TLS_PEM_CHARS) throw new DidTlsParseError("oversized-cert", `Certificate PEM exceeds ${MAX_DID_TLS_PEM_CHARS} characters`);
|
|
145
|
+
const beginMarker = "-----BEGIN CERTIFICATE-----";
|
|
146
|
+
const endMarker = "-----END CERTIFICATE-----";
|
|
147
|
+
const firstBegin = certDerOrPem.indexOf(beginMarker);
|
|
148
|
+
if (firstBegin < 0) throw new DidTlsParseError("malformed-cert", "Missing BEGIN CERTIFICATE PEM header");
|
|
149
|
+
if (certDerOrPem.indexOf(beginMarker, firstBegin + 27) >= 0) throw new DidTlsParseError("malformed-cert", "Multiple CERTIFICATE PEM blocks are not permitted");
|
|
150
|
+
const endIdx = certDerOrPem.indexOf(endMarker, firstBegin + 27);
|
|
151
|
+
if (endIdx < 0) throw new DidTlsParseError("malformed-cert", "Missing END CERTIFICATE PEM footer");
|
|
152
|
+
const leading = certDerOrPem.slice(0, firstBegin).trim();
|
|
153
|
+
const trailing = certDerOrPem.slice(endIdx + 25).trim();
|
|
154
|
+
if (leading.length > 0 || trailing.length > 0) throw new DidTlsParseError("malformed-cert", "Unexpected content outside CERTIFICATE PEM armor");
|
|
155
|
+
const der = base64ToBytesStrict(certDerOrPem.slice(firstBegin + 27, endIdx));
|
|
156
|
+
if (der.byteLength > MAX_CERT_BYTES) throw new DidTlsParseError("oversized-cert", `Certificate DER length ${der.byteLength} exceeds max ${MAX_CERT_BYTES}`);
|
|
157
|
+
return der;
|
|
158
|
+
}
|
|
159
|
+
if (!(certDerOrPem instanceof Uint8Array)) throw new DidTlsParseError("malformed-cert", "Certificate must be Uint8Array, Buffer, or PEM string");
|
|
160
|
+
if (certDerOrPem.byteLength === 0) throw new DidTlsParseError("malformed-cert", "Certificate DER is empty");
|
|
161
|
+
if (certDerOrPem.byteLength > MAX_CERT_BYTES) throw new DidTlsParseError("oversized-cert", `Certificate DER length ${certDerOrPem.byteLength} exceeds max ${MAX_CERT_BYTES}`);
|
|
162
|
+
let firstNonWs = 0;
|
|
163
|
+
while (firstNonWs < certDerOrPem.byteLength && (certDerOrPem[firstNonWs] === 32 || certDerOrPem[firstNonWs] === 9 || certDerOrPem[firstNonWs] === 10 || certDerOrPem[firstNonWs] === 13)) firstNonWs++;
|
|
164
|
+
if (firstNonWs < certDerOrPem.byteLength && certDerOrPem[firstNonWs] === 45) {
|
|
165
|
+
let text;
|
|
166
|
+
try {
|
|
167
|
+
text = TEXT_DECODER.decode(certDerOrPem);
|
|
168
|
+
} catch {
|
|
169
|
+
throw new DidTlsParseError("malformed-cert", "Invalid UTF-8 in PEM buffer");
|
|
170
|
+
}
|
|
171
|
+
return extractCertDer(text);
|
|
172
|
+
}
|
|
173
|
+
return new Uint8Array(certDerOrPem.buffer, certDerOrPem.byteOffset, certDerOrPem.byteLength);
|
|
174
|
+
}
|
|
175
|
+
const W3C_METHOD_NAME_RE = /^[a-z0-9]+$/;
|
|
176
|
+
const W3C_METHOD_ID_RE = /^(?:(?:[A-Za-z0-9._-]|%[0-9A-Fa-f]{2})*:)*(?:[A-Za-z0-9._-]|%[0-9A-Fa-f]{2})+$/;
|
|
177
|
+
const CRYPTO_ARCBLOCK_METHODS = new Set([
|
|
178
|
+
"abt",
|
|
179
|
+
"spaces",
|
|
180
|
+
"afs",
|
|
181
|
+
"aos"
|
|
182
|
+
]);
|
|
183
|
+
function isValidW3cDidSyntax(value) {
|
|
184
|
+
if (typeof value !== "string" || !value.startsWith("did:")) return false;
|
|
185
|
+
if (value.length > MAX_DID_TLS_DID_LENGTH) return false;
|
|
186
|
+
for (let i = 0; i < value.length; i++) {
|
|
187
|
+
const code = value.charCodeAt(i);
|
|
188
|
+
if (code <= 32 || code >= 127) return false;
|
|
189
|
+
}
|
|
190
|
+
const rest = value.slice(4);
|
|
191
|
+
const methodSep = rest.indexOf(":");
|
|
192
|
+
if (methodSep <= 0) return false;
|
|
193
|
+
const method = rest.slice(0, methodSep);
|
|
194
|
+
if (!W3C_METHOD_NAME_RE.test(method)) return false;
|
|
195
|
+
const methodId = rest.slice(methodSep + 1);
|
|
196
|
+
if (!methodId || !W3C_METHOD_ID_RE.test(methodId)) return false;
|
|
197
|
+
if (CRYPTO_ARCBLOCK_METHODS.has(method) && !(0, _arcblock_did.isValid)((0, _arcblock_did.toAddress)(value))) return false;
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Normalize either a bare OCAP DID (`z1...`) or a W3C DID (`did:abt:z1...`, `did:spaces:z1...`, `did:arc:...`)
|
|
202
|
+
* into its canonical W3C DID string (`did:...`).
|
|
203
|
+
*/
|
|
204
|
+
function canonicalizeTlsDid(rawDid, fieldName = "DID") {
|
|
205
|
+
if (typeof rawDid !== "string") throw new DidTlsParseError("invalid-did", `Invalid ${fieldName}`);
|
|
206
|
+
const trimmed = rawDid.trim();
|
|
207
|
+
if (!trimmed || trimmed.length > MAX_DID_TLS_DID_LENGTH) throw new DidTlsParseError("invalid-did", `Invalid ${fieldName} length`);
|
|
208
|
+
for (let i = 0; i < trimmed.length; i++) {
|
|
209
|
+
const code = trimmed.charCodeAt(i);
|
|
210
|
+
if (code <= 32 || code >= 127) throw new DidTlsParseError("invalid-did", `Control or non-ASCII byte in ${fieldName}`);
|
|
211
|
+
}
|
|
212
|
+
if (!trimmed.startsWith("did:")) {
|
|
213
|
+
if ((0, _arcblock_did.isValid)(trimmed)) return (0, _arcblock_did.formatDid)((0, _arcblock_did.toAddress)(trimmed), "abt");
|
|
214
|
+
throw new DidTlsParseError("invalid-did", `Invalid ${fieldName}: '${trimmed.slice(0, 80)}'`);
|
|
215
|
+
}
|
|
216
|
+
if (!isValidW3cDidSyntax(trimmed)) throw new DidTlsParseError("invalid-did", `Invalid ${fieldName}: '${String(trimmed).slice(0, 80)}'`);
|
|
217
|
+
const method = (0, _arcblock_did.extractMethod)(trimmed);
|
|
218
|
+
if (method && CRYPTO_ARCBLOCK_METHODS.has(method)) return (0, _arcblock_did.formatDid)((0, _arcblock_did.toAddress)(trimmed), method);
|
|
219
|
+
return trimmed;
|
|
220
|
+
}
|
|
221
|
+
function assertStrictX509Did(did, fieldName) {
|
|
222
|
+
if (!isValidW3cDidSyntax(did)) throw new DidTlsParseError("invalid-did", `Invalid ${fieldName}: '${String(did).slice(0, 80)}'`);
|
|
223
|
+
}
|
|
224
|
+
function parseIpv4Bytes(ip) {
|
|
225
|
+
if (!/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(ip)) return null;
|
|
226
|
+
const parts = ip.split(".");
|
|
227
|
+
if (parts.length !== 4) return null;
|
|
228
|
+
const out = new Uint8Array(4);
|
|
229
|
+
for (let i = 0; i < 4; i++) {
|
|
230
|
+
const part = parts[i];
|
|
231
|
+
if (part.length > 1 && part.startsWith("0")) return null;
|
|
232
|
+
const val = Number.parseInt(part, 10);
|
|
233
|
+
if (!Number.isInteger(val) || val < 0 || val > 255) return null;
|
|
234
|
+
out[i] = val;
|
|
235
|
+
}
|
|
236
|
+
return out;
|
|
237
|
+
}
|
|
238
|
+
function parseIpv6Bytes(rawIp) {
|
|
239
|
+
const ip = rawIp.startsWith("[") && rawIp.endsWith("]") ? rawIp.slice(1, -1) : rawIp;
|
|
240
|
+
if (!ip.includes(":")) return null;
|
|
241
|
+
if (/[^0-9a-fA-F:.]/.test(ip)) return null;
|
|
242
|
+
let working = ip;
|
|
243
|
+
if (working.includes(".")) {
|
|
244
|
+
const lastColon = working.lastIndexOf(":");
|
|
245
|
+
if (lastColon < 0) return null;
|
|
246
|
+
const v4 = parseIpv4Bytes(working.slice(lastColon + 1));
|
|
247
|
+
if (!v4) return null;
|
|
248
|
+
const hi = (v4[0] << 8 | v4[1]).toString(16);
|
|
249
|
+
const lo = (v4[2] << 8 | v4[3]).toString(16);
|
|
250
|
+
working = `${working.slice(0, lastColon)}:${hi}:${lo}`;
|
|
251
|
+
}
|
|
252
|
+
const doubleColonParts = working.split("::");
|
|
253
|
+
if (doubleColonParts.length > 2) return null;
|
|
254
|
+
let groups;
|
|
255
|
+
if (doubleColonParts.length === 2) {
|
|
256
|
+
const left = doubleColonParts[0] ? doubleColonParts[0].split(":") : [];
|
|
257
|
+
const right = doubleColonParts[1] ? doubleColonParts[1].split(":") : [];
|
|
258
|
+
const missing = 8 - (left.length + right.length);
|
|
259
|
+
if (missing < 1) return null;
|
|
260
|
+
groups = [
|
|
261
|
+
...left,
|
|
262
|
+
...Array.from({ length: missing }, () => "0"),
|
|
263
|
+
...right
|
|
264
|
+
];
|
|
265
|
+
} else {
|
|
266
|
+
groups = working.split(":");
|
|
267
|
+
if (groups.length !== 8) return null;
|
|
268
|
+
}
|
|
269
|
+
if (groups.length !== 8) return null;
|
|
270
|
+
const out = new Uint8Array(16);
|
|
271
|
+
for (let i = 0; i < 8; i++) {
|
|
272
|
+
const g = groups[i];
|
|
273
|
+
if (g.length === 0 || g.length > 4 || !/^[0-9a-fA-F]+$/.test(g)) return null;
|
|
274
|
+
const v = Number.parseInt(g, 16);
|
|
275
|
+
out[i * 2] = v >> 8 & 255;
|
|
276
|
+
out[i * 2 + 1] = v & 255;
|
|
277
|
+
}
|
|
278
|
+
return out;
|
|
279
|
+
}
|
|
280
|
+
function parseIpBytes(ip) {
|
|
281
|
+
return parseIpv4Bytes(ip) ?? parseIpv6Bytes(ip);
|
|
282
|
+
}
|
|
283
|
+
function formatIpBytes(bytes) {
|
|
284
|
+
if (bytes.byteLength === 4) return `${bytes[0]}.${bytes[1]}.${bytes[2]}.${bytes[3]}`;
|
|
285
|
+
if (bytes.byteLength === 16) {
|
|
286
|
+
const words = [];
|
|
287
|
+
for (let i = 0; i < 16; i += 2) words.push(bytes[i] << 8 | bytes[i + 1]);
|
|
288
|
+
let bestStart = -1;
|
|
289
|
+
let bestLen = 0;
|
|
290
|
+
let curStart = -1;
|
|
291
|
+
let curLen = 0;
|
|
292
|
+
for (let i = 0; i < 8; i++) if (words[i] === 0) {
|
|
293
|
+
if (curStart < 0) {
|
|
294
|
+
curStart = i;
|
|
295
|
+
curLen = 1;
|
|
296
|
+
} else curLen++;
|
|
297
|
+
if (curLen > bestLen && curLen >= 2) {
|
|
298
|
+
bestStart = curStart;
|
|
299
|
+
bestLen = curLen;
|
|
300
|
+
}
|
|
301
|
+
} else {
|
|
302
|
+
curStart = -1;
|
|
303
|
+
curLen = 0;
|
|
304
|
+
}
|
|
305
|
+
if (bestStart >= 0) return `${words.slice(0, bestStart).map((w) => w.toString(16)).join(":")}::${words.slice(bestStart + bestLen).map((w) => w.toString(16)).join(":")}`;
|
|
306
|
+
return words.map((w) => w.toString(16)).join(":");
|
|
307
|
+
}
|
|
308
|
+
throw new DidTlsParseError("malformed-cert", `Invalid iPAddress SAN byte length: ${bytes.byteLength}`);
|
|
309
|
+
}
|
|
310
|
+
const DNS_LABEL_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
311
|
+
function validateAndNormalizeDnsSan(raw) {
|
|
312
|
+
if (typeof raw !== "string") throw new DidTlsParseError("malformed-cert", "DNS SAN must be a string");
|
|
313
|
+
const lower = raw.toLowerCase();
|
|
314
|
+
if (lower.length === 0 || lower.length > 253) throw new DidTlsParseError("malformed-cert", `Invalid DNS SAN length: '${raw}'`);
|
|
315
|
+
if (parseIpBytes(lower) !== null) throw new DidTlsParseError("malformed-cert", `IP literal not allowed in dNSName SAN: '${raw}'`);
|
|
316
|
+
const isWildcard = lower.startsWith("*.");
|
|
317
|
+
const rest = isWildcard ? lower.slice(2) : lower;
|
|
318
|
+
if (rest.includes("*")) throw new DidTlsParseError("malformed-cert", `Invalid wildcard placement in DNS SAN: '${raw}'`);
|
|
319
|
+
const labels = rest.split(".");
|
|
320
|
+
if (isWildcard && labels.length < 2) throw new DidTlsParseError("malformed-cert", `Single-label wildcard DNS SAN is forbidden: '${raw}'`);
|
|
321
|
+
for (const label of labels) if (!DNS_LABEL_RE.test(label)) throw new DidTlsParseError("malformed-cert", `Invalid DNS label in SAN: '${raw}'`);
|
|
322
|
+
if (labels.length >= 2 && /^\d+$/.test(labels[labels.length - 1])) throw new DidTlsParseError("malformed-cert", `Numeric TLD not allowed in DNS SAN: '${raw}'`);
|
|
323
|
+
return lower;
|
|
324
|
+
}
|
|
325
|
+
function matchesDnsPattern(pattern, candidateHost) {
|
|
326
|
+
if (pattern === candidateHost) return true;
|
|
327
|
+
if (!pattern.startsWith("*.")) return false;
|
|
328
|
+
const suffix = pattern.slice(2);
|
|
329
|
+
if (!suffix.includes(".")) return false;
|
|
330
|
+
if (!candidateHost.endsWith(`.${suffix}`)) return false;
|
|
331
|
+
const prefix = candidateHost.slice(0, candidateHost.length - suffix.length - 1);
|
|
332
|
+
return prefix.length > 0 && !prefix.includes(".") && DNS_LABEL_RE.test(prefix);
|
|
333
|
+
}
|
|
334
|
+
const TAG_BOOLEAN = 1;
|
|
335
|
+
const TAG_INTEGER = 2;
|
|
336
|
+
const TAG_BIT_STRING = 3;
|
|
337
|
+
const TAG_OCTET_STRING = 4;
|
|
338
|
+
const TAG_OID = 6;
|
|
339
|
+
const TAG_UTF8_STRING = 12;
|
|
340
|
+
const TAG_UTC_TIME = 23;
|
|
341
|
+
const TAG_GENERALIZED_TIME = 24;
|
|
342
|
+
const TAG_SEQUENCE = 48;
|
|
343
|
+
const TAG_SET = 49;
|
|
344
|
+
function derEncodeLength(len) {
|
|
345
|
+
if (!Number.isInteger(len) || len < 0) throw new Error(`Invalid DER length: ${len}`);
|
|
346
|
+
if (len < 128) return new Uint8Array([len]);
|
|
347
|
+
const bytes = [];
|
|
348
|
+
let rem = len;
|
|
349
|
+
while (rem > 0) {
|
|
350
|
+
bytes.unshift(rem & 255);
|
|
351
|
+
rem = Math.floor(rem / 256);
|
|
352
|
+
}
|
|
353
|
+
return new Uint8Array([128 | bytes.length, ...bytes]);
|
|
354
|
+
}
|
|
355
|
+
function derTlv(tag, content) {
|
|
356
|
+
return concatBytes(new Uint8Array([tag]), derEncodeLength(content.byteLength), content);
|
|
357
|
+
}
|
|
358
|
+
function derSequence(...items) {
|
|
359
|
+
return derTlv(TAG_SEQUENCE, concatBytes(...items));
|
|
360
|
+
}
|
|
361
|
+
function derSet(...items) {
|
|
362
|
+
return derTlv(TAG_SET, concatBytes(...items));
|
|
363
|
+
}
|
|
364
|
+
function derBoolean(value) {
|
|
365
|
+
return new Uint8Array([
|
|
366
|
+
TAG_BOOLEAN,
|
|
367
|
+
1,
|
|
368
|
+
value ? 255 : 0
|
|
369
|
+
]);
|
|
370
|
+
}
|
|
371
|
+
function derPositiveIntegerBytes(unsignedBytes) {
|
|
372
|
+
let start = 0;
|
|
373
|
+
while (start < unsignedBytes.byteLength - 1 && unsignedBytes[start] === 0) start++;
|
|
374
|
+
const trimmed = unsignedBytes.subarray(start);
|
|
375
|
+
if ((trimmed[0] & 128) !== 0) return derTlv(TAG_INTEGER, concatBytes(new Uint8Array([0]), trimmed));
|
|
376
|
+
return derTlv(TAG_INTEGER, trimmed);
|
|
377
|
+
}
|
|
378
|
+
function derSmallUint(n) {
|
|
379
|
+
if (!Number.isInteger(n) || n < 0 || n > 2147483647) throw new Error(`Invalid non-negative DER integer: ${n}`);
|
|
380
|
+
if (n === 0) return new Uint8Array([
|
|
381
|
+
TAG_INTEGER,
|
|
382
|
+
1,
|
|
383
|
+
0
|
|
384
|
+
]);
|
|
385
|
+
const bytes = [];
|
|
386
|
+
let rem = n;
|
|
387
|
+
while (rem > 0) {
|
|
388
|
+
bytes.unshift(rem & 255);
|
|
389
|
+
rem = Math.floor(rem / 256);
|
|
390
|
+
}
|
|
391
|
+
return derPositiveIntegerBytes(new Uint8Array(bytes));
|
|
392
|
+
}
|
|
393
|
+
function derBitString(content, unusedBits = 0) {
|
|
394
|
+
if (unusedBits < 0 || unusedBits > 7) throw new Error(`Invalid DER BIT STRING unusedBits: ${unusedBits}`);
|
|
395
|
+
return derTlv(TAG_BIT_STRING, concatBytes(new Uint8Array([unusedBits]), content));
|
|
396
|
+
}
|
|
397
|
+
function derOctetString(content) {
|
|
398
|
+
return derTlv(TAG_OCTET_STRING, content);
|
|
399
|
+
}
|
|
400
|
+
function derUtf8String(value) {
|
|
401
|
+
return derTlv(TAG_UTF8_STRING, TEXT_ENCODER.encode(value));
|
|
402
|
+
}
|
|
403
|
+
function derOid(oid) {
|
|
404
|
+
const parts = oid.split(".").map((p) => {
|
|
405
|
+
if (!/^\d+$/.test(p)) throw new Error(`Invalid OID arc in '${oid}'`);
|
|
406
|
+
return Number.parseInt(p, 10);
|
|
407
|
+
});
|
|
408
|
+
if (parts.length < 2) throw new Error(`OID '${oid}' must have at least 2 arcs`);
|
|
409
|
+
const [first, second, ...rest] = parts;
|
|
410
|
+
if (first === void 0 || second === void 0 || first > 2 || first < 2 && second >= 40) throw new Error(`Invalid OID root arcs in '${oid}'`);
|
|
411
|
+
const out = [first * 40 + second];
|
|
412
|
+
for (const arc of rest) {
|
|
413
|
+
if (!Number.isSafeInteger(arc) || arc < 0) throw new Error(`Invalid OID arc ${arc}`);
|
|
414
|
+
if (arc < 128) out.push(arc);
|
|
415
|
+
else {
|
|
416
|
+
const vlq = [arc & 127];
|
|
417
|
+
let rem = Math.floor(arc / 128);
|
|
418
|
+
while (rem > 0) {
|
|
419
|
+
vlq.unshift(128 | rem & 127);
|
|
420
|
+
rem = Math.floor(rem / 128);
|
|
421
|
+
}
|
|
422
|
+
out.push(...vlq);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
return derTlv(TAG_OID, new Uint8Array(out));
|
|
426
|
+
}
|
|
427
|
+
function derExplicitContext(tagNumber, innerDer) {
|
|
428
|
+
return derTlv(160 | tagNumber, innerDer);
|
|
429
|
+
}
|
|
430
|
+
function derImplicitPrimitiveContext(tagNumber, content) {
|
|
431
|
+
return derTlv(128 | tagNumber, content);
|
|
432
|
+
}
|
|
433
|
+
function derX509Time(date) {
|
|
434
|
+
const ms = date.getTime();
|
|
435
|
+
if (!Number.isFinite(ms)) throw new Error("Invalid certificate validity Date");
|
|
436
|
+
const year = date.getUTCFullYear();
|
|
437
|
+
const month = String(date.getUTCMonth() + 1).padStart(2, "0");
|
|
438
|
+
const day = String(date.getUTCDate()).padStart(2, "0");
|
|
439
|
+
const hour = String(date.getUTCHours()).padStart(2, "0");
|
|
440
|
+
const min = String(date.getUTCMinutes()).padStart(2, "0");
|
|
441
|
+
const sec = String(date.getUTCSeconds()).padStart(2, "0");
|
|
442
|
+
if (year >= 1950 && year <= 2049) {
|
|
443
|
+
const yy = String(year % 100).padStart(2, "0");
|
|
444
|
+
return derTlv(TAG_UTC_TIME, TEXT_ENCODER.encode(`${yy}${month}${day}${hour}${min}${sec}Z`));
|
|
445
|
+
}
|
|
446
|
+
if (year >= 2050 && year <= 9999) {
|
|
447
|
+
const yyyy = String(year).padStart(4, "0");
|
|
448
|
+
return derTlv(TAG_GENERALIZED_TIME, TEXT_ENCODER.encode(`${yyyy}${month}${day}${hour}${min}${sec}Z`));
|
|
449
|
+
}
|
|
450
|
+
throw new Error(`Certificate validity year ${year} out of RFC 5280 range (1950..9999)`);
|
|
451
|
+
}
|
|
452
|
+
function derX509NameCommonName(did) {
|
|
453
|
+
return derSequence(derSet(derSequence(derOid(OID_COMMON_NAME), derUtf8String(did))));
|
|
454
|
+
}
|
|
455
|
+
function derX509Extension(oid, critical, valueDer) {
|
|
456
|
+
return critical ? derSequence(derOid(oid), derBoolean(true), derOctetString(valueDer)) : derSequence(derOid(oid), derOctetString(valueDer));
|
|
457
|
+
}
|
|
458
|
+
var StrictDerReader = class StrictDerReader {
|
|
459
|
+
constructor(buf, offset = 0, end = buf.byteLength, depth = 0) {
|
|
460
|
+
if (depth > MAX_ASN1_DEPTH) throw new DidTlsParseError("malformed-cert", "ASN.1 nesting depth limit exceeded");
|
|
461
|
+
this.buf = buf;
|
|
462
|
+
this.offset = offset;
|
|
463
|
+
this.end = end;
|
|
464
|
+
this.depth = depth;
|
|
465
|
+
}
|
|
466
|
+
get hasMore() {
|
|
467
|
+
return this.offset < this.end;
|
|
468
|
+
}
|
|
469
|
+
peekTag() {
|
|
470
|
+
return this.offset < this.end ? this.buf[this.offset] : void 0;
|
|
471
|
+
}
|
|
472
|
+
assertEnd(context) {
|
|
473
|
+
if (this.offset !== this.end) throw new DidTlsParseError("malformed-cert", `Unexpected trailing DER bytes in ${context} (${this.end - this.offset} extra bytes)`);
|
|
474
|
+
}
|
|
475
|
+
readElement() {
|
|
476
|
+
if (this.offset + 2 > this.end) throw new DidTlsParseError("malformed-cert", "Truncated DER element header");
|
|
477
|
+
const start = this.offset;
|
|
478
|
+
const tag = this.buf[this.offset++];
|
|
479
|
+
if ((tag & 31) === 31) throw new DidTlsParseError("malformed-cert", "Unsupported high-tag-number DER tag");
|
|
480
|
+
const firstLen = this.buf[this.offset++];
|
|
481
|
+
let contentLen;
|
|
482
|
+
if ((firstLen & 128) === 0) contentLen = firstLen;
|
|
483
|
+
else {
|
|
484
|
+
const lenBytes = firstLen & 127;
|
|
485
|
+
if (lenBytes === 0) throw new DidTlsParseError("malformed-cert", "Indefinite BER length is forbidden in DER");
|
|
486
|
+
if (lenBytes > 2) throw new DidTlsParseError("malformed-cert", "DER length exceeds certificate size cap");
|
|
487
|
+
if (this.offset + lenBytes > this.end) throw new DidTlsParseError("malformed-cert", "Truncated multi-byte DER length");
|
|
488
|
+
if (this.buf[this.offset] === 0) throw new DidTlsParseError("malformed-cert", "Non-minimal leading zero in DER length");
|
|
489
|
+
contentLen = 0;
|
|
490
|
+
for (let i = 0; i < lenBytes; i++) contentLen = contentLen << 8 | this.buf[this.offset++];
|
|
491
|
+
if (contentLen < 128) throw new DidTlsParseError("malformed-cert", "Non-minimal multi-byte DER length for value < 128");
|
|
492
|
+
}
|
|
493
|
+
const headerLength = this.offset - start;
|
|
494
|
+
const contentEnd = this.offset + contentLen;
|
|
495
|
+
if (contentEnd > this.end) throw new DidTlsParseError("malformed-cert", "Truncated DER element value");
|
|
496
|
+
const content = this.buf.subarray(this.offset, contentEnd);
|
|
497
|
+
const raw = this.buf.subarray(start, contentEnd);
|
|
498
|
+
this.offset = contentEnd;
|
|
499
|
+
return {
|
|
500
|
+
tag,
|
|
501
|
+
headerLength,
|
|
502
|
+
content,
|
|
503
|
+
raw
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
readExpected(expectedTag, label) {
|
|
507
|
+
const el = this.readElement();
|
|
508
|
+
if (el.tag !== expectedTag) throw new DidTlsParseError("malformed-cert", `Expected DER tag 0x${expectedTag.toString(16)} for ${label}, got 0x${el.tag.toString(16)}`);
|
|
509
|
+
return el;
|
|
510
|
+
}
|
|
511
|
+
readSequence(label) {
|
|
512
|
+
const element = this.readExpected(TAG_SEQUENCE, label);
|
|
513
|
+
return {
|
|
514
|
+
element,
|
|
515
|
+
reader: new StrictDerReader(element.content, 0, element.content.byteLength, this.depth + 1)
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
subReader(content) {
|
|
519
|
+
return new StrictDerReader(content, 0, content.byteLength, this.depth + 1);
|
|
520
|
+
}
|
|
521
|
+
};
|
|
522
|
+
function decodeDerBoolean(el, label) {
|
|
523
|
+
if (el.tag !== TAG_BOOLEAN || el.content.byteLength !== 1) throw new DidTlsParseError("malformed-cert", `Invalid DER BOOLEAN in ${label}`);
|
|
524
|
+
const b = el.content[0];
|
|
525
|
+
if (b === 255) return true;
|
|
526
|
+
if (b === 0) return false;
|
|
527
|
+
throw new DidTlsParseError("malformed-cert", `Non-canonical DER BOOLEAN byte 0x${b.toString(16)} in ${label}`);
|
|
528
|
+
}
|
|
529
|
+
function decodeDerPositiveIntBytes(el, label) {
|
|
530
|
+
if (el.tag !== TAG_INTEGER || el.content.byteLength === 0) throw new DidTlsParseError("malformed-cert", `Empty or non-INTEGER in ${label}`);
|
|
531
|
+
const c = el.content;
|
|
532
|
+
if (c.byteLength > 1) {
|
|
533
|
+
if (c[0] === 0 && (c[1] & 128) === 0) throw new DidTlsParseError("malformed-cert", `Non-minimal leading 0x00 in INTEGER ${label}`);
|
|
534
|
+
if (c[0] === 255 && (c[1] & 128) !== 0) throw new DidTlsParseError("malformed-cert", `Non-minimal leading 0xff in INTEGER ${label}`);
|
|
535
|
+
}
|
|
536
|
+
if ((c[0] & 128) !== 0) throw new DidTlsParseError("malformed-cert", `Negative INTEGER not allowed in ${label}`);
|
|
537
|
+
if (c.byteLength > 1 && c[0] === 0) return c.subarray(1);
|
|
538
|
+
return c;
|
|
539
|
+
}
|
|
540
|
+
function decodeDerSmallUint(el, label) {
|
|
541
|
+
const bytes = decodeDerPositiveIntBytes(el, label);
|
|
542
|
+
if (bytes.byteLength > 4) throw new DidTlsParseError("malformed-cert", `INTEGER overflow in ${label}`);
|
|
543
|
+
let val = 0;
|
|
544
|
+
for (let i = 0; i < bytes.byteLength; i++) val = val * 256 + bytes[i];
|
|
545
|
+
return val;
|
|
546
|
+
}
|
|
547
|
+
function decodeDerBitString(el, label) {
|
|
548
|
+
if (el.tag !== TAG_BIT_STRING || el.content.byteLength < 1) throw new DidTlsParseError("malformed-cert", `Invalid BIT STRING in ${label}`);
|
|
549
|
+
const unusedBits = el.content[0];
|
|
550
|
+
if (unusedBits > 7) throw new DidTlsParseError("malformed-cert", `Invalid BIT STRING unusedBits in ${label}`);
|
|
551
|
+
const bytes = el.content.subarray(1);
|
|
552
|
+
if (bytes.byteLength === 0 && unusedBits !== 0) throw new DidTlsParseError("malformed-cert", "Empty BIT STRING has non-zero unusedBits");
|
|
553
|
+
if (bytes.byteLength > 0 && unusedBits > 0) {
|
|
554
|
+
const mask = (1 << unusedBits) - 1;
|
|
555
|
+
if ((bytes[bytes.byteLength - 1] & mask) !== 0) throw new DidTlsParseError("malformed-cert", `Non-zero padding bits in DER BIT STRING ${label}`);
|
|
556
|
+
}
|
|
557
|
+
return {
|
|
558
|
+
bytes,
|
|
559
|
+
unusedBits
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
function decodeDerOid(el, label) {
|
|
563
|
+
if (el.tag !== TAG_OID || el.content.byteLength === 0) throw new DidTlsParseError("malformed-cert", `Invalid OID in ${label}`);
|
|
564
|
+
const b0 = el.content[0];
|
|
565
|
+
const first = b0 < 80 ? Math.floor(b0 / 40) : 2;
|
|
566
|
+
const arcs = [first, b0 - first * 40];
|
|
567
|
+
let acc = 0;
|
|
568
|
+
let inArc = false;
|
|
569
|
+
for (let i = 1; i < el.content.byteLength; i++) {
|
|
570
|
+
const byte = el.content[i];
|
|
571
|
+
if (!inArc && byte === 128) throw new DidTlsParseError("malformed-cert", `Non-minimal VLQ arc in OID ${label}`);
|
|
572
|
+
inArc = true;
|
|
573
|
+
acc = acc * 128 + (byte & 127);
|
|
574
|
+
if (!Number.isSafeInteger(acc)) throw new DidTlsParseError("malformed-cert", `OID arc overflow in ${label}`);
|
|
575
|
+
if ((byte & 128) === 0) {
|
|
576
|
+
arcs.push(acc);
|
|
577
|
+
acc = 0;
|
|
578
|
+
inArc = false;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
if (inArc) throw new DidTlsParseError("malformed-cert", `Truncated VLQ arc in OID ${label}`);
|
|
582
|
+
return arcs.join(".");
|
|
583
|
+
}
|
|
584
|
+
function decodeAsciiIa5(bytes, label) {
|
|
585
|
+
let out = "";
|
|
586
|
+
for (let i = 0; i < bytes.byteLength; i++) {
|
|
587
|
+
const b = bytes[i];
|
|
588
|
+
if (b <= 32 || b >= 127) throw new DidTlsParseError("malformed-cert", `Invalid IA5String character in ${label}`);
|
|
589
|
+
out += String.fromCharCode(b);
|
|
590
|
+
}
|
|
591
|
+
return out;
|
|
592
|
+
}
|
|
593
|
+
function decodeDerX509Time(el, label) {
|
|
594
|
+
let raw;
|
|
595
|
+
try {
|
|
596
|
+
raw = TEXT_DECODER.decode(el.content);
|
|
597
|
+
} catch {
|
|
598
|
+
throw new DidTlsParseError("malformed-cert", `Invalid UTF-8 in ${label}`);
|
|
599
|
+
}
|
|
600
|
+
let year;
|
|
601
|
+
let rest;
|
|
602
|
+
if (el.tag === TAG_UTC_TIME) {
|
|
603
|
+
if (!/^\d{12}Z$/.test(raw)) throw new DidTlsParseError("malformed-cert", `Invalid UTCTime syntax in ${label}`);
|
|
604
|
+
const yy = Number.parseInt(raw.slice(0, 2), 10);
|
|
605
|
+
year = yy >= 50 ? 1900 + yy : 2e3 + yy;
|
|
606
|
+
rest = raw.slice(2);
|
|
607
|
+
} else if (el.tag === TAG_GENERALIZED_TIME) {
|
|
608
|
+
if (!/^\d{14}Z$/.test(raw)) throw new DidTlsParseError("malformed-cert", `Invalid GeneralizedTime syntax in ${label}`);
|
|
609
|
+
year = Number.parseInt(raw.slice(0, 4), 10);
|
|
610
|
+
if (year < 2050) throw new DidTlsParseError("malformed-cert", `GeneralizedTime forbidden for year < 2050 in ${label}`);
|
|
611
|
+
rest = raw.slice(4);
|
|
612
|
+
} else throw new DidTlsParseError("malformed-cert", `Invalid time tag in ${label}`);
|
|
613
|
+
const month = Number.parseInt(rest.slice(0, 2), 10);
|
|
614
|
+
const day = Number.parseInt(rest.slice(2, 4), 10);
|
|
615
|
+
const hour = Number.parseInt(rest.slice(4, 6), 10);
|
|
616
|
+
const min = Number.parseInt(rest.slice(6, 8), 10);
|
|
617
|
+
const sec = Number.parseInt(rest.slice(8, 10), 10);
|
|
618
|
+
if (month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || min > 59 || sec > 59) throw new DidTlsParseError("malformed-cert", `Out-of-range calendar field in ${label}`);
|
|
619
|
+
const dt = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0));
|
|
620
|
+
if (dt.getUTCFullYear() !== year || dt.getUTCMonth() !== month - 1 || dt.getUTCDate() !== day) throw new DidTlsParseError("malformed-cert", `Invalid calendar date in ${label}`);
|
|
621
|
+
return dt;
|
|
622
|
+
}
|
|
623
|
+
function decodeSingleCommonNameDid(nameSeqReader, fieldLabel) {
|
|
624
|
+
if (!nameSeqReader.hasMore) throw new DidTlsParseError("invalid-did", `Empty ${fieldLabel} Name`);
|
|
625
|
+
const rdnSetEl = nameSeqReader.readExpected(TAG_SET, `${fieldLabel} RDN`);
|
|
626
|
+
nameSeqReader.assertEnd(`${fieldLabel} Name`);
|
|
627
|
+
const rdnReader = nameSeqReader.subReader(rdnSetEl.content);
|
|
628
|
+
const avaSeq = rdnReader.readSequence(`${fieldLabel} AttributeTypeAndValue`).reader;
|
|
629
|
+
rdnReader.assertEnd(`${fieldLabel} RDN`);
|
|
630
|
+
if (decodeDerOid(avaSeq.readExpected(TAG_OID, `${fieldLabel} OID`), fieldLabel) !== OID_COMMON_NAME) throw new DidTlsParseError("invalid-did", `${fieldLabel} must contain single CN attribute`);
|
|
631
|
+
const valEl = avaSeq.readElement();
|
|
632
|
+
avaSeq.assertEnd(`${fieldLabel} AttributeTypeAndValue`);
|
|
633
|
+
if (valEl.tag !== TAG_UTF8_STRING && valEl.tag !== 19 && valEl.tag !== 22) throw new DidTlsParseError("malformed-cert", `Unsupported string tag in ${fieldLabel} CN`);
|
|
634
|
+
let did;
|
|
635
|
+
try {
|
|
636
|
+
did = TEXT_DECODER.decode(valEl.content);
|
|
637
|
+
} catch {
|
|
638
|
+
throw new DidTlsParseError("malformed-cert", `Invalid UTF-8 in ${fieldLabel} CN`);
|
|
639
|
+
}
|
|
640
|
+
assertStrictX509Did(did, fieldLabel);
|
|
641
|
+
return did;
|
|
642
|
+
}
|
|
643
|
+
function modPos(a, m) {
|
|
644
|
+
const r = a % m;
|
|
645
|
+
return r < 0n ? r + m : r;
|
|
646
|
+
}
|
|
647
|
+
function modInv(a, m) {
|
|
648
|
+
let t = 0n;
|
|
649
|
+
let newT = 1n;
|
|
650
|
+
let r = m;
|
|
651
|
+
let newR = modPos(a, m);
|
|
652
|
+
while (newR !== 0n) {
|
|
653
|
+
const q = r / newR;
|
|
654
|
+
[t, newT] = [newT, t - q * newT];
|
|
655
|
+
[r, newR] = [newR, r - q * newR];
|
|
656
|
+
}
|
|
657
|
+
if (r !== 1n) throw new Error("Element is not invertible modulo p");
|
|
658
|
+
return t < 0n ? t + m : t;
|
|
659
|
+
}
|
|
660
|
+
const P256_INFINITY = {
|
|
661
|
+
x: 0n,
|
|
662
|
+
y: 1n,
|
|
663
|
+
z: 0n
|
|
664
|
+
};
|
|
665
|
+
function p256Double(pt) {
|
|
666
|
+
if (pt.z === 0n || pt.y === 0n) return P256_INFINITY;
|
|
667
|
+
const { x, y, z } = pt;
|
|
668
|
+
const z2 = modPos(z * z, P256_P);
|
|
669
|
+
const m = modPos(3n * modPos(x - z2, P256_P) * modPos(x + z2, P256_P), P256_P);
|
|
670
|
+
const y2 = modPos(y * y, P256_P);
|
|
671
|
+
const s = modPos(4n * x * y2, P256_P);
|
|
672
|
+
const x3 = modPos(m * m - 2n * s, P256_P);
|
|
673
|
+
const y4 = modPos(y2 * y2, P256_P);
|
|
674
|
+
return {
|
|
675
|
+
x: x3,
|
|
676
|
+
y: modPos(m * (s - x3) - 8n * y4, P256_P),
|
|
677
|
+
z: modPos(2n * y * z, P256_P)
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
function p256AddAffine(p1, qx, qy) {
|
|
681
|
+
if (p1.z === 0n) return {
|
|
682
|
+
x: qx,
|
|
683
|
+
y: qy,
|
|
684
|
+
z: 1n
|
|
685
|
+
};
|
|
686
|
+
const z1z1 = modPos(p1.z * p1.z, P256_P);
|
|
687
|
+
const u2 = modPos(qx * z1z1, P256_P);
|
|
688
|
+
const s2 = modPos(qy * modPos(p1.z * z1z1, P256_P), P256_P);
|
|
689
|
+
const h = modPos(u2 - p1.x, P256_P);
|
|
690
|
+
const r = modPos(2n * (s2 - p1.y), P256_P);
|
|
691
|
+
if (h === 0n) return r === 0n ? p256Double(p1) : P256_INFINITY;
|
|
692
|
+
const i = modPos(4n * modPos(h * h, P256_P), P256_P);
|
|
693
|
+
const j = modPos(h * i, P256_P);
|
|
694
|
+
const v = modPos(p1.x * i, P256_P);
|
|
695
|
+
const x3 = modPos(r * r - j - 2n * v, P256_P);
|
|
696
|
+
return {
|
|
697
|
+
x: x3,
|
|
698
|
+
y: modPos(r * (v - x3) - 2n * p1.y * j, P256_P),
|
|
699
|
+
z: modPos(2n * p1.z * h, P256_P)
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
function isValidP256Point(x, y) {
|
|
703
|
+
if (x < 0n || x >= P256_P || y < 0n || y >= P256_P) return false;
|
|
704
|
+
return modPos(y * y, P256_P) === modPos(modPos(modPos(x * x, P256_P) * x, P256_P) + P256_A * x + P256_B, P256_P);
|
|
705
|
+
}
|
|
706
|
+
function p256ScalarBaseMul(scalar) {
|
|
707
|
+
if (scalar <= 0n || scalar >= P256_N) throw new Error("P-256 scalar out of range [1, n-1]");
|
|
708
|
+
let acc = P256_INFINITY;
|
|
709
|
+
for (let bit = 255; bit >= 0; bit--) {
|
|
710
|
+
acc = p256Double(acc);
|
|
711
|
+
if ((scalar >> BigInt(bit) & 1n) === 1n) acc = p256AddAffine(acc, P256_GX, P256_GY);
|
|
712
|
+
}
|
|
713
|
+
if (acc.z === 0n) throw new Error("P-256 scalar multiplication yielded point at infinity");
|
|
714
|
+
const zInv = modInv(acc.z, P256_P);
|
|
715
|
+
const zInv2 = modPos(zInv * zInv, P256_P);
|
|
716
|
+
const zInv3 = modPos(zInv2 * zInv, P256_P);
|
|
717
|
+
const x = modPos(acc.x * zInv2, P256_P);
|
|
718
|
+
const y = modPos(acc.y * zInv3, P256_P);
|
|
719
|
+
if (!isValidP256Point(x, y)) throw new Error("Derived P-256 point failed curve check");
|
|
720
|
+
return {
|
|
721
|
+
x,
|
|
722
|
+
y
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
function bytesToBigInt(bytes) {
|
|
726
|
+
let n = 0n;
|
|
727
|
+
for (let i = 0; i < bytes.byteLength; i++) n = n << 8n | BigInt(bytes[i]);
|
|
728
|
+
return n;
|
|
729
|
+
}
|
|
730
|
+
function bigIntTo32Bytes(n) {
|
|
731
|
+
const out = new Uint8Array(32);
|
|
732
|
+
let rem = n;
|
|
733
|
+
for (let i = 31; i >= 0; i--) {
|
|
734
|
+
out[i] = Number(rem & 255n);
|
|
735
|
+
rem >>= 8n;
|
|
736
|
+
}
|
|
737
|
+
return out;
|
|
738
|
+
}
|
|
739
|
+
function validateUncompressedP256Point(point) {
|
|
740
|
+
if (point.byteLength !== 65 || point[0] !== 4) throw new DidTlsParseError("malformed-cert", "Invalid uncompressed P-256 EC point");
|
|
741
|
+
if (!isValidP256Point(bytesToBigInt(point.subarray(1, 33)), bytesToBigInt(point.subarray(33, 65)))) throw new DidTlsParseError("malformed-cert", "P-256 public key point is not on prime256v1");
|
|
742
|
+
}
|
|
743
|
+
function encodeEd25519Pkcs8Der(seed32) {
|
|
744
|
+
return derSequence(derSmallUint(0), derSequence(derOid(OID_ED25519)), derOctetString(derOctetString(seed32)));
|
|
745
|
+
}
|
|
746
|
+
function encodeEd25519SpkiDer(pubKey32) {
|
|
747
|
+
return derSequence(derSequence(derOid(OID_ED25519)), derBitString(pubKey32, 0));
|
|
748
|
+
}
|
|
749
|
+
function encodeP256SpkiDer(publicPoint65) {
|
|
750
|
+
return derSequence(derSequence(derOid(OID_EC_PUBLIC_KEY), derOid(OID_PRIME256V1)), derBitString(publicPoint65, 0));
|
|
751
|
+
}
|
|
752
|
+
function encodeP256Pkcs8Der(privateScalar32, publicPoint65) {
|
|
753
|
+
const ecPrivateKey = derSequence(derSmallUint(1), derOctetString(privateScalar32), derExplicitContext(1, derBitString(publicPoint65, 0)));
|
|
754
|
+
return derSequence(derSmallUint(0), derSequence(derOid(OID_EC_PUBLIC_KEY), derOid(OID_PRIME256V1)), derOctetString(ecPrivateKey));
|
|
755
|
+
}
|
|
756
|
+
function deriveEd25519PubRawFrom32ByteSeed(seed32) {
|
|
757
|
+
const pkcs8 = encodeEd25519Pkcs8Der(seed32);
|
|
758
|
+
const privKey = node_crypto.default.createPrivateKey({
|
|
759
|
+
key: Buffer.from(pkcs8),
|
|
760
|
+
format: "der",
|
|
761
|
+
type: "pkcs8"
|
|
762
|
+
});
|
|
763
|
+
const spki = new Uint8Array(node_crypto.default.createPublicKey(privKey).export({
|
|
764
|
+
format: "der",
|
|
765
|
+
type: "spki"
|
|
766
|
+
}));
|
|
767
|
+
if (spki.byteLength !== 44) throw new Error(`Unexpected Ed25519 SPKI DER length: ${spki.byteLength}`);
|
|
768
|
+
return spki.subarray(12, 44);
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* Extract a validated 32-byte Ed25519 secret seed from a 32-byte seed or 64-byte OCAP/TweetNaCl
|
|
772
|
+
* Ed25519 secret key (`Uint8Array`, `0x`/bare hex, or `z...` Base58btc).
|
|
773
|
+
* Never echoes key material in error messages.
|
|
774
|
+
*/
|
|
775
|
+
function extractEd25519SeedFromSecretKey(secretKey, label = "Ed25519 secret key") {
|
|
776
|
+
let rawBytes;
|
|
777
|
+
if (secretKey instanceof Uint8Array) rawBytes = new Uint8Array(secretKey);
|
|
778
|
+
else if (typeof secretKey === "string") {
|
|
779
|
+
const trimmed = secretKey.trim();
|
|
780
|
+
if (!trimmed) throw new Error(`${label} cannot be empty`);
|
|
781
|
+
if (trimmed.startsWith("z")) try {
|
|
782
|
+
rawBytes = new Uint8Array((0, _ocap_util.fromBase58)(trimmed));
|
|
783
|
+
} catch {
|
|
784
|
+
throw new Error(`Invalid Base58btc encoding in ${label}`);
|
|
785
|
+
}
|
|
786
|
+
else {
|
|
787
|
+
const cleanHex = trimmed.startsWith("0x") || trimmed.startsWith("0X") ? trimmed.slice(2) : trimmed;
|
|
788
|
+
if (cleanHex.length === 0 || cleanHex.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(cleanHex)) throw new Error(`Invalid hex encoding in ${label}`);
|
|
789
|
+
rawBytes = didTlsHexToBytes(cleanHex);
|
|
790
|
+
}
|
|
791
|
+
} else throw new Error(`Invalid ${label} type`);
|
|
792
|
+
if (rawBytes.byteLength === 32) return rawBytes;
|
|
793
|
+
if (rawBytes.byteLength === 64) {
|
|
794
|
+
const seed32 = rawBytes.subarray(0, 32);
|
|
795
|
+
const embeddedPub32 = rawBytes.subarray(32, 64);
|
|
796
|
+
if (!constantTimeEqual(deriveEd25519PubRawFrom32ByteSeed(seed32), embeddedPub32)) throw new Error(`64-byte ${label} has inconsistent embedded Ed25519 public key suffix`);
|
|
797
|
+
return new Uint8Array(seed32);
|
|
798
|
+
}
|
|
799
|
+
throw new Error(`${label} must decode to 32 or 64 bytes (got ${rawBytes.byteLength})`);
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* Decode a pinned 32-byte Ed25519 public key from `Uint8Array(32)`, 64-char hex (`0x` optional),
|
|
803
|
+
* `did:key:z6Mk...`, multibase `z6Mk...` (`0xed 0x01` + 32 bytes), or OCAP `z...` Base58btc (32 bytes).
|
|
804
|
+
*/
|
|
805
|
+
function decodeEd25519PublicKeyPin(input, label = "Ed25519 public key") {
|
|
806
|
+
if (input instanceof Uint8Array) {
|
|
807
|
+
if (input.byteLength !== 32) throw new Error(`${label} must be 32 bytes (got ${input.byteLength})`);
|
|
808
|
+
return new Uint8Array(input);
|
|
809
|
+
}
|
|
810
|
+
if (typeof input !== "string") throw new Error(`Invalid ${label}`);
|
|
811
|
+
const trimmed = input.trim();
|
|
812
|
+
if (!trimmed) throw new Error(`${label} cannot be empty`);
|
|
813
|
+
const strippedDidKey = trimmed.startsWith("did:key:") ? trimmed.slice(8) : trimmed;
|
|
814
|
+
if (strippedDidKey.startsWith("z")) {
|
|
815
|
+
let decoded;
|
|
816
|
+
try {
|
|
817
|
+
decoded = new Uint8Array((0, _ocap_util.fromBase58)(strippedDidKey));
|
|
818
|
+
} catch {
|
|
819
|
+
throw new Error(`Invalid multibase Base58btc ${label}`);
|
|
820
|
+
}
|
|
821
|
+
if (decoded.byteLength === 34 && decoded[0] === 237 && decoded[1] === 1) return decoded.subarray(2, 34);
|
|
822
|
+
if (decoded.byteLength === 32) return decoded;
|
|
823
|
+
throw new Error(`Unsupported multibase ${label} byte length (${decoded.byteLength})`);
|
|
824
|
+
}
|
|
825
|
+
return didTlsHexToBytes(trimmed, 32);
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* Derive the 32-byte Ed25519 public key from a 32-byte seed (or 64-byte Ed25519 secret key).
|
|
829
|
+
*/
|
|
830
|
+
function deriveEd25519PublicKeyFromSeed(seed) {
|
|
831
|
+
return deriveEd25519PubRawFrom32ByteSeed(extractEd25519SeedFromSecretKey(seed, "Ed25519 seed"));
|
|
832
|
+
}
|
|
833
|
+
function ed25519Sign(seed32, message) {
|
|
834
|
+
const privKey = node_crypto.default.createPrivateKey({
|
|
835
|
+
key: Buffer.from(encodeEd25519Pkcs8Der(seed32)),
|
|
836
|
+
format: "der",
|
|
837
|
+
type: "pkcs8"
|
|
838
|
+
});
|
|
839
|
+
return new Uint8Array(node_crypto.default.sign(null, new Uint8Array(message), privKey));
|
|
840
|
+
}
|
|
841
|
+
function ed25519Verify(pubKey32, message, signature64) {
|
|
842
|
+
if (pubKey32.byteLength !== 32 || signature64.byteLength !== 64) return false;
|
|
843
|
+
try {
|
|
844
|
+
const pubKey = node_crypto.default.createPublicKey({
|
|
845
|
+
key: Buffer.from(encodeEd25519SpkiDer(pubKey32)),
|
|
846
|
+
format: "der",
|
|
847
|
+
type: "spki"
|
|
848
|
+
});
|
|
849
|
+
return node_crypto.default.verify(null, new Uint8Array(message), pubKey, new Uint8Array(signature64));
|
|
850
|
+
} catch {
|
|
851
|
+
return false;
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* Deterministically derive an ECDSA P-256 keypair from a 32-byte Ed25519 DID seed
|
|
856
|
+
* and canonical W3C DID string via HKDF-SHA256 with rejection sampling over `[1, n-1]`.
|
|
857
|
+
*/
|
|
858
|
+
function deriveDidTlsP256KeyPair(seed, did) {
|
|
859
|
+
const canonicalDid = canonicalizeTlsDid(did, "DID");
|
|
860
|
+
const seed32 = extractEd25519SeedFromSecretKey(seed, "DID seed");
|
|
861
|
+
const saltBytes = TEXT_ENCODER.encode(DID_TLS_P256_HKDF_SALT);
|
|
862
|
+
for (let counter = 0; counter < 256; counter++) {
|
|
863
|
+
const infoStr = counter === 0 ? `${DID_TLS_P256_HKDF_INFO_PREFIX}${canonicalDid}` : `${DID_TLS_P256_HKDF_INFO_PREFIX}${canonicalDid}:${counter}`;
|
|
864
|
+
const candidate = new Uint8Array(node_crypto.default.hkdfSync("sha256", seed32, saltBytes, TEXT_ENCODER.encode(infoStr), 32));
|
|
865
|
+
const d = bytesToBigInt(candidate);
|
|
866
|
+
if (d > 0n && d < P256_N) {
|
|
867
|
+
const { x, y } = p256ScalarBaseMul(d);
|
|
868
|
+
const publicKeyUncompressed = concatBytes(new Uint8Array([4]), bigIntTo32Bytes(x), bigIntTo32Bytes(y));
|
|
869
|
+
return {
|
|
870
|
+
privateKeyScalar: candidate,
|
|
871
|
+
publicKeyUncompressed,
|
|
872
|
+
spkiDer: encodeP256SpkiDer(publicKeyUncompressed),
|
|
873
|
+
pkcs8Der: encodeP256Pkcs8Der(candidate, publicKeyUncompressed)
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
throw new Error("Exhausted HKDF counter deriving P-256 scalar");
|
|
878
|
+
}
|
|
879
|
+
function p1363ToDerEcdsaSignature(p1363) {
|
|
880
|
+
if (p1363.byteLength !== 64) throw new Error(`Expected 64-byte P1363 ECDSA signature, got ${p1363.byteLength}`);
|
|
881
|
+
const r = p1363.subarray(0, 32);
|
|
882
|
+
const s = p1363.subarray(32, 64);
|
|
883
|
+
if (bytesToBigInt(r) === 0n || bytesToBigInt(s) === 0n) throw new Error("Invalid zero r/s component in ECDSA signature");
|
|
884
|
+
return derSequence(derPositiveIntegerBytes(r), derPositiveIntegerBytes(s));
|
|
885
|
+
}
|
|
886
|
+
function derToP1363EcdsaSignature(derSig) {
|
|
887
|
+
try {
|
|
888
|
+
const outer = new StrictDerReader(derSig);
|
|
889
|
+
const { reader: seq } = outer.readSequence("Ecdsa-Sig-Value");
|
|
890
|
+
outer.assertEnd("Ecdsa-Sig-Value outer");
|
|
891
|
+
const rBytes = decodeDerPositiveIntBytes(seq.readExpected(TAG_INTEGER, "r"), "ECDSA r");
|
|
892
|
+
const sBytes = decodeDerPositiveIntBytes(seq.readExpected(TAG_INTEGER, "s"), "ECDSA s");
|
|
893
|
+
seq.assertEnd("Ecdsa-Sig-Value");
|
|
894
|
+
if (rBytes.byteLength > 32 || sBytes.byteLength > 32) return null;
|
|
895
|
+
const r = bytesToBigInt(rBytes);
|
|
896
|
+
const s = bytesToBigInt(sBytes);
|
|
897
|
+
if (r <= 0n || r >= P256_N || s <= 0n || s >= P256_N) return null;
|
|
898
|
+
return concatBytes(bigIntTo32Bytes(r), bigIntTo32Bytes(s));
|
|
899
|
+
} catch {
|
|
900
|
+
return null;
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
function p256SignDer(pkcs8Der, message) {
|
|
904
|
+
const privKey = node_crypto.default.createPrivateKey({
|
|
905
|
+
key: Buffer.from(pkcs8Der),
|
|
906
|
+
format: "der",
|
|
907
|
+
type: "pkcs8"
|
|
908
|
+
});
|
|
909
|
+
return p1363ToDerEcdsaSignature(new Uint8Array(node_crypto.default.sign("sha256", new Uint8Array(message), {
|
|
910
|
+
key: privKey,
|
|
911
|
+
dsaEncoding: "ieee-p1363"
|
|
912
|
+
})));
|
|
913
|
+
}
|
|
914
|
+
function p256VerifyDer(spkiDer, message, derSignature) {
|
|
915
|
+
const p1363 = derToP1363EcdsaSignature(derSignature);
|
|
916
|
+
if (!p1363) return false;
|
|
917
|
+
try {
|
|
918
|
+
const pubKey = node_crypto.default.createPublicKey({
|
|
919
|
+
key: Buffer.from(spkiDer),
|
|
920
|
+
format: "der",
|
|
921
|
+
type: "spki"
|
|
922
|
+
});
|
|
923
|
+
return node_crypto.default.verify("sha256", new Uint8Array(message), {
|
|
924
|
+
key: pubKey,
|
|
925
|
+
dsaEncoding: "ieee-p1363"
|
|
926
|
+
}, new Uint8Array(p1363));
|
|
927
|
+
} catch {
|
|
928
|
+
return false;
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
function buildDidBindingMessage(params) {
|
|
932
|
+
const nul = new Uint8Array([0]);
|
|
933
|
+
return concatBytes(TEXT_ENCODER.encode(DID_TLS_BINDING_DOMAIN), nul, TEXT_ENCODER.encode(params.subjectDid), nul, TEXT_ENCODER.encode(params.issuerDid), nul, params.spkiSha256, nul, TEXT_ENCODER.encode(params.notBeforeIso), nul, TEXT_ENCODER.encode(params.notAfterIso), nul, params.issuerTlsSpkiSha256, nul, params.extensionsSha256);
|
|
934
|
+
}
|
|
935
|
+
function issueDidTlsCertificate(options) {
|
|
936
|
+
const subjectSeed = extractEd25519SeedFromSecretKey(options.subjectSeed, "subjectSeed");
|
|
937
|
+
const subjectEd25519PublicKey = deriveEd25519PubRawFrom32ByteSeed(subjectSeed);
|
|
938
|
+
const subjectDid = options.subjectDid !== void 0 && options.subjectDid.trim() !== "" ? canonicalizeTlsDid(options.subjectDid, "subjectDid") : (0, _arcblock_did.formatDid)((0, _arcblock_did.fromPublicKey)(`0x${didTlsBytesToHex(subjectEd25519PublicKey)}`), "abt");
|
|
939
|
+
const issuerDid = options.issuerDid !== void 0 && options.issuerDid.trim() !== "" ? canonicalizeTlsDid(options.issuerDid, "issuerDid") : subjectDid;
|
|
940
|
+
if (issuerDid !== subjectDid && options.issuerSeed === void 0) throw new Error("issuerSeed is required when issuerDid differs from subjectDid");
|
|
941
|
+
const issuerSeed = options.issuerSeed !== void 0 ? extractEd25519SeedFromSecretKey(options.issuerSeed, "issuerSeed") : subjectSeed;
|
|
942
|
+
const wireAlgorithm = options.wireAlgorithm ?? "ed25519";
|
|
943
|
+
if (wireAlgorithm !== "ed25519" && wireAlgorithm !== "p256") throw new Error(`Unsupported wireAlgorithm: ${String(wireAlgorithm)}`);
|
|
944
|
+
const role = options.role ?? "dual";
|
|
945
|
+
if (role !== "server" && role !== "client" && role !== "dual" && role !== "ca") throw new Error(`Unsupported DID-TLS role: ${String(role)}`);
|
|
946
|
+
const normalizedDns = [];
|
|
947
|
+
const seenDns = /* @__PURE__ */ new Set();
|
|
948
|
+
for (const rawDns of options.dnsNames ?? []) {
|
|
949
|
+
const clean = validateAndNormalizeDnsSan(rawDns);
|
|
950
|
+
if (!seenDns.has(clean)) {
|
|
951
|
+
seenDns.add(clean);
|
|
952
|
+
normalizedDns.push(clean);
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
const ipBytesList = [];
|
|
956
|
+
const normalizedIps = [];
|
|
957
|
+
const seenIps = /* @__PURE__ */ new Set();
|
|
958
|
+
for (const rawIp of options.ipAddresses ?? []) {
|
|
959
|
+
const parsed = parseIpBytes(rawIp);
|
|
960
|
+
if (!parsed) throw new Error(`Invalid IP address in SAN: '${rawIp}'`);
|
|
961
|
+
const formatted = formatIpBytes(parsed);
|
|
962
|
+
if (!seenIps.has(formatted)) {
|
|
963
|
+
seenIps.add(formatted);
|
|
964
|
+
ipBytesList.push(parsed);
|
|
965
|
+
normalizedIps.push(formatted);
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
const nowWholeSec = Math.floor(Date.now() / 1e3) * 1e3;
|
|
969
|
+
const notBeforeMs = options.notBefore !== void 0 ? Math.floor(options.notBefore.getTime() / 1e3) * 1e3 : nowWholeSec;
|
|
970
|
+
if (!Number.isFinite(notBeforeMs)) throw new Error("Invalid notBefore timestamp");
|
|
971
|
+
let notAfterMs;
|
|
972
|
+
if (options.notAfter !== void 0) notAfterMs = Math.floor(options.notAfter.getTime() / 1e3) * 1e3;
|
|
973
|
+
else {
|
|
974
|
+
const days = options.validityDays ?? 365;
|
|
975
|
+
if (!Number.isInteger(days) || days < 1 || days > 3650) throw new Error(`validityDays must be an integer between 1 and 3650 (got ${days})`);
|
|
976
|
+
notAfterMs = notBeforeMs + days * 864e5;
|
|
977
|
+
}
|
|
978
|
+
if (!Number.isFinite(notAfterMs) || notAfterMs <= notBeforeMs) throw new Error("notAfter must be strictly greater than notBefore");
|
|
979
|
+
const notBefore = new Date(notBeforeMs);
|
|
980
|
+
const notAfter = new Date(notAfterMs);
|
|
981
|
+
let serialBytes;
|
|
982
|
+
if (options.serialNumber !== void 0) {
|
|
983
|
+
if (options.serialNumber.byteLength < 1 || options.serialNumber.byteLength > 20) throw new Error("serialNumber must be 1..20 bytes");
|
|
984
|
+
if ((options.serialNumber[0] & 128) !== 0 || bytesToBigInt(options.serialNumber) === 0n) throw new Error("serialNumber must be a positive non-zero unsigned integer");
|
|
985
|
+
serialBytes = new Uint8Array(options.serialNumber);
|
|
986
|
+
} else {
|
|
987
|
+
serialBytes = new Uint8Array(node_crypto.default.randomBytes(16));
|
|
988
|
+
serialBytes[0] = serialBytes[0] & 127 | 64;
|
|
989
|
+
}
|
|
990
|
+
const issuerEd25519PublicKey = issuerDid === subjectDid && constantTimeEqual(issuerSeed, subjectSeed) ? subjectEd25519PublicKey : deriveEd25519PubRawFrom32ByteSeed(issuerSeed);
|
|
991
|
+
let spkiDer;
|
|
992
|
+
let subjectBitStringBytes;
|
|
993
|
+
let issuerBitStringBytes;
|
|
994
|
+
let privateKeyPkcs8Der;
|
|
995
|
+
let sigAlgDer;
|
|
996
|
+
let issuerP256KeyPair;
|
|
997
|
+
if (wireAlgorithm === "ed25519") {
|
|
998
|
+
spkiDer = encodeEd25519SpkiDer(subjectEd25519PublicKey);
|
|
999
|
+
subjectBitStringBytes = subjectEd25519PublicKey;
|
|
1000
|
+
issuerBitStringBytes = issuerEd25519PublicKey;
|
|
1001
|
+
privateKeyPkcs8Der = encodeEd25519Pkcs8Der(subjectSeed);
|
|
1002
|
+
sigAlgDer = derSequence(derOid(OID_ED25519));
|
|
1003
|
+
} else {
|
|
1004
|
+
const subjectP256 = deriveDidTlsP256KeyPair(subjectSeed, subjectDid);
|
|
1005
|
+
issuerP256KeyPair = issuerDid === subjectDid && constantTimeEqual(issuerSeed, subjectSeed) ? subjectP256 : deriveDidTlsP256KeyPair(issuerSeed, issuerDid);
|
|
1006
|
+
spkiDer = subjectP256.spkiDer;
|
|
1007
|
+
subjectBitStringBytes = subjectP256.publicKeyUncompressed;
|
|
1008
|
+
issuerBitStringBytes = issuerP256KeyPair.publicKeyUncompressed;
|
|
1009
|
+
privateKeyPkcs8Der = subjectP256.pkcs8Der;
|
|
1010
|
+
sigAlgDer = derSequence(derOid(OID_ECDSA_WITH_SHA256));
|
|
1011
|
+
}
|
|
1012
|
+
const spkiSha256 = sha256Bytes(spkiDer);
|
|
1013
|
+
const ski20 = sha256Bytes(subjectBitStringBytes).subarray(0, 20);
|
|
1014
|
+
const aki20 = sha256Bytes(issuerBitStringBytes).subarray(0, 20);
|
|
1015
|
+
const basicConstraintsDer = role === "ca" ? derSequence(derBoolean(true), derSmallUint(0)) : derSequence();
|
|
1016
|
+
const keyUsageDer = role === "ca" ? derBitString(new Uint8Array([6]), 1) : derBitString(new Uint8Array([128]), 7);
|
|
1017
|
+
const sanDer = derSequence(...[
|
|
1018
|
+
derImplicitPrimitiveContext(6, TEXT_ENCODER.encode(subjectDid)),
|
|
1019
|
+
...normalizedDns.map((d) => derImplicitPrimitiveContext(2, TEXT_ENCODER.encode(d))),
|
|
1020
|
+
...ipBytesList.map((ip) => derImplicitPrimitiveContext(7, ip))
|
|
1021
|
+
]);
|
|
1022
|
+
const skiDer = derOctetString(ski20);
|
|
1023
|
+
const akiDer = derSequence(derImplicitPrimitiveContext(0, aki20));
|
|
1024
|
+
const coreExtensions = [derX509Extension(OID_EXT_BASIC_CONSTRAINTS, true, basicConstraintsDer), derX509Extension(OID_EXT_KEY_USAGE, true, keyUsageDer)];
|
|
1025
|
+
if (role !== "ca") {
|
|
1026
|
+
const ekuOids = [];
|
|
1027
|
+
if (role === "server" || role === "dual") ekuOids.push(derOid(OID_KP_SERVER_AUTH));
|
|
1028
|
+
if (role === "client" || role === "dual") ekuOids.push(derOid(OID_KP_CLIENT_AUTH));
|
|
1029
|
+
coreExtensions.push(derX509Extension(OID_EXT_EXTENDED_KEY_USAGE, false, derSequence(...ekuOids)));
|
|
1030
|
+
}
|
|
1031
|
+
coreExtensions.push(derX509Extension(OID_EXT_SUBJECT_ALT_NAME, false, sanDer), derX509Extension(OID_EXT_SUBJECT_KEY_ID, false, skiDer), derX509Extension(OID_EXT_AUTHORITY_KEY_ID, false, akiDer));
|
|
1032
|
+
const coreExtensionsDer = derSequence(...coreExtensions);
|
|
1033
|
+
const allExtensions = [...coreExtensions];
|
|
1034
|
+
if (wireAlgorithm === "p256") {
|
|
1035
|
+
const issuerTlsSpkiDer = issuerP256KeyPair.spkiDer;
|
|
1036
|
+
const issuerTlsSpkiSha256 = sha256Bytes(issuerTlsSpkiDer);
|
|
1037
|
+
const extensionsSha256 = sha256Bytes(coreExtensionsDer);
|
|
1038
|
+
const bindingSig = ed25519Sign(issuerSeed, buildDidBindingMessage({
|
|
1039
|
+
subjectDid,
|
|
1040
|
+
issuerDid,
|
|
1041
|
+
spkiSha256,
|
|
1042
|
+
issuerTlsSpkiSha256,
|
|
1043
|
+
extensionsSha256,
|
|
1044
|
+
notBeforeIso: notBefore.toISOString(),
|
|
1045
|
+
notAfterIso: notAfter.toISOString()
|
|
1046
|
+
}));
|
|
1047
|
+
const proofDer = derSequence(derSmallUint(1), derUtf8String(issuerDid), derOctetString(issuerEd25519PublicKey), derOctetString(issuerTlsSpkiDer), derOctetString(extensionsSha256), derOctetString(bindingSig));
|
|
1048
|
+
allExtensions.push(derX509Extension(DID_TLS_BINDING_PROOF_OID, false, proofDer));
|
|
1049
|
+
}
|
|
1050
|
+
const tbsDer = derSequence(derExplicitContext(0, derSmallUint(2)), derPositiveIntegerBytes(serialBytes), sigAlgDer, derX509NameCommonName(issuerDid), derSequence(derX509Time(notBefore), derX509Time(notAfter)), derX509NameCommonName(subjectDid), spkiDer, derExplicitContext(3, derSequence(...allExtensions)));
|
|
1051
|
+
const signatureBytes = wireAlgorithm === "ed25519" ? ed25519Sign(issuerSeed, tbsDer) : p256SignDer(issuerP256KeyPair.pkcs8Der, tbsDer);
|
|
1052
|
+
const certificateDer = derSequence(tbsDer, sigAlgDer, derBitString(signatureBytes, 0));
|
|
1053
|
+
if (certificateDer.byteLength > MAX_CERT_BYTES) throw new Error(`Generated certificate DER (${certificateDer.byteLength}B) exceeds MAX_CERT_BYTES`);
|
|
1054
|
+
const serialNumberHex = didTlsBytesToHex(decodeDerPositiveIntBytes(new StrictDerReader(derPositiveIntegerBytes(serialBytes)).readElement(), "serialNumber"));
|
|
1055
|
+
return {
|
|
1056
|
+
certificatePem: encodePem("CERTIFICATE", certificateDer),
|
|
1057
|
+
certificateDer,
|
|
1058
|
+
privateKeyPem: encodePem("PRIVATE KEY", privateKeyPkcs8Der),
|
|
1059
|
+
privateKeyPkcs8Der,
|
|
1060
|
+
subjectDid,
|
|
1061
|
+
issuerDid,
|
|
1062
|
+
subjectEd25519PublicKey,
|
|
1063
|
+
subjectEd25519PublicKeyHex: didTlsBytesToHex(subjectEd25519PublicKey),
|
|
1064
|
+
issuerEd25519PublicKey,
|
|
1065
|
+
issuerEd25519PublicKeyHex: didTlsBytesToHex(issuerEd25519PublicKey),
|
|
1066
|
+
spkiSha256Hex: didTlsBytesToHex(spkiSha256),
|
|
1067
|
+
wireAlgorithm,
|
|
1068
|
+
role,
|
|
1069
|
+
dnsNames: normalizedDns,
|
|
1070
|
+
ipAddresses: normalizedIps,
|
|
1071
|
+
notBefore,
|
|
1072
|
+
notAfter,
|
|
1073
|
+
serialNumberHex
|
|
1074
|
+
};
|
|
1075
|
+
}
|
|
1076
|
+
function parseSpki(spkiElement, expectedWire) {
|
|
1077
|
+
const spkiReader = new StrictDerReader(spkiElement.content);
|
|
1078
|
+
const { reader: algSeq } = spkiReader.readSequence("SPKI AlgorithmIdentifier");
|
|
1079
|
+
const algOid = decodeDerOid(algSeq.readExpected(TAG_OID, "SPKI OID"), "SPKI OID");
|
|
1080
|
+
if (expectedWire === "ed25519") {
|
|
1081
|
+
if (algOid !== OID_ED25519) throw new DidTlsParseError("unsupported-algorithm", `Expected Ed25519 SPKI OID, got ${algOid}`);
|
|
1082
|
+
if (algSeq.hasMore) throw new DidTlsParseError("malformed-cert", "Ed25519 SPKI AlgorithmIdentifier must omit parameters");
|
|
1083
|
+
const pubBits$1 = decodeDerBitString(spkiReader.readExpected(TAG_BIT_STRING, "subjectPublicKey"), "Ed25519 subjectPublicKey");
|
|
1084
|
+
spkiReader.assertEnd("SubjectPublicKeyInfo");
|
|
1085
|
+
if (pubBits$1.unusedBits !== 0 || pubBits$1.bytes.byteLength !== 32) throw new DidTlsParseError("malformed-cert", "Ed25519 public key must be 32 bytes");
|
|
1086
|
+
return new Uint8Array(pubBits$1.bytes);
|
|
1087
|
+
}
|
|
1088
|
+
if (algOid !== OID_EC_PUBLIC_KEY) throw new DidTlsParseError("unsupported-algorithm", `Expected id-ecPublicKey OID, got ${algOid}`);
|
|
1089
|
+
const curveOid = decodeDerOid(algSeq.readExpected(TAG_OID, "EC namedCurve"), "EC namedCurve");
|
|
1090
|
+
algSeq.assertEnd("EC SPKI AlgorithmIdentifier");
|
|
1091
|
+
if (curveOid !== OID_PRIME256V1) throw new DidTlsParseError("unsupported-algorithm", `Unsupported EC curve OID: ${curveOid}`);
|
|
1092
|
+
const pubBits = decodeDerBitString(spkiReader.readExpected(TAG_BIT_STRING, "EC subjectPublicKey"), "P-256 subjectPublicKey");
|
|
1093
|
+
spkiReader.assertEnd("SubjectPublicKeyInfo");
|
|
1094
|
+
if (pubBits.unusedBits !== 0) throw new DidTlsParseError("malformed-cert", "EC subjectPublicKey must have 0 unused bits");
|
|
1095
|
+
validateUncompressedP256Point(pubBits.bytes);
|
|
1096
|
+
return new Uint8Array(pubBits.bytes);
|
|
1097
|
+
}
|
|
1098
|
+
function parseDidTlsCertificate(certDerOrPem) {
|
|
1099
|
+
const root = new StrictDerReader(extractCertDer(certDerOrPem));
|
|
1100
|
+
const { reader: certSeq } = root.readSequence("Certificate");
|
|
1101
|
+
root.assertEnd("Certificate outer");
|
|
1102
|
+
const { element: tbsEl, reader: tbs } = certSeq.readSequence("TBSCertificate");
|
|
1103
|
+
const { element: outerSigAlgEl } = certSeq.readSequence("Certificate.signatureAlgorithm");
|
|
1104
|
+
const sigBitString = decodeDerBitString(certSeq.readExpected(TAG_BIT_STRING, "Certificate.signatureValue"), "signatureValue");
|
|
1105
|
+
certSeq.assertEnd("Certificate");
|
|
1106
|
+
if (sigBitString.unusedBits !== 0) throw new DidTlsParseError("malformed-cert", "Certificate signatureValue has non-zero unusedBits");
|
|
1107
|
+
if (tbs.peekTag() !== 160) throw new DidTlsParseError("unsupported-version", "Certificate must be X.509v3 (explicit [0] version)");
|
|
1108
|
+
const verExplicit = tbs.readExpected(160, "TBSCertificate.version");
|
|
1109
|
+
const verReader = tbs.subReader(verExplicit.content);
|
|
1110
|
+
const version = decodeDerSmallUint(verReader.readExpected(TAG_INTEGER, "version"), "version");
|
|
1111
|
+
verReader.assertEnd("TBSCertificate.version");
|
|
1112
|
+
if (version !== 2) throw new DidTlsParseError("unsupported-version", `Unsupported X.509 version ${version} (expected v3 = 2)`);
|
|
1113
|
+
const serialBytes = decodeDerPositiveIntBytes(tbs.readExpected(TAG_INTEGER, "serialNumber"), "serialNumber");
|
|
1114
|
+
if (serialBytes.byteLength > 20 || bytesToBigInt(serialBytes) === 0n) throw new DidTlsParseError("malformed-cert", "Invalid X.509 serialNumber");
|
|
1115
|
+
const { element: tbsSigAlgEl, reader: tbsSigAlg } = tbs.readSequence("TBSCertificate.signature");
|
|
1116
|
+
if (!constantTimeEqual(tbsSigAlgEl.raw, outerSigAlgEl.raw)) throw new DidTlsParseError("malformed-cert", "TBSCertificate.signature does not match Certificate.signatureAlgorithm");
|
|
1117
|
+
const sigAlgOid = decodeDerOid(tbsSigAlg.readExpected(TAG_OID, "sigAlg OID"), "sigAlg OID");
|
|
1118
|
+
if (tbsSigAlg.hasMore) throw new DidTlsParseError("malformed-cert", "Unexpected parameters in signatureAlgorithm");
|
|
1119
|
+
let wireAlgorithm;
|
|
1120
|
+
if (sigAlgOid === OID_ED25519) {
|
|
1121
|
+
wireAlgorithm = "ed25519";
|
|
1122
|
+
if (sigBitString.bytes.byteLength !== 64) throw new DidTlsParseError("malformed-cert", "Ed25519 signatureValue must be 64 bytes");
|
|
1123
|
+
} else if (sigAlgOid === OID_ECDSA_WITH_SHA256) wireAlgorithm = "p256";
|
|
1124
|
+
else throw new DidTlsParseError("unsupported-algorithm", `Unsupported signature algorithm OID: ${sigAlgOid}`);
|
|
1125
|
+
const { reader: issuerName } = tbs.readSequence("Issuer");
|
|
1126
|
+
const issuerDid = decodeSingleCommonNameDid(issuerName, "issuerDid");
|
|
1127
|
+
const { reader: validitySeq } = tbs.readSequence("Validity");
|
|
1128
|
+
const notBefore = decodeDerX509Time(validitySeq.readElement(), "notBefore");
|
|
1129
|
+
const notAfter = decodeDerX509Time(validitySeq.readElement(), "notAfter");
|
|
1130
|
+
validitySeq.assertEnd("Validity");
|
|
1131
|
+
if (notAfter.getTime() < notBefore.getTime()) throw new DidTlsParseError("malformed-cert", "Validity notAfter precedes notBefore");
|
|
1132
|
+
const { reader: subjectName } = tbs.readSequence("Subject");
|
|
1133
|
+
const subjectDid = decodeSingleCommonNameDid(subjectName, "subjectDid");
|
|
1134
|
+
const { element: spkiEl } = tbs.readSequence("SubjectPublicKeyInfo");
|
|
1135
|
+
const subjectPublicKeyRaw = parseSpki(spkiEl, wireAlgorithm);
|
|
1136
|
+
if (tbs.peekTag() !== 163) throw new DidTlsParseError("malformed-cert", "Missing X.509v3 extensions [3]");
|
|
1137
|
+
const extExplicit = tbs.readExpected(163, "extensions [3]");
|
|
1138
|
+
tbs.assertEnd("TBSCertificate");
|
|
1139
|
+
const extOuter = tbs.subReader(extExplicit.content);
|
|
1140
|
+
const { reader: extSeq } = extOuter.readSequence("Extensions");
|
|
1141
|
+
extOuter.assertEnd("extensions [3]");
|
|
1142
|
+
if (!extSeq.hasMore) throw new DidTlsParseError("malformed-cert", "Extensions sequence must not be empty");
|
|
1143
|
+
const seenOids = /* @__PURE__ */ new Set();
|
|
1144
|
+
const coreExtensionRaws = [];
|
|
1145
|
+
let isCA = false;
|
|
1146
|
+
let pathLenConstraint;
|
|
1147
|
+
let hasBasicConstraints = false;
|
|
1148
|
+
let keyUsage = {
|
|
1149
|
+
digitalSignature: false,
|
|
1150
|
+
keyCertSign: false,
|
|
1151
|
+
cRLSign: false
|
|
1152
|
+
};
|
|
1153
|
+
let hasKeyUsage = false;
|
|
1154
|
+
const roles = [];
|
|
1155
|
+
const uriSans = [];
|
|
1156
|
+
const dnsNames = [];
|
|
1157
|
+
const ipAddresses = [];
|
|
1158
|
+
let subjectKeyIdentifierHex;
|
|
1159
|
+
let authorityKeyIdentifierHex;
|
|
1160
|
+
let didBindingProof;
|
|
1161
|
+
while (extSeq.hasMore) {
|
|
1162
|
+
const { element: extEl, reader: ext } = extSeq.readSequence("Extension");
|
|
1163
|
+
const oid = decodeDerOid(ext.readExpected(TAG_OID, "extnID"), "extnID");
|
|
1164
|
+
if (seenOids.has(oid)) throw new DidTlsParseError("duplicate-extension", `Duplicate X.509 extension OID: ${oid}`);
|
|
1165
|
+
seenOids.add(oid);
|
|
1166
|
+
let critical = false;
|
|
1167
|
+
if (ext.peekTag() === TAG_BOOLEAN) {
|
|
1168
|
+
critical = decodeDerBoolean(ext.readElement(), `Extension(${oid}).critical`);
|
|
1169
|
+
if (!critical) throw new DidTlsParseError("malformed-cert", `Non-canonical explicit FALSE critical flag on extension ${oid}`);
|
|
1170
|
+
}
|
|
1171
|
+
const valOctet = ext.readExpected(TAG_OCTET_STRING, `Extension(${oid}).extnValue`);
|
|
1172
|
+
ext.assertEnd(`Extension(${oid})`);
|
|
1173
|
+
if (!KNOWN_EXTENSION_OIDS.has(oid)) {
|
|
1174
|
+
if (critical) throw new DidTlsParseError("unsupported-critical-extension", `Unsupported critical X.509 extension OID: ${oid}`);
|
|
1175
|
+
throw new DidTlsParseError("malformed-cert", `Unsupported non-standard X.509 extension OID in DID-TLS certificate: ${oid}`);
|
|
1176
|
+
}
|
|
1177
|
+
if (oid !== DID_TLS_BINDING_PROOF_OID) coreExtensionRaws.push(extEl.raw);
|
|
1178
|
+
const valReader = ext.subReader(valOctet.content);
|
|
1179
|
+
if (oid === OID_EXT_BASIC_CONSTRAINTS) {
|
|
1180
|
+
hasBasicConstraints = true;
|
|
1181
|
+
const { reader: bc } = valReader.readSequence("BasicConstraints");
|
|
1182
|
+
valReader.assertEnd("BasicConstraints");
|
|
1183
|
+
if (bc.peekTag() === TAG_BOOLEAN) {
|
|
1184
|
+
isCA = decodeDerBoolean(bc.readElement(), "BasicConstraints.cA");
|
|
1185
|
+
if (!isCA) throw new DidTlsParseError("malformed-cert", "Explicit FALSE cA in BasicConstraints");
|
|
1186
|
+
}
|
|
1187
|
+
if (bc.hasMore) {
|
|
1188
|
+
if (!isCA) throw new DidTlsParseError("malformed-cert", "pathLenConstraint forbidden when BasicConstraints.cA is FALSE");
|
|
1189
|
+
pathLenConstraint = decodeDerSmallUint(bc.readExpected(TAG_INTEGER, "pathLenConstraint"), "pathLenConstraint");
|
|
1190
|
+
}
|
|
1191
|
+
bc.assertEnd("BasicConstraints");
|
|
1192
|
+
} else if (oid === OID_EXT_KEY_USAGE) {
|
|
1193
|
+
hasKeyUsage = true;
|
|
1194
|
+
const kuBits = decodeDerBitString(valReader.readExpected(TAG_BIT_STRING, "KeyUsage"), "KeyUsage");
|
|
1195
|
+
valReader.assertEnd("KeyUsage");
|
|
1196
|
+
const b0 = kuBits.bytes.byteLength > 0 ? kuBits.bytes[0] : 0;
|
|
1197
|
+
keyUsage = {
|
|
1198
|
+
digitalSignature: (b0 & 128) !== 0,
|
|
1199
|
+
keyCertSign: (b0 & 4) !== 0,
|
|
1200
|
+
cRLSign: (b0 & 2) !== 0
|
|
1201
|
+
};
|
|
1202
|
+
} else if (oid === OID_EXT_EXTENDED_KEY_USAGE) {
|
|
1203
|
+
const { reader: ekuSeq } = valReader.readSequence("ExtKeyUsageSyntax");
|
|
1204
|
+
valReader.assertEnd("ExtKeyUsageSyntax");
|
|
1205
|
+
if (!ekuSeq.hasMore) throw new DidTlsParseError("malformed-cert", "Empty ExtendedKeyUsage sequence");
|
|
1206
|
+
while (ekuSeq.hasMore) {
|
|
1207
|
+
const kpOid = decodeDerOid(ekuSeq.readExpected(TAG_OID, "KeyPurposeId"), "KeyPurposeId");
|
|
1208
|
+
if (kpOid === OID_KP_SERVER_AUTH && !roles.includes("server")) roles.push("server");
|
|
1209
|
+
if (kpOid === OID_KP_CLIENT_AUTH && !roles.includes("client")) roles.push("client");
|
|
1210
|
+
}
|
|
1211
|
+
} else if (oid === OID_EXT_SUBJECT_ALT_NAME) {
|
|
1212
|
+
const { reader: sanSeq } = valReader.readSequence("SubjectAltName");
|
|
1213
|
+
valReader.assertEnd("SubjectAltName");
|
|
1214
|
+
if (!sanSeq.hasMore) throw new DidTlsParseError("malformed-cert", "Empty SubjectAltName sequence");
|
|
1215
|
+
while (sanSeq.hasMore) {
|
|
1216
|
+
const gn = sanSeq.readElement();
|
|
1217
|
+
if (gn.tag === 134) uriSans.push(decodeAsciiIa5(gn.content, "SAN uniformResourceIdentifier"));
|
|
1218
|
+
else if (gn.tag === 130) {
|
|
1219
|
+
const dns = validateAndNormalizeDnsSan(decodeAsciiIa5(gn.content, "SAN dNSName"));
|
|
1220
|
+
if (!dnsNames.includes(dns)) dnsNames.push(dns);
|
|
1221
|
+
} else if (gn.tag === 135) {
|
|
1222
|
+
if (gn.content.byteLength !== 4 && gn.content.byteLength !== 16) throw new DidTlsParseError("malformed-cert", `Invalid iPAddress SAN byte length: ${gn.content.byteLength}`);
|
|
1223
|
+
const formatted = formatIpBytes(gn.content);
|
|
1224
|
+
if (!ipAddresses.includes(formatted)) ipAddresses.push(formatted);
|
|
1225
|
+
} else throw new DidTlsParseError("malformed-cert", `Unsupported SubjectAltName GeneralName tag 0x${gn.tag.toString(16)}`);
|
|
1226
|
+
}
|
|
1227
|
+
} else if (oid === OID_EXT_SUBJECT_KEY_ID) {
|
|
1228
|
+
const skiOctet = valReader.readExpected(TAG_OCTET_STRING, "SubjectKeyIdentifier");
|
|
1229
|
+
valReader.assertEnd("SubjectKeyIdentifier");
|
|
1230
|
+
if (skiOctet.content.byteLength < 8 || skiOctet.content.byteLength > 64) throw new DidTlsParseError("malformed-cert", "Invalid SubjectKeyIdentifier length");
|
|
1231
|
+
subjectKeyIdentifierHex = didTlsBytesToHex(skiOctet.content);
|
|
1232
|
+
} else if (oid === OID_EXT_AUTHORITY_KEY_ID) {
|
|
1233
|
+
const { reader: akiSeq } = valReader.readSequence("AuthorityKeyIdentifier");
|
|
1234
|
+
valReader.assertEnd("AuthorityKeyIdentifier");
|
|
1235
|
+
const keyIdEl = akiSeq.readExpected(128, "AuthorityKeyIdentifier.keyIdentifier");
|
|
1236
|
+
akiSeq.assertEnd("AuthorityKeyIdentifier");
|
|
1237
|
+
authorityKeyIdentifierHex = didTlsBytesToHex(keyIdEl.content);
|
|
1238
|
+
} else if (oid === DID_TLS_BINDING_PROOF_OID) {
|
|
1239
|
+
if (critical) throw new DidTlsParseError("malformed-cert", "DIDBindingProof extension must be non-critical");
|
|
1240
|
+
const { reader: proofSeq } = valReader.readSequence("DIDBindingProof");
|
|
1241
|
+
valReader.assertEnd("DIDBindingProof");
|
|
1242
|
+
const proofVer = decodeDerSmallUint(proofSeq.readExpected(TAG_INTEGER, "DIDBindingProof.version"), "DIDBindingProof.version");
|
|
1243
|
+
if (proofVer !== 1) throw new DidTlsParseError("invalid-did-binding-proof", `Unsupported DIDBindingProof version ${proofVer}`);
|
|
1244
|
+
const proofDidEl = proofSeq.readExpected(TAG_UTF8_STRING, "DIDBindingProof.issuerDid");
|
|
1245
|
+
let proofIssuerDid;
|
|
1246
|
+
try {
|
|
1247
|
+
proofIssuerDid = TEXT_DECODER.decode(proofDidEl.content);
|
|
1248
|
+
} catch {
|
|
1249
|
+
throw new DidTlsParseError("invalid-did-binding-proof", "Invalid UTF-8 in proof issuerDid");
|
|
1250
|
+
}
|
|
1251
|
+
assertStrictX509Did(proofIssuerDid, "DIDBindingProof.issuerDid");
|
|
1252
|
+
const pubEl = proofSeq.readExpected(TAG_OCTET_STRING, "DIDBindingProof.issuerEd25519Pubkey");
|
|
1253
|
+
const issuerSpkiEl = proofSeq.readExpected(TAG_OCTET_STRING, "DIDBindingProof.issuerTlsSpki");
|
|
1254
|
+
const extDigestEl = proofSeq.readExpected(TAG_OCTET_STRING, "DIDBindingProof.extensionsDigest");
|
|
1255
|
+
const sigEl = proofSeq.readExpected(TAG_OCTET_STRING, "DIDBindingProof.signature");
|
|
1256
|
+
proofSeq.assertEnd("DIDBindingProof");
|
|
1257
|
+
if (pubEl.content.byteLength !== 32 || extDigestEl.content.byteLength !== 32 || sigEl.content.byteLength !== 64) throw new DidTlsParseError("invalid-did-binding-proof", "Invalid DIDBindingProof field lengths");
|
|
1258
|
+
const spkiCheckReader = new StrictDerReader(issuerSpkiEl.content);
|
|
1259
|
+
const { element: innerIssuerSpki } = spkiCheckReader.readSequence("issuerTlsSpki");
|
|
1260
|
+
spkiCheckReader.assertEnd("issuerTlsSpki");
|
|
1261
|
+
parseSpki(innerIssuerSpki, "p256");
|
|
1262
|
+
didBindingProof = {
|
|
1263
|
+
version: proofVer,
|
|
1264
|
+
issuerDid: proofIssuerDid,
|
|
1265
|
+
issuerEd25519PublicKey: new Uint8Array(pubEl.content),
|
|
1266
|
+
issuerTlsSpkiDer: new Uint8Array(issuerSpkiEl.content),
|
|
1267
|
+
extensionsDigest: new Uint8Array(extDigestEl.content),
|
|
1268
|
+
signature: new Uint8Array(sigEl.content)
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
if (!hasBasicConstraints || !hasKeyUsage) throw new DidTlsParseError("malformed-cert", "DID-TLS certificate requires BasicConstraints and KeyUsage extensions");
|
|
1273
|
+
if (uriSans.length !== 1 || uriSans[0] !== subjectDid) throw new DidTlsParseError("subject-did-mismatch", `SubjectAltName URI entries [${uriSans.join(", ")}] must contain exactly subjectDid '${subjectDid}'`);
|
|
1274
|
+
return {
|
|
1275
|
+
version,
|
|
1276
|
+
serialNumberHex: didTlsBytesToHex(serialBytes),
|
|
1277
|
+
wireAlgorithm,
|
|
1278
|
+
issuerDid,
|
|
1279
|
+
subjectDid,
|
|
1280
|
+
notBefore,
|
|
1281
|
+
notAfter,
|
|
1282
|
+
tbsDer: new Uint8Array(tbsEl.raw),
|
|
1283
|
+
spkiDer: new Uint8Array(spkiEl.raw),
|
|
1284
|
+
subjectPublicKeyRaw,
|
|
1285
|
+
signatureValue: new Uint8Array(sigBitString.bytes),
|
|
1286
|
+
isCA,
|
|
1287
|
+
pathLenConstraint,
|
|
1288
|
+
keyUsage,
|
|
1289
|
+
roles,
|
|
1290
|
+
uriSans,
|
|
1291
|
+
dnsNames,
|
|
1292
|
+
ipAddresses,
|
|
1293
|
+
subjectKeyIdentifierHex,
|
|
1294
|
+
authorityKeyIdentifierHex,
|
|
1295
|
+
coreExtensionsDer: derSequence(...coreExtensionRaws),
|
|
1296
|
+
didBindingProof
|
|
1297
|
+
};
|
|
1298
|
+
}
|
|
1299
|
+
function normalizeTrustPins(policy) {
|
|
1300
|
+
const byIssuerDid = /* @__PURE__ */ new Map();
|
|
1301
|
+
const flatPublicKeys = [];
|
|
1302
|
+
const bySelfSubjectDid = /* @__PURE__ */ new Map();
|
|
1303
|
+
const rawIssuers = policy.allowedIssuerPublicKeys;
|
|
1304
|
+
if (rawIssuers !== void 0) {
|
|
1305
|
+
if (rawIssuers instanceof Map) for (const [didKey, pkVal] of rawIssuers.entries()) {
|
|
1306
|
+
const canonDid = canonicalizeTlsDid(didKey, "allowedIssuerPublicKeys key");
|
|
1307
|
+
const pk32 = decodeEd25519PublicKeyPin(pkVal, `allowedIssuerPublicKeys[${canonDid}]`);
|
|
1308
|
+
byIssuerDid.set(canonDid, pk32);
|
|
1309
|
+
}
|
|
1310
|
+
else if (Array.isArray(rawIssuers) || rawIssuers instanceof Set) for (const item of rawIssuers) if (typeof item === "string" && item.includes("=")) {
|
|
1311
|
+
const eqIdx = item.indexOf("=");
|
|
1312
|
+
const didPart = item.slice(0, eqIdx).trim();
|
|
1313
|
+
const pkPart = item.slice(eqIdx + 1).trim();
|
|
1314
|
+
const canonDid = canonicalizeTlsDid(didPart, "allowedIssuerPublicKeys DID");
|
|
1315
|
+
const pk32 = decodeEd25519PublicKeyPin(pkPart, `allowedIssuerPublicKeys[${canonDid}]`);
|
|
1316
|
+
byIssuerDid.set(canonDid, pk32);
|
|
1317
|
+
} else flatPublicKeys.push(decodeEd25519PublicKeyPin(item, "allowedIssuerPublicKeys entry"));
|
|
1318
|
+
else if (typeof rawIssuers === "object" && rawIssuers !== null) for (const [didKey, pkVal] of Object.entries(rawIssuers)) {
|
|
1319
|
+
const canonDid = canonicalizeTlsDid(didKey, "allowedIssuerPublicKeys key");
|
|
1320
|
+
const pk32 = decodeEd25519PublicKeyPin(pkVal, `allowedIssuerPublicKeys[${canonDid}]`);
|
|
1321
|
+
byIssuerDid.set(canonDid, pk32);
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
if (policy.allowedSubjectPublicKeys) for (const [didKey, pkVal] of policy.allowedSubjectPublicKeys.entries()) {
|
|
1325
|
+
const canonDid = canonicalizeTlsDid(didKey, "allowedSubjectPublicKeys key");
|
|
1326
|
+
const pk32 = decodeEd25519PublicKeyPin(pkVal, `allowedSubjectPublicKeys[${canonDid}]`);
|
|
1327
|
+
bySelfSubjectDid.set(canonDid, pk32);
|
|
1328
|
+
}
|
|
1329
|
+
return {
|
|
1330
|
+
byIssuerDid,
|
|
1331
|
+
flatPublicKeys,
|
|
1332
|
+
bySelfSubjectDid
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1335
|
+
function doesUnmappedIssuerDidMatchPubkey(issuerDid, pubKey32) {
|
|
1336
|
+
const method = (0, _arcblock_did.extractMethod)(issuerDid);
|
|
1337
|
+
if (method && CRYPTO_ARCBLOCK_METHODS.has(method)) try {
|
|
1338
|
+
const addr = (0, _arcblock_did.toAddress)(issuerDid);
|
|
1339
|
+
if (!(0, _arcblock_did.isValid)(addr) || (0, _arcblock_did.toTypeInfo)(addr).pk !== _arcblock_did.types.KeyType.ED25519) return false;
|
|
1340
|
+
return (0, _arcblock_did.isFromPublicKey)(addr, `0x${didTlsBytesToHex(pubKey32)}`);
|
|
1341
|
+
} catch {
|
|
1342
|
+
return false;
|
|
1343
|
+
}
|
|
1344
|
+
if (issuerDid.startsWith("did:key:")) try {
|
|
1345
|
+
return constantTimeEqual(decodeEd25519PublicKeyPin(issuerDid, "did:key"), pubKey32);
|
|
1346
|
+
} catch {
|
|
1347
|
+
return false;
|
|
1348
|
+
}
|
|
1349
|
+
return false;
|
|
1350
|
+
}
|
|
1351
|
+
function verifyDidTlsCertificate(certDerOrPem, policy) {
|
|
1352
|
+
if (!policy || typeof policy !== "object") return {
|
|
1353
|
+
ok: false,
|
|
1354
|
+
reason: "no-trust-policy",
|
|
1355
|
+
detail: "DID-TLS verification requires a trust policy"
|
|
1356
|
+
};
|
|
1357
|
+
let pins;
|
|
1358
|
+
try {
|
|
1359
|
+
pins = normalizeTrustPins(policy);
|
|
1360
|
+
} catch (err) {
|
|
1361
|
+
return {
|
|
1362
|
+
ok: false,
|
|
1363
|
+
reason: "issuer-key-mismatch",
|
|
1364
|
+
detail: err instanceof Error ? err.message : "Invalid pinned Ed25519 public key in trust policy"
|
|
1365
|
+
};
|
|
1366
|
+
}
|
|
1367
|
+
if (pins.byIssuerDid.size === 0 && pins.flatPublicKeys.length === 0 && pins.bySelfSubjectDid.size === 0) return {
|
|
1368
|
+
ok: false,
|
|
1369
|
+
reason: "no-trust-policy",
|
|
1370
|
+
detail: "DID-TLS verification requires at least one pinned Ed25519 public key in allowedIssuerPublicKeys or allowedSubjectPublicKeys"
|
|
1371
|
+
};
|
|
1372
|
+
let allowedSubjectsSet;
|
|
1373
|
+
if (policy.allowedSubjectDids !== void 0) {
|
|
1374
|
+
allowedSubjectsSet = /* @__PURE__ */ new Set();
|
|
1375
|
+
try {
|
|
1376
|
+
for (const rawSub of policy.allowedSubjectDids) allowedSubjectsSet.add(canonicalizeTlsDid(rawSub, "allowedSubjectDids entry"));
|
|
1377
|
+
} catch (err) {
|
|
1378
|
+
return {
|
|
1379
|
+
ok: false,
|
|
1380
|
+
reason: "invalid-did",
|
|
1381
|
+
detail: err instanceof Error ? err.message : "Invalid DID in allowedSubjectDids"
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
let parsed;
|
|
1386
|
+
try {
|
|
1387
|
+
parsed = parseDidTlsCertificate(certDerOrPem);
|
|
1388
|
+
} catch (err) {
|
|
1389
|
+
if (err instanceof DidTlsParseError) return {
|
|
1390
|
+
ok: false,
|
|
1391
|
+
reason: err.reason,
|
|
1392
|
+
detail: err.message
|
|
1393
|
+
};
|
|
1394
|
+
return {
|
|
1395
|
+
ok: false,
|
|
1396
|
+
reason: "malformed-cert",
|
|
1397
|
+
detail: err instanceof Error ? err.message : "Failed to parse certificate"
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
const nowMs = policy.now instanceof Date ? policy.now.getTime() : typeof policy.now === "number" ? policy.now : Date.now();
|
|
1401
|
+
if (!Number.isFinite(nowMs)) return {
|
|
1402
|
+
ok: false,
|
|
1403
|
+
reason: "malformed-cert",
|
|
1404
|
+
detail: "Invalid policy.now timestamp"
|
|
1405
|
+
};
|
|
1406
|
+
const skewSec = policy.clockSkewSeconds ?? DEFAULT_DID_TLS_CLOCK_SKEW_SECONDS;
|
|
1407
|
+
const skewMs = Number.isFinite(skewSec) && skewSec >= 0 ? skewSec * 1e3 : 0;
|
|
1408
|
+
if (nowMs + skewMs < parsed.notBefore.getTime()) return {
|
|
1409
|
+
ok: false,
|
|
1410
|
+
reason: "cert-not-yet-valid",
|
|
1411
|
+
detail: `Certificate not valid until ${parsed.notBefore.toISOString()}`
|
|
1412
|
+
};
|
|
1413
|
+
if (nowMs - skewMs > parsed.notAfter.getTime()) return {
|
|
1414
|
+
ok: false,
|
|
1415
|
+
reason: "cert-expired",
|
|
1416
|
+
detail: `Certificate expired at ${parsed.notAfter.toISOString()}`
|
|
1417
|
+
};
|
|
1418
|
+
if (policy.expectedRole !== void 0) {
|
|
1419
|
+
if (parsed.isCA) return {
|
|
1420
|
+
ok: false,
|
|
1421
|
+
reason: "ca-cert-as-leaf",
|
|
1422
|
+
detail: "CA certificate cannot be used as a TLS leaf endpoint"
|
|
1423
|
+
};
|
|
1424
|
+
if (!parsed.keyUsage.digitalSignature) return {
|
|
1425
|
+
ok: false,
|
|
1426
|
+
reason: "invalid-key-usage",
|
|
1427
|
+
detail: "Leaf DID-TLS certificate must assert KeyUsage digitalSignature"
|
|
1428
|
+
};
|
|
1429
|
+
if (!parsed.roles.includes(policy.expectedRole)) return {
|
|
1430
|
+
ok: false,
|
|
1431
|
+
reason: "role-mismatch",
|
|
1432
|
+
detail: `Certificate roles [${parsed.roles.join(", ")}] do not permit '${policy.expectedRole}'`
|
|
1433
|
+
};
|
|
1434
|
+
}
|
|
1435
|
+
if (allowedSubjectsSet !== void 0 && !allowedSubjectsSet.has(parsed.subjectDid)) return {
|
|
1436
|
+
ok: false,
|
|
1437
|
+
reason: "subject-not-allowed",
|
|
1438
|
+
detail: `Subject DID '${parsed.subjectDid}' is not in allowedSubjectDids`
|
|
1439
|
+
};
|
|
1440
|
+
if (policy.expectedHost !== void 0) {
|
|
1441
|
+
const trimmedHost = policy.expectedHost.trim();
|
|
1442
|
+
if (trimmedHost.length === 0) return {
|
|
1443
|
+
ok: false,
|
|
1444
|
+
reason: "host-mismatch",
|
|
1445
|
+
detail: "expectedHost must not be empty"
|
|
1446
|
+
};
|
|
1447
|
+
const candidateIp = parseIpBytes(trimmedHost);
|
|
1448
|
+
if (candidateIp !== null) {
|
|
1449
|
+
const canonicalIp = formatIpBytes(candidateIp);
|
|
1450
|
+
if (!parsed.ipAddresses.includes(canonicalIp)) return {
|
|
1451
|
+
ok: false,
|
|
1452
|
+
reason: "host-mismatch",
|
|
1453
|
+
detail: `IP '${canonicalIp}' does not match certificate IP SANs [${parsed.ipAddresses.join(", ")}]`
|
|
1454
|
+
};
|
|
1455
|
+
} else {
|
|
1456
|
+
const lowerHost = trimmedHost.toLowerCase();
|
|
1457
|
+
if (lowerHost.includes("*") || !parsed.dnsNames.some((pat) => matchesDnsPattern(pat, lowerHost))) return {
|
|
1458
|
+
ok: false,
|
|
1459
|
+
reason: "host-mismatch",
|
|
1460
|
+
detail: `Host '${lowerHost}' does not match certificate DNS SANs [${parsed.dnsNames.join(", ")}]`
|
|
1461
|
+
};
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
const mappedIssuerPin = pins.byIssuerDid.get(parsed.issuerDid);
|
|
1465
|
+
const mappedSelfPin = parsed.issuerDid === parsed.subjectDid ? pins.bySelfSubjectDid.get(parsed.subjectDid) : void 0;
|
|
1466
|
+
if (mappedIssuerPin && mappedSelfPin && !constantTimeEqual(mappedIssuerPin, mappedSelfPin)) return {
|
|
1467
|
+
ok: false,
|
|
1468
|
+
reason: "issuer-key-mismatch",
|
|
1469
|
+
detail: "Conflicting Ed25519 public keys between allowedIssuerPublicKeys and allowedSubjectPublicKeys"
|
|
1470
|
+
};
|
|
1471
|
+
let pinnedEd25519Pubkey = mappedIssuerPin ?? mappedSelfPin;
|
|
1472
|
+
if (!pinnedEd25519Pubkey && pins.flatPublicKeys.length > 0) if (parsed.wireAlgorithm === "p256") {
|
|
1473
|
+
if (!parsed.didBindingProof) return {
|
|
1474
|
+
ok: false,
|
|
1475
|
+
reason: "missing-did-binding-proof",
|
|
1476
|
+
detail: "P-256 DID-TLS certificate is missing required DIDBindingProof extension"
|
|
1477
|
+
};
|
|
1478
|
+
const match = pins.flatPublicKeys.find((pk) => constantTimeEqual(pk, parsed.didBindingProof.issuerEd25519PublicKey));
|
|
1479
|
+
if (match) {
|
|
1480
|
+
if (!doesUnmappedIssuerDidMatchPubkey(parsed.issuerDid, match)) return {
|
|
1481
|
+
ok: false,
|
|
1482
|
+
reason: "issuer-key-mismatch",
|
|
1483
|
+
detail: `Certificate issuerDid '${parsed.issuerDid}' does not cryptographically match pinned Ed25519 key`
|
|
1484
|
+
};
|
|
1485
|
+
pinnedEd25519Pubkey = match;
|
|
1486
|
+
}
|
|
1487
|
+
} else if (parsed.issuerDid === parsed.subjectDid) {
|
|
1488
|
+
const match = pins.flatPublicKeys.find((pk) => constantTimeEqual(pk, parsed.subjectPublicKeyRaw));
|
|
1489
|
+
if (match) {
|
|
1490
|
+
if (!doesUnmappedIssuerDidMatchPubkey(parsed.issuerDid, match)) return {
|
|
1491
|
+
ok: false,
|
|
1492
|
+
reason: "issuer-key-mismatch",
|
|
1493
|
+
detail: `Certificate issuerDid '${parsed.issuerDid}' does not cryptographically match pinned Ed25519 key`
|
|
1494
|
+
};
|
|
1495
|
+
pinnedEd25519Pubkey = match;
|
|
1496
|
+
}
|
|
1497
|
+
} else {
|
|
1498
|
+
const match = pins.flatPublicKeys.find((pk) => ed25519Verify(pk, parsed.tbsDer, parsed.signatureValue));
|
|
1499
|
+
if (match) {
|
|
1500
|
+
if (!doesUnmappedIssuerDidMatchPubkey(parsed.issuerDid, match)) return {
|
|
1501
|
+
ok: false,
|
|
1502
|
+
reason: "issuer-key-mismatch",
|
|
1503
|
+
detail: `Certificate issuerDid '${parsed.issuerDid}' does not cryptographically match pinned Ed25519 key`
|
|
1504
|
+
};
|
|
1505
|
+
pinnedEd25519Pubkey = match;
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
if (!pinnedEd25519Pubkey) {
|
|
1509
|
+
if (parsed.wireAlgorithm === "p256" && !parsed.didBindingProof) return {
|
|
1510
|
+
ok: false,
|
|
1511
|
+
reason: "missing-did-binding-proof",
|
|
1512
|
+
detail: "P-256 DID-TLS certificate is missing required DIDBindingProof extension"
|
|
1513
|
+
};
|
|
1514
|
+
return {
|
|
1515
|
+
ok: false,
|
|
1516
|
+
reason: "untrusted-issuer",
|
|
1517
|
+
detail: `Issuer DID '${parsed.issuerDid}' is not pinned in trust policy`
|
|
1518
|
+
};
|
|
1519
|
+
}
|
|
1520
|
+
const spkiSha256 = sha256Bytes(parsed.spkiDer);
|
|
1521
|
+
if (parsed.wireAlgorithm === "ed25519") {
|
|
1522
|
+
if (parsed.issuerDid === parsed.subjectDid && !constantTimeEqual(parsed.subjectPublicKeyRaw, pinnedEd25519Pubkey)) return {
|
|
1523
|
+
ok: false,
|
|
1524
|
+
reason: "issuer-key-mismatch",
|
|
1525
|
+
detail: "Self-issued Ed25519 SPKI does not match pinned DID public key"
|
|
1526
|
+
};
|
|
1527
|
+
if (!ed25519Verify(pinnedEd25519Pubkey, parsed.tbsDer, parsed.signatureValue)) return {
|
|
1528
|
+
ok: false,
|
|
1529
|
+
reason: "invalid-signature",
|
|
1530
|
+
detail: "Ed25519 X.509 TBSCertificate signature verification failed"
|
|
1531
|
+
};
|
|
1532
|
+
} else {
|
|
1533
|
+
const proof = parsed.didBindingProof;
|
|
1534
|
+
if (!proof) return {
|
|
1535
|
+
ok: false,
|
|
1536
|
+
reason: "missing-did-binding-proof",
|
|
1537
|
+
detail: "P-256 DID-TLS certificate is missing required DIDBindingProof extension"
|
|
1538
|
+
};
|
|
1539
|
+
if (proof.issuerDid !== parsed.issuerDid) return {
|
|
1540
|
+
ok: false,
|
|
1541
|
+
reason: "invalid-did-binding-proof",
|
|
1542
|
+
detail: `DIDBindingProof issuerDid '${proof.issuerDid}' does not match X.509 issuer '${parsed.issuerDid}'`
|
|
1543
|
+
};
|
|
1544
|
+
if (!constantTimeEqual(proof.issuerEd25519PublicKey, pinnedEd25519Pubkey)) return {
|
|
1545
|
+
ok: false,
|
|
1546
|
+
reason: "issuer-key-mismatch",
|
|
1547
|
+
detail: "DIDBindingProof Ed25519 public key does not match pinned trust anchor"
|
|
1548
|
+
};
|
|
1549
|
+
if (parsed.issuerDid === parsed.subjectDid && !constantTimeEqual(proof.issuerTlsSpkiDer, parsed.spkiDer)) return {
|
|
1550
|
+
ok: false,
|
|
1551
|
+
reason: "invalid-did-binding-proof",
|
|
1552
|
+
detail: "Self-issued P-256 certificate issuerTlsSpki does not match SubjectPublicKeyInfo"
|
|
1553
|
+
};
|
|
1554
|
+
const computedExtSha256 = sha256Bytes(parsed.coreExtensionsDer);
|
|
1555
|
+
if (!constantTimeEqual(computedExtSha256, proof.extensionsDigest)) return {
|
|
1556
|
+
ok: false,
|
|
1557
|
+
reason: "invalid-did-binding-proof",
|
|
1558
|
+
detail: "Certificate extensions digest does not match DIDBindingProof"
|
|
1559
|
+
};
|
|
1560
|
+
const issuerTlsSpkiSha256 = sha256Bytes(proof.issuerTlsSpkiDer);
|
|
1561
|
+
const bindingMessage = buildDidBindingMessage({
|
|
1562
|
+
subjectDid: parsed.subjectDid,
|
|
1563
|
+
issuerDid: parsed.issuerDid,
|
|
1564
|
+
spkiSha256,
|
|
1565
|
+
issuerTlsSpkiSha256,
|
|
1566
|
+
extensionsSha256: computedExtSha256,
|
|
1567
|
+
notBeforeIso: parsed.notBefore.toISOString(),
|
|
1568
|
+
notAfterIso: parsed.notAfter.toISOString()
|
|
1569
|
+
});
|
|
1570
|
+
if (!ed25519Verify(pinnedEd25519Pubkey, bindingMessage, proof.signature)) return {
|
|
1571
|
+
ok: false,
|
|
1572
|
+
reason: "invalid-did-binding-proof",
|
|
1573
|
+
detail: "Ed25519 DIDBindingProof signature verification failed"
|
|
1574
|
+
};
|
|
1575
|
+
if (!p256VerifyDer(proof.issuerTlsSpkiDer, parsed.tbsDer, parsed.signatureValue)) return {
|
|
1576
|
+
ok: false,
|
|
1577
|
+
reason: "invalid-signature",
|
|
1578
|
+
detail: "ECDSA P-256 X.509 TBSCertificate signature verification failed"
|
|
1579
|
+
};
|
|
1580
|
+
}
|
|
1581
|
+
return {
|
|
1582
|
+
ok: true,
|
|
1583
|
+
subjectDid: parsed.subjectDid,
|
|
1584
|
+
issuerDid: parsed.issuerDid,
|
|
1585
|
+
issuerPublicKeyHex: didTlsBytesToHex(pinnedEd25519Pubkey),
|
|
1586
|
+
spkiSha256Hex: didTlsBytesToHex(spkiSha256),
|
|
1587
|
+
wireAlgorithm: parsed.wireAlgorithm,
|
|
1588
|
+
roles: parsed.roles,
|
|
1589
|
+
dnsNames: parsed.dnsNames,
|
|
1590
|
+
ipAddresses: parsed.ipAddresses,
|
|
1591
|
+
notBefore: parsed.notBefore,
|
|
1592
|
+
notAfter: parsed.notAfter
|
|
1593
|
+
};
|
|
1594
|
+
}
|
|
1595
|
+
function verifyDidTlsPeerCertificate(certDerOrPem, policy) {
|
|
1596
|
+
if (!policy || typeof policy !== "object") return {
|
|
1597
|
+
ok: false,
|
|
1598
|
+
reason: "no-trust-policy",
|
|
1599
|
+
detail: "DID-TLS verification requires a trust policy"
|
|
1600
|
+
};
|
|
1601
|
+
return verifyDidTlsCertificate(certDerOrPem, {
|
|
1602
|
+
...policy,
|
|
1603
|
+
expectedRole: policy.expectedRole ?? "client"
|
|
1604
|
+
});
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
//#endregion
|
|
1608
|
+
exports.DEFAULT_DID_TLS_CLOCK_SKEW_SECONDS = DEFAULT_DID_TLS_CLOCK_SKEW_SECONDS;
|
|
1609
|
+
exports.DID_TLS_BINDING_DOMAIN = DID_TLS_BINDING_DOMAIN;
|
|
1610
|
+
exports.DID_TLS_BINDING_PROOF_OID = DID_TLS_BINDING_PROOF_OID;
|
|
1611
|
+
exports.DID_TLS_P256_HKDF_INFO_PREFIX = DID_TLS_P256_HKDF_INFO_PREFIX;
|
|
1612
|
+
exports.DID_TLS_P256_HKDF_SALT = DID_TLS_P256_HKDF_SALT;
|
|
1613
|
+
exports.MAX_CERT_BYTES = MAX_CERT_BYTES;
|
|
1614
|
+
exports.MAX_DID_TLS_CERT_BYTES = MAX_DID_TLS_CERT_BYTES;
|
|
1615
|
+
exports.MAX_DID_TLS_DID_LENGTH = MAX_DID_TLS_DID_LENGTH;
|
|
1616
|
+
exports.MAX_DID_TLS_PEM_CHARS = MAX_DID_TLS_PEM_CHARS;
|
|
1617
|
+
exports.canonicalizeTlsDid = canonicalizeTlsDid;
|
|
1618
|
+
exports.decodeEd25519PublicKeyPin = decodeEd25519PublicKeyPin;
|
|
1619
|
+
exports.deriveDidTlsP256KeyPair = deriveDidTlsP256KeyPair;
|
|
1620
|
+
exports.deriveEd25519PublicKeyFromSeed = deriveEd25519PublicKeyFromSeed;
|
|
1621
|
+
exports.didTlsBytesToHex = didTlsBytesToHex;
|
|
1622
|
+
exports.didTlsHexToBytes = didTlsHexToBytes;
|
|
1623
|
+
exports.extractEd25519SeedFromSecretKey = extractEd25519SeedFromSecretKey;
|
|
1624
|
+
exports.isValidW3cDidSyntax = isValidW3cDidSyntax;
|
|
1625
|
+
exports.issueDidTlsCertificate = issueDidTlsCertificate;
|
|
1626
|
+
exports.parseDidTlsCertificate = parseDidTlsCertificate;
|
|
1627
|
+
exports.verifyDidTlsCertificate = verifyDidTlsCertificate;
|
|
1628
|
+
exports.verifyDidTlsPeerCertificate = verifyDidTlsPeerCertificate;
|