@sphereon/ssi-sdk-ext.x509-utils 0.28.1-feature.esm.cjs.8 → 0.28.1-feature.oyd.cmsm.improv.16

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.d.ts +5 -171
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +21 -749
  4. package/dist/index.js.map +1 -1
  5. package/dist/types/index.d.ts +14 -0
  6. package/dist/types/index.d.ts.map +1 -0
  7. package/dist/types/index.js +9 -0
  8. package/dist/types/index.js.map +1 -0
  9. package/dist/x509/crypto.d.ts +2 -0
  10. package/dist/x509/crypto.d.ts.map +1 -0
  11. package/dist/x509/crypto.js +28 -0
  12. package/dist/x509/crypto.js.map +1 -0
  13. package/dist/x509/index.d.ts +5 -0
  14. package/dist/x509/index.d.ts.map +1 -0
  15. package/dist/x509/index.js +21 -0
  16. package/dist/x509/index.js.map +1 -0
  17. package/dist/x509/rsa-key.d.ts +10 -0
  18. package/dist/x509/rsa-key.d.ts.map +1 -0
  19. package/dist/x509/rsa-key.js +102 -0
  20. package/dist/x509/rsa-key.js.map +1 -0
  21. package/dist/x509/rsa-signer.d.ts +24 -0
  22. package/dist/x509/rsa-signer.d.ts.map +1 -0
  23. package/dist/x509/rsa-signer.js +105 -0
  24. package/dist/x509/rsa-signer.js.map +1 -0
  25. package/dist/x509/x509-utils.d.ts +31 -0
  26. package/dist/x509/x509-utils.d.ts.map +1 -0
  27. package/dist/x509/x509-utils.js +215 -0
  28. package/dist/x509/x509-utils.js.map +1 -0
  29. package/dist/x509/x509-validator.d.ts +97 -0
  30. package/dist/x509/x509-validator.d.ts.map +1 -0
  31. package/dist/x509/x509-validator.js +489 -0
  32. package/dist/x509/x509-validator.js.map +1 -0
  33. package/package.json +12 -24
  34. package/src/x509/crypto.ts +5 -11
  35. package/src/x509/rsa-key.ts +2 -7
  36. package/src/x509/rsa-signer.ts +5 -10
  37. package/src/x509/x509-utils.ts +5 -9
  38. package/src/x509/x509-validator.ts +4 -8
  39. package/dist/index.cjs +0 -776
  40. package/dist/index.cjs.map +0 -1
  41. package/dist/index.d.cts +0 -173
package/dist/index.cjs DELETED
@@ -1,776 +0,0 @@
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 import_to_string2 = require("uint8arrays/to-string");
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 import_from_string = require("uint8arrays/from-string");
105
- var import_to_string = require("uint8arrays/to-string");
106
- var import_keyto = __toESM(require("@trust/keyto"), 1);
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((0, import_from_string.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 (0, import_from_string.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 (0, import_to_string.toString)((0, import_from_string.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 (0, import_to_string.toString)((0, import_from_string.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 usage = /* @__PURE__ */ __name((jwk) => {
254
- if (jwk.key_ops && jwk.key_ops.length > 0) {
255
- return jwk.key_ops;
256
- }
257
- if (jwk.use) {
258
- const usages = [];
259
- if (jwk.use.includes("sig")) {
260
- usages.push("sign", "verify");
261
- } else if (jwk.use.includes("enc")) {
262
- usages.push("encrypt", "decrypt");
263
- }
264
- if (usages.length > 0) {
265
- return usages;
266
- }
267
- }
268
- if (jwk.kty === "RSA") {
269
- if (jwk.d) {
270
- return jwk.alg?.toUpperCase()?.includes("QAEP") ? [
271
- "encrypt"
272
- ] : [
273
- "sign"
274
- ];
275
- }
276
- return jwk.alg?.toUpperCase()?.includes("QAEP") ? [
277
- "decrypt"
278
- ] : [
279
- "verify"
280
- ];
281
- }
282
- return jwk.d && jwk.kty !== "RSA" ? [
283
- "sign",
284
- "decrypt",
285
- "verify",
286
- "encrypt"
287
- ] : [
288
- "verify"
289
- ];
290
- }, "usage");
291
- var signAlgorithmToSchemeAndHashAlg = /* @__PURE__ */ __name((signingAlg) => {
292
- const alg = signingAlg.toUpperCase();
293
- let scheme;
294
- if (alg.startsWith("RS")) {
295
- scheme = "RSASSA-PKCS1-V1_5";
296
- } else if (alg.startsWith("PS")) {
297
- scheme = "RSA-PSS";
298
- } else {
299
- throw Error(`Invalid signing algorithm supplied ${signingAlg}`);
300
- }
301
- const hashAlgorithm = `SHA-${alg.substring(2)}`;
302
- return {
303
- scheme,
304
- hashAlgorithm
305
- };
306
- }, "signAlgorithmToSchemeAndHashAlg");
307
- var cryptoSubtleImportRSAKey = /* @__PURE__ */ __name(async (jwk, scheme, hashAlgorithm) => {
308
- const hashName = hashAlgorithm ? hashAlgorithm : jwk.alg ? `SHA-${jwk.alg.substring(2)}` : "SHA-256";
309
- const importParams = {
310
- name: scheme,
311
- hash: hashName
312
- };
313
- return await globalCrypto(false).subtle.importKey("jwk", jwk, importParams, false, usage(jwk));
314
- }, "cryptoSubtleImportRSAKey");
315
- var generateRSAKeyAsPEM = /* @__PURE__ */ __name(async (scheme, hashAlgorithm, modulusLength) => {
316
- const hashName = hashAlgorithm ? hashAlgorithm : "SHA-256";
317
- const params = {
318
- name: scheme,
319
- hash: hashName,
320
- modulusLength: modulusLength ? modulusLength : 2048,
321
- publicExponent: new Uint8Array([
322
- 1,
323
- 0,
324
- 1
325
- ])
326
- };
327
- const keyUsage = scheme === "RSA-PSS" || scheme === "RSASSA-PKCS1-V1_5" ? [
328
- "sign",
329
- "verify"
330
- ] : [
331
- "encrypt",
332
- "decrypt"
333
- ];
334
- const keypair = await globalCrypto(false).subtle.generateKey(params, true, keyUsage);
335
- const pkcs8 = await globalCrypto(false).subtle.exportKey("pkcs8", keypair.privateKey);
336
- const uint8Array = new Uint8Array(pkcs8);
337
- return derToPEM((0, import_to_string2.toString)(uint8Array, "base64pad"), "RSA PRIVATE KEY");
338
- }, "generateRSAKeyAsPEM");
339
-
340
- // src/x509/rsa-signer.ts
341
- var import_from_string2 = require("uint8arrays/from-string");
342
- var import_to_string3 = require("uint8arrays/to-string");
343
- var RSASigner = class {
344
- static {
345
- __name(this, "RSASigner");
346
- }
347
- hashAlgorithm;
348
- jwk;
349
- key;
350
- scheme;
351
- /**
352
- *
353
- * @param key Either in PEM or JWK format (no raw hex keys here!)
354
- * @param opts The algorithm and signature/encryption schemes
355
- */
356
- constructor(key, opts) {
357
- if (typeof key === "string") {
358
- this.jwk = PEMToJwk(key, opts?.visibility);
359
- } else {
360
- this.jwk = key;
361
- }
362
- this.hashAlgorithm = opts?.hashAlgorithm ?? "SHA-256";
363
- this.scheme = opts?.scheme ?? "RSA-PSS";
364
- }
365
- getImportParams() {
366
- if (this.scheme === "RSA-PSS") {
367
- return {
368
- name: this.scheme,
369
- saltLength: 32
370
- };
371
- }
372
- return {
373
- name: this.scheme
374
- /*, hash: this.hashAlgorithm*/
375
- };
376
- }
377
- async getKey() {
378
- if (!this.key) {
379
- this.key = await cryptoSubtleImportRSAKey(this.jwk, this.scheme, this.hashAlgorithm);
380
- }
381
- return this.key;
382
- }
383
- bufferToString(buf) {
384
- const uint8Array = new Uint8Array(buf);
385
- return (0, import_to_string3.toString)(uint8Array, "base64url");
386
- }
387
- async sign(data) {
388
- const input = data;
389
- const key = await this.getKey();
390
- const signature = this.bufferToString(await globalCrypto(false).subtle.sign(this.getImportParams(), key, input));
391
- if (!signature) {
392
- throw Error("Could not sign input data");
393
- }
394
- return signature;
395
- }
396
- async verify(data, signature) {
397
- const jws = signature.includes(".") ? signature.split(".")[2] : signature;
398
- const input = typeof data == "string" ? (0, import_from_string2.fromString)(data, "utf-8") : data;
399
- let key = await this.getKey();
400
- if (!key.usages.includes("verify")) {
401
- const verifyJwk = {
402
- ...this.jwk
403
- };
404
- delete verifyJwk.d;
405
- delete verifyJwk.use;
406
- delete verifyJwk.key_ops;
407
- key = await cryptoSubtleImportRSAKey(verifyJwk, this.scheme, this.hashAlgorithm);
408
- }
409
- const verificationResult = await globalCrypto(false).subtle.verify(this.getImportParams(), key, (0, import_from_string2.fromString)(jws, "base64url"), input);
410
- return verificationResult;
411
- }
412
- };
413
-
414
- // src/x509/x509-validator.ts
415
- var import_asn1_schema = require("@peculiar/asn1-schema");
416
- var import_asn1_x509 = require("@peculiar/asn1-x509");
417
- var import_x509 = require("@peculiar/x509");
418
- var import_js_x509_utils = __toESM(require("js-x509-utils"), 1);
419
- var import_pkijs2 = require("pkijs");
420
- var import_tsyringe = require("tsyringe");
421
- var import_from_string3 = require("uint8arrays/from-string");
422
- var import_to_string4 = require("uint8arrays/to-string");
423
- var defaultCryptoEngine = /* @__PURE__ */ __name(() => {
424
- const name = "crypto";
425
- (0, import_pkijs2.setEngine)(name, new import_pkijs2.CryptoEngine({
426
- name,
427
- crypto: globalCrypto(false)
428
- }));
429
- return (0, import_pkijs2.getCrypto)(true);
430
- }, "defaultCryptoEngine");
431
- var getCertificateInfo = /* @__PURE__ */ __name(async (certificate, opts) => {
432
- let publicKeyJWK;
433
- try {
434
- publicKeyJWK = await getCertificateSubjectPublicKeyJWK(certificate);
435
- } catch (e) {
436
- }
437
- return {
438
- issuer: {
439
- dn: getIssuerDN(certificate)
440
- },
441
- subject: {
442
- dn: getSubjectDN(certificate),
443
- subjectAlternativeNames: getSubjectAlternativeNames(certificate, {
444
- typeFilter: opts?.sanTypeFilter
445
- })
446
- },
447
- publicKeyJWK,
448
- notBefore: certificate.notBefore.value,
449
- notAfter: certificate.notAfter.value
450
- };
451
- }, "getCertificateInfo");
452
- var validateX509CertificateChain = /* @__PURE__ */ __name(async ({ chain: pemOrDerChain, trustAnchors, verificationTime = /* @__PURE__ */ new Date(), opts = {
453
- // If no trust anchor is found, but the chain itself checks out, allow. (defaults to false:)
454
- allowNoTrustAnchorsFound: false,
455
- trustRootWhenNoAnchors: false,
456
- allowSingleNoCAChainElement: true,
457
- blindlyTrustedAnchors: [],
458
- disallowReversedChain: false
459
- } }) => {
460
- return await validateX509CertificateChainImpl({
461
- reversed: false,
462
- chain: [
463
- ...pemOrDerChain
464
- ].reverse(),
465
- trustAnchors,
466
- verificationTime,
467
- opts
468
- });
469
- }, "validateX509CertificateChain");
470
- var validateX509CertificateChainImpl = /* @__PURE__ */ __name(async ({ reversed, chain: pemOrDerChain, trustAnchors, verificationTime: verifyAt, opts }) => {
471
- const verificationTime = typeof verifyAt === "string" ? new Date(verifyAt) : verifyAt;
472
- const { allowNoTrustAnchorsFound = false, trustRootWhenNoAnchors = false, allowSingleNoCAChainElement = true, blindlyTrustedAnchors = [], disallowReversedChain = false, client } = opts;
473
- const trustedPEMs = trustRootWhenNoAnchors && !trustAnchors ? [
474
- pemOrDerChain[pemOrDerChain.length - 1]
475
- ] : trustAnchors;
476
- if (pemOrDerChain.length === 0) {
477
- return {
478
- error: true,
479
- critical: true,
480
- message: "Certificate chain in DER or PEM format must not be empty",
481
- verificationTime
482
- };
483
- }
484
- defaultCryptoEngine();
485
- const chain = await Promise.all(pemOrDerChain.map((raw) => parseCertificate(raw)));
486
- const x5cOrdereredChain = reversed ? [
487
- ...chain
488
- ] : [
489
- ...chain
490
- ].reverse();
491
- const trustedCerts = trustedPEMs ? await Promise.all(trustedPEMs.map((raw) => parseCertificate(raw))) : void 0;
492
- const blindlyTrusted = (await Promise.all(blindlyTrustedAnchors.map((raw) => {
493
- try {
494
- return parseCertificate(raw);
495
- } catch (e) {
496
- console.log(`Failed to parse blindly trusted certificate ${raw}. Error: ${e.message}`);
497
- return void 0;
498
- }
499
- }))).filter((cert) => cert !== void 0) ?? [];
500
- const leafCert = x5cOrdereredChain[0];
501
- const chainLength = chain.length;
502
- var foundTrustAnchor = void 0;
503
- for (let i = 0; i < chainLength; i++) {
504
- const currentCert = chain[i];
505
- const previousCert = i > 0 ? chain[i - 1] : void 0;
506
- const blindlyTrustedCert = blindlyTrusted.find((trusted) => areCertificatesEqual(trusted.certificate, currentCert.certificate));
507
- if (blindlyTrustedCert) {
508
- console.log(`Certificate chain validation success as single cert if blindly trusted. WARNING: ONLY USE FOR TESTING PURPOSES.`);
509
- return {
510
- error: false,
511
- critical: false,
512
- message: `Certificate chain validation success as single cert if blindly trusted. WARNING: ONLY USE FOR TESTING PURPOSES.`,
513
- detailMessage: `Blindly trusted certificate ${blindlyTrustedCert.certificateInfo.subject.dn.DN} was found in the chain.`,
514
- trustAnchor: blindlyTrustedCert?.certificateInfo,
515
- verificationTime,
516
- certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),
517
- ...client && {
518
- client
519
- }
520
- };
521
- }
522
- if (previousCert) {
523
- if (currentCert.x509Certificate.issuer !== previousCert.x509Certificate.subject) {
524
- if (!reversed && !disallowReversedChain) {
525
- return await validateX509CertificateChainImpl({
526
- reversed: true,
527
- chain: [
528
- ...pemOrDerChain
529
- ].reverse(),
530
- opts,
531
- verificationTime,
532
- trustAnchors
533
- });
534
- }
535
- return {
536
- error: true,
537
- critical: true,
538
- certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),
539
- message: `Certificate chain validation failed for ${leafCert.certificateInfo.subject.dn.DN}.`,
540
- 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}.`,
541
- verificationTime,
542
- ...client && {
543
- client
544
- }
545
- };
546
- }
547
- }
548
- const result = await currentCert.x509Certificate.verify({
549
- date: verificationTime,
550
- publicKey: previousCert?.x509Certificate?.publicKey
551
- }, (0, import_pkijs2.getCrypto)()?.crypto ?? crypto ?? global.crypto);
552
- if (!result) {
553
- if (i == 0 && !reversed && !disallowReversedChain) {
554
- return await validateX509CertificateChainImpl({
555
- reversed: true,
556
- chain: [
557
- ...pemOrDerChain
558
- ].reverse(),
559
- opts,
560
- verificationTime,
561
- trustAnchors
562
- });
563
- }
564
- return {
565
- error: true,
566
- critical: true,
567
- message: `Certificate chain validation failed for ${leafCert.certificateInfo.subject.dn.DN}.`,
568
- certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),
569
- detailMessage: `Verification of the certificate ${currentCert.certificateInfo.subject.dn.DN} with issuer ${currentCert.x509Certificate.issuer} failed. Public key: ${JSON.stringify(currentCert.certificateInfo.publicKeyJWK)}.`,
570
- verificationTime,
571
- ...client && {
572
- client
573
- }
574
- };
575
- }
576
- foundTrustAnchor = foundTrustAnchor ?? trustedCerts?.find((trusted) => isSameCertificate(trusted.x509Certificate, currentCert.x509Certificate));
577
- if (i === 0 && chainLength === 1 && allowSingleNoCAChainElement) {
578
- return {
579
- error: false,
580
- critical: false,
581
- message: `Certificate chain succeeded as allow single cert result is allowed: ${leafCert.certificateInfo.subject.dn.DN}.`,
582
- certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),
583
- trustAnchor: foundTrustAnchor?.certificateInfo,
584
- verificationTime,
585
- ...client && {
586
- client
587
- }
588
- };
589
- }
590
- }
591
- if (foundTrustAnchor?.certificateInfo || allowNoTrustAnchorsFound) {
592
- return {
593
- error: false,
594
- critical: false,
595
- message: `Certificate chain was valid`,
596
- certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),
597
- 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}).)`,
598
- trustAnchor: foundTrustAnchor?.certificateInfo,
599
- verificationTime,
600
- ...client && {
601
- client
602
- }
603
- };
604
- }
605
- return {
606
- error: true,
607
- critical: true,
608
- message: `Certificate chain validation failed for ${leafCert.certificateInfo.subject.dn.DN}.`,
609
- certificateChain: x5cOrdereredChain.map((cert) => cert.certificateInfo),
610
- 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}.`,
611
- verificationTime,
612
- ...client && {
613
- client
614
- }
615
- };
616
- }, "validateX509CertificateChainImpl");
617
- var isSameCertificate = /* @__PURE__ */ __name((cert1, cert2) => {
618
- return cert1.rawData.toString() === cert2.rawData.toString();
619
- }, "isSameCertificate");
620
- var algorithmProvider = import_tsyringe.container.resolve(import_x509.AlgorithmProvider);
621
- var getX509AlgorithmProvider = /* @__PURE__ */ __name(() => {
622
- return algorithmProvider;
623
- }, "getX509AlgorithmProvider");
624
- var parseCertificate = /* @__PURE__ */ __name(async (rawCert) => {
625
- const x509Certificate = new import_x509.X509Certificate(rawCert);
626
- const publicKeyInfo = import_asn1_schema.AsnParser.parse(x509Certificate.publicKey.rawData, import_asn1_x509.SubjectPublicKeyInfo);
627
- const publicKeyRaw = new Uint8Array(publicKeyInfo.subjectPublicKey);
628
- let publicKeyJwk = void 0;
629
- try {
630
- publicKeyJwk = await getCertificateSubjectPublicKeyJWK(new Uint8Array(x509Certificate.rawData));
631
- } catch (e) {
632
- console.error(e.message);
633
- }
634
- const certificate = pemOrDerToX509Certificate(rawCert);
635
- const certificateInfo = await getCertificateInfo(certificate);
636
- const publicKeyAlgorithm = getX509AlgorithmProvider().toWebAlgorithm(publicKeyInfo.algorithm);
637
- return {
638
- publicKeyAlgorithm,
639
- publicKeyInfo,
640
- publicKeyJwk,
641
- publicKeyRaw,
642
- certificateInfo,
643
- certificate,
644
- x509Certificate
645
- };
646
- }, "parseCertificate");
647
- var rdnmap = {
648
- "2.5.4.6": "C",
649
- "2.5.4.10": "O",
650
- "2.5.4.11": "OU",
651
- "2.5.4.3": "CN",
652
- "2.5.4.7": "L",
653
- "2.5.4.8": "ST",
654
- "2.5.4.12": "T",
655
- "2.5.4.42": "GN",
656
- "2.5.4.43": "I",
657
- "2.5.4.4": "SN",
658
- "1.2.840.113549.1.9.1": "E-mail"
659
- };
660
- var getIssuerDN = /* @__PURE__ */ __name((cert) => {
661
- return {
662
- DN: getDNString(cert.issuer.typesAndValues),
663
- attributes: getDNObject(cert.issuer.typesAndValues)
664
- };
665
- }, "getIssuerDN");
666
- var getSubjectDN = /* @__PURE__ */ __name((cert) => {
667
- return {
668
- DN: getDNString(cert.subject.typesAndValues),
669
- attributes: getDNObject(cert.subject.typesAndValues)
670
- };
671
- }, "getSubjectDN");
672
- var getDNObject = /* @__PURE__ */ __name((typesAndValues) => {
673
- const DN = {};
674
- for (const typeAndValue of typesAndValues) {
675
- const type = rdnmap[typeAndValue.type] ?? typeAndValue.type;
676
- DN[type] = typeAndValue.value.getValue();
677
- }
678
- return DN;
679
- }, "getDNObject");
680
- var getDNString = /* @__PURE__ */ __name((typesAndValues) => {
681
- return Object.entries(getDNObject(typesAndValues)).map(([key, value]) => `${key}=${value}`).join(",");
682
- }, "getDNString");
683
- var getCertificateSubjectPublicKeyJWK = /* @__PURE__ */ __name(async (pemOrDerCert) => {
684
- const pemOrDerStr = typeof pemOrDerCert === "string" ? (0, import_to_string4.toString)((0, import_from_string3.fromString)(pemOrDerCert, "base64pad"), "base64pad") : pemOrDerCert instanceof Uint8Array ? (0, import_to_string4.toString)(pemOrDerCert, "base64pad") : (0, import_to_string4.toString)((0, import_from_string3.fromString)(pemOrDerCert.toString("base64"), "base64pad"), "base64pad");
685
- const pem = derToPEM(pemOrDerStr);
686
- const certificate = pemOrDerToX509Certificate(pem);
687
- var jwk;
688
- try {
689
- const subtle = (0, import_pkijs2.getCrypto)(true).subtle;
690
- const pk = await certificate.getPublicKey(void 0, defaultCryptoEngine());
691
- jwk = await subtle.exportKey("jwk", pk);
692
- } catch (error) {
693
- console.log(`Error in primary get JWK from cert:`, error?.message);
694
- }
695
- if (!jwk) {
696
- try {
697
- jwk = await import_js_x509_utils.default.toJwk(pem, "pem");
698
- } catch (error) {
699
- console.log(`Error in secondary get JWK from cert as well:`, error?.message);
700
- }
701
- }
702
- if (!jwk) {
703
- throw Error(`Failed to get JWK from certificate ${pem}`);
704
- }
705
- return jwk;
706
- }, "getCertificateSubjectPublicKeyJWK");
707
- var SubjectAlternativeGeneralName = /* @__PURE__ */ function(SubjectAlternativeGeneralName2) {
708
- SubjectAlternativeGeneralName2[SubjectAlternativeGeneralName2["rfc822Name"] = 1] = "rfc822Name";
709
- SubjectAlternativeGeneralName2[SubjectAlternativeGeneralName2["dnsName"] = 2] = "dnsName";
710
- SubjectAlternativeGeneralName2[SubjectAlternativeGeneralName2["uniformResourceIdentifier"] = 6] = "uniformResourceIdentifier";
711
- SubjectAlternativeGeneralName2[SubjectAlternativeGeneralName2["ipAddress"] = 7] = "ipAddress";
712
- return SubjectAlternativeGeneralName2;
713
- }({});
714
- var assertCertificateMatchesClientIdScheme = /* @__PURE__ */ __name((certificate, clientId, clientIdScheme) => {
715
- const sans = getSubjectAlternativeNames(certificate, {
716
- clientIdSchemeFilter: clientIdScheme
717
- });
718
- const clientIdMatches = sans.find((san) => san.value === clientId);
719
- if (!clientIdMatches) {
720
- 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(",")}`);
721
- }
722
- }, "assertCertificateMatchesClientIdScheme");
723
- var validateCertificateChainMatchesClientIdScheme = /* @__PURE__ */ __name(async (certificate, clientId, clientIdScheme) => {
724
- const result = {
725
- error: true,
726
- critical: true,
727
- message: `Client Id ${clientId} was not present in certificate using scheme ${clientIdScheme}`,
728
- client: {
729
- clientId,
730
- clientIdScheme
731
- },
732
- certificateChain: [
733
- await getCertificateInfo(certificate)
734
- ],
735
- verificationTime: /* @__PURE__ */ new Date()
736
- };
737
- try {
738
- assertCertificateMatchesClientIdScheme(certificate, clientId, clientIdScheme);
739
- } catch (error) {
740
- return result;
741
- }
742
- result.error = false;
743
- result.message = `Client Id ${clientId} was present in certificate using scheme ${clientIdScheme}`;
744
- return result;
745
- }, "validateCertificateChainMatchesClientIdScheme");
746
- var getSubjectAlternativeNames = /* @__PURE__ */ __name((certificate, opts) => {
747
- let typeFilter;
748
- if (opts?.clientIdSchemeFilter) {
749
- typeFilter = opts.clientIdSchemeFilter === "x509_san_dns" ? [
750
- 2
751
- ] : [
752
- 6
753
- ];
754
- } else if (opts?.typeFilter) {
755
- typeFilter = Array.isArray(opts.typeFilter) ? opts.typeFilter : [
756
- opts.typeFilter
757
- ];
758
- } else {
759
- typeFilter = [
760
- 2,
761
- 6
762
- ];
763
- }
764
- const parsedValue = certificate.extensions?.find((ext) => ext.extnID === import_pkijs2.id_SubjectAltName)?.parsedValue;
765
- if (!parsedValue) {
766
- return [];
767
- }
768
- const altNames = parsedValue.toJSON().altNames;
769
- return altNames.filter((altName) => typeFilter.includes(altName.type)).map((altName) => {
770
- return {
771
- type: altName.type,
772
- value: altName.value
773
- };
774
- });
775
- }, "getSubjectAlternativeNames");
776
- //# sourceMappingURL=index.cjs.map