@blamejs/pki 0.6.22 → 0.6.24

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,22 @@ 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.6.24 — 2026-09-02
8
+
9
+ A caller option of an unexpected type now yields the module's typed error, not a native TypeError.
10
+
11
+ ### Fixed
12
+
13
+ - An option of an unexpected type passed to a build, sign, export, or enrollment verb (a BigInt, an object with no primitive form, or one whose Symbol.toPrimitive throws) is reported as the module's typed bad-input error instead of a native TypeError leaking from a diagnostic string, a lookup-table key, a Date conversion, or a numeric coercion. This covers the timestamp, OCSP, CMP, CMC, SCEP, EST, ACME, PKCS#12, S/MIME, attribute-certificate, HPKE, Certificate Transparency, and Sigstore APIs.
14
+
15
+ ## v0.6.23 — 2026-09-01
16
+
17
+ The SCEP client can carry a PKIOperation over HTTP GET for a CA that does not support POST.
18
+
19
+ ### Added
20
+
21
+ - pki.scep.enroll / renew / getCert / getCrl accept httpMethod: "POST" (default) or "GET". Under "GET" the client sends the PKIOperation message as GET SCEPPATH?operation=PKIOperation&message=<base64-CMS> with no body (RFC 8894 sec. 4.1), for a CA that does not advertise POST support. POST stays the default and the recommended transport; a bad httpMethod is refused with scep/bad-input.
22
+
7
23
  ## v0.6.22 — 2026-09-01
8
24
 
9
25
  pki.acme.client gains scheduleRenewal, the RFC 9773 auto-sleeping certificate-renewal loop.
package/README.md CHANGED
@@ -222,7 +222,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
222
222
  | `pki.schema.cmp` | CMP messages (RFC 9810): the header (version, sender and recipient including the anonymous NULL-DN, nonces, transaction id, general info), the 27-arm body (certificate requests via the CRMF parser, an encrypted certificate's EnvelopedData via CMS, response / revocation / confirmation / error / support / polling arms structural, the rest raw), and the exact `headerBytes` and `bodyBytes` slices an external verifier reconstructs the protected part from. The CMP-before-OCSP dispatch order is enforced Fail-closed — `parse`, `pemDecode`, `pemEncode` |
223
223
  | `pki.schema.csrattrs` | EST CSR Attributes (`CsrAttrs`, RFC 8951 §3.5 / RFC 9908) — the `AttrOrOID` items a server sends to shape an enrollment: bare OIDs, attributes with raw values, and decoded views of the RFC 9908 meaningful types (extension requests, EC and RSA key-type conventions, the certification-request-info template). Unknown types are surfaced raw; structure and the RFC 9908 semantic MUSTs are fail-closed — `parse` |
224
224
  | `pki.est` | Enrollment over Secure Transport (RFC 7030 / 8951 / 9908 / 7616). The client verbs `cacerts`, `simpleenroll`, `simplereenroll`, `serverkeygen`, `csrattrs`, and `fullcmc` drive the RFC 7030 flow over `pki.transport` (inject your own via `opts.transport`, or take the fail-closed default): HTTPS only, an explicit trust anchor required, same-origin redirects followed while a downgrade or loop is refused, a 202 Retry-After surfaced but never slept, HTTP Basic or Digest (RFC 7616, SHA-256 / SHA-512-256; MD5 and no-qop refused by default) answered only after the server is authenticated, and the issued certificate chosen by public-key match. `serverkeygen` requests a server-generated key, cleartext or an opaque CMS EnvelopedData, with encryption bound to the CSR's key-identifier attribute over a confidentiality-bearing cipher. `csrattrs` fetches the CA's RFC 9908 attributes policy. `fullcmc` (§4.3) carries a CMC Full PKI Request and reduces the CA's answer through `pki.cmc.verify` to one terminal outcome, refusing a response that fails to echo the transaction and nonce the request carried, or that covers a key the request never asked for; a certs-only reply to a bound request is refused rather than read as an issuance. Under the verbs sit the transport-agnostic codecs they compose: the RFC 8951 base64 transfer codec (which ignores Content-Transfer-Encoding), the `multipart/mixed` splitter, the certs-only and serverkeygen response validators over CMS, the enroll-attribute builders, and the HTTP response classifier — `transferDecode`/`transferEncode`, `parseCertsOnly`, `splitMultipartMixed`, `parseServerKeygenResponse`, `findIssuedCert`, `classifyResponse`, `paths`, and the builders |
225
- | `pki.scep` | SCEP pkiMessage codec (RFC 8894), the client side of Simple Certificate Enrollment. `build(spec)` assembles a request: a `PKCSReq` or `RenewalReq` wraps a PKCS#10 certification request, whose own proof-of-possession it verifies first; a `CertPoll` wraps an IssuerAndSubject naming the issuing CA and the request subject; and a `GetCert` or `GetCRL` wraps an IssuerAndSerialNumber naming a certificate by its issuer and a positive serial of at most 20 octets. It encrypts the messageData to the CA as the inner EnvelopedData (`pkcsPKIEnvelope`, AES-128-CBC), and signs that under the transaction attributes RFC 8894 §3.2 defines, a messageType, a caller-unique transactionId, and a 16-byte senderNonce. The recipient CA certificate must assert `keyEncipherment`. `build` also issues the CA-side `CertRep` response (§3.3.2): a SUCCESS envelopes a certs-only SignedData of the issued certificate (or the CRL for a GetCRL) to the requester and signs it under the CA key, while a FAILURE (carrying a `failInfo`) or a PENDING omits the pkcsPKIEnvelope and is signed detached, each echoing the request's senderNonce as `recipientNonce`. `parse(bytes, opts?)` reads a `PKCSReq`, `RenewalReq`, `CertPoll`, `GetCert`, `GetCRL`, or `CertRep` back (a messageType outside the RFC 8894 registry is refused): it verifies the outer signature first and refuses a message whose signature does not check, so the transaction attributes it returns come only from a verified signer, never alongside a false verdict. Because a valid signature only proves self-consistency with the embedded certificate, pass `opts.signerCert` to authenticate a CA response against the CA certificate you hold (a public-key mismatch is refused, `signerAuthenticated` reports the result); a caller that omits it gets a crypto-only verdict and must authenticate the surfaced `signerCert` itself. It maps the messageType, pkiStatus, failInfo, and the nonces from their RFC 8894 enumerants and refuses an unknown one; given `recipientKey` it decrypts the `pkcsPKIEnvelope` to the messageData, and given `expectedSenderNonce` it refuses a response whose recipientNonce does not echo it. It reads a CA's CertRep in full. `getCACaps(baseUrl, opts?)`, `getCACert(baseUrl, opts?)`, `getNextCACert(baseUrl, opts)`, `enroll(baseUrl, opts)`, `renew(baseUrl, opts)`, `getCert(baseUrl, opts)`, and `getCrl(baseUrl, opts)` carry that codec to a live CA over HTTP (RFC 8894 §4) through an injectable transport (`pki.transport.https` by default): `getCACaps` reports the CA's advertised capabilities and never lowers the client's algorithm choice on the unauthenticated response, `getCACert` pins the CA certificate to an out-of-band `expectedFingerprint` a returned certificate must match, `getNextCACert` fetches the CA's next (rollover) certificate and verifies the SignedData response against the current CA certificate (`caCertificate`) before returning it, refusing a response signed by any other key, and `enroll` and `renew` POST a PKCSReq or RenewalReq, authenticate the CertRep against the CA certificate and its nonce echo, select the issued certificate by public-key match, throw on a FAILURE with the CA's failInfo, and poll a PENDING response with CertPoll requests until the CA answers or a bounded poll-count and total-wait budget is spent. `getCert` and `getCrl` retrieve an already-issued certificate or a CA CRL by issuer and serial number, authenticated the same way; RFC 8894 §2.6, §2.7, and §3.3.4 recommend these queries only where HTTP certificate-store access (RFC 4387), LDAP, or a CRL distribution point is unavailable, so prefer those where a CA offers them. GET-carried PKIOperation and HTTP proxy authentication are not yet built — `build`, `parse`, `parseCapabilities`, `getCACaps`, `getCACert`, `getNextCACert`, `enroll`, `renew`, `getCert`, `getCrl` |
225
+ | `pki.scep` | SCEP pkiMessage codec (RFC 8894), the client side of Simple Certificate Enrollment. `build(spec)` assembles a request: a `PKCSReq` or `RenewalReq` wraps a PKCS#10 certification request, whose own proof-of-possession it verifies first; a `CertPoll` wraps an IssuerAndSubject naming the issuing CA and the request subject; and a `GetCert` or `GetCRL` wraps an IssuerAndSerialNumber naming a certificate by its issuer and a positive serial of at most 20 octets. It encrypts the messageData to the CA as the inner EnvelopedData (`pkcsPKIEnvelope`, AES-128-CBC), and signs that under the transaction attributes RFC 8894 §3.2 defines, a messageType, a caller-unique transactionId, and a 16-byte senderNonce. The recipient CA certificate must assert `keyEncipherment`. `build` also issues the CA-side `CertRep` response (§3.3.2): a SUCCESS envelopes a certs-only SignedData of the issued certificate (or the CRL for a GetCRL) to the requester and signs it under the CA key, while a FAILURE (carrying a `failInfo`) or a PENDING omits the pkcsPKIEnvelope and is signed detached, each echoing the request's senderNonce as `recipientNonce`. `parse(bytes, opts?)` reads a `PKCSReq`, `RenewalReq`, `CertPoll`, `GetCert`, `GetCRL`, or `CertRep` back (a messageType outside the RFC 8894 registry is refused): it verifies the outer signature first and refuses a message whose signature does not check, so the transaction attributes it returns come only from a verified signer, never alongside a false verdict. Because a valid signature only proves self-consistency with the embedded certificate, pass `opts.signerCert` to authenticate a CA response against the CA certificate you hold (a public-key mismatch is refused, `signerAuthenticated` reports the result); a caller that omits it gets a crypto-only verdict and must authenticate the surfaced `signerCert` itself. It maps the messageType, pkiStatus, failInfo, and the nonces from their RFC 8894 enumerants and refuses an unknown one; given `recipientKey` it decrypts the `pkcsPKIEnvelope` to the messageData, and given `expectedSenderNonce` it refuses a response whose recipientNonce does not echo it. It reads a CA's CertRep in full. `getCACaps(baseUrl, opts?)`, `getCACert(baseUrl, opts?)`, `getNextCACert(baseUrl, opts)`, `enroll(baseUrl, opts)`, `renew(baseUrl, opts)`, `getCert(baseUrl, opts)`, and `getCrl(baseUrl, opts)` carry that codec to a live CA over HTTP (RFC 8894 §4) through an injectable transport (`pki.transport.https` by default): `getCACaps` reports the CA's advertised capabilities and never lowers the client's algorithm choice on the unauthenticated response, `getCACert` pins the CA certificate to an out-of-band `expectedFingerprint` a returned certificate must match, `getNextCACert` fetches the CA's next (rollover) certificate and verifies the SignedData response against the current CA certificate (`caCertificate`) before returning it, refusing a response signed by any other key, and `enroll` and `renew` POST a PKCSReq or RenewalReq, authenticate the CertRep against the CA certificate and its nonce echo, select the issued certificate by public-key match, throw on a FAILURE with the CA's failInfo, and poll a PENDING response with CertPoll requests until the CA answers or a bounded poll-count and total-wait budget is spent. `getCert` and `getCrl` retrieve an already-issued certificate or a CA CRL by issuer and serial number, authenticated the same way; RFC 8894 §2.6, §2.7, and §3.3.4 recommend these queries only where HTTP certificate-store access (RFC 4387), LDAP, or a CRL distribution point is unavailable, so prefer those where a CA offers them. A PKIOperation goes over HTTP POST by default; `httpMethod: "GET"` carries it base64-encoded in the URL query for a legacy CA that accepts only GET (RFC 8894 §4.1). HTTP proxy authentication is not yet built — `build`, `parse`, `parseCapabilities`, `getCACaps`, `getCACert`, `getNextCACert`, `enroll`, `renew`, `getCert`, `getCrl` |
226
226
  | `pki.transport` | The shared, fail-closed `node:https` transport the enrollment clients drive. `pki.transport.https(defaults)` returns a `transport(request) → { status, headers, body, tls }`, where `tls` carries the negotiated `protocol`, `cipher`, and raw `peerCertificate`. This is the toolkit's only socket choke point: an explicit trust anchor (or an opt-in to the system store) is required, `rejectUnauthorized` is always on, TLS is floored at 1.2, the response body is capped while it streams, and a stalled socket times out. The EST, ACME, and CMP clients reuse it verbatim. If you inject your own transport, return `tls` too: `pki.est.serverkeygen` asserts the negotiated cipher can protect the delivered private key, and a transport that reports no cipher is trusted rather than refused, so omitting the field silently skips that check — `https` |
227
227
  | `pki.jose` | Flattened JWS (RFC 7515) and JWK thumbprints (RFC 7638). `sign` and `verify` run a Flattened JWS against declarative profiles (ACME outer, EAB inner, keyChange inner) that carry the required and forbidden header rules as data. `base64url` is the strict RFC 4648 §5 codec, rejecting padding, non-alphabet characters, and non-canonical trailing bits. `parseJson` is a bounded reader that refuses duplicate members at any depth. `thumbprint` is the RFC 7638 / 8037 / 9964 canonical digest. The algorithm registry binds each `alg` to its key type (ES/RS/PS/EdDSA/ML-DSA), leaving no code path for `alg:none`, an RS256→HS256 key confusion, or an all-zero ECDSA signature; `assertPublicJwk` refuses a JWK carrying private material, so an exported private key is never published. `opts.key` names the key a message must be signed under and governs: where the profile also permits an embedded header `jwk`, the two must be the same key — compared as RFC 7638 thumbprints, so member order cannot make equal keys differ — and a disagreement is refused rather than resolved in the message's favor. `keySource` reports which key answered, since a signature checked against a key you named is a different claim from one checked against the key the message carried — `sign`, `verify`, `base64url`, `parseJson`, `thumbprint`, `assertPublicJwk` |
228
228
  | `pki.acme` | ACME (RFC 8555 / 8737 / 8738 / 9773). `client(directoryUrl, opts)` is a stateful client driving a live CA directory over `pki.transport`: `newAccount`, `newOrder`, `newAuthz`, `getOrder`, `getAuthorization`, `getChallenge`, `respondToChallenge`, `finalize`, `pollOrder`, `pollAuthorization`, and `downloadCertificate` walk the issuance flow, with `newAuthz` pre-authorizing a single identifier (§7.4.1) and `downloadCertificate` binding the issued certificate to the order — its key, its identifiers, or both; at least one is required by default and the result reports `boundToKey` / `boundToIdentifiers` — before choosing among alternate chains (`Link rel="alternate"`, §7.4.2, via a `selectChain` predicate bounded by `maxAlternates`). `revokeCert` (account-key or certificate-key signed), `keyChange`, `updateAccount` (change the account contacts, §7.3.2), `listOrders` (the account's orders list, following the §7.1.2.1 `Link rel="next"` pagination bounded by a page cap and confined to the orders origin), `deactivateAccount`, `deactivateAuthorization`, `renewalInfo` (ARI), `renewalWindow` (the RFC 9773 §4.2/4.3 renewal decision), and `scheduleRenewal` (the §4.1 auto-sleeping renewal loop that sleeps until the selected instant and refetches until it is time to renew, stopping at the certificate's notAfter) complete the lifecycle. Every URL is HTTPS only, an explicit trust anchor is required, each request carries a fresh single-use nonce with a bounded badNonce retry (and, when `opts.resignKeys` supplies caller-approved alternative account-key algorithms, a bounded RFC 8555 §6.2 badSignatureAlgorithm re-sign that the CA's advertised list can only filter, never widen, so it cannot force a weaker algorithm), reads are POST-as-GET, polling is bounded and sleeps on a Retry-After via an injectable sleeper capped by a poll count and a total-wait budget, and every response body is size-capped. The transport is injectable via `opts.transport`. Over the message layer it composes resource-object validators (closed status enums, conditional-required fields, unknown fields ignored), the three §7.1.6 state machines, the request builders (newAccount with External Account Binding, newOrder with `replaces`, finalize with a CSR identifier-set match and account-key-reuse rejection, challenge responses, deactivation, revokeCert in both key modes, the keyChange nested JWS, POST-as-GET), the http-01 / dns-01 / tls-alpn-01 challenge computations, the dns and ip identifier validators, and the ARI certID with serial sign-padding preserved — `client`, `validate`, `identify`, `assertTransition`, the builders, `keyAuthorization`, `http01`, `dns01`, `tlsAlpn01Extension`, `verifyTlsAlpn01`, `ariCertId` |
package/lib/acme.js CHANGED
@@ -432,11 +432,11 @@ var TRANSITIONS = intrinsic.assign(intrinsic.create(null), {
432
432
  * pki.acme.assertTransition("order", "pending", "ready"); // ok
433
433
  */
434
434
  function assertTransition(kind, from, to) {
435
- var table = TRANSITIONS[kind];
436
- if (!table) throw E("acme/bad-input", "unknown resource kind " + JSON.stringify(kind));
435
+ var table = TRANSITIONS[guard.text.keyOf(kind)];
436
+ if (!table) throw E("acme/bad-input", "unknown resource kind " + guard.text.showValue(kind));
437
437
  if (from === to) return;
438
- var allowed = _hasOwn(table, from) ? table[from] : null;
439
- if (!allowed || allowed.indexOf(to) === -1) throw E("acme/bad-transition", "illegal " + kind + " transition " + JSON.stringify(from) + " -> " + JSON.stringify(to) + " (RFC 8555 sec. 7.1.6)");
438
+ var allowed = _hasOwn(table, guard.text.keyOf(from)) ? table[guard.text.keyOf(from)] : null;
439
+ if (!allowed || allowed.indexOf(to) === -1) throw E("acme/bad-transition", "illegal " + kind + " transition " + guard.text.showValue(from) + " -> " + guard.text.showValue(to) + " (RFC 8555 sec. 7.1.6)");
440
440
  }
441
441
 
442
442
 
@@ -500,7 +500,7 @@ function validateProblem(obj) {
500
500
  function validate(kind, obj) {
501
501
  if (kind === "problem") return validateProblem(obj);
502
502
  if (kind === "renewalInfo") return validateRenewalInfo(obj);
503
- if (!SPECS[kind]) throw E("acme/bad-input", "unknown ACME object kind " + JSON.stringify(kind));
503
+ if (!SPECS[guard.text.keyOf(kind)]) throw E("acme/bad-input", "unknown ACME object kind " + guard.text.showValue(kind));
504
504
  return _validate(kind, obj);
505
505
  }
506
506
 
@@ -720,7 +720,7 @@ async function verifyTlsAlpn01(certDer, token, accountJwk, identifier) {
720
720
  var sanIp = _ipBytesToText(entry.value);
721
721
  if (sanIp === null || sanIp !== identifier.value) throw E("acme/bad-tlsalpn", "the iPAddress SAN does not match the ip identifier (RFC 8738 sec. 6)");
722
722
  } else {
723
- throw E("acme/bad-tlsalpn", "unsupported tls-alpn-01 identifier type " + JSON.stringify(identifier.type));
723
+ throw E("acme/bad-tlsalpn", "unsupported tls-alpn-01 identifier type " + guard.text.showValue(identifier.type));
724
724
  }
725
725
  }
726
726
 
@@ -846,7 +846,7 @@ async function externalAccountBinding(o) {
846
846
  jose.assertPublicJwk(o.accountJwk);
847
847
  if (!_isString(o.kid)) throw E("acme/bad-input", "externalAccountBinding requires the CA-issued kid");
848
848
  var alg = o.alg || "HS256";
849
- if (!_HMAC_HASH[alg]) throw E("acme/bad-input", "an EAB inner JWS must use an HS* MAC algorithm (sec. 7.3.4), not " + JSON.stringify(alg));
849
+ if (!_HMAC_HASH[guard.text.keyOf(alg)]) throw E("acme/bad-input", "an EAB inner JWS must use an HS* MAC algorithm (sec. 7.3.4), not " + guard.text.showValue(alg));
850
850
  var key = o.macKey;
851
851
  if (Buffer.isBuffer(key)) {
852
852
  try { key = await subtle.importKey("raw", key, { name: "HMAC", hash: _HMAC_HASH[alg] }, false, ["sign"]); }
@@ -934,7 +934,7 @@ async function _jwkToSpki(jwk) {
934
934
  else if (jwk.kty === "RSA") importAlg = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };
935
935
  else if (jwk.kty === "OKP") importAlg = { name: jwk.crv };
936
936
  else if (jwk.kty === "AKP") importAlg = { name: jwk.alg };
937
- else throw E("acme/bad-key", "unsupported account key type " + JSON.stringify(jwk && jwk.kty));
937
+ else throw E("acme/bad-key", "unsupported account key type " + guard.text.showValue(jwk && jwk.kty));
938
938
  var key;
939
939
  try { key = await subtle.importKey("jwk", jwk, importAlg, true, []); }
940
940
  catch (e) { throw E("acme/bad-key", "the account key JWK could not be imported to derive its SubjectPublicKeyInfo", e); }
@@ -61,7 +61,7 @@ var EXT_META = {
61
61
  };
62
62
  var REQUIRED_CRITICALITY = {};
63
63
  Object.keys(EXT_META).forEach(function (k) { REQUIRED_CRITICALITY[O(EXT_META[k].name)] = EXT_META[k].critical; });
64
- var CLASSLIST_BIT = { unmarked: 0, unclassified: 1, restricted: 2, confidential: 3, secret: 4, topSecret: 5 };
64
+ var CLASSLIST_BIT = intrinsic.assign(intrinsic.create(null), { unmarked: 0, unclassified: 1, restricted: 2, confidential: 3, secret: 4, topSecret: 5 });
65
65
 
66
66
  var _tbsNameBytes = pkiBuild.tbsNameField;
67
67
  function _parseCert(cert, what) {
@@ -92,10 +92,10 @@ function _issuerSerialContent(is) {
92
92
  }
93
93
  return Buffer.concat(parts);
94
94
  }
95
- var ODT_CODE = { publicKey: 0, publicKeyCert: 1 };
95
+ var ODT_CODE = intrinsic.assign(intrinsic.create(null), { publicKey: 0, publicKeyCert: 1 });
96
96
  function _objectDigestInfoContent(odi) {
97
97
  if (!odi || typeof odi !== "object" || Buffer.isBuffer(odi)) throw _err("attrcert/bad-input", "objectDigestInfo must be an object");
98
- var code = ODT_CODE[odi.digestedObjectType];
98
+ var code = ODT_CODE[guard.text.keyOf(odi.digestedObjectType)];
99
99
  if (code == null) throw _err("attrcert/bad-input", "objectDigestInfo.digestedObjectType must be 'publicKey' or 'publicKeyCert' (otherObjectTypes is forbidden, RFC 5755 sec. 7.3)");
100
100
  if (!Buffer.isBuffer(odi.objectDigest)) throw _err("attrcert/bad-input", "objectDigestInfo.objectDigest must be a Buffer (the whole-octet digest)");
101
101
  var algName = odi.digestAlgorithm;
@@ -152,8 +152,8 @@ function _encodeClearance(cl) {
152
152
  if (cl.classList != null) {
153
153
  if (!Array.isArray(cl.classList)) throw _err("attrcert/bad-input", "clearance.classList must be an array of class names");
154
154
  var positions = cl.classList.map(function (n) {
155
- var pos = CLASSLIST_BIT[n];
156
- if (pos == null) throw _err("attrcert/bad-input", "unknown clearance class " + JSON.stringify(n));
155
+ var pos = CLASSLIST_BIT[guard.text.keyOf(n)];
156
+ if (pos == null) throw _err("attrcert/bad-input", "unknown clearance class " + guard.text.showValue(n));
157
157
  return pos;
158
158
  });
159
159
  var isDefault = positions.length === 1 && positions[0] === CLASSLIST_BIT.unclassified;
@@ -219,7 +219,7 @@ function _encodeSeqOfTargets(targets) {
219
219
  function _attrSpec(names, tag, label) {
220
220
  if (!Array.isArray(names)) throw _err("attrcert/bad-input", "aaControls." + label + " must be an array of attribute-type OIDs");
221
221
  var oids = names.map(function (n) {
222
- try { return b.oid(O(n) || n); } catch (e) { throw _err("attrcert/bad-input", "aaControls." + label + " contains an invalid object identifier " + JSON.stringify(n), e); }
222
+ try { return b.oid(O(n) || n); } catch (e) { throw _err("attrcert/bad-input", "aaControls." + label + " contains an invalid object identifier " + guard.text.showValue(n), e); }
223
223
  });
224
224
  return b.contextConstructed(tag, Buffer.concat(oids));
225
225
  }
package/lib/cmc-build.js CHANGED
@@ -59,7 +59,7 @@ function makeIdAllocator() {
59
59
  var next = 1;
60
60
  function assertValid(requested, what) {
61
61
  if (typeof requested !== "number" || !Number.isInteger(requested) || requested < 0 || requested > 4294967295) {
62
- throw E("cmc/bad-input", "a bodyPartID must be an integer in 0..4294967295, got " + requested + " (" + what + ")");
62
+ throw E("cmc/bad-input", "a bodyPartID must be an integer in 0..4294967295, got " + guard.text.showValue(requested) + " (" + what + ")");
63
63
  }
64
64
  if (requested === 0) {
65
65
  throw E("cmc/bad-input",
package/lib/cmp-build.js CHANGED
@@ -145,7 +145,7 @@ function _encodeInfoValue(itav) {
145
145
 
146
146
  function _encodeInfoTypeAndValue(itav) {
147
147
  if (!itav || typeof itav !== "object" || Buffer.isBuffer(itav)) throw _err("cmp/bad-info-value", "an InfoTypeAndValue must be an object { infoType, infoValue? }");
148
- if (typeof itav.infoType !== "string" || O(itav.infoType) == null) throw _err("cmp/bad-name", "unknown infoType " + JSON.stringify(itav.infoType));
148
+ if (typeof itav.infoType !== "string" || O(itav.infoType) == null) throw _err("cmp/bad-name", "unknown infoType " + guard.text.showValue(itav.infoType));
149
149
  var children = [b.oid(O(itav.infoType))];
150
150
  var val = _encodeInfoValue(itav);
151
151
  if (val != null) children.push(val);
@@ -192,7 +192,7 @@ function _reqIdInt(v, code, what) { return guard.range.authoredInteger(v, _err,
192
192
  function _encodeFailInfo(names, code) {
193
193
  if (!Array.isArray(names)) throw _err(code, "statusInfo.failInfo must be an array of PKIFailureInfo bit names");
194
194
  return b.namedBitString(names.map(function (n) {
195
- if (typeof n !== "string" || FAIL_INFO_INDEX[n] === undefined) throw _err(code, "unknown PKIFailureInfo bit " + JSON.stringify(n));
195
+ if (typeof n !== "string" || FAIL_INFO_INDEX[n] === undefined) throw _err(code, "unknown PKIFailureInfo bit " + guard.text.showValue(n));
196
196
  return FAIL_INFO_INDEX[n];
197
197
  }));
198
198
  }
@@ -215,7 +215,7 @@ function _encodeCertStatus(cs, state) {
215
215
  ];
216
216
  if (cs.statusInfo != null) children.push(_encodePkiStatusInfo(cs.statusInfo, "cmp/bad-cert-status"));
217
217
  if (cs.hashAlg != null) {
218
- if (typeof cs.hashAlg !== "string" || !CERT_CONF_HASH_ALGS[cs.hashAlg]) throw _err("cmp/bad-name", "certConf hashAlg must be a hash algorithm (sha256 / sha384 / sha512 / sha3-256 / sha3-512 / sha1); got " + JSON.stringify(cs.hashAlg));
218
+ if (typeof cs.hashAlg !== "string" || !CERT_CONF_HASH_ALGS[cs.hashAlg]) throw _err("cmp/bad-name", "certConf hashAlg must be a hash algorithm (sha256 / sha384 / sha512 / sha3-256 / sha3-512 / sha1); got " + guard.text.showValue(cs.hashAlg));
219
219
  children.push(b.explicit(0, _algIdNoParams(cs.hashAlg)));
220
220
  state.usesCmp2021 = true;
221
221
  }
@@ -266,7 +266,7 @@ function _encodeCrlEntryDetails(spec) {
266
266
  guard.identifier.assertKnownKeys(spec, KNOWN_CRL_ENTRY_DETAIL_KEYS, _err, "cmp/bad-rev-req", "unknown crlEntryDetails field ");
267
267
  var reason = spec.reason;
268
268
  if (reason != null && (typeof reason !== "string" || !_hasOwn(CRL_REASON_BY_NAME, reason))) {
269
- throw _err("cmp/bad-rev-req", "unknown CRLReason " + _stringify(reason) + " (RFC 5280 sec. 5.3.1)");
269
+ throw _err("cmp/bad-rev-req", "unknown CRLReason " + guard.text.showValue(reason) + " (RFC 5280 sec. 5.3.1)");
270
270
  }
271
271
  var code = reason == null ? 0 : CRL_REASON_BY_NAME[reason];
272
272
  return b.sequence([_b.ext(O("reasonCode"), false, b.enumerated(_bigInt(code)))]);
@@ -300,7 +300,8 @@ function buildCrlStatusList(spec) {
300
300
  }
301
301
  var status = [source], askedInstant = null, asked = spec.thisUpdate;
302
302
  if (asked != null) {
303
- askedInstant = guard.time.instantOf(asked, _err, "cmp/bad-input", "crlUpdate.thisUpdate");
303
+ guard.time.assertValid(asked, _err, "cmp/bad-input", "crlUpdate.thisUpdate");
304
+ askedInstant = guard.time.instantOf(asked);
304
305
  _push(status, b.raw(_b.timeDer(new _Date(askedInstant), "crlUpdate.thisUpdate")));
305
306
  }
306
307
  return {
@@ -484,7 +485,7 @@ function _encodeBody(bodySpec, key, opts) {
484
485
  var keys = Object.keys(bodySpec);
485
486
  if (keys.length !== 1) throw _err("cmp/bad-input", "message.body must have exactly one arm, got " + keys.length);
486
487
  var arm = keys[0];
487
- if (!KNOWN_BODY_KEYS[arm]) throw _err("cmp/bad-input", "unknown body arm " + JSON.stringify(arm));
488
+ if (!KNOWN_BODY_KEYS[guard.text.keyOf(arm)]) throw _err("cmp/bad-input", "unknown body arm " + guard.text.showValue(arm));
488
489
  var tag = BODY_TAG[arm], state = { usesCmp2021: false };
489
490
 
490
491
  if (CRMF_BODY[arm]) {
@@ -574,7 +575,7 @@ function _resolveProtection(opts) {
574
575
  var m = opts.mac;
575
576
  if (!m || typeof m !== "object" || Buffer.isBuffer(m)) throw _err("cmp/bad-input", "opts.mac must be an object { secret, salt?, iterationCount?, prf?, keyLength? }");
576
577
  guard.identifier.assertKnownKeys(m, KNOWN_MAC_KEYS, _err, "cmp/bad-input", "unknown opts.mac field ");
577
- if (m.algorithm != null && m.algorithm !== "pbmac1") throw _err("cmp/unsupported-algorithm", "opts.mac.algorithm " + JSON.stringify(m.algorithm) + " is not supported (v1 ships pbmac1; passwordBasedMac is deferred)");
578
+ if (m.algorithm != null && m.algorithm !== "pbmac1") throw _err("cmp/unsupported-algorithm", "opts.mac.algorithm " + guard.text.showValue(m.algorithm) + " is not supported (v1 ships pbmac1; passwordBasedMac is deferred)");
578
579
  var secret = m.secret;
579
580
  if (typeof secret !== "string" || !secret) {
580
581
  if (!Buffer.isBuffer(secret) || !secret.length) throw _err("cmp/bad-input", "opts.mac.secret must be a non-empty string or Buffer");
@@ -788,7 +789,7 @@ function _transfer(url, message, opts) {
788
789
  var der = _cmpMessageDer(message);
789
790
  var parsedUrl;
790
791
  try { parsedUrl = new URL(String(url)); }
791
- catch (e) { throw _err("cmp/bad-url", "the CMP URL did not parse: " + String(url), e); }
792
+ catch (e) { throw _err("cmp/bad-url", "the CMP URL did not parse: " + guard.text.showValue(url), e); }
792
793
  var transport = opts.transport;
793
794
  if (!transport) {
794
795
  var t = opts.tls || {};
@@ -854,7 +855,7 @@ function wellKnownUrl(base, opts) {
854
855
  });
855
856
  var u;
856
857
  try { u = new URL(String(base)); }
857
- catch (e) { throw _err("cmp/bad-url", "the CMP base URL did not parse: " + String(base), e); }
858
+ catch (e) { throw _err("cmp/bad-url", "the CMP base URL did not parse: " + guard.text.showValue(base), e); }
858
859
  if (u.protocol !== "https:" && u.protocol !== "http:") throw _err("cmp/bad-url", "the CMP base URL must be http or https (a well-known URI is authority-rooted over HTTP), got " + u.protocol + ": " + JSON.stringify(String(base)));
859
860
  if (u.search || u.hash) throw _err("cmp/bad-url", "the CMP base URL must not carry a query or fragment component (RFC 9811 sec. 3.4)");
860
861
  if (_strIndexOf(String(base), "\\") !== -1) throw _err("cmp/bad-url", "the CMP base URL must not contain a backslash (WHATWG rewrites it to a path separator): " + JSON.stringify(String(base)));
@@ -752,7 +752,7 @@ function session(opts) {
752
752
  throw _err("cmp/bad-input", "an ir / cr / kur enrollment must submit certTemplate.publicKey -- a session enrolls a client-generated key (a raVerified keyless request or central key generation is not supported)");
753
753
  }
754
754
  if (arms[0] !== "p10cr" && armSpec != null && armSpec.pop != null && armSpec.pop.type != null && armSpec.pop.type !== "signature") {
755
- throw _err("cmp/bad-input", "a session ir / cr / kur proves possession by signing the CRMF proof of possession; a non-signature POP mode (" + JSON.stringify(armSpec.pop.type) + ") is not supported (RFC 4211 sec. 4)");
755
+ throw _err("cmp/bad-input", "a session ir / cr / kur proves possession by signing the CRMF proof of possession; a non-signature POP mode (" + guard.text.showValue(armSpec.pop.type) + ") is not supported (RFC 4211 sec. 4)");
756
756
  }
757
757
  if (isMac && arms[0] !== "p10cr" && (armSpec == null || armSpec.key == null)) {
758
758
  throw _err("cmp/bad-input", "a MAC-protected ir / cr / kur must carry the requested key's private half as `key` for the CRMF proof of possession -- a signature session reuses opts.key, but a PBMAC1 session has no signing key, so the request would carry no proof of possession (RFC 4211 sec. 4)");
@@ -829,7 +829,7 @@ function session(opts) {
829
829
  throw _err("cmp/bad-input", "revoke(request) names the certificate by EXACTLY ONE of certificate (the certificate itself) or certDetails ({ issuer, serialNumber })");
830
830
  }
831
831
  if (reasonArg != null && (typeof reasonArg !== "string" || !CRL_REASON_NAMES[reasonArg])) {
832
- throw _err("cmp/bad-input", "revoke request.reason must be a CRLReason name (RFC 5280 sec. 5.3.1); got " + JSON.stringify(reasonArg));
832
+ throw _err("cmp/bad-input", "revoke request.reason must be a CRLReason name (RFC 5280 sec. 5.3.1); got " + guard.text.showValue(reasonArg));
833
833
  }
834
834
  if (certificateArg != null) {
835
835
  var target;
@@ -58,7 +58,7 @@ function _gcmParams(nonce, icvLen) {
58
58
 
59
59
  function _assertKeyIdentifier(form) {
60
60
  if (form != null && form !== "issuerAndSerial" && form !== "issuerAndSerialNumber" && form !== "subjectKeyIdentifier") {
61
- throw _err("cms/bad-input", "unsupported keyIdentifier " + JSON.stringify(form) + " (use \"issuerAndSerial\" or \"subjectKeyIdentifier\")");
61
+ throw _err("cms/bad-input", "unsupported keyIdentifier " + guard.text.showValue(form) + " (use \"issuerAndSerial\" or \"subjectKeyIdentifier\")");
62
62
  }
63
63
  }
64
64
  function _rid(cert, form) {
@@ -92,7 +92,7 @@ function _oaepParams(hashName) {
92
92
  async function _buildKtri(cek, cert, opts) {
93
93
  _assertKeyUsage(cert, "keyEncipherment", "ktri");
94
94
  var hashName = opts.oaepHash || "sha256";
95
- if (!OAEP_HASH[hashName]) throw _err("cms/bad-input", "unsupported oaepHash " + JSON.stringify(hashName));
95
+ if (!OAEP_HASH[guard.text.keyOf(hashName)]) throw _err("cms/bad-input", "unsupported oaepHash " + guard.text.showValue(hashName));
96
96
  var pub = await subtle.importKey("spki", cert.subjectPublicKeyInfo.bytes, { name: "RSA-OAEP", hash: OAEP_HASH[hashName] }, false, ["encrypt"]);
97
97
  var encryptedKey = Buffer.from(await subtle.encrypt({ name: "RSA-OAEP" }, pub, cek));
98
98
  var rid = _rid(cert, opts.keyIdentifier);
@@ -283,7 +283,7 @@ function _pwriWrapIv(kek, cek, iv) {
283
283
  }
284
284
 
285
285
  var PRF_HASH = intrinsic.assign(intrinsic.create(null), { hmacWithSHA1: "SHA-1", hmacWithSHA256: "SHA-256", hmacWithSHA384: "SHA-384", hmacWithSHA512: "SHA-512" });
286
- function _prfHash(prf) { if (!PRF_HASH[prf]) throw _err("cms/bad-input", "unsupported pwri prf " + JSON.stringify(prf)); return PRF_HASH[prf]; }
286
+ function _prfHash(prf) { if (!PRF_HASH[guard.text.keyOf(prf)]) throw _err("cms/bad-input", "unsupported pwri prf " + guard.text.showValue(prf)); return PRF_HASH[guard.text.keyOf(prf)]; }
287
287
 
288
288
  var _PWRI_KEYS = { password: 1, iterations: 1, prf: 1, salt: 1 };
289
289
  var _KEKRI_KEYS = { kek: 1, kekId: 1 };
@@ -385,8 +385,8 @@ function encrypt(content, recipients, opts) {
385
385
  async function _encryptImpl(content, recipients, opts) {
386
386
  opts = opts || {};
387
387
  var algName = opts.contentEncryptionAlgorithm || "aes-256-gcm";
388
- var ca = CONTENT_ALGS[algName];
389
- if (!ca) throw _err("cms/bad-input", "unsupported contentEncryptionAlgorithm " + JSON.stringify(algName));
388
+ var ca = CONTENT_ALGS[guard.text.keyOf(algName)];
389
+ if (!ca) throw _err("cms/bad-input", "unsupported contentEncryptionAlgorithm " + guard.text.showValue(algName));
390
390
  guard.identifier.assertKnownKeys(opts, ca.aead ? _ENCRYPT_OPTS_AEAD : _ENCRYPT_OPTS_CBC, _err, "cms/bad-input",
391
391
  function (k) {
392
392
  return "pki.cms.encrypt has an unknown option " + JSON.stringify(k) +
@@ -577,8 +577,8 @@ async function authenticate(content, recipients, opts) {
577
577
  });
578
578
  var contentBytes = guard.bytes.view(content, CmsError, "cms/bad-input", "content");
579
579
  var macName = opts.macAlgorithm || "hmac-sha256";
580
- var mac = MAC_ALGS[macName];
581
- if (!mac) throw _err("cms/bad-input", "unsupported macAlgorithm " + JSON.stringify(macName) + " (hmac-sha256/384/512)");
580
+ var mac = MAC_ALGS[guard.text.keyOf(macName)];
581
+ if (!mac) throw _err("cms/bad-input", "unsupported macAlgorithm " + guard.text.showValue(macName) + " (hmac-sha256/384/512)");
582
582
  if (!Array.isArray(recipients) || !recipients.length) throw _err("cms/bad-input", "at least one recipient is required (RFC 5652 sec. 9.1)");
583
583
  var contentType = opts.contentType || "data";
584
584
  if (contentType !== "data" && !withAttrs) throw _err("cms/bad-input", "AuthenticatedData with a non-data contentType requires authenticated attributes (RFC 5652 sec. 9.1)");
@@ -594,7 +594,7 @@ async function authenticate(content, recipients, opts) {
594
594
  var digestAlgTagged = null, authAttrsDer = null, preimage;
595
595
  if (withAttrs) {
596
596
  var digestName = opts.digestAlgorithm || mac.node;
597
- if (!SUPPORTED_DIGEST[digestName]) throw _err("cms/bad-input", "unsupported digestAlgorithm " + JSON.stringify(digestName) + " (sha256/384/512)");
597
+ if (!SUPPORTED_DIGEST[guard.text.keyOf(digestName)]) throw _err("cms/bad-input", "unsupported digestAlgorithm " + guard.text.showValue(digestName) + " (sha256/384/512)");
598
598
  var mdDigest = nodeCrypto.createHash(digestName).update(contentBytes).digest();
599
599
  var pairs = [
600
600
  b.sequence([b.oid(O("contentType")), b.setOf([b.oid(O(contentType))])]),
package/lib/crl-sign.js CHANGED
@@ -55,7 +55,7 @@ var EXT_DECODERS = pkix.certExtensionDecoders(NS).byOid;
55
55
  var OID_SKI = O("subjectKeyIdentifier");
56
56
 
57
57
  var CRL_REASON = constants.NAMES.CRL_REASON;
58
- var REASON_BY_NAME = {};
58
+ var REASON_BY_NAME = intrinsic.create(null);
59
59
  Object.keys(CRL_REASON).forEach(function (v) { REASON_BY_NAME[CRL_REASON[v]] = Number(v); });
60
60
 
61
61
  var KNOWN_CRL_EXT_KEYS = { authorityKeyIdentifier: 1, issuingDistributionPoint: 1, deltaCRLIndicator: 1, freshestCRL: 1, authorityInfoAccess: 1 };
@@ -115,7 +115,7 @@ function _resolveReason(reason, isDelta) {
115
115
  var codeNum;
116
116
  if (typeof reason === "number") codeNum = reason;
117
117
  else if (typeof reason === "string") {
118
- if (!_hasOwn(REASON_BY_NAME, reason)) throw _err("crl/bad-reason-code", "unknown CRLReason " + JSON.stringify(reason));
118
+ if (!_hasOwn(REASON_BY_NAME, guard.text.keyOf(reason))) throw _err("crl/bad-reason-code", "unknown CRLReason " + guard.text.showValue(reason));
119
119
  codeNum = REASON_BY_NAME[reason];
120
120
  } else throw _err("crl/bad-reason-code", "reason must be a CRLReason name or number");
121
121
  if (!_hasOwn(CRL_REASON, String(codeNum))) throw _err("crl/bad-reason-code", "undefined or reserved CRLReason " + codeNum + " (RFC 5280 sec. 5.3.1)");
package/lib/crmf-sign.js CHANGED
@@ -146,9 +146,9 @@ function _encodeCertId(id) {
146
146
  return b.sequence([_b.encodeGeneralName(id.issuer), _b.serialInteger(id.serialNumber)]);
147
147
  }
148
148
 
149
- var POPO_PRIVKEY_TAGS = { keyEncipherment: 2, keyAgreement: 3 };
149
+ var POPO_PRIVKEY_TAGS = intrinsic.assign(intrinsic.create(null), { keyEncipherment: 2, keyAgreement: 3 });
150
150
  var SUBSEQUENT_MESSAGE = { encrCert: 0n, challengeResp: 1n };
151
- var DEPRECATED_POPO_METHOD = { thisMessage: "encryptedKey", dhMAC: "agreeMAC" };
151
+ var DEPRECATED_POPO_METHOD = intrinsic.assign(intrinsic.create(null), { thisMessage: "encryptedKey", dhMAC: "agreeMAC" });
152
152
 
153
153
  function _encKeyWithID(privateKeyDer, identifier) {
154
154
  var idNode;
@@ -158,12 +158,12 @@ function _encKeyWithID(privateKeyDer, identifier) {
158
158
  }
159
159
 
160
160
  function _buildPopoPrivKey(pop, mode, template) {
161
- var outerTag = POPO_PRIVKEY_TAGS[mode];
161
+ var outerTag = POPO_PRIVKEY_TAGS[guard.text.keyOf(mode)];
162
162
  var method = pop && pop.method;
163
163
  if (typeof method !== "string") {
164
164
  throw _err("crmf/bad-popo", "a " + mode + " proof of possession requires pop.method ('subsequentMessage' or 'encryptedKey')");
165
165
  }
166
- if (_hasOwn(DEPRECATED_POPO_METHOD, method)) {
166
+ if (_hasOwn(DEPRECATED_POPO_METHOD, guard.text.keyOf(method))) {
167
167
  throw _err("crmf/bad-popo", "the " + method + " proof of possession is deprecated by RFC 4211 sec. 4.2 in favor of " +
168
168
  DEPRECATED_POPO_METHOD[method] + "; a reader still accepts it, a new message should not carry it");
169
169
  }
@@ -185,7 +185,7 @@ function _buildPopoPrivKey(pop, mode, template) {
185
185
  return b.explicit(outerTag, b.implicit(1, b.integer(SUBSEQUENT_MESSAGE[which])));
186
186
  }
187
187
  if (method !== "encryptedKey") {
188
- throw _err("crmf/bad-popo", "unsupported POPOPrivKey method " + JSON.stringify(method) +
188
+ throw _err("crmf/bad-popo", "unsupported POPOPrivKey method " + guard.text.showValue(method) +
189
189
  " (supported: 'subsequentMessage', 'encryptedKey')");
190
190
  }
191
191
  return _buildEncryptedKeyPop(pop, outerTag, template);
@@ -287,7 +287,7 @@ function _bareEnvelopedData(contentInfoDer) {
287
287
  }
288
288
 
289
289
  function _assertPopArmKeys(pop, mode) {
290
- var arm = _hasOwn(POPO_PRIVKEY_TAGS, mode) ? pop.method : mode;
290
+ var arm = _hasOwn(POPO_PRIVKEY_TAGS, guard.text.keyOf(mode)) ? pop.method : mode;
291
291
  var allowed = (typeof arm === "string" && _hasOwn(POP_KEYS_BY_ARM, arm))
292
292
  ? POP_KEYS_BY_ARM[arm]
293
293
  : { type: 1, method: 1 };
@@ -306,9 +306,9 @@ function _buildProofOfPossession(pop, certReqDer, template, signingKey, opts) {
306
306
  if (!(pop && pop.raVerified === true)) throw _err("crmf/bad-popo", "raVerified must be explicitly opted into (pop: { type: 'raVerified', raVerified: true }) -- a requester does not normally assert it (RFC 4211 sec. 4)");
307
307
  return b.implicit(0, b.nullValue());
308
308
  }
309
- if (_hasOwn(POPO_PRIVKEY_TAGS, mode)) return _buildPopoPrivKey(pop, mode, template);
309
+ if (_hasOwn(POPO_PRIVKEY_TAGS, guard.text.keyOf(mode))) return _buildPopoPrivKey(pop, mode, template);
310
310
  if (mode !== "signature") {
311
- throw _err("crmf/bad-popo", "unsupported proof-of-possession type " + JSON.stringify(mode) +
311
+ throw _err("crmf/bad-popo", "unsupported proof-of-possession type " + guard.text.showValue(mode) +
312
312
  " (supported: 'signature', 'raVerified', 'keyEncipherment', 'keyAgreement')");
313
313
  }
314
314
  if (signingKey == null) throw _err("crmf/bad-input", "a signature proof of possession requires the requester's private key");
package/lib/ct.js CHANGED
@@ -259,7 +259,7 @@ function reconstructSignedData(entry, sct) {
259
259
  entry = entry || {};
260
260
  var entryType = entry.entryType;
261
261
  if (entryType !== 0 && entryType !== 1) {
262
- throw new CtError("ct/bad-entry-type", "entryType must be x509_entry(0) or precert_entry(1), got " + entryType + " (RFC 6962 sec. 3.1)");
262
+ throw new CtError("ct/bad-entry-type", "entryType must be x509_entry(0) or precert_entry(1), got " + guard.text.showValue(entryType) + " (RFC 6962 sec. 3.1)");
263
263
  }
264
264
  if (!sct || typeof sct.timestamp !== "bigint" || sct.version !== 0) {
265
265
  throw new CtError("ct/bad-input", "reconstructSignedData expects a decoded v1 SCT from parseSctList().scts[]");
package/lib/est.js CHANGED
@@ -552,7 +552,7 @@ function classifyResponse(status, headers, body, opts) {
552
552
  opts = opts || {};
553
553
  _knownOpts(opts, CLASSIFY_OPTS, "classifyResponse");
554
554
  var op = opts.op;
555
- if (op !== undefined && op !== null && CLASSIFIABLE_OPS.indexOf(op) === -1) throw E("est/unsupported-operation", "unrecognized EST operation " + JSON.stringify(op));
555
+ if (op !== undefined && op !== null && CLASSIFIABLE_OPS.indexOf(op) === -1) throw E("est/unsupported-operation", "unrecognized EST operation " + guard.text.showValue(op));
556
556
  var h = {
557
557
  "content-type": _ciHeader(headers, "content-type"),
558
558
  "retry-after": _ciHeader(headers, "retry-after"),
@@ -912,7 +912,7 @@ function _drive(method, url, body, headers, opts, transport, budgets) {
912
912
  function _client(op, method, baseUrl, body, headers, opts) {
913
913
  var base;
914
914
  try { base = new URL(String(baseUrl)); }
915
- catch (e) { throw E("est/bad-url", "the EST base URL did not parse: " + String(baseUrl), e); }
915
+ catch (e) { throw E("est/bad-url", "the EST base URL did not parse: " + guard.text.showValue(baseUrl), e); }
916
916
  if (base.search || base.hash) throw E("est/bad-url", "the EST base URL must not carry a query or fragment component (RFC 7030 sec. 3.2.2)");
917
917
  var url = _parseUrl(paths(baseUrl, { label: opts.label })[op]);
918
918
  var transport = opts.transport;
package/lib/guard-text.js CHANGED
@@ -37,4 +37,17 @@ function decode(input, maxBytes, ErrorClass, spec) {
37
37
  throw new ErrorClass(spec.badInput, spec.label + " expects a string or a byte source (Buffer / TypedArray / DataView / ArrayBuffer)");
38
38
  }
39
39
 
40
- module.exports = intrinsic.freeze({ decode: decode });
40
+ // @enforced-by behavioral -- a safe error-message formatter has no rename-proof code shape; the RED vector (a BigInt or cyclic caller value renders to a typed error, never a native TypeError out of a raw JSON.stringify) is the guard.
41
+ function showValue(v) {
42
+ if (typeof v === "string") return intrinsic.stringify(v);
43
+ if (typeof v === "number" || typeof v === "boolean" || typeof v === "bigint") return intrinsic.String(v);
44
+ if (v === null) return "null";
45
+ return "a value of type " + typeof v;
46
+ }
47
+
48
+ // @enforced-by behavioral -- a coercion-safe property-key narrowing has no rename-proof code shape; the RED vector (a caller value with no primitive coercion, an Object.create(null) or a throwing Symbol.toPrimitive, reaches a table lookup as the typed error, never a native TypeError from the key coercion) is the guard. A string or number passes through; anything else becomes undefined so the lookup misses without coercing the value.
49
+ function keyOf(v) {
50
+ return typeof v === "string" || typeof v === "number" ? v : undefined;
51
+ }
52
+
53
+ module.exports = intrinsic.freeze({ decode: decode, showValue: showValue, keyOf: keyOf });
package/lib/guard-time.js CHANGED
@@ -6,6 +6,7 @@
6
6
  var util = { types: require("./guard-intrinsic").types };
7
7
  var _freeze = require("./guard-intrinsic").freeze;
8
8
  var _isNaN = Number.isNaN;
9
+ var _Date = Date;
9
10
 
10
11
  var _dateGetTime = require("./guard-intrinsic").uncurry(Date.prototype.getTime);
11
12
 
@@ -37,9 +38,17 @@ function isDate(value) {
37
38
  return util.types.isDate(value);
38
39
  }
39
40
 
41
+ // @enforced-by behavioral -- a coercion-safe Date converter has no rename-proof code shape; the RED vector (a caller value with no numeric or string form, a BigInt or a throwing Symbol.toPrimitive, becomes an invalid Date the downstream isNaN check rejects, never a native TypeError out of the Date constructor) is the guard.
42
+ function toDate(value) {
43
+ if (util.types.isDate(value)) return value;
44
+ if (typeof value === "string" || typeof value === "number") return new _Date(value);
45
+ return new _Date(NaN);
46
+ }
47
+
40
48
  module.exports = _freeze({
41
49
  assertValid: assertValid,
42
50
  instantOf: instantOf,
43
51
  isDate: isDate,
52
+ toDate: toDate,
44
53
  within: within,
45
54
  });
package/lib/hpke.js CHANGED
@@ -47,29 +47,29 @@ var HPKE_V1 = Buffer.from("HPKE-v1", "ascii");
47
47
  function L(s) { return Buffer.from(s, "ascii"); }
48
48
 
49
49
 
50
- var KDFS = {
50
+ var KDFS = intrinsic.assign(intrinsic.create(null), {
51
51
  0x0001: { hash: "sha256", Nh: 32 },
52
52
  0x0003: { hash: "sha512", Nh: 64 },
53
- };
54
- var AEADS = {
53
+ });
54
+ var AEADS = intrinsic.assign(intrinsic.create(null), {
55
55
  0x0001: { cipher: "aes-128-gcm", Nk: 16, Nn: 12, Nt: 16 },
56
56
  0x0002: { cipher: "aes-256-gcm", Nk: 32, Nn: 12, Nt: 16 },
57
57
  0x0003: { cipher: "chacha20-poly1305", Nk: 32, Nn: 12, Nt: 16 },
58
58
  0xFFFF: { exportOnly: true, Nn: 12 },
59
- };
60
- var KEMS = {
59
+ });
60
+ var KEMS = intrinsic.assign(intrinsic.create(null), {
61
61
  0x0010: { kind: "ec", curve: "P-256", nodeCurve: "prime256v1", kdf: 0x0001, Nsecret: 32, Npub: 65 },
62
62
  0x0012: { kind: "ec", curve: "P-521", nodeCurve: "secp521r1", kdf: 0x0003, Nsecret: 64, Npub: 133 },
63
63
  0x0020: { kind: "okp", curve: "X25519", oid: "2b656e", kdf: 0x0001, Nsecret: 32, Npub: 32 },
64
64
  0x0021: { kind: "okp", curve: "X448", oid: "2b656f", kdf: 0x0003, Nsecret: 64, Npub: 56 },
65
- };
65
+ });
66
66
 
67
67
  var MODE_BASE = 0x00, MODE_PSK = 0x01, MODE_AUTH = 0x02, MODE_AUTH_PSK = 0x03;
68
68
 
69
- function _idStr(id) { return typeof id === "number" ? "0x" + id.toString(16) : String(id); }
70
- function _kem(id) { var s = KEMS[id]; if (!s) throw _err("hpke/unknown-suite", "unsupported KEM id " + _idStr(id)); return s; }
71
- function _kdf(id) { var s = KDFS[id]; if (!s) throw _err("hpke/unknown-suite", "unsupported KDF id " + _idStr(id)); return s; }
72
- function _aead(id) { var s = AEADS[id]; if (!s) throw _err("hpke/unknown-suite", "unsupported AEAD id " + _idStr(id)); return s; }
69
+ function _idStr(id) { return typeof id === "number" ? "0x" + id.toString(16) : guard.text.showValue(id); }
70
+ function _kem(id) { var s = KEMS[guard.text.keyOf(id)]; if (!s) throw _err("hpke/unknown-suite", "unsupported KEM id " + _idStr(id)); return s; }
71
+ function _kdf(id) { var s = KDFS[guard.text.keyOf(id)]; if (!s) throw _err("hpke/unknown-suite", "unsupported KDF id " + _idStr(id)); return s; }
72
+ function _aead(id) { var s = AEADS[guard.text.keyOf(id)]; if (!s) throw _err("hpke/unknown-suite", "unsupported AEAD id " + _idStr(id)); return s; }
73
73
 
74
74
 
75
75
  function _extract(hash, Nh, salt, ikm) {
@@ -342,7 +342,7 @@ function _mode(opts, keys, who) {
342
342
  });
343
343
  var mode = (opts.mode == null) ? MODE_BASE : opts.mode;
344
344
  if (mode !== MODE_BASE && mode !== MODE_PSK && mode !== MODE_AUTH && mode !== MODE_AUTH_PSK) {
345
- throw _err("hpke/unknown-mode", "unsupported HPKE mode " + JSON.stringify(mode) + " (RFC 9180 sec. 5.1 defines base / psk / auth / auth-psk)");
345
+ throw _err("hpke/unknown-mode", "unsupported HPKE mode " + guard.text.showValue(mode) + " (RFC 9180 sec. 5.1 defines base / psk / auth / auth-psk)");
346
346
  }
347
347
  return mode;
348
348
  }
package/lib/key.js CHANGED
@@ -97,8 +97,9 @@ async function encrypt(privateKey, password, opts) {
97
97
  "`maxIterations` is the decrypt-side cap): ");
98
98
  var der = await _toPrivateKeyDer(privateKey);
99
99
  try { pkcs8.parse(der); } catch (e) { throw _err("key/bad-input", "the private key is not a well-formed PKCS#8 PrivateKeyInfo", e); }
100
+ if (opts.cipher != null && typeof opts.cipher !== "string") throw _err("key/bad-input", "unsupported cipher " + guard.text.showValue(opts.cipher) + " (aes-128-cbc / aes-192-cbc / aes-256-cbc)");
100
101
  var cipherName = CIPHER_NAME[opts.cipher || "aes-256-cbc"];
101
- if (!cipherName) throw _err("key/bad-input", "unsupported cipher " + JSON.stringify(opts.cipher) + " (aes-128-cbc / aes-192-cbc / aes-256-cbc)");
102
+ if (!cipherName) throw _err("key/bad-input", "unsupported cipher " + guard.text.showValue(opts.cipher) + " (aes-128-cbc / aes-192-cbc / aes-256-cbc)");
102
103
  var keyBits = pbes2.CONTENT_KEYBITS[O(cipherName)];
103
104
  var prf = opts.prf || "hmacWithSHA256";
104
105
  var prfNode = pbes2.prfNodeByName(prf, _err, "key");
@@ -218,7 +219,7 @@ async function export_(key, opts) {
218
219
  var fmt = opts.format || "der";
219
220
  if (fmt === "der") return der;
220
221
  if (fmt === "pem") return pkix.pemEncode(der, opts.label || defaultLabel, PemError);
221
- throw _err("key/bad-input", "unsupported format " + JSON.stringify(opts.format) + " (der / pem)");
222
+ throw _err("key/bad-input", "unsupported format " + guard.text.showValue(opts.format) + " (der / pem)");
222
223
  }
223
224
 
224
225
  /**
package/lib/ocsp.js CHANGED
@@ -45,8 +45,8 @@ function O(name) { return oid.byName(name); }
45
45
  function _err(code, message, cause) { return new OcspError(code, message, cause); }
46
46
  function _signE(kind, message, cause) { return new OcspError("ocsp/" + kind, message, cause); }
47
47
 
48
- var HASH_WC = { sha1: "SHA-1", sha256: "SHA-256", sha384: "SHA-384", sha512: "SHA-512" };
49
- var REASON_CODE = {};
48
+ var HASH_WC = Object.assign(Object.create(null), { sha1: "SHA-1", sha256: "SHA-256", sha384: "SHA-384", sha512: "SHA-512" });
49
+ var REASON_CODE = Object.create(null);
50
50
  Object.keys(constants.NAMES.CRL_REASON).forEach(function (k) { REASON_CODE[constants.NAMES.CRL_REASON[k]] = parseInt(k, 10); });
51
51
  var OID_OCSP_NONCE = O("ocspNonce");
52
52
  var OID_OCSP_BASIC = O("ocspBasic");
@@ -84,8 +84,8 @@ function _assertNonce(nonceBytes) {
84
84
  }
85
85
  }
86
86
  function _buildCertID(cert, issuer, hashName) {
87
- var wc = HASH_WC[hashName];
88
- if (!wc) throw _err("ocsp/bad-input", "unsupported CertID hashAlgorithm " + JSON.stringify(hashName) + " (sha1 / sha256 / sha384 / sha512)");
87
+ var wc = HASH_WC[guard.text.keyOf(hashName)];
88
+ if (!wc) throw _err("ocsp/bad-input", "unsupported CertID hashAlgorithm " + guard.text.showValue(hashName) + " (sha1 / sha256 / sha384 / sha512)");
89
89
  return Promise.all([
90
90
  _digest(wc, issuer.subject.bytes),
91
91
  _digest(wc, _keyValue(issuer.subjectPublicKeyInfo.bytes)),
@@ -299,8 +299,8 @@ function _signResponse(responseData, responder, respCert, respCertDer, responder
299
299
  }
300
300
  function _asDate(d) {
301
301
  if (d == null) return null;
302
- var dt = guard.time.isDate(d) ? d : new Date(d);
303
- if (isNaN(guard.time.instantOf(dt))) throw _err("ocsp/bad-input", "an invalid date value " + JSON.stringify(d));
302
+ var dt = guard.time.toDate(d);
303
+ if (isNaN(guard.time.instantOf(dt))) throw _err("ocsp/bad-input", "an invalid date value " + guard.text.showValue(d));
304
304
  return dt;
305
305
  }
306
306
  function _snapshotSignerKey(key, owned) {
@@ -341,8 +341,8 @@ function _certStatusNode(status, opts) {
341
341
  if (typeof status === "object" && status.revoked != null) {
342
342
  var ri = [b.generalizedTime(_asDate(status.revoked))];
343
343
  if (status.revocationReason != null) {
344
- var code = typeof status.revocationReason === "number" ? status.revocationReason : REASON_CODE[status.revocationReason];
345
- if (code == null) throw _err("ocsp/bad-input", "unknown revocationReason " + JSON.stringify(status.revocationReason));
344
+ var code = typeof status.revocationReason === "number" ? status.revocationReason : REASON_CODE[guard.text.keyOf(status.revocationReason)];
345
+ if (code == null) throw _err("ocsp/bad-input", "unknown revocationReason " + guard.text.showValue(status.revocationReason));
346
346
  ri.push(b.explicit(0, b.enumerated(BigInt(code))));
347
347
  }
348
348
  return b.contextConstructed(1, Buffer.concat(ri));
@@ -365,9 +365,9 @@ function _certStatusNode(status, opts) {
365
365
  * @example
366
366
  * var der = pki.ocsp.buildErrorResponse("tryLater");
367
367
  */
368
- var ERROR_STATUS = { malformedRequest: 1, internalError: 2, tryLater: 3, sigRequired: 5, unauthorized: 6 };
368
+ var ERROR_STATUS = Object.assign(Object.create(null), { malformedRequest: 1, internalError: 2, tryLater: 3, sigRequired: 5, unauthorized: 6 });
369
369
  function buildErrorResponse(status) {
370
- var code = ERROR_STATUS[status];
370
+ var code = ERROR_STATUS[guard.text.keyOf(status)];
371
371
  if (code == null) throw _err("ocsp/bad-input", "an error responseStatus must be one of " + Object.keys(ERROR_STATUS).join(" / "));
372
372
  return b.sequence([b.enumerated(BigInt(code))]);
373
373
  }
@@ -1851,7 +1851,7 @@ function resolvePurposeOpts(opts) {
1851
1851
  if (typeof p !== "string" || p.length === 0) throw E("path/bad-input", "validate: opts.requiredEku entries must be non-empty strings");
1852
1852
  if (_startsWithDigit(p)) return guard.identifier.assertCanonicalOid(p, E, "path/bad-input", "validate: opts.requiredEku entry " + JSON.stringify(p));
1853
1853
  var dotted = oid.byName(p);
1854
- if (typeof dotted !== "string") throw E("path/bad-input", "validate: opts.requiredEku entry " + JSON.stringify(p) + " is not a registered OID name");
1854
+ if (typeof dotted !== "string") throw E("path/bad-input", "validate: opts.requiredEku entry " + guard.text.showValue(p) + " is not a registered OID name");
1855
1855
  return dotted;
1856
1856
  });
1857
1857
  }
@@ -1864,7 +1864,7 @@ function resolvePurposeOpts(opts) {
1864
1864
  var cpDotted = guard.identifier.assertCanonicalOid(opts.checkPurpose, E, "path/bad-input", "validate: opts.checkPurpose");
1865
1865
  checkPurpose = oid.name(cpDotted) || cpDotted;
1866
1866
  } else {
1867
- if (typeof oid.byName(opts.checkPurpose) !== "string") throw E("path/bad-input", "validate: opts.checkPurpose " + JSON.stringify(opts.checkPurpose) + " is not a registered OID name");
1867
+ if (typeof oid.byName(opts.checkPurpose) !== "string") throw E("path/bad-input", "validate: opts.checkPurpose " + guard.text.showValue(opts.checkPurpose) + " is not a registered OID name");
1868
1868
  checkPurpose = opts.checkPurpose;
1869
1869
  }
1870
1870
  }
package/lib/pbes2.js CHANGED
@@ -43,7 +43,7 @@ function assertSalt(salt, E, prefix) {
43
43
  return salt;
44
44
  }
45
45
 
46
- function prfNodeByName(prf, E, prefix) { if (!PRF_NODE_BY_NAME[prf]) throw E(prefix + "/bad-input", "unsupported prf " + JSON.stringify(prf)); return PRF_NODE_BY_NAME[prf]; }
46
+ function prfNodeByName(prf, E, prefix) { if (typeof prf !== "string" || !PRF_NODE_BY_NAME[prf]) throw E(prefix + "/bad-input", "unsupported prf " + guard.text.showValue(prf)); return PRF_NODE_BY_NAME[prf]; }
47
47
  function prfNodeByOid(oidStr, E, prefix) { if (!PRF_NODE_BY_OID[oidStr]) throw E(prefix + "/unsupported-algorithm", "unsupported PBKDF2 prf " + oidStr); return PRF_NODE_BY_OID[oidStr]; }
48
48
 
49
49
  function pbkdf2ParamsSeq(salt, iterations, prf) {
@@ -210,9 +210,9 @@ function _safeBag(bagName, bagValueDer, bag) {
210
210
 
211
211
  function _buildBag(bag, opts, depth) {
212
212
  if (!bag || typeof bag !== "object") throw _err("pkcs12/bad-input", "each bag must be an object with a type");
213
- if (intrinsic.hasOwn(_BAG_KEYS_BY_TYPE, bag.type)) {
213
+ if (intrinsic.hasOwn(_BAG_KEYS_BY_TYPE, guard.text.keyOf(bag.type))) {
214
214
  guard.identifier.assertKnownKeys(bag, _BAG_KEYS_BY_TYPE[bag.type], _err, "pkcs12/bad-input", function (k) {
215
- return "unknown field " + JSON.stringify(k) + " on a " + JSON.stringify(bag.type) +
215
+ return "unknown field " + JSON.stringify(k) + " on a " + guard.text.showValue(bag.type) +
216
216
  " bag; that field is not read for this bag type";
217
217
  });
218
218
  }
@@ -253,7 +253,7 @@ function _buildBag(bag, opts, depth) {
253
253
  return _safeBag("safeContentsBag", _buildSafeContents(bag.nested || [], opts, depth + 1), bag);
254
254
  }
255
255
  default:
256
- throw _err("pkcs12/bad-input", "unknown bag type " + JSON.stringify(bag.type) + " (key / shroudedKey / cert / crl / secret / safeContents)");
256
+ throw _err("pkcs12/bad-input", "unknown bag type " + guard.text.showValue(bag.type) + " (key / shroudedKey / cert / crl / secret / safeContents)");
257
257
  }
258
258
  }
259
259
 
@@ -279,8 +279,9 @@ function _pbeOpts(enc) {
279
279
  return "unknown encrypt field " + JSON.stringify(k) +
280
280
  "; the PBE descriptor is { password?, cipher?, salt?, iterations?, prf? }";
281
281
  });
282
+ if (enc.cipher != null && typeof enc.cipher !== "string") throw _err("pkcs12/bad-input", "unsupported PBES2 cipher " + guard.text.showValue(enc.cipher) + " (aes-128-cbc / aes-192-cbc / aes-256-cbc)");
282
283
  var cipher = CIPHER_NAME[enc.cipher || "aes-256-cbc"];
283
- if (!cipher) throw _err("pkcs12/bad-input", "unsupported PBES2 cipher " + JSON.stringify(enc.cipher) + " (aes-128-cbc / aes-192-cbc / aes-256-cbc)");
284
+ if (!cipher) throw _err("pkcs12/bad-input", "unsupported PBES2 cipher " + guard.text.showValue(enc.cipher) + " (aes-128-cbc / aes-192-cbc / aes-256-cbc)");
284
285
  return {
285
286
  cipher: cipher,
286
287
  salt: enc.salt != null ? _bytes(enc.salt, "encrypt salt") : undefined,
@@ -314,7 +315,7 @@ async function _buildAuthSafeElement(sc, opts) {
314
315
  if (!r || typeof r !== "object" || r.cert == null) throw _err("pkcs12/bad-input", "a public-key privacy recipient must be a certificate recipient { cert } (a password or KEK recipient is not public-key privacy and cannot be reopened by pkcs12.open)");
315
316
  });
316
317
  var alg = sc.contentEncryptionAlgorithm || "aes-256-cbc";
317
- if (alg !== "aes-128-cbc" && alg !== "aes-192-cbc" && alg !== "aes-256-cbc") throw _err("pkcs12/bad-input", "a public-key privacy safe requires an AES-CBC content cipher (aes-128|192|256-cbc), not " + JSON.stringify(alg) + " -- RFC 7292 sec. 4.1 admits only id-envelopedData, not GCM/AuthEnvelopedData");
318
+ if (alg !== "aes-128-cbc" && alg !== "aes-192-cbc" && alg !== "aes-256-cbc") throw _err("pkcs12/bad-input", "a public-key privacy safe requires an AES-CBC content cipher (aes-128|192|256-cbc), not " + guard.text.showValue(alg) + " -- RFC 7292 sec. 4.1 admits only id-envelopedData, not GCM/AuthEnvelopedData");
318
319
  var envCi = await cms.encrypt(safeContentsDer, sc.recipients, { contentEncryptionAlgorithm: alg, contentType: "data" });
319
320
  return b.raw(envCi);
320
321
  }
@@ -342,8 +343,8 @@ async function _buildMacData(macOpts, sharedPassword, authSafeDer) {
342
343
  if (salt.length > C.LIMITS.PBKDF2_MAX_SALT) throw _err("pkcs12/bad-input", "the MAC salt exceeds the " + C.LIMITS.PBKDF2_MAX_SALT + "-octet cap");
343
344
 
344
345
  if (algorithm === "hmac") {
345
- var node = DIGEST_NAME[hash];
346
- if (!node || !P12_KDF_UV[node]) throw _err("pkcs12/unsupported-algorithm", "unsupported classic MAC hash " + JSON.stringify(hash) + " (sha1 / sha256 / sha384 / sha512)");
346
+ var node = DIGEST_NAME[guard.text.keyOf(hash)];
347
+ if (!node || !P12_KDF_UV[node]) throw _err("pkcs12/unsupported-algorithm", "unsupported classic MAC hash " + guard.text.showValue(hash) + " (sha1 / sha256 / sha384 / sha512)");
347
348
  var iter = _assertMacIter(macOpts.iterations == null ? DEFAULT_MAC_ITER : macOpts.iterations, CLASSIC_MAC_MAX_ITERATIONS);
348
349
  var macPw = _p12PasswordOwned(password);
349
350
  var macKey = _p12Kdf(node, 3, macPw.bytes, salt, iter, P12_KDF_UV[node].u);
@@ -357,7 +358,7 @@ async function _buildMacData(macOpts, sharedPassword, authSafeDer) {
357
358
  }
358
359
  }
359
360
  if (algorithm === "pbmac1") {
360
- var prf = PBMAC1_PRF[hash];
361
+ var prf = PBMAC1_PRF[guard.text.keyOf(hash)];
361
362
  if (!prf) throw _err("pkcs12/unsupported-algorithm", "PBMAC1 requires a SHA-256/384/512 digest (RFC 9579 sec. 5/7 forbids a <= 160-bit digest, e.g. SHA-1)");
362
363
  var iter2 = _assertMacIter(macOpts.iterations == null ? DEFAULT_PBMAC1_ITER : macOpts.iterations, C.LIMITS.PBKDF2_MAX_ITERATIONS);
363
364
  var keyLen = macOpts.keyLength != null ? macOpts.keyLength : prf.keyLen;
@@ -370,7 +371,7 @@ async function _buildMacData(macOpts, sharedPassword, authSafeDer) {
370
371
  var digestInfo2 = b.sequence([pbes2.pbmac1AlgId(desc), b.octetString(mac)]);
371
372
  return b.sequence([digestInfo2, b.octetString(salt), b.integer(BigInt(iter2))]);
372
373
  }
373
- throw _err("pkcs12/bad-input", "opts.mac.algorithm must be 'hmac' or 'pbmac1', got " + JSON.stringify(algorithm));
374
+ throw _err("pkcs12/bad-input", "opts.mac.algorithm must be 'hmac' or 'pbmac1', got " + guard.text.showValue(algorithm));
374
375
  }
375
376
 
376
377
 
@@ -468,7 +469,7 @@ async function _build(spec, opts) {
468
469
  if (typeof opts.integrity !== "object" || Array.isArray(opts.integrity)) throw _err("pkcs12/bad-input", "opts.integrity must be an object { mode, signer|signers, ... }");
469
470
  guard.identifier.assertKnownKeys(opts.integrity, _INTEGRITY_OPTS, _err, "pkcs12/bad-input", "opts.integrity has an unknown option ");
470
471
  if (opts.integrity.mode !== "public-key") {
471
- throw _err("pkcs12/bad-integrity-mode", "opts.integrity.mode must be \"public-key\" (the only mode it selects); omit opts.integrity for password integrity, got " + JSON.stringify(opts.integrity.mode));
472
+ throw _err("pkcs12/bad-integrity-mode", "opts.integrity.mode must be \"public-key\" (the only mode it selects); omit opts.integrity for password integrity, got " + guard.text.showValue(opts.integrity.mode));
472
473
  }
473
474
  }
474
475
  var pubKey = opts.integrity != null;
package/lib/pki-build.js CHANGED
@@ -242,10 +242,10 @@ function _isDottedOid(s) {
242
242
 
243
243
  var b = asn1.build;
244
244
 
245
- var KU_BIT = {
245
+ var KU_BIT = intrinsic.assign(intrinsic.create(null), {
246
246
  digitalSignature: 0, nonRepudiation: 1, contentCommitment: 1, keyEncipherment: 2,
247
247
  dataEncipherment: 3, keyAgreement: 4, keyCertSign: 5, cRLSign: 6, encipherOnly: 7, decipherOnly: 8,
248
- };
248
+ });
249
249
 
250
250
  function reqDenseArrayImpl(list, what, E, code) {
251
251
  if (!_isArray(list)) throw E(code, what + " must be an array");
@@ -284,7 +284,7 @@ function makeBuilder(ctx) {
284
284
  function encodeAtv(attrName, value) {
285
285
  if (value == null || value === "") throw E("bad-name", "the " + attrName + " attribute value must be a non-empty string");
286
286
  var typeOid = O(attrName);
287
- if (typeOid == null) throw E("bad-name", "unknown distinguished-name attribute " + JSON.stringify(attrName));
287
+ if (typeOid == null) throw E("bad-name", "unknown distinguished-name attribute " + guard.text.showValue(attrName));
288
288
  var valueTlv;
289
289
  try { valueTlv = atvString(attrName, value); }
290
290
  catch (e) { if (e instanceof ErrorClass) throw e; throw E("bad-name", "the " + attrName + " value has characters invalid for its string type", e); }
@@ -365,7 +365,7 @@ function makeBuilder(ctx) {
365
365
  guard.der.tlv(v.value, E, "bad-input", "otherName `value`");
366
366
  var typeIdDer;
367
367
  try { typeIdDer = b.oid(v.typeId); }
368
- catch (e) { throw E("bad-input", "invalid otherName type-id OID " + JSON.stringify(v.typeId) + " (violates the X.660 arc bounds)", e); }
368
+ catch (e) { throw E("bad-input", "invalid otherName type-id OID " + guard.text.showValue(v.typeId) + " (violates the X.660 arc bounds)", e); }
369
369
  return b.contextConstructed(0, Buffer.concat([typeIdDer, b.explicit(0, v.value)]));
370
370
  default: throw E("bad-input", "unsupported GeneralName form " + JSON.stringify(k) + " (supported: rfc822Name, dNSName, uniformResourceIdentifier, iPAddress, directoryName, otherName)");
371
371
  }
@@ -374,8 +374,8 @@ function makeBuilder(ctx) {
374
374
  function extKeyUsage(names) {
375
375
  if (!_isArray(names) || !names.length) throw E("bad-input", "keyUsage must assert at least one bit (RFC 5280 sec. 4.2.1.3)");
376
376
  var positions = names.map(function (n) {
377
- var pos = KU_BIT[n];
378
- if (pos == null) throw E("bad-input", "unknown keyUsage bit " + JSON.stringify(n));
377
+ var pos = KU_BIT[guard.text.keyOf(n)];
378
+ if (pos == null) throw E("bad-input", "unknown keyUsage bit " + guard.text.showValue(n));
379
379
  return pos;
380
380
  });
381
381
  return b.namedBitString(positions);
@@ -385,10 +385,10 @@ function makeBuilder(ctx) {
385
385
  if (dotted != null) return dotted;
386
386
  if (typeof n === "string" && _isDottedOid(n)) {
387
387
  try { b.oid(n); }
388
- catch (e) { throw E("bad-input", "invalid " + label + " OID " + JSON.stringify(n) + " (violates the X.660 arc bounds)", e); }
388
+ catch (e) { throw E("bad-input", "invalid " + label + " OID " + guard.text.showValue(n) + " (violates the X.660 arc bounds)", e); }
389
389
  return n;
390
390
  }
391
- throw E("bad-input", "unknown " + label + " " + JSON.stringify(n) + " (expected a registered name or a dotted-decimal OID)");
391
+ throw E("bad-input", "unknown " + label + " " + guard.text.showValue(n) + " (expected a registered name or a dotted-decimal OID)");
392
392
  }
393
393
  function extExtKeyUsage(names) {
394
394
  if (!_isArray(names) || !names.length) throw E("bad-input", "extendedKeyUsage must list at least one KeyPurposeId");
@@ -424,7 +424,7 @@ function makeBuilder(ctx) {
424
424
  var seen = {};
425
425
  return b.sequence(names.map(function (n) {
426
426
  var pOid = _resolveOid(n, "certificate policy");
427
- if (seen[pOid]) throw E("bad-input", "duplicate certificate policy " + JSON.stringify(n) + " (RFC 5280 sec. 4.2.1.4)");
427
+ if (seen[pOid]) throw E("bad-input", "duplicate certificate policy " + guard.text.showValue(n) + " (RFC 5280 sec. 4.2.1.4)");
428
428
  seen[pOid] = true;
429
429
  return b.sequence([b.oid(pOid)]);
430
430
  }));
package/lib/scep.js CHANGED
@@ -60,6 +60,7 @@ var _defaultSleep = require("./sleep").sleep;
60
60
  var nodeCrypto = require("node:crypto");
61
61
 
62
62
  function _err(code, msg, cause) { return new ScepError(code, msg, cause); }
63
+ function _showValue(v) { return guard.text.showValue(v); }
63
64
 
64
65
  var _KU_NS = pkix.makeNS("scep", ScepError, oid);
65
66
 
@@ -256,8 +257,8 @@ function _captureRecipientKey(rk) {
256
257
  */
257
258
  async function build(spec) {
258
259
  spec = guard.identifier.optionsObject(spec, _err, "scep/bad-input", "pki.scep.build spec");
259
- var mtCode = MESSAGE_TYPE[spec.messageType];
260
- if (mtCode == null) throw _err("scep/bad-message-type", "unknown messageType " + JSON.stringify(spec.messageType) + " (RFC 8894 sec. 3.2.1.2)");
260
+ var mtCode = MESSAGE_TYPE[guard.text.keyOf(spec.messageType)];
261
+ if (mtCode == null) throw _err("scep/bad-message-type", "unknown messageType " + _showValue(spec.messageType) + " (RFC 8894 sec. 3.2.1.2)");
261
262
  if (spec.messageType === "CertRep") {
262
263
  guard.identifier.assertKnownKeys(spec, _CERTREP_KEYS, _err, "scep/bad-input", "pki.scep.build (CertRep) has an unknown option: ");
263
264
  return await _buildCertRep(spec);
@@ -312,9 +313,9 @@ var _CERTREP_KEYS = { messageType: 1, signer: 1, transactionId: 1, senderNonce:
312
313
 
313
314
  async function _buildCertRep(spec) {
314
315
  if (spec.signer == null || typeof spec.signer !== "object") throw _err("scep/bad-input", "a signer { cert, key } is required");
315
- if (typeof spec.pkiStatus !== "string") throw _err("scep/bad-input", "a CertRep pkiStatus must be SUCCESS, FAILURE, or PENDING (RFC 8894 sec. 3.2.1.3), got " + JSON.stringify(spec.pkiStatus));
316
+ if (typeof spec.pkiStatus !== "string") throw _err("scep/bad-input", "a CertRep pkiStatus must be SUCCESS, FAILURE, or PENDING (RFC 8894 sec. 3.2.1.3), got " + _showValue(spec.pkiStatus));
316
317
  var statusCode = PKI_STATUS[spec.pkiStatus];
317
- if (statusCode == null) throw _err("scep/bad-input", "a CertRep pkiStatus must be SUCCESS, FAILURE, or PENDING (RFC 8894 sec. 3.2.1.3), got " + JSON.stringify(spec.pkiStatus));
318
+ if (statusCode == null) throw _err("scep/bad-input", "a CertRep pkiStatus must be SUCCESS, FAILURE, or PENDING (RFC 8894 sec. 3.2.1.3), got " + _showValue(spec.pkiStatus));
318
319
  var txnId = _transactionId(spec.transactionId);
319
320
  if (spec.recipientNonce == null) throw _err("scep/bad-input", "a CertRep must echo the request's senderNonce as recipientNonce (RFC 8894 sec. 3.2.1.5)");
320
321
  var recipientNonce = _nonce(spec.recipientNonce, "recipientNonce");
@@ -354,8 +355,8 @@ async function _buildCertRep(spec) {
354
355
  throw _err("scep/bad-input", "a " + spec.pkiStatus + " CertRep must omit certificates, crls, and recipient: the pkcsPKIEnvelope is omitted (RFC 8894 sec. 3.3.2." + (spec.pkiStatus === "FAILURE" ? "2" : "3") + ")");
355
356
  }
356
357
  if (spec.pkiStatus === "FAILURE") {
357
- var failCode = FAIL_INFO[spec.failInfo];
358
- if (failCode == null) throw _err("scep/bad-input", "a FAILURE CertRep must carry a failInfo of badAlg / badMessageCheck / badRequest / badTime / badCertId (RFC 8894 sec. 3.2.1.4), got " + JSON.stringify(spec.failInfo));
358
+ var failCode = FAIL_INFO[guard.text.keyOf(spec.failInfo)];
359
+ if (failCode == null) throw _err("scep/bad-input", "a FAILURE CertRep must carry a failInfo of badAlg / badMessageCheck / badRequest / badTime / badCertId (RFC 8894 sec. 3.2.1.4), got " + _showValue(spec.failInfo));
359
360
  attrs.push(_attr("scepFailInfo", b.printable(failCode)));
360
361
  if (spec.failInfoText != null) attrs.push(_attr("scepFailInfoText", b.utf8(String(spec.failInfoText))));
361
362
  }
@@ -395,7 +396,7 @@ function _serialToInteger(s) {
395
396
  else if (typeof s === "number") { if (!Number.isSafeInteger(s)) throw _err("scep/bad-input", "serialNumber as a number must be a safe integer"); n = BigInt(s); }
396
397
  else if (typeof s === "string" && s.length > 0) {
397
398
  var t = (s.slice(0, 2) === "0x" || s.slice(0, 2) === "0X") ? s.slice(2) : s;
398
- try { n = BigInt("0x" + t); } catch (_e) { throw _err("scep/bad-input", "serialNumber must be a hex string, a non-negative safe integer, or a BigInt: " + JSON.stringify(s)); }
399
+ try { n = BigInt("0x" + t); } catch (_e) { throw _err("scep/bad-input", "serialNumber must be a hex string, a non-negative safe integer, or a BigInt: " + _showValue(s)); }
399
400
  } else {
400
401
  throw _err("scep/bad-input", "serialNumber must be a hex string, a non-negative safe integer, or a BigInt");
401
402
  }
@@ -662,12 +663,26 @@ function _redirectTarget(current, location, method, allowCrossOrigin) {
662
663
  function _scepUrl(baseUrl, operation) {
663
664
  var url;
664
665
  try { url = new URL(String(baseUrl)); }
665
- catch (e) { throw _err("scep/bad-url", "the SCEP base URL did not parse: " + String(baseUrl), e); }
666
+ catch (e) { throw _err("scep/bad-url", "the SCEP base URL did not parse: " + _showValue(baseUrl), e); }
666
667
  if (url.protocol !== "http:" && url.protocol !== "https:") throw _err("scep/bad-url", "the SCEP base URL must be http or https, got " + url.protocol);
667
668
  if (url.hash) throw _err("scep/bad-url", "the SCEP base URL must not carry a fragment");
668
669
  url.searchParams.set("operation", operation);
669
670
  return url;
670
671
  }
672
+ function _pkiMethod(opts) {
673
+ var m = opts.httpMethod;
674
+ if (m == null) return "POST";
675
+ if (m !== "POST" && m !== "GET") throw _err("scep/bad-input", "httpMethod must be \"POST\" or \"GET\" (RFC 8894 sec. 4.1), got " + _showValue(m));
676
+ return m;
677
+ }
678
+ function _pkiRequest(method, opUrl, reqMsg, clientOpts) {
679
+ if (method === "GET") {
680
+ var getUrl = new URL(opUrl.href);
681
+ getUrl.searchParams.set("message", Buffer.from(reqMsg).toString("base64"));
682
+ return _client("GET", getUrl, null, {}, clientOpts);
683
+ }
684
+ return _client("POST", opUrl, reqMsg, { "content-type": CT_PKI_MESSAGE }, clientOpts);
685
+ }
671
686
  function _drive(method, url, body, headers, opts, transport, budgets) {
672
687
  var redirects = 0, curMethod = method, curBody = body, initialOrigin = url.origin;
673
688
  var tlsBase = _tlsForRequest(opts);
@@ -816,7 +831,7 @@ function findIssuedCert(certs, wantSpki) {
816
831
  function _normalizeFingerprint(fp, algName) {
817
832
  var algorithm = _foldLower(String(algName == null ? "sha256" : algName));
818
833
  try { nodeCrypto.createHash(algorithm); }
819
- catch (_e) { throw _err("scep/bad-input", "fingerprintAlgorithm " + JSON.stringify(algorithm) + " is not an available hash"); }
834
+ catch (_e) { throw _err("scep/bad-input", "fingerprintAlgorithm " + _showValue(algorithm) + " is not an available hash"); }
820
835
  var value;
821
836
  if (Buffer.isBuffer(fp)) value = Buffer.from(fp);
822
837
  else if (typeof fp === "string") {
@@ -991,7 +1006,7 @@ async function _pollForIssuance(ctx) {
991
1006
  var sn = nodeCrypto.randomBytes(16);
992
1007
  lastNonce = sn;
993
1008
  var certPoll = await build({ messageType: "CertPoll", requestSubject: ctx.csrSubject, issuer: issuerName, recipient: ctx.caCert, signer: ctx.signer, transactionId: ctx.transactionId, senderNonce: sn });
994
- res = await _client("POST", ctx.postUrl, certPoll, { "content-type": CT_PKI_MESSAGE }, ctx.clientOpts);
1009
+ res = await _pkiRequest(ctx.httpMethod, ctx.postUrl, certPoll, ctx.clientOpts);
995
1010
  var body = _requireOk(res, [CT_PKI_MESSAGE], "PKIOperation");
996
1011
  var rep = await parse(body, { signerCert: ctx.signerCert, expectedSenderNonce: sn, recipientKey: ctx.recipientKey });
997
1012
  var d = _dispatchCertRep(rep, ctx.transactionId, ctx.spki);
@@ -1019,6 +1034,7 @@ async function _pkiOperation(messageType, baseUrl, opts, verbName) {
1019
1034
  maxResponseBytes: opts.maxResponseBytes,
1020
1035
  };
1021
1036
  var postUrl = _scepUrl(baseUrl, "PKIOperation");
1037
+ var httpMethod = _pkiMethod(opts);
1022
1038
  var csrView = guard.bytes.snapshotSource(opts.csr, ScepError, "scep/bad-input", "the csr");
1023
1039
  var spki, csrSubject;
1024
1040
  try { var _pcsr = schemaCsr.parse(csrView); spki = _pcsr.subjectPublicKeyInfo; csrSubject = _pcsr.subject.bytes; }
@@ -1030,14 +1046,14 @@ async function _pkiOperation(messageType, baseUrl, opts, verbName) {
1030
1046
  var senderNonce = nodeCrypto.randomBytes(16);
1031
1047
  var transactionId = opts.transactionId != null ? opts.transactionId : _defaultTransactionId();
1032
1048
  var reqMsg = await build({ messageType: messageType, messageData: csrView, recipient: caCert, signer: signer, transactionId: transactionId, senderNonce: senderNonce });
1033
- var res = await _client("POST", postUrl, reqMsg, { "content-type": CT_PKI_MESSAGE }, clientOpts);
1049
+ var res = await _pkiRequest(httpMethod, postUrl, reqMsg, clientOpts);
1034
1050
  var body = _requireOk(res, [CT_PKI_MESSAGE], "PKIOperation");
1035
1051
  var rep = await parse(body, { signerCert: signerCert, expectedSenderNonce: senderNonce, recipientKey: recipientKey });
1036
1052
  var d = _dispatchCertRep(rep, transactionId, spki);
1037
1053
  if (!d.pending) return d.result;
1038
1054
  if (pollCount <= 0) return { status: "PENDING", transactionId: rep.transactionId, senderNonce: senderNonce };
1039
1055
  return _pollForIssuance({
1040
- firstResponse: res, firstSenderNonce: senderNonce, postUrl: postUrl, clientOpts: clientOpts,
1056
+ firstResponse: res, firstSenderNonce: senderNonce, postUrl: postUrl, httpMethod: httpMethod, clientOpts: clientOpts,
1041
1057
  caCert: caCert, csrSubject: csrSubject, issuerCert: issuerCert, signer: signer, signerCert: signerCert, recipientKey: recipientKey,
1042
1058
  spki: spki, transactionId: transactionId, pollCount: pollCount, maxTotalWait: maxTotalWait,
1043
1059
  sleep: sleep, onRetryAfter: onRetryAfter,
@@ -1079,6 +1095,7 @@ async function _pkiOperation(messageType, baseUrl, opts, verbName) {
1079
1095
  * - `maxTotalWait` -- the total Retry-After sleep budget in seconds across all polls (default the Retry-After horizon).
1080
1096
  * - `sleep` -- an injectable sleeper `(ms) -> Promise` for the Retry-After wait (default a real timer).
1081
1097
  * - `onRetryAfter` -- an optional observer `(delaySeconds) -> void` called before each poll sleep.
1098
+ * - `httpMethod` -- `"POST"` (default) or `"GET"`. RFC 8894 sec. 4.1 sends the PKIOperation message over POST; `"GET"` carries it base64-encoded in the URL `message` query for a legacy CA that lacks POST.
1082
1099
  * - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` -- transport bounds.
1083
1100
  * @example
1084
1101
  * // requires: scepCsr, caCertDer, clientCertDer, clientKeyPkcs8, scepTransport
@@ -1158,8 +1175,9 @@ async function _queryOperation(messageType, baseUrl, opts, verbName) {
1158
1175
  var clientOpts = { transport: opts.transport, tls: opts.tls != null ? Object.assign({}, opts.tls) : opts.tls, maxRedirects: opts.maxRedirects, allowCrossOriginRedirect: opts.allowCrossOriginRedirect, timeout: opts.timeout, maxResponseBytes: opts.maxResponseBytes };
1159
1176
  var senderNonce = nodeCrypto.randomBytes(16);
1160
1177
  var transactionId = opts.transactionId != null ? opts.transactionId : _defaultTransactionId();
1178
+ var httpMethod = _pkiMethod(opts);
1161
1179
  var reqMsg = await build(Object.assign({ messageType: messageType, recipient: caCert, signer: signer, transactionId: transactionId, senderNonce: senderNonce }, want.buildSpec));
1162
- var res = await _client("POST", _scepUrl(baseUrl, "PKIOperation"), reqMsg, { "content-type": CT_PKI_MESSAGE }, clientOpts);
1180
+ var res = await _pkiRequest(httpMethod, _scepUrl(baseUrl, "PKIOperation"), reqMsg, clientOpts);
1163
1181
  var body = _requireOk(res, [CT_PKI_MESSAGE], "PKIOperation");
1164
1182
  var rep = await parse(body, { signerCert: signerCert, expectedSenderNonce: senderNonce, recipientKey: recipientKey });
1165
1183
  _dispatchQueryRep(rep, transactionId);
@@ -1192,6 +1210,7 @@ async function _queryOperation(messageType, baseUrl, opts, verbName) {
1192
1210
  * - `recipientKey` -- `{ cert, key }`, the RSA key the CA encrypts the response to, to decrypt the CertRep.
1193
1211
  * - `responderCert` -- the certificate to authenticate the CA response signature against (defaults to `caCert`).
1194
1212
  * - `transactionId` -- a caller-unique PrintableString (defaults to 16 random bytes, hex-encoded).
1213
+ * - `httpMethod` -- `"POST"` (default) or `"GET"`. RFC 8894 sec. 4.1 sends the PKIOperation message over POST; `"GET"` carries it base64-encoded in the URL `message` query for a legacy CA that lacks POST.
1195
1214
  * - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` -- transport bounds.
1196
1215
  * @example
1197
1216
  * // requires: clientCertDer, caCertDer, clientKeyPkcs8, scepTransport
@@ -1240,6 +1259,7 @@ async function getCert(baseUrl, opts) {
1240
1259
  * - `recipientKey` -- `{ cert, key }`, the RSA key the CA encrypts the response to.
1241
1260
  * - `responderCert` -- the certificate to authenticate the CA response against (defaults to `caCert`).
1242
1261
  * - `transactionId` -- a caller-unique PrintableString (defaults to 16 random bytes, hex-encoded).
1262
+ * - `httpMethod` -- `"POST"` (default) or `"GET"`. RFC 8894 sec. 4.1 sends the PKIOperation message over POST; `"GET"` carries it base64-encoded in the URL `message` query for a legacy CA that lacks POST.
1243
1263
  * - `transport` / `timeout` / `maxResponseBytes` / `maxRedirects` / `tls` / `allowCrossOriginRedirect` -- transport bounds.
1244
1264
  * @example
1245
1265
  * // requires: clientCertDer, caCertDer, clientKeyPkcs8, scepTransport
@@ -1268,8 +1288,8 @@ function _withKeys(extra) { var o = {}, k; for (k in _TRANSPORT_KEYS) o[k] = 1;
1268
1288
  var _CACAPS_KEYS = _withKeys({ expectSCEPStandard: 1, requireStrongProfile: 1 });
1269
1289
  var _CACERT_KEYS = _withKeys({ expectedFingerprint: 1, fingerprintAlgorithm: 1 });
1270
1290
  var _NEXTCACERT_KEYS = _withKeys({ caCertificate: 1 });
1271
- var _ENROLL_KEYS = _withKeys({ csr: 1, caCert: 1, signer: 1, recipientKey: 1, responderCert: 1, issuerCert: 1, transactionId: 1, pollCount: 1, maxTotalWait: 1, sleep: 1, onRetryAfter: 1 });
1272
- var _QUERY_KEYS = _withKeys({ certificate: 1, issuer: 1, serialNumber: 1, caCert: 1, signer: 1, recipientKey: 1, responderCert: 1, transactionId: 1 });
1291
+ var _ENROLL_KEYS = _withKeys({ csr: 1, caCert: 1, signer: 1, recipientKey: 1, responderCert: 1, issuerCert: 1, transactionId: 1, pollCount: 1, maxTotalWait: 1, sleep: 1, onRetryAfter: 1, httpMethod: 1 });
1292
+ var _QUERY_KEYS = _withKeys({ certificate: 1, issuer: 1, serialNumber: 1, caCert: 1, signer: 1, recipientKey: 1, responderCert: 1, transactionId: 1, httpMethod: 1 });
1273
1293
 
1274
1294
  module.exports = {
1275
1295
  build: build,
package/lib/sigstore.js CHANGED
@@ -164,7 +164,7 @@ function parseBundle(input) {
164
164
  if (!obj || typeof obj !== "object" || Array.isArray(obj)) throw _err("sigstore/bad-bundle", "bundle must be a JSON object");
165
165
  var mt = obj.mediaType;
166
166
  if (!_isBundleMediaType(mt)) {
167
- throw _err("sigstore/bad-bundle-version", "unsupported or unknown bundle media type: " + (mt === undefined ? "(none)" : mt));
167
+ throw _err("sigstore/bad-bundle-version", "unsupported or unknown bundle media type: " + (mt === undefined ? "(none)" : guard.text.showValue(mt)));
168
168
  }
169
169
  if (!obj.verificationMaterial || typeof obj.verificationMaterial !== "object") {
170
170
  throw _err("sigstore/bad-bundle", "bundle is missing verificationMaterial");
package/lib/smime.js CHANGED
@@ -127,7 +127,7 @@ function _applyHcp(name, value, hcp) {
127
127
 
128
128
  function _outerHeaderList(list, mode, hcp) {
129
129
  var policy = hcp == null ? "hcp_baseline" : hcp;
130
- if (policy !== "hcp_baseline" && policy !== "hcp_no_confidentiality") throw _err("smime/bad-input", "unknown opts.hcp policy " + JSON.stringify(hcp) + " (only \"hcp_baseline\" or \"hcp_no_confidentiality\")");
130
+ if (policy !== "hcp_baseline" && policy !== "hcp_no_confidentiality") throw _err("smime/bad-input", "unknown opts.hcp policy " + guard.text.showValue(hcp) + " (only \"hcp_baseline\" or \"hcp_no_confidentiality\")");
131
131
  var out = [];
132
132
  list.forEach(function (h) {
133
133
  if (mode === "cipher") {
@@ -143,8 +143,10 @@ function _outerHeaderList(list, mode, hcp) {
143
143
  function _protectedInnerEntity(content, opts, mode, hpList, outerList) {
144
144
  if (opts.entity) throw _err("smime/bad-input", "opts.entity is not supported with protectHeaders -- pass raw content + opts.contentType");
145
145
  var raw = guard.bytes.view(content, SmimeError, "smime/bad-input", "content");
146
- if (opts.contentType != null && mime.hasParam(String(opts.contentType), "hp")) throw _err("smime/bad-input", "opts.contentType must not set the hp parameter -- header protection sets it (hp=" + JSON.stringify(mode) + ")");
147
- var ct = (opts.contentType || "text/plain; charset=utf-8") + "; hp=\"" + mode + "\"";
146
+ var cty = opts.contentType;
147
+ if (cty != null && typeof cty !== "string") throw _err("smime/bad-input", "opts.contentType must be a string, got " + guard.text.showValue(cty));
148
+ if (cty != null && mime.hasParam(cty, "hp")) throw _err("smime/bad-input", "opts.contentType must not set the hp parameter -- header protection sets it (hp=" + guard.text.showValue(mode) + ")");
149
+ var ct = (cty || "text/plain; charset=utf-8") + "; hp=\"" + mode + "\"";
148
150
  var fields = [{ name: "Content-Type", value: ct }, { name: "Content-Transfer-Encoding", value: _is7bit(raw) ? "7bit" : "8bit" }];
149
151
  hpList.forEach(function (h) { fields.push(h); });
150
152
  if (mode === "cipher") {
@@ -104,7 +104,7 @@ function _resolveAllowed(opts) {
104
104
  return list.map(function (a) {
105
105
  var name = (typeof a === "number") ? ALG_BY_NUMBER[a] : a;
106
106
  if (typeof name !== "string" || SUPPORTED.indexOf(name) === -1) {
107
- throw _err("tls/bad-input", "opts.allowedAlgorithms names an algorithm this toolkit cannot decompress: " + JSON.stringify(a));
107
+ throw _err("tls/bad-input", "opts.allowedAlgorithms names an algorithm this toolkit cannot decompress: " + guard.text.showValue(a));
108
108
  }
109
109
  return name;
110
110
  });
package/lib/tsp-sign.js CHANGED
@@ -60,7 +60,7 @@ function _moreEstablished(candidate, current) {
60
60
  }
61
61
 
62
62
  function _hashAlgId(name) {
63
- if (!NODE_DIGEST[name]) throw _err("tsp/unsupported-algorithm", "unsupported hash algorithm " + JSON.stringify(name));
63
+ if (!NODE_DIGEST[guard.text.keyOf(name)]) throw _err("tsp/unsupported-algorithm", "unsupported hash algorithm " + guard.text.showValue(name));
64
64
  return b.sequence([b.oid(O(name)), b.nullValue()]);
65
65
  }
66
66
  function _policy(p) {
@@ -153,7 +153,7 @@ function _sign(messageImprint, tsa, opts) {
153
153
  });
154
154
  }
155
155
  var mi = messageImprint || {};
156
- if (!mi.hashAlgorithm || !NODE_DIGEST[mi.hashAlgorithm]) throw _err("tsp/unsupported-algorithm", "messageImprint.hashAlgorithm must be a supported hash name");
156
+ if (!mi.hashAlgorithm || !NODE_DIGEST[guard.text.keyOf(mi.hashAlgorithm)]) throw _err("tsp/unsupported-algorithm", "messageImprint.hashAlgorithm must be a supported hash name");
157
157
  if (!guard.bytes.isByteSource(mi.hashedMessage)) throw _err("tsp/bad-input", "messageImprint.hashedMessage must be a BufferSource");
158
158
  var _signHmLen = guard.bytes.source(mi.hashedMessage, TspError, "tsp/bad-input", "messageImprint.hashedMessage").length;
159
159
  if (_signHmLen !== HASH_LEN[mi.hashAlgorithm]) throw _err("tsp/bad-input", "messageImprint.hashedMessage length (" + _signHmLen + ") does not match the " + mi.hashAlgorithm + " digest length (" + HASH_LEN[mi.hashAlgorithm] + ")");
@@ -162,7 +162,7 @@ function _sign(messageImprint, tsa, opts) {
162
162
 
163
163
  var certDer = _certDer(tsa && tsa.cert);
164
164
  var certHashAlg = opts.certHashAlgorithm || "sha256";
165
- if (!NODE_DIGEST[certHashAlg]) throw _err("tsp/unsupported-algorithm", "unsupported certHashAlgorithm " + JSON.stringify(certHashAlg));
165
+ if (!NODE_DIGEST[guard.text.keyOf(certHashAlg)]) throw _err("tsp/unsupported-algorithm", "unsupported certHashAlgorithm " + guard.text.showValue(certHashAlg));
166
166
 
167
167
  var imprint = b.sequence([_hashAlgId(mi.hashAlgorithm), b.octetString(guard.bytes.source(mi.hashedMessage, TspError, "tsp/bad-input", "messageImprint.hashedMessage"))]);
168
168
  if (opts.genTime != null) guard.time.assertValid(opts.genTime, _err, "tsp/bad-input", "genTime");
@@ -192,29 +192,32 @@ function _accuracy(a) {
192
192
  return "unknown accuracy field " + JSON.stringify(k) + "; Accuracy is { seconds?, millis?, micros? }";
193
193
  });
194
194
  var f = [];
195
- if (a.seconds != null) {
196
- var s = Number(a.seconds);
195
+ var sec = a.seconds, mil = a.millis, mic = a.micros;
196
+ if (sec != null) {
197
+ if (typeof sec !== "number" && typeof sec !== "bigint") throw _err("tsp/bad-input", "Accuracy seconds must be a non-negative integer, got " + guard.text.showValue(sec));
198
+ var s = intrinsic.Number(sec);
197
199
  if (!Number.isInteger(s) || s < 0 || s > 0x7fffffff) throw _err("tsp/bad-input", "Accuracy seconds must be a non-negative integer");
198
200
  f.push(b.integer(BigInt(s)));
199
201
  }
200
- if (a.millis != null) f.push(b.contextPrimitive(0, _subMilliBytes(a.millis, "millis")));
201
- if (a.micros != null) f.push(b.contextPrimitive(1, _subMilliBytes(a.micros, "micros")));
202
+ if (mil != null) f.push(b.contextPrimitive(0, _subMilliBytes(mil, "millis")));
203
+ if (mic != null) f.push(b.contextPrimitive(1, _subMilliBytes(mic, "micros")));
202
204
  return b.sequence(f);
203
205
  }
204
206
  function _subMilliBytes(n, label) {
205
- var v = Number(n);
207
+ if (typeof n !== "number" && typeof n !== "bigint") throw _err("tsp/bad-input", "Accuracy " + label + " must be an integer in 1..999 (RFC 3161 sec. 2.4.2), got " + guard.text.showValue(n));
208
+ var v = intrinsic.Number(n);
206
209
  if (!Number.isInteger(v) || v < 1 || v > 999) throw _err("tsp/bad-input", "Accuracy " + label + " must be an integer in 1..999 (RFC 3161 sec. 2.4.2)");
207
210
  return b.integer(BigInt(v)).subarray(2);
208
211
  }
209
212
 
210
213
 
211
- var FAILINFO_BIT = { badAlg: 0, badRequest: 2, badDataFormat: 5, timeNotAvailable: 14, unacceptedPolicy: 15, unacceptedExtension: 16, addInfoNotAvailable: 17, systemFailure: 25 };
214
+ var FAILINFO_BIT = intrinsic.assign(intrinsic.create(null), { badAlg: 0, badRequest: 2, badDataFormat: 5, timeNotAvailable: 14, unacceptedPolicy: 15, unacceptedExtension: 16, addInfoNotAvailable: 17, systemFailure: 25 });
212
215
 
213
216
  function _failInfoBits(names) {
214
217
  if (!Array.isArray(names)) throw _err("tsp/bad-input", "failInfo must be an array of PKIFailureInfo names");
215
218
  var idxs = names.map(function (n) {
216
- var i = FAILINFO_BIT[n];
217
- if (i == null) throw _err("tsp/bad-input", "unknown PKIFailureInfo name " + JSON.stringify(n) + " (RFC 3161 sec. 2.4.2)");
219
+ var i = FAILINFO_BIT[guard.text.keyOf(n)];
220
+ if (i == null) throw _err("tsp/bad-input", "unknown PKIFailureInfo name " + guard.text.showValue(n) + " (RFC 3161 sec. 2.4.2)");
218
221
  return i;
219
222
  });
220
223
  return b.namedBitString(idxs);
@@ -227,7 +230,7 @@ function _tokenDer(t) {
227
230
  }
228
231
 
229
232
  function _assertImprint(mi) {
230
- if (!mi.hashAlgorithm || !NODE_DIGEST[mi.hashAlgorithm]) throw _err("tsp/unsupported-algorithm", "messageImprint.hashAlgorithm must be a supported hash name");
233
+ if (!mi.hashAlgorithm || !NODE_DIGEST[guard.text.keyOf(mi.hashAlgorithm)]) throw _err("tsp/unsupported-algorithm", "messageImprint.hashAlgorithm must be a supported hash name");
231
234
  if (!guard.bytes.isByteSource(mi.hashedMessage)) throw _err("tsp/bad-input", "messageImprint.hashedMessage must be a BufferSource");
232
235
  var hmLen = guard.bytes.source(mi.hashedMessage, TspError, "tsp/bad-input", "messageImprint.hashedMessage").length;
233
236
  if (hmLen !== HASH_LEN[mi.hashAlgorithm]) throw _err("tsp/bad-input", "messageImprint.hashedMessage length (" + hmLen + ") does not match the " + mi.hashAlgorithm + " digest length (" + HASH_LEN[mi.hashAlgorithm] + ")");
@@ -348,7 +351,9 @@ function response(token, opts) {
348
351
  opts = opts || {};
349
352
  if (typeof opts !== "object" || Buffer.isBuffer(opts)) throw _err("tsp/bad-input", "pki.tsp.response options must be an object");
350
353
  guard.identifier.assertKnownKeys(opts, _RESPONSE_OPTS, _err, "tsp/bad-input", "pki.tsp.response has an unknown option ");
351
- var status = opts.status == null ? 0 : Number(opts.status);
354
+ var st = opts.status;
355
+ if (st != null && typeof st !== "number" && typeof st !== "bigint") throw _err("tsp/bad-input", "PKIStatus must be an integer in 0..5 (RFC 3161 sec. 2.4.2), got " + guard.text.showValue(st));
356
+ var status = st == null ? 0 : intrinsic.Number(st);
352
357
  if (!Number.isInteger(status) || status < 0 || status > 5) throw _err("tsp/bad-input", "PKIStatus must be an integer in 0..5 (RFC 3161 sec. 2.4.2)");
353
358
  var granted = status === 0 || status === 1;
354
359
  if (granted && token == null) throw _err("tsp/missing-token", "a granted TimeStampResp requires a timeStampToken (RFC 3161 sec. 2.4.2)");
@@ -114,8 +114,8 @@ function normalizeObjectAttributePolicy(policy, E, code) {
114
114
  guard.identifier.assertKnownKeys(policy, _TPM_POLICY_KEYS, function (c, m) { return new E(c, m); }, code, "opts.tpmPolicy has an unknown key ");
115
115
  var want = {};
116
116
  if (policy.profile !== undefined) {
117
- var preset = TPM_POLICY_PROFILES[policy.profile];
118
- if (!preset) throw new E(code, "opts.tpmPolicy.profile " + JSON.stringify(policy.profile) + " is not a defined profile");
117
+ var preset = TPM_POLICY_PROFILES[guard.text.keyOf(policy.profile)];
118
+ if (!preset) throw new E(code, "opts.tpmPolicy.profile " + guard.text.showValue(policy.profile) + " is not a defined profile");
119
119
  Object.keys(preset).forEach(function (n) { want[n] = preset[n]; });
120
120
  }
121
121
  var explicit = policy.objectAttributes;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.6.22",
3
+ "version": "0.6.24",
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:79647de9-cba8-48fb-9af1-d6ec9bebf2be",
5
+ "serialNumber": "urn:uuid:1037cbc5-0592-4848-bd2e-b05cbc135e0a",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-09-02T01:10:34.456Z",
8
+ "timestamp": "2026-09-02T08:11:54.685Z",
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.6.22",
22
+ "bom-ref": "@blamejs/pki@0.6.24",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.6.22",
25
+ "version": "0.6.24",
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.6.22",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.6.24",
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.6.22",
57
+ "ref": "@blamejs/pki@0.6.24",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]