@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.mjs CHANGED
@@ -1,23 +1,24 @@
1
- import { compare as compare$1, hash as hash$1 } from 'bcrypt';
1
+ import { compare as compare$1, hash as hash$1 } from '@node-rs/bcrypt';
2
2
  import { createPrivateKey, generateKeyPair, createPublicKey } from 'node:crypto';
3
- import { isObject, TokenError, KeyType, DomainEventName, buildDomainEventFullName, parseProxyConnectionString } from '@authup/core';
3
+ import { isObject, TokenError, JWTAlgorithm, JWKType, buildEventFullName } from '@authup/kit';
4
4
  import path from 'node:path';
5
5
  import fs from 'node:fs';
6
- import { decode, sign, verify } from 'jsonwebtoken';
7
- import { isObject as isObject$1, merge } from 'smob';
8
- import { hasClient, hasConfig, useClient } from 'redis-extension';
6
+ import { Algorithm, sign, verify } from '@node-rs/jsonwebtoken';
7
+ import { isObject as isObject$1 } from 'smob';
8
+ import * as process$1 from 'node:process';
9
+ import { transports, createLogger as createLogger$1, format } from 'winston';
10
+ export { Logger } from 'winston';
11
+ import { singa } from 'singa';
12
+ export { Cache as RedisCache, Client as RedisClient, ClientOptions as RedisClientOptions, KeyPathID as RedisKeyPathID, buildKeyPath as buildRedisKeyPath, createClient as createRedisClient } from 'redis-extension';
13
+ export { VaultClient, createClient as createVaultClient } from '@hapic/vault';
9
14
  import { Emitter } from '@socket.io/redis-emitter';
10
- import http from 'node:http';
11
- import https from 'node:https';
12
- import { getProxyForUrl } from 'proxy-from-env';
13
- import { createTransport, createTestAccount } from 'nodemailer';
14
15
 
15
16
  async function compare(value, hashedValue) {
16
17
  return compare$1(value, hashedValue);
17
18
  }
18
19
 
19
- async function hash(str, saltOrRounds = 10) {
20
- return hash$1(str, saltOrRounds);
20
+ async function hash(str, rounds = 10) {
21
+ return hash$1(str, rounds);
21
22
  }
22
23
 
23
24
  /*
@@ -124,6 +125,41 @@ function decryptRSAPrivateKey(context, key) {
124
125
  return content;
125
126
  }
126
127
 
128
+ /*
129
+ * Copyright (c) 2024.
130
+ * Author Peter Placzek (tada5hi)
131
+ * For the full copyright and license information,
132
+ * view the LICENSE file that was distributed with this source code.
133
+ */ function wrapPem(type, input) {
134
+ if (typeof input !== 'string') {
135
+ input = Buffer.from(input).toString('base64');
136
+ }
137
+ return `-----BEGIN ${type}-----\n${input}\n-----END ${type}-----`;
138
+ }
139
+ function wrapPrivateKeyPem(input) {
140
+ return wrapPem('PRIVATE KEY', input);
141
+ }
142
+ function wrapPublicKeyPem(input) {
143
+ return wrapPem('PUBLIC KEY', input);
144
+ }
145
+ // ------------------------------------------------------------
146
+ function unwrapPem(type, input) {
147
+ if (typeof input !== 'string') {
148
+ input = Buffer.from(input).toString('base64');
149
+ }
150
+ input = input.replace(`-----BEGIN ${type}-----\n`, '');
151
+ input = input.replace(`\n-----END ${type}-----\n`, '');
152
+ input = input.replace(`-----END ${type}-----\n`, '');
153
+ input = input.replace(`\n-----END ${type}-----`, '');
154
+ return input;
155
+ }
156
+ function unwrapPrivateKeyPem(input) {
157
+ return unwrapPem('PRIVATE KEY', input);
158
+ }
159
+ function unwrapPublicKeyPem(input) {
160
+ return unwrapPem('PUBLIC KEY', input);
161
+ }
162
+
127
163
  async function saveKeyPair(keyPair, context) {
128
164
  context = extendKeyPairOptions(context);
129
165
  await fs.promises.mkdir(context.directory, {
@@ -262,26 +298,89 @@ async function useKeyPair(value) {
262
298
  return keyPair;
263
299
  }
264
300
 
301
+ /**
302
+ * Decode a JWT token with no verification.
303
+ *
304
+ * @param token
305
+ *
306
+ * @throws TokenError
307
+ */ function extractTokenHeader(token) {
308
+ const parts = token.split('.');
309
+ if (parts.length !== 3) {
310
+ throw TokenError.payloadInvalid('The token format is not valid.');
311
+ }
312
+ const [headerBase64] = parts;
313
+ try {
314
+ const payload = atob(headerBase64);
315
+ return JSON.parse(payload);
316
+ /*
317
+ return {
318
+ typ: 'JWT',
319
+ alg: transformInternalToJWTAlgorithm(header.algorithm),
320
+ cty: header.contentType,
321
+ jku: header.jsonKeyUrl,
322
+ kid: header.keyId,
323
+ x5u: header.x5Url,
324
+ x5c: header.x5CertChain,
325
+ x5t: header.x5CertThumbprint,
326
+ 'x5t#S256': header.x5TS256CertThumbprint,
327
+ };
328
+ */ } catch (e) {
329
+ throw TokenError.headerInvalid('The token header could not be extracted.');
330
+ }
331
+ }
332
+ function extractTokenPayload(token) {
333
+ const parts = token.split('.');
334
+ if (parts.length !== 3) {
335
+ throw TokenError.payloadInvalid('The token format is not valid.');
336
+ }
337
+ const [, payloadBase64] = parts;
338
+ try {
339
+ const payload = atob(payloadBase64);
340
+ return JSON.parse(payload);
341
+ } catch (e) {
342
+ throw TokenError.payloadInvalid('The token payload could not be extracted.');
343
+ }
344
+ }
345
+
265
346
  function createErrorForJWTError(e) {
266
- if (isObject$1(e) && typeof e.name === 'string') {
267
- switch(e.name){
268
- case 'TokenExpiredError':
347
+ if (isObject$1(e)) {
348
+ if (typeof e.name === 'string') {
349
+ switch(e.name){
350
+ case 'TokenExpiredError':
351
+ {
352
+ return TokenError.expired();
353
+ }
354
+ case 'NotBeforeError':
355
+ {
356
+ if (typeof e.date === 'string' || e.date instanceof Date) {
357
+ return TokenError.notActiveBefore(e.date);
358
+ }
359
+ break;
360
+ }
361
+ case 'JsonWebTokenError':
362
+ {
363
+ if (typeof e.message === 'string') {
364
+ return TokenError.payloadInvalid(e.message);
365
+ }
366
+ break;
367
+ }
368
+ }
369
+ }
370
+ // @see https://github.com/Keats/jsonwebtoken/blob/master/src/errors.rs
371
+ switch(e.message){
372
+ case 'ExpiredSignature':
269
373
  {
270
374
  return TokenError.expired();
271
375
  }
272
- case 'NotBeforeError':
376
+ case 'ImmatureSignature':
273
377
  {
274
- if (typeof e.date === 'string' || e.date instanceof Date) {
275
- return TokenError.notActiveBefore(e.date);
276
- }
277
- break;
378
+ return TokenError.notActiveBefore();
278
379
  }
279
- case 'JsonWebTokenError':
380
+ case 'InvalidToken':
381
+ case 'InvalidSignature':
280
382
  {
281
- if (typeof e.message === 'string') {
282
- return TokenError.payloadInvalid(e.message);
283
- }
284
- break;
383
+ return TokenError.payloadInvalid();
285
384
  }
286
385
  }
287
386
  }
@@ -291,101 +390,140 @@ function createErrorForJWTError(e) {
291
390
  message: 'The JWT error could not be determined.'
292
391
  });
293
392
  }
294
-
295
- function decodeToken(token, options) {
296
- options ?? (options = {});
297
- let output;
298
- try {
299
- output = decode(token, {
300
- ...options
301
- });
302
- } catch (e) {
303
- throw createErrorForJWTError(e);
304
- }
305
- if (output === null) {
306
- throw TokenError.payloadInvalid('The token could not be decoded.');
393
+ function transformJWTAlgorithmToInternal(algorithm) {
394
+ switch(algorithm){
395
+ case JWTAlgorithm.HS256:
396
+ {
397
+ return Algorithm.HS256;
398
+ }
399
+ case JWTAlgorithm.HS384:
400
+ {
401
+ return Algorithm.HS384;
402
+ }
403
+ case JWTAlgorithm.HS512:
404
+ {
405
+ return Algorithm.HS512;
406
+ }
407
+ case JWTAlgorithm.RS256:
408
+ {
409
+ return Algorithm.RS256;
410
+ }
411
+ case JWTAlgorithm.RS384:
412
+ {
413
+ return Algorithm.RS384;
414
+ }
415
+ case JWTAlgorithm.RS512:
416
+ {
417
+ return Algorithm.RS512;
418
+ }
419
+ case JWTAlgorithm.ES256:
420
+ {
421
+ return Algorithm.ES256;
422
+ }
423
+ case JWTAlgorithm.ES384:
424
+ {
425
+ return Algorithm.ES384;
426
+ }
427
+ case JWTAlgorithm.PS256:
428
+ {
429
+ return Algorithm.PS256;
430
+ }
431
+ case JWTAlgorithm.PS384:
432
+ {
433
+ return Algorithm.PS384;
434
+ }
435
+ case JWTAlgorithm.PS512:
436
+ {
437
+ return Algorithm.PS512;
438
+ }
307
439
  }
308
- return output;
440
+ throw new Error(`The algorithm ${algorithm} is not supported.`);
309
441
  }
310
442
 
311
- async function signToken(payload, context) {
312
- context.expiresIn = context.expiresIn || 3600;
443
+ const getUtcTimestamp = ()=>Math.floor(new Date().getTime() / 1000);
444
+ async function signToken(claims, context) {
445
+ if (typeof claims.exp !== 'number') {
446
+ claims.exp = getUtcTimestamp() + 3600;
447
+ }
448
+ if (typeof claims.iat !== 'number') {
449
+ claims.iat = getUtcTimestamp();
450
+ }
313
451
  switch(context.type){
314
- case KeyType.RSA:
315
- case KeyType.EC:
452
+ case JWKType.RSA:
453
+ case JWKType.EC:
316
454
  {
317
- const { type, keyPair, ...options } = context;
318
- const { privateKey } = isKeyPair(keyPair) ? keyPair : await useKeyPair(keyPair);
319
- if (type === KeyType.RSA) {
320
- options.algorithm = options.algorithm || 'RS256';
455
+ const { privateKey } = isKeyPair(context.keyPair) ? context.keyPair : await useKeyPair(context.keyPair);
456
+ let algorithm;
457
+ if (context.type === JWKType.RSA) {
458
+ algorithm = context.algorithm ? transformJWTAlgorithmToInternal(context.algorithm) : Algorithm.RS256;
321
459
  } else {
322
- options.algorithm = options.algorithm || 'ES256';
460
+ algorithm = context.algorithm ? transformJWTAlgorithmToInternal(context.algorithm) : Algorithm.ES256;
323
461
  }
324
- return sign(payload, privateKey, options);
462
+ return sign(claims, privateKey, {
463
+ algorithm,
464
+ keyId: context.keyId
465
+ });
325
466
  }
326
- case KeyType.OCT:
467
+ case JWKType.OCT:
327
468
  {
328
- const { type, secret, ...options } = context;
329
- options.algorithm = options.algorithm || 'HS256';
330
- return sign(payload, secret, options);
469
+ const algorithm = context.algorithm ? transformJWTAlgorithmToInternal(context.algorithm) : Algorithm.HS256;
470
+ return sign(claims, context.key, {
471
+ algorithm,
472
+ keyId: context.keyId
473
+ });
331
474
  }
332
475
  }
333
476
  throw new TokenError();
334
477
  }
335
478
 
336
- async function verifyToken(token, context) {
479
+ /**
480
+ * Verify JWT.
481
+ *
482
+ * @param token
483
+ * @param context
484
+ *
485
+ * @throws TokenError
486
+ */ async function verifyToken(token, context) {
337
487
  let promise;
338
488
  let output;
339
489
  try {
340
490
  switch(context.type){
341
- case KeyType.RSA:
342
- case KeyType.EC:
491
+ case JWKType.RSA:
492
+ case JWKType.EC:
343
493
  {
344
- const { type, keyPair, ...options } = context;
345
- const { publicKey } = isKeyPairWithPublicKey(keyPair) ? keyPair : await useKeyPair(keyPair);
346
- if (type === KeyType.RSA) {
347
- options.algorithms = options.algorithms || [
348
- 'RS256',
349
- 'RS384',
350
- 'RS512',
351
- 'PS256',
352
- 'PS384',
353
- 'PS512'
494
+ const { publicKey } = isKeyPairWithPublicKey(context.keyPair) ? context.keyPair : await useKeyPair(context.keyPair);
495
+ let algorithms;
496
+ if (context.type === JWKType.RSA) {
497
+ algorithms = context.algorithms ? context.algorithms.map((algorithm)=>transformJWTAlgorithmToInternal(algorithm)) : [
498
+ Algorithm.RS256,
499
+ Algorithm.RS384,
500
+ Algorithm.RS512,
501
+ Algorithm.PS256,
502
+ Algorithm.PS384,
503
+ Algorithm.PS512
354
504
  ];
355
505
  } else {
356
- options.algorithms = options.algorithms || [
357
- 'ES256',
358
- 'ES384',
359
- 'ES512'
506
+ algorithms = context.algorithms ? context.algorithms.map((algorithm)=>transformJWTAlgorithmToInternal(algorithm)) : [
507
+ Algorithm.ES256,
508
+ Algorithm.ES384
360
509
  ];
361
510
  }
362
- promise = new Promise((resolve, reject)=>{
363
- verify(token, publicKey, options, (err, decoded)=>{
364
- if (err) {
365
- reject(err);
366
- return;
367
- }
368
- resolve(decoded);
369
- });
511
+ promise = verify(token, publicKey, {
512
+ algorithms,
513
+ validateNbf: true
370
514
  });
371
515
  break;
372
516
  }
373
- case KeyType.OCT:
517
+ case JWKType.OCT:
374
518
  {
375
- const { type, secret, ...options } = context;
376
- options.algorithms = options.algorithms || [
377
- 'HS256',
378
- 'HS384',
379
- 'HS512'
519
+ const algorithms = context.algorithms ? context.algorithms.map((algorithm)=>transformJWTAlgorithmToInternal(algorithm)) : [
520
+ Algorithm.HS256,
521
+ Algorithm.HS384,
522
+ Algorithm.HS512
380
523
  ];
381
- promise = new Promise((resolve, reject)=>{
382
- verify(token, secret, options, (err, decoded)=>{
383
- if (err) {
384
- reject(err);
385
- return;
386
- }
387
- resolve(decoded);
388
- });
524
+ promise = verify(token, context.key, {
525
+ algorithms,
526
+ validateNbf: true
389
527
  });
390
528
  }
391
529
  }
@@ -401,6 +539,85 @@ async function verifyToken(token, context) {
401
539
  return output;
402
540
  }
403
541
 
542
+ function createLogger(context) {
543
+ let items;
544
+ const cwd = context.directory || process$1.cwd();
545
+ if (context.env === 'production') {
546
+ items = [
547
+ new transports.Console({
548
+ level: 'info'
549
+ }),
550
+ new transports.File({
551
+ filename: path.join(cwd, 'access.log'),
552
+ level: 'http',
553
+ maxsize: 10 * 1024 * 1024,
554
+ maxFiles: 5
555
+ }),
556
+ new transports.File({
557
+ filename: path.join(cwd, 'error.log'),
558
+ level: 'warn',
559
+ maxsize: 10 * 1024 * 1024,
560
+ maxFiles: 5
561
+ })
562
+ ];
563
+ } else {
564
+ items = [
565
+ new transports.Console({
566
+ level: 'debug'
567
+ })
568
+ ];
569
+ }
570
+ return createLogger$1({
571
+ format: format.combine(format.timestamp(), format.json()),
572
+ transports: items
573
+ });
574
+ }
575
+
576
+ const instance$2 = singa({
577
+ name: 'logger'
578
+ });
579
+ function setLoggerFactory(factory) {
580
+ instance$2.setFactory(factory);
581
+ }
582
+ function isLoggerUsable() {
583
+ return instance$2.has() || instance$2.hasFactory();
584
+ }
585
+ function setLogger(input) {
586
+ instance$2.set(input);
587
+ }
588
+ function useLogger() {
589
+ return instance$2.use();
590
+ }
591
+
592
+ const instance$1 = singa({
593
+ name: 'redis'
594
+ });
595
+ function setRedisFactory(factory) {
596
+ instance$1.setFactory(factory);
597
+ }
598
+ function isRedisClientUsable() {
599
+ return instance$1.has() || instance$1.hasFactory();
600
+ }
601
+ function setRedisClient(input) {
602
+ instance$1.set(input);
603
+ }
604
+ function useRedisClient() {
605
+ return instance$1.use();
606
+ }
607
+
608
+ const instance = singa({
609
+ name: 'vault'
610
+ });
611
+ function setVaultFactory(factory) {
612
+ instance.setFactory(factory);
613
+ }
614
+ function isVaultClientUsable() {
615
+ return instance.has() || instance.hasFactory();
616
+ }
617
+ function useVaultClient() {
618
+ return instance.use();
619
+ }
620
+
404
621
  function transformDomainEventData(input) {
405
622
  if (isObject(input)) {
406
623
  const keys = Object.keys(input);
@@ -420,255 +637,81 @@ function buildDomainEventChannelName(input, id) {
420
637
  return input(id);
421
638
  }
422
639
 
423
- async function publishDomainRedisEvent(context, destinations) {
424
- if (!hasClient() && !hasConfig()) {
425
- return Promise.resolve();
426
- }
427
- context = transformDomainEventData(context);
428
- const json = JSON.stringify(context);
429
- const client = useClient();
430
- const pipeline = client.pipeline();
431
- for(let i = 0; i < destinations.length; i++){
432
- const { namespace } = destinations[i];
433
- const keyPrefix = namespace ? `${namespace}:` : '';
434
- let key = keyPrefix + buildDomainEventChannelName(destinations[i].channel);
435
- pipeline.publish(key, json);
436
- if (context.event !== DomainEventName.CREATED && typeof destinations[i].channel === 'function') {
437
- key = keyPrefix + buildDomainEventChannelName(destinations[i].channel, context.data.id);
438
- pipeline.publish(key, json);
640
+ class DomainEventRedisPublisher {
641
+ async publish(ctx) {
642
+ const data = JSON.stringify(transformDomainEventData(ctx.content));
643
+ const pipeline = this.driver.pipeline();
644
+ for(let i = 0; i < ctx.destinations.length; i++){
645
+ const { namespace } = ctx.destinations[i];
646
+ const keyPrefix = namespace ? `${namespace}:` : '';
647
+ let key = keyPrefix + buildDomainEventChannelName(ctx.destinations[i].channel);
648
+ pipeline.publish(key, data);
649
+ if (typeof ctx.destinations[i].channel === 'function') {
650
+ key = keyPrefix + buildDomainEventChannelName(ctx.destinations[i].channel, ctx.content.data.id);
651
+ pipeline.publish(key, data);
652
+ }
439
653
  }
654
+ await pipeline.exec();
440
655
  }
441
- return pipeline.exec();
442
- }
443
-
444
- let instance$3;
445
- function useSocketEmitter() {
446
- if (typeof instance$3 !== 'undefined') {
447
- return instance$3;
656
+ constructor(client){
657
+ this.driver = client;
448
658
  }
449
- instance$3 = new Emitter(useClient());
450
- return instance$3;
451
659
  }
452
660
 
453
- function publishDomainSocketEvent(context, destinations) {
454
- if (!hasClient() && !hasConfig()) {
455
- return;
456
- }
457
- context = transformDomainEventData(context);
458
- for(let i = 0; i < destinations.length; i++){
459
- let emitter = useSocketEmitter();
460
- if (destinations[i].namespace) {
461
- emitter = emitter.of(destinations[i].namespace);
462
- }
463
- let roomName = buildDomainEventChannelName(destinations[i].channel);
464
- const fullEventName = buildDomainEventFullName(context.type, context.event);
465
- emitter.in(roomName)// eslint-disable-next-line @typescript-eslint/ban-ts-comment
466
- // @ts-ignore
467
- .emit(fullEventName, {
468
- ...context,
469
- meta: {
470
- roomName
661
+ class DomainEventSocketPublisher {
662
+ async publish(ctx) {
663
+ ctx.content = transformDomainEventData(ctx.content);
664
+ for(let i = 0; i < ctx.destinations.length; i++){
665
+ let emitter;
666
+ if (ctx.destinations[i].namespace) {
667
+ emitter = this.driver.of(ctx.destinations[i].namespace);
668
+ } else {
669
+ emitter = this.driver;
471
670
  }
472
- });
473
- if (context.event !== DomainEventName.CREATED && typeof destinations[i].channel === 'function') {
474
- roomName = buildDomainEventChannelName(destinations[i].channel, context.data.id);
475
- emitter.in(roomName)// eslint-disable-next-line @typescript-eslint/ban-ts-comment
476
- // @ts-ignore
477
- .emit(fullEventName, {
478
- ...context,
671
+ let roomName = buildDomainEventChannelName(ctx.destinations[i].channel);
672
+ const fullEventName = buildEventFullName(ctx.content.type, ctx.content.event);
673
+ emitter.in(roomName).emit(fullEventName, {
674
+ ...ctx.content,
479
675
  meta: {
480
- roomName,
481
- roomId: context.data.id
676
+ roomName
482
677
  }
483
678
  });
679
+ if (typeof ctx.destinations[i].channel === 'function') {
680
+ roomName = buildDomainEventChannelName(ctx.destinations[i].channel, ctx.content.data.id);
681
+ emitter.in(roomName).emit(fullEventName, {
682
+ ...ctx.content,
683
+ meta: {
684
+ roomName,
685
+ roomId: ctx.content.data.id
686
+ }
687
+ });
688
+ }
484
689
  }
485
690
  }
486
- }
487
-
488
- async function publishDomainEvent(context, destinations) {
489
- await publishDomainRedisEvent(context, destinations);
490
- publishDomainSocketEvent(context, destinations);
491
- }
492
-
493
- /*
494
- * Copyright (c) 2022.
495
- * Author Peter Placzek (tada5hi)
496
- * For the full copyright and license information,
497
- * view the LICENSE file that was distributed with this source code.
498
- */ class VoidLogger {
499
- error() {
500
- return this;
501
- }
502
- warn() {
503
- return this;
504
- }
505
- info() {
506
- return this;
507
- }
508
- http() {
509
- return this;
510
- }
511
- verbose() {
512
- return this;
513
- }
514
- debug() {
515
- return this;
691
+ constructor(client){
692
+ this.driver = new Emitter(client);
516
693
  }
517
694
  }
518
695
 
519
- let instance$2;
520
- function useLogger() {
521
- if (typeof instance$2 !== 'undefined') {
522
- return instance$2;
523
- }
524
- instance$2 = new VoidLogger();
525
- return instance$2;
526
- }
527
- function setLogger(logger) {
528
- instance$2 = logger;
529
- }
530
-
531
- class ProxyClient {
532
- /**
533
- * Create a http agent for an url.
534
- *
535
- * @param input
536
- */ async createAgent(input) {
537
- return new Promise((resolve, reject)=>{
538
- const headers = {};
539
- if (this.options.user && this.options.password) {
540
- headers['Proxy-Authorization'] = `Basic ${Buffer.from(`${this.options.user}:${this.options.password}`).toString('base64')}`;
696
+ class DomainEventPublisher {
697
+ async publish(ctx) {
698
+ const publishers = this.publishers.values();
699
+ while(true){
700
+ const it = publishers.next();
701
+ if (it.done) {
702
+ return;
541
703
  }
542
- const urlParsed = new URL(input);
543
- const request = http.request({
544
- host: this.options.host,
545
- port: this.options.port,
546
- method: 'CONNECT',
547
- path: `${urlParsed.hostname}:443`,
548
- headers
549
- });
550
- request.on('connect', (res, socket)=>{
551
- if (res.statusCode >= 200 && res.statusCode < 300) {
552
- resolve(new https.Agent({
553
- socket,
554
- ...this.agentOptions
555
- }));
556
- } else {
557
- reject(new Error('Could not connect to proxy!'));
558
- }
559
- });
560
- request.on('error', (err)=>{
561
- reject(err);
562
- });
563
- request.on('timeout', (err)=>{
564
- reject(err);
565
- });
566
- request.end();
567
- });
568
- }
569
- constructor(options, agentOptions){
570
- this.options = options;
571
- this.agentOptions = merge(agentOptions || {}, {
572
- keepAlive: false
573
- });
574
- }
575
- }
576
-
577
- async function buildHTTPClientConfigForProxy(url) {
578
- const connectionString = getProxyForUrl(url);
579
- if (connectionString) {
580
- const connectionDetails = parseProxyConnectionString(connectionString);
581
- const proxyClient = new ProxyClient({
582
- host: connectionDetails.host,
583
- port: connectionDetails.port || 3128,
584
- ...connectionDetails.auth.username ? {
585
- user: connectionDetails.auth.username
586
- } : {},
587
- ...connectionDetails.auth.password ? {
588
- password: connectionDetails.auth.password
589
- } : {}
590
- });
591
- const agent = await proxyClient.createAgent(url);
592
- return {
593
- agent
594
- };
595
- }
596
- return {};
597
- }
598
-
599
- /*
600
- * Copyright (c) 2022.
601
- * Author Peter Placzek (tada5hi)
602
- * For the full copyright and license information,
603
- * view the LICENSE file that was distributed with this source code.
604
- */ let instance$1;
605
- function hasSmtpConfig() {
606
- return !!instance$1;
607
- }
608
- function setSmtpConfig(value) {
609
- instance$1 = value;
610
- }
611
- function useSmtpConfig() {
612
- if (typeof instance$1 !== 'undefined') {
613
- return instance$1;
614
- }
615
- instance$1 = {};
616
- return instance$1;
617
- }
618
-
619
- function createSmtpClient(options) {
620
- let transport;
621
- options = options || {};
622
- if (typeof options === 'string') {
623
- transport = createTransport(options);
624
- } else if (options.connectionString) {
625
- transport = createTransport(options.connectionString);
626
- } else {
627
- let auth;
628
- if (options.user && options.password) {
629
- auth = {
630
- type: 'login',
631
- user: options.user,
632
- pass: options.password
633
- };
704
+ await it.value.publish(ctx);
634
705
  }
635
- transport = createTransport({
636
- host: options.host,
637
- port: options.port,
638
- auth,
639
- secure: options.ssl,
640
- opportunisticTLS: options.starttls,
641
- tls: {
642
- rejectUnauthorized: false
643
- }
644
- });
645
- }
646
- transport.on('error', (e)=>{
647
- useLogger().error(e.message);
648
- });
649
- return transport;
650
- }
651
-
652
- let instance;
653
- async function useSMTPClient() {
654
- if (typeof instance !== 'undefined') {
655
- return instance;
656
706
  }
657
- let options;
658
- if (process.env.NODE_ENV === 'test') {
659
- const testAccount = await createTestAccount();
660
- options = {
661
- host: 'smtp.ethereal.email',
662
- port: 587,
663
- ssl: false,
664
- user: testAccount.user,
665
- password: testAccount.pass
666
- };
667
- } else {
668
- options = useSmtpConfig();
707
+ constructor(){
708
+ this.publishers = new Set();
709
+ if (isRedisClientUsable()) {
710
+ const client = useRedisClient();
711
+ this.publishers.add(new DomainEventRedisPublisher(client));
712
+ this.publishers.add(new DomainEventSocketPublisher(client));
713
+ }
669
714
  }
670
- instance = createSmtpClient(options);
671
- return instance;
672
715
  }
673
716
 
674
717
  /*
@@ -680,5 +723,5 @@ async function useSMTPClient() {
680
723
  return Object.prototype.hasOwnProperty.call(obj, prop);
681
724
  }
682
725
 
683
- export { KeyPairKind, ProxyClient, VoidLogger, buildHTTPClientConfigForProxy, buildKeyFileName, compare, createKeyPair, createSmtpClient, decodeToken, decryptRSAPrivateKey, deleteKeyPair, extendKeyPairOptions, hasOwnProperty, hasSmtpConfig, hash, isKeyPair, isKeyPairWithPublicKey, loadKeyPair, publishDomainEvent, publishDomainRedisEvent, publishDomainSocketEvent, saveKeyPair, setLogger, setSmtpConfig, signToken, useKeyPair, useLogger, useSMTPClient, useSmtpConfig, useSocketEmitter, verifyToken };
726
+ export { DomainEventPublisher, DomainEventRedisPublisher, DomainEventSocketPublisher, KeyPairKind, buildKeyFileName, compare, createKeyPair, createLogger, decryptRSAPrivateKey, deleteKeyPair, extendKeyPairOptions, extractTokenHeader, extractTokenPayload, hasOwnProperty, hash, isKeyPair, isKeyPairWithPublicKey, isLoggerUsable, isRedisClientUsable, isVaultClientUsable, loadKeyPair, saveKeyPair, setLogger, setLoggerFactory, setRedisClient, setRedisFactory, setVaultFactory, signToken, unwrapPrivateKeyPem, unwrapPublicKeyPem, useKeyPair, useLogger, useRedisClient, useVaultClient, verifyToken, wrapPrivateKeyPem, wrapPublicKeyPem };
684
727
  //# sourceMappingURL=index.mjs.map