micro509 0.14.0 → 0.15.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 (161) hide show
  1. package/CHANGELOG.md +2064 -0
  2. package/README.md +105 -225
  3. package/dist/crypto/crypto.d.ts +42 -11
  4. package/dist/crypto/crypto.js +53 -22
  5. package/dist/crypto/crypto.js.map +1 -1
  6. package/dist/crypto.d.ts +2 -2
  7. package/dist/crypto.js +1 -2
  8. package/dist/der/der.d.ts +41 -33
  9. package/dist/der/der.js +26 -24
  10. package/dist/der/der.js.map +1 -1
  11. package/dist/index.d.ts +10 -10
  12. package/dist/index.js +19 -19
  13. package/dist/internal/asn1/asn1.d.ts +3 -6
  14. package/dist/internal/asn1/asn1.js +343 -43
  15. package/dist/internal/asn1/asn1.js.map +1 -1
  16. package/dist/internal/asn1/ber.js +146 -0
  17. package/dist/internal/asn1/ber.js.map +1 -0
  18. package/dist/internal/asn1/decode-refusal.js +29 -0
  19. package/dist/internal/asn1/decode-refusal.js.map +1 -0
  20. package/dist/internal/asn1/der.d.ts +38 -41
  21. package/dist/internal/asn1/der.js +131 -52
  22. package/dist/internal/asn1/der.js.map +1 -1
  23. package/dist/internal/asn1/oids.js +83 -53
  24. package/dist/internal/asn1/oids.js.map +1 -1
  25. package/dist/internal/asn1/oids2.js +1 -2
  26. package/dist/internal/asn1/oids2.js.map +1 -1
  27. package/dist/internal/crypto/algorithm-names.js +1 -2
  28. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  29. package/dist/internal/crypto/ecdsa.js +13 -8
  30. package/dist/internal/crypto/ecdsa.js.map +1 -1
  31. package/dist/internal/crypto/hash.js +1 -2
  32. package/dist/internal/crypto/hash.js.map +1 -1
  33. package/dist/internal/crypto/pbes2.d.ts +24 -11
  34. package/dist/internal/crypto/pbes2.js +79 -26
  35. package/dist/internal/crypto/pbes2.js.map +1 -1
  36. package/dist/internal/crypto/rsa-pss.js +46 -44
  37. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  38. package/dist/internal/crypto/sig-verify.d.ts +4 -7
  39. package/dist/internal/crypto/sig-verify.js +107 -60
  40. package/dist/internal/crypto/sig-verify.js.map +1 -1
  41. package/dist/internal/crypto/signing.d.ts +1 -4
  42. package/dist/internal/crypto/signing.js +28 -29
  43. package/dist/internal/crypto/signing.js.map +1 -1
  44. package/dist/internal/crypto/webcrypto.js +1 -2
  45. package/dist/internal/crypto/webcrypto.js.map +1 -1
  46. package/dist/internal/shared/base64.js +1 -2
  47. package/dist/internal/shared/base64.js.map +1 -1
  48. package/dist/internal/shared/dn.d.ts +3 -6
  49. package/dist/internal/shared/dn.js +99 -53
  50. package/dist/internal/shared/dn.js.map +1 -1
  51. package/dist/internal/shared/idna-tables.js +7217 -0
  52. package/dist/internal/shared/idna-tables.js.map +1 -0
  53. package/dist/internal/shared/idna.js +296 -0
  54. package/dist/internal/shared/idna.js.map +1 -0
  55. package/dist/internal/shared/ip.d.ts +4 -7
  56. package/dist/internal/shared/ip.js +1 -2
  57. package/dist/internal/shared/ip.js.map +1 -1
  58. package/dist/internal/shared/mailbox.js +26 -0
  59. package/dist/internal/shared/mailbox.js.map +1 -0
  60. package/dist/internal/shared/punycode.js +101 -0
  61. package/dist/internal/shared/punycode.js.map +1 -0
  62. package/dist/internal/shared/rfc3454-tables.js +1 -2
  63. package/dist/internal/shared/rfc3454-tables.js.map +1 -1
  64. package/dist/internal/shared/rfc4518-tables.js +119 -0
  65. package/dist/internal/shared/rfc4518-tables.js.map +1 -0
  66. package/dist/internal/shared/uri-host.js +102 -0
  67. package/dist/internal/shared/uri-host.js.map +1 -0
  68. package/dist/internal/verify/name-constraints-engine.js +246 -131
  69. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  70. package/dist/internal/verify/policy-engine.js +6 -21
  71. package/dist/internal/verify/policy-engine.js.map +1 -1
  72. package/dist/internal/verify/verify-path.d.ts +1 -4
  73. package/dist/internal/verify/verify-path.js +267 -131
  74. package/dist/internal/verify/verify-path.js.map +1 -1
  75. package/dist/internal/x509/directory-name.js +1 -2
  76. package/dist/internal/x509/directory-name.js.map +1 -1
  77. package/dist/internal/x509/extension-bits.js +2 -3
  78. package/dist/internal/x509/extension-bits.js.map +1 -1
  79. package/dist/internal/x509/extension-errors.d.ts +1 -4
  80. package/dist/internal/x509/extension-errors.js +1 -2
  81. package/dist/internal/x509/extension-errors.js.map +1 -1
  82. package/dist/internal/x509/extension-registry.js +107 -89
  83. package/dist/internal/x509/extension-registry.js.map +1 -1
  84. package/dist/internal/x509/general-name-profile.js +129 -0
  85. package/dist/internal/x509/general-name-profile.js.map +1 -0
  86. package/dist/internal/x509/general-name-tags.js +1 -2
  87. package/dist/internal/x509/general-name-tags.js.map +1 -1
  88. package/dist/internal/x509/general-name.js +128 -42
  89. package/dist/internal/x509/general-name.js.map +1 -1
  90. package/dist/internal/x509/name-fields.js +1 -2
  91. package/dist/internal/x509/name-fields.js.map +1 -1
  92. package/dist/internal/x509/or-address.js +217 -0
  93. package/dist/internal/x509/or-address.js.map +1 -0
  94. package/dist/keys/keys.d.ts +112 -97
  95. package/dist/keys/keys.js +211 -204
  96. package/dist/keys/keys.js.map +1 -1
  97. package/dist/keys.d.ts +3 -3
  98. package/dist/pem/pem.d.ts +14 -17
  99. package/dist/pem/pem.js +16 -17
  100. package/dist/pem/pem.js.map +1 -1
  101. package/dist/pem.js +1 -2
  102. package/dist/pkcs/pfx.d.ts +57 -32
  103. package/dist/pkcs/pfx.js +209 -173
  104. package/dist/pkcs/pfx.js.map +1 -1
  105. package/dist/pkcs/pkcs12-mac.d.ts +104 -27
  106. package/dist/pkcs/pkcs12-mac.js +266 -79
  107. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  108. package/dist/pkcs/pkcs7.d.ts +43 -37
  109. package/dist/pkcs/pkcs7.js +218 -217
  110. package/dist/pkcs/pkcs7.js.map +1 -1
  111. package/dist/pkcs.d.ts +4 -3
  112. package/dist/result/result.d.ts +27 -20
  113. package/dist/result/result.js +8 -3
  114. package/dist/result/result.js.map +1 -1
  115. package/dist/result.d.ts +2 -2
  116. package/dist/result.js +1 -2
  117. package/dist/revocation/chain.d.ts +101 -23
  118. package/dist/revocation/chain.js +436 -182
  119. package/dist/revocation/chain.js.map +1 -1
  120. package/dist/revocation/crl.d.ts +131 -67
  121. package/dist/revocation/crl.js +444 -323
  122. package/dist/revocation/crl.js.map +1 -1
  123. package/dist/revocation/ocsp.d.ts +94 -59
  124. package/dist/revocation/ocsp.js +331 -293
  125. package/dist/revocation/ocsp.js.map +1 -1
  126. package/dist/revocation/revocation.d.ts +47 -35
  127. package/dist/revocation/revocation.js +88 -57
  128. package/dist/revocation/revocation.js.map +1 -1
  129. package/dist/revocation.d.ts +3 -3
  130. package/dist/verify/identity.d.ts +16 -19
  131. package/dist/verify/identity.js +118 -89
  132. package/dist/verify/identity.js.map +1 -1
  133. package/dist/verify/name-constraints.d.ts +1 -4
  134. package/dist/verify/policy.d.ts +9 -7
  135. package/dist/verify/verify.d.ts +84 -46
  136. package/dist/verify/verify.js +300 -152
  137. package/dist/verify/verify.js.map +1 -1
  138. package/dist/verify.d.ts +2 -2
  139. package/dist/x509/certificate.d.ts +20 -21
  140. package/dist/x509/certificate.js +62 -46
  141. package/dist/x509/certificate.js.map +1 -1
  142. package/dist/x509/csr.d.ts +5 -7
  143. package/dist/x509/csr.js +10 -11
  144. package/dist/x509/csr.js.map +1 -1
  145. package/dist/x509/extensions.d.ts +154 -66
  146. package/dist/x509/extensions.js +317 -151
  147. package/dist/x509/extensions.js.map +1 -1
  148. package/dist/x509/fingerprint.d.ts +4 -7
  149. package/dist/x509/fingerprint.js +1 -2
  150. package/dist/x509/fingerprint.js.map +1 -1
  151. package/dist/x509/name-text.d.ts +7 -9
  152. package/dist/x509/name-text.js +18 -4
  153. package/dist/x509/name-text.js.map +1 -1
  154. package/dist/x509/name.d.ts +9 -11
  155. package/dist/x509/name.js +18 -19
  156. package/dist/x509/name.js.map +1 -1
  157. package/dist/x509/parse.d.ts +84 -69
  158. package/dist/x509/parse.js +421 -400
  159. package/dist/x509/parse.js.map +1 -1
  160. package/dist/x509.d.ts +2 -2
  161. package/package.json +76 -59
package/README.md CHANGED
@@ -1,7 +1,19 @@
1
1
  <picture>
2
- <source media="(prefers-color-scheme: dark)" srcset="https://github.com/kjanat/micro509/raw/e7e2007bfd7a18f6f247864b14ef60d54ed91dd6/site/assets/icon-light.svg">
3
- <source media="(prefers-color-scheme: light)" srcset="https://github.com/kjanat/micro509/raw/e7e2007bfd7a18f6f247864b14ef60d54ed91dd6/site/assets/icon.svg">
4
- <img alt="" src="https://github.com/kjanat/micro509/raw/e7e2007bfd7a18f6f247864b14ef60d54ed91dd6/site/assets/icon.svg" width="64" height="64" align="left">
2
+ <source
3
+ media="(prefers-color-scheme: dark)"
4
+ srcset="https://github.com/kjanat/micro509/raw/e7e2007bfd7a18f6f247864b14ef60d54ed91dd6/site/assets/icon-light.svg"
5
+ >
6
+ <source
7
+ media="(prefers-color-scheme: light)"
8
+ srcset="https://github.com/kjanat/micro509/raw/e7e2007bfd7a18f6f247864b14ef60d54ed91dd6/site/assets/icon.svg"
9
+ >
10
+ <img
11
+ alt=""
12
+ src="https://github.com/kjanat/micro509/raw/e7e2007bfd7a18f6f247864b14ef60d54ed91dd6/site/assets/icon.svg"
13
+ width="64"
14
+ height="64"
15
+ align="left"
16
+ >
5
17
  </picture>
6
18
 
7
19
  # micro509
@@ -10,9 +22,12 @@
10
22
  [![JSR](https://img.shields.io/jsr/v/@kjanat/micro509?logoColor=083344&logo=jsr&logoSize=auto&label=&labelColor=f7df1e&color=black)][jsr]
11
23
  [![Socket](https://badge.socket.dev/npm/package/micro509)][socket]
12
24
 
13
- A zero-dependency TypeScript PKI toolkit for certificates, verification, revocation, and PKCS workflows.
25
+ A zero-dependency TypeScript X.509 and PKI toolkit. Create certificates and
26
+ CSRs, verify certificate chains and identities, manage revocation, and work
27
+ with keys and PKCS containers using WebCrypto.
14
28
 
15
- Zero dependencies. Tree-shakeable subpath entrypoints. Pure WebCrypto. Runs everywhere: Node, Bun, Deno, browsers, Cloudflare Workers.
29
+ Zero dependencies. Tree-shakeable subpath entrypoints. Pure WebCrypto. Runs in
30
+ Node, Bun, Deno, browsers, and Cloudflare Workers.
16
31
 
17
32
  > **Prerelease** — API may change before 1.0.
18
33
 
@@ -22,256 +37,122 @@ Zero dependencies. Tree-shakeable subpath entrypoints. Pure WebCrypto. Runs ever
22
37
  npm install micro509
23
38
  ```
24
39
 
25
- In a browser, no build step — it is WebCrypto and nothing else:
26
-
27
- ```html
28
- <script type="module">
29
- import { createSelfSignedCertificate } from 'https://esm.run/micro509';
30
- </script>
31
- ```
32
-
33
- Two runnable examples:
34
-
35
- - [`examples/browser`][browser-example] is that, in full: one HTML file that
36
- issues a certificate and parses it back, with nothing installed and nothing
37
- built. [open in stackblitz][browser-example:stackblitz]
38
- - [`examples/vite`][vite-example]: the same demo with types and a dev server.
39
- [open in stackblitz][vite-example:stackblitz]
40
-
41
- ## Why micro509
42
-
43
- JavaScript PKI libraries usually force a bad tradeoff:
44
- heavyweight standards toolkits, legacy crypto kitchen sinks,
45
- or narrow parsing utilities.
46
-
47
- micro509 is the practical middle: a modern, WebCrypto-native
48
- PKI toolkit with zero runtime dependencies and typed APIs for
49
- the workflows most applications actually need.
50
-
51
- It gives you one library for certificate and CSR creation,
52
- chain verification, service-identity matching, CRLs, OCSP,
53
- PKCS#7 SignedData, PFX/PKCS#12, PEM handling, and key
54
- import/export.
40
+ ## Quick start
55
41
 
56
- And when verification fails, you get typed results your code
57
- can act on: [a typed error code for every failure mode], the failing
58
- certificate index, and structured failure details instead of `false`.
42
+ Create a self-signed certificate, verify its chain and service identity, then
43
+ see a typed failure when the requested identity does not match:
59
44
 
60
45
  ```ts
61
- import { createSelfSignedCertificate, unwrap, verifyCertificateChain } from 'micro509';
46
+ import { createSelfSignedCertificate, verifyCertificateChain } from 'micro509';
62
47
 
63
48
  const { certificate } = await createSelfSignedCertificate({
64
- subject: { commonName: 'app.example.com' },
65
- extensions: {
66
- subjectAltNames: [{ type: 'dns', value: 'app.example.com' }],
67
- },
49
+ subject: { commonName: 'app.example.com' },
50
+ extensions: {
51
+ subjectAltNames: [{ type: 'dns', value: 'app.example.com' }],
52
+ },
68
53
  });
69
54
 
70
- const result = await verifyCertificateChain({
71
- leaf: certificate.pem,
72
- roots: [certificate.pem],
73
- allowSelfSignedLeaf: true,
74
- serviceIdentity: { type: 'dns', value: 'evil.example.com' },
75
- });
76
-
77
- if (!result.ok) {
78
- switch (result.error.code) {
79
- case 'certificate_expired':
80
- console.log('renew the certificate at index', result.error.index);
81
- break;
82
- case 'subject_alt_name_mismatch': {
83
- const { expected, actual } = result.error.details ?? {};
84
- console.log(`identity mismatch: wanted ${expected}, presented ${actual}`);
85
- break;
86
- }
87
- default:
88
- unwrap(result); // rethrows the typed error
89
- }
90
- }
91
- ```
92
-
93
- Beyond verification, micro509 covers PKI surface that's hard to find
94
- in a single zero-dependency JS package:
55
+ const options = {
56
+ leaf: certificate.pem,
57
+ roots: [certificate.pem],
58
+ allowSelfSignedLeaf: true,
59
+ } as const;
95
60
 
96
- - **OCSP** — build requests, parse and validate responses, verify responder authorization
97
- - **PFX / PKCS#12** — create and parse password-protected key+cert bundles
98
- - **PKCS#7 / CMS** — sign content, parse and verify SignedData with each signer's certificate resolved, extract cert bags
99
- - **CRLs** — create, parse, verify, and check revocation status
100
- - **Encrypted keys** — PBES2 PKCS#8, legacy OpenSSL encrypted PEM, PKCS#1, SEC1, parameter inspection without the password
101
- - **Key import/export** — PKCS#8, SPKI, JWK, PKCS#1, SEC1 with generation for RSA, ECDSA, Ed25519
102
- - **Detached signatures** — sign and verify raw bytes, ECDSA DER/raw signature conversion
103
- - **Service identity** — wildcard DNS, IPv6 normalization, URI-ID, SRV-ID, explicit CN opt-in
104
-
105
- Narrow defaults, explicit escape hatches — dangerous operations like CN
106
- fallback or self-signed leaf acceptance require opt-in. All with no `any`,
107
- no type assertions, no non-null assertions, and no runtime DI frameworks
108
- that break edge runtimes.
109
-
110
- ## Quick start
111
-
112
- Create a self-signed certificate:
113
-
114
- ```ts
115
- import { createSelfSignedCertificate } from 'micro509';
116
-
117
- const { certificate, keyPair } = await createSelfSignedCertificate({
118
- subject: {
119
- commonName: 'example.com',
120
- organization: 'Acme',
121
- country: 'US',
122
- },
123
- validity: { days: 30 },
124
- extensions: {
125
- keyUsage: ['digitalSignature', 'keyEncipherment'],
126
- subjectAltNames: [
127
- { type: 'dns', value: 'example.com' },
128
- { type: 'dns', value: 'www.example.com' },
129
- ],
130
- },
61
+ const valid = await verifyCertificateChain({
62
+ ...options,
63
+ serviceIdentity: { type: 'dns', value: 'app.example.com' },
131
64
  });
65
+ console.log(valid.ok ? 'verified app.example.com' : valid.error.code);
132
66
 
133
- console.log(certificate.pem);
134
- console.log(await keyPair.exportPkcs8Pem());
135
- ```
136
-
137
- Create a CSR:
138
-
139
- ```ts
140
- import { createCertificateSigningRequest, generateKeyPair } from 'micro509';
141
-
142
- const keyPair = await generateKeyPair({ kind: 'ed25519' });
143
- const csr = await createCertificateSigningRequest({
144
- subject: { commonName: 'csr.example' },
145
- publicKey: keyPair.publicKey,
146
- signerPrivateKey: keyPair.privateKey,
147
- extensions: {
148
- subjectAltNames: [{ type: 'dns', value: 'csr.example' }],
149
- },
67
+ const mismatch = await verifyCertificateChain({
68
+ ...options,
69
+ serviceIdentity: { type: 'dns', value: 'admin.example.com' },
150
70
  });
151
-
152
- console.log(csr.pem);
71
+ console.log(mismatch.ok ? 'verified' : mismatch.error.code);
153
72
  ```
154
73
 
155
- Parse a certificate:
156
-
157
- ```ts
158
- import { createSelfSignedCertificate, parseCertificatePem, unwrap } from 'micro509';
159
-
160
- const { certificate } = await createSelfSignedCertificate({
161
- subject: { commonName: 'example.com' },
162
- extensions: { extendedKeyUsage: ['serverAuth'] },
163
- });
74
+ Output:
164
75
 
165
- const parsed = unwrap(parseCertificatePem(certificate.pem));
166
- console.log(parsed.subject.values.commonName);
167
- console.log(parsed.serialNumberHex);
168
- console.log(parsed.extendedKeyUsage);
76
+ ```text
77
+ verified app.example.com
78
+ subject_alt_name_mismatch
169
79
  ```
170
80
 
171
- `parseCertificatePem` returns a typed `Result` — check `result.ok`, or
172
- `unwrap()` to throw on malformed input.
81
+ A verification failure is a typed result with an error code, failing
82
+ certificate index when relevant, and structured details. Callers can handle a
83
+ specific case without parsing messages or collapsing every failure into
84
+ `false`.
173
85
 
174
- Verify a chain:
86
+ The self-signed leaf option above is useful for a compact local demo. In
87
+ production, supply the appropriate trust anchors and intermediates for your
88
+ PKI.
175
89
 
176
- ```ts
177
- import { createSelfSignedCertificate, verifyCertificateChain } from 'micro509';
90
+ ## What it covers
178
91
 
179
- const { certificate } = await createSelfSignedCertificate({
180
- subject: { commonName: 'example.com' },
181
- extensions: {
182
- extendedKeyUsage: ['serverAuth'],
183
- subjectAltNames: [{ type: 'dns', value: 'example.com' }],
184
- },
185
- });
92
+ - **Certificates and CSRs:** create, parse, and encode common X.509 extensions
93
+ - **Verification:** build and validate chains, enforce policy, and match DNS,
94
+ IP, URI, and SRV service identities
95
+ - **Revocation:** create and process CRLs and OCSP requests and responses
96
+ - **Keys and signatures:** import, export, and generate RSA, ECDSA, and
97
+ Ed25519 keys, plus signing and verification of detached data
98
+ - **PKCS workflows:** PKCS#7 SignedData and password-protected PFX/PKCS#12
99
+ - **PEM and DER:** encode, decode, and parse common formats
186
100
 
187
- // Self-signed leaf as its own root: development shape, explicit opt-in
188
- const result = await verifyCertificateChain({
189
- leaf: certificate.pem,
190
- roots: [certificate.pem],
191
- purpose: 'serverAuth',
192
- serviceIdentity: { type: 'dns', value: 'example.com' },
193
- allowSelfSignedLeaf: true,
194
- });
101
+ The root package exports the usual workflows:
195
102
 
196
- if (result.ok) {
197
- console.log(result.value.chain.length, result.value.leaf.serialNumberHex);
198
- } else {
199
- console.log(result.error.code);
200
- }
103
+ ```ts
104
+ import { createCertificate, parseCertificatePem, verifyCertificateChain } from 'micro509';
201
105
  ```
202
106
 
203
- ## Runtime support
204
-
205
- | Runtime | Status | Notes |
206
- | ------- | --------- | -------------------------------------------------- |
207
- | Node | supported | modern Node with WebCrypto globals (tested on 24+) |
208
- | Bun | supported | Bun 1.3+ |
209
- | Deno | supported | requires WebCrypto and web text/base64 globals |
210
- | Browser | supported | modern browsers only |
211
- | Worker | supported | same WebCrypto and text/base64 globals required |
212
-
213
- The core stays ESM-only and side-effect-free.
214
-
215
- ## Algorithm support
216
-
217
- | Area | Shipped support |
218
- | ------------------------------ | -------------------------------------------------------------------- |
219
- | Certificate and CSR signatures | RSA PKCS#1 v1.5, RSA-PSS, ECDSA `P-256` / `P-384` / `P-521`, Ed25519 |
220
- | RSA key APIs | `scheme: 'pkcs1-v1_5'`, `'pss'`, `'oaep'` (encryption) |
221
- | ECDSA key APIs | `P-256`, `P-384`, `P-521` |
222
- | Encrypted PKCS#8 and PFX | PBES2 with AES-CBC plus PBKDF2 HMAC-SHA1/HMAC-SHA256 |
223
- | Encrypted traditional PEM | AES-128-CBC, AES-192-CBC, AES-256-CBC for RSA and EC private keys |
107
+ For smaller imports or more specialized types, use domain entrypoints:
224
108
 
225
- `micro509` focuses on algorithms that are broadly interoperable in modern X.509 and WebCrypto-backed runtimes.\
226
- It intentionally excludes niche, blockchain-specific, or key-agreement-only primitives from the core API unless they are needed for a PKI workflow the library explicitly supports.
109
+ ```ts
110
+ import { parseCertificatePem } from 'micro509/x509';
111
+ import { verifyCertificateChain } from 'micro509/verify';
112
+ import { checkCertificateRevocation } from 'micro509/revocation';
113
+ import { createPfx } from 'micro509/pkcs';
114
+ import { generateKeyPair } from 'micro509/keys';
115
+ ```
227
116
 
228
- ## Standards status
117
+ See the [API reference](https://micro509.kjanat.dev/api/) for the full entrypoint list.
229
118
 
230
- | Area | Status |
231
- | ------------------------------------- | -------- |
232
- | RFC 5280 path validation | complete |
233
- | RFC 6960 + 9919 OCSP | complete |
234
- | RFC 9525 service identity | complete |
235
- | RFC 9618 policy validation | complete |
236
- | RFC 7468 PEM textual encodings | complete |
237
- | RFC 8410 + 9295 safe-curve profiles | complete |
238
- | PKCS containers: RFC 5652, 7292, 8018 | partial |
119
+ ## Standards and algorithms
239
120
 
240
- See [`docs/PKIX-SCOPE.md`](./docs/PKIX-SCOPE.md) for the detailed scope boundary
241
- and the [API reference](https://micro509.kjanat.dev/api/) for the public module surface.
121
+ micro509 implements core certificate path validation, service identity,
122
+ policy, PEM, safe-curve, OCSP, and PKCS container workflows. The exact claim
123
+ boundary and partial areas are documented in the [PKIX scope](./docs/PKIX-SCOPE.md).
124
+ See [algorithms](https://micro509.kjanat.dev/reference/algorithms) for supported
125
+ curves and signature schemes, [runtimes](https://micro509.kjanat.dev/reference/runtimes)
126
+ for environment support, and [standards](https://micro509.kjanat.dev/reference/standards)
127
+ for implementation coverage.
242
128
 
243
- ## Imports
129
+ ## Try it in a browser
244
130
 
245
- Use the root package for most applications:
131
+ The browser example is a single HTML file that issues a certificate and parses
132
+ it back with no build step. The Vite example adds TypeScript and a dev server.
246
133
 
247
- ```ts
248
- import { createCertificate, parseCertificatePem, verifyCertificateChain } from 'micro509';
249
- ```
134
+ - [Browser example][browser-example], [open in StackBlitz][browser-example:stackblitz]
135
+ - [Vite example][vite-example], [open in StackBlitz][vite-example:stackblitz]
250
136
 
251
- Use domain entrypoints when you want exhaustive advanced types or a narrower
252
- workflow surface:
137
+ ## Documentation
253
138
 
254
- ```ts
255
- import { parseCertificatePem } from 'micro509/x509';
256
- import { verifyCertificateChain, matchServiceIdentity } from 'micro509/verify';
257
- import { createOcspRequest, checkCertificateRevocation } from 'micro509/revocation';
258
- import { createPfx } from 'micro509/pkcs';
259
- import { signData, verifySignature } from 'micro509/crypto';
260
- import { generateKeyPair } from 'micro509/keys';
261
- import { pemDecode, pemEncode } from 'micro509/pem';
262
- import { readDerRoot, decodeDerOid } from 'micro509/der';
263
- import type { Micro509Error } from 'micro509/result';
264
- ```
139
+ - [Recipes: server verification, CSR issuance, PFX import](https://micro509.kjanat.dev/guide/recipes)
140
+ - [Migration from 0.14.0](https://micro509.kjanat.dev/guide/migration)
265
141
 
266
- The full stable subpath list lives in the [API reference](https://micro509.kjanat.dev/api/).
142
+ - [Getting started](https://micro509.kjanat.dev/guide/getting-started)
143
+ - [Certificates and extensions](https://micro509.kjanat.dev/guide/certificates)
144
+ - [Verification and trust inputs](https://micro509.kjanat.dev/guide/verification)
145
+ - [CRL and OCSP revocation](https://micro509.kjanat.dev/guide/revocation)
146
+ - [Keys and encrypted formats](https://micro509.kjanat.dev/guide/keys)
147
+ - [PKCS#7 and PKCS#12](https://micro509.kjanat.dev/guide/pkcs)
148
+ - [Error reference](https://micro509.kjanat.dev/reference/errors)
149
+ - [API reference](https://micro509.kjanat.dev/api/)
150
+ - [Contributing](./CONTRIBUTING.md)
267
151
 
268
- ## More docs
152
+ ## OpenSSL builds
269
153
 
270
- - API reference: [micro509.kjanat.dev/api](https://micro509.kjanat.dev/api/)
271
- - Standards scope: [`docs/PKIX-SCOPE.md`](./docs/PKIX-SCOPE.md)
272
- - PKITS harness: [`test/pkits.test.ts`](./test/pkits.test.ts)
273
- - Differential harness: [`test/differential.test.ts`](./test/differential.test.ts)
274
- - Contributing: [`CONTRIBUTING.md`](./CONTRIBUTING.md)
154
+ This repository also publishes statically linked OpenSSL builds to GHCR for
155
+ micro509 CI and general use. See [build details](./.github/openssl/README.md).
275
156
 
276
157
  ## License
277
158
 
@@ -280,8 +161,7 @@ The full stable subpath list lives in the [API reference](https://micro509.kjana
280
161
  [npm]: https://npm.im/micro509
281
162
  [jsr]: https://jsr.io/@kjanat/micro509
282
163
  [socket]: https://socket.dev/npm/package/micro509
283
- [browser-example]: ./examples/browser/README.md 'GitHub'
284
- [browser-example:stackblitz]: https://stackblitz.com/github/kjanat/micro509/tree/master/examples/browser?title=micro509%20in%20the%20browser 'Stackblitz'
285
- [vite-example]: ./examples/vite/README.md 'GitHub'
286
- [vite-example:stackblitz]: https://stackblitz.com/github/kjanat/micro509/tree/master/examples/vite?title=micro509%20with%20Vite 'Stackblitz'
287
- [a typed error code for every failure mode]: https://micro509.kjanat.dev/guide/verification#error-codes
164
+ [browser-example]: ./examples/browser/README.md "GitHub"
165
+ [browser-example:stackblitz]: https://stackblitz.com/github/kjanat/micro509/tree/master/examples/browser?title=micro509%20in%20the%20browser "StackBlitz"
166
+ [vite-example]: ./examples/vite/README.md "GitHub"
167
+ [vite-example:stackblitz]: https://stackblitz.com/github/kjanat/micro509/tree/master/examples/vite?title=micro509%20with%20Vite "StackBlitz"
@@ -1,9 +1,19 @@
1
1
  import { EcNamedCurve } from "../keys/keys.js";
2
2
  import { VerifySignatureConfigFailure, VerifySignedDataFailure, VerifySignedDataResult, VerifySignedDataSuccess } from "../internal/crypto/sig-verify.js";
3
3
  import { SignatureProfileInput } from "../internal/crypto/signing.js";
4
- //#region src/crypto/crypto.d.ts
4
+ /** Failure: the signature algorithm parameters exceed a micro509 decoding limit. */
5
+ export interface VerifySignatureLimitFailure {
6
+ /** Discriminant for the failure branch. */
7
+ readonly ok: false;
8
+ /** Machine-readable failure code. */
9
+ readonly code: "limit_exceeded";
10
+ /** Human-readable description of the limit. */
11
+ readonly reason: string;
12
+ }
13
+ /** Result of {@linkcode verifySignature} and {@linkcode verifySignatureWithKey}. */
14
+ export type VerifySignatureResult = VerifySignedDataResult | VerifySignatureLimitFailure;
5
15
  /** Input for {@linkcode verifySignature}. */
6
- interface VerifySignatureInput {
16
+ export interface VerifySignatureInput {
7
17
  /** DER `SubjectPublicKeyInfo` of the signer (`subjectPublicKeyInfoDer` on a parsed certificate). */
8
18
  readonly signerSpkiDer: Uint8Array;
9
19
  /** The signature algorithm as carried beside the signature. */
@@ -25,8 +35,30 @@ interface VerifySignatureInput {
25
35
  /** The exact bytes the signature covers. */
26
36
  readonly data: Uint8Array;
27
37
  }
38
+ /** Input for {@linkcode verifySignatureWithKey}. */
39
+ export interface VerifySignatureWithKeyInput {
40
+ /** An existing public key with verify usage; extractability is not required. */
41
+ readonly publicKey: CryptoKey;
42
+ /** Explicit signature OID and parameters, including RSA-PSS salt length. */
43
+ readonly signatureAlgorithm: VerifySignatureInput["signatureAlgorithm"];
44
+ /** ECDSA accepts raw r || s or DER; RSA and Ed25519 require raw. No encoding retry occurs. */
45
+ readonly signatureEncoding: "raw" | "der";
46
+ /** The signature bytes in the declared encoding. */
47
+ readonly signature: Uint8Array;
48
+ /** The exact bytes the signature covers. */
49
+ readonly data: Uint8Array;
50
+ }
51
+ /**
52
+ * Verifies a detached signature using an existing WebCrypto public key without
53
+ * exporting or importing it. Repeated calls may reuse non-extractable keys.
54
+ * Signature algorithms and parameters follow {@linkcode verifySignature}; RSA
55
+ * scheme and hash must match the key. ECDSA encoding is explicit and never retried.
56
+ * Returns the same validity, unsupported-parameter, operational-error and decoding-limit
57
+ * branches as {@linkcode verifySignature}.
58
+ */
59
+ export declare function verifySignatureWithKey(input: VerifySignatureWithKeyInput): Promise<VerifySignatureResult>;
28
60
  /** Result of {@linkcode signData}: the signature plus its on-wire algorithm identity. */
29
- interface SignDataResult {
61
+ export interface SignDataResult {
30
62
  /** The signature bytes. ECDSA is DER `ECDSA-Sig-Value`, everything else raw. */
31
63
  readonly signature: Uint8Array;
32
64
  /** Dotted-decimal signature algorithm OID. */
@@ -42,10 +74,10 @@ interface SignDataResult {
42
74
  * verify under one encoding, the alternate DER/raw encoding is retried.
43
75
  *
44
76
  * Returns a typed union: `{ ok: true, valid }` when verification ran,
45
- * `unsupported_signature_algorithm_parameters` or `verification_error`
46
- * failures otherwise.
77
+ * `unsupported_signature_algorithm_parameters`, `verification_error` or
78
+ * `limit_exceeded` failures otherwise.
47
79
  */
48
- declare function verifySignature(input: VerifySignatureInput): Promise<VerifySignedDataResult>;
80
+ export declare function verifySignature(input: VerifySignatureInput): Promise<VerifySignatureResult>;
49
81
  /**
50
82
  * Signs `data` with a WebCrypto private key and returns the signature beside
51
83
  * the resolved `AlgorithmIdentifier` material for embedding in a signed
@@ -55,19 +87,18 @@ declare function verifySignature(input: VerifySignatureInput): Promise<VerifySig
55
87
  * RSA-PSS keys require an explicit `{ kind: 'rsa-pss' }` profile. ECDSA
56
88
  * signatures are returned DER-encoded. Throws on unsupported key algorithms.
57
89
  */
58
- declare function signData(privateKey: CryptoKey, data: Uint8Array, profile?: SignatureProfileInput): Promise<SignDataResult>;
90
+ export declare function signData(privateKey: CryptoKey, data: Uint8Array, profile?: SignatureProfileInput): Promise<SignDataResult>;
59
91
  /**
60
92
  * Converts a DER `ECDSA-Sig-Value` (RFC 5480: SEQUENCE of INTEGERs r and s)
61
93
  * to the fixed-width raw `r || s` encoding WebCrypto and JOSE use.
62
94
  * Throws on malformed DER or integers too large for the curve.
63
95
  */
64
- declare function ecdsaSignatureDerToRaw(signature: Uint8Array, curve: EcNamedCurve): Uint8Array;
96
+ export declare function ecdsaSignatureDerToRaw(signature: Uint8Array, curve: EcNamedCurve): Uint8Array;
65
97
  /**
66
98
  * Converts a fixed-width raw `r || s` ECDSA signature to the DER
67
99
  * `ECDSA-Sig-Value` encoding X.509 and CMS structures embed.
68
100
  * Throws when the input length does not match the curve.
69
101
  */
70
- declare function ecdsaSignatureRawToDer(signature: Uint8Array, curve: EcNamedCurve): Uint8Array;
71
- //#endregion
72
- export { SignDataResult, type SignatureProfileInput, type VerifySignatureConfigFailure, VerifySignatureInput, type VerifySignedDataFailure, type VerifySignedDataResult, type VerifySignedDataSuccess, ecdsaSignatureDerToRaw, ecdsaSignatureRawToDer, signData, verifySignature };
102
+ export declare function ecdsaSignatureRawToDer(signature: Uint8Array, curve: EcNamedCurve): Uint8Array;
103
+ export type { SignatureProfileInput, VerifySignatureConfigFailure, VerifySignedDataFailure, VerifySignedDataResult, VerifySignedDataSuccess };
73
104
  //# sourceMappingURL=crypto.d.ts.map
@@ -1,15 +1,37 @@
1
- import { derEcdsaSignatureToRaw as e, rawEcdsaSignatureToDer as t } from "../internal/crypto/ecdsa.js";
2
- import { verifySignedDataDetailed as n } from "../internal/crypto/sig-verify.js";
3
- import { getSignatureAlgorithm as r, signBytes as i } from "../internal/crypto/signing.js";
4
- //#region src/crypto/crypto.ts
1
+ import { DECODE_LIMIT_CODES as e, decodeRefusalOf as t } from "../internal/asn1/decode-refusal.js";
2
+ import { derEcdsaSignatureToRaw as n, rawEcdsaSignatureToDer as r } from "../internal/crypto/ecdsa.js";
3
+ import { verifySignedDataDetailed as i, verifySignedDataWithKeyDetailed as a } from "../internal/crypto/sig-verify.js";
4
+ import { getSignatureAlgorithm as o, signBytes as s } from "../internal/crypto/signing.js";
5
+ // src/crypto/crypto.ts
5
6
  /**
6
- * Detached-signature primitives: verify a signature against a signer's SPKI,
7
+ * Detached-signature primitives: verify a signature against a signer's SPKI or CryptoKey,
7
8
  * sign arbitrary bytes with a WebCrypto private key, and convert ECDSA
8
9
  * signatures between DER `ECDSA-Sig-Value` and fixed-width raw encodings.
9
10
  *
10
11
  * @module
11
12
  */
12
13
  /**
14
+ * Verifies a detached signature using an existing WebCrypto public key without
15
+ * exporting or importing it. Repeated calls may reuse non-extractable keys.
16
+ * Signature algorithms and parameters follow {@linkcode verifySignature}; RSA
17
+ * scheme and hash must match the key. ECDSA encoding is explicit and never retried.
18
+ * Returns the same validity, unsupported-parameter, operational-error and decoding-limit
19
+ * branches as {@linkcode verifySignature}.
20
+ */
21
+ async function verifySignatureWithKey(n) {
22
+ try {
23
+ return await a(n.publicKey, n.signatureAlgorithm.oid, n.signatureAlgorithm.parametersDer, n.signature, n.data, n.signatureEncoding);
24
+ } catch (n) {
25
+ let r = t(n, e);
26
+ if (r === void 0) throw n;
27
+ return {
28
+ ok: !1,
29
+ code: r.code,
30
+ reason: r.message
31
+ };
32
+ }
33
+ }
34
+ /**
13
35
  * Verifies a detached signature against the signer's DER `SubjectPublicKeyInfo`.
14
36
  *
15
37
  * Supports RSA PKCS#1 v1.5 (SHA-256/384/512), RSA-PSS with parsed parameters,
@@ -17,11 +39,21 @@ import { getSignatureAlgorithm as r, signBytes as i } from "../internal/crypto/s
17
39
  * verify under one encoding, the alternate DER/raw encoding is retried.
18
40
  *
19
41
  * Returns a typed union: `{ ok: true, valid }` when verification ran,
20
- * `unsupported_signature_algorithm_parameters` or `verification_error`
21
- * failures otherwise.
42
+ * `unsupported_signature_algorithm_parameters`, `verification_error` or
43
+ * `limit_exceeded` failures otherwise.
22
44
  */
23
- function verifySignature(e) {
24
- return n(e.signatureAlgorithm.oid, e.signatureAlgorithm.parametersDer, e.publicKeyAlgorithm.oid, e.publicKeyAlgorithm.parametersOid, e.signerSpkiDer, e.signature, e.data);
45
+ async function verifySignature(n) {
46
+ try {
47
+ return await i(n.signatureAlgorithm.oid, n.signatureAlgorithm.parametersDer, n.publicKeyAlgorithm.oid, n.publicKeyAlgorithm.parametersOid, n.signerSpkiDer, n.signature, n.data);
48
+ } catch (n) {
49
+ let r = t(n, e);
50
+ if (r === void 0) throw n;
51
+ return {
52
+ ok: !1,
53
+ code: r.code,
54
+ reason: r.message
55
+ };
56
+ }
25
57
  }
26
58
  /**
27
59
  * Signs `data` with a WebCrypto private key and returns the signature beside
@@ -33,14 +65,14 @@ function verifySignature(e) {
33
65
  * signatures are returned DER-encoded. Throws on unsupported key algorithms.
34
66
  */
35
67
  async function signData(e, t, n) {
36
- let a = r(e, n), o = await i(e, a, t);
37
- return a.parameters === void 0 ? {
38
- signature: o,
39
- algorithmOid: a.algorithmOid
68
+ let r = o(e, n), i = await s(e, r, t);
69
+ return r.parameters === void 0 ? {
70
+ signature: i,
71
+ algorithmOid: r.algorithmOid
40
72
  } : {
41
- signature: o,
42
- algorithmOid: a.algorithmOid,
43
- parametersDer: a.parameters
73
+ signature: i,
74
+ algorithmOid: r.algorithmOid,
75
+ parametersDer: r.parameters
44
76
  };
45
77
  }
46
78
  /**
@@ -48,16 +80,16 @@ async function signData(e, t, n) {
48
80
  * to the fixed-width raw `r || s` encoding WebCrypto and JOSE use.
49
81
  * Throws on malformed DER or integers too large for the curve.
50
82
  */
51
- function ecdsaSignatureDerToRaw(t, n) {
52
- return e(t, ecdsaPartLength(n));
83
+ function ecdsaSignatureDerToRaw(e, t) {
84
+ return n(e, ecdsaPartLength(t));
53
85
  }
54
86
  /**
55
87
  * Converts a fixed-width raw `r || s` ECDSA signature to the DER
56
88
  * `ECDSA-Sig-Value` encoding X.509 and CMS structures embed.
57
89
  * Throws when the input length does not match the curve.
58
90
  */
59
- function ecdsaSignatureRawToDer(e, n) {
60
- return t(e, ecdsaPartLength(n));
91
+ function ecdsaSignatureRawToDer(e, t) {
92
+ return r(e, ecdsaPartLength(t));
61
93
  }
62
94
  /** Byte width of one ECDSA signature integer for the given curve. */
63
95
  function ecdsaPartLength(e) {
@@ -68,7 +100,6 @@ function ecdsaPartLength(e) {
68
100
  default: throw Error(`Unhandled EcNamedCurve: ${String(e)}`);
69
101
  }
70
102
  }
71
- //#endregion
72
- export { ecdsaSignatureDerToRaw, ecdsaSignatureRawToDer, signData, verifySignature };
103
+ export { ecdsaSignatureDerToRaw, ecdsaSignatureRawToDer, signData, verifySignature, verifySignatureWithKey };
73
104
 
74
105
  //# sourceMappingURL=crypto.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"crypto.js","names":["_exhaustive"],"sources":["../../src/crypto/crypto.ts"],"sourcesContent":["/**\n * Detached-signature primitives: verify a signature against a signer's SPKI,\n * sign arbitrary bytes with a WebCrypto private key, and convert ECDSA\n * signatures between DER `ECDSA-Sig-Value` and fixed-width raw encodings.\n *\n * @module\n */\n\nimport { derEcdsaSignatureToRaw, rawEcdsaSignatureToDer } from '#micro509/internal/crypto/ecdsa';\nimport type { VerifySignedDataResult } from '#micro509/internal/crypto/sig-verify';\nimport { verifySignedDataDetailed } from '#micro509/internal/crypto/sig-verify';\nimport type { SignatureProfileInput } from '#micro509/internal/crypto/signing';\nimport { getSignatureAlgorithm, signBytes } from '#micro509/internal/crypto/signing';\nimport type { EcNamedCurve } from '#micro509/keys/keys';\n\nexport type {\n\tVerifySignatureConfigFailure,\n\tVerifySignedDataFailure,\n\tVerifySignedDataResult,\n\tVerifySignedDataSuccess,\n} from '#micro509/internal/crypto/sig-verify';\nexport type { SignatureProfileInput } from '#micro509/internal/crypto/signing';\n\n/** Input for {@linkcode verifySignature}. */\nexport interface VerifySignatureInput {\n\t/** DER `SubjectPublicKeyInfo` of the signer (`subjectPublicKeyInfoDer` on a parsed certificate). */\n\treadonly signerSpkiDer: Uint8Array;\n\t/** The signature algorithm as carried beside the signature. */\n\treadonly signatureAlgorithm: {\n\t\t/** Dotted-decimal signature algorithm OID. */\n\t\treadonly oid: string;\n\t\t/** DER algorithm parameters when the algorithm carries them (RSA-PSS). */\n\t\treadonly parametersDer?: Uint8Array;\n\t};\n\t/** The signer's public key algorithm as carried in its SPKI. */\n\treadonly publicKeyAlgorithm: {\n\t\t/** Dotted-decimal public key algorithm OID. */\n\t\treadonly oid: string;\n\t\t/** Named-curve or scheme parameters OID, when present. */\n\t\treadonly parametersOid?: string;\n\t};\n\t/** The signature bytes. ECDSA accepts DER or raw encoding. */\n\treadonly signature: Uint8Array;\n\t/** The exact bytes the signature covers. */\n\treadonly data: Uint8Array;\n}\n\n/** Result of {@linkcode signData}: the signature plus its on-wire algorithm identity. */\nexport interface SignDataResult {\n\t/** The signature bytes. ECDSA is DER `ECDSA-Sig-Value`, everything else raw. */\n\treadonly signature: Uint8Array;\n\t/** Dotted-decimal signature algorithm OID. */\n\treadonly algorithmOid: string;\n\t/** DER algorithm parameters when the algorithm carries them (NULL for PKCS#1 v1.5, RSA-PSS params). */\n\treadonly parametersDer?: Uint8Array;\n}\n\n/**\n * Verifies a detached signature against the signer's DER `SubjectPublicKeyInfo`.\n *\n * Supports RSA PKCS#1 v1.5 (SHA-256/384/512), RSA-PSS with parsed parameters,\n * ECDSA P-256/P-384/P-521, and Ed25519. When an ECDSA signature fails to\n * verify under one encoding, the alternate DER/raw encoding is retried.\n *\n * Returns a typed union: `{ ok: true, valid }` when verification ran,\n * `unsupported_signature_algorithm_parameters` or `verification_error`\n * failures otherwise.\n */\nexport function verifySignature(input: VerifySignatureInput): Promise<VerifySignedDataResult> {\n\treturn verifySignedDataDetailed(\n\t\tinput.signatureAlgorithm.oid,\n\t\tinput.signatureAlgorithm.parametersDer,\n\t\tinput.publicKeyAlgorithm.oid,\n\t\tinput.publicKeyAlgorithm.parametersOid,\n\t\tinput.signerSpkiDer,\n\t\tinput.signature,\n\t\tinput.data,\n\t);\n}\n\n/**\n * Signs `data` with a WebCrypto private key and returns the signature beside\n * the resolved `AlgorithmIdentifier` material for embedding in a signed\n * structure.\n *\n * The algorithm is inferred from the key (RSASSA-PKCS1-v1_5, ECDSA, Ed25519);\n * RSA-PSS keys require an explicit `{ kind: 'rsa-pss' }` profile. ECDSA\n * signatures are returned DER-encoded. Throws on unsupported key algorithms.\n */\nexport async function signData(\n\tprivateKey: CryptoKey,\n\tdata: Uint8Array,\n\tprofile?: SignatureProfileInput,\n): Promise<SignDataResult> {\n\tconst algorithm = getSignatureAlgorithm(privateKey, profile);\n\tconst signature = await signBytes(privateKey, algorithm, data);\n\treturn algorithm.parameters === undefined\n\t\t? { signature, algorithmOid: algorithm.algorithmOid }\n\t\t: { signature, algorithmOid: algorithm.algorithmOid, parametersDer: algorithm.parameters };\n}\n\n/**\n * Converts a DER `ECDSA-Sig-Value` (RFC 5480: SEQUENCE of INTEGERs r and s)\n * to the fixed-width raw `r || s` encoding WebCrypto and JOSE use.\n * Throws on malformed DER or integers too large for the curve.\n */\nexport function ecdsaSignatureDerToRaw(signature: Uint8Array, curve: EcNamedCurve): Uint8Array {\n\treturn derEcdsaSignatureToRaw(signature, ecdsaPartLength(curve));\n}\n\n/**\n * Converts a fixed-width raw `r || s` ECDSA signature to the DER\n * `ECDSA-Sig-Value` encoding X.509 and CMS structures embed.\n * Throws when the input length does not match the curve.\n */\nexport function ecdsaSignatureRawToDer(signature: Uint8Array, curve: EcNamedCurve): Uint8Array {\n\treturn rawEcdsaSignatureToDer(signature, ecdsaPartLength(curve));\n}\n\n/** Byte width of one ECDSA signature integer for the given curve. */\nfunction ecdsaPartLength(curve: EcNamedCurve): number {\n\tswitch (curve) {\n\t\tcase 'P-256':\n\t\t\treturn 32;\n\t\tcase 'P-384':\n\t\t\treturn 48;\n\t\tcase 'P-521':\n\t\t\treturn 66;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = curve;\n\t\t\tthrow new Error(`Unhandled EcNamedCurve: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoEA,SAAgB,gBAAgB,GAA8D;CAC7F,OAAO,EACN,EAAM,mBAAmB,KACzB,EAAM,mBAAmB,eACzB,EAAM,mBAAmB,KACzB,EAAM,mBAAmB,eACzB,EAAM,eACN,EAAM,WACN,EAAM,IACP;AACD;;;;;;;;;;AAWA,eAAsB,SACrB,GACA,GACA,GAC0B;CAC1B,IAAM,IAAY,EAAsB,GAAY,CAAO,GACrD,IAAY,MAAM,EAAU,GAAY,GAAW,CAAI;CAC7D,OAAO,EAAU,eAAe,KAAA,IAC7B;EAAE;EAAW,cAAc,EAAU;CAAa,IAClD;EAAE;EAAW,cAAc,EAAU;EAAc,eAAe,EAAU;CAAW;AAC3F;;;;;;AAOA,SAAgB,uBAAuB,GAAuB,GAAiC;CAC9F,OAAO,EAAuB,GAAW,gBAAgB,CAAK,CAAC;AAChE;;;;;;AAOA,SAAgB,uBAAuB,GAAuB,GAAiC;CAC9F,OAAO,EAAuB,GAAW,gBAAgB,CAAK,CAAC;AAChE;;AAGA,SAAS,gBAAgB,GAA6B;CACrD,QAAQ,GAAR;EACC,KAAK,SACJ,OAAO;EACR,KAAK,SACJ,OAAO;EACR,KAAK,SACJ,OAAO;EACR,SAEC,MAAU,MAAM,2BAA2B,OAAOA,CAAW,GAAG;CAElE;AACD"}
1
+ {"version":3,"file":"crypto.js","names":["_exhaustive","verifySignedDataWithKeyDetailed","input","error","refusal","decodeRefusalOf","DECODE_LIMIT_CODES","verifySignedDataDetailed","algorithm","getSignatureAlgorithm","privateKey","profile","signature","signBytes","data","derEcdsaSignatureToRaw","curve","rawEcdsaSignatureToDer"],"sources":["../../src/crypto/crypto.ts"],"sourcesContent":["/**\n * Detached-signature primitives: verify a signature against a signer's SPKI or CryptoKey,\n * sign arbitrary bytes with a WebCrypto private key, and convert ECDSA\n * signatures between DER `ECDSA-Sig-Value` and fixed-width raw encodings.\n *\n * @module\n */\n\nimport { DECODE_LIMIT_CODES, decodeRefusalOf } from '#micro509/internal/asn1/decode-refusal';\nimport { derEcdsaSignatureToRaw, rawEcdsaSignatureToDer } from '#micro509/internal/crypto/ecdsa';\nimport type { VerifySignedDataResult } from '#micro509/internal/crypto/sig-verify';\nimport {\n\tverifySignedDataDetailed,\n\tverifySignedDataWithKeyDetailed,\n} from '#micro509/internal/crypto/sig-verify';\nimport type { SignatureProfileInput } from '#micro509/internal/crypto/signing';\nimport { getSignatureAlgorithm, signBytes } from '#micro509/internal/crypto/signing';\nimport type { EcNamedCurve } from '#micro509/keys/keys';\n\nexport type {\n\tVerifySignatureConfigFailure,\n\tVerifySignedDataFailure,\n\tVerifySignedDataResult,\n\tVerifySignedDataSuccess,\n} from '#micro509/internal/crypto/sig-verify';\nexport type { SignatureProfileInput } from '#micro509/internal/crypto/signing';\n\n/** Failure: the signature algorithm parameters exceed a micro509 decoding limit. */\nexport interface VerifySignatureLimitFailure {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'limit_exceeded';\n\t/** Human-readable description of the limit. */\n\treadonly reason: string;\n}\n\n/** Result of {@linkcode verifySignature} and {@linkcode verifySignatureWithKey}. */\nexport type VerifySignatureResult = VerifySignedDataResult | VerifySignatureLimitFailure;\n\n/** Input for {@linkcode verifySignature}. */\nexport interface VerifySignatureInput {\n\t/** DER `SubjectPublicKeyInfo` of the signer (`subjectPublicKeyInfoDer` on a parsed certificate). */\n\treadonly signerSpkiDer: Uint8Array;\n\t/** The signature algorithm as carried beside the signature. */\n\treadonly signatureAlgorithm: {\n\t\t/** Dotted-decimal signature algorithm OID. */\n\t\treadonly oid: string;\n\t\t/** DER algorithm parameters when the algorithm carries them (RSA-PSS). */\n\t\treadonly parametersDer?: Uint8Array;\n\t};\n\t/** The signer's public key algorithm as carried in its SPKI. */\n\treadonly publicKeyAlgorithm: {\n\t\t/** Dotted-decimal public key algorithm OID. */\n\t\treadonly oid: string;\n\t\t/** Named-curve or scheme parameters OID, when present. */\n\t\treadonly parametersOid?: string;\n\t};\n\t/** The signature bytes. ECDSA accepts DER or raw encoding. */\n\treadonly signature: Uint8Array;\n\t/** The exact bytes the signature covers. */\n\treadonly data: Uint8Array;\n}\n\n/** Input for {@linkcode verifySignatureWithKey}. */\nexport interface VerifySignatureWithKeyInput {\n\t/** An existing public key with verify usage; extractability is not required. */\n\treadonly publicKey: CryptoKey;\n\t/** Explicit signature OID and parameters, including RSA-PSS salt length. */\n\treadonly signatureAlgorithm: VerifySignatureInput['signatureAlgorithm'];\n\t/** ECDSA accepts raw r || s or DER; RSA and Ed25519 require raw. No encoding retry occurs. */\n\treadonly signatureEncoding: 'raw' | 'der';\n\t/** The signature bytes in the declared encoding. */\n\treadonly signature: Uint8Array;\n\t/** The exact bytes the signature covers. */\n\treadonly data: Uint8Array;\n}\n\n/**\n * Verifies a detached signature using an existing WebCrypto public key without\n * exporting or importing it. Repeated calls may reuse non-extractable keys.\n * Signature algorithms and parameters follow {@linkcode verifySignature}; RSA\n * scheme and hash must match the key. ECDSA encoding is explicit and never retried.\n * Returns the same validity, unsupported-parameter, operational-error and decoding-limit\n * branches as {@linkcode verifySignature}.\n */\nexport async function verifySignatureWithKey(\n\tinput: VerifySignatureWithKeyInput,\n): Promise<VerifySignatureResult> {\n\ttry {\n\t\treturn await verifySignedDataWithKeyDetailed(\n\t\t\tinput.publicKey,\n\t\t\tinput.signatureAlgorithm.oid,\n\t\t\tinput.signatureAlgorithm.parametersDer,\n\t\t\tinput.signature,\n\t\t\tinput.data,\n\t\t\tinput.signatureEncoding,\n\t\t);\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_LIMIT_CODES);\n\t\tif (refusal === undefined) throw error;\n\t\treturn { ok: false, code: refusal.code, reason: refusal.message };\n\t}\n}\n\n/** Result of {@linkcode signData}: the signature plus its on-wire algorithm identity. */\nexport interface SignDataResult {\n\t/** The signature bytes. ECDSA is DER `ECDSA-Sig-Value`, everything else raw. */\n\treadonly signature: Uint8Array;\n\t/** Dotted-decimal signature algorithm OID. */\n\treadonly algorithmOid: string;\n\t/** DER algorithm parameters when the algorithm carries them (NULL for PKCS#1 v1.5, RSA-PSS params). */\n\treadonly parametersDer?: Uint8Array;\n}\n\n/**\n * Verifies a detached signature against the signer's DER `SubjectPublicKeyInfo`.\n *\n * Supports RSA PKCS#1 v1.5 (SHA-256/384/512), RSA-PSS with parsed parameters,\n * ECDSA P-256/P-384/P-521, and Ed25519. When an ECDSA signature fails to\n * verify under one encoding, the alternate DER/raw encoding is retried.\n *\n * Returns a typed union: `{ ok: true, valid }` when verification ran,\n * `unsupported_signature_algorithm_parameters`, `verification_error` or\n * `limit_exceeded` failures otherwise.\n */\nexport async function verifySignature(input: VerifySignatureInput): Promise<VerifySignatureResult> {\n\ttry {\n\t\treturn await verifySignedDataDetailed(\n\t\t\tinput.signatureAlgorithm.oid,\n\t\t\tinput.signatureAlgorithm.parametersDer,\n\t\t\tinput.publicKeyAlgorithm.oid,\n\t\t\tinput.publicKeyAlgorithm.parametersOid,\n\t\t\tinput.signerSpkiDer,\n\t\t\tinput.signature,\n\t\t\tinput.data,\n\t\t);\n\t} catch (error) {\n\t\tconst refusal = decodeRefusalOf(error, DECODE_LIMIT_CODES);\n\t\tif (refusal === undefined) {\n\t\t\tthrow error;\n\t\t}\n\t\treturn { ok: false, code: refusal.code, reason: refusal.message };\n\t}\n}\n\n/**\n * Signs `data` with a WebCrypto private key and returns the signature beside\n * the resolved `AlgorithmIdentifier` material for embedding in a signed\n * structure.\n *\n * The algorithm is inferred from the key (RSASSA-PKCS1-v1_5, ECDSA, Ed25519);\n * RSA-PSS keys require an explicit `{ kind: 'rsa-pss' }` profile. ECDSA\n * signatures are returned DER-encoded. Throws on unsupported key algorithms.\n */\nexport async function signData(\n\tprivateKey: CryptoKey,\n\tdata: Uint8Array,\n\tprofile?: SignatureProfileInput,\n): Promise<SignDataResult> {\n\tconst algorithm = getSignatureAlgorithm(privateKey, profile);\n\tconst signature = await signBytes(privateKey, algorithm, data);\n\treturn algorithm.parameters === undefined\n\t\t? { signature, algorithmOid: algorithm.algorithmOid }\n\t\t: { signature, algorithmOid: algorithm.algorithmOid, parametersDer: algorithm.parameters };\n}\n\n/**\n * Converts a DER `ECDSA-Sig-Value` (RFC 5480: SEQUENCE of INTEGERs r and s)\n * to the fixed-width raw `r || s` encoding WebCrypto and JOSE use.\n * Throws on malformed DER or integers too large for the curve.\n */\nexport function ecdsaSignatureDerToRaw(signature: Uint8Array, curve: EcNamedCurve): Uint8Array {\n\treturn derEcdsaSignatureToRaw(signature, ecdsaPartLength(curve));\n}\n\n/**\n * Converts a fixed-width raw `r || s` ECDSA signature to the DER\n * `ECDSA-Sig-Value` encoding X.509 and CMS structures embed.\n * Throws when the input length does not match the curve.\n */\nexport function ecdsaSignatureRawToDer(signature: Uint8Array, curve: EcNamedCurve): Uint8Array {\n\treturn rawEcdsaSignatureToDer(signature, ecdsaPartLength(curve));\n}\n\n/** Byte width of one ECDSA signature integer for the given curve. */\nfunction ecdsaPartLength(curve: EcNamedCurve): number {\n\tswitch (curve) {\n\t\tcase 'P-256':\n\t\t\treturn 32;\n\t\tcase 'P-384':\n\t\t\treturn 48;\n\t\tcase 'P-521':\n\t\t\treturn 66;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = curve;\n\t\t\tthrow new Error(`Unhandled EcNamedCurve: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsFA,eAAsB,uBACrB,GACiC;CACjC,IAAI;EACH,OAAO,MAAMC,EACZC,EAAM,WACNA,EAAM,mBAAmB,KACzBA,EAAM,mBAAmB,eACzBA,EAAM,WACNA,EAAM,MACNA,EAAM,iBACP;CACD,SAASC,GAAO;EACf,IAAMC,IAAUC,EAAgBF,GAAOG,CAAkB;EACzD,IAAIF,MAAY,KAAA,GAAW,MAAMD;EACjC,OAAO;GAAE,IAAI;GAAO,MAAMC,EAAQ;GAAM,QAAQA,EAAQ;EAAQ;CACjE;AACD;;;;;;;;;;;;AAuBA,eAAsB,gBAAgB,GAA6D;CAClG,IAAI;EACH,OAAO,MAAMG,EACZL,EAAM,mBAAmB,KACzBA,EAAM,mBAAmB,eACzBA,EAAM,mBAAmB,KACzBA,EAAM,mBAAmB,eACzBA,EAAM,eACNA,EAAM,WACNA,EAAM,IACP;CACD,SAASC,GAAO;EACf,IAAMC,IAAUC,EAAgBF,GAAOG,CAAkB;EACzD,IAAIF,MAAY,KAAA,GACf,MAAMD;EAEP,OAAO;GAAE,IAAI;GAAO,MAAMC,EAAQ;GAAM,QAAQA,EAAQ;EAAQ;CACjE;AACD;;;;;;;;;;AAWA,eAAsB,SACrB,GACA,GACA,GAC0B;CAC1B,IAAMI,IAAYC,EAAsBC,GAAYC,CAAO,GACrDC,IAAY,MAAMC,EAAUH,GAAYF,GAAWM,CAAI;CAC7D,OAAON,EAAU,eAAe,KAAA,IAC7B;EAAE;EAAW,cAAcA,EAAU;CAAa,IAClD;EAAE;EAAW,cAAcA,EAAU;EAAc,eAAeA,EAAU;CAAW;AAC3F;;;;;;AAOA,SAAgB,uBAAuB,GAAuB,GAAiC;CAC9F,OAAOO,EAAuBH,GAAW,gBAAgBI,CAAK,CAAC;AAChE;;;;;;AAOA,SAAgB,uBAAuB,GAAuB,GAAiC;CAC9F,OAAOC,EAAuBL,GAAW,gBAAgBI,CAAK,CAAC;AAChE;;AAGA,SAAS,gBAAgB,GAA6B;CACrD,QAAQA,GAAR;EACC,KAAK,SACJ,OAAO;EACR,KAAK,SACJ,OAAO;EACR,KAAK,SACJ,OAAO;EACR,SAEC,MAAU,MAAM,2BAA2B,OAAOhB,CAAW,GAAG;CAElE;AACD"}