alepha 0.13.0 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (461) hide show
  1. package/README.md +1 -1
  2. package/dist/api-files/index.d.ts +28 -91
  3. package/dist/api-files/index.js +10 -755
  4. package/dist/api-files/index.js.map +1 -1
  5. package/dist/api-jobs/index.d.ts +67 -67
  6. package/dist/api-jobs/index.js +13 -13
  7. package/dist/api-jobs/index.js.map +1 -1
  8. package/dist/api-notifications/index.d.ts +129 -146
  9. package/dist/api-notifications/index.js +17 -39
  10. package/dist/api-notifications/index.js.map +1 -1
  11. package/dist/api-parameters/index.d.ts +21 -22
  12. package/dist/api-parameters/index.js +22 -22
  13. package/dist/api-parameters/index.js.map +1 -1
  14. package/dist/api-users/index.d.ts +224 -2001
  15. package/dist/api-users/index.js +914 -4787
  16. package/dist/api-users/index.js.map +1 -1
  17. package/dist/api-verifications/index.d.ts +96 -96
  18. package/dist/batch/index.d.ts +13 -13
  19. package/dist/batch/index.js +8 -8
  20. package/dist/batch/index.js.map +1 -1
  21. package/dist/bucket/index.d.ts +14 -14
  22. package/dist/bucket/index.js +12 -12
  23. package/dist/bucket/index.js.map +1 -1
  24. package/dist/cache/index.d.ts +11 -11
  25. package/dist/cache/index.js +9 -9
  26. package/dist/cache/index.js.map +1 -1
  27. package/dist/cli/{dist-Sz2EXvQX.cjs → dist-Dl9Vl7Ur.js} +17 -13
  28. package/dist/cli/{dist-BBPjuQ56.js.map → dist-Dl9Vl7Ur.js.map} +1 -1
  29. package/dist/cli/index.d.ts +31 -37
  30. package/dist/cli/index.js +152 -83
  31. package/dist/cli/index.js.map +1 -1
  32. package/dist/command/index.d.ts +19 -19
  33. package/dist/command/index.js +25 -25
  34. package/dist/command/index.js.map +1 -1
  35. package/dist/core/index.browser.js +218 -218
  36. package/dist/core/index.browser.js.map +1 -1
  37. package/dist/core/index.d.ts +232 -232
  38. package/dist/core/index.js +218 -218
  39. package/dist/core/index.js.map +1 -1
  40. package/dist/core/{index.cjs → index.native.js} +304 -455
  41. package/dist/core/index.native.js.map +1 -0
  42. package/dist/datetime/index.d.ts +9 -9
  43. package/dist/datetime/index.js +7 -7
  44. package/dist/datetime/index.js.map +1 -1
  45. package/dist/email/index.d.ts +16 -16
  46. package/dist/email/index.js +80 -82
  47. package/dist/email/index.js.map +1 -1
  48. package/dist/file/index.js +1 -1
  49. package/dist/file/index.js.map +1 -1
  50. package/dist/lock/index.d.ts +9 -9
  51. package/dist/lock/index.js +8 -8
  52. package/dist/lock/index.js.map +1 -1
  53. package/dist/lock-redis/index.js +3 -66
  54. package/dist/lock-redis/index.js.map +1 -1
  55. package/dist/logger/index.d.ts +5 -5
  56. package/dist/logger/index.js +8 -8
  57. package/dist/logger/index.js.map +1 -1
  58. package/dist/orm/index.browser.js +114 -114
  59. package/dist/orm/index.browser.js.map +1 -1
  60. package/dist/orm/index.d.ts +219 -219
  61. package/dist/orm/index.js +46 -46
  62. package/dist/orm/index.js.map +1 -1
  63. package/dist/queue/index.d.ts +25 -25
  64. package/dist/queue/index.js +20 -20
  65. package/dist/queue/index.js.map +1 -1
  66. package/dist/queue-redis/index.d.ts +2 -2
  67. package/dist/redis/index.d.ts +10 -10
  68. package/dist/retry/index.d.ts +20 -20
  69. package/dist/retry/index.js +9 -9
  70. package/dist/retry/index.js.map +1 -1
  71. package/dist/scheduler/index.d.ts +12 -12
  72. package/dist/scheduler/index.js +9 -9
  73. package/dist/scheduler/index.js.map +1 -1
  74. package/dist/security/index.d.ts +53 -53
  75. package/dist/security/index.js +32 -32
  76. package/dist/security/index.js.map +1 -1
  77. package/dist/server/index.browser.js +1 -1
  78. package/dist/server/index.browser.js.map +1 -1
  79. package/dist/server/index.d.ts +101 -101
  80. package/dist/server/index.js +17 -17
  81. package/dist/server/index.js.map +1 -1
  82. package/dist/server-auth/index.browser.js +4 -982
  83. package/dist/server-auth/index.browser.js.map +1 -1
  84. package/dist/server-auth/index.d.ts +204 -785
  85. package/dist/server-auth/index.js +47 -1239
  86. package/dist/server-auth/index.js.map +1 -1
  87. package/dist/server-cache/index.d.ts +10 -10
  88. package/dist/server-cache/index.js +2 -2
  89. package/dist/server-cache/index.js.map +1 -1
  90. package/dist/server-compress/index.d.ts +4 -4
  91. package/dist/server-compress/index.js +1 -1
  92. package/dist/server-compress/index.js.map +1 -1
  93. package/dist/server-cookies/index.browser.js +8 -8
  94. package/dist/server-cookies/index.browser.js.map +1 -1
  95. package/dist/server-cookies/index.d.ts +17 -17
  96. package/dist/server-cookies/index.js +10 -10
  97. package/dist/server-cookies/index.js.map +1 -1
  98. package/dist/server-cors/index.d.ts +17 -17
  99. package/dist/server-cors/index.js +9 -9
  100. package/dist/server-cors/index.js.map +1 -1
  101. package/dist/server-health/index.d.ts +2 -2
  102. package/dist/server-helmet/index.d.ts +1 -1
  103. package/dist/server-links/index.browser.js +12 -12
  104. package/dist/server-links/index.browser.js.map +1 -1
  105. package/dist/server-links/index.d.ts +59 -251
  106. package/dist/server-links/index.js +23 -502
  107. package/dist/server-links/index.js.map +1 -1
  108. package/dist/server-metrics/index.d.ts +4 -4
  109. package/dist/server-metrics/index.js +170 -174
  110. package/dist/server-metrics/index.js.map +1 -1
  111. package/dist/server-multipart/index.d.ts +2 -2
  112. package/dist/server-proxy/index.d.ts +12 -12
  113. package/dist/server-proxy/index.js +10 -10
  114. package/dist/server-proxy/index.js.map +1 -1
  115. package/dist/server-rate-limit/index.d.ts +22 -22
  116. package/dist/server-rate-limit/index.js +12 -12
  117. package/dist/server-rate-limit/index.js.map +1 -1
  118. package/dist/server-security/index.d.ts +24 -24
  119. package/dist/server-security/index.js +15 -15
  120. package/dist/server-security/index.js.map +1 -1
  121. package/dist/server-static/index.d.ts +14 -14
  122. package/dist/server-static/index.js +8 -8
  123. package/dist/server-static/index.js.map +1 -1
  124. package/dist/server-swagger/index.d.ts +25 -184
  125. package/dist/server-swagger/index.js +21 -724
  126. package/dist/server-swagger/index.js.map +1 -1
  127. package/dist/sms/index.d.ts +14 -14
  128. package/dist/sms/index.js +9 -9
  129. package/dist/sms/index.js.map +1 -1
  130. package/dist/thread/index.d.ts +11 -11
  131. package/dist/thread/index.js +17 -17
  132. package/dist/thread/index.js.map +1 -1
  133. package/dist/topic/index.d.ts +26 -26
  134. package/dist/topic/index.js +16 -16
  135. package/dist/topic/index.js.map +1 -1
  136. package/dist/topic-redis/index.d.ts +1 -1
  137. package/dist/vite/index.d.ts +3 -3
  138. package/dist/vite/index.js +12 -13
  139. package/dist/vite/index.js.map +1 -1
  140. package/dist/websocket/index.browser.js +11 -11
  141. package/dist/websocket/index.browser.js.map +1 -1
  142. package/dist/websocket/index.d.ts +51 -51
  143. package/dist/websocket/index.js +13 -13
  144. package/dist/websocket/index.js.map +1 -1
  145. package/package.json +62 -52
  146. package/src/api-files/services/FileService.ts +5 -7
  147. package/src/api-jobs/index.ts +1 -1
  148. package/src/api-jobs/{descriptors → primitives}/$job.ts +8 -8
  149. package/src/api-jobs/providers/JobProvider.ts +9 -9
  150. package/src/api-jobs/services/JobService.ts +5 -5
  151. package/src/api-notifications/index.ts +5 -15
  152. package/src/api-notifications/{descriptors → primitives}/$notification.ts +10 -10
  153. package/src/api-notifications/services/NotificationSenderService.ts +3 -3
  154. package/src/api-parameters/index.ts +1 -1
  155. package/src/api-parameters/{descriptors → primitives}/$config.ts +7 -12
  156. package/src/api-users/index.ts +1 -1
  157. package/src/api-users/{descriptors → primitives}/$userRealm.ts +8 -8
  158. package/src/api-users/providers/UserRealmProvider.ts +1 -1
  159. package/src/batch/index.ts +3 -3
  160. package/src/batch/{descriptors → primitives}/$batch.ts +13 -16
  161. package/src/bucket/index.ts +8 -8
  162. package/src/bucket/{descriptors → primitives}/$bucket.ts +8 -8
  163. package/src/bucket/providers/LocalFileStorageProvider.ts +3 -3
  164. package/src/cache/index.ts +4 -4
  165. package/src/cache/{descriptors → primitives}/$cache.ts +15 -15
  166. package/src/cli/apps/AlephaPackageBuilderCli.ts +30 -3
  167. package/src/cli/assets/appRouterTs.ts +9 -0
  168. package/src/cli/assets/indexHtml.ts +2 -1
  169. package/src/cli/assets/mainBrowserTs.ts +10 -0
  170. package/src/cli/commands/CoreCommands.ts +6 -5
  171. package/src/cli/commands/DrizzleCommands.ts +69 -61
  172. package/src/cli/commands/VerifyCommands.ts +2 -2
  173. package/src/cli/commands/ViteCommands.ts +6 -1
  174. package/src/cli/services/ProjectUtils.ts +78 -41
  175. package/src/command/index.ts +5 -5
  176. package/src/command/{descriptors → primitives}/$command.ts +9 -12
  177. package/src/command/providers/CliProvider.ts +10 -10
  178. package/src/core/Alepha.ts +30 -33
  179. package/src/core/constants/KIND.ts +1 -1
  180. package/src/core/constants/OPTIONS.ts +1 -1
  181. package/src/core/helpers/{descriptor.ts → primitive.ts} +18 -18
  182. package/src/core/helpers/ref.ts +1 -1
  183. package/src/core/index.shared.ts +8 -8
  184. package/src/core/{descriptors → primitives}/$context.ts +5 -5
  185. package/src/core/{descriptors → primitives}/$hook.ts +4 -4
  186. package/src/core/{descriptors → primitives}/$inject.ts +2 -2
  187. package/src/core/{descriptors → primitives}/$module.ts +9 -9
  188. package/src/core/{descriptors → primitives}/$use.ts +2 -2
  189. package/src/core/providers/CodecManager.ts +1 -1
  190. package/src/core/providers/JsonSchemaCodec.ts +1 -1
  191. package/src/core/providers/StateManager.ts +2 -2
  192. package/src/datetime/index.ts +3 -3
  193. package/src/datetime/{descriptors → primitives}/$interval.ts +6 -6
  194. package/src/email/index.ts +4 -4
  195. package/src/email/{descriptors → primitives}/$email.ts +8 -8
  196. package/src/file/index.ts +1 -1
  197. package/src/lock/index.ts +3 -3
  198. package/src/lock/{descriptors → primitives}/$lock.ts +10 -10
  199. package/src/logger/index.ts +8 -8
  200. package/src/logger/{descriptors → primitives}/$logger.ts +2 -2
  201. package/src/logger/services/Logger.ts +1 -1
  202. package/src/orm/constants/PG_SYMBOLS.ts +2 -2
  203. package/src/orm/index.browser.ts +2 -2
  204. package/src/orm/index.ts +8 -8
  205. package/src/orm/{descriptors → primitives}/$entity.ts +11 -11
  206. package/src/orm/{descriptors → primitives}/$repository.ts +2 -2
  207. package/src/orm/{descriptors → primitives}/$sequence.ts +8 -8
  208. package/src/orm/{descriptors → primitives}/$transaction.ts +4 -4
  209. package/src/orm/providers/DrizzleKitProvider.ts +1 -1
  210. package/src/orm/providers/PostgresTypeProvider.ts +3 -3
  211. package/src/orm/providers/RepositoryProvider.ts +4 -4
  212. package/src/orm/providers/drivers/DatabaseProvider.ts +7 -7
  213. package/src/orm/services/ModelBuilder.ts +9 -9
  214. package/src/orm/services/PgRelationManager.ts +2 -2
  215. package/src/orm/services/PostgresModelBuilder.ts +5 -5
  216. package/src/orm/services/Repository.ts +7 -7
  217. package/src/orm/services/SqliteModelBuilder.ts +5 -5
  218. package/src/queue/index.ts +7 -7
  219. package/src/queue/{descriptors → primitives}/$consumer.ts +15 -15
  220. package/src/queue/{descriptors → primitives}/$queue.ts +12 -12
  221. package/src/queue/providers/WorkerProvider.ts +7 -7
  222. package/src/retry/index.ts +3 -3
  223. package/src/retry/{descriptors → primitives}/$retry.ts +19 -17
  224. package/src/scheduler/index.ts +3 -3
  225. package/src/scheduler/{descriptors → primitives}/$scheduler.ts +9 -9
  226. package/src/scheduler/providers/CronProvider.ts +1 -1
  227. package/src/security/index.ts +9 -9
  228. package/src/security/{descriptors → primitives}/$permission.ts +7 -7
  229. package/src/security/{descriptors → primitives}/$realm.ts +6 -12
  230. package/src/security/{descriptors → primitives}/$role.ts +12 -12
  231. package/src/security/{descriptors → primitives}/$serviceAccount.ts +8 -8
  232. package/src/server/index.browser.ts +1 -1
  233. package/src/server/index.ts +14 -14
  234. package/src/server/{descriptors → primitives}/$action.ts +13 -13
  235. package/src/server/{descriptors → primitives}/$route.ts +9 -9
  236. package/src/server/providers/NodeHttpServerProvider.ts +2 -2
  237. package/src/server/services/HttpClient.ts +1 -1
  238. package/src/server-auth/index.browser.ts +1 -1
  239. package/src/server-auth/index.ts +6 -6
  240. package/src/server-auth/{descriptors → primitives}/$auth.ts +10 -10
  241. package/src/server-auth/{descriptors → primitives}/$authCredentials.ts +4 -4
  242. package/src/server-auth/{descriptors → primitives}/$authGithub.ts +4 -4
  243. package/src/server-auth/{descriptors → primitives}/$authGoogle.ts +4 -4
  244. package/src/server-auth/providers/ServerAuthProvider.ts +4 -4
  245. package/src/server-cache/providers/ServerCacheProvider.ts +7 -7
  246. package/src/server-compress/providers/ServerCompressProvider.ts +3 -3
  247. package/src/server-cookies/index.browser.ts +2 -2
  248. package/src/server-cookies/index.ts +5 -5
  249. package/src/server-cookies/{descriptors → primitives}/$cookie.browser.ts +12 -12
  250. package/src/server-cookies/{descriptors → primitives}/$cookie.ts +13 -13
  251. package/src/server-cookies/providers/ServerCookiesProvider.ts +4 -4
  252. package/src/server-cookies/services/CookieParser.ts +1 -1
  253. package/src/server-cors/index.ts +3 -3
  254. package/src/server-cors/{descriptors → primitives}/$cors.ts +11 -13
  255. package/src/server-cors/providers/ServerCorsProvider.ts +5 -5
  256. package/src/server-links/index.browser.ts +5 -5
  257. package/src/server-links/index.ts +9 -9
  258. package/src/server-links/{descriptors → primitives}/$remote.ts +11 -11
  259. package/src/server-links/providers/LinkProvider.ts +7 -7
  260. package/src/server-links/providers/{RemoteDescriptorProvider.ts → RemotePrimitiveProvider.ts} +6 -6
  261. package/src/server-links/providers/ServerLinksProvider.ts +3 -3
  262. package/src/server-proxy/index.ts +3 -3
  263. package/src/server-proxy/{descriptors → primitives}/$proxy.ts +8 -8
  264. package/src/server-proxy/providers/ServerProxyProvider.ts +4 -4
  265. package/src/server-rate-limit/index.ts +6 -6
  266. package/src/server-rate-limit/{descriptors → primitives}/$rateLimit.ts +13 -13
  267. package/src/server-rate-limit/providers/ServerRateLimitProvider.ts +5 -5
  268. package/src/server-security/index.ts +3 -3
  269. package/src/server-security/{descriptors → primitives}/$basicAuth.ts +13 -13
  270. package/src/server-security/providers/ServerBasicAuthProvider.ts +5 -5
  271. package/src/server-security/providers/ServerSecurityProvider.ts +4 -4
  272. package/src/server-static/index.ts +3 -3
  273. package/src/server-static/{descriptors → primitives}/$serve.ts +8 -10
  274. package/src/server-static/providers/ServerStaticProvider.ts +6 -6
  275. package/src/server-swagger/index.ts +5 -5
  276. package/src/server-swagger/{descriptors → primitives}/$swagger.ts +9 -9
  277. package/src/server-swagger/providers/ServerSwaggerProvider.ts +11 -10
  278. package/src/sms/index.ts +4 -4
  279. package/src/sms/{descriptors → primitives}/$sms.ts +8 -8
  280. package/src/thread/index.ts +3 -3
  281. package/src/thread/{descriptors → primitives}/$thread.ts +13 -13
  282. package/src/thread/providers/ThreadProvider.ts +7 -9
  283. package/src/topic/index.ts +5 -5
  284. package/src/topic/{descriptors → primitives}/$subscriber.ts +14 -14
  285. package/src/topic/{descriptors → primitives}/$topic.ts +10 -10
  286. package/src/topic/providers/TopicProvider.ts +4 -4
  287. package/src/vite/helpers/boot.ts +3 -3
  288. package/src/vite/tasks/copyAssets.ts +1 -1
  289. package/src/vite/tasks/generateSitemap.ts +3 -3
  290. package/src/vite/tasks/prerenderPages.ts +2 -2
  291. package/src/vite/tasks/runAlepha.ts +2 -2
  292. package/src/websocket/index.browser.ts +3 -3
  293. package/src/websocket/index.shared.ts +2 -2
  294. package/src/websocket/index.ts +4 -4
  295. package/src/websocket/interfaces/WebSocketInterfaces.ts +3 -3
  296. package/src/websocket/{descriptors → primitives}/$channel.ts +10 -10
  297. package/src/websocket/{descriptors → primitives}/$websocket.ts +8 -8
  298. package/src/websocket/providers/NodeWebSocketServerProvider.ts +7 -7
  299. package/src/websocket/providers/WebSocketServerProvider.ts +3 -3
  300. package/src/websocket/services/WebSocketClient.ts +5 -5
  301. package/dist/api-files/index.cjs +0 -1293
  302. package/dist/api-files/index.cjs.map +0 -1
  303. package/dist/api-files/index.d.cts +0 -829
  304. package/dist/api-jobs/index.cjs +0 -274
  305. package/dist/api-jobs/index.cjs.map +0 -1
  306. package/dist/api-jobs/index.d.cts +0 -654
  307. package/dist/api-notifications/index.cjs +0 -380
  308. package/dist/api-notifications/index.cjs.map +0 -1
  309. package/dist/api-notifications/index.d.cts +0 -289
  310. package/dist/api-parameters/index.cjs +0 -66
  311. package/dist/api-parameters/index.cjs.map +0 -1
  312. package/dist/api-parameters/index.d.cts +0 -84
  313. package/dist/api-users/index.cjs +0 -6009
  314. package/dist/api-users/index.cjs.map +0 -1
  315. package/dist/api-users/index.d.cts +0 -4740
  316. package/dist/api-verifications/index.cjs +0 -407
  317. package/dist/api-verifications/index.cjs.map +0 -1
  318. package/dist/api-verifications/index.d.cts +0 -207
  319. package/dist/batch/index.cjs +0 -408
  320. package/dist/batch/index.cjs.map +0 -1
  321. package/dist/batch/index.d.cts +0 -330
  322. package/dist/bin/index.cjs +0 -17
  323. package/dist/bin/index.cjs.map +0 -1
  324. package/dist/bin/index.d.cts +0 -1
  325. package/dist/bucket/index.cjs +0 -303
  326. package/dist/bucket/index.cjs.map +0 -1
  327. package/dist/bucket/index.d.cts +0 -355
  328. package/dist/cache/index.cjs +0 -241
  329. package/dist/cache/index.cjs.map +0 -1
  330. package/dist/cache/index.d.cts +0 -202
  331. package/dist/cache-redis/index.cjs +0 -84
  332. package/dist/cache-redis/index.cjs.map +0 -1
  333. package/dist/cache-redis/index.d.cts +0 -40
  334. package/dist/cli/chunk-DSlc6foC.cjs +0 -43
  335. package/dist/cli/dist-BBPjuQ56.js +0 -2778
  336. package/dist/cli/dist-Sz2EXvQX.cjs.map +0 -1
  337. package/dist/cli/index.cjs +0 -1241
  338. package/dist/cli/index.cjs.map +0 -1
  339. package/dist/cli/index.d.cts +0 -422
  340. package/dist/command/index.cjs +0 -693
  341. package/dist/command/index.cjs.map +0 -1
  342. package/dist/command/index.d.cts +0 -340
  343. package/dist/core/index.cjs.map +0 -1
  344. package/dist/core/index.d.cts +0 -1927
  345. package/dist/datetime/index.cjs +0 -318
  346. package/dist/datetime/index.cjs.map +0 -1
  347. package/dist/datetime/index.d.cts +0 -145
  348. package/dist/email/index.cjs +0 -10874
  349. package/dist/email/index.cjs.map +0 -1
  350. package/dist/email/index.d.cts +0 -186
  351. package/dist/fake/index.cjs +0 -34641
  352. package/dist/fake/index.cjs.map +0 -1
  353. package/dist/fake/index.d.cts +0 -74
  354. package/dist/file/index.cjs +0 -1212
  355. package/dist/file/index.cjs.map +0 -1
  356. package/dist/file/index.d.cts +0 -698
  357. package/dist/lock/index.cjs +0 -226
  358. package/dist/lock/index.cjs.map +0 -1
  359. package/dist/lock/index.d.cts +0 -361
  360. package/dist/lock-redis/index.cjs +0 -113
  361. package/dist/lock-redis/index.cjs.map +0 -1
  362. package/dist/lock-redis/index.d.cts +0 -24
  363. package/dist/logger/index.cjs +0 -521
  364. package/dist/logger/index.cjs.map +0 -1
  365. package/dist/logger/index.d.cts +0 -281
  366. package/dist/orm/index.cjs +0 -2986
  367. package/dist/orm/index.cjs.map +0 -1
  368. package/dist/orm/index.d.cts +0 -2213
  369. package/dist/queue/index.cjs +0 -1044
  370. package/dist/queue/index.cjs.map +0 -1
  371. package/dist/queue/index.d.cts +0 -1265
  372. package/dist/queue-redis/index.cjs +0 -873
  373. package/dist/queue-redis/index.cjs.map +0 -1
  374. package/dist/queue-redis/index.d.cts +0 -82
  375. package/dist/redis/index.cjs +0 -153
  376. package/dist/redis/index.cjs.map +0 -1
  377. package/dist/redis/index.d.cts +0 -82
  378. package/dist/retry/index.cjs +0 -146
  379. package/dist/retry/index.cjs.map +0 -1
  380. package/dist/retry/index.d.cts +0 -172
  381. package/dist/router/index.cjs +0 -111
  382. package/dist/router/index.cjs.map +0 -1
  383. package/dist/router/index.d.cts +0 -46
  384. package/dist/scheduler/index.cjs +0 -576
  385. package/dist/scheduler/index.cjs.map +0 -1
  386. package/dist/scheduler/index.d.cts +0 -145
  387. package/dist/security/index.cjs +0 -2402
  388. package/dist/security/index.cjs.map +0 -1
  389. package/dist/security/index.d.cts +0 -598
  390. package/dist/server/index.cjs +0 -1680
  391. package/dist/server/index.cjs.map +0 -1
  392. package/dist/server/index.d.cts +0 -810
  393. package/dist/server-auth/index.cjs +0 -3146
  394. package/dist/server-auth/index.cjs.map +0 -1
  395. package/dist/server-auth/index.d.cts +0 -1164
  396. package/dist/server-cache/index.cjs +0 -252
  397. package/dist/server-cache/index.cjs.map +0 -1
  398. package/dist/server-cache/index.d.cts +0 -164
  399. package/dist/server-compress/index.cjs +0 -141
  400. package/dist/server-compress/index.cjs.map +0 -1
  401. package/dist/server-compress/index.d.cts +0 -38
  402. package/dist/server-cookies/index.cjs +0 -234
  403. package/dist/server-cookies/index.cjs.map +0 -1
  404. package/dist/server-cookies/index.d.cts +0 -144
  405. package/dist/server-cors/index.cjs +0 -201
  406. package/dist/server-cors/index.cjs.map +0 -1
  407. package/dist/server-cors/index.d.cts +0 -140
  408. package/dist/server-health/index.cjs +0 -62
  409. package/dist/server-health/index.cjs.map +0 -1
  410. package/dist/server-health/index.d.cts +0 -58
  411. package/dist/server-helmet/index.cjs +0 -131
  412. package/dist/server-helmet/index.cjs.map +0 -1
  413. package/dist/server-helmet/index.d.cts +0 -97
  414. package/dist/server-links/index.cjs +0 -992
  415. package/dist/server-links/index.cjs.map +0 -1
  416. package/dist/server-links/index.d.cts +0 -513
  417. package/dist/server-metrics/index.cjs +0 -4535
  418. package/dist/server-metrics/index.cjs.map +0 -1
  419. package/dist/server-metrics/index.d.cts +0 -35
  420. package/dist/server-multipart/index.cjs +0 -237
  421. package/dist/server-multipart/index.cjs.map +0 -1
  422. package/dist/server-multipart/index.d.cts +0 -50
  423. package/dist/server-proxy/index.cjs +0 -186
  424. package/dist/server-proxy/index.cjs.map +0 -1
  425. package/dist/server-proxy/index.d.cts +0 -234
  426. package/dist/server-rate-limit/index.cjs +0 -241
  427. package/dist/server-rate-limit/index.cjs.map +0 -1
  428. package/dist/server-rate-limit/index.d.cts +0 -183
  429. package/dist/server-security/index.cjs +0 -316
  430. package/dist/server-security/index.cjs.map +0 -1
  431. package/dist/server-security/index.d.cts +0 -173
  432. package/dist/server-static/index.cjs +0 -170
  433. package/dist/server-static/index.cjs.map +0 -1
  434. package/dist/server-static/index.d.cts +0 -121
  435. package/dist/server-swagger/index.cjs +0 -1021
  436. package/dist/server-swagger/index.cjs.map +0 -1
  437. package/dist/server-swagger/index.d.cts +0 -382
  438. package/dist/sms/index.cjs +0 -221
  439. package/dist/sms/index.cjs.map +0 -1
  440. package/dist/sms/index.d.cts +0 -130
  441. package/dist/thread/index.cjs +0 -350
  442. package/dist/thread/index.cjs.map +0 -1
  443. package/dist/thread/index.d.cts +0 -260
  444. package/dist/topic/index.cjs +0 -282
  445. package/dist/topic/index.cjs.map +0 -1
  446. package/dist/topic/index.d.cts +0 -523
  447. package/dist/topic-redis/index.cjs +0 -71
  448. package/dist/topic-redis/index.cjs.map +0 -1
  449. package/dist/topic-redis/index.d.cts +0 -42
  450. package/dist/vite/index.cjs +0 -1077
  451. package/dist/vite/index.cjs.map +0 -1
  452. package/dist/vite/index.d.cts +0 -542
  453. package/dist/websocket/index.cjs +0 -1117
  454. package/dist/websocket/index.cjs.map +0 -1
  455. package/dist/websocket/index.d.cts +0 -861
  456. package/src/api-notifications/providers/MemorySmsProvider.ts +0 -20
  457. package/src/api-notifications/providers/SmsProvider.ts +0 -8
  458. /package/src/core/{descriptors → primitives}/$atom.ts +0 -0
  459. /package/src/core/{descriptors → primitives}/$env.ts +0 -0
  460. /package/src/server-auth/{descriptors → primitives}/$authApple.ts +0 -0
  461. /package/src/server-links/{descriptors → primitives}/$client.ts +0 -0
@@ -1,2402 +0,0 @@
1
- let alepha = require("alepha");
2
- let alepha_logger = require("alepha/logger");
3
- let node_crypto = require("node:crypto");
4
- let alepha_datetime = require("alepha/datetime");
5
- let node_util = require("node:util");
6
- let alepha_server = require("alepha/server");
7
-
8
- //#region src/security/errors/InvalidPermissionError.ts
9
- var InvalidPermissionError = class extends Error {
10
- constructor(name) {
11
- super(`Permission '${name}' is invalid`);
12
- }
13
- };
14
-
15
- //#endregion
16
- //#region src/security/errors/InvalidTokenError.ts
17
- var InvalidTokenError = class extends Error {
18
- status = 401;
19
- };
20
-
21
- //#endregion
22
- //#region src/security/errors/RealmNotFoundError.ts
23
- var RealmNotFoundError = class extends Error {
24
- constructor(realm) {
25
- super(`Realm '${realm}' not found`);
26
- }
27
- };
28
-
29
- //#endregion
30
- //#region src/security/errors/SecurityError.ts
31
- var SecurityError = class extends Error {
32
- name = "SecurityError";
33
- status = 403;
34
- };
35
-
36
- //#endregion
37
- //#region ../../node_modules/jose/dist/webapi/lib/buffer_utils.js
38
- const encoder = new TextEncoder();
39
- const decoder = new TextDecoder();
40
- const MAX_INT32 = 2 ** 32;
41
- function concat(...buffers) {
42
- const size = buffers.reduce((acc, { length }) => acc + length, 0);
43
- const buf = new Uint8Array(size);
44
- let i = 0;
45
- for (const buffer of buffers) {
46
- buf.set(buffer, i);
47
- i += buffer.length;
48
- }
49
- return buf;
50
- }
51
- function encode$1(string) {
52
- const bytes = new Uint8Array(string.length);
53
- for (let i = 0; i < string.length; i++) {
54
- const code = string.charCodeAt(i);
55
- if (code > 127) throw new TypeError("non-ASCII string encountered in encode()");
56
- bytes[i] = code;
57
- }
58
- return bytes;
59
- }
60
-
61
- //#endregion
62
- //#region ../../node_modules/jose/dist/webapi/lib/base64.js
63
- function encodeBase64(input) {
64
- if (Uint8Array.prototype.toBase64) return input.toBase64();
65
- const CHUNK_SIZE = 32768;
66
- const arr = [];
67
- for (let i = 0; i < input.length; i += CHUNK_SIZE) arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
68
- return btoa(arr.join(""));
69
- }
70
- function decodeBase64(encoded) {
71
- if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded);
72
- const binary = atob(encoded);
73
- const bytes = new Uint8Array(binary.length);
74
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
75
- return bytes;
76
- }
77
-
78
- //#endregion
79
- //#region ../../node_modules/jose/dist/webapi/util/base64url.js
80
- function decode(input) {
81
- if (Uint8Array.fromBase64) return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { alphabet: "base64url" });
82
- let encoded = input;
83
- if (encoded instanceof Uint8Array) encoded = decoder.decode(encoded);
84
- encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
85
- try {
86
- return decodeBase64(encoded);
87
- } catch {
88
- throw new TypeError("The input to be decoded is not correctly encoded.");
89
- }
90
- }
91
- function encode(input) {
92
- let unencoded = input;
93
- if (typeof unencoded === "string") unencoded = encoder.encode(unencoded);
94
- if (Uint8Array.prototype.toBase64) return unencoded.toBase64({
95
- alphabet: "base64url",
96
- omitPadding: true
97
- });
98
- return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
99
- }
100
-
101
- //#endregion
102
- //#region ../../node_modules/jose/dist/webapi/util/errors.js
103
- var JOSEError = class extends Error {
104
- static code = "ERR_JOSE_GENERIC";
105
- code = "ERR_JOSE_GENERIC";
106
- constructor(message$1, options) {
107
- super(message$1, options);
108
- this.name = this.constructor.name;
109
- Error.captureStackTrace?.(this, this.constructor);
110
- }
111
- };
112
- var JWTClaimValidationFailed = class extends JOSEError {
113
- static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
114
- code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
115
- claim;
116
- reason;
117
- payload;
118
- constructor(message$1, payload, claim = "unspecified", reason = "unspecified") {
119
- super(message$1, { cause: {
120
- claim,
121
- reason,
122
- payload
123
- } });
124
- this.claim = claim;
125
- this.reason = reason;
126
- this.payload = payload;
127
- }
128
- };
129
- var JWTExpired = class extends JOSEError {
130
- static code = "ERR_JWT_EXPIRED";
131
- code = "ERR_JWT_EXPIRED";
132
- claim;
133
- reason;
134
- payload;
135
- constructor(message$1, payload, claim = "unspecified", reason = "unspecified") {
136
- super(message$1, { cause: {
137
- claim,
138
- reason,
139
- payload
140
- } });
141
- this.claim = claim;
142
- this.reason = reason;
143
- this.payload = payload;
144
- }
145
- };
146
- var JOSEAlgNotAllowed = class extends JOSEError {
147
- static code = "ERR_JOSE_ALG_NOT_ALLOWED";
148
- code = "ERR_JOSE_ALG_NOT_ALLOWED";
149
- };
150
- var JOSENotSupported = class extends JOSEError {
151
- static code = "ERR_JOSE_NOT_SUPPORTED";
152
- code = "ERR_JOSE_NOT_SUPPORTED";
153
- };
154
- var JWSInvalid = class extends JOSEError {
155
- static code = "ERR_JWS_INVALID";
156
- code = "ERR_JWS_INVALID";
157
- };
158
- var JWTInvalid = class extends JOSEError {
159
- static code = "ERR_JWT_INVALID";
160
- code = "ERR_JWT_INVALID";
161
- };
162
- var JWKSInvalid = class extends JOSEError {
163
- static code = "ERR_JWKS_INVALID";
164
- code = "ERR_JWKS_INVALID";
165
- };
166
- var JWKSNoMatchingKey = class extends JOSEError {
167
- static code = "ERR_JWKS_NO_MATCHING_KEY";
168
- code = "ERR_JWKS_NO_MATCHING_KEY";
169
- constructor(message$1 = "no applicable key found in the JSON Web Key Set", options) {
170
- super(message$1, options);
171
- }
172
- };
173
- var JWKSMultipleMatchingKeys = class extends JOSEError {
174
- [Symbol.asyncIterator];
175
- static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
176
- code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
177
- constructor(message$1 = "multiple matching keys found in the JSON Web Key Set", options) {
178
- super(message$1, options);
179
- }
180
- };
181
- var JWKSTimeout = class extends JOSEError {
182
- static code = "ERR_JWKS_TIMEOUT";
183
- code = "ERR_JWKS_TIMEOUT";
184
- constructor(message$1 = "request timed out", options) {
185
- super(message$1, options);
186
- }
187
- };
188
- var JWSSignatureVerificationFailed = class extends JOSEError {
189
- static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
190
- code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
191
- constructor(message$1 = "signature verification failed", options) {
192
- super(message$1, options);
193
- }
194
- };
195
-
196
- //#endregion
197
- //#region ../../node_modules/jose/dist/webapi/lib/crypto_key.js
198
- const unusable = (name, prop = "algorithm.name") => /* @__PURE__ */ new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
199
- const isAlgorithm = (algorithm, name) => algorithm.name === name;
200
- function getHashLength(hash) {
201
- return parseInt(hash.name.slice(4), 10);
202
- }
203
- function getNamedCurve(alg) {
204
- switch (alg) {
205
- case "ES256": return "P-256";
206
- case "ES384": return "P-384";
207
- case "ES512": return "P-521";
208
- default: throw new Error("unreachable");
209
- }
210
- }
211
- function checkUsage(key, usage) {
212
- if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
213
- }
214
- function checkSigCryptoKey(key, alg, usage) {
215
- switch (alg) {
216
- case "HS256":
217
- case "HS384":
218
- case "HS512": {
219
- if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC");
220
- const expected = parseInt(alg.slice(2), 10);
221
- if (getHashLength(key.algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
222
- break;
223
- }
224
- case "RS256":
225
- case "RS384":
226
- case "RS512": {
227
- if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5");
228
- const expected = parseInt(alg.slice(2), 10);
229
- if (getHashLength(key.algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
230
- break;
231
- }
232
- case "PS256":
233
- case "PS384":
234
- case "PS512": {
235
- if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS");
236
- const expected = parseInt(alg.slice(2), 10);
237
- if (getHashLength(key.algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
238
- break;
239
- }
240
- case "Ed25519":
241
- case "EdDSA":
242
- if (!isAlgorithm(key.algorithm, "Ed25519")) throw unusable("Ed25519");
243
- break;
244
- case "ML-DSA-44":
245
- case "ML-DSA-65":
246
- case "ML-DSA-87":
247
- if (!isAlgorithm(key.algorithm, alg)) throw unusable(alg);
248
- break;
249
- case "ES256":
250
- case "ES384":
251
- case "ES512": {
252
- if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA");
253
- const expected = getNamedCurve(alg);
254
- if (key.algorithm.namedCurve !== expected) throw unusable(expected, "algorithm.namedCurve");
255
- break;
256
- }
257
- default: throw new TypeError("CryptoKey does not support this operation");
258
- }
259
- checkUsage(key, usage);
260
- }
261
-
262
- //#endregion
263
- //#region ../../node_modules/jose/dist/webapi/lib/invalid_key_input.js
264
- function message(msg, actual, ...types) {
265
- types = types.filter(Boolean);
266
- if (types.length > 2) {
267
- const last = types.pop();
268
- msg += `one of type ${types.join(", ")}, or ${last}.`;
269
- } else if (types.length === 2) msg += `one of type ${types[0]} or ${types[1]}.`;
270
- else msg += `of type ${types[0]}.`;
271
- if (actual == null) msg += ` Received ${actual}`;
272
- else if (typeof actual === "function" && actual.name) msg += ` Received function ${actual.name}`;
273
- else if (typeof actual === "object" && actual != null) {
274
- if (actual.constructor?.name) msg += ` Received an instance of ${actual.constructor.name}`;
275
- }
276
- return msg;
277
- }
278
- const invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
279
- const withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
280
-
281
- //#endregion
282
- //#region ../../node_modules/jose/dist/webapi/lib/is_key_like.js
283
- const isCryptoKey = (key) => {
284
- if (key?.[Symbol.toStringTag] === "CryptoKey") return true;
285
- try {
286
- return key instanceof CryptoKey;
287
- } catch {
288
- return false;
289
- }
290
- };
291
- const isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
292
- const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
293
-
294
- //#endregion
295
- //#region ../../node_modules/jose/dist/webapi/lib/is_disjoint.js
296
- function isDisjoint(...headers) {
297
- const sources = headers.filter(Boolean);
298
- if (sources.length === 0 || sources.length === 1) return true;
299
- let acc;
300
- for (const header of sources) {
301
- const parameters = Object.keys(header);
302
- if (!acc || acc.size === 0) {
303
- acc = new Set(parameters);
304
- continue;
305
- }
306
- for (const parameter of parameters) {
307
- if (acc.has(parameter)) return false;
308
- acc.add(parameter);
309
- }
310
- }
311
- return true;
312
- }
313
-
314
- //#endregion
315
- //#region ../../node_modules/jose/dist/webapi/lib/is_object.js
316
- const isObjectLike = (value) => typeof value === "object" && value !== null;
317
- function isObject(input) {
318
- if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") return false;
319
- if (Object.getPrototypeOf(input) === null) return true;
320
- let proto = input;
321
- while (Object.getPrototypeOf(proto) !== null) proto = Object.getPrototypeOf(proto);
322
- return Object.getPrototypeOf(input) === proto;
323
- }
324
-
325
- //#endregion
326
- //#region ../../node_modules/jose/dist/webapi/lib/check_key_length.js
327
- function checkKeyLength(alg, key) {
328
- if (alg.startsWith("RS") || alg.startsWith("PS")) {
329
- const { modulusLength } = key.algorithm;
330
- if (typeof modulusLength !== "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
331
- }
332
- }
333
-
334
- //#endregion
335
- //#region ../../node_modules/jose/dist/webapi/lib/jwk_to_key.js
336
- function subtleMapping(jwk) {
337
- let algorithm;
338
- let keyUsages;
339
- switch (jwk.kty) {
340
- case "AKP":
341
- switch (jwk.alg) {
342
- case "ML-DSA-44":
343
- case "ML-DSA-65":
344
- case "ML-DSA-87":
345
- algorithm = { name: jwk.alg };
346
- keyUsages = jwk.priv ? ["sign"] : ["verify"];
347
- break;
348
- default: throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
349
- }
350
- break;
351
- case "RSA":
352
- switch (jwk.alg) {
353
- case "PS256":
354
- case "PS384":
355
- case "PS512":
356
- algorithm = {
357
- name: "RSA-PSS",
358
- hash: `SHA-${jwk.alg.slice(-3)}`
359
- };
360
- keyUsages = jwk.d ? ["sign"] : ["verify"];
361
- break;
362
- case "RS256":
363
- case "RS384":
364
- case "RS512":
365
- algorithm = {
366
- name: "RSASSA-PKCS1-v1_5",
367
- hash: `SHA-${jwk.alg.slice(-3)}`
368
- };
369
- keyUsages = jwk.d ? ["sign"] : ["verify"];
370
- break;
371
- case "RSA-OAEP":
372
- case "RSA-OAEP-256":
373
- case "RSA-OAEP-384":
374
- case "RSA-OAEP-512":
375
- algorithm = {
376
- name: "RSA-OAEP",
377
- hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
378
- };
379
- keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
380
- break;
381
- default: throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
382
- }
383
- break;
384
- case "EC":
385
- switch (jwk.alg) {
386
- case "ES256":
387
- algorithm = {
388
- name: "ECDSA",
389
- namedCurve: "P-256"
390
- };
391
- keyUsages = jwk.d ? ["sign"] : ["verify"];
392
- break;
393
- case "ES384":
394
- algorithm = {
395
- name: "ECDSA",
396
- namedCurve: "P-384"
397
- };
398
- keyUsages = jwk.d ? ["sign"] : ["verify"];
399
- break;
400
- case "ES512":
401
- algorithm = {
402
- name: "ECDSA",
403
- namedCurve: "P-521"
404
- };
405
- keyUsages = jwk.d ? ["sign"] : ["verify"];
406
- break;
407
- case "ECDH-ES":
408
- case "ECDH-ES+A128KW":
409
- case "ECDH-ES+A192KW":
410
- case "ECDH-ES+A256KW":
411
- algorithm = {
412
- name: "ECDH",
413
- namedCurve: jwk.crv
414
- };
415
- keyUsages = jwk.d ? ["deriveBits"] : [];
416
- break;
417
- default: throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
418
- }
419
- break;
420
- case "OKP":
421
- switch (jwk.alg) {
422
- case "Ed25519":
423
- case "EdDSA":
424
- algorithm = { name: "Ed25519" };
425
- keyUsages = jwk.d ? ["sign"] : ["verify"];
426
- break;
427
- case "ECDH-ES":
428
- case "ECDH-ES+A128KW":
429
- case "ECDH-ES+A192KW":
430
- case "ECDH-ES+A256KW":
431
- algorithm = { name: jwk.crv };
432
- keyUsages = jwk.d ? ["deriveBits"] : [];
433
- break;
434
- default: throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
435
- }
436
- break;
437
- default: throw new JOSENotSupported("Invalid or unsupported JWK \"kty\" (Key Type) Parameter value");
438
- }
439
- return {
440
- algorithm,
441
- keyUsages
442
- };
443
- }
444
- async function jwkToKey(jwk) {
445
- if (!jwk.alg) throw new TypeError("\"alg\" argument is required when \"jwk.alg\" is not present");
446
- const { algorithm, keyUsages } = subtleMapping(jwk);
447
- const keyData = { ...jwk };
448
- if (keyData.kty !== "AKP") delete keyData.alg;
449
- delete keyData.use;
450
- return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
451
- }
452
-
453
- //#endregion
454
- //#region ../../node_modules/jose/dist/webapi/key/import.js
455
- async function importJWK(jwk, alg, options) {
456
- if (!isObject(jwk)) throw new TypeError("JWK must be an object");
457
- let ext;
458
- alg ??= jwk.alg;
459
- ext ??= options?.extractable ?? jwk.ext;
460
- switch (jwk.kty) {
461
- case "oct":
462
- if (typeof jwk.k !== "string" || !jwk.k) throw new TypeError("missing \"k\" (Key Value) Parameter value");
463
- return decode(jwk.k);
464
- case "RSA":
465
- if ("oth" in jwk && jwk.oth !== void 0) throw new JOSENotSupported("RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported");
466
- return jwkToKey({
467
- ...jwk,
468
- alg,
469
- ext
470
- });
471
- case "AKP":
472
- if (typeof jwk.alg !== "string" || !jwk.alg) throw new TypeError("missing \"alg\" (Algorithm) Parameter value");
473
- if (alg !== void 0 && alg !== jwk.alg) throw new TypeError("JWK alg and alg option value mismatch");
474
- return jwkToKey({
475
- ...jwk,
476
- ext
477
- });
478
- case "EC":
479
- case "OKP": return jwkToKey({
480
- ...jwk,
481
- alg,
482
- ext
483
- });
484
- default: throw new JOSENotSupported("Unsupported \"kty\" (Key Type) Parameter value");
485
- }
486
- }
487
-
488
- //#endregion
489
- //#region ../../node_modules/jose/dist/webapi/lib/validate_crit.js
490
- function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
491
- if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) throw new Err("\"crit\" (Critical) Header Parameter MUST be integrity protected");
492
- if (!protectedHeader || protectedHeader.crit === void 0) return /* @__PURE__ */ new Set();
493
- if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) throw new Err("\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present");
494
- let recognized;
495
- if (recognizedOption !== void 0) recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
496
- else recognized = recognizedDefault;
497
- for (const parameter of protectedHeader.crit) {
498
- if (!recognized.has(parameter)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
499
- if (joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`);
500
- if (recognized.get(parameter) && protectedHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
501
- }
502
- return new Set(protectedHeader.crit);
503
- }
504
-
505
- //#endregion
506
- //#region ../../node_modules/jose/dist/webapi/lib/validate_algorithms.js
507
- function validateAlgorithms(option, algorithms) {
508
- if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) throw new TypeError(`"${option}" option must be an array of strings`);
509
- if (!algorithms) return;
510
- return new Set(algorithms);
511
- }
512
-
513
- //#endregion
514
- //#region ../../node_modules/jose/dist/webapi/lib/is_jwk.js
515
- const isJWK = (key) => isObject(key) && typeof key.kty === "string";
516
- const isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
517
- const isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
518
- const isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
519
-
520
- //#endregion
521
- //#region ../../node_modules/jose/dist/webapi/lib/normalize_key.js
522
- let cache;
523
- const handleJWK = async (key, jwk, alg, freeze = false) => {
524
- cache ||= /* @__PURE__ */ new WeakMap();
525
- let cached = cache.get(key);
526
- if (cached?.[alg]) return cached[alg];
527
- const cryptoKey = await jwkToKey({
528
- ...jwk,
529
- alg
530
- });
531
- if (freeze) Object.freeze(key);
532
- if (!cached) cache.set(key, { [alg]: cryptoKey });
533
- else cached[alg] = cryptoKey;
534
- return cryptoKey;
535
- };
536
- const handleKeyObject = (keyObject, alg) => {
537
- cache ||= /* @__PURE__ */ new WeakMap();
538
- let cached = cache.get(keyObject);
539
- if (cached?.[alg]) return cached[alg];
540
- const isPublic = keyObject.type === "public";
541
- const extractable = isPublic ? true : false;
542
- let cryptoKey;
543
- if (keyObject.asymmetricKeyType === "x25519") {
544
- switch (alg) {
545
- case "ECDH-ES":
546
- case "ECDH-ES+A128KW":
547
- case "ECDH-ES+A192KW":
548
- case "ECDH-ES+A256KW": break;
549
- default: throw new TypeError("given KeyObject instance cannot be used for this algorithm");
550
- }
551
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
552
- }
553
- if (keyObject.asymmetricKeyType === "ed25519") {
554
- if (alg !== "EdDSA" && alg !== "Ed25519") throw new TypeError("given KeyObject instance cannot be used for this algorithm");
555
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]);
556
- }
557
- switch (keyObject.asymmetricKeyType) {
558
- case "ml-dsa-44":
559
- case "ml-dsa-65":
560
- case "ml-dsa-87":
561
- if (alg !== keyObject.asymmetricKeyType.toUpperCase()) throw new TypeError("given KeyObject instance cannot be used for this algorithm");
562
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]);
563
- }
564
- if (keyObject.asymmetricKeyType === "rsa") {
565
- let hash;
566
- switch (alg) {
567
- case "RSA-OAEP":
568
- hash = "SHA-1";
569
- break;
570
- case "RS256":
571
- case "PS256":
572
- case "RSA-OAEP-256":
573
- hash = "SHA-256";
574
- break;
575
- case "RS384":
576
- case "PS384":
577
- case "RSA-OAEP-384":
578
- hash = "SHA-384";
579
- break;
580
- case "RS512":
581
- case "PS512":
582
- case "RSA-OAEP-512":
583
- hash = "SHA-512";
584
- break;
585
- default: throw new TypeError("given KeyObject instance cannot be used for this algorithm");
586
- }
587
- if (alg.startsWith("RSA-OAEP")) return keyObject.toCryptoKey({
588
- name: "RSA-OAEP",
589
- hash
590
- }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
591
- cryptoKey = keyObject.toCryptoKey({
592
- name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
593
- hash
594
- }, extractable, [isPublic ? "verify" : "sign"]);
595
- }
596
- if (keyObject.asymmetricKeyType === "ec") {
597
- const namedCurve = new Map([
598
- ["prime256v1", "P-256"],
599
- ["secp384r1", "P-384"],
600
- ["secp521r1", "P-521"]
601
- ]).get(keyObject.asymmetricKeyDetails?.namedCurve);
602
- if (!namedCurve) throw new TypeError("given KeyObject instance cannot be used for this algorithm");
603
- if (alg === "ES256" && namedCurve === "P-256") cryptoKey = keyObject.toCryptoKey({
604
- name: "ECDSA",
605
- namedCurve
606
- }, extractable, [isPublic ? "verify" : "sign"]);
607
- if (alg === "ES384" && namedCurve === "P-384") cryptoKey = keyObject.toCryptoKey({
608
- name: "ECDSA",
609
- namedCurve
610
- }, extractable, [isPublic ? "verify" : "sign"]);
611
- if (alg === "ES512" && namedCurve === "P-521") cryptoKey = keyObject.toCryptoKey({
612
- name: "ECDSA",
613
- namedCurve
614
- }, extractable, [isPublic ? "verify" : "sign"]);
615
- if (alg.startsWith("ECDH-ES")) cryptoKey = keyObject.toCryptoKey({
616
- name: "ECDH",
617
- namedCurve
618
- }, extractable, isPublic ? [] : ["deriveBits"]);
619
- }
620
- if (!cryptoKey) throw new TypeError("given KeyObject instance cannot be used for this algorithm");
621
- if (!cached) cache.set(keyObject, { [alg]: cryptoKey });
622
- else cached[alg] = cryptoKey;
623
- return cryptoKey;
624
- };
625
- async function normalizeKey(key, alg) {
626
- if (key instanceof Uint8Array) return key;
627
- if (isCryptoKey(key)) return key;
628
- if (isKeyObject(key)) {
629
- if (key.type === "secret") return key.export();
630
- if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") try {
631
- return handleKeyObject(key, alg);
632
- } catch (err) {
633
- if (err instanceof TypeError) throw err;
634
- }
635
- return handleJWK(key, key.export({ format: "jwk" }), alg);
636
- }
637
- if (isJWK(key)) {
638
- if (key.k) return decode(key.k);
639
- return handleJWK(key, key, alg, true);
640
- }
641
- throw new Error("unreachable");
642
- }
643
-
644
- //#endregion
645
- //#region ../../node_modules/jose/dist/webapi/lib/check_key_type.js
646
- const tag = (key) => key?.[Symbol.toStringTag];
647
- const jwkMatchesOp = (alg, key, usage) => {
648
- if (key.use !== void 0) {
649
- let expected;
650
- switch (usage) {
651
- case "sign":
652
- case "verify":
653
- expected = "sig";
654
- break;
655
- case "encrypt":
656
- case "decrypt":
657
- expected = "enc";
658
- break;
659
- }
660
- if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
661
- }
662
- if (key.alg !== void 0 && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
663
- if (Array.isArray(key.key_ops)) {
664
- let expectedKeyOp;
665
- switch (true) {
666
- case usage === "sign" || usage === "verify":
667
- case alg === "dir":
668
- case alg.includes("CBC-HS"):
669
- expectedKeyOp = usage;
670
- break;
671
- case alg.startsWith("PBES2"):
672
- expectedKeyOp = "deriveBits";
673
- break;
674
- case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
675
- if (!alg.includes("GCM") && alg.endsWith("KW")) expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
676
- else expectedKeyOp = usage;
677
- break;
678
- case usage === "encrypt" && alg.startsWith("RSA"):
679
- expectedKeyOp = "wrapKey";
680
- break;
681
- case usage === "decrypt":
682
- expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
683
- break;
684
- }
685
- if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
686
- }
687
- return true;
688
- };
689
- const symmetricTypeCheck = (alg, key, usage) => {
690
- if (key instanceof Uint8Array) return;
691
- if (isJWK(key)) {
692
- if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) return;
693
- throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
694
- }
695
- if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
696
- if (key.type !== "secret") throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
697
- };
698
- const asymmetricTypeCheck = (alg, key, usage) => {
699
- if (isJWK(key)) switch (usage) {
700
- case "decrypt":
701
- case "sign":
702
- if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return;
703
- throw new TypeError(`JSON Web Key for this operation be a private JWK`);
704
- case "encrypt":
705
- case "verify":
706
- if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return;
707
- throw new TypeError(`JSON Web Key for this operation be a public JWK`);
708
- }
709
- if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
710
- if (key.type === "secret") throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
711
- if (key.type === "public") switch (usage) {
712
- case "sign": throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
713
- case "decrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
714
- }
715
- if (key.type === "private") switch (usage) {
716
- case "verify": throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
717
- case "encrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
718
- }
719
- };
720
- function checkKeyType(alg, key, usage) {
721
- switch (alg.substring(0, 2)) {
722
- case "A1":
723
- case "A2":
724
- case "di":
725
- case "HS":
726
- case "PB":
727
- symmetricTypeCheck(alg, key, usage);
728
- break;
729
- default: asymmetricTypeCheck(alg, key, usage);
730
- }
731
- }
732
-
733
- //#endregion
734
- //#region ../../node_modules/jose/dist/webapi/lib/subtle_dsa.js
735
- function subtleAlgorithm(alg, algorithm) {
736
- const hash = `SHA-${alg.slice(-3)}`;
737
- switch (alg) {
738
- case "HS256":
739
- case "HS384":
740
- case "HS512": return {
741
- hash,
742
- name: "HMAC"
743
- };
744
- case "PS256":
745
- case "PS384":
746
- case "PS512": return {
747
- hash,
748
- name: "RSA-PSS",
749
- saltLength: parseInt(alg.slice(-3), 10) >> 3
750
- };
751
- case "RS256":
752
- case "RS384":
753
- case "RS512": return {
754
- hash,
755
- name: "RSASSA-PKCS1-v1_5"
756
- };
757
- case "ES256":
758
- case "ES384":
759
- case "ES512": return {
760
- hash,
761
- name: "ECDSA",
762
- namedCurve: algorithm.namedCurve
763
- };
764
- case "Ed25519":
765
- case "EdDSA": return { name: "Ed25519" };
766
- case "ML-DSA-44":
767
- case "ML-DSA-65":
768
- case "ML-DSA-87": return { name: alg };
769
- default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
770
- }
771
- }
772
-
773
- //#endregion
774
- //#region ../../node_modules/jose/dist/webapi/lib/get_sign_verify_key.js
775
- async function getSigKey(alg, key, usage) {
776
- if (key instanceof Uint8Array) {
777
- if (!alg.startsWith("HS")) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
778
- return crypto.subtle.importKey("raw", key, {
779
- hash: `SHA-${alg.slice(-3)}`,
780
- name: "HMAC"
781
- }, false, [usage]);
782
- }
783
- checkSigCryptoKey(key, alg, usage);
784
- return key;
785
- }
786
-
787
- //#endregion
788
- //#region ../../node_modules/jose/dist/webapi/lib/verify.js
789
- async function verify(alg, key, signature, data) {
790
- const cryptoKey = await getSigKey(alg, key, "verify");
791
- checkKeyLength(alg, cryptoKey);
792
- const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
793
- try {
794
- return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
795
- } catch {
796
- return false;
797
- }
798
- }
799
-
800
- //#endregion
801
- //#region ../../node_modules/jose/dist/webapi/jws/flattened/verify.js
802
- async function flattenedVerify(jws, key, options) {
803
- if (!isObject(jws)) throw new JWSInvalid("Flattened JWS must be an object");
804
- if (jws.protected === void 0 && jws.header === void 0) throw new JWSInvalid("Flattened JWS must have either of the \"protected\" or \"header\" members");
805
- if (jws.protected !== void 0 && typeof jws.protected !== "string") throw new JWSInvalid("JWS Protected Header incorrect type");
806
- if (jws.payload === void 0) throw new JWSInvalid("JWS Payload missing");
807
- if (typeof jws.signature !== "string") throw new JWSInvalid("JWS Signature missing or incorrect type");
808
- if (jws.header !== void 0 && !isObject(jws.header)) throw new JWSInvalid("JWS Unprotected Header incorrect type");
809
- let parsedProt = {};
810
- if (jws.protected) try {
811
- const protectedHeader = decode(jws.protected);
812
- parsedProt = JSON.parse(decoder.decode(protectedHeader));
813
- } catch {
814
- throw new JWSInvalid("JWS Protected Header is invalid");
815
- }
816
- if (!isDisjoint(parsedProt, jws.header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
817
- const joseHeader = {
818
- ...parsedProt,
819
- ...jws.header
820
- };
821
- const extensions = validateCrit(JWSInvalid, new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
822
- let b64 = true;
823
- if (extensions.has("b64")) {
824
- b64 = parsedProt.b64;
825
- if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
826
- }
827
- const { alg } = joseHeader;
828
- if (typeof alg !== "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
829
- const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
830
- if (algorithms && !algorithms.has(alg)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed");
831
- if (b64) {
832
- if (typeof jws.payload !== "string") throw new JWSInvalid("JWS Payload must be a string");
833
- } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
834
- let resolvedKey = false;
835
- if (typeof key === "function") {
836
- key = await key(parsedProt, jws);
837
- resolvedKey = true;
838
- }
839
- checkKeyType(alg, key, "verify");
840
- const data = concat(jws.protected !== void 0 ? encode$1(jws.protected) : new Uint8Array(), encode$1("."), typeof jws.payload === "string" ? b64 ? encode$1(jws.payload) : encoder.encode(jws.payload) : jws.payload);
841
- let signature;
842
- try {
843
- signature = decode(jws.signature);
844
- } catch {
845
- throw new JWSInvalid("Failed to base64url decode the signature");
846
- }
847
- const k = await normalizeKey(key, alg);
848
- if (!await verify(alg, k, signature, data)) throw new JWSSignatureVerificationFailed();
849
- let payload;
850
- if (b64) try {
851
- payload = decode(jws.payload);
852
- } catch {
853
- throw new JWSInvalid("Failed to base64url decode the payload");
854
- }
855
- else if (typeof jws.payload === "string") payload = encoder.encode(jws.payload);
856
- else payload = jws.payload;
857
- const result = { payload };
858
- if (jws.protected !== void 0) result.protectedHeader = parsedProt;
859
- if (jws.header !== void 0) result.unprotectedHeader = jws.header;
860
- if (resolvedKey) return {
861
- ...result,
862
- key: k
863
- };
864
- return result;
865
- }
866
-
867
- //#endregion
868
- //#region ../../node_modules/jose/dist/webapi/jws/compact/verify.js
869
- async function compactVerify(jws, key, options) {
870
- if (jws instanceof Uint8Array) jws = decoder.decode(jws);
871
- if (typeof jws !== "string") throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
872
- const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
873
- if (length !== 3) throw new JWSInvalid("Invalid Compact JWS");
874
- const verified = await flattenedVerify({
875
- payload,
876
- protected: protectedHeader,
877
- signature
878
- }, key, options);
879
- const result = {
880
- payload: verified.payload,
881
- protectedHeader: verified.protectedHeader
882
- };
883
- if (typeof key === "function") return {
884
- ...result,
885
- key: verified.key
886
- };
887
- return result;
888
- }
889
-
890
- //#endregion
891
- //#region ../../node_modules/jose/dist/webapi/lib/jwt_claims_set.js
892
- const epoch = (date) => Math.floor(date.getTime() / 1e3);
893
- const minute = 60;
894
- const hour = minute * 60;
895
- const day = hour * 24;
896
- const week = day * 7;
897
- const year = day * 365.25;
898
- const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
899
- function secs(str) {
900
- const matched = REGEX.exec(str);
901
- if (!matched || matched[4] && matched[1]) throw new TypeError("Invalid time period format");
902
- const value = parseFloat(matched[2]);
903
- const unit = matched[3].toLowerCase();
904
- let numericDate;
905
- switch (unit) {
906
- case "sec":
907
- case "secs":
908
- case "second":
909
- case "seconds":
910
- case "s":
911
- numericDate = Math.round(value);
912
- break;
913
- case "minute":
914
- case "minutes":
915
- case "min":
916
- case "mins":
917
- case "m":
918
- numericDate = Math.round(value * minute);
919
- break;
920
- case "hour":
921
- case "hours":
922
- case "hr":
923
- case "hrs":
924
- case "h":
925
- numericDate = Math.round(value * hour);
926
- break;
927
- case "day":
928
- case "days":
929
- case "d":
930
- numericDate = Math.round(value * day);
931
- break;
932
- case "week":
933
- case "weeks":
934
- case "w":
935
- numericDate = Math.round(value * week);
936
- break;
937
- default:
938
- numericDate = Math.round(value * year);
939
- break;
940
- }
941
- if (matched[1] === "-" || matched[4] === "ago") return -numericDate;
942
- return numericDate;
943
- }
944
- function validateInput(label, input) {
945
- if (!Number.isFinite(input)) throw new TypeError(`Invalid ${label} input`);
946
- return input;
947
- }
948
- const normalizeTyp = (value) => {
949
- if (value.includes("/")) return value.toLowerCase();
950
- return `application/${value.toLowerCase()}`;
951
- };
952
- const checkAudiencePresence = (audPayload, audOption) => {
953
- if (typeof audPayload === "string") return audOption.includes(audPayload);
954
- if (Array.isArray(audPayload)) return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
955
- return false;
956
- };
957
- function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
958
- let payload;
959
- try {
960
- payload = JSON.parse(decoder.decode(encodedPayload));
961
- } catch {}
962
- if (!isObject(payload)) throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
963
- const { typ } = options;
964
- if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", payload, "typ", "check_failed");
965
- const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
966
- const presenceCheck = [...requiredClaims];
967
- if (maxTokenAge !== void 0) presenceCheck.push("iat");
968
- if (audience !== void 0) presenceCheck.push("aud");
969
- if (subject !== void 0) presenceCheck.push("sub");
970
- if (issuer !== void 0) presenceCheck.push("iss");
971
- for (const claim of new Set(presenceCheck.reverse())) if (!(claim in payload)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
972
- if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) throw new JWTClaimValidationFailed("unexpected \"iss\" claim value", payload, "iss", "check_failed");
973
- if (subject && payload.sub !== subject) throw new JWTClaimValidationFailed("unexpected \"sub\" claim value", payload, "sub", "check_failed");
974
- if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) throw new JWTClaimValidationFailed("unexpected \"aud\" claim value", payload, "aud", "check_failed");
975
- let tolerance;
976
- switch (typeof options.clockTolerance) {
977
- case "string":
978
- tolerance = secs(options.clockTolerance);
979
- break;
980
- case "number":
981
- tolerance = options.clockTolerance;
982
- break;
983
- case "undefined":
984
- tolerance = 0;
985
- break;
986
- default: throw new TypeError("Invalid clockTolerance option type");
987
- }
988
- const { currentDate } = options;
989
- const now = epoch(currentDate || /* @__PURE__ */ new Date());
990
- if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") throw new JWTClaimValidationFailed("\"iat\" claim must be a number", payload, "iat", "invalid");
991
- if (payload.nbf !== void 0) {
992
- if (typeof payload.nbf !== "number") throw new JWTClaimValidationFailed("\"nbf\" claim must be a number", payload, "nbf", "invalid");
993
- if (payload.nbf > now + tolerance) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", payload, "nbf", "check_failed");
994
- }
995
- if (payload.exp !== void 0) {
996
- if (typeof payload.exp !== "number") throw new JWTClaimValidationFailed("\"exp\" claim must be a number", payload, "exp", "invalid");
997
- if (payload.exp <= now - tolerance) throw new JWTExpired("\"exp\" claim timestamp check failed", payload, "exp", "check_failed");
998
- }
999
- if (maxTokenAge) {
1000
- const age = now - payload.iat;
1001
- const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
1002
- if (age - tolerance > max) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", payload, "iat", "check_failed");
1003
- if (age < 0 - tolerance) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", payload, "iat", "check_failed");
1004
- }
1005
- return payload;
1006
- }
1007
- var JWTClaimsBuilder = class {
1008
- #payload;
1009
- constructor(payload) {
1010
- if (!isObject(payload)) throw new TypeError("JWT Claims Set MUST be an object");
1011
- this.#payload = structuredClone(payload);
1012
- }
1013
- data() {
1014
- return encoder.encode(JSON.stringify(this.#payload));
1015
- }
1016
- get iss() {
1017
- return this.#payload.iss;
1018
- }
1019
- set iss(value) {
1020
- this.#payload.iss = value;
1021
- }
1022
- get sub() {
1023
- return this.#payload.sub;
1024
- }
1025
- set sub(value) {
1026
- this.#payload.sub = value;
1027
- }
1028
- get aud() {
1029
- return this.#payload.aud;
1030
- }
1031
- set aud(value) {
1032
- this.#payload.aud = value;
1033
- }
1034
- set jti(value) {
1035
- this.#payload.jti = value;
1036
- }
1037
- set nbf(value) {
1038
- if (typeof value === "number") this.#payload.nbf = validateInput("setNotBefore", value);
1039
- else if (value instanceof Date) this.#payload.nbf = validateInput("setNotBefore", epoch(value));
1040
- else this.#payload.nbf = epoch(/* @__PURE__ */ new Date()) + secs(value);
1041
- }
1042
- set exp(value) {
1043
- if (typeof value === "number") this.#payload.exp = validateInput("setExpirationTime", value);
1044
- else if (value instanceof Date) this.#payload.exp = validateInput("setExpirationTime", epoch(value));
1045
- else this.#payload.exp = epoch(/* @__PURE__ */ new Date()) + secs(value);
1046
- }
1047
- set iat(value) {
1048
- if (value === void 0) this.#payload.iat = epoch(/* @__PURE__ */ new Date());
1049
- else if (value instanceof Date) this.#payload.iat = validateInput("setIssuedAt", epoch(value));
1050
- else if (typeof value === "string") this.#payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value));
1051
- else this.#payload.iat = validateInput("setIssuedAt", value);
1052
- }
1053
- };
1054
-
1055
- //#endregion
1056
- //#region ../../node_modules/jose/dist/webapi/jwt/verify.js
1057
- async function jwtVerify(jwt, key, options) {
1058
- const verified = await compactVerify(jwt, key, options);
1059
- if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
1060
- const result = {
1061
- payload: validateClaimsSet(verified.protectedHeader, verified.payload, options),
1062
- protectedHeader: verified.protectedHeader
1063
- };
1064
- if (typeof key === "function") return {
1065
- ...result,
1066
- key: verified.key
1067
- };
1068
- return result;
1069
- }
1070
-
1071
- //#endregion
1072
- //#region ../../node_modules/jose/dist/webapi/lib/sign.js
1073
- async function sign(alg, key, data) {
1074
- const cryptoKey = await getSigKey(alg, key, "sign");
1075
- checkKeyLength(alg, cryptoKey);
1076
- const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);
1077
- return new Uint8Array(signature);
1078
- }
1079
-
1080
- //#endregion
1081
- //#region ../../node_modules/jose/dist/webapi/jws/flattened/sign.js
1082
- var FlattenedSign = class {
1083
- #payload;
1084
- #protectedHeader;
1085
- #unprotectedHeader;
1086
- constructor(payload) {
1087
- if (!(payload instanceof Uint8Array)) throw new TypeError("payload must be an instance of Uint8Array");
1088
- this.#payload = payload;
1089
- }
1090
- setProtectedHeader(protectedHeader) {
1091
- if (this.#protectedHeader) throw new TypeError("setProtectedHeader can only be called once");
1092
- this.#protectedHeader = protectedHeader;
1093
- return this;
1094
- }
1095
- setUnprotectedHeader(unprotectedHeader) {
1096
- if (this.#unprotectedHeader) throw new TypeError("setUnprotectedHeader can only be called once");
1097
- this.#unprotectedHeader = unprotectedHeader;
1098
- return this;
1099
- }
1100
- async sign(key, options) {
1101
- if (!this.#protectedHeader && !this.#unprotectedHeader) throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
1102
- if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
1103
- const joseHeader = {
1104
- ...this.#protectedHeader,
1105
- ...this.#unprotectedHeader
1106
- };
1107
- const extensions = validateCrit(JWSInvalid, new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader);
1108
- let b64 = true;
1109
- if (extensions.has("b64")) {
1110
- b64 = this.#protectedHeader.b64;
1111
- if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
1112
- }
1113
- const { alg } = joseHeader;
1114
- if (typeof alg !== "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
1115
- checkKeyType(alg, key, "sign");
1116
- let payloadS;
1117
- let payloadB;
1118
- if (b64) {
1119
- payloadS = encode(this.#payload);
1120
- payloadB = encode$1(payloadS);
1121
- } else {
1122
- payloadB = this.#payload;
1123
- payloadS = "";
1124
- }
1125
- let protectedHeaderString;
1126
- let protectedHeaderBytes;
1127
- if (this.#protectedHeader) {
1128
- protectedHeaderString = encode(JSON.stringify(this.#protectedHeader));
1129
- protectedHeaderBytes = encode$1(protectedHeaderString);
1130
- } else {
1131
- protectedHeaderString = "";
1132
- protectedHeaderBytes = new Uint8Array();
1133
- }
1134
- const data = concat(protectedHeaderBytes, encode$1("."), payloadB);
1135
- const jws = {
1136
- signature: encode(await sign(alg, await normalizeKey(key, alg), data)),
1137
- payload: payloadS
1138
- };
1139
- if (this.#unprotectedHeader) jws.header = this.#unprotectedHeader;
1140
- if (this.#protectedHeader) jws.protected = protectedHeaderString;
1141
- return jws;
1142
- }
1143
- };
1144
-
1145
- //#endregion
1146
- //#region ../../node_modules/jose/dist/webapi/jws/compact/sign.js
1147
- var CompactSign = class {
1148
- #flattened;
1149
- constructor(payload) {
1150
- this.#flattened = new FlattenedSign(payload);
1151
- }
1152
- setProtectedHeader(protectedHeader) {
1153
- this.#flattened.setProtectedHeader(protectedHeader);
1154
- return this;
1155
- }
1156
- async sign(key, options) {
1157
- const jws = await this.#flattened.sign(key, options);
1158
- if (jws.payload === void 0) throw new TypeError("use the flattened module for creating JWS with b64: false");
1159
- return `${jws.protected}.${jws.payload}.${jws.signature}`;
1160
- }
1161
- };
1162
-
1163
- //#endregion
1164
- //#region ../../node_modules/jose/dist/webapi/jwt/sign.js
1165
- var SignJWT = class {
1166
- #protectedHeader;
1167
- #jwt;
1168
- constructor(payload = {}) {
1169
- this.#jwt = new JWTClaimsBuilder(payload);
1170
- }
1171
- setIssuer(issuer) {
1172
- this.#jwt.iss = issuer;
1173
- return this;
1174
- }
1175
- setSubject(subject) {
1176
- this.#jwt.sub = subject;
1177
- return this;
1178
- }
1179
- setAudience(audience) {
1180
- this.#jwt.aud = audience;
1181
- return this;
1182
- }
1183
- setJti(jwtId) {
1184
- this.#jwt.jti = jwtId;
1185
- return this;
1186
- }
1187
- setNotBefore(input) {
1188
- this.#jwt.nbf = input;
1189
- return this;
1190
- }
1191
- setExpirationTime(input) {
1192
- this.#jwt.exp = input;
1193
- return this;
1194
- }
1195
- setIssuedAt(input) {
1196
- this.#jwt.iat = input;
1197
- return this;
1198
- }
1199
- setProtectedHeader(protectedHeader) {
1200
- this.#protectedHeader = protectedHeader;
1201
- return this;
1202
- }
1203
- async sign(key, options) {
1204
- const sig = new CompactSign(this.#jwt.data());
1205
- sig.setProtectedHeader(this.#protectedHeader);
1206
- if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && this.#protectedHeader.b64 === false) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
1207
- return sig.sign(key, options);
1208
- }
1209
- };
1210
-
1211
- //#endregion
1212
- //#region ../../node_modules/jose/dist/webapi/jwks/local.js
1213
- function getKtyFromAlg(alg) {
1214
- switch (typeof alg === "string" && alg.slice(0, 2)) {
1215
- case "RS":
1216
- case "PS": return "RSA";
1217
- case "ES": return "EC";
1218
- case "Ed": return "OKP";
1219
- case "ML": return "AKP";
1220
- default: throw new JOSENotSupported("Unsupported \"alg\" value for a JSON Web Key Set");
1221
- }
1222
- }
1223
- function isJWKSLike(jwks) {
1224
- return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike);
1225
- }
1226
- function isJWKLike(key) {
1227
- return isObject(key);
1228
- }
1229
- var LocalJWKSet = class {
1230
- #jwks;
1231
- #cached = /* @__PURE__ */ new WeakMap();
1232
- constructor(jwks) {
1233
- if (!isJWKSLike(jwks)) throw new JWKSInvalid("JSON Web Key Set malformed");
1234
- this.#jwks = structuredClone(jwks);
1235
- }
1236
- jwks() {
1237
- return this.#jwks;
1238
- }
1239
- async getKey(protectedHeader, token) {
1240
- const { alg, kid } = {
1241
- ...protectedHeader,
1242
- ...token?.header
1243
- };
1244
- const kty = getKtyFromAlg(alg);
1245
- const candidates = this.#jwks.keys.filter((jwk$1) => {
1246
- let candidate = kty === jwk$1.kty;
1247
- if (candidate && typeof kid === "string") candidate = kid === jwk$1.kid;
1248
- if (candidate && (typeof jwk$1.alg === "string" || kty === "AKP")) candidate = alg === jwk$1.alg;
1249
- if (candidate && typeof jwk$1.use === "string") candidate = jwk$1.use === "sig";
1250
- if (candidate && Array.isArray(jwk$1.key_ops)) candidate = jwk$1.key_ops.includes("verify");
1251
- if (candidate) switch (alg) {
1252
- case "ES256":
1253
- candidate = jwk$1.crv === "P-256";
1254
- break;
1255
- case "ES384":
1256
- candidate = jwk$1.crv === "P-384";
1257
- break;
1258
- case "ES512":
1259
- candidate = jwk$1.crv === "P-521";
1260
- break;
1261
- case "Ed25519":
1262
- case "EdDSA":
1263
- candidate = jwk$1.crv === "Ed25519";
1264
- break;
1265
- }
1266
- return candidate;
1267
- });
1268
- const { 0: jwk, length } = candidates;
1269
- if (length === 0) throw new JWKSNoMatchingKey();
1270
- if (length !== 1) {
1271
- const error = new JWKSMultipleMatchingKeys();
1272
- const _cached = this.#cached;
1273
- error[Symbol.asyncIterator] = async function* () {
1274
- for (const jwk$1 of candidates) try {
1275
- yield await importWithAlgCache(_cached, jwk$1, alg);
1276
- } catch {}
1277
- };
1278
- throw error;
1279
- }
1280
- return importWithAlgCache(this.#cached, jwk, alg);
1281
- }
1282
- };
1283
- async function importWithAlgCache(cache$1, jwk, alg) {
1284
- const cached = cache$1.get(jwk) || cache$1.set(jwk, {}).get(jwk);
1285
- if (cached[alg] === void 0) {
1286
- const key = await importJWK({
1287
- ...jwk,
1288
- ext: true
1289
- }, alg);
1290
- if (key instanceof Uint8Array || key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys");
1291
- cached[alg] = key;
1292
- }
1293
- return cached[alg];
1294
- }
1295
- function createLocalJWKSet(jwks) {
1296
- const set = new LocalJWKSet(jwks);
1297
- const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
1298
- Object.defineProperties(localJWKSet, { jwks: {
1299
- value: () => structuredClone(set.jwks()),
1300
- enumerable: false,
1301
- configurable: false,
1302
- writable: false
1303
- } });
1304
- return localJWKSet;
1305
- }
1306
-
1307
- //#endregion
1308
- //#region ../../node_modules/jose/dist/webapi/jwks/remote.js
1309
- function isCloudflareWorkers() {
1310
- return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel";
1311
- }
1312
- let USER_AGENT;
1313
- if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) USER_AGENT = `jose/v6.1.2`;
1314
- const customFetch = Symbol();
1315
- async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
1316
- const response = await fetchImpl(url, {
1317
- method: "GET",
1318
- signal,
1319
- redirect: "manual",
1320
- headers
1321
- }).catch((err) => {
1322
- if (err.name === "TimeoutError") throw new JWKSTimeout();
1323
- throw err;
1324
- });
1325
- if (response.status !== 200) throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
1326
- try {
1327
- return await response.json();
1328
- } catch {
1329
- throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON");
1330
- }
1331
- }
1332
- const jwksCache = Symbol();
1333
- function isFreshJwksCache(input, cacheMaxAge) {
1334
- if (typeof input !== "object" || input === null) return false;
1335
- if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) return false;
1336
- if (!("jwks" in input) || !isObject(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject)) return false;
1337
- return true;
1338
- }
1339
- var RemoteJWKSet = class {
1340
- #url;
1341
- #timeoutDuration;
1342
- #cooldownDuration;
1343
- #cacheMaxAge;
1344
- #jwksTimestamp;
1345
- #pendingFetch;
1346
- #headers;
1347
- #customFetch;
1348
- #local;
1349
- #cache;
1350
- constructor(url, options) {
1351
- if (!(url instanceof URL)) throw new TypeError("url must be an instance of URL");
1352
- this.#url = new URL(url.href);
1353
- this.#timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3;
1354
- this.#cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4;
1355
- this.#cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5;
1356
- this.#headers = new Headers(options?.headers);
1357
- if (USER_AGENT && !this.#headers.has("User-Agent")) this.#headers.set("User-Agent", USER_AGENT);
1358
- if (!this.#headers.has("accept")) {
1359
- this.#headers.set("accept", "application/json");
1360
- this.#headers.append("accept", "application/jwk-set+json");
1361
- }
1362
- this.#customFetch = options?.[customFetch];
1363
- if (options?.[jwksCache] !== void 0) {
1364
- this.#cache = options?.[jwksCache];
1365
- if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) {
1366
- this.#jwksTimestamp = this.#cache.uat;
1367
- this.#local = createLocalJWKSet(this.#cache.jwks);
1368
- }
1369
- }
1370
- }
1371
- pendingFetch() {
1372
- return !!this.#pendingFetch;
1373
- }
1374
- coolingDown() {
1375
- return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration : false;
1376
- }
1377
- fresh() {
1378
- return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge : false;
1379
- }
1380
- jwks() {
1381
- return this.#local?.jwks();
1382
- }
1383
- async getKey(protectedHeader, token) {
1384
- if (!this.#local || !this.fresh()) await this.reload();
1385
- try {
1386
- return await this.#local(protectedHeader, token);
1387
- } catch (err) {
1388
- if (err instanceof JWKSNoMatchingKey) {
1389
- if (this.coolingDown() === false) {
1390
- await this.reload();
1391
- return this.#local(protectedHeader, token);
1392
- }
1393
- }
1394
- throw err;
1395
- }
1396
- }
1397
- async reload() {
1398
- if (this.#pendingFetch && isCloudflareWorkers()) this.#pendingFetch = void 0;
1399
- this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch).then((json) => {
1400
- this.#local = createLocalJWKSet(json);
1401
- if (this.#cache) {
1402
- this.#cache.uat = Date.now();
1403
- this.#cache.jwks = json;
1404
- }
1405
- this.#jwksTimestamp = Date.now();
1406
- this.#pendingFetch = void 0;
1407
- }).catch((err) => {
1408
- this.#pendingFetch = void 0;
1409
- throw err;
1410
- });
1411
- await this.#pendingFetch;
1412
- }
1413
- };
1414
- function createRemoteJWKSet(url, options) {
1415
- const set = new RemoteJWKSet(url, options);
1416
- const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
1417
- Object.defineProperties(remoteJWKSet, {
1418
- coolingDown: {
1419
- get: () => set.coolingDown(),
1420
- enumerable: true,
1421
- configurable: false
1422
- },
1423
- fresh: {
1424
- get: () => set.fresh(),
1425
- enumerable: true,
1426
- configurable: false
1427
- },
1428
- reload: {
1429
- value: () => set.reload(),
1430
- enumerable: true,
1431
- configurable: false,
1432
- writable: false
1433
- },
1434
- reloading: {
1435
- get: () => set.pendingFetch(),
1436
- enumerable: true,
1437
- configurable: false
1438
- },
1439
- jwks: {
1440
- value: () => set.jwks(),
1441
- enumerable: true,
1442
- configurable: false,
1443
- writable: false
1444
- }
1445
- });
1446
- return remoteJWKSet;
1447
- }
1448
-
1449
- //#endregion
1450
- //#region src/security/providers/JwtProvider.ts
1451
- /**
1452
- * Provides utilities for working with JSON Web Tokens (JWT).
1453
- */
1454
- var JwtProvider = class {
1455
- log = (0, alepha_logger.$logger)();
1456
- keystore = [];
1457
- dateTimeProvider = (0, alepha.$inject)(alepha_datetime.DateTimeProvider);
1458
- encoder = new TextEncoder();
1459
- /**
1460
- * Adds a key loader to the embedded keystore.
1461
- *
1462
- * @param name
1463
- * @param secretKeyOrJwks
1464
- */
1465
- setKeyLoader(name, secretKeyOrJwks) {
1466
- if (typeof secretKeyOrJwks === "object") {
1467
- this.log.info(`will verify JWTs from key '${name}' with JWKS object (x${secretKeyOrJwks.keys.length})`);
1468
- this.keystore.push({
1469
- name,
1470
- keyLoader: createLocalJWKSet(secretKeyOrJwks)
1471
- });
1472
- } else if (this.isSecretKey(secretKeyOrJwks)) {
1473
- const secretKey = this.encoder.encode(secretKeyOrJwks);
1474
- this.log.info(`will verify JWTs from '${name}' with secret a key (${secretKey.length} bytes)`);
1475
- this.keystore.push({
1476
- name,
1477
- secretKey: secretKeyOrJwks,
1478
- keyLoader: () => Promise.resolve((0, node_crypto.createSecretKey)(secretKey))
1479
- });
1480
- } else {
1481
- this.log.info(`will verify JWTs from '${name}' with JWKS ${secretKeyOrJwks}`);
1482
- this.keystore.push({
1483
- name,
1484
- keyLoader: createRemoteJWKSet(new URL(secretKeyOrJwks))
1485
- });
1486
- }
1487
- }
1488
- /**
1489
- * Retrieves the payload from a JSON Web Token (JWT).
1490
- *
1491
- * @param token - The JWT to extract the payload from.
1492
- *
1493
- * @return A Promise that resolves with the payload object from the token.
1494
- */
1495
- async parse(token, keyName, options) {
1496
- for (const it of this.keystore) {
1497
- if (keyName && it.name !== keyName) continue;
1498
- this.log.trace(`Trying to verify token`, {
1499
- keyName: it.name,
1500
- options
1501
- });
1502
- try {
1503
- const verified = {
1504
- keyName: it.name,
1505
- result: await jwtVerify(token, it.keyLoader, {
1506
- currentDate: this.dateTimeProvider.now().toDate(),
1507
- ...options
1508
- })
1509
- };
1510
- this.log.trace("Token verified successfully", { keyName: verified.keyName });
1511
- return verified;
1512
- } catch (error) {
1513
- this.log.trace("Token verification has failed", error);
1514
- if (error instanceof JWTExpired) throw new SecurityError("Token expired", { cause: error });
1515
- if (error instanceof JWTClaimValidationFailed) throw new SecurityError("Token claim validation failed", { cause: error });
1516
- }
1517
- }
1518
- this.log.warn(`No valid key loader found to verify the token (keystore size: ${this.keystore.length})`);
1519
- throw new SecurityError("Invalid token");
1520
- }
1521
- /**
1522
- * Creates a JWT token with the provided payload and secret key.
1523
- *
1524
- * @param payload - The payload to be encoded in the token.
1525
- * It should include the `realm_access` property which contains an array of roles.
1526
- * @param keyName - The name of the key to use when signing the token.
1527
- *
1528
- * @returns The signed JWT token.
1529
- */
1530
- async create(payload, keyName, signOptions) {
1531
- const secretKey = keyName ? this.keystore.find((it) => it.name === keyName)?.secretKey : this.keystore[0]?.secretKey;
1532
- if (!secretKey) throw new alepha.AlephaError("No secret key found in the keystore");
1533
- const signJwt = new SignJWT(payload);
1534
- signJwt.setProtectedHeader({
1535
- alg: "HS256",
1536
- ...signOptions?.header
1537
- });
1538
- return await signJwt.sign(this.encoder.encode(secretKey));
1539
- }
1540
- /**
1541
- * Determines if the provided key is a secret key.
1542
- *
1543
- * @param key
1544
- * @protected
1545
- */
1546
- isSecretKey(key) {
1547
- return !key.startsWith("http");
1548
- }
1549
- };
1550
-
1551
- //#endregion
1552
- //#region src/security/providers/SecurityProvider.ts
1553
- const DEFAULT_APP_SECRET = "05759934015388327323179852515731";
1554
- const envSchema = alepha.t.object({ APP_SECRET: alepha.t.text({ default: DEFAULT_APP_SECRET }) });
1555
- var SecurityProvider = class {
1556
- UNKNOWN_USER_NAME = "Anonymous User";
1557
- PERMISSION_REGEXP = /^[\w-]+((:[\w-]+)+)?$/;
1558
- PERMISSION_REGEXP_WILDCARD = /^[\w-]+((:[\w-]+)*:\*|(:[\w-]+)+)?$/;
1559
- log = (0, alepha_logger.$logger)();
1560
- jwt = (0, alepha.$inject)(JwtProvider);
1561
- env = (0, alepha.$env)(envSchema);
1562
- alepha = (0, alepha.$inject)(alepha.Alepha);
1563
- get secretKey() {
1564
- return this.env.APP_SECRET;
1565
- }
1566
- /**
1567
- * The permissions configured for the security provider.
1568
- */
1569
- permissions = [];
1570
- /**
1571
- * The realms configured for the security provider.
1572
- */
1573
- realms = this.alepha.isTest() ? [{
1574
- name: "default",
1575
- secret: this.env.APP_SECRET,
1576
- roles: [{
1577
- name: "admin",
1578
- permissions: [{ name: "*" }]
1579
- }]
1580
- }] : [];
1581
- start = (0, alepha.$hook)({
1582
- on: "start",
1583
- handler: async () => {
1584
- if (this.alepha.isProduction() && this.secretKey === DEFAULT_APP_SECRET) this.log.warn("Using default APP_SECRET in production is not recommended. Please set a strong APP_SECRET value.");
1585
- for (const realm of this.realms) if (realm.secret) {
1586
- const secret = typeof realm.secret === "function" ? realm.secret() : realm.secret;
1587
- this.jwt.setKeyLoader(realm.name, secret);
1588
- }
1589
- }
1590
- });
1591
- /**
1592
- * Adds a role to one or more realms.
1593
- *
1594
- * @param role
1595
- * @param realms
1596
- */
1597
- createRole(role, ...realms) {
1598
- const list = realms.length ? realms.map((it) => {
1599
- const item = this.realms.find((realm) => realm.name === it);
1600
- if (!item) throw new RealmNotFoundError(it);
1601
- return item;
1602
- }) : this.realms;
1603
- for (const realm of list) {
1604
- for (const { name } of role.permissions) if (this.alepha.isStarted()) {
1605
- if (name === "*") continue;
1606
- if (this.permissions.find((it) => this.permissionToString(it) === name)) continue;
1607
- if (name.endsWith(":*")) {
1608
- const groupPrefix = name.slice(0, -2);
1609
- if (this.permissions.find((it) => {
1610
- if (!it.group) return false;
1611
- return it.group === groupPrefix || it.group.startsWith(`${groupPrefix}:`);
1612
- })) continue;
1613
- }
1614
- throw new SecurityError(`Permission '${name}' not found`);
1615
- } else if (name !== "*" && !this.PERMISSION_REGEXP_WILDCARD.test(name)) throw new InvalidPermissionError(name);
1616
- realm.roles.push(role);
1617
- }
1618
- return role;
1619
- }
1620
- /**
1621
- * Adds a permission to the security provider.
1622
- *
1623
- * @param raw - The permission to add.
1624
- */
1625
- createPermission(raw) {
1626
- if (this.alepha.isStarted()) throw new alepha.ContainerLockedError();
1627
- let permission;
1628
- if (typeof raw === "string") {
1629
- if (!this.PERMISSION_REGEXP.test(raw)) throw new InvalidPermissionError(raw);
1630
- const parts = raw.split(":");
1631
- if (parts.length === 1) permission = { name: parts[0] };
1632
- else {
1633
- const name = parts[parts.length - 1];
1634
- const groupParts = parts.slice(0, -1);
1635
- if (groupParts.length === 1) permission = {
1636
- group: groupParts[0],
1637
- name
1638
- };
1639
- else permission = {
1640
- group: groupParts.join(":"),
1641
- name
1642
- };
1643
- }
1644
- } else permission = raw;
1645
- const asString = this.permissionToString(permission);
1646
- if (!this.PERMISSION_REGEXP.test(asString)) throw new InvalidPermissionError(asString);
1647
- const existing = this.permissions.find((it) => this.permissionToString(it) === asString);
1648
- if (existing) {
1649
- this.log.warn(`Permission '${asString}' already exists. Skipping.`, {
1650
- current: existing,
1651
- new: permission
1652
- });
1653
- return existing;
1654
- }
1655
- this.log.trace(`Creating permission '${asString}'`);
1656
- this.permissions.push(permission);
1657
- return permission;
1658
- }
1659
- createRealm(realm) {
1660
- if (this.realms.length === 1 && this.realms[0].name === "default") this.realms.pop();
1661
- this.realms.push(realm);
1662
- }
1663
- /**
1664
- * Updates the roles for a realm then synchronizes the user account provider if available.
1665
- *
1666
- * Only available when the app is started.
1667
- *
1668
- * @param realm - The realm to update the roles for.
1669
- * @param roles - The roles to update.
1670
- */
1671
- async updateRealm(realm, roles) {
1672
- if (!this.alepha.isStarted()) throw new alepha.AppNotStartedError();
1673
- const realmInstance = this.realms.find((it) => it.name === realm);
1674
- if (!realmInstance) throw new RealmNotFoundError(realm);
1675
- realmInstance.roles = roles;
1676
- }
1677
- /**
1678
- * Creates a user account from the provided payload.
1679
- *
1680
- * @param payload - The payload to create the user account from.
1681
- * @param [realmName] - The realm containing the roles. Default is all.
1682
- *
1683
- * @returns The user info created from the payload.
1684
- */
1685
- createUserFromPayload(payload, realmName) {
1686
- const id = this.getIdFromPayload(payload);
1687
- const sessionId = this.getSessionIdFromPayload(payload);
1688
- const rolesFromPayload = this.getRolesFromPayload(payload);
1689
- const email = this.getEmailFromPayload(payload);
1690
- const username = this.getUsernameFromPayload(payload);
1691
- const picture = this.getPictureFromPayload(payload);
1692
- const name = this.getNameFromPayload(payload);
1693
- const organizations = this.getOrganizationsFromPayload(payload);
1694
- const rolesFromSystem = this.getRoles(realmName);
1695
- const roles = rolesFromPayload.reduce((arr, roleName) => arr.concat(rolesFromSystem.filter((it) => it.name === roleName)), []).map((it) => it.name);
1696
- const realm = this.realms.find((it) => it.name === realmName);
1697
- if (realm?.profile) return realm.profile(payload);
1698
- return {
1699
- id,
1700
- roles,
1701
- name,
1702
- email,
1703
- username,
1704
- picture,
1705
- organizations,
1706
- sessionId
1707
- };
1708
- }
1709
- /**
1710
- * Checks if the user has the specified permission.
1711
- *
1712
- * Bonus: we check also if the user has "ownership" flag.
1713
- *
1714
- * @param permissionLike - The permission to check for.
1715
- * @param roleEntries - The roles to check for the permission.
1716
- */
1717
- checkPermission(permissionLike, ...roleEntries) {
1718
- const roles = roleEntries.map((it) => {
1719
- const role = this.getRoles().find((role$1) => role$1.name === it);
1720
- if (!role) throw new SecurityError(`Role '${it}' not found`);
1721
- return role;
1722
- });
1723
- const permission = this.permissionToString(permissionLike);
1724
- if (roles.find((it) => it.permissions.find((it$1) => it$1.name === "*" && !it$1.exclude && !it$1.ownership))) return {
1725
- isAuthorized: true,
1726
- ownership: false
1727
- };
1728
- const result = {
1729
- isAuthorized: false,
1730
- ownership: void 0
1731
- };
1732
- const matchesPattern = (permissionName, pattern) => {
1733
- if (pattern === "*") return true;
1734
- if (pattern === permissionName) return true;
1735
- if (pattern.endsWith(":*")) {
1736
- const patternPrefix = pattern.slice(0, -2);
1737
- if (permissionName === patternPrefix) return false;
1738
- return permissionName.startsWith(`${patternPrefix}:`);
1739
- }
1740
- return false;
1741
- };
1742
- for (const role of roles) for (const rolePermission of role.permissions) if (matchesPattern(permission, rolePermission.name)) {
1743
- if (rolePermission.exclude) {
1744
- let isExcluded = false;
1745
- for (const excludePattern of rolePermission.exclude) if (matchesPattern(permission, excludePattern)) {
1746
- isExcluded = true;
1747
- break;
1748
- }
1749
- if (isExcluded) continue;
1750
- }
1751
- result.isAuthorized = true;
1752
- if (rolePermission.ownership) result.ownership = rolePermission.ownership;
1753
- else {
1754
- result.ownership = false;
1755
- return result;
1756
- }
1757
- }
1758
- return result;
1759
- }
1760
- /**
1761
- * Creates a user account from the provided payload.
1762
- */
1763
- async createUserFromToken(headerOrToken, options = {}) {
1764
- const token = headerOrToken?.replace("Bearer", "").trim();
1765
- if (typeof token !== "string" || token === "") throw new InvalidTokenError("Invalid authorization header, maybe token is missing ?");
1766
- const { result, keyName: realm } = await this.jwt.parse(token, options.realm, options.verify);
1767
- const info = this.createUserFromPayload(result.payload, realm);
1768
- const realmRoles = this.getRoles(realm).filter((it) => it.default);
1769
- const roles = info.roles ?? [];
1770
- for (const role of realmRoles) if (!roles.includes(role.name)) roles.push(role.name);
1771
- info.roles = roles;
1772
- await this.alepha.events.emit("security:user:created", {
1773
- realm,
1774
- user: info
1775
- });
1776
- let ownership;
1777
- if (options.permission) {
1778
- const check = this.checkPermission(options.permission, ...roles);
1779
- if (!check.isAuthorized) throw new SecurityError(`User is not allowed to access '${this.permissionToString(options.permission)}'`);
1780
- ownership = check.ownership;
1781
- }
1782
- return {
1783
- ...info,
1784
- ownership,
1785
- token,
1786
- realm
1787
- };
1788
- }
1789
- /**
1790
- * Checks if a user has a specific role.
1791
- *
1792
- * @param roleName - The role to check for.
1793
- * @param permission - The permission to check for.
1794
- * @returns True if the user has the role, false otherwise.
1795
- */
1796
- can(roleName, permission) {
1797
- return this.checkPermission(permission, roleName).isAuthorized;
1798
- }
1799
- /**
1800
- * Checks if a user has ownership of a specific permission.
1801
- */
1802
- ownership(roleName, permission) {
1803
- return this.checkPermission(permission, roleName).ownership;
1804
- }
1805
- /**
1806
- * Converts a permission object to a string.
1807
- *
1808
- * @param permission
1809
- */
1810
- permissionToString(permission) {
1811
- if (typeof permission === "string") return permission;
1812
- if (!permission.group) return permission.name;
1813
- return `${(Array.isArray(permission.group) ? permission.group : [permission.group]).join(":")}:${permission.name}`;
1814
- }
1815
- getRealms() {
1816
- return this.realms;
1817
- }
1818
- /**
1819
- * Retrieves the user account from the provided user ID.
1820
- *
1821
- * @param realm
1822
- */
1823
- getRoles(realm) {
1824
- if (realm) return [...this.realms.find((it) => it.name === realm)?.roles ?? []];
1825
- return this.realms.reduce((arr, it) => arr.concat(it.roles), []);
1826
- }
1827
- /**
1828
- * Returns all permissions.
1829
- *
1830
- * @param user - Filter permissions by user.
1831
- *
1832
- * @return An array containing all permissions.
1833
- */
1834
- getPermissions(user) {
1835
- if (user?.roles) {
1836
- const permissions = [];
1837
- const roles = user.roles ?? [];
1838
- for (const roleOrString of roles) {
1839
- const role = typeof roleOrString === "string" ? this.getRoles(user.realm).find((it) => it.name === roleOrString) : roleOrString;
1840
- if (!role) throw new SecurityError(`Role '${roleOrString}' not found`);
1841
- if (role.permissions.some((it) => it.name === "*" && !it.exclude)) return this.getPermissions();
1842
- for (const permission of role.permissions) {
1843
- let ref = [];
1844
- if (permission.name === "*") ref.push(...this.permissions);
1845
- else if (permission.name.includes(":")) {
1846
- const parts = permission.name.split(":");
1847
- const lastPart = parts[parts.length - 1];
1848
- if (lastPart === "*") {
1849
- const groupPrefix = parts.slice(0, -1).join(":");
1850
- ref.push(...this.permissions.filter((it) => {
1851
- if (!it.group) return false;
1852
- return it.group === groupPrefix || it.group.startsWith(`${groupPrefix}:`);
1853
- }));
1854
- } else {
1855
- const name = lastPart;
1856
- const group = parts.slice(0, -1).join(":");
1857
- ref.push(...this.permissions.filter((it) => {
1858
- if (it.name !== name) return false;
1859
- if (!it.group) return false;
1860
- return it.group === group;
1861
- }));
1862
- }
1863
- } else ref.push(...this.permissions.filter((it) => it.name === permission.name && !it.group));
1864
- const exclude = permission.exclude;
1865
- if (exclude) ref = ref.filter((it) => {
1866
- const permString = this.permissionToString(it);
1867
- return !exclude.some((excludePattern) => {
1868
- if (excludePattern === permString) return true;
1869
- if (excludePattern.endsWith(":*")) {
1870
- const excludePrefix = excludePattern.slice(0, -2);
1871
- return permString.startsWith(`${excludePrefix}:`);
1872
- }
1873
- return false;
1874
- });
1875
- });
1876
- permissions.push(...ref);
1877
- }
1878
- }
1879
- return [...new Set(permissions.filter((it) => it != null))];
1880
- }
1881
- return this.permissions;
1882
- }
1883
- /**
1884
- * Retrieves the user ID from the provided payload object.
1885
- *
1886
- * @param payload - The payload object from which to extract the user ID.
1887
- * @return The user ID as a string.
1888
- */
1889
- getIdFromPayload(payload) {
1890
- if (payload.sub != null) return String(payload.sub);
1891
- if (payload.id != null) return String(payload.id);
1892
- if (payload.userId != null) return String(payload.userId);
1893
- throw new SecurityError("Invalid JWT - missing id");
1894
- }
1895
- getSessionIdFromPayload(payload) {
1896
- if (!payload) return;
1897
- if (payload.sid) return String(payload.sid);
1898
- }
1899
- /**
1900
- * Retrieves the roles from the provided payload object.
1901
- * @param payload - The payload object from which to extract the roles.
1902
- * @return An array of role strings.
1903
- */
1904
- getRolesFromPayload(payload) {
1905
- return payload?.realm_access?.roles ?? payload?.roles ?? [];
1906
- }
1907
- getPictureFromPayload(payload) {
1908
- if (!payload) return;
1909
- if (payload.picture) return payload.picture;
1910
- if (payload.avatar_url) return payload.avatar_url;
1911
- if (payload.user_picture) return payload.user_picture;
1912
- }
1913
- getUsernameFromPayload(payload) {
1914
- if (!payload) return;
1915
- if (payload.preferred_username) return payload.preferred_username;
1916
- if (payload.username) return payload.username;
1917
- }
1918
- getEmailFromPayload(payload) {
1919
- if (!payload) return;
1920
- if (payload.email) return payload.email;
1921
- }
1922
- /**
1923
- * Returns the name from the given payload.
1924
- *
1925
- * @param payload - The payload object.
1926
- * @returns The name extracted from the payload, or an empty string if the payload is falsy or no name is found.
1927
- */
1928
- getNameFromPayload(payload) {
1929
- if (!payload) return this.UNKNOWN_USER_NAME;
1930
- if (payload.name) return payload.name;
1931
- if (typeof payload.given_name === "string" && typeof payload.family_name === "string") return `${payload.given_name} ${payload.family_name}`.trim();
1932
- return this.UNKNOWN_USER_NAME;
1933
- }
1934
- getOrganizationsFromPayload(payload) {
1935
- if (!payload) return;
1936
- if (payload.organization) {
1937
- if (typeof payload.organization === "string") return [payload.organization];
1938
- if (Array.isArray(payload.organization)) return payload.organization;
1939
- }
1940
- }
1941
- };
1942
-
1943
- //#endregion
1944
- //#region src/security/descriptors/$permission.ts
1945
- /**
1946
- * Create a new permission.
1947
- */
1948
- const $permission = (options = {}) => {
1949
- return (0, alepha.createDescriptor)(PermissionDescriptor, options);
1950
- };
1951
- var PermissionDescriptor = class extends alepha.Descriptor {
1952
- securityProvider = (0, alepha.$inject)(SecurityProvider);
1953
- get name() {
1954
- return this.options.name || this.config.propertyKey;
1955
- }
1956
- get group() {
1957
- return this.options.group || this.config.service.name;
1958
- }
1959
- toString() {
1960
- return `${this.group}:${this.name}`;
1961
- }
1962
- onInit() {
1963
- this.securityProvider.createPermission({
1964
- name: this.name,
1965
- group: this.group,
1966
- description: this.options.description
1967
- });
1968
- }
1969
- /**
1970
- * Check if the user has the permission.
1971
- */
1972
- can(user) {
1973
- if (!user.roles) return false;
1974
- return this.securityProvider.checkPermission(this, ...user.roles).isAuthorized;
1975
- }
1976
- };
1977
- $permission[alepha.KIND] = PermissionDescriptor;
1978
-
1979
- //#endregion
1980
- //#region src/security/descriptors/$realm.ts
1981
- /**
1982
- * Create a new realm.
1983
- */
1984
- const $realm = (options) => {
1985
- return (0, alepha.createDescriptor)(RealmDescriptor, options);
1986
- };
1987
- var RealmDescriptor = class extends alepha.Descriptor {
1988
- securityProvider = (0, alepha.$inject)(SecurityProvider);
1989
- dateTimeProvider = (0, alepha.$inject)(alepha_datetime.DateTimeProvider);
1990
- jwt = (0, alepha.$inject)(JwtProvider);
1991
- log = (0, alepha_logger.$logger)();
1992
- get name() {
1993
- return this.options.name || this.config.propertyKey;
1994
- }
1995
- get accessTokenExpiration() {
1996
- return this.dateTimeProvider.duration(this.options.settings?.accessToken?.expiration ?? [15, "minutes"]);
1997
- }
1998
- get refreshTokenExpiration() {
1999
- return this.dateTimeProvider.duration(this.options.settings?.refreshToken?.expiration ?? [30, "days"]);
2000
- }
2001
- onInit() {
2002
- const roles = this.options.roles?.map((it) => {
2003
- if (typeof it === "string") {
2004
- const role = this.getRoles().find((role$1) => role$1.name === it);
2005
- if (!role) throw new SecurityError(`Role '${it}' not found`);
2006
- return role;
2007
- }
2008
- return it;
2009
- }) ?? [];
2010
- this.securityProvider.createRealm({
2011
- name: this.name,
2012
- profile: this.options.profile,
2013
- secret: "jwks" in this.options ? this.options.jwks : this.options.secret,
2014
- roles
2015
- });
2016
- }
2017
- /**
2018
- * Get all roles in the realm.
2019
- */
2020
- getRoles() {
2021
- return this.securityProvider.getRoles(this.name);
2022
- }
2023
- /**
2024
- * Set all roles in the realm.
2025
- */
2026
- async setRoles(roles) {
2027
- await this.securityProvider.updateRealm(this.name, roles);
2028
- }
2029
- /**
2030
- * Get a role by name, throws an error if not found.
2031
- */
2032
- getRoleByName(name) {
2033
- const role = this.getRoles().find((it) => it.name === name);
2034
- if (!role) throw new SecurityError(`Role '${name}' not found`);
2035
- return role;
2036
- }
2037
- async parseToken(token) {
2038
- const { result } = await this.jwt.parse(token, this.name);
2039
- return result.payload;
2040
- }
2041
- /**
2042
- * Create a token for the subject.
2043
- */
2044
- async createToken(user, refreshToken) {
2045
- let sid = refreshToken?.sid;
2046
- let refresh_token = refreshToken?.refresh_token;
2047
- let refresh_token_expires_in = refreshToken?.refresh_token_expires_in;
2048
- const iat = this.dateTimeProvider.now().unix();
2049
- const exp = iat + this.accessTokenExpiration.asSeconds();
2050
- if (!refreshToken) {
2051
- const create = this.options.settings?.onCreateSession;
2052
- if (create) {
2053
- const expiresIn = this.refreshTokenExpiration.asSeconds();
2054
- const { refreshToken: refreshToken$1, sessionId } = await create(user, { expiresIn });
2055
- refresh_token = refreshToken$1;
2056
- refresh_token_expires_in = expiresIn;
2057
- sid = sessionId;
2058
- } else {
2059
- const payload = {
2060
- sub: user.id,
2061
- exp: iat + this.refreshTokenExpiration.asSeconds(),
2062
- iat,
2063
- aud: this.name
2064
- };
2065
- this.log.trace("Creating refresh token", payload);
2066
- sid = crypto.randomUUID();
2067
- refresh_token_expires_in = this.refreshTokenExpiration.asSeconds();
2068
- refresh_token = await this.jwt.create(payload, this.name, { header: { typ: "refresh" } });
2069
- }
2070
- }
2071
- this.log.trace("Creating access token", {
2072
- sub: user.id,
2073
- exp,
2074
- iat,
2075
- aud: this.name
2076
- });
2077
- return {
2078
- access_token: await this.jwt.create({
2079
- sub: user.id,
2080
- exp,
2081
- iat,
2082
- aud: this.name,
2083
- sid,
2084
- name: user.name,
2085
- email: user.email,
2086
- preferred_username: user.username,
2087
- picture: user.picture,
2088
- organizations: user.organizations,
2089
- roles: user.roles
2090
- }, this.name),
2091
- token_type: "Bearer",
2092
- expires_in: this.accessTokenExpiration.asSeconds(),
2093
- issued_at: iat,
2094
- refresh_token,
2095
- refresh_token_expires_in
2096
- };
2097
- }
2098
- async refreshToken(refreshToken, accessToken) {
2099
- if (this.options.settings?.onRefreshSession) {
2100
- const { user: user$1, expiresIn: expiresIn$1, sessionId } = await this.options.settings.onRefreshSession(refreshToken);
2101
- return {
2102
- user: user$1,
2103
- tokens: await this.createToken(user$1, {
2104
- sid: sessionId,
2105
- refresh_token: refreshToken,
2106
- refresh_token_expires_in: expiresIn$1
2107
- })
2108
- };
2109
- }
2110
- if (!accessToken) throw new alepha.AlephaError("An access token is required for refreshing");
2111
- const user = await this.securityProvider.createUserFromToken(accessToken, {
2112
- realm: this.name,
2113
- verify: { currentDate: /* @__PURE__ */ new Date(0) }
2114
- });
2115
- const { result: { payload } } = await this.jwt.parse(refreshToken, this.name, {
2116
- typ: "refresh",
2117
- audience: this.name,
2118
- subject: user.id
2119
- });
2120
- const iat = this.dateTimeProvider.now().unix();
2121
- const expiresIn = payload.exp ? payload.exp - iat : this.refreshTokenExpiration.asSeconds();
2122
- return {
2123
- user,
2124
- tokens: await this.createToken(user, {
2125
- sid: payload.sid,
2126
- refresh_token: refreshToken,
2127
- refresh_token_expires_in: expiresIn
2128
- })
2129
- };
2130
- }
2131
- };
2132
- $realm[alepha.KIND] = RealmDescriptor;
2133
-
2134
- //#endregion
2135
- //#region src/security/descriptors/$role.ts
2136
- /**
2137
- * Create a new role.
2138
- */
2139
- const $role = (options = {}) => {
2140
- return (0, alepha.createDescriptor)(RoleDescriptor, options);
2141
- };
2142
- var RoleDescriptor = class extends alepha.Descriptor {
2143
- securityProvider = (0, alepha.$inject)(SecurityProvider);
2144
- get name() {
2145
- return this.options.name || this.config.propertyKey;
2146
- }
2147
- onInit() {
2148
- this.securityProvider.createRole({
2149
- ...this.options,
2150
- name: this.name,
2151
- permissions: this.options.permissions?.map((it) => {
2152
- if (typeof it === "string") return { name: it };
2153
- return it;
2154
- }) ?? []
2155
- });
2156
- }
2157
- /**
2158
- * Get the realm of the role.
2159
- */
2160
- get realm() {
2161
- return this.options.realm;
2162
- }
2163
- can(permission) {
2164
- return this.securityProvider.can(this.name, permission);
2165
- }
2166
- check(permission) {
2167
- return this.securityProvider.checkPermission(permission, this.name);
2168
- }
2169
- };
2170
- $role[alepha.KIND] = RoleDescriptor;
2171
-
2172
- //#endregion
2173
- //#region src/security/providers/CryptoProvider.ts
2174
- const scryptAsync = (0, node_util.promisify)(node_crypto.scrypt);
2175
- var CryptoProvider = class {
2176
- async hashPassword(password) {
2177
- const salt = (0, node_crypto.randomBytes)(16).toString("hex");
2178
- return `${salt}:${(await scryptAsync(password, salt, 64)).toString("hex")}`;
2179
- }
2180
- async verifyPassword(password, stored) {
2181
- if (!stored || typeof stored !== "string") return false;
2182
- const parts = stored.split(":");
2183
- if (parts.length !== 2) return false;
2184
- const [salt, originalHex] = parts;
2185
- if (!salt || !originalHex) return false;
2186
- if (originalHex.length % 2 !== 0 || !/^[0-9a-f]+$/i.test(originalHex)) return false;
2187
- try {
2188
- const derivedKey = await scryptAsync(password, salt, 64);
2189
- const originalKey = Buffer.from(originalHex, "hex");
2190
- if (derivedKey.length !== originalKey.length) return false;
2191
- return (0, node_crypto.timingSafeEqual)(derivedKey, originalKey);
2192
- } catch (error) {
2193
- return false;
2194
- }
2195
- }
2196
- randomUUID() {
2197
- return (0, node_crypto.randomUUID)();
2198
- }
2199
- };
2200
-
2201
- //#endregion
2202
- //#region src/security/descriptors/$serviceAccount.ts
2203
- /**
2204
- * Allow to get an access token for a service account.
2205
- *
2206
- * You have some options to configure the service account:
2207
- * - a OAUTH2 URL using client credentials grant type
2208
- * - a JWT secret shared between the services
2209
- *
2210
- * @example
2211
- * ```ts
2212
- * import { $serviceAccount } from "alepha/security";
2213
- *
2214
- * class MyService {
2215
- * serviceAccount = $serviceAccount({
2216
- * oauth2: {
2217
- * url: "https://example.com/oauth2/token",
2218
- * clientId: "your-client-id",
2219
- * clientSecret: "your-client-secret",
2220
- * }
2221
- * });
2222
- *
2223
- * async fetchData() {
2224
- * const token = await this.serviceAccount.token();
2225
- * // or
2226
- * const response = await this.serviceAccount.fetch("https://api.example.com/data");
2227
- * }
2228
- * }
2229
- * ```
2230
- */
2231
- const $serviceAccount = (options) => {
2232
- const { alepha: alepha$1 } = (0, alepha.$context)();
2233
- const store = {};
2234
- const dateTimeProvider = alepha$1.inject(alepha_datetime.DateTimeProvider);
2235
- const gracePeriod = options.gracePeriod ?? 30;
2236
- const cacheToken = (response) => {
2237
- store.cache = {
2238
- ...response,
2239
- issued_at: dateTimeProvider.now().unix()
2240
- };
2241
- };
2242
- const getTokenFromCache = () => {
2243
- if (store.cache) {
2244
- const { access_token, expires_in, issued_at } = store.cache;
2245
- if (!expires_in) return access_token;
2246
- const now = dateTimeProvider.now().unix();
2247
- if (issued_at + expires_in - gracePeriod > now) return access_token;
2248
- }
2249
- };
2250
- if ("oauth2" in options) {
2251
- const { url, clientId, clientSecret } = options.oauth2;
2252
- const token = async () => {
2253
- const tokenFromCache = getTokenFromCache();
2254
- if (tokenFromCache) return tokenFromCache;
2255
- let response;
2256
- try {
2257
- response = await fetch(url, {
2258
- method: "POST",
2259
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
2260
- body: new URLSearchParams({
2261
- grant_type: "client_credentials",
2262
- client_id: clientId,
2263
- client_secret: clientSecret
2264
- })
2265
- });
2266
- } catch (error) {
2267
- throw new Error(`Failed to fetch access token from ${url}: ${error instanceof Error ? error.message : String(error)}`);
2268
- }
2269
- if (!response.ok) {
2270
- let errorMessage = `HTTP ${response.status} ${response.statusText}`;
2271
- try {
2272
- const errorBody = await response.text();
2273
- errorMessage += `: ${errorBody}`;
2274
- } catch {}
2275
- throw new Error(`Failed to fetch access token: ${errorMessage}`);
2276
- }
2277
- let json;
2278
- try {
2279
- json = await response.json();
2280
- } catch (error) {
2281
- throw new Error(`Failed to parse access token response as JSON: ${error instanceof Error ? error.message : String(error)}`);
2282
- }
2283
- if (!json.access_token || !json.expires_in) throw new Error(`Invalid access token response: missing access_token or expires_in. Response: ${JSON.stringify(json)}`);
2284
- cacheToken(json);
2285
- return json.access_token;
2286
- };
2287
- return { token };
2288
- }
2289
- return { token: async () => {
2290
- const tokenFromCache = getTokenFromCache();
2291
- if (tokenFromCache) return tokenFromCache;
2292
- const token = await options.realm.createToken(options.user);
2293
- cacheToken({
2294
- ...token,
2295
- issued_at: dateTimeProvider.now().unix()
2296
- });
2297
- return token.access_token;
2298
- } };
2299
- };
2300
-
2301
- //#endregion
2302
- //#region src/security/errors/InvalidCredentialsError.ts
2303
- /**
2304
- * Error thrown when the provided credentials are invalid.
2305
- *
2306
- * Message can not be changed to avoid leaking information.
2307
- * Cause is omitted for the same reason.
2308
- */
2309
- var InvalidCredentialsError = class extends alepha_server.UnauthorizedError {
2310
- name = "UnauthorizedError";
2311
- constructor() {
2312
- super("Invalid credentials");
2313
- }
2314
- };
2315
-
2316
- //#endregion
2317
- //#region src/security/schemas/permissionSchema.ts
2318
- const permissionSchema = alepha.t.object({
2319
- name: alepha.t.text({ description: "Name of the permission." }),
2320
- group: alepha.t.optional(alepha.t.text({ description: "Group of the permission." })),
2321
- description: alepha.t.optional(alepha.t.text({ description: "Describe the permission." })),
2322
- method: alepha.t.optional(alepha.t.text({ description: "HTTP method of the permission. When available." })),
2323
- path: alepha.t.optional(alepha.t.text({ description: "Pathname of the permission. When available." }))
2324
- });
2325
-
2326
- //#endregion
2327
- //#region src/security/schemas/roleSchema.ts
2328
- const roleSchema = alepha.t.object({
2329
- name: alepha.t.text({ description: "Name of the role." }),
2330
- description: alepha.t.optional(alepha.t.text({ description: "Describe the role." })),
2331
- default: alepha.t.optional(alepha.t.boolean({ description: "If true, this role will be assigned to all users by default." })),
2332
- permissions: alepha.t.array(alepha.t.object({
2333
- name: alepha.t.text({ description: "Name of the permission." }),
2334
- ownership: alepha.t.optional(alepha.t.boolean({ description: "If true, user will only have access to it's own resources." })),
2335
- exclude: alepha.t.optional(alepha.t.array(alepha.t.text(), { description: "Exclude some permissions. Useful when 'name' is a wildcard." }))
2336
- }))
2337
- });
2338
-
2339
- //#endregion
2340
- //#region src/security/schemas/userAccountInfoSchema.ts
2341
- const userAccountInfoSchema = alepha.t.object({
2342
- id: alepha.t.text({ description: "Unique identifier for the user." }),
2343
- name: alepha.t.optional(alepha.t.text({ description: "Full name of the user." })),
2344
- email: alepha.t.optional(alepha.t.text({
2345
- description: "Email address of the user.",
2346
- format: "email"
2347
- })),
2348
- username: alepha.t.optional(alepha.t.text({ description: "Preferred username of the user." })),
2349
- picture: alepha.t.optional(alepha.t.text({ description: "URL to the user's profile picture." })),
2350
- sessionId: alepha.t.optional(alepha.t.text({ description: "Session identifier for the user, if applicable." })),
2351
- organizations: alepha.t.optional(alepha.t.array(alepha.t.text(), { description: "List of organizations the user belongs to." })),
2352
- roles: alepha.t.optional(alepha.t.array(alepha.t.text(), { description: "List of roles assigned to the user." }))
2353
- });
2354
-
2355
- //#endregion
2356
- //#region src/security/index.ts
2357
- /**
2358
- * Provides comprehensive authentication and authorization capabilities with JWT tokens, role-based access control, and user management.
2359
- *
2360
- * The security module enables building secure applications using descriptors like `$realm`, `$role`, and `$permission`
2361
- * on class properties. It offers JWT-based authentication, fine-grained permissions, service accounts, and seamless
2362
- * integration with various authentication providers and user management systems.
2363
- *
2364
- * @see {@link $realm}
2365
- * @see {@link $role}
2366
- * @see {@link $permission}
2367
- * @module alepha.security
2368
- */
2369
- const AlephaSecurity = (0, alepha.$module)({
2370
- name: "alepha.security",
2371
- descriptors: [
2372
- $realm,
2373
- $role,
2374
- $permission
2375
- ],
2376
- services: [
2377
- SecurityProvider,
2378
- JwtProvider,
2379
- CryptoProvider
2380
- ]
2381
- });
2382
-
2383
- //#endregion
2384
- exports.$permission = $permission;
2385
- exports.$realm = $realm;
2386
- exports.$role = $role;
2387
- exports.$serviceAccount = $serviceAccount;
2388
- exports.AlephaSecurity = AlephaSecurity;
2389
- exports.CryptoProvider = CryptoProvider;
2390
- exports.DEFAULT_APP_SECRET = DEFAULT_APP_SECRET;
2391
- exports.InvalidCredentialsError = InvalidCredentialsError;
2392
- exports.InvalidPermissionError = InvalidPermissionError;
2393
- exports.JwtProvider = JwtProvider;
2394
- exports.PermissionDescriptor = PermissionDescriptor;
2395
- exports.RealmDescriptor = RealmDescriptor;
2396
- exports.RoleDescriptor = RoleDescriptor;
2397
- exports.SecurityError = SecurityError;
2398
- exports.SecurityProvider = SecurityProvider;
2399
- exports.permissionSchema = permissionSchema;
2400
- exports.roleSchema = roleSchema;
2401
- exports.userAccountInfoSchema = userAccountInfoSchema;
2402
- //# sourceMappingURL=index.cjs.map