@venizia/ignis 0.4.8-0 → 0.4.8-10

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 (275) hide show
  1. package/README.md +7 -14
  2. package/dist/esm/base/applications/base.d.ts +19 -0
  3. package/dist/esm/base/applications/base.js +19 -0
  4. package/dist/esm/base/applications/base.js.map +1 -1
  5. package/dist/esm/base/applications/boot-steps.d.ts +1 -0
  6. package/dist/esm/base/applications/boot-steps.js.map +1 -1
  7. package/dist/esm/base/applications/common/types.d.ts +21 -4
  8. package/dist/esm/base/applications/common/types.js.map +1 -1
  9. package/dist/esm/base/applications/server.d.ts +12 -0
  10. package/dist/esm/base/applications/server.js +11 -0
  11. package/dist/esm/base/applications/server.js.map +1 -1
  12. package/dist/esm/base/metadata/request-context.d.ts +1 -0
  13. package/dist/esm/base/metadata/request-context.js +1 -0
  14. package/dist/esm/base/metadata/request-context.js.map +1 -1
  15. package/dist/esm/base/middlewares/request-spy/request-spy.middleware.d.ts +1 -0
  16. package/dist/esm/base/middlewares/request-spy/request-spy.middleware.js +9 -2
  17. package/dist/esm/base/middlewares/request-spy/request-spy.middleware.js.map +1 -1
  18. package/dist/esm/components/api-reference/common/constants.d.ts +1 -0
  19. package/dist/esm/components/api-reference/common/constants.js +1 -0
  20. package/dist/esm/components/api-reference/common/constants.js.map +1 -1
  21. package/dist/esm/components/api-reference/common/keys.d.ts +1 -0
  22. package/dist/esm/components/api-reference/common/keys.js +1 -0
  23. package/dist/esm/components/api-reference/common/keys.js.map +1 -1
  24. package/dist/esm/components/api-reference/common/types.d.ts +18 -1
  25. package/dist/esm/components/api-reference/common/types.js.map +1 -1
  26. package/dist/esm/components/api-reference/component.d.ts +14 -0
  27. package/dist/esm/components/api-reference/component.js +14 -0
  28. package/dist/esm/components/api-reference/component.js.map +1 -1
  29. package/dist/esm/components/api-reference/ui/factory.d.ts +1 -0
  30. package/dist/esm/components/api-reference/ui/factory.js +1 -0
  31. package/dist/esm/components/api-reference/ui/factory.js.map +1 -1
  32. package/dist/esm/components/api-reference/ui/scalar.d.ts +1 -0
  33. package/dist/esm/components/api-reference/ui/scalar.js +1 -0
  34. package/dist/esm/components/api-reference/ui/scalar.js.map +1 -1
  35. package/dist/esm/components/api-reference/ui/swagger.d.ts +1 -0
  36. package/dist/esm/components/api-reference/ui/swagger.js +1 -0
  37. package/dist/esm/components/api-reference/ui/swagger.js.map +1 -1
  38. package/dist/esm/components/auth/authenticate/component.d.ts +1 -0
  39. package/dist/esm/components/auth/authenticate/component.js +38 -1
  40. package/dist/esm/components/auth/authenticate/component.js.map +1 -1
  41. package/dist/esm/components/auth/authenticate/controllers/factory.d.ts +2 -0
  42. package/dist/esm/components/auth/authenticate/controllers/factory.js +1 -0
  43. package/dist/esm/components/auth/authenticate/controllers/factory.js.map +1 -1
  44. package/dist/esm/components/auth/authenticate/controllers/jwks/controller.d.ts +1 -0
  45. package/dist/esm/components/auth/authenticate/controllers/jwks/controller.js +1 -0
  46. package/dist/esm/components/auth/authenticate/controllers/jwks/controller.js.map +1 -1
  47. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.d.ts +56 -5
  48. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js +115 -11
  49. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js.map +1 -1
  50. package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.d.ts +1 -0
  51. package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.js +3 -2
  52. package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.js.map +1 -1
  53. package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.d.ts +1 -0
  54. package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.js +11 -3
  55. package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.js.map +1 -1
  56. package/dist/esm/components/auth/authenticate/services/bearer/jws.service.d.ts +11 -0
  57. package/dist/esm/components/auth/authenticate/services/bearer/jws.service.js +25 -3
  58. package/dist/esm/components/auth/authenticate/services/bearer/jws.service.js.map +1 -1
  59. package/dist/esm/components/auth/authenticate/services/index.d.ts +1 -0
  60. package/dist/esm/components/auth/authenticate/services/index.js +1 -0
  61. package/dist/esm/components/auth/authenticate/services/index.js.map +1 -1
  62. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.d.ts +42 -0
  63. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js +162 -0
  64. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js.map +1 -0
  65. package/dist/esm/components/auth/authenticate/services/service/verifier.service.js +7 -1
  66. package/dist/esm/components/auth/authenticate/services/service/verifier.service.js.map +1 -1
  67. package/dist/esm/components/auth/authenticate/strategies/jwks/issuer.d.ts +1 -0
  68. package/dist/esm/components/auth/authenticate/strategies/jwks/issuer.js +1 -0
  69. package/dist/esm/components/auth/authenticate/strategies/jwks/issuer.js.map +1 -1
  70. package/dist/esm/components/auth/authenticate/strategies/jwks/verifier.d.ts +1 -0
  71. package/dist/esm/components/auth/authenticate/strategies/jwks/verifier.js +1 -0
  72. package/dist/esm/components/auth/authenticate/strategies/jwks/verifier.js.map +1 -1
  73. package/dist/esm/components/auth/authenticate/strategies/jws.strategy.d.ts +1 -0
  74. package/dist/esm/components/auth/authenticate/strategies/jws.strategy.js +1 -0
  75. package/dist/esm/components/auth/authenticate/strategies/jws.strategy.js.map +1 -1
  76. package/dist/esm/components/auth/authenticate/strategies/service.strategy.js +2 -4
  77. package/dist/esm/components/auth/authenticate/strategies/service.strategy.js.map +1 -1
  78. package/dist/esm/components/auth/authorize/adapters/base-filtered.d.ts +1 -1
  79. package/dist/esm/components/auth/authorize/adapters/base-filtered.js +3 -2
  80. package/dist/esm/components/auth/authorize/adapters/base-filtered.js.map +1 -1
  81. package/dist/esm/components/auth/authorize/adapters/common/types.d.ts +2 -0
  82. package/dist/esm/components/auth/authorize/adapters/common/types.js.map +1 -1
  83. package/dist/esm/components/auth/authorize/adapters/connector.d.ts +2 -2
  84. package/dist/esm/components/auth/authorize/adapters/connector.js +3 -2
  85. package/dist/esm/components/auth/authorize/adapters/connector.js.map +1 -1
  86. package/dist/esm/components/auth/authorize/adapters/custom-grant-expander.js +1 -1
  87. package/dist/esm/components/auth/authorize/adapters/custom-grant-expander.js.map +1 -1
  88. package/dist/esm/components/auth/authorize/adapters/scoped-casbin/common/types.d.ts +2 -0
  89. package/dist/esm/components/auth/authorize/adapters/scoped-casbin/common/types.js.map +1 -1
  90. package/dist/esm/components/auth/authorize/adapters/scoped-casbin/policy-edges.d.ts +1 -0
  91. package/dist/esm/components/auth/authorize/adapters/scoped-casbin/policy-edges.js +1 -0
  92. package/dist/esm/components/auth/authorize/adapters/scoped-casbin/policy-edges.js.map +1 -1
  93. package/dist/esm/components/auth/authorize/component.d.ts +1 -0
  94. package/dist/esm/components/auth/authorize/component.js +1 -0
  95. package/dist/esm/components/auth/authorize/component.js.map +1 -1
  96. package/dist/esm/components/auth/authorize/enforcers/casbin.enforcer.d.ts +1 -0
  97. package/dist/esm/components/auth/authorize/enforcers/casbin.enforcer.js +1 -0
  98. package/dist/esm/components/auth/authorize/enforcers/casbin.enforcer.js.map +1 -1
  99. package/dist/esm/components/auth/models/entities/columns.d.ts +1 -0
  100. package/dist/esm/components/auth/models/entities/columns.js.map +1 -1
  101. package/dist/esm/components/auth/models/entities/permission.model.d.ts +2 -0
  102. package/dist/esm/components/auth/models/entities/permission.model.js.map +1 -1
  103. package/dist/esm/components/auth/models/entities/policy-definition.model.d.ts +1 -0
  104. package/dist/esm/components/auth/models/entities/policy-definition.model.js.map +1 -1
  105. package/dist/esm/components/controller/grpc/common/types.d.ts +2 -0
  106. package/dist/esm/components/controller/grpc/common/types.js +1 -0
  107. package/dist/esm/components/controller/grpc/common/types.js.map +1 -1
  108. package/dist/esm/components/controller/grpc/grpc.component.d.ts +1 -0
  109. package/dist/esm/components/controller/grpc/grpc.component.js +1 -0
  110. package/dist/esm/components/controller/grpc/grpc.component.js.map +1 -1
  111. package/dist/esm/components/health-check/common/constants.d.ts +1 -0
  112. package/dist/esm/components/health-check/common/constants.js +1 -0
  113. package/dist/esm/components/health-check/common/constants.js.map +1 -1
  114. package/dist/esm/components/health-check/common/keys.d.ts +1 -0
  115. package/dist/esm/components/health-check/common/keys.js +1 -0
  116. package/dist/esm/components/health-check/common/keys.js.map +1 -1
  117. package/dist/esm/components/health-check/common/rest-paths.d.ts +1 -0
  118. package/dist/esm/components/health-check/common/rest-paths.js +1 -0
  119. package/dist/esm/components/health-check/common/rest-paths.js.map +1 -1
  120. package/dist/esm/components/health-check/common/types.d.ts +24 -3
  121. package/dist/esm/components/health-check/common/types.js.map +1 -1
  122. package/dist/esm/components/health-check/component.d.ts +15 -0
  123. package/dist/esm/components/health-check/component.js +15 -0
  124. package/dist/esm/components/health-check/component.js.map +1 -1
  125. package/dist/esm/components/health-check/controller.d.ts +1 -0
  126. package/dist/esm/components/health-check/controller.js +1 -0
  127. package/dist/esm/components/health-check/controller.js.map +1 -1
  128. package/dist/esm/components/health-check/reporter.js +2 -2
  129. package/dist/esm/components/health-check/reporter.js.map +1 -1
  130. package/dist/esm/components/index.d.ts +1 -0
  131. package/dist/esm/components/index.js +1 -0
  132. package/dist/esm/components/index.js.map +1 -1
  133. package/dist/esm/components/mail/common/constants.d.ts +6 -0
  134. package/dist/esm/components/mail/common/constants.js +5 -0
  135. package/dist/esm/components/mail/common/constants.js.map +1 -1
  136. package/dist/esm/components/mail/common/keys.d.ts +1 -0
  137. package/dist/esm/components/mail/common/keys.js +1 -0
  138. package/dist/esm/components/mail/common/keys.js.map +1 -1
  139. package/dist/esm/components/mail/common/types/message.d.ts +10 -0
  140. package/dist/esm/components/mail/common/types/message.js.map +1 -1
  141. package/dist/esm/components/mail/common/types/options.d.ts +22 -1
  142. package/dist/esm/components/mail/common/types/options.js.map +1 -1
  143. package/dist/esm/components/mail/common/types/queue.d.ts +7 -0
  144. package/dist/esm/components/mail/common/types/queue.js.map +1 -1
  145. package/dist/esm/components/mail/common/types/template.d.ts +2 -0
  146. package/dist/esm/components/mail/common/types/template.js.map +1 -1
  147. package/dist/esm/components/mail/common/types/verification.d.ts +6 -0
  148. package/dist/esm/components/mail/common/types/verification.js.map +1 -1
  149. package/dist/esm/components/mail/component.d.ts +1 -0
  150. package/dist/esm/components/mail/component.js +1 -0
  151. package/dist/esm/components/mail/component.js.map +1 -1
  152. package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.d.ts +1 -0
  153. package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js +1 -0
  154. package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js.map +1 -1
  155. package/dist/esm/components/mail/helpers/executors/direct-executor.helper.d.ts +1 -0
  156. package/dist/esm/components/mail/helpers/executors/direct-executor.helper.js +1 -0
  157. package/dist/esm/components/mail/helpers/executors/direct-executor.helper.js.map +1 -1
  158. package/dist/esm/components/mail/helpers/executors/internal-queue-executor.helper.d.ts +1 -0
  159. package/dist/esm/components/mail/helpers/executors/internal-queue-executor.helper.js +1 -0
  160. package/dist/esm/components/mail/helpers/executors/internal-queue-executor.helper.js.map +1 -1
  161. package/dist/esm/components/mail/helpers/transporters/amazon-ses-transporter.helper.d.ts +1 -0
  162. package/dist/esm/components/mail/helpers/transporters/amazon-ses-transporter.helper.js +1 -0
  163. package/dist/esm/components/mail/helpers/transporters/amazon-ses-transporter.helper.js.map +1 -1
  164. package/dist/esm/components/mail/helpers/transporters/mailgun-transporter.helper.d.ts +1 -0
  165. package/dist/esm/components/mail/helpers/transporters/mailgun-transporter.helper.js +1 -0
  166. package/dist/esm/components/mail/helpers/transporters/mailgun-transporter.helper.js.map +1 -1
  167. package/dist/esm/components/mail/helpers/transporters/nodemail-transporter.helper.d.ts +1 -0
  168. package/dist/esm/components/mail/helpers/transporters/nodemail-transporter.helper.js +1 -0
  169. package/dist/esm/components/mail/helpers/transporters/nodemail-transporter.helper.js.map +1 -1
  170. package/dist/esm/components/mail/providers/mail-queue-executor.provider.d.ts +2 -0
  171. package/dist/esm/components/mail/providers/mail-queue-executor.provider.js +1 -0
  172. package/dist/esm/components/mail/providers/mail-queue-executor.provider.js.map +1 -1
  173. package/dist/esm/components/mail/providers/mail-transporter.provider.d.ts +2 -0
  174. package/dist/esm/components/mail/providers/mail-transporter.provider.js +1 -0
  175. package/dist/esm/components/mail/providers/mail-transporter.provider.js.map +1 -1
  176. package/dist/esm/components/mail/services/generators/numeric-code.d.ts +1 -5
  177. package/dist/esm/components/mail/services/generators/numeric-code.js +3 -30
  178. package/dist/esm/components/mail/services/generators/numeric-code.js.map +1 -1
  179. package/dist/esm/components/mail/services/generators/random-token.d.ts +4 -0
  180. package/dist/esm/components/mail/services/generators/random-token.js +9 -5
  181. package/dist/esm/components/mail/services/generators/random-token.js.map +1 -1
  182. package/dist/esm/components/mail/services/generators/verification-data.d.ts +1 -0
  183. package/dist/esm/components/mail/services/generators/verification-data.js +1 -0
  184. package/dist/esm/components/mail/services/generators/verification-data.js.map +1 -1
  185. package/dist/esm/components/mail/services/mail.service.d.ts +1 -0
  186. package/dist/esm/components/mail/services/mail.service.js +1 -0
  187. package/dist/esm/components/mail/services/mail.service.js.map +1 -1
  188. package/dist/esm/components/mail/services/template.service.d.ts +1 -0
  189. package/dist/esm/components/mail/services/template.service.js +1 -0
  190. package/dist/esm/components/mail/services/template.service.js.map +1 -1
  191. package/dist/esm/components/mail/utilities/address.utility.d.ts +1 -0
  192. package/dist/esm/components/mail/utilities/address.utility.js +1 -0
  193. package/dist/esm/components/mail/utilities/address.utility.js.map +1 -1
  194. package/dist/esm/components/mail/utilities/mime.utility.d.ts +1 -0
  195. package/dist/esm/components/mail/utilities/mime.utility.js +5 -4
  196. package/dist/esm/components/mail/utilities/mime.utility.js.map +1 -1
  197. package/dist/esm/components/mail/utilities/verification.utility.d.ts +1 -0
  198. package/dist/esm/components/mail/utilities/verification.utility.js +1 -0
  199. package/dist/esm/components/mail/utilities/verification.utility.js.map +1 -1
  200. package/dist/esm/components/request-tracker/component.d.ts +1 -0
  201. package/dist/esm/components/request-tracker/component.js +1 -0
  202. package/dist/esm/components/request-tracker/component.js.map +1 -1
  203. package/dist/esm/components/server-info/common/constants.d.ts +6 -0
  204. package/dist/esm/components/server-info/common/constants.js +6 -0
  205. package/dist/esm/components/server-info/common/constants.js.map +1 -0
  206. package/dist/esm/components/server-info/common/index.d.ts +5 -0
  207. package/dist/esm/components/server-info/common/index.js +5 -0
  208. package/dist/esm/components/server-info/common/index.js.map +1 -0
  209. package/dist/esm/components/server-info/common/keys.d.ts +5 -0
  210. package/dist/esm/components/server-info/common/keys.js +5 -0
  211. package/dist/esm/components/server-info/common/keys.js.map +1 -0
  212. package/dist/esm/components/server-info/common/rest-paths.d.ts +5 -0
  213. package/dist/esm/components/server-info/common/rest-paths.js +5 -0
  214. package/dist/esm/components/server-info/common/rest-paths.js.map +1 -0
  215. package/dist/esm/components/server-info/common/types.d.ts +68 -0
  216. package/dist/esm/components/server-info/common/types.js +2 -0
  217. package/dist/esm/components/server-info/common/types.js.map +1 -0
  218. package/dist/esm/components/server-info/component.d.ts +31 -0
  219. package/dist/esm/components/server-info/component.js +87 -0
  220. package/dist/esm/components/server-info/component.js.map +1 -0
  221. package/dist/esm/components/server-info/controller.d.ts +14 -0
  222. package/dist/esm/components/server-info/controller.js +68 -0
  223. package/dist/esm/components/server-info/controller.js.map +1 -0
  224. package/dist/esm/components/server-info/index.d.ts +5 -0
  225. package/dist/esm/components/server-info/index.js +5 -0
  226. package/dist/esm/components/server-info/index.js.map +1 -0
  227. package/dist/esm/components/server-info/reporter.d.ts +25 -0
  228. package/dist/esm/components/server-info/reporter.js +68 -0
  229. package/dist/esm/components/server-info/reporter.js.map +1 -0
  230. package/dist/esm/components/socket-io/common/keys.d.ts +1 -0
  231. package/dist/esm/components/socket-io/common/keys.js +1 -0
  232. package/dist/esm/components/socket-io/common/keys.js.map +1 -1
  233. package/dist/esm/components/socket-io/component.d.ts +1 -0
  234. package/dist/esm/components/socket-io/component.js +1 -0
  235. package/dist/esm/components/socket-io/component.js.map +1 -1
  236. package/dist/esm/components/static-asset/common/constants.d.ts +5 -0
  237. package/dist/esm/components/static-asset/common/constants.js +3 -0
  238. package/dist/esm/components/static-asset/common/constants.js.map +1 -1
  239. package/dist/esm/components/static-asset/common/keys.d.ts +1 -0
  240. package/dist/esm/components/static-asset/common/keys.js +1 -0
  241. package/dist/esm/components/static-asset/common/keys.js.map +1 -1
  242. package/dist/esm/components/static-asset/common/types.d.ts +48 -6
  243. package/dist/esm/components/static-asset/common/types.js.map +1 -1
  244. package/dist/esm/components/static-asset/controller/base.definition.d.ts +2 -0
  245. package/dist/esm/components/static-asset/controller/base.definition.js +6 -4
  246. package/dist/esm/components/static-asset/controller/base.definition.js.map +1 -1
  247. package/dist/esm/components/static-asset/controller/factory.d.ts +3 -0
  248. package/dist/esm/components/static-asset/controller/factory.js +18 -9
  249. package/dist/esm/components/static-asset/controller/factory.js.map +1 -1
  250. package/dist/esm/components/static-asset/controller/meta-link.js +1 -1
  251. package/dist/esm/components/static-asset/controller/meta-link.js.map +1 -1
  252. package/dist/esm/components/static-asset/controller/route-options.d.ts +9 -0
  253. package/dist/esm/components/static-asset/controller/route-options.js +16 -3
  254. package/dist/esm/components/static-asset/controller/route-options.js.map +1 -1
  255. package/dist/esm/components/static-asset/ingest.d.ts +7 -3
  256. package/dist/esm/components/static-asset/ingest.js +2 -2
  257. package/dist/esm/components/static-asset/ingest.js.map +1 -1
  258. package/dist/esm/components/static-asset/models/base.model.d.ts +2 -0
  259. package/dist/esm/components/static-asset/models/base.model.js.map +1 -1
  260. package/dist/esm/components/websocket/common/keys.d.ts +1 -0
  261. package/dist/esm/components/websocket/common/keys.js +1 -0
  262. package/dist/esm/components/websocket/common/keys.js.map +1 -1
  263. package/dist/esm/components/websocket/component.d.ts +1 -0
  264. package/dist/esm/components/websocket/component.js +1 -0
  265. package/dist/esm/components/websocket/component.js.map +1 -1
  266. package/dist/esm/testing/assert-application-boots.d.ts +48 -8
  267. package/dist/esm/testing/assert-application-boots.js +25 -1
  268. package/dist/esm/testing/assert-application-boots.js.map +1 -1
  269. package/dist/esm/utilities/drizzle-result.utility.d.ts +1 -0
  270. package/dist/esm/utilities/drizzle-result.utility.js +1 -0
  271. package/dist/esm/utilities/drizzle-result.utility.js.map +1 -1
  272. package/dist/presets/app/preset.json +4 -4
  273. package/dist/presets/lib/preset.json +3 -3
  274. package/dist/presets/shared/preset.json +1 -1
  275. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"issuer.service.js","sourceRoot":"","sources":["../../../../../../../../src/components/auth/authenticate/services/bearer/jwks/issuer.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAuC,MAAM,+BAA+B,CAAC;AAC1F,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,uBAAuB,EAIvB,MAAM,EACN,cAAc,EACd,cAAc,GAEf,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAE9D,IAAa,sBAAsB,8BAAnC,MAAa,sBAA4C,SAAQ,wBAA2B;IAK1F,YAEE,OAAqC;QAErC,KAAK,CAAC,EAAE,KAAK,EAAE,wBAAsB,CAAC,IAAI,EAAE,CAAC,CAAC;QAFpC,YAAO,GAAP,OAAO,CAAoB;QAN7B,eAAU,GAAsC,IAAI,CAAC;QACrD,cAAS,GAAsC,IAAI,CAAC;QACpD,SAAI,GAA2B,IAAI,CAAC;QAQ5C,IAAI,CAAC,0BAA0B,CAAC;YAC9B,YAAY,EAAE,IAAI,CAAC,OAAO,CAAC,YAAY;YACvC,iBAAiB,EAAE,IAAI,CAAC,OAAO,CAAC,iBAAiB;YACjD,WAAW,EAAE,IAAI,CAAC,OAA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O;QACL,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YACf,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,iFAAiF;aAC3F,CAAC,CAAC;QACL,CAAC;QAED,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IAED,KAAK,CAAC,YAAY;QAChB,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAE/B,OAAO,IAAI,CAAC,IAAK,CAAC;IACpB,CAAC;CACF,CAAA;AArOY,sBAAsB;IAM9B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,YAAY,EAAE,CAAC,CAAA;;GAN7C,sBAAsB,CAqOlC","sourcesContent":["import { HTTP, type TNullable, type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n AuthenticateBindingKeys,\n type IJWKSIssuerOptions,\n type IJWTIssueClaims,\n type IJWTTokenPayload,\n inject,\n JWKSKeyDrivers,\n JWKSKeyFormats,\n type TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { type Env } from 'hono';\nimport type { CryptoKey, JWK } from 'jose';\nimport { readFile } from 'node:fs/promises';\nimport { JoseLoader } from '../../jose-loader';\nimport { AbstractJWKSTokenService } from './abstract.service';\n\nexport class JWKSIssuerTokenService<E extends Env = Env> extends AbstractJWKSTokenService<E> {\n protected privateKey: TNullable<CryptoKey | Uint8Array> = null;\n protected publicKey: TNullable<CryptoKey | Uint8Array> = null;\n protected jwks: { keys: JWK[] } | null = null;\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n protected options: IJWKSIssuerOptions,\n ) {\n super({ scope: JWKSIssuerTokenService.name });\n\n this.configurePayloadEncryption({\n aesAlgorithm: this.options.aesAlgorithm,\n applicationSecret: this.options.applicationSecret,\n fieldCodecs: this.options.fieldCodecs,\n sign: this.options.sign,\n });\n }\n\n protected override async initialize(): Promise<void> {\n const { keys, algorithm } = this.options;\n\n const raw = await this.resolveKeyContent({ keys });\n const built = await this.parseKeyMaterial({ raw, algorithm, keys });\n\n this.privateKey = built.priv;\n this.publicKey = built.pub;\n\n const { exportJWK } = await JoseLoader.load();\n const publicJWK = await exportJWK(this.publicKey!);\n\n // Belt and braces. `assertPublicJWK` already refused a private JWK on the way IN, but this is\n // the exact object an unauthenticated `/certs` serves - the last place to notice a signing key\n // about to be published, whatever route the material took to get here.\n this.assertPublicJWK({ jwk: publicJWK });\n\n publicJWK.kid = this.options.kid;\n publicJWK.alg = algorithm;\n publicJWK.use = 'sig';\n\n this.jwks = { keys: [publicJWK] };\n\n this.initialized = true;\n\n this.logger\n .for(this.initialize.name)\n .info(\n 'JWKS issuer initialized | driver: %s | format: %s | kid: %s',\n keys.driver,\n keys.format,\n this.options.kid,\n );\n }\n\n protected async resolveKeyContent(opts: { keys: IJWKSIssuerOptions['keys'] }) {\n const { keys } = opts;\n\n switch (keys.driver) {\n case JWKSKeyDrivers.FILE: {\n const [priv, pub] = await Promise.all([\n readFile(keys.private, 'utf-8'),\n readFile(keys.public, 'utf-8'),\n ]);\n\n return { priv, pub };\n }\n case JWKSKeyDrivers.TEXT: {\n return {\n priv: keys.private,\n pub: keys.public,\n };\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] Unknown key driver: ${keys.driver}`,\n });\n }\n }\n }\n\n /**\n * Refuses a JWK carrying private material where a PUBLIC key is expected.\n *\n * The `pem` format cannot reach this state - `importSPKI` rejects a private PEM outright. The\n * `jwk` format can: `importJWK` imports whatever it is handed, and a private JWK marked\n * `\"ext\": true` yields an EXTRACTABLE key, so `exportJWK` then carries `d` straight into the\n * document `/certs` serves without authentication. Measured on jose 6.2.3: with `ext: true` the\n * round trip returns `d`; without it, export throws. So the only thing standing between a\n * mis-pasted key and a published signing key was an optional flag on attacker-irrelevant input.\n *\n * Named members, not a blanket scan: `d` covers EC/OKP and RSA's private exponent, and the CRT\n * members are the rest of an RSA private key.\n */\n protected assertPublicJWK(opts: { jwk: JWK }): void {\n const PRIVATE_MEMBERS = ['d', 'p', 'q', 'dp', 'dq', 'qi', 'k'] as const;\n\n const present = PRIVATE_MEMBERS.filter((member) => opts.jwk[member] !== undefined);\n\n if (present.length === 0) {\n return;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] The public key material carries PRIVATE members (${present.join(', ')}) | this key would be published at the JWKS endpoint | pass the public half in keys.public`,\n });\n }\n\n protected async parseKeyMaterial(opts: {\n raw: { priv: string; pub: string };\n algorithm: IJWKSIssuerOptions['algorithm'];\n keys: IJWKSIssuerOptions['keys'];\n }) {\n const { raw, algorithm, keys } = opts;\n\n if (!raw.priv) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid raw.priv key!',\n });\n }\n\n if (!raw.pub) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid raw.pub key!',\n });\n }\n\n const { importJWK, importPKCS8, importSPKI } = await JoseLoader.load();\n\n switch (keys.format) {\n case JWKSKeyFormats.PEM: {\n const priv = await importPKCS8(raw.priv, algorithm);\n const pub = await importSPKI(raw.pub, algorithm);\n\n return { priv, pub };\n }\n case JWKSKeyFormats.JWK: {\n try {\n const parsed = {\n priv: JSON.parse(raw.priv) as JWK,\n pub: JSON.parse(raw.pub) as JWK,\n };\n\n this.assertPublicJWK({ jwk: parsed.pub });\n\n const priv = await importJWK(parsed.priv, algorithm);\n const pub = await importJWK(parsed.pub, algorithm);\n\n return { priv, pub };\n } catch (error) {\n this.logger\n .for(this.parseKeyMaterial.name)\n .error('Invalid JWK key material | Error: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid JWK key material',\n });\n }\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] Unknown key format: ${keys.format}`,\n });\n }\n }\n }\n\n protected override async doVerify(token: string): Promise<IJWTTokenPayload> {\n await this.ensureInitialized();\n const { jwtVerify } = await JoseLoader.load();\n const result = await jwtVerify<IJWTTokenPayload>(token, this.publicKey!, this.options.verify);\n\n return this.decryptPayload({ result });\n }\n\n override async getSigner(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n claims?: IJWTIssueClaims;\n }) {\n await this.ensureInitialized();\n const { SignJWT } = await JoseLoader.load();\n\n const now = Math.floor(Date.now() / 1000);\n const expiresIn = await opts.getTokenExpiresFn();\n\n const encryptedPayload = await this.encryptPayload(opts.payload);\n\n const signer = new SignJWT({ ...encryptedPayload })\n .setProtectedHeader({ alg: this.options.algorithm, kid: this.options.kid })\n .setIssuedAt()\n .setExpirationTime(now + expiresIn)\n .setNotBefore(now);\n\n return this.applySignClaims({ signer, payload: encryptedPayload, claims: opts.claims });\n }\n\n protected override getSigningKey(): ValueOrPromise<Uint8Array | CryptoKey> {\n if (!this.privateKey) {\n throw getError({ message: '[getSigningKey] Invalid privateKey!' });\n }\n\n return this.privateKey;\n }\n\n protected override getDefaultTokenExpiresFn(): TGetTokenExpiresFn {\n return this.options.getTokenExpiresFn;\n }\n\n getJWKS(): { keys: JWK[] } {\n if (!this.jwks) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] JWKS not initialized yet. Call getJWKSAsync() instead.',\n });\n }\n\n return this.jwks;\n }\n\n async getJWKSAsync(): Promise<{ keys: JWK[] }> {\n await this.ensureInitialized();\n\n return this.jwks!;\n }\n}\n"]}
1
+ {"version":3,"file":"issuer.service.js","sourceRoot":"","sources":["../../../../../../../../src/components/auth/authenticate/services/bearer/jwks/issuer.service.ts"],"names":[],"mappings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QAE/B,OAAO,IAAI,CAAC,IAAK,CAAC;IACpB,CAAC;CACF,CAAA;AArOY,sBAAsB;IAM9B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,YAAY,EAAE,CAAC,CAAA;;GAN7C,sBAAsB,CAqOlC","sourcesContent":["import { HTTP, type TNullable, type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n AuthenticateBindingKeys,\n type IJWKSIssuerOptions,\n type IJWTIssueClaims,\n type IJWTTokenPayload,\n inject,\n JWKSKeyDrivers,\n JWKSKeyFormats,\n type TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { type Env } from 'hono';\nimport type { CryptoKey, JWK } from 'jose';\nimport { readFile } from 'node:fs/promises';\nimport { JoseLoader } from '../../jose-loader';\nimport { AbstractJWKSTokenService } from './abstract.service';\n\n/** Signs tokens with a private key loaded from `IJWKSIssuerOptions` and exposes the matching public keys as a JWKS via `getJWKSAsync()`. */\nexport class JWKSIssuerTokenService<E extends Env = Env> extends AbstractJWKSTokenService<E> {\n protected privateKey: TNullable<CryptoKey | Uint8Array> = null;\n protected publicKey: TNullable<CryptoKey | Uint8Array> = null;\n protected jwks: { keys: JWK[] } | null = null;\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n protected options: IJWKSIssuerOptions,\n ) {\n super({ scope: JWKSIssuerTokenService.name });\n\n this.configureClaims({ options: this.options, pinnedAlgorithms: [this.options.algorithm] });\n this.configurePayloadEncryption({\n aesAlgorithm: this.options.aesAlgorithm,\n applicationSecret: this.options.applicationSecret,\n fieldCodecs: this.options.fieldCodecs,\n });\n }\n\n protected override async initialize(): Promise<void> {\n const { keys, algorithm } = this.options;\n\n const raw = await this.resolveKeyContent({ keys });\n const built = await this.parseKeyMaterial({ raw, algorithm, keys });\n\n this.privateKey = built.priv;\n this.publicKey = built.pub;\n\n const { exportJWK } = await JoseLoader.load();\n const publicJWK = await exportJWK(this.publicKey!);\n\n // Belt and braces. `assertPublicJWK` already refused a private JWK on the way IN, but this is\n // the exact object an unauthenticated `/certs` serves - the last place to notice a signing key\n // about to be published, whatever route the material took to get here.\n this.assertPublicJWK({ jwk: publicJWK });\n\n publicJWK.kid = this.options.kid;\n publicJWK.alg = algorithm;\n publicJWK.use = 'sig';\n\n this.jwks = { keys: [publicJWK] };\n\n this.initialized = true;\n\n this.logger\n .for(this.initialize.name)\n .info(\n 'JWKS issuer initialized | driver: %s | format: %s | kid: %s',\n keys.driver,\n keys.format,\n this.options.kid,\n );\n }\n\n protected async resolveKeyContent(opts: { keys: IJWKSIssuerOptions['keys'] }) {\n const { keys } = opts;\n\n switch (keys.driver) {\n case JWKSKeyDrivers.FILE: {\n const [priv, pub] = await Promise.all([\n readFile(keys.private, 'utf-8'),\n readFile(keys.public, 'utf-8'),\n ]);\n\n return { priv, pub };\n }\n case JWKSKeyDrivers.TEXT: {\n return {\n priv: keys.private,\n pub: keys.public,\n };\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] Unknown key driver: ${keys.driver}`,\n });\n }\n }\n }\n\n /**\n * Refuses a JWK carrying private material where a PUBLIC key is expected.\n *\n * The `pem` format cannot reach this state - `importSPKI` rejects a private PEM outright. The\n * `jwk` format can: `importJWK` imports whatever it is handed, and a private JWK marked\n * `\"ext\": true` yields an EXTRACTABLE key, so `exportJWK` then carries `d` straight into the\n * document `/certs` serves without authentication. Measured on jose 6.2.3: with `ext: true` the\n * round trip returns `d`; without it, export throws. So the only thing standing between a\n * mis-pasted key and a published signing key was an optional flag on attacker-irrelevant input.\n *\n * Named members, not a blanket scan: `d` covers EC/OKP and RSA's private exponent, and the CRT\n * members are the rest of an RSA private key.\n */\n protected assertPublicJWK(opts: { jwk: JWK }): void {\n const PRIVATE_MEMBERS = ['d', 'p', 'q', 'dp', 'dq', 'qi', 'k'] as const;\n\n const present = PRIVATE_MEMBERS.filter((member) => opts.jwk[member] !== undefined);\n\n if (present.length === 0) {\n return;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] The public key material carries PRIVATE members (${present.join(', ')}) | this key would be published at the JWKS endpoint | pass the public half in keys.public`,\n });\n }\n\n protected async parseKeyMaterial(opts: {\n raw: { priv: string; pub: string };\n algorithm: IJWKSIssuerOptions['algorithm'];\n keys: IJWKSIssuerOptions['keys'];\n }) {\n const { raw, algorithm, keys } = opts;\n\n if (!raw.priv) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid raw.priv key!',\n });\n }\n\n if (!raw.pub) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid raw.pub key!',\n });\n }\n\n const { importJWK, importPKCS8, importSPKI } = await JoseLoader.load();\n\n switch (keys.format) {\n case JWKSKeyFormats.PEM: {\n const priv = await importPKCS8(raw.priv, algorithm);\n const pub = await importSPKI(raw.pub, algorithm);\n\n return { priv, pub };\n }\n case JWKSKeyFormats.JWK: {\n try {\n const parsed = {\n priv: JSON.parse(raw.priv) as JWK,\n pub: JSON.parse(raw.pub) as JWK,\n };\n\n this.assertPublicJWK({ jwk: parsed.pub });\n\n const priv = await importJWK(parsed.priv, algorithm);\n const pub = await importJWK(parsed.pub, algorithm);\n\n return { priv, pub };\n } catch (error) {\n this.logger\n .for(this.parseKeyMaterial.name)\n .error('Invalid JWK key material | Error: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid JWK key material',\n });\n }\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] Unknown key format: ${keys.format}`,\n });\n }\n }\n }\n\n protected override async doVerify(token: string): Promise<IJWTTokenPayload> {\n await this.ensureInitialized();\n const { jwtVerify } = await JoseLoader.load();\n const result = await jwtVerify<IJWTTokenPayload>(token, this.publicKey!, this.verifyOptions!);\n\n return this.decryptPayload({ result });\n }\n\n override async getSigner(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n claims?: IJWTIssueClaims;\n }) {\n await this.ensureInitialized();\n const { SignJWT } = await JoseLoader.load();\n\n const now = Math.floor(Date.now() / 1000);\n const expiresIn = await opts.getTokenExpiresFn();\n\n const encryptedPayload = await this.encryptPayload(opts.payload);\n\n const signer = new SignJWT({ ...encryptedPayload })\n .setProtectedHeader({ alg: this.options.algorithm, kid: this.options.kid })\n .setIssuedAt()\n .setExpirationTime(now + expiresIn)\n .setNotBefore(now);\n\n return this.applySignClaims({ signer, payload: encryptedPayload, claims: opts.claims });\n }\n\n protected override getSigningKey(): ValueOrPromise<Uint8Array | CryptoKey> {\n if (!this.privateKey) {\n throw getError({ message: '[getSigningKey] Invalid privateKey!' });\n }\n\n return this.privateKey;\n }\n\n protected override getDefaultTokenExpiresFn(): TGetTokenExpiresFn {\n return this.options.getTokenExpiresFn;\n }\n\n getJWKS(): { keys: JWK[] } {\n if (!this.jwks) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] JWKS not initialized yet. Call getJWKSAsync() instead.',\n });\n }\n\n return this.jwks;\n }\n\n async getJWKSAsync(): Promise<{ keys: JWK[] }> {\n await this.ensureInitialized();\n\n return this.jwks!;\n }\n}\n"]}
@@ -2,6 +2,7 @@ import { type IJWKSVerifierOptions, type IJWTTokenPayload, type TGetTokenExpires
2
2
  import { type Env } from 'hono';
3
3
  import type { createRemoteJWKSet, SignJWT } from 'jose';
4
4
  import { AbstractJWKSTokenService } from './abstract.service.js';
5
+ /** Verifies tokens against a remote JWKS fetched from `jwksUrl`. The key set is cached for `cacheTtlMs` (default 43_200_000 ms) with a `cooldownMs` refetch cooldown (default 30_000 ms). */
5
6
  export declare class JWKSVerifierTokenService<E extends Env = Env> extends AbstractJWKSTokenService<E> {
6
7
  protected options: IJWKSVerifierOptions;
7
8
  protected jwksVerifier: ReturnType<typeof createRemoteJWKSet> | null;
@@ -15,12 +15,15 @@ import { HTTP } from '@venizia/ignis-helpers/common';
15
15
  import { getError } from '@venizia/ignis-helpers/core';
16
16
  import { AuthenticateBindingKeys, inject, } from '@venizia/ignis-kernel';
17
17
  import { JoseLoader } from '../../jose-loader.js';
18
+ import { JWKSUrlPolicy } from '../../jwks-url-policy.js';
18
19
  import { AbstractJWKSTokenService } from './abstract.service.js';
20
+ /** Verifies tokens against a remote JWKS fetched from `jwksUrl`. The key set is cached for `cacheTtlMs` (default 43_200_000 ms) with a `cooldownMs` refetch cooldown (default 30_000 ms). */
19
21
  let JWKSVerifierTokenService = JWKSVerifierTokenService_1 = class JWKSVerifierTokenService extends AbstractJWKSTokenService {
20
22
  constructor(options) {
21
23
  super({ scope: JWKSVerifierTokenService_1.name });
22
24
  this.options = options;
23
25
  this.jwksVerifier = null;
26
+ this.configureClaims({ options: this.options });
24
27
  this.configurePayloadEncryption({
25
28
  aesAlgorithm: this.options.aesAlgorithm,
26
29
  applicationSecret: this.options.applicationSecret,
@@ -29,7 +32,12 @@ let JWKSVerifierTokenService = JWKSVerifierTokenService_1 = class JWKSVerifierTo
29
32
  }
30
33
  async initialize() {
31
34
  const { createRemoteJWKSet } = await JoseLoader.load();
32
- const jwksUrl = new URL(this.options.jwksUrl);
35
+ const jwksUrl = JWKSUrlPolicy.assertUrl({
36
+ scope: JWKSVerifierTokenService_1.name,
37
+ label: 'jwksUrl',
38
+ url: this.options.jwksUrl,
39
+ hosts: this.options.jwks?.hosts?.http,
40
+ });
33
41
  this.jwksVerifier = createRemoteJWKSet(jwksUrl, {
34
42
  cacheMaxAge: this.options.cacheTtlMs ?? 43_200_000,
35
43
  cooldownDuration: this.options.cooldownMs ?? 30_000,
@@ -37,12 +45,12 @@ let JWKSVerifierTokenService = JWKSVerifierTokenService_1 = class JWKSVerifierTo
37
45
  this.initialized = true;
38
46
  this.logger
39
47
  .for(this.initialize.name)
40
- .info('JWKS verifier initialized | url: %s', this.options.jwksUrl);
48
+ .info('JWKS verifier initialized | origin: %s', jwksUrl.origin);
41
49
  }
42
50
  async doVerify(token) {
43
51
  await this.ensureInitialized();
44
52
  const { jwtVerify } = await JoseLoader.load();
45
- const result = await jwtVerify(token, this.jwksVerifier, this.options.verify);
53
+ const result = await jwtVerify(token, this.jwksVerifier, this.verifyOptions);
46
54
  return this.decryptPayload({ result });
47
55
  }
48
56
  async getSigner(_opts) {
@@ -1 +1 @@
1
- {"version":3,"file":"verifier.service.js","sourceRoot":"","sources":["../../../../../../../../src/components/auth/authenticate/services/bearer/jwks/verifier.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,uBAAuB,EAGvB,MAAM,GAEP,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAE9D,IAAa,wBAAwB,gCAArC,MAAa,wBAA8C,SAAQ,wBAA2B;IAG5F,YAEE,OAAuC;QAEvC,KAAK,CAAC,EAAE,KAAK,EAAE,0BAAwB,CAAC,IAAI,EAAE,CAAC,CAAC;QAFtC,YAAO,GAAP,OAAO,CAAsB;QAJ/B,iBAAY,GAAiD,IAAI,CAAC;QAO1E,IAAI,CAAC,0BAA0B,CAAC;YAC9B,YAAY,EAAE,IAAI,CAAC,OAAO,CAAC,YAAY;YACvC,iBAAiB,EAAE,IAAI,CAAC,OAAO,CAAC,iBAAiB;YACjD,WAAW,EAAE,IAAI,CAAC,OAAO,CAAC,WAAW;SACtC,CAAC,CAAC;IACL,CAAC;IAEkB,KAAK,CAAC,UAAU;QACjC,MAAM,E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;IACL,CAAC;IAEkB,wBAAwB;QACzC,MAAM,QAAQ,CAAC;YACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;YACrD,OAAO,EAAE,8DAA8D;SACxE,CAAC,CAAC;IACL,CAAC;CACF,CAAA;AAjEY,wBAAwB;IAIhC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,YAAY,EAAE,CAAC,CAAA;;GAJ7C,wBAAwB,CAiEpC","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n AuthenticateBindingKeys,\n type IJWKSVerifierOptions,\n type IJWTTokenPayload,\n inject,\n type TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { type Env } from 'hono';\nimport type { createRemoteJWKSet, SignJWT } from 'jose';\nimport { JoseLoader } from '../../jose-loader';\nimport { AbstractJWKSTokenService } from './abstract.service';\n\nexport class JWKSVerifierTokenService<E extends Env = Env> extends AbstractJWKSTokenService<E> {\n protected jwksVerifier: ReturnType<typeof createRemoteJWKSet> | null = null;\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n protected options: IJWKSVerifierOptions,\n ) {\n super({ scope: JWKSVerifierTokenService.name });\n this.configurePayloadEncryption({\n aesAlgorithm: this.options.aesAlgorithm,\n applicationSecret: this.options.applicationSecret,\n fieldCodecs: this.options.fieldCodecs,\n });\n }\n\n protected override async initialize(): Promise<void> {\n const { createRemoteJWKSet } = await JoseLoader.load();\n const jwksUrl = new URL(this.options.jwksUrl);\n this.jwksVerifier = createRemoteJWKSet(jwksUrl, {\n cacheMaxAge: this.options.cacheTtlMs ?? 43_200_000,\n cooldownDuration: this.options.cooldownMs ?? 30_000,\n });\n\n this.initialized = true;\n\n this.logger\n .for(this.initialize.name)\n .info('JWKS verifier initialized | url: %s', this.options.jwksUrl);\n }\n\n protected override async doVerify(token: string): Promise<IJWTTokenPayload> {\n await this.ensureInitialized();\n const { jwtVerify } = await JoseLoader.load();\n const result = await jwtVerify<IJWTTokenPayload>(\n token,\n this.jwksVerifier!,\n this.options.verify,\n );\n\n return this.decryptPayload({ result });\n }\n\n override async getSigner(_opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n }): Promise<SignJWT> {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSVerifierTokenService] Verifier mode cannot sign tokens',\n });\n }\n\n protected override getSigningKey(): never {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSVerifierTokenService] Verifier mode cannot sign tokens',\n });\n }\n\n protected override getDefaultTokenExpiresFn(): never {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSVerifierTokenService] Verifier mode has no token expiry',\n });\n }\n}\n"]}
1
+ {"version":3,"file":"verifier.service.js","sourceRoot":"","sources":["../../../../../../../../src/components/auth/authenticate/services/bearer/jwks/verifier.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,uBAAuB,EAGvB,MAAM,GAEP,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAE9D,6LAA6L;AAC7L,IAAa,wBAAwB,gCAArC,MAAa,wBAA8C,SAAQ,wBAA2B;IAG5F,YAEE,OAAuC;QAEvC,KAAK,CAAC,EAAE,KAAK,EAAE,0BAAwB,CAAC,IAAI,EAAE,CAAC,CAAC;QAFtC,YAAO,GAAP,OAAO,CAAsB;QAJ/B,iBAAY,GAAiD,IAAI,CAAC;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CAC5B,KAAK,EACL,IAAI,CAAC,YAAa,EAClB,IAAI,CAAC,aAAc,CACpB,CAAC;QAEF,OAAO,IAAI,CAAC,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;IACzC,CAAC;IAEQ,KAAK,CAAC,SAAS,CAAC,KAGxB;QACC,MAAM,QAAQ,CAAC;YACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;YACrD,OAAO,EAAE,6DAA6D;SACvE,CAAC,CAAC;IACL,CAAC;IAEkB,aAAa;QAC9B,MAAM,QAAQ,CAAC;YACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;YACrD,OAAO,EAAE,6DAA6D;SACvE,CAAC,CAAC;IACL,CAAC;IAEkB,wBAAwB;QACzC,MAAM,QAAQ,CAAC;YACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;YACrD,OAAO,EAAE,8DAA8D;SACxE,CAAC,CAAC;IACL,CAAC;CACF,CAAA;AAvEY,wBAAwB;IAIhC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,YAAY,EAAE,CAAC,CAAA;;GAJ7C,wBAAwB,CAuEpC","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n AuthenticateBindingKeys,\n type IJWKSVerifierOptions,\n type IJWTTokenPayload,\n inject,\n type TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { type Env } from 'hono';\nimport type { createRemoteJWKSet, SignJWT } from 'jose';\nimport { JoseLoader } from '../../jose-loader';\nimport { JWKSUrlPolicy } from '../../jwks-url-policy';\nimport { AbstractJWKSTokenService } from './abstract.service';\n\n/** Verifies tokens against a remote JWKS fetched from `jwksUrl`. The key set is cached for `cacheTtlMs` (default 43_200_000 ms) with a `cooldownMs` refetch cooldown (default 30_000 ms). */\nexport class JWKSVerifierTokenService<E extends Env = Env> extends AbstractJWKSTokenService<E> {\n protected jwksVerifier: ReturnType<typeof createRemoteJWKSet> | null = null;\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n protected options: IJWKSVerifierOptions,\n ) {\n super({ scope: JWKSVerifierTokenService.name });\n this.configureClaims({ options: this.options });\n this.configurePayloadEncryption({\n aesAlgorithm: this.options.aesAlgorithm,\n applicationSecret: this.options.applicationSecret,\n fieldCodecs: this.options.fieldCodecs,\n });\n }\n\n protected override async initialize(): Promise<void> {\n const { createRemoteJWKSet } = await JoseLoader.load();\n const jwksUrl = JWKSUrlPolicy.assertUrl({\n scope: JWKSVerifierTokenService.name,\n label: 'jwksUrl',\n url: this.options.jwksUrl,\n hosts: this.options.jwks?.hosts?.http,\n });\n this.jwksVerifier = createRemoteJWKSet(jwksUrl, {\n cacheMaxAge: this.options.cacheTtlMs ?? 43_200_000,\n cooldownDuration: this.options.cooldownMs ?? 30_000,\n });\n\n this.initialized = true;\n\n this.logger\n .for(this.initialize.name)\n .info('JWKS verifier initialized | origin: %s', jwksUrl.origin);\n }\n\n protected override async doVerify(token: string): Promise<IJWTTokenPayload> {\n await this.ensureInitialized();\n const { jwtVerify } = await JoseLoader.load();\n const result = await jwtVerify<IJWTTokenPayload>(\n token,\n this.jwksVerifier!,\n this.verifyOptions!,\n );\n\n return this.decryptPayload({ result });\n }\n\n override async getSigner(_opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n }): Promise<SignJWT> {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSVerifierTokenService] Verifier mode cannot sign tokens',\n });\n }\n\n protected override getSigningKey(): never {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSVerifierTokenService] Verifier mode cannot sign tokens',\n });\n }\n\n protected override getDefaultTokenExpiresFn(): never {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSVerifierTokenService] Verifier mode has no token expiry',\n });\n }\n}\n"]}
@@ -5,7 +5,18 @@ import { AbstractBearerTokenService } from './abstract.service.js';
5
5
  /** Symmetric JWT (JWS) token service with optional AES-encrypted payloads. */
6
6
  export declare class JWSTokenService<E extends Env = Env> extends AbstractBearerTokenService<E> {
7
7
  protected options: IJWSTokenServiceOptions;
8
+ /** The shortest `jwtSecret` accepted, in bytes: an HMAC key is as strong as it is long, and 32 bytes is the size of a SHA-256 output. */
9
+ static readonly MIN_SECRET_BYTES = 32;
8
10
  protected jwtSecret: Uint8Array;
11
+ /**
12
+ * Refuses a `jwtSecret` shorter than {@link JWSTokenService.MIN_SECRET_BYTES} (counted in UTF-8 bytes, not
13
+ * characters), saying how to make one. The secret is never echoed. The component calls it at boot and the
14
+ * service when it is built.
15
+ */
16
+ static assertSecretStrength(opts: {
17
+ scope: string;
18
+ secret: string;
19
+ }): void;
9
20
  constructor(options: IJWSTokenServiceOptions);
10
21
  protected doVerify(token: string): Promise<IJWTTokenPayload>;
11
22
  getSigner(opts: {
@@ -17,7 +17,25 @@ import { AuthenticateBindingKeys, inject, } from '@venizia/ignis-kernel';
17
17
  import { JoseLoader } from '../jose-loader.js';
18
18
  import { AbstractBearerTokenService } from './abstract.service.js';
19
19
  /** Symmetric JWT (JWS) token service with optional AES-encrypted payloads. */
20
- let JWSTokenService = JWSTokenService_1 = class JWSTokenService extends AbstractBearerTokenService {
20
+ let JWSTokenService = class JWSTokenService extends AbstractBearerTokenService {
21
+ static { JWSTokenService_1 = this; }
22
+ /** The shortest `jwtSecret` accepted, in bytes: an HMAC key is as strong as it is long, and 32 bytes is the size of a SHA-256 output. */
23
+ static { this.MIN_SECRET_BYTES = 32; }
24
+ /**
25
+ * Refuses a `jwtSecret` shorter than {@link JWSTokenService.MIN_SECRET_BYTES} (counted in UTF-8 bytes, not
26
+ * characters), saying how to make one. The secret is never echoed. The component calls it at boot and the
27
+ * service when it is built.
28
+ */
29
+ static assertSecretStrength(opts) {
30
+ const bytes = new TextEncoder().encode(opts.secret).length;
31
+ if (bytes >= JWSTokenService_1.MIN_SECRET_BYTES) {
32
+ return;
33
+ }
34
+ throw getError({
35
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
36
+ message: `[${opts.scope}] jwtSecret is too short: ${bytes} bytes, at least ${JWSTokenService_1.MIN_SECRET_BYTES} are required | Generate one with: openssl rand -base64 48`,
37
+ });
38
+ }
21
39
  constructor(options) {
22
40
  super({ scope: JWSTokenService_1.name });
23
41
  this.options = options;
@@ -34,17 +52,21 @@ let JWSTokenService = JWSTokenService_1 = class JWSTokenService extends Abstract
34
52
  message: '[JWSTokenService] Invalid getTokenExpiresFn',
35
53
  });
36
54
  }
55
+ this.configureClaims({
56
+ options,
57
+ pinnedAlgorithms: [options.headerAlgorithm ?? 'HS256'],
58
+ });
59
+ JWSTokenService_1.assertSecretStrength({ scope: JWSTokenService_1.name, secret: jwtSecret });
37
60
  this.configurePayloadEncryption({
38
61
  aesAlgorithm,
39
62
  applicationSecret,
40
63
  fieldCodecs: options.fieldCodecs,
41
- sign: options.sign,
42
64
  });
43
65
  this.jwtSecret = new TextEncoder().encode(this.options.jwtSecret);
44
66
  }
45
67
  async doVerify(token) {
46
68
  const { jwtVerify } = await JoseLoader.load();
47
- const decodedToken = await jwtVerify(token, this.jwtSecret, this.options.verify);
69
+ const decodedToken = await jwtVerify(token, this.jwtSecret, this.verifyOptions);
48
70
  return this.decryptPayload({ result: decodedToken });
49
71
  }
50
72
  async getSigner(opts) {
@@ -1 +1 @@
1
- {"version":3,"file":"jws.service.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authenticate/services/bearer/jws.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAuB,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,uBAAuB,EAIvB,MAAM,GAEP,MAAM,uBAAuB,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MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,WAAW,EAAE,CAAC,CAAA;;GAJ5C,eAAe,CA4E3B","sourcesContent":["import { HTTP, type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n AuthenticateBindingKeys,\n type IJWSTokenServiceOptions,\n type IJWTIssueClaims,\n type IJWTTokenPayload,\n inject,\n type TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { type Env } from 'hono';\nimport { JoseLoader } from '../jose-loader';\nimport { AbstractBearerTokenService } from './abstract.service';\n\n/** Symmetric JWT (JWS) token service with optional AES-encrypted payloads. */\nexport class JWSTokenService<E extends Env = Env> extends AbstractBearerTokenService<E> {\n protected jwtSecret: Uint8Array;\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.JWT_OPTIONS })\n protected options: IJWSTokenServiceOptions,\n ) {\n super({ scope: JWSTokenService.name });\n\n const { aesAlgorithm, jwtSecret, applicationSecret, getTokenExpiresFn } = options ?? {};\n\n if (!jwtSecret) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWSTokenService] Invalid jwtSecret',\n });\n }\n\n if (!getTokenExpiresFn) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWSTokenService] Invalid getTokenExpiresFn',\n });\n }\n\n this.configurePayloadEncryption({\n aesAlgorithm,\n applicationSecret,\n fieldCodecs: options.fieldCodecs,\n sign: options.sign,\n });\n this.jwtSecret = new TextEncoder().encode(this.options.jwtSecret);\n }\n\n protected override async doVerify(token: string): Promise<IJWTTokenPayload> {\n const { jwtVerify } = await JoseLoader.load();\n const decodedToken = await jwtVerify<IJWTTokenPayload>(\n token,\n this.jwtSecret,\n this.options.verify,\n );\n\n return this.decryptPayload({ result: decodedToken });\n }\n\n override async getSigner(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n claims?: IJWTIssueClaims;\n }) {\n const { SignJWT } = await JoseLoader.load();\n const now = Math.floor(Date.now() / 1000);\n const expiresIn = await opts.getTokenExpiresFn();\n\n const encryptedPayload = await this.encryptPayload(opts.payload);\n\n const signer = new SignJWT(Object.assign({}, encryptedPayload))\n .setProtectedHeader({ alg: this.options.headerAlgorithm ?? 'HS256' })\n .setIssuedAt()\n .setExpirationTime(now + expiresIn)\n .setNotBefore(now);\n\n return this.applySignClaims({ signer, payload: encryptedPayload, claims: opts.claims });\n }\n\n protected override getSigningKey(): ValueOrPromise<Uint8Array> {\n if (!this.jwtSecret) {\n throw getError({ message: '[getSigningKey] Invalid jwtSecret!' });\n }\n\n return this.jwtSecret;\n }\n\n protected override getDefaultTokenExpiresFn(): TGetTokenExpiresFn {\n return this.options.getTokenExpiresFn;\n }\n}\n"]}
1
+ {"version":3,"file":"jws.service.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authenticate/services/bearer/jws.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAuB,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,uBAAuB,EAIvB,MAAM,GAEP,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,0BAA0B,EAAE,MAAM,oBAAoB,CAAC;AAEhE,8EAA8E;AAC9E,IAAa,eAAe,GAA5B,MAAa,eAAqC,SAAQ,0BAA6B;;IACrF,yIAAyI;aACzH,qBAAgB,GAAG,EAAE,AAAL,CAAM;IAItC;;;;OAIG;IACH,MAAM,CAAC,oBAAoB,CAAC,IAAuC;QACjE,MAAM,KAAK,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC;QAE3D,IAAI,KAAK,IAAI,iBAAe,CAAC,gBAAgB,EAAE,CAAC;YA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QAAQ,CAAC,EAAE,OAAO,EAAE,oCAAoC,EAAE,CAAC,CAAC;QACpE,CAAC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAEkB,wBAAwB;QACzC,OAAO,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC;IACxC,CAAC;;AArGU,eAAe;IAyBvB,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,WAAW,EAAE,CAAC,CAAA;;GAzB5C,eAAe,CAsG3B","sourcesContent":["import { HTTP, type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n AuthenticateBindingKeys,\n type IJWSTokenServiceOptions,\n type IJWTIssueClaims,\n type IJWTTokenPayload,\n inject,\n type TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { type Env } from 'hono';\nimport { JoseLoader } from '../jose-loader';\nimport { AbstractBearerTokenService } from './abstract.service';\n\n/** Symmetric JWT (JWS) token service with optional AES-encrypted payloads. */\nexport class JWSTokenService<E extends Env = Env> extends AbstractBearerTokenService<E> {\n /** The shortest `jwtSecret` accepted, in bytes: an HMAC key is as strong as it is long, and 32 bytes is the size of a SHA-256 output. */\n static readonly MIN_SECRET_BYTES = 32;\n\n protected jwtSecret: Uint8Array;\n\n /**\n * Refuses a `jwtSecret` shorter than {@link JWSTokenService.MIN_SECRET_BYTES} (counted in UTF-8 bytes, not\n * characters), saying how to make one. The secret is never echoed. The component calls it at boot and the\n * service when it is built.\n */\n static assertSecretStrength(opts: { scope: string; secret: string }): void {\n const bytes = new TextEncoder().encode(opts.secret).length;\n\n if (bytes >= JWSTokenService.MIN_SECRET_BYTES) {\n return;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${opts.scope}] jwtSecret is too short: ${bytes} bytes, at least ${JWSTokenService.MIN_SECRET_BYTES} are required | Generate one with: openssl rand -base64 48`,\n });\n }\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.JWT_OPTIONS })\n protected options: IJWSTokenServiceOptions,\n ) {\n super({ scope: JWSTokenService.name });\n\n const { aesAlgorithm, jwtSecret, applicationSecret, getTokenExpiresFn } = options ?? {};\n\n if (!jwtSecret) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWSTokenService] Invalid jwtSecret',\n });\n }\n\n if (!getTokenExpiresFn) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWSTokenService] Invalid getTokenExpiresFn',\n });\n }\n\n this.configureClaims({\n options,\n pinnedAlgorithms: [options.headerAlgorithm ?? 'HS256'],\n });\n JWSTokenService.assertSecretStrength({ scope: JWSTokenService.name, secret: jwtSecret });\n\n this.configurePayloadEncryption({\n aesAlgorithm,\n applicationSecret,\n fieldCodecs: options.fieldCodecs,\n });\n this.jwtSecret = new TextEncoder().encode(this.options.jwtSecret);\n }\n\n protected override async doVerify(token: string): Promise<IJWTTokenPayload> {\n const { jwtVerify } = await JoseLoader.load();\n const decodedToken = await jwtVerify<IJWTTokenPayload>(\n token,\n this.jwtSecret,\n this.verifyOptions!,\n );\n\n return this.decryptPayload({ result: decodedToken });\n }\n\n override async getSigner(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n claims?: IJWTIssueClaims;\n }) {\n const { SignJWT } = await JoseLoader.load();\n const now = Math.floor(Date.now() / 1000);\n const expiresIn = await opts.getTokenExpiresFn();\n\n const encryptedPayload = await this.encryptPayload(opts.payload);\n\n const signer = new SignJWT(Object.assign({}, encryptedPayload))\n .setProtectedHeader({ alg: this.options.headerAlgorithm ?? 'HS256' })\n .setIssuedAt()\n .setExpirationTime(now + expiresIn)\n .setNotBefore(now);\n\n return this.applySignClaims({ signer, payload: encryptedPayload, claims: opts.claims });\n }\n\n protected override getSigningKey(): ValueOrPromise<Uint8Array> {\n if (!this.jwtSecret) {\n throw getError({ message: '[getSigningKey] Invalid jwtSecret!' });\n }\n\n return this.jwtSecret;\n }\n\n protected override getDefaultTokenExpiresFn(): TGetTokenExpiresFn {\n return this.options.getTokenExpiresFn;\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  export * from './basic/index.js';
2
2
  export * from './bearer/index.js';
3
+ export * from './jwks-url-policy.js';
3
4
  export * from './service/index.js';
4
5
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,5 @@
1
1
  export * from './basic/index.js';
2
2
  export * from './bearer/index.js';
3
+ export * from './jwks-url-policy.js';
3
4
  export * from './service/index.js';
4
5
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/services/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC","sourcesContent":["export * from './basic';\nexport * from './bearer';\nexport * from './service';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/services/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC;AACzB,cAAc,mBAAmB,CAAC;AAClC,cAAc,WAAW,CAAC","sourcesContent":["export * from './basic';\nexport * from './bearer';\nexport * from './jwks-url-policy';\nexport * from './service';\n"]}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Where a JWKS may be fetched from. A key set read over plain `http:` can be replaced on the way, and
3
+ * whoever replaces it signs tokens that verify, so a JWKS URL is `https:` unless its host is loopback or
4
+ * is listed in `jwks.hosts.http`. The one policy serves the JWKS verifier and the service-assertion
5
+ * callers: both fetch a key set to decide who may call.
6
+ *
7
+ * The opt-in is an EXACT entry, never a pattern or a range: a host name, an IPv4 address, or an IPv6 address in
8
+ * brackets, each optionally with a port (`identity-service`, `10.0.0.5:8080`, `[fd00::1]:8443`). An entry without a
9
+ * port covers every port of that host; an entry with one covers that port only. An entry and a URL are both read by
10
+ * the URL parser, so the two sides are compared in the form the parser gives them: `http://2130706433` is
11
+ * `127.0.0.1`, and `http://[::ffff:10.0.0.5]` is `[::ffff:a00:5]`, which is not `10.0.0.5`.
12
+ */
13
+ export declare class JWKSUrlPolicy {
14
+ /**
15
+ * Refuses an entry of `jwks.hosts.http` that is not exactly a host with an optional port, and answers the entries
16
+ * in the form a URL is matched in: the host as the URL parser writes it (lower case), then `:port` when there is one.
17
+ * An entry is valid only when `new URL('http://' + entry)` gives the same host back, and the same port.
18
+ */
19
+ static resolveHttpHosts(opts: {
20
+ scope: string;
21
+ hosts?: unknown;
22
+ }): ReadonlySet<string>;
23
+ /** The canonical form of one entry, or `undefined` when it is not exactly a host with an optional port. */
24
+ private static canonicalEntry;
25
+ /** Whether a name is within the DNS limits: 253 characters, and 63 for each label. */
26
+ private static isWithinLimits;
27
+ /** `http://<authority>` through the URL parser, or `undefined` when it refuses it. */
28
+ private static parseHttp;
29
+ /** Whether the URL parser's hostname is a loopback one: `localhost`, `127.0.0.0/8` or `::1`. */
30
+ static isLoopback(hostname: string): boolean;
31
+ /**
32
+ * Parses a JWKS URL and refuses it unless it is `https:`, or `http:` to a loopback host or a host listed in
33
+ * `jwks.hosts.http`. Only the host name goes into the message: a URL may carry credentials.
34
+ */
35
+ static assertUrl(opts: {
36
+ scope: string;
37
+ label: string;
38
+ url: string;
39
+ hosts?: unknown;
40
+ }): URL;
41
+ }
42
+ //# sourceMappingURL=jwks-url-policy.d.ts.map
@@ -0,0 +1,162 @@
1
+ import { HTTP } from '@venizia/ignis-helpers/common';
2
+ import { getError } from '@venizia/ignis-helpers/core';
3
+ /** One host name: labels of letters, digits and hyphens joined by single dots - no empty label, no wildcard. */
4
+ const HOST_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/;
5
+ /** An IPv4 address, in any spelling a caller might write; the URL parser decides whether it is the address it looks like. */
6
+ const IPV4_PATTERN = /^\d{1,3}(?:\.\d{1,3}){3}$/;
7
+ /**
8
+ * An entry of `jwks.hosts.http`: a host (a name, an IPv4 address, or an IPv6 address in brackets) and an optional
9
+ * `:port`. Nothing else: no scheme, path, userinfo or wildcard.
10
+ */
11
+ const ENTRY_PATTERN = /^(?<host>\[[0-9a-f:.]+\]|[a-z0-9][a-z0-9.-]*)(?::(?<port>[0-9]{1,5}))?$/;
12
+ /** The port of an `http:` URL that names none. */
13
+ const DEFAULT_HTTP_PORT = '80';
14
+ /** The longest label and the longest name DNS has (RFC 1035): a longer entry is not a host name. */
15
+ const MAX_LABEL_LENGTH = 63;
16
+ const MAX_NAME_LENGTH = 253;
17
+ /** The addresses that mean "any local address", not a host: as the URL parser writes them. */
18
+ const UNSPECIFIED_HOSTS = new Set(['0.0.0.0', '[::]']);
19
+ /** `127.0.0.0/8`, as the URL parser writes an IPv4 host. */
20
+ const LOOPBACK_IPV4_PATTERN = /^127(?:\.\d{1,3}){3}$/;
21
+ const LOOPBACK_HOSTS = new Set(['localhost', '[::1]']);
22
+ /**
23
+ * Where a JWKS may be fetched from. A key set read over plain `http:` can be replaced on the way, and
24
+ * whoever replaces it signs tokens that verify, so a JWKS URL is `https:` unless its host is loopback or
25
+ * is listed in `jwks.hosts.http`. The one policy serves the JWKS verifier and the service-assertion
26
+ * callers: both fetch a key set to decide who may call.
27
+ *
28
+ * The opt-in is an EXACT entry, never a pattern or a range: a host name, an IPv4 address, or an IPv6 address in
29
+ * brackets, each optionally with a port (`identity-service`, `10.0.0.5:8080`, `[fd00::1]:8443`). An entry without a
30
+ * port covers every port of that host; an entry with one covers that port only. An entry and a URL are both read by
31
+ * the URL parser, so the two sides are compared in the form the parser gives them: `http://2130706433` is
32
+ * `127.0.0.1`, and `http://[::ffff:10.0.0.5]` is `[::ffff:a00:5]`, which is not `10.0.0.5`.
33
+ */
34
+ export class JWKSUrlPolicy {
35
+ /**
36
+ * Refuses an entry of `jwks.hosts.http` that is not exactly a host with an optional port, and answers the entries
37
+ * in the form a URL is matched in: the host as the URL parser writes it (lower case), then `:port` when there is one.
38
+ * An entry is valid only when `new URL('http://' + entry)` gives the same host back, and the same port.
39
+ */
40
+ static resolveHttpHosts(opts) {
41
+ const { scope, hosts } = opts;
42
+ if (hosts === undefined) {
43
+ return new Set();
44
+ }
45
+ if (!Array.isArray(hosts)) {
46
+ throw getError({
47
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
48
+ message: `[${scope}] jwks.hosts.http must be a list of hosts`,
49
+ });
50
+ }
51
+ const resolved = new Set();
52
+ for (const entry of hosts) {
53
+ const canonical = typeof entry === 'string' ? JWKSUrlPolicy.canonicalEntry({ entry }) : undefined;
54
+ if (canonical === undefined) {
55
+ throw getError({
56
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
57
+ message: `[${scope}] jwks.hosts.http holds ${JSON.stringify(entry)} | list exact hosts only: a name, an IPv4 address or an IPv6 address in brackets, with an optional :port, for example 'identity-service', '10.0.0.5:8080' or '[fd00::1]:8443' - no scheme, path, credentials, wildcard or range`,
58
+ });
59
+ }
60
+ resolved.add(canonical);
61
+ }
62
+ return resolved;
63
+ }
64
+ /** The canonical form of one entry, or `undefined` when it is not exactly a host with an optional port. */
65
+ static canonicalEntry(opts) {
66
+ // Not trimmed: an entry with a space, a tab or a newline around it is a typo, and is refused rather than corrected.
67
+ const matched = ENTRY_PATTERN.exec(opts.entry.toLowerCase());
68
+ const { host, port } = matched?.groups ?? {};
69
+ if (host === undefined) {
70
+ return undefined;
71
+ }
72
+ // A name has labels of its own shape; an IPv4 or an IPv6 address is judged by the parser alone, below.
73
+ const isAddress = host.startsWith('[') || IPV4_PATTERN.test(host);
74
+ if (!isAddress &&
75
+ !(HOST_NAME_PATTERN.test(host) && JWKSUrlPolicy.isWithinLimits({ name: host }))) {
76
+ return undefined;
77
+ }
78
+ const parsed = JWKSUrlPolicy.parseHttp({
79
+ authority: port === undefined ? host : `${host}:${port}`,
80
+ });
81
+ // The host must be what the parser makes of it: `2130706433`, `0x7f000001`, `1.2.3`, `010.0.0.5` and
82
+ // `[::ffff:10.0.0.5]` are spellings the parser rewrites, so none of them is the host it looks like.
83
+ if (parsed === undefined || parsed.hostname !== host || UNSPECIFIED_HOSTS.has(host)) {
84
+ return undefined;
85
+ }
86
+ if (port === undefined) {
87
+ return host;
88
+ }
89
+ // The parser drops the default port, so `:80` reads back as no port; a port is valid only as the parser keeps it.
90
+ const kept = parsed.port === '' ? DEFAULT_HTTP_PORT : parsed.port;
91
+ if (kept !== port || Number(port) < 1) {
92
+ return undefined;
93
+ }
94
+ return `${host}:${port}`;
95
+ }
96
+ /** Whether a name is within the DNS limits: 253 characters, and 63 for each label. */
97
+ static isWithinLimits(opts) {
98
+ return (opts.name.length <= MAX_NAME_LENGTH &&
99
+ opts.name.split('.').every((label) => label.length <= MAX_LABEL_LENGTH));
100
+ }
101
+ /** `http://<authority>` through the URL parser, or `undefined` when it refuses it. */
102
+ static parseHttp(opts) {
103
+ try {
104
+ return new URL(`http://${opts.authority}`);
105
+ // eslint-disable-next-line venizia/no-silent-catch -- an authority the parser refuses is not a host: the caller refuses the entry
106
+ }
107
+ catch {
108
+ return undefined;
109
+ }
110
+ }
111
+ /** Whether the URL parser's hostname is a loopback one: `localhost`, `127.0.0.0/8` or `::1`. */
112
+ static isLoopback(hostname) {
113
+ return LOOPBACK_HOSTS.has(hostname) || LOOPBACK_IPV4_PATTERN.test(hostname);
114
+ }
115
+ /**
116
+ * Parses a JWKS URL and refuses it unless it is `https:`, or `http:` to a loopback host or a host listed in
117
+ * `jwks.hosts.http`. Only the host name goes into the message: a URL may carry credentials.
118
+ */
119
+ static assertUrl(opts) {
120
+ const { scope, label, url } = opts;
121
+ let parsed;
122
+ try {
123
+ parsed = new URL(url);
124
+ // eslint-disable-next-line venizia/no-silent-catch -- the refusal below names the key and withholds the URL, which may carry credentials
125
+ }
126
+ catch {
127
+ throw getError({
128
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
129
+ message: `[${scope}] ${label} is not a valid URL`,
130
+ });
131
+ }
132
+ if (parsed.protocol === 'https:') {
133
+ return parsed;
134
+ }
135
+ if (parsed.protocol !== 'http:') {
136
+ throw getError({
137
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
138
+ message: `[${scope}] ${label} must use https | scheme: ${parsed.protocol}`,
139
+ });
140
+ }
141
+ const allowed = JWKSUrlPolicy.resolveHttpHosts({ scope, hosts: opts.hosts });
142
+ // Nothing listens on port 0: a URL that names it is a mistake, and no entry without a port should cover it.
143
+ if (parsed.port === '0') {
144
+ throw getError({
145
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
146
+ message: `[${scope}] ${label} uses port 0 | the host is '${parsed.hostname}'`,
147
+ });
148
+ }
149
+ // An entry without a port covers every port; one with a port covers that port only (an `http:` URL with none is on 80).
150
+ const port = parsed.port === '' ? DEFAULT_HTTP_PORT : parsed.port;
151
+ if (JWKSUrlPolicy.isLoopback(parsed.hostname) ||
152
+ allowed.has(parsed.hostname) ||
153
+ allowed.has(`${parsed.hostname}:${port}`)) {
154
+ return parsed;
155
+ }
156
+ throw getError({
157
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
158
+ message: `[${scope}] ${label} uses http: and the host '${parsed.hostname}' is not allowed | use https, or list the host in jwks.hosts.http`,
159
+ });
160
+ }
161
+ }
162
+ //# sourceMappingURL=jwks-url-policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwks-url-policy.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/services/jwks-url-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,gHAAgH;AAChH,MAAM,iBAAiB,GAAG,yEAAyE,CAAC;AAEpG,6HAA6H;AAC7H,MAAM,YAAY,GAAG,2BAA2B,CAAC;AAEjD;;;GAGG;AACH,MAAM,aAAa,GAAG,y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AAM,CAAC,QAAQ,CAAC;YAC5B,OAAO,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,QAAQ,IAAI,IAAI,EAAE,CAAC,EACzC,CAAC;YACD,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,MAAM,QAAQ,CAAC;YACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;YACrD,OAAO,EAAE,IAAI,KAAK,KAAK,KAAK,6BAA6B,MAAM,CAAC,QAAQ,mEAAmE;SAC5I,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\n\n/** One host name: labels of letters, digits and hyphens joined by single dots - no empty label, no wildcard. */\nconst HOST_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/;\n\n/** An IPv4 address, in any spelling a caller might write; the URL parser decides whether it is the address it looks like. */\nconst IPV4_PATTERN = /^\\d{1,3}(?:\\.\\d{1,3}){3}$/;\n\n/**\n * An entry of `jwks.hosts.http`: a host (a name, an IPv4 address, or an IPv6 address in brackets) and an optional\n * `:port`. Nothing else: no scheme, path, userinfo or wildcard.\n */\nconst ENTRY_PATTERN = /^(?<host>\\[[0-9a-f:.]+\\]|[a-z0-9][a-z0-9.-]*)(?::(?<port>[0-9]{1,5}))?$/;\n\n/** The port of an `http:` URL that names none. */\nconst DEFAULT_HTTP_PORT = '80';\n\n/** The longest label and the longest name DNS has (RFC 1035): a longer entry is not a host name. */\nconst MAX_LABEL_LENGTH = 63;\nconst MAX_NAME_LENGTH = 253;\n\n/** The addresses that mean \"any local address\", not a host: as the URL parser writes them. */\nconst UNSPECIFIED_HOSTS: ReadonlySet<string> = new Set(['0.0.0.0', '[::]']);\n\n/** `127.0.0.0/8`, as the URL parser writes an IPv4 host. */\nconst LOOPBACK_IPV4_PATTERN = /^127(?:\\.\\d{1,3}){3}$/;\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '[::1]']);\n\n/**\n * Where a JWKS may be fetched from. A key set read over plain `http:` can be replaced on the way, and\n * whoever replaces it signs tokens that verify, so a JWKS URL is `https:` unless its host is loopback or\n * is listed in `jwks.hosts.http`. The one policy serves the JWKS verifier and the service-assertion\n * callers: both fetch a key set to decide who may call.\n *\n * The opt-in is an EXACT entry, never a pattern or a range: a host name, an IPv4 address, or an IPv6 address in\n * brackets, each optionally with a port (`identity-service`, `10.0.0.5:8080`, `[fd00::1]:8443`). An entry without a\n * port covers every port of that host; an entry with one covers that port only. An entry and a URL are both read by\n * the URL parser, so the two sides are compared in the form the parser gives them: `http://2130706433` is\n * `127.0.0.1`, and `http://[::ffff:10.0.0.5]` is `[::ffff:a00:5]`, which is not `10.0.0.5`.\n */\nexport class JWKSUrlPolicy {\n /**\n * Refuses an entry of `jwks.hosts.http` that is not exactly a host with an optional port, and answers the entries\n * in the form a URL is matched in: the host as the URL parser writes it (lower case), then `:port` when there is one.\n * An entry is valid only when `new URL('http://' + entry)` gives the same host back, and the same port.\n */\n static resolveHttpHosts(opts: { scope: string; hosts?: unknown }): ReadonlySet<string> {\n const { scope, hosts } = opts;\n\n if (hosts === undefined) {\n return new Set();\n }\n\n if (!Array.isArray(hosts)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] jwks.hosts.http must be a list of hosts`,\n });\n }\n\n const resolved = new Set<string>();\n\n for (const entry of hosts) {\n const canonical =\n typeof entry === 'string' ? JWKSUrlPolicy.canonicalEntry({ entry }) : undefined;\n\n if (canonical === undefined) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] jwks.hosts.http holds ${JSON.stringify(entry)} | list exact hosts only: a name, an IPv4 address or an IPv6 address in brackets, with an optional :port, for example 'identity-service', '10.0.0.5:8080' or '[fd00::1]:8443' - no scheme, path, credentials, wildcard or range`,\n });\n }\n\n resolved.add(canonical);\n }\n\n return resolved;\n }\n\n /** The canonical form of one entry, or `undefined` when it is not exactly a host with an optional port. */\n private static canonicalEntry(opts: { entry: string }): string | undefined {\n // Not trimmed: an entry with a space, a tab or a newline around it is a typo, and is refused rather than corrected.\n const matched = ENTRY_PATTERN.exec(opts.entry.toLowerCase());\n const { host, port } = matched?.groups ?? {};\n\n if (host === undefined) {\n return undefined;\n }\n\n // A name has labels of its own shape; an IPv4 or an IPv6 address is judged by the parser alone, below.\n const isAddress = host.startsWith('[') || IPV4_PATTERN.test(host);\n\n if (\n !isAddress &&\n !(HOST_NAME_PATTERN.test(host) && JWKSUrlPolicy.isWithinLimits({ name: host }))\n ) {\n return undefined;\n }\n\n const parsed = JWKSUrlPolicy.parseHttp({\n authority: port === undefined ? host : `${host}:${port}`,\n });\n\n // The host must be what the parser makes of it: `2130706433`, `0x7f000001`, `1.2.3`, `010.0.0.5` and\n // `[::ffff:10.0.0.5]` are spellings the parser rewrites, so none of them is the host it looks like.\n if (parsed === undefined || parsed.hostname !== host || UNSPECIFIED_HOSTS.has(host)) {\n return undefined;\n }\n\n if (port === undefined) {\n return host;\n }\n\n // The parser drops the default port, so `:80` reads back as no port; a port is valid only as the parser keeps it.\n const kept = parsed.port === '' ? DEFAULT_HTTP_PORT : parsed.port;\n\n if (kept !== port || Number(port) < 1) {\n return undefined;\n }\n\n return `${host}:${port}`;\n }\n\n /** Whether a name is within the DNS limits: 253 characters, and 63 for each label. */\n private static isWithinLimits(opts: { name: string }): boolean {\n return (\n opts.name.length <= MAX_NAME_LENGTH &&\n opts.name.split('.').every((label) => label.length <= MAX_LABEL_LENGTH)\n );\n }\n\n /** `http://<authority>` through the URL parser, or `undefined` when it refuses it. */\n private static parseHttp(opts: { authority: string }): URL | undefined {\n try {\n return new URL(`http://${opts.authority}`);\n // eslint-disable-next-line venizia/no-silent-catch -- an authority the parser refuses is not a host: the caller refuses the entry\n } catch {\n return undefined;\n }\n }\n\n /** Whether the URL parser's hostname is a loopback one: `localhost`, `127.0.0.0/8` or `::1`. */\n static isLoopback(hostname: string): boolean {\n return LOOPBACK_HOSTS.has(hostname) || LOOPBACK_IPV4_PATTERN.test(hostname);\n }\n\n /**\n * Parses a JWKS URL and refuses it unless it is `https:`, or `http:` to a loopback host or a host listed in\n * `jwks.hosts.http`. Only the host name goes into the message: a URL may carry credentials.\n */\n static assertUrl(opts: { scope: string; label: string; url: string; hosts?: unknown }): URL {\n const { scope, label, url } = opts;\n\n let parsed: URL;\n\n try {\n parsed = new URL(url);\n // eslint-disable-next-line venizia/no-silent-catch -- the refusal below names the key and withholds the URL, which may carry credentials\n } catch {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} is not a valid URL`,\n });\n }\n\n if (parsed.protocol === 'https:') {\n return parsed;\n }\n\n if (parsed.protocol !== 'http:') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} must use https | scheme: ${parsed.protocol}`,\n });\n }\n\n const allowed = JWKSUrlPolicy.resolveHttpHosts({ scope, hosts: opts.hosts });\n\n // Nothing listens on port 0: a URL that names it is a mistake, and no entry without a port should cover it.\n if (parsed.port === '0') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} uses port 0 | the host is '${parsed.hostname}'`,\n });\n }\n\n // An entry without a port covers every port; one with a port covers that port only (an `http:` URL with none is on 80).\n const port = parsed.port === '' ? DEFAULT_HTTP_PORT : parsed.port;\n\n if (\n JWKSUrlPolicy.isLoopback(parsed.hostname) ||\n allowed.has(parsed.hostname) ||\n allowed.has(`${parsed.hostname}:${port}`)\n ) {\n return parsed;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} uses http: and the host '${parsed.hostname}' is not allowed | use https, or list the host in jwks.hosts.http`,\n });\n }\n}\n"]}
@@ -15,6 +15,7 @@ import { inject } from '../../../../../base/metadata/index.js';
15
15
  import { AuthenticateBindingKeys, AuthenticationErrors, BaseService, ServiceAssertion, } from '@venizia/ignis-kernel';
16
16
  import { getError } from '@venizia/ignis-helpers/core';
17
17
  import { JoseLoader } from '../jose-loader.js';
18
+ import { JWKSUrlPolicy } from '../jwks-url-policy.js';
18
19
  /**
19
20
  * Verifies an incoming service assertion against the CALLER's own JWKS.
20
21
  *
@@ -91,7 +92,12 @@ let ServiceAssertionVerifierService = ServiceAssertionVerifierService_1 = class
91
92
  callerOverride: typeof entry === 'string' ? undefined : entry.acceptMaxAgeSeconds,
92
93
  serviceDefault: this.options.acceptMaxAgeSeconds,
93
94
  }));
94
- const keySet = jose.createRemoteJWKSet(new URL(jwksUrl), {
95
+ const keySet = jose.createRemoteJWKSet(JWKSUrlPolicy.assertUrl({
96
+ scope: ServiceAssertionVerifierService_1.name,
97
+ label: 'the caller jwksUrl',
98
+ url: jwksUrl,
99
+ hosts: this.options.jwks?.hosts?.http,
100
+ }), {
95
101
  cacheMaxAge: this.options.jwks?.cacheMaxAgeMs ?? ServiceAssertion.DEFAULT_JWKS_CACHE_MAX_AGE_MS,
96
102
  cooldownDuration: this.options.jwks?.cooldownMs ?? ServiceAssertion.DEFAULT_JWKS_COOLDOWN_MS,
97
103
  });
@@ -1 +1 @@
1
- {"version":3,"file":"verifier.service.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authenticate/services/service/verifier.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EACL,uBAAuB,EACvB,oBAAoB,EACpB,WAAW,EACX,gBAAgB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAI5C;;;;;;;;GAQG;AACH,IAAa,+BAA+B,uCAA5C,MAAa,+BAAgC,SAAQ,WAAW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,CAAC;YACtB,OAAO;QACT,CAAC;QAED,IAAI,CAAC,MAAM;aACR,GAAG,CAAC,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC;aACnC,IAAI,CAAC,oDAAoD,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;QAE9E,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAE,oBAAoB,CAAC,wBAAwB,EAAE,CAAC,CAAC;IAC3E,CAAC;CACF,CAAA;AAhLY,+BAA+B;IAQvC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,eAAe,EAAE,CAAC,CAAA;;GARhD,+BAA+B,CAgL3C","sourcesContent":["import { inject } from '@/base/metadata';\nimport {\n AuthenticateBindingKeys,\n AuthenticationErrors,\n BaseService,\n ServiceAssertion,\n} from '@venizia/ignis-kernel';\nimport type { IServiceAssertionClaims, IServiceAuthOptions } from '@venizia/ignis-kernel';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { createRemoteJWKSet } from 'jose';\nimport { JoseLoader } from '../jose-loader';\n\ntype TRemoteKeySet = ReturnType<typeof createRemoteJWKSet>;\n\n/**\n * Verifies an incoming service assertion against the CALLER's own JWKS.\n *\n * What the assertion covers, and nothing else: the HTTP method and the percent-encoded path. It does\n * NOT cover the query string, any header, or the body. Tenant selectors in particular are usually a\n * header or a query parameter, so an assertion alone does not authenticate which tenant a call acts\n * on - the caller allowlist and the application's own scoping have to do that. Stated because the\n * gap is invisible from the call site.\n */\nexport class ServiceAssertionVerifierService extends BaseService {\n /** One remote key set per caller, kept because `createRemoteJWKSet` owns its own cache. */\n private readonly keySets = new Map<string, TRemoteKeySet>();\n\n /** Per-caller accepted age, resolved once alongside its key set. */\n private readonly acceptMaxAges = new Map<string, number>();\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.SERVICE_OPTIONS })\n private readonly options: IServiceAuthOptions,\n ) {\n super({ scope: ServiceAssertionVerifierService.name });\n }\n\n /**\n * @param path The percent-ENCODED pathname, from `new URL(context.req.url).pathname`. Never\n * `context.req.path` - Hono decodes that one, and the caller signed the encoded form.\n */\n async verify(opts: { token: string; method: string; path: string }): Promise<{ issuer: string }> {\n const { token, method, path } = opts;\n\n const jose = await JoseLoader.load();\n const issuer = this.readIssuer({ token, jose });\n const keySet = this.resolveKeySet({ issuer, jose });\n const payload = await this.runVerify({ token, issuer, keySet, jose });\n\n this.assertRequestBinding({ payload, method, path });\n\n return { issuer };\n }\n\n /**\n * Reads `iss` WITHOUT verifying, only to choose which key set checks the signature. The same value\n * is then enforced as the expected issuer, so a forged `iss` buys nothing beyond selecting the key\n * set that will reject it.\n */\n private readIssuer(opts: { token: string; jose: typeof import('jose') }): string {\n let issuer: unknown;\n\n try {\n ({ iss: issuer } = opts.jose.decodeJwt(opts.token));\n } catch (error) {\n this.logger.for(this.readIssuer.name).warn('Undecodable assertion | error: %s', error);\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID });\n }\n\n // Typed, not merely present: a numeric `iss` would index the caller map by coercion.\n if (typeof issuer !== 'string' || issuer.length === 0) {\n this.logger\n .for(this.readIssuer.name)\n .warn('Undecodable assertion | iss is missing or not a string');\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID });\n }\n\n return issuer;\n }\n\n private resolveKeySet(opts: { issuer: string; jose: typeof import('jose') }): TRemoteKeySet {\n const { issuer, jose } = opts;\n\n const cached = this.keySets.get(issuer);\n\n if (cached) {\n return cached;\n }\n\n const callers = this.options.callers ?? {};\n\n // `Object.hasOwn`, never a truthiness check on the index: the map arrives as a plain object, so\n // `iss: 'constructor'` would otherwise return `Function` - truthy - walk past this guard, and\n // reach `new URL(<function>)` as an uncaught TypeError.\n if (!Object.hasOwn(callers, issuer)) {\n this.logger\n .for(this.resolveKeySet.name)\n .warn('Caller not on the allowlist | iss: %s', issuer);\n throw getError({ error: AuthenticationErrors.CALLER_NOT_ALLOWED });\n }\n\n const entry = callers[issuer];\n const jwksUrl = typeof entry === 'string' ? entry : entry.jwksUrl;\n\n this.acceptMaxAges.set(\n issuer,\n ServiceAssertion.resolveAcceptMaxAge({\n callerOverride: typeof entry === 'string' ? undefined : entry.acceptMaxAgeSeconds,\n serviceDefault: this.options.acceptMaxAgeSeconds,\n }),\n );\n\n const keySet = jose.createRemoteJWKSet(new URL(jwksUrl), {\n cacheMaxAge:\n this.options.jwks?.cacheMaxAgeMs ?? ServiceAssertion.DEFAULT_JWKS_CACHE_MAX_AGE_MS,\n cooldownDuration: this.options.jwks?.cooldownMs ?? ServiceAssertion.DEFAULT_JWKS_COOLDOWN_MS,\n });\n\n this.keySets.set(issuer, keySet);\n\n return keySet;\n }\n\n private async runVerify(opts: {\n token: string;\n issuer: string;\n keySet: TRemoteKeySet;\n jose: typeof import('jose');\n }): Promise<IServiceAssertionClaims> {\n const { token, issuer, keySet, jose } = opts;\n\n // Resolved when the key set was, so a per-caller override is already folded in.\n const maxTokenAge =\n this.acceptMaxAges.get(issuer) ??\n ServiceAssertion.resolveAcceptMaxAge({\n serviceDefault: this.options.acceptMaxAgeSeconds,\n });\n\n const clockTolerance =\n this.options.clockToleranceSeconds ?? ServiceAssertion.DEFAULT_CLOCK_TOLERANCE_SECONDS;\n\n try {\n const { payload } = await jose.jwtVerify<IServiceAssertionClaims>(token, keySet, {\n algorithms: [ServiceAssertion.ALGORITHM],\n typ: ServiceAssertion.TYP,\n issuer,\n audience: this.options.name,\n // NOT redundant with `exp`, though it looks it. An honest caller stamps `exp = iat +\n // lifetime`, so the two are numerically tied and jose reaches `exp` first - measured.\n // `maxTokenAge` is the only bound that still holds when the CALLER is the attacker and picks\n // its own `exp`, which is precisely the case it exists for. Do not delete it as dead config.\n //\n // And it is the CALLEE's number, never one the caller may request: a caller that could ask\n // for a longer window would be choosing its own replay window, which is the whole thing this\n // is here to deny.\n //\n // TWO NUMBERS, and they answer different questions. Measured at the defaults, 60 + 5:\n // - 65s is the ACCEPTANCE window on this machine's clock. Age 64 passes, 65 does not.\n // - 70s is the REPLAY window in wall-clock time, when the caller's clock runs the full\n // tolerance fast: we accept an `iat` up to 5s in our future, then keep accepting for\n // another 64. Measured: still accepted 69s after minting.\n // The second is the one a threat model asks for. Widening `clockToleranceSeconds` widens it\n // second for second, so it is a security knob, not an operational one.\n maxTokenAge,\n clockTolerance,\n requiredClaims: ['htm', 'htu', 'jti'],\n });\n\n return payload;\n } catch (error) {\n // One code out, the reason on `cause`: a wrong audience, clock skew and a rotated key are\n // otherwise the same string to whoever is reading the log at 2am.\n const reason = (error as { cause?: unknown })?.cause ?? error;\n this.logger.for(this.runVerify.name).warn('Rejected | iss: %s | reason: %s', issuer, reason);\n\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID, cause: error });\n }\n }\n\n private assertRequestBinding(opts: {\n payload: IServiceAssertionClaims;\n method: string;\n path: string;\n }): void {\n const { payload, method, path } = opts;\n\n const signed = `${payload.htm} ${payload.htu}`;\n const actual = `${method.toUpperCase()} ${path}`;\n\n if (signed === actual) {\n return;\n }\n\n this.logger\n .for(this.assertRequestBinding.name)\n .warn('Request binding mismatch | signed: %s | actual: %s', signed, actual);\n\n throw getError({ error: AuthenticationErrors.REQUEST_BINDING_MISMATCH });\n }\n}\n"]}
1
+ {"version":3,"file":"verifier.service.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authenticate/services/service/verifier.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EACL,uBAAuB,EACvB,oBAAoB,EACpB,WAAW,EACX,gBAAgB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAInD;;;;;;;;GAQG;AACH,IAAa,+BAA+B,uCAA5C,MAAa,+BAAgC,SAAQ,WAAW;IAO9D,YAEE,OAA6C;QAE7C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AC,GAAG,EAAE,CAAC;QAC/C,MAAM,MAAM,GAAG,GAAG,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,EAAE,CAAC;QAEjD,IAAI,MAAM,KAAK,MAAM,EAAE,CAAC;YACtB,OAAO;QACT,CAAC;QAED,IAAI,CAAC,MAAM;aACR,GAAG,CAAC,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC;aACnC,IAAI,CAAC,oDAAoD,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;QAE9E,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAE,oBAAoB,CAAC,wBAAwB,EAAE,CAAC,CAAC;IAC3E,CAAC;CACF,CAAA;AAzLY,+BAA+B;IAQvC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,eAAe,EAAE,CAAC,CAAA;;GARhD,+BAA+B,CAyL3C","sourcesContent":["import { inject } from '@/base/metadata';\nimport {\n AuthenticateBindingKeys,\n AuthenticationErrors,\n BaseService,\n ServiceAssertion,\n} from '@venizia/ignis-kernel';\nimport type { IServiceAssertionClaims, IServiceAuthOptions } from '@venizia/ignis-kernel';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { createRemoteJWKSet } from 'jose';\nimport { JoseLoader } from '../jose-loader';\nimport { JWKSUrlPolicy } from '../jwks-url-policy';\n\ntype TRemoteKeySet = ReturnType<typeof createRemoteJWKSet>;\n\n/**\n * Verifies an incoming service assertion against the CALLER's own JWKS.\n *\n * What the assertion covers, and nothing else: the HTTP method and the percent-encoded path. It does\n * NOT cover the query string, any header, or the body. Tenant selectors in particular are usually a\n * header or a query parameter, so an assertion alone does not authenticate which tenant a call acts\n * on - the caller allowlist and the application's own scoping have to do that. Stated because the\n * gap is invisible from the call site.\n */\nexport class ServiceAssertionVerifierService extends BaseService {\n /** One remote key set per caller, kept because `createRemoteJWKSet` owns its own cache. */\n private readonly keySets = new Map<string, TRemoteKeySet>();\n\n /** Per-caller accepted age, resolved once alongside its key set. */\n private readonly acceptMaxAges = new Map<string, number>();\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.SERVICE_OPTIONS })\n private readonly options: IServiceAuthOptions,\n ) {\n super({ scope: ServiceAssertionVerifierService.name });\n }\n\n /**\n * @param path The percent-ENCODED pathname, from `new URL(context.req.url).pathname`. Never\n * `context.req.path` - Hono decodes that one, and the caller signed the encoded form.\n */\n async verify(opts: { token: string; method: string; path: string }): Promise<{ issuer: string }> {\n const { token, method, path } = opts;\n\n const jose = await JoseLoader.load();\n const issuer = this.readIssuer({ token, jose });\n const keySet = this.resolveKeySet({ issuer, jose });\n const payload = await this.runVerify({ token, issuer, keySet, jose });\n\n this.assertRequestBinding({ payload, method, path });\n\n return { issuer };\n }\n\n /**\n * Reads `iss` WITHOUT verifying, only to choose which key set checks the signature. The same value\n * is then enforced as the expected issuer, so a forged `iss` buys nothing beyond selecting the key\n * set that will reject it.\n */\n private readIssuer(opts: { token: string; jose: typeof import('jose') }): string {\n let issuer: unknown;\n\n try {\n ({ iss: issuer } = opts.jose.decodeJwt(opts.token));\n } catch (error) {\n this.logger.for(this.readIssuer.name).warn('Undecodable assertion | error: %s', error);\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID });\n }\n\n // Typed, not merely present: a numeric `iss` would index the caller map by coercion.\n if (typeof issuer !== 'string' || issuer.length === 0) {\n this.logger\n .for(this.readIssuer.name)\n .warn('Undecodable assertion | iss is missing or not a string');\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID });\n }\n\n return issuer;\n }\n\n private resolveKeySet(opts: { issuer: string; jose: typeof import('jose') }): TRemoteKeySet {\n const { issuer, jose } = opts;\n\n const cached = this.keySets.get(issuer);\n\n if (cached) {\n return cached;\n }\n\n const callers = this.options.callers ?? {};\n\n // `Object.hasOwn`, never a truthiness check on the index: the map arrives as a plain object, so\n // `iss: 'constructor'` would otherwise return `Function` - truthy - walk past this guard, and\n // reach `new URL(<function>)` as an uncaught TypeError.\n if (!Object.hasOwn(callers, issuer)) {\n this.logger\n .for(this.resolveKeySet.name)\n .warn('Caller not on the allowlist | iss: %s', issuer);\n throw getError({ error: AuthenticationErrors.CALLER_NOT_ALLOWED });\n }\n\n const entry = callers[issuer];\n const jwksUrl = typeof entry === 'string' ? entry : entry.jwksUrl;\n\n this.acceptMaxAges.set(\n issuer,\n ServiceAssertion.resolveAcceptMaxAge({\n callerOverride: typeof entry === 'string' ? undefined : entry.acceptMaxAgeSeconds,\n serviceDefault: this.options.acceptMaxAgeSeconds,\n }),\n );\n\n const keySet = jose.createRemoteJWKSet(\n JWKSUrlPolicy.assertUrl({\n scope: ServiceAssertionVerifierService.name,\n label: 'the caller jwksUrl',\n url: jwksUrl,\n hosts: this.options.jwks?.hosts?.http,\n }),\n {\n cacheMaxAge:\n this.options.jwks?.cacheMaxAgeMs ?? ServiceAssertion.DEFAULT_JWKS_CACHE_MAX_AGE_MS,\n cooldownDuration:\n this.options.jwks?.cooldownMs ?? ServiceAssertion.DEFAULT_JWKS_COOLDOWN_MS,\n },\n );\n\n this.keySets.set(issuer, keySet);\n\n return keySet;\n }\n\n private async runVerify(opts: {\n token: string;\n issuer: string;\n keySet: TRemoteKeySet;\n jose: typeof import('jose');\n }): Promise<IServiceAssertionClaims> {\n const { token, issuer, keySet, jose } = opts;\n\n // Resolved when the key set was, so a per-caller override is already folded in.\n const maxTokenAge =\n this.acceptMaxAges.get(issuer) ??\n ServiceAssertion.resolveAcceptMaxAge({\n serviceDefault: this.options.acceptMaxAgeSeconds,\n });\n\n const clockTolerance =\n this.options.clockToleranceSeconds ?? ServiceAssertion.DEFAULT_CLOCK_TOLERANCE_SECONDS;\n\n try {\n const { payload } = await jose.jwtVerify<IServiceAssertionClaims>(token, keySet, {\n algorithms: [ServiceAssertion.ALGORITHM],\n typ: ServiceAssertion.TYP,\n issuer,\n audience: this.options.name,\n // NOT redundant with `exp`, though it looks it. An honest caller stamps `exp = iat +\n // lifetime`, so the two are numerically tied and jose reaches `exp` first - measured.\n // `maxTokenAge` is the only bound that still holds when the CALLER is the attacker and picks\n // its own `exp`, which is precisely the case it exists for. Do not delete it as dead config.\n //\n // And it is the CALLEE's number, never one the caller may request: a caller that could ask\n // for a longer window would be choosing its own replay window, which is the whole thing this\n // is here to deny.\n //\n // TWO NUMBERS, and they answer different questions. Measured at the defaults, 60 + 5:\n // - 65s is the ACCEPTANCE window on this machine's clock. Age 64 passes, 65 does not.\n // - 70s is the REPLAY window in wall-clock time, when the caller's clock runs the full\n // tolerance fast: we accept an `iat` up to 5s in our future, then keep accepting for\n // another 64. Measured: still accepted 69s after minting.\n // The second is the one a threat model asks for. Widening `clockToleranceSeconds` widens it\n // second for second, so it is a security knob, not an operational one.\n maxTokenAge,\n clockTolerance,\n requiredClaims: ['htm', 'htu', 'jti'],\n });\n\n return payload;\n } catch (error) {\n // One code out, the reason on `cause`: a wrong audience, clock skew and a rotated key are\n // otherwise the same string to whoever is reading the log at 2am.\n const reason = (error as { cause?: unknown })?.cause ?? error;\n this.logger.for(this.runVerify.name).warn('Rejected | iss: %s | reason: %s', issuer, reason);\n\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID, cause: error });\n }\n }\n\n private assertRequestBinding(opts: {\n payload: IServiceAssertionClaims;\n method: string;\n path: string;\n }): void {\n const { payload, method, path } = opts;\n\n const signed = `${payload.htm} ${payload.htu}`;\n const actual = `${method.toUpperCase()} ${path}`;\n\n if (signed === actual) {\n return;\n }\n\n this.logger\n .for(this.assertRequestBinding.name)\n .warn('Request binding mismatch | signed: %s | actual: %s', signed, actual);\n\n throw getError({ error: AuthenticationErrors.REQUEST_BINDING_MISMATCH });\n }\n}\n"]}