@venizia/ignis-kernel 0.4.8-8 → 0.4.8
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/artifact-index.d.ts +3 -3
- package/dist/esm/base/applications/artifact-index.js.map +1 -1
- package/dist/esm/base/applications/body-limit.js +1 -1
- package/dist/esm/base/applications/body-limit.js.map +1 -1
- package/dist/esm/base/applications/common/types/application.d.ts +2 -2
- package/dist/esm/base/applications/common/types/application.js.map +1 -1
- package/dist/esm/base/applications/common/types/middlewares.d.ts +2 -2
- package/dist/esm/base/applications/common/types/middlewares.js.map +1 -1
- package/dist/esm/base/applications/rest.js +6 -1
- package/dist/esm/base/applications/rest.js.map +1 -1
- package/dist/esm/base/auth/authenticate/common/types/jwt.d.ts +1 -1
- package/dist/esm/base/auth/authenticate/common/types/jwt.js.map +1 -1
- package/dist/esm/base/auth/authenticate/common/types/strategy.d.ts +2 -3
- package/dist/esm/base/auth/authenticate/common/types/strategy.js.map +1 -1
- package/dist/esm/base/auth/authenticate/strategies/strategy-registry.d.ts +1 -1
- package/dist/esm/base/auth/authenticate/strategies/strategy-registry.js +1 -1
- package/dist/esm/base/auth/authenticate/strategies/strategy-registry.js.map +1 -1
- package/dist/esm/base/auth/authorize/providers/request-domain.js +2 -1
- package/dist/esm/base/auth/authorize/providers/request-domain.js.map +1 -1
- package/dist/esm/base/controllers/common/types/route.d.ts +13 -4
- package/dist/esm/base/controllers/common/types/route.js.map +1 -1
- package/dist/esm/base/controllers/factory/controller.d.ts +3 -4
- package/dist/esm/base/controllers/factory/controller.js +0 -1
- package/dist/esm/base/controllers/factory/controller.js.map +1 -1
- package/dist/esm/base/controllers/factory/crud/abstract.d.ts +3 -4
- package/dist/esm/base/controllers/factory/crud/abstract.js.map +1 -1
- package/dist/esm/base/controllers/factory/definition.d.ts +21 -1
- package/dist/esm/base/controllers/factory/definition.js +45 -31
- package/dist/esm/base/controllers/factory/definition.js.map +1 -1
- package/dist/esm/base/controllers/factory/index.d.ts +1 -0
- package/dist/esm/base/controllers/factory/index.js +1 -0
- package/dist/esm/base/controllers/factory/index.js.map +1 -1
- package/dist/esm/base/controllers/factory/injection.d.ts +38 -0
- package/dist/esm/base/controllers/factory/injection.js +54 -0
- package/dist/esm/base/controllers/factory/injection.js.map +1 -0
- package/dist/esm/base/controllers/rest/abstract.js +1 -1
- package/dist/esm/base/controllers/rest/abstract.js.map +1 -1
- package/dist/esm/base/controllers/rest/base.d.ts +3 -3
- package/dist/esm/base/controllers/rest/base.js.map +1 -1
- package/dist/esm/base/datasources/abstract.d.ts +4 -92
- package/dist/esm/base/datasources/abstract.js +3 -217
- package/dist/esm/base/datasources/abstract.js.map +1 -1
- package/dist/esm/base/datasources/common/types.d.ts +2 -2
- package/dist/esm/base/datasources/common/types.js.map +1 -1
- package/dist/esm/base/datasources/index.d.ts +1 -0
- package/dist/esm/base/datasources/index.js +1 -0
- package/dist/esm/base/datasources/index.js.map +1 -1
- package/dist/esm/base/datasources/root.d.ts +107 -0
- package/dist/esm/base/datasources/root.js +237 -0
- package/dist/esm/base/datasources/root.js.map +1 -0
- package/dist/esm/base/events/event-bus.js.map +1 -1
- package/dist/esm/base/metadata/index.d.ts +1 -1
- package/dist/esm/base/metadata/index.js +1 -1
- package/dist/esm/base/metadata/injectors.d.ts +1 -1
- package/dist/esm/base/metadata/persistents/datasource.d.ts +21 -0
- package/dist/esm/base/metadata/persistents/datasource.js +46 -0
- package/dist/esm/base/metadata/persistents/datasource.js.map +1 -0
- package/dist/esm/base/metadata/persistents/index.d.ts +5 -0
- package/dist/esm/base/metadata/persistents/index.js +5 -0
- package/dist/esm/base/metadata/persistents/index.js.map +1 -0
- package/dist/esm/base/metadata/persistents/model.d.ts +18 -0
- package/dist/esm/base/metadata/persistents/model.js +64 -0
- package/dist/esm/base/metadata/persistents/model.js.map +1 -0
- package/dist/esm/base/metadata/persistents/repository/index.d.ts +19 -0
- package/dist/esm/base/metadata/persistents/repository/index.js +32 -0
- package/dist/esm/base/metadata/persistents/repository/index.js.map +1 -0
- package/dist/esm/base/metadata/persistents/repository/injection.d.ts +15 -0
- package/dist/esm/base/metadata/persistents/repository/injection.js +64 -0
- package/dist/esm/base/metadata/persistents/repository/injection.js.map +1 -0
- package/dist/esm/base/metadata/persistents/repository/resolve.d.ts +15 -0
- package/dist/esm/base/metadata/persistents/repository/resolve.js +76 -0
- package/dist/esm/base/metadata/persistents/repository/resolve.js.map +1 -0
- package/dist/esm/base/metadata/persistents/repository/validate.d.ts +15 -0
- package/dist/esm/base/metadata/persistents/repository/validate.js +50 -0
- package/dist/esm/base/metadata/persistents/repository/validate.js.map +1 -0
- package/dist/esm/base/models/common/utilities.d.ts +1 -1
- package/dist/esm/base/repositories/common/response-reader.d.ts +30 -0
- package/dist/esm/base/repositories/common/response-reader.js +53 -0
- package/dist/esm/base/repositories/common/response-reader.js.map +1 -1
- package/dist/esm/base/repositories/common/types/contracts.d.ts +2 -2
- package/dist/esm/base/repositories/common/types/contracts.js.map +1 -1
- package/dist/esm/base/repositories/common/types/options.d.ts +2 -2
- package/dist/esm/base/repositories/common/types/options.js.map +1 -1
- package/dist/esm/base/repositories/common/types/query.d.ts +6 -15
- package/dist/esm/base/repositories/common/types/query.js.map +1 -1
- package/dist/esm/base/repositories/core/abstract.d.ts +6 -6
- package/dist/esm/base/repositories/core/abstract.js.map +1 -1
- package/dist/esm/base/repositories/query-schemas/index.js +7 -0
- package/dist/esm/base/repositories/query-schemas/index.js.map +1 -1
- package/dist/esm/helpers/inversion/common/types/model.d.ts +1 -1
- package/dist/esm/helpers/inversion/common/types/model.js.map +1 -1
- package/dist/esm/helpers/inversion/mixins/artifact.mixin.d.ts +4 -3
- package/dist/esm/helpers/inversion/mixins/artifact.mixin.js +1 -0
- package/dist/esm/helpers/inversion/mixins/artifact.mixin.js.map +1 -1
- package/dist/esm/helpers/inversion/mixins/controllers/controller.d.ts +4 -3
- package/dist/esm/helpers/inversion/mixins/controllers/controller.js +1 -0
- package/dist/esm/helpers/inversion/mixins/controllers/controller.js.map +1 -1
- package/dist/esm/helpers/inversion/mixins/controllers/grpc.d.ts +4 -3
- package/dist/esm/helpers/inversion/mixins/controllers/grpc.js +1 -0
- package/dist/esm/helpers/inversion/mixins/controllers/grpc.js.map +1 -1
- package/dist/esm/helpers/inversion/mixins/controllers/rest.d.ts +4 -3
- package/dist/esm/helpers/inversion/mixins/controllers/rest.js +1 -0
- package/dist/esm/helpers/inversion/mixins/controllers/rest.js.map +1 -1
- package/dist/esm/helpers/inversion/mixins/datasource.mixin.d.ts +4 -3
- package/dist/esm/helpers/inversion/mixins/datasource.mixin.js +1 -0
- package/dist/esm/helpers/inversion/mixins/datasource.mixin.js.map +1 -1
- package/dist/esm/helpers/inversion/mixins/model.mixin.d.ts +4 -3
- package/dist/esm/helpers/inversion/mixins/model.mixin.js +1 -0
- package/dist/esm/helpers/inversion/mixins/model.mixin.js.map +1 -1
- package/dist/esm/helpers/inversion/mixins/repository.mixin.d.ts +9 -8
- package/dist/esm/helpers/inversion/mixins/repository.mixin.js +6 -6
- package/dist/esm/helpers/inversion/mixins/repository.mixin.js.map +1 -1
- package/dist/esm/helpers/inversion/registry.d.ts +26 -26
- package/dist/esm/helpers/inversion/registry.js.map +1 -1
- package/dist/esm/helpers/singleton-realm.js +5 -4
- package/dist/esm/helpers/singleton-realm.js.map +1 -1
- package/dist/esm/metadata.d.ts +1 -1
- package/dist/esm/metadata.js +1 -1
- package/dist/esm/repository.d.ts +1 -0
- package/dist/esm/repository.js +1 -0
- package/dist/esm/repository.js.map +1 -1
- package/dist/esm/utilities/index.d.ts +1 -0
- package/dist/esm/utilities/index.js +1 -0
- package/dist/esm/utilities/index.js.map +1 -1
- package/dist/esm/utilities/toggle.utility.d.ts +22 -0
- package/dist/esm/utilities/toggle.utility.js +16 -0
- package/dist/esm/utilities/toggle.utility.js.map +1 -0
- package/package.json +5 -5
- package/dist/esm/base/metadata/persistents.d.ts +0 -54
- package/dist/esm/base/metadata/persistents.js +0 -302
- package/dist/esm/base/metadata/persistents.js.map +0 -1
|
@@ -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 * 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 listed in `http`.\n */\nexport interface IJWKSHosts {\n /**\n * Exact hosts that may serve a JWKS over `http:`: a name (`identity-service`), an IPv4 address (`10.0.0.5`) or an\n * IPv6 address in brackets (`[fd00::1]`), each with an optional `:port` (`10.0.0.5:8080`, `[fd00::1]:8443`). An entry\n * without a port covers every port of that host; an entry with one covers that port only. Never a wildcard, range or\n * CIDR. An entry is valid only when `new URL('http://' + entry)` gives the same host back, so `2130706433` and\n * `[::ffff:10.0.0.5]` refuse the boot, as do a scheme, a path, credentials or an empty label.\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]:
|
|
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 listed in `http`.\n */\nexport interface IJWKSHosts {\n /**\n * Exact hosts that may serve a JWKS over `http:`: a name (`identity-service`), an IPv4 address (`10.0.0.5`) or an\n * IPv6 address in brackets (`[fd00::1]`), each with an optional `:port` (`10.0.0.5:8080`, `[fd00::1]:8443`). An entry\n * without a port covers every port of that host; an entry with one covers that port only. Never a wildcard, range or\n * CIDR. An entry is valid only when `new URL('http://' + entry)` gives the same host back, so `2130706433` and\n * `[::ffff:10.0.0.5]` refuse the boot, as do a scheme, a path, credentials or an empty label.\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]: unknown;\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"]}
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
import type { TContext } from '../../../../controllers/common/types/index.js';
|
|
2
2
|
import type { IdType } from '../../../../models/common/index.js';
|
|
3
|
-
import type { AnyObject } from '@venizia/ignis-helpers/common';
|
|
4
3
|
import type { Env, MiddlewareHandler } from 'hono';
|
|
5
4
|
import type { TChangePasswordRequest, TSignInRequest, TSignUpRequest } from '../../../models/requests/index.js';
|
|
6
5
|
import type { TAuthMode } from '../constants/index.js';
|
|
7
6
|
/** The authenticated identity a strategy returns and the request context stores. Carries at least `userId`. */
|
|
8
7
|
export interface IAuthUser {
|
|
9
8
|
userId: IdType;
|
|
10
|
-
[extra: string | symbol]:
|
|
9
|
+
[extra: string | symbol]: unknown;
|
|
11
10
|
}
|
|
12
11
|
/** A strategy that authenticates a request. `name` is the name it is registered under; `authenticate` returns the user or throws. */
|
|
13
12
|
export interface IAuthenticationStrategy<E extends Env = Env> {
|
|
@@ -21,7 +20,7 @@ export type TAuthenticateFn<RouteEnv extends Env = Env> = (opts: {
|
|
|
21
20
|
mode?: TAuthMode;
|
|
22
21
|
}) => MiddlewareHandler<RouteEnv>;
|
|
23
22
|
/** The service behind the auth controller routes. `getUserInformation` and `refreshToken` are optional. The type parameters set each route's request and response types. */
|
|
24
|
-
export interface IAuthService<E extends Env = Env, SIRQ extends TSignInRequest = TSignInRequest, SIRS =
|
|
23
|
+
export interface IAuthService<E extends Env = Env, SIRQ extends TSignInRequest = TSignInRequest, SIRS = Record<string, unknown>, SURQ extends TSignUpRequest = TSignUpRequest, SURS = Record<string, unknown>, CPRQ extends TChangePasswordRequest = TChangePasswordRequest, CPRS = Record<string, unknown>, UIRQ = Record<string, unknown>, UIRS = Record<string, unknown>, RTRS = Record<string, unknown>> {
|
|
25
24
|
signIn(context: TContext<E>, opts: SIRQ): Promise<SIRS>;
|
|
26
25
|
signUp(context: TContext<E>, opts: SURQ): Promise<SURS>;
|
|
27
26
|
changePassword(context: TContext<E>, opts: CPRQ): Promise<CPRS>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"strategy.js","sourceRoot":"","sources":["../../../../../../../src/base/auth/authenticate/common/types/strategy.ts"],"names":[],"mappings":"","sourcesContent":["import type { TContext } from '@/base/controllers/common/types';\nimport type { IdType } from '@/base/models/common';\nimport type {
|
|
1
|
+
{"version":3,"file":"strategy.js","sourceRoot":"","sources":["../../../../../../../src/base/auth/authenticate/common/types/strategy.ts"],"names":[],"mappings":"","sourcesContent":["import type { TContext } from '@/base/controllers/common/types';\nimport type { IdType } from '@/base/models/common';\nimport type { Env, MiddlewareHandler } from 'hono';\nimport type {\n TChangePasswordRequest,\n TSignInRequest,\n TSignUpRequest,\n} from '../../../models/requests';\nimport type { TAuthMode } from '../constants';\n\n/** The authenticated identity a strategy returns and the request context stores. Carries at least `userId`. */\nexport interface IAuthUser {\n userId: IdType;\n [extra: string | symbol]: unknown;\n}\n\n/** A strategy that authenticates a request. `name` is the name it is registered under; `authenticate` returns the user or throws. */\nexport interface IAuthenticationStrategy<E extends Env = Env> {\n name: string;\n authenticate(context: TContext<E, string>): Promise<IAuthUser>;\n}\n\n/** Builds the authentication middleware for the listed strategy names. */\nexport type TAuthenticateFn<RouteEnv extends Env = Env> = (opts: {\n strategies: string[];\n\n /** @default 'any' */\n mode?: TAuthMode;\n}) => MiddlewareHandler<RouteEnv>;\n\n/** The service behind the auth controller routes. `getUserInformation` and `refreshToken` are optional. The type parameters set each route's request and response types. */\nexport interface IAuthService<\n E extends Env = Env,\n // SignIn types\n SIRQ extends TSignInRequest = TSignInRequest,\n SIRS = Record<string, unknown>,\n // SignUp types\n SURQ extends TSignUpRequest = TSignUpRequest,\n SURS = Record<string, unknown>,\n // ChangePassword types\n CPRQ extends TChangePasswordRequest = TChangePasswordRequest,\n CPRS = Record<string, unknown>,\n // UserInformation types\n UIRQ = Record<string, unknown>,\n UIRS = Record<string, unknown>,\n // RefreshToken types\n RTRS = Record<string, unknown>,\n> {\n signIn(context: TContext<E>, opts: SIRQ): Promise<SIRS>;\n signUp(context: TContext<E>, opts: SURQ): Promise<SURS>;\n changePassword(context: TContext<E>, opts: CPRQ): Promise<CPRS>;\n getUserInformation?(context: TContext<E>, opts: UIRQ): Promise<UIRS>;\n refreshToken?(context: TContext<E>): Promise<RTRS>;\n}\n"]}
|
|
@@ -37,7 +37,7 @@ export declare class AuthenticationStrategyRegistry extends AbstractAuthRegistry
|
|
|
37
37
|
*
|
|
38
38
|
* The framework does NOT call this - it reports instead. A hard failure cannot be the default
|
|
39
39
|
* here: a route listing several strategies in ANY mode tolerates one that does not resolve, and
|
|
40
|
-
* `AuthControllerFactory.
|
|
40
|
+
* `AuthControllerFactory.build` hard-codes `'jwt'` on four of its routes, so an application that
|
|
41
41
|
* registers its JWT strategy under a different name works today and would stop booting.
|
|
42
42
|
*/
|
|
43
43
|
assertRegistered(opts: {
|
|
@@ -50,7 +50,7 @@ export class AuthenticationStrategyRegistry extends AbstractAuthRegistry {
|
|
|
50
50
|
*
|
|
51
51
|
* The framework does NOT call this - it reports instead. A hard failure cannot be the default
|
|
52
52
|
* here: a route listing several strategies in ANY mode tolerates one that does not resolve, and
|
|
53
|
-
* `AuthControllerFactory.
|
|
53
|
+
* `AuthControllerFactory.build` hard-codes `'jwt'` on four of its routes, so an application that
|
|
54
54
|
* registers its JWT strategy under a different name works today and would stop booting.
|
|
55
55
|
*/
|
|
56
56
|
assertRegistered(opts) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"strategy-registry.js","sourceRoot":"","sources":["../../../../../../src/base/auth/authenticate/strategies/strategy-registry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAElD,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAE3C,2JAA2J;AAC3J,MAAM,OAAO,8BAA+B,SAAQ,oBAA6C;aAC/E,uBAAkB,GAAG,kCAAkC,CAAC;IAExE;QACE,KAAK,CAAC,EAAE,KAAK,EAAE,8BAA8B,CAAC,IAAI,EAAE,CAAC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AAC,CAAC;QAEtD,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC9B,OAAO;QACT,CAAC;QAED,MAAM,QAAQ,CAAC;YACb,OAAO,EAAE,IAAI,KAAK,qDAAqD,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,kBAAkB,IAAI,CAAC,QAAQ,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,4FAA4F;SACvO,CAAC,CAAC;IACL,CAAC;IAED;;;;;;OAMG;IACH,kBAAkB,CAAC,IAAyC;QAC1D,MAAM,EAAE,KAAK,EAAE,KAAK,GAAG,OAAO,EAAE,GAAG,IAAI,CAAC;QAExC,MAAM,YAAY,GAAG,IAAI,CAAC,gBAAgB,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAEtD,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC9B,OAAO;QACT,CAAC;QAED,IAAI,CAAC,MAAM;aACR,GAAG,CAAC,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC;aACjC,KAAK,CACJ,uHAAuH,EACvH,KAAK,EACL,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,EACvB,IAAI,CAAC,QAAQ,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAC3B,CAAC;IACN,CAAC","sourcesContent":["import type { Container } from '@/helpers/inversion/container';\nimport { SingletonRealm } from '@/helpers/singleton-realm';\nimport type { TClass } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { AbstractAuthRegistry } from '../../base';\nimport type { IAuthenticationStrategy } from '../common';\nimport { Authentication } from '../common';\n\n/** Registry of authentication strategies by name. Use `getInstance()` for the shared one; register application strategies before controllers are bound. */\nexport class AuthenticationStrategyRegistry extends AbstractAuthRegistry<IAuthenticationStrategy> {\n static readonly SINGLETON_REAL_KEY = 'authentication-strategy-registry';\n\n constructor() {\n super({ scope: AuthenticationStrategyRegistry.name });\n }\n\n static getInstance() {\n return SingletonRealm.resolve({\n key: AuthenticationStrategyRegistry.SINGLETON_REAL_KEY,\n create: () => new AuthenticationStrategyRegistry(),\n });\n }\n\n protected getBindingPrefix(): string {\n return Authentication.AUTHENTICATION_STRATEGY;\n }\n\n register(opts: {\n container: Container;\n strategies: { strategy: TClass<IAuthenticationStrategy>; name: string }[];\n }) {\n const { container, strategies } = opts;\n\n for (const { strategy, name } of strategies) {\n this.registerDescriptor({ container, target: strategy, name });\n }\n\n return this;\n }\n\n resolveStrategy(opts: { name: string }): IAuthenticationStrategy {\n return this.resolveDescriptor(opts);\n }\n\n /**\n * The names on this list that no registered strategy answers to.\n *\n * An EMPTY list yields nothing - it is the framework's own encoding of\n * `authenticate: { skip: true }`, so treating it as a problem would flag every public route.\n *\n * Nothing is reported while the registry is empty. Route configs are built during\n * `registerControllers()`, after `preConfigure()` and `registerComponents()`, so a real\n * application has registered by then; an empty registry means this is running outside that\n * lifecycle - a unit test on a controller - where no name could resolve either way.\n */\n findUnregistered(opts: { names: string[] }): string[] {\n const { names } = opts;\n\n if (names.length === 0 || this.descriptors.size === 0) {\n return [];\n }\n\n return names.filter((name) => !this.has({ name }));\n }\n\n /**\n * Refuses to continue past an unregistered name. For an APPLICATION's own startup check.\n *\n * The framework does NOT call this - it reports instead. A hard failure cannot be the default\n * here: a route listing several strategies in ANY mode tolerates one that does not resolve, and\n * `AuthControllerFactory.
|
|
1
|
+
{"version":3,"file":"strategy-registry.js","sourceRoot":"","sources":["../../../../../../src/base/auth/authenticate/strategies/strategy-registry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAElD,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAE3C,2JAA2J;AAC3J,MAAM,OAAO,8BAA+B,SAAQ,oBAA6C;aAC/E,uBAAkB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EAAE,GAAG,IAAI,CAAC;QAExC,MAAM,YAAY,GAAG,IAAI,CAAC,gBAAgB,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAEtD,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC9B,OAAO;QACT,CAAC;QAED,MAAM,QAAQ,CAAC;YACb,OAAO,EAAE,IAAI,KAAK,qDAAqD,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,kBAAkB,IAAI,CAAC,QAAQ,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,4FAA4F;SACvO,CAAC,CAAC;IACL,CAAC;IAED;;;;;;OAMG;IACH,kBAAkB,CAAC,IAAyC;QAC1D,MAAM,EAAE,KAAK,EAAE,KAAK,GAAG,OAAO,EAAE,GAAG,IAAI,CAAC;QAExC,MAAM,YAAY,GAAG,IAAI,CAAC,gBAAgB,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAEtD,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC9B,OAAO;QACT,CAAC;QAED,IAAI,CAAC,MAAM;aACR,GAAG,CAAC,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC;aACjC,KAAK,CACJ,uHAAuH,EACvH,KAAK,EACL,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,EACvB,IAAI,CAAC,QAAQ,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAC3B,CAAC;IACN,CAAC","sourcesContent":["import type { Container } from '@/helpers/inversion/container';\nimport { SingletonRealm } from '@/helpers/singleton-realm';\nimport type { TClass } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { AbstractAuthRegistry } from '../../base';\nimport type { IAuthenticationStrategy } from '../common';\nimport { Authentication } from '../common';\n\n/** Registry of authentication strategies by name. Use `getInstance()` for the shared one; register application strategies before controllers are bound. */\nexport class AuthenticationStrategyRegistry extends AbstractAuthRegistry<IAuthenticationStrategy> {\n static readonly SINGLETON_REAL_KEY = 'authentication-strategy-registry';\n\n constructor() {\n super({ scope: AuthenticationStrategyRegistry.name });\n }\n\n static getInstance() {\n return SingletonRealm.resolve({\n key: AuthenticationStrategyRegistry.SINGLETON_REAL_KEY,\n create: () => new AuthenticationStrategyRegistry(),\n });\n }\n\n protected getBindingPrefix(): string {\n return Authentication.AUTHENTICATION_STRATEGY;\n }\n\n register(opts: {\n container: Container;\n strategies: { strategy: TClass<IAuthenticationStrategy>; name: string }[];\n }) {\n const { container, strategies } = opts;\n\n for (const { strategy, name } of strategies) {\n this.registerDescriptor({ container, target: strategy, name });\n }\n\n return this;\n }\n\n resolveStrategy(opts: { name: string }): IAuthenticationStrategy {\n return this.resolveDescriptor(opts);\n }\n\n /**\n * The names on this list that no registered strategy answers to.\n *\n * An EMPTY list yields nothing - it is the framework's own encoding of\n * `authenticate: { skip: true }`, so treating it as a problem would flag every public route.\n *\n * Nothing is reported while the registry is empty. Route configs are built during\n * `registerControllers()`, after `preConfigure()` and `registerComponents()`, so a real\n * application has registered by then; an empty registry means this is running outside that\n * lifecycle - a unit test on a controller - where no name could resolve either way.\n */\n findUnregistered(opts: { names: string[] }): string[] {\n const { names } = opts;\n\n if (names.length === 0 || this.descriptors.size === 0) {\n return [];\n }\n\n return names.filter((name) => !this.has({ name }));\n }\n\n /**\n * Refuses to continue past an unregistered name. For an APPLICATION's own startup check.\n *\n * The framework does NOT call this - it reports instead. A hard failure cannot be the default\n * here: a route listing several strategies in ANY mode tolerates one that does not resolve, and\n * `AuthControllerFactory.build` hard-codes `'jwt'` on four of its routes, so an application that\n * registers its JWT strategy under a different name works today and would stop booting.\n */\n assertRegistered(opts: { names: string[]; scope?: string }): void {\n const { names, scope = 'route' } = opts;\n\n const unregistered = this.findUnregistered({ names });\n\n if (unregistered.length === 0) {\n return;\n }\n\n throw getError({\n message: `[${scope}] Unknown authentication strategy | unregistered: ${unregistered.join(', ')} | registered: ${this.getNames().join(', ')} | register it with AuthenticationStrategyRegistry.register() before controllers are bound`,\n });\n }\n\n /**\n * Names an unregistered strategy at boot, at a level someone sees. Never throws.\n *\n * This is what replaces the guard the open `TAuthStrategy` gave up: `resolveStrategy` throws at\n * request time, the provider's ANY mode swallows it at DEBUG, and the route 401s with nothing to\n * explain why.\n */\n reportUnregistered(opts: { names: string[]; scope?: string }): void {\n const { names, scope = 'route' } = opts;\n\n const unregistered = this.findUnregistered({ names });\n\n if (unregistered.length === 0) {\n return;\n }\n\n this.logger\n .for(this.reportUnregistered.name)\n .error(\n '[%s] Unknown authentication strategy - requests relying on it cannot authenticate | unregistered: %s | registered: %s',\n scope,\n unregistered.join(', '),\n this.getNames().join(', '),\n );\n }\n}\n"]}
|
|
@@ -15,7 +15,8 @@ export class RequestDomainResolver {
|
|
|
15
15
|
return context.req.query(source.key) ?? null;
|
|
16
16
|
}
|
|
17
17
|
case AuthorizationDomainSources.CONTEXT: {
|
|
18
|
-
|
|
18
|
+
// A declarative key is a string read off the request, so it cannot satisfy `get`'s `keyof Variables` parameter.
|
|
19
|
+
const value = Reflect.apply(context.get, context, [source.key]);
|
|
19
20
|
return value == null ? null : String(value);
|
|
20
21
|
}
|
|
21
22
|
default: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-domain.js","sourceRoot":"","sources":["../../../../../../src/base/auth/authorize/providers/request-domain.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,yBAAyB,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AAO5F,kEAAkE;AAClE,MAAM,OAAO,qBAAqB;IAChC,yEAAyE;IACzE,MAAM,CAAC,eAAe,CAAC,IAGtB;QACC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAEjC,QAAQ,MAAM,CAAC,IAAI,EAAE,CAAC;YACpB,KAAK,0BAA0B,CAAC,KAAK,CAAC,CAAC,CAAC;gBACtC,OAAO,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC;YAC/C,CAAC;YACD,KAAK,0BAA0B,CAAC,MAAM,CAAC,CAAC,CAAC;gBACvC,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC;YAChD,CAAC;YACD,KAAK,0BAA0B,CAAC,KAAK,CAAC,CAAC,CAAC;gBACtC,OAAO,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC;YAC/C,CAAC;YACD,KAAK,0BAA0B,CAAC,OAAO,CAAC,CAAC,CAAC;gBACxC,MAAM,KAAK,
|
|
1
|
+
{"version":3,"file":"request-domain.js","sourceRoot":"","sources":["../../../../../../src/base/auth/authorize/providers/request-domain.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,yBAAyB,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AAO5F,kEAAkE;AAClE,MAAM,OAAO,qBAAqB;IAChC,yEAAyE;IACzE,MAAM,CAAC,eAAe,CAAC,IAGtB;QACC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAEjC,QAAQ,MAAM,CAAC,IAAI,EAAE,CAAC;YACpB,KAAK,0BAA0B,CAAC,KAAK,CAAC,CAAC,CAAC;gBACtC,OAAO,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC;YAC/C,CAAC;YACD,KAAK,0BAA0B,CAAC,MAAM,CAAC,CAAC,CAAC;gBACvC,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC;YAChD,CAAC;YACD,KAAK,0BAA0B,CAAC,KAAK,CAAC,CAAC,CAAC;gBACtC,OAAO,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC;YAC/C,CAAC;YACD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c,IAAI,IAAI,CAAC;QAEvD,IAAI,cAAc,EAAE,CAAC;YACnB,MAAM,QAAQ,GAAG,MAAM,cAAc,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC;YAEnD,OAAO,QAAQ;gBACb,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;gBACxC,CAAC,CAAC,yBAAyB,CAAC,WAAW,CAAC;QAC5C,CAAC;QAED,OAAO,yBAAyB,CAAC,WAAW,CAAC;IAC/C,CAAC;CACF","sourcesContent":["import type { TContext } from '@/base/controllers/common/types';\nimport type { TNullable } from '@venizia/ignis-helpers/common';\nimport type { Env } from 'hono';\nimport { AuthorizationDomainScopes, AuthorizationDomainSources } from '../common/constants';\nimport type {\n IAuthorizationDomainSource,\n IAuthorizationSpec,\n IAuthorizeOptions,\n} from '../common/types';\n\n/** Reads the domain of an authorization check off the request. */\nexport class RequestDomainResolver {\n /** Read a domain value from a declarative source on the Hono context. */\n static readDeclarative(opts: {\n source: IAuthorizationDomainSource;\n context: TContext<Env, string>;\n }): TNullable<string> {\n const { source, context } = opts;\n\n switch (source.from) {\n case AuthorizationDomainSources.PARAM: {\n return context.req.param(source.key) ?? null;\n }\n case AuthorizationDomainSources.HEADER: {\n return context.req.header(source.key) ?? null;\n }\n case AuthorizationDomainSources.QUERY: {\n return context.req.query(source.key) ?? null;\n }\n case AuthorizationDomainSources.CONTEXT: {\n // A declarative key is a string read off the request, so it cannot satisfy `get`'s `keyof Variables` parameter.\n const value: unknown = Reflect.apply(context.get, context, [source.key]);\n\n return value == null ? null : String(value);\n }\n default: {\n return null;\n }\n }\n }\n\n /** Resolve the request domain, precedence spec.domain (method | declarative) -> options.domainResolver -> SYSTEM_WIDE, as a casbin domain string (\"<type>_<id>\") or the SYSTEM_WIDE sentinel. */\n static async resolveRequestDomain(opts: {\n spec: IAuthorizationSpec;\n context: TContext<Env, string>;\n options: TNullable<IAuthorizeOptions>;\n }): Promise<string> {\n const { spec, context, options } = opts;\n\n if (typeof spec.domain === 'function') {\n const resolved = await spec.domain({ context });\n\n return resolved\n ? [resolved.type, resolved.id].join('_')\n : AuthorizationDomainScopes.SYSTEM_WIDE;\n }\n\n if (spec.domain) {\n const id = RequestDomainResolver.readDeclarative({ source: spec.domain, context });\n\n return id ? [spec.domain.type, id].join('_') : AuthorizationDomainScopes.SYSTEM_WIDE;\n }\n\n const globalResolver = options?.domainResolver ?? null;\n\n if (globalResolver) {\n const resolved = await globalResolver({ context });\n\n return resolved\n ? [resolved.type, resolved.id].join('_')\n : AuthorizationDomainScopes.SYSTEM_WIDE;\n }\n\n return AuthorizationDomainScopes.SYSTEM_WIDE;\n }\n}\n"]}
|
|
@@ -2,7 +2,6 @@ import type { TAuthMode, TAuthStrategy } from '../../../auth/authenticate/common
|
|
|
2
2
|
import type { IAuthorizationSpec } from '../../../auth/authorize/common/types/index.js';
|
|
3
3
|
import type { TAnyObjectSchema } from '../schema-builders.js';
|
|
4
4
|
import type { createRoute, RouteConfig as HonoRouteConfig, OpenAPIHono, z } from '@hono/zod-openapi';
|
|
5
|
-
import type { AnyType } from '@venizia/ignis-helpers/common';
|
|
6
5
|
import type { Env, Schema } from 'hono';
|
|
7
6
|
import type { TRouteHandler } from './context.js';
|
|
8
7
|
/** Registered route with its configuration and router instance. */
|
|
@@ -53,10 +52,17 @@ export type TResponseHeaderObject = {
|
|
|
53
52
|
/** OpenAPI response headers format */
|
|
54
53
|
export type TResponseHeaders = Record<string, TResponseHeaderObject>;
|
|
55
54
|
type TInferDistributive<S> = S extends z.ZodType ? z.infer<S> : never;
|
|
55
|
+
type TJsonSchemaOf<Response> = Response extends {
|
|
56
|
+
content: {
|
|
57
|
+
'application/json': {
|
|
58
|
+
schema: infer JsonSchema;
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
} ? JsonSchema : never;
|
|
56
62
|
/** The JSON response body type of a route config `R`: the union of the schemas under `application/json` across all its response codes. */
|
|
57
63
|
export type TResponseBodyOf<R extends {
|
|
58
|
-
responses:
|
|
59
|
-
}> = TInferDistributive<R['responses'][keyof R['responses']]
|
|
64
|
+
responses: object;
|
|
65
|
+
}> = TInferDistributive<TJsonSchemaOf<R['responses'][keyof R['responses']]>>;
|
|
60
66
|
/** What a CRUD route lets a caller override: auth, the request schemas (params, query, body, headers) and the response schema and headers. */
|
|
61
67
|
export type TCustomizableRouteConfig = TRouteAuthConfig & {
|
|
62
68
|
request?: {
|
|
@@ -88,7 +94,10 @@ export interface ICustomizableRoutes<RouteConfig extends TCustomizableRouteConfi
|
|
|
88
94
|
* The routes of a CRUD controller: only a listed route exists, as `true` (on, with its defaults) or a config
|
|
89
95
|
* (on, with overrides). `restoreById` and `restoreBy` are listed only for a repository that has both methods.
|
|
90
96
|
*/
|
|
91
|
-
export type TCrudRoutes<Repository extends object =
|
|
97
|
+
export type TCrudRoutes<Repository extends object = {
|
|
98
|
+
restoreById: unknown;
|
|
99
|
+
restoreBy: unknown;
|
|
100
|
+
}> = {
|
|
92
101
|
[Key in keyof ICustomizableRoutes]?: Key extends 'restoreById' | 'restoreBy' ? Repository extends {
|
|
93
102
|
restoreById: unknown;
|
|
94
103
|
restoreBy: unknown;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route.js","sourceRoot":"","sources":["../../../../../../src/base/controllers/common/types/route.ts"],"names":[],"mappings":"","sourcesContent":["import type { TAuthMode, TAuthStrategy } from '@/base/auth/authenticate/common/constants';\nimport type { IAuthorizationSpec } from '@/base/auth/authorize/common/types';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport type {\n createRoute,\n RouteConfig as HonoRouteConfig,\n OpenAPIHono,\n z,\n} from '@hono/zod-openapi';\nimport type {
|
|
1
|
+
{"version":3,"file":"route.js","sourceRoot":"","sources":["../../../../../../src/base/controllers/common/types/route.ts"],"names":[],"mappings":"","sourcesContent":["import type { TAuthMode, TAuthStrategy } from '@/base/auth/authenticate/common/constants';\nimport type { IAuthorizationSpec } from '@/base/auth/authorize/common/types';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport type {\n createRoute,\n RouteConfig as HonoRouteConfig,\n OpenAPIHono,\n z,\n} from '@hono/zod-openapi';\nimport type { Env, Schema } from 'hono';\nimport type { TRouteHandler } from './context';\n\n/** Registered route with its configuration and router instance. */\nexport interface IDefineRouteOptions<\n RouteConfig extends HonoRouteConfig,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n> {\n configs: ReturnType<typeof createRoute<string, RouteConfig>>;\n route: OpenAPIHono<RouteEnv, RouteSchema, BasePath>;\n}\n\n/** Fluent binding for two-step route registration: bindRoute({ configs }).to({ handler }). */\nexport interface IBindRouteOptions<\n RouteConfig extends HonoRouteConfig,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n> {\n configs: RouteConfig;\n to: <ResponseType = unknown>(opts: {\n handler: TRouteHandler<ResponseType, RouteEnv>;\n }) => IDefineRouteOptions<RouteConfig, RouteEnv, RouteSchema, BasePath>;\n}\n\n/** Route configuration extended with optional authenticate and authorize fields. */\nexport interface IAuthRouteConfig extends HonoRouteConfig {\n authenticate?: { strategies?: TAuthStrategy[]; mode?: TAuthMode };\n authorize?: IAuthorizationSpec | IAuthorizationSpec[];\n}\n\n/** Per-route authentication config: { skip: true } or { strategies, mode }. */\nexport type TRouteAuthenticateConfig =\n | { skip: true }\n | { skip?: false; strategies?: TAuthStrategy[]; mode?: TAuthMode };\n\n/** Per-route authorization config: { skip: true }, single spec, or array of specs. */\nexport type TRouteAuthorizeConfig = { skip: true } | IAuthorizationSpec | IAuthorizationSpec[];\n\n/** Per-route auth config. Endpoint config takes precedence over controller-level config. */\nexport type TRouteAuthConfig = {\n authenticate?: TRouteAuthenticateConfig;\n authorize?: TRouteAuthorizeConfig;\n};\n\n/** OpenAPI response header object */\nexport type TResponseHeaderObject = {\n description?: string;\n schema: { type: 'string'; examples?: string[] };\n};\n\n/** OpenAPI response headers format */\nexport type TResponseHeaders = Record<string, TResponseHeaderObject>;\n\n// Response body types derived from route definitions; a distributive conditional applies z.infer to each schema of the union separately.\ntype TInferDistributive<S> = S extends z.ZodType ? z.infer<S> : never;\ntype TJsonSchemaOf<Response> = Response extends {\n content: { 'application/json': { schema: infer JsonSchema } };\n}\n ? JsonSchema\n : never;\n/** The JSON response body type of a route config `R`: the union of the schemas under `application/json` across all its response codes. */\nexport type TResponseBodyOf<R extends { responses: object }> = TInferDistributive<\n TJsonSchemaOf<R['responses'][keyof R['responses']]>\n>;\n\n/** What a CRUD route lets a caller override: auth, the request schemas (params, query, body, headers) and the response schema and headers. */\nexport type TCustomizableRouteConfig = TRouteAuthConfig & {\n request?: {\n params?: TAnyObjectSchema;\n query?: TAnyObjectSchema;\n body?: TAnyObjectSchema;\n headers?: TAnyObjectSchema;\n };\n response?: {\n schema?: z.ZodType;\n headers?: TResponseHeaders;\n };\n};\n\n/** Per-route configuration for CRUD controller endpoints (auth, request, response). */\nexport interface ICustomizableRoutes<\n RouteConfig extends TCustomizableRouteConfig = TCustomizableRouteConfig,\n> {\n count?: RouteConfig;\n find?: RouteConfig;\n findById?: RouteConfig;\n findOne?: RouteConfig;\n create?: RouteConfig;\n updateById?: RouteConfig;\n updateBy?: RouteConfig;\n deleteById?: RouteConfig;\n deleteBy?: RouteConfig;\n restoreById?: RouteConfig;\n restoreBy?: RouteConfig;\n}\n\n/**\n * The routes of a CRUD controller: only a listed route exists, as `true` (on, with its defaults) or a config\n * (on, with overrides). `restoreById` and `restoreBy` are listed only for a repository that has both methods.\n */\nexport type TCrudRoutes<Repository extends object = { restoreById: unknown; restoreBy: unknown }> =\n {\n [Key in keyof ICustomizableRoutes]?: Key extends 'restoreById' | 'restoreBy'\n ? Repository extends { restoreById: unknown; restoreBy: unknown }\n ? true | TCustomizableRouteConfig\n : never\n : true | TCustomizableRouteConfig;\n };\n"]}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { AnyType } from '@venizia/ignis-helpers/common';
|
|
2
1
|
import type { AbstractRepository } from '../../repositories/index.js';
|
|
3
2
|
import type { IAuthorizationSpec } from '../../auth/authorize/common/types/index.js';
|
|
4
3
|
import type { TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';
|
|
@@ -22,7 +21,7 @@ export declare class CrudControllerFactory extends BaseHelper {
|
|
|
22
21
|
repositoryName: string;
|
|
23
22
|
}): void;
|
|
24
23
|
static build<Repository extends TCrudRepositoryClass, RouteEnv extends Env = Env, RouteSchema extends Schema = {}, BasePath extends string = '/', ConfigurableOptions extends object = {}, TDataObject extends object = TRepositoryDataObject<InstanceType<Repository>>, TPersistObject extends object = TRepositoryPersistObject<InstanceType<Repository>>>(opts: ICrudControllerOptions<Repository>): {
|
|
25
|
-
new (repositoryInstance: AbstractRepository<TDataObject, TPersistObject
|
|
24
|
+
new (repositoryInstance: AbstractRepository<TDataObject, TPersistObject>): {
|
|
26
25
|
/** The routes of a generated controller come from `routes`; a subclass adds its own here. */
|
|
27
26
|
binding(): ValueOrPromise<void>;
|
|
28
27
|
/** Registers each listed CRUD route, after `binding()`: a custom static path is never taken by `/{id}`. */
|
|
@@ -96,8 +95,8 @@ export declare class CrudControllerFactory extends BaseHelper {
|
|
|
96
95
|
scope: string;
|
|
97
96
|
args: unknown;
|
|
98
97
|
task: () => Promise<R>;
|
|
99
|
-
}): Promise<
|
|
100
|
-
normalizeCountData<ResponseSchema
|
|
98
|
+
}): Promise<R>;
|
|
99
|
+
normalizeCountData<ResponseSchema, RequestContext extends import("../index.js").TRouteContext<RouteEnv> = import("../index.js").TRouteContext<RouteEnv>, ResponseData extends {
|
|
101
100
|
count: number;
|
|
102
101
|
data?: import("@venizia/ignis-helpers/common").TNullable<ResponseSchema>;
|
|
103
102
|
} = {
|
|
@@ -79,7 +79,6 @@ export class CrudControllerFactory extends BaseHelper {
|
|
|
79
79
|
serverStampedKeys: [...(settings?.properties?.stamped ?? AuditFields.SCHEME_SET)],
|
|
80
80
|
});
|
|
81
81
|
const controllerClass = class extends PersistableCrudController {
|
|
82
|
-
// Any extra options: a repository whose options narrow `IExtraOptions` (a typed transaction) must fit.
|
|
83
82
|
constructor(repositoryInstance) {
|
|
84
83
|
super({
|
|
85
84
|
scope: new.target.name,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"controller.js","sourceRoot":"","sources":["../../../../../src/base/controllers/factory/controller.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAG9E,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAE1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEpE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AASnD,OAAO,EAAE,yBAAyB,EAAE,MAAM,QAAQ,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAEnD,6EAA6E;AAC7E,MAAM,OAAO,qBAAsB,SAAQ,UAAU;IACnD,0GAA0G;aAClF,gBAAW,GAAG;QACpC,QAAQ;QACR,YAAY;QACZ,UAAU;QACV,YAAY;QACZ,UAAU;QACV,aAAa;QACb,WAAW;KACH,CAAC;IAEX;QACE,KAAK,CAAC,EAAE,KAAK,EAAE,qBAAqB,CAAC,IAAI,EAAE,CAAC,CAAC;IAC/C,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,2BAA2B,CAAC,IAIlC;QACC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,cAAc,EAAE,GAAG,IAAI,CAAC;QAErD,IAAI,CAAC,cAAc,EAAE,CAAC;YACpB,MAAM,QAAQ,CAAC;gBACb,OAAO,EA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CAAC,CAAC;IACL,CAAC","sourcesContent":["import type { AnyType } from '@venizia/ignis-helpers/common';\nimport type { AbstractRepository } from '@/base/repositories';\nimport { AuthorizationActions } from '@/base/auth/authorize/common/constants';\nimport type { IAuthorizationSpec } from '@/base/auth/authorize/common/types';\nimport type { AbstractEntity } from '@/base/models';\nimport { AuditFields, SchemaTypes } from '@/base/models/common/constants';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport { BindingNamespaces } from '@/common/bindings';\nimport { BindingKeys, MetadataRegistry } from '@/helpers/inversion';\nimport type { TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { isClass } from '@venizia/ignis-inversion';\nimport type { Env, Schema } from 'hono';\nimport type {\n ICrudControllerOptions,\n TCrudRepositoryClass,\n TCrudRoutes,\n TRepositoryDataObject,\n TRepositoryPersistObject,\n} from '../common';\nimport { PersistableCrudController } from './crud';\nimport { RouteConfigResolver } from './definition';\n\n/** Factory for generating typed CRUD controllers from entity definitions. */\nexport class CrudControllerFactory extends BaseHelper {\n /** The generated routes that change data: the ones that must never be answered by a `read` permission. */\n private static readonly WRITE_VERBS = [\n 'create',\n 'updateById',\n 'updateBy',\n 'deleteById',\n 'deleteBy',\n 'restoreById',\n 'restoreBy',\n ] as const;\n\n constructor() {\n super({ scope: CrudControllerFactory.name });\n }\n\n /**\n * Injects `repositories.<repositoryName>` into constructor parameter 0 of a factory-generated\n * controller, so a subclass needs no constructor. Recorded as metadata rather than a parameter\n * decorator, which Bun drops in some configurations. A subclass that declares its own `@inject` at\n * index 0 wins, and a sibling subclass keeps the factory's key.\n */\n static registerRepositoryInjection(opts: {\n target: TClass<unknown>;\n factoryName: string;\n repositoryName: string;\n }): void {\n const { target, factoryName, repositoryName } = opts;\n\n if (!repositoryName) {\n throw getError({\n message: `[${factoryName}] Invalid repository name | repository.name must name the repository binding`,\n });\n }\n\n MetadataRegistry.getInstance().setInjectMetadata({\n target,\n index: 0,\n metadata: {\n key: BindingKeys.build({ namespace: BindingNamespaces.REPOSITORY, key: repositoryName }),\n index: 0,\n isOptional: false,\n },\n });\n }\n\n static build<\n Repository extends TCrudRepositoryClass,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TRepositoryDataObject<InstanceType<Repository>>,\n TPersistObject extends object = TRepositoryPersistObject<InstanceType<Repository>>,\n >(opts: ICrudControllerOptions<Repository>) {\n const { repository, authenticate, authorize, routes, isStrict = {} } = opts;\n\n CrudControllerFactory.assertWriteVerbsDeclareAuthorize({\n repositoryName: repository.name,\n authorize,\n routes,\n });\n CrudControllerFactory.assertRestoreRoutesSupported({ repository, routes });\n\n const model = MetadataRegistry.getInstance().getRepositoryBinding({\n target: repository,\n })?.model;\n\n if (!model) {\n throw getError({\n message: `[CrudControllerFactory.build] Cannot resolve the entity | repository: ${repository.name} | declare it with @repository({ model })`,\n });\n }\n\n const entityClass = isClass(model) ? model : model();\n const entityInstance = new entityClass();\n const settings = MetadataRegistry.getInstance().getModelMetadata({\n target: entityClass,\n })?.settings;\n\n const routeDefinitions = RouteConfigResolver.defineControllerRouteConfigs({\n isStrict: isStrict.requestSchema ?? true,\n idType: entityInstance.getIdType(),\n authenticate,\n authorize,\n routes,\n schema: {\n select: entityInstance.getSchema<TAnyObjectSchema>({ type: SchemaTypes.SELECT }),\n create: entityInstance.getSchema<TAnyObjectSchema>({ type: SchemaTypes.CREATE }),\n update: entityInstance.getSchema<TAnyObjectSchema>({ type: SchemaTypes.UPDATE }),\n },\n serverStampedKeys: [...(settings?.properties?.stamped ?? AuditFields.SCHEME_SET)],\n });\n\n const controllerClass = class extends PersistableCrudController<\n AbstractEntity<TAnyObjectSchema>,\n RouteEnv,\n RouteSchema,\n BasePath,\n ConfigurableOptions,\n TDataObject,\n TPersistObject\n > {\n // Any extra options: a repository whose options narrow `IExtraOptions` (a typed transaction) must fit.\n constructor(repositoryInstance: AbstractRepository<TDataObject, TPersistObject, AnyType>) {\n super({\n scope: new.target.name,\n isStrict: isStrict.path ?? true,\n repository: repositoryInstance,\n definitions: routeDefinitions,\n });\n }\n\n /** The routes of a generated controller come from `routes`; a subclass adds its own here. */\n override binding(): ValueOrPromise<void> {}\n\n /** Registers each listed CRUD route, after `binding()`: a custom static path is never taken by `/{id}`. */\n override bindDefaultRoutes(): ValueOrPromise<void> {\n if (routeDefinitions.COUNT) {\n this.defineRoute({\n configs: routeDefinitions.COUNT,\n handler: async (context) => this.count({ context }),\n });\n }\n\n if (routeDefinitions.FIND) {\n this.defineRoute({\n configs: routeDefinitions.FIND,\n handler: async (context) => this.find({ context }),\n });\n }\n\n if (routeDefinitions.FIND_ONE) {\n this.defineRoute({\n configs: routeDefinitions.FIND_ONE,\n handler: async (context) => this.findOne({ context }),\n });\n }\n\n if (routeDefinitions.FIND_BY_ID) {\n this.defineRoute({\n configs: routeDefinitions.FIND_BY_ID,\n handler: async (context) => this.findById({ context }),\n });\n }\n\n if (routeDefinitions.CREATE) {\n this.defineRoute({\n configs: routeDefinitions.CREATE,\n handler: async (context) => this.create({ context }),\n });\n }\n\n if (routeDefinitions.UPDATE_BY_ID) {\n this.defineRoute({\n configs: routeDefinitions.UPDATE_BY_ID,\n handler: async (context) => this.updateById({ context }),\n });\n }\n\n if (routeDefinitions.UPDATE_BY) {\n this.defineRoute({\n configs: routeDefinitions.UPDATE_BY,\n handler: async (context) => this.updateBy({ context }),\n });\n }\n\n if (routeDefinitions.DELETE_BY_ID) {\n this.defineRoute({\n configs: routeDefinitions.DELETE_BY_ID,\n handler: async (context) => this.deleteById({ context }),\n });\n }\n\n if (routeDefinitions.DELETE_BY) {\n this.defineRoute({\n configs: routeDefinitions.DELETE_BY,\n handler: async (context) => this.deleteBy({ context }),\n });\n }\n\n if (routeDefinitions.RESTORE_BY) {\n this.defineRoute({\n configs: routeDefinitions.RESTORE_BY,\n handler: async (context) => this.restoreBy({ context }),\n });\n }\n\n if (routeDefinitions.RESTORE_BY_ID) {\n this.defineRoute({\n configs: routeDefinitions.RESTORE_BY_ID,\n handler: async (context) => this.restoreById({ context }),\n });\n }\n }\n };\n\n CrudControllerFactory.registerRepositoryInjection({\n target: controllerClass,\n factoryName: 'CrudControllerFactory.build',\n repositoryName: repository.name,\n });\n\n return controllerClass;\n }\n\n /** A restore route needs a repository that has the restore methods; the types already refuse one, this is the backstop for an untyped caller. */\n private static assertRestoreRoutesSupported(opts: {\n repository: TCrudRepositoryClass;\n routes: TCrudRoutes | undefined;\n }): void {\n const { repository, routes } = opts;\n\n const isRestoreListed = routes?.restoreById !== undefined || routes?.restoreBy !== undefined;\n const isRestorable =\n typeof repository.prototype.restoreById === 'function' &&\n typeof repository.prototype.restoreBy === 'function';\n\n if (isRestoreListed && !isRestorable) {\n throw getError({\n message: `[CrudControllerFactory.build] a restore route needs a repository with both restoreById and restoreBy | repository: ${repository.name}`,\n });\n }\n }\n\n private static describeSpec(opts: { spec: IAuthorizationSpec }): string {\n const { spec } = opts;\n\n return `{ action: ${String(spec.action)}, resource: ${String(spec.resource)} }`;\n }\n\n /**\n * Refuses a CRUD controller that lists a write verb which would inherit a controller-level `authorize`\n * that is only a `read` permission: the verb would then answer to anyone who may read.\n *\n * A listed write verb is fine when it declares its own `authorize` (a spec, an array, or `{ skip: true }`) or\n * skips authentication. Only the literal action `read` is detected; a custom action name is the application's own\n * vocabulary. An array counts when every spec in it is `read`, since the specs of one route must all pass.\n */\n static assertWriteVerbsDeclareAuthorize(opts: {\n repositoryName: string;\n authorize: IAuthorizationSpec | IAuthorizationSpec[] | undefined;\n routes: TCrudRoutes | undefined;\n }): void {\n const { repositoryName, authorize, routes } = opts;\n\n if (authorize == null) {\n return;\n }\n\n const specs = Array.isArray(authorize) ? authorize : [authorize];\n const isReadOnlyPermission =\n specs.length > 0 && specs.every((spec) => spec.action === AuthorizationActions.READ);\n\n if (!isReadOnlyPermission) {\n return;\n }\n\n const offending = CrudControllerFactory.WRITE_VERBS.filter((verb) => {\n const route = routes?.[verb];\n\n if (route === undefined) {\n return false;\n }\n\n return route === true || (route.authenticate?.skip !== true && route.authorize == null);\n });\n\n if (offending.length === 0) {\n return;\n }\n\n const inherited = specs.map((spec) => CrudControllerFactory.describeSpec({ spec })).join(', ');\n const verbs = offending.map((verb) => `${repositoryName}.${verb}`).join(', ');\n\n throw getError({\n message: [\n `[CrudControllerFactory.build] Write routes would inherit a read-only authorize | repository: ${repositoryName} | routes: ${verbs} | inherited: ${inherited}`,\n 'Anyone allowed to read could then create, update, delete or restore.',\n 'Fix: declare routes.<verb>.authorize for each of them (a spec, an array or { skip: true }), or leave them out of routes.',\n ].join(' | '),\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"controller.js","sourceRoot":"","sources":["../../../../../src/base/controllers/factory/controller.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAG9E,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAE1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEpE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AASnD,OAAO,EAAE,yBAAyB,EAAE,MAAM,QAAQ,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAEnD,6EAA6E;AAC7E,MAAM,OAAO,qBAAsB,SAAQ,UAAU;IACnD,0GAA0G;aAClF,gBAAW,GAAG;QACpC,QAAQ;QACR,YAAY;QACZ,UAAU;QACV,YAAY;QACZ,UAAU;QACV,aAAa;QACb,WAAW;KACH,CAAC;IAEX;QACE,KAAK,CAAC,EAAE,KAAK,EAAE,qBAAqB,CAAC,IAAI,EAAE,CA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AC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAE9E,MAAM,QAAQ,CAAC;YACb,OAAO,EAAE;gBACP,gGAAgG,cAAc,cAAc,KAAK,iBAAiB,SAAS,EAAE;gBAC7J,sEAAsE;gBACtE,0HAA0H;aAC3H,CAAC,IAAI,CAAC,KAAK,CAAC;SACd,CAAC,CAAC;IACL,CAAC","sourcesContent":["import type { AbstractRepository } from '@/base/repositories';\nimport { AuthorizationActions } from '@/base/auth/authorize/common/constants';\nimport type { IAuthorizationSpec } from '@/base/auth/authorize/common/types';\nimport type { AbstractEntity } from '@/base/models';\nimport { AuditFields, SchemaTypes } from '@/base/models/common/constants';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport { BindingNamespaces } from '@/common/bindings';\nimport { BindingKeys, MetadataRegistry } from '@/helpers/inversion';\nimport type { TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { isClass } from '@venizia/ignis-inversion';\nimport type { Env, Schema } from 'hono';\nimport type {\n ICrudControllerOptions,\n TCrudRepositoryClass,\n TCrudRoutes,\n TRepositoryDataObject,\n TRepositoryPersistObject,\n} from '../common';\nimport { PersistableCrudController } from './crud';\nimport { RouteConfigResolver } from './definition';\n\n/** Factory for generating typed CRUD controllers from entity definitions. */\nexport class CrudControllerFactory extends BaseHelper {\n /** The generated routes that change data: the ones that must never be answered by a `read` permission. */\n private static readonly WRITE_VERBS = [\n 'create',\n 'updateById',\n 'updateBy',\n 'deleteById',\n 'deleteBy',\n 'restoreById',\n 'restoreBy',\n ] as const;\n\n constructor() {\n super({ scope: CrudControllerFactory.name });\n }\n\n /**\n * Injects `repositories.<repositoryName>` into constructor parameter 0 of a factory-generated\n * controller, so a subclass needs no constructor. Recorded as metadata rather than a parameter\n * decorator, which Bun drops in some configurations. A subclass that declares its own `@inject` at\n * index 0 wins, and a sibling subclass keeps the factory's key.\n */\n static registerRepositoryInjection(opts: {\n target: TClass<unknown>;\n factoryName: string;\n repositoryName: string;\n }): void {\n const { target, factoryName, repositoryName } = opts;\n\n if (!repositoryName) {\n throw getError({\n message: `[${factoryName}] Invalid repository name | repository.name must name the repository binding`,\n });\n }\n\n MetadataRegistry.getInstance().setInjectMetadata({\n target,\n index: 0,\n metadata: {\n key: BindingKeys.build({ namespace: BindingNamespaces.REPOSITORY, key: repositoryName }),\n index: 0,\n isOptional: false,\n },\n });\n }\n\n static build<\n Repository extends TCrudRepositoryClass,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TRepositoryDataObject<InstanceType<Repository>>,\n TPersistObject extends object = TRepositoryPersistObject<InstanceType<Repository>>,\n >(opts: ICrudControllerOptions<Repository>) {\n const { repository, authenticate, authorize, routes, isStrict = {} } = opts;\n\n CrudControllerFactory.assertWriteVerbsDeclareAuthorize({\n repositoryName: repository.name,\n authorize,\n routes,\n });\n CrudControllerFactory.assertRestoreRoutesSupported({ repository, routes });\n\n const model = MetadataRegistry.getInstance().getRepositoryBinding({\n target: repository,\n })?.model;\n\n if (!model) {\n throw getError({\n message: `[CrudControllerFactory.build] Cannot resolve the entity | repository: ${repository.name} | declare it with @repository({ model })`,\n });\n }\n\n const entityClass = isClass(model) ? model : model();\n const entityInstance = new entityClass();\n const settings = MetadataRegistry.getInstance().getModelMetadata({\n target: entityClass,\n })?.settings;\n\n const routeDefinitions = RouteConfigResolver.defineControllerRouteConfigs({\n isStrict: isStrict.requestSchema ?? true,\n idType: entityInstance.getIdType(),\n authenticate,\n authorize,\n routes,\n schema: {\n select: entityInstance.getSchema<TAnyObjectSchema>({ type: SchemaTypes.SELECT }),\n create: entityInstance.getSchema<TAnyObjectSchema>({ type: SchemaTypes.CREATE }),\n update: entityInstance.getSchema<TAnyObjectSchema>({ type: SchemaTypes.UPDATE }),\n },\n serverStampedKeys: [...(settings?.properties?.stamped ?? AuditFields.SCHEME_SET)],\n });\n\n const controllerClass = class extends PersistableCrudController<\n AbstractEntity<TAnyObjectSchema>,\n RouteEnv,\n RouteSchema,\n BasePath,\n ConfigurableOptions,\n TDataObject,\n TPersistObject\n > {\n constructor(repositoryInstance: AbstractRepository<TDataObject, TPersistObject>) {\n super({\n scope: new.target.name,\n isStrict: isStrict.path ?? true,\n repository: repositoryInstance,\n definitions: routeDefinitions,\n });\n }\n\n /** The routes of a generated controller come from `routes`; a subclass adds its own here. */\n override binding(): ValueOrPromise<void> {}\n\n /** Registers each listed CRUD route, after `binding()`: a custom static path is never taken by `/{id}`. */\n override bindDefaultRoutes(): ValueOrPromise<void> {\n if (routeDefinitions.COUNT) {\n this.defineRoute({\n configs: routeDefinitions.COUNT,\n handler: async (context) => this.count({ context }),\n });\n }\n\n if (routeDefinitions.FIND) {\n this.defineRoute({\n configs: routeDefinitions.FIND,\n handler: async (context) => this.find({ context }),\n });\n }\n\n if (routeDefinitions.FIND_ONE) {\n this.defineRoute({\n configs: routeDefinitions.FIND_ONE,\n handler: async (context) => this.findOne({ context }),\n });\n }\n\n if (routeDefinitions.FIND_BY_ID) {\n this.defineRoute({\n configs: routeDefinitions.FIND_BY_ID,\n handler: async (context) => this.findById({ context }),\n });\n }\n\n if (routeDefinitions.CREATE) {\n this.defineRoute({\n configs: routeDefinitions.CREATE,\n handler: async (context) => this.create({ context }),\n });\n }\n\n if (routeDefinitions.UPDATE_BY_ID) {\n this.defineRoute({\n configs: routeDefinitions.UPDATE_BY_ID,\n handler: async (context) => this.updateById({ context }),\n });\n }\n\n if (routeDefinitions.UPDATE_BY) {\n this.defineRoute({\n configs: routeDefinitions.UPDATE_BY,\n handler: async (context) => this.updateBy({ context }),\n });\n }\n\n if (routeDefinitions.DELETE_BY_ID) {\n this.defineRoute({\n configs: routeDefinitions.DELETE_BY_ID,\n handler: async (context) => this.deleteById({ context }),\n });\n }\n\n if (routeDefinitions.DELETE_BY) {\n this.defineRoute({\n configs: routeDefinitions.DELETE_BY,\n handler: async (context) => this.deleteBy({ context }),\n });\n }\n\n if (routeDefinitions.RESTORE_BY) {\n this.defineRoute({\n configs: routeDefinitions.RESTORE_BY,\n handler: async (context) => this.restoreBy({ context }),\n });\n }\n\n if (routeDefinitions.RESTORE_BY_ID) {\n this.defineRoute({\n configs: routeDefinitions.RESTORE_BY_ID,\n handler: async (context) => this.restoreById({ context }),\n });\n }\n }\n };\n\n CrudControllerFactory.registerRepositoryInjection({\n target: controllerClass,\n factoryName: 'CrudControllerFactory.build',\n repositoryName: repository.name,\n });\n\n return controllerClass;\n }\n\n /** A restore route needs a repository that has the restore methods; the types already refuse one, this is the backstop for an untyped caller. */\n private static assertRestoreRoutesSupported(opts: {\n repository: TCrudRepositoryClass;\n routes: TCrudRoutes | undefined;\n }): void {\n const { repository, routes } = opts;\n\n const isRestoreListed = routes?.restoreById !== undefined || routes?.restoreBy !== undefined;\n const isRestorable =\n typeof repository.prototype.restoreById === 'function' &&\n typeof repository.prototype.restoreBy === 'function';\n\n if (isRestoreListed && !isRestorable) {\n throw getError({\n message: `[CrudControllerFactory.build] a restore route needs a repository with both restoreById and restoreBy | repository: ${repository.name}`,\n });\n }\n }\n\n private static describeSpec(opts: { spec: IAuthorizationSpec }): string {\n const { spec } = opts;\n\n return `{ action: ${String(spec.action)}, resource: ${String(spec.resource)} }`;\n }\n\n /**\n * Refuses a CRUD controller that lists a write verb which would inherit a controller-level `authorize`\n * that is only a `read` permission: the verb would then answer to anyone who may read.\n *\n * A listed write verb is fine when it declares its own `authorize` (a spec, an array, or `{ skip: true }`) or\n * skips authentication. Only the literal action `read` is detected; a custom action name is the application's own\n * vocabulary. An array counts when every spec in it is `read`, since the specs of one route must all pass.\n */\n static assertWriteVerbsDeclareAuthorize(opts: {\n repositoryName: string;\n authorize: IAuthorizationSpec | IAuthorizationSpec[] | undefined;\n routes: TCrudRoutes | undefined;\n }): void {\n const { repositoryName, authorize, routes } = opts;\n\n if (authorize == null) {\n return;\n }\n\n const specs = Array.isArray(authorize) ? authorize : [authorize];\n const isReadOnlyPermission =\n specs.length > 0 && specs.every((spec) => spec.action === AuthorizationActions.READ);\n\n if (!isReadOnlyPermission) {\n return;\n }\n\n const offending = CrudControllerFactory.WRITE_VERBS.filter((verb) => {\n const route = routes?.[verb];\n\n if (route === undefined) {\n return false;\n }\n\n return route === true || (route.authenticate?.skip !== true && route.authorize == null);\n });\n\n if (offending.length === 0) {\n return;\n }\n\n const inherited = specs.map((spec) => CrudControllerFactory.describeSpec({ spec })).join(', ');\n const verbs = offending.map((verb) => `${repositoryName}.${verb}`).join(', ');\n\n throw getError({\n message: [\n `[CrudControllerFactory.build] Write routes would inherit a read-only authorize | repository: ${repositoryName} | routes: ${verbs} | inherited: ${inherited}`,\n 'Anyone allowed to read could then create, update, delete or restore.',\n 'Fix: declare routes.<verb>.authorize for each of them (a spec, an array or { skip: true }), or leave them out of routes.',\n ].join(' | '),\n });\n }\n}\n"]}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import type { AbstractEntity } from '../../../models/base.js';
|
|
2
2
|
import type { AbstractRepository } from '../../../repositories/index.js';
|
|
3
3
|
import type { TAnyObjectSchema } from '../../common/schema-builders.js';
|
|
4
|
-
import type { AnyType } from '@venizia/ignis-helpers/common';
|
|
5
4
|
import type { Env, Schema } from 'hono';
|
|
6
|
-
import type { TEntityDataObject, TEntityPersistObject, TRouteContext } from '../../common/index.js';
|
|
5
|
+
import type { IAuthRouteConfig, TEntityDataObject, TEntityPersistObject, TRouteContext } from '../../common/index.js';
|
|
7
6
|
import { BaseRestController } from '../../rest/base.js';
|
|
8
7
|
type TBulkWhereResolution<WhereType> = {
|
|
9
8
|
where: WhereType;
|
|
@@ -18,8 +17,8 @@ export declare abstract class AbstractCrudController<TEntity extends AbstractEnt
|
|
|
18
17
|
constructor(opts: {
|
|
19
18
|
scope: string;
|
|
20
19
|
isStrict?: boolean;
|
|
21
|
-
repository: AbstractRepository<TDataObject, TPersistObject
|
|
22
|
-
definitions:
|
|
20
|
+
repository: AbstractRepository<TDataObject, TPersistObject>;
|
|
21
|
+
definitions: Record<string, IAuthRouteConfig>;
|
|
23
22
|
});
|
|
24
23
|
/**
|
|
25
24
|
* Refuses (400) a filter the client sent when it names a field the model hides (`where`, `order`, an include scope).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../../../src/base/controllers/factory/crud/abstract.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../../../src/base/controllers/factory/crud/abstract.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAQrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAMrD,yRAAyR;AACzR,MAAM,OAAgB,sBAQpB,SAAQ,kBAAwE;IAGhF,YAAY,IAKX;QACC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;QACtD,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;QAClC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC;IACtC,CAAC;IAED;;;OAGG;IACH,mBAAmB,CAAC,IAEnB;QAEG,IAAI,CAAC,UACN,CAAC,mBAAmB,EAAE,CAAC,IAAI,CAAC,CAAC;IAChC,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 { HTTP } from '@venizia/ignis-helpers/common';\nimport type { Env, Schema } from 'hono';\nimport type {\n IAuthRouteConfig,\n TEntityDataObject,\n TEntityPersistObject,\n TRouteContext,\n} 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 isStrict?: boolean;\n repository: AbstractRepository<TDataObject, TPersistObject>;\n definitions: Record<string, IAuthRouteConfig>;\n }) {\n super({ scope: opts.scope, 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"]}
|
|
@@ -3,7 +3,7 @@ import type { IAuthorizationSpec } from '../../auth/authorize/common/types/index
|
|
|
3
3
|
import type { TIdSchemaType } from '../../models/common/index.js';
|
|
4
4
|
import type { TAnyObjectSchema } from '../common/schema-builders.js';
|
|
5
5
|
import { z } from '@hono/zod-openapi';
|
|
6
|
-
import type { ICustomizableRoutes, TCrudRoutes } from '../common/index.js';
|
|
6
|
+
import type { ICustomizableRoutes, TCrudRoutes, TRouteAuthConfig, TRouteAuthenticateConfig } from '../common/index.js';
|
|
7
7
|
/** Picks user-overridden response schema if present (and non-undefined), else the default. */
|
|
8
8
|
type TResolvedResponseSchema<C, D extends z.ZodType> = C extends {
|
|
9
9
|
response: {
|
|
@@ -230,6 +230,26 @@ export declare class RouteConfigResolver {
|
|
|
230
230
|
private static resolveDeleteByConfig;
|
|
231
231
|
private static resolveRestoreByIdConfig;
|
|
232
232
|
private static resolveRestoreByConfig;
|
|
233
|
+
/**
|
|
234
|
+
* The authentication of one route: its own `authenticate` wins over the controller's, and
|
|
235
|
+
* `{ skip: true }` leaves the route with no strategy at all. Shared by every controller factory so
|
|
236
|
+
* the priority is written once.
|
|
237
|
+
*/
|
|
238
|
+
static resolveAuthenticate(opts: {
|
|
239
|
+
controller?: {
|
|
240
|
+
strategies?: TAuthStrategy[];
|
|
241
|
+
mode?: TAuthMode;
|
|
242
|
+
};
|
|
243
|
+
endpoint?: TRouteAuthenticateConfig;
|
|
244
|
+
}): {
|
|
245
|
+
strategies?: TAuthStrategy[];
|
|
246
|
+
mode?: TAuthMode;
|
|
247
|
+
};
|
|
248
|
+
/** The authorization of one route. Priority: endpoint authenticate.skip > endpoint authorize.skip > endpoint authorize > controller authorize. */
|
|
249
|
+
static resolveAuthorize(opts: {
|
|
250
|
+
controller?: IAuthorizationSpec | IAuthorizationSpec[];
|
|
251
|
+
endpoint?: TRouteAuthConfig;
|
|
252
|
+
}): IAuthorizationSpec | IAuthorizationSpec[] | undefined;
|
|
233
253
|
/**
|
|
234
254
|
* Generates the route configurations of a CRUD controller: one for each route listed in `routes`, none for
|
|
235
255
|
* the rest. `serverStampedKeys` - the keys the default write bodies leave out.
|
|
@@ -290,50 +290,64 @@ export class RouteConfigResolver {
|
|
|
290
290
|
},
|
|
291
291
|
};
|
|
292
292
|
}
|
|
293
|
+
/**
|
|
294
|
+
* The authentication of one route: its own `authenticate` wins over the controller's, and
|
|
295
|
+
* `{ skip: true }` leaves the route with no strategy at all. Shared by every controller factory so
|
|
296
|
+
* the priority is written once.
|
|
297
|
+
*/
|
|
298
|
+
static resolveAuthenticate(opts) {
|
|
299
|
+
const { controller = {}, endpoint } = opts;
|
|
300
|
+
const { strategies: defaultStrategies = [], mode: defaultMode } = controller;
|
|
301
|
+
if (endpoint == null) {
|
|
302
|
+
return { strategies: defaultStrategies, mode: defaultMode };
|
|
303
|
+
}
|
|
304
|
+
if (endpoint.skip === true) {
|
|
305
|
+
return { strategies: [] };
|
|
306
|
+
}
|
|
307
|
+
return {
|
|
308
|
+
strategies: endpoint.strategies ?? defaultStrategies,
|
|
309
|
+
mode: endpoint.mode ?? defaultMode,
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
/** The authorization of one route. Priority: endpoint authenticate.skip > endpoint authorize.skip > endpoint authorize > controller authorize. */
|
|
313
|
+
static resolveAuthorize(opts) {
|
|
314
|
+
const { controller, endpoint } = opts;
|
|
315
|
+
if (endpoint?.authenticate?.skip === true) {
|
|
316
|
+
return undefined;
|
|
317
|
+
}
|
|
318
|
+
const authorize = endpoint?.authorize;
|
|
319
|
+
if (authorize == null) {
|
|
320
|
+
return controller;
|
|
321
|
+
}
|
|
322
|
+
if (Array.isArray(authorize)) {
|
|
323
|
+
return authorize;
|
|
324
|
+
}
|
|
325
|
+
if ('skip' in authorize) {
|
|
326
|
+
return undefined;
|
|
327
|
+
}
|
|
328
|
+
return authorize;
|
|
329
|
+
}
|
|
293
330
|
/**
|
|
294
331
|
* Generates the route configurations of a CRUD controller: one for each route listed in `routes`, none for
|
|
295
332
|
* the rest. `serverStampedKeys` - the keys the default write bodies leave out.
|
|
296
333
|
*/
|
|
297
334
|
static defineControllerRouteConfigs(opts) {
|
|
298
335
|
const { isStrict, idType, authenticate: controllerAuth = {}, authorize: controllerAuthorize, schema: { select: selectSchema, create: createSchema, update: updateSchema }, serverStampedKeys = [], routes, } = opts;
|
|
299
|
-
const { strategies: defaultStrategies = [], mode: defaultMode } = controllerAuth;
|
|
300
336
|
/** The overrides of a listed route (`true` has none), or `undefined` for a route that is not listed. */
|
|
301
337
|
const configOf = (routeKey) => {
|
|
302
338
|
const value = routes?.[routeKey];
|
|
303
339
|
return value === true ? {} : value;
|
|
304
340
|
};
|
|
305
341
|
/** Priority: endpoint authenticate > controller authenticate. */
|
|
306
|
-
const resolveRouteAuth = (routeKey) => {
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
}
|
|
311
|
-
if (authConfig.skip === true) {
|
|
312
|
-
return { strategies: [] };
|
|
313
|
-
}
|
|
314
|
-
return {
|
|
315
|
-
strategies: authConfig.strategies ?? defaultStrategies,
|
|
316
|
-
mode: authConfig.mode ?? defaultMode,
|
|
317
|
-
};
|
|
318
|
-
};
|
|
342
|
+
const resolveRouteAuth = (routeKey) => RouteConfigResolver.resolveAuthenticate({
|
|
343
|
+
controller: controllerAuth,
|
|
344
|
+
endpoint: configOf(routeKey)?.authenticate,
|
|
345
|
+
});
|
|
319
346
|
/** Priority: endpoint authenticate.skip > endpoint authorize.skip > endpoint authorize > controller authorize. */
|
|
320
|
-
const resolveRouteAuthorize = (routeKey) => {
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
}
|
|
325
|
-
const authorize = endpointConfig?.authorize;
|
|
326
|
-
if (authorize == null) {
|
|
327
|
-
return controllerAuthorize;
|
|
328
|
-
}
|
|
329
|
-
if (Array.isArray(authorize)) {
|
|
330
|
-
return authorize;
|
|
331
|
-
}
|
|
332
|
-
if ('skip' in authorize) {
|
|
333
|
-
return undefined;
|
|
334
|
-
}
|
|
335
|
-
return authorize;
|
|
336
|
-
};
|
|
347
|
+
const resolveRouteAuthorize = (routeKey) => RouteConfigResolver.resolveAuthorize({
|
|
348
|
+
controller: controllerAuthorize,
|
|
349
|
+
endpoint: configOf(routeKey),
|
|
350
|
+
});
|
|
337
351
|
const countConfig = configOf('count');
|
|
338
352
|
const count = countConfig && RouteConfigResolver.resolveCountConfig({ config: countConfig, isStrict });
|
|
339
353
|
const findConfig = configOf('find');
|