@sphereon/ssi-sdk-ext.x509-utils 0.28.1-feature.oyd.cmsm.improv.21 → 0.28.1-next.53

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.
Files changed (41) hide show
  1. package/dist/index.cjs +777 -0
  2. package/dist/index.cjs.map +1 -0
  3. package/dist/index.d.cts +173 -0
  4. package/dist/index.d.ts +171 -5
  5. package/dist/index.js +750 -21
  6. package/dist/index.js.map +1 -1
  7. package/package.json +25 -12
  8. package/src/x509/crypto.ts +11 -5
  9. package/src/x509/rsa-key.ts +8 -2
  10. package/src/x509/rsa-signer.ts +9 -5
  11. package/src/x509/x509-utils.ts +8 -5
  12. package/src/x509/x509-validator.ts +6 -3
  13. package/dist/index.d.ts.map +0 -1
  14. package/dist/types/index.d.ts +0 -14
  15. package/dist/types/index.d.ts.map +0 -1
  16. package/dist/types/index.js +0 -9
  17. package/dist/types/index.js.map +0 -1
  18. package/dist/x509/crypto.d.ts +0 -2
  19. package/dist/x509/crypto.d.ts.map +0 -1
  20. package/dist/x509/crypto.js +0 -28
  21. package/dist/x509/crypto.js.map +0 -1
  22. package/dist/x509/index.d.ts +0 -5
  23. package/dist/x509/index.d.ts.map +0 -1
  24. package/dist/x509/index.js +0 -21
  25. package/dist/x509/index.js.map +0 -1
  26. package/dist/x509/rsa-key.d.ts +0 -10
  27. package/dist/x509/rsa-key.d.ts.map +0 -1
  28. package/dist/x509/rsa-key.js +0 -102
  29. package/dist/x509/rsa-key.js.map +0 -1
  30. package/dist/x509/rsa-signer.d.ts +0 -24
  31. package/dist/x509/rsa-signer.d.ts.map +0 -1
  32. package/dist/x509/rsa-signer.js +0 -105
  33. package/dist/x509/rsa-signer.js.map +0 -1
  34. package/dist/x509/x509-utils.d.ts +0 -31
  35. package/dist/x509/x509-utils.d.ts.map +0 -1
  36. package/dist/x509/x509-utils.js +0 -215
  37. package/dist/x509/x509-utils.js.map +0 -1
  38. package/dist/x509/x509-validator.d.ts +0 -97
  39. package/dist/x509/x509-validator.d.ts.map +0 -1
  40. package/dist/x509/x509-validator.js +0 -489
  41. package/dist/x509/x509-validator.js.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,777 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var index_exports = {};
33
+ __export(index_exports, {
34
+ JwkKeyUse: () => JwkKeyUse,
35
+ PEMToBinary: () => PEMToBinary,
36
+ PEMToDer: () => PEMToDer,
37
+ PEMToHex: () => PEMToHex,
38
+ PEMToJwk: () => PEMToJwk,
39
+ RSASigner: () => RSASigner,
40
+ SubjectAlternativeGeneralName: () => SubjectAlternativeGeneralName,
41
+ areCertificatesEqual: () => areCertificatesEqual,
42
+ assertCertificateMatchesClientIdScheme: () => assertCertificateMatchesClientIdScheme,
43
+ base64ToHex: () => base64ToHex,
44
+ cryptoSubtleImportRSAKey: () => cryptoSubtleImportRSAKey,
45
+ derToPEM: () => derToPEM,
46
+ generateRSAKeyAsPEM: () => generateRSAKeyAsPEM,
47
+ getCertificateInfo: () => getCertificateInfo,
48
+ getCertificateSubjectPublicKeyJWK: () => getCertificateSubjectPublicKeyJWK,
49
+ getIssuerDN: () => getIssuerDN,
50
+ getSubjectAlternativeNames: () => getSubjectAlternativeNames,
51
+ getSubjectDN: () => getSubjectDN,
52
+ getX509AlgorithmProvider: () => getX509AlgorithmProvider,
53
+ hexKeyFromPEMBasedJwk: () => hexKeyFromPEMBasedJwk,
54
+ hexToBase64: () => hexToBase64,
55
+ hexToPEM: () => hexToPEM,
56
+ jwkToPEM: () => jwkToPEM,
57
+ parseCertificate: () => parseCertificate,
58
+ pemCertChainTox5c: () => pemCertChainTox5c,
59
+ pemOrDerToX509Certificate: () => pemOrDerToX509Certificate,
60
+ privateKeyHexFromPEM: () => privateKeyHexFromPEM,
61
+ publicKeyHexFromPEM: () => publicKeyHexFromPEM,
62
+ signAlgorithmToSchemeAndHashAlg: () => signAlgorithmToSchemeAndHashAlg,
63
+ toKeyObject: () => toKeyObject,
64
+ validateCertificateChainMatchesClientIdScheme: () => validateCertificateChainMatchesClientIdScheme,
65
+ validateX509CertificateChain: () => validateX509CertificateChain,
66
+ x5cToPemCertChain: () => x5cToPemCertChain
67
+ });
68
+ module.exports = __toCommonJS(index_exports);
69
+
70
+ // src/types/index.ts
71
+ var JwkKeyUse = /* @__PURE__ */ function(JwkKeyUse2) {
72
+ JwkKeyUse2["Encryption"] = "enc";
73
+ JwkKeyUse2["Signature"] = "sig";
74
+ return JwkKeyUse2;
75
+ }({});
76
+
77
+ // src/x509/rsa-key.ts
78
+ var u8a2 = __toESM(require("uint8arrays"), 1);
79
+
80
+ // src/x509/crypto.ts
81
+ var globalCrypto = /* @__PURE__ */ __name((setGlobal, suppliedCrypto) => {
82
+ let webcrypto;
83
+ if (typeof suppliedCrypto !== "undefined") {
84
+ webcrypto = suppliedCrypto;
85
+ } else if (typeof crypto !== "undefined") {
86
+ webcrypto = crypto;
87
+ } else if (typeof global.crypto !== "undefined") {
88
+ webcrypto = global.crypto;
89
+ } else {
90
+ if (typeof global.window?.crypto?.subtle !== "undefined") {
91
+ webcrypto = global.window.crypto;
92
+ } else {
93
+ webcrypto = require("crypto");
94
+ }
95
+ }
96
+ if (setGlobal) {
97
+ global.crypto = webcrypto;
98
+ }
99
+ return webcrypto;
100
+ }, "globalCrypto");
101
+
102
+ // src/x509/x509-utils.ts
103
+ var import_pkijs = require("pkijs");
104
+ var u8a = __toESM(require("uint8arrays"), 1);
105
+ var import_keyto = __toESM(require("@trust/keyto"), 1);
106
+ var { fromString, toString } = u8a;
107
+ function pemCertChainTox5c(cert, maxDepth) {
108
+ if (!maxDepth) {
109
+ maxDepth = 0;
110
+ }
111
+ const intermediate = cert.replace(/-----[^\n]+\n?/gm, ",").replace(/\n/g, "").replace(/\r/g, "");
112
+ let x5c = intermediate.split(",").filter(function(c) {
113
+ return c.length > 0;
114
+ });
115
+ if (maxDepth > 0) {
116
+ x5c = x5c.splice(0, maxDepth);
117
+ }
118
+ return x5c;
119
+ }
120
+ __name(pemCertChainTox5c, "pemCertChainTox5c");
121
+ function x5cToPemCertChain(x5c, maxDepth) {
122
+ if (!maxDepth) {
123
+ maxDepth = 0;
124
+ }
125
+ const length = maxDepth === 0 ? x5c.length : Math.min(maxDepth, x5c.length);
126
+ let pem = "";
127
+ for (let i = 0; i < length; i++) {
128
+ pem += derToPEM(x5c[i], "CERTIFICATE");
129
+ }
130
+ return pem;
131
+ }
132
+ __name(x5cToPemCertChain, "x5cToPemCertChain");
133
+ var pemOrDerToX509Certificate = /* @__PURE__ */ __name((cert) => {
134
+ let DER = typeof cert === "string" ? cert : void 0;
135
+ if (typeof cert === "object" && !(cert instanceof Uint8Array)) {
136
+ return import_pkijs.Certificate.fromBER(cert.rawData);
137
+ } else if (typeof cert !== "string") {
138
+ return import_pkijs.Certificate.fromBER(cert);
139
+ } else if (cert.includes("CERTIFICATE")) {
140
+ DER = PEMToDer(cert);
141
+ }
142
+ if (!DER) {
143
+ throw Error("Invalid cert input value supplied. PEM, DER, Bytes and X509Certificate object are supported");
144
+ }
145
+ return import_pkijs.Certificate.fromBER(fromString(DER, "base64pad"));
146
+ }, "pemOrDerToX509Certificate");
147
+ var areCertificatesEqual = /* @__PURE__ */ __name((cert1, cert2) => {
148
+ return cert1.signatureValue.isEqual(cert2.signatureValue);
149
+ }, "areCertificatesEqual");
150
+ var toKeyObject = /* @__PURE__ */ __name((PEM, visibility = "public") => {
151
+ const jwk = PEMToJwk(PEM, visibility);
152
+ const keyVisibility = jwk.d ? "private" : "public";
153
+ const keyHex = keyVisibility === "private" ? privateKeyHexFromPEM(PEM) : publicKeyHexFromPEM(PEM);
154
+ return {
155
+ pem: hexToPEM(keyHex, visibility),
156
+ jwk,
157
+ keyHex,
158
+ keyType: keyVisibility
159
+ };
160
+ }, "toKeyObject");
161
+ var jwkToPEM = /* @__PURE__ */ __name((jwk, visibility = "public") => {
162
+ return import_keyto.default.from(jwk, "jwk").toString("pem", visibility === "public" ? "public_pkcs8" : "private_pkcs8");
163
+ }, "jwkToPEM");
164
+ var PEMToJwk = /* @__PURE__ */ __name((pem, visibility = "public") => {
165
+ return import_keyto.default.from(pem, "pem").toJwk(visibility);
166
+ }, "PEMToJwk");
167
+ var privateKeyHexFromPEM = /* @__PURE__ */ __name((PEM) => {
168
+ return PEMToHex(PEM);
169
+ }, "privateKeyHexFromPEM");
170
+ var hexKeyFromPEMBasedJwk = /* @__PURE__ */ __name((jwk, visibility = "public") => {
171
+ if (visibility === "private") {
172
+ return privateKeyHexFromPEM(jwkToPEM(jwk, "private"));
173
+ } else {
174
+ return publicKeyHexFromPEM(jwkToPEM(jwk, "public"));
175
+ }
176
+ }, "hexKeyFromPEMBasedJwk");
177
+ var publicKeyHexFromPEM = /* @__PURE__ */ __name((PEM) => {
178
+ const hex = PEMToHex(PEM);
179
+ if (PEM.includes("CERTIFICATE")) {
180
+ throw Error("Cannot directly deduce public Key from PEM Certificate yet");
181
+ } else if (!PEM.includes("PRIVATE")) {
182
+ return hex;
183
+ }
184
+ const publicJwk = PEMToJwk(PEM, "public");
185
+ const publicPEM = jwkToPEM(publicJwk, "public");
186
+ return PEMToHex(publicPEM);
187
+ }, "publicKeyHexFromPEM");
188
+ var PEMToHex = /* @__PURE__ */ __name((PEM, headerKey) => {
189
+ if (PEM.indexOf("-----BEGIN ") == -1) {
190
+ throw Error(`PEM header not found: ${headerKey}`);
191
+ }
192
+ let strippedPem;
193
+ if (headerKey) {
194
+ strippedPem = PEM.replace(new RegExp("^[^]*-----BEGIN " + headerKey + "-----"), "");
195
+ strippedPem = strippedPem.replace(new RegExp("-----END " + headerKey + "-----[^]*$"), "");
196
+ } else {
197
+ strippedPem = PEM.replace(/^[^]*-----BEGIN [^-]+-----/, "");
198
+ strippedPem = strippedPem.replace(/-----END [^-]+-----[^]*$/, "");
199
+ }
200
+ return base64ToHex(strippedPem, "base64pad");
201
+ }, "PEMToHex");
202
+ function PEMToBinary(pem) {
203
+ const pemContents = pem.replace(/^[^]*-----BEGIN [^-]+-----/, "").replace(/-----END [^-]+-----[^]*$/, "").replace(/\s/g, "");
204
+ return fromString(pemContents, "base64pad");
205
+ }
206
+ __name(PEMToBinary, "PEMToBinary");
207
+ var base64ToHex = /* @__PURE__ */ __name((input, inputEncoding) => {
208
+ const base64NoNewlines = input.replace(/[^0-9A-Za-z_\-~\/+=]*/g, "");
209
+ return toString(fromString(base64NoNewlines, inputEncoding ? inputEncoding : "base64pad"), "base16");
210
+ }, "base64ToHex");
211
+ var hexToBase64 = /* @__PURE__ */ __name((input, targetEncoding) => {
212
+ let hex = typeof input === "string" ? input : input.toString(16);
213
+ if (hex.length % 2 === 1) {
214
+ hex = `0${hex}`;
215
+ }
216
+ return toString(fromString(hex, "base16"), targetEncoding ? targetEncoding : "base64pad");
217
+ }, "hexToBase64");
218
+ var hexToPEM = /* @__PURE__ */ __name((hex, type) => {
219
+ const base64 = hexToBase64(hex, "base64pad");
220
+ const headerKey = type === "private" ? "RSA PRIVATE KEY" : "PUBLIC KEY";
221
+ if (type === "private") {
222
+ const pem = derToPEM(base64, headerKey);
223
+ try {
224
+ PEMToJwk(pem);
225
+ return pem;
226
+ } catch (error) {
227
+ return derToPEM(base64, "PRIVATE KEY");
228
+ }
229
+ }
230
+ return derToPEM(base64, headerKey);
231
+ }, "hexToPEM");
232
+ function PEMToDer(pem) {
233
+ return pem.replace(/(-----(BEGIN|END) CERTIFICATE-----|[\n\r])/g, "");
234
+ }
235
+ __name(PEMToDer, "PEMToDer");
236
+ function derToPEM(cert, headerKey) {
237
+ const key = headerKey ?? "CERTIFICATE";
238
+ if (cert.includes(key)) {
239
+ return cert;
240
+ }
241
+ const matches = cert.match(/.{1,64}/g);
242
+ if (!matches) {
243
+ throw Error("Invalid cert input value supplied");
244
+ }
245
+ return `-----BEGIN ${key}-----
246
+ ${matches.join("\n")}
247
+ -----END ${key}-----
248
+ `;
249
+ }
250
+ __name(derToPEM, "derToPEM");
251
+
252
+ // src/x509/rsa-key.ts
253
+ var { toString: toString2 } = u8a2;
254
+ var usage = /* @__PURE__ */ __name((jwk) => {
255
+ if (jwk.key_ops && jwk.key_ops.length > 0) {
256
+ return jwk.key_ops;
257
+ }
258
+ if (jwk.use) {
259
+ const usages = [];
260
+ if (jwk.use.includes("sig")) {
261
+ usages.push("sign", "verify");
262
+ } else if (jwk.use.includes("enc")) {
263
+ usages.push("encrypt", "decrypt");
264
+ }
265
+ if (usages.length > 0) {
266
+ return usages;
267
+ }
268
+ }
269
+ if (jwk.kty === "RSA") {
270
+ if (jwk.d) {
271
+ return jwk.alg?.toUpperCase()?.includes("QAEP") ? [
272
+ "encrypt"
273
+ ] : [
274
+ "sign"
275
+ ];
276
+ }
277
+ return jwk.alg?.toUpperCase()?.includes("QAEP") ? [
278
+ "decrypt"
279
+ ] : [
280
+ "verify"
281
+ ];
282
+ }
283
+ return jwk.d && jwk.kty !== "RSA" ? [
284
+ "sign",
285
+ "decrypt",
286
+ "verify",
287
+ "encrypt"
288
+ ] : [
289
+ "verify"
290
+ ];
291
+ }, "usage");
292
+ var signAlgorithmToSchemeAndHashAlg = /* @__PURE__ */ __name((signingAlg) => {
293
+ const alg = signingAlg.toUpperCase();
294
+ let scheme;
295
+ if (alg.startsWith("RS")) {
296
+ scheme = "RSASSA-PKCS1-V1_5";
297
+ } else if (alg.startsWith("PS")) {
298
+ scheme = "RSA-PSS";
299
+ } else {
300
+ throw Error(`Invalid signing algorithm supplied ${signingAlg}`);
301
+ }
302
+ const hashAlgorithm = `SHA-${alg.substring(2)}`;
303
+ return {
304
+ scheme,
305
+ hashAlgorithm
306
+ };
307
+ }, "signAlgorithmToSchemeAndHashAlg");
308
+ var cryptoSubtleImportRSAKey = /* @__PURE__ */ __name(async (jwk, scheme, hashAlgorithm) => {
309
+ const hashName = hashAlgorithm ? hashAlgorithm : jwk.alg ? `SHA-${jwk.alg.substring(2)}` : "SHA-256";
310
+ const importParams = {
311
+ name: scheme,
312
+ hash: hashName
313
+ };
314
+ return await globalCrypto(false).subtle.importKey("jwk", jwk, importParams, false, usage(jwk));
315
+ }, "cryptoSubtleImportRSAKey");
316
+ var generateRSAKeyAsPEM = /* @__PURE__ */ __name(async (scheme, hashAlgorithm, modulusLength) => {
317
+ const hashName = hashAlgorithm ? hashAlgorithm : "SHA-256";
318
+ const params = {
319
+ name: scheme,
320
+ hash: hashName,
321
+ modulusLength: modulusLength ? modulusLength : 2048,
322
+ publicExponent: new Uint8Array([
323
+ 1,
324
+ 0,
325
+ 1
326
+ ])
327
+ };
328
+ const keyUsage = scheme === "RSA-PSS" || scheme === "RSASSA-PKCS1-V1_5" ? [
329
+ "sign",
330
+ "verify"
331
+ ] : [
332
+ "encrypt",
333
+ "decrypt"
334
+ ];
335
+ const keypair = await globalCrypto(false).subtle.generateKey(params, true, keyUsage);
336
+ const pkcs8 = await globalCrypto(false).subtle.exportKey("pkcs8", keypair.privateKey);
337
+ const uint8Array = new Uint8Array(pkcs8);
338
+ return derToPEM(toString2(uint8Array, "base64pad"), "RSA PRIVATE KEY");
339
+ }, "generateRSAKeyAsPEM");
340
+
341
+ // src/x509/rsa-signer.ts
342
+ var u8a3 = __toESM(require("uint8arrays"), 1);
343
+ var { fromString: fromString2, toString: toString3 } = u8a3;
344
+ var RSASigner = class {
345
+ static {
346
+ __name(this, "RSASigner");
347
+ }
348
+ hashAlgorithm;
349
+ jwk;
350
+ key;
351
+ scheme;
352
+ /**
353
+ *
354
+ * @param key Either in PEM or JWK format (no raw hex keys here!)
355
+ * @param opts The algorithm and signature/encryption schemes
356
+ */
357
+ constructor(key, opts) {
358
+ if (typeof key === "string") {
359
+ this.jwk = PEMToJwk(key, opts?.visibility);
360
+ } else {
361
+ this.jwk = key;
362
+ }
363
+ this.hashAlgorithm = opts?.hashAlgorithm ?? "SHA-256";
364
+ this.scheme = opts?.scheme ?? "RSA-PSS";
365
+ }
366
+ getImportParams() {
367
+ if (this.scheme === "RSA-PSS") {
368
+ return {
369
+ name: this.scheme,
370
+ saltLength: 32
371
+ };
372
+ }
373
+ return {
374
+ name: this.scheme
375
+ /*, hash: this.hashAlgorithm*/
376
+ };
377
+ }
378
+ async getKey() {
379
+ if (!this.key) {
380
+ this.key = await cryptoSubtleImportRSAKey(this.jwk, this.scheme, this.hashAlgorithm);
381
+ }
382
+ return this.key;
383
+ }
384
+ bufferToString(buf) {
385
+ const uint8Array = new Uint8Array(buf);
386
+ return toString3(uint8Array, "base64url");
387
+ }
388
+ async sign(data) {
389
+ const input = data;
390
+ const key = await this.getKey();
391
+ const signature = this.bufferToString(await globalCrypto(false).subtle.sign(this.getImportParams(), key, input));
392
+ if (!signature) {
393
+ throw Error("Could not sign input data");
394
+ }
395
+ return signature;
396
+ }
397
+ async verify(data, signature) {
398
+ const jws = signature.includes(".") ? signature.split(".")[2] : signature;
399
+ const input = typeof data == "string" ? fromString2(data, "utf-8") : data;
400
+ let key = await this.getKey();
401
+ if (!key.usages.includes("verify")) {
402
+ const verifyJwk = {
403
+ ...this.jwk
404
+ };
405
+ delete verifyJwk.d;
406
+ delete verifyJwk.use;
407
+ delete verifyJwk.key_ops;
408
+ key = await cryptoSubtleImportRSAKey(verifyJwk, this.scheme, this.hashAlgorithm);
409
+ }
410
+ const verificationResult = await globalCrypto(false).subtle.verify(this.getImportParams(), key, fromString2(jws, "base64url"), input);
411
+ return verificationResult;
412
+ }
413
+ };
414
+
415
+ // src/x509/x509-validator.ts
416
+ var import_asn1_schema = require("@peculiar/asn1-schema");
417
+ var import_asn1_x509 = require("@peculiar/asn1-x509");
418
+ var import_x509 = require("@peculiar/x509");
419
+ var import_js_x509_utils = __toESM(require("js-x509-utils"), 1);
420
+ var import_pkijs2 = require("pkijs");
421
+ var import_tsyringe = require("tsyringe");
422
+ var u8a4 = __toESM(require("uint8arrays"), 1);
423
+ var { fromString: fromString3, toString: toString4 } = u8a4;
424
+ var defaultCryptoEngine = /* @__PURE__ */ __name(() => {
425
+ const name = "crypto";
426
+ (0, import_pkijs2.setEngine)(name, new import_pkijs2.CryptoEngine({
427
+ name,
428
+ crypto: globalCrypto(false)
429
+ }));
430
+ return (0, import_pkijs2.getCrypto)(true);
431
+ }, "defaultCryptoEngine");
432
+ var getCertificateInfo = /* @__PURE__ */ __name(async (certificate, opts) => {
433
+ let publicKeyJWK;
434
+ try {
435
+ publicKeyJWK = await getCertificateSubjectPublicKeyJWK(certificate);
436
+ } catch (e) {
437
+ }
438
+ return {
439
+ issuer: {
440
+ dn: getIssuerDN(certificate)
441
+ },
442
+ subject: {
443
+ dn: getSubjectDN(certificate),
444
+ subjectAlternativeNames: getSubjectAlternativeNames(certificate, {
445
+ typeFilter: opts?.sanTypeFilter
446
+ })
447
+ },
448
+ publicKeyJWK,
449
+ notBefore: certificate.notBefore.value,
450
+ notAfter: certificate.notAfter.value
451
+ };
452
+ }, "getCertificateInfo");
453
+ var validateX509CertificateChain = /* @__PURE__ */ __name(async ({ chain: pemOrDerChain, trustAnchors, verificationTime = /* @__PURE__ */ new Date(), opts = {
454
+ // If no trust anchor is found, but the chain itself checks out, allow. (defaults to false:)
455
+ allowNoTrustAnchorsFound: false,
456
+ trustRootWhenNoAnchors: false,
457
+ allowSingleNoCAChainElement: true,
458
+ blindlyTrustedAnchors: [],
459
+ disallowReversedChain: false
460
+ } }) => {
461
+ return await validateX509CertificateChainImpl({
462
+ reversed: false,
463
+ chain: [
464
+ ...pemOrDerChain
465
+ ].reverse(),
466
+ trustAnchors,
467
+ verificationTime,
468
+ opts
469
+ });
470
+ }, "validateX509CertificateChain");
471
+ var validateX509CertificateChainImpl = /* @__PURE__ */ __name(async ({ reversed, chain: pemOrDerChain, trustAnchors, verificationTime: verifyAt, opts }) => {
472
+ const verificationTime = typeof verifyAt === "string" ? new Date(verifyAt) : verifyAt;
473
+ const { allowNoTrustAnchorsFound = false, trustRootWhenNoAnchors = false, allowSingleNoCAChainElement = true, blindlyTrustedAnchors = [], disallowReversedChain = false, client } = opts;
474
+ const trustedPEMs = trustRootWhenNoAnchors && !trustAnchors ? [
475
+ pemOrDerChain[pemOrDerChain.length - 1]
476
+ ] : trustAnchors;
477
+ if (pemOrDerChain.length === 0) {
478
+ return {
479
+ error: true,
480
+ critical: true,
481
+ message: "Certificate chain in DER or PEM format must not be empty",
482
+ verificationTime
483
+ };
484
+ }
485
+ defaultCryptoEngine();
486
+ const chain = await Promise.all(pemOrDerChain.map((raw) => parseCertificate(raw)));
487
+ const x5cOrdereredChain = reversed ? [
488
+ ...chain
489
+ ] : [
490
+ ...chain
491
+ ].reverse();
492
+ const trustedCerts = trustedPEMs ? await Promise.all(trustedPEMs.map((raw) => parseCertificate(raw))) : void 0;
493
+ const blindlyTrusted = (await Promise.all(blindlyTrustedAnchors.map((raw) => {
494
+ try {
495
+ return parseCertificate(raw);
496
+ } catch (e) {
497
+ console.log(`Failed to parse blindly trusted certificate ${raw}. Error: ${e.message}`);
498
+ return void 0;
499
+ }
500
+ }))).filter((cert) => cert !== void 0) ?? [];
501
+ const leafCert = x5cOrdereredChain[0];
502
+ const chainLength = chain.length;
503
+ var foundTrustAnchor = void 0;
504
+ for (let i = 0; i < chainLength; i++) {
505
+ const currentCert = chain[i];
506
+ const previousCert = i > 0 ? chain[i - 1] : void 0;
507
+ const blindlyTrustedCert = blindlyTrusted.find((trusted) => areCertificatesEqual(trusted.certificate, currentCert.certificate));
508
+ if (blindlyTrustedCert) {
509
+ console.log(`Certificate chain validation success as single cert if blindly trusted. WARNING: ONLY USE FOR TESTING PURPOSES.`);
510
+ return {
511
+ error: false,
512
+ critical: false,
513
+ message: `Certificate chain validation success as single cert if blindly trusted. WARNING: ONLY USE FOR TESTING PURPOSES.`,
514
+ detailMessage: `Blindly trusted certificate ${blindlyTrustedCert.certificateInfo.subject.dn.DN} was found in the chain.`,
515
+ trustAnchor: blindlyTrustedCert?.certificateInfo,
516
+ verificationTime,
517
+ certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),
518
+ ...client && {
519
+ client
520
+ }
521
+ };
522
+ }
523
+ if (previousCert) {
524
+ if (currentCert.x509Certificate.issuer !== previousCert.x509Certificate.subject) {
525
+ if (!reversed && !disallowReversedChain) {
526
+ return await validateX509CertificateChainImpl({
527
+ reversed: true,
528
+ chain: [
529
+ ...pemOrDerChain
530
+ ].reverse(),
531
+ opts,
532
+ verificationTime,
533
+ trustAnchors
534
+ });
535
+ }
536
+ return {
537
+ error: true,
538
+ critical: true,
539
+ certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),
540
+ message: `Certificate chain validation failed for ${leafCert.certificateInfo.subject.dn.DN}.`,
541
+ detailMessage: `The certificate ${currentCert.certificateInfo.subject.dn.DN} with issuer ${currentCert.x509Certificate.issuer}, is not signed by the previous certificate ${previousCert?.certificateInfo.subject.dn.DN} with subject string ${previousCert?.x509Certificate.subject}.`,
542
+ verificationTime,
543
+ ...client && {
544
+ client
545
+ }
546
+ };
547
+ }
548
+ }
549
+ const result = await currentCert.x509Certificate.verify({
550
+ date: verificationTime,
551
+ publicKey: previousCert?.x509Certificate?.publicKey
552
+ }, (0, import_pkijs2.getCrypto)()?.crypto ?? crypto ?? global.crypto);
553
+ if (!result) {
554
+ if (i == 0 && !reversed && !disallowReversedChain) {
555
+ return await validateX509CertificateChainImpl({
556
+ reversed: true,
557
+ chain: [
558
+ ...pemOrDerChain
559
+ ].reverse(),
560
+ opts,
561
+ verificationTime,
562
+ trustAnchors
563
+ });
564
+ }
565
+ return {
566
+ error: true,
567
+ critical: true,
568
+ message: `Certificate chain validation failed for ${leafCert.certificateInfo.subject.dn.DN}.`,
569
+ certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),
570
+ detailMessage: `Verification of the certificate ${currentCert.certificateInfo.subject.dn.DN} with issuer ${currentCert.x509Certificate.issuer} failed. Public key: ${JSON.stringify(currentCert.certificateInfo.publicKeyJWK)}.`,
571
+ verificationTime,
572
+ ...client && {
573
+ client
574
+ }
575
+ };
576
+ }
577
+ foundTrustAnchor = foundTrustAnchor ?? trustedCerts?.find((trusted) => isSameCertificate(trusted.x509Certificate, currentCert.x509Certificate));
578
+ if (i === 0 && chainLength === 1 && allowSingleNoCAChainElement) {
579
+ return {
580
+ error: false,
581
+ critical: false,
582
+ message: `Certificate chain succeeded as allow single cert result is allowed: ${leafCert.certificateInfo.subject.dn.DN}.`,
583
+ certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),
584
+ trustAnchor: foundTrustAnchor?.certificateInfo,
585
+ verificationTime,
586
+ ...client && {
587
+ client
588
+ }
589
+ };
590
+ }
591
+ }
592
+ if (foundTrustAnchor?.certificateInfo || allowNoTrustAnchorsFound) {
593
+ return {
594
+ error: false,
595
+ critical: false,
596
+ message: `Certificate chain was valid`,
597
+ certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),
598
+ detailMessage: foundTrustAnchor ? `The leaf certificate ${leafCert.certificateInfo.subject.dn.DN} is part of a chain with trust anchor ${foundTrustAnchor?.certificateInfo.subject.dn.DN}.` : `The leaf certificate ${leafCert.certificateInfo.subject.dn.DN} and chain were valid, but no trust anchor has been found. Ignoring as user allowed (allowNoTrustAnchorsFound: ${allowNoTrustAnchorsFound}).)`,
599
+ trustAnchor: foundTrustAnchor?.certificateInfo,
600
+ verificationTime,
601
+ ...client && {
602
+ client
603
+ }
604
+ };
605
+ }
606
+ return {
607
+ error: true,
608
+ critical: true,
609
+ message: `Certificate chain validation failed for ${leafCert.certificateInfo.subject.dn.DN}.`,
610
+ certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),
611
+ detailMessage: `No trust anchor was found in the chain. between (intermediate) CA ${x5cOrdereredChain[chain.length - 1].certificateInfo.subject.dn.DN} and leaf ${x5cOrdereredChain[0].certificateInfo.subject.dn.DN}.`,
612
+ verificationTime,
613
+ ...client && {
614
+ client
615
+ }
616
+ };
617
+ }, "validateX509CertificateChainImpl");
618
+ var isSameCertificate = /* @__PURE__ */ __name((cert1, cert2) => {
619
+ return cert1.rawData.toString() === cert2.rawData.toString();
620
+ }, "isSameCertificate");
621
+ var algorithmProvider = import_tsyringe.container.resolve(import_x509.AlgorithmProvider);
622
+ var getX509AlgorithmProvider = /* @__PURE__ */ __name(() => {
623
+ return algorithmProvider;
624
+ }, "getX509AlgorithmProvider");
625
+ var parseCertificate = /* @__PURE__ */ __name(async (rawCert) => {
626
+ const x509Certificate = new import_x509.X509Certificate(rawCert);
627
+ const publicKeyInfo = import_asn1_schema.AsnParser.parse(x509Certificate.publicKey.rawData, import_asn1_x509.SubjectPublicKeyInfo);
628
+ const publicKeyRaw = new Uint8Array(publicKeyInfo.subjectPublicKey);
629
+ let publicKeyJwk = void 0;
630
+ try {
631
+ publicKeyJwk = await getCertificateSubjectPublicKeyJWK(new Uint8Array(x509Certificate.rawData));
632
+ } catch (e) {
633
+ console.error(e.message);
634
+ }
635
+ const certificate = pemOrDerToX509Certificate(rawCert);
636
+ const certificateInfo = await getCertificateInfo(certificate);
637
+ const publicKeyAlgorithm = getX509AlgorithmProvider().toWebAlgorithm(publicKeyInfo.algorithm);
638
+ return {
639
+ publicKeyAlgorithm,
640
+ publicKeyInfo,
641
+ publicKeyJwk,
642
+ publicKeyRaw,
643
+ certificateInfo,
644
+ certificate,
645
+ x509Certificate
646
+ };
647
+ }, "parseCertificate");
648
+ var rdnmap = {
649
+ "2.5.4.6": "C",
650
+ "2.5.4.10": "O",
651
+ "2.5.4.11": "OU",
652
+ "2.5.4.3": "CN",
653
+ "2.5.4.7": "L",
654
+ "2.5.4.8": "ST",
655
+ "2.5.4.12": "T",
656
+ "2.5.4.42": "GN",
657
+ "2.5.4.43": "I",
658
+ "2.5.4.4": "SN",
659
+ "1.2.840.113549.1.9.1": "E-mail"
660
+ };
661
+ var getIssuerDN = /* @__PURE__ */ __name((cert) => {
662
+ return {
663
+ DN: getDNString(cert.issuer.typesAndValues),
664
+ attributes: getDNObject(cert.issuer.typesAndValues)
665
+ };
666
+ }, "getIssuerDN");
667
+ var getSubjectDN = /* @__PURE__ */ __name((cert) => {
668
+ return {
669
+ DN: getDNString(cert.subject.typesAndValues),
670
+ attributes: getDNObject(cert.subject.typesAndValues)
671
+ };
672
+ }, "getSubjectDN");
673
+ var getDNObject = /* @__PURE__ */ __name((typesAndValues) => {
674
+ const DN = {};
675
+ for (const typeAndValue of typesAndValues) {
676
+ const type = rdnmap[typeAndValue.type] ?? typeAndValue.type;
677
+ DN[type] = typeAndValue.value.getValue();
678
+ }
679
+ return DN;
680
+ }, "getDNObject");
681
+ var getDNString = /* @__PURE__ */ __name((typesAndValues) => {
682
+ return Object.entries(getDNObject(typesAndValues)).map(([key, value]) => `${key}=${value}`).join(",");
683
+ }, "getDNString");
684
+ var getCertificateSubjectPublicKeyJWK = /* @__PURE__ */ __name(async (pemOrDerCert) => {
685
+ const pemOrDerStr = typeof pemOrDerCert === "string" ? toString4(fromString3(pemOrDerCert, "base64pad"), "base64pad") : pemOrDerCert instanceof Uint8Array ? toString4(pemOrDerCert, "base64pad") : toString4(fromString3(pemOrDerCert.toString("base64"), "base64pad"), "base64pad");
686
+ const pem = derToPEM(pemOrDerStr);
687
+ const certificate = pemOrDerToX509Certificate(pem);
688
+ var jwk;
689
+ try {
690
+ const subtle = (0, import_pkijs2.getCrypto)(true).subtle;
691
+ const pk = await certificate.getPublicKey(void 0, defaultCryptoEngine());
692
+ jwk = await subtle.exportKey("jwk", pk);
693
+ } catch (error) {
694
+ console.log(`Error in primary get JWK from cert:`, error?.message);
695
+ }
696
+ if (!jwk) {
697
+ try {
698
+ jwk = await import_js_x509_utils.default.toJwk(pem, "pem");
699
+ } catch (error) {
700
+ console.log(`Error in secondary get JWK from cert as well:`, error?.message);
701
+ }
702
+ }
703
+ if (!jwk) {
704
+ throw Error(`Failed to get JWK from certificate ${pem}`);
705
+ }
706
+ return jwk;
707
+ }, "getCertificateSubjectPublicKeyJWK");
708
+ var SubjectAlternativeGeneralName = /* @__PURE__ */ function(SubjectAlternativeGeneralName2) {
709
+ SubjectAlternativeGeneralName2[SubjectAlternativeGeneralName2["rfc822Name"] = 1] = "rfc822Name";
710
+ SubjectAlternativeGeneralName2[SubjectAlternativeGeneralName2["dnsName"] = 2] = "dnsName";
711
+ SubjectAlternativeGeneralName2[SubjectAlternativeGeneralName2["uniformResourceIdentifier"] = 6] = "uniformResourceIdentifier";
712
+ SubjectAlternativeGeneralName2[SubjectAlternativeGeneralName2["ipAddress"] = 7] = "ipAddress";
713
+ return SubjectAlternativeGeneralName2;
714
+ }({});
715
+ var assertCertificateMatchesClientIdScheme = /* @__PURE__ */ __name((certificate, clientId, clientIdScheme) => {
716
+ const sans = getSubjectAlternativeNames(certificate, {
717
+ clientIdSchemeFilter: clientIdScheme
718
+ });
719
+ const clientIdMatches = sans.find((san) => san.value === clientId);
720
+ if (!clientIdMatches) {
721
+ throw Error(`Client id scheme ${clientIdScheme} used had no matching subject alternative names in certificate with DN ${getSubjectDN(certificate).DN}. SANS: ${sans.map((san) => san.value).join(",")}`);
722
+ }
723
+ }, "assertCertificateMatchesClientIdScheme");
724
+ var validateCertificateChainMatchesClientIdScheme = /* @__PURE__ */ __name(async (certificate, clientId, clientIdScheme) => {
725
+ const result = {
726
+ error: true,
727
+ critical: true,
728
+ message: `Client Id ${clientId} was not present in certificate using scheme ${clientIdScheme}`,
729
+ client: {
730
+ clientId,
731
+ clientIdScheme
732
+ },
733
+ certificateChain: [
734
+ await getCertificateInfo(certificate)
735
+ ],
736
+ verificationTime: /* @__PURE__ */ new Date()
737
+ };
738
+ try {
739
+ assertCertificateMatchesClientIdScheme(certificate, clientId, clientIdScheme);
740
+ } catch (error) {
741
+ return result;
742
+ }
743
+ result.error = false;
744
+ result.message = `Client Id ${clientId} was present in certificate using scheme ${clientIdScheme}`;
745
+ return result;
746
+ }, "validateCertificateChainMatchesClientIdScheme");
747
+ var getSubjectAlternativeNames = /* @__PURE__ */ __name((certificate, opts) => {
748
+ let typeFilter;
749
+ if (opts?.clientIdSchemeFilter) {
750
+ typeFilter = opts.clientIdSchemeFilter === "x509_san_dns" ? [
751
+ 2
752
+ ] : [
753
+ 6
754
+ ];
755
+ } else if (opts?.typeFilter) {
756
+ typeFilter = Array.isArray(opts.typeFilter) ? opts.typeFilter : [
757
+ opts.typeFilter
758
+ ];
759
+ } else {
760
+ typeFilter = [
761
+ 2,
762
+ 6
763
+ ];
764
+ }
765
+ const parsedValue = certificate.extensions?.find((ext) => ext.extnID === import_pkijs2.id_SubjectAltName)?.parsedValue;
766
+ if (!parsedValue) {
767
+ return [];
768
+ }
769
+ const altNames = parsedValue.toJSON().altNames;
770
+ return altNames.filter((altName) => typeFilter.includes(altName.type)).map((altName) => {
771
+ return {
772
+ type: altName.type,
773
+ value: altName.value
774
+ };
775
+ });
776
+ }, "getSubjectAlternativeNames");
777
+ //# sourceMappingURL=index.cjs.map