micro509 0.7.2 → 0.8.0

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 (109) hide show
  1. package/dist/index.d.ts +5 -5
  2. package/dist/index.js +15 -1
  3. package/dist/internal/asn1/asn1.js +280 -2
  4. package/dist/internal/asn1/der.js +378 -2
  5. package/dist/internal/asn1/oids.js +103 -2
  6. package/dist/internal/crypto/algorithm-names.js +58 -2
  7. package/dist/internal/crypto/ecdsa.js +68 -2
  8. package/dist/internal/crypto/hash.js +286 -2
  9. package/dist/internal/crypto/pbes2.js +213 -2
  10. package/dist/internal/crypto/rsa-pss.js +184 -2
  11. package/dist/internal/crypto/sig-verify.js +192 -2
  12. package/dist/internal/crypto/signing.d.ts +1 -2
  13. package/dist/internal/crypto/signing.js +123 -2
  14. package/dist/internal/crypto/webcrypto.js +14 -2
  15. package/dist/internal/shared/base64.js +16 -2
  16. package/dist/internal/shared/dn.js +84 -2
  17. package/dist/internal/shared/ip.js +164 -2
  18. package/dist/internal/verify/name-constraints-engine.js +450 -2
  19. package/dist/internal/verify/policy-engine.js +382 -2
  20. package/dist/internal/verify/verify-path.js +298 -2
  21. package/dist/internal/x509/extension-bits.js +132 -2
  22. package/dist/internal/x509/extension-registry.js +229 -2
  23. package/dist/internal/x509/name-fields.js +93 -2
  24. package/dist/keys/keys.d.ts +231 -7
  25. package/dist/keys/keys.js +1087 -5
  26. package/dist/keys.d.ts +2 -2
  27. package/dist/keys.js +2 -1
  28. package/dist/pem/pem.d.ts +2 -2
  29. package/dist/pem/pem.js +172 -6
  30. package/dist/pem.js +2 -1
  31. package/dist/pkcs/pfx.d.ts +4 -5
  32. package/dist/pkcs/pfx.js +395 -2
  33. package/dist/pkcs/pkcs12-mac.d.ts +2 -2
  34. package/dist/pkcs/pkcs12-mac.js +175 -2
  35. package/dist/pkcs/pkcs7.d.ts +1 -2
  36. package/dist/pkcs/pkcs7.js +653 -2
  37. package/dist/pkcs.d.ts +2 -2
  38. package/dist/pkcs.js +4 -1
  39. package/dist/result/result.d.ts +1 -2
  40. package/dist/result/result.js +111 -2
  41. package/dist/result.js +2 -1
  42. package/dist/revocation/chain.d.ts +4 -5
  43. package/dist/revocation/chain.js +536 -2
  44. package/dist/revocation/crl.d.ts +2 -2
  45. package/dist/revocation/crl.js +1119 -2
  46. package/dist/revocation/ocsp.d.ts +3 -2
  47. package/dist/revocation/ocsp.js +958 -2
  48. package/dist/revocation/revocation.d.ts +1 -2
  49. package/dist/revocation/revocation.js +261 -2
  50. package/dist/revocation.d.ts +2 -2
  51. package/dist/revocation.js +5 -1
  52. package/dist/verify/identity.d.ts +1 -2
  53. package/dist/verify/identity.js +270 -2
  54. package/dist/verify/name-constraints.d.ts +1 -2
  55. package/dist/verify/policy.d.ts +1 -2
  56. package/dist/verify/verify.d.ts +1 -2
  57. package/dist/verify/verify.js +764 -2
  58. package/dist/verify.js +3 -1
  59. package/dist/x509/certificate.d.ts +1 -2
  60. package/dist/x509/certificate.js +151 -2
  61. package/dist/x509/csr.d.ts +1 -2
  62. package/dist/x509/csr.js +71 -2
  63. package/dist/x509/extensions.d.ts +1 -2
  64. package/dist/x509/extensions.js +387 -2
  65. package/dist/x509/name.d.ts +1 -2
  66. package/dist/x509/name.js +173 -2
  67. package/dist/x509/parse.d.ts +84 -2
  68. package/dist/x509/parse.js +1090 -2
  69. package/dist/x509.d.ts +2 -2
  70. package/dist/x509.js +6 -1
  71. package/package.json +74 -34
  72. package/dist/internal/asn1/asn1.js.map +0 -1
  73. package/dist/internal/asn1/der.js.map +0 -1
  74. package/dist/internal/asn1/oids.js.map +0 -1
  75. package/dist/internal/crypto/algorithm-names.js.map +0 -1
  76. package/dist/internal/crypto/ecdsa.js.map +0 -1
  77. package/dist/internal/crypto/hash.js.map +0 -1
  78. package/dist/internal/crypto/pbes2.d.ts +0 -23
  79. package/dist/internal/crypto/pbes2.js.map +0 -1
  80. package/dist/internal/crypto/rsa-pss.js.map +0 -1
  81. package/dist/internal/crypto/sig-verify.js.map +0 -1
  82. package/dist/internal/crypto/signing.js.map +0 -1
  83. package/dist/internal/crypto/webcrypto.js.map +0 -1
  84. package/dist/internal/shared/base64.js.map +0 -1
  85. package/dist/internal/shared/dn.js.map +0 -1
  86. package/dist/internal/shared/ip.js.map +0 -1
  87. package/dist/internal/verify/name-constraints-engine.js.map +0 -1
  88. package/dist/internal/verify/policy-engine.js.map +0 -1
  89. package/dist/internal/verify/verify-path.js.map +0 -1
  90. package/dist/internal/x509/extension-bits.js.map +0 -1
  91. package/dist/internal/x509/extension-registry.js.map +0 -1
  92. package/dist/internal/x509/name-fields.js.map +0 -1
  93. package/dist/keys/keys.js.map +0 -1
  94. package/dist/pem/pem.js.map +0 -1
  95. package/dist/pkcs/pfx.js.map +0 -1
  96. package/dist/pkcs/pkcs12-mac.js.map +0 -1
  97. package/dist/pkcs/pkcs7.js.map +0 -1
  98. package/dist/result/result.js.map +0 -1
  99. package/dist/revocation/chain.js.map +0 -1
  100. package/dist/revocation/crl.js.map +0 -1
  101. package/dist/revocation/ocsp.js.map +0 -1
  102. package/dist/revocation/revocation.js.map +0 -1
  103. package/dist/verify/identity.js.map +0 -1
  104. package/dist/verify/verify.js.map +0 -1
  105. package/dist/x509/certificate.js.map +0 -1
  106. package/dist/x509/csr.js.map +0 -1
  107. package/dist/x509/extensions.js.map +0 -1
  108. package/dist/x509/name.js.map +0 -1
  109. package/dist/x509/parse.js.map +0 -1
@@ -1,2 +1,164 @@
1
- const e=/^[0-9a-f]{1,4}$/;function t(t){let n=t.toLowerCase(),r=n.split(`::`),i=r[0]??``,a=r[1];if(a!==void 0&&n.indexOf(`::`)!==n.lastIndexOf(`::`))throw Error(`Invalid IPv6 address: ${t}`);let o=i.length>0?i.split(`:`):[],s=a!==void 0&&a.length>0?a.split(`:`):[],c=8-(o.length+s.length);if(a===void 0&&o.length!==8||c<0)throw Error(`Invalid IPv6 address: ${t}`);let l=Array.from({length:c},()=>`0`),u=a===void 0?o:[...o,...l,...s];if(u.length!==8)throw Error(`Invalid IPv6 address: ${t}`);return u.map(n=>{if(!e.test(n))throw Error(`Invalid IPv6 address: ${t}`);return n.padStart(4,`0`)})}function n(e){if(e.includes(`:`))return a(e);let t=e.split(`.`);if(t.length!==4)throw Error(`Invalid IPv4 address: ${e}`);return Uint8Array.from(t.map(t=>{if(t.length===0)throw Error(`Invalid IPv4 address: ${e}`);let n=Number(t);if(!Number.isInteger(n)||n<0||n>255)throw Error(`Invalid IPv4 address: ${e}`);return n}))}function r(e){if(e.length===4)return Array.from(e,e=>String(e)).join(`.`);if(e.length===16){let t=[];for(let n=0;n<e.length;n+=2){let r=e[n]??0,i=e[n+1]??0;t.push((r<<8|i).toString(16))}return t.join(`:`)}throw Error(`Unsupported IP address length: ${e.length}`)}function i(e){let t=n(e),r=new Uint8Array(t.length);return r.fill(255),r}function a(e){let n=t(e),r=new Uint8Array(16);return n.forEach((e,t)=>{let n=Number.parseInt(e,16);r[t*2]=n>>8,r[t*2+1]=n&255}),r}export{i as allOnesMaskForIpAddress,r as decodeIpAddress,t as expandIpv6,n as parseIpAddressToBytes};
2
- //# sourceMappingURL=ip.js.map
1
+ //#region src/internal/shared/ip.ts
2
+ /**
3
+ * IP address parsing and normalization helpers shared by parsing,
4
+ * validation, and identity matching flows.
5
+ *
6
+ * These utilities keep IPv4 and IPv6 handling consistent for SAN
7
+ * matching and name constraint evaluation.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import {
12
+ * allOnesMaskForIpAddress,
13
+ * decodeIpAddress,
14
+ * expandIpv6,
15
+ * normalizeIpAddress,
16
+ * parseIpAddressToBytes,
17
+ * } from './ip.ts';
18
+ *
19
+ * normalizeIpAddress('::1');
20
+ * // '0000:0000:0000:0000:0000:0000:0000:0001'
21
+ *
22
+ * expandIpv6('2001:db8::1');
23
+ * // ['2001', '0db8', '0000', '0000', '0000', '0000', '0000', '0001']
24
+ *
25
+ * Array.from(parseIpAddressToBytes('127.0.0.1'));
26
+ * // [127, 0, 0, 1]
27
+ *
28
+ * decodeIpAddress(Uint8Array.of(127, 0, 0, 1));
29
+ * // '127.0.0.1'
30
+ *
31
+ * Array.from(allOnesMaskForIpAddress('127.0.0.1'));
32
+ * // [255, 255, 255, 255]
33
+ * ```
34
+ *
35
+ * @module
36
+ */
37
+ /** Matches a single valid IPv6 hex segment (1–4 hex digits). */
38
+ const IPV6_SEGMENT = /^[0-9a-f]{1,4}$/;
39
+ /**
40
+ * Expands an IPv6 address, including `::` shorthand, into exactly 8
41
+ * zero-padded four-character hex segments.\
42
+ * Throws on malformed input.
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * expandIpv6('2001:db8::1');
47
+ * // ['2001', '0db8', '0000', '0000', '0000', '0000', '0000', '0001']
48
+ * ```
49
+ *
50
+ * @param value IPv6 address string to expand.
51
+ * @returns The 8 normalized IPv6 segments.
52
+ */
53
+ function expandIpv6(value) {
54
+ const normalized = value.toLowerCase();
55
+ const pieces = normalized.split("::");
56
+ const head = pieces[0] ?? "";
57
+ const tail = pieces[1];
58
+ if (tail !== void 0 && normalized.indexOf("::") !== normalized.lastIndexOf("::")) throw new Error(`Invalid IPv6 address: ${value}`);
59
+ const headParts = head.length > 0 ? head.split(":") : [];
60
+ const tailParts = tail !== void 0 && tail.length > 0 ? tail.split(":") : [];
61
+ const missing = 8 - (headParts.length + tailParts.length);
62
+ if (tail === void 0 && headParts.length !== 8 || missing < 0) throw new Error(`Invalid IPv6 address: ${value}`);
63
+ const zeroes = Array.from({ length: missing }, () => "0");
64
+ const parts = tail === void 0 ? headParts : [
65
+ ...headParts,
66
+ ...zeroes,
67
+ ...tailParts
68
+ ];
69
+ if (parts.length !== 8) throw new Error(`Invalid IPv6 address: ${value}`);
70
+ return parts.map((segment) => {
71
+ if (!IPV6_SEGMENT.test(segment)) throw new Error(`Invalid IPv6 address: ${value}`);
72
+ return segment.padStart(4, "0");
73
+ });
74
+ }
75
+ /**
76
+ * Parses an IPv4 or IPv6 address string into raw bytes.\
77
+ * Returns 4 bytes for IPv4 and 16 bytes for IPv6.
78
+ *
79
+ * Suitable for encoding into SAN iPAddress octets or name-constraint ranges.
80
+ *
81
+ * @example
82
+ * ```ts
83
+ * Array.from(parseIpAddressToBytes('127.0.0.1'));
84
+ * // [127, 0, 0, 1]
85
+ * ```
86
+ *
87
+ * @param value IPv4 or IPv6 address string to parse.
88
+ * @returns The raw address bytes.
89
+ */
90
+ function parseIpAddressToBytes(value) {
91
+ if (value.includes(":")) return parseIpv6ToBytes(value);
92
+ const segments = value.split(".");
93
+ if (segments.length !== 4) throw new Error(`Invalid IPv4 address: ${value}`);
94
+ return Uint8Array.from(segments.map((segment) => {
95
+ if (segment.length === 0) throw new Error(`Invalid IPv4 address: ${value}`);
96
+ const parsed = Number(segment);
97
+ if (!Number.isInteger(parsed) || parsed < 0 || parsed > 255) throw new Error(`Invalid IPv4 address: ${value}`);
98
+ return parsed;
99
+ }));
100
+ }
101
+ /**
102
+ * Converts raw IP address bytes back to a human-readable string.\
103
+ * Returns dotted-decimal IPv4 for 4-byte input and colon-separated hex
104
+ * IPv6 for 16-byte input.
105
+ *
106
+ * Throws on any other length.
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * decodeIpAddress(Uint8Array.of(127, 0, 0, 1));
111
+ * // '127.0.0.1'
112
+ * ```
113
+ *
114
+ * @param bytes Raw IPv4 or IPv6 address bytes.
115
+ * @returns The decoded address string.
116
+ */
117
+ function decodeIpAddress(bytes) {
118
+ if (bytes.length === 4) return Array.from(bytes, (value) => String(value)).join(".");
119
+ if (bytes.length === 16) {
120
+ const groups = [];
121
+ for (let index = 0; index < bytes.length; index += 2) {
122
+ const left = bytes[index] ?? 0;
123
+ const right = bytes[index + 1] ?? 0;
124
+ groups.push((left << 8 | right).toString(16));
125
+ }
126
+ return groups.join(":");
127
+ }
128
+ throw new Error(`Unsupported IP address length: ${bytes.length}`);
129
+ }
130
+ /**
131
+ * Returns an all-ones (`0xff`) mask of the appropriate length for the
132
+ * given IP address string.\
133
+ * Returns 4 bytes for IPv4 and 16 bytes for IPv6.
134
+ *
135
+ * Used to build name-constraint subnet masks that match a single host.
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * Array.from(allOnesMaskForIpAddress('127.0.0.1'));
140
+ * // [255, 255, 255, 255]
141
+ * ```
142
+ *
143
+ * @param value IPv4 or IPv6 address string used to choose mask length.
144
+ * @returns An all-ones mask for the same address family.
145
+ */
146
+ function allOnesMaskForIpAddress(value) {
147
+ const parsed = parseIpAddressToBytes(value);
148
+ const mask = new Uint8Array(parsed.length);
149
+ mask.fill(255);
150
+ return mask;
151
+ }
152
+ /** Parses an IPv6 address string into a 16-byte `Uint8Array`. */
153
+ function parseIpv6ToBytes(value) {
154
+ const expanded = expandIpv6(value);
155
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
156
+ expanded.forEach((segment, index) => {
157
+ const parsed = Number.parseInt(segment, 16);
158
+ bytes[index * 2] = parsed >> 8;
159
+ bytes[index * 2 + 1] = parsed & 255;
160
+ });
161
+ return bytes;
162
+ }
163
+ //#endregion
164
+ export { allOnesMaskForIpAddress, decodeIpAddress, expandIpv6, parseIpAddressToBytes };
@@ -1,2 +1,450 @@
1
- import{readRootElement as e}from"../asn1/der.js";import{childrenOf as t,decodeObjectIdentifier as n,decodeString as r,hexToBytes as i,requireElement as a,toHex as o}from"../asn1/asn1.js";import{OIDS as s}from"../asn1/oids.js";import{allOnesMaskForIpAddress as c,decodeIpAddress as l,parseIpAddressToBytes as u}from"../shared/ip.js";import{nameFieldKeyFromOid as d}from"../x509/name-fields.js";import{compareDistinguishedNames as f,isWithinDirectoryNameSubtree as p}from"../shared/dn.js";function m(e,t,n,r){return{ok:!1,code:e,message:t,index:n,...r===void 0?{}:{details:r}}}function h(e){let t={...e.subjectCommonName===void 0?{}:{subjectCommonName:e.subjectCommonName},...e.actual===void 0?{}:{actual:e.actual}};return Object.keys(t).length===0?void 0:t}function g(e){return f(e.subject,e.issuer)}function _(e){return{initialPermittedSubtrees:e.permittedSubtrees?.map(e=>e.base)??[],initialExcludedSubtrees:e.excludedSubtrees?.map(e=>e.base)??[]}}function v(e,t){let n=b(t),r=e[e.length-1];r?.nameConstraints!==void 0&&(n=x(n,r.nameConstraints,y(r)));for(let t=e.length-2;t>=0;--t){let r=e[t];if(r===void 0)throw Error(`Certificate chain contains undefined at index ${String(t)}`);if(!g(r)||t===0){let e=w(r,n,t);if(!e.ok)return e}r.nameConstraints!==void 0&&(n=x(n,r.nameConstraints,y(r)))}return{ok:!0}}function y(e){return e.extensions.some(e=>e.oid===s.nameConstraints&&e.critical)}function b(e){return{permittedLevels:e.initialPermittedSubtrees.length>0?[e.initialPermittedSubtrees]:[],excluded:e.initialExcludedSubtrees,unsupportedCriticalForms:new Set}}function x(e,t,n){let r=t.permittedSubtrees!==void 0&&t.permittedSubtrees.length>0?[...e.permittedLevels,t.permittedSubtrees.flatMap(e=>C(e.base)?[e.base]:[])]:e.permittedLevels,i=t.excludedSubtrees!==void 0&&t.excludedSubtrees.length>0?[...e.excluded,...t.excludedSubtrees.flatMap(e=>C(e.base)?[e.base]:[])]:e.excluded,a=n?S(t):[];return{permittedLevels:r,excluded:i,unsupportedCriticalForms:a.length>0?new Set([...e.unsupportedCriticalForms,...a]):e.unsupportedCriticalForms}}function S(e){let t=new Set;for(let n of e.permittedSubtrees??[])C(n.base)||t.add(n.base.type);for(let n of e.excludedSubtrees??[])C(n.base)||t.add(n.base.type);return[...t]}function C(e){switch(e.type){case`dns`:case`email`:case`uri`:case`ip`:case`directoryName`:return!0;case`otherName`:case`x400Address`:case`ediPartyName`:case`registeredID`:return!1;default:throw Error(`Unhandled NameConstraintForm type: ${String(e)}`)}}function w(e,t,n){if(e.subject.derHex!==`3000`&&!O({type:`directoryName`,derHex:e.subject.derHex},t))return m(`name_constraints_violated`,`subject distinguished name violates name constraints`,n,h({subjectCommonName:e.subject.values.commonName}));if(e.subjectAltNames!==void 0)for(let r of e.subjectAltNames){let i=E(r);if(i!==void 0&&t.unsupportedCriticalForms.has(i))return m(`unsupported_name_constraints`,`critical name constraints impose ${i} constraints that cannot be processed, and the certificate contains a ${i} subject alternative name`,n,h({subjectCommonName:e.subject.values.commonName,actual:i}));let a=D(r);if(!a.ok)return m(`name_constraints_violated`,`SAN ${a.actual} is malformed and cannot be checked against name constraints`,n,h({subjectCommonName:e.subject.values.commonName,actual:a.actual}));let o=a.value;if(o!==void 0&&!O(o,t))return m(`name_constraints_violated`,`SAN ${z(o)} violates name constraints`,n,h({subjectCommonName:e.subject.values.commonName,actual:z(o)}))}return T(t)&&!(e.subjectAltNames?.some(e=>e.type===`email`)??!1)&&e.subject.values.emailAddress!==void 0&&!O({type:`email`,value:e.subject.values.emailAddress},t)?m(`name_constraints_violated`,`subject emailAddress ${e.subject.values.emailAddress} violates name constraints`,n,h({subjectCommonName:e.subject.values.commonName,actual:e.subject.values.emailAddress})):{ok:!0}}function T(e){for(let t of e.permittedLevels)if(t.some(e=>e.type===`email`))return!0;return e.excluded.some(e=>e.type===`email`)}function E(e){if(e.type===`srv`)return`otherName`;if(e.type===`unknown`)switch(e.tag){case 160:return`otherName`;case 163:return`x400Address`;case 165:return`ediPartyName`;case 136:return`registeredID`;default:return}}function D(e){switch(e.type){case`dns`:return{ok:!0,value:{type:`dns`,value:e.value}};case`email`:return{ok:!0,value:{type:`email`,value:e.value}};case`uri`:return{ok:!0,value:{type:`uri`,value:e.value}};case`srv`:return{ok:!0,value:void 0};case`ip`:try{return{ok:!0,value:{type:`ip`,addressBytes:u(e.value),maskBytes:c(e.value)}}}catch{return{ok:!1,actual:`ip:${e.value}`}}case`directoryName`:return{ok:!0,value:{type:`directoryName`,derHex:e.derHex}};case`unknown`:return{ok:!0,value:void 0};default:throw Error(`Unhandled SubjectAltName type: ${String(e)}`)}}function O(e,t){for(let n of t.excluded)if(k(e,n))return!1;for(let n of t.permittedLevels){let t=n.filter(t=>t.type===e.type);if(t.length!==0&&!t.some(t=>k(e,t)))return!1}return!0}function k(e,t){return e.type===`dns`&&t.type===`dns`?A(e.value,t.value):e.type===`email`&&t.type===`email`?j(e.value,t.value):e.type===`uri`&&t.type===`uri`?M(e.value,t.value):e.type===`ip`&&t.type===`ip`?P(e.addressBytes,t.addressBytes,t.maskBytes):e.type===`directoryName`&&t.type===`directoryName`?F(e.derHex,t.derHex):!1}function A(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return r.length===0?!0:r.startsWith(`.`)?n.endsWith(r):n===r||n.endsWith(`.${r}`)}function j(e,t){let n=e.toLowerCase(),r=t.toLowerCase();if(r.includes(`@`))return n===r;let i=n.indexOf(`@`);if(i<0)return!1;let a=n.slice(i+1);return r.startsWith(`.`)?a.endsWith(r):a===r}function M(e,t){let n=N(e);if(n===void 0)return!1;let r=n.toLowerCase(),i=t.toLowerCase();return i.length===0?!0:i.startsWith(`.`)?r.endsWith(i):r===i}function N(e){try{return new URL(e).hostname}catch{return}}function P(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){let i=e[r]??0,a=t[r]??0,o=n[r]??0;if((i&o)!==(a&o))return!1}return!0}function F(e,t){let n=I(e),r=I(t);return n===void 0||r===void 0?!1:p(n,r)}function I(n){if(/^(?:[0-9a-fA-F]{2})+$/.test(n))try{let r=i(n),a=L(r,e(r,{maxDepth:64}));if(a.tag!==48)return;let s=[],c=[],l={};for(let e of t(r,a)){let t=R(r,e);if(t===void 0)return;s.push(t);for(let e of t.attributes)c.push(e),e.key!==void 0&&l[e.key]===void 0&&(l[e.key]=e.value)}return{derHex:o(r),rdns:s,attributes:c,values:l}}catch{return}}function L(e,n){if(n.tag!==48)return n;let r=t(e,n),i=r[0];return r.length===1&&i?.tag===48?i:n}function R(e,i){if(i.tag!==49)return;let s=t(e,i);if(s.length===0)return;let c=[],l={};for(let i of s){if(i.tag!==48)return;let o=t(e,i),s=o[0],u=o[1];if(s===void 0||u===void 0||o.length!==2||s.tag!==6)return;let f=n(a(s,`directoryName OID`).value),p;try{p=r(u.tag,a(u,`directoryName value`).value)}catch{return}let m=d(f),h=m===void 0?{oid:f,valueTag:u.tag,value:p}:{oid:f,key:m,valueTag:u.tag,value:p};c.push(h),m!==void 0&&l[m]===void 0&&(l[m]=p)}if(c.length!==0)return{derHex:o(e.slice(i.start-i.headerLength,i.end)),attributes:c,values:l}}function z(e){switch(e.type){case`dns`:return`dns:${e.value}`;case`email`:return`email:${e.value}`;case`uri`:return`uri:${e.value}`;case`ip`:return`ip:${l(e.addressBytes)}`;case`directoryName`:return`dn:${e.derHex.slice(0,20)}${e.derHex.length>20?`...`:``}`;default:throw Error(`Unhandled NameConstraintForm type: ${String(e)}`)}}export{_ as createNameConstraintValidationState,v as evaluateNameConstraints};
2
- //# sourceMappingURL=name-constraints-engine.js.map
1
+ import { readRootElement } from "../asn1/der.js";
2
+ import { childrenOf, decodeObjectIdentifier, decodeString, hexToBytes, requireElement, toHex } from "../asn1/asn1.js";
3
+ import { OIDS } from "../asn1/oids.js";
4
+ import { allOnesMaskForIpAddress, decodeIpAddress, parseIpAddressToBytes } from "../shared/ip.js";
5
+ import { nameFieldKeyFromOid } from "../x509/name-fields.js";
6
+ import { compareDistinguishedNames, isWithinDirectoryNameSubtree } from "../shared/dn.js";
7
+ //#region src/internal/verify/name-constraints-engine.ts
8
+ /**
9
+ * Internal name-constraints evaluation engine.
10
+ *
11
+ * Accumulates and evaluates the shipped RFC 5280 §4.2.1.10 / §6.1
12
+ * name-constraint subset during certificate path validation.
13
+ *
14
+ * @module
15
+ */
16
+ /** Constructs a {@linkcode NameConstraintValidationFailure} with optional details. */
17
+ function nameConstraintFailure(code, message, index, details) {
18
+ return {
19
+ ok: false,
20
+ code,
21
+ message,
22
+ index,
23
+ ...details === void 0 ? {} : { details }
24
+ };
25
+ }
26
+ /** Strips undefined fields and returns `undefined` when all fields are empty. */
27
+ function nameConstraintDetails(input) {
28
+ const details = {
29
+ ...input.subjectCommonName === void 0 ? {} : { subjectCommonName: input.subjectCommonName },
30
+ ...input.actual === void 0 ? {} : { actual: input.actual }
31
+ };
32
+ return Object.keys(details).length === 0 ? void 0 : details;
33
+ }
34
+ /** A certificate is self-issued when subject and issuer DNs are semantically equal (RFC 5280 §7.1). */
35
+ function isSelfIssued(certificate) {
36
+ return compareDistinguishedNames(certificate.subject, certificate.issuer);
37
+ }
38
+ /**
39
+ * Initializes validation state from caller-supplied initial constraints.
40
+ *
41
+ * Call once before {@linkcode evaluateNameConstraints}.
42
+ */
43
+ function createNameConstraintValidationState(input) {
44
+ return {
45
+ initialPermittedSubtrees: input.permittedSubtrees?.map((subtree) => subtree.base) ?? [],
46
+ initialExcludedSubtrees: input.excludedSubtrees?.map((subtree) => subtree.base) ?? []
47
+ };
48
+ }
49
+ /** Empty SEQUENCE DER hex — represents an empty subject DN. */
50
+ const EMPTY_SEQUENCE_HEX = "3000";
51
+ /**
52
+ * Walks the chain root-to-leaf, accumulating nameConstraints from CA
53
+ * certificates and checking each non-self-issued certificate's names
54
+ * against the accumulated constraints.
55
+ *
56
+ * RFC 5280 §6.1.3(b)–(c) for intermediates, §6.1.5(g) for the leaf.
57
+ */
58
+ function evaluateNameConstraints(chain, state) {
59
+ let accumulated = seedInitialNameConstraints(state);
60
+ const root = chain[chain.length - 1];
61
+ if (root?.nameConstraints !== void 0) accumulated = accumulateConstraints(accumulated, root.nameConstraints, hasCriticalNameConstraintsExtension(root));
62
+ for (let index = chain.length - 2; index >= 0; index -= 1) {
63
+ const current = chain[index];
64
+ if (current === void 0) throw new Error(`Certificate chain contains undefined at index ${String(index)}`);
65
+ if (!isSelfIssued(current) || index === 0) {
66
+ const nameCheckResult = checkCertificateNames(current, accumulated, index);
67
+ if (!nameCheckResult.ok) return nameCheckResult;
68
+ }
69
+ if (current.nameConstraints !== void 0) accumulated = accumulateConstraints(accumulated, current.nameConstraints, hasCriticalNameConstraintsExtension(current));
70
+ }
71
+ return { ok: true };
72
+ }
73
+ /** True when the certificate carries a critical nameConstraints extension. */
74
+ function hasCriticalNameConstraintsExtension(certificate) {
75
+ return certificate.extensions.some((entry) => entry.oid === OIDS.nameConstraints && entry.critical);
76
+ }
77
+ /** Converts initial state into the starting accumulated-constraints snapshot. */
78
+ function seedInitialNameConstraints(state) {
79
+ return {
80
+ permittedLevels: state.initialPermittedSubtrees.length > 0 ? [state.initialPermittedSubtrees] : [],
81
+ excluded: state.initialExcludedSubtrees,
82
+ unsupportedCriticalForms: /* @__PURE__ */ new Set()
83
+ };
84
+ }
85
+ /**
86
+ * Merges one certificate's nameConstraints extension into the running totals.
87
+ *
88
+ * Unsupported constraint forms from a critical extension are recorded so
89
+ * subsequent certificates carrying a name of that form fail closed
90
+ * (RFC 5280 §4.2.1.10). Unsupported forms in a non-critical extension are
91
+ * dropped — the RFC's rejection requirement is scoped to critical
92
+ * extensions (conforming CAs MUST mark nameConstraints critical anyway).
93
+ */
94
+ function accumulateConstraints(current, constraints, critical) {
95
+ const permittedLevels = constraints.permittedSubtrees !== void 0 && constraints.permittedSubtrees.length > 0 ? [...current.permittedLevels, constraints.permittedSubtrees.flatMap((subtree) => isSupportedNameConstraintForm(subtree.base) ? [subtree.base] : [])] : current.permittedLevels;
96
+ const excluded = constraints.excludedSubtrees !== void 0 && constraints.excludedSubtrees.length > 0 ? [...current.excluded, ...constraints.excludedSubtrees.flatMap((subtree) => isSupportedNameConstraintForm(subtree.base) ? [subtree.base] : [])] : current.excluded;
97
+ const newUnsupported = critical ? listUnsupportedNameConstraintTypes(constraints) : [];
98
+ return {
99
+ permittedLevels,
100
+ excluded,
101
+ unsupportedCriticalForms: newUnsupported.length > 0 ? /* @__PURE__ */ new Set([...current.unsupportedCriticalForms, ...newUnsupported]) : current.unsupportedCriticalForms
102
+ };
103
+ }
104
+ /** Collects the distinct unsupported GeneralName form types from a nameConstraints extension. */
105
+ function listUnsupportedNameConstraintTypes(constraints) {
106
+ const unsupportedTypes = /* @__PURE__ */ new Set();
107
+ for (const subtree of constraints.permittedSubtrees ?? []) if (!isSupportedNameConstraintForm(subtree.base)) unsupportedTypes.add(subtree.base.type);
108
+ for (const subtree of constraints.excludedSubtrees ?? []) if (!isSupportedNameConstraintForm(subtree.base)) unsupportedTypes.add(subtree.base.type);
109
+ return [...unsupportedTypes];
110
+ }
111
+ /** True for name forms this engine can evaluate: dns, email, uri, ip, directoryName. */
112
+ function isSupportedNameConstraintForm(form) {
113
+ switch (form.type) {
114
+ case "dns":
115
+ case "email":
116
+ case "uri":
117
+ case "ip":
118
+ case "directoryName": return true;
119
+ case "otherName":
120
+ case "x400Address":
121
+ case "ediPartyName":
122
+ case "registeredID": return false;
123
+ default: throw new Error(`Unhandled NameConstraintForm type: ${String(form)}`);
124
+ }
125
+ }
126
+ /**
127
+ * Checks a certificate's subject DN and SANs against accumulated
128
+ * name constraints. Returns a failure if any name violates constraints.
129
+ */
130
+ function checkCertificateNames(certificate, accumulated, index) {
131
+ if (certificate.subject.derHex !== EMPTY_SEQUENCE_HEX) {
132
+ if (!isNamePermitted({
133
+ type: "directoryName",
134
+ derHex: certificate.subject.derHex
135
+ }, accumulated)) return nameConstraintFailure("name_constraints_violated", "subject distinguished name violates name constraints", index, nameConstraintDetails({ subjectCommonName: certificate.subject.values.commonName }));
136
+ }
137
+ if (certificate.subjectAltNames !== void 0) for (const san of certificate.subjectAltNames) {
138
+ const unsupportedForm = sanUnsupportedFormType(san);
139
+ if (unsupportedForm !== void 0 && accumulated.unsupportedCriticalForms.has(unsupportedForm)) return nameConstraintFailure("unsupported_name_constraints", `critical name constraints impose ${unsupportedForm} constraints that cannot be processed, and the certificate contains a ${unsupportedForm} subject alternative name`, index, nameConstraintDetails({
140
+ subjectCommonName: certificate.subject.values.commonName,
141
+ actual: unsupportedForm
142
+ }));
143
+ const checkableResult = sanToConstraintCheckable(san);
144
+ if (!checkableResult.ok) return nameConstraintFailure("name_constraints_violated", `SAN ${checkableResult.actual} is malformed and cannot be checked against name constraints`, index, nameConstraintDetails({
145
+ subjectCommonName: certificate.subject.values.commonName,
146
+ actual: checkableResult.actual
147
+ }));
148
+ const checkable = checkableResult.value;
149
+ if (checkable === void 0) continue;
150
+ if (!isNamePermitted(checkable, accumulated)) return nameConstraintFailure("name_constraints_violated", `SAN ${formatConstraintForm(checkable)} violates name constraints`, index, nameConstraintDetails({
151
+ subjectCommonName: certificate.subject.values.commonName,
152
+ actual: formatConstraintForm(checkable)
153
+ }));
154
+ }
155
+ if (accumulatedHasEmailConstraints(accumulated)) {
156
+ if (!(certificate.subjectAltNames?.some((san) => san.type === "email") ?? false) && certificate.subject.values.emailAddress !== void 0) {
157
+ if (!isNamePermitted({
158
+ type: "email",
159
+ value: certificate.subject.values.emailAddress
160
+ }, accumulated)) return nameConstraintFailure("name_constraints_violated", `subject emailAddress ${certificate.subject.values.emailAddress} violates name constraints`, index, nameConstraintDetails({
161
+ subjectCommonName: certificate.subject.values.commonName,
162
+ actual: certificate.subject.values.emailAddress
163
+ }));
164
+ }
165
+ }
166
+ return { ok: true };
167
+ }
168
+ /** True when any level of accumulated constraints addresses the email name form. */
169
+ function accumulatedHasEmailConstraints(accumulated) {
170
+ for (const level of accumulated.permittedLevels) if (level.some((c) => c.type === "email")) return true;
171
+ return accumulated.excluded.some((c) => c.type === "email");
172
+ }
173
+ /**
174
+ * Maps a SAN to the unsupported constraint form it instantiates, if any.
175
+ *
176
+ * SRV-ID SANs are otherName [0] instances. Unknown SANs carry the full DER
177
+ * tag byte: 0xa0 otherName [0], 0xa3 x400Address [3], 0xa5 ediPartyName [5],
178
+ * 0x88 registeredID [8].
179
+ */
180
+ function sanUnsupportedFormType(san) {
181
+ if (san.type === "srv") return "otherName";
182
+ if (san.type !== "unknown") return;
183
+ switch (san.tag) {
184
+ case 160: return "otherName";
185
+ case 163: return "x400Address";
186
+ case 165: return "ediPartyName";
187
+ case 136: return "registeredID";
188
+ default: return;
189
+ }
190
+ }
191
+ /**
192
+ * Converts a SubjectAltName to a NameConstraintForm for checking.
193
+ * Returns `undefined` for name forms that don't participate in
194
+ * constraint checking (unknown tags).
195
+ */
196
+ function sanToConstraintCheckable(san) {
197
+ switch (san.type) {
198
+ case "dns": return {
199
+ ok: true,
200
+ value: {
201
+ type: "dns",
202
+ value: san.value
203
+ }
204
+ };
205
+ case "email": return {
206
+ ok: true,
207
+ value: {
208
+ type: "email",
209
+ value: san.value
210
+ }
211
+ };
212
+ case "uri": return {
213
+ ok: true,
214
+ value: {
215
+ type: "uri",
216
+ value: san.value
217
+ }
218
+ };
219
+ case "srv": return {
220
+ ok: true,
221
+ value: void 0
222
+ };
223
+ case "ip": try {
224
+ return {
225
+ ok: true,
226
+ value: {
227
+ type: "ip",
228
+ addressBytes: parseIpAddressToBytes(san.value),
229
+ maskBytes: allOnesMaskForIpAddress(san.value)
230
+ }
231
+ };
232
+ } catch {
233
+ return {
234
+ ok: false,
235
+ actual: `ip:${san.value}`
236
+ };
237
+ }
238
+ case "directoryName": return {
239
+ ok: true,
240
+ value: {
241
+ type: "directoryName",
242
+ derHex: san.derHex
243
+ }
244
+ };
245
+ case "unknown": return {
246
+ ok: true,
247
+ value: void 0
248
+ };
249
+ default: throw new Error(`Unhandled SubjectAltName type: ${String(san)}`);
250
+ }
251
+ }
252
+ /**
253
+ * Checks whether a name is permitted by the accumulated constraints.
254
+ * A name is permitted if:
255
+ * 1. It does NOT match any excluded constraint, AND
256
+ * 2. For every permitted level that contains constraints of the same
257
+ * name form, it matches at least one.
258
+ */
259
+ function isNamePermitted(name, accumulated) {
260
+ for (const constraint of accumulated.excluded) if (nameMatchesConstraint(name, constraint)) return false;
261
+ for (const level of accumulated.permittedLevels) {
262
+ const relevant = level.filter((constraint) => constraint.type === name.type);
263
+ if (relevant.length === 0) continue;
264
+ if (!relevant.some((constraint) => nameMatchesConstraint(name, constraint))) return false;
265
+ }
266
+ return true;
267
+ }
268
+ /** Dispatches to the type-specific matching function for the name form. */
269
+ function nameMatchesConstraint(name, constraint) {
270
+ if (name.type === "dns" && constraint.type === "dns") return matchesDnsConstraint(name.value, constraint.value);
271
+ if (name.type === "email" && constraint.type === "email") return matchesEmailConstraint(name.value, constraint.value);
272
+ if (name.type === "uri" && constraint.type === "uri") return matchesUriConstraint(name.value, constraint.value);
273
+ if (name.type === "ip" && constraint.type === "ip") return matchesIpConstraint(name.addressBytes, constraint.addressBytes, constraint.maskBytes);
274
+ if (name.type === "directoryName" && constraint.type === "directoryName") return matchesDnConstraint(name.derHex, constraint.derHex);
275
+ return false;
276
+ }
277
+ /**
278
+ * RFC 5280 §4.2.1.10: DNS name constraint matching.
279
+ * Constraint "example.com" matches "example.com" and any subdomain.
280
+ * Constraint ".example.com" matches only subdomains, not "example.com" itself.
281
+ */
282
+ function matchesDnsConstraint(name, constraint) {
283
+ const lowerName = name.toLowerCase();
284
+ const lowerConstraint = constraint.toLowerCase();
285
+ if (lowerConstraint.length === 0) return true;
286
+ if (lowerConstraint.startsWith(".")) return lowerName.endsWith(lowerConstraint);
287
+ return lowerName === lowerConstraint || lowerName.endsWith(`.${lowerConstraint}`);
288
+ }
289
+ /**
290
+ * RFC 5280 §4.2.1.10: Email constraint matching.
291
+ * - "user@example.com" matches only that exact address.
292
+ * - "example.com" matches any address @example.com.
293
+ * - ".example.com" matches any address @subdomain.example.com.
294
+ */
295
+ function matchesEmailConstraint(name, constraint) {
296
+ const lowerName = name.toLowerCase();
297
+ const lowerConstraint = constraint.toLowerCase();
298
+ if (lowerConstraint.includes("@")) return lowerName === lowerConstraint;
299
+ const atIndex = lowerName.indexOf("@");
300
+ if (atIndex < 0) return false;
301
+ const host = lowerName.slice(atIndex + 1);
302
+ if (lowerConstraint.startsWith(".")) return host.endsWith(lowerConstraint);
303
+ return host === lowerConstraint;
304
+ }
305
+ /**
306
+ * RFC 5280 §4.2.1.10: URI constraint matching.
307
+ * Applied to the host part of the URI.
308
+ * - Constraint ".example.com" matches subdomains only.
309
+ * - Constraint "example.com" matches ONLY that exact host (no subdomain
310
+ * expansion, unlike DNS constraints).
311
+ */
312
+ function matchesUriConstraint(uri, constraint) {
313
+ const host = extractUriHost(uri);
314
+ if (host === void 0) return false;
315
+ const lowerHost = host.toLowerCase();
316
+ const lowerConstraint = constraint.toLowerCase();
317
+ if (lowerConstraint.length === 0) return true;
318
+ if (lowerConstraint.startsWith(".")) return lowerHost.endsWith(lowerConstraint);
319
+ return lowerHost === lowerConstraint;
320
+ }
321
+ /** Extracts the host (reg-name) portion of a URI, stripping scheme, userinfo, port, and path. */
322
+ function extractUriHost(uri) {
323
+ try {
324
+ return new URL(uri).hostname;
325
+ } catch {
326
+ return;
327
+ }
328
+ }
329
+ /**
330
+ * RFC 5280 §4.2.1.10: IP constraint matching.
331
+ * (nameiP & mask) == (constraintiP & mask)
332
+ */
333
+ function matchesIpConstraint(nameBytes, constraintAddr, constraintMask) {
334
+ if (nameBytes.length !== constraintAddr.length) return false;
335
+ for (let i = 0; i < nameBytes.length; i += 1) {
336
+ const nameByte = nameBytes[i] ?? 0;
337
+ const addrByte = constraintAddr[i] ?? 0;
338
+ const maskByte = constraintMask[i] ?? 0;
339
+ if ((nameByte & maskByte) !== (addrByte & maskByte)) return false;
340
+ }
341
+ return true;
342
+ }
343
+ /**
344
+ * RFC 5280 §4.2.1.10: DirectoryName constraint matching.
345
+ * The subject DN must equal or be subordinate to the constraint DN,
346
+ * using RFC 5280 section 7.1 name comparison semantics.
347
+ */
348
+ function matchesDnConstraint(subjectDerHex, constraintDerHex) {
349
+ const subjectName = parseDirectoryNameDerHex(subjectDerHex);
350
+ const constraintName = parseDirectoryNameDerHex(constraintDerHex);
351
+ if (subjectName === void 0 || constraintName === void 0) return false;
352
+ return isWithinDirectoryNameSubtree(subjectName, constraintName);
353
+ }
354
+ /** Re-parses a hex-encoded DER Name for RDN-by-RDN comparison. Returns `undefined` on malformed input. */
355
+ function parseDirectoryNameDerHex(derHex) {
356
+ if (!/^(?:[0-9a-fA-F]{2})+$/.test(derHex)) return;
357
+ try {
358
+ const bytes = hexToBytes(derHex);
359
+ const element = unwrapDirectoryNameElement(bytes, readRootElement(bytes, { maxDepth: 64 }));
360
+ if (element.tag !== 48) return;
361
+ const rdns = [];
362
+ const attributes = [];
363
+ const values = {};
364
+ for (const setElement of childrenOf(bytes, element)) {
365
+ const rdn = parseDirectoryNameRdn(bytes, setElement);
366
+ if (rdn === void 0) return;
367
+ rdns.push(rdn);
368
+ for (const attribute of rdn.attributes) {
369
+ attributes.push(attribute);
370
+ if (attribute.key !== void 0 && values[attribute.key] === void 0) values[attribute.key] = attribute.value;
371
+ }
372
+ }
373
+ return {
374
+ derHex: toHex(bytes),
375
+ rdns,
376
+ attributes,
377
+ values
378
+ };
379
+ } catch {
380
+ return;
381
+ }
382
+ }
383
+ /**
384
+ * Unwraps doubly-nested directoryName SEQUENCE encoding.
385
+ *
386
+ * Some encoders produce `[4] { SEQ { SEQ { SET... } } }` instead of `[4] { SEQ { SET... } }`.
387
+ * A single SEQUENCE child indicates the extra wrapper (valid Names have SET children).
388
+ */
389
+ function unwrapDirectoryNameElement(source, element) {
390
+ if (element.tag !== 48) return element;
391
+ const children = childrenOf(source, element);
392
+ const child = children[0];
393
+ if (children.length === 1 && child?.tag === 48) return child;
394
+ return element;
395
+ }
396
+ /** Parses one SET element (a single RDN) from the DER Name SEQUENCE. */
397
+ function parseDirectoryNameRdn(source, setElement) {
398
+ if (setElement.tag !== 49) return;
399
+ const children = childrenOf(source, setElement);
400
+ if (children.length === 0) return;
401
+ const attributes = [];
402
+ const values = {};
403
+ for (const attributeSequence of children) {
404
+ if (attributeSequence.tag !== 48) return;
405
+ const parts = childrenOf(source, attributeSequence);
406
+ const oidElement = parts[0];
407
+ const valueElement = parts[1];
408
+ if (oidElement === void 0 || valueElement === void 0 || parts.length !== 2) return;
409
+ if (oidElement.tag !== 6) return;
410
+ const oid = decodeObjectIdentifier(requireElement(oidElement, "directoryName OID").value);
411
+ let fieldValue;
412
+ try {
413
+ fieldValue = decodeString(valueElement.tag, requireElement(valueElement, "directoryName value").value);
414
+ } catch {
415
+ return;
416
+ }
417
+ const fieldKey = nameFieldKeyFromOid(oid);
418
+ const attribute = fieldKey !== void 0 ? {
419
+ oid,
420
+ key: fieldKey,
421
+ valueTag: valueElement.tag,
422
+ value: fieldValue
423
+ } : {
424
+ oid,
425
+ valueTag: valueElement.tag,
426
+ value: fieldValue
427
+ };
428
+ attributes.push(attribute);
429
+ if (fieldKey !== void 0 && values[fieldKey] === void 0) values[fieldKey] = fieldValue;
430
+ }
431
+ if (attributes.length === 0) return;
432
+ return {
433
+ derHex: toHex(source.slice(setElement.start - setElement.headerLength, setElement.end)),
434
+ attributes,
435
+ values
436
+ };
437
+ }
438
+ /** Human-readable label for a constraint form, used in error messages. */
439
+ function formatConstraintForm(form) {
440
+ switch (form.type) {
441
+ case "dns": return `dns:${form.value}`;
442
+ case "email": return `email:${form.value}`;
443
+ case "uri": return `uri:${form.value}`;
444
+ case "ip": return `ip:${decodeIpAddress(form.addressBytes)}`;
445
+ case "directoryName": return `dn:${form.derHex.slice(0, 20)}${form.derHex.length > 20 ? "..." : ""}`;
446
+ default: throw new Error(`Unhandled NameConstraintForm type: ${String(form)}`);
447
+ }
448
+ }
449
+ //#endregion
450
+ export { createNameConstraintValidationState, evaluateNameConstraints };