@blamejs/pki 0.4.7 → 0.4.8

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
@@ -4,6 +4,16 @@ All notable changes to `@blamejs/pki` are documented here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this
5
5
  project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## v0.4.8 — 2026-08-08
8
+
9
+ A stored android-safetynet WebAuthn attestation can be re-verified in full -- the signature, the registration binding, and the certificate chain -- behind an opt-in and against a root the caller supplies.
10
+
11
+ ### Added
12
+
13
+ - pki.webauthn.verify verifies the android-safetynet attestation format, which it previously refused as unsupported. Enable it with opts.verifySafetyNetJws and supply the Google root(s) to anchor the chain to as opts.safetyNetRoots -- both are required, and with either missing the call is refused rather than falling back to a weaker check. The format is off by default and this library bundles no root, because the service that produced these statements is retired and choosing a trust anchor on a caller's behalf is not this library's decision to make. A caller who does not enable it sees the same result as before.
14
+ - Every binding the specification states is checked, and each failure names which one: the response must be a three-part JWS whose algorithm is RS256, its signature must verify under the certificate in its own header, its nonce must match this registration's authenticator data and client data, the certificate must be issued to attest.android.com, and the chain must validate to one of the supplied roots. The algorithm is pinned rather than read from the token, so a statement cannot select its own verification algorithm. The hostname is matched exactly against the certificate's subject alternative name, falling back to its common name only when it carries no alternative name at all -- a name merely ending in attest.android.com does not pass. The chain goes through full path validation, so an expired or otherwise non-conforming certificate cannot pass on a signature alone. On success the result reports attestation type Basic with the embedded chain as its trust path.
15
+ - Device-integrity signals in the response -- whether the device passed the compatibility test suite, the reported timestamp, the requesting package -- are deliberately not gated on, because the specification does not make them part of attestation verification. They remain relying-party policy.
16
+
7
17
  ## v0.4.7 — 2026-08-08
8
18
 
9
19
  One certificate now renders one distinguished-name string whichever parser read it -- a C509 certificate's subject and issuer strings joined their components without the separating space every other parser in the toolkit uses.
package/lib/constants.js CHANGED
@@ -297,6 +297,15 @@ var LIMITS = {
297
297
  // terminates but exhausts memory. This matches PATH_MAX_CERTS: a chain longer than the path
298
298
  // validator will ever accept has nothing to offer, so refusing it at the decoder is free.
299
299
  TLS_CERT_MAX_ENTRIES: 100,
300
+ // A WebAuthn android-safetynet attestation statement carries the SafetyNet response as a JWS
301
+ // compact serialization: two small JSON objects plus a signature, with the certificate chain
302
+ // inline in the header. Real ones run a few kilobytes. The cap bounds the text decode before the
303
+ // string is materialized, so an oversized statement is refused rather than allocated (CWE-770).
304
+ SAFETYNET_JWS_MAX_BYTES: BYTES.kib(64),
305
+ // One x5c entry is a single DER certificate; PATH_MAX_CERT_BYTES is the ceiling the path
306
+ // validator already applies to any certificate it will accept, and an entry above it could not
307
+ // chain even if it decoded.
308
+ SAFETYNET_CERT_MAX_BYTES: BYTES.kib(64),
300
309
  // ACME challenge token entropy floor (RFC 8555 sec. 8, errata 6950): >= 128
301
310
  // bits of base64url is >= 22 characters. A shorter token is refused before use.
302
311
  ACME_TOKEN_MIN_CHARS: 22,
package/lib/webauthn.js CHANGED
@@ -8,8 +8,8 @@
8
8
  * @intro Trust evaluation of a W3C WebAuthn (Level 3) / passkey attestation: parse
9
9
  * the attestation object + authenticatorData, decode the COSE credential public
10
10
  * key, and verify each defined attestation-statement format (packed, tpm,
11
- * android-key, apple, fido-u2f, none) -- the attestation-statement signature and
12
- * each format's structural bindings. The attestation CBOR is decoded by the strict,
11
+ * android-key, apple, fido-u2f, none, and android-safetynet behind an opt-in) --
12
+ * the attestation-statement signature and each format's structural bindings. The attestation CBOR is decoded by the strict,
13
13
  * fail-closed `pki.cbor` codec (WebAuthn keys are CTAP2-canonical), the signature by
14
14
  * `pki.webcrypto`. Chaining the returned x5c trust path to a caller-pinned root via
15
15
  * `pki.path.validate` is the caller's step: this module verifies the statement, not
@@ -31,6 +31,9 @@ var webcrypto = require("./webcrypto");
31
31
  var constants = require("./constants");
32
32
  var validator = require("./validator-all");
33
33
  var edwardsPoint = require("./edwards-point");
34
+ var guard = require("./guard-all");
35
+ var jose = require("./jose");
36
+ var pathValidate = require("./path-validate");
34
37
  var nodeCrypto = require("crypto");
35
38
 
36
39
  var WebauthnError = frameworkError.WebauthnError;
@@ -517,6 +520,122 @@ var VERIFIERS = {
517
520
  });
518
521
  },
519
522
 
523
+ // android-safetynet (WebAuthn 8.5): the attStmt carries a SafetyNet JWS ("response") whose payload
524
+ // binds a nonce to this registration and whose x5c header chains to a Google root.
525
+ //
526
+ // OFF BY DEFAULT, and anchored only by the caller. Google retired the SafetyNet Attestation API, so
527
+ // nothing mints these any more -- the surviving use is a relying party re-checking attestations it
528
+ // stored years ago. Enabling a format whose producer is gone, against a root this library chose,
529
+ // would widen what every caller trusts for no live benefit; so the caller opts in AND supplies the
530
+ // root. With the opt off the verdict is byte-identical to the one this format had before the arm
531
+ // existed. There is no bundled root and no trust-on-first-use.
532
+ "android-safetynet": function (att, clientDataHash, opts) {
533
+ opts = opts || {};
534
+ if (opts.verifySafetyNetJws !== true) {
535
+ if (opts.verifySafetyNetJws !== undefined && typeof opts.verifySafetyNetJws !== "boolean") {
536
+ throw _err("webauthn/bad-input", "opts.verifySafetyNetJws must be a boolean");
537
+ }
538
+ throw _err("webauthn/unsupported-format", "attestation statement format 'android-safetynet' is not supported");
539
+ }
540
+ var roots = opts.safetyNetRoots;
541
+ if (!Array.isArray(roots) || roots.length === 0) {
542
+ throw _err("webauthn/safetynet-no-root", "verifying an android-safetynet attestation requires opts.safetyNetRoots -- the Google root(s) to anchor the x5c chain to; this library bundles none (WebAuthn 8.5)");
543
+ }
544
+ if (opts.time !== undefined) guard.time.assertValid(opts.time, WebauthnError, "webauthn/bad-input", "opts.time");
545
+
546
+ // 8.5 attStmt syntax: safetynetStmtFormat = { ver: text, response: bytes }. `ver` is READ but
547
+ // never gated on -- 8.5 states it is reserved for future use.
548
+ _requireAttShape(att.attStmt, ["ver", "response"], ["ver", "response"]);
549
+ _attRead(att.attStmt, "ver", cbor.read.textString, "a text string");
550
+ var responseBytes = _attRead(att.attStmt, "response", cbor.read.byteString, "a byte string");
551
+ if (!responseBytes.length) throw _err("webauthn/bad-att-stmt", "the android-safetynet response is empty");
552
+
553
+ // RFC 7515 sec. 3.1 Compact Serialization: exactly three base64url segments.
554
+ var segs = guard.text.decode(responseBytes, constants.LIMITS.SAFETYNET_JWS_MAX_BYTES, WebauthnError, "webauthn/bad-att-stmt", "the android-safetynet response").split(".");
555
+ if (segs.length !== 3) throw _err("webauthn/bad-att-stmt", "the android-safetynet response is not a three-part JWS compact serialization (RFC 7515 sec. 3.1)");
556
+ var header, payload, sigBytes;
557
+ try {
558
+ header = jose.parseJson(jose.base64url.decode(segs[0]));
559
+ payload = jose.parseJson(jose.base64url.decode(segs[1]));
560
+ sigBytes = Buffer.from(jose.base64url.decode(segs[2]));
561
+ } catch (e) { throw _err("webauthn/bad-att-stmt", "the android-safetynet response is not a decodable JWS", e); }
562
+ // A JWS segment must decode to a JSON OBJECT. `null`, a number, a string and an array are all
563
+ // valid JSON, so the parse succeeds and every later field read would be a raw TypeError escaping
564
+ // this module's typed contract -- the caller's error handling would never see a webauthn/* code.
565
+ if (!_isPlainObject(header) || !_isPlainObject(payload)) {
566
+ throw _err("webauthn/bad-att-stmt", "the android-safetynet JWS header and payload must each be a JSON object");
567
+ }
568
+
569
+ // Pin the algorithm rather than reading it from the token: an attacker-chosen alg is the JWS
570
+ // algorithm-confusion class, and SafetyNet only ever signed RS256.
571
+ if (header.alg !== "RS256") throw _err("webauthn/unsupported-algorithm", "the android-safetynet JWS alg must be RS256, got " + JSON.stringify(header.alg));
572
+ if (!Array.isArray(header.x5c) || header.x5c.length === 0) {
573
+ throw _err("webauthn/bad-att-stmt", "the android-safetynet JWS header carries no x5c certificate chain (RFC 7515 sec. 4.1.6)");
574
+ }
575
+ // x5c entries are STANDARD base64 (RFC 7515 sec. 4.1.6), not base64url like the segments.
576
+ var chain = header.x5c.map(function (entry, i) {
577
+ if (typeof entry !== "string") throw _err("webauthn/bad-att-stmt", "the android-safetynet x5c entry " + i + " is not a string");
578
+ var der;
579
+ try { der = guard.encoding.base64(entry, constants.LIMITS.SAFETYNET_CERT_MAX_BYTES, WebauthnError, "webauthn/bad-att-stmt", "an android-safetynet x5c entry"); }
580
+ catch (e) { throw _err("webauthn/bad-att-stmt", "the android-safetynet x5c entry " + i + " is not canonical base64", e); }
581
+ try { return x509.parse(der); }
582
+ catch (e) { throw _err("webauthn/bad-att-cert", "the android-safetynet x5c entry " + i + " is not a decodable certificate", e); }
583
+ });
584
+ var leaf = chain[0];
585
+
586
+ // 8.5 bullet 3: nonce == STANDARD Base64 of SHA-256(authenticatorData || clientDataHash). Note
587
+ // standard base64 (+/=), NOT base64url -- and the digest is over the raw concatenation.
588
+ var wantNonce = _sha("sha256", Buffer.concat([att.authDataBytes, clientDataHash])).toString("base64");
589
+ if (typeof payload.nonce !== "string" || !guard.crypto.constantTimeEqual(Buffer.from(payload.nonce, "utf8"), Buffer.from(wantNonce, "utf8"))) {
590
+ throw _err("webauthn/safetynet-nonce-mismatch", "the android-safetynet nonce does not bind this authenticatorData and clientDataHash (WebAuthn 8.5)");
591
+ }
592
+
593
+ // 8.5 bullet 4 (via the SafetyNet documentation): the response must come from the SafetyNet
594
+ // service, which is established by the leaf being issued to attest.android.com AND the chain
595
+ // validating to a Google root. The hostname alone proves nothing until the chain is anchored.
596
+ if (!_safetyNetHostnameOk(leaf)) {
597
+ throw _err("webauthn/safetynet-bad-hostname", "the android-safetynet x5c leaf is not issued to attest.android.com (WebAuthn 8.5)");
598
+ }
599
+
600
+ // The device-integrity signals are NOT part of the 8.5 verification procedure -- its five bullets
601
+ // never mention them -- so gating the attestation verdict on them would invent a requirement the
602
+ // specification does not state. They are relying-party policy, so they are surfaced on the result
603
+ // for a caller to act on, and enforced here only when the caller explicitly asks. A caller that
604
+ // asks and finds them missing or false gets a refusal, never a silent pass.
605
+ var signals = {
606
+ ctsProfileMatch: payload.ctsProfileMatch, basicIntegrity: payload.basicIntegrity,
607
+ timestampMs: payload.timestampMs, apkPackageName: payload.apkPackageName,
608
+ apkCertificateDigestSha256: payload.apkCertificateDigestSha256, advice: payload.advice,
609
+ };
610
+ if (opts.requireCtsProfileMatch === true && signals.ctsProfileMatch !== true) {
611
+ throw _err("webauthn/safetynet-cts-profile", "the android-safetynet response reports ctsProfileMatch " + JSON.stringify(signals.ctsProfileMatch) + ", and opts.requireCtsProfileMatch demands true");
612
+ }
613
+ if (opts.requireCtsProfileMatch !== undefined && typeof opts.requireCtsProfileMatch !== "boolean") {
614
+ throw _err("webauthn/bad-input", "opts.requireCtsProfileMatch must be a boolean");
615
+ }
616
+
617
+ return _verifySig(-257, sigBytes, leaf.subjectPublicKeyInfo.bytes,
618
+ Buffer.from(segs[0] + "." + segs[1], "ascii"), _err).then(function (ok) {
619
+ if (!ok) throw _err("webauthn/verify-failed", "the android-safetynet JWS signature does not verify under the x5c leaf key");
620
+ // WHEN to judge the chain. These attestations are historical by construction -- the service is
621
+ // retired -- so a leaf that was valid when the response was signed is routinely expired now,
622
+ // and judging it against the current clock would refuse every genuine stored registration.
623
+ // The response carries its own signing time, and by this point that value is covered by the
624
+ // signature just verified under the leaf, so it is authenticated rather than caller-asserted.
625
+ // Precedence: an explicit opts.time (the caller knows when the registration happened) beats
626
+ // the signed timestamp, which beats now (a response that carries no usable timestamp).
627
+ var at = opts.time !== undefined ? opts.time
628
+ : (typeof payload.timestampMs === "number" && isFinite(payload.timestampMs) && payload.timestampMs > 0
629
+ ? new Date(payload.timestampMs) : undefined);
630
+ return _safetyNetChainTrusted(chain, roots, at);
631
+ }).then(function () {
632
+ // 8.5 bullet 5: attestation type Basic, trust path x5c.
633
+ var res = _result("android-safetynet", "Basic", chain, att);
634
+ res.safetyNet = signals;
635
+ return res;
636
+ });
637
+ },
638
+
520
639
  // none (WebAuthn 8.7): the authenticator provides no attestation. attStmt MUST be
521
640
  // an empty map; there is no statement to verify, so the result carries no trust
522
641
  // path. The credential public key still binds via authenticatorData (AT flag).
@@ -530,6 +649,71 @@ var VERIFIERS = {
530
649
  },
531
650
  };
532
651
 
652
+ // A decoded JSON value that is safe to read named members off. JSON.parse yields null, numbers,
653
+ // strings and arrays too, and a member read on any of those would leave this module's typed error
654
+ // contract as a raw TypeError.
655
+ function _isPlainObject(v) { return !!v && typeof v === "object" && !Array.isArray(v); }
656
+
657
+ // WebAuthn 8.5 (via the SafetyNet documentation): the JWS leaf is issued to attest.android.com.
658
+ // Checked on the SAN dNSName entries first -- the name a TLS-style certificate is actually issued
659
+ // to -- falling back to the commonName only when the certificate carries no SAN at all, the way a
660
+ // hostname match has been specified since RFC 6125. Compared case-insensitively (a DNS name is
661
+ // case-insensitive) and exactly: no wildcard, no suffix match, so attest.android.com.evil.test
662
+ // cannot pass.
663
+ function _safetyNetHostnameOk(leaf) {
664
+ var want = "attest.android.com";
665
+ // Decoded through the SAME shared pkix extension decoder every other format here uses, so the
666
+ // general-name parse cannot drift from the rest of the toolkit.
667
+ var san = _decodeExt(leaf, "subjectAltName");
668
+ var entries = san && Array.isArray(san.value) ? san.value : [];
669
+ var dns = entries.filter(function (gn) { return gn && gn.type === "dNSName" && typeof gn.value === "string"; });
670
+ // A SAN carrying dNSName entries is authoritative: the commonName is not consulted at all.
671
+ if (dns.length) return dns.some(function (gn) { return gn.value.toLowerCase() === want; });
672
+ // rdns is a sequence of RDNs, each a set of attribute/value pairs -- hence the nested walk.
673
+ return leaf.subject.rdns.some(function (rdn) {
674
+ return rdn.some(function (atv) {
675
+ return atv.name === "commonName" && typeof atv.value === "string" && atv.value.toLowerCase() === want;
676
+ });
677
+ });
678
+ }
679
+
680
+ // WebAuthn 8.5 (via the SafetyNet documentation): the x5c chain must validate to a Google root the
681
+ // CALLER supplied. Every anchor is tried because a caller may hold several Google roots across a
682
+ // rotation; the first that validates wins, and if none does the attestation is refused. The chain
683
+ // goes through the full path validator rather than a signature-only walk, so an expired, revoked-by-
684
+ // policy, or otherwise non-conforming intermediate cannot slip past on a signature alone.
685
+ function _safetyNetChainTrusted(chain, roots, time) {
686
+ var ordered = chain.slice().reverse(); // path.validate takes anchor-adjacent first
687
+ var when = time === undefined ? new Date() : time;
688
+ var attempts = roots.map(function (root, i) {
689
+ return function () {
690
+ var anchorCert;
691
+ try { anchorCert = Buffer.isBuffer(root) || typeof root === "string" ? x509.parse(root) : root; }
692
+ catch (e) { throw _err("webauthn/bad-input", "opts.safetyNetRoots[" + i + "] is not a decodable certificate", e); }
693
+ if (!anchorCert || !anchorCert.subject || !anchorCert.subjectPublicKeyInfo) {
694
+ throw _err("webauthn/bad-input", "opts.safetyNetRoots[" + i + "] is not a certificate");
695
+ }
696
+ // An x5c chain conventionally carries the root as its last entry. The anchor is supplied
697
+ // separately and is what establishes trust, so drop a trailing self-issued certificate that
698
+ // IS this anchor rather than validating it against itself as a path element.
699
+ var path = ordered.slice();
700
+ if (path.length > 1 && guard.name.dnEqual(path[0].subject, anchorCert.subject) &&
701
+ guard.name.dnEqual(path[0].issuer, path[0].subject)) {
702
+ path = path.slice(1);
703
+ }
704
+ return pathValidate.validate(path, {
705
+ time: when,
706
+ trustAnchor: { name: anchorCert.subject, publicKey: anchorCert.subjectPublicKeyInfo.bytes, algorithm: anchorCert.signatureAlgorithm.oid },
707
+ }).then(function (r) { return !!(r && r.valid); }, function () { return false; });
708
+ };
709
+ });
710
+ return attempts.reduce(function (p, next) {
711
+ return p.then(function (done) { return done ? true : next(); });
712
+ }, Promise.resolve(false)).then(function (trusted) {
713
+ if (!trusted) throw _err("webauthn/safetynet-cert-untrusted", "the android-safetynet x5c chain does not validate to any supplied root (opts.safetyNetRoots)");
714
+ });
715
+ }
716
+
533
717
  // `chain` is the x5c order (leaf-first); trustPath is surfaced in pki.path.validate
534
718
  // order (anchor-adjacent first, target/leaf last) so the caller passes it straight
535
719
  // to the path validator without re-ordering. The input array is not mutated.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.4.7",
3
+ "version": "0.4.8",
4
4
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
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:a7694ebc-a9fb-440b-ac11-b024d67aae76",
5
+ "serialNumber": "urn:uuid:4a21ad89-1930-46c8-811e-74c422b23db6",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-08-08T20:51:12.787Z",
8
+ "timestamp": "2026-08-08T23:49:55.172Z",
9
9
  "lifecycles": [
10
10
  {
11
11
  "phase": "build"
@@ -19,14 +19,14 @@
19
19
  }
20
20
  ],
21
21
  "component": {
22
- "bom-ref": "@blamejs/pki@0.4.7",
22
+ "bom-ref": "@blamejs/pki@0.4.8",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.4.7",
25
+ "version": "0.4.8",
26
26
  "scope": "required",
27
27
  "author": "blamejs contributors",
28
28
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
29
- "purl": "pkg:npm/%40blamejs/pki@0.4.7",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.4.8",
30
30
  "properties": [],
31
31
  "externalReferences": [
32
32
  {
@@ -54,7 +54,7 @@
54
54
  "components": [],
55
55
  "dependencies": [
56
56
  {
57
- "ref": "@blamejs/pki@0.4.7",
57
+ "ref": "@blamejs/pki@0.4.8",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]