@venizia/ignis-kernel 0.4.8-0 → 0.4.8-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. package/README.md +5 -4
  2. package/dist/esm/base/applications/abstract.d.ts +1 -0
  3. package/dist/esm/base/applications/abstract.js +1 -0
  4. package/dist/esm/base/applications/abstract.js.map +1 -1
  5. package/dist/esm/base/applications/boot-sequence.d.ts +2 -0
  6. package/dist/esm/base/applications/boot-sequence.js.map +1 -1
  7. package/dist/esm/base/applications/common/constants.d.ts +2 -0
  8. package/dist/esm/base/applications/common/constants.js +1 -0
  9. package/dist/esm/base/applications/common/constants.js.map +1 -1
  10. package/dist/esm/base/applications/common/types/application.d.ts +30 -8
  11. package/dist/esm/base/applications/common/types/application.js.map +1 -1
  12. package/dist/esm/base/applications/common/types/middlewares.d.ts +16 -1
  13. package/dist/esm/base/applications/common/types/middlewares.js.map +1 -1
  14. package/dist/esm/base/auth/authenticate/common/codecs.d.ts +1 -0
  15. package/dist/esm/base/auth/authenticate/common/codecs.js +1 -0
  16. package/dist/esm/base/auth/authenticate/common/codecs.js.map +1 -1
  17. package/dist/esm/base/auth/authenticate/common/constants/authentication.d.ts +6 -0
  18. package/dist/esm/base/auth/authenticate/common/constants/authentication.js +4 -0
  19. package/dist/esm/base/auth/authenticate/common/constants/authentication.js.map +1 -1
  20. package/dist/esm/base/auth/authenticate/common/constants/jose.d.ts +8 -0
  21. package/dist/esm/base/auth/authenticate/common/constants/jose.js +4 -0
  22. package/dist/esm/base/auth/authenticate/common/constants/jose.js.map +1 -1
  23. package/dist/esm/base/auth/authenticate/common/keys.d.ts +1 -0
  24. package/dist/esm/base/auth/authenticate/common/keys.js +1 -0
  25. package/dist/esm/base/auth/authenticate/common/keys.js.map +1 -1
  26. package/dist/esm/base/auth/authenticate/common/types/basic.d.ts +1 -0
  27. package/dist/esm/base/auth/authenticate/common/types/basic.js.map +1 -1
  28. package/dist/esm/base/auth/authenticate/common/types/jwt.d.ts +42 -0
  29. package/dist/esm/base/auth/authenticate/common/types/jwt.js.map +1 -1
  30. package/dist/esm/base/auth/authenticate/common/types/rest.d.ts +2 -0
  31. package/dist/esm/base/auth/authenticate/common/types/rest.js.map +1 -1
  32. package/dist/esm/base/auth/authenticate/common/types/service.d.ts +10 -1
  33. package/dist/esm/base/auth/authenticate/common/types/service.js.map +1 -1
  34. package/dist/esm/base/auth/authenticate/common/types/strategy.d.ts +5 -0
  35. package/dist/esm/base/auth/authenticate/common/types/strategy.js.map +1 -1
  36. package/dist/esm/base/auth/authenticate/middlewares/authenticate.middleware.d.ts +1 -0
  37. package/dist/esm/base/auth/authenticate/middlewares/authenticate.middleware.js +1 -0
  38. package/dist/esm/base/auth/authenticate/middlewares/authenticate.middleware.js.map +1 -1
  39. package/dist/esm/base/auth/authenticate/providers/authentication.provider.d.ts +5 -0
  40. package/dist/esm/base/auth/authenticate/providers/authentication.provider.js +5 -0
  41. package/dist/esm/base/auth/authenticate/providers/authentication.provider.js.map +1 -1
  42. package/dist/esm/base/auth/authenticate/strategies/strategy-registry.d.ts +1 -0
  43. package/dist/esm/base/auth/authenticate/strategies/strategy-registry.js +1 -0
  44. package/dist/esm/base/auth/authenticate/strategies/strategy-registry.js.map +1 -1
  45. package/dist/esm/base/auth/authorize/builders/grant.builder.d.ts +1 -0
  46. package/dist/esm/base/auth/authorize/builders/grant.builder.js +1 -0
  47. package/dist/esm/base/auth/authorize/builders/grant.builder.js.map +1 -1
  48. package/dist/esm/base/auth/authorize/builders/policy.builder.d.ts +1 -0
  49. package/dist/esm/base/auth/authorize/builders/policy.builder.js +1 -0
  50. package/dist/esm/base/auth/authorize/builders/policy.builder.js.map +1 -1
  51. package/dist/esm/base/auth/authorize/common/constants/authorization.d.ts +8 -0
  52. package/dist/esm/base/auth/authorize/common/constants/authorization.js +5 -0
  53. package/dist/esm/base/auth/authorize/common/constants/authorization.js.map +1 -1
  54. package/dist/esm/base/auth/authorize/common/constants/binding-keys.d.ts +1 -0
  55. package/dist/esm/base/auth/authorize/common/constants/binding-keys.js +1 -0
  56. package/dist/esm/base/auth/authorize/common/constants/binding-keys.js.map +1 -1
  57. package/dist/esm/base/auth/authorize/common/constants/enforcer.d.ts +9 -0
  58. package/dist/esm/base/auth/authorize/common/constants/enforcer.js +4 -0
  59. package/dist/esm/base/auth/authorize/common/constants/enforcer.js.map +1 -1
  60. package/dist/esm/base/auth/authorize/common/types/enforcer.d.ts +21 -3
  61. package/dist/esm/base/auth/authorize/common/types/enforcer.js.map +1 -1
  62. package/dist/esm/base/auth/authorize/common/types/grant.d.ts +1 -0
  63. package/dist/esm/base/auth/authorize/common/types/grant.js.map +1 -1
  64. package/dist/esm/base/auth/authorize/common/types/request.d.ts +3 -0
  65. package/dist/esm/base/auth/authorize/common/types/request.js.map +1 -1
  66. package/dist/esm/base/auth/authorize/enforcers/enforcer-registry.d.ts +1 -0
  67. package/dist/esm/base/auth/authorize/enforcers/enforcer-registry.js +1 -0
  68. package/dist/esm/base/auth/authorize/enforcers/enforcer-registry.js.map +1 -1
  69. package/dist/esm/base/auth/authorize/middlewares/authorize.middleware.d.ts +1 -0
  70. package/dist/esm/base/auth/authorize/middlewares/authorize.middleware.js +1 -0
  71. package/dist/esm/base/auth/authorize/middlewares/authorize.middleware.js.map +1 -1
  72. package/dist/esm/base/auth/authorize/models/authorization-role.model.d.ts +6 -0
  73. package/dist/esm/base/auth/authorize/models/authorization-role.model.js +1 -0
  74. package/dist/esm/base/auth/authorize/models/authorization-role.model.js.map +1 -1
  75. package/dist/esm/base/auth/authorize/providers/authorization.provider.d.ts +1 -0
  76. package/dist/esm/base/auth/authorize/providers/authorization.provider.js +1 -0
  77. package/dist/esm/base/auth/authorize/providers/authorization.provider.js.map +1 -1
  78. package/dist/esm/base/auth/base/abstract-auth-registry.d.ts +2 -0
  79. package/dist/esm/base/auth/base/abstract-auth-registry.js +1 -0
  80. package/dist/esm/base/auth/base/abstract-auth-registry.js.map +1 -1
  81. package/dist/esm/base/auth/models/requests/change-password.schema.d.ts +2 -0
  82. package/dist/esm/base/auth/models/requests/change-password.schema.js +1 -0
  83. package/dist/esm/base/auth/models/requests/change-password.schema.js.map +1 -1
  84. package/dist/esm/base/auth/models/requests/sign-in.schema.d.ts +2 -0
  85. package/dist/esm/base/auth/models/requests/sign-in.schema.js +1 -0
  86. package/dist/esm/base/auth/models/requests/sign-in.schema.js.map +1 -1
  87. package/dist/esm/base/auth/models/requests/sign-up.schema.d.ts +2 -0
  88. package/dist/esm/base/auth/models/requests/sign-up.schema.js +1 -0
  89. package/dist/esm/base/auth/models/requests/sign-up.schema.js.map +1 -1
  90. package/dist/esm/base/components/base.d.ts +1 -0
  91. package/dist/esm/base/components/base.js +1 -0
  92. package/dist/esm/base/components/base.js.map +1 -1
  93. package/dist/esm/base/components/controller/rest/common/types.d.ts +2 -0
  94. package/dist/esm/base/components/controller/rest/common/types.js +1 -0
  95. package/dist/esm/base/components/controller/rest/common/types.js.map +1 -1
  96. package/dist/esm/base/configurations/base.d.ts +1 -0
  97. package/dist/esm/base/configurations/base.js +1 -0
  98. package/dist/esm/base/configurations/base.js.map +1 -1
  99. package/dist/esm/base/configurations/common/types.d.ts +1 -0
  100. package/dist/esm/base/configurations/common/types.js.map +1 -1
  101. package/dist/esm/base/controllers/common/constants.d.ts +4 -0
  102. package/dist/esm/base/controllers/common/constants.js +2 -0
  103. package/dist/esm/base/controllers/common/constants.js.map +1 -1
  104. package/dist/esm/base/controllers/common/schema-builders.d.ts +3 -0
  105. package/dist/esm/base/controllers/common/schema-builders.js +1 -0
  106. package/dist/esm/base/controllers/common/schema-builders.js.map +1 -1
  107. package/dist/esm/base/controllers/common/schemas.d.ts +2 -0
  108. package/dist/esm/base/controllers/common/schemas.js +2 -0
  109. package/dist/esm/base/controllers/common/schemas.js.map +1 -1
  110. package/dist/esm/base/controllers/common/types/context.d.ts +2 -0
  111. package/dist/esm/base/controllers/common/types/context.js.map +1 -1
  112. package/dist/esm/base/controllers/common/types/controller.d.ts +5 -1
  113. package/dist/esm/base/controllers/common/types/controller.js.map +1 -1
  114. package/dist/esm/base/controllers/common/types/route.d.ts +7 -1
  115. package/dist/esm/base/controllers/common/types/route.js.map +1 -1
  116. package/dist/esm/base/datasources/common/types.d.ts +5 -0
  117. package/dist/esm/base/datasources/common/types.js +1 -0
  118. package/dist/esm/base/datasources/common/types.js.map +1 -1
  119. package/dist/esm/base/events/common/constants.d.ts +4 -0
  120. package/dist/esm/base/events/common/constants.js +3 -0
  121. package/dist/esm/base/events/common/constants.js.map +1 -1
  122. package/dist/esm/base/events/common/types.d.ts +10 -2
  123. package/dist/esm/base/events/common/types.js.map +1 -1
  124. package/dist/esm/base/metadata/injectable.d.ts +46 -0
  125. package/dist/esm/base/metadata/injectable.js +46 -0
  126. package/dist/esm/base/metadata/injectable.js.map +1 -1
  127. package/dist/esm/base/metadata/persistents.d.ts +47 -2
  128. package/dist/esm/base/metadata/persistents.js +47 -2
  129. package/dist/esm/base/metadata/persistents.js.map +1 -1
  130. package/dist/esm/base/metadata/routes/controller.d.ts +17 -0
  131. package/dist/esm/base/metadata/routes/controller.js +17 -0
  132. package/dist/esm/base/metadata/routes/controller.js.map +1 -1
  133. package/dist/esm/base/middlewares/emoji-favicon/emoji-favicon.middleware.d.ts +1 -0
  134. package/dist/esm/base/middlewares/emoji-favicon/emoji-favicon.middleware.js +1 -0
  135. package/dist/esm/base/middlewares/emoji-favicon/emoji-favicon.middleware.js.map +1 -1
  136. package/dist/esm/base/middlewares/not-found/not-found.middleware.d.ts +1 -0
  137. package/dist/esm/base/middlewares/not-found/not-found.middleware.js +1 -0
  138. package/dist/esm/base/middlewares/not-found/not-found.middleware.js.map +1 -1
  139. package/dist/esm/base/mixins/common/types.d.ts +14 -1
  140. package/dist/esm/base/mixins/common/types.js.map +1 -1
  141. package/dist/esm/base/models/common/constants.d.ts +2 -0
  142. package/dist/esm/base/models/common/constants.js +1 -0
  143. package/dist/esm/base/models/common/constants.js.map +1 -1
  144. package/dist/esm/base/models/common/schemas.d.ts +1 -0
  145. package/dist/esm/base/models/common/schemas.js.map +1 -1
  146. package/dist/esm/base/models/common/types/id.d.ts +4 -0
  147. package/dist/esm/base/models/common/types/id.js.map +1 -1
  148. package/dist/esm/base/providers/base.d.ts +1 -0
  149. package/dist/esm/base/providers/base.js +1 -0
  150. package/dist/esm/base/providers/base.js.map +1 -1
  151. package/dist/esm/base/repositories/common/constants.d.ts +2 -2
  152. package/dist/esm/base/repositories/common/constants.js +2 -2
  153. package/dist/esm/base/repositories/common/constants.js.map +1 -1
  154. package/dist/esm/base/repositories/common/scope-through.d.ts +18 -1
  155. package/dist/esm/base/repositories/common/scope-through.js +18 -1
  156. package/dist/esm/base/repositories/common/scope-through.js.map +1 -1
  157. package/dist/esm/base/repositories/common/types/options.d.ts +10 -4
  158. package/dist/esm/base/repositories/common/types/options.js.map +1 -1
  159. package/dist/esm/base/repositories/query-schemas/index.d.ts +18 -3
  160. package/dist/esm/base/repositories/query-schemas/index.js +17 -1
  161. package/dist/esm/base/repositories/query-schemas/index.js.map +1 -1
  162. package/dist/esm/base/request-context/registry.d.ts +1 -0
  163. package/dist/esm/base/request-context/registry.js +1 -0
  164. package/dist/esm/base/request-context/registry.js.map +1 -1
  165. package/dist/esm/base/services/base.d.ts +1 -0
  166. package/dist/esm/base/services/base.js +1 -0
  167. package/dist/esm/base/services/base.js.map +1 -1
  168. package/dist/esm/base/services/common/types.d.ts +1 -0
  169. package/dist/esm/base/services/common/types.js.map +1 -1
  170. package/dist/esm/common/bindings.d.ts +1 -0
  171. package/dist/esm/common/bindings.js.map +1 -1
  172. package/dist/esm/common/error-codes.d.ts +2 -0
  173. package/dist/esm/common/error-codes.js.map +1 -1
  174. package/dist/esm/helpers/inversion/common/keys.d.ts +1 -0
  175. package/dist/esm/helpers/inversion/common/keys.js +1 -0
  176. package/dist/esm/helpers/inversion/common/keys.js.map +1 -1
  177. package/dist/esm/helpers/inversion/common/relation-builder.d.ts +1 -0
  178. package/dist/esm/helpers/inversion/common/relation-builder.js +1 -0
  179. package/dist/esm/helpers/inversion/common/relation-builder.js.map +1 -1
  180. package/dist/esm/helpers/inversion/common/types/artifact.d.ts +9 -2
  181. package/dist/esm/helpers/inversion/common/types/artifact.js.map +1 -1
  182. package/dist/esm/helpers/inversion/common/types/controller.d.ts +4 -0
  183. package/dist/esm/helpers/inversion/common/types/controller.js.map +1 -1
  184. package/dist/esm/helpers/inversion/common/types/model.d.ts +80 -8
  185. package/dist/esm/helpers/inversion/common/types/model.js.map +1 -1
  186. package/dist/esm/helpers/inversion/common/types/persistence.d.ts +9 -1
  187. package/dist/esm/helpers/inversion/common/types/persistence.js.map +1 -1
  188. package/dist/esm/helpers/inversion/container.d.ts +1 -0
  189. package/dist/esm/helpers/inversion/container.js +1 -0
  190. package/dist/esm/helpers/inversion/container.js.map +1 -1
  191. package/package.json +5 -5
@@ -51,10 +51,25 @@ export interface IJWTIssueClaims {
51
51
  subject?: string;
52
52
  jwtId?: string;
53
53
  }
54
+ /**
55
+ * Options of the JWS token service, which signs with the shared `jwtSecret`.
56
+ *
57
+ * `getTokenExpiresFn` is required. AES payload encryption is active only when `applicationSecret` is set.
58
+ */
54
59
  export interface IJWSTokenServiceOptions {
60
+ /**
61
+ * The JWS `alg` header.
62
+ *
63
+ * @default 'HS256'
64
+ */
55
65
  headerAlgorithm?: string;
56
66
  jwtSecret: string;
57
67
  getTokenExpiresFn: TGetTokenExpiresFn;
68
+ /**
69
+ * The AES algorithm of payload encryption, used when `applicationSecret` is set.
70
+ *
71
+ * @default 'aes-256-cbc'
72
+ */
58
73
  aesAlgorithm?: AESAlgorithmType;
59
74
  applicationSecret?: string;
60
75
  fieldCodecs?: IPayloadFieldCodec[];
@@ -63,10 +78,12 @@ export interface IJWSTokenServiceOptions {
63
78
  /** Claims stamped on every issued token. A configured value WINS over one supplied in the payload. */
64
79
  sign?: IJWTSignOptions;
65
80
  }
81
+ /** 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. */
66
82
  export interface IJWKSIssuerOptions {
67
83
  mode: typeof JWKSModes.ISSUER;
68
84
  algorithm: TJWKSAlgorithm;
69
85
  rest?: {
86
+ /** @default '/certs' */
70
87
  path: string;
71
88
  };
72
89
  keys: {
@@ -77,6 +94,11 @@ export interface IJWKSIssuerOptions {
77
94
  };
78
95
  kid: string;
79
96
  getTokenExpiresFn: TGetTokenExpiresFn;
97
+ /**
98
+ * The AES algorithm of payload encryption, used when `applicationSecret` is set.
99
+ *
100
+ * @default 'aes-256-cbc'
101
+ */
80
102
  aesAlgorithm?: AESAlgorithmType;
81
103
  applicationSecret?: string;
82
104
  fieldCodecs?: IPayloadFieldCodec[];
@@ -85,18 +107,36 @@ export interface IJWKSIssuerOptions {
85
107
  /** Claims stamped on every issued token. A configured value WINS over one supplied in the payload. */
86
108
  sign?: IJWTSignOptions;
87
109
  }
110
+ /** Options of a JWKS verifier, which checks tokens against the key set served at `jwksUrl`. */
88
111
  export interface IJWKSVerifierOptions {
89
112
  mode: typeof JWKSModes.VERIFIER;
90
113
  jwksUrl: string;
114
+ /**
115
+ * How long the fetched key set stays cached, in ms (12 hours).
116
+ *
117
+ * @default 43_200_000
118
+ */
91
119
  cacheTtlMs?: number;
120
+ /**
121
+ * Minimum wait between refetches of the key set, in ms (30 seconds).
122
+ *
123
+ * @default 30_000
124
+ */
92
125
  cooldownMs?: number;
126
+ /**
127
+ * The AES algorithm of payload encryption, used when `applicationSecret` is set.
128
+ *
129
+ * @default 'aes-256-cbc'
130
+ */
93
131
  aesAlgorithm?: AESAlgorithmType;
94
132
  applicationSecret?: string;
95
133
  fieldCodecs?: IPayloadFieldCodec[];
96
134
  /** Claim checks applied on verify. Unset means signature and time claims only. */
97
135
  verify?: IJWTVerifyOptions;
98
136
  }
137
+ /** Options of the JWKS token service, selected by `mode`. */
99
138
  export type TJWKSTokenServiceOptions = IJWKSIssuerOptions | IJWKSVerifierOptions;
139
+ /** Options of the JWT token service, selected by `standard` (`JWS` or `JWKS`). */
100
140
  export type TJWTTokenServiceOptions = {
101
141
  standard: typeof JOSEStandards.JWS;
102
142
  options: IJWSTokenServiceOptions;
@@ -123,6 +163,7 @@ export interface IJWTTokenPayload extends JWTPayload, IAuthUser {
123
163
  name?: string;
124
164
  [extra: string | symbol]: any;
125
165
  }
166
+ /** Converts one payload field, found under `key`, to a string and back around the AES envelope. */
126
167
  export interface IPayloadFieldCodec<T = unknown> {
127
168
  key: string;
128
169
  serialize(opts: {
@@ -132,5 +173,6 @@ export interface IPayloadFieldCodec<T = unknown> {
132
173
  raw: string;
133
174
  }): T;
134
175
  }
176
+ /** Returns the lifetime of a token to issue, in seconds from now. */
135
177
  export type TGetTokenExpiresFn = () => ValueOrPromise<number>;
136
178
  //# sourceMappingURL=jwt.d.ts.map
@@ -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 * Claim checks applied when VERIFYING a JWT. Field names and types mirror jose's `JWTVerifyOptions`\n * exactly, so this is a pass-through with no translation layer.\n *\n * Every field is optional and unset by default, which is today's behaviour: nothing is checked\n * beyond the signature and the time claims. In a fleet where every verifier points at the same\n * issuer JWKS, that means a token minted for one service is accepted verbatim 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 IJWTVerifyOptions {\n /** Expected `aud`. Setting it makes the claim required. Matching is jose's OVERLAP semantics, not equality: a token carrying `['a','b']` satisfies `audience: 'a'`. Enforce single-valued audiences at issue time if that matters. */\n audience?: string | string[];\n\n /** Expected `iss`. Setting it makes the claim required. */\n issuer?: string | string[];\n\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 means the accepted algorithm is decided entirely by what the JWKS serves. */\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/** Default `iss` / `aud` stamped on every issued token. Configured values are AUTHORITATIVE - see {@link IJWTIssueClaims}. */\nexport interface IJWTSignOptions {\n issuer?: string;\n audience?: string | 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 {@link IJWTSignOptions}; the payload never does.\n */\nexport interface IJWTIssueClaims {\n issuer?: string;\n audience?: string | string[];\n subject?: string;\n jwtId?: string;\n}\n\nexport interface IJWSTokenServiceOptions {\n headerAlgorithm?: string;\n jwtSecret: string;\n getTokenExpiresFn: TGetTokenExpiresFn;\n aesAlgorithm?: AESAlgorithmType;\n applicationSecret?: string;\n fieldCodecs?: IPayloadFieldCodec[];\n\n /** Claim checks applied on verify. Unset means signature and time claims only. */\n verify?: IJWTVerifyOptions;\n\n /** Claims stamped on every issued token. A configured value WINS over one supplied in the payload. */\n sign?: IJWTSignOptions;\n}\n\nexport interface IJWKSIssuerOptions {\n mode: typeof JWKSModes.ISSUER;\n algorithm: TJWKSAlgorithm;\n rest?: { path: string };\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 aesAlgorithm?: AESAlgorithmType;\n applicationSecret?: string;\n fieldCodecs?: IPayloadFieldCodec[];\n\n /** Claim checks applied on verify. Unset means signature and time claims only. */\n verify?: IJWTVerifyOptions;\n\n /** Claims stamped on every issued token. A configured value WINS over one supplied in the payload. */\n sign?: IJWTSignOptions;\n}\n\nexport interface IJWKSVerifierOptions {\n mode: typeof JWKSModes.VERIFIER;\n jwksUrl: string;\n cacheTtlMs?: number; // Default: 43_200_000 (12h)\n cooldownMs?: number; // Default: 30_000 (30s)\n aesAlgorithm?: AESAlgorithmType;\n applicationSecret?: string;\n fieldCodecs?: IPayloadFieldCodec[];\n\n /** Claim checks applied on verify. Unset means signature and time claims only. */\n verify?: IJWTVerifyOptions;\n}\n\nexport type TJWKSTokenServiceOptions = IJWKSIssuerOptions | IJWKSVerifierOptions;\n\nexport type TJWTTokenServiceOptions =\n | { standard: typeof JOSEStandards.JWS; options: IJWSTokenServiceOptions }\n | { standard: typeof JOSEStandards.JWKS; options: TJWKSTokenServiceOptions };\n\n/** One role as a token carries it. */\nexport type TJWTTokenRole = { id: IdType; identifier: string; priority: number };\n\n/**\n * What a token carries. `roles` may be absent: `generate` signs a payload without it as is, `verify`\n * returns it without `roles`, and authorization reads its roles as none. Check it before you read it.\n */\nexport interface IJWTTokenPayload extends JWTPayload, IAuthUser {\n userId: IdType;\n roles?: TJWTTokenRole[];\n\n clientId?: string;\n provider?: string;\n email?: string;\n name?: string;\n\n [extra: string | symbol]: any;\n}\n\nexport interface IPayloadFieldCodec<T = unknown> {\n key: string;\n serialize(opts: { value: T }): string;\n deserialize(opts: { raw: string }): T;\n}\n\nexport type TGetTokenExpiresFn = () => ValueOrPromise<number>;\n"]}
1
+ {"version":3,"file":"jwt.js","sourceRoot":"","sources":["../../../../../../../src/base/auth/authenticate/common/types/jwt.ts"],"names":[],"mappings":"","sourcesContent":["import type { IdType } from '@/base/models/common';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type { AESAlgorithmType } from '@venizia/ignis-helpers/core';\nimport type { JWTPayload } from 'jose';\nimport type {\n JOSEStandards,\n JWKSModes,\n TJWKSAlgorithm,\n TJWKSKeyDriver,\n TJWKSKeyFormat,\n} from '../constants';\nimport type { IAuthUser } from './strategy';\n\n/**\n * Claim checks applied when VERIFYING a JWT. Field names and types mirror jose's `JWTVerifyOptions`\n * exactly, so this is a pass-through with no translation layer.\n *\n * Every field is optional and unset by default, which is today's behaviour: nothing is checked\n * beyond the signature and the time claims. In a fleet where every verifier points at the same\n * issuer JWKS, that means a token minted for one service is accepted verbatim 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 IJWTVerifyOptions {\n /** Expected `aud`. Setting it makes the claim required. Matching is jose's OVERLAP semantics, not equality: a token carrying `['a','b']` satisfies `audience: 'a'`. Enforce single-valued audiences at issue time if that matters. */\n audience?: string | string[];\n\n /** Expected `iss`. Setting it makes the claim required. */\n issuer?: string | string[];\n\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 means the accepted algorithm is decided entirely by what the JWKS serves. */\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/** Default `iss` / `aud` stamped on every issued token. Configured values are AUTHORITATIVE - see {@link IJWTIssueClaims}. */\nexport interface IJWTSignOptions {\n issuer?: string;\n audience?: string | 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 {@link IJWTSignOptions}; 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 /**\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 /** Claim checks applied on verify. Unset means signature and time claims only. */\n verify?: IJWTVerifyOptions;\n\n /** Claims stamped on every issued token. A configured value WINS over one supplied in the payload. */\n sign?: IJWTSignOptions;\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 /**\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 /** Claim checks applied on verify. Unset means signature and time claims only. */\n verify?: IJWTVerifyOptions;\n\n /** Claims stamped on every issued token. A configured value WINS over one supplied in the payload. */\n sign?: IJWTSignOptions;\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 /**\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 /** Claim checks applied on verify. Unset means signature and time claims only. */\n verify?: IJWTVerifyOptions;\n}\n\n/** Options of the JWKS token service, selected by `mode`. */\nexport type TJWKSTokenServiceOptions = IJWKSIssuerOptions | IJWKSVerifierOptions;\n\n/** Options of the JWT token service, selected by `standard` (`JWS` or `JWKS`). */\nexport type TJWTTokenServiceOptions =\n | { standard: typeof JOSEStandards.JWS; options: IJWSTokenServiceOptions }\n | { standard: typeof JOSEStandards.JWKS; options: TJWKSTokenServiceOptions };\n\n/** One role as a token carries it. */\nexport type TJWTTokenRole = { id: IdType; identifier: string; priority: number };\n\n/**\n * What a token carries. `roles` may be absent: `generate` signs a payload without it as is, `verify`\n * returns it without `roles`, and authorization reads its roles as none. Check it before you read it.\n */\nexport interface IJWTTokenPayload extends JWTPayload, IAuthUser {\n userId: IdType;\n roles?: TJWTTokenRole[];\n\n clientId?: string;\n provider?: string;\n email?: string;\n name?: string;\n\n [extra: string | symbol]: any;\n}\n\n/** Converts one payload field, found under `key`, to a string and back around the AES envelope. */\nexport interface IPayloadFieldCodec<T = unknown> {\n key: string;\n serialize(opts: { value: T }): string;\n deserialize(opts: { raw: string }): T;\n}\n\n/** Returns the lifetime of a token to issue, in seconds from now. */\nexport type TGetTokenExpiresFn = () => ValueOrPromise<number>;\n"]}
@@ -1,4 +1,5 @@
1
1
  import type { TAnyObjectSchema } from '../../../../controllers/common/schema-builders.js';
2
+ /** Options for defining the auth controller. `serviceKey` is the container key of the `IAuthService` it calls; each `payload` entry overrides the request or response schema of one route. */
2
3
  export type TDefineAuthControllerOpts = {
3
4
  restPath?: string;
4
5
  serviceKey: string;
@@ -40,6 +41,7 @@ export type TDefineAuthControllerOpts = {
40
41
  };
41
42
  };
42
43
  };
44
+ /** REST options of the authenticate component: `controllerOpts` is required when `useAuthController` is `true`. */
43
45
  export type TAuthenticationRestOptions = {} & ({
44
46
  useAuthController?: false | undefined;
45
47
  } | {
@@ -1 +1 @@
1
- {"version":3,"file":"rest.js","sourceRoot":"","sources":["../../../../../../../src/base/auth/authenticate/common/types/rest.ts"],"names":[],"mappings":"","sourcesContent":["import type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\n\nexport type TDefineAuthControllerOpts = {\n restPath?: string;\n serviceKey: string;\n requireAuthenticatedSignUp?: boolean;\n payload?: {\n signIn?: {\n request: { schema: TAnyObjectSchema };\n response: { schema: TAnyObjectSchema };\n };\n signUp?: {\n request: { schema: TAnyObjectSchema };\n response: { schema: TAnyObjectSchema };\n };\n changePassword?: {\n request: { schema?: TAnyObjectSchema };\n response: { schema: TAnyObjectSchema };\n };\n refreshToken?: {\n response: { schema: TAnyObjectSchema };\n };\n getUserInformation?: {\n response: { schema: TAnyObjectSchema };\n };\n };\n};\n\nexport type TAuthenticationRestOptions = {} & (\n | { useAuthController?: false | undefined }\n | {\n useAuthController: true;\n controllerOpts: TDefineAuthControllerOpts;\n }\n);\n"]}
1
+ {"version":3,"file":"rest.js","sourceRoot":"","sources":["../../../../../../../src/base/auth/authenticate/common/types/rest.ts"],"names":[],"mappings":"","sourcesContent":["import type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\n\n/** Options for defining the auth controller. `serviceKey` is the container key of the `IAuthService` it calls; each `payload` entry overrides the request or response schema of one route. */\nexport type TDefineAuthControllerOpts = {\n restPath?: string;\n serviceKey: string;\n requireAuthenticatedSignUp?: boolean;\n payload?: {\n signIn?: {\n request: { schema: TAnyObjectSchema };\n response: { schema: TAnyObjectSchema };\n };\n signUp?: {\n request: { schema: TAnyObjectSchema };\n response: { schema: TAnyObjectSchema };\n };\n changePassword?: {\n request: { schema?: TAnyObjectSchema };\n response: { schema: TAnyObjectSchema };\n };\n refreshToken?: {\n response: { schema: TAnyObjectSchema };\n };\n getUserInformation?: {\n response: { schema: TAnyObjectSchema };\n };\n };\n};\n\n/** REST options of the authenticate component: `controllerOpts` is required when `useAuthController` is `true`. */\nexport type TAuthenticationRestOptions = {} & (\n | { useAuthController?: false | undefined }\n | {\n useAuthController: true;\n controllerOpts: TDefineAuthControllerOpts;\n }\n);\n"]}
@@ -49,12 +49,15 @@ export interface IServiceAuthOptions<E extends Env = Env> {
49
49
  * granting it per caller keeps the concession named and visible in config.
50
50
  */
51
51
  callers?: Record<string, TServiceCallerEntry>;
52
- /** Where the certs route is mounted. Defaults to `ServiceAssertion.DEFAULT_REST_PATH`. */
52
+ /** Where the certs route is mounted. */
53
53
  rest?: {
54
+ /** @default '/svc-certs' */
54
55
  path: string;
55
56
  };
56
57
  /**
57
58
  * How long the assertions this service MINTS stay valid. Only meaningful where `keys` is set.
59
+ *
60
+ * @default 60
58
61
  */
59
62
  signLifetimeSeconds?: number;
60
63
  /**
@@ -66,6 +69,8 @@ export interface IServiceAuthOptions<E extends Env = Env> {
66
69
  * assertion.
67
70
  *
68
71
  * Composes with `clockToleranceSeconds`: the real acceptance window is the sum of the two.
72
+ *
73
+ * @default 60
69
74
  */
70
75
  acceptMaxAgeSeconds?: number;
71
76
  /**
@@ -76,10 +81,14 @@ export interface IServiceAuthOptions<E extends Env = Env> {
76
81
  * callee accepting an `iat` 5s in its own future keeps accepting that token for the rest of the
77
82
  * window too. Measured at the defaults: 65s accepted on our clock, 70s of wall-clock life for a
78
83
  * capture minted by a caller running the full tolerance fast.
84
+ *
85
+ * @default 5
79
86
  */
80
87
  clockToleranceSeconds?: number;
81
88
  jwks?: {
89
+ /** @default 600_000 */
82
90
  cacheMaxAgeMs?: number;
91
+ /** @default 30_000 */
83
92
  cooldownMs?: number;
84
93
  };
85
94
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"service.js","sourceRoot":"","sources":["../../../../../../../src/base/auth/authenticate/common/types/service.ts"],"names":[],"mappings":"","sourcesContent":["import type { TContext } from '@/base/controllers/common/types';\nimport type { TNullable, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type { Env } from 'hono';\nimport type { JWTPayload } from 'jose';\nimport type { TJWKSKeyDriver, TJWKSKeyFormat } from '../constants';\nimport type { IAuthUser } from './strategy';\n\n/**\n * The request binding, following RFC 9449's `htm`/`htu`. A captured assertion cannot be replayed\n * against a different method or path.\n *\n * `htu` is the percent-ENCODED pathname on both ends. Compare it against\n * `new URL(context.req.url).pathname`, never `context.req.path` - Hono hands that one back DECODED,\n * so any route carrying a space or a non-ASCII slug would never match what the caller signed.\n */\nexport interface IServiceAssertionClaims extends JWTPayload {\n htm: string;\n htu: string;\n}\n\n/**\n * One entry in the caller allowlist: the JWKS url, or that url plus settings for this caller alone.\n */\nexport type TServiceCallerEntry =\n | string\n | {\n jwksUrl: string;\n /** Widens the accepted age for THIS caller only. Falls back to the service-wide setting. */\n acceptMaxAgeSeconds?: number;\n };\n\n/** Service-to-service authentication: an Ed25519 assertion per request, verified against the caller's JWKS. */\nexport interface IServiceAuthOptions<E extends Env = Env> {\n /** What this service calls itself: the `iss` it stamps, and the `aud` it demands. */\n name: string;\n\n /**\n * Present only on a service that CALLS OUT. Absent means verify-only, and no certs route is\n * mounted - which is the common case, since most services are called and never call.\n */\n keys?: {\n driver: TJWKSKeyDriver;\n format: TJWKSKeyFormat;\n /** PEM or JWK by `format`; content for the `text` driver, a path for `file`. */\n private: string;\n public: string;\n kid?: string;\n };\n\n /**\n * Caller name to its JWKS url. THIS IS ALSO THE ALLOWLIST - a name absent from the map cannot\n * call, and an empty map correctly allows nobody.\n *\n * The bare-string form is the common case. The object form exists to widen the accepted age for\n * ONE caller: a nightly batch may legitimately need more slack than an interactive service, and\n * granting it per caller keeps the concession named and visible in config.\n */\n callers?: Record<string, TServiceCallerEntry>;\n\n /** Where the certs route is mounted. Defaults to `ServiceAssertion.DEFAULT_REST_PATH`. */\n rest?: { path: string };\n\n /**\n * How long the assertions this service MINTS stay valid. Only meaningful where `keys` is set.\n */\n signLifetimeSeconds?: number;\n\n /**\n * The oldest assertion this service ACCEPTS, measured from `iat`.\n *\n * Deliberately separate from `signLifetimeSeconds`, and deliberately not requestable by the\n * caller. The caller already controls `exp` - it signs the token - so this is the only bound that\n * survives a compromised caller. A per-caller override belongs in {@link callers}, never in the\n * assertion.\n *\n * Composes with `clockToleranceSeconds`: the real acceptance window is the sum of the two.\n */\n acceptMaxAgeSeconds?: number;\n\n /**\n * Clock skew allowance. A SECURITY knob, not an operational one.\n *\n * Its job is the future case: two machines never agree to the second, and without it a caller one\n * second ahead is refused outright. But it also widens the REPLAY window second for second - a\n * callee accepting an `iat` 5s in its own future keeps accepting that token for the rest of the\n * window too. Measured at the defaults: 65s accepted on our clock, 70s of wall-clock life for a\n * capture minted by a caller running the full tolerance fast.\n */\n clockToleranceSeconds?: number;\n\n jwks?: { cacheMaxAgeMs?: number; cooldownMs?: number };\n\n /**\n * WHO a verified assertion acts as. The framework has already proven the caller; this only maps a\n * caller name onto an application principal. Return `null` to refuse a caller the allowlist\n * admits but the application does not recognise.\n */\n resolvePrincipal: (opts: {\n issuer: string;\n context: TContext<E, string>;\n }) => ValueOrPromise<TNullable<IAuthUser>>;\n}\n"]}
1
+ {"version":3,"file":"service.js","sourceRoot":"","sources":["../../../../../../../src/base/auth/authenticate/common/types/service.ts"],"names":[],"mappings":"","sourcesContent":["import type { TContext } from '@/base/controllers/common/types';\nimport type { TNullable, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type { Env } from 'hono';\nimport type { JWTPayload } from 'jose';\nimport type { TJWKSKeyDriver, TJWKSKeyFormat } from '../constants';\nimport type { IAuthUser } from './strategy';\n\n/**\n * The request binding, following RFC 9449's `htm`/`htu`. A captured assertion cannot be replayed\n * against a different method or path.\n *\n * `htu` is the percent-ENCODED pathname on both ends. Compare it against\n * `new URL(context.req.url).pathname`, never `context.req.path` - Hono hands that one back DECODED,\n * so any route carrying a space or a non-ASCII slug would never match what the caller signed.\n */\nexport interface IServiceAssertionClaims extends JWTPayload {\n htm: string;\n htu: string;\n}\n\n/**\n * One entry in the caller allowlist: the JWKS url, or that url plus settings for this caller alone.\n */\nexport type TServiceCallerEntry =\n | string\n | {\n jwksUrl: string;\n /** Widens the accepted age for THIS caller only. Falls back to the service-wide setting. */\n acceptMaxAgeSeconds?: number;\n };\n\n/** Service-to-service authentication: an Ed25519 assertion per request, verified against the caller's JWKS. */\nexport interface IServiceAuthOptions<E extends Env = Env> {\n /** What this service calls itself: the `iss` it stamps, and the `aud` it demands. */\n name: string;\n\n /**\n * Present only on a service that CALLS OUT. Absent means verify-only, and no certs route is\n * mounted - which is the common case, since most services are called and never call.\n */\n keys?: {\n driver: TJWKSKeyDriver;\n format: TJWKSKeyFormat;\n /** PEM or JWK by `format`; content for the `text` driver, a path for `file`. */\n private: string;\n public: string;\n kid?: string;\n };\n\n /**\n * Caller name to its JWKS url. THIS IS ALSO THE ALLOWLIST - a name absent from the map cannot\n * call, and an empty map correctly allows nobody.\n *\n * The bare-string form is the common case. The object form exists to widen the accepted age for\n * ONE caller: a nightly batch may legitimately need more slack than an interactive service, and\n * granting it per caller keeps the concession named and visible in config.\n */\n callers?: Record<string, TServiceCallerEntry>;\n\n /** Where the certs route is mounted. */\n rest?: {\n /** @default '/svc-certs' */\n path: string;\n };\n\n /**\n * How long the assertions this service MINTS stay valid. Only meaningful where `keys` is set.\n *\n * @default 60\n */\n signLifetimeSeconds?: number;\n\n /**\n * The oldest assertion this service ACCEPTS, measured from `iat`.\n *\n * Deliberately separate from `signLifetimeSeconds`, and deliberately not requestable by the\n * caller. The caller already controls `exp` - it signs the token - so this is the only bound that\n * survives a compromised caller. A per-caller override belongs in {@link callers}, never in the\n * assertion.\n *\n * Composes with `clockToleranceSeconds`: the real acceptance window is the sum of the two.\n *\n * @default 60\n */\n acceptMaxAgeSeconds?: number;\n\n /**\n * Clock skew allowance. A SECURITY knob, not an operational one.\n *\n * Its job is the future case: two machines never agree to the second, and without it a caller one\n * second ahead is refused outright. But it also widens the REPLAY window second for second - a\n * callee accepting an `iat` 5s in its own future keeps accepting that token for the rest of the\n * window too. Measured at the defaults: 65s accepted on our clock, 70s of wall-clock life for a\n * capture minted by a caller running the full tolerance fast.\n *\n * @default 5\n */\n clockToleranceSeconds?: number;\n\n jwks?: {\n /** @default 600_000 */\n cacheMaxAgeMs?: number;\n\n /** @default 30_000 */\n cooldownMs?: number;\n };\n\n /**\n * WHO a verified assertion acts as. The framework has already proven the caller; this only maps a\n * caller name onto an application principal. Return `null` to refuse a caller the allowlist\n * admits but the application does not recognise.\n */\n resolvePrincipal: (opts: {\n issuer: string;\n context: TContext<E, string>;\n }) => ValueOrPromise<TNullable<IAuthUser>>;\n}\n"]}
@@ -4,18 +4,23 @@ import type { AnyObject } from '@venizia/ignis-helpers/common';
4
4
  import type { Env, MiddlewareHandler } from 'hono';
5
5
  import type { TChangePasswordRequest, TSignInRequest, TSignUpRequest } from '../../../models/requests/index.js';
6
6
  import type { TAuthMode } from '../constants/index.js';
7
+ /** The authenticated identity a strategy returns and the request context stores. Carries at least `userId`. */
7
8
  export interface IAuthUser {
8
9
  userId: IdType;
9
10
  [extra: string | symbol]: any;
10
11
  }
12
+ /** A strategy that authenticates a request. `name` is the name it is registered under; `authenticate` returns the user or throws. */
11
13
  export interface IAuthenticationStrategy<E extends Env = Env> {
12
14
  name: string;
13
15
  authenticate(context: TContext<E, string>): Promise<IAuthUser>;
14
16
  }
17
+ /** Builds the authentication middleware for the listed strategy names. */
15
18
  export type TAuthenticateFn<RouteEnv extends Env = Env> = (opts: {
16
19
  strategies: string[];
20
+ /** @default 'any' */
17
21
  mode?: TAuthMode;
18
22
  }) => MiddlewareHandler<RouteEnv>;
23
+ /** The service behind the auth controller routes. `getUserInformation` and `refreshToken` are optional. The type parameters set each route's request and response types. */
19
24
  export interface IAuthService<E extends Env = Env, SIRQ extends TSignInRequest = TSignInRequest, SIRS = AnyObject, SURQ extends TSignUpRequest = TSignUpRequest, SURS = AnyObject, CPRQ extends TChangePasswordRequest = TChangePasswordRequest, CPRS = AnyObject, UIRQ = AnyObject, UIRS = AnyObject, RTRS = AnyObject> {
20
25
  signIn(context: TContext<E>, opts: SIRQ): Promise<SIRS>;
21
26
  signUp(context: TContext<E>, opts: SURQ): Promise<SURS>;
@@ -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 { AnyObject } from '@venizia/ignis-helpers/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\nexport interface IAuthUser {\n userId: IdType;\n [extra: string | symbol]: any;\n}\n\nexport interface IAuthenticationStrategy<E extends Env = Env> {\n name: string;\n authenticate(context: TContext<E, string>): Promise<IAuthUser>;\n}\n\nexport type TAuthenticateFn<RouteEnv extends Env = Env> = (opts: {\n strategies: string[];\n mode?: TAuthMode;\n}) => MiddlewareHandler<RouteEnv>;\n\nexport interface IAuthService<\n E extends Env = Env,\n // SignIn types\n SIRQ extends TSignInRequest = TSignInRequest,\n SIRS = AnyObject,\n // SignUp types\n SURQ extends TSignUpRequest = TSignUpRequest,\n SURS = AnyObject,\n // ChangePassword types\n CPRQ extends TChangePasswordRequest = TChangePasswordRequest,\n CPRS = AnyObject,\n // UserInformation types\n UIRQ = AnyObject,\n UIRS = AnyObject,\n // RefreshToken types\n RTRS = AnyObject,\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"]}
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 { AnyObject } from '@venizia/ignis-helpers/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]: any;\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 = AnyObject,\n // SignUp types\n SURQ extends TSignUpRequest = TSignUpRequest,\n SURS = AnyObject,\n // ChangePassword types\n CPRQ extends TChangePasswordRequest = TChangePasswordRequest,\n CPRS = AnyObject,\n // UserInformation types\n UIRQ = AnyObject,\n UIRS = AnyObject,\n // RefreshToken types\n RTRS = AnyObject,\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"]}
@@ -1,5 +1,6 @@
1
1
  import type { Env } from 'hono';
2
2
  import type { TAuthMode } from '../common/index.js';
3
+ /** Route middleware factory: `authenticate({ strategies, mode })` authenticates a request with the named strategies, `mode` defaulting to `any`. */
3
4
  export declare const authenticate: (opts: {
4
5
  strategies: string[];
5
6
  mode?: TAuthMode;
@@ -1,6 +1,7 @@
1
1
  import { AuthenticationProvider } from '../providers/index.js';
2
2
  const authenticationProvider = new AuthenticationProvider();
3
3
  const authenticateFn = authenticationProvider.value();
4
+ /** Route middleware factory: `authenticate({ strategies, mode })` authenticates a request with the named strategies, `mode` defaulting to `any`. */
4
5
  export const authenticate = (opts) => {
5
6
  return authenticateFn(opts);
6
7
  };
@@ -1 +1 @@
1
- {"version":3,"file":"authenticate.middleware.js","sourceRoot":"","sources":["../../../../../../src/base/auth/authenticate/middlewares/authenticate.middleware.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAEtD,MAAM,sBAAsB,GAAG,IAAI,sBAAsB,EAAO,CAAC;AACjE,MAAM,cAAc,GAAG,sBAAsB,CAAC,KAAK,EAAE,CAAC;AAEtD,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,IAAgD,EAAE,EAAE;IAC/E,OAAO,cAAc,CAAC,IAAI,CAAC,CAAC;AAC9B,CAAC,CAAC","sourcesContent":["import type { Env } from 'hono';\nimport type { TAuthMode } from '../common';\nimport { AuthenticationProvider } from '../providers';\n\nconst authenticationProvider = new AuthenticationProvider<Env>();\nconst authenticateFn = authenticationProvider.value();\n\nexport const authenticate = (opts: { strategies: string[]; mode?: TAuthMode }) => {\n return authenticateFn(opts);\n};\n"]}
1
+ {"version":3,"file":"authenticate.middleware.js","sourceRoot":"","sources":["../../../../../../src/base/auth/authenticate/middlewares/authenticate.middleware.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAEtD,MAAM,sBAAsB,GAAG,IAAI,sBAAsB,EAAO,CAAC;AACjE,MAAM,cAAc,GAAG,sBAAsB,CAAC,KAAK,EAAE,CAAC;AAEtD,oJAAoJ;AACpJ,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,IAAgD,EAAE,EAAE;IAC/E,OAAO,cAAc,CAAC,IAAI,CAAC,CAAC;AAC9B,CAAC,CAAC","sourcesContent":["import type { Env } from 'hono';\nimport type { TAuthMode } from '../common';\nimport { AuthenticationProvider } from '../providers';\n\nconst authenticationProvider = new AuthenticationProvider<Env>();\nconst authenticateFn = authenticationProvider.value();\n\n/** Route middleware factory: `authenticate({ strategies, mode })` authenticates a request with the named strategies, `mode` defaulting to `any`. */\nexport const authenticate = (opts: { strategies: string[]; mode?: TAuthMode }) => {\n return authenticateFn(opts);\n};\n"]}
@@ -2,6 +2,11 @@ import { BaseHelper } from '@venizia/ignis-helpers/core';
2
2
  import type { IProvider } from '@venizia/ignis-inversion';
3
3
  import type { Env } from 'hono';
4
4
  import type { TAuthenticateFn } from '../common/index.js';
5
+ /**
6
+ * Provides the `authenticate` middleware factory. Strategies resolve from `AuthenticationStrategyRegistry`.
7
+ *
8
+ * The middleware skips a request flagged `Authentication.SKIP_AUTHENTICATION` or already holding a current user. On success it stores the user and its audit user id in the request context.
9
+ */
5
10
  export declare class AuthenticationProvider<RouteEnv extends Env = Env> extends BaseHelper implements IProvider<TAuthenticateFn<RouteEnv>> {
6
11
  constructor();
7
12
  value(): TAuthenticateFn<RouteEnv>;
@@ -3,6 +3,11 @@ import { HTTP } from '@venizia/ignis-helpers/common';
3
3
  import { createMiddleware } from 'hono/factory';
4
4
  import { Authentication, AuthenticationErrors, AuthenticationModes } from '../common/index.js';
5
5
  import { AuthenticationStrategyRegistry } from '../strategies/strategy-registry.js';
6
+ /**
7
+ * Provides the `authenticate` middleware factory. Strategies resolve from `AuthenticationStrategyRegistry`.
8
+ *
9
+ * The middleware skips a request flagged `Authentication.SKIP_AUTHENTICATION` or already holding a current user. On success it stores the user and its audit user id in the request context.
10
+ */
6
11
  export class AuthenticationProvider extends BaseHelper {
7
12
  constructor() {
8
13
  super({ scope: AuthenticationProvider.name });
@@ -1 +1 @@
1
- {"version":3,"file":"authentication.provider.js","sourceRoot":"","sources":["../../../../../../src/base/auth/authenticate/providers/authentication.provider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAGrD,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAEhD,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AACtF,OAAO,EAAE,8BAA8B,EAAE,MAAM,iCAAiC,CAAC;AAEjF,MAAM,OAAO,sBACX,SAAQ,UAAU;IAGlB;QACE,KAAK,CAAC,EAAE,KAAK,EAAE,sBAAsB,CAAC,IAAI,EAAE,CAAC,CAAC;IAChD,CAAC;IAED,KAAK;QACH,OAAO,CAAC,IAAI,EAAE,EAAE;YACd,OAAO,IAAI,CAAC,4BAA4B,CAAC,IAAI,CAAC,CAAC;QACjD,CAAC,CAAC;IACJ,CAAC;IAEO,4BAA4B,CAAC,IAAgD;QACnF,MAAM,EAAE,UAAU,EAAE,IAAI,GAAG,mBAAmB,CA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,QAAQ,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QAErD,sGAAsG;QACtG,IAAI,QAAQ,GAAqB,IAAI,CAAC;QAEtC,KAAK,MAAM,YAAY,IAAI,UAAU,EAAE,CAAC;YACtC,MAAM,QAAQ,GAAG,QAAQ,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;YAClE,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;YAElD,QAAQ,KAAK,IAAI,CAAC;QACpB,CAAC;QAED,IAAI,QAAQ,EAAE,MAAM,EAAE,CAAC;YACrB,IAAI,CAAC,cAAc,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC;iBAC7B,KAAK,CACJ,+DAA+D,EAC/D,QAAQ,EACR,QAAQ,EAAE,MAAM,CACjB,CAAC;YACJ,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAE,oBAAoB,CAAC,eAAe,EAAE,CAAC,CAAC;QAClE,CAAC;QAED,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC;IAEO,cAAc,CAAC,IAA4C;QACjE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QAC/B,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;QAE/C,IAAI,IAAI,EAAE,MAAM,EAAE,CAAC;YACjB,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,aAAa,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QACzD,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { TContext } from '@/base/controllers/common/types';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { IProvider } from '@venizia/ignis-inversion';\nimport type { Env } from 'hono';\nimport { createMiddleware } from 'hono/factory';\nimport type { IAuthUser, TAuthenticateFn, TAuthMode } from '../common';\nimport { Authentication, AuthenticationErrors, AuthenticationModes } from '../common';\nimport { AuthenticationStrategyRegistry } from '../strategies/strategy-registry';\n\nexport class AuthenticationProvider<RouteEnv extends Env = Env>\n extends BaseHelper\n implements IProvider<TAuthenticateFn<RouteEnv>>\n{\n constructor() {\n super({ scope: AuthenticationProvider.name });\n }\n\n value(): TAuthenticateFn<RouteEnv> {\n return (opts) => {\n return this.createAuthenticateMiddleware(opts);\n };\n }\n\n private createAuthenticateMiddleware(opts: { strategies: string[]; mode?: TAuthMode }) {\n const { strategies, mode = AuthenticationModes.ANY } = opts;\n const registry = AuthenticationStrategyRegistry.getInstance();\n\n return createMiddleware(async (context, next) => {\n const isSkipAuthenticate = context.get(Authentication.SKIP_AUTHENTICATION);\n\n if (isSkipAuthenticate) {\n this.logger\n .for(this.createAuthenticateMiddleware.name)\n .debug('SKIP checking authentication | path: %s', context.req.path);\n\n return next();\n }\n\n const isAuthenticated = context.get(Authentication.CURRENT_USER);\n\n if (isAuthenticated) {\n return next();\n }\n\n switch (mode) {\n case AuthenticationModes.ANY: {\n await this.executeAnyMode({\n context: context as TContext,\n strategies,\n registry,\n next,\n });\n\n return;\n }\n case AuthenticationModes.ALL: {\n await this.executeAllMode({\n context: context as TContext,\n strategies,\n registry,\n next,\n });\n\n return;\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `Invalid authentication mode | mode: ${mode}`,\n });\n }\n }\n });\n }\n\n private async executeAnyMode(opts: {\n context: TContext;\n strategies: string[];\n registry: AuthenticationStrategyRegistry;\n next: () => Promise<void>;\n }) {\n const { context, strategies, registry, next } = opts;\n\n // The first strategy's failure is the primary one - kept so the 401 carries WHY, instead of only which strategies were tried.\n let primaryFailure: unknown;\n\n for (const strategyName of strategies) {\n try {\n const strategy = registry.resolveStrategy({ name: strategyName });\n const user = await strategy.authenticate(context);\n this.setCurrentUser({ context, user });\n break;\n } catch (error) {\n primaryFailure ??= error;\n this.logger\n .for(this.executeAnyMode.name)\n .debug('Strategy %s failed, trying next... | Error: %s', strategyName, error);\n }\n }\n\n const currentUser = context.get(Authentication.CURRENT_USER);\n\n if (!currentUser) {\n throw getError({\n error: AuthenticationErrors.FAILED,\n message: `Authentication failed. Tried strategies: ${strategies.join(', ')}`,\n logLevel: 'warn',\n cause: primaryFailure,\n });\n }\n\n await next();\n }\n\n private async executeAllMode(opts: {\n context: TContext;\n strategies: string[];\n registry: AuthenticationStrategyRegistry;\n next: () => Promise<void>;\n }) {\n const { context, strategies, registry, next } = opts;\n\n // Use the first strategy's user as the identity source - all must succeed but first wins for identity\n let authUser: IAuthUser | null = null;\n\n for (const strategyName of strategies) {\n const strategy = registry.resolveStrategy({ name: strategyName });\n const user = await strategy.authenticate(context);\n\n authUser ??= user;\n }\n\n if (authUser?.userId) {\n this.setCurrentUser({ context, user: authUser });\n } else {\n this.logger\n .for(this.executeAllMode.name)\n .error(\n 'Failed to identify authenticated user | user: %j | userId: %s',\n authUser,\n authUser?.userId,\n );\n throw getError({ error: AuthenticationErrors.USER_UNRESOLVED });\n }\n\n return next();\n }\n\n private setCurrentUser(opts: { context: TContext; user: IAuthUser }) {\n const { context, user } = opts;\n context.set(Authentication.CURRENT_USER, user);\n\n if (user?.userId) {\n context.set(Authentication.AUDIT_USER_ID, user.userId);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"authentication.provider.js","sourceRoot":"","sources":["../../../../../../src/base/auth/authenticate/providers/authentication.provider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAGrD,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAEhD,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,m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B,CAAC;IAEO,cAAc,CAAC,IAA4C;QACjE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QAC/B,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;QAE/C,IAAI,IAAI,EAAE,MAAM,EAAE,CAAC;YACjB,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,aAAa,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QACzD,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { TContext } from '@/base/controllers/common/types';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { IProvider } from '@venizia/ignis-inversion';\nimport type { Env } from 'hono';\nimport { createMiddleware } from 'hono/factory';\nimport type { IAuthUser, TAuthenticateFn, TAuthMode } from '../common';\nimport { Authentication, AuthenticationErrors, AuthenticationModes } from '../common';\nimport { AuthenticationStrategyRegistry } from '../strategies/strategy-registry';\n\n/**\n * Provides the `authenticate` middleware factory. Strategies resolve from `AuthenticationStrategyRegistry`.\n *\n * The middleware skips a request flagged `Authentication.SKIP_AUTHENTICATION` or already holding a current user. On success it stores the user and its audit user id in the request context.\n */\nexport class AuthenticationProvider<RouteEnv extends Env = Env>\n extends BaseHelper\n implements IProvider<TAuthenticateFn<RouteEnv>>\n{\n constructor() {\n super({ scope: AuthenticationProvider.name });\n }\n\n value(): TAuthenticateFn<RouteEnv> {\n return (opts) => {\n return this.createAuthenticateMiddleware(opts);\n };\n }\n\n private createAuthenticateMiddleware(opts: { strategies: string[]; mode?: TAuthMode }) {\n const { strategies, mode = AuthenticationModes.ANY } = opts;\n const registry = AuthenticationStrategyRegistry.getInstance();\n\n return createMiddleware(async (context, next) => {\n const isSkipAuthenticate = context.get(Authentication.SKIP_AUTHENTICATION);\n\n if (isSkipAuthenticate) {\n this.logger\n .for(this.createAuthenticateMiddleware.name)\n .debug('SKIP checking authentication | path: %s', context.req.path);\n\n return next();\n }\n\n const isAuthenticated = context.get(Authentication.CURRENT_USER);\n\n if (isAuthenticated) {\n return next();\n }\n\n switch (mode) {\n case AuthenticationModes.ANY: {\n await this.executeAnyMode({\n context: context as TContext,\n strategies,\n registry,\n next,\n });\n\n return;\n }\n case AuthenticationModes.ALL: {\n await this.executeAllMode({\n context: context as TContext,\n strategies,\n registry,\n next,\n });\n\n return;\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `Invalid authentication mode | mode: ${mode}`,\n });\n }\n }\n });\n }\n\n private async executeAnyMode(opts: {\n context: TContext;\n strategies: string[];\n registry: AuthenticationStrategyRegistry;\n next: () => Promise<void>;\n }) {\n const { context, strategies, registry, next } = opts;\n\n // The first strategy's failure is the primary one - kept so the 401 carries WHY, instead of only which strategies were tried.\n let primaryFailure: unknown;\n\n for (const strategyName of strategies) {\n try {\n const strategy = registry.resolveStrategy({ name: strategyName });\n const user = await strategy.authenticate(context);\n this.setCurrentUser({ context, user });\n break;\n } catch (error) {\n primaryFailure ??= error;\n this.logger\n .for(this.executeAnyMode.name)\n .debug('Strategy %s failed, trying next... | Error: %s', strategyName, error);\n }\n }\n\n const currentUser = context.get(Authentication.CURRENT_USER);\n\n if (!currentUser) {\n throw getError({\n error: AuthenticationErrors.FAILED,\n message: `Authentication failed. Tried strategies: ${strategies.join(', ')}`,\n logLevel: 'warn',\n cause: primaryFailure,\n });\n }\n\n await next();\n }\n\n private async executeAllMode(opts: {\n context: TContext;\n strategies: string[];\n registry: AuthenticationStrategyRegistry;\n next: () => Promise<void>;\n }) {\n const { context, strategies, registry, next } = opts;\n\n // Use the first strategy's user as the identity source - all must succeed but first wins for identity\n let authUser: IAuthUser | null = null;\n\n for (const strategyName of strategies) {\n const strategy = registry.resolveStrategy({ name: strategyName });\n const user = await strategy.authenticate(context);\n\n authUser ??= user;\n }\n\n if (authUser?.userId) {\n this.setCurrentUser({ context, user: authUser });\n } else {\n this.logger\n .for(this.executeAllMode.name)\n .error(\n 'Failed to identify authenticated user | user: %j | userId: %s',\n authUser,\n authUser?.userId,\n );\n throw getError({ error: AuthenticationErrors.USER_UNRESOLVED });\n }\n\n return next();\n }\n\n private setCurrentUser(opts: { context: TContext; user: IAuthUser }) {\n const { context, user } = opts;\n context.set(Authentication.CURRENT_USER, user);\n\n if (user?.userId) {\n context.set(Authentication.AUDIT_USER_ID, user.userId);\n }\n }\n}\n"]}
@@ -2,6 +2,7 @@ import type { Container } from '../../../../helpers/inversion/container.js';
2
2
  import type { TClass } from '@venizia/ignis-helpers/common';
3
3
  import { AbstractAuthRegistry } from '../../base/index.js';
4
4
  import type { IAuthenticationStrategy } from '../common/index.js';
5
+ /** Registry of authentication strategies by name. Use `getInstance()` for the shared one; register application strategies before controllers are bound. */
5
6
  export declare class AuthenticationStrategyRegistry extends AbstractAuthRegistry<IAuthenticationStrategy> {
6
7
  static readonly SINGLETON_REAL_KEY = "authentication-strategy-registry";
7
8
  constructor();
@@ -2,6 +2,7 @@ import { SingletonRealm } from '../../../../helpers/singleton-realm.js';
2
2
  import { getError } from '@venizia/ignis-helpers/core';
3
3
  import { AbstractAuthRegistry } from '../../base/index.js';
4
4
  import { Authentication } from '../common/index.js';
5
+ /** Registry of authentication strategies by name. Use `getInstance()` for the shared one; register application strategies before controllers are bound. */
5
6
  export class AuthenticationStrategyRegistry extends AbstractAuthRegistry {
6
7
  static { this.SINGLETON_REAL_KEY = 'authentication-strategy-registry'; }
7
8
  constructor() {
@@ -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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AC,IAAyC;QACxD,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,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\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.define` 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"]}
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,CAAC;IACxD,CAAC;IAED,MAAM,CAAC,WAAW;QAChB,OAAO,cAAc,CAAC,OAAO,CAAC;YAC5B,GAAG,EAAE,8BAA8B,CAAC,kBAAkB;YACtD,MAAM,EAAE,GAAG,EAAE,CAAC,IAAI,8BAA8B,EAAE;SACnD,CAAC,CAAC;IACL,CAAC;IAES,gBAAgB;QACxB,OAAO,cAAc,CAAC,uBAAuB,CAAC;IAChD,CAAC;IAED,QAAQ,CAAC,IAGR;QACC,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,I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AM,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.define` 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"]}
@@ -3,6 +3,7 @@ import { BaseHelper } from '@venizia/ignis-helpers/core';
3
3
  import { type TNullable } from '@venizia/ignis-helpers/common';
4
4
  import { type TAuthorizationAction, type TAuthorizationDecision, type TGrantIntent, type TPlannedGrantRow } from '../common/index.js';
5
5
  import { type TPolicyDomainInput } from './policy.builder.js';
6
+ /** Pure planner for grant rows: validates and shapes grant intents (tier or per-operation) into `PolicyDefinition` rows. Persisting and the operation catalog stay with the caller. */
6
7
  export declare class GrantBuilder extends BaseHelper {
7
8
  static readonly SINGLETON_REAL_KEY = "grant-builder";
8
9
  /** Tiers a caller may ask for; `custom` is an encoding marker and is never a valid intent. */
@@ -15,6 +15,7 @@ const expandCoveredActions = (opts) => {
15
15
  }
16
16
  return grew;
17
17
  };
18
+ /** Pure planner for grant rows: validates and shapes grant intents (tier or per-operation) into `PolicyDefinition` rows. Persisting and the operation catalog stay with the caller. */
18
19
  export class GrantBuilder extends BaseHelper {
19
20
  static { this.SINGLETON_REAL_KEY = 'grant-builder'; }
20
21
  /** Tiers a caller may ask for; `custom` is an encoding marker and is never a valid intent. */
@@ -1 +1 @@
1
- {"version":3,"file":"grant.builder.js","sourceRoot":"","sources":["../../../../../../src/base/auth/authorize/builders/grant.builder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEnE,OAAO,EACL,oBAAoB,EACpB,sBAAsB,GAKvB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,0BAA0B,EAA2B,MAAM,kBAAkB,CAAC;AAEvF,2IAA2I;AAC3I,MAAM,oBAAoB,GAAG,CAAC,IAA8B,EAAW,EAAE;IACvE,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IACzB,IAAI,IAAI,GAAG,KAAK,CAAC;IAEjB,KAAK,MAAM,IAAI,IAAI,oBAAoB,CAAC,OAAO,EAAE,CAAC;QAChD,IAAI,C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AI,CAAC,OAAO,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;gBACzE,SAAS;YACX,CAAC;YAED,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;YAEzB,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;gBAC7B,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YAC3B,CAAC;QACH,CAAC;IACH,CAAC","sourcesContent":["import { SingletonRealm } from '@/helpers/singleton-realm';\nimport type { IdType } from '@/base';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { type TNullable } from '@venizia/ignis-helpers/common';\nimport {\n AuthorizationActions,\n AuthorizationDecisions,\n type TAuthorizationAction,\n type TAuthorizationDecision,\n type TGrantIntent,\n type TPlannedGrantRow,\n} from '../common';\nimport { AuthorizationPolicyBuilder, type TPolicyDomainInput } from './policy.builder';\n\n/** One closure pass over the action lattice: adds every child reachable from an already-covered parent, reporting whether the set grew. */\nconst expandCoveredActions = (opts: { covered: Set<string> }): boolean => {\n const { covered } = opts;\n let grew = false;\n\n for (const edge of AuthorizationActions.LATTICE) {\n if (!covered.has(edge.parent) || covered.has(edge.child)) {\n continue;\n }\n\n covered.add(edge.child);\n grew = true;\n }\n\n return grew;\n};\n\nexport class GrantBuilder extends BaseHelper {\n static readonly SINGLETON_REAL_KEY = 'grant-builder';\n\n /** Tiers a caller may ask for; `custom` is an encoding marker and is never a valid intent. */\n private static readonly PLANNABLE_TIERS = new Set<string>([\n AuthorizationActions.READ,\n AuthorizationActions.WRITE,\n AuthorizationActions.EXECUTE,\n AuthorizationActions.MANAGE,\n ]);\n\n /** Tried after `manage`; disjoint from each other, since an operation has one catalogued action. */\n private static readonly NARROW_TIERS: ReadonlyArray<TAuthorizationAction> = [\n AuthorizationActions.READ,\n AuthorizationActions.WRITE,\n AuthorizationActions.EXECUTE,\n ];\n\n constructor() {\n super({ scope: GrantBuilder.name });\n }\n\n static getInstance() {\n return SingletonRealm.resolve({\n key: GrantBuilder.SINGLETON_REAL_KEY,\n create: () => new GrantBuilder(),\n });\n }\n\n decodeMetadata<MetadataType = unknown>(opts: { metadata: MetadataType }) {\n if (typeof opts.metadata !== 'string') {\n return opts.metadata;\n }\n\n try {\n return JSON.parse(opts.metadata);\n } catch (error) {\n this.logger\n .for(this.decodeMetadata.name)\n .error('Failed to parse metadata | Error: %s', error);\n\n return null;\n }\n }\n\n /** Read `{ ops }` off a grant row's metadata, or null when the shape is unusable. Callers treat null as a defect to log and skip - never as an empty grant. */\n parseCustomGrantMetadata(opts: { metadata: unknown }): { ops: string[] } | null {\n const decoded = this.decodeMetadata(opts);\n\n if (typeof decoded !== 'object' || decoded === null || Array.isArray(decoded)) {\n return null;\n }\n\n const ops = (decoded as { ops?: unknown }).ops;\n\n if (!Array.isArray(ops) || ops.length === 0) {\n return null;\n }\n\n const seen = new Set<string>();\n const unique: string[] = [];\n\n for (const op of ops) {\n if (typeof op !== 'string' || op.length === 0) {\n return null;\n }\n\n if (!seen.has(op)) {\n seen.add(op);\n unique.push(op);\n }\n }\n\n return { ops: unique };\n }\n\n /** Split operation names into those present in the catalog for `subject` and those that are not. Pure - the caller supplies the catalog slice; the adapter re-runs this independently at read time. */\n validateCustomGrantOps(opts: {\n ops: string[];\n subject: string;\n catalog: Array<{ subject: string; method: string }>;\n }): { valid: string[]; unknown: string[] } {\n const known = new Set<string>();\n\n for (const entry of opts.catalog) {\n if (entry.subject === opts.subject) {\n known.add(entry.method);\n }\n }\n\n const valid: string[] = [];\n const unknown: string[] = [];\n\n for (const op of opts.ops) {\n if (known.has(op)) {\n valid.push(op);\n continue;\n }\n\n unknown.push(op);\n }\n\n return { valid, unknown };\n }\n\n /** Actions a tier confers, derived from LATTICE rather than hardcoded so the two cannot drift. */\n actionsCoveredBy(opts: { tier: TAuthorizationAction }): Set<string> {\n const covered = new Set<string>([opts.tier]);\n\n let grew = true;\n\n while (grew) {\n grew = expandCoveredActions({ covered });\n }\n\n return covered;\n }\n\n /** Decide which rows express an intent: a custom row is a last resort, so as much of the selection as possible collapses into tier grants first. `exact` disables collapsing when the caller means these operations and no future ones. Pure - the caller supplies the catalog and persists. */\n planGrant(opts: {\n subject: { type: string; id: IdType };\n resource: { type: string; id: IdType; subject: string };\n intent: TGrantIntent;\n catalog: Array<{ subject: string; method: string; code: string; action: string }>;\n domain?: TNullable<TPolicyDomainInput>;\n effect?: TAuthorizationDecision;\n supportsCustomMetadata?: boolean;\n exact?: boolean;\n }): TPlannedGrantRow[] {\n const effect = opts.effect ?? AuthorizationDecisions.ALLOW;\n const domain = opts.domain ?? null;\n\n if ('tier' in opts.intent) {\n if (!GrantBuilder.PLANNABLE_TIERS.has(opts.intent.tier)) {\n throw getError({\n message: `[planGrant] Invalid tier: ${opts.intent.tier} | Valids: [${[...GrantBuilder.PLANNABLE_TIERS].join(', ')}]`,\n });\n }\n\n return [\n AuthorizationPolicyBuilder.grant({\n subject: opts.subject,\n permission: { type: opts.resource.type, id: opts.resource.id },\n action: opts.intent.tier,\n domain,\n effect,\n }),\n ];\n }\n\n const seen = new Set<string>();\n const ops: string[] = [];\n\n for (const op of opts.intent.ops) {\n if (seen.has(op)) {\n continue;\n }\n\n seen.add(op);\n ops.push(op);\n }\n\n if (!ops.length) {\n throw getError({ message: '[planGrant] intent.ops must not be empty.' });\n }\n\n const subjectCatalog = opts.catalog.filter((entry) => entry.subject === opts.resource.subject);\n const byMethod = new Map(subjectCatalog.map((entry) => [entry.method, entry]));\n\n const unknown = ops.filter((op) => !byMethod.has(op));\n\n if (unknown.length) {\n throw getError({\n message: `[planGrant] Unknown operations for resource \"${opts.resource.subject}\": ${unknown.join(', ')}`,\n });\n }\n\n const tierRow = (tier: TAuthorizationAction) =>\n AuthorizationPolicyBuilder.grant({\n subject: opts.subject,\n permission: { type: opts.resource.type, id: opts.resource.id },\n action: tier,\n domain,\n effect,\n });\n\n const rows: TPlannedGrantRow[] = [];\n const remaining = new Set(ops);\n\n if (opts.exact !== true) {\n this.collapseRemainingIntoTiers({ subjectCatalog, remaining, rows, tierRow });\n }\n\n const leftover = ops.filter((op) => remaining.has(op));\n\n if (!leftover.length) {\n return rows;\n }\n\n const isPerOperationGrant = leftover.length === 1 || opts.supportsCustomMetadata === false;\n\n if (!isPerOperationGrant) {\n rows.push(\n AuthorizationPolicyBuilder.customGrant({\n subject: opts.subject,\n permission: { type: opts.resource.type, id: opts.resource.id },\n ops: leftover,\n domain,\n effect,\n }),\n );\n\n return rows;\n }\n\n for (const op of leftover) {\n const entry = byMethod.get(op);\n\n if (!entry) {\n throw getError({ message: `[planGrant] No catalog entry for operation \"${op}\".` });\n }\n\n rows.push(\n AuthorizationPolicyBuilder.grant({\n subject: opts.subject,\n permission: { type: opts.resource.type, id: entry.code },\n action: entry.action,\n domain,\n effect,\n }),\n );\n }\n\n return rows;\n }\n\n /** Collapse `remaining` into the fewest tier grants, mutating `remaining` and appending to `rows`. */\n protected collapseRemainingIntoTiers(opts: {\n subjectCatalog: Array<{ subject: string; method: string; code: string; action: string }>;\n remaining: Set<string>;\n rows: TPlannedGrantRow[];\n tierRow: (tier: TAuthorizationAction) => TPlannedGrantRow;\n }): void {\n const { subjectCatalog, remaining, rows, tierRow } = opts;\n\n // manage equals read+write+execute only when the subject has at least one operation in EACH narrow tier; otherwise manage also covers a future tier, which is more than the narrow tiers confer today.\n const spansAllNarrowTiers = GrantBuilder.NARROW_TIERS.every((tier) => {\n const covered = this.actionsCoveredBy({ tier });\n\n return subjectCatalog.some((entry) => covered.has(entry.action));\n });\n\n const manageCovered = this.actionsCoveredBy({ tier: AuthorizationActions.MANAGE });\n const manageOps = subjectCatalog\n .filter((entry) => manageCovered.has(entry.action))\n .map((entry) => entry.method);\n\n if (\n spansAllNarrowTiers &&\n manageOps.length &&\n manageOps.every((method) => remaining.has(method))\n ) {\n rows.push(tierRow(AuthorizationActions.MANAGE));\n\n for (const method of manageOps) {\n remaining.delete(method);\n }\n\n return;\n }\n\n for (const tier of GrantBuilder.NARROW_TIERS) {\n const covered = this.actionsCoveredBy({ tier });\n const methods = subjectCatalog\n .filter((entry) => covered.has(entry.action))\n .map((entry) => entry.method);\n\n if (!methods.length || !methods.every((method) => remaining.has(method))) {\n continue;\n }\n\n rows.push(tierRow(tier));\n\n for (const method of methods) {\n remaining.delete(method);\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"grant.builder.js","sourceRoot":"","sources":["../../../../../../src/base/auth/authorize/builders/grant.builder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEnE,OAAO,EACL,oBAAoB,EACpB,sBAAsB,GAKvB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,0BAA0B,EAA2B,MAAM,kBAAkB,CAAC;AAEvF,2IAA2I;AAC3I,MAAM,oBAAoB,GAAG,CAAC,IAA8B,EAAW,EAAE;IACvE,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IACzB,IAAI,IAAI,GAAG,KAAK,CAAC;IAEjB,KAAK,MAAM,IAAI,IAAI,oBAAoB,CAAC,OAAO,EAAE,CAAC;QAChD,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACzD,SAAS;QACX,CAAC;QAED,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxB,IAAI,GAAG,IAAI,CAAC;IACd,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AAEF,uLAAuL;AACvL,MAAM,OAAO,YAAa,SAAQ,UAAU;aAC1B,uBAAkB,GAAG,eAAe,CAAC;IA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CAAC;IACH,CAAC","sourcesContent":["import { SingletonRealm } from '@/helpers/singleton-realm';\nimport type { IdType } from '@/base';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { type TNullable } from '@venizia/ignis-helpers/common';\nimport {\n AuthorizationActions,\n AuthorizationDecisions,\n type TAuthorizationAction,\n type TAuthorizationDecision,\n type TGrantIntent,\n type TPlannedGrantRow,\n} from '../common';\nimport { AuthorizationPolicyBuilder, type TPolicyDomainInput } from './policy.builder';\n\n/** One closure pass over the action lattice: adds every child reachable from an already-covered parent, reporting whether the set grew. */\nconst expandCoveredActions = (opts: { covered: Set<string> }): boolean => {\n const { covered } = opts;\n let grew = false;\n\n for (const edge of AuthorizationActions.LATTICE) {\n if (!covered.has(edge.parent) || covered.has(edge.child)) {\n continue;\n }\n\n covered.add(edge.child);\n grew = true;\n }\n\n return grew;\n};\n\n/** Pure planner for grant rows: validates and shapes grant intents (tier or per-operation) into `PolicyDefinition` rows. Persisting and the operation catalog stay with the caller. */\nexport class GrantBuilder extends BaseHelper {\n static readonly SINGLETON_REAL_KEY = 'grant-builder';\n\n /** Tiers a caller may ask for; `custom` is an encoding marker and is never a valid intent. */\n private static readonly PLANNABLE_TIERS = new Set<string>([\n AuthorizationActions.READ,\n AuthorizationActions.WRITE,\n AuthorizationActions.EXECUTE,\n AuthorizationActions.MANAGE,\n ]);\n\n /** Tried after `manage`; disjoint from each other, since an operation has one catalogued action. */\n private static readonly NARROW_TIERS: ReadonlyArray<TAuthorizationAction> = [\n AuthorizationActions.READ,\n AuthorizationActions.WRITE,\n AuthorizationActions.EXECUTE,\n ];\n\n constructor() {\n super({ scope: GrantBuilder.name });\n }\n\n static getInstance() {\n return SingletonRealm.resolve({\n key: GrantBuilder.SINGLETON_REAL_KEY,\n create: () => new GrantBuilder(),\n });\n }\n\n decodeMetadata<MetadataType = unknown>(opts: { metadata: MetadataType }) {\n if (typeof opts.metadata !== 'string') {\n return opts.metadata;\n }\n\n try {\n return JSON.parse(opts.metadata);\n } catch (error) {\n this.logger\n .for(this.decodeMetadata.name)\n .error('Failed to parse metadata | Error: %s', error);\n\n return null;\n }\n }\n\n /** Read `{ ops }` off a grant row's metadata, or null when the shape is unusable. Callers treat null as a defect to log and skip - never as an empty grant. */\n parseCustomGrantMetadata(opts: { metadata: unknown }): { ops: string[] } | null {\n const decoded = this.decodeMetadata(opts);\n\n if (typeof decoded !== 'object' || decoded === null || Array.isArray(decoded)) {\n return null;\n }\n\n const ops = (decoded as { ops?: unknown }).ops;\n\n if (!Array.isArray(ops) || ops.length === 0) {\n return null;\n }\n\n const seen = new Set<string>();\n const unique: string[] = [];\n\n for (const op of ops) {\n if (typeof op !== 'string' || op.length === 0) {\n return null;\n }\n\n if (!seen.has(op)) {\n seen.add(op);\n unique.push(op);\n }\n }\n\n return { ops: unique };\n }\n\n /** Split operation names into those present in the catalog for `subject` and those that are not. Pure - the caller supplies the catalog slice; the adapter re-runs this independently at read time. */\n validateCustomGrantOps(opts: {\n ops: string[];\n subject: string;\n catalog: Array<{ subject: string; method: string }>;\n }): { valid: string[]; unknown: string[] } {\n const known = new Set<string>();\n\n for (const entry of opts.catalog) {\n if (entry.subject === opts.subject) {\n known.add(entry.method);\n }\n }\n\n const valid: string[] = [];\n const unknown: string[] = [];\n\n for (const op of opts.ops) {\n if (known.has(op)) {\n valid.push(op);\n continue;\n }\n\n unknown.push(op);\n }\n\n return { valid, unknown };\n }\n\n /** Actions a tier confers, derived from LATTICE rather than hardcoded so the two cannot drift. */\n actionsCoveredBy(opts: { tier: TAuthorizationAction }): Set<string> {\n const covered = new Set<string>([opts.tier]);\n\n let grew = true;\n\n while (grew) {\n grew = expandCoveredActions({ covered });\n }\n\n return covered;\n }\n\n /** Decide which rows express an intent: a custom row is a last resort, so as much of the selection as possible collapses into tier grants first. `exact` disables collapsing when the caller means these operations and no future ones. Pure - the caller supplies the catalog and persists. */\n planGrant(opts: {\n subject: { type: string; id: IdType };\n resource: { type: string; id: IdType; subject: string };\n intent: TGrantIntent;\n catalog: Array<{ subject: string; method: string; code: string; action: string }>;\n domain?: TNullable<TPolicyDomainInput>;\n effect?: TAuthorizationDecision;\n supportsCustomMetadata?: boolean;\n exact?: boolean;\n }): TPlannedGrantRow[] {\n const effect = opts.effect ?? AuthorizationDecisions.ALLOW;\n const domain = opts.domain ?? null;\n\n if ('tier' in opts.intent) {\n if (!GrantBuilder.PLANNABLE_TIERS.has(opts.intent.tier)) {\n throw getError({\n message: `[planGrant] Invalid tier: ${opts.intent.tier} | Valids: [${[...GrantBuilder.PLANNABLE_TIERS].join(', ')}]`,\n });\n }\n\n return [\n AuthorizationPolicyBuilder.grant({\n subject: opts.subject,\n permission: { type: opts.resource.type, id: opts.resource.id },\n action: opts.intent.tier,\n domain,\n effect,\n }),\n ];\n }\n\n const seen = new Set<string>();\n const ops: string[] = [];\n\n for (const op of opts.intent.ops) {\n if (seen.has(op)) {\n continue;\n }\n\n seen.add(op);\n ops.push(op);\n }\n\n if (!ops.length) {\n throw getError({ message: '[planGrant] intent.ops must not be empty.' });\n }\n\n const subjectCatalog = opts.catalog.filter((entry) => entry.subject === opts.resource.subject);\n const byMethod = new Map(subjectCatalog.map((entry) => [entry.method, entry]));\n\n const unknown = ops.filter((op) => !byMethod.has(op));\n\n if (unknown.length) {\n throw getError({\n message: `[planGrant] Unknown operations for resource \"${opts.resource.subject}\": ${unknown.join(', ')}`,\n });\n }\n\n const tierRow = (tier: TAuthorizationAction) =>\n AuthorizationPolicyBuilder.grant({\n subject: opts.subject,\n permission: { type: opts.resource.type, id: opts.resource.id },\n action: tier,\n domain,\n effect,\n });\n\n const rows: TPlannedGrantRow[] = [];\n const remaining = new Set(ops);\n\n if (opts.exact !== true) {\n this.collapseRemainingIntoTiers({ subjectCatalog, remaining, rows, tierRow });\n }\n\n const leftover = ops.filter((op) => remaining.has(op));\n\n if (!leftover.length) {\n return rows;\n }\n\n const isPerOperationGrant = leftover.length === 1 || opts.supportsCustomMetadata === false;\n\n if (!isPerOperationGrant) {\n rows.push(\n AuthorizationPolicyBuilder.customGrant({\n subject: opts.subject,\n permission: { type: opts.resource.type, id: opts.resource.id },\n ops: leftover,\n domain,\n effect,\n }),\n );\n\n return rows;\n }\n\n for (const op of leftover) {\n const entry = byMethod.get(op);\n\n if (!entry) {\n throw getError({ message: `[planGrant] No catalog entry for operation \"${op}\".` });\n }\n\n rows.push(\n AuthorizationPolicyBuilder.grant({\n subject: opts.subject,\n permission: { type: opts.resource.type, id: entry.code },\n action: entry.action,\n domain,\n effect,\n }),\n );\n }\n\n return rows;\n }\n\n /** Collapse `remaining` into the fewest tier grants, mutating `remaining` and appending to `rows`. */\n protected collapseRemainingIntoTiers(opts: {\n subjectCatalog: Array<{ subject: string; method: string; code: string; action: string }>;\n remaining: Set<string>;\n rows: TPlannedGrantRow[];\n tierRow: (tier: TAuthorizationAction) => TPlannedGrantRow;\n }): void {\n const { subjectCatalog, remaining, rows, tierRow } = opts;\n\n // manage equals read+write+execute only when the subject has at least one operation in EACH narrow tier; otherwise manage also covers a future tier, which is more than the narrow tiers confer today.\n const spansAllNarrowTiers = GrantBuilder.NARROW_TIERS.every((tier) => {\n const covered = this.actionsCoveredBy({ tier });\n\n return subjectCatalog.some((entry) => covered.has(entry.action));\n });\n\n const manageCovered = this.actionsCoveredBy({ tier: AuthorizationActions.MANAGE });\n const manageOps = subjectCatalog\n .filter((entry) => manageCovered.has(entry.action))\n .map((entry) => entry.method);\n\n if (\n spansAllNarrowTiers &&\n manageOps.length &&\n manageOps.every((method) => remaining.has(method))\n ) {\n rows.push(tierRow(AuthorizationActions.MANAGE));\n\n for (const method of manageOps) {\n remaining.delete(method);\n }\n\n return;\n }\n\n for (const tier of GrantBuilder.NARROW_TIERS) {\n const covered = this.actionsCoveredBy({ tier });\n const methods = subjectCatalog\n .filter((entry) => covered.has(entry.action))\n .map((entry) => entry.method);\n\n if (!methods.length || !methods.every((method) => remaining.has(method))) {\n continue;\n }\n\n rows.push(tierRow(tier));\n\n for (const method of methods) {\n remaining.delete(method);\n }\n }\n }\n}\n"]}
@@ -40,6 +40,7 @@ type TBuilderCustomGrantRow = Omit<TBuilderGrantRow, 'action'> & {
40
40
  action: typeof AuthorizationActions.CUSTOM;
41
41
  metadata: TSubsetGrantMetadata;
42
42
  };
43
+ /** Static factories for the `PolicyDefinition` rows behind each edge kind in `AuthorizationPolicyVariants` (grant, role assignment, domain join, inheritance). Returns plain row objects; nothing is persisted. */
43
44
  export declare class AuthorizationPolicyBuilder {
44
45
  static readonly ACTION_PRINCIPAL = "Action";
45
46
  /** A domain as the two columns that store it. `ANY_MEMBER` normalises to null - admitting both spellings would leave one state reachable two ways. */
@@ -1,4 +1,5 @@
1
1
  import { AuthorizationActions, AuthorizationDomainScopes, AuthorizationPolicyVariants, } from '../common/constants/index.js';
2
+ /** Static factories for the `PolicyDefinition` rows behind each edge kind in `AuthorizationPolicyVariants` (grant, role assignment, domain join, inheritance). Returns plain row objects; nothing is persisted. */
2
3
  export class AuthorizationPolicyBuilder {
3
4
  static { this.ACTION_PRINCIPAL = 'Action'; }
4
5
  /** A domain as the two columns that store it. `ANY_MEMBER` normalises to null - admitting both spellings would leave one state reachable two ways. */