node-pki-signer 0.0.0-stage → 0.1.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 (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +46 -2
  3. package/dist/algorithms.d.ts +10 -0
  4. package/dist/algorithms.js +73 -0
  5. package/dist/algorithms.js.map +1 -0
  6. package/dist/allowlist.d.ts +2 -0
  7. package/dist/allowlist.js +45 -0
  8. package/dist/allowlist.js.map +1 -0
  9. package/dist/ca-sign-csr.d.ts +31 -0
  10. package/dist/ca-sign-csr.js +197 -0
  11. package/dist/ca-sign-csr.js.map +1 -0
  12. package/dist/errors.d.ts +12 -0
  13. package/dist/errors.js +20 -0
  14. package/dist/errors.js.map +1 -0
  15. package/dist/extensions.d.ts +3 -0
  16. package/dist/extensions.js +298 -0
  17. package/dist/extensions.js.map +1 -0
  18. package/dist/index.d.ts +11 -0
  19. package/dist/index.js +10 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/keys.d.ts +24 -0
  22. package/dist/keys.js +76 -0
  23. package/dist/keys.js.map +1 -0
  24. package/dist/kms-key.d.ts +19 -0
  25. package/dist/kms-key.js +49 -0
  26. package/dist/kms-key.js.map +1 -0
  27. package/dist/openssl-key.d.ts +14 -0
  28. package/dist/openssl-key.js +60 -0
  29. package/dist/openssl-key.js.map +1 -0
  30. package/dist/options.d.ts +48 -0
  31. package/dist/options.js +2 -0
  32. package/dist/options.js.map +1 -0
  33. package/dist/pkcs11-key.d.ts +12 -0
  34. package/dist/pkcs11-key.js +266 -0
  35. package/dist/pkcs11-key.js.map +1 -0
  36. package/dist/shadow.d.ts +25 -0
  37. package/dist/shadow.js +45 -0
  38. package/dist/shadow.js.map +1 -0
  39. package/dist/signer.d.ts +49 -0
  40. package/dist/signer.js +96 -0
  41. package/dist/signer.js.map +1 -0
  42. package/dist/signing-key.d.ts +15 -0
  43. package/dist/signing-key.js +2 -0
  44. package/dist/signing-key.js.map +1 -0
  45. package/dist/software-key.d.ts +3 -0
  46. package/dist/software-key.js +34 -0
  47. package/dist/software-key.js.map +1 -0
  48. package/dist/subject.d.ts +3 -0
  49. package/dist/subject.js +90 -0
  50. package/dist/subject.js.map +1 -0
  51. package/dist/tbs-fields.d.ts +14 -0
  52. package/dist/tbs-fields.js +57 -0
  53. package/dist/tbs-fields.js.map +1 -0
  54. package/package.json +51 -4
@@ -0,0 +1,48 @@
1
+ /** What node-openssl-cert2's x509.CASignCSR takes, as PKIaaS.io and the IoT HSM agent call it. */
2
+ export interface SignParams {
3
+ /** the certificate request, PEM */
4
+ csr: string;
5
+ options: SignOptions;
6
+ /** issuer certificate, PEM */
7
+ ca: string;
8
+ /** issuer private key, PEM (encrypted PKCS#8 in PKIaaS.io) */
9
+ key: string;
10
+ password?: string;
11
+ /** a key on a PKCS#11 token instead of `key`, as the IoT HSM agent passes it */
12
+ pkcs11?: Pkcs11KeyRef | false | null;
13
+ /**
14
+ * a Google Cloud KMS key, signed with the KMS API (ADR 0003). The agent passes it beside `pkcs11`
15
+ * (libkmsp11), which the OpenSSL fallback keeps using.
16
+ */
17
+ kms?: {
18
+ keyVersion: string;
19
+ } | null;
20
+ }
21
+ /** A private key on a PKCS#11 token. */
22
+ export interface Pkcs11KeyRef {
23
+ /** RFC 7512 URI, e.g. `pkcs11:serial=0123;id=%01;type=private` */
24
+ uri: string;
25
+ /** the user PIN */
26
+ pin?: string;
27
+ /** the PKCS#11 module, e.g. /usr/lib/x86_64-linux-gnu/libykcs11.so */
28
+ modulePath: string;
29
+ }
30
+ /** The options object pkiaas builds in lib/template/processTemplate.js. */
31
+ export interface SignOptions {
32
+ hash?: string;
33
+ /** the certificate's subject in this order; false or null for an empty subject */
34
+ subject?: Record<string, string | string[]> | false | null;
35
+ extensions?: Record<string, unknown> | null;
36
+ startdate?: Date | string | number;
37
+ enddate?: Date | string | number;
38
+ /** validity from now when there is no startdate; 365 by default */
39
+ days?: number;
40
+ /** the PKCS#11 module node-openssl-cert2 loads through pkcs11-provider; the agent sets it beside `pkcs11` */
41
+ module?: string;
42
+ }
43
+ export interface SignResult {
44
+ /** the certificate, PEM */
45
+ data: string;
46
+ /** the serial number, upper-case hex */
47
+ serial: string;
48
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"options.js","sourceRoot":"","sources":["../src/options.ts"],"names":[],"mappings":""}
@@ -0,0 +1,12 @@
1
+ import type { Pkcs11KeyRef } from './options.ts';
2
+ import type { SigningKey } from './signing-key.ts';
3
+ /** The attributes of an RFC 7512 PKCS#11 URI's path, percent-decoded. */
4
+ export declare function parsePkcs11URI(uri: string): Map<string, Buffer>;
5
+ /** The loaded PKCS#11 modules and logged-in tokens; one per process, closed on exit. */
6
+ export declare class Pkcs11Sessions {
7
+ #private;
8
+ /** A SigningKey for an RSA or EC key on a token, signing `algorithm` (the CA certificate's). */
9
+ key(ref: Pkcs11KeyRef, algorithm: string, publicKey: Uint8Array): Promise<SigningKey>;
10
+ /** Logs out of every token and unloads the modules, e.g. before the agent changes a YubiKey. */
11
+ close(): void;
12
+ }
@@ -0,0 +1,266 @@
1
+ // Keys on a PKCS#11 token (YubiKey, SoftHSM), signing with pkcs11js (ADR 0003). Each module stays
2
+ // loaded and each token keeps one logged-in session between signatures; every signature opens its
3
+ // own session, which shares that login, and looks the key up again.
4
+ import { createHash, timingSafeEqual } from 'node:crypto';
5
+ import * as asn1js from 'asn1js';
6
+ import { signatureHash } from "./algorithms.js";
7
+ import { SignerError, UnsupportedError } from "./errors.js";
8
+ // what RSASSA-PKCS1-v1_5 puts before the digest (RFC 8017 section 9.2)
9
+ const digestInfo = {
10
+ sha1: '3021300906052b0e03021a05000414',
11
+ sha224: '302d300d06096086480165030402040500041c',
12
+ sha256: '3031300d060960864801650304020105000420',
13
+ sha384: '3041300d060960864801650304020205000430',
14
+ sha512: '3051300d060960864801650304020305000440',
15
+ };
16
+ /** The attributes of an RFC 7512 PKCS#11 URI's path, percent-decoded. */
17
+ export function parsePkcs11URI(uri) {
18
+ if (!uri.startsWith('pkcs11:'))
19
+ throw new SignerError('parse PKCS#11 URI', 'not a pkcs11: URI');
20
+ const attributes = new Map();
21
+ for (const part of (uri.slice('pkcs11:'.length).split('?')[0] ?? '').split(';')) {
22
+ if (!part)
23
+ continue;
24
+ const separator = part.indexOf('=');
25
+ if (separator < 1)
26
+ throw new SignerError('parse PKCS#11 URI', 'an attribute has no value');
27
+ const bytes = [];
28
+ const value = part.slice(separator + 1);
29
+ for (let i = 0; i < value.length; i++) {
30
+ if (value[i] === '%' && /^[0-9a-f]{2}$/i.test(value.slice(i + 1, i + 3))) {
31
+ bytes.push(parseInt(value.slice(i + 1, i + 3), 16));
32
+ i += 2;
33
+ }
34
+ else {
35
+ bytes.push(...Buffer.from(value[i] ?? ''));
36
+ }
37
+ }
38
+ attributes.set(part.slice(0, separator), Buffer.from(bytes));
39
+ }
40
+ return attributes;
41
+ }
42
+ // a PKCS#11 error's CKR_ name, without the native stack
43
+ const ckr = (err) => /CKR_[A-Z_]+/.exec(err instanceof Error ? err.message : String(err))?.[0] ?? 'error';
44
+ /** The loaded PKCS#11 modules and logged-in tokens; one per process, closed on exit. */
45
+ export class Pkcs11Sessions {
46
+ #lib;
47
+ #modules = new Map();
48
+ async #module(path) {
49
+ if (!this.#lib) {
50
+ try {
51
+ this.#lib = (await import('pkcs11js')).default;
52
+ }
53
+ catch {
54
+ throw new UnsupportedError('load PKCS#11 module', 'pkcs11js is not installed');
55
+ }
56
+ }
57
+ const lib = this.#lib;
58
+ let module = this.#modules.get(path);
59
+ if (!module) {
60
+ const pkcs11 = new lib.PKCS11();
61
+ try {
62
+ pkcs11.load(path);
63
+ pkcs11.C_Initialize({ flags: lib.CKF_OS_LOCKING_OK });
64
+ }
65
+ catch (err) {
66
+ // pkcs11js can't use it; openssl may
67
+ throw new UnsupportedError('load PKCS#11 module', `${path}: ${ckr(err)}`);
68
+ }
69
+ module = { pkcs11, tokens: new Map() };
70
+ this.#modules.set(path, module);
71
+ }
72
+ return { lib, module };
73
+ }
74
+ // the slot whose token matches the URI's token attributes
75
+ #slot(pkcs11, uri) {
76
+ const wanted = [
77
+ ['serial', 'serialNumber'],
78
+ ['token', 'label'],
79
+ ['manufacturer', 'manufacturerID'],
80
+ ['model', 'model'],
81
+ ];
82
+ const slots = pkcs11.C_GetSlotList(true).filter((slot) => {
83
+ const info = pkcs11.C_GetTokenInfo(slot);
84
+ return wanted.every(([attribute, field]) => {
85
+ const value = uri.get(attribute);
86
+ return !value || info[field].trim() === value.toString('utf8');
87
+ });
88
+ });
89
+ if (slots.length !== 1) {
90
+ throw new SignerError('find PKCS#11 token', slots.length ? 'more than one token matches' : 'no token matches');
91
+ }
92
+ return slots[0];
93
+ }
94
+ // logs in once per token, again only when the PIN changes
95
+ #login(lib, module, slot, pin) {
96
+ const id = slot.toString('hex');
97
+ const hash = createHash('sha256')
98
+ .update(pin ?? '')
99
+ .digest();
100
+ const token = module.tokens.get(id);
101
+ if (token && timingSafeEqual(token.pin, hash))
102
+ return;
103
+ if (token)
104
+ this.#logout(module, id);
105
+ const { pkcs11 } = module;
106
+ let session;
107
+ try {
108
+ session = pkcs11.C_OpenSession(slot, lib.CKF_SERIAL_SESSION);
109
+ }
110
+ catch (err) {
111
+ throw new SignerError('open PKCS#11 session', ckr(err));
112
+ }
113
+ if (pin !== undefined) {
114
+ try {
115
+ pkcs11.C_Login(session, lib.CKU_USER, pin);
116
+ }
117
+ catch (err) {
118
+ if (ckr(err) !== 'CKR_USER_ALREADY_LOGGED_IN') {
119
+ pkcs11.C_CloseSession(session);
120
+ throw new SignerError('PKCS#11 login', ckr(err));
121
+ }
122
+ }
123
+ }
124
+ module.tokens.set(id, { session, pin: hash });
125
+ }
126
+ #logout(module, id) {
127
+ const token = module.tokens.get(id);
128
+ module.tokens.delete(id);
129
+ if (!token)
130
+ return;
131
+ try {
132
+ module.pkcs11.C_Logout(token.session);
133
+ }
134
+ catch {
135
+ // not logged in, or the token is gone
136
+ }
137
+ try {
138
+ module.pkcs11.C_CloseSession(token.session);
139
+ }
140
+ catch {
141
+ // the token is gone
142
+ }
143
+ }
144
+ /** A SigningKey for an RSA or EC key on a token, signing `algorithm` (the CA certificate's). */
145
+ async key(ref, algorithm, publicKey) {
146
+ const uri = parsePkcs11URI(ref.uri);
147
+ const hash = signatureHash(algorithm);
148
+ const rsa = algorithm.endsWith('WithRSAEncryption');
149
+ if (!hash || !(rsa || algorithm.startsWith('ecdsa-with-'))) {
150
+ throw new UnsupportedError('load CA key', `${algorithm} with PKCS#11 keys`);
151
+ }
152
+ const prefix = rsa ? digestInfo[hash] : '';
153
+ if (prefix === undefined)
154
+ throw new UnsupportedError('load CA key', `hash ${hash}`);
155
+ const { lib, module } = await this.#module(ref.modulePath);
156
+ // after a failure (e.g. the token was unplugged), the next signature logs in again
157
+ const reset = () => {
158
+ this.#logout(module, slot.toString('hex'));
159
+ };
160
+ const { pkcs11 } = module;
161
+ const slot = this.#slot(pkcs11, uri);
162
+ const login = () => {
163
+ this.#login(lib, module, slot, ref.pin);
164
+ };
165
+ login();
166
+ const template = [{ type: lib.CKA_CLASS, value: lib.CKO_PRIVATE_KEY }];
167
+ const label = uri.get('object');
168
+ const id = uri.get('id');
169
+ if (label)
170
+ template.push({ type: lib.CKA_LABEL, value: label.toString('utf8') });
171
+ if (id)
172
+ template.push({ type: lib.CKA_ID, value: id });
173
+ const signOnce = async (input) => {
174
+ let session;
175
+ try {
176
+ session = pkcs11.C_OpenSession(slot, lib.CKF_SERIAL_SESSION);
177
+ }
178
+ catch (err) {
179
+ reset();
180
+ throw new SignerError('open PKCS#11 session', ckr(err));
181
+ }
182
+ try {
183
+ pkcs11.C_FindObjectsInit(session, template);
184
+ const keys = pkcs11.C_FindObjects(session, 2);
185
+ pkcs11.C_FindObjectsFinal(session);
186
+ if (keys.length !== 1) {
187
+ throw new SignerError('find PKCS#11 key', keys.length ? 'more than one private key matches' : 'no private key matches');
188
+ }
189
+ try {
190
+ pkcs11.C_SignInit(session, { mechanism: rsa ? lib.CKM_RSA_PKCS : lib.CKM_ECDSA }, keys[0]);
191
+ }
192
+ catch (err) {
193
+ // the token can't sign this way, so OpenSSL may
194
+ throw new UnsupportedError('PKCS#11 sign', ckr(err));
195
+ }
196
+ const signature = await new Promise((resolve, reject) => {
197
+ pkcs11.C_Sign(session, input, Buffer.alloc(2048), (err, data) => {
198
+ if (err)
199
+ reject(new SignerError('PKCS#11 sign', ckr(err)));
200
+ else
201
+ resolve(data);
202
+ });
203
+ });
204
+ return rsa ? new Uint8Array(signature) : ecdsaDER(signature);
205
+ }
206
+ catch (err) {
207
+ reset();
208
+ if (err instanceof SignerError)
209
+ throw err;
210
+ throw new SignerError('find PKCS#11 key', ckr(err));
211
+ }
212
+ finally {
213
+ try {
214
+ pkcs11.C_CloseSession(session);
215
+ }
216
+ catch {
217
+ // the token is gone
218
+ }
219
+ }
220
+ };
221
+ return {
222
+ backend: 'pkcs11',
223
+ algorithm,
224
+ publicKey: () => Promise.resolve(publicKey),
225
+ async sign(tbs) {
226
+ const digest = createHash(hash).update(tbs).digest();
227
+ const input = rsa ? Buffer.concat([Buffer.from(prefix, 'hex'), digest]) : digest;
228
+ try {
229
+ return await signOnce(input);
230
+ }
231
+ catch (err) {
232
+ // another process using a YubiKey resets its login, which hides the private keys from this
233
+ // one until it logs in again (ADR 0003)
234
+ const loggedOut = ['find PKCS#11 key: no private key matches', 'PKCS#11 sign: CKR_USER_NOT_LOGGED_IN'];
235
+ if (!(err instanceof SignerError && loggedOut.includes(err.message)))
236
+ throw err;
237
+ login();
238
+ return signOnce(input);
239
+ }
240
+ },
241
+ };
242
+ }
243
+ /** Logs out of every token and unloads the modules, e.g. before the agent changes a YubiKey. */
244
+ close() {
245
+ for (const module of this.#modules.values()) {
246
+ for (const id of [...module.tokens.keys()])
247
+ this.#logout(module, id);
248
+ try {
249
+ module.pkcs11.C_Finalize();
250
+ }
251
+ catch {
252
+ // already finalized
253
+ }
254
+ module.pkcs11.close();
255
+ }
256
+ this.#modules.clear();
257
+ }
258
+ }
259
+ /** A PKCS#11 ECDSA signature (r and s, each the size of the curve) as the DER ECDSA-Sig-Value X.509 needs. */
260
+ function ecdsaDER(raw) {
261
+ const half = raw.length / 2;
262
+ const integer = (bytes) => asn1js.Integer.fromBigInt(BigInt(`0x${bytes.toString('hex') || '0'}`));
263
+ const sequence = new asn1js.Sequence({ value: [integer(raw.subarray(0, half)), integer(raw.subarray(half))] });
264
+ return new Uint8Array(sequence.toBER());
265
+ }
266
+ //# sourceMappingURL=pkcs11-key.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pkcs11-key.js","sourceRoot":"","sources":["../src/pkcs11-key.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,kGAAkG;AAClG,oEAAoE;AACpE,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AAEjC,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAM5D,uEAAuE;AACvE,MAAM,UAAU,GAA2B;IACzC,IAAI,EAAE,gCAAgC;IACtC,MAAM,EAAE,wCAAwC;IAChD,MAAM,EAAE,wCAAwC;IAChD,MAAM,EAAE,wCAAwC;IAChD,MAAM,EAAE,wCAAwC;CACjD,CAAC;AAEF,yEAAyE;AACzE,MAAM,UAAU,cAAc,CAAC,GAAW;IACxC,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,SAAS,CAAC;QAAE,MAAM,IAAI,WAAW,CAAC,mBAAmB,EAAE,mBAAmB,CAAC,CAAC;IAChG,MAAM,UAAU,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC7C,KAAK,MAAM,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,K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G,CAAC,QAAQ,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC/G,OAAO,IAAI,UAAU,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC;AAC1C,CAAC"}
@@ -0,0 +1,25 @@
1
+ import type { SignParams } from './options.ts';
2
+ /**
3
+ * What the native signer would have done: `match` built the same TBS byte for byte, `differ` lists
4
+ * the TBS fields that differ (names only, never values), `unsupported` would have gone to OpenSSL and
5
+ * `refused` would have refused the request. `algorithm` is the CA's signature algorithm, when known.
6
+ */
7
+ export type ShadowResult = {
8
+ outcome: 'match';
9
+ algorithm: string;
10
+ } | {
11
+ outcome: 'differ';
12
+ algorithm: string;
13
+ fields: string[];
14
+ } | {
15
+ outcome: 'unsupported' | 'refused';
16
+ algorithm?: string;
17
+ step: string;
18
+ reason: string;
19
+ };
20
+ /**
21
+ * Compares `certificate` (PEM), issued for `params`, with the TBS the native signer builds for
22
+ * `params` using the certificate's serial number, and its validity when the options give no
23
+ * startdate. Needs no private key: `params.key`, `pkcs11` and `kms` are ignored.
24
+ */
25
+ export declare function shadowCASignCSR(params: Pick<SignParams, 'csr' | 'options' | 'ca'>, certificate: string): Promise<ShadowResult>;
package/dist/shadow.js ADDED
@@ -0,0 +1,45 @@
1
+ // Shadow mode (ADR 0004): checks a certificate that node-openssl-cert2 (or an IoT HSM agent) issued
2
+ // against the TBS the native signer would build for the same request, without signing anything.
3
+ import { AsnConvert } from '@peculiar/asn1-schema';
4
+ import { Certificate } from '@peculiar/asn1-x509';
5
+ import { X509Certificate } from 'node:crypto';
6
+ import { signatureAlgorithm } from "./algorithms.js";
7
+ import { buildTBS, parseRequest, validity } from "./ca-sign-csr.js";
8
+ import { SignerError, UnsupportedError } from "./errors.js";
9
+ import { children, decode, tbsFields } from "./tbs-fields.js";
10
+ const message = (err) => (err instanceof Error ? err.message : String(err));
11
+ /**
12
+ * Compares `certificate` (PEM), issued for `params`, with the TBS the native signer builds for
13
+ * `params` using the certificate's serial number, and its validity when the options give no
14
+ * startdate. Needs no private key: `params.key`, `pkcs11` and `kms` are ignored.
15
+ */
16
+ export async function shadowCASignCSR(params, certificate) {
17
+ let algorithm;
18
+ try {
19
+ let issued;
20
+ try {
21
+ const der = new Uint8Array(new X509Certificate(certificate).raw);
22
+ const tbs = children(decode(der))[0];
23
+ if (!tbs)
24
+ throw new Error('not a Certificate');
25
+ issued = { tbs: tbsFields(tbs), certificate: AsnConvert.parse(der, Certificate) };
26
+ }
27
+ catch (err) {
28
+ throw new SignerError('parse issued certificate', message(err));
29
+ }
30
+ const request = await parseRequest({ ...params, key: '' });
31
+ algorithm = signatureAlgorithm(request.issuer.publicKey, params.options.hash ?? 'sha256');
32
+ const dates = params.options.startdate ? validity(params.options) : issued.certificate.tbsCertificate.validity;
33
+ const tbs = buildTBS({ ...params, key: '' }, request, algorithm, new Uint8Array(issued.tbs.serial).buffer, dates);
34
+ const native = tbsFields(decode(new Uint8Array(AsnConvert.serialize(tbs)))).fields;
35
+ const fields = [...new Set([...native.keys(), ...issued.tbs.fields.keys()])].filter((field) => native.get(field) !== issued.tbs.fields.get(field));
36
+ return fields.length ? { outcome: 'differ', algorithm, fields } : { outcome: 'match', algorithm };
37
+ }
38
+ catch (err) {
39
+ const step = err instanceof SignerError ? err.step : 'native signer';
40
+ const reason = err instanceof SignerError ? err.message : `native signer: unexpected error: ${message(err)}`;
41
+ const outcome = err instanceof UnsupportedError || !(err instanceof SignerError) ? 'unsupported' : 'refused';
42
+ return { outcome, ...(algorithm ? { algorithm } : {}), step, reason };
43
+ }
44
+ }
45
+ //# sourceMappingURL=shadow.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shadow.js","sourceRoot":"","sources":["../src/shadow.ts"],"names":[],"mappings":"AAAA,oGAAoG;AACpG,gGAAgG;AAChG,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,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,OAAO,EAAE,SAAS,EAAE,CAAC;IACpG,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,IAAI,GAAG,GAAG,YAAY,WAAW,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC;QACrE,MAAM,MAAM,GAAG,GAAG,YAAY,WAAW,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,oCAAoC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QAC7G,MAAM,OAAO,GAAG,GAAG,YAAY,gBAAgB,IAAI,CAAC,CAAC,GAAG,YAAY,WAAW,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC;QAC7G,OAAO,EAAE,OAAO,EAAE,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;IACxE,CAAC;AACH,CAAC"}
@@ -0,0 +1,49 @@
1
+ import { type KmsClient } from './kms-key.ts';
2
+ import type { SignParams, SignResult } from './options.ts';
3
+ /** Why an operation went to OpenSSL. Never contains keys, passphrases or CSRs. */
4
+ export interface Fallback {
5
+ /** e.g. 'CASignCSR' */
6
+ operation: string;
7
+ /** the native step that couldn't go on, e.g. 'load CA key' */
8
+ step: string;
9
+ /** e.g. 'load CA key: PKCS#11 keys' */
10
+ reason: string;
11
+ }
12
+ export interface SignerSettings {
13
+ /** the openssl binary for the fallback (node-openssl-cert2's `binpath`); `openssl` on the PATH by default */
14
+ binpath?: string;
15
+ /** signature algorithms always signed with OpenSSL, e.g. ['ML-DSA-65']; true for every algorithm */
16
+ forceOpenSSL?: boolean | readonly string[];
17
+ /** called for every fallback, e.g. to write it to the CA's log; a console.warn by default */
18
+ onFallback?: (fallback: Fallback) => void;
19
+ /** the backends that may sign natively, e.g. ['software', 'kms', 'openssl-pkcs11']; all by default */
20
+ backends?: readonly string[];
21
+ /** the KMS client for `params.kms` keys; one with Application Default Credentials by default */
22
+ kms?: KmsClient;
23
+ }
24
+ /** Which path signed: the library itself or node-openssl-cert2. */
25
+ export type SignedBy = 'native' | 'openssl';
26
+ /** What x509.CASignCSR passes its callback: node-openssl-cert2's result, plus who signed. */
27
+ export interface CASignCSRResult {
28
+ data: string | null;
29
+ serial?: string;
30
+ command: string[] | null;
31
+ files?: {
32
+ config: string;
33
+ };
34
+ signedBy?: SignedBy;
35
+ }
36
+ export interface Signer {
37
+ /** Signs a CSR natively or, failing that, with OpenSSL. Rejects with a SignerError naming the step. */
38
+ caSignCSR(params: SignParams): Promise<SignResult & {
39
+ signedBy: SignedBy;
40
+ }>;
41
+ /** The same, called exactly like node-openssl-cert2's: errors and results as it passes them. */
42
+ x509: {
43
+ CASignCSR(params: SignParams, callback: (err: false | string | Error, result: CASignCSRResult | false) => void): void;
44
+ };
45
+ /** Logs out of PKCS#11 tokens and unloads their modules; the next signature opens them again. */
46
+ close(): void;
47
+ }
48
+ /** A signer with its fallback settings; create one per process and reuse it. */
49
+ export declare function createSigner(settings?: SignerSettings): Signer;
package/dist/signer.js ADDED
@@ -0,0 +1,96 @@
1
+ // The drop-in for node-openssl-cert2's x509.CASignCSR (ADR 0001): signs natively when it can and
2
+ // hands the whole operation to node-openssl-cert2 when it can't, reporting every fallback.
3
+ import NodeOpenSSL from 'node-openssl-cert2';
4
+ import { caSignCSR } from "./ca-sign-csr.js";
5
+ import { SignerError, UnsupportedError } from "./errors.js";
6
+ import { createKmsClient } from "./kms-key.js";
7
+ import { Pkcs11Sessions } from "./pkcs11-key.js";
8
+ const message = (err) => (err instanceof Error ? err.message : String(err).trim());
9
+ /** A signer with its fallback settings; create one per process and reuse it. */
10
+ export function createSigner(settings = {}) {
11
+ const openssl = new NodeOpenSSL(settings.binpath ? { binpath: settings.binpath } : undefined);
12
+ const force = settings.forceOpenSSL ?? false;
13
+ const pkcs11 = new Pkcs11Sessions();
14
+ let kms = settings.kms && Promise.resolve(settings.kms);
15
+ const keySettings = {
16
+ pkcs11,
17
+ kms: () => {
18
+ kms ??= createKmsClient().catch((err) => {
19
+ kms = undefined;
20
+ throw err;
21
+ });
22
+ return kms;
23
+ },
24
+ ...(settings.binpath ? { binpath: settings.binpath } : {}),
25
+ ...(settings.backends ? { backends: settings.backends } : {}),
26
+ };
27
+ const onFallback = settings.onFallback ??
28
+ ((fallback) => {
29
+ console.warn(`node-pki-signer: ${fallback.operation} fell back to OpenSSL: ${fallback.reason}`);
30
+ });
31
+ // the native certificate, or why the request must go to OpenSSL; refusals reject
32
+ async function native(params) {
33
+ const operation = 'CASignCSR';
34
+ if (force === true) {
35
+ return {
36
+ fallback: {
37
+ operation,
38
+ step: 'check allowlist',
39
+ reason: 'check allowlist: every algorithm is set to sign with OpenSSL',
40
+ },
41
+ };
42
+ }
43
+ try {
44
+ return { result: await caSignCSR(params, { ...keySettings, forceOpenSSL: force === false ? [] : force }) };
45
+ }
46
+ catch (err) {
47
+ if (err instanceof UnsupportedError)
48
+ return { fallback: { operation, step: err.step, reason: err.message } };
49
+ // a refusal of the request itself, which OpenSSL would refuse too (the differential harness checks)
50
+ if (err instanceof SignerError)
51
+ throw err;
52
+ // a bug in the native path mustn't stop issuance
53
+ return {
54
+ fallback: { operation, step: 'native signer', reason: `native signer: unexpected error: ${message(err)}` },
55
+ };
56
+ }
57
+ }
58
+ return {
59
+ async caSignCSR(params) {
60
+ const outcome = await native(params);
61
+ if ('result' in outcome)
62
+ return { ...outcome.result, signedBy: 'native' };
63
+ onFallback(outcome.fallback);
64
+ return new Promise((resolve, reject) => {
65
+ openssl.x509.CASignCSR(params, (err, result) => {
66
+ if (err || !result || !result.data || !result.serial) {
67
+ reject(new SignerError('sign with OpenSSL', err ? message(err) : 'no certificate'));
68
+ }
69
+ else {
70
+ resolve({ data: result.data, serial: result.serial, signedBy: 'openssl' });
71
+ }
72
+ });
73
+ });
74
+ },
75
+ x509: {
76
+ CASignCSR(params, callback) {
77
+ native(params).then((outcome) => {
78
+ if ('result' in outcome) {
79
+ callback(false, { ...outcome.result, command: null, signedBy: 'native' });
80
+ return;
81
+ }
82
+ onFallback(outcome.fallback);
83
+ openssl.x509.CASignCSR(params, (err, result) => {
84
+ callback(err, result && { ...result, signedBy: 'openssl' });
85
+ });
86
+ }, (err) => {
87
+ callback(err instanceof Error ? err : new Error(message(err)), { command: null, data: null });
88
+ });
89
+ },
90
+ },
91
+ close() {
92
+ pkcs11.close();
93
+ },
94
+ };
95
+ }
96
+ //# sourceMappingURL=signer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signer.js","sourceRoot":"","sources":["../src/signer.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,2FAA2F;AAC3F,OAAO,WAAW,MAAM,oBAAoB,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAkB,MAAM,cAAc,CAAC;AAE/D,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAmDjD,MAAM,OAAO,GAAG,CAAC,GAAY,EAAE,EAAE,CAAC,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;AAE5F,gFAAgF;AAChF,MAAM,UAAU,YAAY,CAAC,WAA2B,EAAE;IACxD,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;IAC9F,MAAM,KAAK,GAAG,QAAQ,CAAC,YAAY,IAAI,KAAK,CAAC;IAC7C,MAAM,MAAM,GAAG,IAAI,cAAc,EAAE,CAAC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. Building a certificate, CRL or CSR only needs
3
+ * the issuer's public key and a signature over the to-be-signed bytes, so every key custody
4
+ * (software key, PKCS#11 token, Google Cloud KMS, OpenSSL fallback) is one implementation of this.
5
+ */
6
+ export interface SigningKey {
7
+ /** Where the key lives, e.g. 'software'; the allowlist is per backend. */
8
+ readonly backend: string;
9
+ /** The signature algorithm this key produces, e.g. 'sha256WithRSAEncryption', 'ecdsa-with-SHA384', 'ML-DSA-65'. */
10
+ readonly algorithm: string;
11
+ /** The public key as DER-encoded SubjectPublicKeyInfo. */
12
+ publicKey(): Promise<Uint8Array>;
13
+ /** Signs the DER-encoded to-be-signed structure and returns the signature value as it goes in the BIT STRING. */
14
+ sign(tbs: Uint8Array): Promise<Uint8Array>;
15
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=signing-key.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signing-key.js","sourceRoot":"","sources":["../src/signing-key.ts"],"names":[],"mappings":""}
@@ -0,0 +1,3 @@
1
+ import type { SigningKey } from './signing-key.ts';
2
+ /** A SigningKey for a PEM private key, encrypted or not, signing with `hash` (default sha256). */
3
+ export declare function softwareKey(pem: string, passphrase: string | undefined, hash?: string): SigningKey;