@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.
- package/README.md +1422 -146
- package/build/BaseController.d.ts +20 -0
- package/build/BaseController.js +64 -0
- package/build/BaseCore.d.ts +586 -33
- package/build/BaseCore.js +821 -127
- package/build/BaseExternalApiGateway.d.ts +16 -0
- package/build/BaseExternalApiGateway.js +54 -0
- package/build/BaseGateway.d.ts +455 -17
- package/build/BaseGateway.js +502 -56
- package/build/BaseRestApiCrudController.d.ts +37 -0
- package/build/BaseRestApiCrudController.js +134 -0
- package/build/DataCache.d.ts +116 -5
- package/build/DataCache.js +144 -22
- package/build/Database.d.ts +165 -4
- package/build/Database.js +224 -51
- package/build/DbMigratorAndSeeder.d.ts +127 -26
- package/build/DbMigratorAndSeeder.js +180 -69
- package/build/IpRateLimiter.d.ts +105 -0
- package/build/IpRateLimiter.js +104 -0
- package/build/RedisDataLoader.d.ts +144 -21
- package/build/RedisDataLoader.js +178 -49
- package/build/apiContext.d.ts +0 -8
- package/build/apiContext.js +30 -32
- package/build/checkItHelpers.d.ts +32 -0
- package/build/checkItHelpers.js +73 -7
- package/build/commonValidators.d.ts +107 -16
- package/build/commonValidators.js +211 -106
- package/build/configBuilder.d.ts +23 -0
- package/build/configBuilder.js +73 -0
- package/build/constants.d.ts +134 -17
- package/build/constants.js +95 -15
- package/build/dbHelpers.d.ts +89 -29
- package/build/dbHelpers.js +175 -86
- package/build/dbSeeder.d.ts +10 -1
- package/build/dbSeeder.js +80 -15
- package/build/dbTableHelpers.d.ts +122 -5
- package/build/dbTableHelpers.js +151 -13
- package/build/downloadHelpers.d.ts +24 -1
- package/build/downloadHelpers.js +51 -21
- package/build/esm/BaseController.d.ts +20 -0
- package/build/esm/BaseController.js +58 -0
- package/build/esm/BaseCore.d.ts +586 -33
- package/build/esm/BaseCore.js +812 -118
- package/build/esm/BaseExternalApiGateway.d.ts +16 -0
- package/build/esm/BaseExternalApiGateway.js +48 -0
- package/build/esm/BaseGateway.d.ts +455 -17
- package/build/esm/BaseGateway.js +503 -57
- package/build/esm/BaseRestApiCrudController.d.ts +37 -0
- package/build/esm/BaseRestApiCrudController.js +131 -0
- package/build/esm/DataCache.d.ts +116 -5
- package/build/esm/DataCache.js +142 -20
- package/build/esm/Database.d.ts +165 -4
- package/build/esm/Database.js +224 -51
- package/build/esm/DbMigratorAndSeeder.d.ts +127 -26
- package/build/esm/DbMigratorAndSeeder.js +184 -71
- package/build/esm/IpRateLimiter.d.ts +105 -0
- package/build/esm/IpRateLimiter.js +100 -0
- package/build/esm/RedisDataLoader.d.ts +144 -21
- package/build/esm/RedisDataLoader.js +179 -50
- package/build/esm/apiContext.d.ts +0 -8
- package/build/esm/apiContext.js +30 -32
- package/build/esm/checkItHelpers.d.ts +32 -0
- package/build/esm/checkItHelpers.js +73 -7
- package/build/esm/commonValidators.d.ts +107 -16
- package/build/esm/commonValidators.js +209 -105
- package/build/esm/configBuilder.d.ts +23 -0
- package/build/esm/configBuilder.js +69 -0
- package/build/esm/constants.d.ts +134 -17
- package/build/esm/constants.js +94 -14
- package/build/esm/dbHelpers.d.ts +89 -29
- package/build/esm/dbHelpers.js +171 -81
- package/build/esm/dbSeeder.d.ts +10 -1
- package/build/esm/dbSeeder.js +81 -16
- package/build/esm/dbTableHelpers.d.ts +122 -5
- package/build/esm/dbTableHelpers.js +152 -14
- package/build/esm/downloadHelpers.d.ts +24 -1
- package/build/esm/downloadHelpers.js +51 -21
- package/build/esm/index.d.ts +6 -2
- package/build/esm/index.js +6 -2
- package/build/esm/interfaces/ApiContext.d.ts +33 -3
- package/build/esm/interfaces/ApiContext.js +1 -0
- package/build/esm/interfaces/ApiContextInterface.d.ts +1 -1
- package/build/esm/interfaces/BaseControllerPropsInterface.d.ts +5 -0
- package/build/esm/interfaces/BaseControllerPropsInterface.js +1 -0
- package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
- package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
- package/build/esm/interfaces/BaseCorePropsInterface.d.ts +146 -9
- package/build/esm/interfaces/BaseCorePropsInterface.js +1 -0
- package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
- package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.js +2 -0
- package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
- package/build/esm/interfaces/BaseGatewayPropsInterface.js +1 -0
- package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
- package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.js +2 -0
- package/build/esm/interfaces/BuildConfigOptions.d.ts +18 -0
- package/build/esm/interfaces/BuildConfigOptions.js +1 -0
- package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
- package/build/esm/interfaces/BuildListQueryArgsInterface.js +1 -0
- package/build/esm/interfaces/CacheInterface.d.ts +18 -1
- package/build/esm/interfaces/CacheInterface.js +1 -0
- package/build/esm/interfaces/CoreActionInterface.d.ts +60 -0
- package/build/esm/interfaces/CoreActionInterface.js +1 -0
- package/build/esm/interfaces/CreateUserTokenArgs.d.ts +38 -4
- package/build/esm/interfaces/CreateUserTokenArgs.js +1 -0
- package/build/esm/interfaces/DataCachePropsInterface.d.ts +21 -0
- package/build/esm/interfaces/DataCachePropsInterface.js +2 -0
- package/build/esm/interfaces/DatabaseOptions.d.ts +24 -10
- package/build/esm/interfaces/DatabaseOptions.js +1 -0
- package/build/esm/interfaces/DatabaseReadInterface.d.ts +58 -3
- package/build/esm/interfaces/DatabaseReadInterface.js +1 -0
- package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
- package/build/esm/interfaces/DbFieldAddDefaultInterface.js +1 -0
- package/build/esm/interfaces/DownloadFileArgs.d.ts +21 -2
- package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +15 -4
- package/build/esm/interfaces/ExtractCredentialsArgs.js +1 -0
- package/build/esm/interfaces/ListArgsInterface.d.ts +18 -0
- package/build/esm/interfaces/ListArgsInterface.js +1 -0
- package/build/esm/interfaces/LoaderInterface.d.ts +36 -1
- package/build/esm/interfaces/LoaderInterface.js +1 -0
- package/build/esm/interfaces/UserTokenParams.d.ts +23 -5
- package/build/esm/interfaces/UserTokenParams.js +1 -0
- package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +42 -2
- package/build/esm/interfaces/VerifyUserTokenArgs.js +1 -0
- package/build/esm/interfaces/index.d.ts +4 -0
- package/build/esm/interfaces/index.js +4 -0
- package/build/esm/knexConfigBuilder.d.ts +25 -0
- package/build/esm/knexConfigBuilder.js +100 -36
- package/build/esm/parseIds.d.ts +6 -0
- package/build/esm/parseIds.js +13 -0
- package/build/esm/passwordHelpers.d.ts +22 -0
- package/build/esm/passwordHelpers.js +40 -8
- package/build/esm/redisClient.d.ts +57 -4
- package/build/esm/redisClient.js +40 -54
- package/build/esm/resolveClientIp.d.ts +15 -0
- package/build/esm/resolveClientIp.js +34 -0
- package/build/esm/resolversHelpers.d.ts +21 -1
- package/build/esm/resolversHelpers.js +48 -26
- package/build/esm/userToken.d.ts +50 -1
- package/build/esm/userToken.js +85 -20
- package/build/esm/utils.d.ts +20 -2
- package/build/esm/utils.js +23 -13
- package/build/index.d.ts +6 -2
- package/build/index.js +6 -2
- package/build/interfaces/ApiContext.d.ts +33 -3
- package/build/interfaces/ApiContext.js +1 -0
- package/build/interfaces/ApiContextInterface.d.ts +1 -1
- package/build/interfaces/BaseControllerPropsInterface.d.ts +5 -0
- package/build/interfaces/BaseControllerPropsInterface.js +2 -0
- package/build/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
- package/build/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
- package/build/interfaces/BaseCorePropsInterface.d.ts +146 -9
- package/build/interfaces/BaseCorePropsInterface.js +1 -0
- package/build/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
- package/build/interfaces/BaseExternalApiGatewayPropsInterface.js +3 -0
- package/build/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
- package/build/interfaces/BaseGatewayPropsInterface.js +1 -0
- package/build/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
- package/build/interfaces/BaseRestApiCrudControllerPropsInterface.js +3 -0
- package/build/interfaces/BuildConfigOptions.d.ts +18 -0
- package/build/interfaces/BuildConfigOptions.js +1 -0
- package/build/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
- package/build/interfaces/BuildListQueryArgsInterface.js +1 -0
- package/build/interfaces/CacheInterface.d.ts +18 -1
- package/build/interfaces/CacheInterface.js +1 -0
- package/build/interfaces/CoreActionInterface.d.ts +60 -0
- package/build/interfaces/CoreActionInterface.js +1 -0
- package/build/interfaces/CreateUserTokenArgs.d.ts +38 -4
- package/build/interfaces/CreateUserTokenArgs.js +1 -0
- package/build/interfaces/DataCachePropsInterface.d.ts +21 -0
- package/build/interfaces/DataCachePropsInterface.js +3 -0
- package/build/interfaces/DatabaseOptions.d.ts +24 -10
- package/build/interfaces/DatabaseOptions.js +1 -0
- package/build/interfaces/DatabaseReadInterface.d.ts +58 -3
- package/build/interfaces/DatabaseReadInterface.js +1 -0
- package/build/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
- package/build/interfaces/DbFieldAddDefaultInterface.js +1 -0
- package/build/interfaces/DownloadFileArgs.d.ts +21 -2
- package/build/interfaces/ExtractCredentialsArgs.d.ts +15 -4
- package/build/interfaces/ExtractCredentialsArgs.js +1 -0
- package/build/interfaces/ListArgsInterface.d.ts +18 -0
- package/build/interfaces/ListArgsInterface.js +1 -0
- package/build/interfaces/LoaderInterface.d.ts +36 -1
- package/build/interfaces/LoaderInterface.js +1 -0
- package/build/interfaces/UserTokenParams.d.ts +23 -5
- package/build/interfaces/UserTokenParams.js +1 -0
- package/build/interfaces/VerifyUserTokenArgs.d.ts +42 -2
- package/build/interfaces/VerifyUserTokenArgs.js +1 -0
- package/build/interfaces/index.d.ts +4 -0
- package/build/interfaces/index.js +4 -0
- package/build/knexConfigBuilder.d.ts +25 -0
- package/build/knexConfigBuilder.js +99 -35
- package/build/parseIds.d.ts +6 -0
- package/build/parseIds.js +17 -0
- package/build/passwordHelpers.d.ts +22 -0
- package/build/passwordHelpers.js +40 -8
- package/build/redisClient.d.ts +57 -4
- package/build/redisClient.js +40 -54
- package/build/resolveClientIp.d.ts +15 -0
- package/build/resolveClientIp.js +38 -0
- package/build/resolversHelpers.d.ts +21 -1
- package/build/resolversHelpers.js +48 -26
- package/build/userToken.d.ts +50 -1
- package/build/userToken.js +85 -20
- package/build/utils.d.ts +20 -2
- package/build/utils.js +24 -16
- package/package.json +19 -18
- package/build/baseController.d.ts +0 -17
- package/build/baseController.js +0 -64
- package/build/configBulder.d.ts +0 -2
- package/build/configBulder.js +0 -36
- package/build/esm/baseController.d.ts +0 -17
- package/build/esm/baseController.js +0 -58
- package/build/esm/configBulder.d.ts +0 -2
- package/build/esm/configBulder.js +0 -32
|
@@ -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
|
-
|
|
3
|
-
|
|
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
|
-
|
|
12
|
-
|
|
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
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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 };
|
package/build/esm/redisClient.js
CHANGED
|
@@ -1,32 +1,53 @@
|
|
|
1
|
+
// ./src/redisClient.ts
|
|
1
2
|
import { createClient } from 'redis';
|
|
2
|
-
|
|
3
|
-
|
|
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
|
|
31
|
+
connectTimeout: connectionTimeout ?? 5000,
|
|
17
32
|
noDelay: true,
|
|
18
33
|
keepAlive: true,
|
|
19
|
-
keepAliveInitialDelay: pingInterval
|
|
20
|
-
reconnectStrategy: (retries) => Math.min(retries * 50,
|
|
34
|
+
keepAliveInitialDelay: pingInterval ?? 5000,
|
|
35
|
+
reconnectStrategy: (retries) => Math.min(retries * 50, maxDelay),
|
|
21
36
|
};
|
|
22
37
|
const socketConfig = redisSsl
|
|
23
|
-
? {
|
|
24
|
-
|
|
25
|
-
|
|
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
|
-
|
|
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
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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`] = (
|
|
12
|
-
return context.cores[coreToUse]
|
|
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`] = (
|
|
17
|
-
return context.cores[coreToUse]
|
|
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`] = (
|
|
22
|
-
return context.cores[coreToUse]
|
|
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`] = (
|
|
27
|
-
return context.cores[coreToUse]
|
|
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`] = (
|
|
32
|
-
return context.cores[coreToUse]
|
|
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`] = (
|
|
37
|
-
return context.cores[coreToUse]
|
|
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`] = (
|
|
42
|
-
return context.cores[coreToUse]
|
|
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`] = (
|
|
47
|
-
return context.cores[coreToUse]
|
|
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`] = (
|
|
52
|
-
return context.cores[coreToUse]
|
|
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`] = (
|
|
57
|
-
return context.cores[coreToUse]
|
|
78
|
+
Mutation[`${prefix}RemoveMany`] = (_parent, args, context) => {
|
|
79
|
+
return context.cores?.[coreToUse]?.removeMany(args);
|
|
58
80
|
};
|
|
59
81
|
}
|
|
60
82
|
return {
|
package/build/esm/userToken.d.ts
CHANGED
|
@@ -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
|
-
|
|
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;
|