@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
package/build/esm/userToken.js
CHANGED
|
@@ -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
|
-
|
|
27
|
-
params['fingerprint'] = fingerprint;
|
|
74
|
+
params['fingerprint'] = uuid();
|
|
28
75
|
}
|
|
29
|
-
const
|
|
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
|
|
39
|
-
}
|
|
40
|
-
|
|
85
|
+
expiresIn: expiresIn,
|
|
86
|
+
};
|
|
87
|
+
const token = jwt.sign(params, secret, signOptions);
|
|
88
|
+
return OpResult.ok({ token, fingerprint: params['fingerprint'] ?? null });
|
|
41
89
|
};
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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).
|
|
138
|
+
return OpResult.fail(OP_RESULT_CODES.EXPIRED, null, `User authorization has expired at ${dayjs(ex.expiredAt).toISOString()}`);
|
|
74
139
|
}
|
|
75
|
-
|
|
76
|
-
return OpResult.fail(OP_RESULT_CODES.
|
|
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
|
}
|
package/build/esm/utils.d.ts
CHANGED
|
@@ -1,4 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Returns `func` if it is a function, otherwise returns `defaultFunc`.
|
|
3
|
+
* Useful for ensuring a callback is always callable.
|
|
4
|
+
*
|
|
5
|
+
* @param func Value to check
|
|
6
|
+
* @param defaultFunc Fallback function if `func` is not a function
|
|
7
|
+
*/
|
|
1
8
|
export declare const setFunction: (func: any, defaultFunc: () => any) => any;
|
|
9
|
+
/**
|
|
10
|
+
* Builds an object containing only the keys from `defaultFuncs` where
|
|
11
|
+
* the corresponding value in `obj` is a function.
|
|
12
|
+
*
|
|
13
|
+
* Keys present in `defaultFuncs` but missing or non-function in `obj`
|
|
14
|
+
* are omitted from the result entirely — no fallback is applied.
|
|
15
|
+
* Keys present in `obj` but not in `defaultFuncs` are ignored.
|
|
16
|
+
*
|
|
17
|
+
* Use `setFunction()` for single-function fallback with a default.
|
|
18
|
+
*
|
|
19
|
+
* @param obj Source object to read functions from
|
|
20
|
+
* @param defaultFuncs Defines which keys to look for in `obj`
|
|
21
|
+
*/
|
|
2
22
|
export declare const setFunctions: (obj: any, defaultFuncs?: any) => any;
|
|
3
|
-
export declare const isOpResult: (result: any) => any;
|
|
4
|
-
export declare const isLogger: (obj: any) => boolean;
|
package/build/esm/utils.js
CHANGED
|
@@ -1,25 +1,35 @@
|
|
|
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
|
-
|
|
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;
|
|
12
34
|
}, {});
|
|
13
35
|
};
|
|
14
|
-
export const isOpResult = (result) => {
|
|
15
|
-
return result &&
|
|
16
|
-
typeof result.code === 'number' &&
|
|
17
|
-
typeof result.didFail === 'function';
|
|
18
|
-
};
|
|
19
|
-
export const isLogger = (obj) => {
|
|
20
|
-
return obj &&
|
|
21
|
-
typeof obj.warn === 'function' &&
|
|
22
|
-
typeof obj.error === 'function' &&
|
|
23
|
-
typeof obj.debug === 'function' &&
|
|
24
|
-
typeof obj.log === 'function';
|
|
25
|
-
};
|
package/build/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export * from './constants';
|
|
2
2
|
export * from './interfaces';
|
|
3
|
-
export * from './
|
|
3
|
+
export * from './configBuilder';
|
|
4
4
|
export * from './Database';
|
|
5
5
|
export * from './dbHelpers';
|
|
6
6
|
export * from './DbMigratorAndSeeder';
|
|
@@ -12,10 +12,14 @@ export * from './DataCache';
|
|
|
12
12
|
export * from './BaseGateway';
|
|
13
13
|
export * from './BaseCore';
|
|
14
14
|
export * from './apiContext';
|
|
15
|
-
export * from './
|
|
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';
|
|
25
|
+
export * from './IpRateLimiter';
|
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("./
|
|
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,14 @@ __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("./
|
|
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);
|
|
41
|
+
__exportStar(require("./IpRateLimiter"), exports);
|
|
@@ -1,12 +1,16 @@
|
|
|
1
|
-
|
|
2
|
-
* Interface of application API interface which should be created on receiving of a request
|
|
3
|
-
*/
|
|
1
|
+
import { RateLimiterInterface, RateLimitRule } from '../IpRateLimiter';
|
|
4
2
|
export interface ApiContext {
|
|
5
3
|
requestId: string;
|
|
6
4
|
cores: any;
|
|
7
5
|
gateways: any;
|
|
6
|
+
usedKeyPrefixes: Record<string, any>;
|
|
8
7
|
req: any;
|
|
9
8
|
res?: any;
|
|
9
|
+
db?: any;
|
|
10
|
+
headers?: Record<string, any>;
|
|
11
|
+
cookies?: Record<string, any>;
|
|
12
|
+
isExternalDb?: boolean;
|
|
13
|
+
authorizationToken?: string;
|
|
10
14
|
spaceId?: string;
|
|
11
15
|
apiKey?: string;
|
|
12
16
|
managementApiKey?: string;
|
|
@@ -17,9 +21,35 @@ export interface ApiContext {
|
|
|
17
21
|
languages?: string[];
|
|
18
22
|
requestedLang?: string;
|
|
19
23
|
authorization?: string;
|
|
24
|
+
fingerprint?: string;
|
|
20
25
|
accountId?: string;
|
|
21
26
|
roleId?: string;
|
|
22
27
|
userId?: string;
|
|
23
28
|
lang?: string;
|
|
29
|
+
/**
|
|
30
|
+
* App-level rate-limiter singleton. Created once at startup (e.g. in
|
|
31
|
+
* createContextDefault) and shared across every core in every request.
|
|
32
|
+
*
|
|
33
|
+
* BaseCore.getRateLimiter() reads this field when no per-core override is
|
|
34
|
+
* set in BaseCorePropsInterface.rateLimiter. Setting it to null on the
|
|
35
|
+
* context disables rate limiting for all cores that don't have their own
|
|
36
|
+
* override.
|
|
37
|
+
*
|
|
38
|
+
* Typed as RateLimiterInterface so any compatible implementation works —
|
|
39
|
+
* the built-in IpRateLimiter is the default but tests can swap in a no-op.
|
|
40
|
+
*/
|
|
41
|
+
rateLimiter?: RateLimiterInterface | null;
|
|
42
|
+
/**
|
|
43
|
+
* Service-wide rate-limit rule applied as a global tier on every runAction
|
|
44
|
+
* call across all cores. Runs independently alongside the core-or-action
|
|
45
|
+
* tier — both must pass. Cannot be opted out by per-core or per-action config.
|
|
46
|
+
*
|
|
47
|
+
* Set once at app startup via createContextDefault (or your own context
|
|
48
|
+
* factory). Leave unset to skip the global tier entirely.
|
|
49
|
+
*
|
|
50
|
+
* Example — cap every IP at 300 requests per minute across the whole service:
|
|
51
|
+
* globalRateLimit: { limit: 300, windowSec: 60 }
|
|
52
|
+
*/
|
|
53
|
+
globalRateLimit?: RateLimitRule;
|
|
24
54
|
[key: string]: any;
|
|
25
55
|
}
|
|
@@ -5,7 +5,7 @@ export interface ApiContextInterface {
|
|
|
5
5
|
gateways: any;
|
|
6
6
|
req: any;
|
|
7
7
|
res: any;
|
|
8
|
-
requestId
|
|
8
|
+
requestId?: string;
|
|
9
9
|
getCoreContext?(args: any): Promise<BaseCorePropsInterface>;
|
|
10
10
|
getGatewayContext?(args: any): Promise<BaseGatewayPropsInterface>;
|
|
11
11
|
extendContext?(args: any): any;
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
export interface BaseCoreDoingWhatInterface {
|
|
2
|
-
list
|
|
3
|
-
get
|
|
4
|
-
getMany
|
|
5
|
-
create
|
|
6
|
-
createMany
|
|
7
|
-
update
|
|
8
|
-
updateMany
|
|
9
|
-
set
|
|
10
|
-
remove
|
|
11
|
-
removeMany
|
|
12
|
-
[key: string]: string;
|
|
2
|
+
list?: string;
|
|
3
|
+
get?: string;
|
|
4
|
+
getMany?: string;
|
|
5
|
+
create?: string;
|
|
6
|
+
createMany?: string;
|
|
7
|
+
update?: string;
|
|
8
|
+
updateMany?: string;
|
|
9
|
+
set?: string;
|
|
10
|
+
remove?: string;
|
|
11
|
+
removeMany?: string;
|
|
12
|
+
[key: string]: string | undefined;
|
|
13
13
|
}
|
|
@@ -1,37 +1,174 @@
|
|
|
1
1
|
import { Logger } from '@sdflc/utils';
|
|
2
2
|
import { Database } from '../Database';
|
|
3
|
-
import { BaseGateway } from '../BaseGateway';
|
|
4
3
|
import { BaseCoreValidatorsInterface } from './BaseCoreValidatorsInterface';
|
|
5
4
|
import { BaseCoreDoingWhatInterface } from './BaseCoreDoingWhatInterface';
|
|
6
5
|
import { VerifyUserTokenArgs } from './VerifyUserTokenArgs';
|
|
7
6
|
import { ApiContext } from './ApiContext';
|
|
8
7
|
import { ID_TYPES } from '../constants';
|
|
9
8
|
import { BaseCoreDoAuthOnActionInterface } from './BaseCoreDoAuthOnActionInterface';
|
|
9
|
+
import { RateLimiterInterface, RateLimitRule } from '../IpRateLimiter';
|
|
10
|
+
/**
|
|
11
|
+
* Per-action rate-limit overrides. Each key maps to either:
|
|
12
|
+
* - A RateLimitRule object — use this rule for the action
|
|
13
|
+
* - false — explicitly disable rate limiting for the action
|
|
14
|
+
* even if a core-level default rule is configured
|
|
15
|
+
*
|
|
16
|
+
* Actions not listed here fall back to the core-level `rateLimit` default.
|
|
17
|
+
*/
|
|
18
|
+
export type BaseCoreRateLimitOnActionInterface = Partial<Record<'list' | 'get' | 'getMany' | 'create' | 'createMany' | 'update' | 'updateMany' | 'set' | 'remove' | 'removeMany', RateLimitRule | false>>;
|
|
10
19
|
export interface BaseCorePropsInterface {
|
|
11
20
|
/**
|
|
12
|
-
*
|
|
21
|
+
* Full request-scoped ApiContext. Required — cores use it to access
|
|
22
|
+
* userId, spaceId, gateways, requestId, headers, etc.
|
|
13
23
|
*/
|
|
14
24
|
context: ApiContext;
|
|
15
25
|
/**
|
|
16
|
-
* Database instance
|
|
26
|
+
* Database instance for transaction management and raw query access.
|
|
27
|
+
* Required — used by runAction() for startTransaction, commit, rollback,
|
|
28
|
+
* and by exceptionFailure() for isDbError() checks.
|
|
17
29
|
*/
|
|
18
30
|
db: Database;
|
|
19
31
|
/**
|
|
20
|
-
* Name of
|
|
32
|
+
* Name of the default gateway in context.gateways used for CRUD operations.
|
|
33
|
+
* Optional — some cores orchestrate other cores or always specify the
|
|
34
|
+
* gateway name explicitly via getGateway(name).
|
|
35
|
+
*/
|
|
36
|
+
gatewayName?: string;
|
|
37
|
+
/**
|
|
38
|
+
* Optional — available to subclasses that vary behaviour between
|
|
39
|
+
* production and non-production environments (e.g. verbose error messages).
|
|
40
|
+
*/
|
|
41
|
+
isProduction?: boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Optional — falls back to a module-level Logger({ level: ERROR }) if not
|
|
44
|
+
* provided or if the value fails the isLogger() duck-type check.
|
|
45
|
+
* Duck-typed to avoid instanceof failures across package versions.
|
|
46
|
+
*/
|
|
47
|
+
logger?: Logger;
|
|
48
|
+
/**
|
|
49
|
+
* Human-readable name for this core. Used as the default `doingWhat`
|
|
50
|
+
* string in log messages and error reports when doingWhat is not set.
|
|
21
51
|
*/
|
|
22
|
-
gatewayName: string;
|
|
23
|
-
isProduction: boolean;
|
|
24
|
-
logger: Logger;
|
|
25
52
|
name?: string;
|
|
26
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Master auth switch. When true, all actions require authentication
|
|
55
|
+
* unless overridden per-action via doAuthOnAction.
|
|
56
|
+
* Optional — defaults to false (no auth required).
|
|
57
|
+
*/
|
|
58
|
+
doAuth?: boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Per-action auth overrides. Each action independently enables or disables
|
|
61
|
+
* auth. Falls back to doAuth if not set for a specific action.
|
|
62
|
+
*
|
|
63
|
+
* Example — require auth globally but allow public list:
|
|
64
|
+
* { doAuth: true, doAuthOnAction: { list: false } }
|
|
65
|
+
*/
|
|
27
66
|
doAuthOnAction?: BaseCoreDoAuthOnActionInterface;
|
|
67
|
+
/**
|
|
68
|
+
* Custom doingWhat strings for log messages per action.
|
|
69
|
+
* e.g. { create: 'creating a user account', remove: 'deleting a user' }
|
|
70
|
+
* Falls back to `name` then to a built-in default string if not set.
|
|
71
|
+
*/
|
|
28
72
|
doingWhat?: BaseCoreDoingWhatInterface;
|
|
73
|
+
/**
|
|
74
|
+
* Custom validator map. If not provided, getValidators() returns the
|
|
75
|
+
* default validators (validateGet, validateGetMany, validateRemove,
|
|
76
|
+
* validateRemoveMany, and no-op defaults for mutations).
|
|
77
|
+
*/
|
|
29
78
|
validators?: BaseCoreValidatorsInterface;
|
|
30
|
-
|
|
79
|
+
/**
|
|
80
|
+
* Gateway used to resolve the current space by spaceId.
|
|
81
|
+
* Typed structurally rather than as BaseGateway to avoid instanceof
|
|
82
|
+
* coupling across package versions — any object with a get() method works.
|
|
83
|
+
*
|
|
84
|
+
* Used by findSpace() to look up space config (tokenSecret, apiKey, etc.)
|
|
85
|
+
* when context.space is not already populated.
|
|
86
|
+
*/
|
|
87
|
+
spaceGw?: {
|
|
88
|
+
get(id: string): Promise<any>;
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* Shared secret for service-to-service API calls.
|
|
92
|
+
* When context.apiKey matches this value, authentication is bypassed
|
|
93
|
+
* and the request is treated as a trusted interservice call.
|
|
94
|
+
*/
|
|
31
95
|
interserviceApiKey?: string;
|
|
96
|
+
/**
|
|
97
|
+
* JWT secret used to verify user tokens.
|
|
98
|
+
* Can be overridden per-space via getJwtTokenSecretAndSettings().
|
|
99
|
+
*/
|
|
32
100
|
jwtSecret?: string;
|
|
101
|
+
/**
|
|
102
|
+
* Additional options passed to the JWT verification function.
|
|
103
|
+
* e.g. algorithms, audience, issuer, clockTolerance.
|
|
104
|
+
* Merged with defaults in getJwtTokenSecretAndSettings().
|
|
105
|
+
*/
|
|
33
106
|
verifyTokenArgs?: VerifyUserTokenArgs;
|
|
107
|
+
/**
|
|
108
|
+
* When true, create() automatically calculates and sets the orderNo
|
|
109
|
+
* field before inserting. Uses getFilterToSetOrderNo() to scope the
|
|
110
|
+
* sequence and getGatewayToSetOrerNo() to query the current max.
|
|
111
|
+
*/
|
|
34
112
|
hasOrderNo?: boolean;
|
|
113
|
+
/**
|
|
114
|
+
* Controls the orderNo strategy when hasOrderNo is true.
|
|
115
|
+
* true — numeric ordering (10, 20, 30...)
|
|
116
|
+
* false — lexicographic string ordering via StrOrderHelpers
|
|
117
|
+
*/
|
|
35
118
|
orderNoAsDecimal?: boolean;
|
|
119
|
+
/**
|
|
120
|
+
* The ID type this core operates with (UUID, integer, etc.).
|
|
121
|
+
* Used by consumers that need to validate or coerce ID formats.
|
|
122
|
+
* Defaults to ID_TYPES.UNKNOWN if not set.
|
|
123
|
+
*/
|
|
36
124
|
idType?: ID_TYPES;
|
|
125
|
+
/**
|
|
126
|
+
* Per-core rate-limiter override. When set, BaseCore uses this instance
|
|
127
|
+
* instead of the app-level context.rateLimiter singleton. Typed structurally
|
|
128
|
+
* via RateLimiterInterface — any compatible implementation works.
|
|
129
|
+
*
|
|
130
|
+
* The normal path is to leave this unset and place one IpRateLimiter on
|
|
131
|
+
* context.rateLimiter at app startup so all cores share it automatically.
|
|
132
|
+
* Use this field only when a specific core needs a different limiter
|
|
133
|
+
* (e.g. a stricter in-memory limiter for a payment core in tests, or a
|
|
134
|
+
* no-op stub when integrating with an external rate-limiting proxy).
|
|
135
|
+
*
|
|
136
|
+
* Set to null to explicitly disable rate limiting for this core even when
|
|
137
|
+
* context.rateLimiter is configured.
|
|
138
|
+
*/
|
|
139
|
+
rateLimiter?: RateLimiterInterface | null;
|
|
140
|
+
/**
|
|
141
|
+
* Default rate-limit rule applied to every runAction call in this core
|
|
142
|
+
* unless overridden by rateLimitOnAction or CoreActionInterface.rateLimit.
|
|
143
|
+
*
|
|
144
|
+
* Example — limit all actions to 60 requests per minute:
|
|
145
|
+
* { limit: 60, windowSec: 60 }
|
|
146
|
+
*
|
|
147
|
+
* Omit to disable rate limiting at the core level (actions can still
|
|
148
|
+
* opt in individually via CoreActionInterface.rateLimit).
|
|
149
|
+
*/
|
|
150
|
+
rateLimit?: RateLimitRule;
|
|
151
|
+
/**
|
|
152
|
+
* Per-action rate-limit rules. An entry here replaces the core-level
|
|
153
|
+
* `rateLimit` rule for that specific action — core and action are
|
|
154
|
+
* mutually exclusive so a raised action limit is not silently capped
|
|
155
|
+
* by the core counter still running alongside it.
|
|
156
|
+
*
|
|
157
|
+
* The global counter (context.globalRateLimit) always runs independently
|
|
158
|
+
* and is never affected by entries here.
|
|
159
|
+
*
|
|
160
|
+
* Use a RateLimitRule to override the core default for an action.
|
|
161
|
+
* Use false to disable the core-or-action tier for that action entirely
|
|
162
|
+
* so only the global counter applies.
|
|
163
|
+
*
|
|
164
|
+
* Example — raise the limit for uploads, tighten sign-in, drop reads
|
|
165
|
+
* down to global-only:
|
|
166
|
+
* {
|
|
167
|
+
* list: false,
|
|
168
|
+
* get: false,
|
|
169
|
+
* create: { limit: 50, windowSec: 60 }, // replaces core rule
|
|
170
|
+
* update: { limit: 5, windowSec: 300 }, // tighter than core
|
|
171
|
+
* }
|
|
172
|
+
*/
|
|
173
|
+
rateLimitOnAction?: BaseCoreRateLimitOnActionInterface;
|
|
37
174
|
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface BaseExternalApiGatewayPropsInterface {
|
|
2
|
+
/**
|
|
3
|
+
* Optional credentials — a plain API key string or a structured object
|
|
4
|
+
* with whatever keys the external service requires.
|
|
5
|
+
* Can also be set later via setCredentials() once resolved at runtime.
|
|
6
|
+
*/
|
|
7
|
+
credentials?: string | Record<string, any>;
|
|
8
|
+
/**
|
|
9
|
+
* Base URL of the external API.
|
|
10
|
+
* Can be overridden in the subclass if it never changes.
|
|
11
|
+
*/
|
|
12
|
+
baseUrl?: string;
|
|
13
|
+
/**
|
|
14
|
+
* Timeout in milliseconds for outbound requests.
|
|
15
|
+
* Defaults to 10000.
|
|
16
|
+
*/
|
|
17
|
+
timeoutMs?: number;
|
|
18
|
+
logger?: any;
|
|
19
|
+
}
|