@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,7 +1,42 @@
1
+ /**
2
+ * Interface for batch-loading data by key with per-request caching.
3
+ * Implemented by DataCache (DataLoader-backed) and any custom loaders
4
+ * passed via BaseGatewayPropsInterface.loader.
5
+ *
6
+ * Follows DataLoader semantics:
7
+ * - load() and loadMany() batch all calls within the same tick
8
+ * - Results are cached for the duration of the instance's lifetime
9
+ * - clear() and clearAll() invalidate cached entries
10
+ * - prime() seeds the cache without a round-trip
11
+ */
1
12
  export interface LoaderInterface {
13
+ /**
14
+ * Loads a single record by id. Batches concurrent calls within the
15
+ * same tick into a single underlying query.
16
+ * Returns null if the record is not found.
17
+ */
2
18
  load(id: any): Promise<any>;
3
- loadMany(id: any): Promise<any[]>;
19
+ /**
20
+ * Loads multiple records by their ids in a single batched call.
21
+ * Returns results in the same order as the input ids array,
22
+ * with null entries for any ids that were not found.
23
+ */
24
+ loadMany(ids: any[]): Promise<any[]>;
25
+ /**
26
+ * Clears the cached value for one or more keys.
27
+ * Accepts either a single id or an array of ids.
28
+ * Returns `this` for chaining.
29
+ */
4
30
  clear(key: any | any[]): this;
31
+ /**
32
+ * Clears all cached values from this loader instance.
33
+ * Returns `this` for chaining.
34
+ */
5
35
  clearAll(): this;
36
+ /**
37
+ * Seeds the cache with a known value for the given key, avoiding
38
+ * a load() round-trip for recently written records.
39
+ * Returns `this` for chaining.
40
+ */
6
41
  prime(key: any, value: any): this;
7
42
  }
@@ -1 +1,2 @@
1
+ // ./src/interfaces/LoaderInterface.ts
1
2
  export {};
@@ -1,8 +1,26 @@
1
1
  export interface UserTokenParams {
2
- spaceId: string;
3
- accountId: string;
4
- roleId: string;
2
+ /**
3
+ * The user's ID — used as the JWT `subject` claim. Required.
4
+ */
5
5
  userId: string;
6
- lang: string;
7
- [tokenProp: string]: string;
6
+ /**
7
+ * The space (tenant) ID the token is scoped to.
8
+ */
9
+ spaceId?: string;
10
+ /**
11
+ * The account ID associated with the user.
12
+ */
13
+ accountId?: string;
14
+ /**
15
+ * The role ID assigned to the user for this token.
16
+ */
17
+ roleId?: string;
18
+ /**
19
+ * The language preference for this session.
20
+ */
21
+ lang?: string;
22
+ /**
23
+ * Additional arbitrary string claims to include in the token payload.
24
+ */
25
+ [tokenProp: string]: string | undefined;
8
26
  }
@@ -1 +1,2 @@
1
+ // ./src/interfaces/UserTokenParams.ts
1
2
  export {};
@@ -1,13 +1,53 @@
1
1
  export interface VerifyUserTokenArgs {
2
- algorithms?: any;
2
+ /**
3
+ * Accepted signing algorithms. Defaults to [defaultJwtAlgorithm] (HS256).
4
+ */
5
+ algorithms?: string[];
6
+ /**
7
+ * Expected audience claim. Must match the `aud` in the token.
8
+ */
3
9
  audience?: string | string[];
10
+ /**
11
+ * Expected issuer claim. Must match the `iss` in the token.
12
+ * Accepts a single string or array of accepted issuers.
13
+ */
4
14
  issuer?: string | string[];
15
+ /**
16
+ * When true, expired tokens are accepted without error.
17
+ * Use only in specific scenarios (e.g. token refresh flows).
18
+ */
5
19
  ignoreExpiration?: boolean;
20
+ /**
21
+ * When true, ignores the `nbf` (not-before) claim.
22
+ */
6
23
  ignoreNotBefore?: boolean;
24
+ /**
25
+ * Expected subject claim. Must match the `sub` in the token.
26
+ */
7
27
  subject?: string;
28
+ /**
29
+ * Allowed clock skew in seconds when validating `exp` and `nbf` claims.
30
+ * Useful for systems with slight clock drift between services.
31
+ */
8
32
  clockTolerance?: number;
9
- maxAge?: number;
33
+ /**
34
+ * Maximum allowed token age as seconds or a string duration (e.g. '2h').
35
+ * Tokens older than this are rejected even if `exp` has not been reached.
36
+ */
37
+ maxAge?: number | string;
38
+ /**
39
+ * Override the current timestamp (Unix seconds) used for claim validation.
40
+ * Useful in tests to simulate token verification at a specific point in time.
41
+ */
10
42
  clockTimestamp?: number;
43
+ /**
44
+ * Expected `nonce` claim for OpenID Connect ID tokens.
45
+ */
11
46
  nonce?: string;
47
+ /**
48
+ * Client-side fingerprint (from a secure cookie) to compare against the
49
+ * fingerprint embedded in the token payload.
50
+ * A mismatch results in UNAUTHORIZED — mitigates token theft.
51
+ */
12
52
  fingerprint?: string;
13
53
  }
@@ -1 +1,2 @@
1
+ // ./src/interfaces/VerifyUserTokenArgs.ts
1
2
  export {};
@@ -26,3 +26,7 @@ export * from './ExtractCredentialsArgs';
26
26
  export * from './DownloadFileArgs';
27
27
  export * from './BuildListQueryArgsInterface';
28
28
  export * from './BaseCoreDoAuthOnActionInterface';
29
+ export * from './BaseControllerPropsInterface';
30
+ export * from './BaseRestApiCrudControllerPropsInterface';
31
+ export * from './BaseExternalApiGatewayPropsInterface';
32
+ export * from './DataCachePropsInterface';
@@ -25,3 +25,7 @@ export * from './ExtractCredentialsArgs';
25
25
  export * from './DownloadFileArgs';
26
26
  export * from './BuildListQueryArgsInterface';
27
27
  export * from './BaseCoreDoAuthOnActionInterface';
28
+ export * from './BaseControllerPropsInterface';
29
+ export * from './BaseRestApiCrudControllerPropsInterface';
30
+ export * from './BaseExternalApiGatewayPropsInterface';
31
+ export * from './DataCachePropsInterface';
@@ -1 +1,26 @@
1
+ /**
2
+ * Builds a Knex configuration object for the current environment.
3
+ *
4
+ * Reads connection and migration settings from `appConfig` (typically built
5
+ * by `buildConfig()`) and returns a fully configured Knex config object
6
+ * for the active `nodeEnv`. Falls back to the `development` config if
7
+ * `nodeEnv` does not match 'development' or 'production'.
8
+ *
9
+ * Built-in behaviours:
10
+ * - All query results are post-processed to camelCase via `camelResponse`
11
+ * - All identifiers are converted to snake_case via `wrapIdentifier`,
12
+ * with an optional override map for exceptions
13
+ * - Pool config can be provided as a full object (`dbPool`) or as
14
+ * individual min/max values (`dbPoolMin`, `dbPoolMax`)
15
+ * - Database port is coerced to a Number internally — no need to do this
16
+ * in the consuming app
17
+ * - MSSQL-specific connection options (encrypt, trustServerCertificate, etc.)
18
+ * are included automatically when `dbType === 'mssql'`
19
+ * - PostgreSQL searchPath is set automatically when `dbType === 'pg'`
20
+ * and `dbSchema` is provided
21
+ *
22
+ * @param dirName Absolute path to the directory containing migrations/seeds.
23
+ * Pass `__dirname` or `import.meta.dirname` from your entry point.
24
+ * @param appConfig Flat config object, typically from `buildConfig()`.
25
+ */
1
26
  export declare const buildKnexConfig: (dirName: string, appConfig: any) => any;
@@ -1,42 +1,82 @@
1
+ // ./src/knexConfigBuilder.ts
1
2
  import path from 'path';
2
- import { snakeCase, get } from 'lodash';
3
+ import { snakeCase } from 'lodash';
3
4
  import { camelKeys } from '@sdflc/utils';
4
5
  const defaultMigrationsTable = 'migrations';
5
6
  const defaultMigrationsFolder = 'migrations';
6
7
  const defaultMigrationsTemplateFileName = 'migrations-template.js';
7
8
  const defaultSeedsFolder = 'seeds';
9
+ /**
10
+ * Post-processes Knex query results by converting all keys to camelCase.
11
+ *
12
+ * Knex calls this with the already-processed result which is either:
13
+ * - An array of row objects (SELECT queries)
14
+ * - A non-array object (INSERT/UPDATE with RETURNING, aggregate queries, etc.)
15
+ *
16
+ * The `result.rows` guard handles edge cases where a raw pg-driver result
17
+ * shape leaks through — in that case we return it unchanged since Knex's
18
+ * own processing has not yet run.
19
+ *
20
+ * See: https://knexjs.org/guide/#post-process-response
21
+ */
8
22
  const camelResponse = (result) => {
9
23
  if (!result || result.rows) {
10
24
  return result;
11
25
  }
12
26
  return camelKeys(result);
13
27
  };
28
+ /**
29
+ * Builds a Knex configuration object for the current environment.
30
+ *
31
+ * Reads connection and migration settings from `appConfig` (typically built
32
+ * by `buildConfig()`) and returns a fully configured Knex config object
33
+ * for the active `nodeEnv`. Falls back to the `development` config if
34
+ * `nodeEnv` does not match 'development' or 'production'.
35
+ *
36
+ * Built-in behaviours:
37
+ * - All query results are post-processed to camelCase via `camelResponse`
38
+ * - All identifiers are converted to snake_case via `wrapIdentifier`,
39
+ * with an optional override map for exceptions
40
+ * - Pool config can be provided as a full object (`dbPool`) or as
41
+ * individual min/max values (`dbPoolMin`, `dbPoolMax`)
42
+ * - Database port is coerced to a Number internally — no need to do this
43
+ * in the consuming app
44
+ * - MSSQL-specific connection options (encrypt, trustServerCertificate, etc.)
45
+ * are included automatically when `dbType === 'mssql'`
46
+ * - PostgreSQL searchPath is set automatically when `dbType === 'pg'`
47
+ * and `dbSchema` is provided
48
+ *
49
+ * @param dirName Absolute path to the directory containing migrations/seeds.
50
+ * Pass `__dirname` or `import.meta.dirname` from your entry point.
51
+ * @param appConfig Flat config object, typically from `buildConfig()`.
52
+ */
14
53
  export const buildKnexConfig = (dirName, appConfig) => {
15
54
  const { dbType, dbHost, dbPort, dbName, dbSchema, dbUser, dbPassword, dbPoolMin, dbPoolMax, debug, nodeEnv, migrationsTemplateFileName, migrationsFolder, migrationsTable, useSchemaForMigrationsTable, seedsFolder, seedsFolderDev, seedsFolderProd, wrapIdentifierOverrideMap, dbPool, } = appConfig;
16
- const sharedConfig = {
17
- client: dbType || 'pg',
18
- postProcessResponse: camelResponse,
19
- wrapIdentifier: (value, origImpl) => {
20
- if (value === '*') {
21
- return origImpl(value);
22
- }
23
- const value2use = wrapIdentifierOverrideMap?.[value] || origImpl(snakeCase(value));
24
- return value2use;
25
- },
26
- connection: {
27
- host: dbHost,
28
- port: dbPort,
29
- user: dbUser,
30
- password: dbPassword,
31
- database: dbName,
32
- //ssl: database.ssl,
33
- },
55
+ const resolvedDbType = dbType || 'pg';
56
+ // ─── Connection ──────────────────────────────────────────────────────────
57
+ const connection = {
58
+ host: dbHost,
59
+ // Fix: coerce port to Number here so consuming apps don't need to do it
60
+ port: dbPort != null ? Number(dbPort) : undefined,
61
+ user: dbUser,
62
+ password: dbPassword,
63
+ database: dbName,
64
+ connectionTimeout: 30000,
34
65
  };
35
- if (typeof dbPool === 'object') {
36
- sharedConfig.pool = dbPool;
66
+ // MSSQL-specific connection options — previously repeated in every project
67
+ if (resolvedDbType === 'mssql') {
68
+ connection.options = {
69
+ encrypt: true,
70
+ trustServerCertificate: false,
71
+ enableArithAbort: true,
72
+ requestTimeout: 30000,
73
+ connectionTimeout: 30000,
74
+ };
37
75
  }
38
- else {
39
- sharedConfig.pool = {
76
+ // ─── Pool ─────────────────────────────────────────────────────────────────
77
+ const pool = typeof dbPool === 'object'
78
+ ? dbPool
79
+ : {
40
80
  min: dbPoolMin != null && !isNaN(dbPoolMin) ? dbPoolMin : 0,
41
81
  max: dbPoolMax != null && !isNaN(dbPoolMax) ? dbPoolMax : 50,
42
82
  acquireTimeoutMillis: 30000,
@@ -47,17 +87,45 @@ export const buildKnexConfig = (dirName, appConfig) => {
47
87
  createRetryIntervalMillis: 200,
48
88
  propagateCreateError: false,
49
89
  };
90
+ // ─── Shared config ────────────────────────────────────────────────────────
91
+ const sharedConfig = {
92
+ client: resolvedDbType,
93
+ postProcessResponse: camelResponse,
94
+ /**
95
+ * Converts camelCase JS identifiers to snake_case DB column names.
96
+ * '*' is passed through unchanged (Knex uses it for SELECT *).
97
+ * `wrapIdentifierOverrideMap` allows exceptions for identifiers that
98
+ * should not be snake_cased (e.g. already-snake_cased names, reserved words).
99
+ */
100
+ wrapIdentifier: (value, origImpl) => {
101
+ if (value === '*') {
102
+ return origImpl(value);
103
+ }
104
+ return wrapIdentifierOverrideMap?.[value] || origImpl(snakeCase(value));
105
+ },
106
+ connection,
107
+ pool,
108
+ };
109
+ // pg searchPath — previously set in every project after buildKnexConfig()
110
+ if (resolvedDbType === 'pg' && dbSchema) {
111
+ sharedConfig.searchPath = [dbSchema, 'public'];
50
112
  }
113
+ // ─── Migration config ─────────────────────────────────────────────────────
114
+ const migrationsConfig = {
115
+ directory: path.join(dirName, migrationsFolder || defaultMigrationsFolder),
116
+ schemaName: useSchemaForMigrationsTable ? dbSchema : undefined,
117
+ tableName: migrationsTable || defaultMigrationsTable,
118
+ };
119
+ // ─── Environment configs ──────────────────────────────────────────────────
51
120
  const config = {
52
121
  development: {
53
122
  ...sharedConfig,
123
+ // debug defaults to false in production even if env var is set
54
124
  debug,
55
125
  migrations: {
56
- // https://knexjs.org/guide/migrations.html#migration-api
126
+ // stub is only needed in development (used by `knex migrate:make`)
57
127
  stub: path.join(dirName, migrationsTemplateFileName || defaultMigrationsTemplateFileName),
58
- directory: path.join(dirName, migrationsFolder || defaultMigrationsFolder),
59
- schemaName: useSchemaForMigrationsTable ? dbSchema : undefined,
60
- tableName: migrationsTable || defaultMigrationsTable,
128
+ ...migrationsConfig,
61
129
  },
62
130
  seeds: {
63
131
  directory: path.join(dirName, seedsFolderDev || seedsFolder || defaultSeedsFolder),
@@ -65,20 +133,16 @@ export const buildKnexConfig = (dirName, appConfig) => {
65
133
  },
66
134
  production: {
67
135
  ...sharedConfig,
68
- debug,
136
+ debug: false, // never enable debug in production regardless of env var
69
137
  migrations: {
70
- directory: path.join(dirName, migrationsFolder || defaultMigrationsFolder),
71
- schemaName: useSchemaForMigrationsTable ? dbSchema : undefined,
72
- tableName: migrationsTable || defaultMigrationsTable,
138
+ ...migrationsConfig,
73
139
  },
74
140
  seeds: {
75
141
  directory: path.join(dirName, seedsFolderProd || seedsFolder || defaultSeedsFolder),
76
142
  },
77
143
  },
78
144
  };
79
- let config2use = get(config, nodeEnv);
80
- if (!config2use) {
81
- config2use = config.development;
82
- }
83
- return config2use;
145
+ // Fix: direct bracket access instead of lodash get() — avoids dot-notation
146
+ // path interpretation (e.g. 'development.migrations' would be misread)
147
+ return config[nodeEnv] ?? config.development;
84
148
  };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Parses a raw :id route param into a single string or an array of strings.
3
+ * If the value contains commas, it is split, trimmed, and empty entries removed.
4
+ * Returns a tuple so callers can branch cleanly without re-checking.
5
+ */
6
+ export declare const parseIds: (raw: string) => [isSingle: boolean, ids: string[]];
@@ -0,0 +1,13 @@
1
+ // ./src/utils/parseIds.ts
2
+ /**
3
+ * Parses a raw :id route param into a single string or an array of strings.
4
+ * If the value contains commas, it is split, trimmed, and empty entries removed.
5
+ * Returns a tuple so callers can branch cleanly without re-checking.
6
+ */
7
+ export const parseIds = (raw) => {
8
+ const ids = raw
9
+ .split(',')
10
+ .map((id) => id.trim())
11
+ .filter(Boolean);
12
+ return [ids.length === 1, ids];
13
+ };
@@ -1,5 +1,27 @@
1
+ /**
2
+ * Generates a bcrypt salt and hashes the provided password.
3
+ *
4
+ * @param password The plaintext password to hash. Must be a non-empty string.
5
+ * @param saltRounds The bcrypt cost factor. Higher = slower but more secure.
6
+ * Defaults to 10 (OWASP recommended minimum).
7
+ * Clamped to [10, 31] — values below 10 are insecure,
8
+ * values above 31 would block the event loop for an
9
+ * impractical amount of time.
10
+ * @returns Object containing the generated `salt` and `hash`.
11
+ * @throws If `password` is empty or not a string.
12
+ */
1
13
  export declare const getSaltAndHash: (password: string, saltRounds?: number) => Promise<{
2
14
  salt: string;
3
15
  hash: string;
4
16
  }>;
17
+ /**
18
+ * Compares a plaintext password against a bcrypt hash.
19
+ *
20
+ * Returns false immediately if either argument is missing or not a string —
21
+ * avoids passing invalid input to bcrypt which may throw or behave unexpectedly.
22
+ *
23
+ * @param password The plaintext password to verify.
24
+ * @param hashedPassword The stored bcrypt hash to compare against.
25
+ * @returns True if the password matches the hash, false otherwise.
26
+ */
5
27
  export declare const checkPassword: (password: string, hashedPassword: string) => Promise<boolean>;
@@ -1,13 +1,45 @@
1
+ // ./src/passwordHelpers.ts
1
2
  import bcrypt from 'bcrypt';
2
- export const getSaltAndHash = async (password, saltRounds = 10) => {
3
- const salt = await bcrypt.genSalt(saltRounds);
3
+ const MIN_SALT_ROUNDS = 10;
4
+ const MAX_SALT_ROUNDS = 31; // bcrypt max — 32+ would block the event loop indefinitely
5
+ /**
6
+ * Generates a bcrypt salt and hashes the provided password.
7
+ *
8
+ * @param password The plaintext password to hash. Must be a non-empty string.
9
+ * @param saltRounds The bcrypt cost factor. Higher = slower but more secure.
10
+ * Defaults to 10 (OWASP recommended minimum).
11
+ * Clamped to [10, 31] — values below 10 are insecure,
12
+ * values above 31 would block the event loop for an
13
+ * impractical amount of time.
14
+ * @returns Object containing the generated `salt` and `hash`.
15
+ * @throws If `password` is empty or not a string.
16
+ */
17
+ export const getSaltAndHash = async (password, saltRounds = MIN_SALT_ROUNDS) => {
18
+ if (!password || typeof password !== 'string') {
19
+ throw new Error('getSaltAndHash: password must be a non-empty string');
20
+ }
21
+ // Clamp saltRounds to a safe range — bcrypt cost factor grows exponentially
22
+ const rounds = Math.max(MIN_SALT_ROUNDS, Math.min(saltRounds, MAX_SALT_ROUNDS));
23
+ const salt = await bcrypt.genSalt(rounds);
4
24
  const hash = await bcrypt.hash(password, salt);
5
- return {
6
- salt,
7
- hash,
8
- };
25
+ return { salt, hash };
9
26
  };
27
+ /**
28
+ * Compares a plaintext password against a bcrypt hash.
29
+ *
30
+ * Returns false immediately if either argument is missing or not a string —
31
+ * avoids passing invalid input to bcrypt which may throw or behave unexpectedly.
32
+ *
33
+ * @param password The plaintext password to verify.
34
+ * @param hashedPassword The stored bcrypt hash to compare against.
35
+ * @returns True if the password matches the hash, false otherwise.
36
+ */
10
37
  export const checkPassword = async (password, hashedPassword) => {
11
- const isCorrect = await bcrypt.compare(password, hashedPassword);
12
- return isCorrect;
38
+ if (!password || typeof password !== 'string') {
39
+ return false;
40
+ }
41
+ if (!hashedPassword || typeof hashedPassword !== 'string') {
42
+ return false;
43
+ }
44
+ return bcrypt.compare(password, hashedPassword);
13
45
  };
@@ -1,17 +1,70 @@
1
+ /**
2
+ * Configuration for creating a Redis client via `createRedisClient()`.
3
+ */
1
4
  interface CreateRedisClientInterface {
5
+ /** Redis server hostname or IP address. Required — returns null if not provided. */
2
6
  redisHost: string;
7
+ /** Redis server port. Coerced to Number internally. */
3
8
  redisPort: string | number;
9
+ /** Redis AUTH password. Pass empty string or omit for no authentication. */
4
10
  redisPassword: string;
11
+ /** When true, enables TLS for the connection. */
5
12
  redisSsl: boolean;
6
- retryAttempts?: number;
7
- firstTimeout?: number;
8
- pingInterval?: number;
13
+ /**
14
+ * When true, disables TLS certificate validation.
15
+ * Only applies when `redisSsl` is true.
16
+ * Defaults to true (certificates are validated).
17
+ * Set to false only for self-signed certs in development environments.
18
+ */
19
+ rejectUnauthorized?: boolean;
20
+ /**
21
+ * Maximum reconnect delay in milliseconds.
22
+ * Reconnect delay grows as `retries × 50ms`, capped at this value.
23
+ * Defaults to 500ms.
24
+ */
25
+ maxReconnectDelay?: number;
26
+ /**
27
+ * TCP connection timeout in milliseconds.
28
+ * Defaults to 5000ms.
29
+ */
9
30
  connectionTimeout?: number;
31
+ /**
32
+ * TCP keep-alive initial delay in milliseconds.
33
+ * Defaults to 5000ms.
34
+ */
35
+ pingInterval?: number;
36
+ /** Called when the client begins connecting to the server. */
10
37
  onConnecting?(): void;
38
+ /** Called when the client is connected and ready to accept commands. */
11
39
  onConnected?(): void;
40
+ /** Called when the connection is closed. */
12
41
  onDisconnected?(): void;
42
+ /** Called when the client is attempting to reconnect. */
13
43
  onReconnecting?(): void;
44
+ /**
45
+ * Called when the client encounters an error.
46
+ * If not provided, errors are logged to console.error to prevent
47
+ * unhandled 'error' events from crashing the Node.js process.
48
+ */
14
49
  onError?(err: any): void;
15
50
  }
51
+ /**
52
+ * Creates and configures a Redis client without connecting.
53
+ *
54
+ * The caller is responsible for calling `await redisClient.connect()`
55
+ * when ready — this is intentional to allow the client to be created
56
+ * early in the startup sequence and connected at a controlled point.
57
+ *
58
+ * Returns null if `redisHost` is not provided.
59
+ *
60
+ * Socket behaviour:
61
+ * - `family: 0` — tries IPv6 first, falls back to IPv4
62
+ * - `noDelay: true` — disables Nagle's algorithm for lower latency
63
+ * - `keepAlive: true` — enables TCP keep-alive to detect dead connections
64
+ * - Reconnect delay grows linearly (retries × 50ms), capped at `maxReconnectDelay`
65
+ *
66
+ * @param args CreateRedisClientInterface configuration
67
+ * @returns Configured but unconnected Redis client, or null if redisHost is absent
68
+ */
16
69
  declare const createRedisClient: (args: CreateRedisClientInterface) => any;
17
- export { createRedisClient };
70
+ export { createRedisClient, CreateRedisClientInterface };