@authup/server-kit 1.0.0-beta.2 → 1.0.0-beta.20

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