@sdflc/backend-helpers 1.0.111 → 1.0.113

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