@venizia/ignis-kernel 0.4.8-4 → 0.4.8-5
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/dist/esm/base/applications/body-limit.d.ts +29 -0
- package/dist/esm/base/applications/body-limit.js +49 -0
- package/dist/esm/base/applications/body-limit.js.map +1 -0
- package/dist/esm/base/applications/common/types/middlewares.d.ts +7 -1
- package/dist/esm/base/applications/common/types/middlewares.js.map +1 -1
- package/dist/esm/base/applications/index.d.ts +1 -0
- package/dist/esm/base/applications/index.js +1 -0
- package/dist/esm/base/applications/index.js.map +1 -1
- package/dist/esm/base/applications/rest.d.ts +2 -0
- package/dist/esm/base/applications/rest.js +15 -14
- package/dist/esm/base/applications/rest.js.map +1 -1
- package/dist/esm/base/auth/authenticate/common/types/jwt.d.ts +57 -24
- package/dist/esm/base/auth/authenticate/common/types/jwt.js.map +1 -1
- package/dist/esm/base/auth/authenticate/common/types/service.d.ts +3 -0
- package/dist/esm/base/auth/authenticate/common/types/service.js.map +1 -1
- package/dist/esm/base/auth/authenticate/providers/authentication.provider.js +5 -0
- package/dist/esm/base/auth/authenticate/providers/authentication.provider.js.map +1 -1
- package/dist/esm/base/controllers/factory/controller.d.ts +7 -0
- package/dist/esm/base/controllers/factory/crud/abstract.d.ts +11 -0
- package/dist/esm/base/controllers/factory/crud/abstract.js +7 -0
- package/dist/esm/base/controllers/factory/crud/abstract.js.map +1 -1
- package/dist/esm/base/controllers/factory/crud/persistable.js +2 -0
- package/dist/esm/base/controllers/factory/crud/persistable.js.map +1 -1
- package/dist/esm/base/controllers/factory/crud/readable.js +5 -0
- package/dist/esm/base/controllers/factory/crud/readable.js.map +1 -1
- package/dist/esm/base/controllers/factory/definition.d.ts +16 -16
- package/dist/esm/base/middlewares/app-error/app-error.middleware.d.ts +14 -0
- package/dist/esm/base/middlewares/app-error/app-error.middleware.js +68 -2
- package/dist/esm/base/middlewares/app-error/app-error.middleware.js.map +1 -1
- package/dist/esm/base/middlewares/app-error/zod.handler.js +4 -1
- package/dist/esm/base/middlewares/app-error/zod.handler.js.map +1 -1
- package/dist/esm/base/repositories/common/index.d.ts +1 -0
- package/dist/esm/base/repositories/common/index.js +1 -0
- package/dist/esm/base/repositories/common/index.js.map +1 -1
- package/dist/esm/base/repositories/common/request-filter-guard.d.ts +68 -0
- package/dist/esm/base/repositories/common/request-filter-guard.js +94 -0
- package/dist/esm/base/repositories/common/request-filter-guard.js.map +1 -0
- package/dist/esm/base/repositories/core/abstract.d.ts +16 -0
- package/dist/esm/base/repositories/core/abstract.js +26 -0
- package/dist/esm/base/repositories/core/abstract.js.map +1 -1
- package/dist/esm/base/repositories/query-schemas/index.d.ts +6 -6
- package/package.json +3 -3
|
@@ -5,25 +5,40 @@ import type { JWTPayload } from 'jose';
|
|
|
5
5
|
import type { JOSEStandards, JWKSModes, TJWKSAlgorithm, TJWKSKeyDriver, TJWKSKeyFormat } from '../constants/index.js';
|
|
6
6
|
import type { IAuthUser } from './strategy.js';
|
|
7
7
|
/**
|
|
8
|
-
*
|
|
9
|
-
*
|
|
8
|
+
* The `iss` and, optionally, the `aud` of a service: stamped on every token it signs and REQUIRED on every token it
|
|
9
|
+
* verifies. `issuer` is required, `audience` is optional, and no other key is accepted.
|
|
10
10
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* issuer JWKS
|
|
11
|
+
* Without them a token signed with the same key for another purpose (a password-reset or an invite
|
|
12
|
+
* token that carries a user id) would authenticate a request, and in a fleet where every verifier
|
|
13
|
+
* points at the same issuer JWKS a token minted for one service would be accepted by every other.
|
|
14
14
|
* `audience` is what makes "this token was meant for me" a cryptographic statement rather than a
|
|
15
15
|
* convention.
|
|
16
16
|
*/
|
|
17
|
-
export interface
|
|
18
|
-
/**
|
|
17
|
+
export interface IJWTClaimsOptions {
|
|
18
|
+
/** The `iss` stamped on every issued token and required on every verified one. */
|
|
19
|
+
issuer: string;
|
|
20
|
+
/**
|
|
21
|
+
* The `aud` stamped on every issued token and required on every verified one. Optional: without it no `aud` is
|
|
22
|
+
* stamped and none is checked, so a token with or without one verifies. Set, it must be a non-empty string or a
|
|
23
|
+
* non-empty list of them. Matching is jose's OVERLAP semantics, not equality: a token carrying `['a','b']`
|
|
24
|
+
* satisfies `audience: 'a'`. Enforce single-valued audiences at issue time if that matters.
|
|
25
|
+
*/
|
|
19
26
|
audience?: string | string[];
|
|
20
|
-
|
|
21
|
-
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The other claim checks applied when VERIFYING a JWT. Field names and types mirror jose's
|
|
30
|
+
* `JWTVerifyOptions`, so this is a pass-through with no translation layer. `issuer` and `audience`
|
|
31
|
+
* are not here: they are the required {@link IJWTClaimsOptions}.
|
|
32
|
+
*
|
|
33
|
+
* Every field is optional and unset by default: nothing is checked beyond the signature, the time
|
|
34
|
+
* claims, the `claims` and the algorithm pin.
|
|
35
|
+
*/
|
|
36
|
+
export interface IJWTVerifyOptions {
|
|
22
37
|
/** Expected `sub`. Setting it makes the claim required. */
|
|
23
38
|
subject?: string;
|
|
24
39
|
/** Clock skew tolerance: seconds, or a jose duration string such as `'30 seconds'`. */
|
|
25
40
|
clockTolerance?: string | number;
|
|
26
|
-
/** Accepted JWS `alg` header values. Unset
|
|
41
|
+
/** Accepted JWS `alg` header values. Unset pins the one algorithm the service signs with: `headerAlgorithm` (`HS256` by default) of the JWS service, `algorithm` of a JWKS issuer. A JWKS verifier cannot know it, so it requires this ({@link IJWKSVerifierVerifyOptions}). */
|
|
27
42
|
algorithms?: string[];
|
|
28
43
|
/** Caps elapsed time since `iat`. The real replay window for a short-lived assertion, independent of whatever `exp` the caller chose to stamp. */
|
|
29
44
|
maxTokenAge?: string | number;
|
|
@@ -32,18 +47,13 @@ export interface IJWTVerifyOptions {
|
|
|
32
47
|
/** Claims that must be present, beyond those implied by the checks above. */
|
|
33
48
|
requiredClaims?: string[];
|
|
34
49
|
}
|
|
35
|
-
/** Default `iss` / `aud` stamped on every issued token. Configured values are AUTHORITATIVE - see {@link IJWTIssueClaims}. */
|
|
36
|
-
export interface IJWTSignOptions {
|
|
37
|
-
issuer?: string;
|
|
38
|
-
audience?: string | string[];
|
|
39
|
-
}
|
|
40
50
|
/**
|
|
41
51
|
* Per-token registered claims, passed to `generate()`.
|
|
42
52
|
*
|
|
43
53
|
* This is the supported way to vary `aud` or `sub` per token. Putting them on the payload used to
|
|
44
54
|
* work by accident - `iss`, `aud`, `sub` and `jti` ride through the AES envelope in the clear
|
|
45
55
|
* because they are standard JWT fields - but a claim the payload can set is a claim any caller who
|
|
46
|
-
* shapes the payload can forge. These win over {@link
|
|
56
|
+
* shapes the payload can forge. These win over the configured {@link IJWTClaimsOptions}; the payload never does.
|
|
47
57
|
*/
|
|
48
58
|
export interface IJWTIssueClaims {
|
|
49
59
|
issuer?: string;
|
|
@@ -65,6 +75,8 @@ export interface IJWSTokenServiceOptions {
|
|
|
65
75
|
headerAlgorithm?: string;
|
|
66
76
|
jwtSecret: string;
|
|
67
77
|
getTokenExpiresFn: TGetTokenExpiresFn;
|
|
78
|
+
/** The `iss` and `aud` stamped on every issued token and required on every verified one. A configured value WINS over one supplied in the payload. */
|
|
79
|
+
claims: IJWTClaimsOptions;
|
|
68
80
|
/**
|
|
69
81
|
* The AES algorithm of payload encryption, used when `applicationSecret` is set.
|
|
70
82
|
*
|
|
@@ -73,10 +85,8 @@ export interface IJWSTokenServiceOptions {
|
|
|
73
85
|
aesAlgorithm?: AESAlgorithmType;
|
|
74
86
|
applicationSecret?: string;
|
|
75
87
|
fieldCodecs?: IPayloadFieldCodec[];
|
|
76
|
-
/**
|
|
88
|
+
/** Further checks applied on verify, beside `claims` and the algorithm pin. */
|
|
77
89
|
verify?: IJWTVerifyOptions;
|
|
78
|
-
/** Claims stamped on every issued token. A configured value WINS over one supplied in the payload. */
|
|
79
|
-
sign?: IJWTSignOptions;
|
|
80
90
|
}
|
|
81
91
|
/** Options of a JWKS issuer, which signs tokens with its own key pair. `keys.private` and `keys.public` hold content or a file path according to `keys.driver`. `rest.path` sets where the public key set is served. */
|
|
82
92
|
export interface IJWKSIssuerOptions {
|
|
@@ -94,6 +104,8 @@ export interface IJWKSIssuerOptions {
|
|
|
94
104
|
};
|
|
95
105
|
kid: string;
|
|
96
106
|
getTokenExpiresFn: TGetTokenExpiresFn;
|
|
107
|
+
/** The `iss` and `aud` stamped on every issued token and required on every verified one. A configured value WINS over one supplied in the payload. */
|
|
108
|
+
claims: IJWTClaimsOptions;
|
|
97
109
|
/**
|
|
98
110
|
* The AES algorithm of payload encryption, used when `applicationSecret` is set.
|
|
99
111
|
*
|
|
@@ -102,15 +114,36 @@ export interface IJWKSIssuerOptions {
|
|
|
102
114
|
aesAlgorithm?: AESAlgorithmType;
|
|
103
115
|
applicationSecret?: string;
|
|
104
116
|
fieldCodecs?: IPayloadFieldCodec[];
|
|
105
|
-
/**
|
|
117
|
+
/** Further checks applied on verify, beside `claims` and the algorithm pin. */
|
|
106
118
|
verify?: IJWTVerifyOptions;
|
|
107
|
-
|
|
108
|
-
|
|
119
|
+
}
|
|
120
|
+
/** The verify checks of a JWKS verifier: `algorithms` is required, because the verifier cannot know what the issuer signs with. */
|
|
121
|
+
export interface IJWKSVerifierVerifyOptions extends IJWTVerifyOptions {
|
|
122
|
+
/** The JWS `alg` values accepted, for example `['RS256']`. At least one. */
|
|
123
|
+
algorithms: string[];
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Where a JWKS may be fetched over plain `http:`. A JWKS URL is `https:` unless its host is loopback (`localhost`,
|
|
127
|
+
* `127.0.0.0/8`, `::1`) or is named in `http`.
|
|
128
|
+
*/
|
|
129
|
+
export interface IJWKSHosts {
|
|
130
|
+
/**
|
|
131
|
+
* Host NAMES that may serve a JWKS over `http:`, for example `['identity-service']`: a service inside a private
|
|
132
|
+
* network. Names only, never an address range, because what a name resolves to can change. A name matches on the
|
|
133
|
+
* host and ignores the port. An entry with a port, a scheme or a wildcard refuses the boot.
|
|
134
|
+
*/
|
|
135
|
+
http?: string[];
|
|
109
136
|
}
|
|
110
137
|
/** Options of a JWKS verifier, which checks tokens against the key set served at `jwksUrl`. */
|
|
111
138
|
export interface IJWKSVerifierOptions {
|
|
112
139
|
mode: typeof JWKSModes.VERIFIER;
|
|
113
140
|
jwksUrl: string;
|
|
141
|
+
/** The `iss` and `aud` required on every verified token. */
|
|
142
|
+
claims: IJWTClaimsOptions;
|
|
143
|
+
/** Where the key set may be fetched from over `http:`. Unset means `https:` or loopback only. */
|
|
144
|
+
jwks?: {
|
|
145
|
+
hosts?: IJWKSHosts;
|
|
146
|
+
};
|
|
114
147
|
/**
|
|
115
148
|
* How long the fetched key set stays cached, in ms (12 hours).
|
|
116
149
|
*
|
|
@@ -131,8 +164,8 @@ export interface IJWKSVerifierOptions {
|
|
|
131
164
|
aesAlgorithm?: AESAlgorithmType;
|
|
132
165
|
applicationSecret?: string;
|
|
133
166
|
fieldCodecs?: IPayloadFieldCodec[];
|
|
134
|
-
/**
|
|
135
|
-
verify
|
|
167
|
+
/** Further checks applied on verify, beside `claims`. `algorithms` is required. */
|
|
168
|
+
verify: IJWKSVerifierVerifyOptions;
|
|
136
169
|
}
|
|
137
170
|
/** Options of the JWKS token service, selected by `mode`. */
|
|
138
171
|
export type TJWKSTokenServiceOptions = IJWKSIssuerOptions | IJWKSVerifierOptions;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jwt.js","sourceRoot":"","sources":["../../../../../../../src/base/auth/authenticate/common/types/jwt.ts"],"names":[],"mappings":"","sourcesContent":["import type { IdType } from '@/base/models/common';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type { AESAlgorithmType } from '@venizia/ignis-helpers/core';\nimport type { JWTPayload } from 'jose';\nimport type {\n JOSEStandards,\n JWKSModes,\n TJWKSAlgorithm,\n TJWKSKeyDriver,\n TJWKSKeyFormat,\n} from '../constants';\nimport type { IAuthUser } from './strategy';\n\n/**\n *
|
|
1
|
+
{"version":3,"file":"jwt.js","sourceRoot":"","sources":["../../../../../../../src/base/auth/authenticate/common/types/jwt.ts"],"names":[],"mappings":"","sourcesContent":["import type { IdType } from '@/base/models/common';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type { AESAlgorithmType } from '@venizia/ignis-helpers/core';\nimport type { JWTPayload } from 'jose';\nimport type {\n JOSEStandards,\n JWKSModes,\n TJWKSAlgorithm,\n TJWKSKeyDriver,\n TJWKSKeyFormat,\n} from '../constants';\nimport type { IAuthUser } from './strategy';\n\n/**\n * The `iss` and, optionally, the `aud` of a service: stamped on every token it signs and REQUIRED on every token it\n * verifies. `issuer` is required, `audience` is optional, and no other key is accepted.\n *\n * Without them a token signed with the same key for another purpose (a password-reset or an invite\n * token that carries a user id) would authenticate a request, and in a fleet where every verifier\n * points at the same issuer JWKS a token minted for one service would be accepted by every other.\n * `audience` is what makes \"this token was meant for me\" a cryptographic statement rather than a\n * convention.\n */\nexport interface IJWTClaimsOptions {\n /** The `iss` stamped on every issued token and required on every verified one. */\n issuer: string;\n\n /**\n * The `aud` stamped on every issued token and required on every verified one. Optional: without it no `aud` is\n * stamped and none is checked, so a token with or without one verifies. Set, it must be a non-empty string or a\n * non-empty list of them. Matching is jose's OVERLAP semantics, not equality: a token carrying `['a','b']`\n * satisfies `audience: 'a'`. Enforce single-valued audiences at issue time if that matters.\n */\n audience?: string | string[];\n}\n\n/**\n * The other claim checks applied when VERIFYING a JWT. Field names and types mirror jose's\n * `JWTVerifyOptions`, so this is a pass-through with no translation layer. `issuer` and `audience`\n * are not here: they are the required {@link IJWTClaimsOptions}.\n *\n * Every field is optional and unset by default: nothing is checked beyond the signature, the time\n * claims, the `claims` and the algorithm pin.\n */\nexport interface IJWTVerifyOptions {\n /** Expected `sub`. Setting it makes the claim required. */\n subject?: string;\n\n /** Clock skew tolerance: seconds, or a jose duration string such as `'30 seconds'`. */\n clockTolerance?: string | number;\n\n /** Accepted JWS `alg` header values. Unset pins the one algorithm the service signs with: `headerAlgorithm` (`HS256` by default) of the JWS service, `algorithm` of a JWKS issuer. A JWKS verifier cannot know it, so it requires this ({@link IJWKSVerifierVerifyOptions}). */\n algorithms?: string[];\n\n /** Caps elapsed time since `iat`. The real replay window for a short-lived assertion, independent of whatever `exp` the caller chose to stamp. */\n maxTokenAge?: string | number;\n\n /** Expected JWS `typ` header. The standard defence against cross-token-type confusion when one JWKS serves more than one kind of token. */\n typ?: string;\n\n /** Claims that must be present, beyond those implied by the checks above. */\n requiredClaims?: string[];\n}\n\n/**\n * Per-token registered claims, passed to `generate()`.\n *\n * This is the supported way to vary `aud` or `sub` per token. Putting them on the payload used to\n * work by accident - `iss`, `aud`, `sub` and `jti` ride through the AES envelope in the clear\n * because they are standard JWT fields - but a claim the payload can set is a claim any caller who\n * shapes the payload can forge. These win over the configured {@link IJWTClaimsOptions}; the payload never does.\n */\nexport interface IJWTIssueClaims {\n issuer?: string;\n audience?: string | string[];\n subject?: string;\n jwtId?: string;\n}\n\n/**\n * Options of the JWS token service, which signs with the shared `jwtSecret`.\n *\n * `getTokenExpiresFn` is required. AES payload encryption is active only when `applicationSecret` is set.\n */\nexport interface IJWSTokenServiceOptions {\n /**\n * The JWS `alg` header.\n *\n * @default 'HS256'\n */\n headerAlgorithm?: string;\n jwtSecret: string;\n getTokenExpiresFn: TGetTokenExpiresFn;\n\n /** The `iss` and `aud` stamped on every issued token and required on every verified one. A configured value WINS over one supplied in the payload. */\n claims: IJWTClaimsOptions;\n\n /**\n * The AES algorithm of payload encryption, used when `applicationSecret` is set.\n *\n * @default 'aes-256-cbc'\n */\n aesAlgorithm?: AESAlgorithmType;\n applicationSecret?: string;\n fieldCodecs?: IPayloadFieldCodec[];\n\n /** Further checks applied on verify, beside `claims` and the algorithm pin. */\n verify?: IJWTVerifyOptions;\n}\n\n/** Options of a JWKS issuer, which signs tokens with its own key pair. `keys.private` and `keys.public` hold content or a file path according to `keys.driver`. `rest.path` sets where the public key set is served. */\nexport interface IJWKSIssuerOptions {\n mode: typeof JWKSModes.ISSUER;\n algorithm: TJWKSAlgorithm;\n rest?: {\n /** @default '/certs' */\n path: string;\n };\n keys: {\n driver: TJWKSKeyDriver;\n format: TJWKSKeyFormat;\n private: string; // Key content (text) or file path (file) — PEM or JWK based on format\n public: string; // Key content (text) or file path (file) — PEM or JWK based on format\n };\n kid: string;\n getTokenExpiresFn: TGetTokenExpiresFn;\n\n /** The `iss` and `aud` stamped on every issued token and required on every verified one. A configured value WINS over one supplied in the payload. */\n claims: IJWTClaimsOptions;\n\n /**\n * The AES algorithm of payload encryption, used when `applicationSecret` is set.\n *\n * @default 'aes-256-cbc'\n */\n aesAlgorithm?: AESAlgorithmType;\n applicationSecret?: string;\n fieldCodecs?: IPayloadFieldCodec[];\n\n /** Further checks applied on verify, beside `claims` and the algorithm pin. */\n verify?: IJWTVerifyOptions;\n}\n\n/** The verify checks of a JWKS verifier: `algorithms` is required, because the verifier cannot know what the issuer signs with. */\nexport interface IJWKSVerifierVerifyOptions extends IJWTVerifyOptions {\n /** The JWS `alg` values accepted, for example `['RS256']`. At least one. */\n algorithms: string[];\n}\n\n/**\n * Where a JWKS may be fetched over plain `http:`. A JWKS URL is `https:` unless its host is loopback (`localhost`,\n * `127.0.0.0/8`, `::1`) or is named in `http`.\n */\nexport interface IJWKSHosts {\n /**\n * Host NAMES that may serve a JWKS over `http:`, for example `['identity-service']`: a service inside a private\n * network. Names only, never an address range, because what a name resolves to can change. A name matches on the\n * host and ignores the port. An entry with a port, a scheme or a wildcard refuses the boot.\n */\n http?: string[];\n}\n\n/** Options of a JWKS verifier, which checks tokens against the key set served at `jwksUrl`. */\nexport interface IJWKSVerifierOptions {\n mode: typeof JWKSModes.VERIFIER;\n jwksUrl: string;\n\n /** The `iss` and `aud` required on every verified token. */\n claims: IJWTClaimsOptions;\n\n /** Where the key set may be fetched from over `http:`. Unset means `https:` or loopback only. */\n jwks?: { hosts?: IJWKSHosts };\n\n /**\n * How long the fetched key set stays cached, in ms (12 hours).\n *\n * @default 43_200_000\n */\n cacheTtlMs?: number;\n\n /**\n * Minimum wait between refetches of the key set, in ms (30 seconds).\n *\n * @default 30_000\n */\n cooldownMs?: number;\n\n /**\n * The AES algorithm of payload encryption, used when `applicationSecret` is set.\n *\n * @default 'aes-256-cbc'\n */\n aesAlgorithm?: AESAlgorithmType;\n applicationSecret?: string;\n fieldCodecs?: IPayloadFieldCodec[];\n\n /** Further checks applied on verify, beside `claims`. `algorithms` is required. */\n verify: IJWKSVerifierVerifyOptions;\n}\n\n/** Options of the JWKS token service, selected by `mode`. */\nexport type TJWKSTokenServiceOptions = IJWKSIssuerOptions | IJWKSVerifierOptions;\n\n/** Options of the JWT token service, selected by `standard` (`JWS` or `JWKS`). */\nexport type TJWTTokenServiceOptions =\n | { standard: typeof JOSEStandards.JWS; options: IJWSTokenServiceOptions }\n | { standard: typeof JOSEStandards.JWKS; options: TJWKSTokenServiceOptions };\n\n/** One role as a token carries it. */\nexport type TJWTTokenRole = { id: IdType; identifier: string; priority: number };\n\n/**\n * What a token carries. `roles` may be absent: `generate` signs a payload without it as is, `verify`\n * returns it without `roles`, and authorization reads its roles as none. Check it before you read it.\n */\nexport interface IJWTTokenPayload extends JWTPayload, IAuthUser {\n userId: IdType;\n roles?: TJWTTokenRole[];\n\n clientId?: string;\n provider?: string;\n email?: string;\n name?: string;\n\n [extra: string | symbol]: any;\n}\n\n/** Converts one payload field, found under `key`, to a string and back around the AES envelope. */\nexport interface IPayloadFieldCodec<T = unknown> {\n key: string;\n serialize(opts: { value: T }): string;\n deserialize(opts: { raw: string }): T;\n}\n\n/** Returns the lifetime of a token to issue, in seconds from now. */\nexport type TGetTokenExpiresFn = () => ValueOrPromise<number>;\n"]}
|
|
@@ -3,6 +3,7 @@ import type { TNullable, ValueOrPromise } from '@venizia/ignis-helpers/common';
|
|
|
3
3
|
import type { Env } from 'hono';
|
|
4
4
|
import type { JWTPayload } from 'jose';
|
|
5
5
|
import type { TJWKSKeyDriver, TJWKSKeyFormat } from '../constants/index.js';
|
|
6
|
+
import type { IJWKSHosts } from './jwt.js';
|
|
6
7
|
import type { IAuthUser } from './strategy.js';
|
|
7
8
|
/**
|
|
8
9
|
* The request binding, following RFC 9449's `htm`/`htu`. A captured assertion cannot be replayed
|
|
@@ -90,6 +91,8 @@ export interface IServiceAuthOptions<E extends Env = Env> {
|
|
|
90
91
|
cacheMaxAgeMs?: number;
|
|
91
92
|
/** @default 30_000 */
|
|
92
93
|
cooldownMs?: number;
|
|
94
|
+
/** Host names that may serve a caller's key set over `http:`. Unset means `https:` or loopback only. */
|
|
95
|
+
hosts?: IJWKSHosts;
|
|
93
96
|
};
|
|
94
97
|
/**
|
|
95
98
|
* WHO a verified assertion acts as. The framework has already proven the caller; this only maps a
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.js","sourceRoot":"","sources":["../../../../../../../src/base/auth/authenticate/common/types/service.ts"],"names":[],"mappings":"","sourcesContent":["import type { TContext } from '@/base/controllers/common/types';\nimport type { TNullable, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type { Env } from 'hono';\nimport type { JWTPayload } from 'jose';\nimport type { TJWKSKeyDriver, TJWKSKeyFormat } from '../constants';\nimport type { IAuthUser } from './strategy';\n\n/**\n * The request binding, following RFC 9449's `htm`/`htu`. A captured assertion cannot be replayed\n * against a different method or path.\n *\n * `htu` is the percent-ENCODED pathname on both ends. Compare it against\n * `new URL(context.req.url).pathname`, never `context.req.path` - Hono hands that one back DECODED,\n * so any route carrying a space or a non-ASCII slug would never match what the caller signed.\n */\nexport interface IServiceAssertionClaims extends JWTPayload {\n htm: string;\n htu: string;\n}\n\n/**\n * One entry in the caller allowlist: the JWKS url, or that url plus settings for this caller alone.\n */\nexport type TServiceCallerEntry =\n | string\n | {\n jwksUrl: string;\n /** Widens the accepted age for THIS caller only. Falls back to the service-wide setting. */\n acceptMaxAgeSeconds?: number;\n };\n\n/** Service-to-service authentication: an Ed25519 assertion per request, verified against the caller's JWKS. */\nexport interface IServiceAuthOptions<E extends Env = Env> {\n /** What this service calls itself: the `iss` it stamps, and the `aud` it demands. */\n name: string;\n\n /**\n * Present only on a service that CALLS OUT. Absent means verify-only, and no certs route is\n * mounted - which is the common case, since most services are called and never call.\n */\n keys?: {\n driver: TJWKSKeyDriver;\n format: TJWKSKeyFormat;\n /** PEM or JWK by `format`; content for the `text` driver, a path for `file`. */\n private: string;\n public: string;\n kid?: string;\n };\n\n /**\n * Caller name to its JWKS url. THIS IS ALSO THE ALLOWLIST - a name absent from the map cannot\n * call, and an empty map correctly allows nobody.\n *\n * The bare-string form is the common case. The object form exists to widen the accepted age for\n * ONE caller: a nightly batch may legitimately need more slack than an interactive service, and\n * granting it per caller keeps the concession named and visible in config.\n */\n callers?: Record<string, TServiceCallerEntry>;\n\n /** Where the certs route is mounted. */\n rest?: {\n /** @default '/svc-certs' */\n path: string;\n };\n\n /**\n * How long the assertions this service MINTS stay valid. Only meaningful where `keys` is set.\n *\n * @default 60\n */\n signLifetimeSeconds?: number;\n\n /**\n * The oldest assertion this service ACCEPTS, measured from `iat`.\n *\n * Deliberately separate from `signLifetimeSeconds`, and deliberately not requestable by the\n * caller. The caller already controls `exp` - it signs the token - so this is the only bound that\n * survives a compromised caller. A per-caller override belongs in {@link callers}, never in the\n * assertion.\n *\n * Composes with `clockToleranceSeconds`: the real acceptance window is the sum of the two.\n *\n * @default 60\n */\n acceptMaxAgeSeconds?: number;\n\n /**\n * Clock skew allowance. A SECURITY knob, not an operational one.\n *\n * Its job is the future case: two machines never agree to the second, and without it a caller one\n * second ahead is refused outright. But it also widens the REPLAY window second for second - a\n * callee accepting an `iat` 5s in its own future keeps accepting that token for the rest of the\n * window too. Measured at the defaults: 65s accepted on our clock, 70s of wall-clock life for a\n * capture minted by a caller running the full tolerance fast.\n *\n * @default 5\n */\n clockToleranceSeconds?: number;\n\n jwks?: {\n /** @default 600_000 */\n cacheMaxAgeMs?: number;\n\n /** @default 30_000 */\n cooldownMs?: number;\n };\n\n /**\n * WHO a verified assertion acts as. The framework has already proven the caller; this only maps a\n * caller name onto an application principal. Return `null` to refuse a caller the allowlist\n * admits but the application does not recognise.\n */\n resolvePrincipal: (opts: {\n issuer: string;\n context: TContext<E, string>;\n }) => ValueOrPromise<TNullable<IAuthUser>>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"service.js","sourceRoot":"","sources":["../../../../../../../src/base/auth/authenticate/common/types/service.ts"],"names":[],"mappings":"","sourcesContent":["import type { TContext } from '@/base/controllers/common/types';\nimport type { TNullable, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type { Env } from 'hono';\nimport type { JWTPayload } from 'jose';\nimport type { TJWKSKeyDriver, TJWKSKeyFormat } from '../constants';\nimport type { IJWKSHosts } from './jwt';\nimport type { IAuthUser } from './strategy';\n\n/**\n * The request binding, following RFC 9449's `htm`/`htu`. A captured assertion cannot be replayed\n * against a different method or path.\n *\n * `htu` is the percent-ENCODED pathname on both ends. Compare it against\n * `new URL(context.req.url).pathname`, never `context.req.path` - Hono hands that one back DECODED,\n * so any route carrying a space or a non-ASCII slug would never match what the caller signed.\n */\nexport interface IServiceAssertionClaims extends JWTPayload {\n htm: string;\n htu: string;\n}\n\n/**\n * One entry in the caller allowlist: the JWKS url, or that url plus settings for this caller alone.\n */\nexport type TServiceCallerEntry =\n | string\n | {\n jwksUrl: string;\n /** Widens the accepted age for THIS caller only. Falls back to the service-wide setting. */\n acceptMaxAgeSeconds?: number;\n };\n\n/** Service-to-service authentication: an Ed25519 assertion per request, verified against the caller's JWKS. */\nexport interface IServiceAuthOptions<E extends Env = Env> {\n /** What this service calls itself: the `iss` it stamps, and the `aud` it demands. */\n name: string;\n\n /**\n * Present only on a service that CALLS OUT. Absent means verify-only, and no certs route is\n * mounted - which is the common case, since most services are called and never call.\n */\n keys?: {\n driver: TJWKSKeyDriver;\n format: TJWKSKeyFormat;\n /** PEM or JWK by `format`; content for the `text` driver, a path for `file`. */\n private: string;\n public: string;\n kid?: string;\n };\n\n /**\n * Caller name to its JWKS url. THIS IS ALSO THE ALLOWLIST - a name absent from the map cannot\n * call, and an empty map correctly allows nobody.\n *\n * The bare-string form is the common case. The object form exists to widen the accepted age for\n * ONE caller: a nightly batch may legitimately need more slack than an interactive service, and\n * granting it per caller keeps the concession named and visible in config.\n */\n callers?: Record<string, TServiceCallerEntry>;\n\n /** Where the certs route is mounted. */\n rest?: {\n /** @default '/svc-certs' */\n path: string;\n };\n\n /**\n * How long the assertions this service MINTS stay valid. Only meaningful where `keys` is set.\n *\n * @default 60\n */\n signLifetimeSeconds?: number;\n\n /**\n * The oldest assertion this service ACCEPTS, measured from `iat`.\n *\n * Deliberately separate from `signLifetimeSeconds`, and deliberately not requestable by the\n * caller. The caller already controls `exp` - it signs the token - so this is the only bound that\n * survives a compromised caller. A per-caller override belongs in {@link callers}, never in the\n * assertion.\n *\n * Composes with `clockToleranceSeconds`: the real acceptance window is the sum of the two.\n *\n * @default 60\n */\n acceptMaxAgeSeconds?: number;\n\n /**\n * Clock skew allowance. A SECURITY knob, not an operational one.\n *\n * Its job is the future case: two machines never agree to the second, and without it a caller one\n * second ahead is refused outright. But it also widens the REPLAY window second for second - a\n * callee accepting an `iat` 5s in its own future keeps accepting that token for the rest of the\n * window too. Measured at the defaults: 65s accepted on our clock, 70s of wall-clock life for a\n * capture minted by a caller running the full tolerance fast.\n *\n * @default 5\n */\n clockToleranceSeconds?: number;\n\n jwks?: {\n /** @default 600_000 */\n cacheMaxAgeMs?: number;\n\n /** @default 30_000 */\n cooldownMs?: number;\n\n /** Host names that may serve a caller's key set over `http:`. Unset means `https:` or loopback only. */\n hosts?: IJWKSHosts;\n };\n\n /**\n * WHO a verified assertion acts as. The framework has already proven the caller; this only maps a\n * caller name onto an application principal. Return `null` to refuse a caller the allowlist\n * admits but the application does not recognise.\n */\n resolvePrincipal: (opts: {\n issuer: string;\n context: TContext<E, string>;\n }) => ValueOrPromise<TNullable<IAuthUser>>;\n}\n"]}
|
|
@@ -68,6 +68,11 @@ export class AuthenticationProvider extends BaseHelper {
|
|
|
68
68
|
try {
|
|
69
69
|
const strategy = registry.resolveStrategy({ name: strategyName });
|
|
70
70
|
const user = await strategy.authenticate(context);
|
|
71
|
+
// A verified credential is not yet a user: a token signed by the same key for another purpose verifies too. Both
|
|
72
|
+
// modes need an id, so a strategy that answers without one has not authenticated this request.
|
|
73
|
+
if (!user?.userId) {
|
|
74
|
+
throw getError({ error: AuthenticationErrors.USER_UNRESOLVED });
|
|
75
|
+
}
|
|
71
76
|
this.setCurrentUser({ context, user });
|
|
72
77
|
break;
|
|
73
78
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authentication.provider.js","sourceRoot":"","sources":["../../../../../../src/base/auth/authenticate/providers/authentication.provider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAGrD,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAEhD,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AACtF,OAAO,EAAE,8BAA8B,EAAE,MAAM,iCAAiC,CAAC;AAEjF;;;;GAIG;AACH,MAAM,OAAO,sBACX,SAAQ,UAAU;IAGlB;QACE,KAAK,CAAC,EAAE,KAAK,EAAE,sBAAsB,CAAC,IAAI,EAAE,CAAC,CAAC;IAChD,CAAC;IAED,KAAK;QACH,OAAO,CAAC,IAAI,EAAE,EAAE;YACd,OAAO,IAAI,CAAC,4BAA4B,CAAC,IAAI,CAAC,CAAC;QACjD,CAAC,CAAC;IACJ,CAAC;IAEO,4BAA4B,CAAC,IAAgD;QACnF,MAAM,EAAE,UAAU,EAAE,IAAI,GAAG,mBAAmB,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;QAC5D,MAAM,QAAQ,GAAG,8BAA8B,CAAC,WAAW,EAAE,CAAC;QAE9D,OAAO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,MAAM,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QAErD,8HAA8H;QAC9H,IAAI,cAAuB,CAAC;QAE5B,KAAK,MAAM,YAAY,IAAI,UAAU,EAAE,CAAC;YACtC,IAAI,CAAC;gBACH,MAAM,QAAQ,GAAG,QAAQ,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;gBAClE,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"authentication.provider.js","sourceRoot":"","sources":["../../../../../../src/base/auth/authenticate/providers/authentication.provider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAGrD,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAEhD,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AACtF,OAAO,EAAE,8BAA8B,EAAE,MAAM,iCAAiC,CAAC;AAEjF;;;;GAIG;AACH,MAAM,OAAO,sBACX,SAAQ,UAAU;IAGlB;QACE,KAAK,CAAC,EAAE,KAAK,EAAE,sBAAsB,CAAC,IAAI,EAAE,CAAC,CAAC;IAChD,CAAC;IAED,KAAK;QACH,OAAO,CAAC,IAAI,EAAE,EAAE;YACd,OAAO,IAAI,CAAC,4BAA4B,CAAC,IAAI,CAAC,CAAC;QACjD,CAAC,CAAC;IACJ,CAAC;IAEO,4BAA4B,CAAC,IAAgD;QACnF,MAAM,EAAE,UAAU,EAAE,IAAI,GAAG,mBAAmB,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;QAC5D,MAAM,QAAQ,GAAG,8BAA8B,CAAC,WAAW,EAAE,CAAC;QAE9D,OAAO,gBAAgB,CAAC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ignis-helpers/core';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { IProvider } from '@venizia/ignis-inversion';\nimport type { Env } from 'hono';\nimport { createMiddleware } from 'hono/factory';\nimport type { IAuthUser, TAuthenticateFn, TAuthMode } from '../common';\nimport { Authentication, AuthenticationErrors, AuthenticationModes } from '../common';\nimport { AuthenticationStrategyRegistry } from '../strategies/strategy-registry';\n\n/**\n * Provides the `authenticate` middleware factory. Strategies resolve from `AuthenticationStrategyRegistry`.\n *\n * The middleware skips a request flagged `Authentication.SKIP_AUTHENTICATION` or already holding a current user. On success it stores the user and its audit user id in the request context.\n */\nexport class AuthenticationProvider<RouteEnv extends Env = Env>\n extends BaseHelper\n implements IProvider<TAuthenticateFn<RouteEnv>>\n{\n constructor() {\n super({ scope: AuthenticationProvider.name });\n }\n\n value(): TAuthenticateFn<RouteEnv> {\n return (opts) => {\n return this.createAuthenticateMiddleware(opts);\n };\n }\n\n private createAuthenticateMiddleware(opts: { strategies: string[]; mode?: TAuthMode }) {\n const { strategies, mode = AuthenticationModes.ANY } = opts;\n const registry = AuthenticationStrategyRegistry.getInstance();\n\n return createMiddleware(async (context, next) => {\n const isSkipAuthenticate = context.get(Authentication.SKIP_AUTHENTICATION);\n\n if (isSkipAuthenticate) {\n this.logger\n .for(this.createAuthenticateMiddleware.name)\n .debug('SKIP checking authentication | path: %s', context.req.path);\n\n return next();\n }\n\n const isAuthenticated = context.get(Authentication.CURRENT_USER);\n\n if (isAuthenticated) {\n return next();\n }\n\n switch (mode) {\n case AuthenticationModes.ANY: {\n await this.executeAnyMode({\n context: context as TContext,\n strategies,\n registry,\n next,\n });\n\n return;\n }\n case AuthenticationModes.ALL: {\n await this.executeAllMode({\n context: context as TContext,\n strategies,\n registry,\n next,\n });\n\n return;\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `Invalid authentication mode | mode: ${mode}`,\n });\n }\n }\n });\n }\n\n private async executeAnyMode(opts: {\n context: TContext;\n strategies: string[];\n registry: AuthenticationStrategyRegistry;\n next: () => Promise<void>;\n }) {\n const { context, strategies, registry, next } = opts;\n\n // The first strategy's failure is the primary one - kept so the 401 carries WHY, instead of only which strategies were tried.\n let primaryFailure: unknown;\n\n for (const strategyName of strategies) {\n try {\n const strategy = registry.resolveStrategy({ name: strategyName });\n const user = await strategy.authenticate(context);\n\n // A verified credential is not yet a user: a token signed by the same key for another purpose verifies too. Both\n // modes need an id, so a strategy that answers without one has not authenticated this request.\n if (!user?.userId) {\n throw getError({ error: AuthenticationErrors.USER_UNRESOLVED });\n }\n\n this.setCurrentUser({ context, user });\n break;\n } catch (error) {\n primaryFailure ??= error;\n this.logger\n .for(this.executeAnyMode.name)\n .debug('Strategy %s failed, trying next... | Error: %s', strategyName, error);\n }\n }\n\n const currentUser = context.get(Authentication.CURRENT_USER);\n\n if (!currentUser) {\n throw getError({\n error: AuthenticationErrors.FAILED,\n message: `Authentication failed. Tried strategies: ${strategies.join(', ')}`,\n logLevel: 'warn',\n cause: primaryFailure,\n });\n }\n\n await next();\n }\n\n private async executeAllMode(opts: {\n context: TContext;\n strategies: string[];\n registry: AuthenticationStrategyRegistry;\n next: () => Promise<void>;\n }) {\n const { context, strategies, registry, next } = opts;\n\n // Use the first strategy's user as the identity source - all must succeed but first wins for identity\n let authUser: IAuthUser | null = null;\n\n for (const strategyName of strategies) {\n const strategy = registry.resolveStrategy({ name: strategyName });\n const user = await strategy.authenticate(context);\n\n authUser ??= user;\n }\n\n if (authUser?.userId) {\n this.setCurrentUser({ context, user: authUser });\n } else {\n this.logger\n .for(this.executeAllMode.name)\n .error(\n 'Failed to identify authenticated user | user: %j | userId: %s',\n authUser,\n authUser?.userId,\n );\n throw getError({ error: AuthenticationErrors.USER_UNRESOLVED });\n }\n\n return next();\n }\n\n private setCurrentUser(opts: { context: TContext; user: IAuthUser }) {\n const { context, user } = opts;\n context.set(Authentication.CURRENT_USER, user);\n\n if (user?.userId) {\n context.set(Authentication.AUDIT_USER_ID, user.userId);\n }\n }\n}\n"]}
|
|
@@ -62,6 +62,13 @@ export declare class ControllerFactory extends BaseHelper {
|
|
|
62
62
|
context: import("../index.js").TRouteContext<RouteEnv>;
|
|
63
63
|
}): Promise<import("../index.js").TJsonResponse<unknown, 200>>;
|
|
64
64
|
repository: AbstractRepository<TDataObject, TPersistObject, import("../../repositories/index.js").IExtraOptions>;
|
|
65
|
+
assertRequestFilter(opts: {
|
|
66
|
+
filter?: {
|
|
67
|
+
where?: unknown;
|
|
68
|
+
order?: unknown;
|
|
69
|
+
include?: unknown;
|
|
70
|
+
};
|
|
71
|
+
}): void;
|
|
65
72
|
bulkWhereError(opts: {
|
|
66
73
|
context: import("../index.js").TRouteContext<RouteEnv>;
|
|
67
74
|
where?: object;
|
|
@@ -22,6 +22,17 @@ export declare abstract class AbstractCrudController<TEntity extends AbstractEnt
|
|
|
22
22
|
repository: AbstractRepository<TDataObject, TPersistObject, AnyType>;
|
|
23
23
|
definitions: AnyType;
|
|
24
24
|
});
|
|
25
|
+
/**
|
|
26
|
+
* Refuses (400) a filter the client sent when it names a field the model hides (`where`, `order`, an include scope).
|
|
27
|
+
* The repository answers it; a stand-in that does not extend `AbstractRepository` has no hidden fields to hold the filter to.
|
|
28
|
+
*/
|
|
29
|
+
assertRequestFilter(opts: {
|
|
30
|
+
filter?: {
|
|
31
|
+
where?: unknown;
|
|
32
|
+
order?: unknown;
|
|
33
|
+
include?: unknown;
|
|
34
|
+
};
|
|
35
|
+
}): void;
|
|
25
36
|
/** 400 when a bulk operation is missing its `where` filter; undefined when it is present. */
|
|
26
37
|
bulkWhereError(opts: {
|
|
27
38
|
context: TRouteContext<RouteEnv>;
|
|
@@ -7,6 +7,13 @@ export class AbstractCrudController extends BaseRestController {
|
|
|
7
7
|
this.repository = opts.repository;
|
|
8
8
|
this.definitions = opts.definitions;
|
|
9
9
|
}
|
|
10
|
+
/**
|
|
11
|
+
* Refuses (400) a filter the client sent when it names a field the model hides (`where`, `order`, an include scope).
|
|
12
|
+
* The repository answers it; a stand-in that does not extend `AbstractRepository` has no hidden fields to hold the filter to.
|
|
13
|
+
*/
|
|
14
|
+
assertRequestFilter(opts) {
|
|
15
|
+
this.repository.assertRequestFilter?.(opts);
|
|
16
|
+
}
|
|
10
17
|
/** 400 when a bulk operation is missing its `where` filter; undefined when it is present. */
|
|
11
18
|
bulkWhereError(opts) {
|
|
12
19
|
const { context, where } = opts;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../../../src/base/controllers/factory/crud/abstract.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAGrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAMrD,yRAAyR;AACzR,MAAM,OAAgB,sBAQpB,SAAQ,kBAAwE;IAGhF,YAAY,IAMX;QACC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;QACvE,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;QAClC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC;IACtC,CAAC;IAED,6FAA6F;IAC7F,cAAc,CAAC,IAA0D;QACvE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QAEhC,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC9C,OAAO,OAAO,CAAC,IAAI,CACjB,EAAE,OAAO,EAAE,8CAA8C,EAAE,EAC3D,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU,CACjC,CAAC;QACJ,CAAC;QAED,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,2GAA2G;IAC3G,gBAAgB,CAA2B,IAM1C;QACC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,GAAG,IAAI,CAAC;QAC9C,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,GAAG,YAAY,IAAI,EAAE,CAAC;QAEnD,IAAI,SAAS,KAAK,SAAS,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YACtD,OAAO;gBACL,KAAK,EAAE,OAAO,CAAC,IAAI,CACjB,EAAE,OAAO,EAAE,6DAA6D,EAAE,EAC1E,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU,CACjC;aACF,CAAC;QACJ,CAAC;QAED,MAAM,KAAK,GAAG,SAAS,IAAI,QAAQ,CAAC;QAEpC,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC9C,OAAO;gBACL,KAAK,EAAE,OAAO,CAAC,IAAI,CACjB,EAAE,OAAO,EAAE,8CAA8C,EAAE,EAC3D,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU,CACjC;aACF,CAAC;QACJ,CAAC;QAED,OAAO,EAAE,KAAK,EAAE,CAAC;IACnB,CAAC;CACF","sourcesContent":["import type { AbstractEntity } from '@/base/models/base';\nimport type { AbstractRepository } from '@/base/repositories';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport type { AnyType } from '@venizia/ignis-helpers/common';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { Env, Schema } from 'hono';\nimport type { TEntityDataObject, TEntityPersistObject, TRouteContext } from '../../common';\nimport { BaseRestController } from '../../rest/base';\n\ntype TBulkWhereResolution<WhereType> =\n | { where: WhereType; error?: undefined }\n | { where?: undefined; error: Response };\n\n/** Base tier of a generated CRUD controller - the repository handle; the response helpers (`respond`, `setListHeaders`) live on BaseRestController so hand-written controllers share them. Read and write verbs are layered on by ReadableCrudController / PersistableCrudController. */\nexport abstract class AbstractCrudController<\n TEntity extends AbstractEntity<TAnyObjectSchema> = AbstractEntity<TAnyObjectSchema>,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TEntityDataObject<TEntity>,\n TPersistObject extends object = TEntityPersistObject<TEntity>,\n> extends BaseRestController<RouteEnv, RouteSchema, BasePath, ConfigurableOptions> {\n repository: AbstractRepository<TDataObject, TPersistObject>;\n\n constructor(opts: {\n scope: string;\n path: string;\n isStrict?: boolean;\n repository: AbstractRepository<TDataObject, TPersistObject, AnyType>;\n definitions: AnyType;\n }) {\n super({ scope: opts.scope, path: opts.path, isStrict: opts.isStrict });\n this.repository = opts.repository;\n this.definitions = opts.definitions;\n }\n\n /** 400 when a bulk operation is missing its `where` filter; undefined when it is present. */\n bulkWhereError(opts: { context: TRouteContext<RouteEnv>; where?: object }) {\n const { context, where } = opts;\n\n if (!where || Object.keys(where).length === 0) {\n return context.json(\n { message: 'where filter is required for bulk operations' },\n HTTP.ResultCodes.RS_4.BadRequest,\n );\n }\n\n return undefined;\n }\n\n /** Bulk `where` from the query or the JSON body (long id lists outgrow a URL). Both, or none, is a 400. */\n resolveBulkWhere<WhereType extends object>(opts: {\n context: TRouteContext<RouteEnv>;\n where?: {\n fromQuery?: WhereType;\n fromBody?: WhereType;\n };\n }): TBulkWhereResolution<WhereType> {\n const { context, where: whereSources } = opts;\n const { fromQuery, fromBody } = whereSources ?? {};\n\n if (fromQuery !== undefined && fromBody !== undefined) {\n return {\n error: context.json(\n { message: 'where given in both the query and the body - send it in one' },\n HTTP.ResultCodes.RS_4.BadRequest,\n ),\n };\n }\n\n const where = fromQuery ?? fromBody;\n\n if (!where || Object.keys(where).length === 0) {\n return {\n error: context.json(\n { message: 'where filter is required for bulk operations' },\n HTTP.ResultCodes.RS_4.BadRequest,\n ),\n };\n }\n\n return { where };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../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SAAS,EAAE,CAAC;YACtD,OAAO;gBACL,KAAK,EAAE,OAAO,CAAC,IAAI,CACjB,EAAE,OAAO,EAAE,6DAA6D,EAAE,EAC1E,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU,CACjC;aACF,CAAC;QACJ,CAAC;QAED,MAAM,KAAK,GAAG,SAAS,IAAI,QAAQ,CAAC;QAEpC,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC9C,OAAO;gBACL,KAAK,EAAE,OAAO,CAAC,IAAI,CACjB,EAAE,OAAO,EAAE,8CAA8C,EAAE,EAC3D,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU,CACjC;aACF,CAAC;QACJ,CAAC;QAED,OAAO,EAAE,KAAK,EAAE,CAAC;IACnB,CAAC;CACF","sourcesContent":["import type { AbstractEntity } from '@/base/models/base';\nimport type { AbstractRepository } from '@/base/repositories';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport type { AnyType } from '@venizia/ignis-helpers/common';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { Env, Schema } from 'hono';\nimport type { TEntityDataObject, TEntityPersistObject, TRouteContext } from '../../common';\nimport { BaseRestController } from '../../rest/base';\n\ntype TBulkWhereResolution<WhereType> =\n | { where: WhereType; error?: undefined }\n | { where?: undefined; error: Response };\n\n/** Base tier of a generated CRUD controller - the repository handle; the response helpers (`respond`, `setListHeaders`) live on BaseRestController so hand-written controllers share them. Read and write verbs are layered on by ReadableCrudController / PersistableCrudController. */\nexport abstract class AbstractCrudController<\n TEntity extends AbstractEntity<TAnyObjectSchema> = AbstractEntity<TAnyObjectSchema>,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TEntityDataObject<TEntity>,\n TPersistObject extends object = TEntityPersistObject<TEntity>,\n> extends BaseRestController<RouteEnv, RouteSchema, BasePath, ConfigurableOptions> {\n repository: AbstractRepository<TDataObject, TPersistObject>;\n\n constructor(opts: {\n scope: string;\n path: string;\n isStrict?: boolean;\n repository: AbstractRepository<TDataObject, TPersistObject, AnyType>;\n definitions: AnyType;\n }) {\n super({ scope: opts.scope, path: opts.path, isStrict: opts.isStrict });\n this.repository = opts.repository;\n this.definitions = opts.definitions;\n }\n\n /**\n * Refuses (400) a filter the client sent when it names a field the model hides (`where`, `order`, an include scope).\n * The repository answers it; a stand-in that does not extend `AbstractRepository` has no hidden fields to hold the filter to.\n */\n assertRequestFilter(opts: {\n filter?: { where?: unknown; order?: unknown; include?: unknown };\n }): void {\n (\n this.repository as Partial<Pick<AbstractRepository<object>, 'assertRequestFilter'>>\n ).assertRequestFilter?.(opts);\n }\n\n /** 400 when a bulk operation is missing its `where` filter; undefined when it is present. */\n bulkWhereError(opts: { context: TRouteContext<RouteEnv>; where?: object }) {\n const { context, where } = opts;\n\n if (!where || Object.keys(where).length === 0) {\n return context.json(\n { message: 'where filter is required for bulk operations' },\n HTTP.ResultCodes.RS_4.BadRequest,\n );\n }\n\n return undefined;\n }\n\n /** Bulk `where` from the query or the JSON body (long id lists outgrow a URL). Both, or none, is a 400. */\n resolveBulkWhere<WhereType extends object>(opts: {\n context: TRouteContext<RouteEnv>;\n where?: {\n fromQuery?: WhereType;\n fromBody?: WhereType;\n };\n }): TBulkWhereResolution<WhereType> {\n const { context, where: whereSources } = opts;\n const { fromQuery, fromBody } = whereSources ?? {};\n\n if (fromQuery !== undefined && fromBody !== undefined) {\n return {\n error: context.json(\n { message: 'where given in both the query and the body - send it in one' },\n HTTP.ResultCodes.RS_4.BadRequest,\n ),\n };\n }\n\n const where = fromQuery ?? fromBody;\n\n if (!where || Object.keys(where).length === 0) {\n return {\n error: context.json(\n { message: 'where filter is required for bulk operations' },\n HTTP.ResultCodes.RS_4.BadRequest,\n ),\n };\n }\n\n return { where };\n }\n}\n"]}
|
|
@@ -75,6 +75,7 @@ export class PersistableCrudController extends ReadableCrudController {
|
|
|
75
75
|
return resolved.error;
|
|
76
76
|
}
|
|
77
77
|
const { where } = resolved;
|
|
78
|
+
this.assertRequestFilter({ filter: { where } });
|
|
78
79
|
const rs = await this.measure({
|
|
79
80
|
scope: 'updateBy',
|
|
80
81
|
args: { where, data },
|
|
@@ -130,6 +131,7 @@ export class PersistableCrudController extends ReadableCrudController {
|
|
|
130
131
|
return resolved.error;
|
|
131
132
|
}
|
|
132
133
|
const { where } = resolved;
|
|
134
|
+
this.assertRequestFilter({ filter: { where } });
|
|
133
135
|
const rs = await this.measure({
|
|
134
136
|
scope: 'deleteBy',
|
|
135
137
|
args: { where },
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"persistable.js","sourceRoot":"","sources":["../../../../../../src/base/controllers/factory/crud/persistable.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,MAAM,kCAAkC,CAAC;AAGjE,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAE/C,mGAAmG;AACnG,MAAM,OAAgB,yBAQpB,SAAQ,sBAQT;IACC,aAAa;IACb,KAAK,CAAC,MAAM,CAAC,IAA0C;QACrD,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QACzB,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,CAAiB,MAAM,CAAC,CAAC;QAEvD,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC;YAC5B,KAAK,EAAE,QAAQ;YACf,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,KAAK,IAAI,EAAE;gBACf,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC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AC,EAAE,CAAC,CAAC;IACpD,CAAC;CACF","sourcesContent":["import type { IdType } from '@/base/models';\nimport type { AbstractEntity } from '@/base/models/base';\nimport { RequestErrors } from '@/base/middlewares/common/errors';\nimport type { TWhere } from '@venizia/ignis-filter';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { Env, Schema } from 'hono';\nimport type { TEntityDataObject, TEntityPersistObject, TRouteContext } from '../../common';\nimport { ReadableCrudController } from './readable';\nimport { ResponseFormats } from '../../common';\n\n/** Write tier: create / updateById / updateBy / deleteById / deleteBy. Inherits the read verbs. */\nexport abstract class PersistableCrudController<\n TEntity extends AbstractEntity<TAnyObjectSchema> = AbstractEntity<TAnyObjectSchema>,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TEntityDataObject<TEntity>,\n TPersistObject extends object = TEntityPersistObject<TEntity>,\n> extends ReadableCrudController<\n TEntity,\n RouteEnv,\n RouteSchema,\n BasePath,\n ConfigurableOptions,\n TDataObject,\n TPersistObject\n> {\n /** POST / */\n async create(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const data = context.req.valid<TPersistObject>('json');\n\n const rs = await this.measure({\n scope: 'create',\n args: data,\n task: async () => {\n const payload = await this.repository.create({ data });\n\n return this.respond<TDataObject>({\n context,\n format: ResponseFormats.OBJECT,\n payload,\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Created);\n }\n\n /**\n * 400 when the validated body leaves no field to write - `{}`, or only keys the body schema drops.\n * The repository would otherwise fail with a 500.\n */\n assertNonEmptyUpdate(opts: { scope: string; data: object }): void {\n const { scope, data } = opts;\n\n if (Object.keys(data).length === 0) {\n throw getError({\n error: RequestErrors.NOTHING_TO_UPDATE,\n message: `[${scope}] Nothing to update | The body has no field this route writes`,\n logLevel: 'warn',\n });\n }\n }\n\n /** PATCH /:id */\n async updateById(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { id } = context.req.valid<{ id: IdType }>('param');\n const data = context.req.valid<Partial<TPersistObject>>('json');\n this.assertNonEmptyUpdate({ scope: 'updateById', data });\n\n const rs = await this.measure({\n scope: 'updateById',\n args: { id, data },\n task: async () => {\n const payload = await this.repository.updateById({ id, data });\n\n return this.respond<TDataObject>({\n context,\n format: ResponseFormats.OBJECT,\n payload,\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** PATCH / */\n async updateBy(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { where: queryWhere } = context.req.valid<{ where?: TWhere<TDataObject> }>('query');\n const { where: bodyWhere } = context.req.valid<{ where?: TWhere<TDataObject> }>('json');\n // A COPY: `where` selects rows and is never written, and hono hands the same validated object to\n // an override that calls this through `super`.\n const data: Partial<TPersistObject> = { ...context.req.valid<Partial<TPersistObject>>('json') };\n Reflect.deleteProperty(data, 'where');\n this.assertNonEmptyUpdate({ scope: 'updateBy', data });\n\n const resolved = this.resolveBulkWhere({\n context,\n where: { fromQuery: queryWhere, fromBody: bodyWhere },\n });\n\n if (resolved.error !== undefined) {\n return resolved.error;\n }\n\n const { where } = resolved;\n\n const rs = await this.measure({\n scope: 'updateBy',\n args: { where, data },\n task: async () => {\n const payload = await this.repository.updateBy({ where, data });\n\n return this.respond<Array<TDataObject>>({\n context,\n format: ResponseFormats.ARRAY,\n payload,\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** DELETE /:id */\n async deleteById(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { id } = context.req.valid<{ id: IdType }>('param');\n\n const rs = await this.measure({\n scope: 'deleteById',\n args: { id },\n task: async () => {\n const payload = await this.repository.deleteById({ id });\n\n return this.respond<TDataObject>({\n context,\n format: ResponseFormats.OBJECT,\n payload,\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** DELETE / */\n async deleteBy(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { where: queryWhere } = context.req.valid<{ where?: TWhere<TDataObject> }>('query');\n // Read, never validated: a declared body schema would gate the media type and answer 400 to a\n // client that sends a content-type and no body. A body that is not JSON is simply not a `where`.\n let body;\n\n try {\n const result = await context.req.json<{ where?: TWhere<TDataObject> }>();\n body = result;\n // eslint-disable-next-line venizia/no-silent-catch -- a body that is not JSON is not a `where`; the bulk delete then relies on the query alone and nothing else is lost\n } catch {\n body = undefined;\n }\n\n const resolved = this.resolveBulkWhere({\n context,\n where: { fromQuery: queryWhere, fromBody: body?.where },\n });\n\n if (resolved.error !== undefined) {\n return resolved.error;\n }\n\n const { where } = resolved;\n\n const rs = await this.measure({\n scope: 'deleteBy',\n args: { where },\n task: async () => {\n const payload = await this.repository.deleteBy({ where });\n\n return this.respond<Array<TDataObject>>({\n context,\n format: ResponseFormats.ARRAY,\n payload,\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"persistable.js","sourceRoot":"","sources":["../../../../../../src/base/controllers/factory/crud/persistable.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,MAAM,kCAAkC,CAAC;AAGjE,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAE/C,mGAAmG;AACnG,MAAM,OAAgB,yBAQpB,SAAQ,sBAQT;IACC,aAAa;IACb,KAAK,CAAC,MAAM,CAAC,IAA0C;QACrD,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QACzB,MAAM,IAAI,GAAG,O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AAO,CAAC;YAC5B,KAAK,EAAE,UAAU;YACjB,IAAI,EAAE,EAAE,KAAK,EAAE;YACf,IAAI,EAAE,KAAK,IAAI,EAAE;gBACf,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;gBAE1D,OAAO,IAAI,CAAC,OAAO,CAAqB;oBACtC,OAAO;oBACP,MAAM,EAAE,eAAe,CAAC,KAAK;oBAC7B,OAAO;iBACR,CAAC,CAAC;YACL,CAAC;SACF,CAAC,CAAC;QAEH,OAAO,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACpD,CAAC;CACF","sourcesContent":["import type { IdType } from '@/base/models';\nimport type { AbstractEntity } from '@/base/models/base';\nimport { RequestErrors } from '@/base/middlewares/common/errors';\nimport type { TWhere } from '@venizia/ignis-filter';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { Env, Schema } from 'hono';\nimport type { TEntityDataObject, TEntityPersistObject, TRouteContext } from '../../common';\nimport { ReadableCrudController } from './readable';\nimport { ResponseFormats } from '../../common';\n\n/** Write tier: create / updateById / updateBy / deleteById / deleteBy. Inherits the read verbs. */\nexport abstract class PersistableCrudController<\n TEntity extends AbstractEntity<TAnyObjectSchema> = AbstractEntity<TAnyObjectSchema>,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TEntityDataObject<TEntity>,\n TPersistObject extends object = TEntityPersistObject<TEntity>,\n> extends ReadableCrudController<\n TEntity,\n RouteEnv,\n RouteSchema,\n BasePath,\n ConfigurableOptions,\n TDataObject,\n TPersistObject\n> {\n /** POST / */\n async create(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const data = context.req.valid<TPersistObject>('json');\n\n const rs = await this.measure({\n scope: 'create',\n args: data,\n task: async () => {\n const payload = await this.repository.create({ data });\n\n return this.respond<TDataObject>({\n context,\n format: ResponseFormats.OBJECT,\n payload,\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Created);\n }\n\n /**\n * 400 when the validated body leaves no field to write - `{}`, or only keys the body schema drops.\n * The repository would otherwise fail with a 500.\n */\n assertNonEmptyUpdate(opts: { scope: string; data: object }): void {\n const { scope, data } = opts;\n\n if (Object.keys(data).length === 0) {\n throw getError({\n error: RequestErrors.NOTHING_TO_UPDATE,\n message: `[${scope}] Nothing to update | The body has no field this route writes`,\n logLevel: 'warn',\n });\n }\n }\n\n /** PATCH /:id */\n async updateById(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { id } = context.req.valid<{ id: IdType }>('param');\n const data = context.req.valid<Partial<TPersistObject>>('json');\n this.assertNonEmptyUpdate({ scope: 'updateById', data });\n\n const rs = await this.measure({\n scope: 'updateById',\n args: { id, data },\n task: async () => {\n const payload = await this.repository.updateById({ id, data });\n\n return this.respond<TDataObject>({\n context,\n format: ResponseFormats.OBJECT,\n payload,\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** PATCH / */\n async updateBy(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { where: queryWhere } = context.req.valid<{ where?: TWhere<TDataObject> }>('query');\n const { where: bodyWhere } = context.req.valid<{ where?: TWhere<TDataObject> }>('json');\n // A COPY: `where` selects rows and is never written, and hono hands the same validated object to\n // an override that calls this through `super`.\n const data: Partial<TPersistObject> = { ...context.req.valid<Partial<TPersistObject>>('json') };\n Reflect.deleteProperty(data, 'where');\n this.assertNonEmptyUpdate({ scope: 'updateBy', data });\n\n const resolved = this.resolveBulkWhere({\n context,\n where: { fromQuery: queryWhere, fromBody: bodyWhere },\n });\n\n if (resolved.error !== undefined) {\n return resolved.error;\n }\n\n const { where } = resolved;\n\n this.assertRequestFilter({ filter: { where } });\n\n const rs = await this.measure({\n scope: 'updateBy',\n args: { where, data },\n task: async () => {\n const payload = await this.repository.updateBy({ where, data });\n\n return this.respond<Array<TDataObject>>({\n context,\n format: ResponseFormats.ARRAY,\n payload,\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** DELETE /:id */\n async deleteById(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { id } = context.req.valid<{ id: IdType }>('param');\n\n const rs = await this.measure({\n scope: 'deleteById',\n args: { id },\n task: async () => {\n const payload = await this.repository.deleteById({ id });\n\n return this.respond<TDataObject>({\n context,\n format: ResponseFormats.OBJECT,\n payload,\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** DELETE / */\n async deleteBy(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { where: queryWhere } = context.req.valid<{ where?: TWhere<TDataObject> }>('query');\n // Read, never validated: a declared body schema would gate the media type and answer 400 to a\n // client that sends a content-type and no body. A body that is not JSON is simply not a `where`.\n let body;\n\n try {\n const result = await context.req.json<{ where?: TWhere<TDataObject> }>();\n body = result;\n // eslint-disable-next-line venizia/no-silent-catch -- a body that is not JSON is not a `where`; the bulk delete then relies on the query alone and nothing else is lost\n } catch {\n body = undefined;\n }\n\n const resolved = this.resolveBulkWhere({\n context,\n where: { fromQuery: queryWhere, fromBody: body?.where },\n });\n\n if (resolved.error !== undefined) {\n return resolved.error;\n }\n\n const { where } = resolved;\n\n this.assertRequestFilter({ filter: { where } });\n\n const rs = await this.measure({\n scope: 'deleteBy',\n args: { where },\n task: async () => {\n const payload = await this.repository.deleteBy({ where });\n\n return this.respond<Array<TDataObject>>({\n context,\n format: ResponseFormats.ARRAY,\n payload,\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n}\n"]}
|
|
@@ -26,6 +26,8 @@ export class ReadableCrudController extends AbstractCrudController {
|
|
|
26
26
|
async count(opts) {
|
|
27
27
|
const { context } = opts;
|
|
28
28
|
const { where } = context.req.valid('query');
|
|
29
|
+
// What the client sent, before the base where joins it: a hidden field cannot be asked about.
|
|
30
|
+
this.assertRequestFilter({ filter: { where } });
|
|
29
31
|
const baseWhere = await this.getBaseWhere({ context });
|
|
30
32
|
const scopedWhere = baseWhere ? withBaseWhere({ baseWhere, where }) : where;
|
|
31
33
|
const rs = await this.measure({
|
|
@@ -39,6 +41,7 @@ export class ReadableCrudController extends AbstractCrudController {
|
|
|
39
41
|
async find(opts) {
|
|
40
42
|
const { context } = opts;
|
|
41
43
|
const { filter = {} } = context.req.valid('query');
|
|
44
|
+
this.assertRequestFilter({ filter });
|
|
42
45
|
const baseWhere = await this.getBaseWhere({ context });
|
|
43
46
|
const scopedFilter = baseWhere
|
|
44
47
|
? { ...filter, where: withBaseWhere({ baseWhere, where: filter.where }) }
|
|
@@ -66,6 +69,7 @@ export class ReadableCrudController extends AbstractCrudController {
|
|
|
66
69
|
const { context } = opts;
|
|
67
70
|
const { id } = context.req.valid('param');
|
|
68
71
|
const { filter } = context.req.valid('query');
|
|
72
|
+
this.assertRequestFilter({ filter });
|
|
69
73
|
const baseWhere = await this.getBaseWhere({ context });
|
|
70
74
|
// `repository.findById` takes no where, so a scoped read goes through `findOne` - the same
|
|
71
75
|
// substrate every family's findById delegates to - and answers null on an out-of-scope id.
|
|
@@ -93,6 +97,7 @@ export class ReadableCrudController extends AbstractCrudController {
|
|
|
93
97
|
async findOne(opts) {
|
|
94
98
|
const { context } = opts;
|
|
95
99
|
const { filter = {} } = context.req.valid('query');
|
|
100
|
+
this.assertRequestFilter({ filter });
|
|
96
101
|
const baseWhere = await this.getBaseWhere({ context });
|
|
97
102
|
const scopedFilter = baseWhere
|
|
98
103
|
? { ...filter, where: withBaseWhere({ baseWhere, where: filter.where }) }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readable.js","sourceRoot":"","s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c;oBAC/B,OAAO;oBACP,MAAM,EAAE,eAAe,CAAC,MAAM;oBAC9B,OAAO,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE;iBACjD,CAAC,CAAC;YACL,CAAC;SACF,CAAC,CAAC;QAEH,OAAO,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACpD,CAAC;CACF","sourcesContent":["import type { AbstractEntity, IdType } from '@/base/models';\nimport type { TFilter, TWhere } from '@venizia/ignis-filter';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { Env, Schema } from 'hono';\nimport type { TEntityDataObject, TEntityPersistObject, TRouteContext } from '../../common';\nimport { AbstractCrudController } from './abstract';\nimport { ResponseFormats } from '../../common';\n\n/** The one combination point of a base where and a request where; without a request side there is no `and` wrapper. */\nconst withBaseWhere = <TDataObject extends object>(opts: {\n baseWhere: TWhere<TDataObject>;\n where?: TWhere<TDataObject>;\n}): TWhere<TDataObject> => {\n const { baseWhere, where } = opts;\n\n if (!where) {\n return baseWhere;\n }\n\n // `Pick` resolves the one key: a literal cannot be checked against `TWhere` over an unresolved type parameter.\n const scoped: Pick<TWhere<TDataObject>, 'and'> = { and: [baseWhere, where] };\n\n return scoped;\n};\n\n/** `id` is the primary key every entity family reads by; built at the default `TWhere` for the same unresolved-parameter reason. */\nconst whereById = <TDataObject extends object>(opts: { id: IdType }): TWhere<TDataObject> => {\n const where: TWhere = { id: opts.id };\n\n return where;\n};\n\n/** Read tier: count / find / findById / findOne. Read-only controllers can extend this directly. */\nexport abstract class ReadableCrudController<\n TEntity extends AbstractEntity<TAnyObjectSchema> = AbstractEntity<TAnyObjectSchema>,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TEntityDataObject<TEntity>,\n TPersistObject extends object = TEntityPersistObject<TEntity>,\n> extends AbstractCrudController<\n TEntity,\n RouteEnv,\n RouteSchema,\n BasePath,\n ConfigurableOptions,\n TDataObject,\n TPersistObject\n> {\n /** Narrows EVERY read of this controller - override it to scope rows to a tenant, an owner or a status. Public because a generated controller's declaration cannot carry a protected member (TS4094). */\n async getBaseWhere(_opts: {\n context: TRouteContext<RouteEnv>;\n }): Promise<TWhere<TDataObject> | undefined> {\n return undefined;\n }\n\n /** GET /count */\n async count(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { where } = context.req.valid<{ where: TWhere<TDataObject> }>('query');\n const baseWhere = await this.getBaseWhere({ context });\n const scopedWhere = baseWhere ? withBaseWhere({ baseWhere, where }) : where;\n\n const rs = await this.measure({\n scope: 'count',\n args: { where: scopedWhere },\n task: () => this.repository.count({ where: scopedWhere }),\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** GET / - paginated list with a Content-Range header. */\n async find(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { filter = {} } = context.req.valid<{ filter?: TFilter<TDataObject> }>('query');\n const baseWhere = await this.getBaseWhere({ context });\n const scopedFilter = baseWhere\n ? { ...filter, where: withBaseWhere({ baseWhere, where: filter.where }) }\n : filter;\n\n const rs = await this.measure({\n scope: 'find',\n args: scopedFilter,\n task: async () => {\n const { data, range } = await this.repository.find({\n filter: scopedFilter,\n options: { shouldQueryRange: true },\n });\n\n return this.respond<Array<TDataObject>>({\n context,\n format: ResponseFormats.ARRAY,\n payload: { count: data.length, data },\n range,\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** GET /:id */\n async findById(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { id } = context.req.valid<{ id: IdType }>('param');\n const { filter } = context.req.valid<{ filter?: Omit<TFilter<TDataObject>, 'where'> }>('query');\n const baseWhere = await this.getBaseWhere({ context });\n\n // `repository.findById` takes no where, so a scoped read goes through `findOne` - the same\n // substrate every family's findById delegates to - and answers null on an out-of-scope id.\n const scopedWhere = baseWhere\n ? withBaseWhere({ baseWhere, where: whereById({ id }) })\n : undefined;\n\n const rs = await this.measure({\n scope: 'findById',\n args: filter,\n task: async () => {\n const lookup = scopedWhere\n ? this.repository.findOne({ filter: { ...filter, where: scopedWhere } })\n : this.repository.findById({ id, filter });\n const record = await lookup;\n\n return this.respond<TDataObject>({\n context,\n format: ResponseFormats.OBJECT,\n payload: { count: record ? 1 : 0, data: record },\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** GET /find-one */\n async findOne(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { filter = {} } = context.req.valid<{ filter?: TFilter<TDataObject> }>('query');\n const baseWhere = await this.getBaseWhere({ context });\n const scopedFilter = baseWhere\n ? { ...filter, where: withBaseWhere({ baseWhere, where: filter.where }) }\n : filter;\n\n const rs = await this.measure({\n scope: 'findOne',\n args: scopedFilter,\n task: async () => {\n const record = await this.repository.findOne({ filter: scopedFilter });\n\n return this.respond<TDataObject>({\n context,\n format: ResponseFormats.OBJECT,\n payload: { count: record ? 1 : 0, data: record },\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"readable.js","sourceRoot":"","sources":["../../../../../../src/base/controllers/factory/crud/readable.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAGrD,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAE/C,uHAAuH;AACvH,MAAM,aAAa,GAAG,CAA6B,IAGlD,EAAuB,EAAE;IACxB,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,IAAI,CAA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AAE,eAAe,CAAC,MAAM;oBAC9B,OAAO,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE;iBACjD,CAAC,CAAC;YACL,CAAC;SACF,CAAC,CAAC;QAEH,OAAO,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACpD,CAAC;CACF","sourcesContent":["import type { AbstractEntity, IdType } from '@/base/models';\nimport type { TFilter, TWhere } from '@venizia/ignis-filter';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { Env, Schema } from 'hono';\nimport type { TEntityDataObject, TEntityPersistObject, TRouteContext } from '../../common';\nimport { AbstractCrudController } from './abstract';\nimport { ResponseFormats } from '../../common';\n\n/** The one combination point of a base where and a request where; without a request side there is no `and` wrapper. */\nconst withBaseWhere = <TDataObject extends object>(opts: {\n baseWhere: TWhere<TDataObject>;\n where?: TWhere<TDataObject>;\n}): TWhere<TDataObject> => {\n const { baseWhere, where } = opts;\n\n if (!where) {\n return baseWhere;\n }\n\n // `Pick` resolves the one key: a literal cannot be checked against `TWhere` over an unresolved type parameter.\n const scoped: Pick<TWhere<TDataObject>, 'and'> = { and: [baseWhere, where] };\n\n return scoped;\n};\n\n/** `id` is the primary key every entity family reads by; built at the default `TWhere` for the same unresolved-parameter reason. */\nconst whereById = <TDataObject extends object>(opts: { id: IdType }): TWhere<TDataObject> => {\n const where: TWhere = { id: opts.id };\n\n return where;\n};\n\n/** Read tier: count / find / findById / findOne. Read-only controllers can extend this directly. */\nexport abstract class ReadableCrudController<\n TEntity extends AbstractEntity<TAnyObjectSchema> = AbstractEntity<TAnyObjectSchema>,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TEntityDataObject<TEntity>,\n TPersistObject extends object = TEntityPersistObject<TEntity>,\n> extends AbstractCrudController<\n TEntity,\n RouteEnv,\n RouteSchema,\n BasePath,\n ConfigurableOptions,\n TDataObject,\n TPersistObject\n> {\n /** Narrows EVERY read of this controller - override it to scope rows to a tenant, an owner or a status. Public because a generated controller's declaration cannot carry a protected member (TS4094). */\n async getBaseWhere(_opts: {\n context: TRouteContext<RouteEnv>;\n }): Promise<TWhere<TDataObject> | undefined> {\n return undefined;\n }\n\n /** GET /count */\n async count(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { where } = context.req.valid<{ where: TWhere<TDataObject> }>('query');\n\n // What the client sent, before the base where joins it: a hidden field cannot be asked about.\n this.assertRequestFilter({ filter: { where } });\n\n const baseWhere = await this.getBaseWhere({ context });\n const scopedWhere = baseWhere ? withBaseWhere({ baseWhere, where }) : where;\n\n const rs = await this.measure({\n scope: 'count',\n args: { where: scopedWhere },\n task: () => this.repository.count({ where: scopedWhere }),\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** GET / - paginated list with a Content-Range header. */\n async find(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { filter = {} } = context.req.valid<{ filter?: TFilter<TDataObject> }>('query');\n\n this.assertRequestFilter({ filter });\n\n const baseWhere = await this.getBaseWhere({ context });\n const scopedFilter = baseWhere\n ? { ...filter, where: withBaseWhere({ baseWhere, where: filter.where }) }\n : filter;\n\n const rs = await this.measure({\n scope: 'find',\n args: scopedFilter,\n task: async () => {\n const { data, range } = await this.repository.find({\n filter: scopedFilter,\n options: { shouldQueryRange: true },\n });\n\n return this.respond<Array<TDataObject>>({\n context,\n format: ResponseFormats.ARRAY,\n payload: { count: data.length, data },\n range,\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** GET /:id */\n async findById(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { id } = context.req.valid<{ id: IdType }>('param');\n const { filter } = context.req.valid<{ filter?: Omit<TFilter<TDataObject>, 'where'> }>('query');\n\n this.assertRequestFilter({ filter });\n\n const baseWhere = await this.getBaseWhere({ context });\n\n // `repository.findById` takes no where, so a scoped read goes through `findOne` - the same\n // substrate every family's findById delegates to - and answers null on an out-of-scope id.\n const scopedWhere = baseWhere\n ? withBaseWhere({ baseWhere, where: whereById({ id }) })\n : undefined;\n\n const rs = await this.measure({\n scope: 'findById',\n args: filter,\n task: async () => {\n const lookup = scopedWhere\n ? this.repository.findOne({ filter: { ...filter, where: scopedWhere } })\n : this.repository.findById({ id, filter });\n const record = await lookup;\n\n return this.respond<TDataObject>({\n context,\n format: ResponseFormats.OBJECT,\n payload: { count: record ? 1 : 0, data: record },\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** GET /find-one */\n async findOne(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { filter = {} } = context.req.valid<{ filter?: TFilter<TDataObject> }>('query');\n\n this.assertRequestFilter({ filter });\n\n const baseWhere = await this.getBaseWhere({ context });\n const scopedFilter = baseWhere\n ? { ...filter, where: withBaseWhere({ baseWhere, where: filter.where }) }\n : filter;\n\n const rs = await this.measure({\n scope: 'findOne',\n args: scopedFilter,\n task: async () => {\n const record = await this.repository.findOne({ filter: scopedFilter });\n\n return this.respond<TDataObject>({\n context,\n format: ResponseFormats.OBJECT,\n payload: { count: record ? 1 : 0, data: record },\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n}\n"]}
|