@sdflc/backend-helpers 1.0.112 → 1.0.114

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 (214) hide show
  1. package/README.md +1422 -146
  2. package/build/BaseController.d.ts +20 -0
  3. package/build/BaseController.js +64 -0
  4. package/build/BaseCore.d.ts +586 -33
  5. package/build/BaseCore.js +821 -127
  6. package/build/BaseExternalApiGateway.d.ts +16 -0
  7. package/build/BaseExternalApiGateway.js +54 -0
  8. package/build/BaseGateway.d.ts +455 -17
  9. package/build/BaseGateway.js +502 -56
  10. package/build/BaseRestApiCrudController.d.ts +37 -0
  11. package/build/BaseRestApiCrudController.js +134 -0
  12. package/build/DataCache.d.ts +116 -5
  13. package/build/DataCache.js +144 -22
  14. package/build/Database.d.ts +165 -4
  15. package/build/Database.js +224 -51
  16. package/build/DbMigratorAndSeeder.d.ts +127 -26
  17. package/build/DbMigratorAndSeeder.js +180 -69
  18. package/build/IpRateLimiter.d.ts +105 -0
  19. package/build/IpRateLimiter.js +104 -0
  20. package/build/RedisDataLoader.d.ts +144 -21
  21. package/build/RedisDataLoader.js +178 -49
  22. package/build/apiContext.d.ts +0 -8
  23. package/build/apiContext.js +30 -32
  24. package/build/checkItHelpers.d.ts +32 -0
  25. package/build/checkItHelpers.js +73 -7
  26. package/build/commonValidators.d.ts +107 -16
  27. package/build/commonValidators.js +211 -106
  28. package/build/configBuilder.d.ts +23 -0
  29. package/build/configBuilder.js +73 -0
  30. package/build/constants.d.ts +134 -17
  31. package/build/constants.js +95 -15
  32. package/build/dbHelpers.d.ts +89 -29
  33. package/build/dbHelpers.js +175 -86
  34. package/build/dbSeeder.d.ts +10 -1
  35. package/build/dbSeeder.js +80 -15
  36. package/build/dbTableHelpers.d.ts +122 -5
  37. package/build/dbTableHelpers.js +151 -13
  38. package/build/downloadHelpers.d.ts +24 -1
  39. package/build/downloadHelpers.js +51 -21
  40. package/build/esm/BaseController.d.ts +20 -0
  41. package/build/esm/BaseController.js +58 -0
  42. package/build/esm/BaseCore.d.ts +586 -33
  43. package/build/esm/BaseCore.js +812 -118
  44. package/build/esm/BaseExternalApiGateway.d.ts +16 -0
  45. package/build/esm/BaseExternalApiGateway.js +48 -0
  46. package/build/esm/BaseGateway.d.ts +455 -17
  47. package/build/esm/BaseGateway.js +503 -57
  48. package/build/esm/BaseRestApiCrudController.d.ts +37 -0
  49. package/build/esm/BaseRestApiCrudController.js +131 -0
  50. package/build/esm/DataCache.d.ts +116 -5
  51. package/build/esm/DataCache.js +142 -20
  52. package/build/esm/Database.d.ts +165 -4
  53. package/build/esm/Database.js +224 -51
  54. package/build/esm/DbMigratorAndSeeder.d.ts +127 -26
  55. package/build/esm/DbMigratorAndSeeder.js +184 -71
  56. package/build/esm/IpRateLimiter.d.ts +105 -0
  57. package/build/esm/IpRateLimiter.js +100 -0
  58. package/build/esm/RedisDataLoader.d.ts +144 -21
  59. package/build/esm/RedisDataLoader.js +179 -50
  60. package/build/esm/apiContext.d.ts +0 -8
  61. package/build/esm/apiContext.js +30 -32
  62. package/build/esm/checkItHelpers.d.ts +32 -0
  63. package/build/esm/checkItHelpers.js +73 -7
  64. package/build/esm/commonValidators.d.ts +107 -16
  65. package/build/esm/commonValidators.js +209 -105
  66. package/build/esm/configBuilder.d.ts +23 -0
  67. package/build/esm/configBuilder.js +69 -0
  68. package/build/esm/constants.d.ts +134 -17
  69. package/build/esm/constants.js +94 -14
  70. package/build/esm/dbHelpers.d.ts +89 -29
  71. package/build/esm/dbHelpers.js +171 -81
  72. package/build/esm/dbSeeder.d.ts +10 -1
  73. package/build/esm/dbSeeder.js +81 -16
  74. package/build/esm/dbTableHelpers.d.ts +122 -5
  75. package/build/esm/dbTableHelpers.js +152 -14
  76. package/build/esm/downloadHelpers.d.ts +24 -1
  77. package/build/esm/downloadHelpers.js +51 -21
  78. package/build/esm/index.d.ts +6 -2
  79. package/build/esm/index.js +6 -2
  80. package/build/esm/interfaces/ApiContext.d.ts +33 -3
  81. package/build/esm/interfaces/ApiContext.js +1 -0
  82. package/build/esm/interfaces/ApiContextInterface.d.ts +1 -1
  83. package/build/esm/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  84. package/build/esm/interfaces/BaseControllerPropsInterface.js +1 -0
  85. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  86. package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  87. package/build/esm/interfaces/BaseCorePropsInterface.d.ts +146 -9
  88. package/build/esm/interfaces/BaseCorePropsInterface.js +1 -0
  89. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  90. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.js +2 -0
  91. package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  92. package/build/esm/interfaces/BaseGatewayPropsInterface.js +1 -0
  93. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  94. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.js +2 -0
  95. package/build/esm/interfaces/BuildConfigOptions.d.ts +18 -0
  96. package/build/esm/interfaces/BuildConfigOptions.js +1 -0
  97. package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  98. package/build/esm/interfaces/BuildListQueryArgsInterface.js +1 -0
  99. package/build/esm/interfaces/CacheInterface.d.ts +18 -1
  100. package/build/esm/interfaces/CacheInterface.js +1 -0
  101. package/build/esm/interfaces/CoreActionInterface.d.ts +60 -0
  102. package/build/esm/interfaces/CoreActionInterface.js +1 -0
  103. package/build/esm/interfaces/CreateUserTokenArgs.d.ts +38 -4
  104. package/build/esm/interfaces/CreateUserTokenArgs.js +1 -0
  105. package/build/esm/interfaces/DataCachePropsInterface.d.ts +21 -0
  106. package/build/esm/interfaces/DataCachePropsInterface.js +2 -0
  107. package/build/esm/interfaces/DatabaseOptions.d.ts +24 -10
  108. package/build/esm/interfaces/DatabaseOptions.js +1 -0
  109. package/build/esm/interfaces/DatabaseReadInterface.d.ts +58 -3
  110. package/build/esm/interfaces/DatabaseReadInterface.js +1 -0
  111. package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  112. package/build/esm/interfaces/DbFieldAddDefaultInterface.js +1 -0
  113. package/build/esm/interfaces/DownloadFileArgs.d.ts +21 -2
  114. package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  115. package/build/esm/interfaces/ExtractCredentialsArgs.js +1 -0
  116. package/build/esm/interfaces/ListArgsInterface.d.ts +18 -0
  117. package/build/esm/interfaces/ListArgsInterface.js +1 -0
  118. package/build/esm/interfaces/LoaderInterface.d.ts +36 -1
  119. package/build/esm/interfaces/LoaderInterface.js +1 -0
  120. package/build/esm/interfaces/UserTokenParams.d.ts +23 -5
  121. package/build/esm/interfaces/UserTokenParams.js +1 -0
  122. package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  123. package/build/esm/interfaces/VerifyUserTokenArgs.js +1 -0
  124. package/build/esm/interfaces/index.d.ts +4 -0
  125. package/build/esm/interfaces/index.js +4 -0
  126. package/build/esm/knexConfigBuilder.d.ts +25 -0
  127. package/build/esm/knexConfigBuilder.js +100 -36
  128. package/build/esm/parseIds.d.ts +6 -0
  129. package/build/esm/parseIds.js +13 -0
  130. package/build/esm/passwordHelpers.d.ts +22 -0
  131. package/build/esm/passwordHelpers.js +40 -8
  132. package/build/esm/redisClient.d.ts +57 -4
  133. package/build/esm/redisClient.js +40 -54
  134. package/build/esm/resolveClientIp.d.ts +15 -0
  135. package/build/esm/resolveClientIp.js +34 -0
  136. package/build/esm/resolversHelpers.d.ts +21 -1
  137. package/build/esm/resolversHelpers.js +48 -26
  138. package/build/esm/userToken.d.ts +50 -1
  139. package/build/esm/userToken.js +85 -20
  140. package/build/esm/utils.d.ts +20 -2
  141. package/build/esm/utils.js +23 -13
  142. package/build/index.d.ts +6 -2
  143. package/build/index.js +6 -2
  144. package/build/interfaces/ApiContext.d.ts +33 -3
  145. package/build/interfaces/ApiContext.js +1 -0
  146. package/build/interfaces/ApiContextInterface.d.ts +1 -1
  147. package/build/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  148. package/build/interfaces/BaseControllerPropsInterface.js +2 -0
  149. package/build/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  150. package/build/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  151. package/build/interfaces/BaseCorePropsInterface.d.ts +146 -9
  152. package/build/interfaces/BaseCorePropsInterface.js +1 -0
  153. package/build/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  154. package/build/interfaces/BaseExternalApiGatewayPropsInterface.js +3 -0
  155. package/build/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  156. package/build/interfaces/BaseGatewayPropsInterface.js +1 -0
  157. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  158. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.js +3 -0
  159. package/build/interfaces/BuildConfigOptions.d.ts +18 -0
  160. package/build/interfaces/BuildConfigOptions.js +1 -0
  161. package/build/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  162. package/build/interfaces/BuildListQueryArgsInterface.js +1 -0
  163. package/build/interfaces/CacheInterface.d.ts +18 -1
  164. package/build/interfaces/CacheInterface.js +1 -0
  165. package/build/interfaces/CoreActionInterface.d.ts +60 -0
  166. package/build/interfaces/CoreActionInterface.js +1 -0
  167. package/build/interfaces/CreateUserTokenArgs.d.ts +38 -4
  168. package/build/interfaces/CreateUserTokenArgs.js +1 -0
  169. package/build/interfaces/DataCachePropsInterface.d.ts +21 -0
  170. package/build/interfaces/DataCachePropsInterface.js +3 -0
  171. package/build/interfaces/DatabaseOptions.d.ts +24 -10
  172. package/build/interfaces/DatabaseOptions.js +1 -0
  173. package/build/interfaces/DatabaseReadInterface.d.ts +58 -3
  174. package/build/interfaces/DatabaseReadInterface.js +1 -0
  175. package/build/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  176. package/build/interfaces/DbFieldAddDefaultInterface.js +1 -0
  177. package/build/interfaces/DownloadFileArgs.d.ts +21 -2
  178. package/build/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  179. package/build/interfaces/ExtractCredentialsArgs.js +1 -0
  180. package/build/interfaces/ListArgsInterface.d.ts +18 -0
  181. package/build/interfaces/ListArgsInterface.js +1 -0
  182. package/build/interfaces/LoaderInterface.d.ts +36 -1
  183. package/build/interfaces/LoaderInterface.js +1 -0
  184. package/build/interfaces/UserTokenParams.d.ts +23 -5
  185. package/build/interfaces/UserTokenParams.js +1 -0
  186. package/build/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  187. package/build/interfaces/VerifyUserTokenArgs.js +1 -0
  188. package/build/interfaces/index.d.ts +4 -0
  189. package/build/interfaces/index.js +4 -0
  190. package/build/knexConfigBuilder.d.ts +25 -0
  191. package/build/knexConfigBuilder.js +99 -35
  192. package/build/parseIds.d.ts +6 -0
  193. package/build/parseIds.js +17 -0
  194. package/build/passwordHelpers.d.ts +22 -0
  195. package/build/passwordHelpers.js +40 -8
  196. package/build/redisClient.d.ts +57 -4
  197. package/build/redisClient.js +40 -54
  198. package/build/resolveClientIp.d.ts +15 -0
  199. package/build/resolveClientIp.js +38 -0
  200. package/build/resolversHelpers.d.ts +21 -1
  201. package/build/resolversHelpers.js +48 -26
  202. package/build/userToken.d.ts +50 -1
  203. package/build/userToken.js +85 -20
  204. package/build/utils.d.ts +20 -2
  205. package/build/utils.js +24 -16
  206. package/package.json +19 -18
  207. package/build/baseController.d.ts +0 -17
  208. package/build/baseController.js +0 -64
  209. package/build/configBulder.d.ts +0 -2
  210. package/build/configBulder.js +0 -36
  211. package/build/esm/baseController.d.ts +0 -17
  212. package/build/esm/baseController.js +0 -58
  213. package/build/esm/configBulder.d.ts +0 -2
  214. package/build/esm/configBulder.js +0 -32
@@ -1,35 +1,56 @@
1
1
  "use strict";
2
+ // ./src/redisClient.ts
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
3
4
  exports.createRedisClient = void 0;
4
5
  const redis_1 = require("redis");
5
- // const DEFAULT_RETRY_ATTEMPTS = 10;
6
- // const DEFAULT_FIRST_TIMEOUT = 3000;
6
+ /**
7
+ * Creates and configures a Redis client without connecting.
8
+ *
9
+ * The caller is responsible for calling `await redisClient.connect()`
10
+ * when ready — this is intentional to allow the client to be created
11
+ * early in the startup sequence and connected at a controlled point.
12
+ *
13
+ * Returns null if `redisHost` is not provided.
14
+ *
15
+ * Socket behaviour:
16
+ * - `family: 0` — tries IPv6 first, falls back to IPv4
17
+ * - `noDelay: true` — disables Nagle's algorithm for lower latency
18
+ * - `keepAlive: true` — enables TCP keep-alive to detect dead connections
19
+ * - Reconnect delay grows linearly (retries × 50ms), capped at `maxReconnectDelay`
20
+ *
21
+ * @param args CreateRedisClientInterface configuration
22
+ * @returns Configured but unconnected Redis client, or null if redisHost is absent
23
+ */
7
24
  const createRedisClient = (args) => {
8
- const { redisHost, redisPort, redisPassword, redisSsl,
9
- //retryAttempts,
10
- //firstTimeout,
11
- pingInterval, connectionTimeout, onConnecting, onConnected, onDisconnected, onReconnecting, onError, } = args || {};
25
+ const { redisHost, redisPort, redisPassword, redisSsl, rejectUnauthorized, pingInterval, connectionTimeout, maxReconnectDelay, onConnecting, onConnected, onDisconnected, onReconnecting, onError, } = args || {};
12
26
  if (!redisHost) {
13
27
  return null;
14
28
  }
29
+ const maxDelay = maxReconnectDelay ?? 500;
15
30
  const baseSocketConfig = {
16
31
  host: redisHost,
17
32
  port: Number(redisPort),
18
33
  family: 0,
19
- connectTimeout: connectionTimeout != undefined ? connectionTimeout : 5000,
34
+ connectTimeout: connectionTimeout ?? 5000,
20
35
  noDelay: true,
21
36
  keepAlive: true,
22
- keepAliveInitialDelay: pingInterval != undefined ? pingInterval : 5000,
23
- reconnectStrategy: (retries) => Math.min(retries * 50, 500),
37
+ keepAliveInitialDelay: pingInterval ?? 5000,
38
+ reconnectStrategy: (retries) => Math.min(retries * 50, maxDelay),
24
39
  };
25
40
  const socketConfig = redisSsl
26
- ? { ...baseSocketConfig, tls: true, rejectUnauthorized: false }
27
- : { ...baseSocketConfig, tls: false };
28
- const cfg = {
41
+ ? {
42
+ ...baseSocketConfig,
43
+ tls: true,
44
+ rejectUnauthorized: rejectUnauthorized ?? true,
45
+ }
46
+ : {
47
+ ...baseSocketConfig,
48
+ tls: false,
49
+ };
50
+ const redisClient = (0, redis_1.createClient)({
29
51
  socket: socketConfig,
30
52
  password: redisPassword || undefined,
31
- };
32
- const redisClient = (0, redis_1.createClient)(cfg);
53
+ });
33
54
  redisClient.on('connect', () => {
34
55
  if (typeof onConnecting === 'function') {
35
56
  onConnecting();
@@ -54,47 +75,12 @@ const createRedisClient = (args) => {
54
75
  if (typeof onError === 'function') {
55
76
  onError(err);
56
77
  }
78
+ else {
79
+ // Default handler prevents unhandled 'error' events from crashing
80
+ // the Node.js process — an unhandled EventEmitter error event throws.
81
+ console.error('Redis client error (no onError handler provided):', err);
82
+ }
57
83
  });
58
- // const redisClientOld = redis.createClient({
59
- // host: redisHost,
60
- // port: Number(redisPort),
61
- // password: redisPassword || undefined,
62
- // no_ready_check: true,
63
- // retry_strategy: function (options) {
64
- // if (options.error && options.error.code === 'ECONNREFUSED') {
65
- // // End reconnecting on a specific error and flush all commands with
66
- // // a individual error
67
- // return new Error('The server refused the connection');
68
- // }
69
- // if (options.total_retry_time > 1000 * 60 * 60) {
70
- // // End reconnecting after a specific timeout and flush all commands
71
- // // with a individual error
72
- // return new Error('Retry time exhausted');
73
- // }
74
- // const attempts =
75
- // !retryAttempts || retryAttempts == null || isNaN(retryAttempts)
76
- // ? DEFAULT_RETRY_ATTEMPTS
77
- // : Number(retryAttempts);
78
- // if (options.attempt > attempts) {
79
- // // End reconnecting with built in error
80
- // return undefined;
81
- // }
82
- // const timeout =
83
- // !firstTimeout || firstTimeout == null || isNaN(firstTimeout) ? DEFAULT_FIRST_TIMEOUT : Number(firstTimeout);
84
- // // reconnect after
85
- // return Math.min(options.attempt * 100, timeout);
86
- // },
87
- // tls: redisSsl
88
- // ? {
89
- // servername: redisHost,
90
- // }
91
- // : undefined,
92
- // });
93
- // if (pingInterval && !isNaN(pingInterval) && pingInterval > 1000) {
94
- // setInterval(async () => {
95
- // redisClient.ping();
96
- // }, pingInterval);
97
- // }
98
84
  return redisClient;
99
85
  };
100
86
  exports.createRedisClient = createRedisClient;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Resolves the real client IP address from request headers,
3
+ * accounting for common reverse proxies (nginx, Cloudflare, etc.).
4
+ *
5
+ * Priority:
6
+ * 1. X-Real-IP — set by nginx, single trusted IP
7
+ * 2. CF-Connecting-IP — set by Cloudflare, single trusted IP
8
+ * 3. X-Forwarded-For — leftmost entry is original client,
9
+ * but the header can contain a chain
10
+ * 4. req.socket.remoteAddress — direct TCP connection (may be the proxy)
11
+ *
12
+ * Note: X-Forwarded-For can be spoofed by clients if your proxy
13
+ * does not strip/overwrite it. Prefer X-Real-IP when using nginx.
14
+ */
15
+ export declare const resolveClientIp: (headers: Record<string, any>, req: any) => string;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ // ./src/utils/resolveClientIp.ts
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.resolveClientIp = void 0;
5
+ /**
6
+ * Resolves the real client IP address from request headers,
7
+ * accounting for common reverse proxies (nginx, Cloudflare, etc.).
8
+ *
9
+ * Priority:
10
+ * 1. X-Real-IP — set by nginx, single trusted IP
11
+ * 2. CF-Connecting-IP — set by Cloudflare, single trusted IP
12
+ * 3. X-Forwarded-For — leftmost entry is original client,
13
+ * but the header can contain a chain
14
+ * 4. req.socket.remoteAddress — direct TCP connection (may be the proxy)
15
+ *
16
+ * Note: X-Forwarded-For can be spoofed by clients if your proxy
17
+ * does not strip/overwrite it. Prefer X-Real-IP when using nginx.
18
+ */
19
+ const resolveClientIp = (headers, req) => {
20
+ // nginx: proxy_set_header X-Real-IP $remote_addr
21
+ const xRealIp = headers['x-real-ip'];
22
+ if (xRealIp)
23
+ return xRealIp;
24
+ // Cloudflare: always a single IP, only trustworthy behind CF
25
+ const cfConnectingIp = headers['cf-connecting-ip'];
26
+ if (cfConnectingIp)
27
+ return cfConnectingIp;
28
+ // Standard proxy chain — take the leftmost (original client)
29
+ const xForwardedFor = headers['x-forwarded-for'];
30
+ if (xForwardedFor) {
31
+ const firstIp = xForwardedFor.split(',')[0].trim();
32
+ if (firstIp)
33
+ return firstIp;
34
+ }
35
+ // Direct socket connection — will be the proxy's IP if behind one
36
+ return req.socket?.remoteAddress ?? '';
37
+ };
38
+ exports.resolveClientIp = resolveClientIp;
@@ -1,3 +1,23 @@
1
1
  import { BuildDefaultResolvers } from './interfaces';
2
- declare const buildDefaultResolvers: (args: BuildDefaultResolvers) => any;
2
+ /**
3
+ * Builds a standard set of GraphQL resolvers for a resource, delegating
4
+ * each operation to the matching method on the configured core.
5
+ *
6
+ * Resolvers are added to `Query` or `Mutation` based on operation type.
7
+ * Each can be individually disabled via `disable*` flags — useful when a
8
+ * resource needs to expose only a subset of the standard CRUD operations.
9
+ *
10
+ * The core is resolved from `context.cores` at request time using either
11
+ * the explicit `core` name or `${prefix}Core` as the default.
12
+ *
13
+ * Resolver naming convention:
14
+ * Query: `${prefix}List`, `${prefix}Get`, `${prefix}GetMany`
15
+ * Mutation: `${prefix}Create`, `${prefix}CreateMany`, `${prefix}Update`,
16
+ * `${prefix}UpdateMany`, `${prefix}Set`, `${prefix}Remove`,
17
+ * `${prefix}RemoveMany`
18
+ *
19
+ * @param args BuildDefaultResolvers configuration
20
+ * @returns Object with `Query`, `Mutation`, and any additional `types`
21
+ */
22
+ declare const buildDefaultResolvers: (args: BuildDefaultResolvers) => Record<string, any>;
3
23
  export { buildDefaultResolvers };
@@ -1,63 +1,85 @@
1
1
  "use strict";
2
+ // ./src/resolversHelpers.ts
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
3
4
  exports.buildDefaultResolvers = void 0;
5
+ /**
6
+ * Builds a standard set of GraphQL resolvers for a resource, delegating
7
+ * each operation to the matching method on the configured core.
8
+ *
9
+ * Resolvers are added to `Query` or `Mutation` based on operation type.
10
+ * Each can be individually disabled via `disable*` flags — useful when a
11
+ * resource needs to expose only a subset of the standard CRUD operations.
12
+ *
13
+ * The core is resolved from `context.cores` at request time using either
14
+ * the explicit `core` name or `${prefix}Core` as the default.
15
+ *
16
+ * Resolver naming convention:
17
+ * Query: `${prefix}List`, `${prefix}Get`, `${prefix}GetMany`
18
+ * Mutation: `${prefix}Create`, `${prefix}CreateMany`, `${prefix}Update`,
19
+ * `${prefix}UpdateMany`, `${prefix}Set`, `${prefix}Remove`,
20
+ * `${prefix}RemoveMany`
21
+ *
22
+ * @param args BuildDefaultResolvers configuration
23
+ * @returns Object with `Query`, `Mutation`, and any additional `types`
24
+ */
4
25
  const buildDefaultResolvers = (args) => {
5
26
  const { prefix, core, query, mutation, types, disableList, disableGet, disableGetMany, disableCreate, disableCreateMany, disableUpdate, disableUpdateMany, disableSet, disableRemove, disableRemoveMany, } = args || {};
6
- const Query = {
7
- ...(query || {}),
8
- };
9
- const Mutation = {
10
- ...(mutation || {}),
11
- };
27
+ // Guard: without prefix or core, resolver and core names would be
28
+ // 'undefinedList', 'undefinedCore', etc. — fail fast with a clear message
29
+ if (!core && !prefix) {
30
+ throw new Error('buildDefaultResolvers: either `prefix` or `core` must be provided');
31
+ }
32
+ const Query = { ...(query || {}) };
33
+ const Mutation = { ...(mutation || {}) };
12
34
  const coreToUse = core || `${prefix}Core`;
13
35
  if (disableList !== true) {
14
- Query[`${prefix}List`] = (parent, args, context) => {
15
- return context.cores[coreToUse].list(args);
36
+ Query[`${prefix}List`] = (_parent, args, context) => {
37
+ return context.cores?.[coreToUse]?.list(args);
16
38
  };
17
39
  }
18
40
  if (disableGet !== true) {
19
- Query[`${prefix}Get`] = (parent, args, context) => {
20
- return context.cores[coreToUse].get(args);
41
+ Query[`${prefix}Get`] = (_parent, args, context) => {
42
+ return context.cores?.[coreToUse]?.get(args);
21
43
  };
22
44
  }
23
45
  if (disableGetMany !== true) {
24
- Query[`${prefix}GetMany`] = (parent, args, context) => {
25
- return context.cores[coreToUse].getMany(args);
46
+ Query[`${prefix}GetMany`] = (_parent, args, context) => {
47
+ return context.cores?.[coreToUse]?.getMany(args);
26
48
  };
27
49
  }
28
50
  if (disableCreate !== true) {
29
- Mutation[`${prefix}Create`] = (parent, args, context) => {
30
- return context.cores[coreToUse].create(args);
51
+ Mutation[`${prefix}Create`] = (_parent, args, context) => {
52
+ return context.cores?.[coreToUse]?.create(args);
31
53
  };
32
54
  }
33
55
  if (disableCreateMany !== true) {
34
- Mutation[`${prefix}CreateMany`] = (parent, args, context) => {
35
- return context.cores[coreToUse].createMany(args);
56
+ Mutation[`${prefix}CreateMany`] = (_parent, args, context) => {
57
+ return context.cores?.[coreToUse]?.createMany(args);
36
58
  };
37
59
  }
38
60
  if (disableUpdate !== true) {
39
- Mutation[`${prefix}Update`] = (parent, args, context) => {
40
- return context.cores[coreToUse].update(args);
61
+ Mutation[`${prefix}Update`] = (_parent, args, context) => {
62
+ return context.cores?.[coreToUse]?.update(args);
41
63
  };
42
64
  }
43
65
  if (disableUpdateMany !== true) {
44
- Mutation[`${prefix}UpdateMany`] = (parent, args, context) => {
45
- return context.cores[coreToUse].updateMany(args);
66
+ Mutation[`${prefix}UpdateMany`] = (_parent, args, context) => {
67
+ return context.cores?.[coreToUse]?.updateMany(args);
46
68
  };
47
69
  }
48
70
  if (disableSet !== true) {
49
- Mutation[`${prefix}Set`] = (parent, args, context) => {
50
- return context.cores[coreToUse].set(args);
71
+ Mutation[`${prefix}Set`] = (_parent, args, context) => {
72
+ return context.cores?.[coreToUse]?.set(args);
51
73
  };
52
74
  }
53
75
  if (disableRemove !== true) {
54
- Mutation[`${prefix}Remove`] = (parent, args, context) => {
55
- return context.cores[coreToUse].remove(args);
76
+ Mutation[`${prefix}Remove`] = (_parent, args, context) => {
77
+ return context.cores?.[coreToUse]?.remove(args);
56
78
  };
57
79
  }
58
80
  if (disableRemoveMany !== true) {
59
- Mutation[`${prefix}RemoveMany`] = (parent, args, context) => {
60
- return context.cores[coreToUse].removeMany(args);
81
+ Mutation[`${prefix}RemoveMany`] = (_parent, args, context) => {
82
+ return context.cores?.[coreToUse]?.removeMany(args);
61
83
  };
62
84
  }
63
85
  return {
@@ -1,8 +1,57 @@
1
1
  import { OpResult } from '@sdflc/api-helpers';
2
2
  import { UserTokenParams, CreateUserTokenArgs, VerifyUserTokenArgs } from './interfaces';
3
+ /**
4
+ * Overrides the default JWT signing algorithm for all subsequent operations.
5
+ * Defaults to HS256 (from DEFAULT_JWT_ALGORITHM).
6
+ */
3
7
  export declare const setDefaultJwtAlgorithm: (algorithm: string) => void;
8
+ /**
9
+ * Returns the current default JWT signing algorithm.
10
+ */
4
11
  export declare const getDefaultJwtAlgorithm: () => string;
12
+ /**
13
+ * Overrides the default JWT issuer claim for all subsequent operations.
14
+ * Defaults to DEFAULT_JWT_ISSUER.
15
+ */
5
16
  export declare const setDefaultJwtIssuer: (issuer: string) => void;
17
+ /**
18
+ * Returns the current default JWT issuer.
19
+ */
6
20
  export declare const getDefaultJwtIssuer: () => string;
7
- export declare const createUserToken: (params: UserTokenParams, secret: string, opt: CreateUserTokenArgs) => any;
21
+ /**
22
+ * Signs a JWT token with the provided params and secret.
23
+ *
24
+ * When `useFingerprint` is true, a UUID fingerprint is generated and embedded
25
+ * in the token payload. The fingerprint should be stored in a secure httpOnly
26
+ * cookie and passed to `verifyUserToken()` to mitigate token theft.
27
+ *
28
+ * Returns an OpResult containing `{ token, fingerprint }` on success.
29
+ * `fingerprint` is null when `useFingerprint` is false.
30
+ *
31
+ * Note: `params.userId` is used as the JWT `subject` claim.
32
+ *
33
+ * @param params Token payload (userId, accountId, roleId, spaceId, lang, etc.)
34
+ * @param secret JWT signing secret
35
+ * @param opt Signing options (algorithm, audience, issuer, expiresIn, etc.)
36
+ */
37
+ export declare const createUserToken: (params: UserTokenParams, secret: string, opt: CreateUserTokenArgs) => OpResult;
38
+ /**
39
+ * Verifies a JWT token against the provided secret and options.
40
+ *
41
+ * Returns a successful OpResult containing the decoded token payload,
42
+ * or a failed OpResult with an appropriate code:
43
+ * - VALIDATION_FAILED — args not provided
44
+ * - EXPIRED — token has expired (TokenExpiredError)
45
+ * - INVALID_SIGNATURE — token is malformed or signature is invalid (JsonWebTokenError)
46
+ * - UNAUTHORIZED — fingerprint mismatch or other verification failure
47
+ *
48
+ * Fingerprint verification:
49
+ * If the token payload contains a `fingerprint` field and `args.fingerprint`
50
+ * is provided, they are compared. A mismatch returns UNAUTHORIZED — this
51
+ * mitigates token theft where the attacker does not have the fingerprint cookie.
52
+ *
53
+ * @param token The JWT string to verify
54
+ * @param secret The secret used to sign the token
55
+ * @param args Verification options (algorithms, audience, issuer, fingerprint, etc.)
56
+ */
8
57
  export declare const verifyUserToken: (token: string, secret: string, args?: VerifyUserTokenArgs) => OpResult;
@@ -1,4 +1,5 @@
1
1
  "use strict";
2
+ // ./src/userToken.ts
2
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
5
  };
@@ -7,63 +8,126 @@ exports.verifyUserToken = exports.createUserToken = exports.getDefaultJwtIssuer
7
8
  const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
9
  const uuid_1 = require("uuid");
9
10
  const api_helpers_1 = require("@sdflc/api-helpers");
10
- const constants_1 = require("./constants");
11
11
  const dayjs_1 = __importDefault(require("dayjs"));
12
+ const constants_1 = require("./constants");
13
+ /**
14
+ * Module-level defaults for JWT algorithm and issuer.
15
+ *
16
+ * These can be overridden at application startup via `setDefaultJwtAlgorithm()`
17
+ * and `setDefaultJwtIssuer()`. Note that these are module-level singletons —
18
+ * changing them affects all subsequent token operations in the process.
19
+ * In test environments, restore defaults between test suites if overriding.
20
+ */
12
21
  let defaultJwtAlgorithm = constants_1.DEFAULT_JWT_ALGORITHM;
13
22
  let defaultIssuer = constants_1.DEFAULT_JWT_ISSUER;
23
+ /**
24
+ * Overrides the default JWT signing algorithm for all subsequent operations.
25
+ * Defaults to HS256 (from DEFAULT_JWT_ALGORITHM).
26
+ */
14
27
  const setDefaultJwtAlgorithm = (algorithm) => {
15
28
  defaultJwtAlgorithm = algorithm;
16
29
  };
17
30
  exports.setDefaultJwtAlgorithm = setDefaultJwtAlgorithm;
31
+ /**
32
+ * Returns the current default JWT signing algorithm.
33
+ */
18
34
  const getDefaultJwtAlgorithm = () => {
19
35
  return defaultJwtAlgorithm;
20
36
  };
21
37
  exports.getDefaultJwtAlgorithm = getDefaultJwtAlgorithm;
38
+ /**
39
+ * Overrides the default JWT issuer claim for all subsequent operations.
40
+ * Defaults to DEFAULT_JWT_ISSUER.
41
+ */
22
42
  const setDefaultJwtIssuer = (issuer) => {
23
43
  defaultIssuer = issuer;
24
44
  };
25
45
  exports.setDefaultJwtIssuer = setDefaultJwtIssuer;
46
+ /**
47
+ * Returns the current default JWT issuer.
48
+ */
26
49
  const getDefaultJwtIssuer = () => {
27
50
  return defaultIssuer;
28
51
  };
29
52
  exports.getDefaultJwtIssuer = getDefaultJwtIssuer;
53
+ /**
54
+ * Helper to convert an array to a non-empty tuple type required by jsonwebtoken.
55
+ * Returns undefined for empty or absent arrays.
56
+ */
57
+ function toNonEmptyArray(arr) {
58
+ if (!arr || arr.length === 0)
59
+ return undefined;
60
+ return arr;
61
+ }
62
+ /**
63
+ * Signs a JWT token with the provided params and secret.
64
+ *
65
+ * When `useFingerprint` is true, a UUID fingerprint is generated and embedded
66
+ * in the token payload. The fingerprint should be stored in a secure httpOnly
67
+ * cookie and passed to `verifyUserToken()` to mitigate token theft.
68
+ *
69
+ * Returns an OpResult containing `{ token, fingerprint }` on success.
70
+ * `fingerprint` is null when `useFingerprint` is false.
71
+ *
72
+ * Note: `params.userId` is used as the JWT `subject` claim.
73
+ *
74
+ * @param params Token payload (userId, accountId, roleId, spaceId, lang, etc.)
75
+ * @param secret JWT signing secret
76
+ * @param opt Signing options (algorithm, audience, issuer, expiresIn, etc.)
77
+ */
30
78
  const createUserToken = (params, secret, opt) => {
31
79
  const { algorithm, audience, issuer, jwtid, noTimestamp, header, keyid, expiresIn, useFingerprint } = opt || {};
32
80
  if (!params || !secret) {
33
81
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'Failed to create user JWT');
34
82
  }
35
83
  if (useFingerprint) {
36
- const fingerprint = (0, uuid_1.v4)();
37
- params['fingerprint'] = fingerprint;
84
+ params['fingerprint'] = (0, uuid_1.v4)();
38
85
  }
39
- const token = jsonwebtoken_1.default.sign(params, secret, {
40
- algorithm: algorithm || defaultJwtAlgorithm,
86
+ const signOptions = {
87
+ algorithm: (algorithm || defaultJwtAlgorithm),
41
88
  audience,
42
89
  issuer: issuer || defaultIssuer,
43
90
  jwtid: jwtid || (0, uuid_1.v4)(),
44
91
  subject: params.userId,
45
92
  noTimestamp: noTimestamp ?? false,
46
- header,
93
+ header: header,
47
94
  keyid,
48
- expiresIn: expiresIn && !isNaN(expiresIn) ? expiresIn : undefined,
49
- });
50
- return api_helpers_1.OpResult.ok({ token, fingerprint: params.fingerprint });
95
+ expiresIn: expiresIn,
96
+ };
97
+ const token = jsonwebtoken_1.default.sign(params, secret, signOptions);
98
+ return api_helpers_1.OpResult.ok({ token, fingerprint: params['fingerprint'] ?? null });
51
99
  };
52
100
  exports.createUserToken = createUserToken;
53
- function toNonEmptyArray(arr) {
54
- if (!arr || arr.length === 0)
55
- return undefined;
56
- return arr;
57
- }
101
+ /**
102
+ * Verifies a JWT token against the provided secret and options.
103
+ *
104
+ * Returns a successful OpResult containing the decoded token payload,
105
+ * or a failed OpResult with an appropriate code:
106
+ * - VALIDATION_FAILED — args not provided
107
+ * - EXPIRED — token has expired (TokenExpiredError)
108
+ * - INVALID_SIGNATURE — token is malformed or signature is invalid (JsonWebTokenError)
109
+ * - UNAUTHORIZED — fingerprint mismatch or other verification failure
110
+ *
111
+ * Fingerprint verification:
112
+ * If the token payload contains a `fingerprint` field and `args.fingerprint`
113
+ * is provided, they are compared. A mismatch returns UNAUTHORIZED — this
114
+ * mitigates token theft where the attacker does not have the fingerprint cookie.
115
+ *
116
+ * @param token The JWT string to verify
117
+ * @param secret The secret used to sign the token
118
+ * @param args Verification options (algorithms, audience, issuer, fingerprint, etc.)
119
+ */
58
120
  const verifyUserToken = (token, secret, args) => {
59
- const { algorithms, audience, issuer, ignoreExpiration, ignoreNotBefore, subject, clockTolerance, maxAge, clockTimestamp, nonce, fingerprint, } = args || {};
121
+ // Guard must come before destructuring — args || {} in the destructure
122
+ // would make !args always false since it coerces to an object first
60
123
  if (!args) {
61
124
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'Cannot verify user token as there are no parameters specified');
62
125
  }
126
+ const { algorithms, audience, issuer, ignoreExpiration, ignoreNotBefore, subject, clockTolerance, maxAge, clockTimestamp, nonce, fingerprint, } = args;
63
127
  try {
64
128
  const issuerToUse = issuer || defaultIssuer;
65
129
  const obj = jsonwebtoken_1.default.verify(token, secret, {
66
- algorithms: algorithms || [defaultJwtAlgorithm],
130
+ algorithms: (algorithms || [defaultJwtAlgorithm]),
67
131
  audience: typeof audience === 'string' ? audience : toNonEmptyArray(audience),
68
132
  issuer: typeof issuerToUse === 'string' ? issuerToUse : toNonEmptyArray(issuerToUse),
69
133
  ignoreExpiration,
@@ -74,17 +138,18 @@ const verifyUserToken = (token, secret, args) => {
74
138
  clockTimestamp,
75
139
  nonce,
76
140
  });
77
- if (obj?.fingerprint && obj.fingerprint != fingerprint) {
141
+ // Fingerprint check — mitigates token theft when fingerprint cookie is used
142
+ if (obj?.fingerprint && obj.fingerprint !== fingerprint) {
78
143
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.UNAUTHORIZED, null, 'User unauthenticated');
79
144
  }
80
145
  return api_helpers_1.OpResult.ok(obj);
81
146
  }
82
147
  catch (ex) {
83
148
  if (ex.name === 'TokenExpiredError') {
84
- return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.EXPIRED, null, `User authorization has expired at ${(0, dayjs_1.default)(ex.expiredAt).toDate()}`);
149
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.EXPIRED, null, `User authorization has expired at ${(0, dayjs_1.default)(ex.expiredAt).toISOString()}`);
85
150
  }
86
- else if (ex.name === 'JsonWebTokenError') {
87
- return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.EXPIRED, null, `JWT is invalid, reason: ${ex.message}`);
151
+ if (ex.name === 'JsonWebTokenError') {
152
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.INVALID_SIGNATURE, null, `JWT is invalid: ${ex.message}`);
88
153
  }
89
154
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.UNAUTHORIZED, null, 'User unauthenticated');
90
155
  }
package/build/utils.d.ts CHANGED
@@ -1,4 +1,22 @@
1
+ /**
2
+ * Returns `func` if it is a function, otherwise returns `defaultFunc`.
3
+ * Useful for ensuring a callback is always callable.
4
+ *
5
+ * @param func Value to check
6
+ * @param defaultFunc Fallback function if `func` is not a function
7
+ */
1
8
  export declare const setFunction: (func: any, defaultFunc: () => any) => any;
9
+ /**
10
+ * Builds an object containing only the keys from `defaultFuncs` where
11
+ * the corresponding value in `obj` is a function.
12
+ *
13
+ * Keys present in `defaultFuncs` but missing or non-function in `obj`
14
+ * are omitted from the result entirely — no fallback is applied.
15
+ * Keys present in `obj` but not in `defaultFuncs` are ignored.
16
+ *
17
+ * Use `setFunction()` for single-function fallback with a default.
18
+ *
19
+ * @param obj Source object to read functions from
20
+ * @param defaultFuncs Defines which keys to look for in `obj`
21
+ */
2
22
  export declare const setFunctions: (obj: any, defaultFuncs?: any) => any;
3
- export declare const isOpResult: (result: any) => any;
4
- export declare const isLogger: (obj: any) => boolean;
package/build/utils.js CHANGED
@@ -1,35 +1,43 @@
1
1
  "use strict";
2
+ // ./src/utils.ts
2
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
5
  };
5
6
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.isLogger = exports.isOpResult = exports.setFunctions = exports.setFunction = void 0;
7
+ exports.setFunctions = exports.setFunction = void 0;
7
8
  const check_types_1 = __importDefault(require("check-types"));
9
+ /**
10
+ * Returns `func` if it is a function, otherwise returns `defaultFunc`.
11
+ * Useful for ensuring a callback is always callable.
12
+ *
13
+ * @param func Value to check
14
+ * @param defaultFunc Fallback function if `func` is not a function
15
+ */
8
16
  const setFunction = (func, defaultFunc) => {
9
17
  return check_types_1.default.function(func) ? func : defaultFunc;
10
18
  };
11
19
  exports.setFunction = setFunction;
20
+ /**
21
+ * Builds an object containing only the keys from `defaultFuncs` where
22
+ * the corresponding value in `obj` is a function.
23
+ *
24
+ * Keys present in `defaultFuncs` but missing or non-function in `obj`
25
+ * are omitted from the result entirely — no fallback is applied.
26
+ * Keys present in `obj` but not in `defaultFuncs` are ignored.
27
+ *
28
+ * Use `setFunction()` for single-function fallback with a default.
29
+ *
30
+ * @param obj Source object to read functions from
31
+ * @param defaultFuncs Defines which keys to look for in `obj`
32
+ */
12
33
  const setFunctions = (obj, defaultFuncs = {}) => {
13
34
  const keys = Object.keys(defaultFuncs || {});
14
35
  return keys.reduce((acc, key) => {
15
- if (check_types_1.default.function(obj[key])) {
36
+ // use optional chaining to guard against null/undefined obj
37
+ if (check_types_1.default.function(obj?.[key])) {
16
38
  acc[key] = obj[key];
17
39
  }
18
40
  return acc;
19
41
  }, {});
20
42
  };
21
43
  exports.setFunctions = setFunctions;
22
- const isOpResult = (result) => {
23
- return result &&
24
- typeof result.code === 'number' &&
25
- typeof result.didFail === 'function';
26
- };
27
- exports.isOpResult = isOpResult;
28
- const isLogger = (obj) => {
29
- return obj &&
30
- typeof obj.warn === 'function' &&
31
- typeof obj.error === 'function' &&
32
- typeof obj.debug === 'function' &&
33
- typeof obj.log === 'function';
34
- };
35
- exports.isLogger = isLogger;