micro509 0.10.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.
- package/README.md +17 -3
- package/dist/index.d.ts +4 -2
- package/dist/index.js +14 -12
- package/dist/internal/asn1/oids.js +22 -0
- package/dist/internal/shared/dn.js +1 -1
- package/dist/internal/shared/dn.js.map +1 -1
- package/dist/internal/verify/policy-engine.js +1 -1
- package/dist/internal/verify/policy-engine.js.map +1 -1
- package/dist/internal/x509/name-fields.js +19 -4
- package/dist/internal/x509/name-fields.js.map +1 -1
- package/dist/revocation/crl.js +2 -2
- package/dist/revocation/crl.js.map +1 -1
- package/dist/revocation/ocsp.js +1 -1
- package/dist/revocation/ocsp.js.map +1 -1
- package/dist/x509/fingerprint.d.ts +58 -0
- package/dist/x509/fingerprint.js +58 -0
- package/dist/x509/fingerprint.js.map +1 -0
- package/dist/x509/name-text.d.ts +50 -0
- package/dist/x509/name-text.js +111 -0
- package/dist/x509/name-text.js.map +1 -0
- package/dist/x509/parse.d.ts +107 -1
- package/dist/x509/parse.js +162 -30
- package/dist/x509/parse.js.map +1 -1
- package/dist/x509.d.ts +4 -2
- package/dist/x509.js +6 -4
- package/package.json +21 -10
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { toArrayBuffer as e, toHex as t } from "../internal/asn1/asn1.js";
|
|
2
|
+
import { getCrypto as n } from "../internal/crypto/webcrypto.js";
|
|
3
|
+
import { parseCertificateFromSource as r } from "./parse.js";
|
|
4
|
+
//#region src/x509/fingerprint.ts
|
|
5
|
+
/**
|
|
6
|
+
* Certificate fingerprints: a cryptographic hash over the DER encoding.
|
|
7
|
+
*
|
|
8
|
+
* This is the identifier that `openssl x509 -fingerprint` and every TLS UI show.
|
|
9
|
+
* The helper accepts the same PEM / DER / parsed-certificate source union as
|
|
10
|
+
* the verification APIs and returns the digest in the forms callers actually
|
|
11
|
+
* paste around: raw bytes, lowercase hex, and uppercase colon-separated hex.
|
|
12
|
+
*
|
|
13
|
+
* @module
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* Compute a certificate fingerprint — a hash over the DER encoding.
|
|
17
|
+
*
|
|
18
|
+
* The certificate is parsed (validating the input and, for PEM, decoding it to
|
|
19
|
+
* DER) before hashing, so the digest is always taken over the canonical DER of
|
|
20
|
+
* a well-formed certificate. Malformed input throws, matching the other DER/PEM
|
|
21
|
+
* boundaries in the library.
|
|
22
|
+
*
|
|
23
|
+
* **Asynchronous:** hashing uses WebCrypto's `crypto.subtle.digest`. Await the
|
|
24
|
+
* returned promise before reading `bytes`, `hex`, or `colonHex`.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```ts
|
|
28
|
+
* const fingerprint = await certificateFingerprint(pemString);
|
|
29
|
+
* console.log(fingerprint.colonHex); // "AB:CD:…" — matches `openssl x509 -fingerprint -sha256`
|
|
30
|
+
* ```
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```ts
|
|
34
|
+
* // Reuse an already-parsed certificate and request SHA-1.
|
|
35
|
+
* const parsed = parseCertificatePemOrThrow(pemString);
|
|
36
|
+
* const legacy = await certificateFingerprint(parsed, 'SHA-1');
|
|
37
|
+
* console.log(legacy.hex);
|
|
38
|
+
* ```
|
|
39
|
+
*
|
|
40
|
+
* @param certificate PEM string, DER bytes, or a {@linkcode ParsedCertificate}.
|
|
41
|
+
* @param algorithm Digest algorithm to use. Defaults to `'SHA-256'`.
|
|
42
|
+
*/
|
|
43
|
+
async function certificateFingerprint(i, a = "SHA-256") {
|
|
44
|
+
let { der: o } = r(i), s = await n().subtle.digest(a, e(o)), c = new Uint8Array(s);
|
|
45
|
+
return {
|
|
46
|
+
bytes: c,
|
|
47
|
+
hex: t(c),
|
|
48
|
+
colonHex: toColonHex(c)
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Renders bytes as uppercase, colon-separated hex (openssl fingerprint style). */
|
|
52
|
+
function toColonHex(e) {
|
|
53
|
+
return Array.from(e, (e) => e.toString(16).padStart(2, "0").toUpperCase()).join(":");
|
|
54
|
+
}
|
|
55
|
+
//#endregion
|
|
56
|
+
export { certificateFingerprint };
|
|
57
|
+
|
|
58
|
+
//# sourceMappingURL=fingerprint.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fingerprint.js","names":[],"sources":["../../src/x509/fingerprint.ts"],"sourcesContent":["/**\n * Certificate fingerprints: a cryptographic hash over the DER encoding.\n *\n * This is the identifier that `openssl x509 -fingerprint` and every TLS UI show.\n * The helper accepts the same PEM / DER / parsed-certificate source union as\n * the verification APIs and returns the digest in the forms callers actually\n * paste around: raw bytes, lowercase hex, and uppercase colon-separated hex.\n *\n * @module\n */\n\nimport { toArrayBuffer, toHex } from '#micro509/internal/asn1/asn1';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificateFromSource } from '#micro509/x509/parse';\n\n/**\n * A PEM string, raw DER bytes, or an already-parsed certificate.\n *\n * Mirrors the source union accepted by the verification, revocation, and\n * PKCS APIs so a fingerprint can be taken from whatever a caller already holds.\n */\nexport type CertificateFingerprintSource = string | Uint8Array | ParsedCertificate;\n\n/**\n * Digest algorithms supported by {@linkcode certificateFingerprint}.\n *\n * SHA-1 is intentionally included: legacy ecosystems (PGP-adjacent tooling,\n * older certificate pinning) still identify certificates by their SHA-1\n * fingerprint. Prefer SHA-256 for anything new.\n */\nexport type CertificateFingerprintAlgorithm = 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n/** The three rendered forms of a certificate fingerprint. */\nexport interface CertificateFingerprint {\n\t/** Raw digest bytes. */\n\treadonly bytes: Uint8Array;\n\t/** Lowercase hex, no separators (e.g. `\"a1b2c3…\"`). */\n\treadonly hex: string;\n\t/** Uppercase hex, colon-separated (e.g. `\"A1:B2:C3:…\"`, `openssl x509 -fingerprint` style). */\n\treadonly colonHex: string;\n}\n\n/**\n * Compute a certificate fingerprint — a hash over the DER encoding.\n *\n * The certificate is parsed (validating the input and, for PEM, decoding it to\n * DER) before hashing, so the digest is always taken over the canonical DER of\n * a well-formed certificate. Malformed input throws, matching the other DER/PEM\n * boundaries in the library.\n *\n * **Asynchronous:** hashing uses WebCrypto's `crypto.subtle.digest`. Await the\n * returned promise before reading `bytes`, `hex`, or `colonHex`.\n *\n * @example\n * ```ts\n * const fingerprint = await certificateFingerprint(pemString);\n * console.log(fingerprint.colonHex); // \"AB:CD:…\" — matches `openssl x509 -fingerprint -sha256`\n * ```\n *\n * @example\n * ```ts\n * // Reuse an already-parsed certificate and request SHA-1.\n * const parsed = parseCertificatePemOrThrow(pemString);\n * const legacy = await certificateFingerprint(parsed, 'SHA-1');\n * console.log(legacy.hex);\n * ```\n *\n * @param certificate PEM string, DER bytes, or a {@linkcode ParsedCertificate}.\n * @param algorithm Digest algorithm to use. Defaults to `'SHA-256'`.\n */\nexport async function certificateFingerprint(\n\tcertificate: CertificateFingerprintSource,\n\talgorithm: CertificateFingerprintAlgorithm = 'SHA-256',\n): Promise<CertificateFingerprint> {\n\tconst { der } = parseCertificateFromSource(certificate);\n\tconst digest = await getCrypto().subtle.digest(algorithm, toArrayBuffer(der));\n\tconst bytes = new Uint8Array(digest);\n\treturn {\n\t\tbytes,\n\t\thex: toHex(bytes),\n\t\tcolonHex: toColonHex(bytes),\n\t};\n}\n\n/** Renders bytes as uppercase, colon-separated hex (openssl fingerprint style). */\nfunction toColonHex(bytes: Uint8Array): string {\n\treturn Array.from(bytes, (value) => value.toString(16).padStart(2, '0').toUpperCase()).join(':');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,eAAsB,uBACrB,GACA,IAA6C,WACX;CAClC,IAAM,EAAE,WAAQ,EAA2B,CAAW,GAChD,IAAS,MAAM,EAAU,CAAC,CAAC,OAAO,OAAO,GAAW,EAAc,CAAG,CAAC,GACtE,IAAQ,IAAI,WAAW,CAAM;CACnC,OAAO;EACN;EACA,KAAK,EAAM,CAAK;EAChB,UAAU,WAAW,CAAK;CAC3B;AACD;;AAGA,SAAS,WAAW,GAA2B;CAC9C,OAAO,MAAM,KAAK,IAAQ,MAAU,EAAM,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,GAAG;AAChG"}
|
|
@@ -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"}
|
package/dist/x509/parse.d.ts
CHANGED
|
@@ -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
|
*/
|
|
@@ -437,6 +440,109 @@ declare function getSubjectPublicKeyOrThrow<TMap extends ExtensionDecoderMap = R
|
|
|
437
440
|
* @see `getSubjectPublicKeyOrThrow` for the throwing variant
|
|
438
441
|
*/
|
|
439
442
|
declare function getSubjectPublicKey<TMap extends ExtensionDecoderMap = Record<never, never>>(parsed: ParsedCertificate<TMap> | ParsedCertificateSigningRequest<TMap>, algorithm?: PublicKeyImportInput): Promise<ImportKeyResult<CryptoKey>>;
|
|
443
|
+
/**
|
|
444
|
+
* Check whether a certificate's subject public key belongs to a private key.
|
|
445
|
+
*
|
|
446
|
+
* Confirming that an uploaded private key actually matches the certificate it
|
|
447
|
+
* was submitted with is the first thing a key-intake or issuance endpoint must
|
|
448
|
+
* do. This derives the public half of `privateKey`, exports it as
|
|
449
|
+
* SubjectPublicKeyInfo DER, and compares those bytes against the certificate's
|
|
450
|
+
* own SubjectPublicKeyInfo — the canonical, algorithm-agnostic way to test key
|
|
451
|
+
* ownership. (Comparing JWKs field by field, or signing a probe and verifying
|
|
452
|
+
* it, are both more fragile.)
|
|
453
|
+
*
|
|
454
|
+
* A private key of a different type — e.g. an ECDSA key against an RSA
|
|
455
|
+
* certificate — simply produces different SPKI DER and returns `false`, so
|
|
456
|
+
* callers get a single boolean without branching on the kind of mismatch. Reach
|
|
457
|
+
* for {@linkcode matchCertificatePrivateKey} when you need the reason a match
|
|
458
|
+
* failed (or a typed failure instead of a thrown error) at a trust boundary.
|
|
459
|
+
*
|
|
460
|
+
* The comparison is over the exact DER encoding. A certificate whose
|
|
461
|
+
* SubjectPublicKeyInfo pins RSASSA-PSS parameters (rather than the plain
|
|
462
|
+
* `rsaEncryption` OID that WebCrypto emits) therefore will not match even for
|
|
463
|
+
* the same modulus; such certificates are rare in practice.
|
|
464
|
+
*
|
|
465
|
+
* @param certificate PEM string, DER bytes, or an already-parsed certificate.
|
|
466
|
+
* @param privateKey An extractable private `CryptoKey`.
|
|
467
|
+
* @returns `true` when the private key's public half matches the certificate's
|
|
468
|
+
* subject public key.
|
|
469
|
+
*
|
|
470
|
+
* @throws {Error} If `certificate` is malformed, or `privateKey` is not an
|
|
471
|
+
* extractable private key of a supported type (propagated from
|
|
472
|
+
* {@linkcode derivePublicKey}). Use {@linkcode matchCertificatePrivateKey} for a
|
|
473
|
+
* typed `Result` instead of thrown errors.
|
|
474
|
+
*
|
|
475
|
+
* @example
|
|
476
|
+
* ```ts
|
|
477
|
+
* const privateKey = await importPkcs8PemOrThrow(keyPem, { kind: 'ecdsa', curve: 'P-256' });
|
|
478
|
+
* if (!(await certificateMatchesPrivateKey(certificatePem, privateKey))) {
|
|
479
|
+
* throw new Error('uploaded key does not match the certificate');
|
|
480
|
+
* }
|
|
481
|
+
* ```
|
|
482
|
+
*
|
|
483
|
+
* @see {@linkcode matchCertificatePrivateKey} for the typed-`Result` variant with a mismatch reason
|
|
484
|
+
* @see {@linkcode getSubjectPublicKeyOrThrow} to obtain the certificate's public key directly
|
|
485
|
+
* @see {@linkcode derivePublicKey} for the private-to-public bridge this builds on
|
|
486
|
+
*/
|
|
487
|
+
declare function certificateMatchesPrivateKey<TMap extends ExtensionDecoderMap = Record<never, never>>(certificate: ParsedCertificate<TMap> | string | Uint8Array, privateKey: CryptoKey): Promise<boolean>;
|
|
488
|
+
/** Machine-readable failure reason for {@linkcode matchCertificatePrivateKey}. */
|
|
489
|
+
type MatchCertificatePrivateKeyErrorCode = "malformed_certificate" | "unsupported_private_key" | "key_type_mismatch" | "key_mismatch";
|
|
490
|
+
/** Structured failure payload for {@linkcode matchCertificatePrivateKey}. */
|
|
491
|
+
interface MatchCertificatePrivateKeyFailure extends Micro509Error<MatchCertificatePrivateKeyErrorCode> {
|
|
492
|
+
/** Always `false` for failures. */
|
|
493
|
+
readonly ok: false;
|
|
494
|
+
}
|
|
495
|
+
/** A successful match: the private key's public half is the certificate's subject public key. */
|
|
496
|
+
interface MatchCertificatePrivateKeySuccess {
|
|
497
|
+
/** Always `true` for success. */
|
|
498
|
+
readonly ok: true;
|
|
499
|
+
/** No payload on success — the match itself is the signal. */
|
|
500
|
+
readonly value: undefined;
|
|
501
|
+
}
|
|
502
|
+
/** Failure branch of {@linkcode MatchCertificatePrivateKeyResult} with structured error details. */
|
|
503
|
+
type MatchCertificatePrivateKeyFailureResult = ErrorResult<MatchCertificatePrivateKeyErrorCode, Record<never, never>, MatchCertificatePrivateKeyFailure>;
|
|
504
|
+
/** Result of {@linkcode matchCertificatePrivateKey}. */
|
|
505
|
+
type MatchCertificatePrivateKeyResult = MatchCertificatePrivateKeySuccess | MatchCertificatePrivateKeyFailureResult;
|
|
506
|
+
/**
|
|
507
|
+
* Check whether a certificate's subject public key belongs to a private key,
|
|
508
|
+
* returning a typed {@linkcode MatchCertificatePrivateKeyResult}.
|
|
509
|
+
*
|
|
510
|
+
* The `Result`-returning companion to {@linkcode certificateMatchesPrivateKey}:
|
|
511
|
+
* where the boolean helper answers only "does it match?" (and throws on bad
|
|
512
|
+
* input), this surfaces the expected failures a key-intake or issuance endpoint
|
|
513
|
+
* meets on untrusted input as typed codes rather than exceptions — matching the
|
|
514
|
+
* house rule of returning `Result` for expected failures and throwing only for
|
|
515
|
+
* invariants. `ok: true` means the key owns the certificate; a failure carries
|
|
516
|
+
* one of:
|
|
517
|
+
*
|
|
518
|
+
* - `malformed_certificate` — `certificate` could not be parsed.
|
|
519
|
+
* - `unsupported_private_key` — `privateKey` is not an extractable private key
|
|
520
|
+
* of a supported type (from {@linkcode derivePublicKey}).
|
|
521
|
+
* - `key_type_mismatch` — the key is a different algorithm than the
|
|
522
|
+
* certificate's subject public key.
|
|
523
|
+
* - `key_mismatch` — the key is the right algorithm but a different key.
|
|
524
|
+
*
|
|
525
|
+
* As with {@linkcode certificateMatchesPrivateKey}, the comparison is over exact
|
|
526
|
+
* SPKI DER, so a certificate pinning RSASSA-PSS parameters reports
|
|
527
|
+
* `key_type_mismatch` against the `rsaEncryption` SPKI WebCrypto emits.
|
|
528
|
+
*
|
|
529
|
+
* @param certificate PEM string, DER bytes, or an already-parsed certificate.
|
|
530
|
+
* @param privateKey An extractable private `CryptoKey`.
|
|
531
|
+
* @returns A success when the key matches, or a typed failure otherwise.
|
|
532
|
+
*
|
|
533
|
+
* @example
|
|
534
|
+
* ```ts
|
|
535
|
+
* const result = await matchCertificatePrivateKey(certificatePem, privateKey);
|
|
536
|
+
* if (!result.ok) {
|
|
537
|
+
* // result.code is 'malformed_certificate' | 'unsupported_private_key'
|
|
538
|
+
* // | 'key_type_mismatch' | 'key_mismatch'
|
|
539
|
+
* throw new Error(`key does not match certificate: ${result.code}`);
|
|
540
|
+
* }
|
|
541
|
+
* ```
|
|
542
|
+
*
|
|
543
|
+
* @see {@linkcode certificateMatchesPrivateKey} for the plain-boolean variant
|
|
544
|
+
*/
|
|
545
|
+
declare function matchCertificatePrivateKey<TMap extends ExtensionDecoderMap = Record<never, never>>(certificate: ParsedCertificate<TMap> | string | Uint8Array, privateKey: CryptoKey): Promise<MatchCertificatePrivateKeyResult>;
|
|
440
546
|
/**
|
|
441
547
|
* Find a raw extension by OID within a parsed extension list.
|
|
442
548
|
*
|
|
@@ -468,5 +574,5 @@ declare function decodeExtensions(extensions: readonly ParsedExtension[], decode
|
|
|
468
574
|
*/
|
|
469
575
|
declare function decodeExtensionMap<TMap extends ExtensionDecoderMap>(extensions: readonly ParsedExtension[], decoderMap: TMap): DecodedExtensionMap<TMap>;
|
|
470
576
|
//#endregion
|
|
471
|
-
export { DecodedExtensionMap, DecodedExtensionValue, ExtensionDecoder, ExtensionDecoderMap, ParseCertificateErrorCode, ParseCertificateFailure, ParseCertificateResult, ParseCertificateSigningRequestErrorCode, ParseCertificateSigningRequestFailure, ParseCertificateSigningRequestResult, ParseOptions, type ParsedBitFlags, ParsedCertificate, ParsedCertificateSigningRequest, ParsedDistributionPoint, ParsedDistributionPointName, ParsedExtension, ParsedIssuingDistributionPoint, ParsedName, ParsedNameAttribute, ParsedRelativeDistinguishedName, decodeExtension, decodeExtensionMap, decodeExtensions, defineExtensionDecoder, defineExtensionDecoderMap, findExtension, getSubjectPublicKey, getSubjectPublicKeyOrThrow, parseCertificateChainPem, parseCertificateDer, parseCertificateDerOrThrow, parseCertificatePem, parseCertificatePemOrThrow, parseCertificateSigningRequestDer, parseCertificateSigningRequestDerOrThrow, parseCertificateSigningRequestPem, parseCertificateSigningRequestPemOrThrow };
|
|
577
|
+
export { DecodedExtensionMap, DecodedExtensionValue, ExtensionDecoder, ExtensionDecoderMap, MatchCertificatePrivateKeyErrorCode, MatchCertificatePrivateKeyFailure, MatchCertificatePrivateKeyFailureResult, MatchCertificatePrivateKeyResult, MatchCertificatePrivateKeySuccess, ParseCertificateErrorCode, ParseCertificateFailure, ParseCertificateResult, ParseCertificateSigningRequestErrorCode, ParseCertificateSigningRequestFailure, ParseCertificateSigningRequestResult, ParseOptions, type ParsedBitFlags, ParsedCertificate, ParsedCertificateSigningRequest, ParsedDistributionPoint, ParsedDistributionPointName, ParsedExtension, ParsedIssuingDistributionPoint, ParsedName, ParsedNameAttribute, ParsedRelativeDistinguishedName, certificateMatchesPrivateKey, decodeExtension, decodeExtensionMap, decodeExtensions, defineExtensionDecoder, defineExtensionDecoderMap, findExtension, getSubjectPublicKey, getSubjectPublicKeyOrThrow, matchCertificatePrivateKey, parseCertificateChainPem, parseCertificateDer, parseCertificateDerOrThrow, parseCertificatePem, parseCertificatePemOrThrow, parseCertificateSigningRequestDer, parseCertificateSigningRequestDerOrThrow, parseCertificateSigningRequestPem, parseCertificateSigningRequestPemOrThrow };
|
|
472
578
|
//# sourceMappingURL=parse.d.ts.map
|