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