@authup/server-kit 1.0.0-beta.4 → 1.0.0-beta.40

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 (191) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1 -1
  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/index.d.ts +1 -1
  6. package/dist/crypto/index.d.ts.map +1 -1
  7. package/dist/crypto/json-web-token/extract.d.ts +16 -0
  8. package/dist/crypto/json-web-token/extract.d.ts.map +1 -0
  9. package/dist/crypto/json-web-token/index.d.ts +1 -1
  10. package/dist/crypto/json-web-token/index.d.ts.map +1 -1
  11. package/dist/crypto/json-web-token/sign/index.d.ts +3 -0
  12. package/dist/crypto/json-web-token/sign/index.d.ts.map +1 -0
  13. package/dist/crypto/json-web-token/sign/module.d.ts +4 -0
  14. package/dist/crypto/json-web-token/sign/module.d.ts.map +1 -0
  15. package/dist/crypto/json-web-token/sign/types.d.ts +28 -0
  16. package/dist/crypto/json-web-token/sign/types.d.ts.map +1 -0
  17. package/dist/crypto/json-web-token/type.d.ts +4 -33
  18. package/dist/crypto/json-web-token/type.d.ts.map +1 -1
  19. package/dist/crypto/json-web-token/utils.d.ts +5 -2
  20. package/dist/crypto/json-web-token/utils.d.ts.map +1 -1
  21. package/dist/crypto/json-web-token/verify/index.d.ts +3 -0
  22. package/dist/crypto/json-web-token/verify/index.d.ts.map +1 -0
  23. package/dist/crypto/json-web-token/verify/module.d.ts +12 -0
  24. package/dist/crypto/json-web-token/verify/module.d.ts.map +1 -0
  25. package/dist/crypto/json-web-token/verify/types.d.ts +25 -0
  26. package/dist/crypto/json-web-token/verify/types.d.ts.map +1 -0
  27. package/dist/crypto/key/asymmetric/check.d.ts +3 -0
  28. package/dist/crypto/key/asymmetric/check.d.ts.map +1 -0
  29. package/dist/crypto/key/asymmetric/constants.d.ts +8 -0
  30. package/dist/crypto/key/asymmetric/constants.d.ts.map +1 -0
  31. package/dist/crypto/key/asymmetric/create.d.ts +3 -0
  32. package/dist/crypto/key/asymmetric/create.d.ts.map +1 -0
  33. package/dist/crypto/key/asymmetric/helpers/index.d.ts +2 -0
  34. package/dist/crypto/key/asymmetric/helpers/index.d.ts.map +1 -0
  35. package/dist/crypto/key/asymmetric/helpers/wrap.d.ts +5 -0
  36. package/dist/crypto/key/asymmetric/helpers/wrap.d.ts.map +1 -0
  37. package/dist/crypto/key/asymmetric/index.d.ts +9 -0
  38. package/dist/crypto/key/asymmetric/index.d.ts.map +1 -0
  39. package/dist/crypto/key/asymmetric/key-usages.d.ts +5 -0
  40. package/dist/crypto/key/asymmetric/key-usages.d.ts.map +1 -0
  41. package/dist/crypto/key/asymmetric/module.d.ts +20 -0
  42. package/dist/crypto/key/asymmetric/module.d.ts.map +1 -0
  43. package/dist/crypto/key/asymmetric/normalize.d.ts +4 -0
  44. package/dist/crypto/key/asymmetric/normalize.d.ts.map +1 -0
  45. package/dist/crypto/key/asymmetric/types.d.ts +35 -0
  46. package/dist/crypto/key/asymmetric/types.d.ts.map +1 -0
  47. package/dist/crypto/key/base.d.ts +9 -0
  48. package/dist/crypto/key/base.d.ts.map +1 -0
  49. package/dist/crypto/key/index.d.ts +4 -0
  50. package/dist/crypto/key/index.d.ts.map +1 -0
  51. package/dist/crypto/key/symmetric/check.d.ts +3 -0
  52. package/dist/crypto/key/symmetric/check.d.ts.map +1 -0
  53. package/dist/crypto/key/symmetric/constants.d.ts +7 -0
  54. package/dist/crypto/key/symmetric/constants.d.ts.map +1 -0
  55. package/dist/crypto/key/symmetric/create.d.ts +3 -0
  56. package/dist/crypto/key/symmetric/create.d.ts.map +1 -0
  57. package/dist/crypto/key/symmetric/index.d.ts +7 -0
  58. package/dist/crypto/key/symmetric/index.d.ts.map +1 -0
  59. package/dist/crypto/key/symmetric/key-usages.d.ts +2 -0
  60. package/dist/crypto/key/symmetric/key-usages.d.ts.map +1 -0
  61. package/dist/crypto/key/symmetric/module.d.ts +13 -0
  62. package/dist/crypto/key/symmetric/module.d.ts.map +1 -0
  63. package/dist/crypto/key/symmetric/normalize.d.ts +4 -0
  64. package/dist/crypto/key/symmetric/normalize.d.ts.map +1 -0
  65. package/dist/crypto/key/symmetric/types.d.ts +32 -0
  66. package/dist/crypto/key/symmetric/types.d.ts.map +1 -0
  67. package/dist/domain-event/index.d.ts +1 -1
  68. package/dist/domain-event/index.d.ts.map +1 -1
  69. package/dist/domain-event/module.d.ts +9 -0
  70. package/dist/domain-event/module.d.ts.map +1 -0
  71. package/dist/domain-event/redis/index.d.ts +1 -1
  72. package/dist/domain-event/redis/index.d.ts.map +1 -1
  73. package/dist/domain-event/redis/module.d.ts +9 -0
  74. package/dist/domain-event/redis/module.d.ts.map +1 -0
  75. package/dist/domain-event/socket/index.d.ts +1 -2
  76. package/dist/domain-event/socket/index.d.ts.map +1 -1
  77. package/dist/domain-event/socket/module.d.ts +9 -0
  78. package/dist/domain-event/socket/module.d.ts.map +1 -0
  79. package/dist/domain-event/type.d.ts +8 -0
  80. package/dist/domain-event/type.d.ts.map +1 -1
  81. package/dist/domain-event/utils.d.ts +2 -1
  82. package/dist/domain-event/utils.d.ts.map +1 -1
  83. package/dist/index.d.mts +379 -0
  84. package/dist/index.d.mts.map +1 -0
  85. package/dist/index.d.ts +1 -2
  86. package/dist/index.d.ts.map +1 -1
  87. package/dist/index.mjs +705 -579
  88. package/dist/index.mjs.map +1 -1
  89. package/dist/services/cache/adapters/index.d.ts +3 -0
  90. package/dist/services/cache/adapters/index.d.ts.map +1 -0
  91. package/dist/services/cache/adapters/memory.d.ts +15 -0
  92. package/dist/services/cache/adapters/memory.d.ts.map +1 -0
  93. package/dist/services/cache/adapters/redis.d.ts +17 -0
  94. package/dist/services/cache/adapters/redis.d.ts.map +1 -0
  95. package/dist/services/cache/helper.d.ts +3 -0
  96. package/dist/services/cache/helper.d.ts.map +1 -0
  97. package/dist/services/cache/index.d.ts +4 -0
  98. package/dist/services/cache/index.d.ts.map +1 -0
  99. package/dist/services/cache/types.d.ts +25 -0
  100. package/dist/services/cache/types.d.ts.map +1 -0
  101. package/dist/services/index.d.ts +5 -0
  102. package/dist/services/index.d.ts.map +1 -0
  103. package/dist/services/logger/index.d.ts +4 -0
  104. package/dist/services/logger/index.d.ts.map +1 -0
  105. package/dist/services/logger/module.d.ts +4 -0
  106. package/dist/services/logger/module.d.ts.map +1 -0
  107. package/dist/services/logger/singleton.d.ts +7 -0
  108. package/dist/services/logger/singleton.d.ts.map +1 -0
  109. package/dist/services/logger/types.d.ts +7 -0
  110. package/dist/services/logger/types.d.ts.map +1 -0
  111. package/dist/services/redis/check.d.ts +3 -0
  112. package/dist/services/redis/check.d.ts.map +1 -0
  113. package/dist/services/redis/factory.d.ts +4 -0
  114. package/dist/services/redis/factory.d.ts.map +1 -0
  115. package/dist/services/redis/index.d.ts +4 -0
  116. package/dist/services/redis/index.d.ts.map +1 -0
  117. package/dist/services/redis/module.d.ts +5 -0
  118. package/dist/services/redis/module.d.ts.map +1 -0
  119. package/dist/services/vault/index.d.ts +3 -0
  120. package/dist/services/vault/index.d.ts.map +1 -0
  121. package/dist/services/vault/module.d.ts +3 -0
  122. package/dist/services/vault/module.d.ts.map +1 -0
  123. package/dist/services/vault/singleton.d.ts +6 -0
  124. package/dist/services/vault/singleton.d.ts.map +1 -0
  125. package/package.json +45 -34
  126. package/dist/crypto/json-web-token/decode.d.ts +0 -15
  127. package/dist/crypto/json-web-token/decode.d.ts.map +0 -1
  128. package/dist/crypto/json-web-token/sign.d.ts +0 -4
  129. package/dist/crypto/json-web-token/sign.d.ts.map +0 -1
  130. package/dist/crypto/json-web-token/verify.d.ts +0 -15
  131. package/dist/crypto/json-web-token/verify.d.ts.map +0 -1
  132. package/dist/crypto/key-pair/constants.d.ts +0 -5
  133. package/dist/crypto/key-pair/constants.d.ts.map +0 -1
  134. package/dist/crypto/key-pair/create.d.ts +0 -3
  135. package/dist/crypto/key-pair/create.d.ts.map +0 -1
  136. package/dist/crypto/key-pair/delete.d.ts +0 -3
  137. package/dist/crypto/key-pair/delete.d.ts.map +0 -1
  138. package/dist/crypto/key-pair/index.d.ts +0 -9
  139. package/dist/crypto/key-pair/index.d.ts.map +0 -1
  140. package/dist/crypto/key-pair/load.d.ts +0 -3
  141. package/dist/crypto/key-pair/load.d.ts.map +0 -1
  142. package/dist/crypto/key-pair/module.d.ts +0 -3
  143. package/dist/crypto/key-pair/module.d.ts.map +0 -1
  144. package/dist/crypto/key-pair/save.d.ts +0 -3
  145. package/dist/crypto/key-pair/save.d.ts.map +0 -1
  146. package/dist/crypto/key-pair/type.d.ts +0 -65
  147. package/dist/crypto/key-pair/type.d.ts.map +0 -1
  148. package/dist/crypto/key-pair/utils/check.d.ts +0 -4
  149. package/dist/crypto/key-pair/utils/check.d.ts.map +0 -1
  150. package/dist/crypto/key-pair/utils/file-name.d.ts +0 -4
  151. package/dist/crypto/key-pair/utils/file-name.d.ts.map +0 -1
  152. package/dist/crypto/key-pair/utils/index.d.ts +0 -5
  153. package/dist/crypto/key-pair/utils/index.d.ts.map +0 -1
  154. package/dist/crypto/key-pair/utils/options.d.ts +0 -3
  155. package/dist/crypto/key-pair/utils/options.d.ts.map +0 -1
  156. package/dist/crypto/key-pair/utils/private-key.d.ts +0 -4
  157. package/dist/crypto/key-pair/utils/private-key.d.ts.map +0 -1
  158. package/dist/domain-event/publish.d.ts +0 -4
  159. package/dist/domain-event/publish.d.ts.map +0 -1
  160. package/dist/domain-event/redis/publish.d.ts +0 -4
  161. package/dist/domain-event/redis/publish.d.ts.map +0 -1
  162. package/dist/domain-event/socket/publish.d.ts +0 -4
  163. package/dist/domain-event/socket/publish.d.ts.map +0 -1
  164. package/dist/domain-event/socket/singleton.d.ts +0 -4
  165. package/dist/domain-event/socket/singleton.d.ts.map +0 -1
  166. package/dist/domain-event/socket/type.d.ts +0 -5
  167. package/dist/domain-event/socket/type.d.ts.map +0 -1
  168. package/dist/index.cjs +0 -642
  169. package/dist/index.cjs.map +0 -1
  170. package/dist/logger/index.d.ts +0 -4
  171. package/dist/logger/index.d.ts.map +0 -1
  172. package/dist/logger/module.d.ts +0 -4
  173. package/dist/logger/module.d.ts.map +0 -1
  174. package/dist/logger/presets/index.d.ts +0 -2
  175. package/dist/logger/presets/index.d.ts.map +0 -1
  176. package/dist/logger/presets/void.d.ts +0 -16
  177. package/dist/logger/presets/void.d.ts.map +0 -1
  178. package/dist/logger/type.d.ts +0 -14
  179. package/dist/logger/type.d.ts.map +0 -1
  180. package/dist/smtp/config/index.d.ts +0 -2
  181. package/dist/smtp/config/index.d.ts.map +0 -1
  182. package/dist/smtp/config/singleton.d.ts +0 -5
  183. package/dist/smtp/config/singleton.d.ts.map +0 -1
  184. package/dist/smtp/index.d.ts +0 -5
  185. package/dist/smtp/index.d.ts.map +0 -1
  186. package/dist/smtp/module.d.ts +0 -4
  187. package/dist/smtp/module.d.ts.map +0 -1
  188. package/dist/smtp/singleton.d.ts +0 -3
  189. package/dist/smtp/singleton.d.ts.map +0 -1
  190. package/dist/smtp/type.d.ts +0 -14
  191. package/dist/smtp/type.d.ts.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,613 +1,739 @@
1
- import { compare as compare$1, hash as hash$1 } from 'bcrypt';
2
- import { createPrivateKey, generateKeyPair, createPublicKey } from 'node:crypto';
3
- import { isObject, TokenError, KeyType, DomainEventName, buildDomainEventFullName } from '@authup/core';
4
- import path from 'node:path';
5
- import fs from 'node:fs';
6
- import { decode, sign, verify } from 'jsonwebtoken';
7
- import { isObject as isObject$1 } from 'smob';
8
- import { hasClient, hasConfig, useClient } from 'redis-extension';
9
- import { Emitter } from '@socket.io/redis-emitter';
10
- import { createTransport, createTestAccount } from 'nodemailer';
11
-
1
+ import { compare as compare$1, hash as hash$1 } from "@node-rs/bcrypt";
2
+ import { arrayBufferToBase64, base64ToArrayBuffer, isObject } from "@authup/kit";
3
+ import { JWKType, JWTAlgorithm, JWTError } from "@authup/specs";
4
+ import { subtle } from "uncrypto";
5
+ import { Algorithm, sign, verify } from "@node-rs/jsonwebtoken";
6
+ import { isObject as isObject$1 } from "smob";
7
+ import { TTLCache } from "@isaacs/ttlcache";
8
+ import { Client as RedisClient, JsonAdapter, JsonAdapter as RedisJsonAdapter, Watcher as RedisWatcher, buildKeyPath as buildRedisKeyPath, createClient, escapeKey as escapeRedisKey, parseKeyPath as parseRedisKeyPath } from "redis-extension";
9
+ import path from "node:path";
10
+ import process from "node:process";
11
+ import { Logger, createLogger as createLogger$1, format, transports } from "winston";
12
+ import { singa } from "singa";
13
+ import { VaultClient, createClient as createVaultClient } from "@hapic/vault";
14
+ import { buildEventFullName } from "@authup/core-realtime-kit";
15
+ import { Emitter } from "@socket.io/redis-emitter";
16
+ //#region src/crypto/hash/compare.ts
12
17
  async function compare(value, hashedValue) {
13
- return compare$1(value, hashedValue);
18
+ return compare$1(value, hashedValue);
14
19
  }
15
-
16
- async function hash(str, saltOrRounds = 10) {
17
- return hash$1(str, saltOrRounds);
20
+ //#endregion
21
+ //#region src/crypto/hash/hash.ts
22
+ async function hash(str, rounds = 10) {
23
+ return hash$1(str, rounds);
18
24
  }
19
-
20
- /*
21
- * Copyright (c) 2022.
22
- * Author Peter Placzek (tada5hi)
23
- * For the full copyright and license information,
24
- * view the LICENSE file that was distributed with this source code.
25
- */ var KeyPairKind;
26
- (function(KeyPairKind) {
27
- KeyPairKind["PRIVATE"] = "private";
28
- KeyPairKind["PUBLIC"] = "public";
29
- })(KeyPairKind || (KeyPairKind = {}));
30
-
31
- function isKeyPair(data) {
32
- return isObject(data) && typeof data.privateKey !== 'undefined' && typeof data.publicKey !== 'undefined';
25
+ //#endregion
26
+ //#region src/crypto/key/asymmetric/constants.ts
27
+ let CryptoAsymmetricAlgorithm = /* @__PURE__ */ function(CryptoAsymmetricAlgorithm) {
28
+ CryptoAsymmetricAlgorithm["RSA_PSS"] = "RSA-PSS";
29
+ CryptoAsymmetricAlgorithm["RSASSA_PKCS1_V1_5"] = "RSASSA-PKCS1-v1_5";
30
+ CryptoAsymmetricAlgorithm["RSA_OAEP"] = "RSA-OAEP";
31
+ CryptoAsymmetricAlgorithm["ECDSA"] = "ECDSA";
32
+ CryptoAsymmetricAlgorithm["ECDH"] = "ECDH";
33
+ return CryptoAsymmetricAlgorithm;
34
+ }({});
35
+ //#endregion
36
+ //#region src/crypto/key/base.ts
37
+ var BaseKey = class {
38
+ key;
39
+ constructor(cryptoKey) {
40
+ this.key = cryptoKey;
41
+ }
42
+ async toArrayBuffer() {
43
+ if (this.key.type === "private") return subtle.exportKey("pkcs8", this.key);
44
+ if (this.key.type === "public") return subtle.exportKey("spki", this.key);
45
+ return subtle.exportKey("raw", this.key);
46
+ }
47
+ async toUint8Array() {
48
+ const arrayBuffer = await this.toArrayBuffer();
49
+ return new Uint8Array(arrayBuffer);
50
+ }
51
+ async toBase64() {
52
+ return arrayBufferToBase64(await this.toArrayBuffer());
53
+ }
54
+ async toJWK() {
55
+ return subtle.exportKey("jwk", this.key);
56
+ }
57
+ };
58
+ //#endregion
59
+ //#region src/crypto/key/asymmetric/helpers/wrap.ts
60
+ function enc(type, input) {
61
+ return `-----BEGIN ${type}-----\n${input}\n-----END ${type}-----`;
33
62
  }
34
- function isKeyPairWithPublicKey(data) {
35
- return isObject(data) && typeof data.publicKey !== 'undefined';
63
+ function encodePKCS8ToPEM(base64) {
64
+ return enc("PRIVATE KEY", base64);
36
65
  }
37
-
38
- function extendKeyPairOptions(options) {
39
- var _options;
40
- options = options ?? {};
41
- options.directory = options.directory || process.cwd();
42
- options.directory = path.isAbsolute(options.directory) ? options.directory : path.resolve(process.cwd(), options.directory);
43
- (_options = options).type ?? (_options.type = 'rsa');
44
- if (options.type === 'rsa' || options.type === 'rsa-pss' || options.type === 'dsa') {
45
- options.modulusLength = 2048;
46
- }
47
- if (!options.privateKeyEncoding) {
48
- options.privateKeyEncoding = {
49
- type: 'pkcs8',
50
- format: 'pem'
51
- };
52
- }
53
- if (!options.publicKeyEncoding) {
54
- options.publicKeyEncoding = {
55
- type: 'spki',
56
- format: 'pem'
57
- };
58
- }
59
- if (options.privateKeyEncoding.passphrase && !options.privateKeyEncoding.cipher) {
60
- options.privateKeyEncoding.cipher = 'aes-256-cbc';
61
- }
62
- return options;
66
+ function encodeSPKIToPem(input) {
67
+ return enc("PUBLIC KEY", input);
63
68
  }
64
-
65
- function buildKeyFileName(type, context) {
66
- const options = extendKeyPairOptions(context);
67
- const parts = [];
68
- switch(type){
69
- case KeyPairKind.PRIVATE:
70
- {
71
- if (options.privateName) {
72
- parts.push(options.privateName);
73
- } else {
74
- parts.push(type);
75
- }
76
- if (options.privateExtension) {
77
- if (options.privateExtension.startsWith('.')) {
78
- options.privateExtension = options.privateExtension.slice(1);
79
- }
80
- parts.push(options.privateExtension);
81
- } else {
82
- parts.push('pem');
83
- }
84
- break;
85
- }
86
- case KeyPairKind.PUBLIC:
87
- {
88
- if (options.publicName) {
89
- parts.push(options.publicName);
90
- } else {
91
- parts.push(type);
92
- }
93
- if (options.publicExtension) {
94
- if (options.publicExtension.startsWith('.')) {
95
- options.publicExtension = options.publicExtension.slice(1);
96
- }
97
- parts.push(options.publicExtension);
98
- } else {
99
- parts.push('pem');
100
- }
101
- break;
102
- }
103
- }
104
- return parts.join('.');
69
+ function dec(type, input) {
70
+ input = input.replace(`-----BEGIN ${type}-----\n`, "");
71
+ input = input.replace(`\n-----END ${type}-----\n`, "");
72
+ input = input.replace(`-----END ${type}-----\n`, "");
73
+ input = input.replace(`\n-----END ${type}-----`, "");
74
+ return input;
105
75
  }
106
-
107
- function decryptRSAPrivateKey(context, key) {
108
- const privateKey = createPrivateKey({
109
- type: context.privateKeyEncoding.type,
110
- format: context.privateKeyEncoding.format,
111
- key,
112
- passphrase: context.privateKeyEncoding.passphrase || context.passphrase
113
- });
114
- let content = privateKey.export({
115
- type: context.privateKeyEncoding.type,
116
- format: context.privateKeyEncoding.format
117
- });
118
- if (typeof content !== 'string') {
119
- content = Buffer.from(content).toString('utf-8');
120
- }
121
- return content;
76
+ function decodePemToPKCS8(input) {
77
+ return dec("PRIVATE KEY", input);
122
78
  }
123
-
124
- async function saveKeyPair(keyPair, context) {
125
- context = extendKeyPairOptions(context);
126
- await fs.promises.mkdir(context.directory, {
127
- recursive: true
128
- });
129
- await Promise.all([
130
- {
131
- path: path.resolve(context.directory, buildKeyFileName(KeyPairKind.PRIVATE, context)),
132
- content: keyPair.privateKey
133
- },
134
- {
135
- path: path.resolve(context.directory, buildKeyFileName(KeyPairKind.PUBLIC, context)),
136
- content: keyPair.publicKey
137
- }
138
- ].map((file)=>fs.promises.writeFile(file.path, file.content)));
139
- return keyPair;
79
+ function decodePemToSpki(input) {
80
+ return dec("PUBLIC KEY", input);
140
81
  }
141
-
142
- async function createKeyPair(context) {
143
- const options = extendKeyPairOptions(context);
144
- const keyPair = await new Promise((resolve, reject)=>{
145
- const callback = (err, publicKey, privateKey)=>{
146
- if (err) reject(err);
147
- resolve({
148
- privateKey,
149
- publicKey
150
- });
151
- };
152
- switch(options.type){
153
- case 'dsa':
154
- generateKeyPair(options.type, options, callback);
155
- break;
156
- case 'ec':
157
- generateKeyPair(options.type, options, callback);
158
- break;
159
- case 'rsa':
160
- generateKeyPair(options.type, options, callback);
161
- break;
162
- case 'rsa-pss':
163
- generateKeyPair(options.type, options, callback);
164
- break;
165
- }
166
- });
167
- if (options.save) {
168
- await saveKeyPair(keyPair, options);
169
- }
170
- if (options.passphrase || options.privateKeyEncoding.passphrase) {
171
- keyPair.privateKey = decryptRSAPrivateKey(options, keyPair.privateKey);
172
- }
173
- return keyPair;
82
+ //#endregion
83
+ //#region src/crypto/key/asymmetric/key-usages.ts
84
+ /**
85
+ * @see https://nodejs.org/api/webcrypto.html#cryptokeyusages
86
+ */
87
+ function getKeyUsagesForAsymmetricAlgorithm(name, format) {
88
+ if (name === "RSA-PSS" || name === "ECDSA" || name === "RSASSA-PKCS1-v1_5") {
89
+ if (format === "spki") return ["verify"];
90
+ if (format === "pkcs8") return ["sign"];
91
+ return ["sign", "verify"];
92
+ }
93
+ if (name === "ECDH") {
94
+ if (format === "spki") return [];
95
+ return ["deriveKey", "deriveBits"];
96
+ }
97
+ if (name === "RSA-OAEP") {
98
+ if (format === "spki") return ["encrypt"];
99
+ if (format === "pkcs8") return ["decrypt"];
100
+ return ["encrypt", "decrypt"];
101
+ }
102
+ throw new SyntaxError(`Key usages can not be determined for asymmetric algorithm: ${name}`);
174
103
  }
175
-
176
- async function deleteKeyPair(context) {
177
- const options = extendKeyPairOptions(context);
178
- const privateKeyPath = path.resolve(options.directory, buildKeyFileName(KeyPairKind.PRIVATE, options));
179
- const publicKeyPath = path.resolve(options.directory, buildKeyFileName(KeyPairKind.PUBLIC, options));
180
- try {
181
- await Promise.all([
182
- privateKeyPath,
183
- publicKeyPath
184
- ].map((filePath)=>fs.promises.stat(filePath)));
185
- } catch (e) {
186
- return;
187
- }
188
- await Promise.all([
189
- privateKeyPath,
190
- publicKeyPath
191
- ].map((filePath)=>fs.promises.rm(filePath)));
104
+ //#endregion
105
+ //#region src/crypto/key/asymmetric/normalize.ts
106
+ function normalizeAsymmetricKeyPairCreateOptions(options) {
107
+ let optionsNormalized;
108
+ switch (options.name) {
109
+ case "RSASSA-PKCS1-v1_5":
110
+ case "RSA-PSS":
111
+ case "RSA-OAEP":
112
+ optionsNormalized = {
113
+ modulusLength: 2048,
114
+ publicExponent: new Uint8Array([
115
+ 1,
116
+ 0,
117
+ 1
118
+ ]),
119
+ hash: "SHA-256",
120
+ ...options
121
+ };
122
+ break;
123
+ case "ECDSA":
124
+ case "ECDH": optionsNormalized = {
125
+ namedCurve: "P-256",
126
+ ...options
127
+ };
128
+ }
129
+ return optionsNormalized;
192
130
  }
193
-
194
- async function loadKeyPair(context) {
195
- const options = extendKeyPairOptions(context);
196
- const privateKeyPath = path.resolve(options.directory, buildKeyFileName(KeyPairKind.PRIVATE, options));
197
- try {
198
- await fs.promises.stat(privateKeyPath);
199
- } catch (e) {
200
- return undefined;
201
- }
202
- const privateKeyBuffer = await fs.promises.readFile(privateKeyPath);
203
- let privateKey = privateKeyBuffer.toString();
204
- if (options.passphrase || options.privateKeyEncoding.passphrase) {
205
- privateKey = decryptRSAPrivateKey(options, privateKey);
206
- }
207
- const publicKeyPath = path.resolve(options.directory, buildKeyFileName(KeyPairKind.PUBLIC, options));
208
- let publicKey;
209
- try {
210
- await fs.promises.stat(publicKeyPath);
211
- const publicKeyBuffer = await fs.promises.readFile(publicKeyPath);
212
- publicKey = publicKeyBuffer.toString();
213
- } catch (e) {
214
- const publicKeyObject = createPublicKey({
215
- key: privateKey,
216
- format: options.privateKeyEncoding.format,
217
- type: options.publicKeyEncoding.type
218
- });
219
- const stringOrBuffer = publicKeyObject.export({
220
- format: options.publicKeyEncoding.format,
221
- type: options.publicKeyEncoding.type
222
- });
223
- if (typeof stringOrBuffer !== 'string') {
224
- publicKey = stringOrBuffer.toString();
225
- } else {
226
- publicKey = stringOrBuffer;
227
- }
228
- if (options.save) {
229
- await saveKeyPair({
230
- privateKey,
231
- publicKey
232
- }, options);
233
- }
234
- }
235
- return {
236
- privateKey,
237
- publicKey
238
- };
131
+ function normalizeAsymmetricKeyImportOptions(options) {
132
+ let optionsNormalized;
133
+ switch (options.name) {
134
+ case "RSASSA-PKCS1-v1_5":
135
+ case "RSA-PSS":
136
+ case "RSA-OAEP":
137
+ optionsNormalized = {
138
+ hash: "SHA-256",
139
+ ...options
140
+ };
141
+ break;
142
+ case "ECDSA":
143
+ case "ECDH": optionsNormalized = {
144
+ namedCurve: "P-256",
145
+ ...options
146
+ };
147
+ }
148
+ return optionsNormalized;
239
149
  }
240
-
241
- const keyPairCache = {};
242
- async function useKeyPair(value) {
243
- let options;
244
- if (typeof value === 'string') {
245
- options = extendKeyPairOptions({
246
- privateName: value
247
- });
248
- } else {
249
- options = extendKeyPairOptions(value || {});
250
- }
251
- if (Object.prototype.hasOwnProperty.call(keyPairCache, options.privateName)) {
252
- return keyPairCache[options.privateName];
253
- }
254
- let keyPair = await loadKeyPair(options);
255
- if (typeof keyPair === 'undefined') {
256
- keyPair = await createKeyPair(options);
257
- }
258
- keyPairCache[options.privateName] = keyPair;
259
- return keyPair;
150
+ //#endregion
151
+ //#region src/crypto/key/asymmetric/module.ts
152
+ var AsymmetricKey = class AsymmetricKey extends BaseKey {
153
+ async toPem() {
154
+ const base64 = await this.toBase64();
155
+ if (this.key.type === "public") return encodeSPKIToPem(base64);
156
+ if (this.key.type === "private") return encodePKCS8ToPEM(base64);
157
+ throw new Error(`${this.key.type} can not be converted to pem.`);
158
+ }
159
+ static async fromPem(ctx) {
160
+ if (ctx.format === "pkcs8") return AsymmetricKey.fromBase64({
161
+ ...ctx,
162
+ key: decodePemToPKCS8(ctx.key)
163
+ });
164
+ return AsymmetricKey.fromBase64({
165
+ ...ctx,
166
+ key: decodePemToSpki(ctx.key)
167
+ });
168
+ }
169
+ static async fromBase64(ctx) {
170
+ const arrayBuffer = base64ToArrayBuffer(ctx.key);
171
+ return AsymmetricKey.fromArrayBuffer({
172
+ ...ctx,
173
+ key: arrayBuffer
174
+ });
175
+ }
176
+ static async fromArrayBuffer(ctx) {
177
+ const normalizedOptions = normalizeAsymmetricKeyImportOptions(ctx.options);
178
+ return new AsymmetricKey(await subtle.importKey(ctx.format, ctx.key, normalizedOptions, true, getKeyUsagesForAsymmetricAlgorithm(normalizedOptions.name, ctx.format)));
179
+ }
180
+ static buildImportOptionsForJWTAlgorithm(alg) {
181
+ if (alg === JWTAlgorithm.RS256) return {
182
+ name: "RSASSA-PKCS1-v1_5",
183
+ hash: "SHA-256"
184
+ };
185
+ if (alg === JWTAlgorithm.RS384) return {
186
+ name: "RSASSA-PKCS1-v1_5",
187
+ hash: "SHA-384"
188
+ };
189
+ if (alg === JWTAlgorithm.RS512) return {
190
+ name: "RSASSA-PKCS1-v1_5",
191
+ hash: "SHA-512"
192
+ };
193
+ if (alg === JWTAlgorithm.ES256) return {
194
+ name: "ECDSA",
195
+ namedCurve: "P-256"
196
+ };
197
+ if (alg === JWTAlgorithm.ES384) return {
198
+ name: "ECDSA",
199
+ namedCurve: "P-384"
200
+ };
201
+ if (alg === JWTAlgorithm.ES512) return {
202
+ name: "ECDSA",
203
+ namedCurve: "P-521"
204
+ };
205
+ throw new Error(`Signature algorithm ${alg} is not supported.`);
206
+ }
207
+ };
208
+ //#endregion
209
+ //#region src/crypto/key/asymmetric/check.ts
210
+ function isAsymmetricAlgorithm(input) {
211
+ return Object.values(CryptoAsymmetricAlgorithm).includes(input);
260
212
  }
261
-
213
+ //#endregion
214
+ //#region src/crypto/key/asymmetric/create.ts
215
+ async function createAsymmetricKeyPair(options) {
216
+ const optionsNormalized = normalizeAsymmetricKeyPairCreateOptions(options);
217
+ return subtle.generateKey(optionsNormalized, true, getKeyUsagesForAsymmetricAlgorithm(optionsNormalized.name));
218
+ }
219
+ //#endregion
220
+ //#region src/crypto/key/symmetric/constants.ts
221
+ let SymmetricAlgorithm = /* @__PURE__ */ function(SymmetricAlgorithm) {
222
+ SymmetricAlgorithm["HMAC"] = "HMAC";
223
+ SymmetricAlgorithm["AES_CTR"] = "AES-CTR";
224
+ SymmetricAlgorithm["AES_CBC"] = "AES-CBC";
225
+ SymmetricAlgorithm["AES_GCM"] = "AES-GCM";
226
+ return SymmetricAlgorithm;
227
+ }({});
228
+ //#endregion
229
+ //#region src/crypto/key/symmetric/check.ts
230
+ function isSymmetricAlgorithm(input) {
231
+ return Object.values(SymmetricAlgorithm).includes(input);
232
+ }
233
+ //#endregion
234
+ //#region src/crypto/key/symmetric/key-usages.ts
235
+ function getKeyUsagesForSymmetricAlgorithm(name) {
236
+ /**
237
+ * @see https://nodejs.org/api/webcrypto.html#cryptokeyusages
238
+ */
239
+ if (name === "HMAC") return ["sign", "verify"];
240
+ if (name === "AES-CBC" || name === "AES-GCM" || name === "AES-CTR") return ["encrypt", "decrypt"];
241
+ throw new SyntaxError(`Key usages can not be determined for symmetric algorithm: ${name}`);
242
+ }
243
+ //#endregion
244
+ //#region src/crypto/key/symmetric/normalize.ts
245
+ function normalizeSymmetricKeyCreateOptions(input) {
246
+ if (input.name === "HMAC") return {
247
+ hash: "SHA-256",
248
+ ...input
249
+ };
250
+ return {
251
+ length: 256,
252
+ name: input.name
253
+ };
254
+ }
255
+ function normalizeSymmetricKeyImportOptions(input) {
256
+ if (input.name === "HMAC") return {
257
+ hash: "SHA-256",
258
+ ...input
259
+ };
260
+ return input;
261
+ }
262
+ //#endregion
263
+ //#region src/crypto/key/symmetric/module.ts
264
+ var SymmetricKey = class SymmetricKey extends BaseKey {
265
+ static async fromBase64(ctx) {
266
+ const arrayBuffer = base64ToArrayBuffer(ctx.key);
267
+ return SymmetricKey.fromArrayBuffer({
268
+ ...ctx,
269
+ key: arrayBuffer
270
+ });
271
+ }
272
+ static async fromArrayBuffer(ctx) {
273
+ const normalizedOptions = normalizeSymmetricKeyImportOptions(ctx.options);
274
+ return new SymmetricKey(await subtle.importKey(ctx.format, ctx.key, normalizedOptions, true, getKeyUsagesForSymmetricAlgorithm(normalizedOptions.name)));
275
+ }
276
+ static buildImportOptionsForJWTAlgorithm(alg) {
277
+ if (alg === JWTAlgorithm.HS256) return {
278
+ name: "HMAC",
279
+ hash: "SHA-256"
280
+ };
281
+ if (alg === JWTAlgorithm.HS384) return {
282
+ name: "HMAC",
283
+ hash: "SHA-384"
284
+ };
285
+ if (alg === JWTAlgorithm.HS512) return {
286
+ name: "HMAC",
287
+ hash: "SHA-512"
288
+ };
289
+ throw new Error(`Signature algorithm ${alg} is not supported.`);
290
+ }
291
+ };
292
+ //#endregion
293
+ //#region src/crypto/key/symmetric/create.ts
294
+ async function createSymmetricKey(input) {
295
+ const optionsNormalized = normalizeSymmetricKeyCreateOptions(input);
296
+ return subtle.generateKey(optionsNormalized, true, getKeyUsagesForSymmetricAlgorithm(optionsNormalized.name));
297
+ }
298
+ //#endregion
299
+ //#region src/crypto/json-web-token/extract.ts
300
+ /**
301
+ * Decode a JWT token with no verification.
302
+ *
303
+ * @param token
304
+ *
305
+ * @throws JWTError
306
+ */
307
+ function extractTokenHeader(token) {
308
+ const parts = token.split(".");
309
+ if (parts.length !== 3) throw JWTError.invalid();
310
+ const [headerBase64] = parts;
311
+ try {
312
+ const payload = atob(headerBase64);
313
+ return JSON.parse(payload);
314
+ } catch {
315
+ throw JWTError.headerInvalid("The token header could not be extracted.");
316
+ }
317
+ }
318
+ /**
319
+ * @param token
320
+ *
321
+ * @throws JWTError
322
+ */
323
+ function extractTokenPayload(token) {
324
+ const parts = token.split(".");
325
+ if (parts.length !== 3) throw JWTError.invalid();
326
+ const [, payloadBase64] = parts;
327
+ try {
328
+ const payload = atob(payloadBase64);
329
+ return JSON.parse(payload);
330
+ } catch {
331
+ throw JWTError.payloadInvalid("The token payload could not be extracted.");
332
+ }
333
+ }
334
+ //#endregion
335
+ //#region src/crypto/json-web-token/utils.ts
262
336
  function createErrorForJWTError(e) {
263
- if (isObject$1(e) && typeof e.name === 'string') {
264
- switch(e.name){
265
- case 'TokenExpiredError':
266
- {
267
- return TokenError.expired();
268
- }
269
- case 'NotBeforeError':
270
- {
271
- if (typeof e.date === 'string' || e.date instanceof Date) {
272
- return TokenError.notActiveBefore(e.date);
273
- }
274
- break;
275
- }
276
- case 'JsonWebTokenError':
277
- {
278
- if (typeof e.message === 'string') {
279
- return TokenError.payloadInvalid(e.message);
280
- }
281
- break;
282
- }
283
- }
284
- }
285
- return new TokenError({
286
- cause: e,
287
- logMessage: true,
288
- message: 'The JWT error could not be determined.'
289
- });
337
+ if (isObject$1(e)) {
338
+ if (typeof e.name === "string") switch (e.name) {
339
+ case "TokenExpiredError": return JWTError.expired();
340
+ case "NotBeforeError":
341
+ if (typeof e.date === "string" || e.date instanceof Date) return JWTError.notActiveBefore(e.date);
342
+ break;
343
+ case "JsonWebTokenError":
344
+ if (typeof e.message === "string") return JWTError.payloadInvalid(e.message);
345
+ break;
346
+ }
347
+ switch (e.message) {
348
+ case "ExpiredSignature": return JWTError.expired();
349
+ case "ImmatureSignature": return JWTError.notActiveBefore();
350
+ case "InvalidToken":
351
+ case "InvalidSignature": return JWTError.payloadInvalid();
352
+ }
353
+ }
354
+ return new JWTError({
355
+ cause: e,
356
+ logMessage: true,
357
+ message: "The JWT error could not be determined."
358
+ });
290
359
  }
291
-
292
- function decodeToken(token, options) {
293
- options ?? (options = {});
294
- let output;
295
- try {
296
- output = decode(token, {
297
- ...options
298
- });
299
- } catch (e) {
300
- throw createErrorForJWTError(e);
301
- }
302
- if (output === null) {
303
- throw TokenError.payloadInvalid('The token could not be decoded.');
304
- }
305
- return output;
360
+ function transformJWTAlgorithmToInternal(algorithm) {
361
+ switch (algorithm) {
362
+ case JWTAlgorithm.HS256: return Algorithm.HS256;
363
+ case JWTAlgorithm.HS384: return Algorithm.HS384;
364
+ case JWTAlgorithm.HS512: return Algorithm.HS512;
365
+ case JWTAlgorithm.RS256: return Algorithm.RS256;
366
+ case JWTAlgorithm.RS384: return Algorithm.RS384;
367
+ case JWTAlgorithm.RS512: return Algorithm.RS512;
368
+ case JWTAlgorithm.ES256: return Algorithm.ES256;
369
+ case JWTAlgorithm.ES384: return Algorithm.ES384;
370
+ case JWTAlgorithm.PS256: return Algorithm.PS256;
371
+ case JWTAlgorithm.PS384: return Algorithm.PS384;
372
+ case JWTAlgorithm.PS512: return Algorithm.PS512;
373
+ }
374
+ throw new Error(`The algorithm ${algorithm} is not supported.`);
306
375
  }
307
-
308
- async function signToken(payload, context) {
309
- context.expiresIn = context.expiresIn || 3600;
310
- switch(context.type){
311
- case KeyType.RSA:
312
- case KeyType.EC:
313
- {
314
- const { type, keyPair, ...options } = context;
315
- const { privateKey } = isKeyPair(keyPair) ? keyPair : await useKeyPair(keyPair);
316
- if (type === KeyType.RSA) {
317
- options.algorithm = options.algorithm || 'RS256';
318
- } else {
319
- options.algorithm = options.algorithm || 'ES256';
320
- }
321
- return sign(payload, privateKey, options);
322
- }
323
- case KeyType.OCT:
324
- {
325
- const { type, secret, ...options } = context;
326
- options.algorithm = options.algorithm || 'HS256';
327
- return sign(payload, secret, options);
328
- }
329
- }
330
- throw new TokenError();
376
+ //#endregion
377
+ //#region src/crypto/json-web-token/sign/module.ts
378
+ const getUtcTimestamp = () => Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3);
379
+ async function signToken(claims, context) {
380
+ if (typeof claims.exp !== "number") claims.exp = getUtcTimestamp() + 3600;
381
+ if (typeof claims.iat !== "number") claims.iat = getUtcTimestamp();
382
+ switch (context.type) {
383
+ case JWKType.RSA:
384
+ case JWKType.EC: {
385
+ let algorithm;
386
+ let key;
387
+ if (typeof context.key === "string") key = encodePKCS8ToPEM(context.key);
388
+ else key = await new AsymmetricKey(context.key).toPem();
389
+ if (context.type === JWKType.RSA) algorithm = context.algorithm ? transformJWTAlgorithmToInternal(context.algorithm) : Algorithm.RS256;
390
+ else algorithm = context.algorithm ? transformJWTAlgorithmToInternal(context.algorithm) : Algorithm.ES256;
391
+ return sign(claims, key, {
392
+ algorithm,
393
+ keyId: context.keyId
394
+ });
395
+ }
396
+ case JWKType.OCT: {
397
+ const algorithm = context.algorithm ? transformJWTAlgorithmToInternal(context.algorithm) : Algorithm.HS256;
398
+ let key;
399
+ if (typeof context.key === "string") key = context.key;
400
+ else key = await new SymmetricKey(context.key).toUint8Array();
401
+ return sign(claims, key, {
402
+ algorithm,
403
+ keyId: context.keyId
404
+ });
405
+ }
406
+ }
407
+ throw new JWTError();
331
408
  }
332
-
409
+ //#endregion
410
+ //#region src/crypto/json-web-token/verify/module.ts
411
+ /**
412
+ * Verify JWT.
413
+ *
414
+ * @param token
415
+ * @param context
416
+ *
417
+ * @throws OAuth2Error
418
+ */
333
419
  async function verifyToken(token, context) {
334
- let promise;
335
- let output;
336
- try {
337
- switch(context.type){
338
- case KeyType.RSA:
339
- case KeyType.EC:
340
- {
341
- const { type, keyPair, ...options } = context;
342
- const { publicKey } = isKeyPairWithPublicKey(keyPair) ? keyPair : await useKeyPair(keyPair);
343
- if (type === KeyType.RSA) {
344
- options.algorithms = options.algorithms || [
345
- 'RS256',
346
- 'RS384',
347
- 'RS512',
348
- 'PS256',
349
- 'PS384',
350
- 'PS512'
351
- ];
352
- } else {
353
- options.algorithms = options.algorithms || [
354
- 'ES256',
355
- 'ES384',
356
- 'ES512'
357
- ];
358
- }
359
- promise = new Promise((resolve, reject)=>{
360
- verify(token, publicKey, options, (err, decoded)=>{
361
- if (err) {
362
- reject(err);
363
- return;
364
- }
365
- resolve(decoded);
366
- });
367
- });
368
- break;
369
- }
370
- case KeyType.OCT:
371
- {
372
- const { type, secret, ...options } = context;
373
- options.algorithms = options.algorithms || [
374
- 'HS256',
375
- 'HS384',
376
- 'HS512'
377
- ];
378
- promise = new Promise((resolve, reject)=>{
379
- verify(token, secret, options, (err, decoded)=>{
380
- if (err) {
381
- reject(err);
382
- return;
383
- }
384
- resolve(decoded);
385
- });
386
- });
387
- }
388
- }
389
- output = await promise;
390
- } catch (e) {
391
- throw createErrorForJWTError(e);
392
- }
393
- if (typeof output === 'undefined') {
394
- throw new TokenError({
395
- message: 'Invalid type.'
396
- });
397
- }
398
- return output;
420
+ let promise;
421
+ let output;
422
+ try {
423
+ switch (context.type) {
424
+ case JWKType.RSA:
425
+ case JWKType.EC: {
426
+ let algorithms;
427
+ if (context.type === JWKType.RSA) algorithms = context.algorithms ? context.algorithms.map((algorithm) => transformJWTAlgorithmToInternal(algorithm)) : [
428
+ Algorithm.RS256,
429
+ Algorithm.RS384,
430
+ Algorithm.RS512,
431
+ Algorithm.PS256,
432
+ Algorithm.PS384,
433
+ Algorithm.PS512
434
+ ];
435
+ else algorithms = context.algorithms ? context.algorithms.map((algorithm) => transformJWTAlgorithmToInternal(algorithm)) : [Algorithm.ES256, Algorithm.ES384];
436
+ let key;
437
+ if (typeof context.key === "string") key = encodeSPKIToPem(context.key);
438
+ else key = await new AsymmetricKey(context.key).toPem();
439
+ promise = verify(token, key, {
440
+ algorithms,
441
+ validateNbf: true
442
+ });
443
+ break;
444
+ }
445
+ case JWKType.OCT: {
446
+ const algorithms = context.algorithms ? context.algorithms.map((algorithm) => transformJWTAlgorithmToInternal(algorithm)) : [
447
+ Algorithm.HS256,
448
+ Algorithm.HS384,
449
+ Algorithm.HS512
450
+ ];
451
+ let key;
452
+ if (typeof context.key === "string") key = context.key;
453
+ else key = await new SymmetricKey(context.key).toUint8Array();
454
+ promise = verify(token, key, {
455
+ algorithms,
456
+ validateNbf: true
457
+ });
458
+ }
459
+ }
460
+ if (promise) output = await promise;
461
+ } catch (e) {
462
+ throw createErrorForJWTError(e);
463
+ }
464
+ if (!output) throw new JWTError();
465
+ return output;
399
466
  }
400
-
401
- function transformDomainEventData(input) {
402
- if (isObject(input)) {
403
- const keys = Object.keys(input);
404
- for(let i = 0; i < keys.length; i++){
405
- const value = input[keys[i]];
406
- if (value instanceof Date) {
407
- input[keys[i]] = value.toISOString();
408
- }
409
- }
410
- }
411
- return input;
467
+ //#endregion
468
+ //#region src/domain-event/module.ts
469
+ var DomainEventPublisher = class {
470
+ publishers;
471
+ constructor() {
472
+ this.publishers = /* @__PURE__ */ new Set();
473
+ }
474
+ mount(publisher) {
475
+ this.publishers.add(publisher);
476
+ }
477
+ async publish(ctx) {
478
+ const publishers = this.publishers.values();
479
+ while (true) {
480
+ const it = publishers.next();
481
+ if (it.done) return;
482
+ await it.value.publish(ctx);
483
+ }
484
+ }
485
+ };
486
+ //#endregion
487
+ //#region src/services/cache/adapters/memory.ts
488
+ var MemoryCache = class {
489
+ instance;
490
+ constructor(options = {}) {
491
+ this.instance = new TTLCache({
492
+ checkAgeOnGet: true,
493
+ ttl: Infinity,
494
+ ...options || {}
495
+ });
496
+ }
497
+ async pop(key) {
498
+ if (this.instance.has(key)) {
499
+ const output = this.instance.get(key);
500
+ this.instance.delete(key);
501
+ return output;
502
+ }
503
+ return null;
504
+ }
505
+ async has(key) {
506
+ return this.instance.has(key);
507
+ }
508
+ async get(key) {
509
+ const output = await this.instance.get(key);
510
+ if (output) return output;
511
+ return null;
512
+ }
513
+ async set(key, value, options) {
514
+ this.instance.set(key, value, { ttl: options.ttl });
515
+ }
516
+ async drop(key) {
517
+ this.instance.delete(key);
518
+ }
519
+ async dropMany(keys) {
520
+ for (const key of keys) this.instance.delete(key);
521
+ }
522
+ async clear(options = {}) {
523
+ if (options.prefix) {
524
+ const keys = this.instance.keys();
525
+ let iterator = keys.next();
526
+ while (!iterator.done) {
527
+ if (typeof iterator.value !== "string") continue;
528
+ if (iterator.value.startsWith(options.prefix)) this.instance.delete(iterator.value);
529
+ iterator = keys.next();
530
+ }
531
+ return;
532
+ }
533
+ this.instance.clear();
534
+ }
535
+ };
536
+ //#endregion
537
+ //#region src/services/redis/check.ts
538
+ function isRedisClient(data) {
539
+ return isObject$1(data) && typeof data.connect === "function" && typeof data.disconnect === "function";
412
540
  }
413
- function buildDomainEventChannelName(input, id) {
414
- if (typeof input === 'string') {
415
- return input;
416
- }
417
- return input(id);
541
+ //#endregion
542
+ //#region src/services/redis/factory.ts
543
+ function createRedisClient(input) {
544
+ if (typeof input === "boolean") return createClient({ connectionString: "redis://127.0.0.1" });
545
+ if (typeof input === "string") return createClient({ connectionString: input });
546
+ if (!isRedisClient(input)) return createClient({ options: input });
547
+ return input;
418
548
  }
419
-
420
- async function publishDomainRedisEvent(context, destinations) {
421
- if (!hasClient() && !hasConfig()) {
422
- return Promise.resolve();
423
- }
424
- context = transformDomainEventData(context);
425
- const json = JSON.stringify(context);
426
- const client = useClient();
427
- const pipeline = client.pipeline();
428
- for(let i = 0; i < destinations.length; i++){
429
- const { namespace } = destinations[i];
430
- const keyPrefix = namespace ? `${namespace}:` : '';
431
- let key = keyPrefix + buildDomainEventChannelName(destinations[i].channel);
432
- pipeline.publish(key, json);
433
- if (context.event !== DomainEventName.CREATED && typeof destinations[i].channel === 'function') {
434
- key = keyPrefix + buildDomainEventChannelName(destinations[i].channel, context.data.id);
435
- pipeline.publish(key, json);
436
- }
437
- }
438
- return pipeline.exec();
549
+ //#endregion
550
+ //#region src/services/cache/adapters/redis.ts
551
+ var RedisCache = class {
552
+ client;
553
+ jsonAdapter;
554
+ constructor(input) {
555
+ this.client = createRedisClient(input);
556
+ this.jsonAdapter = new JsonAdapter(this.client);
557
+ }
558
+ async get(key) {
559
+ const output = await this.jsonAdapter.get(key);
560
+ if (output) return output;
561
+ return null;
562
+ }
563
+ async pop(key) {
564
+ const raw = await this.client.getdel(key);
565
+ if (!raw) return null;
566
+ try {
567
+ return JSON.parse(raw);
568
+ } catch {
569
+ return null;
570
+ }
571
+ }
572
+ async has(key) {
573
+ return !!await this.get(key);
574
+ }
575
+ async set(key, value, options) {
576
+ await this.jsonAdapter.set(key, value, { milliseconds: options.ttl });
577
+ }
578
+ async drop(key) {
579
+ await this.jsonAdapter.drop(key);
580
+ }
581
+ async dropMany(keys) {
582
+ const pipeline = this.client.pipeline();
583
+ for (const key of keys) pipeline.del(key);
584
+ await pipeline.exec();
585
+ }
586
+ async clear(options = {}) {
587
+ if (options.prefix) {
588
+ const pipeline = this.client.pipeline();
589
+ const keys = await this.client.keys(`${options.prefix}*`);
590
+ for (const key of keys) pipeline.del(key);
591
+ await pipeline.exec();
592
+ return;
593
+ }
594
+ await this.client.flushdb();
595
+ }
596
+ };
597
+ //#endregion
598
+ //#region src/services/cache/helper.ts
599
+ function buildCacheKey(options) {
600
+ return buildRedisKeyPath(options);
439
601
  }
440
-
441
- let instance$3;
442
- function useSocketEmitter() {
443
- if (typeof instance$3 !== 'undefined') {
444
- return instance$3;
445
- }
446
- instance$3 = new Emitter(useClient());
447
- return instance$3;
602
+ //#endregion
603
+ //#region src/services/logger/module.ts
604
+ function createNoopLogger() {
605
+ return createLogger$1({ silent: true });
448
606
  }
449
-
450
- function publishDomainSocketEvent(context, destinations) {
451
- if (!hasClient() && !hasConfig()) {
452
- return;
453
- }
454
- context = transformDomainEventData(context);
455
- for(let i = 0; i < destinations.length; i++){
456
- let emitter = useSocketEmitter();
457
- if (destinations[i].namespace) {
458
- emitter = emitter.of(destinations[i].namespace);
459
- }
460
- let roomName = buildDomainEventChannelName(destinations[i].channel);
461
- const fullEventName = buildDomainEventFullName(context.type, context.event);
462
- emitter.in(roomName)// eslint-disable-next-line @typescript-eslint/ban-ts-comment
463
- // @ts-ignore
464
- .emit(fullEventName, {
465
- ...context,
466
- meta: {
467
- roomName
468
- }
469
- });
470
- if (context.event !== DomainEventName.CREATED && typeof destinations[i].channel === 'function') {
471
- roomName = buildDomainEventChannelName(destinations[i].channel, context.data.id);
472
- emitter.in(roomName)// eslint-disable-next-line @typescript-eslint/ban-ts-comment
473
- // @ts-ignore
474
- .emit(fullEventName, {
475
- ...context,
476
- meta: {
477
- roomName,
478
- roomId: context.data.id
479
- }
480
- });
481
- }
482
- }
607
+ function createLogger(context) {
608
+ let items;
609
+ const cwd = context.directory || process.cwd();
610
+ if (context.env === "production") items = [
611
+ new transports.Console({ level: "info" }),
612
+ new transports.File({
613
+ filename: path.join(cwd, "http.log"),
614
+ level: "http",
615
+ maxsize: 10 * 1024 * 1024,
616
+ maxFiles: 5
617
+ }),
618
+ new transports.File({
619
+ filename: path.join(cwd, "error.log"),
620
+ level: "warn",
621
+ maxsize: 10 * 1024 * 1024,
622
+ maxFiles: 5
623
+ })
624
+ ];
625
+ else items = [new transports.Console({ level: "debug" })];
626
+ return createLogger$1({
627
+ format: format.combine(format.errors({ stack: true }), format.timestamp(), format.colorize(), format.simple()),
628
+ transports: items
629
+ });
483
630
  }
484
-
485
- async function publishDomainEvent(context, destinations) {
486
- await publishDomainRedisEvent(context, destinations);
487
- publishDomainSocketEvent(context, destinations);
631
+ //#endregion
632
+ //#region src/services/logger/singleton.ts
633
+ const instance$1 = singa({ name: "logger" });
634
+ function setLoggerFactory(factory) {
635
+ instance$1.setFactory(factory);
488
636
  }
489
-
490
- /*
491
- * Copyright (c) 2022.
492
- * Author Peter Placzek (tada5hi)
493
- * For the full copyright and license information,
494
- * view the LICENSE file that was distributed with this source code.
495
- */ class VoidLogger {
496
- error() {
497
- return this;
498
- }
499
- warn() {
500
- return this;
501
- }
502
- info() {
503
- return this;
504
- }
505
- http() {
506
- return this;
507
- }
508
- verbose() {
509
- return this;
510
- }
511
- debug() {
512
- return this;
513
- }
637
+ function isLoggerUsable() {
638
+ return instance$1.has() || instance$1.hasFactory();
639
+ }
640
+ function setLogger(input) {
641
+ instance$1.set(input);
514
642
  }
515
-
516
- let instance$2;
517
643
  function useLogger() {
518
- if (typeof instance$2 !== 'undefined') {
519
- return instance$2;
520
- }
521
- instance$2 = new VoidLogger();
522
- return instance$2;
644
+ return instance$1.use();
523
645
  }
524
- function setLogger(logger) {
525
- instance$2 = logger;
646
+ //#endregion
647
+ //#region src/services/vault/singleton.ts
648
+ const instance = singa({ name: "vault" });
649
+ function setVaultFactory(factory) {
650
+ instance.setFactory(factory);
526
651
  }
527
-
528
- /*
529
- * Copyright (c) 2022.
530
- * Author Peter Placzek (tada5hi)
531
- * For the full copyright and license information,
532
- * view the LICENSE file that was distributed with this source code.
533
- */ let instance$1;
534
- function hasSmtpConfig() {
535
- return !!instance$1;
536
- }
537
- function setSmtpConfig(value) {
538
- instance$1 = value;
539
- }
540
- function useSmtpConfig() {
541
- if (typeof instance$1 !== 'undefined') {
542
- return instance$1;
543
- }
544
- instance$1 = {};
545
- return instance$1;
652
+ function isVaultClientUsable() {
653
+ return instance.has() || instance.hasFactory();
546
654
  }
547
-
548
- function createSmtpClient(options) {
549
- let transport;
550
- options = options || {};
551
- if (typeof options === 'string') {
552
- transport = createTransport(options);
553
- } else if (options.connectionString) {
554
- transport = createTransport(options.connectionString);
555
- } else {
556
- let auth;
557
- if (options.user && options.password) {
558
- auth = {
559
- type: 'login',
560
- user: options.user,
561
- pass: options.password
562
- };
563
- }
564
- transport = createTransport({
565
- host: options.host,
566
- port: options.port,
567
- auth,
568
- secure: options.ssl,
569
- opportunisticTLS: options.starttls,
570
- tls: {
571
- rejectUnauthorized: false
572
- }
573
- });
574
- }
575
- transport.on('error', (e)=>{
576
- useLogger().error(e.message);
577
- });
578
- return transport;
655
+ function useVaultClient() {
656
+ return instance.use();
579
657
  }
580
-
581
- let instance;
582
- async function useSMTPClient() {
583
- if (typeof instance !== 'undefined') {
584
- return instance;
585
- }
586
- let options;
587
- if (process.env.NODE_ENV === 'test') {
588
- const testAccount = await createTestAccount();
589
- options = {
590
- host: 'smtp.ethereal.email',
591
- port: 587,
592
- ssl: false,
593
- user: testAccount.user,
594
- password: testAccount.pass
595
- };
596
- } else {
597
- options = useSmtpConfig();
598
- }
599
- instance = createSmtpClient(options);
600
- return instance;
658
+ //#endregion
659
+ //#region src/domain-event/utils.ts
660
+ function transformDomainEventData(input) {
661
+ const keys = Object.keys(input);
662
+ for (const key_ of keys) {
663
+ const key = key_;
664
+ const value = input[key];
665
+ if (!isObject(value)) continue;
666
+ if (value instanceof Date) input[key] = value.toISOString();
667
+ }
668
+ return input;
601
669
  }
602
-
603
- /*
604
- * Copyright (c) 2022.
605
- * Author Peter Placzek (tada5hi)
606
- * For the full copyright and license information,
607
- * view the LICENSE file that was distributed with this source code.
608
- */ function hasOwnProperty(obj, prop) {
609
- return Object.prototype.hasOwnProperty.call(obj, prop);
670
+ function buildDomainEventChannelName(input, id) {
671
+ if (typeof input === "string") return input;
672
+ return input(id);
673
+ }
674
+ //#endregion
675
+ //#region src/domain-event/redis/module.ts
676
+ var DomainEventRedisPublisher = class {
677
+ driver;
678
+ constructor(input) {
679
+ this.driver = createRedisClient(input);
680
+ }
681
+ async publish(ctx) {
682
+ const data = JSON.stringify(transformDomainEventData(ctx.content));
683
+ const pipeline = this.driver.pipeline();
684
+ for (let i = 0; i < ctx.destinations.length; i++) {
685
+ const { namespace } = ctx.destinations[i];
686
+ const keyPrefix = namespace ? `${namespace}:` : "";
687
+ let key = keyPrefix + buildDomainEventChannelName(ctx.destinations[i].channel);
688
+ pipeline.publish(key, data);
689
+ if (typeof ctx.destinations[i].channel === "function") {
690
+ key = keyPrefix + buildDomainEventChannelName(ctx.destinations[i].channel, ctx.content.data.id);
691
+ pipeline.publish(key, data);
692
+ }
693
+ }
694
+ await pipeline.exec();
695
+ }
696
+ };
697
+ //#endregion
698
+ //#region src/domain-event/socket/module.ts
699
+ var DomainEventSocketPublisher = class {
700
+ driver;
701
+ constructor(input) {
702
+ const client = createRedisClient(input);
703
+ this.driver = new Emitter(client);
704
+ }
705
+ async publish(ctx) {
706
+ ctx.content = transformDomainEventData(ctx.content);
707
+ for (let i = 0; i < ctx.destinations.length; i++) {
708
+ const destination = ctx.destinations[i];
709
+ let emitter;
710
+ if (destination.namespace) emitter = this.driver.of(destination.namespace);
711
+ else emitter = this.driver;
712
+ let roomName = buildDomainEventChannelName(destination.channel);
713
+ const fullEventName = buildEventFullName(ctx.content.type, ctx.content.event);
714
+ emitter.in(roomName).emit(fullEventName, {
715
+ ...ctx.content,
716
+ meta: { roomName }
717
+ });
718
+ if (typeof destination.channel === "function") {
719
+ roomName = buildDomainEventChannelName(destination.channel, ctx.content.data.id);
720
+ emitter.in(roomName).emit(fullEventName, {
721
+ ...ctx.content,
722
+ meta: {
723
+ roomName,
724
+ roomId: ctx.content.data.id
725
+ }
726
+ });
727
+ }
728
+ }
729
+ }
730
+ };
731
+ //#endregion
732
+ //#region src/utils/has-property.ts
733
+ function hasOwnProperty(obj, prop) {
734
+ return Object.prototype.hasOwnProperty.call(obj, prop);
610
735
  }
736
+ //#endregion
737
+ export { AsymmetricKey, BaseKey, CryptoAsymmetricAlgorithm, DomainEventPublisher, DomainEventRedisPublisher, DomainEventSocketPublisher, Logger, MemoryCache, RedisCache, RedisClient, RedisJsonAdapter, RedisWatcher, SymmetricAlgorithm, SymmetricKey, VaultClient, buildCacheKey, buildRedisKeyPath, compare, createAsymmetricKeyPair, createLogger, createNoopLogger, createRedisClient, createSymmetricKey, createVaultClient, decodePemToPKCS8, decodePemToSpki, encodePKCS8ToPEM, encodeSPKIToPem, escapeRedisKey, extractTokenHeader, extractTokenPayload, getKeyUsagesForAsymmetricAlgorithm, getKeyUsagesForSymmetricAlgorithm, hasOwnProperty, hash, isAsymmetricAlgorithm, isLoggerUsable, isRedisClient, isSymmetricAlgorithm, isVaultClientUsable, normalizeAsymmetricKeyImportOptions, normalizeAsymmetricKeyPairCreateOptions, parseRedisKeyPath, setLogger, setLoggerFactory, setVaultFactory, signToken, useLogger, useVaultClient, verifyToken };
611
738
 
612
- export { KeyPairKind, VoidLogger, 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 };
613
- //# sourceMappingURL=index.mjs.map
739
+ //# sourceMappingURL=index.mjs.map