@authup/server-core 0.29.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 (127) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +23 -0
  3. package/dist/config/index.d.ts +4 -0
  4. package/dist/config/index.d.ts.map +1 -0
  5. package/dist/config/read.d.ts +3 -0
  6. package/dist/config/read.d.ts.map +1 -0
  7. package/dist/config/type.d.ts +5 -0
  8. package/dist/config/type.d.ts.map +1 -0
  9. package/dist/config/utils.d.ts +2 -0
  10. package/dist/config/utils.d.ts.map +1 -0
  11. package/dist/crypto/hash/compare.d.ts +2 -0
  12. package/dist/crypto/hash/compare.d.ts.map +1 -0
  13. package/dist/crypto/hash/hash.d.ts +2 -0
  14. package/dist/crypto/hash/hash.d.ts.map +1 -0
  15. package/dist/crypto/hash/index.d.ts +3 -0
  16. package/dist/crypto/hash/index.d.ts.map +1 -0
  17. package/dist/crypto/index.d.ts +4 -0
  18. package/dist/crypto/index.d.ts.map +1 -0
  19. package/dist/crypto/json-web-token/decode.d.ts +15 -0
  20. package/dist/crypto/json-web-token/decode.d.ts.map +1 -0
  21. package/dist/crypto/json-web-token/index.d.ts +5 -0
  22. package/dist/crypto/json-web-token/index.d.ts.map +1 -0
  23. package/dist/crypto/json-web-token/sign.d.ts +4 -0
  24. package/dist/crypto/json-web-token/sign.d.ts.map +1 -0
  25. package/dist/crypto/json-web-token/type.d.ts +32 -0
  26. package/dist/crypto/json-web-token/type.d.ts.map +1 -0
  27. package/dist/crypto/json-web-token/utils.d.ts +2 -0
  28. package/dist/crypto/json-web-token/utils.d.ts.map +1 -0
  29. package/dist/crypto/json-web-token/verify.d.ts +15 -0
  30. package/dist/crypto/json-web-token/verify.d.ts.map +1 -0
  31. package/dist/crypto/key-pair/constants.d.ts +5 -0
  32. package/dist/crypto/key-pair/constants.d.ts.map +1 -0
  33. package/dist/crypto/key-pair/create.d.ts +3 -0
  34. package/dist/crypto/key-pair/create.d.ts.map +1 -0
  35. package/dist/crypto/key-pair/delete.d.ts +3 -0
  36. package/dist/crypto/key-pair/delete.d.ts.map +1 -0
  37. package/dist/crypto/key-pair/index.d.ts +9 -0
  38. package/dist/crypto/key-pair/index.d.ts.map +1 -0
  39. package/dist/crypto/key-pair/load.d.ts +3 -0
  40. package/dist/crypto/key-pair/load.d.ts.map +1 -0
  41. package/dist/crypto/key-pair/module.d.ts +3 -0
  42. package/dist/crypto/key-pair/module.d.ts.map +1 -0
  43. package/dist/crypto/key-pair/save.d.ts +3 -0
  44. package/dist/crypto/key-pair/save.d.ts.map +1 -0
  45. package/dist/crypto/key-pair/type.d.ts +65 -0
  46. package/dist/crypto/key-pair/type.d.ts.map +1 -0
  47. package/dist/crypto/key-pair/utils/check.d.ts +3 -0
  48. package/dist/crypto/key-pair/utils/check.d.ts.map +1 -0
  49. package/dist/crypto/key-pair/utils/file-name.d.ts +4 -0
  50. package/dist/crypto/key-pair/utils/file-name.d.ts.map +1 -0
  51. package/dist/crypto/key-pair/utils/index.d.ts +5 -0
  52. package/dist/crypto/key-pair/utils/index.d.ts.map +1 -0
  53. package/dist/crypto/key-pair/utils/options.d.ts +3 -0
  54. package/dist/crypto/key-pair/utils/options.d.ts.map +1 -0
  55. package/dist/crypto/key-pair/utils/private-key.d.ts +4 -0
  56. package/dist/crypto/key-pair/utils/private-key.d.ts.map +1 -0
  57. package/dist/domain-event/index.d.ts +5 -0
  58. package/dist/domain-event/index.d.ts.map +1 -0
  59. package/dist/domain-event/publish.d.ts +4 -0
  60. package/dist/domain-event/publish.d.ts.map +1 -0
  61. package/dist/domain-event/redis/index.d.ts +2 -0
  62. package/dist/domain-event/redis/index.d.ts.map +1 -0
  63. package/dist/domain-event/redis/publish.d.ts +4 -0
  64. package/dist/domain-event/redis/publish.d.ts.map +1 -0
  65. package/dist/domain-event/socket/index.d.ts +3 -0
  66. package/dist/domain-event/socket/index.d.ts.map +1 -0
  67. package/dist/domain-event/socket/publish.d.ts +4 -0
  68. package/dist/domain-event/socket/publish.d.ts.map +1 -0
  69. package/dist/domain-event/socket/singleton.d.ts +4 -0
  70. package/dist/domain-event/socket/singleton.d.ts.map +1 -0
  71. package/dist/domain-event/socket/type.d.ts +5 -0
  72. package/dist/domain-event/socket/type.d.ts.map +1 -0
  73. package/dist/domain-event/type.d.ts +7 -0
  74. package/dist/domain-event/type.d.ts.map +1 -0
  75. package/dist/domain-event/utils.d.ts +4 -0
  76. package/dist/domain-event/utils.d.ts.map +1 -0
  77. package/dist/domains/index.d.ts +2 -0
  78. package/dist/domains/index.d.ts.map +1 -0
  79. package/dist/domains/robot/index.d.ts +2 -0
  80. package/dist/domains/robot/index.d.ts.map +1 -0
  81. package/dist/domains/robot/vault.d.ts +5 -0
  82. package/dist/domains/robot/vault.d.ts.map +1 -0
  83. package/dist/index.cjs +873 -0
  84. package/dist/index.cjs.map +1 -0
  85. package/dist/index.d.ts +10 -0
  86. package/dist/index.d.ts.map +1 -0
  87. package/dist/index.mjs +831 -0
  88. package/dist/index.mjs.map +1 -0
  89. package/dist/logger/index.d.ts +4 -0
  90. package/dist/logger/index.d.ts.map +1 -0
  91. package/dist/logger/module.d.ts +4 -0
  92. package/dist/logger/module.d.ts.map +1 -0
  93. package/dist/logger/presets/index.d.ts +2 -0
  94. package/dist/logger/presets/index.d.ts.map +1 -0
  95. package/dist/logger/presets/void.d.ts +16 -0
  96. package/dist/logger/presets/void.d.ts.map +1 -0
  97. package/dist/logger/type.d.ts +14 -0
  98. package/dist/logger/type.d.ts.map +1 -0
  99. package/dist/proxy/index.d.ts +3 -0
  100. package/dist/proxy/index.d.ts.map +1 -0
  101. package/dist/proxy/module.d.ts +24 -0
  102. package/dist/proxy/module.d.ts.map +1 -0
  103. package/dist/proxy/utils.d.ts +3 -0
  104. package/dist/proxy/utils.d.ts.map +1 -0
  105. package/dist/smtp/config/index.d.ts +2 -0
  106. package/dist/smtp/config/index.d.ts.map +1 -0
  107. package/dist/smtp/config/singleton.d.ts +5 -0
  108. package/dist/smtp/config/singleton.d.ts.map +1 -0
  109. package/dist/smtp/index.d.ts +5 -0
  110. package/dist/smtp/index.d.ts.map +1 -0
  111. package/dist/smtp/module.d.ts +4 -0
  112. package/dist/smtp/module.d.ts.map +1 -0
  113. package/dist/smtp/singleton.d.ts +3 -0
  114. package/dist/smtp/singleton.d.ts.map +1 -0
  115. package/dist/smtp/type.d.ts +14 -0
  116. package/dist/smtp/type.d.ts.map +1 -0
  117. package/dist/utils/env.d.ts +7 -0
  118. package/dist/utils/env.d.ts.map +1 -0
  119. package/dist/utils/has-property.d.ts +2 -0
  120. package/dist/utils/has-property.d.ts.map +1 -0
  121. package/dist/utils/index.d.ts +3 -0
  122. package/dist/utils/index.d.ts.map +1 -0
  123. package/dist/vault/index.d.ts +2 -0
  124. package/dist/vault/index.d.ts.map +1 -0
  125. package/dist/vault/module.d.ts +4 -0
  126. package/dist/vault/module.d.ts.map +1 -0
  127. package/package.json +79 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,831 @@
1
+ import { hasOwnProperty as hasOwnProperty$1, isObject, TokenError, KeyType, DomainEventName, buildDomainEventFullName, parseProxyConnectionString } from '@authup/core';
2
+ import { locateMany, load, getModuleExport } from 'locter';
3
+ import path from 'node:path';
4
+ import process$1 from 'node:process';
5
+ import { merge } from 'smob';
6
+ import { compare as compare$1, hash as hash$1 } from 'bcrypt';
7
+ import { createPrivateKey, generateKeyPair, createPublicKey } from 'node:crypto';
8
+ import fs from 'node:fs';
9
+ import { decode, sign, verify } from 'jsonwebtoken';
10
+ import { hasClient, hasConfig, useClient } from 'redis-extension';
11
+ import { Emitter } from '@socket.io/redis-emitter';
12
+ import { hasConfig as hasConfig$1, useClient as useClient$1, hasClient as hasClient$1, unsetClient, setConfig } from '@hapic/vault';
13
+ import http from 'node:http';
14
+ import https from 'node:https';
15
+ import { getProxyForUrl } from 'proxy-from-env';
16
+ import { createTransport, createTestAccount } from 'nodemailer';
17
+
18
+ function hasProcessEnv(key) {
19
+ const keys = Array.isArray(key) ? key : [
20
+ key
21
+ ];
22
+ for(let i = 0; i < keys.length; i++){
23
+ if (hasOwnProperty$1(process$1.env, keys[i])) {
24
+ return true;
25
+ }
26
+ }
27
+ return false;
28
+ }
29
+ function readFromProcessEnv(key, alt) {
30
+ const keys = Array.isArray(key) ? key : [
31
+ key
32
+ ];
33
+ for(let i = 0; i < keys.length; i++){
34
+ if (hasOwnProperty$1(process$1.env, keys[i])) {
35
+ return process$1.env[keys[i]];
36
+ }
37
+ }
38
+ return alt;
39
+ }
40
+ function readBoolFromProcessEnv(key, alt) {
41
+ const keys = Array.isArray(key) ? key : [
42
+ key
43
+ ];
44
+ for(let i = 0; i < keys.length; i++){
45
+ const value = readFromProcessEnv(keys[i], alt);
46
+ switch(value){
47
+ case true:
48
+ case 'true':
49
+ case 't':
50
+ case '1':
51
+ return true;
52
+ case false:
53
+ case 'false':
54
+ case 'f':
55
+ case '0':
56
+ return false;
57
+ }
58
+ }
59
+ return alt;
60
+ }
61
+ function readBoolOrStringFromProcessEnv(key, alt) {
62
+ if (hasProcessEnv(key)) {
63
+ const value = readBoolFromProcessEnv(key, undefined);
64
+ if (typeof value === 'undefined') {
65
+ return readFromProcessEnv(key, alt);
66
+ }
67
+ return value;
68
+ }
69
+ return alt;
70
+ }
71
+ function readIntFromProcessEnv(key, alt) {
72
+ const keys = Array.isArray(key) ? key : [
73
+ key
74
+ ];
75
+ for(let i = 0; i < keys.length; i++){
76
+ const value = readFromProcessEnv(keys[i], alt);
77
+ const intValue = parseInt(`${value}`, 10);
78
+ if (!Number.isNaN(intValue)) {
79
+ return intValue;
80
+ }
81
+ }
82
+ return alt;
83
+ }
84
+
85
+ /*
86
+ * Copyright (c) 2022.
87
+ * Author Peter Placzek (tada5hi)
88
+ * For the full copyright and license information,
89
+ * view the LICENSE file that was distributed with this source code.
90
+ */ function hasOwnProperty(obj, prop) {
91
+ return Object.prototype.hasOwnProperty.call(obj, prop);
92
+ }
93
+
94
+ function buildWorkingDirectoryPathsForConfigFile() {
95
+ const cwd = [
96
+ process$1.cwd()
97
+ ];
98
+ if (hasProcessEnv('WRITABLE_DIRECTORY_PATH')) {
99
+ let writableDirectoryPath = readFromProcessEnv('WRITABLE_DIRECTORY_PATH');
100
+ if (!path.isAbsolute(writableDirectoryPath)) {
101
+ writableDirectoryPath = path.join(process$1.cwd(), writableDirectoryPath);
102
+ }
103
+ cwd.push(writableDirectoryPath);
104
+ } else {
105
+ cwd.push(path.join(process$1.cwd(), 'writable'));
106
+ }
107
+ return cwd;
108
+ }
109
+
110
+ async function readConfigFile(context) {
111
+ context = context || {};
112
+ const cwd = [];
113
+ if (context.cwd) {
114
+ const arr = Array.isArray(context.cwd) ? context.cwd : [
115
+ context.cwd
116
+ ];
117
+ for(let i = 0; i < arr.length; i++){
118
+ if (path.isAbsolute(arr[i])) {
119
+ cwd.push(arr[i]);
120
+ } else {
121
+ cwd.push(path.join(process$1.cwd(), arr[i]));
122
+ }
123
+ }
124
+ }
125
+ if (cwd.length === 0) {
126
+ cwd.push(...buildWorkingDirectoryPathsForConfigFile());
127
+ }
128
+ const locations = await locateMany([
129
+ 'authup.*.{conf,js,mjs,cjs,ts,mts,mts}',
130
+ 'authup.{conf,js,mjs,cjs,ts,mts,mts}'
131
+ ], {
132
+ path: cwd
133
+ });
134
+ const content = {};
135
+ for(let i = 0; i < locations.length; i++){
136
+ const file = await load(locations[i]);
137
+ const fileExport = getModuleExport(file);
138
+ if (!isObject(fileExport.value)) {
139
+ continue;
140
+ }
141
+ const [root, name] = locations[i].name.split('.');
142
+ if (root && name) {
143
+ if (context.name === name) {
144
+ merge(content, fileExport.value);
145
+ } else if (!context.name) {
146
+ content[name] = content[name] || {};
147
+ merge(content[name], fileExport.value);
148
+ }
149
+ }
150
+ if (root && !name) {
151
+ if (context.name) {
152
+ if (isObject(fileExport.value[context.name])) {
153
+ merge(content, fileExport.value[context.name]);
154
+ }
155
+ } else {
156
+ merge(content, fileExport.value);
157
+ }
158
+ }
159
+ }
160
+ return content;
161
+ }
162
+
163
+ async function compare(value, hashedValue) {
164
+ return compare$1(value, hashedValue);
165
+ }
166
+
167
+ async function hash(str, saltOrRounds = 10) {
168
+ return hash$1(str, saltOrRounds);
169
+ }
170
+
171
+ /*
172
+ * Copyright (c) 2022.
173
+ * Author Peter Placzek (tada5hi)
174
+ * For the full copyright and license information,
175
+ * view the LICENSE file that was distributed with this source code.
176
+ */ var KeyPairKind;
177
+ (function(KeyPairKind) {
178
+ KeyPairKind["PRIVATE"] = 'private';
179
+ KeyPairKind["PUBLIC"] = 'public';
180
+ })(KeyPairKind || (KeyPairKind = {}));
181
+
182
+ function isKeyPair(data) {
183
+ return typeof data === 'object' && data !== null && hasOwnProperty$1(data, 'privateKey') && hasOwnProperty$1(data, 'publicKey');
184
+ }
185
+
186
+ function extendKeyPairOptions(options) {
187
+ var _options;
188
+ options = options ?? {};
189
+ options.directory = options.directory || process.cwd();
190
+ options.directory = path.isAbsolute(options.directory) ? options.directory : path.resolve(process.cwd(), options.directory);
191
+ (_options = options).type ?? (_options.type = 'rsa');
192
+ if (options.type === 'rsa' || options.type === 'rsa-pss' || options.type === 'dsa') {
193
+ options.modulusLength = 2048;
194
+ }
195
+ if (!options.privateKeyEncoding) {
196
+ options.privateKeyEncoding = {
197
+ type: 'pkcs8',
198
+ format: 'pem'
199
+ };
200
+ }
201
+ if (!options.publicKeyEncoding) {
202
+ options.publicKeyEncoding = {
203
+ type: 'spki',
204
+ format: 'pem'
205
+ };
206
+ }
207
+ if (options.privateKeyEncoding.passphrase && !options.privateKeyEncoding.cipher) {
208
+ options.privateKeyEncoding.cipher = 'aes-256-cbc';
209
+ }
210
+ return options;
211
+ }
212
+
213
+ function buildKeyFileName(type, context) {
214
+ const options = extendKeyPairOptions(context);
215
+ const parts = [];
216
+ switch(type){
217
+ case KeyPairKind.PRIVATE:
218
+ {
219
+ if (options.privateName) {
220
+ parts.push(options.privateName);
221
+ } else {
222
+ parts.push(type);
223
+ }
224
+ if (options.privateExtension) {
225
+ if (options.privateExtension.startsWith('.')) {
226
+ options.privateExtension = options.privateExtension.slice(1);
227
+ }
228
+ parts.push(options.privateExtension);
229
+ } else {
230
+ parts.push('pem');
231
+ }
232
+ break;
233
+ }
234
+ case KeyPairKind.PUBLIC:
235
+ {
236
+ if (options.publicName) {
237
+ parts.push(options.publicName);
238
+ } else {
239
+ parts.push(type);
240
+ }
241
+ if (options.publicExtension) {
242
+ if (options.publicExtension.startsWith('.')) {
243
+ options.publicExtension = options.publicExtension.slice(1);
244
+ }
245
+ parts.push(options.publicExtension);
246
+ } else {
247
+ parts.push('pem');
248
+ }
249
+ break;
250
+ }
251
+ }
252
+ return parts.join('.');
253
+ }
254
+
255
+ function decryptRSAPrivateKey(context, key) {
256
+ const privateKey = createPrivateKey({
257
+ type: context.privateKeyEncoding.type,
258
+ format: context.privateKeyEncoding.format,
259
+ key,
260
+ passphrase: context.privateKeyEncoding.passphrase || context.passphrase
261
+ });
262
+ let content = privateKey.export({
263
+ type: context.privateKeyEncoding.type,
264
+ format: context.privateKeyEncoding.format
265
+ });
266
+ if (typeof content !== 'string') {
267
+ content = Buffer.from(content).toString('utf-8');
268
+ }
269
+ return content;
270
+ }
271
+
272
+ async function saveKeyPair(keyPair, context) {
273
+ context = extendKeyPairOptions(context);
274
+ await fs.promises.mkdir(context.directory, {
275
+ recursive: true
276
+ });
277
+ await Promise.all([
278
+ {
279
+ path: path.resolve(context.directory, buildKeyFileName(KeyPairKind.PRIVATE, context)),
280
+ content: keyPair.privateKey
281
+ },
282
+ {
283
+ path: path.resolve(context.directory, buildKeyFileName(KeyPairKind.PUBLIC, context)),
284
+ content: keyPair.publicKey
285
+ }
286
+ ].map((file)=>fs.promises.writeFile(file.path, file.content)));
287
+ return keyPair;
288
+ }
289
+
290
+ async function createKeyPair(context) {
291
+ const options = extendKeyPairOptions(context);
292
+ const keyPair = await new Promise((resolve, reject)=>{
293
+ const callback = (err, publicKey, privateKey)=>{
294
+ if (err) reject(err);
295
+ resolve({
296
+ privateKey,
297
+ publicKey
298
+ });
299
+ };
300
+ switch(options.type){
301
+ case 'dsa':
302
+ generateKeyPair(options.type, options, callback);
303
+ break;
304
+ case 'ec':
305
+ generateKeyPair(options.type, options, callback);
306
+ break;
307
+ case 'rsa':
308
+ generateKeyPair(options.type, options, callback);
309
+ break;
310
+ case 'rsa-pss':
311
+ generateKeyPair(options.type, options, callback);
312
+ break;
313
+ }
314
+ });
315
+ if (options.save) {
316
+ await saveKeyPair(keyPair, options);
317
+ }
318
+ if (options.passphrase || options.privateKeyEncoding.passphrase) {
319
+ keyPair.privateKey = decryptRSAPrivateKey(options, keyPair.privateKey);
320
+ }
321
+ return keyPair;
322
+ }
323
+
324
+ async function deleteKeyPair(context) {
325
+ const options = extendKeyPairOptions(context);
326
+ const privateKeyPath = path.resolve(options.directory, buildKeyFileName(KeyPairKind.PRIVATE, options));
327
+ const publicKeyPath = path.resolve(options.directory, buildKeyFileName(KeyPairKind.PUBLIC, options));
328
+ try {
329
+ await Promise.all([
330
+ privateKeyPath,
331
+ publicKeyPath
332
+ ].map((filePath)=>fs.promises.stat(filePath)));
333
+ } catch (e) {
334
+ return;
335
+ }
336
+ await Promise.all([
337
+ privateKeyPath,
338
+ publicKeyPath
339
+ ].map((filePath)=>fs.promises.rm(filePath)));
340
+ }
341
+
342
+ async function loadKeyPair(context) {
343
+ const options = extendKeyPairOptions(context);
344
+ const privateKeyPath = path.resolve(options.directory, buildKeyFileName(KeyPairKind.PRIVATE, options));
345
+ try {
346
+ await fs.promises.stat(privateKeyPath);
347
+ } catch (e) {
348
+ return undefined;
349
+ }
350
+ const privateKeyBuffer = await fs.promises.readFile(privateKeyPath);
351
+ let privateKey = privateKeyBuffer.toString();
352
+ if (options.passphrase || options.privateKeyEncoding.passphrase) {
353
+ privateKey = decryptRSAPrivateKey(options, privateKey);
354
+ }
355
+ const publicKeyPath = path.resolve(options.directory, buildKeyFileName(KeyPairKind.PUBLIC, options));
356
+ let publicKey;
357
+ try {
358
+ await fs.promises.stat(publicKeyPath);
359
+ const publicKeyBuffer = await fs.promises.readFile(publicKeyPath);
360
+ publicKey = publicKeyBuffer.toString();
361
+ } catch (e) {
362
+ const publicKeyObject = createPublicKey({
363
+ key: privateKey,
364
+ format: options.privateKeyEncoding.format,
365
+ type: options.publicKeyEncoding.type
366
+ });
367
+ const stringOrBuffer = publicKeyObject.export({
368
+ format: options.publicKeyEncoding.format,
369
+ type: options.publicKeyEncoding.type
370
+ });
371
+ if (typeof stringOrBuffer !== 'string') {
372
+ publicKey = stringOrBuffer.toString();
373
+ } else {
374
+ publicKey = stringOrBuffer;
375
+ }
376
+ if (options.save) {
377
+ await saveKeyPair({
378
+ privateKey,
379
+ publicKey
380
+ }, options);
381
+ }
382
+ }
383
+ return {
384
+ privateKey,
385
+ publicKey
386
+ };
387
+ }
388
+
389
+ const keyPairCache = {};
390
+ async function useKeyPair(value) {
391
+ let options;
392
+ if (typeof value === 'string') {
393
+ options = extendKeyPairOptions({
394
+ privateName: value
395
+ });
396
+ } else {
397
+ options = extendKeyPairOptions(value || {});
398
+ }
399
+ if (Object.prototype.hasOwnProperty.call(keyPairCache, options.privateName)) {
400
+ return keyPairCache[options.privateName];
401
+ }
402
+ let keyPair = await loadKeyPair(options);
403
+ if (typeof keyPair === 'undefined') {
404
+ keyPair = await createKeyPair(options);
405
+ }
406
+ keyPairCache[options.privateName] = keyPair;
407
+ return keyPair;
408
+ }
409
+
410
+ function handleJWTError(e) {
411
+ if (e && typeof e === 'object' && hasOwnProperty$1(e, 'name')) {
412
+ switch(e.name){
413
+ case 'TokenExpiredError':
414
+ throw TokenError.expired();
415
+ case 'NotBeforeError':
416
+ {
417
+ if (hasOwnProperty$1(e, 'date') && typeof e.date === 'string') {
418
+ throw TokenError.notActiveBefore(e.date);
419
+ }
420
+ break;
421
+ }
422
+ case 'JsonWebTokenError':
423
+ {
424
+ if (hasOwnProperty$1(e, 'message') && typeof e.message === 'string') {
425
+ throw TokenError.payloadInvalid(e.message);
426
+ }
427
+ }
428
+ }
429
+ }
430
+ throw new TokenError({
431
+ previous: e,
432
+ decorateMessage: true,
433
+ logMessage: true,
434
+ message: 'The JWT error could not be determined.'
435
+ });
436
+ }
437
+
438
+ function decodeToken(token, options) {
439
+ options ?? (options = {});
440
+ try {
441
+ return decode(token, {
442
+ ...options
443
+ });
444
+ } catch (e) {
445
+ handleJWTError(e);
446
+ throw e;
447
+ }
448
+ }
449
+
450
+ async function signToken(payload, context) {
451
+ context.expiresIn = context.expiresIn || 3600;
452
+ switch(context.type){
453
+ case KeyType.RSA:
454
+ case KeyType.EC:
455
+ {
456
+ const { type , keyPair , ...options } = context;
457
+ const { privateKey } = isKeyPair(keyPair) ? keyPair : await useKeyPair(keyPair);
458
+ if (type === KeyType.RSA) {
459
+ options.algorithm = options.algorithm || 'RS256';
460
+ } else {
461
+ options.algorithm = options.algorithm || 'ES256';
462
+ }
463
+ return sign(payload, privateKey, options);
464
+ }
465
+ case KeyType.OCT:
466
+ {
467
+ const { type , secret , ...options } = context;
468
+ options.algorithm = options.algorithm || 'HS256';
469
+ return sign(payload, secret, options);
470
+ }
471
+ }
472
+ throw new TokenError();
473
+ }
474
+
475
+ async function verifyToken(token, context) {
476
+ try {
477
+ switch(context.type){
478
+ case KeyType.RSA:
479
+ case KeyType.EC:
480
+ {
481
+ const { type , keyPair , ...options } = context;
482
+ const { publicKey } = isKeyPair(keyPair) ? keyPair : await useKeyPair(keyPair);
483
+ if (type === KeyType.RSA) {
484
+ options.algorithms = options.algorithms || [
485
+ 'RS256',
486
+ 'RS384',
487
+ 'RS512',
488
+ 'PS256',
489
+ 'PS384',
490
+ 'PS512'
491
+ ];
492
+ } else {
493
+ options.algorithms = options.algorithms || [
494
+ 'ES256',
495
+ 'ES384',
496
+ 'ES512'
497
+ ];
498
+ }
499
+ return verify(token, publicKey, {
500
+ ...options
501
+ });
502
+ }
503
+ case KeyType.OCT:
504
+ {
505
+ const { type , secret , ...options } = context;
506
+ options.algorithms = options.algorithms || [
507
+ 'HS256',
508
+ 'HS384',
509
+ 'HS512'
510
+ ];
511
+ return verify(token, secret, {
512
+ ...options
513
+ });
514
+ }
515
+ }
516
+ } catch (e) {
517
+ handleJWTError(e);
518
+ throw e;
519
+ }
520
+ throw new TokenError({
521
+ message: 'Invalid type.'
522
+ });
523
+ }
524
+
525
+ function transformDomainEventData(input) {
526
+ if (isObject(input)) {
527
+ const keys = Object.keys(input);
528
+ for(let i = 0; i < keys.length; i++){
529
+ const value = input[keys[i]];
530
+ if (value instanceof Date) {
531
+ input[keys[i]] = value.toISOString();
532
+ }
533
+ }
534
+ }
535
+ return input;
536
+ }
537
+ function buildDomainEventChannelName(input, id) {
538
+ if (typeof input === 'string') {
539
+ return input;
540
+ }
541
+ return input(id);
542
+ }
543
+
544
+ async function publishDomainRedisEvent(context, destinations) {
545
+ if (!hasClient() && !hasConfig()) {
546
+ return Promise.resolve();
547
+ }
548
+ context = transformDomainEventData(context);
549
+ const json = JSON.stringify(context);
550
+ const client = useClient();
551
+ const pipeline = client.pipeline();
552
+ for(let i = 0; i < destinations.length; i++){
553
+ const { namespace } = destinations[i];
554
+ const keyPrefix = namespace ? `${namespace}:` : '';
555
+ let key = keyPrefix + buildDomainEventChannelName(destinations[i].channel);
556
+ pipeline.publish(key, json);
557
+ if (context.event !== DomainEventName.CREATED && typeof destinations[i].channel === 'function') {
558
+ key = keyPrefix + buildDomainEventChannelName(destinations[i].channel, context.data.id);
559
+ pipeline.publish(key, json);
560
+ }
561
+ }
562
+ return pipeline.exec();
563
+ }
564
+
565
+ let instance$3;
566
+ function useSocketEmitter() {
567
+ if (typeof instance$3 !== 'undefined') {
568
+ return instance$3;
569
+ }
570
+ instance$3 = new Emitter(useClient());
571
+ return instance$3;
572
+ }
573
+
574
+ function publishDomainSocketEvent(context, destinations) {
575
+ if (!hasClient() && !hasConfig()) {
576
+ return;
577
+ }
578
+ context = transformDomainEventData(context);
579
+ for(let i = 0; i < destinations.length; i++){
580
+ let emitter = useSocketEmitter();
581
+ if (destinations[i].namespace) {
582
+ emitter = emitter.of(destinations[i].namespace);
583
+ }
584
+ let roomName = buildDomainEventChannelName(destinations[i].channel);
585
+ const fullEventName = buildDomainEventFullName(context.type, context.event);
586
+ emitter.in(roomName).emit(fullEventName, {
587
+ data: context,
588
+ meta: {
589
+ roomName
590
+ }
591
+ });
592
+ if (context.event !== DomainEventName.CREATED && typeof destinations[i].channel === 'function') {
593
+ roomName = buildDomainEventChannelName(destinations[i].channel, context.data.id);
594
+ emitter.in(roomName).emit(fullEventName, {
595
+ data: context,
596
+ meta: {
597
+ roomName,
598
+ roomId: context.data.id
599
+ }
600
+ });
601
+ }
602
+ }
603
+ }
604
+
605
+ async function publishDomainEvent(context, destinations) {
606
+ await publishDomainRedisEvent(context, destinations);
607
+ publishDomainSocketEvent(context, destinations);
608
+ }
609
+
610
+ async function saveRobotCredentialsToVault(entity) {
611
+ if (!hasConfig$1()) {
612
+ return;
613
+ }
614
+ const client = useClient$1();
615
+ await client.keyValue.save('robots', entity.name, {
616
+ id: entity.id,
617
+ secret: entity.secret
618
+ });
619
+ }
620
+ async function removeRobotCredentialsFromVault(entity) {
621
+ if (!hasConfig$1()) {
622
+ return;
623
+ }
624
+ const client = useClient$1();
625
+ await client.keyValue.delete('robots', entity.name);
626
+ }
627
+ async function findRobotCredentialsInVault(entity) {
628
+ if (!hasConfig$1()) {
629
+ return undefined;
630
+ }
631
+ const client = useClient$1();
632
+ const response = await client.keyValue.find('robots', entity.name);
633
+ if (response && response.data) {
634
+ return response.data;
635
+ }
636
+ return undefined;
637
+ }
638
+
639
+ /*
640
+ * Copyright (c) 2022.
641
+ * Author Peter Placzek (tada5hi)
642
+ * For the full copyright and license information,
643
+ * view the LICENSE file that was distributed with this source code.
644
+ */ class VoidLogger {
645
+ error(message, ...meta) {
646
+ return this;
647
+ }
648
+ warn(message, ...meta) {
649
+ return this;
650
+ }
651
+ info(message, ...meta) {
652
+ return this;
653
+ }
654
+ http(message, ...meta) {
655
+ return this;
656
+ }
657
+ verbose(message, ...meta) {
658
+ return this;
659
+ }
660
+ debug(message, ...meta) {
661
+ return this;
662
+ }
663
+ }
664
+
665
+ let instance$2;
666
+ function useLogger() {
667
+ if (typeof instance$2 !== 'undefined') {
668
+ return instance$2;
669
+ }
670
+ instance$2 = new VoidLogger();
671
+ return instance$2;
672
+ }
673
+ function setLogger(logger) {
674
+ instance$2 = logger;
675
+ }
676
+
677
+ class ProxyClient {
678
+ /**
679
+ * Create a http agent for an url.
680
+ *
681
+ * @param input
682
+ */ async createAgent(input) {
683
+ return new Promise((resolve, reject)=>{
684
+ const headers = {};
685
+ if (this.options.user && this.options.password) {
686
+ headers['Proxy-Authorization'] = `Basic ${Buffer.from(`${this.options.user}:${this.options.password}`).toString('base64')}`;
687
+ }
688
+ const urlParsed = new URL(input);
689
+ const request = http.request({
690
+ host: this.options.host,
691
+ port: this.options.port,
692
+ method: 'CONNECT',
693
+ path: `${urlParsed.hostname}:443`,
694
+ headers
695
+ });
696
+ request.on('connect', (res, socket)=>{
697
+ if (res.statusCode >= 200 && res.statusCode < 300) {
698
+ resolve(new https.Agent({
699
+ socket,
700
+ ...this.agentOptions
701
+ }));
702
+ } else {
703
+ reject(new Error('Could not connect to proxy!'));
704
+ }
705
+ });
706
+ request.on('error', (err)=>{
707
+ reject(err);
708
+ });
709
+ request.on('timeout', (err)=>{
710
+ reject(err);
711
+ });
712
+ request.end();
713
+ });
714
+ }
715
+ constructor(options, agentOptions){
716
+ this.options = options;
717
+ this.agentOptions = agentOptions || {};
718
+ }
719
+ }
720
+
721
+ async function buildHTTPClientConfigForProxy(url) {
722
+ const connectionString = getProxyForUrl(url);
723
+ if (connectionString) {
724
+ const connectionDetails = parseProxyConnectionString(connectionString);
725
+ const proxyClient = new ProxyClient({
726
+ host: connectionDetails.host,
727
+ port: connectionDetails.port || 3128,
728
+ ...connectionDetails.auth.username ? {
729
+ user: connectionDetails.auth.username
730
+ } : {},
731
+ ...connectionDetails.auth.password ? {
732
+ password: connectionDetails.auth.password
733
+ } : {}
734
+ });
735
+ const agent = await proxyClient.createAgent(url);
736
+ return {
737
+ httpAgent: agent,
738
+ httpsAgent: agent,
739
+ proxy: false
740
+ };
741
+ }
742
+ return {};
743
+ }
744
+
745
+ /*
746
+ * Copyright (c) 2022.
747
+ * Author Peter Placzek (tada5hi)
748
+ * For the full copyright and license information,
749
+ * view the LICENSE file that was distributed with this source code.
750
+ */ let instance$1;
751
+ function hasSmtpConfig() {
752
+ return !!instance$1;
753
+ }
754
+ function setSmtpConfig(value) {
755
+ instance$1 = value;
756
+ }
757
+ function useSmtpConfig() {
758
+ if (typeof instance$1 !== 'undefined') {
759
+ return instance$1;
760
+ }
761
+ instance$1 = {};
762
+ return instance$1;
763
+ }
764
+
765
+ function createSmtpClient(options) {
766
+ let transport;
767
+ options = options || {};
768
+ if (typeof options === 'string') {
769
+ transport = createTransport(options);
770
+ } else if (options.connectionString) {
771
+ transport = createTransport(options.connectionString);
772
+ } else {
773
+ let auth;
774
+ if (options.user && options.password) {
775
+ auth = {
776
+ type: 'login',
777
+ user: options.user,
778
+ pass: options.password
779
+ };
780
+ }
781
+ transport = createTransport({
782
+ host: options.host,
783
+ port: options.port,
784
+ auth,
785
+ secure: options.ssl,
786
+ opportunisticTLS: options.starttls,
787
+ tls: {
788
+ rejectUnauthorized: false
789
+ }
790
+ });
791
+ }
792
+ transport.on('error', (e)=>{
793
+ useLogger().error(e.message);
794
+ });
795
+ return transport;
796
+ }
797
+
798
+ let instance;
799
+ async function useSMTPClient() {
800
+ if (typeof instance !== 'undefined') {
801
+ return instance;
802
+ }
803
+ let options;
804
+ if (process.env.NODE_ENV === 'test') {
805
+ const testAccount = await createTestAccount();
806
+ options = {
807
+ host: 'smtp.ethereal.email',
808
+ port: 587,
809
+ ssl: false,
810
+ user: testAccount.user,
811
+ password: testAccount.pass
812
+ };
813
+ } else {
814
+ options = useSmtpConfig();
815
+ }
816
+ instance = createSmtpClient(options);
817
+ return instance;
818
+ }
819
+
820
+ function setVaultConfig(input) {
821
+ if (hasClient$1()) {
822
+ unsetClient();
823
+ }
824
+ setConfig(input);
825
+ }
826
+ function hasVaultConfig() {
827
+ return hasConfig$1();
828
+ }
829
+
830
+ export { KeyPairKind, ProxyClient, VoidLogger, buildHTTPClientConfigForProxy, buildKeyFileName, buildWorkingDirectoryPathsForConfigFile, compare, createKeyPair, createSmtpClient, decodeToken, decryptRSAPrivateKey, deleteKeyPair, extendKeyPairOptions, findRobotCredentialsInVault, hasOwnProperty, hasProcessEnv, hasSmtpConfig, hasVaultConfig, hash, isKeyPair, loadKeyPair, publishDomainEvent, publishDomainRedisEvent, publishDomainSocketEvent, readBoolFromProcessEnv, readBoolOrStringFromProcessEnv, readConfigFile, readFromProcessEnv, readIntFromProcessEnv, removeRobotCredentialsFromVault, saveKeyPair, saveRobotCredentialsToVault, setLogger, setSmtpConfig, setVaultConfig, signToken, useKeyPair, useLogger, useSMTPClient, useSmtpConfig, useSocketEmitter, verifyToken };
831
+ //# sourceMappingURL=index.mjs.map