@blamejs/core 0.12.39 → 0.12.41

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/CHANGELOG.md CHANGED
@@ -8,6 +8,10 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.12.x
10
10
 
11
+ - v0.12.41 (2026-05-24) — **`b.did` — W3C DID resolution (did:key + did:web) feeding the credential verifiers.** Resolve W3C Decentralized Identifiers (DID Core 1.0) to verification keys — the link that lets a credential's issuer be named by a DID rather than a raw key. Resolve the issuer DID of a b.vc / b.mdoc / b.scitt credential to a node:crypto KeyObject and hand it to the verifier. did:key encodes the public key in the identifier (multicodec + base58btc), so resolution is deterministic and offline — Ed25519, P-256, P-384, and secp256k1 round-trip; did:web places the DID document at an HTTPS URL derived from the identifier, with the network fetch left to the operator (the framework parses the operator-fetched document and extracts its verification methods, as publicKeyMultibase or publicKeyJwk). b.did.keyToDid encodes a KeyObject as a did:key (an issuer naming itself), b.did.parse splits the identifier (and returns the did:web URL to fetch), and b.did.resolve returns the document and verification keys. DID Core 1.0 is a W3C Recommendation; the method specs (did:key W3C CCG report, did:web DID method registry — EUDI-mandated) are deployed-stable. Composes node:crypto; no new runtime dependency. **Added:** *`b.did.resolve(did, opts?)` / `b.did.keyToDid(publicKey)` / `b.did.parse(did)`* — `resolve` returns `{ didDocument, verificationMethods: [{ id, controller, type, publicKey }] }` with each `publicKey` a `node:crypto` KeyObject ready for `b.vc.verify` / `b.mdoc.verifyIssuerSigned` / `b.scitt.verifyStatement`. did:key resolves deterministically and offline (base58btc + multicodec → Ed25519 raw key or EC compressed point, rebuilt via SPKI); did:web requires the operator to pass the fetched DID document as `opts.document` (the URL to GET is on `b.did.parse(did).url`) and the document `id` must match the requested DID. A publicKeyJwk in a DID document is imported only after its `kty`/`crv` is allowlisted (Ed25519 / P-256 / P-384 / secp256k1) — an unexpected key type from an untrusted document is refused, not blindly imported. `keyToDid` encodes an Ed25519 / P-256 / P-384 / secp256k1 KeyObject as a did:key; `parse` derives the did:web HTTPS URL (`host[:port][:path]` → `https://host/path/did.json`, or `/.well-known/did.json`). Unknown methods, malformed base58, unsupported multicodec codes, and unsupported key types are each refused.
12
+
13
+ - v0.12.40 (2026-05-24) — **`b.mdoc` — ISO 18013-5 mdoc / mDL issuer-data verification.** Verify the issuer-signed data of an ISO/IEC 18013-5 mdoc — the credential format behind mobile driving licences (mDL) and the ISO track of the EU Digital Identity Wallet. This is the relying-party side: confirm that the data elements a holder presents were signed by the issuer and have not been altered. An mdoc's IssuerSigned carries the disclosed data elements and an issuerAuth that is a COSE_Sign1 (b.cose) over a Mobile Security Object (MSO) holding a per-element digest. b.mdoc.verifyIssuerSigned verifies the COSE signature with the issuer certificate from the COSE x5chain header, parses the MSO, enforces its validityInfo window, and recomputes each disclosed element's digest (the full Tag-24 IssuerSignedItemBytes) to match it against the MSO constant-time — the integrity check that makes selective disclosure trustworthy. An absent or mismatched digest is refused. Signing algorithms follow b.cose verification (the classical ES256/384/512 + EdDSA that real mDL issuers use; the caller names the allowlist); opts.trustAnchorsPem additionally verifies the issuer certificate chain. This completes the credential trio alongside W3C VCDM (b.vc) and IETF SD-JWT VC (b.auth.sdJwtVc). Composes b.cose + b.cbor; no new runtime dependency. **Added:** *`b.mdoc.verifyIssuerSigned(issuerSigned, opts)`* — Takes the CBOR `IssuerSigned` map (the operator extracts it from the device response / QR) and returns `{ docType, version, digestAlgorithm, validityInfo, namespaces, signerCert, alg }`. Verifies the COSE_Sign1 `issuerAuth` against the mandatory `opts.algorithms` allowlist using the issuer certificate from its `x5chain` (label 33) header; parses the Tag-24 Mobile Security Object; enforces the MSO `validityInfo` window against `opts.at` (default now; must be a valid Date; malformed dates fail closed); and recomputes the digest of every disclosed `IssuerSignedItem` (over the full Tag-24 bytes, with the MSO `digestAlgorithm` — SHA-256/384/512) to match the MSO `valueDigests` constant-time — an absent or mismatched digest is refused with `mdoc/digest-mismatch`. `opts.expectedDocType` pins the document type; `opts.trustAnchorsPem` (a PEM string or array) additionally verifies the issuer certificate chain and validity at the asserted time. A malformed `x5chain` certificate is refused with a clean `mdoc/bad-cert`. The mdoc device-authentication half (the SessionTranscript-bound holder-binding proof) is a presentation-protocol concern and is not part of issuer-data verification.
14
+
11
15
  - v0.12.39 (2026-05-24) — **`b.vc` — W3C Verifiable Credentials 2.0 (issue / verify, JOSE + COSE securing).** Issue and verify W3C Verifiable Credentials (VC Data Model 2.0, a W3C Recommendation) secured per Securing Verifiable Credentials using JOSE and COSE (VC-JOSE-COSE, also a W3C Recommendation, May 2025). A verifiable credential is a tamper-evident, signed set of claims an issuer makes about a subject — a diploma, a membership, a license, an age assertion. Two securing mechanisms are supported, both signing the credential itself (no JWT/CWT claims wrapper): JOSE produces a compact JWS with the vc+jwt media type, signed with ES256/384/512 or EdDSA; COSE produces a COSE_Sign1 (application/vc+cose) over b.cose, which also accepts ML-DSA-87 for PQC-forward deployments. b.vc.verify auto-detects the form from the input, requires an algorithm allowlist, always refuses the JOSE none algorithm, re-checks the VCDM 2.0 structural rules, and enforces the validFrom / validUntil window. This is the W3C credential model, distinct from the IETF SD-JWT VC already at b.auth.sdJwtVc. Composes b.cose; no new runtime dependency. **Added:** *`b.vc.issue(credential, opts)` / `b.vc.verify(secured, opts)`* — `issue` validates the credential against the VCDM 2.0 structural rules (the `credentials/v2` context first, a `VerifiableCredential` type, an issuer, a credential subject) and signs it: `securing: "jose"` returns a compact JWS string (`typ` header `vc+jwt`), `securing: "cose"` returns COSE_Sign1 bytes (`typ` header `application/vc+cose`, content type `application/vc`) via `b.cose`. The credential is the exact signed payload — no JWT/CWT claims are injected. `verify` auto-detects the securing form from the input (compact-JWS string vs. COSE_Sign1 bytes), verifies the signature against the mandatory `opts.algorithms` allowlist (the JOSE `none` algorithm is always refused), re-checks the structural rules, enforces the `validFrom` / `validUntil` window against `opts.at` (default now; must be a valid Date), and optionally matches `opts.expectedIssuer` against the credential issuer id. Returns `{ credential, securing, alg, issuer }`.
12
16
 
13
17
  - v0.12.38 (2026-05-24) — **`b.tsa` — RFC 3161 trusted timestamping client (build / parse / verify).** A timestamp authority binds a hash of your data to a trusted time, producing a token that proves the data existed at that instant — timestamp a release artifact, an audit-log checkpoint, a b.scitt signed statement, or a contract. b.tsa is the requester/verifier side of RFC 3161: buildRequest produces the DER TimeStampReq (the message imprint plus an optional nonce and a cert request), parseResponse reads the TimeStampResp (PKIStatus, failure-info bits, and the token), and verifyToken checks a token against your data and returns the asserted time. Verification is done in full per §2.4.2 / §2.3: the token is a CMS SignedData (b.cms) whose eContentType must be id-ct-TSTInfo; the message imprint must equal the hash of your data (constant-time); a sent nonce must round-trip; the signer certificate's extendedKeyUsage must be a critical, sole id-kp-timeStamping; and the CMS signature over the signed attributes must verify after the messageDigest attribute is matched to the recomputed eContent digest. An optional trust-anchor set verifies the certificate chain and validity at the asserted time. The HTTP transport to the TSA is the operator's to make. Composes b.cms and the in-tree ASN.1 DER codec; no new runtime dependency. **Added:** *`b.tsa.buildRequest(data, opts?)` / `b.tsa.parseResponse(der)` / `b.tsa.verifyToken(token, opts)`* — `buildRequest` returns `{ der, nonce, hashAlg, messageImprint }`; the imprint hash defaults to SHA-512 and may be SHA-256/384/512 or SHA3-256/512, a random 64-bit nonce and a certificate request are included by default, and a pre-hashed input is accepted with `hashed: true`. `parseResponse` returns `{ granted, status, statusString, failInfo, token }`, decoding the PKIFailureInfo bits for a non-granted response rather than throwing. `verifyToken` enforces the imprint match (`opts.data` or `opts.hash`), the nonce round-trip, the critical/sole `id-kp-timeStamping` EKU, and the CMS signature, returning `{ genTime, policy, serialHex, accuracy, hashAlg, signerCertPem }`; pass `opts.trustAnchorsPem` to also verify the certificate chain and validity at the asserted time. Timestamp tokens are third-party artifacts, so verification accepts the classical RSA (PKCS#1 v1.5 and PSS) and ECDSA-over-SHA-2 signatures that public TSAs emit — the same consume-what-exists posture as `b.cose` verification, not a framework signing default.
package/README.md CHANGED
@@ -132,6 +132,8 @@ The framework bundles the surface a typical Node app reaches for. Every primitiv
132
132
  - **SCITT signed statements** — `b.scitt` sign/verify a signed, attributable claim about an artifact (signed SBOM, build attestation, release approval) over `b.cose`: the issuer + subject bind in the integrity-protected CWT_Claims header (RFC 9597); verification refuses any statement missing the iss/sub binding. The issuer side, on finalized RFCs; the transparency receipt (COSE Receipts draft) opts in on publication
133
133
  - **Trusted timestamping** — `b.tsa` RFC 3161 timestamp client: `buildRequest` a TimeStampReq, `parseResponse`, and `verifyToken` against your data — the message imprint, sent nonce, critical/sole `id-kp-timeStamping` EKU, and CMS signature are all checked, with optional certificate-chain verification. Timestamp a release artifact, audit checkpoint, or signed statement against any RFC 3161 TSA. Composes `b.cms` + the in-tree ASN.1 DER codec
134
134
  - **Verifiable Credentials** — `b.vc` W3C Verifiable Credentials Data Model 2.0 (VC-JOSE-COSE): `issue` / `verify` a signed credential as a compact JWS (`vc+jwt`, ES256/384/512 + EdDSA) or a COSE_Sign1 (`vc+cose`, + ML-DSA-87) over `b.cose`. VCDM structural + `validFrom`/`validUntil` checks; the JOSE `none` algorithm is always refused. The W3C model, distinct from the IETF SD-JWT VC at `b.auth.sdJwtVc`
135
+ - **Mobile credentials (mDL)** — `b.mdoc` ISO/IEC 18013-5 issuer-data verification: `verifyIssuerSigned` checks the COSE_Sign1 IssuerAuth (issuer cert from the `x5chain` header), the Mobile Security Object validity window, and every disclosed element's digest against the MSO `valueDigests` (the selective-disclosure integrity check), with optional issuer-chain verification. The ISO credential ecosystem alongside `b.vc` and `b.auth.sdJwtVc`. Composes `b.cose` + `b.cbor`
136
+ - **Decentralized Identifiers** — `b.did` W3C DID resolution (DID Core 1.0): `resolve` a `did:key` (deterministic, offline — Ed25519 / P-256 / P-384 / secp256k1) or `did:web` (operator-fetched document) to `node:crypto` verification keys, so a credential's issuer DID resolves to the key that verifies it (`b.vc` / `b.mdoc` / `b.scitt`). `keyToDid` names a key as a `did:key`; document JWKs are kty/crv-allowlisted before import
135
137
  - **Document parsers** — `b.parsers` (XML / TOML / YAML / .env); `b.config` (schema-validated env)
136
138
  - **File-type detection** — `b.fileType` magic-byte content classification with deny-on-upload categories (image / document / archive / executable / etc.)
137
139
  ### Content-safety gates
package/index.js CHANGED
@@ -462,6 +462,8 @@ module.exports = {
462
462
  scitt: require("./lib/scitt"),
463
463
  tsa: require("./lib/tsa"),
464
464
  vc: require("./lib/vc"),
465
+ mdoc: require("./lib/mdoc"),
466
+ did: require("./lib/did"),
465
467
  queue: queue,
466
468
  logStream: logStream,
467
469
  redact: redact,
package/lib/did.js ADDED
@@ -0,0 +1,367 @@
1
+ "use strict";
2
+ /**
3
+ * @module b.did
4
+ * @nav Crypto
5
+ * @title Decentralized Identifiers (DID)
6
+ *
7
+ * @intro
8
+ * Resolve W3C Decentralized Identifiers (DID Core 1.0, a W3C
9
+ * Recommendation) to verification keys — the missing link that lets a
10
+ * credential's issuer be named by a DID rather than a raw key. Resolve
11
+ * the issuer DID of a <code>b.vc</code> / <code>b.mdoc</code> /
12
+ * <code>b.scitt</code> credential to a <code>node:crypto</code>
13
+ * KeyObject, then hand that key to the verifier.
14
+ *
15
+ * Two methods are supported. <strong>did:key</strong> encodes a public
16
+ * key directly in the identifier (multicodec + base58btc multibase),
17
+ * so resolution is deterministic and offline — Ed25519, P-256, P-384,
18
+ * and secp256k1 keys round-trip. <strong>did:web</strong> places the
19
+ * DID document at an HTTPS URL derived from the identifier; the network
20
+ * fetch is the operator's to make (the same operator-supplied-input
21
+ * stance as the rest of the framework), and <code>resolve</code> takes
22
+ * the fetched document and extracts its verification methods.
23
+ *
24
+ * <code>b.did.keyToDid(publicKey)</code> produces a did:key from a
25
+ * KeyObject (an issuer naming itself); <code>b.did.parse(did)</code>
26
+ * splits the identifier (and, for did:web, returns the HTTPS URL to
27
+ * fetch); <code>b.did.resolve(did, opts)</code> returns the DID
28
+ * document and its verification methods as KeyObjects. Verification
29
+ * methods expressed as <code>publicKeyMultibase</code> or
30
+ * <code>publicKeyJwk</code> are both understood.
31
+ *
32
+ * <strong>Maturity.</strong> DID Core 1.0 is a Recommendation, but the
33
+ * method specs are deployed-stable rather than Recommendations:
34
+ * did:key is a W3C CCG report and did:web is a registered DID method
35
+ * (mandated by the EU Digital Identity Wallet). They are widely
36
+ * deployed and interoperable today; pin the dependency deliberately.
37
+ *
38
+ * @card
39
+ * W3C DID resolution (did:key + did:web) → verification KeyObjects for
40
+ * the credential verifiers. did:key is deterministic + offline
41
+ * (Ed25519 / P-256 / P-384 / secp256k1); did:web parses an
42
+ * operator-fetched DID document. Composes node:crypto; no new dep.
43
+ */
44
+
45
+ var nodeCrypto = require("node:crypto");
46
+ var validateOpts = require("./validate-opts");
47
+ var { defineClass } = require("./framework-error");
48
+
49
+ var DidError = defineClass("DidError", { alwaysPermanent: true });
50
+
51
+ var B58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
52
+ var B58_MAP = (function () {
53
+ var m = {};
54
+ for (var i = 0; i < B58_ALPHABET.length; i += 1) m[B58_ALPHABET[i]] = i;
55
+ return m;
56
+ })();
57
+ var MAX_MULTIBASE_CHARS = 1024; // allow:raw-byte-literal — bounded did:key multibase length (DoS cap)
58
+
59
+ // multicodec public-key codes (unsigned-varint) → curve descriptor.
60
+ // keyLen is the multicodec payload: Ed25519 raw 32; EC compressed point.
61
+ var MULTICODEC = {
62
+ 0xed: { name: "Ed25519", kind: "okp" }, // ed25519-pub
63
+ 0x1200: { name: "P-256", kind: "ec", curveOid: "1.2.840.10045.3.1.7" }, // allow:raw-byte-literal allow:raw-time-literal — p256-pub multicodec code + OID dotted-form
64
+ 0x1201: { name: "P-384", kind: "ec", curveOid: "1.3.132.0.34" }, // allow:raw-byte-literal — p384-pub multicodec code
65
+ 0xe7: { name: "secp256k1", kind: "ec", curveOid: "1.3.132.0.10" }, // secp256k1-pub
66
+ };
67
+ var NAME_TO_CODE = {};
68
+ Object.keys(MULTICODEC).forEach(function (c) { NAME_TO_CODE[MULTICODEC[c].name] = Number(c); });
69
+
70
+ // ---- base58btc (bounded) ----
71
+
72
+ function _b58decode(str) {
73
+ if (str.length > MAX_MULTIBASE_CHARS) {
74
+ throw new DidError("did/too-long", "did: multibase value exceeds the " + MAX_MULTIBASE_CHARS + "-char cap");
75
+ }
76
+ var bytes = [0];
77
+ for (var i = 0; i < str.length; i += 1) {
78
+ var v = B58_MAP[str[i]];
79
+ if (v === undefined) throw new DidError("did/bad-base58", "did: invalid base58btc character '" + str[i] + "'");
80
+ var carry = v;
81
+ for (var j = 0; j < bytes.length; j += 1) {
82
+ carry += bytes[j] * 58;
83
+ bytes[j] = carry & 0xff;
84
+ carry >>= 8; // allow:raw-byte-literal — base-256 carry
85
+ }
86
+ while (carry > 0) { bytes.push(carry & 0xff); carry >>= 8; } // allow:raw-byte-literal — base-256 carry
87
+ }
88
+ // Leading '1's are leading zero bytes.
89
+ for (var k = 0; k < str.length && str[k] === "1"; k += 1) bytes.push(0);
90
+ return Buffer.from(bytes.reverse());
91
+ }
92
+
93
+ function _b58encode(buf) {
94
+ var digits = [0];
95
+ for (var i = 0; i < buf.length; i += 1) {
96
+ var carry = buf[i];
97
+ for (var j = 0; j < digits.length; j += 1) {
98
+ carry += digits[j] << 8; // allow:raw-byte-literal — base-256 shift
99
+ digits[j] = carry % 58;
100
+ carry = (carry / 58) | 0;
101
+ }
102
+ while (carry > 0) { digits.push(carry % 58); carry = (carry / 58) | 0; }
103
+ }
104
+ var out = "";
105
+ for (var z = 0; z < buf.length && buf[z] === 0; z += 1) out += "1";
106
+ for (var d = digits.length - 1; d >= 0; d -= 1) out += B58_ALPHABET[digits[d]];
107
+ return out;
108
+ }
109
+
110
+ // Read an unsigned LEB128 varint (multicodec code). Bounded to 4 bytes.
111
+ function _readVarint(buf) {
112
+ var value = 0, shift = 0, len = 0;
113
+ for (var i = 0; i < buf.length && i < 4; i += 1) { // allow:raw-byte-literal — multicodec varint ≤ 4 bytes
114
+ var b = buf[i];
115
+ value |= (b & 0x7f) << shift;
116
+ len += 1;
117
+ if ((b & 0x80) === 0) return { value: value >>> 0, length: len };
118
+ shift += 7; // allow:raw-byte-literal — 7 bits per varint byte
119
+ }
120
+ throw new DidError("did/bad-multicodec", "did: multicodec varint did not terminate");
121
+ }
122
+ function _encodeVarint(code) {
123
+ var out = [];
124
+ var n = code;
125
+ do { var b = n & 0x7f; n >>>= 7; if (n > 0) b |= 0x80; out.push(b); } while (n > 0); // allow:raw-byte-literal — LEB128 7-bit groups
126
+ return Buffer.from(out);
127
+ }
128
+
129
+ // ---- key <-> bytes ----
130
+
131
+ var ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex"); // RFC 8410 Ed25519 SubjectPublicKeyInfo header
132
+
133
+ function _keyObjectFromMulticodec(code, keyBytes) {
134
+ var desc = MULTICODEC[code];
135
+ if (!desc) throw new DidError("did/unsupported-key", "did: unsupported multicodec key code 0x" + code.toString(16)); // allow:raw-byte-literal — hex radix
136
+ if (desc.kind === "okp") {
137
+ if (keyBytes.length !== 32) { // allow:raw-byte-literal — Ed25519 public key is 32 bytes
138
+ throw new DidError("did/bad-key", "did: Ed25519 key must be 32 bytes (got " + keyBytes.length + ")");
139
+ }
140
+ return nodeCrypto.createPublicKey({ key: Buffer.concat([ED25519_SPKI_PREFIX, keyBytes]), format: "der", type: "spki" });
141
+ }
142
+ // EC: keyBytes is a compressed point (0x02/0x03 + X). Build an SPKI and
143
+ // let node decompress.
144
+ if (keyBytes.length < 2 || (keyBytes[0] !== 0x02 && keyBytes[0] !== 0x03)) {
145
+ throw new DidError("did/bad-key", "did: EC key must be a compressed point (0x02/0x03 prefix)");
146
+ }
147
+ var algid = _ecAlgId(desc.curveOid);
148
+ var bitstr = Buffer.concat([Buffer.from([0x03, keyBytes.length + 1, 0x00]), keyBytes]);
149
+ var body = Buffer.concat([algid, bitstr]);
150
+ var spki = Buffer.concat([Buffer.from([0x30, body.length]), body]); // allow:raw-byte-literal — SEQUENCE tag; single-byte DER length holds for these curves
151
+ try { return nodeCrypto.createPublicKey({ key: spki, format: "der", type: "spki" }); }
152
+ catch (e) { throw new DidError("did/bad-key", "did: could not import EC key: " + ((e && e.message) || e)); }
153
+ }
154
+
155
+ // AlgorithmIdentifier SEQUENCE { id-ecPublicKey, namedCurve OID }.
156
+ function _ecAlgId(curveOid) {
157
+ var idEcPublicKey = Buffer.from("06072a8648ce3d0201", "hex"); // allow:raw-byte-literal allow:raw-time-literal — DER OID for id-ecPublicKey
158
+ var curve = _oidDer(curveOid);
159
+ var inner = Buffer.concat([idEcPublicKey, curve]);
160
+ return Buffer.concat([Buffer.from([0x30, inner.length]), inner]);
161
+ }
162
+ function _oidDer(dotted) {
163
+ var parts = dotted.split(".").map(Number);
164
+ var bytes = [parts[0] * 40 + parts[1]]; // allow:raw-byte-literal — X.690 first-arc encoding
165
+ for (var i = 2; i < parts.length; i += 1) {
166
+ var arc = parts[i], stack = [];
167
+ do { stack.unshift(arc & 0x7f); arc >>>= 7; } while (arc > 0); // allow:raw-byte-literal — base-128 OID arc
168
+ for (var j = 0; j < stack.length - 1; j += 1) stack[j] |= 0x80; // allow:raw-byte-literal — continuation bit
169
+ bytes = bytes.concat(stack);
170
+ }
171
+ return Buffer.concat([Buffer.from([0x06, bytes.length]), Buffer.from(bytes)]);
172
+ }
173
+
174
+ // Compressed point + curve name from an EC KeyObject's JWK.
175
+ function _compressedPoint(jwk) {
176
+ var x = Buffer.from(jwk.x, "base64url");
177
+ var y = Buffer.from(jwk.y, "base64url");
178
+ return Buffer.concat([Buffer.from([(y[y.length - 1] & 1) ? 0x03 : 0x02]), x]);
179
+ }
180
+
181
+ /**
182
+ * @primitive b.did.parse
183
+ * @signature b.did.parse(did)
184
+ * @since 0.12.41
185
+ * @status experimental
186
+ * @related b.did.resolve, b.did.keyToDid
187
+ *
188
+ * Split a DID string into its method and method-specific id. For
189
+ * <code>did:web</code> the HTTPS URL of the DID document is also
190
+ * returned (host[:port][:path] → <code>https://host/path/did.json</code>,
191
+ * or <code>/.well-known/did.json</code> with no path).
192
+ *
193
+ * @example
194
+ * b.did.parse("did:web:example.com:issuers:42");
195
+ * // → { method: "web", id: "example.com:issuers:42", url: "https://example.com/issuers/42/did.json" }
196
+ */
197
+ function parse(did) {
198
+ if (typeof did !== "string" || did.indexOf("did:") !== 0) {
199
+ throw new DidError("did/bad-did", "did.parse: not a DID (must start with 'did:')");
200
+ }
201
+ var rest = did.slice(4);
202
+ var colon = rest.indexOf(":");
203
+ if (colon <= 0) throw new DidError("did/bad-did", "did.parse: DID is missing a method-specific id");
204
+ var method = rest.slice(0, colon);
205
+ var id = rest.slice(colon + 1);
206
+ var out = { method: method, id: id };
207
+ if (method === "web") out.url = _didWebUrl(id);
208
+ return out;
209
+ }
210
+
211
+ function _didWebUrl(id) {
212
+ // did-method-web §read: ':' separates segments (→ '/'); only the host
213
+ // may carry a percent-encoded port (%3A → ':'). Path segments are kept
214
+ // verbatim — NOT percent-decoded — so an escaped reserved char (e.g.
215
+ // %3F) stays path data rather than becoming URL control syntax, and a
216
+ // malformed escape never throws a raw URIError.
217
+ var segs = id.split(":");
218
+ var host = segs[0].replace(/%3[Aa]/g, ":");
219
+ if (!host) throw new DidError("did/bad-did", "did:web: missing host");
220
+ var path = segs.slice(1);
221
+ var base = "https://" + host;
222
+ return path.length ? base + "/" + path.join("/") + "/did.json" : base + "/.well-known/did.json";
223
+ }
224
+
225
+ /**
226
+ * @primitive b.did.keyToDid
227
+ * @signature b.did.keyToDid(publicKey)
228
+ * @since 0.12.41
229
+ * @status experimental
230
+ * @related b.did.resolve
231
+ *
232
+ * Encode a public key (a <code>node:crypto</code> KeyObject or PEM) as a
233
+ * <code>did:key</code> — the inverse of resolution, for an issuer that
234
+ * names itself by its key. Ed25519, P-256, P-384, and secp256k1 are
235
+ * supported.
236
+ *
237
+ * @example
238
+ * var did = b.did.keyToDid(issuerPublicKey); // → "did:key:z6Mk…"
239
+ */
240
+ function keyToDid(publicKey) {
241
+ var key = (publicKey && typeof publicKey === "object" && publicKey.asymmetricKeyType)
242
+ ? publicKey : nodeCrypto.createPublicKey(publicKey);
243
+ var jwk = key.export({ format: "jwk" });
244
+ var code, payload;
245
+ if (jwk.kty === "OKP" && jwk.crv === "Ed25519") {
246
+ code = NAME_TO_CODE["Ed25519"];
247
+ payload = Buffer.from(jwk.x, "base64url");
248
+ } else if (jwk.kty === "EC") {
249
+ var name = jwk.crv === "P-256" ? "P-256" : jwk.crv === "P-384" ? "P-384" : jwk.crv === "secp256k1" ? "secp256k1" : null;
250
+ if (!name) throw new DidError("did/unsupported-key", "did.keyToDid: unsupported EC curve '" + jwk.crv + "'");
251
+ code = NAME_TO_CODE[name];
252
+ payload = _compressedPoint(jwk);
253
+ } else {
254
+ throw new DidError("did/unsupported-key", "did.keyToDid: unsupported key type '" + jwk.kty + "/" + jwk.crv + "'");
255
+ }
256
+ return "did:key:z" + _b58encode(Buffer.concat([_encodeVarint(code), payload]));
257
+ }
258
+
259
+ /**
260
+ * @primitive b.did.resolve
261
+ * @signature b.did.resolve(did, opts?)
262
+ * @since 0.12.41
263
+ * @status experimental
264
+ * @compliance soc2
265
+ * @related b.did.parse, b.vc.verify, b.mdoc.verifyIssuerSigned
266
+ *
267
+ * Resolve a DID to its document and verification methods (each with a
268
+ * <code>node:crypto</code> public KeyObject ready for a verifier).
269
+ * <code>did:key</code> resolves deterministically and offline.
270
+ * <code>did:web</code> requires the operator to supply the fetched DID
271
+ * document as <code>opts.document</code> (the network fetch is the
272
+ * operator's; the URL to fetch is on <code>b.did.parse(did).url</code>).
273
+ *
274
+ * @opts
275
+ * {
276
+ * document: object, // did:web — the fetched did.json (required for did:web)
277
+ * }
278
+ *
279
+ * @example
280
+ * var r = b.did.resolve("did:key:z6Mk…");
281
+ * var key = r.verificationMethods[0].publicKey; // → KeyObject for b.vc.verify / b.mdoc / b.scitt
282
+ */
283
+ function resolve(did, opts) {
284
+ opts = opts || {};
285
+ validateOpts.requireObject(opts, "did.resolve", DidError);
286
+ validateOpts(opts, ["document"], "did.resolve");
287
+ var parsed = parse(did);
288
+
289
+ if (parsed.method === "key") {
290
+ if (parsed.id[0] !== "z") {
291
+ throw new DidError("did/bad-did", "did:key: method-specific id must be base58btc multibase (start with 'z')");
292
+ }
293
+ var raw = _b58decode(parsed.id.slice(1));
294
+ var vh = _readVarint(raw);
295
+ var key = _keyObjectFromMulticodec(vh.value, raw.slice(vh.length));
296
+ var vmId = did + "#" + parsed.id;
297
+ var vm = { id: vmId, controller: did, type: MULTICODEC[vh.value].name, publicKey: key };
298
+ var doc = {
299
+ "@context": ["https://www.w3.org/ns/did/v1"],
300
+ id: did,
301
+ verificationMethod: [{ id: vmId, controller: did, type: "Multikey", publicKeyMultibase: parsed.id }],
302
+ assertionMethod: [vmId], authentication: [vmId],
303
+ };
304
+ return { didDocument: doc, verificationMethods: [vm] };
305
+ }
306
+
307
+ if (parsed.method === "web") {
308
+ if (!opts.document || typeof opts.document !== "object") {
309
+ throw new DidError("did/document-required",
310
+ "did:web: the DID document must be fetched by the operator and passed as opts.document (GET " + parsed.url + ")");
311
+ }
312
+ var docW = opts.document;
313
+ if (docW.id !== did) {
314
+ throw new DidError("did/document-mismatch", "did:web: document id '" + docW.id + "' does not match the requested DID");
315
+ }
316
+ return { didDocument: docW, verificationMethods: _extractVerificationMethods(docW) };
317
+ }
318
+
319
+ throw new DidError("did/unsupported-method", "did.resolve: unsupported DID method '" + parsed.method + "' (did:key and did:web only)");
320
+ }
321
+
322
+ // Import a publicKeyJwk after allowlisting its kty/crv — a DID document
323
+ // is untrusted input, so an unexpected key type (RSA / oct / unknown
324
+ // curve) is refused before it reaches node:crypto rather than blindly
325
+ // imported (the DID-context equivalent of the JWT alg/kty cross-check;
326
+ // there is no single verification `alg` in a DID document).
327
+ function _jwkToKey(jwk) {
328
+ var ok = (jwk.kty === "OKP" && jwk.crv === "Ed25519") ||
329
+ (jwk.kty === "EC" && (jwk.crv === "P-256" || jwk.crv === "P-384" || jwk.crv === "secp256k1"));
330
+ if (!ok) {
331
+ throw new DidError("did/unsupported-key",
332
+ "did: verificationMethod publicKeyJwk has unsupported kty/crv (" + jwk.kty + "/" + jwk.crv + ")");
333
+ }
334
+ try { return nodeCrypto.createPublicKey({ key: jwk, format: "jwk" }); }
335
+ catch (e) { throw new DidError("did/bad-key", "did: verificationMethod publicKeyJwk is invalid: " + ((e && e.message) || e)); }
336
+ }
337
+
338
+ // Extract verification methods from a DID document → KeyObjects.
339
+ function _extractVerificationMethods(doc) {
340
+ var vms = Array.isArray(doc.verificationMethod) ? doc.verificationMethod : [];
341
+ var out = [];
342
+ for (var i = 0; i < vms.length; i += 1) {
343
+ var vm = vms[i];
344
+ if (!vm || typeof vm !== "object") continue;
345
+ var key = null;
346
+ if (typeof vm.publicKeyMultibase === "string" && vm.publicKeyMultibase[0] === "z") {
347
+ var raw = _b58decode(vm.publicKeyMultibase.slice(1));
348
+ var vh = _readVarint(raw);
349
+ key = _keyObjectFromMulticodec(vh.value, raw.slice(vh.length));
350
+ } else if (vm.publicKeyJwk && typeof vm.publicKeyJwk === "object") {
351
+ key = _jwkToKey(vm.publicKeyJwk);
352
+ } else {
353
+ continue; // unknown key encoding — skip rather than guess
354
+ }
355
+ out.push({ id: vm.id, controller: vm.controller, type: vm.type, publicKey: key });
356
+ }
357
+ if (!out.length) throw new DidError("did/no-keys", "did: document has no resolvable verification methods");
358
+ return out;
359
+ }
360
+
361
+ module.exports = {
362
+ parse: parse,
363
+ keyToDid: keyToDid,
364
+ resolve: resolve,
365
+ MULTICODEC: MULTICODEC,
366
+ DidError: DidError,
367
+ };
package/lib/mdoc.js ADDED
@@ -0,0 +1,305 @@
1
+ "use strict";
2
+ /**
3
+ * @module b.mdoc
4
+ * @nav Crypto
5
+ * @title ISO mdoc / mDL (ISO 18013-5)
6
+ *
7
+ * @intro
8
+ * Verify the issuer-signed data of an ISO/IEC 18013-5 mdoc — the
9
+ * credential format behind mobile driving licences (mDL) and the ISO
10
+ * track of the EU Digital Identity Wallet. This is the relying-party
11
+ * side: confirm that the data elements a holder presents were signed
12
+ * by the issuer and have not been altered.
13
+ *
14
+ * An mdoc's <code>IssuerSigned</code> structure carries the disclosed
15
+ * data elements (<code>nameSpaces</code>) and an <code>issuerAuth</code>
16
+ * that is a COSE_Sign1 (<code>b.cose</code>) over a Mobile Security
17
+ * Object (MSO). The MSO holds, per namespace, a SHA-256/384/512 digest
18
+ * of every issued element. <code>b.mdoc.verifyIssuerSigned</code>
19
+ * verifies the COSE signature with the issuer certificate carried in
20
+ * the COSE <code>x5chain</code> (label 33), parses the MSO, enforces
21
+ * its <code>validityInfo</code> window, and — the integrity check that
22
+ * makes selective disclosure trustworthy — recomputes the digest of
23
+ * every disclosed element (the full Tag-24 <code>IssuerSignedItemBytes</code>)
24
+ * and matches it against the MSO, constant-time. A disclosed element
25
+ * whose digest is absent or mismatched is refused.
26
+ *
27
+ * Signing algorithms follow <code>b.cose</code> verification: the
28
+ * classical ES256 / 384 / 512 and EdDSA that real mDL issuers use are
29
+ * accepted (consume-what-exists; the caller names the allowlist).
30
+ * <code>opts.trustAnchorsPem</code> additionally verifies the issuer
31
+ * certificate chain and its validity at the asserted time.
32
+ *
33
+ * <strong>Scope.</strong> This is issuer-data authentication
34
+ * (ISO 18013-5 §9.1.2.4) — the data is genuine and issuer-signed. The
35
+ * mdoc <em>device authentication</em> half (DeviceSigned / the
36
+ * SessionTranscript-bound holder-binding proof, §9.1.3) is deferred:
37
+ * it needs the live session transcript a verifier negotiates, so it is
38
+ * a presentation-protocol concern rather than a credential check.
39
+ * Composes <code>b.cose</code> + <code>b.cbor</code>; no new runtime
40
+ * dependency. Distinct from W3C VCDM (<code>b.vc</code>) and IETF
41
+ * SD-JWT VC (<code>b.auth.sdJwtVc</code>) — the three credential
42
+ * ecosystems.
43
+ *
44
+ * @card
45
+ * ISO 18013-5 mdoc / mDL issuer-data verification — checks the
46
+ * COSE_Sign1 IssuerAuth, the MSO validity window, and every disclosed
47
+ * element's digest against the Mobile Security Object. Composes
48
+ * b.cose + b.cbor; device-auth holder-binding deferred.
49
+ */
50
+
51
+ var nodeCrypto = require("node:crypto");
52
+ var C = require("./constants");
53
+ var cbor = require("./cbor");
54
+ var cose = require("./cose");
55
+ var bCrypto = require("./crypto");
56
+ var validateOpts = require("./validate-opts");
57
+ var { defineClass } = require("./framework-error");
58
+
59
+ var MdocError = defineClass("MdocError", { alwaysPermanent: true });
60
+
61
+ var HDR_X5CHAIN = 33; // allow:raw-byte-literal allow:raw-time-literal — x5chain COSE header label (RFC 9360 is a spec number, not a size/duration)
62
+ var TAG_ENCODED_CBOR = 24; // allow:raw-byte-literal — RFC 8949 §3.4.5.1 embedded-CBOR tag
63
+ // Tags ISO 18013-5 uses in issuer data: tdate(0), epoch(1), embedded
64
+ // CBOR(24), full-date(1004, RFC 8943). Bounded — others are refused.
65
+ var ALLOWED_TAGS = [0, 1, TAG_ENCODED_CBOR, 1004];
66
+ var DIGEST_ALGS = { "SHA-256": "sha256", "SHA-384": "sha384", "SHA-512": "sha512" };
67
+
68
+ function _bytes(x, what) {
69
+ if (Buffer.isBuffer(x)) return x;
70
+ if (x instanceof Uint8Array) return Buffer.from(x);
71
+ throw new MdocError("mdoc/bad-input", "mdoc: " + what + " must be a Buffer / Uint8Array of CBOR");
72
+ }
73
+
74
+ // validityInfo dates are tdate (Tag 0, an RFC 3339 string) or epoch
75
+ // (Tag 1). Returns epoch-ms; fails closed on a malformed value.
76
+ function _validityMs(v, name) {
77
+ var raw = (v instanceof cbor.Tag) ? v.value : v;
78
+ if (typeof raw === "string") {
79
+ var ms = Date.parse(raw);
80
+ if (!isFinite(ms)) throw new MdocError("mdoc/bad-validity", "mdoc: validityInfo." + name + " is not a valid date: " + raw);
81
+ return ms;
82
+ }
83
+ if (typeof raw === "number" && isFinite(raw)) return raw * C.TIME.seconds(1); // epoch seconds → ms
84
+ throw new MdocError("mdoc/bad-validity", "mdoc: validityInfo." + name + " is missing or malformed");
85
+ }
86
+
87
+ function _mapGet(m, k) { return m instanceof Map ? m.get(k) : (m ? m[k] : undefined); }
88
+
89
+ /**
90
+ * @primitive b.mdoc.verifyIssuerSigned
91
+ * @signature b.mdoc.verifyIssuerSigned(issuerSigned, opts)
92
+ * @since 0.12.40
93
+ * @status experimental
94
+ * @compliance gdpr, soc2
95
+ * @related b.cose.verify, b.vc.verify
96
+ *
97
+ * Verify the issuer-signed data of an ISO 18013-5 mdoc and return the
98
+ * disclosed elements. <code>issuerSigned</code> is the CBOR
99
+ * <code>IssuerSigned</code> map (the operator extracts it from the
100
+ * device response / QR). The COSE_Sign1 <code>issuerAuth</code> is
101
+ * verified with the issuer certificate from its <code>x5chain</code>
102
+ * header against the mandatory <code>opts.algorithms</code> allowlist;
103
+ * the MSO <code>validityInfo</code> window is enforced; and every
104
+ * disclosed element's digest is matched against the Mobile Security
105
+ * Object (a mismatch or absence is refused). Pass
106
+ * <code>opts.trustAnchorsPem</code> to also verify the issuer
107
+ * certificate chain.
108
+ *
109
+ * @opts
110
+ * {
111
+ * algorithms: string[], // required — accepted COSE alg names (ES256/384/512, EdDSA)
112
+ * trustAnchorsPem: string|string[], // optional issuer roots — enables chain + validity verification
113
+ * expectedDocType: string, // require the MSO docType to match (e.g. "org.iso.18013.5.1.mDL")
114
+ * at: Date, // validity instant (default now); must be a valid Date
115
+ * maxBytes: number, // forwarded to b.cbor.decode
116
+ * maxDepth: number,
117
+ * }
118
+ *
119
+ * @example
120
+ * var out = await b.mdoc.verifyIssuerSigned(issuerSignedBytes, {
121
+ * algorithms: ["ES256"], expectedDocType: "org.iso.18013.5.1.mDL",
122
+ * });
123
+ * // → { docType, validityInfo, namespaces: { "org.iso.18013.5.1": { family_name, age_over_18, … } }, signerCert, alg }
124
+ */
125
+ async function verifyIssuerSigned(issuerSigned, opts) {
126
+ validateOpts.requireObject(opts, "mdoc.verifyIssuerSigned", MdocError);
127
+ validateOpts(opts, ["algorithms", "trustAnchorsPem", "expectedDocType", "at", "maxBytes", "maxDepth"], "mdoc.verifyIssuerSigned");
128
+ if (!Array.isArray(opts.algorithms) || opts.algorithms.length === 0) {
129
+ throw new MdocError("mdoc/algorithms-required", "mdoc.verifyIssuerSigned: opts.algorithms is required");
130
+ }
131
+ var at = new Date();
132
+ if (opts.at !== undefined && opts.at !== null) {
133
+ if (!(opts.at instanceof Date) || !isFinite(opts.at.getTime())) {
134
+ throw new MdocError("mdoc/bad-at", "mdoc.verifyIssuerSigned: opts.at must be a valid Date");
135
+ }
136
+ at = opts.at;
137
+ }
138
+ var decodeOpts = { allowedTags: ALLOWED_TAGS, maxBytes: opts.maxBytes, maxDepth: opts.maxDepth };
139
+
140
+ var top = cbor.decode(_bytes(issuerSigned, "issuerSigned"), decodeOpts);
141
+ var nameSpaces = _mapGet(top, "nameSpaces");
142
+ var issuerAuth = _mapGet(top, "issuerAuth");
143
+ if (!Array.isArray(issuerAuth) || issuerAuth.length !== 4) {
144
+ throw new MdocError("mdoc/malformed", "mdoc.verifyIssuerSigned: issuerAuth must be a COSE_Sign1 (4-element array)");
145
+ }
146
+
147
+ // The signer certificate rides in the COSE x5chain (label 33): a
148
+ // single cert bstr or an array of bstrs, leaf first.
149
+ var unprotected = issuerAuth[1];
150
+ var x5 = _mapGet(unprotected, HDR_X5CHAIN);
151
+ var chain = Array.isArray(x5) ? x5 : (x5 != null ? [x5] : []);
152
+ if (!chain.length || !Buffer.isBuffer(chain[0])) {
153
+ throw new MdocError("mdoc/no-cert", "mdoc.verifyIssuerSigned: issuerAuth has no x5chain certificate (label 33)");
154
+ }
155
+ // The x5chain certificate is attacker-controlled — a malformed DER
156
+ // must surface as a clean error, not a raw OpenSSL throw.
157
+ var signerCert;
158
+ try { signerCert = new nodeCrypto.X509Certificate(chain[0]); }
159
+ catch (e) {
160
+ throw new MdocError("mdoc/bad-cert", "mdoc.verifyIssuerSigned: x5chain certificate is not valid DER: " + ((e && e.message) || e));
161
+ }
162
+
163
+ // Verify the COSE_Sign1 signature with the embedded signer key.
164
+ var coseBytes = cbor.encode(issuerAuth);
165
+ var verified = await cose.verify(coseBytes, {
166
+ algorithms: opts.algorithms,
167
+ keyResolver: function () { return signerCert.publicKey; },
168
+ maxBytes: opts.maxBytes,
169
+ maxDepth: opts.maxDepth,
170
+ });
171
+
172
+ // payload = Tag 24 ( bstr .cbor MSO ).
173
+ var payloadTag = cbor.decode(verified.payload, decodeOpts);
174
+ var msoBytes = (payloadTag instanceof cbor.Tag && payloadTag.tag === TAG_ENCODED_CBOR) ? payloadTag.value : null;
175
+ if (!Buffer.isBuffer(msoBytes)) {
176
+ throw new MdocError("mdoc/malformed", "mdoc.verifyIssuerSigned: issuerAuth payload is not a Tag-24 MobileSecurityObject");
177
+ }
178
+ var mso = cbor.decode(msoBytes, decodeOpts);
179
+
180
+ var digestAlgName = _mapGet(mso, "digestAlgorithm");
181
+ var digestNode = DIGEST_ALGS[digestAlgName];
182
+ if (!digestNode) {
183
+ throw new MdocError("mdoc/bad-digest-alg", "mdoc.verifyIssuerSigned: unsupported MSO digestAlgorithm '" + digestAlgName + "'");
184
+ }
185
+ var docType = _mapGet(mso, "docType");
186
+ if (opts.expectedDocType !== undefined && docType !== opts.expectedDocType) {
187
+ throw new MdocError("mdoc/doctype-mismatch", "mdoc.verifyIssuerSigned: MSO docType '" + docType + "' does not match expectedDocType");
188
+ }
189
+
190
+ // validityInfo window (fail closed on malformed dates).
191
+ var vi = _mapGet(mso, "validityInfo");
192
+ if (!(vi instanceof Map) && (!vi || typeof vi !== "object")) {
193
+ throw new MdocError("mdoc/malformed", "mdoc.verifyIssuerSigned: MSO has no validityInfo");
194
+ }
195
+ var nowMs = at.getTime();
196
+ var validFromMs = _validityMs(_mapGet(vi, "validFrom"), "validFrom");
197
+ var validUntilMs = _validityMs(_mapGet(vi, "validUntil"), "validUntil");
198
+ if (nowMs < validFromMs) throw new MdocError("mdoc/not-yet-valid", "mdoc.verifyIssuerSigned: credential not yet valid");
199
+ if (nowMs > validUntilMs) throw new MdocError("mdoc/expired", "mdoc.verifyIssuerSigned: credential validity has passed");
200
+
201
+ // Match every disclosed element's digest against the MSO. The digest
202
+ // covers the full Tag-24 IssuerSignedItemBytes (ISO 18013-5 §9.1.2.5).
203
+ var valueDigests = _mapGet(mso, "valueDigests");
204
+ var out = {};
205
+ if (nameSpaces instanceof Map) {
206
+ var nsNames = Array.from(nameSpaces.keys());
207
+ for (var ni = 0; ni < nsNames.length; ni += 1) {
208
+ var ns = nsNames[ni];
209
+ var items = nameSpaces.get(ns);
210
+ var nsDigests = _mapGet(valueDigests, ns);
211
+ if (!Array.isArray(items) || !(nsDigests instanceof Map)) {
212
+ throw new MdocError("mdoc/malformed", "mdoc.verifyIssuerSigned: namespace '" + ns + "' has no matching valueDigests");
213
+ }
214
+ out[ns] = {};
215
+ var seen = Object.create(null); // dup-elementIdentifier guard (proto-safe)
216
+ for (var ii = 0; ii < items.length; ii += 1) {
217
+ var item = items[ii];
218
+ if (!(item instanceof cbor.Tag) || item.tag !== TAG_ENCODED_CBOR || !Buffer.isBuffer(item.value)) {
219
+ throw new MdocError("mdoc/malformed", "mdoc.verifyIssuerSigned: IssuerSignedItem is not a Tag-24 byte string");
220
+ }
221
+ var itemBytes = cbor.encode(new cbor.Tag(TAG_ENCODED_CBOR, item.value));
222
+ var digest = nodeCrypto.createHash(digestNode).update(itemBytes).digest();
223
+ var inner = cbor.decode(item.value, decodeOpts);
224
+ var digestID = _mapGet(inner, "digestID");
225
+ var expected = nsDigests.get(digestID);
226
+ if (!Buffer.isBuffer(expected) || !bCrypto.timingSafeEqual(digest, expected)) {
227
+ throw new MdocError("mdoc/digest-mismatch",
228
+ "mdoc.verifyIssuerSigned: disclosed element (digestID " + digestID + ", namespace " + ns + ") does not match the MSO");
229
+ }
230
+ // Refuse a duplicate elementIdentifier within a namespace — two
231
+ // signed values for one element is ambiguous; fail closed rather
232
+ // than silently keep the last.
233
+ var elementId = _mapGet(inner, "elementIdentifier");
234
+ if (seen[elementId]) {
235
+ throw new MdocError("mdoc/duplicate-element",
236
+ "mdoc.verifyIssuerSigned: namespace '" + ns + "' has duplicate elementIdentifier '" + elementId + "'");
237
+ }
238
+ seen[elementId] = true;
239
+ out[ns][elementId] = _mapGet(inner, "elementValue");
240
+ }
241
+ }
242
+ }
243
+
244
+ // Optional issuer chain + validity at the asserted time.
245
+ if (opts.trustAnchorsPem !== undefined && opts.trustAnchorsPem !== null) {
246
+ var anchors = typeof opts.trustAnchorsPem === "string" ? [opts.trustAnchorsPem] : opts.trustAnchorsPem;
247
+ if (!Array.isArray(anchors) || anchors.length === 0 ||
248
+ !anchors.every(function (a) { return typeof a === "string" && a.length > 0; })) {
249
+ throw new MdocError("mdoc/bad-trust-anchors", "mdoc.verifyIssuerSigned: trustAnchorsPem must be a non-empty PEM string or array");
250
+ }
251
+ _verifyChain(chain, anchors, at);
252
+ }
253
+
254
+ return {
255
+ docType: docType,
256
+ version: _mapGet(mso, "version"),
257
+ digestAlgorithm: digestAlgName,
258
+ validityInfo: { validFrom: new Date(validFromMs), validUntil: new Date(validUntilMs) },
259
+ namespaces: out,
260
+ signerCert: signerCert.toString(),
261
+ alg: verified.alg,
262
+ };
263
+ }
264
+
265
+ // Verify the leaf (chain[0]) chains to a supplied anchor and every cert
266
+ // is valid at `at`. Intermediates in the x5chain are consulted.
267
+ function _verifyChain(chainDer, anchorsPem, at) {
268
+ var anchors = anchorsPem.map(function (p) { return new nodeCrypto.X509Certificate(p); });
269
+ var pool = chainDer.map(function (d) { return new nodeCrypto.X509Certificate(d); });
270
+ var current = pool[0];
271
+ var atMs = at.getTime();
272
+ var steps = 0;
273
+ while (steps <= pool.length + 1) {
274
+ _assertValidAt(current, atMs);
275
+ for (var a = 0; a < anchors.length; a += 1) {
276
+ if (_issued(anchors[a], current)) { _assertValidAt(anchors[a], atMs); return; }
277
+ if (current.fingerprint256 === anchors[a].fingerprint256) return;
278
+ }
279
+ var parent = null;
280
+ for (var p = 0; p < pool.length; p += 1) {
281
+ if (pool[p].fingerprint256 !== current.fingerprint256 && _issued(pool[p], current)) { parent = pool[p]; break; }
282
+ }
283
+ if (!parent) {
284
+ throw new MdocError("mdoc/untrusted-chain", "mdoc.verifyIssuerSigned: issuer certificate does not chain to a supplied trust anchor");
285
+ }
286
+ current = parent;
287
+ steps += 1;
288
+ }
289
+ throw new MdocError("mdoc/chain-loop", "mdoc.verifyIssuerSigned: certificate chain did not terminate");
290
+ }
291
+ function _issued(issuer, subject) {
292
+ try { return subject.checkIssued(issuer) && subject.verify(issuer.publicKey); }
293
+ catch (_e) { return false; }
294
+ }
295
+ function _assertValidAt(cert, atMs) {
296
+ if (atMs < cert.validFromDate.getTime() || atMs > cert.validToDate.getTime()) {
297
+ throw new MdocError("mdoc/cert-expired", "mdoc.verifyIssuerSigned: certificate '" + cert.subject + "' is not valid at the asserted time");
298
+ }
299
+ }
300
+
301
+ module.exports = {
302
+ verifyIssuerSigned: verifyIssuerSigned,
303
+ DIGEST_ALGS: DIGEST_ALGS,
304
+ MdocError: MdocError,
305
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/core",
3
- "version": "0.12.39",
3
+ "version": "0.12.41",
4
4
  "description": "The Node framework that owns its stack.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
package/sbom.cdx.json CHANGED
@@ -2,10 +2,10 @@
2
2
  "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.5",
5
- "serialNumber": "urn:uuid:a7d5bcb5-4579-407d-b2ac-9baa683fb8f4",
5
+ "serialNumber": "urn:uuid:ba982f6c-2fa2-4cc3-b5e7-739e41e6697e",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-05-25T03:32:36.788Z",
8
+ "timestamp": "2026-05-25T05:54:16.448Z",
9
9
  "lifecycles": [
10
10
  {
11
11
  "phase": "build"
@@ -19,14 +19,14 @@
19
19
  }
20
20
  ],
21
21
  "component": {
22
- "bom-ref": "@blamejs/core@0.12.39",
22
+ "bom-ref": "@blamejs/core@0.12.41",
23
23
  "type": "application",
24
24
  "name": "blamejs",
25
- "version": "0.12.39",
25
+ "version": "0.12.41",
26
26
  "scope": "required",
27
27
  "author": "blamejs contributors",
28
28
  "description": "The Node framework that owns its stack.",
29
- "purl": "pkg:npm/%40blamejs/core@0.12.39",
29
+ "purl": "pkg:npm/%40blamejs/core@0.12.41",
30
30
  "properties": [],
31
31
  "externalReferences": [
32
32
  {
@@ -54,7 +54,7 @@
54
54
  "components": [],
55
55
  "dependencies": [
56
56
  {
57
- "ref": "@blamejs/core@0.12.39",
57
+ "ref": "@blamejs/core@0.12.41",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]