@authup/server-kit 1.0.0-beta.0 → 1.0.0-beta.10

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 (132) hide show
  1. package/LICENSE +201 -21
  2. package/README.md +2 -2
  3. package/dist/crypto/hash/hash.d.ts +1 -1
  4. package/dist/crypto/hash/hash.d.ts.map +1 -1
  5. package/dist/crypto/json-web-token/extract.d.ts +11 -0
  6. package/dist/crypto/json-web-token/extract.d.ts.map +1 -0
  7. package/dist/crypto/json-web-token/index.d.ts +1 -1
  8. package/dist/crypto/json-web-token/index.d.ts.map +1 -1
  9. package/dist/crypto/json-web-token/sign/index.d.ts +3 -0
  10. package/dist/crypto/json-web-token/sign/index.d.ts.map +1 -0
  11. package/dist/crypto/json-web-token/sign/module.d.ts +4 -0
  12. package/dist/crypto/json-web-token/sign/module.d.ts.map +1 -0
  13. package/dist/crypto/json-web-token/sign/types.d.ts +24 -0
  14. package/dist/crypto/json-web-token/sign/types.d.ts.map +1 -0
  15. package/dist/crypto/json-web-token/type.d.ts +4 -33
  16. package/dist/crypto/json-web-token/type.d.ts.map +1 -1
  17. package/dist/crypto/json-web-token/utils.d.ts +4 -1
  18. package/dist/crypto/json-web-token/utils.d.ts.map +1 -1
  19. package/dist/crypto/json-web-token/verify/index.d.ts +3 -0
  20. package/dist/crypto/json-web-token/verify/index.d.ts.map +1 -0
  21. package/dist/crypto/json-web-token/verify/module.d.ts +12 -0
  22. package/dist/crypto/json-web-token/verify/module.d.ts.map +1 -0
  23. package/dist/crypto/json-web-token/verify/types.d.ts +21 -0
  24. package/dist/crypto/json-web-token/verify/types.d.ts.map +1 -0
  25. package/dist/crypto/key-pair/helpers/check.d.ts.map +1 -0
  26. package/dist/crypto/key-pair/helpers/file-name.d.ts.map +1 -0
  27. package/dist/crypto/key-pair/{utils → helpers}/index.d.ts +1 -0
  28. package/dist/crypto/key-pair/helpers/index.d.ts.map +1 -0
  29. package/dist/crypto/key-pair/helpers/options.d.ts.map +1 -0
  30. package/dist/crypto/key-pair/helpers/private-key.d.ts.map +1 -0
  31. package/dist/crypto/key-pair/helpers/wrap.d.ts +6 -0
  32. package/dist/crypto/key-pair/helpers/wrap.d.ts.map +1 -0
  33. package/dist/crypto/key-pair/index.d.ts +1 -1
  34. package/dist/crypto/key-pair/index.d.ts.map +1 -1
  35. package/dist/domain-event/index.d.ts +1 -1
  36. package/dist/domain-event/index.d.ts.map +1 -1
  37. package/dist/domain-event/module.d.ts +8 -0
  38. package/dist/domain-event/module.d.ts.map +1 -0
  39. package/dist/domain-event/redis/index.d.ts +1 -1
  40. package/dist/domain-event/redis/index.d.ts.map +1 -1
  41. package/dist/domain-event/redis/module.d.ts +8 -0
  42. package/dist/domain-event/redis/module.d.ts.map +1 -0
  43. package/dist/domain-event/socket/index.d.ts +1 -2
  44. package/dist/domain-event/socket/index.d.ts.map +1 -1
  45. package/dist/domain-event/socket/module.d.ts +9 -0
  46. package/dist/domain-event/socket/module.d.ts.map +1 -0
  47. package/dist/domain-event/type.d.ts +8 -0
  48. package/dist/domain-event/type.d.ts.map +1 -1
  49. package/dist/index.cjs +443 -340
  50. package/dist/index.cjs.map +1 -1
  51. package/dist/index.d.ts +1 -3
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.mjs +366 -323
  54. package/dist/index.mjs.map +1 -1
  55. package/dist/services/index.d.ts +4 -0
  56. package/dist/services/index.d.ts.map +1 -0
  57. package/dist/services/logger/index.d.ts +4 -0
  58. package/dist/services/logger/index.d.ts.map +1 -0
  59. package/dist/services/logger/module.d.ts +3 -0
  60. package/dist/services/logger/module.d.ts.map +1 -0
  61. package/dist/services/logger/singleton.d.ts +7 -0
  62. package/dist/services/logger/singleton.d.ts.map +1 -0
  63. package/dist/services/logger/types.d.ts +7 -0
  64. package/dist/services/logger/types.d.ts.map +1 -0
  65. package/dist/services/redis/helpers.d.ts +3 -0
  66. package/dist/services/redis/helpers.d.ts.map +1 -0
  67. package/dist/services/redis/index.d.ts +4 -0
  68. package/dist/services/redis/index.d.ts.map +1 -0
  69. package/dist/services/redis/module.d.ts +3 -0
  70. package/dist/services/redis/module.d.ts.map +1 -0
  71. package/dist/services/redis/singleton.d.ts +7 -0
  72. package/dist/services/redis/singleton.d.ts.map +1 -0
  73. package/dist/services/vault/index.d.ts +3 -0
  74. package/dist/services/vault/index.d.ts.map +1 -0
  75. package/dist/services/vault/module.d.ts +3 -0
  76. package/dist/services/vault/module.d.ts.map +1 -0
  77. package/dist/services/vault/singleton.d.ts +6 -0
  78. package/dist/services/vault/singleton.d.ts.map +1 -0
  79. package/package.json +13 -16
  80. package/dist/crypto/json-web-token/decode.d.ts +0 -15
  81. package/dist/crypto/json-web-token/decode.d.ts.map +0 -1
  82. package/dist/crypto/json-web-token/sign.d.ts +0 -4
  83. package/dist/crypto/json-web-token/sign.d.ts.map +0 -1
  84. package/dist/crypto/json-web-token/verify.d.ts +0 -15
  85. package/dist/crypto/json-web-token/verify.d.ts.map +0 -1
  86. package/dist/crypto/key-pair/utils/check.d.ts.map +0 -1
  87. package/dist/crypto/key-pair/utils/file-name.d.ts.map +0 -1
  88. package/dist/crypto/key-pair/utils/index.d.ts.map +0 -1
  89. package/dist/crypto/key-pair/utils/options.d.ts.map +0 -1
  90. package/dist/crypto/key-pair/utils/private-key.d.ts.map +0 -1
  91. package/dist/domain-event/publish.d.ts +0 -4
  92. package/dist/domain-event/publish.d.ts.map +0 -1
  93. package/dist/domain-event/redis/publish.d.ts +0 -4
  94. package/dist/domain-event/redis/publish.d.ts.map +0 -1
  95. package/dist/domain-event/socket/publish.d.ts +0 -4
  96. package/dist/domain-event/socket/publish.d.ts.map +0 -1
  97. package/dist/domain-event/socket/singleton.d.ts +0 -4
  98. package/dist/domain-event/socket/singleton.d.ts.map +0 -1
  99. package/dist/domain-event/socket/type.d.ts +0 -5
  100. package/dist/domain-event/socket/type.d.ts.map +0 -1
  101. package/dist/logger/index.d.ts +0 -4
  102. package/dist/logger/index.d.ts.map +0 -1
  103. package/dist/logger/module.d.ts +0 -4
  104. package/dist/logger/module.d.ts.map +0 -1
  105. package/dist/logger/presets/index.d.ts +0 -2
  106. package/dist/logger/presets/index.d.ts.map +0 -1
  107. package/dist/logger/presets/void.d.ts +0 -16
  108. package/dist/logger/presets/void.d.ts.map +0 -1
  109. package/dist/logger/type.d.ts +0 -14
  110. package/dist/logger/type.d.ts.map +0 -1
  111. package/dist/proxy/index.d.ts +0 -3
  112. package/dist/proxy/index.d.ts.map +0 -1
  113. package/dist/proxy/module.d.ts +0 -24
  114. package/dist/proxy/module.d.ts.map +0 -1
  115. package/dist/proxy/utils.d.ts +0 -8
  116. package/dist/proxy/utils.d.ts.map +0 -1
  117. package/dist/smtp/config/index.d.ts +0 -2
  118. package/dist/smtp/config/index.d.ts.map +0 -1
  119. package/dist/smtp/config/singleton.d.ts +0 -5
  120. package/dist/smtp/config/singleton.d.ts.map +0 -1
  121. package/dist/smtp/index.d.ts +0 -5
  122. package/dist/smtp/index.d.ts.map +0 -1
  123. package/dist/smtp/module.d.ts +0 -4
  124. package/dist/smtp/module.d.ts.map +0 -1
  125. package/dist/smtp/singleton.d.ts +0 -3
  126. package/dist/smtp/singleton.d.ts.map +0 -1
  127. package/dist/smtp/type.d.ts +0 -14
  128. package/dist/smtp/type.d.ts.map +0 -1
  129. /package/dist/crypto/key-pair/{utils → helpers}/check.d.ts +0 -0
  130. /package/dist/crypto/key-pair/{utils → helpers}/file-name.d.ts +0 -0
  131. /package/dist/crypto/key-pair/{utils → helpers}/options.d.ts +0 -0
  132. /package/dist/crypto/key-pair/{utils → helpers}/private-key.d.ts +0 -0
package/dist/index.cjs CHANGED
@@ -1,25 +1,44 @@
1
1
  'use strict';
2
2
 
3
- var bcrypt = require('bcrypt');
3
+ var bcrypt = require('@node-rs/bcrypt');
4
4
  var node_crypto = require('node:crypto');
5
- var core = require('@authup/core');
5
+ var kit = require('@authup/kit');
6
6
  var path = require('node:path');
7
7
  var fs = require('node:fs');
8
- var jsonwebtoken = require('jsonwebtoken');
8
+ var jsonwebtoken = require('@node-rs/jsonwebtoken');
9
9
  var smob = require('smob');
10
+ var process$1 = require('node:process');
11
+ var winston = require('winston');
12
+ var singa = require('singa');
10
13
  var redisExtension = require('redis-extension');
14
+ var vault = require('@hapic/vault');
11
15
  var redisEmitter = require('@socket.io/redis-emitter');
12
- var http = require('node:http');
13
- var https = require('node:https');
14
- var proxyFromEnv = require('proxy-from-env');
15
- var nodemailer = require('nodemailer');
16
+
17
+ function _interopNamespaceDefault(e) {
18
+ var n = Object.create(null);
19
+ if (e) {
20
+ Object.keys(e).forEach(function (k) {
21
+ if (k !== 'default') {
22
+ var d = Object.getOwnPropertyDescriptor(e, k);
23
+ Object.defineProperty(n, k, d.get ? d : {
24
+ enumerable: true,
25
+ get: function () { return e[k]; }
26
+ });
27
+ }
28
+ });
29
+ }
30
+ n.default = e;
31
+ return Object.freeze(n);
32
+ }
33
+
34
+ var process__namespace = /*#__PURE__*/_interopNamespaceDefault(process$1);
16
35
 
17
36
  async function compare(value, hashedValue) {
18
37
  return bcrypt.compare(value, hashedValue);
19
38
  }
20
39
 
21
- async function hash(str, saltOrRounds = 10) {
22
- return bcrypt.hash(str, saltOrRounds);
40
+ async function hash(str, rounds = 10) {
41
+ return bcrypt.hash(str, rounds);
23
42
  }
24
43
 
25
44
  /*
@@ -34,10 +53,10 @@ async function hash(str, saltOrRounds = 10) {
34
53
  })(exports.KeyPairKind || (exports.KeyPairKind = {}));
35
54
 
36
55
  function isKeyPair(data) {
37
- return core.isObject(data) && typeof data.privateKey !== 'undefined' && typeof data.publicKey !== 'undefined';
56
+ return kit.isObject(data) && typeof data.privateKey !== 'undefined' && typeof data.publicKey !== 'undefined';
38
57
  }
39
58
  function isKeyPairWithPublicKey(data) {
40
- return core.isObject(data) && typeof data.publicKey !== 'undefined';
59
+ return kit.isObject(data) && typeof data.publicKey !== 'undefined';
41
60
  }
42
61
 
43
62
  function extendKeyPairOptions(options) {
@@ -126,6 +145,41 @@ function decryptRSAPrivateKey(context, key) {
126
145
  return content;
127
146
  }
128
147
 
148
+ /*
149
+ * Copyright (c) 2024.
150
+ * Author Peter Placzek (tada5hi)
151
+ * For the full copyright and license information,
152
+ * view the LICENSE file that was distributed with this source code.
153
+ */ function wrapPem(type, input) {
154
+ if (typeof input !== 'string') {
155
+ input = Buffer.from(input).toString('base64');
156
+ }
157
+ return `-----BEGIN ${type}-----\n${input}\n-----END ${type}-----`;
158
+ }
159
+ function wrapPrivateKeyPem(input) {
160
+ return wrapPem('PRIVATE KEY', input);
161
+ }
162
+ function wrapPublicKeyPem(input) {
163
+ return wrapPem('PUBLIC KEY', input);
164
+ }
165
+ // ------------------------------------------------------------
166
+ function unwrapPem(type, input) {
167
+ if (typeof input !== 'string') {
168
+ input = Buffer.from(input).toString('base64');
169
+ }
170
+ input = input.replace(`-----BEGIN ${type}-----\n`, '');
171
+ input = input.replace(`\n-----END ${type}-----\n`, '');
172
+ input = input.replace(`-----END ${type}-----\n`, '');
173
+ input = input.replace(`\n-----END ${type}-----`, '');
174
+ return input;
175
+ }
176
+ function unwrapPrivateKeyPem(input) {
177
+ return unwrapPem('PRIVATE KEY', input);
178
+ }
179
+ function unwrapPublicKeyPem(input) {
180
+ return unwrapPem('PUBLIC KEY', input);
181
+ }
182
+
129
183
  async function saveKeyPair(keyPair, context) {
130
184
  context = extendKeyPairOptions(context);
131
185
  await fs.promises.mkdir(context.directory, {
@@ -264,130 +318,232 @@ async function useKeyPair(value) {
264
318
  return keyPair;
265
319
  }
266
320
 
321
+ /**
322
+ * Decode a JWT token with no verification.
323
+ *
324
+ * @param token
325
+ *
326
+ * @throws TokenError
327
+ */ function extractTokenHeader(token) {
328
+ const parts = token.split('.');
329
+ if (parts.length !== 3) {
330
+ throw kit.TokenError.payloadInvalid('The token format is not valid.');
331
+ }
332
+ const [headerBase64] = parts;
333
+ try {
334
+ const payload = atob(headerBase64);
335
+ return JSON.parse(payload);
336
+ /*
337
+ return {
338
+ typ: 'JWT',
339
+ alg: transformInternalToJWTAlgorithm(header.algorithm),
340
+ cty: header.contentType,
341
+ jku: header.jsonKeyUrl,
342
+ kid: header.keyId,
343
+ x5u: header.x5Url,
344
+ x5c: header.x5CertChain,
345
+ x5t: header.x5CertThumbprint,
346
+ 'x5t#S256': header.x5TS256CertThumbprint,
347
+ };
348
+ */ } catch (e) {
349
+ throw kit.TokenError.headerInvalid('The token header could not be extracted.');
350
+ }
351
+ }
352
+ function extractTokenPayload(token) {
353
+ const parts = token.split('.');
354
+ if (parts.length !== 3) {
355
+ throw kit.TokenError.payloadInvalid('The token format is not valid.');
356
+ }
357
+ const [, payloadBase64] = parts;
358
+ try {
359
+ const payload = atob(payloadBase64);
360
+ return JSON.parse(payload);
361
+ } catch (e) {
362
+ throw kit.TokenError.payloadInvalid('The token payload could not be extracted.');
363
+ }
364
+ }
365
+
267
366
  function createErrorForJWTError(e) {
268
- if (smob.isObject(e) && typeof e.name === 'string') {
269
- switch(e.name){
270
- case 'TokenExpiredError':
367
+ if (smob.isObject(e)) {
368
+ if (typeof e.name === 'string') {
369
+ switch(e.name){
370
+ case 'TokenExpiredError':
371
+ {
372
+ return kit.TokenError.expired();
373
+ }
374
+ case 'NotBeforeError':
375
+ {
376
+ if (typeof e.date === 'string' || e.date instanceof Date) {
377
+ return kit.TokenError.notActiveBefore(e.date);
378
+ }
379
+ break;
380
+ }
381
+ case 'JsonWebTokenError':
382
+ {
383
+ if (typeof e.message === 'string') {
384
+ return kit.TokenError.payloadInvalid(e.message);
385
+ }
386
+ break;
387
+ }
388
+ }
389
+ }
390
+ // @see https://github.com/Keats/jsonwebtoken/blob/master/src/errors.rs
391
+ switch(e.message){
392
+ case 'ExpiredSignature':
271
393
  {
272
- return core.TokenError.expired();
394
+ return kit.TokenError.expired();
273
395
  }
274
- case 'NotBeforeError':
396
+ case 'ImmatureSignature':
275
397
  {
276
- if (typeof e.date === 'string' || e.date instanceof Date) {
277
- return core.TokenError.notActiveBefore(e.date);
278
- }
279
- break;
398
+ return kit.TokenError.notActiveBefore();
280
399
  }
281
- case 'JsonWebTokenError':
400
+ case 'InvalidToken':
401
+ case 'InvalidSignature':
282
402
  {
283
- if (typeof e.message === 'string') {
284
- return core.TokenError.payloadInvalid(e.message);
285
- }
286
- break;
403
+ return kit.TokenError.payloadInvalid();
287
404
  }
288
405
  }
289
406
  }
290
- return new core.TokenError({
407
+ return new kit.TokenError({
291
408
  cause: e,
292
409
  logMessage: true,
293
410
  message: 'The JWT error could not be determined.'
294
411
  });
295
412
  }
296
-
297
- function decodeToken(token, options) {
298
- options ?? (options = {});
299
- let output;
300
- try {
301
- output = jsonwebtoken.decode(token, {
302
- ...options
303
- });
304
- } catch (e) {
305
- throw createErrorForJWTError(e);
306
- }
307
- if (output === null) {
308
- throw core.TokenError.payloadInvalid('The token could not be decoded.');
413
+ function transformJWTAlgorithmToInternal(algorithm) {
414
+ switch(algorithm){
415
+ case kit.JWTAlgorithm.HS256:
416
+ {
417
+ return jsonwebtoken.Algorithm.HS256;
418
+ }
419
+ case kit.JWTAlgorithm.HS384:
420
+ {
421
+ return jsonwebtoken.Algorithm.HS384;
422
+ }
423
+ case kit.JWTAlgorithm.HS512:
424
+ {
425
+ return jsonwebtoken.Algorithm.HS512;
426
+ }
427
+ case kit.JWTAlgorithm.RS256:
428
+ {
429
+ return jsonwebtoken.Algorithm.RS256;
430
+ }
431
+ case kit.JWTAlgorithm.RS384:
432
+ {
433
+ return jsonwebtoken.Algorithm.RS384;
434
+ }
435
+ case kit.JWTAlgorithm.RS512:
436
+ {
437
+ return jsonwebtoken.Algorithm.RS512;
438
+ }
439
+ case kit.JWTAlgorithm.ES256:
440
+ {
441
+ return jsonwebtoken.Algorithm.ES256;
442
+ }
443
+ case kit.JWTAlgorithm.ES384:
444
+ {
445
+ return jsonwebtoken.Algorithm.ES384;
446
+ }
447
+ case kit.JWTAlgorithm.PS256:
448
+ {
449
+ return jsonwebtoken.Algorithm.PS256;
450
+ }
451
+ case kit.JWTAlgorithm.PS384:
452
+ {
453
+ return jsonwebtoken.Algorithm.PS384;
454
+ }
455
+ case kit.JWTAlgorithm.PS512:
456
+ {
457
+ return jsonwebtoken.Algorithm.PS512;
458
+ }
309
459
  }
310
- return output;
460
+ throw new Error(`The algorithm ${algorithm} is not supported.`);
311
461
  }
312
462
 
313
- async function signToken(payload, context) {
314
- context.expiresIn = context.expiresIn || 3600;
463
+ const getUtcTimestamp = ()=>Math.floor(new Date().getTime() / 1000);
464
+ async function signToken(claims, context) {
465
+ if (typeof claims.exp !== 'number') {
466
+ claims.exp = getUtcTimestamp() + 3600;
467
+ }
468
+ if (typeof claims.iat !== 'number') {
469
+ claims.iat = getUtcTimestamp();
470
+ }
315
471
  switch(context.type){
316
- case core.KeyType.RSA:
317
- case core.KeyType.EC:
472
+ case kit.JWKType.RSA:
473
+ case kit.JWKType.EC:
318
474
  {
319
- const { type, keyPair, ...options } = context;
320
- const { privateKey } = isKeyPair(keyPair) ? keyPair : await useKeyPair(keyPair);
321
- if (type === core.KeyType.RSA) {
322
- options.algorithm = options.algorithm || 'RS256';
475
+ const { privateKey } = isKeyPair(context.keyPair) ? context.keyPair : await useKeyPair(context.keyPair);
476
+ let algorithm;
477
+ if (context.type === kit.JWKType.RSA) {
478
+ algorithm = context.algorithm ? transformJWTAlgorithmToInternal(context.algorithm) : jsonwebtoken.Algorithm.RS256;
323
479
  } else {
324
- options.algorithm = options.algorithm || 'ES256';
480
+ algorithm = context.algorithm ? transformJWTAlgorithmToInternal(context.algorithm) : jsonwebtoken.Algorithm.ES256;
325
481
  }
326
- return jsonwebtoken.sign(payload, privateKey, options);
482
+ return jsonwebtoken.sign(claims, privateKey, {
483
+ algorithm,
484
+ keyId: context.keyId
485
+ });
327
486
  }
328
- case core.KeyType.OCT:
487
+ case kit.JWKType.OCT:
329
488
  {
330
- const { type, secret, ...options } = context;
331
- options.algorithm = options.algorithm || 'HS256';
332
- return jsonwebtoken.sign(payload, secret, options);
489
+ const algorithm = context.algorithm ? transformJWTAlgorithmToInternal(context.algorithm) : jsonwebtoken.Algorithm.HS256;
490
+ return jsonwebtoken.sign(claims, context.key, {
491
+ algorithm,
492
+ keyId: context.keyId
493
+ });
333
494
  }
334
495
  }
335
- throw new core.TokenError();
496
+ throw new kit.TokenError();
336
497
  }
337
498
 
338
- async function verifyToken(token, context) {
499
+ /**
500
+ * Verify JWT.
501
+ *
502
+ * @param token
503
+ * @param context
504
+ *
505
+ * @throws TokenError
506
+ */ async function verifyToken(token, context) {
339
507
  let promise;
340
508
  let output;
341
509
  try {
342
510
  switch(context.type){
343
- case core.KeyType.RSA:
344
- case core.KeyType.EC:
511
+ case kit.JWKType.RSA:
512
+ case kit.JWKType.EC:
345
513
  {
346
- const { type, keyPair, ...options } = context;
347
- const { publicKey } = isKeyPairWithPublicKey(keyPair) ? keyPair : await useKeyPair(keyPair);
348
- if (type === core.KeyType.RSA) {
349
- options.algorithms = options.algorithms || [
350
- 'RS256',
351
- 'RS384',
352
- 'RS512',
353
- 'PS256',
354
- 'PS384',
355
- 'PS512'
514
+ const { publicKey } = isKeyPairWithPublicKey(context.keyPair) ? context.keyPair : await useKeyPair(context.keyPair);
515
+ let algorithms;
516
+ if (context.type === kit.JWKType.RSA) {
517
+ algorithms = context.algorithms ? context.algorithms.map((algorithm)=>transformJWTAlgorithmToInternal(algorithm)) : [
518
+ jsonwebtoken.Algorithm.RS256,
519
+ jsonwebtoken.Algorithm.RS384,
520
+ jsonwebtoken.Algorithm.RS512,
521
+ jsonwebtoken.Algorithm.PS256,
522
+ jsonwebtoken.Algorithm.PS384,
523
+ jsonwebtoken.Algorithm.PS512
356
524
  ];
357
525
  } else {
358
- options.algorithms = options.algorithms || [
359
- 'ES256',
360
- 'ES384',
361
- 'ES512'
526
+ algorithms = context.algorithms ? context.algorithms.map((algorithm)=>transformJWTAlgorithmToInternal(algorithm)) : [
527
+ jsonwebtoken.Algorithm.ES256,
528
+ jsonwebtoken.Algorithm.ES384
362
529
  ];
363
530
  }
364
- promise = new Promise((resolve, reject)=>{
365
- jsonwebtoken.verify(token, publicKey, options, (err, decoded)=>{
366
- if (err) {
367
- reject(err);
368
- return;
369
- }
370
- resolve(decoded);
371
- });
531
+ promise = jsonwebtoken.verify(token, publicKey, {
532
+ algorithms,
533
+ validateNbf: true
372
534
  });
373
535
  break;
374
536
  }
375
- case core.KeyType.OCT:
537
+ case kit.JWKType.OCT:
376
538
  {
377
- const { type, secret, ...options } = context;
378
- options.algorithms = options.algorithms || [
379
- 'HS256',
380
- 'HS384',
381
- 'HS512'
539
+ const algorithms = context.algorithms ? context.algorithms.map((algorithm)=>transformJWTAlgorithmToInternal(algorithm)) : [
540
+ jsonwebtoken.Algorithm.HS256,
541
+ jsonwebtoken.Algorithm.HS384,
542
+ jsonwebtoken.Algorithm.HS512
382
543
  ];
383
- promise = new Promise((resolve, reject)=>{
384
- jsonwebtoken.verify(token, secret, options, (err, decoded)=>{
385
- if (err) {
386
- reject(err);
387
- return;
388
- }
389
- resolve(decoded);
390
- });
544
+ promise = jsonwebtoken.verify(token, context.key, {
545
+ algorithms,
546
+ validateNbf: true
391
547
  });
392
548
  }
393
549
  }
@@ -396,15 +552,94 @@ async function verifyToken(token, context) {
396
552
  throw createErrorForJWTError(e);
397
553
  }
398
554
  if (typeof output === 'undefined') {
399
- throw new core.TokenError({
555
+ throw new kit.TokenError({
400
556
  message: 'Invalid type.'
401
557
  });
402
558
  }
403
559
  return output;
404
560
  }
405
561
 
562
+ function createLogger(context) {
563
+ let items;
564
+ const cwd = context.directory || process__namespace.cwd();
565
+ if (context.env === 'production') {
566
+ items = [
567
+ new winston.transports.Console({
568
+ level: 'info'
569
+ }),
570
+ new winston.transports.File({
571
+ filename: path.join(cwd, 'access.log'),
572
+ level: 'http',
573
+ maxsize: 10 * 1024 * 1024,
574
+ maxFiles: 5
575
+ }),
576
+ new winston.transports.File({
577
+ filename: path.join(cwd, 'error.log'),
578
+ level: 'warn',
579
+ maxsize: 10 * 1024 * 1024,
580
+ maxFiles: 5
581
+ })
582
+ ];
583
+ } else {
584
+ items = [
585
+ new winston.transports.Console({
586
+ level: 'debug'
587
+ })
588
+ ];
589
+ }
590
+ return winston.createLogger({
591
+ format: winston.format.combine(winston.format.timestamp(), winston.format.json()),
592
+ transports: items
593
+ });
594
+ }
595
+
596
+ const instance$2 = singa.singa({
597
+ name: 'logger'
598
+ });
599
+ function setLoggerFactory(factory) {
600
+ instance$2.setFactory(factory);
601
+ }
602
+ function isLoggerUsable() {
603
+ return instance$2.has() || instance$2.hasFactory();
604
+ }
605
+ function setLogger(input) {
606
+ instance$2.set(input);
607
+ }
608
+ function useLogger() {
609
+ return instance$2.use();
610
+ }
611
+
612
+ const instance$1 = singa.singa({
613
+ name: 'redis'
614
+ });
615
+ function setRedisFactory(factory) {
616
+ instance$1.setFactory(factory);
617
+ }
618
+ function isRedisClientUsable() {
619
+ return instance$1.has() || instance$1.hasFactory();
620
+ }
621
+ function setRedisClient(input) {
622
+ instance$1.set(input);
623
+ }
624
+ function useRedisClient() {
625
+ return instance$1.use();
626
+ }
627
+
628
+ const instance = singa.singa({
629
+ name: 'vault'
630
+ });
631
+ function setVaultFactory(factory) {
632
+ instance.setFactory(factory);
633
+ }
634
+ function isVaultClientUsable() {
635
+ return instance.has() || instance.hasFactory();
636
+ }
637
+ function useVaultClient() {
638
+ return instance.use();
639
+ }
640
+
406
641
  function transformDomainEventData(input) {
407
- if (core.isObject(input)) {
642
+ if (kit.isObject(input)) {
408
643
  const keys = Object.keys(input);
409
644
  for(let i = 0; i < keys.length; i++){
410
645
  const value = input[keys[i]];
@@ -422,255 +657,81 @@ function buildDomainEventChannelName(input, id) {
422
657
  return input(id);
423
658
  }
424
659
 
425
- async function publishDomainRedisEvent(context, destinations) {
426
- if (!redisExtension.hasClient() && !redisExtension.hasConfig()) {
427
- return Promise.resolve();
428
- }
429
- context = transformDomainEventData(context);
430
- const json = JSON.stringify(context);
431
- const client = redisExtension.useClient();
432
- const pipeline = client.pipeline();
433
- for(let i = 0; i < destinations.length; i++){
434
- const { namespace } = destinations[i];
435
- const keyPrefix = namespace ? `${namespace}:` : '';
436
- let key = keyPrefix + buildDomainEventChannelName(destinations[i].channel);
437
- pipeline.publish(key, json);
438
- if (context.event !== core.DomainEventName.CREATED && typeof destinations[i].channel === 'function') {
439
- key = keyPrefix + buildDomainEventChannelName(destinations[i].channel, context.data.id);
440
- pipeline.publish(key, json);
660
+ class DomainEventRedisPublisher {
661
+ async publish(ctx) {
662
+ const data = JSON.stringify(transformDomainEventData(ctx.content));
663
+ const pipeline = this.driver.pipeline();
664
+ for(let i = 0; i < ctx.destinations.length; i++){
665
+ const { namespace } = ctx.destinations[i];
666
+ const keyPrefix = namespace ? `${namespace}:` : '';
667
+ let key = keyPrefix + buildDomainEventChannelName(ctx.destinations[i].channel);
668
+ pipeline.publish(key, data);
669
+ if (typeof ctx.destinations[i].channel === 'function') {
670
+ key = keyPrefix + buildDomainEventChannelName(ctx.destinations[i].channel, ctx.content.data.id);
671
+ pipeline.publish(key, data);
672
+ }
441
673
  }
674
+ await pipeline.exec();
442
675
  }
443
- return pipeline.exec();
444
- }
445
-
446
- let instance$3;
447
- function useSocketEmitter() {
448
- if (typeof instance$3 !== 'undefined') {
449
- return instance$3;
676
+ constructor(client){
677
+ this.driver = client;
450
678
  }
451
- instance$3 = new redisEmitter.Emitter(redisExtension.useClient());
452
- return instance$3;
453
679
  }
454
680
 
455
- function publishDomainSocketEvent(context, destinations) {
456
- if (!redisExtension.hasClient() && !redisExtension.hasConfig()) {
457
- return;
458
- }
459
- context = transformDomainEventData(context);
460
- for(let i = 0; i < destinations.length; i++){
461
- let emitter = useSocketEmitter();
462
- if (destinations[i].namespace) {
463
- emitter = emitter.of(destinations[i].namespace);
464
- }
465
- let roomName = buildDomainEventChannelName(destinations[i].channel);
466
- const fullEventName = core.buildDomainEventFullName(context.type, context.event);
467
- emitter.in(roomName)// eslint-disable-next-line @typescript-eslint/ban-ts-comment
468
- // @ts-ignore
469
- .emit(fullEventName, {
470
- ...context,
471
- meta: {
472
- roomName
681
+ class DomainEventSocketPublisher {
682
+ async publish(ctx) {
683
+ ctx.content = transformDomainEventData(ctx.content);
684
+ for(let i = 0; i < ctx.destinations.length; i++){
685
+ let emitter;
686
+ if (ctx.destinations[i].namespace) {
687
+ emitter = this.driver.of(ctx.destinations[i].namespace);
688
+ } else {
689
+ emitter = this.driver;
473
690
  }
474
- });
475
- if (context.event !== core.DomainEventName.CREATED && typeof destinations[i].channel === 'function') {
476
- roomName = buildDomainEventChannelName(destinations[i].channel, context.data.id);
477
- emitter.in(roomName)// eslint-disable-next-line @typescript-eslint/ban-ts-comment
478
- // @ts-ignore
479
- .emit(fullEventName, {
480
- ...context,
691
+ let roomName = buildDomainEventChannelName(ctx.destinations[i].channel);
692
+ const fullEventName = kit.buildEventFullName(ctx.content.type, ctx.content.event);
693
+ emitter.in(roomName).emit(fullEventName, {
694
+ ...ctx.content,
481
695
  meta: {
482
- roomName,
483
- roomId: context.data.id
696
+ roomName
484
697
  }
485
698
  });
699
+ if (typeof ctx.destinations[i].channel === 'function') {
700
+ roomName = buildDomainEventChannelName(ctx.destinations[i].channel, ctx.content.data.id);
701
+ emitter.in(roomName).emit(fullEventName, {
702
+ ...ctx.content,
703
+ meta: {
704
+ roomName,
705
+ roomId: ctx.content.data.id
706
+ }
707
+ });
708
+ }
486
709
  }
487
710
  }
488
- }
489
-
490
- async function publishDomainEvent(context, destinations) {
491
- await publishDomainRedisEvent(context, destinations);
492
- publishDomainSocketEvent(context, destinations);
493
- }
494
-
495
- /*
496
- * Copyright (c) 2022.
497
- * Author Peter Placzek (tada5hi)
498
- * For the full copyright and license information,
499
- * view the LICENSE file that was distributed with this source code.
500
- */ class VoidLogger {
501
- error() {
502
- return this;
503
- }
504
- warn() {
505
- return this;
506
- }
507
- info() {
508
- return this;
509
- }
510
- http() {
511
- return this;
512
- }
513
- verbose() {
514
- return this;
515
- }
516
- debug() {
517
- return this;
711
+ constructor(client){
712
+ this.driver = new redisEmitter.Emitter(client);
518
713
  }
519
714
  }
520
715
 
521
- let instance$2;
522
- function useLogger() {
523
- if (typeof instance$2 !== 'undefined') {
524
- return instance$2;
525
- }
526
- instance$2 = new VoidLogger();
527
- return instance$2;
528
- }
529
- function setLogger(logger) {
530
- instance$2 = logger;
531
- }
532
-
533
- class ProxyClient {
534
- /**
535
- * Create a http agent for an url.
536
- *
537
- * @param input
538
- */ async createAgent(input) {
539
- return new Promise((resolve, reject)=>{
540
- const headers = {};
541
- if (this.options.user && this.options.password) {
542
- headers['Proxy-Authorization'] = `Basic ${Buffer.from(`${this.options.user}:${this.options.password}`).toString('base64')}`;
716
+ class DomainEventPublisher {
717
+ async publish(ctx) {
718
+ const publishers = this.publishers.values();
719
+ while(true){
720
+ const it = publishers.next();
721
+ if (it.done) {
722
+ return;
543
723
  }
544
- const urlParsed = new URL(input);
545
- const request = http.request({
546
- host: this.options.host,
547
- port: this.options.port,
548
- method: 'CONNECT',
549
- path: `${urlParsed.hostname}:443`,
550
- headers
551
- });
552
- request.on('connect', (res, socket)=>{
553
- if (res.statusCode >= 200 && res.statusCode < 300) {
554
- resolve(new https.Agent({
555
- socket,
556
- ...this.agentOptions
557
- }));
558
- } else {
559
- reject(new Error('Could not connect to proxy!'));
560
- }
561
- });
562
- request.on('error', (err)=>{
563
- reject(err);
564
- });
565
- request.on('timeout', (err)=>{
566
- reject(err);
567
- });
568
- request.end();
569
- });
570
- }
571
- constructor(options, agentOptions){
572
- this.options = options;
573
- this.agentOptions = smob.merge(agentOptions || {}, {
574
- keepAlive: false
575
- });
576
- }
577
- }
578
-
579
- async function buildHTTPClientConfigForProxy(url) {
580
- const connectionString = proxyFromEnv.getProxyForUrl(url);
581
- if (connectionString) {
582
- const connectionDetails = core.parseProxyConnectionString(connectionString);
583
- const proxyClient = new ProxyClient({
584
- host: connectionDetails.host,
585
- port: connectionDetails.port || 3128,
586
- ...connectionDetails.auth.username ? {
587
- user: connectionDetails.auth.username
588
- } : {},
589
- ...connectionDetails.auth.password ? {
590
- password: connectionDetails.auth.password
591
- } : {}
592
- });
593
- const agent = await proxyClient.createAgent(url);
594
- return {
595
- agent
596
- };
597
- }
598
- return {};
599
- }
600
-
601
- /*
602
- * Copyright (c) 2022.
603
- * Author Peter Placzek (tada5hi)
604
- * For the full copyright and license information,
605
- * view the LICENSE file that was distributed with this source code.
606
- */ let instance$1;
607
- function hasSmtpConfig() {
608
- return !!instance$1;
609
- }
610
- function setSmtpConfig(value) {
611
- instance$1 = value;
612
- }
613
- function useSmtpConfig() {
614
- if (typeof instance$1 !== 'undefined') {
615
- return instance$1;
616
- }
617
- instance$1 = {};
618
- return instance$1;
619
- }
620
-
621
- function createSmtpClient(options) {
622
- let transport;
623
- options = options || {};
624
- if (typeof options === 'string') {
625
- transport = nodemailer.createTransport(options);
626
- } else if (options.connectionString) {
627
- transport = nodemailer.createTransport(options.connectionString);
628
- } else {
629
- let auth;
630
- if (options.user && options.password) {
631
- auth = {
632
- type: 'login',
633
- user: options.user,
634
- pass: options.password
635
- };
724
+ await it.value.publish(ctx);
636
725
  }
637
- transport = nodemailer.createTransport({
638
- host: options.host,
639
- port: options.port,
640
- auth,
641
- secure: options.ssl,
642
- opportunisticTLS: options.starttls,
643
- tls: {
644
- rejectUnauthorized: false
645
- }
646
- });
647
- }
648
- transport.on('error', (e)=>{
649
- useLogger().error(e.message);
650
- });
651
- return transport;
652
- }
653
-
654
- let instance;
655
- async function useSMTPClient() {
656
- if (typeof instance !== 'undefined') {
657
- return instance;
658
726
  }
659
- let options;
660
- if (process.env.NODE_ENV === 'test') {
661
- const testAccount = await nodemailer.createTestAccount();
662
- options = {
663
- host: 'smtp.ethereal.email',
664
- port: 587,
665
- ssl: false,
666
- user: testAccount.user,
667
- password: testAccount.pass
668
- };
669
- } else {
670
- options = useSmtpConfig();
727
+ constructor(){
728
+ this.publishers = new Set();
729
+ if (isRedisClientUsable()) {
730
+ const client = useRedisClient();
731
+ this.publishers.add(new DomainEventRedisPublisher(client));
732
+ this.publishers.add(new DomainEventSocketPublisher(client));
733
+ }
671
734
  }
672
- instance = createSmtpClient(options);
673
- return instance;
674
735
  }
675
736
 
676
737
  /*
@@ -682,34 +743,76 @@ async function useSMTPClient() {
682
743
  return Object.prototype.hasOwnProperty.call(obj, prop);
683
744
  }
684
745
 
685
- exports.ProxyClient = ProxyClient;
686
- exports.VoidLogger = VoidLogger;
687
- exports.buildHTTPClientConfigForProxy = buildHTTPClientConfigForProxy;
746
+ Object.defineProperty(exports, "Logger", {
747
+ enumerable: true,
748
+ get: function () { return winston.Logger; }
749
+ });
750
+ Object.defineProperty(exports, "RedisCache", {
751
+ enumerable: true,
752
+ get: function () { return redisExtension.Cache; }
753
+ });
754
+ Object.defineProperty(exports, "RedisClient", {
755
+ enumerable: true,
756
+ get: function () { return redisExtension.Client; }
757
+ });
758
+ Object.defineProperty(exports, "RedisClientOptions", {
759
+ enumerable: true,
760
+ get: function () { return redisExtension.ClientOptions; }
761
+ });
762
+ Object.defineProperty(exports, "RedisKeyPathID", {
763
+ enumerable: true,
764
+ get: function () { return redisExtension.KeyPathID; }
765
+ });
766
+ Object.defineProperty(exports, "buildRedisKeyPath", {
767
+ enumerable: true,
768
+ get: function () { return redisExtension.buildKeyPath; }
769
+ });
770
+ Object.defineProperty(exports, "createRedisClient", {
771
+ enumerable: true,
772
+ get: function () { return redisExtension.createClient; }
773
+ });
774
+ Object.defineProperty(exports, "VaultClient", {
775
+ enumerable: true,
776
+ get: function () { return vault.VaultClient; }
777
+ });
778
+ Object.defineProperty(exports, "createVaultClient", {
779
+ enumerable: true,
780
+ get: function () { return vault.createClient; }
781
+ });
782
+ exports.DomainEventPublisher = DomainEventPublisher;
783
+ exports.DomainEventRedisPublisher = DomainEventRedisPublisher;
784
+ exports.DomainEventSocketPublisher = DomainEventSocketPublisher;
688
785
  exports.buildKeyFileName = buildKeyFileName;
689
786
  exports.compare = compare;
690
787
  exports.createKeyPair = createKeyPair;
691
- exports.createSmtpClient = createSmtpClient;
692
- exports.decodeToken = decodeToken;
788
+ exports.createLogger = createLogger;
693
789
  exports.decryptRSAPrivateKey = decryptRSAPrivateKey;
694
790
  exports.deleteKeyPair = deleteKeyPair;
695
791
  exports.extendKeyPairOptions = extendKeyPairOptions;
792
+ exports.extractTokenHeader = extractTokenHeader;
793
+ exports.extractTokenPayload = extractTokenPayload;
696
794
  exports.hasOwnProperty = hasOwnProperty;
697
- exports.hasSmtpConfig = hasSmtpConfig;
698
795
  exports.hash = hash;
699
796
  exports.isKeyPair = isKeyPair;
700
797
  exports.isKeyPairWithPublicKey = isKeyPairWithPublicKey;
798
+ exports.isLoggerUsable = isLoggerUsable;
799
+ exports.isRedisClientUsable = isRedisClientUsable;
800
+ exports.isVaultClientUsable = isVaultClientUsable;
701
801
  exports.loadKeyPair = loadKeyPair;
702
- exports.publishDomainEvent = publishDomainEvent;
703
- exports.publishDomainRedisEvent = publishDomainRedisEvent;
704
- exports.publishDomainSocketEvent = publishDomainSocketEvent;
705
802
  exports.saveKeyPair = saveKeyPair;
706
803
  exports.setLogger = setLogger;
707
- exports.setSmtpConfig = setSmtpConfig;
804
+ exports.setLoggerFactory = setLoggerFactory;
805
+ exports.setRedisClient = setRedisClient;
806
+ exports.setRedisFactory = setRedisFactory;
807
+ exports.setVaultFactory = setVaultFactory;
708
808
  exports.signToken = signToken;
809
+ exports.unwrapPrivateKeyPem = unwrapPrivateKeyPem;
810
+ exports.unwrapPublicKeyPem = unwrapPublicKeyPem;
709
811
  exports.useKeyPair = useKeyPair;
710
812
  exports.useLogger = useLogger;
711
- exports.useSMTPClient = useSMTPClient;
712
- exports.useSmtpConfig = useSmtpConfig;
713
- exports.useSocketEmitter = useSocketEmitter;
813
+ exports.useRedisClient = useRedisClient;
814
+ exports.useVaultClient = useVaultClient;
714
815
  exports.verifyToken = verifyToken;
816
+ exports.wrapPrivateKeyPem = wrapPrivateKeyPem;
817
+ exports.wrapPublicKeyPem = wrapPublicKeyPem;
715
818
  //# sourceMappingURL=index.cjs.map