micro509 0.11.0 → 0.12.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.
@@ -0,0 +1,50 @@
1
+ import { SubjectAltName } from "./extensions.js";
2
+ import { ParsedName, ParsedRelativeDistinguishedName } from "./parse.js";
3
+ //#region src/x509/name-text.d.ts
4
+ /** Options for {@linkcode subjectAltNameToString}. */
5
+ interface SubjectAltNameTextOptions {
6
+ /** Prepend `{@linkcode subjectAltNameLabel}:` to the value, as `openssl x509 -text` does. Defaults to `false`. */
7
+ readonly prefix?: boolean;
8
+ }
9
+ /**
10
+ * Renders one {@linkcode SubjectAltName} as text.
11
+ *
12
+ * | variant | rendering |
13
+ * | --- | --- |
14
+ * | `dns`, `ip`, `email`, `uri`, `srv` | the value itself |
15
+ * | `directoryName` | {@linkcode distinguishedNameToString} of the embedded name, or the DER hex if it does not decode |
16
+ * | `unknown` | lowercase hex of the raw content bytes |
17
+ *
18
+ * @example Render every SAN of a parsed certificate
19
+ * ```ts
20
+ * const names = (parsed.subjectAltNames ?? []).map((name) => subjectAltNameToString(name));
21
+ * // ['example.com', '192.0.2.1', 'CN=Example CA,C=US']
22
+ *
23
+ * subjectAltNameToString({ type: 'dns', value: 'example.com' }, { prefix: true }); // 'DNS:example.com'
24
+ * ```
25
+ */
26
+ declare function subjectAltNameToString(name: SubjectAltName, options?: SubjectAltNameTextOptions): string;
27
+ /**
28
+ * The `openssl x509 -text` label for a {@linkcode SubjectAltName} variant —
29
+ * `DNS`, `IP Address`, `email`, `URI`, `SRV`, `DirName`, or `[tag <n>]` for an unrecognized tag.
30
+ */
31
+ declare function subjectAltNameLabel(name: SubjectAltName): string;
32
+ /**
33
+ * Renders a {@linkcode ParsedName} as an RFC 4514 distinguished name string, e.g. `CN=Example CA,O=Acme,C=US`.
34
+ *
35
+ * RDNs are emitted in reverse encoding order and multi-valued RDNs are joined with `+`,
36
+ * both per RFC 4514 [§2](https://datatracker.ietf.org/doc/html/rfc4514#section-2).
37
+ * Attribute types outside the RFC 4514 [§3](https://datatracker.ietf.org/doc/html/rfc4514#section-3)
38
+ * keyword table use the short names `openssl` prints, falling back to the dotted OID.
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * distinguishedNameToString(parsed.subject); // 'CN=example.com,O=Acme\\, Inc.,C=US'
43
+ * ```
44
+ */
45
+ declare function distinguishedNameToString(name: ParsedName): string;
46
+ /** Renders one {@linkcode ParsedRelativeDistinguishedName}, joining a multi-valued RDN's attributes with `+`. */
47
+ declare function relativeDistinguishedNameToString(rdn: ParsedRelativeDistinguishedName): string;
48
+ //#endregion
49
+ export { SubjectAltNameTextOptions, distinguishedNameToString, relativeDistinguishedNameToString, subjectAltNameLabel, subjectAltNameToString };
50
+ //# sourceMappingURL=name-text.d.ts.map
@@ -0,0 +1,111 @@
1
+ import { hexToBytes as e, toHex as t } from "../internal/asn1/asn1.js";
2
+ import { DN_ATTRIBUTE_KEYWORDS as n } from "../internal/x509/name-fields.js";
3
+ import { parseDistinguishedNameDer as r } from "./parse.js";
4
+ //#region src/x509/name-text.ts
5
+ /**
6
+ * Human-readable text for parsed names.
7
+ *
8
+ * Renders a {@linkcode ParsedName} or {@linkcode SubjectAltName} as a display string,
9
+ * covering every variant of the union without the caller narrowing it by hand.
10
+ *
11
+ * @module micro509/x509/name-text
12
+ */
13
+ /**
14
+ * Renders one {@linkcode SubjectAltName} as text.
15
+ *
16
+ * | variant | rendering |
17
+ * | --- | --- |
18
+ * | `dns`, `ip`, `email`, `uri`, `srv` | the value itself |
19
+ * | `directoryName` | {@linkcode distinguishedNameToString} of the embedded name, or the DER hex if it does not decode |
20
+ * | `unknown` | lowercase hex of the raw content bytes |
21
+ *
22
+ * @example Render every SAN of a parsed certificate
23
+ * ```ts
24
+ * const names = (parsed.subjectAltNames ?? []).map((name) => subjectAltNameToString(name));
25
+ * // ['example.com', '192.0.2.1', 'CN=Example CA,C=US']
26
+ *
27
+ * subjectAltNameToString({ type: 'dns', value: 'example.com' }, { prefix: true }); // 'DNS:example.com'
28
+ * ```
29
+ */
30
+ function subjectAltNameToString(e, t) {
31
+ let n = subjectAltNameText(e);
32
+ return t?.prefix === !0 ? `${subjectAltNameLabel(e)}:${n}` : n;
33
+ }
34
+ /**
35
+ * The `openssl x509 -text` label for a {@linkcode SubjectAltName} variant —
36
+ * `DNS`, `IP Address`, `email`, `URI`, `SRV`, `DirName`, or `[tag <n>]` for an unrecognized tag.
37
+ */
38
+ function subjectAltNameLabel(e) {
39
+ switch (e.type) {
40
+ case "dns": return "DNS";
41
+ case "ip": return "IP Address";
42
+ case "email": return "email";
43
+ case "uri": return "URI";
44
+ case "srv": return "SRV";
45
+ case "directoryName": return "DirName";
46
+ case "unknown": return `[tag ${String(e.tag)}]`;
47
+ }
48
+ }
49
+ /**
50
+ * Renders a {@linkcode ParsedName} as an RFC 4514 distinguished name string, e.g. `CN=Example CA,O=Acme,C=US`.
51
+ *
52
+ * RDNs are emitted in reverse encoding order and multi-valued RDNs are joined with `+`,
53
+ * both per RFC 4514 [§2](https://datatracker.ietf.org/doc/html/rfc4514#section-2).
54
+ * Attribute types outside the RFC 4514 [§3](https://datatracker.ietf.org/doc/html/rfc4514#section-3)
55
+ * keyword table use the short names `openssl` prints, falling back to the dotted OID.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * distinguishedNameToString(parsed.subject); // 'CN=example.com,O=Acme\\, Inc.,C=US'
60
+ * ```
61
+ */
62
+ function distinguishedNameToString(e) {
63
+ return [...e.rdns].reverse().map((e) => relativeDistinguishedNameToString(e)).join(",");
64
+ }
65
+ /** Renders one {@linkcode ParsedRelativeDistinguishedName}, joining a multi-valued RDN's attributes with `+`. */
66
+ function relativeDistinguishedNameToString(e) {
67
+ return e.attributes.map((e) => attributeToString(e)).join("+");
68
+ }
69
+ /** Characters RFC 4514 [§2.4](https://datatracker.ietf.org/doc/html/rfc4514#section-2.4) escapes wherever they appear. */
70
+ const i = /* @__PURE__ */ new Set([
71
+ "\"",
72
+ "+",
73
+ ",",
74
+ ";",
75
+ "<",
76
+ ">",
77
+ "\\"
78
+ ]);
79
+ function attributeToString(e) {
80
+ return `${n[e.oid] ?? e.oid}=${escapeAttributeValue(e.value)}`;
81
+ }
82
+ function escapeAttributeValue(e) {
83
+ let t = [...e];
84
+ return t.map((e, n) => {
85
+ if (i.has(e)) return `\\${e}`;
86
+ let r = e.codePointAt(0) ?? 0;
87
+ return r < 32 || r === 127 ? `\\${r.toString(16).padStart(2, "0")}` : e === " " && (n === 0 || n === t.length - 1) ? "\\ " : e === "#" && n === 0 ? "\\#" : e;
88
+ }).join("");
89
+ }
90
+ function subjectAltNameText(e) {
91
+ switch (e.type) {
92
+ case "dns":
93
+ case "ip":
94
+ case "email":
95
+ case "uri":
96
+ case "srv": return e.value;
97
+ case "directoryName": return directoryNameText(e.derHex);
98
+ case "unknown": return t(e.value);
99
+ }
100
+ }
101
+ function directoryNameText(t) {
102
+ try {
103
+ return distinguishedNameToString(r(e(t)));
104
+ } catch {
105
+ return t;
106
+ }
107
+ }
108
+ //#endregion
109
+ export { distinguishedNameToString, relativeDistinguishedNameToString, subjectAltNameLabel, subjectAltNameToString };
110
+
111
+ //# sourceMappingURL=name-text.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"name-text.js","names":[],"sources":["../../src/x509/name-text.ts"],"sourcesContent":["/**\n * Human-readable text for parsed names.\n *\n * Renders a {@linkcode ParsedName} or {@linkcode SubjectAltName} as a display string,\n * covering every variant of the union without the caller narrowing it by hand.\n *\n * @module micro509/x509/name-text\n */\n\nimport { hexToBytes, toHex } from '#micro509/internal/asn1/asn1';\nimport { DN_ATTRIBUTE_KEYWORDS } from '#micro509/internal/x509/name-fields';\nimport type { SubjectAltName } from '#micro509/x509/extensions';\nimport type {\n\tParsedName,\n\tParsedNameAttribute,\n\tParsedRelativeDistinguishedName,\n} from '#micro509/x509/parse';\nimport { parseDistinguishedNameDer } from '#micro509/x509/parse';\n\n/** Options for {@linkcode subjectAltNameToString}. */\nexport interface SubjectAltNameTextOptions {\n\t/** Prepend `{@linkcode subjectAltNameLabel}:` to the value, as `openssl x509 -text` does. Defaults to `false`. */\n\treadonly prefix?: boolean;\n}\n\n/**\n * Renders one {@linkcode SubjectAltName} as text.\n *\n * | variant | rendering |\n * | --- | --- |\n * | `dns`, `ip`, `email`, `uri`, `srv` | the value itself |\n * | `directoryName` | {@linkcode distinguishedNameToString} of the embedded name, or the DER hex if it does not decode |\n * | `unknown` | lowercase hex of the raw content bytes |\n *\n * @example Render every SAN of a parsed certificate\n * ```ts\n * const names = (parsed.subjectAltNames ?? []).map((name) => subjectAltNameToString(name));\n * // ['example.com', '192.0.2.1', 'CN=Example CA,C=US']\n *\n * subjectAltNameToString({ type: 'dns', value: 'example.com' }, { prefix: true }); // 'DNS:example.com'\n * ```\n */\nexport function subjectAltNameToString(\n\tname: SubjectAltName,\n\toptions?: SubjectAltNameTextOptions,\n): string {\n\tconst text = subjectAltNameText(name);\n\treturn options?.prefix === true ? `${subjectAltNameLabel(name)}:${text}` : text;\n}\n\n/**\n * The `openssl x509 -text` label for a {@linkcode SubjectAltName} variant —\n * `DNS`, `IP Address`, `email`, `URI`, `SRV`, `DirName`, or `[tag <n>]` for an unrecognized tag.\n */\nexport function subjectAltNameLabel(name: SubjectAltName): string {\n\tswitch (name.type) {\n\t\tcase 'dns':\n\t\t\treturn 'DNS';\n\t\tcase 'ip':\n\t\t\treturn 'IP Address';\n\t\tcase 'email':\n\t\t\treturn 'email';\n\t\tcase 'uri':\n\t\t\treturn 'URI';\n\t\tcase 'srv':\n\t\t\treturn 'SRV';\n\t\tcase 'directoryName':\n\t\t\treturn 'DirName';\n\t\tcase 'unknown':\n\t\t\treturn `[tag ${String(name.tag)}]`;\n\t}\n}\n\n/**\n * Renders a {@linkcode ParsedName} as an RFC 4514 distinguished name string, e.g. `CN=Example CA,O=Acme,C=US`.\n *\n * RDNs are emitted in reverse encoding order and multi-valued RDNs are joined with `+`,\n * both per RFC 4514 [§2](https://datatracker.ietf.org/doc/html/rfc4514#section-2).\n * Attribute types outside the RFC 4514 [§3](https://datatracker.ietf.org/doc/html/rfc4514#section-3)\n * keyword table use the short names `openssl` prints, falling back to the dotted OID.\n *\n * @example\n * ```ts\n * distinguishedNameToString(parsed.subject); // 'CN=example.com,O=Acme\\\\, Inc.,C=US'\n * ```\n */\nexport function distinguishedNameToString(name: ParsedName): string {\n\treturn [...name.rdns]\n\t\t.reverse()\n\t\t.map((rdn) => relativeDistinguishedNameToString(rdn))\n\t\t.join(',');\n}\n\n/** Renders one {@linkcode ParsedRelativeDistinguishedName}, joining a multi-valued RDN's attributes with `+`. */\nexport function relativeDistinguishedNameToString(rdn: ParsedRelativeDistinguishedName): string {\n\treturn rdn.attributes.map((attribute) => attributeToString(attribute)).join('+');\n}\n\n/** Characters RFC 4514 [§2.4](https://datatracker.ietf.org/doc/html/rfc4514#section-2.4) escapes wherever they appear. */\nconst ESCAPED_CHARACTERS = new Set(['\"', '+', ',', ';', '<', '>', '\\\\']);\n\nfunction attributeToString(attribute: ParsedNameAttribute): string {\n\tconst keyword = DN_ATTRIBUTE_KEYWORDS[attribute.oid] ?? attribute.oid;\n\treturn `${keyword}=${escapeAttributeValue(attribute.value)}`;\n}\n\nfunction escapeAttributeValue(value: string): string {\n\tconst characters = [...value];\n\treturn characters\n\t\t.map((character, index) => {\n\t\t\tif (ESCAPED_CHARACTERS.has(character)) {\n\t\t\t\treturn `\\\\${character}`;\n\t\t\t}\n\t\t\tconst code = character.codePointAt(0) ?? 0;\n\t\t\tif (code < 0x20 || code === 0x7f) {\n\t\t\t\treturn `\\\\${code.toString(16).padStart(2, '0')}`;\n\t\t\t}\n\t\t\tif (character === ' ' && (index === 0 || index === characters.length - 1)) {\n\t\t\t\treturn '\\\\ ';\n\t\t\t}\n\t\t\treturn character === '#' && index === 0 ? '\\\\#' : character;\n\t\t})\n\t\t.join('');\n}\n\nfunction subjectAltNameText(name: SubjectAltName): string {\n\tswitch (name.type) {\n\t\tcase 'dns':\n\t\tcase 'ip':\n\t\tcase 'email':\n\t\tcase 'uri':\n\t\tcase 'srv':\n\t\t\treturn name.value;\n\t\tcase 'directoryName':\n\t\t\treturn directoryNameText(name.derHex);\n\t\tcase 'unknown':\n\t\t\treturn toHex(name.value);\n\t}\n}\n\nfunction directoryNameText(derHex: string): string {\n\ttry {\n\t\treturn distinguishedNameToString(parseDistinguishedNameDer(hexToBytes(derHex)));\n\t} catch {\n\t\treturn derHex;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,uBACf,GACA,GACS;CACT,IAAM,IAAO,mBAAmB,CAAI;CACpC,OAAO,GAAS,WAAW,KAAO,GAAG,oBAAoB,CAAI,EAAE,GAAG,MAAS;AAC5E;;;;;AAMA,SAAgB,oBAAoB,GAA8B;CACjE,QAAQ,EAAK,MAAb;EACC,KAAK,OACJ,OAAO;EACR,KAAK,MACJ,OAAO;EACR,KAAK,SACJ,OAAO;EACR,KAAK,OACJ,OAAO;EACR,KAAK,OACJ,OAAO;EACR,KAAK,iBACJ,OAAO;EACR,KAAK,WACJ,OAAO,QAAQ,OAAO,EAAK,GAAG,EAAE;CAClC;AACD;;;;;;;;;;;;;;AAeA,SAAgB,0BAA0B,GAA0B;CACnE,OAAO,CAAC,GAAG,EAAK,IAAI,CAAC,CACnB,QAAQ,CAAC,CACT,KAAK,MAAQ,kCAAkC,CAAG,CAAC,CAAC,CACpD,KAAK,GAAG;AACX;;AAGA,SAAgB,kCAAkC,GAA8C;CAC/F,OAAO,EAAI,WAAW,KAAK,MAAc,kBAAkB,CAAS,CAAC,CAAC,CAAC,KAAK,GAAG;AAChF;;AAGA,MAAM,oBAAqB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;AAAI,CAAC;AAEvE,SAAS,kBAAkB,GAAwC;CAElE,OAAO,GADS,EAAsB,EAAU,QAAQ,EAAU,IAChD,GAAG,qBAAqB,EAAU,KAAK;AAC1D;AAEA,SAAS,qBAAqB,GAAuB;CACpD,IAAM,IAAa,CAAC,GAAG,CAAK;CAC5B,OAAO,EACL,KAAK,GAAW,MAAU;EAC1B,IAAI,EAAmB,IAAI,CAAS,GACnC,OAAO,KAAK;EAEb,IAAM,IAAO,EAAU,YAAY,CAAC,KAAK;EAOzC,OANI,IAAO,MAAQ,MAAS,MACpB,KAAK,EAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,MAE1C,MAAc,QAAQ,MAAU,KAAK,MAAU,EAAW,SAAS,KAC/D,QAED,MAAc,OAAO,MAAU,IAAI,QAAQ;CACnD,CAAC,CAAC,CACD,KAAK,EAAE;AACV;AAEA,SAAS,mBAAmB,GAA8B;CACzD,QAAQ,EAAK,MAAb;EACC,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,OACJ,OAAO,EAAK;EACb,KAAK,iBACJ,OAAO,kBAAkB,EAAK,MAAM;EACrC,KAAK,WACJ,OAAO,EAAM,EAAK,KAAK;CACzB;AACD;AAEA,SAAS,kBAAkB,GAAwB;CAClD,IAAI;EACH,OAAO,0BAA0B,EAA0B,EAAW,CAAM,CAAC,CAAC;CAC/E,QAAQ;EACP,OAAO;CACR;AACD"}
@@ -361,6 +361,9 @@ declare function parseCertificatePemOrThrow<TMap extends ExtensionDecoderMap = R
361
361
  * Expects a single `-----BEGIN CERTIFICATE-----` block. For bundles
362
362
  * containing multiple certificates, use {@linkcode parseCertificateChainPem}.
363
363
  *
364
+ * **Synchronous:** returns a {@linkcode ParseCertificateResult} directly. Do
365
+ * not `await` this function.
366
+ *
364
367
  * @param pem PEM string with a CERTIFICATE block.
365
368
  * @param options Custom extension decoders to apply during parsing.
366
369
  */
@@ -195,6 +195,9 @@ function parseCertificatePemOrThrow(e, t) {
195
195
  * Expects a single `-----BEGIN CERTIFICATE-----` block. For bundles
196
196
  * containing multiple certificates, use {@linkcode parseCertificateChainPem}.
197
197
  *
198
+ * **Synchronous:** returns a {@linkcode ParseCertificateResult} directly. Do
199
+ * not `await` this function.
200
+ *
198
201
  * @param pem PEM string with a CERTIFICATE block.
199
202
  * @param options Custom extension decoders to apply during parsing.
200
203
  */
@@ -829,6 +832,12 @@ function parseInhibitAnyPolicy(e) {
829
832
  function parseSubjectAltNames(e) {
830
833
  return i(e, f(n(e, { maxDepth: 64 }), "subjectAltName sequence")).map((t) => parseGeneralName(e, t));
831
834
  }
835
+ /** @internal Decode a bare DER-encoded X.501 Name, as carried in a `directoryName` GeneralName. */
836
+ function parseDistinguishedNameDer(e) {
837
+ let t = f(n(e, { maxDepth: 64 }), "distinguished name sequence");
838
+ if (t.tag !== 48) throw Error("distinguished name must use SEQUENCE");
839
+ return parseName(e, t);
840
+ }
832
841
  /** @internal Decode the Authority Information Access extension value. */
833
842
  function parseAuthorityInfoAccess(e) {
834
843
  let t = f(n(e, { maxDepth: 64 }), "authorityInfoAccess sequence");
@@ -1170,6 +1179,6 @@ function validateImplicitBitStringContent(e, t) {
1170
1179
  if (i & (1 << n) - 1) throw Error(`${t} BIT STRING must not set padding bits`);
1171
1180
  }
1172
1181
  //#endregion
1173
- export { certificateMatchesPrivateKey, decodeExtension, decodeExtensionMap, decodeExtensions, defineExtensionDecoder, defineExtensionDecoderMap, findExtension, getSubjectPublicKey, getSubjectPublicKeyOrThrow, matchCertificatePrivateKey, parseAuthorityInfoAccess, parseAuthorityKeyIdentifier, parseBasicConstraints, parseCertificateChainPem, parseCertificateDer, parseCertificateDerOrThrow, parseCertificateFromSource, parseCertificatePem, parseCertificatePemOrThrow, parseCertificatePolicies, parseCertificateSigningRequestDer, parseCertificateSigningRequestDerOrThrow, parseCertificateSigningRequestPem, parseCertificateSigningRequestPemOrThrow, parseCertificatesFromSource, parseCrlDistributionPoints, parseExtendedKeyUsage, parseInhibitAnyPolicy, parseKeyUsage, parseNameConstraints, parsePolicyConstraints, parsePolicyMappings, parseSubjectAltNames };
1182
+ export { certificateMatchesPrivateKey, decodeExtension, decodeExtensionMap, decodeExtensions, defineExtensionDecoder, defineExtensionDecoderMap, findExtension, getSubjectPublicKey, getSubjectPublicKeyOrThrow, matchCertificatePrivateKey, parseAuthorityInfoAccess, parseAuthorityKeyIdentifier, parseBasicConstraints, parseCertificateChainPem, parseCertificateDer, parseCertificateDerOrThrow, parseCertificateFromSource, parseCertificatePem, parseCertificatePemOrThrow, parseCertificatePolicies, parseCertificateSigningRequestDer, parseCertificateSigningRequestDerOrThrow, parseCertificateSigningRequestPem, parseCertificateSigningRequestPemOrThrow, parseCertificatesFromSource, parseCrlDistributionPoints, parseDistinguishedNameDer, parseExtendedKeyUsage, parseInhibitAnyPolicy, parseKeyUsage, parseNameConstraints, parsePolicyConstraints, parsePolicyMappings, parseSubjectAltNames };
1174
1183
 
1175
1184
  //# sourceMappingURL=parse.js.map