@authup/server-kit 1.0.0-beta.23 → 1.0.0-beta.24

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 (94) hide show
  1. package/dist/crypto/index.d.ts +3 -1
  2. package/dist/crypto/index.d.ts.map +1 -1
  3. package/dist/crypto/json-web-token/extract.d.ts +1 -1
  4. package/dist/crypto/json-web-token/extract.d.ts.map +1 -1
  5. package/dist/crypto/json-web-token/sign/module.d.ts +1 -1
  6. package/dist/crypto/json-web-token/sign/module.d.ts.map +1 -1
  7. package/dist/crypto/json-web-token/sign/types.d.ts +10 -5
  8. package/dist/crypto/json-web-token/sign/types.d.ts.map +1 -1
  9. package/dist/crypto/json-web-token/type.d.ts +1 -1
  10. package/dist/crypto/json-web-token/type.d.ts.map +1 -1
  11. package/dist/crypto/json-web-token/utils.d.ts +1 -1
  12. package/dist/crypto/json-web-token/utils.d.ts.map +1 -1
  13. package/dist/crypto/json-web-token/verify/module.d.ts +1 -1
  14. package/dist/crypto/json-web-token/verify/module.d.ts.map +1 -1
  15. package/dist/crypto/json-web-token/verify/types.d.ts +10 -5
  16. package/dist/crypto/json-web-token/verify/types.d.ts.map +1 -1
  17. package/dist/crypto/key/container.d.ts +14 -0
  18. package/dist/crypto/key/container.d.ts.map +1 -0
  19. package/dist/crypto/key/index.d.ts +3 -0
  20. package/dist/crypto/key/index.d.ts.map +1 -0
  21. package/dist/crypto/key/key-usages.d.ts +2 -0
  22. package/dist/crypto/key/key-usages.d.ts.map +1 -0
  23. package/dist/crypto/key/types.d.ts +14 -0
  24. package/dist/crypto/key/types.d.ts.map +1 -0
  25. package/dist/crypto/key-asymmetric/check.d.ts +3 -0
  26. package/dist/crypto/key-asymmetric/check.d.ts.map +1 -0
  27. package/dist/crypto/key-asymmetric/constants.d.ts +8 -0
  28. package/dist/crypto/key-asymmetric/constants.d.ts.map +1 -0
  29. package/dist/crypto/key-asymmetric/create.d.ts +3 -0
  30. package/dist/crypto/key-asymmetric/create.d.ts.map +1 -0
  31. package/dist/crypto/key-asymmetric/helpers/index.d.ts +2 -0
  32. package/dist/crypto/key-asymmetric/helpers/index.d.ts.map +1 -0
  33. package/dist/crypto/key-asymmetric/helpers/wrap.d.ts +5 -0
  34. package/dist/crypto/key-asymmetric/helpers/wrap.d.ts.map +1 -0
  35. package/dist/crypto/key-asymmetric/index.d.ts +8 -0
  36. package/dist/crypto/key-asymmetric/index.d.ts.map +1 -0
  37. package/dist/crypto/key-asymmetric/key-usages.d.ts +5 -0
  38. package/dist/crypto/key-asymmetric/key-usages.d.ts.map +1 -0
  39. package/dist/crypto/key-asymmetric/normalize.d.ts +4 -0
  40. package/dist/crypto/key-asymmetric/normalize.d.ts.map +1 -0
  41. package/dist/crypto/key-asymmetric/types.d.ts +30 -0
  42. package/dist/crypto/key-asymmetric/types.d.ts.map +1 -0
  43. package/dist/crypto/key-symmetric/check.d.ts +3 -0
  44. package/dist/crypto/key-symmetric/check.d.ts.map +1 -0
  45. package/dist/crypto/key-symmetric/constants.d.ts +7 -0
  46. package/dist/crypto/key-symmetric/constants.d.ts.map +1 -0
  47. package/dist/crypto/key-symmetric/create.d.ts +3 -0
  48. package/dist/crypto/key-symmetric/create.d.ts.map +1 -0
  49. package/dist/crypto/key-symmetric/index.d.ts +6 -0
  50. package/dist/crypto/key-symmetric/index.d.ts.map +1 -0
  51. package/dist/crypto/key-symmetric/key-usages.d.ts +2 -0
  52. package/dist/crypto/key-symmetric/key-usages.d.ts.map +1 -0
  53. package/dist/crypto/key-symmetric/normalize.d.ts +4 -0
  54. package/dist/crypto/key-symmetric/normalize.d.ts.map +1 -0
  55. package/dist/crypto/key-symmetric/types.d.ts +27 -0
  56. package/dist/crypto/key-symmetric/types.d.ts.map +1 -0
  57. package/dist/domain-event/module.d.ts +1 -1
  58. package/dist/domain-event/module.d.ts.map +1 -1
  59. package/dist/domain-event/type.d.ts +1 -1
  60. package/dist/domain-event/type.d.ts.map +1 -1
  61. package/dist/index.cjs +320 -293
  62. package/dist/index.cjs.map +1 -1
  63. package/dist/index.mjs +276 -231
  64. package/dist/index.mjs.map +1 -1
  65. package/dist/services/logger/module.d.ts.map +1 -1
  66. package/package.json +14 -8
  67. package/dist/crypto/key-pair/constants.d.ts +0 -5
  68. package/dist/crypto/key-pair/constants.d.ts.map +0 -1
  69. package/dist/crypto/key-pair/create.d.ts +0 -3
  70. package/dist/crypto/key-pair/create.d.ts.map +0 -1
  71. package/dist/crypto/key-pair/delete.d.ts +0 -3
  72. package/dist/crypto/key-pair/delete.d.ts.map +0 -1
  73. package/dist/crypto/key-pair/helpers/check.d.ts +0 -4
  74. package/dist/crypto/key-pair/helpers/check.d.ts.map +0 -1
  75. package/dist/crypto/key-pair/helpers/file-name.d.ts +0 -4
  76. package/dist/crypto/key-pair/helpers/file-name.d.ts.map +0 -1
  77. package/dist/crypto/key-pair/helpers/index.d.ts +0 -6
  78. package/dist/crypto/key-pair/helpers/index.d.ts.map +0 -1
  79. package/dist/crypto/key-pair/helpers/options.d.ts +0 -3
  80. package/dist/crypto/key-pair/helpers/options.d.ts.map +0 -1
  81. package/dist/crypto/key-pair/helpers/private-key.d.ts +0 -3
  82. package/dist/crypto/key-pair/helpers/private-key.d.ts.map +0 -1
  83. package/dist/crypto/key-pair/helpers/wrap.d.ts +0 -5
  84. package/dist/crypto/key-pair/helpers/wrap.d.ts.map +0 -1
  85. package/dist/crypto/key-pair/index.d.ts +0 -9
  86. package/dist/crypto/key-pair/index.d.ts.map +0 -1
  87. package/dist/crypto/key-pair/load.d.ts +0 -3
  88. package/dist/crypto/key-pair/load.d.ts.map +0 -1
  89. package/dist/crypto/key-pair/module.d.ts +0 -3
  90. package/dist/crypto/key-pair/module.d.ts.map +0 -1
  91. package/dist/crypto/key-pair/save.d.ts +0 -3
  92. package/dist/crypto/key-pair/save.d.ts.map +0 -1
  93. package/dist/crypto/key-pair/type.d.ts +0 -64
  94. package/dist/crypto/key-pair/type.d.ts.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,18 +1,18 @@
1
1
  import { compare as compare$1, hash as hash$1 } from '@node-rs/bcrypt';
2
- import { createPrivateKey, generateKeyPair, createPublicKey } from 'node:crypto';
3
- import { isObject, TokenError, JWTAlgorithm, JWKType, buildEventFullName } from '@authup/kit';
4
- import path from 'node:path';
5
- import fs from 'node:fs';
2
+ import { arrayBufferToBase64, base64ToArrayBuffer, isObject as isObject$1 } from '@authup/kit';
3
+ import { TokenError, JWTAlgorithm, JWKType } from '@authup/specs';
6
4
  import { Algorithm, sign, verify } from '@node-rs/jsonwebtoken';
7
- import { isObject as isObject$1 } from 'smob';
5
+ import { isObject } from 'smob';
8
6
  import { JsonAdapter, buildKeyPath } from 'redis-extension';
9
7
  export { Client as RedisClient, ClientOptions as RedisClientOptions, JsonAdapter as RedisJsonAdapter, Watcher as RedisWatcher, buildKeyPath as buildRedisKeyPath, createClient as createRedisClient, escapeKey as escapeRedisKey, parseKeyPath as parseRedisKeyPath } from 'redis-extension';
10
8
  import { singa } from 'singa';
11
9
  import TTLCache from '@isaacs/ttlcache';
12
- import * as process$1 from 'node:process';
10
+ import path from 'node:path';
11
+ import process from 'node:process';
13
12
  import { transports, createLogger as createLogger$1, format } from 'winston';
14
13
  export { Logger } from 'winston';
15
14
  export { VaultClient, createClient as createVaultClient } from '@hapic/vault';
15
+ import { buildEventFullName } from '@authup/core-realtime-kit';
16
16
  import { Emitter } from '@socket.io/redis-emitter';
17
17
 
18
18
  async function compare(value, hashedValue) {
@@ -28,103 +28,124 @@ async function hash(str, rounds = 10) {
28
28
  * Author Peter Placzek (tada5hi)
29
29
  * For the full copyright and license information,
30
30
  * view the LICENSE file that was distributed with this source code.
31
- */ var KeyPairKind = /*#__PURE__*/ function(KeyPairKind) {
32
- KeyPairKind["PRIVATE"] = "private";
33
- KeyPairKind["PUBLIC"] = "public";
34
- return KeyPairKind;
31
+ */ var CryptoAsymmetricAlgorithm = /*#__PURE__*/ function(CryptoAsymmetricAlgorithm) {
32
+ CryptoAsymmetricAlgorithm["RSA_PSS"] = "RSA-PSS";
33
+ CryptoAsymmetricAlgorithm["RSASSA_PKCS1_V1_5"] = "RSASSA-PKCS1-v1_5";
34
+ CryptoAsymmetricAlgorithm["RSA_OAEP"] = "RSA-OAEP";
35
+ CryptoAsymmetricAlgorithm["ECDSA"] = "ECDSA";
36
+ CryptoAsymmetricAlgorithm["ECDH"] = "ECDH";
37
+ return CryptoAsymmetricAlgorithm;
35
38
  }({});
36
39
 
37
- function isKeyPair(data) {
38
- return isObject(data) && typeof data.privateKey !== 'undefined' && typeof data.publicKey !== 'undefined';
39
- }
40
- function isKeyPairWithPublicKey(data) {
41
- return isObject(data) && typeof data.publicKey !== 'undefined';
40
+ function isAsymmetricAlgorithm(input) {
41
+ return Object.values(CryptoAsymmetricAlgorithm).indexOf(input) !== -1;
42
42
  }
43
43
 
44
- function extendKeyPairOptions(options) {
45
- var _options;
46
- options = options ?? {};
47
- options.directory = options.directory || process.cwd();
48
- options.directory = path.isAbsolute(options.directory) ? options.directory : path.resolve(process.cwd(), options.directory);
49
- (_options = options).type ?? (_options.type = 'rsa');
50
- if (options.type === 'rsa' || options.type === 'rsa-pss' || options.type === 'dsa') {
51
- options.modulusLength = 2048;
52
- }
53
- if (!options.privateKeyEncoding) {
54
- options.privateKeyEncoding = {
55
- type: 'pkcs8',
56
- format: 'pem'
57
- };
44
+ /**
45
+ * @see https://nodejs.org/api/webcrypto.html#cryptokeyusages
46
+ */ function getKeyUsagesForAsymmetricAlgorithm(name, format) {
47
+ if (name === CryptoAsymmetricAlgorithm.RSA_PSS || name === CryptoAsymmetricAlgorithm.ECDSA || name === CryptoAsymmetricAlgorithm.RSASSA_PKCS1_V1_5) {
48
+ if (format === 'spki') {
49
+ return [
50
+ 'verify'
51
+ ];
52
+ }
53
+ if (format === 'pkcs8') {
54
+ return [
55
+ 'sign'
56
+ ];
57
+ }
58
+ return [
59
+ 'sign',
60
+ 'verify'
61
+ ];
58
62
  }
59
- if (!options.publicKeyEncoding) {
60
- options.publicKeyEncoding = {
61
- type: 'spki',
62
- format: 'pem'
63
- };
63
+ if (name === CryptoAsymmetricAlgorithm.ECDH) {
64
+ if (format === 'spki') {
65
+ return [];
66
+ }
67
+ return [
68
+ 'deriveKey',
69
+ 'deriveBits'
70
+ ];
64
71
  }
65
- if (options.privateKeyEncoding.passphrase && !options.privateKeyEncoding.cipher) {
66
- options.privateKeyEncoding.cipher = 'aes-256-cbc';
72
+ if (name === CryptoAsymmetricAlgorithm.RSA_OAEP) {
73
+ if (format === 'spki') {
74
+ return [
75
+ 'encrypt'
76
+ ];
77
+ }
78
+ if (format === 'pkcs8') {
79
+ return [
80
+ 'decrypt'
81
+ ];
82
+ }
83
+ return [
84
+ 'encrypt',
85
+ 'decrypt'
86
+ ];
67
87
  }
68
- return options;
88
+ throw new SyntaxError(`Key usages can not be determined for asymmetric algorithm: ${name}`);
69
89
  }
70
90
 
71
- function buildKeyFileName(type, context) {
72
- const options = extendKeyPairOptions(context);
73
- const parts = [];
74
- switch(type){
75
- case KeyPairKind.PRIVATE:
91
+ function normalizeAsymmetricKeyPairCreateOptions(options) {
92
+ let optionsNormalized;
93
+ switch(options.name){
94
+ case CryptoAsymmetricAlgorithm.RSASSA_PKCS1_V1_5:
95
+ case CryptoAsymmetricAlgorithm.RSA_PSS:
96
+ case CryptoAsymmetricAlgorithm.RSA_OAEP:
76
97
  {
77
- if (options.privateName) {
78
- parts.push(options.privateName);
79
- } else {
80
- parts.push(type);
81
- }
82
- if (options.privateExtension) {
83
- if (options.privateExtension.startsWith('.')) {
84
- options.privateExtension = options.privateExtension.slice(1);
85
- }
86
- parts.push(options.privateExtension);
87
- } else {
88
- parts.push('pem');
89
- }
98
+ optionsNormalized = {
99
+ modulusLength: 2048,
100
+ publicExponent: new Uint8Array([
101
+ 0x01,
102
+ 0x00,
103
+ 0x01
104
+ ]),
105
+ hash: 'SHA-256',
106
+ ...options
107
+ };
90
108
  break;
91
109
  }
92
- case KeyPairKind.PUBLIC:
110
+ case CryptoAsymmetricAlgorithm.ECDSA:
111
+ case CryptoAsymmetricAlgorithm.ECDH:
93
112
  {
94
- if (options.publicName) {
95
- parts.push(options.publicName);
96
- } else {
97
- parts.push(type);
98
- }
99
- if (options.publicExtension) {
100
- if (options.publicExtension.startsWith('.')) {
101
- options.publicExtension = options.publicExtension.slice(1);
102
- }
103
- parts.push(options.publicExtension);
104
- } else {
105
- parts.push('pem');
106
- }
113
+ optionsNormalized = {
114
+ namedCurve: 'P-256',
115
+ ...options
116
+ };
117
+ }
118
+ }
119
+ return optionsNormalized;
120
+ }
121
+ function normalizeAsymmetricKeyImportOptions(options) {
122
+ let optionsNormalized;
123
+ switch(options.name){
124
+ case CryptoAsymmetricAlgorithm.RSASSA_PKCS1_V1_5:
125
+ case CryptoAsymmetricAlgorithm.RSA_PSS:
126
+ case CryptoAsymmetricAlgorithm.RSA_OAEP:
127
+ {
128
+ optionsNormalized = {
129
+ hash: 'SHA-256',
130
+ ...options
131
+ };
107
132
  break;
108
133
  }
134
+ case CryptoAsymmetricAlgorithm.ECDSA:
135
+ case CryptoAsymmetricAlgorithm.ECDH:
136
+ {
137
+ optionsNormalized = {
138
+ namedCurve: 'P-256',
139
+ ...options
140
+ };
141
+ }
109
142
  }
110
- return parts.join('.');
143
+ return optionsNormalized;
111
144
  }
112
145
 
113
- function decryptRSAPrivateKey(context, key) {
114
- const privateKey = createPrivateKey({
115
- type: context.privateKeyEncoding.type,
116
- format: context.privateKeyEncoding.format,
117
- key,
118
- passphrase: context.privateKeyEncoding.passphrase || context.passphrase
119
- });
120
- let content = privateKey.export({
121
- type: context.privateKeyEncoding.type,
122
- format: context.privateKeyEncoding.format
123
- });
124
- if (typeof content !== 'string') {
125
- content = Buffer.from(content).toString('utf-8');
126
- }
127
- return content;
146
+ async function createAsymmetricKeyPair(options) {
147
+ const optionsNormalized = normalizeAsymmetricKeyPairCreateOptions(options);
148
+ return crypto.subtle.generateKey(optionsNormalized, true, getKeyUsagesForAsymmetricAlgorithm(optionsNormalized.name));
128
149
  }
129
150
 
130
151
  /*
@@ -132,172 +153,169 @@ function decryptRSAPrivateKey(context, key) {
132
153
  * Author Peter Placzek (tada5hi)
133
154
  * For the full copyright and license information,
134
155
  * view the LICENSE file that was distributed with this source code.
135
- */ function wrapPem(type, input) {
136
- if (typeof input !== 'string') {
137
- input = Buffer.from(input).toString('base64');
138
- }
156
+ */ function enc(type, input) {
139
157
  return `-----BEGIN ${type}-----\n${input}\n-----END ${type}-----`;
140
158
  }
141
- function wrapPrivateKeyPem(input) {
142
- return wrapPem('PRIVATE KEY', input);
159
+ function encodePKCS8ToPEM(base64) {
160
+ return enc('PRIVATE KEY', base64);
143
161
  }
144
- function wrapPublicKeyPem(input) {
145
- return wrapPem('PUBLIC KEY', input);
162
+ function encodeSPKIToPem(input) {
163
+ return enc('PUBLIC KEY', input);
146
164
  }
147
165
  // ------------------------------------------------------------
148
- function unwrapPem(type, input) {
149
- if (typeof input !== 'string') {
150
- input = Buffer.from(input).toString('base64');
151
- }
166
+ function dec(type, input) {
152
167
  input = input.replace(`-----BEGIN ${type}-----\n`, '');
153
168
  input = input.replace(`\n-----END ${type}-----\n`, '');
154
169
  input = input.replace(`-----END ${type}-----\n`, '');
155
170
  input = input.replace(`\n-----END ${type}-----`, '');
156
171
  return input;
157
172
  }
158
- function unwrapPrivateKeyPem(input) {
159
- return unwrapPem('PRIVATE KEY', input);
173
+ function decodePemToPKCS8(input) {
174
+ return dec('PRIVATE KEY', input);
160
175
  }
161
- function unwrapPublicKeyPem(input) {
162
- return unwrapPem('PUBLIC KEY', input);
176
+ function decodePemToSpki(input) {
177
+ return dec('PUBLIC KEY', input);
163
178
  }
164
179
 
165
- async function saveKeyPair(keyPair, context) {
166
- context = extendKeyPairOptions(context);
167
- await fs.promises.mkdir(context.directory, {
168
- recursive: true
169
- });
170
- await Promise.all([
171
- {
172
- path: path.resolve(context.directory, buildKeyFileName(KeyPairKind.PRIVATE, context)),
173
- content: keyPair.privateKey
174
- },
175
- {
176
- path: path.resolve(context.directory, buildKeyFileName(KeyPairKind.PUBLIC, context)),
177
- content: keyPair.publicKey
178
- }
179
- ].map((file)=>fs.promises.writeFile(file.path, file.content)));
180
- return keyPair;
181
- }
182
-
183
- async function createKeyPair(context) {
184
- const options = extendKeyPairOptions(context);
185
- const keyPair = await new Promise((resolve, reject)=>{
186
- const callback = (err, publicKey, privateKey)=>{
187
- if (err) reject(err);
188
- resolve({
189
- privateKey,
190
- publicKey
191
- });
180
+ /*
181
+ * Copyright (c) 2024.
182
+ * Author Peter Placzek (tada5hi)
183
+ * For the full copyright and license information,
184
+ * view the LICENSE file that was distributed with this source code.
185
+ */ var SymmetricAlgorithm = /*#__PURE__*/ function(SymmetricAlgorithm) {
186
+ SymmetricAlgorithm["HMAC"] = "HMAC";
187
+ SymmetricAlgorithm["AES_CTR"] = "AES-CTR";
188
+ SymmetricAlgorithm["AES_CBC"] = "AES-CBC";
189
+ SymmetricAlgorithm["AES_GCM"] = "AES-GCM";
190
+ return SymmetricAlgorithm;
191
+ }({});
192
+
193
+ function normalizeSymmetricKeyCreateOptions(input) {
194
+ if (input.name === SymmetricAlgorithm.HMAC) {
195
+ return {
196
+ hash: 'SHA-256',
197
+ ...input
192
198
  };
193
- switch(options.type){
194
- case 'dsa':
195
- generateKeyPair(options.type, options, callback);
196
- break;
197
- case 'ec':
198
- generateKeyPair(options.type, options, callback);
199
- break;
200
- case 'rsa':
201
- generateKeyPair(options.type, options, callback);
202
- break;
203
- case 'rsa-pss':
204
- generateKeyPair(options.type, options, callback);
205
- break;
206
- }
207
- });
208
- if (options.save) {
209
- await saveKeyPair(keyPair, options);
210
199
  }
211
- if (options.passphrase || options.privateKeyEncoding.passphrase) {
212
- keyPair.privateKey = decryptRSAPrivateKey(options, keyPair.privateKey);
200
+ return {
201
+ length: 256,
202
+ name: input.name
203
+ };
204
+ }
205
+ function normalizeSymmetricKeyImportOptions(input) {
206
+ if (input.name === SymmetricAlgorithm.HMAC) {
207
+ return {
208
+ hash: 'SHA-256',
209
+ ...input
210
+ };
213
211
  }
214
- return keyPair;
212
+ return input;
215
213
  }
216
214
 
217
- async function deleteKeyPair(context) {
218
- const options = extendKeyPairOptions(context);
219
- const privateKeyPath = path.resolve(options.directory, buildKeyFileName(KeyPairKind.PRIVATE, options));
220
- const publicKeyPath = path.resolve(options.directory, buildKeyFileName(KeyPairKind.PUBLIC, options));
221
- try {
222
- await Promise.all([
223
- privateKeyPath,
224
- publicKeyPath
225
- ].map((filePath)=>fs.promises.stat(filePath)));
226
- } catch (e) {
227
- return;
215
+ function isSymmetricAlgorithm(input) {
216
+ return Object.values(SymmetricAlgorithm).indexOf(input) !== -1;
217
+ }
218
+
219
+ function getKeyUsagesForSymmetricAlgorithm(name) {
220
+ /**
221
+ * @see https://nodejs.org/api/webcrypto.html#cryptokeyusages
222
+ */ if (name === SymmetricAlgorithm.HMAC) {
223
+ return [
224
+ 'sign',
225
+ 'verify'
226
+ ];
228
227
  }
229
- await Promise.all([
230
- privateKeyPath,
231
- publicKeyPath
232
- ].map((filePath)=>fs.promises.rm(filePath)));
228
+ if (name === SymmetricAlgorithm.AES_CBC || name === SymmetricAlgorithm.AES_GCM || name === SymmetricAlgorithm.AES_CTR) {
229
+ return [
230
+ 'encrypt',
231
+ 'decrypt'
232
+ ];
233
+ }
234
+ throw new SyntaxError(`Key usages can not be determined for symmetric algorithm: ${name}`);
233
235
  }
234
236
 
235
- async function loadKeyPair(context) {
236
- const options = extendKeyPairOptions(context);
237
- const privateKeyPath = path.resolve(options.directory, buildKeyFileName(KeyPairKind.PRIVATE, options));
238
- try {
239
- await fs.promises.stat(privateKeyPath);
240
- } catch (e) {
241
- return undefined;
237
+ async function createSymmetricKey(input) {
238
+ const optionsNormalized = normalizeSymmetricKeyCreateOptions(input);
239
+ return crypto.subtle.generateKey(optionsNormalized, true, getKeyUsagesForSymmetricAlgorithm(optionsNormalized.name));
240
+ }
241
+
242
+ function getKeyUsagesForAlgorithm(name, format) {
243
+ if (isAsymmetricAlgorithm(name)) {
244
+ return getKeyUsagesForAsymmetricAlgorithm(name, format);
242
245
  }
243
- const privateKeyBuffer = await fs.promises.readFile(privateKeyPath);
244
- let privateKey = privateKeyBuffer.toString();
245
- if (options.passphrase || options.privateKeyEncoding.passphrase) {
246
- privateKey = decryptRSAPrivateKey(options, privateKey);
246
+ if (isSymmetricAlgorithm(name)) {
247
+ return getKeyUsagesForSymmetricAlgorithm(name);
247
248
  }
248
- const publicKeyPath = path.resolve(options.directory, buildKeyFileName(KeyPairKind.PUBLIC, options));
249
- let publicKey;
250
- try {
251
- await fs.promises.stat(publicKeyPath);
252
- const publicKeyBuffer = await fs.promises.readFile(publicKeyPath);
253
- publicKey = publicKeyBuffer.toString();
254
- } catch (e) {
255
- const publicKeyObject = createPublicKey({
256
- key: privateKey,
257
- format: options.privateKeyEncoding.format,
258
- type: options.publicKeyEncoding.type
259
- });
260
- const stringOrBuffer = publicKeyObject.export({
261
- format: options.publicKeyEncoding.format,
262
- type: options.publicKeyEncoding.type
263
- });
264
- if (typeof stringOrBuffer !== 'string') {
265
- publicKey = stringOrBuffer.toString();
266
- } else {
267
- publicKey = stringOrBuffer;
249
+ throw new SyntaxError(`Key usages can not be determined for algorithm: ${name}`);
250
+ }
251
+
252
+ class CryptoKeyContainer {
253
+ // ----------------------------------------------
254
+ async toArrayBuffer() {
255
+ if (this.key.type === 'private') {
256
+ return crypto.subtle.exportKey('pkcs8', this.key);
268
257
  }
269
- if (options.save) {
270
- await saveKeyPair({
271
- privateKey,
272
- publicKey
273
- }, options);
258
+ if (this.key.type === 'public') {
259
+ return crypto.subtle.exportKey('spki', this.key);
274
260
  }
261
+ return crypto.subtle.exportKey('raw', this.key);
275
262
  }
276
- return {
277
- privateKey,
278
- publicKey
279
- };
280
- }
281
-
282
- const keyPairCache = {};
283
- async function useKeyPair(value) {
284
- let options;
285
- if (typeof value === 'string') {
286
- options = extendKeyPairOptions({
287
- privateName: value
263
+ async toUint8Array() {
264
+ const arrayBuffer = await this.toArrayBuffer();
265
+ return new Uint8Array(arrayBuffer);
266
+ }
267
+ async toBase64() {
268
+ const arrayBuffer = await this.toArrayBuffer();
269
+ return arrayBufferToBase64(arrayBuffer);
270
+ }
271
+ async toPem() {
272
+ const base64 = await this.toBase64();
273
+ if (this.key.type === 'public') {
274
+ return encodeSPKIToPem(base64);
275
+ }
276
+ if (this.key.type === 'private') {
277
+ return encodePKCS8ToPEM(base64);
278
+ }
279
+ throw new Error('A symmetric key can not be encoded as PEM');
280
+ }
281
+ async toJWK() {
282
+ return crypto.subtle.exportKey('jwk', this.key);
283
+ }
284
+ // ----------------------------------------------
285
+ static async fromPem(ctx) {
286
+ if (ctx.format === 'pkcs8') {
287
+ return CryptoKeyContainer.fromBase64({
288
+ ...ctx,
289
+ key: decodePemToPKCS8(ctx.key)
290
+ });
291
+ }
292
+ return CryptoKeyContainer.fromBase64({
293
+ ...ctx,
294
+ key: decodePemToSpki(ctx.key)
288
295
  });
289
- } else {
290
- options = extendKeyPairOptions(value || {});
291
296
  }
292
- if (Object.prototype.hasOwnProperty.call(keyPairCache, options.privateName)) {
293
- return keyPairCache[options.privateName];
297
+ static async fromBase64(ctx) {
298
+ const arrayBuffer = base64ToArrayBuffer(ctx.key);
299
+ return CryptoKeyContainer.fromArrayBuffer({
300
+ ...ctx,
301
+ key: arrayBuffer
302
+ });
303
+ }
304
+ static async fromArrayBuffer(ctx) {
305
+ let normalizedOptions;
306
+ if (ctx.format === 'spki' || ctx.format === 'pkcs8') {
307
+ normalizedOptions = normalizeAsymmetricKeyImportOptions(ctx.options);
308
+ } else if (ctx.format === 'raw') {
309
+ normalizedOptions = normalizeSymmetricKeyImportOptions(ctx.options);
310
+ } else {
311
+ throw new SyntaxError(`Format ${ctx.format} is not supported.`);
312
+ }
313
+ const cryptoKey = await crypto.subtle.importKey(ctx.format, ctx.key, normalizedOptions, true, getKeyUsagesForAlgorithm(normalizedOptions.name, ctx.format));
314
+ return new CryptoKeyContainer(cryptoKey);
294
315
  }
295
- let keyPair = await loadKeyPair(options);
296
- if (typeof keyPair === 'undefined') {
297
- keyPair = await createKeyPair(options);
316
+ constructor(cryptoKey){
317
+ this.key = cryptoKey;
298
318
  }
299
- keyPairCache[options.privateName] = keyPair;
300
- return keyPair;
301
319
  }
302
320
 
303
321
  /**
@@ -346,7 +364,7 @@ function extractTokenPayload(token) {
346
364
  }
347
365
 
348
366
  function createErrorForJWTError(e) {
349
- if (isObject$1(e)) {
367
+ if (isObject(e)) {
350
368
  if (typeof e.name === 'string') {
351
369
  switch(e.name){
352
370
  case 'TokenExpiredError':
@@ -454,14 +472,20 @@ async function signToken(claims, context) {
454
472
  case JWKType.RSA:
455
473
  case JWKType.EC:
456
474
  {
457
- const { privateKey } = isKeyPair(context.keyPair) ? context.keyPair : await useKeyPair(context.keyPair);
458
475
  let algorithm;
476
+ let key;
477
+ if (typeof context.key === 'string') {
478
+ key = encodePKCS8ToPEM(context.key);
479
+ } else {
480
+ const keyContainer = new CryptoKeyContainer(context.key);
481
+ key = await keyContainer.toPem();
482
+ }
459
483
  if (context.type === JWKType.RSA) {
460
484
  algorithm = context.algorithm ? transformJWTAlgorithmToInternal(context.algorithm) : Algorithm.RS256;
461
485
  } else {
462
486
  algorithm = context.algorithm ? transformJWTAlgorithmToInternal(context.algorithm) : Algorithm.ES256;
463
487
  }
464
- return sign(claims, privateKey, {
488
+ return sign(claims, key, {
465
489
  algorithm,
466
490
  keyId: context.keyId
467
491
  });
@@ -469,7 +493,14 @@ async function signToken(claims, context) {
469
493
  case JWKType.OCT:
470
494
  {
471
495
  const algorithm = context.algorithm ? transformJWTAlgorithmToInternal(context.algorithm) : Algorithm.HS256;
472
- return sign(claims, context.key, {
496
+ let key;
497
+ if (typeof context.key === 'string') {
498
+ key = context.key;
499
+ } else {
500
+ const keyContainer = new CryptoKeyContainer(context.key);
501
+ key = await keyContainer.toUint8Array();
502
+ }
503
+ return sign(claims, key, {
473
504
  algorithm,
474
505
  keyId: context.keyId
475
506
  });
@@ -493,7 +524,6 @@ async function signToken(claims, context) {
493
524
  case JWKType.RSA:
494
525
  case JWKType.EC:
495
526
  {
496
- const { publicKey } = isKeyPairWithPublicKey(context.keyPair) ? context.keyPair : await useKeyPair(context.keyPair);
497
527
  let algorithms;
498
528
  if (context.type === JWKType.RSA) {
499
529
  algorithms = context.algorithms ? context.algorithms.map((algorithm)=>transformJWTAlgorithmToInternal(algorithm)) : [
@@ -510,7 +540,14 @@ async function signToken(claims, context) {
510
540
  Algorithm.ES384
511
541
  ];
512
542
  }
513
- promise = verify(token, publicKey, {
543
+ let key;
544
+ if (typeof context.key === 'string') {
545
+ key = encodeSPKIToPem(context.key);
546
+ } else {
547
+ const keyContainer = new CryptoKeyContainer(context.key);
548
+ key = await keyContainer.toPem();
549
+ }
550
+ promise = verify(token, key, {
514
551
  algorithms,
515
552
  validateNbf: true
516
553
  });
@@ -523,7 +560,14 @@ async function signToken(claims, context) {
523
560
  Algorithm.HS384,
524
561
  Algorithm.HS512
525
562
  ];
526
- promise = verify(token, context.key, {
563
+ let key;
564
+ if (typeof context.key === 'string') {
565
+ key = context.key;
566
+ } else {
567
+ const keyContainer = new CryptoKeyContainer(context.key);
568
+ key = await keyContainer.toUint8Array();
569
+ }
570
+ promise = verify(token, key, {
527
571
  algorithms,
528
572
  validateNbf: true
529
573
  });
@@ -689,14 +733,14 @@ function useCache() {
689
733
 
690
734
  function createLogger(context) {
691
735
  let items;
692
- const cwd = context.directory || process$1.cwd();
736
+ const cwd = context.directory || process.cwd();
693
737
  if (context.env === 'production') {
694
738
  items = [
695
739
  new transports.Console({
696
740
  level: 'info'
697
741
  }),
698
742
  new transports.File({
699
- filename: path.join(cwd, 'access.log'),
743
+ filename: path.join(cwd, 'http.log'),
700
744
  level: 'http',
701
745
  maxsize: 10 * 1024 * 1024,
702
746
  maxFiles: 5
@@ -715,6 +759,7 @@ function createLogger(context) {
715
759
  })
716
760
  ];
717
761
  }
762
+ // @see https://github.com/winstonjs/triple-beam/blob/master/config/npm.js
718
763
  return createLogger$1({
719
764
  format: format.combine(format.errors({
720
765
  stack: true
@@ -753,7 +798,7 @@ function useVaultClient() {
753
798
  }
754
799
 
755
800
  function transformDomainEventData(input) {
756
- if (isObject(input)) {
801
+ if (isObject$1(input)) {
757
802
  const keys = Object.keys(input);
758
803
  for(let i = 0; i < keys.length; i++){
759
804
  const value = input[keys[i]];
@@ -857,5 +902,5 @@ class DomainEventPublisher {
857
902
  return Object.prototype.hasOwnProperty.call(obj, prop);
858
903
  }
859
904
 
860
- export { Cache, DomainEventPublisher, DomainEventRedisPublisher, DomainEventSocketPublisher, KeyPairKind, MemoryCacheAdapter, RedisCacheAdapter, buildCacheKey, buildKeyFileName, compare, createCacheAdapter, createKeyPair, createLogger, decryptRSAPrivateKey, deleteKeyPair, extendKeyPairOptions, extractTokenHeader, extractTokenPayload, hasOwnProperty, hash, isKeyPair, isKeyPairWithPublicKey, isLoggerUsable, isRedisClientUsable, isVaultClientUsable, loadKeyPair, saveKeyPair, setLogger, setLoggerFactory, setRedisClient, setRedisFactory, setVaultFactory, signToken, unwrapPrivateKeyPem, unwrapPublicKeyPem, useCache, useKeyPair, useLogger, useRedisClient, useVaultClient, verifyToken, wrapPrivateKeyPem, wrapPublicKeyPem };
905
+ export { Cache, CryptoAsymmetricAlgorithm, CryptoKeyContainer, DomainEventPublisher, DomainEventRedisPublisher, DomainEventSocketPublisher, MemoryCacheAdapter, RedisCacheAdapter, SymmetricAlgorithm, buildCacheKey, compare, createAsymmetricKeyPair, createCacheAdapter, createLogger, createSymmetricKey, decodePemToPKCS8, decodePemToSpki, encodePKCS8ToPEM, encodeSPKIToPem, extractTokenHeader, extractTokenPayload, getKeyUsagesForAlgorithm, getKeyUsagesForAsymmetricAlgorithm, getKeyUsagesForSymmetricAlgorithm, hasOwnProperty, hash, isAsymmetricAlgorithm, isLoggerUsable, isRedisClientUsable, isSymmetricAlgorithm, isVaultClientUsable, normalizeAsymmetricKeyImportOptions, normalizeAsymmetricKeyPairCreateOptions, setLogger, setLoggerFactory, setRedisClient, setRedisFactory, setVaultFactory, signToken, useCache, useLogger, useRedisClient, useVaultClient, verifyToken };
861
906
  //# sourceMappingURL=index.mjs.map