@tempoxyz/id 0.0.0-pr-187.sha-eed04d3

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 (712) hide show
  1. package/README.md +81 -0
  2. package/dist/App.d.ts +20 -0
  3. package/dist/App.d.ts.map +1 -0
  4. package/dist/App.js +26 -0
  5. package/dist/App.js.map +1 -0
  6. package/dist/app/client/.assetsignore +2 -0
  7. package/dist/app/client/assets/BRLA-CZvVDNYr.png +0 -0
  8. package/dist/app/client/assets/CHFAU-DCedc4aH.png +0 -0
  9. package/dist/app/client/assets/DLUSD-BnRXm3EI.png +0 -0
  10. package/dist/app/client/assets/PRIME-CiFp2-3e.svg +14 -0
  11. package/dist/app/client/assets/Pilat-Bold-C1t1eIrF.woff2 +0 -0
  12. package/dist/app/client/assets/Pilat-Book-CbS8ofT8.woff2 +0 -0
  13. package/dist/app/client/assets/Pilat-Demi-CADSbPAt.woff2 +0 -0
  14. package/dist/app/client/assets/Pilat-Regular-Bx8vzE7q.woff2 +0 -0
  15. package/dist/app/client/assets/USD1-COVcO_PB.svg +30 -0
  16. package/dist/app/client/assets/YLDS-CRh8Zw0g.svg +3 -0
  17. package/dist/app/client/assets/ccip-Cq1mMiVl.js +1 -0
  18. package/dist/app/client/assets/frxUSD-n9pTpinR.svg +1 -0
  19. package/dist/app/client/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  20. package/dist/app/client/assets/index-B7YJVP00.css +1 -0
  21. package/dist/app/client/assets/index-UXTxXCLk.js +55 -0
  22. package/dist/app/client/assets/pathUSD-BvaO6ooS.svg +25 -0
  23. package/dist/app/client/assets/reset-co-CHrff.css +1 -0
  24. package/dist/app/client/assets/wYLDS-CaCKDrO-.svg +10 -0
  25. package/dist/app/db/auth.d.ts +3207 -0
  26. package/dist/app/db/auth.d.ts.map +1 -0
  27. package/dist/app/db/auth.js +330 -0
  28. package/dist/app/db/auth.js.map +1 -0
  29. package/dist/app/db/schema.d.ts +932 -0
  30. package/dist/app/db/schema.d.ts.map +1 -0
  31. package/dist/app/db/schema.js +171 -0
  32. package/dist/app/db/schema.js.map +1 -0
  33. package/dist/app/server/.vite/manifest.json +489 -0
  34. package/dist/app/server/assets/BRLA-CZvVDNYr.png +0 -0
  35. package/dist/app/server/assets/CHFAU-DCedc4aH.png +0 -0
  36. package/dist/app/server/assets/DLUSD-BnRXm3EI.png +0 -0
  37. package/dist/app/server/assets/PRIME-CiFp2-3e.svg +14 -0
  38. package/dist/app/server/assets/Pilat-Bold-C1t1eIrF.woff2 +0 -0
  39. package/dist/app/server/assets/Pilat-Book-CbS8ofT8.woff2 +0 -0
  40. package/dist/app/server/assets/Pilat-Demi-CADSbPAt.woff2 +0 -0
  41. package/dist/app/server/assets/Pilat-Regular-Bx8vzE7q.woff2 +0 -0
  42. package/dist/app/server/assets/USD1-COVcO_PB.svg +30 -0
  43. package/dist/app/server/assets/YLDS-CRh8Zw0g.svg +3 -0
  44. package/dist/app/server/assets/_tanstack-start-manifest_v-DjQNeRZp.js +1 -0
  45. package/dist/app/server/assets/arktype-aI7TBD0R-D1R3Byo5.js +2 -0
  46. package/dist/app/server/assets/arktype-aI7TBD0R-D1R3Byo5.js.map +1 -0
  47. package/dist/app/server/assets/authorize-C95F-9E1-CbESJKGU.js +31 -0
  48. package/dist/app/server/assets/authorize-C95F-9E1-CbESJKGU.js.map +1 -0
  49. package/dist/app/server/assets/bun-sqlite-dialect-DoOVo4ja-CtyBkVMb.js +2 -0
  50. package/dist/app/server/assets/bun-sqlite-dialect-DoOVo4ja-CtyBkVMb.js.map +1 -0
  51. package/dist/app/server/assets/call-UQamaCKN.js +32 -0
  52. package/dist/app/server/assets/call-UQamaCKN.js.map +1 -0
  53. package/dist/app/server/assets/ccip-CbNKFO4n.js +2 -0
  54. package/dist/app/server/assets/ccip-CbNKFO4n.js.map +1 -0
  55. package/dist/app/server/assets/compiled-query-Ds2NVcFT.js +2 -0
  56. package/dist/app/server/assets/compiled-query-Ds2NVcFT.js.map +1 -0
  57. package/dist/app/server/assets/convert-BIC8n32x.js +2 -0
  58. package/dist/app/server/assets/convert-BIC8n32x.js.map +1 -0
  59. package/dist/app/server/assets/cookie-CS900nSP.css +1 -0
  60. package/dist/app/server/assets/cookie-Cce9CrIP.js +10 -0
  61. package/dist/app/server/assets/cookie-Cce9CrIP.js.map +1 -0
  62. package/dist/app/server/assets/core-B1HCXUmx.js +56 -0
  63. package/dist/app/server/assets/core-B1HCXUmx.js.map +1 -0
  64. package/dist/app/server/assets/d1-sqlite-dialect-m0f01-4z-Cv-csE1u.js +2 -0
  65. package/dist/app/server/assets/d1-sqlite-dialect-m0f01-4z-Cv-csE1u.js.map +1 -0
  66. package/dist/app/server/assets/default-u_dwuiYb-BJJ9PwCi.js +2 -0
  67. package/dist/app/server/assets/default-u_dwuiYb-BJJ9PwCi.js.map +1 -0
  68. package/dist/app/server/assets/dist-BxSwugSY.js +1 -0
  69. package/dist/app/server/assets/dist-CZGFhmQd.js +2 -0
  70. package/dist/app/server/assets/dist-CZGFhmQd.js.map +1 -0
  71. package/dist/app/server/assets/dist-Dg3PQqiW.js +15 -0
  72. package/dist/app/server/assets/dist-Dg3PQqiW.js.map +1 -0
  73. package/dist/app/server/assets/effect-QlVUlMFu-2tSPDT2b.js +2 -0
  74. package/dist/app/server/assets/effect-QlVUlMFu-2tSPDT2b.js.map +1 -0
  75. package/dist/app/server/assets/empty-plugin-adapters-BaGcmrjC.js +2 -0
  76. package/dist/app/server/assets/empty-plugin-adapters-BaGcmrjC.js.map +1 -0
  77. package/dist/app/server/assets/factory-ipHlJXZY.js +5 -0
  78. package/dist/app/server/assets/factory-ipHlJXZY.js.map +1 -0
  79. package/dist/app/server/assets/frxUSD-n9pTpinR.svg +1 -0
  80. package/dist/app/server/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  81. package/dist/app/server/assets/get-id-field-B0x109VU.js +6 -0
  82. package/dist/app/server/assets/get-id-field-B0x109VU.js.map +1 -0
  83. package/dist/app/server/assets/index-CLddUTqr-xpSuLpBt.js +2 -0
  84. package/dist/app/server/assets/index-CLddUTqr-xpSuLpBt.js.map +1 -0
  85. package/dist/app/server/assets/index-DZEfthgZ-8Uq5s5Pt.js +2 -0
  86. package/dist/app/server/assets/index-DZEfthgZ-8Uq5s5Pt.js.map +1 -0
  87. package/dist/app/server/assets/kysely-adapter-MkHAI9Jk.js +1 -0
  88. package/dist/app/server/assets/node-sqlite-dialect-BowWLXvK.js +2 -0
  89. package/dist/app/server/assets/node-sqlite-dialect-BowWLXvK.js.map +1 -0
  90. package/dist/app/server/assets/pathUSD-BvaO6ooS.svg +25 -0
  91. package/dist/app/server/assets/reset-co-CHrff.css +1 -0
  92. package/dist/app/server/assets/rolldown-runtime-B0Z9INg1.js +1 -0
  93. package/dist/app/server/assets/router-CcbyBCI4.css +1 -0
  94. package/dist/app/server/assets/router-xjZtEeaI.js +7 -0
  95. package/dist/app/server/assets/router-xjZtEeaI.js.map +1 -0
  96. package/dist/app/server/assets/schema-check-Cf7QOZZD.js +9 -0
  97. package/dist/app/server/assets/schema-check-Cf7QOZZD.js.map +1 -0
  98. package/dist/app/server/assets/schemas-C2lCYmR5.js +2 -0
  99. package/dist/app/server/assets/schemas-C2lCYmR5.js.map +1 -0
  100. package/dist/app/server/assets/secp256k1-buM5g4AL.js +2 -0
  101. package/dist/app/server/assets/secp256k1-buM5g4AL.js.map +1 -0
  102. package/dist/app/server/assets/sqlite-adapter-C_LAV4e3.js +2 -0
  103. package/dist/app/server/assets/sqlite-adapter-C_LAV4e3.js.map +1 -0
  104. package/dist/app/server/assets/sqlite-introspector-DSCAP82F-Crx7Ny14.js +6 -0
  105. package/dist/app/server/assets/sqlite-introspector-DSCAP82F-Crx7Ny14.js.map +1 -0
  106. package/dist/app/server/assets/standard-json-Cg1N07hM.js +2 -0
  107. package/dist/app/server/assets/standard-json-Cg1N07hM.js.map +1 -0
  108. package/dist/app/server/assets/standard-json-DY77efq0.js +2 -0
  109. package/dist/app/server/assets/standard-json-DY77efq0.js.map +1 -0
  110. package/dist/app/server/assets/standard-json-ig2t0wRt.js +2 -0
  111. package/dist/app/server/assets/standard-json-ig2t0wRt.js.map +1 -0
  112. package/dist/app/server/assets/standard-json-t-LNckA6.js +2 -0
  113. package/dist/app/server/assets/standard-json-t-LNckA6.js.map +1 -0
  114. package/dist/app/server/assets/standard-openapi-CONmVRl8.js +2 -0
  115. package/dist/app/server/assets/standard-openapi-CONmVRl8.js.map +1 -0
  116. package/dist/app/server/assets/start-C63VetBp.js +2 -0
  117. package/dist/app/server/assets/start-C63VetBp.js.map +1 -0
  118. package/dist/app/server/assets/sury-CWZTCd75-xt1mWc9f.js +2 -0
  119. package/dist/app/server/assets/sury-CWZTCd75-xt1mWc9f.js.map +1 -0
  120. package/dist/app/server/assets/typebox-Dei93FPO-D_lCVdAz.js +2 -0
  121. package/dist/app/server/assets/typebox-Dei93FPO-D_lCVdAz.js.map +1 -0
  122. package/dist/app/server/assets/utils-C4ZXZIZW.js +2 -0
  123. package/dist/app/server/assets/utils-C4ZXZIZW.js.map +1 -0
  124. package/dist/app/server/assets/valibot--1zFm7rT-NSoY2xTp.js +2 -0
  125. package/dist/app/server/assets/valibot--1zFm7rT-NSoY2xTp.js.map +1 -0
  126. package/dist/app/server/assets/valibot-D_HTw1Gn-CJwWeOUE.js +2 -0
  127. package/dist/app/server/assets/valibot-D_HTw1Gn-CJwWeOUE.js.map +1 -0
  128. package/dist/app/server/assets/wYLDS-CaCKDrO-.svg +10 -0
  129. package/dist/app/server/assets/zod-Bwrt9trS-CV38yPnQ.js +2 -0
  130. package/dist/app/server/assets/zod-Bwrt9trS-CV38yPnQ.js.map +1 -0
  131. package/dist/app/server/assets/zod-DSgpEGAE-BvlnBE2L.js +2 -0
  132. package/dist/app/server/assets/zod-DSgpEGAE-BvlnBE2L.js.map +1 -0
  133. package/dist/app/server/index.js +574 -0
  134. package/dist/app/server/index.js.map +1 -0
  135. package/dist/app/server/wrangler.json +1 -0
  136. package/dist/cli/Admin.d.ts +38 -0
  137. package/dist/cli/Admin.d.ts.map +1 -0
  138. package/dist/cli/Admin.js +62 -0
  139. package/dist/cli/Admin.js.map +1 -0
  140. package/dist/cli/Apps.d.ts +9 -0
  141. package/dist/cli/Apps.d.ts.map +1 -0
  142. package/dist/cli/Apps.js +36 -0
  143. package/dist/cli/Apps.js.map +1 -0
  144. package/dist/cli/Cli.d.ts +14 -0
  145. package/dist/cli/Cli.d.ts.map +1 -0
  146. package/dist/cli/Cli.js +27 -0
  147. package/dist/cli/Cli.js.map +1 -0
  148. package/dist/cli/Project.d.ts +20 -0
  149. package/dist/cli/Project.d.ts.map +1 -0
  150. package/dist/cli/Project.js +88 -0
  151. package/dist/cli/Project.js.map +1 -0
  152. package/dist/cli/Realms.d.ts +24 -0
  153. package/dist/cli/Realms.d.ts.map +1 -0
  154. package/dist/cli/Realms.js +49 -0
  155. package/dist/cli/Realms.js.map +1 -0
  156. package/dist/cli/Session.d.ts +85 -0
  157. package/dist/cli/Session.d.ts.map +1 -0
  158. package/dist/cli/Session.js +178 -0
  159. package/dist/cli/Session.js.map +1 -0
  160. package/dist/cli/User.d.ts +29 -0
  161. package/dist/cli/User.d.ts.map +1 -0
  162. package/dist/cli/User.js +39 -0
  163. package/dist/cli/User.js.map +1 -0
  164. package/dist/cli/V1.d.ts +35 -0
  165. package/dist/cli/V1.d.ts.map +1 -0
  166. package/dist/cli/V1.js +41 -0
  167. package/dist/cli/V1.js.map +1 -0
  168. package/dist/cli/bin.d.ts +3 -0
  169. package/dist/cli/bin.d.ts.map +1 -0
  170. package/dist/cli/bin.js +46 -0
  171. package/dist/cli/bin.js.map +1 -0
  172. package/dist/cli/commands/admin/apps/create.d.ts +23 -0
  173. package/dist/cli/commands/admin/apps/create.d.ts.map +1 -0
  174. package/dist/cli/commands/admin/apps/create.js +89 -0
  175. package/dist/cli/commands/admin/apps/create.js.map +1 -0
  176. package/dist/cli/commands/admin/apps/delete.d.ts +14 -0
  177. package/dist/cli/commands/admin/apps/delete.d.ts.map +1 -0
  178. package/dist/cli/commands/admin/apps/delete.js +41 -0
  179. package/dist/cli/commands/admin/apps/delete.js.map +1 -0
  180. package/dist/cli/commands/admin/apps/index.d.ts +5 -0
  181. package/dist/cli/commands/admin/apps/index.d.ts.map +1 -0
  182. package/dist/cli/commands/admin/apps/index.js +14 -0
  183. package/dist/cli/commands/admin/apps/index.js.map +1 -0
  184. package/dist/cli/commands/admin/apps/list.d.ts +9 -0
  185. package/dist/cli/commands/admin/apps/list.d.ts.map +1 -0
  186. package/dist/cli/commands/admin/apps/list.js +26 -0
  187. package/dist/cli/commands/admin/apps/list.js.map +1 -0
  188. package/dist/cli/commands/admin/apps/rotate-secret.d.ts +16 -0
  189. package/dist/cli/commands/admin/apps/rotate-secret.d.ts.map +1 -0
  190. package/dist/cli/commands/admin/apps/rotate-secret.js +47 -0
  191. package/dist/cli/commands/admin/apps/rotate-secret.js.map +1 -0
  192. package/dist/cli/commands/admin/apps/update.d.ts +20 -0
  193. package/dist/cli/commands/admin/apps/update.d.ts.map +1 -0
  194. package/dist/cli/commands/admin/apps/update.js +76 -0
  195. package/dist/cli/commands/admin/apps/update.js.map +1 -0
  196. package/dist/cli/commands/admin/index.d.ts +5 -0
  197. package/dist/cli/commands/admin/index.d.ts.map +1 -0
  198. package/dist/cli/commands/admin/index.js +13 -0
  199. package/dist/cli/commands/admin/index.js.map +1 -0
  200. package/dist/cli/commands/admin/migrate.d.ts +9 -0
  201. package/dist/cli/commands/admin/migrate.d.ts.map +1 -0
  202. package/dist/cli/commands/admin/migrate.js +17 -0
  203. package/dist/cli/commands/admin/migrate.js.map +1 -0
  204. package/dist/cli/commands/admin/realms/add.d.ts +12 -0
  205. package/dist/cli/commands/admin/realms/add.d.ts.map +1 -0
  206. package/dist/cli/commands/admin/realms/add.js +42 -0
  207. package/dist/cli/commands/admin/realms/add.js.map +1 -0
  208. package/dist/cli/commands/admin/realms/index.d.ts +5 -0
  209. package/dist/cli/commands/admin/realms/index.d.ts.map +1 -0
  210. package/dist/cli/commands/admin/realms/index.js +13 -0
  211. package/dist/cli/commands/admin/realms/index.js.map +1 -0
  212. package/dist/cli/commands/admin/realms/list.d.ts +13 -0
  213. package/dist/cli/commands/admin/realms/list.d.ts.map +1 -0
  214. package/dist/cli/commands/admin/realms/list.js +36 -0
  215. package/dist/cli/commands/admin/realms/list.js.map +1 -0
  216. package/dist/cli/commands/admin/realms/passkeys/index.d.ts +5 -0
  217. package/dist/cli/commands/admin/realms/passkeys/index.d.ts.map +1 -0
  218. package/dist/cli/commands/admin/realms/passkeys/index.js +13 -0
  219. package/dist/cli/commands/admin/realms/passkeys/index.js.map +1 -0
  220. package/dist/cli/commands/admin/realms/passkeys/set.d.ts +16 -0
  221. package/dist/cli/commands/admin/realms/passkeys/set.d.ts.map +1 -0
  222. package/dist/cli/commands/admin/realms/passkeys/set.js +46 -0
  223. package/dist/cli/commands/admin/realms/passkeys/set.js.map +1 -0
  224. package/dist/cli/commands/admin/realms/privy/index.d.ts +5 -0
  225. package/dist/cli/commands/admin/realms/privy/index.d.ts.map +1 -0
  226. package/dist/cli/commands/admin/realms/privy/index.js +13 -0
  227. package/dist/cli/commands/admin/realms/privy/index.js.map +1 -0
  228. package/dist/cli/commands/admin/realms/privy/set.d.ts +18 -0
  229. package/dist/cli/commands/admin/realms/privy/set.d.ts.map +1 -0
  230. package/dist/cli/commands/admin/realms/privy/set.js +66 -0
  231. package/dist/cli/commands/admin/realms/privy/set.js.map +1 -0
  232. package/dist/cli/commands/admin/realms/remove.d.ts +11 -0
  233. package/dist/cli/commands/admin/realms/remove.d.ts.map +1 -0
  234. package/dist/cli/commands/admin/realms/remove.js +35 -0
  235. package/dist/cli/commands/admin/realms/remove.js.map +1 -0
  236. package/dist/cli/commands/admin/realms/secp256k1/disable.d.ts +15 -0
  237. package/dist/cli/commands/admin/realms/secp256k1/disable.d.ts.map +1 -0
  238. package/dist/cli/commands/admin/realms/secp256k1/disable.js +42 -0
  239. package/dist/cli/commands/admin/realms/secp256k1/disable.js.map +1 -0
  240. package/dist/cli/commands/admin/realms/secp256k1/enable.d.ts +15 -0
  241. package/dist/cli/commands/admin/realms/secp256k1/enable.d.ts.map +1 -0
  242. package/dist/cli/commands/admin/realms/secp256k1/enable.js +42 -0
  243. package/dist/cli/commands/admin/realms/secp256k1/enable.js.map +1 -0
  244. package/dist/cli/commands/admin/realms/secp256k1/index.d.ts +9 -0
  245. package/dist/cli/commands/admin/realms/secp256k1/index.d.ts.map +1 -0
  246. package/dist/cli/commands/admin/realms/secp256k1/index.js +17 -0
  247. package/dist/cli/commands/admin/realms/secp256k1/index.js.map +1 -0
  248. package/dist/cli/commands/admin/realms/set.d.ts +16 -0
  249. package/dist/cli/commands/admin/realms/set.d.ts.map +1 -0
  250. package/dist/cli/commands/admin/realms/set.js +46 -0
  251. package/dist/cli/commands/admin/realms/set.js.map +1 -0
  252. package/dist/cli/commands/admin/rotate-key.d.ts +15 -0
  253. package/dist/cli/commands/admin/rotate-key.d.ts.map +1 -0
  254. package/dist/cli/commands/admin/rotate-key.js +46 -0
  255. package/dist/cli/commands/admin/rotate-key.js.map +1 -0
  256. package/dist/cli/commands/init.d.ts +11 -0
  257. package/dist/cli/commands/init.d.ts.map +1 -0
  258. package/dist/cli/commands/init.js +34 -0
  259. package/dist/cli/commands/init.js.map +1 -0
  260. package/dist/cli/commands/login.d.ts +12 -0
  261. package/dist/cli/commands/login.d.ts.map +1 -0
  262. package/dist/cli/commands/login.js +29 -0
  263. package/dist/cli/commands/login.js.map +1 -0
  264. package/dist/cli/commands/logout.d.ts +8 -0
  265. package/dist/cli/commands/logout.d.ts.map +1 -0
  266. package/dist/cli/commands/logout.js +19 -0
  267. package/dist/cli/commands/logout.js.map +1 -0
  268. package/dist/cli/commands/whoami.d.ts +12 -0
  269. package/dist/cli/commands/whoami.d.ts.map +1 -0
  270. package/dist/cli/commands/whoami.js +24 -0
  271. package/dist/cli/commands/whoami.js.map +1 -0
  272. package/dist/client/Actions.d.ts +101 -0
  273. package/dist/client/Actions.d.ts.map +1 -0
  274. package/dist/client/Actions.js +90 -0
  275. package/dist/client/Actions.js.map +1 -0
  276. package/dist/client/Auth.d.ts +161 -0
  277. package/dist/client/Auth.d.ts.map +1 -0
  278. package/dist/client/Auth.js +113 -0
  279. package/dist/client/Auth.js.map +1 -0
  280. package/dist/client/Authorization.d.ts +29 -0
  281. package/dist/client/Authorization.d.ts.map +1 -0
  282. package/dist/client/Authorization.js +12 -0
  283. package/dist/client/Authorization.js.map +1 -0
  284. package/dist/client/Decorator.d.ts +170 -0
  285. package/dist/client/Decorator.d.ts.map +1 -0
  286. package/dist/client/Decorator.js +227 -0
  287. package/dist/client/Decorator.js.map +1 -0
  288. package/dist/client/Key.d.ts +85 -0
  289. package/dist/client/Key.d.ts.map +1 -0
  290. package/dist/client/Key.js +83 -0
  291. package/dist/client/Key.js.map +1 -0
  292. package/dist/client/Pending.d.ts +39 -0
  293. package/dist/client/Pending.d.ts.map +1 -0
  294. package/dist/client/Pending.js +12 -0
  295. package/dist/client/Pending.js.map +1 -0
  296. package/dist/client/Permissions.d.ts +34 -0
  297. package/dist/client/Permissions.d.ts.map +1 -0
  298. package/dist/client/Permissions.js +16 -0
  299. package/dist/client/Permissions.js.map +1 -0
  300. package/dist/client/Provider.d.ts +16 -0
  301. package/dist/client/Provider.d.ts.map +1 -0
  302. package/dist/client/Provider.js +12 -0
  303. package/dist/client/Provider.js.map +1 -0
  304. package/dist/client/Step.d.ts +21 -0
  305. package/dist/client/Step.d.ts.map +1 -0
  306. package/dist/client/Step.js +16 -0
  307. package/dist/client/Step.js.map +1 -0
  308. package/dist/client/Storage.d.ts +27 -0
  309. package/dist/client/Storage.d.ts.map +1 -0
  310. package/dist/client/Storage.js +16 -0
  311. package/dist/client/Storage.js.map +1 -0
  312. package/dist/client/TempoAccount.d.ts +40 -0
  313. package/dist/client/TempoAccount.d.ts.map +1 -0
  314. package/dist/client/TempoAccount.js +16 -0
  315. package/dist/client/TempoAccount.js.map +1 -0
  316. package/dist/client/Tokens.d.ts +25 -0
  317. package/dist/client/Tokens.d.ts.map +1 -0
  318. package/dist/client/Tokens.js +12 -0
  319. package/dist/client/Tokens.js.map +1 -0
  320. package/dist/client/User.d.ts +21 -0
  321. package/dist/client/User.d.ts.map +1 -0
  322. package/dist/client/User.js +12 -0
  323. package/dist/client/User.js.map +1 -0
  324. package/dist/client/actions/account.d.ts +25 -0
  325. package/dist/client/actions/account.d.ts.map +1 -0
  326. package/dist/client/actions/account.js +34 -0
  327. package/dist/client/actions/account.js.map +1 -0
  328. package/dist/client/actions/device.d.ts +53 -0
  329. package/dist/client/actions/device.d.ts.map +1 -0
  330. package/dist/client/actions/device.js +79 -0
  331. package/dist/client/actions/device.js.map +1 -0
  332. package/dist/client/actions/email.d.ts +84 -0
  333. package/dist/client/actions/email.d.ts.map +1 -0
  334. package/dist/client/actions/email.js +63 -0
  335. package/dist/client/actions/email.js.map +1 -0
  336. package/dist/client/actions/oauth.d.ts +115 -0
  337. package/dist/client/actions/oauth.d.ts.map +1 -0
  338. package/dist/client/actions/oauth.js +105 -0
  339. package/dist/client/actions/oauth.js.map +1 -0
  340. package/dist/client/actions/passkey.d.ts +88 -0
  341. package/dist/client/actions/passkey.d.ts.map +1 -0
  342. package/dist/client/actions/passkey.js +60 -0
  343. package/dist/client/actions/passkey.js.map +1 -0
  344. package/dist/client/actions/provider.d.ts +49 -0
  345. package/dist/client/actions/provider.d.ts.map +1 -0
  346. package/dist/client/actions/provider.js +34 -0
  347. package/dist/client/actions/provider.js.map +1 -0
  348. package/dist/client/actions/realm.d.ts +24 -0
  349. package/dist/client/actions/realm.d.ts.map +1 -0
  350. package/dist/client/actions/realm.js +15 -0
  351. package/dist/client/actions/realm.js.map +1 -0
  352. package/dist/client/actions/redirect.d.ts +153 -0
  353. package/dist/client/actions/redirect.d.ts.map +1 -0
  354. package/dist/client/actions/redirect.js +236 -0
  355. package/dist/client/actions/redirect.js.map +1 -0
  356. package/dist/client/internal/accessKey.d.ts +21 -0
  357. package/dist/client/internal/accessKey.d.ts.map +1 -0
  358. package/dist/client/internal/accessKey.js +38 -0
  359. package/dist/client/internal/accessKey.js.map +1 -0
  360. package/dist/client/internal/account.d.ts +14 -0
  361. package/dist/client/internal/account.d.ts.map +1 -0
  362. package/dist/client/internal/account.js +3 -0
  363. package/dist/client/internal/account.js.map +1 -0
  364. package/dist/client/internal/api.d.ts +106 -0
  365. package/dist/client/internal/api.d.ts.map +1 -0
  366. package/dist/client/internal/api.js +129 -0
  367. package/dist/client/internal/api.js.map +1 -0
  368. package/dist/client/internal/headless.d.ts +33 -0
  369. package/dist/client/internal/headless.d.ts.map +1 -0
  370. package/dist/client/internal/headless.js +46 -0
  371. package/dist/client/internal/headless.js.map +1 -0
  372. package/dist/client/internal/indexedDb.d.ts +9 -0
  373. package/dist/client/internal/indexedDb.d.ts.map +1 -0
  374. package/dist/client/internal/indexedDb.js +32 -0
  375. package/dist/client/internal/indexedDb.js.map +1 -0
  376. package/dist/client/internal/request.d.ts +58 -0
  377. package/dist/client/internal/request.d.ts.map +1 -0
  378. package/dist/client/internal/request.js +45 -0
  379. package/dist/client/internal/request.js.map +1 -0
  380. package/dist/client/internal/store.d.ts +12 -0
  381. package/dist/client/internal/store.d.ts.map +1 -0
  382. package/dist/client/internal/store.js +15 -0
  383. package/dist/client/internal/store.js.map +1 -0
  384. package/dist/client.d.ts +20 -0
  385. package/dist/client.d.ts.map +1 -0
  386. package/dist/client.js +20 -0
  387. package/dist/client.js.map +1 -0
  388. package/dist/index.d.ts +7 -0
  389. package/dist/index.d.ts.map +1 -0
  390. package/dist/index.js +7 -0
  391. package/dist/index.js.map +1 -0
  392. package/dist/internal/Apps.d.ts +3051 -0
  393. package/dist/internal/Apps.d.ts.map +1 -0
  394. package/dist/internal/Apps.js +472 -0
  395. package/dist/internal/Apps.js.map +1 -0
  396. package/dist/internal/Auth.d.ts +4058 -0
  397. package/dist/internal/Auth.d.ts.map +1 -0
  398. package/dist/internal/Auth.js +137 -0
  399. package/dist/internal/Auth.js.map +1 -0
  400. package/dist/internal/Authorize.d.ts +532 -0
  401. package/dist/internal/Authorize.d.ts.map +1 -0
  402. package/dist/internal/Authorize.js +326 -0
  403. package/dist/internal/Authorize.js.map +1 -0
  404. package/dist/internal/Device.d.ts +371 -0
  405. package/dist/internal/Device.d.ts.map +1 -0
  406. package/dist/internal/Device.js +271 -0
  407. package/dist/internal/Device.js.map +1 -0
  408. package/dist/internal/Env.d.ts +57 -0
  409. package/dist/internal/Env.d.ts.map +1 -0
  410. package/dist/internal/Env.js +2 -0
  411. package/dist/internal/Env.js.map +1 -0
  412. package/dist/internal/ErrorResponse.d.ts +609 -0
  413. package/dist/internal/ErrorResponse.d.ts.map +1 -0
  414. package/dist/internal/ErrorResponse.js +679 -0
  415. package/dist/internal/ErrorResponse.js.map +1 -0
  416. package/dist/internal/Id.d.ts +10 -0
  417. package/dist/internal/Id.d.ts.map +1 -0
  418. package/dist/internal/Id.js +34 -0
  419. package/dist/internal/Id.js.map +1 -0
  420. package/dist/internal/KeyAuthorization.d.ts +1456 -0
  421. package/dist/internal/KeyAuthorization.d.ts.map +1 -0
  422. package/dist/internal/KeyAuthorization.js +1030 -0
  423. package/dist/internal/KeyAuthorization.js.map +1 -0
  424. package/dist/internal/Limits.d.ts +65 -0
  425. package/dist/internal/Limits.d.ts.map +1 -0
  426. package/dist/internal/Limits.js +35 -0
  427. package/dist/internal/Limits.js.map +1 -0
  428. package/dist/internal/Log.d.ts +49 -0
  429. package/dist/internal/Log.d.ts.map +1 -0
  430. package/dist/internal/Log.js +101 -0
  431. package/dist/internal/Log.js.map +1 -0
  432. package/dist/internal/LogLine.d.ts +33 -0
  433. package/dist/internal/LogLine.d.ts.map +1 -0
  434. package/dist/internal/LogLine.js +56 -0
  435. package/dist/internal/LogLine.js.map +1 -0
  436. package/dist/internal/Migrations.d.ts +19 -0
  437. package/dist/internal/Migrations.d.ts.map +1 -0
  438. package/dist/internal/Migrations.js +57 -0
  439. package/dist/internal/Migrations.js.map +1 -0
  440. package/dist/internal/Owner.d.ts +146 -0
  441. package/dist/internal/Owner.d.ts.map +1 -0
  442. package/dist/internal/Owner.js +65 -0
  443. package/dist/internal/Owner.js.map +1 -0
  444. package/dist/internal/Passkey.d.ts +528 -0
  445. package/dist/internal/Passkey.d.ts.map +1 -0
  446. package/dist/internal/Passkey.js +658 -0
  447. package/dist/internal/Passkey.js.map +1 -0
  448. package/dist/internal/PendingKey.d.ts +49 -0
  449. package/dist/internal/PendingKey.d.ts.map +1 -0
  450. package/dist/internal/PendingKey.js +58 -0
  451. package/dist/internal/PendingKey.js.map +1 -0
  452. package/dist/internal/Privy.d.ts +105 -0
  453. package/dist/internal/Privy.d.ts.map +1 -0
  454. package/dist/internal/Privy.js +224 -0
  455. package/dist/internal/Privy.js.map +1 -0
  456. package/dist/internal/RateLimit.d.ts +190 -0
  457. package/dist/internal/RateLimit.d.ts.map +1 -0
  458. package/dist/internal/RateLimit.js +148 -0
  459. package/dist/internal/RateLimit.js.map +1 -0
  460. package/dist/internal/Realm.d.ts +281 -0
  461. package/dist/internal/Realm.d.ts.map +1 -0
  462. package/dist/internal/Realm.js +477 -0
  463. package/dist/internal/Realm.js.map +1 -0
  464. package/dist/internal/RequestId.d.ts +16 -0
  465. package/dist/internal/RequestId.d.ts.map +1 -0
  466. package/dist/internal/RequestId.js +78 -0
  467. package/dist/internal/RequestId.js.map +1 -0
  468. package/dist/internal/SigningKey.d.ts +115 -0
  469. package/dist/internal/SigningKey.d.ts.map +1 -0
  470. package/dist/internal/SigningKey.js +197 -0
  471. package/dist/internal/SigningKey.js.map +1 -0
  472. package/dist/internal/TestInbox.d.ts +42 -0
  473. package/dist/internal/TestInbox.d.ts.map +1 -0
  474. package/dist/internal/TestInbox.js +20 -0
  475. package/dist/internal/TestInbox.js.map +1 -0
  476. package/dist/internal/Timing.d.ts +51 -0
  477. package/dist/internal/Timing.d.ts.map +1 -0
  478. package/dist/internal/Timing.js +103 -0
  479. package/dist/internal/Timing.js.map +1 -0
  480. package/dist/internal/Validation.d.ts +52 -0
  481. package/dist/internal/Validation.d.ts.map +1 -0
  482. package/dist/internal/Validation.js +22 -0
  483. package/dist/internal/Validation.js.map +1 -0
  484. package/dist/internal/Wallet.d.ts +37 -0
  485. package/dist/internal/Wallet.d.ts.map +1 -0
  486. package/dist/internal/Wallet.js +43 -0
  487. package/dist/internal/Wallet.js.map +1 -0
  488. package/dist/worker.d.ts +12 -0
  489. package/dist/worker.d.ts.map +1 -0
  490. package/dist/worker.js +12 -0
  491. package/dist/worker.js.map +1 -0
  492. package/package.json +82 -0
  493. package/src/Api.ts +151 -0
  494. package/src/App.ts +56 -0
  495. package/src/api/account.ts +311 -0
  496. package/src/api/authenticate.ts +1290 -0
  497. package/src/api/authorize.ts +1030 -0
  498. package/src/api/device.ts +874 -0
  499. package/src/api/health.ts +72 -0
  500. package/src/api/lib/AccountStep.ts +335 -0
  501. package/src/api/lib/Auth.ts +134 -0
  502. package/src/api/lib/Consent.ts +339 -0
  503. package/src/api/lib/Cors.ts +107 -0
  504. package/src/api/lib/Database.ts +10 -0
  505. package/src/api/lib/DeviceRequest.ts +265 -0
  506. package/src/api/lib/FirstAccount.ts +90 -0
  507. package/src/api/lib/KeySigner.ts +393 -0
  508. package/src/api/lib/PasskeyLink.ts +162 -0
  509. package/src/api/lib/Session.ts +34 -0
  510. package/src/api/lib/SignInConsent.ts +316 -0
  511. package/src/api/oauth.ts +1282 -0
  512. package/src/api/provider.ts +441 -0
  513. package/src/app/components/Button.tsx +128 -0
  514. package/src/app/components/CodeInput.tsx +186 -0
  515. package/src/app/components/ErrorMessage.tsx +66 -0
  516. package/src/app/components/Grant.tsx +323 -0
  517. package/src/app/components/Input.tsx +48 -0
  518. package/src/app/components/Tooltip.tsx +45 -0
  519. package/src/app/components/icons/BRLA.png +0 -0
  520. package/src/app/components/icons/BRZ.svg +1 -0
  521. package/src/app/components/icons/CHFAU.png +0 -0
  522. package/src/app/components/icons/DLUSD.png +0 -0
  523. package/src/app/components/icons/EURAU.svg +1 -0
  524. package/src/app/components/icons/EURC.e.svg +1 -0
  525. package/src/app/components/icons/GBPA.svg +4 -0
  526. package/src/app/components/icons/GUSD.svg +1 -0
  527. package/src/app/components/icons/MACH.svg +4 -0
  528. package/src/app/components/icons/OUSD.svg +5 -0
  529. package/src/app/components/icons/PRIME.svg +14 -0
  530. package/src/app/components/icons/SBC.svg +1 -0
  531. package/src/app/components/icons/SEKAU.svg +5 -0
  532. package/src/app/components/icons/USD1.svg +30 -0
  533. package/src/app/components/icons/USDB.svg +11 -0
  534. package/src/app/components/icons/USDC.e.svg +1 -0
  535. package/src/app/components/icons/USDT0.svg +1 -0
  536. package/src/app/components/icons/USDY.svg +16 -0
  537. package/src/app/components/icons/USDe.svg +1 -0
  538. package/src/app/components/icons/YLDS.svg +3 -0
  539. package/src/app/components/icons/alphaUSD.svg +1 -0
  540. package/src/app/components/icons/betaUSD.svg +1 -0
  541. package/src/app/components/icons/cUSD.svg +1 -0
  542. package/src/app/components/icons/cbBTC.svg +1 -0
  543. package/src/app/components/icons/frxUSD.svg +1 -0
  544. package/src/app/components/icons/goUSD.svg +5 -0
  545. package/src/app/components/icons/iUSD.svg +1 -0
  546. package/src/app/components/icons/pathUSD.svg +25 -0
  547. package/src/app/components/icons/rUSD.svg +1 -0
  548. package/src/app/components/icons/reUSD.svg +1 -0
  549. package/src/app/components/icons/sUSDe.svg +1 -0
  550. package/src/app/components/icons/siUSD.svg +1 -0
  551. package/src/app/components/icons/stcUSD.svg +1 -0
  552. package/src/app/components/icons/syrupUSDC.svg +5 -0
  553. package/src/app/components/icons/thetaUSD.svg +1 -0
  554. package/src/app/components/icons/wYLDS.svg +10 -0
  555. package/src/app/components/icons/wsrUSD.svg +1 -0
  556. package/src/app/components/logos/OUSD.dark.svg +17 -0
  557. package/src/app/components/logos/OUSD.light.svg +17 -0
  558. package/src/app/crons/cleanup.ts +42 -0
  559. package/src/app/db/auth.ts +416 -0
  560. package/src/app/db/migrations/0000_better_auth.sql +53 -0
  561. package/src/app/db/migrations/0001_oauth_provider.sql +162 -0
  562. package/src/app/db/migrations/0002_device_code.sql +17 -0
  563. package/src/app/db/migrations/0003_realms.sql +27 -0
  564. package/src/app/db/migrations/0004_default_realm.sql +2 -0
  565. package/src/app/db/migrations/0005_passkeys.sql +30 -0
  566. package/src/app/db/migrations/0006_first_accounts.sql +9 -0
  567. package/src/app/db/migrations/0007_pending_keys.sql +13 -0
  568. package/src/app/db/migrations/0008_secp256k1_owners.sql +18 -0
  569. package/src/app/db/migrations/0009_device_requests.sql +8 -0
  570. package/src/app/db/migrations/0010_device_keys.sql +4 -0
  571. package/src/app/db/migrations/meta/0000_snapshot.json +362 -0
  572. package/src/app/db/migrations/meta/0001_snapshot.json +1487 -0
  573. package/src/app/db/migrations/meta/0002_snapshot.json +1603 -0
  574. package/src/app/db/migrations/meta/0003_snapshot.json +1760 -0
  575. package/src/app/db/migrations/meta/0004_snapshot.json +1760 -0
  576. package/src/app/db/migrations/meta/0005_snapshot.json +1911 -0
  577. package/src/app/db/migrations/meta/0006_snapshot.json +1967 -0
  578. package/src/app/db/migrations/meta/0007_snapshot.json +2047 -0
  579. package/src/app/db/migrations/meta/0008_snapshot.json +2157 -0
  580. package/src/app/db/migrations/meta/0009_snapshot.json +2207 -0
  581. package/src/app/db/migrations/meta/0010_snapshot.json +2231 -0
  582. package/src/app/db/migrations/meta/_journal.json +83 -0
  583. package/src/app/db/schema.ts +218 -0
  584. package/src/app/env.ts +49 -0
  585. package/src/app/lib/Client.ts +82 -0
  586. package/src/app/lib/Loader.ts +24 -0
  587. package/src/app/package.json +8 -0
  588. package/src/app/routeTree.gen.ts +198 -0
  589. package/src/app/router.tsx +48 -0
  590. package/src/app/routes/[_].flows.tsx +3001 -0
  591. package/src/app/routes/__root.tsx +91 -0
  592. package/src/app/routes/authorize.tsx +197 -0
  593. package/src/app/routes/choose-account.tsx +111 -0
  594. package/src/app/routes/deposit.tsx +105 -0
  595. package/src/app/routes/device.tsx +227 -0
  596. package/src/app/routes/index.tsx +115 -0
  597. package/src/app/routes/login.tsx +506 -0
  598. package/src/app/screens/Account.tsx +347 -0
  599. package/src/app/screens/Approval.tsx +276 -0
  600. package/src/app/screens/ChooseAccount.tsx +240 -0
  601. package/src/app/screens/Deposit.tsx +762 -0
  602. package/src/app/screens/DeviceApproval.tsx +480 -0
  603. package/src/app/screens/SignIn.tsx +362 -0
  604. package/src/app/screens/chains/base.svg +3 -0
  605. package/src/app/screens/chains/ethereum.svg +11 -0
  606. package/src/app/screens/chains/solana.svg +4 -0
  607. package/src/app/screens/chains/tempo.svg +4 -0
  608. package/src/app/server.ts +204 -0
  609. package/src/app/vite.config.ts +95 -0
  610. package/src/app/void.config.ts +29 -0
  611. package/src/app/zyzz.config.ts +274 -0
  612. package/src/cli/Admin.ts +73 -0
  613. package/src/cli/Apps.ts +29 -0
  614. package/src/cli/Cli.ts +42 -0
  615. package/src/cli/Project.ts +117 -0
  616. package/src/cli/Realms.ts +50 -0
  617. package/src/cli/Session.ts +239 -0
  618. package/src/cli/User.ts +45 -0
  619. package/src/cli/V1.ts +57 -0
  620. package/src/cli/bin.ts +44 -0
  621. package/src/cli/commands/admin/apps/create.ts +101 -0
  622. package/src/cli/commands/admin/apps/delete.ts +38 -0
  623. package/src/cli/commands/admin/apps/index.ts +15 -0
  624. package/src/cli/commands/admin/apps/list.ts +25 -0
  625. package/src/cli/commands/admin/apps/rotate-secret.ts +47 -0
  626. package/src/cli/commands/admin/apps/update.ts +86 -0
  627. package/src/cli/commands/admin/index.ts +14 -0
  628. package/src/cli/commands/admin/migrate.ts +16 -0
  629. package/src/cli/commands/admin/realms/add.ts +40 -0
  630. package/src/cli/commands/admin/realms/index.ts +14 -0
  631. package/src/cli/commands/admin/realms/list.ts +38 -0
  632. package/src/cli/commands/admin/realms/passkeys/index.ts +15 -0
  633. package/src/cli/commands/admin/realms/passkeys/set.ts +44 -0
  634. package/src/cli/commands/admin/realms/privy/index.ts +14 -0
  635. package/src/cli/commands/admin/realms/privy/set.ts +69 -0
  636. package/src/cli/commands/admin/realms/remove.ts +33 -0
  637. package/src/cli/commands/admin/realms/secp256k1/disable.ts +40 -0
  638. package/src/cli/commands/admin/realms/secp256k1/enable.ts +40 -0
  639. package/src/cli/commands/admin/realms/secp256k1/index.ts +19 -0
  640. package/src/cli/commands/admin/realms/set.ts +46 -0
  641. package/src/cli/commands/admin/rotate-key.ts +47 -0
  642. package/src/cli/commands/init.ts +42 -0
  643. package/src/cli/commands/login.ts +32 -0
  644. package/src/cli/commands/logout.ts +19 -0
  645. package/src/cli/commands/whoami.ts +23 -0
  646. package/src/client/Actions.ts +168 -0
  647. package/src/client/Auth.ts +285 -0
  648. package/src/client/Authorization.ts +34 -0
  649. package/src/client/Decorator.ts +410 -0
  650. package/src/client/Key.ts +140 -0
  651. package/src/client/Pending.ts +46 -0
  652. package/src/client/Permissions.ts +39 -0
  653. package/src/client/Provider.ts +18 -0
  654. package/src/client/Step.ts +24 -0
  655. package/src/client/Storage.ts +29 -0
  656. package/src/client/TempoAccount.ts +42 -0
  657. package/src/client/Tokens.ts +27 -0
  658. package/src/client/User.ts +23 -0
  659. package/src/client/actions/account.ts +57 -0
  660. package/src/client/actions/device.ts +151 -0
  661. package/src/client/actions/email.ts +141 -0
  662. package/src/client/actions/oauth.ts +182 -0
  663. package/src/client/actions/passkey.ts +141 -0
  664. package/src/client/actions/provider.ts +70 -0
  665. package/src/client/actions/realm.ts +36 -0
  666. package/src/client/actions/redirect.ts +408 -0
  667. package/src/client/internal/accessKey.ts +54 -0
  668. package/src/client/internal/account.ts +15 -0
  669. package/src/client/internal/api.ts +224 -0
  670. package/src/client/internal/headless.ts +77 -0
  671. package/src/client/internal/indexedDb.ts +44 -0
  672. package/src/client/internal/request.ts +71 -0
  673. package/src/client/internal/store.ts +20 -0
  674. package/src/client.ts +19 -0
  675. package/src/index.ts +6 -0
  676. package/src/internal/Apps.ts +718 -0
  677. package/src/internal/Auth.ts +203 -0
  678. package/src/internal/Authorize.ts +424 -0
  679. package/src/internal/Balance.ts +168 -0
  680. package/src/internal/BodyLimit.ts +36 -0
  681. package/src/internal/Chain.ts +16 -0
  682. package/src/internal/Device.ts +469 -0
  683. package/src/internal/Env.ts +58 -0
  684. package/src/internal/ErrorResponse.ts +854 -0
  685. package/src/internal/Id.ts +41 -0
  686. package/src/internal/KeyAuthorization.ts +1339 -0
  687. package/src/internal/Limits.ts +39 -0
  688. package/src/internal/Log.ts +178 -0
  689. package/src/internal/LogLine.ts +87 -0
  690. package/src/internal/Logout.ts +336 -0
  691. package/src/internal/Migrations.ts +86 -0
  692. package/src/internal/OpenApi.ts +300 -0
  693. package/src/internal/Owner.ts +211 -0
  694. package/src/internal/Passkey.ts +1052 -0
  695. package/src/internal/PendingKey.ts +104 -0
  696. package/src/internal/Privy.ts +402 -0
  697. package/src/internal/Provider.ts +125 -0
  698. package/src/internal/RateLimit.ts +259 -0
  699. package/src/internal/Realm.ts +768 -0
  700. package/src/internal/RequestId.ts +118 -0
  701. package/src/internal/SignInGrant.ts +168 -0
  702. package/src/internal/SigningKey.ts +286 -0
  703. package/src/internal/TempoAccount.ts +342 -0
  704. package/src/internal/TestInbox.ts +51 -0
  705. package/src/internal/Timing.ts +158 -0
  706. package/src/internal/Validation.ts +52 -0
  707. package/src/internal/Wallet.ts +62 -0
  708. package/src/internal/owners/Passkey.ts +72 -0
  709. package/src/internal/owners/Privy.ts +81 -0
  710. package/src/internal/owners/Secp256k1.ts +143 -0
  711. package/src/types/app.d.ts +19 -0
  712. package/src/worker.ts +11 -0
@@ -0,0 +1,31 @@
1
+ import{r as e}from"./rolldown-runtime-B0Z9INg1.js";import{Zt as t}from"./core-B1HCXUmx.js";import{$t as n,B as r,C as i,D as a,O as o,S as s,T as c,_ as l,a as u,b as d,f,g as p,h as m,i as h,in as g,k as _,l as v,n as y,r as b,s as x,t as S,v as C,x as w,y as T,z as E}from"./schemas-C2lCYmR5.js";import{B as D,C as O,F as k,G as A,H as j,I as M,J as N,K as P,L as F,M as I,N as L,O as R,P as z,Q as ee,R as te,S as ne,U as re,V as ie,W as ae,X as oe,Y as se,Z as ce,_ as B,a as le,d as ue,f as de,j as fe,l as pe,t as me,u as he,v as V,w as ge,x as _e,z as ve}from"./get-id-field-B0x109VU.js";import{a as ye}from"./schema-check-Cf7QOZZD.js";function be(e){return r(h,e)}function xe(e){return E(S,e)}var Se=Object.defineProperty,Ce=(e,t)=>{let n={};for(var r in e)Se(n,r,{get:e[r],enumerable:!0});return t||Se(n,Symbol.toStringTag,{value:`Module`}),n},we=`ba_iat`,Te=`ba_pl`,Ee=`ba_param`;function De(e){let t=new URLSearchParams,n=[...e.entries()].sort(([e,t],[n,r])=>e<n?-1:e>n?1:t<r?-1:+(t>r));for(let[e,r]of n)t.append(e,r);return t}function Oe(e){e.delete(Ee);let t=[...new Set([...e.keys(),Ee])].sort();for(let n of t)e.append(Ee,n)}function ke(e){let t=new URLSearchParams(e).get(we);if(!t)return null;let n=Number(t);return!Number.isFinite(n)||n<=0?null:new Date(n)}var Ae=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(ae(e),j(t,void 0,`key`),this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`expected Hash instance`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),N(r)}update(e){return re(this),this.iHash.update(e),this}digestInto(e){re(this),P(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o,canXOF:s}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.canXOF=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},je=(()=>{let e=((e,t,n)=>new Ae(e,t).update(n).digest());return e.create=(e,t)=>new Ae(e,t),e})(),Me=Uint8Array.of(0),Ne=Uint8Array.of();function Pe(e,t,n,r=32,i){ae(e),A(r,`length`),j(t,void 0,`prk`);let a=e.outputLen;if(t.length<a)throw Error(`"prk" must be at least HashLen octets`);if(r>255*a)throw Error(`Length must be <= 255*HashLen`);let o=Math.ceil(r/a);if(n===void 0?n=Ne:j(n,void 0,`info`),!o)return i&&N(t),new Uint8Array;let s=i&&o===1?t:new Uint8Array(o*a),{iHash:c,oHash:l}=je.create(e,t),u=i?t:new Uint8Array(a),d=o>1?i?.iHash||e.create():void 0;for(let e=0;e<o-1;e++){Me[0]=e+1;let t=c._cloneInto(d);e&&t.update(u),t.update(n).update(Me).digestInto(u),l._cloneInto(d).update(u).digestInto(u),s.set(u,a*e)}if(Me[0]=o,o>1&&c.update(u),c.update(n).update(Me).digestInto(u),l.update(u).digestInto(u),s.set(u,a*(o-1)),c.destroy(),l.destroy(),d?.destroy(),u!==s&&N(u),N(Me),r===s.length)return s;let f=s.slice(0,r);return N(s),f}var Fe=(e,t,n,r,i)=>{ae(e),n===void 0&&(n=new Uint8Array(e.outputLen));let a=je.create(e,n).update(t);return Pe(e,a.digest(),r,i,a)},Ie=e=>e/2**32|0,Le=e=>e>>>0;function Re(e,t,n,r){let i=Ie(n),a=Le(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function ze(e,t,n){return e&t^~e&n}function Be(e,t,n){return e&t^e&n^t&n}var Ve=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=oe(this.buffer)}update(e){re(this),j(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length,a=!1;for(let o=0;o<i;){let s=Math.min(r-this.pos,i-o);if(s===r){let t=oe(e);for(;r<=i-o;o+=r)this.process(t,o);a=!0}else n.set(o===0&&s===i?e:e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){re(this),P(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>r-a&&(this.process(n,0),t.fill(0)),Re(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:oe(e),s=this.outputLen,c=s/4,l=this.get();if(s%4||c>l.length)throw Error(`invalid outputLen`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}},He=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ue=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),We=new Uint32Array(64),Ge=class extends Ve{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let n=0;n<16;n++,t+=4)We[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=We[e-15],n=We[e-2],r=ee(t,7)^ee(t,18)^t>>>3,i=ee(n,17)^ee(n,19)^n>>>10;We[e]=i+We[e-7]+r+We[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=ee(o,6)^ee(o,11)^ee(o,25),u=l+t+ze(o,s,c)+Ue[e]+We[e]|0,d=(ee(n,2)^ee(n,13)^ee(n,22))+Be(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){N(We)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),N(this.buffer)}},Ke=class extends Ge{constructor(){super(32,He)}},qe=se(()=>new Ke,ce(1)),Je=new TextEncoder,Ye=new TextDecoder,Xe=new TextDecoder(`utf-8`,{fatal:!0}),Ze=2**32;function Qe(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function $e(e,t,n){if(t<0||t>=Ze)throw RangeError(`value must be >= 0 and <= ${Ze-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function et(e){let t=Math.floor(e/Ze),n=e%Ze,r=new Uint8Array(8);return $e(r,t,0),$e(r,n,4),r}function tt(e){let t=new Uint8Array(4);return $e(t,e),t}var nt=/[^\x00-\x7f]/;function rt(e){if(typeof e==`string`&&e.length>=128){if(nt.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return Je.encode(e)}let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function it(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?`base64url`:`base64`,omitPadding:t});let n=32768,r=[];for(let t=0;t<e.length;t+=n)r.push(String.fromCharCode.apply(null,e.subarray(t,t+n)));let i=btoa(r.join(``));return t?i.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`):i}function at(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?`base64url`:`base64`});if(t){if(e.includes(`+`)||e.includes(`/`))throw TypeError(`Invalid base64url`);e=e.replace(/-/g,`+`).replace(/_/g,`/`)}let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}async function ot(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}var st=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},ct=class extends st{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},lt=class extends st{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},ut=class extends st{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},H=class extends st{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},dt=class extends st{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},U=class extends st{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},W=class extends st{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},ft=class extends st{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},pt=class extends st{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},mt=class extends st{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},ht=class extends st{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},gt=class extends st{[Symbol.asyncIterator]=async function*(){};static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},_t=class extends st{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},vt=class extends st{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}},yt=`The input to be decoded is not correctly encoded.`;function bt(e){try{return at(typeof e==`string`?e:Ye.decode(e),!0)}catch(e){throw TypeError(yt,{cause:e})}}function G(e){return it(typeof e==`string`?Je.encode(e):e,!0)}function xt(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function St(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function Ct(e){return St(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(St)}function wt(...e){let t=new Set;for(let n of e)if(n)for(let e of Object.keys(n)){if(t.has(e))return!1;t.add(e)}return!0}function Tt(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}function Et(e,t,n){try{return bt(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function Dt(e,t,n){try{return rt(e)}catch{throw new n(`The ${t} is not a valid base64url string`)}}function Ot(e,t,n){let r;try{r=JSON.parse(Xe.decode(bt(e)))}catch{throw new t(n)}if(!St(r))throw new t(n);return r}var kt={__proto__:null,b64:!0},At={__proto__:null};function jt(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function Mt(e,t){let{crit:n}=t??{};if(Array.isArray(n)&&new Set(n).size!==n.length)throw new e(`"crit" (Critical) Header Parameter MUST NOT contain duplicate values`)}function Nt(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return[];if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a=n===void 0?t:{__proto__:null,...n,...t};for(let t of r.crit){if(!(t in a))throw new H(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a[t]&&(!Object.hasOwn(r,t)||r[t]===void 0))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return r.crit}function Pt(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new W(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}function Ft(e,t){let n,r;try{n=JSON.stringify(t),r=JSON.parse(n)}catch(t){throw new e(`JOSE Header is not valid JSON`,{cause:t})}if(!St(r))throw new e(`JOSE Header is not a JSON object`);return[r,n]}var It=e=>e[Symbol.toStringTag],Lt=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let e=n===`sign`||n===`verify`?`sig`:`enc`;if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let r=n===`encrypt`||n===`decrypt`?e.ops?.[n===`encrypt`?0:1]:n;if(r&&!t.key_ops.includes(r))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}};async function Rt(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return t;let o,s;if(St(t)){if(o=$t(t),typeof o.kty!=`string`)throw qt(r,t,i);if(!(i?o.kty===`oct`&&typeof o.k==`string`:o.kty!==`oct`&&(a?o.kty===`AKP`&&typeof o.priv==`string`||typeof o.d==`string`:o.d===void 0&&o.priv===void 0)))throw TypeError(i?`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`:`JSON Web Key for this operation must be a ${a?`private`:`public`} JWK`);if(Lt(e,o,n),o.kty===`oct`)return bt(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!Wt(t))throw qt(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${It(t)} instances must be of type "${e}" for the ${r} algorithm`);if(Ht(t))return t;if(s=t,s.type===`secret`)return s.export()}zt||=new WeakMap;let c=t,l=zt.get(c);if(l?.[r])return l[r];if(l||zt.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=Bt[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:n,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return l[r]=s.toCryptoKey(i,t,e.usages[+!t])}return o??=s.export({format:`jwk`}),o.alg=r,l[r]=await tn(e,o)}var zt,Bt={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`};function Vt(e){if(!Ht(e))throw Error(`CryptoKey instance expected`)}var Ht=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},Ut=e=>e?.[Symbol.toStringTag]===`KeyObject`,Wt=e=>Ht(e)||Ut(e);function Gt(e,t,...n){if(n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Kt=(e,...t)=>Gt(`Key must be `,e,...t);function qt(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(Gt(`Key for the ${e} algorithm must be `,t,...r))}var Jt=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Yt(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Xt(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function Zt(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw Jt(t.name);if(t.hash&&r.hash?.name!==t.hash)throw Jt(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw Jt(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw Jt(t.length,`algorithm.length`);Yt(e,n)}function Qt(e){return{__proto__:null,...e}}function $t(e){let t=Qt(e);if(t.ext!==void 0&&typeof t.ext!=`boolean`)throw TypeError(`"ext" (Extractable) Parameter must be a boolean`);if(t.key_ops!==void 0){let e=t.key_ops,n=Array.isArray(e)?[...e]:void 0;if(!n||n.some(e=>typeof e!=`string`)||new Set(n).size!==n.length)throw TypeError(`"key_ops" (Key Operations) Parameter must be an array of unique strings`);t.key_ops=n}return t}function en(e){if(e!==void 0&&typeof e!=`boolean`)throw TypeError(`"extractable" option must be a boolean`);return e}async function tn(e,t,n){if(!e.kty.includes(t.kty))throw new H(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!!(t.d||t.priv),a={...t,ext:n??t.ext};return a.kty!==`AKP`&&delete a.alg,delete a.use,crypto.subtle.importKey(`jwk`,a,r,a.ext??!i,t.key_ops??e.usages[+!!i])}async function nn(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),Zt(e,t,n),e}var rn=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function an(e,t){let n=e.byteLength<<3;if(n!==t)throw new U(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}var on=e=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function sn(e,t){if(t.length<<3!==e.ivBits)throw new U(`Invalid Initialization Vector length`)}async function cn(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(Kt(t,`Uint8Array`));let r=e.cekBits>>1;return[await crypto.subtle.importKey(`raw`,t.subarray(r>>3),`AES-CBC`,!1,[n]),await crypto.subtle.importKey(`raw`,t.subarray(0,r>>3),{hash:`SHA-${r<<1}`,name:`HMAC`},!1,[`sign`]),r]}async function ln(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function un(e,t,n,r,i){let[a,o,s]=await cn(e,n,`encrypt`),c=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},a,t));return{ciphertext:c,tag:await ln(o,Qe(i,r,c,et(i.length*8)),s),iv:r}}async function dn(e,t){let n={name:`HMAC`,hash:`SHA-256`},r=await crypto.subtle.generateKey(n,!1,[`sign`,`verify`]),i=await crypto.subtle.sign(n,r,e);return crypto.subtle.verify(n,r,i,t)}async function fn(e,t,n,r,i,a){let[o,s,c]=await cn(e,t,`decrypt`),l=await ln(s,Qe(a,r,n,et(a.length*8)),c);try{if(await dn(i,l))return new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},o,n))}catch{}throw new dt}async function pn(e,t,n,r,i){if(!Ht(n)&&!(n instanceof Uint8Array))throw TypeError(Kt(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(r?sn(e,r):r=on(e),n instanceof Uint8Array&&an(n,e.cekBits),e.cbc)return un(e,t,n,r,i);let a=await nn(n,e.subtle,`encrypt`),o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:r,name:`AES-GCM`,tagLength:128},a,t));return{ciphertext:o.subarray(0,-16),tag:o.subarray(-16),iv:r}}async function mn(e,t,n,r,i,a){if(!Ht(t)&&!(t instanceof Uint8Array))throw TypeError(Kt(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new U(`JWE Initialization Vector missing`);if(!i)throw new U(`JWE Authentication Tag missing`);if(!e.cbc&&i.length!==16)throw new U(`Invalid Authentication Tag length`);if(sn(e,r),t instanceof Uint8Array&&an(t,e.cekBits),e.cbc)return fn(e,t,n,r,i,a);let o=await nn(t,e.subtle,`decrypt`);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:r,name:`AES-GCM`,tagLength:128},o,Qe(n,i)))}catch{throw new dt}}function hn(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}var gn=[[`encrypt`,`wrapKey`],[`decrypt`,`unwrapKey`]],_n=[[],[`deriveBits`]],vn=[[],[]];function yn(e){return{kty:[`RSA`],mode:`key-encryption`,subtle:{name:`RSA-OAEP`,hash:`SHA-${e}`},usages:gn,ops:[`wrapKey`,`unwrapKey`]}}function bn(e){return{kty:[`EC`,`OKP`],mode:e,subtle:{name:`ECDH`},resolve:({kty:e,crv:t,asymmetricKeyType:n})=>{if(t===`X25519`||n===`x25519`)return{name:`X25519`};if(e===`OKP`)throw new H(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);return{name:`ECDH`,namedCurve:t}},usages:_n,ops:[void 0,`deriveBits`]}}function xn(e,t=!1){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:t?`AES-GCM`:`AES-KW`,length:e},usages:vn,ops:t?[`encrypt`,`decrypt`]:[`wrapKey`,`unwrapKey`]}}function Sn(){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:`PBKDF2`},usages:vn,ops:[`deriveBits`,`deriveBits`]}}var Cn=hn({dir:{kty:[`oct`],mode:`direct-encryption`,secret:!0,subtle:{name:`AES-GCM`},usages:vn,ops:[`encrypt`,`decrypt`]},"RSA-OAEP":yn(1),"RSA-OAEP-256":yn(256),"RSA-OAEP-384":yn(384),"RSA-OAEP-512":yn(512),"ECDH-ES":bn(`direct-key-agreement`),"ECDH-ES+A128KW":bn(`key-agreement-with-key-wrapping`),"ECDH-ES+A192KW":bn(`key-agreement-with-key-wrapping`),"ECDH-ES+A256KW":bn(`key-agreement-with-key-wrapping`),A128KW:xn(128),A192KW:xn(192),A256KW:xn(256),A128GCMKW:xn(128,!0),A192GCMKW:xn(192,!0),A256GCMKW:xn(256,!0),"PBES2-HS256+A128KW":Sn(),"PBES2-HS384+A192KW":Sn(),"PBES2-HS512+A256KW":Sn()}),wn=[`encrypt`,`decrypt`];function Tn(e,t=!1){return{kty:[`oct`],secret:!0,subtle:{name:t?`AES-CBC`:`AES-GCM`,length:e},usages:vn,ops:wn,cekBits:e,ivBits:t?128:96,cbc:t}}var En=hn({A128GCM:Tn(128),A192GCM:Tn(192),A256GCM:Tn(256),"A128CBC-HS256":Tn(256,!0),"A192CBC-HS384":Tn(384,!0),"A256CBC-HS512":Tn(512,!0)});function Dn(e,t){throw new H(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function On(e){return(typeof e==`string`?Cn[e]:void 0)??Dn(`alg`,`Algorithm`)}function kn(e){return e.mode===`key-wrapping`||e.mode===`key-encryption`||e.mode===`key-agreement-with-key-wrapping`}function An(e){return(typeof e==`string`?En[e]:void 0)??Dn(`enc`,`Encryption Algorithm`)}function jn(e,t){if(e.algorithm.name!==`ECDH`&&e.algorithm.name!==`X25519`)throw TypeError(`CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519`);Yt(e,t)}async function Mn(e,t,n){let r=await nn(t,On(e).subtle,`wrapKey`,!0),i=await crypto.subtle.importKey(`raw`,n,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.wrapKey(`raw`,i,r,`AES-KW`))}async function Nn(e,t,n){let r=await nn(t,On(e).subtle,`unwrapKey`,!0),i=await crypto.subtle.unwrapKey(`raw`,n,r,`AES-KW`,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.exportKey(`raw`,i))}function Pn(e,t,n){Zt(t,On(e).subtle,n),Xt(e,t)}async function Fn(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new U(`PBES2 Salt Input must be 8 or more octets`);if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new U(`PBES2 Count Input must be a positive integer`);let i=Qe(rt(t),Uint8Array.of(0),e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:n,name:`PBKDF2`,salt:i},s=await nn(r,On(t).subtle,`deriveBits`);return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}function In(e){return Qe(tt(e.length),e)}async function Ln(e,t,n){let r=t>>3,i=Math.ceil(r/32),a=new Uint8Array(i*32);for(let t=1;t<=i;t++){let r=await ot(`sha256`,Qe(tt(t),e,n));a.set(r,(t-1)*32)}return a.slice(0,r)}async function Rn(e,t,n,r,i=new Uint8Array,a=new Uint8Array){jn(e),jn(t,`deriveBits`);let o=Qe(In(rt(n)),In(i),In(a),tt(r));return Ln(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,e.algorithm.name===`X25519`?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3)),r,o)}function zn(e){Vt(e);let t=e.algorithm.namedCurve;if(t!==`P-256`&&t!==`P-384`&&t!==`P-521`&&e.algorithm.name!==`X25519`)throw new H(`ECDH with the provided key is not allowed or not supported by your javascript runtime`)}function Bn(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw new U(`JOSE Header "${t}" (Agreement Party${t===`apu`?`U`:`V`}Info) invalid`);return Et(n,t,U)}}function Vn(e,t){if(e!==void 0&&t!==void 0&&e.byteLength===t.byteLength){for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return;throw new U(`JOSE Header "apu" and "apv" values must be distinct`)}}function Hn(e){if(e===void 0)throw new U(`JWE Encrypted Key missing`)}function Un(e){if(e!==void 0)throw new U(`Encountered unexpected JWE Encrypted Key`)}function Wn(e){if(e!==void 0&&e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxPBES2Count must be a positive safe integer or Infinity`)}async function Gn(e,t,n,r,i,a){let{alg:o}=e,s=e.mode;if(s===`direct-encryption`)return Un(r),n;let c=s===`direct-key-agreement`;switch(c?Un(r):Hn(r),e.subtle.name){case`ECDH`:{let{epk:r}=i;if(!St(r)||[`d`,`k`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`priv`].some(e=>Object.hasOwn(r,e)))throw new U(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);zn(n);let a=await tn(e,r),s=Bn(i,`apu`),l=Bn(i,`apv`);Vn(s,l);let u=await Rn(a,n,c?t.alg:o,c?t.cekBits:parseInt(o.slice(-5,-2),10),s,l);if(c)return u;n=u;break}case`RSA-OAEP`:return Vt(n),Pn(o,n,`decrypt`),new Uint8Array(await crypto.subtle.decrypt(`RSA-OAEP`,n,r));case`PBKDF2`:{if(typeof i.p2c!=`number`)throw new U(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);Wn(a);let e=a??1e4;if(i.p2c>e)throw new U(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof i.p2s!=`string`)throw new U(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);n=await Fn(Et(i.p2s,`p2s`,U),o,i.p2c,n);break}case`AES-GCM`:{if(typeof i.iv!=`string`)throw new U(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof i.tag!=`string`)throw new U(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let e=Et(i.iv,`iv`,U),t=Et(i.tag,`tag`,U);if(e.byteLength!==12)throw new U(`Invalid Initialization Vector length`);if(t.byteLength!==16)throw new U(`Invalid Authentication Tag length`);return mn(An(o.slice(0,-2)),n,r,e,t,new Uint8Array)}}return Nn(o.slice(-6),n,r)}async function Kn(e,t,n,r,i,a={}){let{alg:o,mode:s}=e,c=kn(e);if(i!==void 0&&!c)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let l=await Rt(s===`direct-encryption`?t:e,n,`encrypt`);if(s===`direct-encryption`)return[l,void 0,void 0];let u=c?i??rn(t):void 0;u&&an(u,t.cekBits);let d,f;switch(e.subtle.name){case`ECDH`:{zn(l);let{apu:n,apv:i}=a;n!==void 0&&xt(n,`"apu"`),i!==void 0&&xt(i,`"apv"`);let c=n??Bn(r,`apu`),u=i??Bn(r,`apv`);Vn(c,u);let d;d=a.epk===void 0?(await crypto.subtle.generateKey(l.algorithm,!0,[`deriveBits`])).privateKey:await Rt(e,a.epk,`decrypt`);let p=crypto.subtle,m=d;if(!m.extractable){if(typeof p.getPublicKey!=`function`)throw TypeError(`CryptoKey for "epk" must be extractable`);m=await p.getPublicKey(d,[])}let{x:h,y:g,crv:_,kty:v}=await p.exportKey(`jwk`,m),y=s===`direct-key-agreement`,b=await Rn(l,d,y?t.alg:o,y?t.cekBits:parseInt(o.slice(-5,-2),10),c,u),x={x:h,crv:_,kty:v};if(v===`EC`&&(x.y=g),f={epk:x},n!==void 0&&(f.apu=G(n)),i!==void 0&&(f.apv=G(i)),y)return[b,void 0,f];l=b;break}case`RSA-OAEP`:Vt(l),Pn(o,l,`encrypt`),d=new Uint8Array(await crypto.subtle.encrypt(`RSA-OAEP`,l,u));break;case`PBKDF2`:{let{p2c:e=2048,p2s:t=crypto.getRandomValues(new Uint8Array(16))}=a;l=await Fn(t,o,e,l),f={p2c:e,p2s:G(t)};break}case`AES-GCM`:{let e=a.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):a.iv;if(!(e instanceof Uint8Array))throw TypeError(`"iv" must be an instance of Uint8Array`);let t=await pn(An(o.slice(0,-2)),u,l,e,new Uint8Array);d=t.ciphertext,f={iv:G(t.iv),tag:G(t.tag)}}}if(d??=await Mn(o.slice(-6),l,u),!(d instanceof Uint8Array)||!d.byteLength)throw TypeError(`JWE key management algorithm did not produce an Encrypted Key`);return[u,d,f]}function qn(e,t){if(e.zip!==void 0&&e.zip!==`DEF`)throw new H(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(e.zip!==void 0&&!t?.zip)throw new U(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`)}function Jn(e){if(typeof globalThis[e]>`u`)throw new H(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function Yn(e,t,n=1/0){let r=e.writable.getWriter();r.write(t).catch(()=>{}),r.close().catch(()=>{});let i=[],a=0,o=e.readable.getReader();for(;;){let{value:e,done:t}=await o.read();if(t)break;if(i.push(e),a+=e.byteLength,n!==1/0&&a>n)throw new U(`Decompressed plaintext exceeded the configured limit`)}return Qe(...i)}async function Xn(e){return Jn(`CompressionStream`),Yn(new CompressionStream(`deflate-raw`),e)}async function Zn(e,t){return Jn(`DecompressionStream`),Yn(new DecompressionStream(`deflate-raw`),e,t)}function Qn(e){let{protected:t,ciphertext:n,iv:r,tag:i,aad:a}=e,o;return t!==void 0&&(o=Ot(t,U,`JWE Protected Header is invalid`)),[o,Et(n,`ciphertext`,U),r===void 0?void 0:Et(r,`iv`,U),i===void 0?void 0:Et(i,`tag`,U),Dt((t??``)+(a===void 0?``:`.${a}`),`aad`,U)]}function $n(e){return[e&&jt(`keyManagementAlgorithms`,e.keyManagementAlgorithms),e&&jt(`contentEncryptionAlgorithms`,e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function er(e,t,n,r=Qn(e)){let[i,a,o,s,c]=r,{header:l,unprotected:u,aad:d}=e,f;if(l!==void 0||u!==void 0){if(!wt(i,l,u))throw new U(`JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint`);f={...i,...l,...u}}else f=i??{};let[p,m,h,g,_]=t,{encrypted_key:v}=e;Nt(U,At,h,i,f),qn(f,i);let{alg:y,enc:b}=f;if(typeof y!=`string`||!y)throw new U(`missing JWE Algorithm (alg) in JWE Header`);let x=Cn[y];if(v===``&&(!x||!kn(x)))throw new U(`JWE Encrypted Key incorrect type`);let S=x?.mode===`integrated-encryption`;if(!S&&(typeof b!=`string`||!b))throw new U(`missing JWE Encryption Algorithm (enc) in JWE Header`);if(p&&!p.has(y)||!p&&y.startsWith(`PBES2`))throw new ut(`"alg" (Algorithm) Header Parameter value not allowed`);let C;if(S){if(b!==void 0)throw new U(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(o?.byteLength)throw new U(`JWE Initialization Vector must be empty for integrated encryption`);if(s?.byteLength)throw new U(`JWE Authentication Tag must be empty for integrated encryption`)}else{if(m&&!m.has(b))throw new ut(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);C=An(b)}let w;if(v!==void 0)try{w=Et(v,`encrypted_key`,U)}catch(e){if(!x||!kn(x))throw e;w=new Uint8Array}let T=!1;typeof n==`function`&&(n=await n(i,e),T=!0);let E=x??On(y);kn(E)&&w===void 0&&(w=new Uint8Array);let D=await Rt(E.mode===`direct-encryption`?C:E,n,`decrypt`),O;if(E.mode===`integrated-encryption`)O=await E.decrypt(D,w,a,c,i,f);else{let e=C,t;try{t=await Gn(E,e,D,w,f,g),kn(E)&&t instanceof Uint8Array&&t.byteLength<<3!==e.cekBits&&(t=rn(e))}catch(n){if(n instanceof TypeError||n instanceof U||n instanceof H)throw n;t=rn(e)}O=await mn(e,t,a,o,s,c)}if(f.zip===`DEF`){let e=_??25e4;if(e===0)throw new H(`JWE "zip" (Compression Algorithm) Header Parameter is not supported.`);if(e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxDecompressedLength must be 0, a positive safe integer, or Infinity`);O=await Zn(O,e).catch(e=>{throw e instanceof U?e:new U(`Failed to decompress plaintext`,{cause:e})})}return{plaintext:O,...i&&{protectedHeader:i},...d!==void 0&&{additionalAuthenticatedData:Et(d,`aad`,U)},...u&&{sharedUnprotectedHeader:u},...l&&{unprotectedHeader:l},...T&&{key:D}}}async function tr(e,t,n){if(e instanceof Uint8Array&&(e=Ye.decode(e)),typeof e!=`string`)throw new U(`Compact JWE must be a string or Uint8Array`);let{0:r,1:i,2:a,3:o,4:s,length:c}=e.split(`.`);if(c!==5)throw new U(`Invalid Compact JWE`);return er({ciphertext:o,iv:a||void 0,protected:r,tag:s||void 0,encrypted_key:i||void 0},t,n)}function nr(e,t,n){if(!wt(e,t,n))throw new U(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`)}function rr(e,t,n=!1){if(!e[1]&&!e[2]&&!e[3])throw new U(`either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()`);t!==void 0&&(e[8]=t?.crit);let[,r,i,a,o,s,c,l,u]=e;if(o!==void 0&&xt(o,`JWE Additional Authenticated Data`),s!==void 0&&xt(s,`JWE Content Encryption Key`),c!==void 0&&xt(c,`JWE Initialization Vector`),!n&&r!==void 0&&(r=Ft(U,r)[0],e[1]=r),i!==void 0&&(i=Ft(U,i)[0],e[2]=i),!n&&a!==void 0&&(a=Ft(U,a)[0],e[3]=a),l!==void 0&&!St(l))throw TypeError(`JWE Key Management Parameters must be an object`);nr(r,i,a);let d={...r,...i,...a};Mt(U,r),Nt(U,At,u,r,d),qn(d,r);let{alg:f,enc:p}=d;if(typeof f!=`string`||!f)throw new U(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);let m=Cn[f];if(m?.mode===`integrated-encryption`){if(p!==void 0)throw new U(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(s!==void 0)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${f}`);if(c!==void 0)throw TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,m]}if(typeof p!=`string`||!p)throw new U(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);return[d,An(p),m]}async function ir(e,t,n){let[r,i,a]=t,[o,s,c,l,u,d,f,p,,m]=e,h=s,g=c,_=a??On(r.alg),v,y,b;_.mode===`integrated-encryption`?b=await Rt(_,n,`encrypt`):[b,v,y]=await Kn(_,i,n,r,d,p),y&&(m?g=g?{...g,...y}:y:h=h?{...h,...y}:y,nr(h,g,l));let x=h?G(JSON.stringify(h)):``,S=u?.byteLength?G(u):void 0,C=rt(S?`${x}.${S}`:x),w=o;r.zip===`DEF`&&(w=await Xn(w).catch(e=>{throw new U(`Failed to compress plaintext`,{cause:e})}));let T,E,D;_.mode===`integrated-encryption`?[v,T]=await _.encrypt(b,w,C,h,r,p):{ciphertext:T,tag:E,iv:D}=await pn(i,w,b,f,C);let O={ciphertext:G(T)};return D&&(O.iv=G(D)),E&&(O.tag=G(E)),v?.byteLength&&(O.encrypted_key=G(v)),S&&(O.aad=S),h&&(O.protected=x),l&&(O.unprotected=l),g&&(O.header=g),O}async function ar(e,t,n){return ir(e,rr(e,n),t)}function or(e){return[e.protected,e.encrypted_key,e.iv,e.ciphertext,e.tag].join(`.`)}var sr=[[`verify`],[`sign`]];function cr(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:sr}}function lr(e,t){let n={name:t?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e}`};return{kty:[`RSA`],subtle:n,signing:t?{...n,saltLength:t}:n,usages:sr,minRsaBits:2048}}function ur(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:sr}}function dr(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:sr}}function fr(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:sr}}var pr=hn({HS256:cr(256),HS384:cr(384),HS512:cr(512),RS256:lr(256),RS384:lr(384),RS512:lr(512),PS256:lr(256,32),PS384:lr(384,48),PS512:lr(512,64),ES256:ur(`P-256`,256),ES384:ur(`P-384`,384),ES512:ur(`P-521`,512),EdDSA:dr(),Ed25519:dr(),"ML-DSA-44":fr(44),"ML-DSA-65":fr(65),"ML-DSA-87":fr(87)});function mr(e){let t=typeof e==`string`?pr[e]:void 0;if(!t)throw new H(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function hr(e){return[e&&jt(`algorithms`,e.algorithms),e?.crit]}function gr(e){return e===void 0?{}:Ot(e,W,`JWS Protected Header is invalid`)}function _r(e){try{return rt(e)}catch{throw new W(`JWS Compact Serialization payload must use only ASCII characters`)}}async function vr(e,t,n,r,i){let{protected:a,header:o,payload:s}=e,c=i??gr(a);if(!wt(c,o))throw new W(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let l={...c,...o},u=Pt(c,Nt(W,kt,t[1],c,l)),{alg:d}=l;if(typeof d!=`string`||!d)throw new W(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);if(t[0]&&!t[0].has(d))throw new ut(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof s!=`string`)throw new W(`JWS Payload must be a string`)}else if(typeof s!=`string`&&!(s instanceof Uint8Array))throw new W(`JWS Payload must be a string or an Uint8Array instance`);let f=u||typeof s!=`string`?s:r(s),p=!1;typeof n==`function`&&(n=await n(c,e),p=!0);let m=mr(d),h=Qe(a===void 0?new Uint8Array:rt(a),rt(`.`),typeof f==`string`?t[2]??=Dt(f,`payload`,W):f),g=Et(e.signature,`signature`,W),_=await Rt(m,n,`verify`),v=await nn(_,m.subtle,`verify`);m.minRsaBits&&Xt(m.alg,v);let y=!1;try{y=await crypto.subtle.verify(m.signing,v,g,h)}catch{}if(!y)throw new vt;let b={payload:typeof f==`string`?Et(f,`payload`,W):f};return a!==void 0&&(b.protectedHeader=c),o!==void 0&&(b.unprotectedHeader=o),p?[{...b,key:_},u]:[b,u]}async function yr(e,t,n){if(e instanceof Uint8Array&&(e=Ye.decode(e)),typeof e!=`string`)throw new W(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new W(`Invalid Compact JWS`);return vr({payload:i,protected:r,signature:a},t,n,_r)}async function br(e,t,n){let[r]=await yr(e,hr(n),t);return r}var xr=e=>Math.floor(e.getTime()/1e3),Sr={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Cr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,wr=`check_failed`;function Tr(){throw TypeError(`Invalid time period format`)}function Er(e){typeof e!=`string`&&Tr();let t=Cr.exec(e);(!t||t[4]&&t[1])&&Tr();let n=parseFloat(t[2]),r=Math.round(n*Sr[t[3][0].toLowerCase()]);return Number.isFinite(r)||Tr(),t[1]===`-`||t[4]===`ago`?-r:r}function Dr(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function Or(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function kr(e){if(typeof e!=`string`&&(!Array.isArray(e)||Array.from(e).some(e=>typeof e!=`string`)))throw TypeError(`"aud" claim must be a string or an array of strings`)}function Ar(e,t){return typeof e==`number`?Dr(t,e):e instanceof Date?Dr(t,xr(e)):xr(new Date)+Er(e)}var jr=e=>{let t=e.toLowerCase();return e.includes(`/`)?t:`application/${t}`},Mr=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(t=>e.includes(t)):!1;function Nr(e,t,n=!1){let r=e[t];if(r!==void 0||n){if(typeof r!=`number`)throw new ct(`"${t}" claim must be a number`,e,t,`invalid`);return r}}function Pr(e,t){throw new ct(`unexpected "${t}" claim value`,e,t,wr)}function Fr(e,t,n={}){let r;try{r=JSON.parse(Xe.decode(t))}catch{}if(!St(r))throw new ft(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i!==void 0&&(typeof e.typ!=`string`||jr(e.typ)!==jr(i)))throw new ct(`unexpected "typ" JWT header value`,r,`typ`,wr);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!Object.hasOwn(r,e))throw new ct(`missing required "${e}" claim`,r,e,`missing`);o!==void 0&&!(Array.isArray(o)?o:[o]).includes(r.iss)&&Pr(r,`iss`),s!==void 0&&r.sub!==s&&Pr(r,`sub`),c!==void 0&&!Mr(r.aud,typeof c==`string`?[c]:c)&&Pr(r,`aud`);let{clockTolerance:d}=n,f=0;if(typeof d==`string`)f=Er(d);else if(d!==void 0){if(typeof d!=`number`)throw TypeError(`Invalid clockTolerance option type`);f=d}Dr(`clockTolerance option`,f);let{currentDate:p}=n,m=Dr(`currentDate option`,xr(p===void 0?new Date:p)),h=Nr(r,`iat`,l!==void 0),g=Nr(r,`nbf`);if(g!==void 0&&g>m+f)throw new ct(`"nbf" claim timestamp check failed`,r,`nbf`,wr);let _=Nr(r,`exp`);if(_!==void 0&&_<=m-f)throw new lt(`"exp" claim timestamp check failed`,r,`exp`,wr);if(l!==void 0){let e=m-h,t=Dr(`maxTokenAge option`,typeof l==`number`?l:Er(l));if(e-f>t)throw new lt(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,wr);if(e<-f)throw new ct(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,wr)}return r}var Ir;function Lr(e){return Ir.get(e)}function Rr(e){let t=Lr(e);for(let e of[`iat`,`nbf`,`exp`]){let n=t[e];if(typeof n==`number`&&!Number.isFinite(n))throw TypeError(`"${e}" claim must be a finite number`)}return Je.encode(JSON.stringify(t))}function zr(e,t){return Lr(e)[t]}var Br=class{constructor(e={}){if(!St(e))throw TypeError(`JWT Claims Set MUST be an object`);(Ir||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return Or(`iss`,e),Lr(this).iss=e,this}setSubject(e){return Or(`sub`,e),Lr(this).sub=e,this}setAudience(e){return kr(e),Lr(this).aud=e,this}setJti(e){return Or(`jti`,e),Lr(this).jti=e,this}setNotBefore(e){return Lr(this).nbf=Ar(e,`setNotBefore`),this}setExpirationTime(e){return Lr(this).exp=Ar(e,`setExpirationTime`),this}setIssuedAt(e){let t=Lr(this);return t.iat=e===void 0?xr(new Date):typeof e==`string`?Dr(`setIssuedAt`,xr(new Date)+Er(e)):Ar(e,`setIssuedAt`),this}};async function Vr(e,t,n){let[r,i]=await yr(e,hr(n),t);if(!i)throw new ft(`JWTs MUST NOT use unencoded payload`);let a=Fr(r.protectedHeader,r.payload,n);return{...r,payload:a}}async function Hr(e,t,n){let{plaintext:r,...i}=await tr(e,$n(n),t),{protectedHeader:a}=i,o=Fr(a,r,n);for(let e of[`iss`,`sub`,`aud`])if(a[e]!==void 0&&(e===`aud`?JSON.stringify(a.aud)!==JSON.stringify(o.aud):a[e]!==o[e]))throw new ct(`replicated "${e}" claim header parameter mismatch`,o,e,`mismatch`);return{payload:o,...i}}async function Ur(e,t,n){let[r,i,a,o]=e,s=``;if(i!==void 0){let e=Ft(W,i);i=e[0],s=G(e[1])}if(a!==void 0&&(a=Ft(W,a)[0]),!i&&!a)throw new W(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!wt(i,a))throw new W(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let c={...i,...a};Mt(W,i);let l=Pt(i,Nt(W,kt,o,i,c));l||n?.();let{alg:u}=c;if(typeof u!=`string`||!u)throw new W(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let d=mr(u),f=``,p=r,m;if(l){let t=e[4];t?(f=t[0]??=G(r),p=t[1]??=rt(f)):(f=G(r),m=Je.encode(`${s}.${f}`))}m??=Qe(rt(s),rt(`.`),p);let h=await nn(await Rt(d,t,`sign`),d.subtle,`sign`);d.minRsaBits&&Xt(d.alg,h);let g={signature:G(new Uint8Array(await crypto.subtle.sign(d.signing,h,m))),payload:f};return i&&(g.protected=s),a&&(g.header=a),[g,l]}async function Wr(e,t,n,r,i){let[a]=await Ur([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}var Gr=Br,Kr=class extends Gr{#e;setProtectedHeader(e){return Tt(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return Wr(Rr(this),this.#e,t?.crit,e,()=>{throw new ft(`JWTs MUST NOT use unencoded payload`)})}},qr=Br,Jr=class extends qr{#e=[void 0];#t;#n;#r;setProtectedHeader(e){return Tt(this.#e[1],`setProtectedHeader`),this.#e[1]=e,this}setKeyManagementParameters(e){return Tt(this.#e[7],`setKeyManagementParameters`),this.#e[7]=e,this}setContentEncryptionKey(e){return Tt(this.#e[5],`setContentEncryptionKey`),this.#e[5]=e,this}setInitializationVector(e){return Tt(this.#e[6],`setInitializationVector`),this.#e[6]=e,this}replicateIssuerAsHeader(){return this.#t=!0,this}replicateSubjectAsHeader(){return this.#n=!0,this}replicateAudienceAsHeader(){return this.#r=!0,this}async encrypt(e,t){let n=Rr(this);this.#e[1]&&(this.#t||this.#n||this.#r)&&(this.#e[1]={...this.#e[1],iss:this.#t?zr(this,`iss`):void 0,sub:this.#n?zr(this,`sub`):void 0,aud:this.#r?zr(this,`aud`):void 0});let r=[...this.#e];return r[0]=n,or(await ar(r,e,t))}},Yr=`"alg" (Algorithm)`;function Xr(e=`JWK "alg" (Algorithm) Parameter`){throw new H(`Invalid or unsupported ${e} value`)}function Zr(e,t){return(typeof e==`string`?pr[e]??Cn[e]:void 0)??Xr(t)}var Qr=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0},$r=e=>({data:e,pos:0}),ei=e=>{let t=e.data[e.pos++];if(t===void 0)throw Error(`Unexpected end of ASN.1 input`);return t},ti=e=>{let t=ei(e);if(t&128){let n=t&127,r=0;for(let t=0;t<n;t++)r=r<<8|ei(e);return r}return t},ni=(e,t,n)=>{if(ei(e)!==t)throw Error(n)},ri=(e,t)=>{if(t<0||e.pos+t>e.data.length)throw Error(`Unexpected end of ASN.1 input`);let n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},ii=e=>(ni(e,6,`Expected algorithm OID`),ri(e,ti(e)));function ai(e,t){if(ni(e,48,`Invalid ${t===`spki`?`SPKI`:`PKCS#8`} structure`),ti(e),t===`pkcs8`){ni(e,2,`Expected version field`);let t=ti(e);e.pos+=t}ni(e,48,`Expected algorithm identifier`),ti(e)}var oi=e=>{let t=ii(e);if(Qr(t,[43,101,110]))return`X25519`;if(!Qr(t,[42,134,72,206,61,2,1]))throw Error(`Unsupported key algorithm`);ni(e,6,`Expected curve OID`);let n=ri(e,ti(e));if(Qr(n,[42,134,72,206,61,3,1,7]))return`P-256`;if(Qr(n,[43,129,4,0,34]))return`P-384`;if(Qr(n,[43,129,4,0,35]))return`P-521`;throw Error(`Unsupported named curve`)},si=async(e,t,n,r)=>{let i=en(r?.extractable),a=Zr(n,Yr);a.secret&&Xr(`"alg" (Algorithm)`);let o=e===`spki`,s;if(a.resolve)try{let n=$r(t);ai(n,e),s=a.resolve({crv:oi(n)})}catch{throw new H(`Invalid or unsupported key format`)}else s=a.subtle;return crypto.subtle.importKey(e,t,s,i??o,a.usages[+!o])},ci=(e,t)=>at(e.replace(t,``)),li=(e,t,n)=>si(`spki`,ci(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),t,n);async function ui(e){if(Ut(e)){if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`})}if(e instanceof Uint8Array)return{kty:`oct`,k:G(e)};if(!Ht(e))throw TypeError(Kt(e,`CryptoKey`,`KeyObject`,`Uint8Array`));if(!e.extractable)throw TypeError(`non-extractable CryptoKey cannot be exported as a JWK`);let t=await crypto.subtle.exportKey(`jwk`,e);delete t.ext,delete t.key_ops,delete t.use,t.kty!==`AKP`&&delete t.alg;for(let e of Object.keys(t))t[e]===void 0&&delete t[e];return t}var di=(e,t)=>{if(typeof e!=`string`||!e)throw new pt(`${t} missing or invalid`)};async function fi(e,t){let n;if(St(e)){if(n=Qt(e),typeof n.kty!=`string`)throw TypeError(Kt(e,`CryptoKey`,`KeyObject`,`JSON Web Key`))}else if(Wt(e))n=Qt(await ui(e));else throw TypeError(Kt(e,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t??=`sha256`,t!==`sha256`&&t!==`sha384`&&t!==`sha512`)throw TypeError(`digestAlgorithm must one of "sha256", "sha384", or "sha512"`);let r;switch(n.kty){case`AKP`:di(n.alg,`"alg" (Algorithm) Parameter`),di(n.pub,`"pub" (Public key) Parameter`),r={alg:n.alg,kty:n.kty,pub:n.pub};break;case`EC`:di(n.crv,`"crv" (Curve) Parameter`),di(n.x,`"x" (X Coordinate) Parameter`),di(n.y,`"y" (Y Coordinate) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case`OKP`:di(n.crv,`"crv" (Subtype of Key Pair) Parameter`),di(n.x,`"x" (Public Key) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x};break;case`RSA`:di(n.e,`"e" (Exponent) Parameter`),di(n.n,`"n" (Modulus) Parameter`),r={e:n.e,kty:n.kty,n:n.n};break;case`oct`:if(typeof n.k!=`string`)throw new pt(`"k" (Key Value) Parameter missing or invalid`);r={k:n.k,kty:n.kty};break;default:throw new H(`"kty" (Key Type) Parameter missing or unsupported`)}let i=rt(JSON.stringify(r));return G(await ot(t,i))}function pi(e,t,n,r){let{kty:i,key_ops:a,ext:o,kid:s,alg:c,use:l,crv:u}=e;return(o===void 0||typeof o==`boolean`)&&(a===void 0||Array.isArray(a)&&a.every((e,t)=>typeof e==`string`&&a.indexOf(e)===t)&&a.includes(`verify`))&&t.kty.includes(i)&&(r===void 0||typeof r==`string`&&r===s)&&(c===void 0?i!==`AKP`:n===c)&&(l===void 0||l===`sig`)&&(!t.crv||u===t.crv)}async function mi(e,t,n){let r=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(r[i]===void 0){let e=tn(n,t,!0).then(e=>{if(e.type!==`public`)throw new mt(`JSON Web Key Set members must be public keys`);return r[i]=e,e}).catch(t=>{throw r[i]===e&&delete r[i],t});r[i]=e}return r[i]}function hi(e){let t;try{t=structuredClone(e)}catch{}if(!Ct(t))throw new mt(`JSON Web Key Set malformed`);let n=t.keys.map(e=>{let t=Qt(e);return Array.isArray(t.key_ops)&&(t.key_ops=[...t.key_ops]),t}),r=new WeakMap;return Object.defineProperty(async(e,i)=>{let{alg:a,kid:o}={...e,...i?.header},s=typeof a==`string`?pr[a]:void 0;if(!s||s.secret)throw new H(`Unsupported "alg" value for a JSON Web Key Set`);let c=t.keys.filter((e,t)=>pi(n[t],s,a,o)),{0:l,length:u}=c;if(!u)throw new ht;if(u!==1){let e=new gt;throw e[Symbol.asyncIterator]=async function*(){for(let e of c)try{yield await mi(r,e,s)}catch{}},e}return mi(r,l,s)},"jwks",{value:()=>structuredClone(t)})}async function gi(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PUBLIC KEY-----`)!==0)throw TypeError(`"spki" must be SPKI formatted string`);return li(e,t,n)}async function _i(e,t,n){if(!St(e))throw TypeError(`JWK must be an object`);let r=$t(e),i=en(n?.extractable),{alg:a}=r;if(t??=a,r.kty!==`oct`&&!t)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);switch(r.kty){case`oct`:if(typeof r.k!=`string`)throw TypeError(`missing "k" (Key Value) Parameter value`);return bt(r.k);case`AKP`:if(typeof a!=`string`||!a)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==a)throw TypeError(`JWK alg and alg option value mismatch`);return tn(Zr(t),r,i);case`RSA`:case`EC`:case`OKP`:return tn(Zr(t),r,i);default:throw new H(`Unsupported "kty" (Key Type) Parameter value`)}}function vi(e){let t;if(typeof e==`string`){let n=e.split(`.`);(n.length===3||n.length===5)&&([t]=n)}else if(typeof e==`object`&&e){if(`protected`in e)t=e.protected;else throw TypeError(`Token does not contain a Protected Header`)}let n=`Invalid Token or Protected Header formatting`;if(typeof t!=`string`||!t)throw TypeError(n);return Ot(t,TypeError,n)}function yi(e){if(typeof e!=`string`)throw new ft(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new ft(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new ft(`Invalid JWT`);if(!t)throw new ft(`JWTs must contain a payload`);let r;try{r=bt(t)}catch{throw new ft(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(Xe.decode(r))}catch{throw new ft(`Failed to parse the decoded payload as JSON`)}if(!St(i))throw new ft(`Invalid JWT Claims Set`);return i}function bi(e){let t=e?.modulusLength??2048;if(typeof t!=`number`||!Number.isInteger(t)||t<2048)throw new H(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return t}async function xi(e,t){let n=en(t?.extractable),r=Zr(e,Yr);r.secret&&Xr(`"alg" (Algorithm)`);let i;if(r.resolve){let e=t?.crv??`P-256`;if(![`P-256`,`P-384`,`P-521`,`X25519`].includes(e))throw new H(`Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519`);i=r.resolve({crv:e})}else{if(r.crv!==void 0&&t?.crv!==void 0&&t.crv!==r.crv)throw new H(`Invalid or unsupported crv option provided, the only supported value for ${e} is ${r.crv}`);i=r.kty[0]===`RSA`?{...r.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:bi(t)}:r.subtle}return crypto.subtle.generateKey(i,n??!1,[...r.usages[1],...r.usages[0]])}async function Si(e,t,n=3600){return await new Kr(e).setProtectedHeader({alg:`HS256`}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+n).sign(new TextEncoder().encode(t))}async function Ci(e,t){try{return(await Vr(e,new TextEncoder().encode(t))).payload}catch{return null}}var wi=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),Ti=()=>Date.now()/1e3|0,Ei=`dir`,Di=`A256CBC-HS512`;function Oi(e,t){return Fe(qe,new TextEncoder().encode(e),new TextEncoder().encode(t),wi,64)}function ki(e){if(typeof e==`string`)return e;let t=e.keys.get(e.currentVersion);if(!t)throw Error(`Secret version ${e.currentVersion} not found in keys`);return t}function Ai(e){if(typeof e==`string`)return[{version:0,value:e}];let t=[];for(let[n,r]of e.keys)t.push({version:n,value:r});return e.legacySecret&&!t.some(t=>t.value===e.legacySecret)&&t.push({version:-1,value:e.legacySecret}),t}async function ji(e,t,n,r=3600){let i=Oi(ki(t),n),a=await fi({kty:`oct`,k:G(i)},`sha256`);return await new Jr(e).setProtectedHeader({alg:Ei,enc:Di,kid:a}).setIssuedAt().setExpirationTime(Ti()+r).setJti(crypto.randomUUID()).encrypt(i)}var Mi={clockTolerance:15,keyManagementAlgorithms:[Ei],contentEncryptionAlgorithms:[Di,`A256GCM`]};async function Ni(e,t,n){if(!e)return null;let r=!1;try{r=vi(e).kid!==void 0}catch{return null}try{let r=Ai(t),{payload:i}=await Hr(e,async e=>{let t=e.kid;if(t!==void 0){for(let e of r){let r=Oi(e.value,n);if(t===await fi({kty:`oct`,k:G(r)},`sha256`))return r}throw Error(`no matching decryption secret`)}return r.length,Oi(r[0].value,n)},Mi);return i}catch{if(r)return null;let i=Ai(t);if(i.length<=1)return null;for(let t=1;t<i.length;t++)try{let r=i[t],{payload:a}=await Hr(e,Oi(r.value,n),Mi);return a}catch{continue}return null}}function Pi(e,t){typeof e==`string`&&(e=new TextEncoder().encode(e)),typeof t==`string`&&(t=new TextEncoder().encode(t));let n=new Uint8Array(e),r=new Uint8Array(t),i=n.length^r.length,a=Math.max(n.length,r.length);for(let e=0;e<a;e++)i|=(e<n.length?n[e]:0)^(e<r.length?r[e]:0);return i===0}var Fi=ie(`a-z`,`0-9`,`A-Z`,`-_`);function Ii(){let e=typeof globalThis<`u`&&globalThis.crypto;if(e&&typeof e.subtle==`object`&&e.subtle!=null)return e.subtle;throw Error(`crypto.subtle must be defined`)}function Li(e,t){return{digest:async n=>{let r=D(n),i=await Ii().digest(e,r);return t===`hex`?Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``):t===`base64`||t===`base64url`||t===`base64urlnopad`?t.includes(`url`)?ve.encode(i,{padding:t!==`base64urlnopad`}):te.encode(i):i}}}function Ri(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}var zi=e=>e?`"${e}" `:``;function Bi(e,t=``){if(typeof e!=`boolean`)throw TypeError(zi(t)+`expected boolean, got type=`+typeof e);return e}function Vi(e,t=``){if(typeof e!=`number`)throw TypeError(zi(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(zi(t)+`expected integer >= 0, got `+e);return e}function K(e,t,n=``){if(Ri(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Vi(t,`length`);let r=Ri(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=zi(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}var Hi=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(t===`object`?`expected valid options object`:`"${t}" expected object, got type=${typeof e}`)};function Ui(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function Wi(e,t){K(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function Gi(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Ki(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function qi(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var Ji=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Yi(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Xi(e){for(let t=0;t<e.length;t++)e[t]=Yi(e[t]);return e}var Zi=Ji?e=>e:Xi,Qi=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,$i=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function ea(e){if(K(e),Qi)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=$i[e[n]];return t}function ta(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function na(e){if(typeof e!=`string`)throw TypeError(`hex string expected, got `+typeof e);if(Qi)try{return Uint8Array.fromHex(e)}catch(e){throw e instanceof SyntaxError?RangeError(e.message):e}let t=e.length,n=t/2;if(t%2)throw RangeError(`hex string expected, got unpadded hex of length `+t);let r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){let n=ta(e.charCodeAt(i)),a=ta(e.charCodeAt(i+1));if(n===void 0||a===void 0){let t=e[i]+e[i+1];throw RangeError(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function ra(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function ia(e,t){return!e.byteLength||!t.byteLength?!1:e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function aa(e,t){if(ia(e,t)&&e.byteOffset<t.byteOffset)throw Error(`complex overlap of input and output is not supported`)}function oa(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];K(r),t+=r.length}let n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}function sa(e,t){return Hi(e,`defaults`),Hi(t,`opts`),Object.assign(e,t)}function ca(e,t){if(e=K(e),t=K(t),e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function la(e,t,n){let r=t,i=n||(()=>[]),a=(e,t)=>r(t,...i(e)).update(e).digest(),o=r(new Uint8Array(e),...i(new Uint8Array));return a.outputLen=o.outputLen,a.blockLen=o.blockLen,a.create=(e,...t)=>r(e,...t),a}var ua=(e,t)=>{function n(n,...r){if(K(n,void 0,`key`),e.nonceLength!==void 0){let t=r[0];K(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength,a=e.nonceLength===void 0?0:1;if(!e.withAAD){for(let e=a;e<r.length;e++)if(Ri(r[e]))throw Error(`AAD not supported`)}e.withAAD&&r[a]!==void 0&&K(r[a],void 0,`AAD`);let o=t(n,...r),s=(e,t)=>{if(t!==void 0){if(e!==2)throw Error(`cipher output not supported`);K(t,void 0,`output`)}},c=!1;return{encrypt(e,t){if(c)throw Error(`cannot encrypt() twice with same key + nonce`);return c=!0,K(e,void 0,`data`),s(o.encrypt.length,t),o.encrypt(e,t)},decrypt(e,t){if(K(e,void 0,`data`),i&&e.length<i)throw Error(`"ciphertext" expected length >= tagLength=`+i);return s(o.decrypt.length,t),o.decrypt(e,t)}}}return Object.assign(n,e),n};function da(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(K(t,e,`output`),n&&!pa(t))throw Error(`invalid output, must be aligned`);return t}function fa(e,t,n){Vi(e),Vi(t),Bi(n);let r=new Uint8Array(16),i=qi(r);return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}function pa(e){return e.byteOffset%4==0}function ma(e){return Uint8Array.from(K(e))}function ha(e=32){Vi(e,`bytesLength`);let t=typeof globalThis==`object`?globalThis.crypto:null;if(typeof t?.getRandomValues!=`function`)throw Error(`crypto.getRandomValues must be defined`);if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}function ga(e,t=ha){if(typeof e!=`function`)throw TypeError(`"fn" expected cipher constructor, got type=`+typeof e);if(typeof t!=`function`)throw TypeError(`"randomBytes_" expected function, got type=`+typeof t);let{nonceLength:n}=e;Vi(n,`fn.nonceLength`);let r=(e,t,n)=>{let r=oa(e,t);return ia(n,t)||t.fill(0),r},i=((i,...a)=>({encrypt(o){K(o,void 0,`data`);let s=t(n),c=e(i,s,...a).encrypt(o);return c instanceof Promise?c.then(e=>r(s,e,o)):r(s,c,o)},decrypt(t){K(t,void 0,`data`);let r=t.subarray(0,n),o=t.subarray(n);return e(i,r,...a).decrypt(o)}}));return`blockSize`in e&&(i.blockSize=e.blockSize),`tagLength`in e&&(i.tagLength=e.tagLength),`withAAD`in e&&(i.withAAD=e.withAAD),i}var _a=e=>Uint8Array.from(e.split(``),e=>e.charCodeAt(0)),va=Zi(Gi(_a(`expand 16-byte k`))),ya=Zi(Gi(_a(`expand 32-byte k`)));function q(e,t){return e<<t|e>>>32-t}var ba=64,xa=16,Sa=2**32-1,Ca=Uint32Array.of();function wa(e,t,n,r,i,a,o,s){let c=i.length,l=new Uint8Array(ba),u=Gi(l),d=Ji&&pa(i)&&pa(a),f=d?Gi(i):Ca,p=d?Gi(a):Ca;if(Ji)for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=Sa)throw Error(`arx: counter overflow`);let h=Math.min(ba,c-m);if(d&&h===ba){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<xa;t++)n=e+t,p[n]=f[n]^u[t];m+=ba}else{for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}else for(let d=0;d<c;o++){if(e(t,n,r,u,o,s),Zi(u),o>=Sa)throw Error(`arx: counter overflow`);let f=Math.min(ba,c-d);for(let e=0,t;e<f;e++)t=d+e,a[t]=i[t]^l[e];d+=f}}function Ta(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=sa({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return Vi(i),Vi(o),Bi(a),Bi(n),(t,s,c,l,u=0)=>{K(t,void 0,`key`),K(s,void 0,`nonce`),K(c,void 0,`data`);let d=c.length,f=l!==void 0;if(l=da(d,l,!1),f&&aa(c,l),Vi(u),u<0||u>=Sa)throw Error(`arx: counter overflow`);let p=[],m=t.length,h,g;if(m===32)p.push(h=ma(t)),g=ya;else if(m===16&&n)h=new Uint8Array(32),h.set(t),h.set(t,16),g=va,p.push(h);else throw K(t,32,`arx key`),Error(`invalid key size`);(!Ji||!pa(s))&&p.push(s=ma(s));let _=Gi(h);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);let e=s.subarray(0,16);if(Ji)r(g,_,Gi(e),_);else{let t=Zi(Uint32Array.from(g));r(t,_,Gi(e),_),Ki(t),Zi(_)}s=s.subarray(16)}else Ji||Zi(_);let v=16-i;if(v!==s.length)throw Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let e=new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,p.push(s)}let y=Zi(Gi(s));try{return wa(e,g,_,y,c,l,u,o),l}finally{Ki(...p)}}}function J(e,t){return e[t++]&255|(e[t++]&255)<<8}var Ea=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=ma(K(e,32,`key`));let t=J(e,0),n=J(e,2),r=J(e,4),i=J(e,6),a=J(e,8),o=J(e,10),s=J(e,12),c=J(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=J(e,16+2*t)}process(e,t,n=!1){let r=n?0:2048,{h:i,r:a}=this,o=a[0],s=a[1],c=a[2],l=a[3],u=a[4],d=a[5],f=a[6],p=a[7],m=a[8],h=a[9],g=J(e,t+0),_=J(e,t+2),v=J(e,t+4),y=J(e,t+6),b=J(e,t+8),x=J(e,t+10),S=J(e,t+12),C=J(e,t+14),w=i[0]+(g&8191),T=i[1]+((g>>>13|_<<3)&8191),E=i[2]+((_>>>10|v<<6)&8191),D=i[3]+((v>>>7|y<<9)&8191),O=i[4]+((y>>>4|b<<12)&8191),k=i[5]+(b>>>1&8191),A=i[6]+((b>>>14|x<<2)&8191),j=i[7]+((x>>>11|S<<5)&8191),M=i[8]+((S>>>8|C<<8)&8191),N=i[9]+(C>>>5|r),P=0,F=P+w*o+5*h*T+5*m*E+5*p*D+5*f*O;P=F>>>13,F&=8191,F+=5*d*k+5*u*A+5*l*j+5*c*M+5*s*N,P+=F>>>13,F&=8191;let I=P+w*s+T*o+5*h*E+5*m*D+5*p*O;P=I>>>13,I&=8191,I+=5*f*k+5*d*A+5*u*j+5*l*M+5*c*N,P+=I>>>13,I&=8191;let L=P+w*c+T*s+E*o+5*h*D+5*m*O;P=L>>>13,L&=8191,L+=5*p*k+5*f*A+5*d*j+5*u*M+5*l*N,P+=L>>>13,L&=8191;let R=P+w*l+T*c+E*s+D*o+5*h*O;P=R>>>13,R&=8191,R+=5*m*k+5*p*A+5*f*j+5*d*M+5*u*N,P+=R>>>13,R&=8191;let z=P+w*u+T*l+E*c+D*s+O*o;P=z>>>13,z&=8191,z+=5*h*k+5*m*A+5*p*j+5*f*M+5*d*N,P+=z>>>13,z&=8191;let ee=P+w*d+T*u+E*l+D*c+O*s;P=ee>>>13,ee&=8191,ee+=k*o+5*h*A+5*m*j+5*p*M+5*f*N,P+=ee>>>13,ee&=8191;let te=P+w*f+T*d+E*u+D*l+O*c;P=te>>>13,te&=8191,te+=k*s+A*o+5*h*j+5*m*M+5*p*N,P+=te>>>13,te&=8191;let ne=P+w*p+T*f+E*d+D*u+O*l;P=ne>>>13,ne&=8191,ne+=k*c+A*s+j*o+5*h*M+5*m*N,P+=ne>>>13,ne&=8191;let re=P+w*m+T*p+E*f+D*d+O*u;P=re>>>13,re&=8191,re+=k*l+A*c+j*s+M*o+5*h*N,P+=re>>>13,re&=8191;let ie=P+w*h+T*m+E*p+D*f+O*d;P=ie>>>13,ie&=8191,ie+=k*u+A*l+j*c+M*s+N*o,P+=ie>>>13,ie&=8191,P=(P<<2)+P|0,P=P+F|0,F=P&8191,P>>>=13,I+=P,i[0]=F,i[1]=I,i[2]=L,i[3]=R,i[4]=z,i[5]=ee,i[6]=te,i[7]=ne,i[8]=re,i[9]=ie}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let i=(r^1)-1;for(let e=0;e<10;e++)n[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|n[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let a=e[0]+t[0];e[0]=a&65535;for(let n=1;n<8;n++)a=(e[n]+t[n]|0)+(a>>>16)|0,e[n]=a&65535;Ki(n)}update(e){Ui(this),K(e),e=ma(e);let{buffer:t,blockLen:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(n-this.pos,r-i);if(a===n)for(;n<=r-i;i+=n)this.process(e,i);else t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,Ki(this.h,this.r,this.buffer,this.pad)}digestInto(e){Ui(this),Wi(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=n[t]>>>0,e[i++]=n[t]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}},Da=la(32,e=>new Ea(e));function Oa(e,t,n,r,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],u=t[0],d=t[1],f=t[2],p=t[3],m=t[4],h=t[5],g=t[6],_=t[7],v=i,y=n[0],b=n[1],x=n[2],S=o,C=s,w=c,T=l,E=u,D=d,O=f,k=p,A=m,j=h,M=g,N=_,P=v,F=y,I=b,L=x;for(let e=0;e<a;e+=2)S=S+E|0,P=q(P^S,16),A=A+P|0,E=q(E^A,12),S=S+E|0,P=q(P^S,8),A=A+P|0,E=q(E^A,7),C=C+D|0,F=q(F^C,16),j=j+F|0,D=q(D^j,12),C=C+D|0,F=q(F^C,8),j=j+F|0,D=q(D^j,7),w=w+O|0,I=q(I^w,16),M=M+I|0,O=q(O^M,12),w=w+O|0,I=q(I^w,8),M=M+I|0,O=q(O^M,7),T=T+k|0,L=q(L^T,16),N=N+L|0,k=q(k^N,12),T=T+k|0,L=q(L^T,8),N=N+L|0,k=q(k^N,7),S=S+D|0,L=q(L^S,16),M=M+L|0,D=q(D^M,12),S=S+D|0,L=q(L^S,8),M=M+L|0,D=q(D^M,7),C=C+O|0,P=q(P^C,16),N=N+P|0,O=q(O^N,12),C=C+O|0,P=q(P^C,8),N=N+P|0,O=q(O^N,7),w=w+k|0,F=q(F^w,16),A=A+F|0,k=q(k^A,12),w=w+k|0,F=q(F^w,8),A=A+F|0,k=q(k^A,7),T=T+E|0,I=q(I^T,16),j=j+I|0,E=q(E^j,12),T=T+E|0,I=q(I^T,8),j=j+I|0,E=q(E^j,7);let R=0;r[R++]=o+S|0,r[R++]=s+C|0,r[R++]=c+w|0,r[R++]=l+T|0,r[R++]=u+E|0,r[R++]=d+D|0,r[R++]=f+O|0,r[R++]=p+k|0,r[R++]=m+A|0,r[R++]=h+j|0,r[R++]=g+M|0,r[R++]=_+N|0,r[R++]=v+P|0,r[R++]=y+F|0,r[R++]=b+I|0,r[R++]=x+L|0}function ka(e,t,n,r){let i=Ji?e:Zi(e.slice(0,4)),a=Ji?t:Zi(t.slice(0,8)),o=Ji?n:Zi(n.slice(0,4)),s=new Uint32Array(16);Oa(i,a,o.subarray(1),s,o[0]);let c=0;r[c++]=s[0]-i[0]|0,r[c++]=s[1]-i[1]|0,r[c++]=s[2]-i[2]|0,r[c++]=s[3]-i[3]|0,r[c++]=s[12]-o[0]|0,r[c++]=s[13]-o[1]|0,r[c++]=s[14]-o[2]|0,r[c++]=s[15]-o[3]|0,Zi(r),Ji||Ki(i,a,o),Ki(s)}var Aa=Ta(Oa,{counterRight:!1,counterLength:8,extendNonceFn:ka,allowShortKeys:!1}),ja=new Uint8Array(16),Ma=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(ja.subarray(n))},Na=new Uint8Array(32);function Pa(e,t,n,r,i){i!==void 0&&K(i,void 0,`AAD`);let a=e(t,n,Na),o=fa(r.length,i?i.length:0,!0),s=Da.create(a);i&&Ma(s,i),Ma(s,r),s.update(o);let c=s.digest();return Ki(a,o),c}var Fa=ua({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},(e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=da(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=Pa(e,t,n,s,r);return a.set(c,o),Ki(c),a},decrypt(i,a){a=da(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=Pa(e,t,n,o,r);if(!ca(s,c))throw Ki(c),Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),Ki(c),a}}))(Aa)),Ia={name:`HMAC`,hash:`SHA-256`},La=`$ba$`;function Ra(e){if(!e.startsWith(La))return null;let t=e.indexOf(`$`,4);if(t===-1)return null;let n=parseInt(e.slice(4,t),10);return!Number.isInteger(n)||n<0?null:{version:n,ciphertext:e.slice(t+1)}}function za(e,t){return`${La}${e}$${t}`}async function Ba(e,t){let n=await Li(`SHA-256`).digest(e),r=ra(t);return ea(ga(Fa)(new Uint8Array(n)).encrypt(r))}async function Va(e,t){let n=await Li(`SHA-256`).digest(e),r=na(t),i=ga(Fa)(new Uint8Array(n));return new TextDecoder().decode(i.decrypt(r))}var Ha=async({key:e,data:t})=>{if(typeof e==`string`)return Ba(e,t);let n=e.keys.get(e.currentVersion);if(!n)throw Error(`Secret version ${e.currentVersion} not found in keys`);let r=await Ba(n,t);return za(e.currentVersion,r)},Ua=async({key:e,data:t})=>{if(typeof e==`string`)return Va(e,t);let n=Ra(t);if(n){let t=e.keys.get(n.version);if(!t)throw Error(`Secret version ${n.version} not found in keys (key may have been retired)`);return Va(t,n.ciphertext)}if(e.legacySecret)return Va(e.legacySecret,t);throw Error(`Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.`)},Wa=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await Ii().importKey(`raw`,t,Ia,!1,[`sign`,`verify`])},Ga=async(e,t)=>{let n=await Wa(t),r=await Ii().sign(Ia.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))},Ka={name:`HMAC`,hash:`SHA-256`},qa=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await Ii().importKey(`raw`,t,Ka,!1,[`sign`,`verify`])},Ja=async(e,t,n)=>{try{let r=atob(e),i=new Uint8Array(r.length);for(let e=0,t=r.length;e<t;e++)i[e]=r.charCodeAt(e);return await Ii().verify(Ka,n,i,new TextEncoder().encode(t))}catch{return!1}},Ya=async(e,t)=>{let n=await qa(t),r=await Ii().sign(Ka.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))},Xa=async(e,t)=>{let n=await Ya(e,t);return e=`${e}.${n}`,e=encodeURIComponent(e),e},Za=/^application\/([a-z0-9.+-]*\+)?json/i;async function Qa(e,t){let n=e.headers.get(`content-type`)||``,r=n.toLowerCase();if(e.body){if(t&&t.length>0&&!t.some(e=>{let t=r.split(`;`)[0].trim(),n=e.toLowerCase().trim();return t===n||t.includes(n)}))throw r?new z(415,{message:`Content-Type "${n}" is not allowed. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`}):new z(415,{message:`Content-Type is required. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`});if(Za.test(r))try{return await e.json()}catch(e){throw e instanceof SyntaxError?new z(400,{message:`Invalid JSON in request body`,code:`BAD_REQUEST`}):e}if(r.includes(`application/x-www-form-urlencoded`)){let t=await e.formData(),n={};return t.forEach((e,t)=>{n[t]=e.toString()}),n}if(r.includes(`multipart/form-data`)){let t=await e.formData(),n={};return t.forEach((e,t)=>{n[t]=e}),n}return r.includes(`text/plain`)?await e.text():r.includes(`application/octet-stream`)?await e.arrayBuffer():r.includes(`application/pdf`)||r.includes(`image/`)||r.includes(`video/`)?await e.blob():r.includes(`application/stream`)||e.body instanceof ReadableStream?e.body:await e.text()}}function $a(e){return e instanceof z||e?.name===`APIError`}function eo(e){try{return e.includes(`%`)?decodeURIComponent(e):e}catch{return e}}async function to(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function no(e){return e instanceof Request||Object.prototype.toString.call(e)===`[object Request]`}var ro={secure:`__Secure-`,host:`__Host-`},io=(e,t)=>{if(!t)return e;if(t===`secure`||t===`host`)return ro[t]+e};function ao(e){if(typeof e!=`string`)throw TypeError(`argument str must be a string`);let t=new Map,n=0;for(;n<e.length;){let r=e.indexOf(`=`,n);if(r===-1)break;let i=e.indexOf(`;`,n);if(i===-1)i=e.length;else if(i<r){n=e.lastIndexOf(`;`,r-1)+1;continue}let a=e.slice(n,r).trim();if(!t.has(a)){let n=e.slice(r+1,i).trim();n.codePointAt(0)===34&&(n=n.slice(1,-1)),t.set(a,eo(n))}n=i+1}return t}function oo(e,t,n={}){let r=io(e,n.prefix)??e,i={...n},a=r.toLowerCase();return a.startsWith(`__host-`)?(i.secure=!0,i.path=`/`,i.domain=void 0):a.startsWith(`__secure-`)&&(i.secure=!0),(i.partitioned===!0||i.sameSite?.toLowerCase()===`none`)&&(i.secure=!0),{name:r,value:t,options:i}}function so({name:e,value:t,options:n}){let r=`${e}=${t}`;if(typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${Math.floor(n.maxAge)}`}if(n.domain&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}return n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.partitioned&&(r+=`; Partitioned`),r}var co=(e,t,n)=>(t=encodeURIComponent(t),so(oo(e,t,n))),lo=async(e,t,n,r)=>(t=await Xa(t,n),so(oo(e,t,r)));async function uo(e,t={}){let n={body:t.body,query:t.query};if(e.body){let r=await e.body[`~standard`].validate(t.body);if(r.issues)return{data:null,error:fo(r.issues,`body`)};n.body=r.value}if(e.query){let r=await e.query[`~standard`].validate(t.query);if(r.issues)return{data:null,error:fo(r.issues,`query`)};n.query=r.value}return e.requireHeaders&&!t.headers?{data:null,error:{message:`Headers is required`,issues:[]}}:e.requireRequest&&!t.request?{data:null,error:{message:`Request is required`,issues:[]}}:{data:n,error:null}}function fo(e,t){return{message:e.map(e=>`[${e.path?.length?`${t}.`+e.path.map(e=>typeof e==`object`?e.key:e).join(`.`):t}] ${e.message}`).join(`; `),issues:e}}var po=async(e,{options:t,path:n})=>{let r=new Headers,i,{data:a,error:o}=await uo(t,e);if(o)throw new M(o.message,o.issues);let s=e.headers===void 0?`request`in e&&no(e.request)?e.request.headers:null:e.headers instanceof Headers?e.headers:new Headers(e.headers),c=s?.get(`cookie`),l=c?ao(c):void 0,u={...e,body:a.body,query:a.query,path:e.path||n||`virtual:`,context:`context`in e&&e.context?e.context:{},returned:void 0,headers:e?.headers,request:e?.request,params:`params`in e?e.params:void 0,method:e.method??(Array.isArray(t.method)?t.method[0]:t.method===`*`?`GET`:t.method),setHeader:(e,t)=>{r.set(e,t)},getHeader:e=>s?s.get(e):null,getCookie:(e,t)=>{let n=io(e,t);return n&&l?.get(n)||null},getSignedCookie:async(e,t,n)=>{let r=io(e,n);if(!r)return null;let i=l?.get(r);if(!i)return null;let a=i.lastIndexOf(`.`);if(a<1)return null;let o=i.substring(0,a),s=i.substring(a+1);return s.length!==44||!s.endsWith(`=`)?null:await Ja(s,o,await qa(t))?o:!1},setCookie:(e,t,n)=>{let i=co(e,t,n);return r.append(`set-cookie`,i),i},setSignedCookie:async(e,t,n,i)=>{let a=await lo(e,t,n,i);return r.append(`set-cookie`,a),a},redirect:e=>(r.set(`location`,e),new z(`FOUND`,void 0,r)),error:(e,t,n)=>new z(e,t,n),setStatus:e=>{i=e},json:(t,n)=>e.asResponse?{body:n?.body||t,routerResponse:n,_flag:`json`}:t,responseHeaders:r,get responseStatus(){return i}};for(let e of t.use||[]){let t=await e({...u,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(u.context,t.response),t.headers&&t.headers.forEach((e,t)=>{u.responseHeaders.set(t,e)})}return u};function mo(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function ho(e){let t=new WeakMap,n=new WeakMap,r=0,i=(e,n)=>{let r=n;for(;r;){if(r===e)return!0;r=t.get(r)}return!1};return JSON.stringify(e,function(e,a){if(typeof a==`bigint`)return a.toString();if(typeof a==`object`&&a){if(i(a,this))return`[Circular ref-${n.get(a)}]`;t.set(a,this),n.has(a)||n.set(a,r++)}return a})}function go(e){return!e||typeof e!=`object`?!1:`_flag`in e&&e._flag===`json`}var _o=new Set(`host.user-agent.referer.from.expect.authorization.proxy-authorization.cookie.origin.accept-charset.accept-encoding.accept-language.if-match.if-none-match.if-modified-since.if-unmodified-since.if-range.range.max-forwards.connection.keep-alive.transfer-encoding.te.upgrade.trailer.proxy-connection.content-length`.split(`.`));function vo(e){for(let t of _o)e.delete(t)}function yo(e,t){if(t)for(let[n,r]of new Headers(t).entries())n.toLowerCase()===`set-cookie`?e.append(n,r):e.set(n,r)}function bo(e,t){if(e instanceof Response){if(t?.headers){let n=new Headers(t.headers);vo(n),yo(e.headers,n)}return e}if(go(e)){let n=e.body,r=e.routerResponse;if(r instanceof Response)return r;let i=new Headers;if(yo(i,r?.headers),yo(i,e.headers),t?.headers){let e=new Headers(t.headers);vo(e),yo(i,e)}i.set(`Content-Type`,`application/json`);let a=e.status??t?.status??r?.status,o=t?.statusText??r?.statusText;return new Response(JSON.stringify(n),{...r,headers:i,...a===void 0?{}:{status:a},...o===void 0?{}:{statusText:o}})}if($a(e))return bo(e.body,{status:t?.status??e.statusCode,statusText:e.status.toString(),headers:t?.headers||e.headers});let n=e,r=new Headers(t?.headers);return vo(r),e?typeof e==`string`?(n=e,r.set(`Content-Type`,`text/plain`)):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?(n=e,r.set(`Content-Type`,`application/octet-stream`)):e instanceof Blob?(n=e,r.set(`Content-Type`,e.type||`application/octet-stream`)):e instanceof FormData?n=e:e instanceof URLSearchParams?(n=e,r.set(`Content-Type`,`application/x-www-form-urlencoded`)):e instanceof ReadableStream?(n=e,r.set(`Content-Type`,`application/octet-stream`)):mo(e)&&(n=ho(e),r.set(`Content-Type`,`application/json`)):(e===null&&(n=JSON.stringify(null)),r.set(`content-type`,`application/json`)),new Response(n,{...t,headers:r})}function xo(e,t,n){let r=typeof e==`string`?e:void 0,i=typeof t==`object`?t:e,a=typeof t==`function`?t:n;if((i.method===`GET`||i.method===`HEAD`)&&i.body)throw new k(`Body is not allowed with GET or HEAD methods`);if(r&&/\/{2,}/.test(r))throw new k(`Path cannot contain consecutive slashes`);let o=async(...e)=>{let t=e[0]||{},{data:n,error:o}=await to(po(t,{options:i,path:r}));if(o)throw o instanceof M?(i.onValidationError&&await i.onValidationError({message:o.message,issues:o.issues}),new z(400,{message:o.message,code:`VALIDATION_ERROR`})):o;let s=await a(n).catch(async e=>{if($a(e)){let n=i.onAPIError;if(n&&await n(e),t.asResponse)return e}throw e}),c=n.responseHeaders,l=n.responseStatus;return t.asResponse?bo(s,l===void 0?{headers:c}:{headers:c,status:l}):t.returnHeaders?t.returnStatus?{headers:c,response:s,status:l}:{headers:c,response:s}:t.returnStatus?{response:s,status:l}:s};return o.options=i,o.path=r,o}function So(e,t){return[...e??[],...t??[]]}xo.create=e=>{function t(...t){if(t.length===3){let[n,r,i]=t;return xo(n,{...r,use:So(r.use,e?.use)},i)}let[n,r]=t;return xo({...n,use:So(n.use,e?.use)},r)}return t};function Co(e,t){let n=async n=>{let r=n,i=typeof e==`function`?e:t,a=await po(r,{options:typeof e==`function`?{}:e,path:`/`});if(!i)throw Error(`handler must be defined`);try{let e=await i(a),t=a.responseHeaders;return r.returnHeaders?{headers:t,response:e}:e}catch(e){throw $a(e)&&Object.defineProperty(e,F,{enumerable:!1,configurable:!0,get(){return a.responseHeaders}}),e}};return n.options=typeof e==`function`?{}:e,n}Co.create=e=>{function t(t,n){if(typeof t==`function`)return Co({use:e?.use},t);if(!n)throw Error(`Middleware handler is required`);return Co({...t,method:`*`,use:[...e?.use||[],...t.use||[]]},n)}return t};var wo={};function To(e){switch(e.constructor.name){case`ZodString`:return`string`;case`ZodNumber`:return`number`;case`ZodBoolean`:return`boolean`;case`ZodObject`:return`object`;case`ZodArray`:return`array`;default:return`string`}}function Eo(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof y&&Object.entries(e.query.shape).forEach(([e,n])=>{n instanceof y&&t.push({name:e,in:`query`,schema:{type:To(n),...`minLength`in n&&n.minLength?{minLength:n.minLength}:{},description:n.description}})}),t)}function Do(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof y||e.body instanceof b)){let t=e.body.shape;if(!t)return;let n={},r=[];return Object.entries(t).forEach(([e,t])=>{t instanceof y&&(n[e]={type:To(t),description:t.description},t instanceof b||r.push(e))}),{required:e.body instanceof b?!1:!!e.body,content:{"application/json":{schema:{type:`object`,properties:n,required:r}}}}}}function Oo(e){return{400:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}},required:[`message`]}}},description:`Bad Request. Usually due to missing parameters, or invalid parameters.`},401:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}},required:[`message`]}}},description:`Unauthorized. Due to missing or invalid authentication.`},403:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Forbidden. You do not have permission to access this resource or to perform this action.`},404:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Not Found. The requested resource was not found.`},429:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Too Many Requests. You have exceeded the rate limit. Try again later.`},500:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Internal Server Error. This is a problem with the server that you cannot fix.`},...e}}async function ko(e,t){return Object.entries(e).forEach(([e,t])=>{let n=t.options;if(t.path&&!n.metadata?.SERVER_ONLY&&(n.method===`GET`&&(wo[t.path]={get:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Eo(n),responses:Oo(n.metadata?.openapi?.responses)}}),n.method===`POST`)){let e=Do(n);wo[t.path]={post:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Eo(n),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:`object`,properties:{}}}}}},responses:Oo(n.metadata?.openapi?.responses)}}}}),{openapi:`3.1.1`,info:{title:`Better Auth`,description:`API Reference for your Better Auth Instance`,version:`1.1.0`},components:{schemas:{}},security:[{apiKeyCookie:[]}],servers:[{url:t?.url}],tags:[{name:`Default`,description:`Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin.`}],paths:wo}}var Ao=(e,t)=>`<!doctype html>
2
+ <html>
3
+ <head>
4
+ <title>Scalar API Reference</title>
5
+ <meta charset="utf-8" />
6
+ <meta
7
+ name="viewport"
8
+ content="width=device-width, initial-scale=1" />
9
+ </head>
10
+ <body>
11
+ <script
12
+ id="api-reference"
13
+ type="application/json">
14
+ ${JSON.stringify(e)}
15
+ <\/script>
16
+ <script>
17
+ var configuration = {
18
+ favicon: ${t?.logo?`data:image/svg+xml;utf8,${encodeURIComponent(t.logo)}`:void 0} ,
19
+ theme: ${t?.theme||`saturn`},
20
+ metaData: {
21
+ title: ${t?.title||`Open API Reference`},
22
+ description: ${t?.description||`Better Call Open API`},
23
+ }
24
+ }
25
+ document.getElementById('api-reference').dataset.configuration =
26
+ JSON.stringify(configuration)
27
+ <\/script>
28
+ <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"><\/script>
29
+ </body>
30
+ </html>`,jo=(()=>{let e=function(){};return e.prototype=Object.create(null),Object.freeze(e.prototype),e})();function Mo(){return{root:{key:``},static:new jo}}function No(e){let t=0,n=0;for(;t<e.length;t++){let r=e.charCodeAt(t);if(r===92)t++;else if(r===40)n++;else if(r===41&&n>0)n--;else if(r===123&&n===0)break}if(t>=e.length)return;let r=t+1;for(n=0;r<e.length;r++){let t=e.charCodeAt(r);if(t===92)r++;else if(t===40)n++;else if(t===41&&n>0)n--;else if(t===125&&n===0)break}if(r>=e.length)return;let i=e[r+1],a=i===`?`||i===`+`||i===`*`;return[e.slice(0,t),e.slice(t+1,r),e.slice(r+(a?2:1)),a?i:void 0]}function Po(e){if(!e.includes(`{`))return;let t=No(e);if(!t)return;let[n,r,i,a]=t;if(!a)return[n+r+i];if(a===`?`)return[n+r+i,n+i];if(r.includes(`/`))throw Error(`unsupported group repetition across segments`);return[`${n}(?:${r})${a}${i}`]}var Fo=`__rou3_unnamed_`,Io=`__rou3_esc_`;function Lo(e){return`${Fo}${e}`}function Ro(e){return/^(?!__rou3_|_\d)[A-Za-z_]\w*$/.test(e)?e:Io+e.replace(/[_-]/g,e=>e===`_`?`__`:`_h`)}function zo(e){return e.charCodeAt(0)===95?e.startsWith(`__rou3_esc_`)?e.slice(11).replace(/__|_h/g,e=>e===`__`?`_`:`-`):e.startsWith(`__rou3_unnamed_`)?e.slice(15):e:e}function Bo(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r===92)n++;else if(r===40)t++;else if(r===41&&t>0)t--;else if(r===42&&t===0)return!0}return!1}function Vo(e,t,n=Lo){let r=0,i=t,a=``;for(let t=0;t<e.length;t++){let o=e.charCodeAt(t);o===92?(a+=e[t],t+1<e.length&&(a+=e[++t])):o===40?(r++,a+=e[t]):o===41&&r>0?(r--,a+=e[t]):a+=o===42&&r===0?`(?<${n(i++)}>[^/]*)`:e[t]}return[a,i]}function Ho(e){return e.includes(`\\`)?e.replace(/\\([:(){}])/g,(e,t)=>`�`+`ABCDE`[`:(){}`.indexOf(t)]):e}function Uo(e){return e.startsWith(`**`)?2:e===`*`||e.includes(`:`)||e.includes(`(`)||Bo(e)?1:e===`\\*`?`*`:e===`\\*\\*`?`**`:e.includes(`�`)?e.replace(/\uFFFD([A-E])/g,(e,t)=>t===`A`?`:`:t===`B`?`(`:t===`C`?`)`:t===`D`?`{`:`}`):e}function Wo(e){for(let t=0;t<e.length;t++){let n=e[t].charCodeAt(e[t].length-1);if(n!==63&&n!==43&&n!==42)continue;let r=e[t].match(/^(.*:[\w-]+(?:\([^)]*\))?)([?+*])$/);if(!r)continue;let i=e.slice(0,t),a=e.slice(t+1);if(r[2]===`?`)return[`/`+i.concat(r[1]).concat(a).join(`/`),`/`+i.concat(a).join(`/`)];let o=r[1].match(/:([\w-]+)/)?.[1]||`_`,s=`/`+[...i,`**:${o}`,...a].join(`/`),c=`/`+[...i,...a].join(`/`);return r[2]===`+`?[s]:[s,c]}}function Go(e){if(!e.includes(`/.`))return e;let t=[];for(let n of e.split(`/`))if(n===`.`)continue;else n===`..`&&t.length>1?t.pop():t.push(n);return t.join(`/`)||`/`}function Ko(e){let t=e.split(`/`);return t.shift(),t[t.length-1]===``&&t.pop(),t}function qo(e){let t=Ko(e);for(;t[t.length-1]===``;)t.pop();return t}function Jo(e,t){let n=new jo;for(let[r,i]of t){let t=r<0?e.slice(-(r+1)).join(`/`):e[r];if(typeof i==`string`)n[i]=t;else{let e=t.match(i);if(e)for(let t in e.groups)n[zo(t)]=e.groups[t]}}return n}function Yo(e,t=``,n,r){t=t.toUpperCase(),n.charCodeAt(0)!==47&&(n=`/${n}`);let i=Po(n);if(i){for(let n of i)Yo(e,t,n,r);return}n=Ho(n);let a=qo(n),o=Wo(a);if(o){for(let n of o)Yo(e,t,n,r);return}let s=e.root,c=0,l=[],u=[];for(let e=0;e<a.length;e++){let t=a[e],n=Uo(t);if(n===2){s.wildcard||(s.wildcard={key:`**`}),s=s.wildcard,l.push([-(e+1),t.split(`:`)[1]||`_`,t.length===2]);break}if(n===1){if(s.param||(s.param={key:`*`}),s=s.param,t===`*`)l.push([e,String(c++),!0]);else if(t.includes(`(`)||t.includes(`:`,1)||!/^:[\w-]+$/.test(t)){let[n,r]=Xo(t,c);c=r,u[e]=n,s.hasRegexParam=!0,l.push([e,n,!1])}else l.push([e,t.slice(1),!1]);continue}t=a[e]=n;let r=s.static?.[t];if(r)s=r;else{let e={key:t};s.static||(s.static=new jo),s.static[t]=e,s=e}}let d=l.length>0,f=s.methods??=new jo;(f[t]??=[]).push({data:r||null,paramsRegexp:u,paramsMap:d?l:void 0}),d||(e.static[`/`+a.join(`/`)]=s)}function Xo(e,t=0){let n=t,r=``,i=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n===40)i++;else if(n===41&&i>0)i--;else if(n===92&&i===0&&t+1<e.length){let n=e[t+1];if(n!==`:`&&n!==`(`&&n!==`*`&&n!==`\\`){r+=`￾`+n,t++;continue}}else if(n===46&&i===0){r+=`\\.`;continue}r+=e[t]}[r,n]=Vo(r,n);let a=r.replace(/:([\w-]+)(?:\(([^)]*)\))?/g,(e,t,n)=>`(?<${Ro(t)}>${n||`[^/]+`})`).replace(/\((?![?<])/g,()=>`(?<${Lo(n++)}>`).replace(/\uFFFE(.)/g,(e,t)=>/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t);return[RegExp(`^${a}$`),n]}function Zo(e,t=``,n,r){r?.normalize&&(n=Go(n)),n.charCodeAt(n.length-1)===47&&(n=n.slice(0,-1));let i=e.static[n];if(i&&i.methods){let e=i.methods[t]||i.methods[``];if(e!==void 0)return e[0]}let a=Ko(n),o=Qo(e.root,t,a,0);if(o!==void 0)return r?.params===!1?o:{data:o.data,params:o.paramsMap?Jo(a,o.paramsMap):void 0}}function Qo(e,t,n,r){if(r===n.length){if(e.methods){let r=$o(e.methods,t,n,e.key===`*`,!1);if(r)return r}return e.param?.methods&&$o(e.param.methods,t,n,!0,!0)||e.wildcard?.methods&&$o(e.wildcard.methods,t,n,!0,!0)||void 0}let i=n[r];if(e.static){let a=e.static[i];if(a){let e=Qo(a,t,n,r+1);if(e)return e}}if(e.param){let i=Qo(e.param,t,n,r+1);if(i)return i}if(e.wildcard&&e.wildcard.methods)return $o(e.wildcard.methods,t,n,!0,!1)}function $o(e,t,n,r,i){let a=e[t]||e[``];if(!a)return;let o=a[0];if(a.length===1&&o.paramsRegexp.length===0){if(!i)return o;let e=o.paramsMap;return e?.[e.length-1]?.[2]?o:void 0}let s,c=-1;for(let e of a){let t=e.paramsMap,a=t?.[t.length-1]?.[2];if(i&&!a)continue;let o=r&&t&&!a?1:0,l=e.paramsRegexp;for(let e=0;e<l.length;e++)if(l[e]){if(!l[e].test(n[e])){o=-1;break}o++}o>c&&(s=e,c=o)}return s}function es(e,t=``,n,r){r?.normalize&&(n=Go(n)),n.charCodeAt(n.length-1)===47&&(n=n.slice(0,-1));let i=Ko(n),a=ts(e.root,t,i,0);return r?.params===!1?a:a.map(e=>({data:e.data,params:e.paramsMap?Jo(i,e.paramsMap):void 0}))}function ts(e,t,n,r,i=[]){let a=n[r];if(e.wildcard&&e.wildcard.methods){let a=e.wildcard.methods[t]||e.wildcard.methods[``];if(a){if(r<n.length)ns(i,a,!0);else{let e=[];for(let t of a){let n=t.paramsMap;n?.[n.length-1]?.[2]&&e.push(t)}ns(i,e,!0)}}}if(e.param){if(r<n.length){let o=i.length;if(ts(e.param,t,n,r+1,i),e.param.hasRegexParam)for(let e=i.length-1;e>=o;e--)i[e].paramsRegexp[r]?.test(a)===!1&&i.splice(e,1)}else if(e.param.methods){let n=e.param.methods[t]||e.param.methods[``];if(n){let e=[];for(let t of n){let n=t.paramsMap;n?.[n.length-1]?.[2]&&e.push(t)}ns(i,e,!0)}}}if(r<n.length){let o=e.static?.[a];o&&ts(o,t,n,r+1,i)}if(r===n.length&&e.methods){let n=e.methods[t]||e.methods[``];n&&ns(i,n,e.key===`*`)}return i}function ns(e,t,n){t.length>1&&(t=t.map(e=>{let t=0,{paramsRegexp:r,paramsMap:i}=e;for(let e=0;e<r.length;e++)r[e]&&t++;return n&&i&&!i[i.length-1][2]&&t++,[e,t]}).sort((e,t)=>e[1]-t[1]).map(e=>e[0]));for(let n of t)e.push(n)}var rs=(e,t)=>{if(!t?.openapi?.disabled){let n={path:`/api/reference`,...t?.openapi};e.openapi=xo(n.path,{method:`GET`},async t=>{let r=await ko(e);return new Response(Ao(r,n.scalar),{headers:{"Content-Type":`text/html`}})})}let n=Mo(),r=Mo();for(let t of Object.values(e)){if(!t.options||!t.path||t.options?.metadata?.SERVER_ONLY)continue;let e=Array.isArray(t.options?.method)?t.options.method:[t.options?.method];for(let r of e)Yo(n,r,t.path,t)}if(t?.routerMiddleware?.length)for(let{path:e,middleware:n}of t.routerMiddleware)Yo(r,`*`,e,n);let i=t?.basePath&&t.basePath!==`/`?t.basePath.replace(/\/+$/,``):``,a=async e=>{let a=new URL(e.url),o=a.pathname,s;if(i){if(!o.startsWith(`${i}/`))return new Response(null,{status:404,statusText:`Not Found`});s=o.slice(i.length)}else s=o;if(s.length===0||/\/{2,}/.test(s))return new Response(null,{status:404,statusText:`Not Found`});let c=Zo(n,e.method,s);if(s.endsWith(`/`)!==c?.data?.path?.endsWith(`/`)&&!t?.skipTrailingSlashes||!c?.data)return new Response(null,{status:404,statusText:`Not Found`});let l={};a.searchParams.forEach((e,t)=>{t in l?Array.isArray(l[t])?l[t].push(e):l[t]=[l[t],e]:l[t]=e});let u=c.data;try{let n=u.options.metadata?.allowedMediaTypes||t?.allowedMediaTypes,i={path:s,method:e.method,headers:e.headers,params:c.params?{...c.params}:{},request:e,body:u.options.disableBody?void 0:await Qa(u.options.cloneRequest?e.clone():e,n),query:l,_flag:`router`,asResponse:!0,context:t?.routerContext},a=es(r,`*`,s);if(a?.length)for(let{data:e,params:t}of a){let n=await e({...i,params:t?{...t}:{},asResponse:!1});if(n instanceof Response)return n}return await u(i)}catch(n){if(t?.onError)try{let r=await t.onError(n,e);if(r instanceof Response)return bo(r)}catch(e){if($a(e))return bo(e);throw e}if(t?.throwError)throw n;return $a(n)?bo(n):(console.error(`# SERVER_ERROR: `,n),new Response(null,{status:500,statusText:`Internal Server Error`}))}};return{handler:async e=>{let n=await t?.onRequest?.(e);if(n instanceof Response)return n;let r=no(n)?n:e,i=await a(r),o=await t?.onResponse?.(i,r);return o instanceof Response?o:i},endpoints:e}};function is(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}var as=is({USER_NOT_FOUND:`User not found`,FAILED_TO_CREATE_USER:`Failed to create user`,FAILED_TO_CREATE_SESSION:`Failed to create session`,FAILED_TO_UPDATE_USER:`Failed to update user`,FAILED_TO_GET_SESSION:`Failed to get session`,INVALID_PASSWORD:`Invalid password`,INVALID_EMAIL:`Invalid email`,INVALID_EMAIL_OR_PASSWORD:`Invalid email or password`,INVALID_USER:`Invalid user`,SOCIAL_ACCOUNT_ALREADY_LINKED:`Social account already linked`,PROVIDER_NOT_FOUND:`Provider not found`,INVALID_TOKEN:`Invalid token`,TOKEN_EXPIRED:`Token expired`,ID_TOKEN_NOT_SUPPORTED:`id_token not supported`,FAILED_TO_GET_USER_INFO:`Failed to get user info`,USER_EMAIL_NOT_FOUND:`User email not found`,EMAIL_NOT_VERIFIED:`Email not verified`,PASSWORD_TOO_SHORT:`Password too short`,PASSWORD_TOO_LONG:`Password too long`,USER_ALREADY_EXISTS:`User already exists.`,USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:`User already exists. Use another email.`,EMAIL_CAN_NOT_BE_UPDATED:`Email can not be updated`,CHANGE_EMAIL_DISABLED:`Change email is disabled`,CREDENTIAL_ACCOUNT_NOT_FOUND:`Credential account not found`,SESSION_EXPIRED:`Session expired. Re-authenticate to perform this action.`,FAILED_TO_UNLINK_LAST_ACCOUNT:`You can't unlink your last account`,ACCOUNT_NOT_FOUND:`Account not found`,USER_ALREADY_HAS_PASSWORD:`User already has a password. Provide that to delete the account.`,CROSS_SITE_NAVIGATION_LOGIN_BLOCKED:`Cross-site navigation login blocked. This request appears to be a CSRF attack.`,VERIFICATION_EMAIL_NOT_ENABLED:`Verification email isn't enabled`,EMAIL_ALREADY_VERIFIED:`Email is already verified`,EMAIL_MISMATCH:`Email mismatch`,SESSION_NOT_FRESH:`Session is not fresh`,LINKED_ACCOUNT_ALREADY_EXISTS:`Linked account already exists`,INVALID_ORIGIN:`Invalid origin`,INVALID_CALLBACK_URL:`Invalid callbackURL`,INVALID_REDIRECT_URL:`Invalid redirectURL`,INVALID_ERROR_CALLBACK_URL:`Invalid errorCallbackURL`,INVALID_NEW_USER_CALLBACK_URL:`Invalid newUserCallbackURL`,MISSING_OR_NULL_ORIGIN:`Missing or null Origin`,CALLBACK_URL_REQUIRED:`callbackURL is required`,FAILED_TO_CREATE_VERIFICATION:`Unable to create verification`,FIELD_NOT_ALLOWED:`Field not allowed to be set`,ASYNC_VALIDATION_NOT_SUPPORTED:`Async validation is not supported`,VALIDATION_ERROR:`Validation Error`,MISSING_FIELD:`Field is required`,METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED:`POST method requires deferSessionRefresh to be enabled in session config`,BODY_MUST_BE_AN_OBJECT:`Body must be an object`,PASSWORD_ALREADY_SET:`User already has a password set`});function os(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):typeof e==`string`?e.trim().split(/\s+/).filter(Boolean):[]}function ss(e){let t=e=>new Date(new Date().getTime()+e*1e3);return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?t(e.expires_in):void 0,refreshTokenExpiresAt:e.refresh_token_expires_in?t(e.refresh_token_expires_in):void 0,scopes:os(e.scope),idToken:e.id_token,raw:e}}function cs(e,t){let n=e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[],r=(t??[]).map(e=>e.trim()).filter(Boolean);return[...new Set([...n,...r])].join(`,`)}function ls(e){let t=Array.isArray(e)?e[0]:e;return typeof t==`string`&&t.length>0?t:void 0}async function us(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return ve.encode(new Uint8Array(n),{padding:!1})}var ds=/^Basic +(.*)$/i;function fs(e){return new URLSearchParams({v:e}).toString().slice(2)}function ps(e){let t=new URLSearchParams(`v=${e}`).get(`v`);if(t===null)throw Error(`form-url-encoded value could not be decoded`);return t}function ms(e,t){let n=`${fs(e)}:${fs(t)}`;return`Basic ${te.encode(n)}`}function hs(e){let t=e.match(ds);if(!t)throw Error(`Authorization header is not a Basic credential`);let n=t[1]??``,r=new TextDecoder().decode(te.decode(n)),i=r.indexOf(`:`);if(i===-1)throw Error(`Basic credential is missing the client id/secret separator`);let a=r.slice(0,i),o=r.slice(i+1);if(!a||!o)throw Error(`Basic credential client id and secret must both be non-empty`);return{clientId:ps(a),clientSecret:ps(o)}}var gs=[`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`,`ES256`,`ES384`,`ES512`,`EdDSA`],_s=`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`;async function vs({getClientAssertion:e,context:t}){return{client_assertion:await e(t),client_assertion_type:_s}}var ys=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}},bs=async(e,t)=>{let n=t||{},r={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:n,hooks:r};for(let i of t?.plugins||[]){if(i.init){let t=await i.init?.call(i,e.toString(),n);n=t.options||n,e=t.url}r.onRequest.push(i.hooks?.onRequest),r.onResponse.push(i.hooks?.onResponse),r.onSuccess.push(i.hooks?.onSuccess),r.onError.push(i.hooks?.onError),r.onRetry.push(i.hooks?.onRetry)}return{url:e,options:n,hooks:r}},xs=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},Ss=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function Cs(e){if(typeof e==`number`)return new xs({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new xs(e);case`exponential`:return new Ss(e);default:throw Error(`Invalid retry strategy`)}}var ws=[`get`,`post`,`put`,`patch`,`delete`];function Ts(e){if(!e.startsWith(`@`))return{method:void 0,path:e};let t=e.indexOf(`/`),n=e.slice(1,t===-1?void 0:t);return ws.includes(n)?{method:n,path:t===-1?e:e.slice(t+1)}:{method:void 0,path:e}}var Es=e=>e===`.`||e===`..`,Ds=e=>e.split(`:`).map(e=>encodeURIComponent(e)).join(`:`);function Os(e,t){let n=t.get(e);if(n===void 0)return Ds(e);if(Es(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function ks(e,t){let{baseURL:n,params:r,query:i}=t||{query:{},params:{},baseURL:``},a=e.startsWith(`http`)?e.split(`/`).slice(0,3).join(`/`):n||``,{path:o}=Ts(e);o!==e&&(e=`/${o}`),a.endsWith(`/`)||(a+=`/`);let[s,c]=e.replace(a,``).split(`?`),l=new URLSearchParams(c);for(let[e,t]of Object.entries(i||{})){if(t==null)continue;let n;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let n of t)l.append(e,n);continue}else n=JSON.stringify(t);l.set(e,n)}let u=new Map;if(r){if(Array.isArray(r)){let e=s.split(`/`).filter(e=>e.startsWith(`:`));for(let[t,n]of e.entries()){let e=r[t];u.set(n,String(e))}}else for(let[e,t]of Object.entries(r))u.set(`:${e}`,String(t))}s=s.split(`/`).map(e=>Os(e,u)).join(`/`),s=s.replace(/^\/+/,``);let d=l.toString();return d=d.length>0?`?${d}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${s}${d}`,a):`${a}${s}${d}`}var As=async e=>{let t={},n=async e=>typeof e==`function`?await e():e;if(e?.auth){if(e.auth.type===`Bearer`){let r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type===`Basic`){let[r,i]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type===`Custom`){let[r,i]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!i)return t;t.authorization=`${r??``} ${i}`}}return t},js=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Ms(e){let t=e.headers.get(`content-type`),n=new Set([`image/svg`,`application/xml`,`application/xhtml`,`application/html`]);if(!t)return`json`;let r=t.split(`;`).shift()||``;return js.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function Ns(e){try{return JSON.parse(e),!0}catch{return!1}}function Ps(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function Fs(e){try{return JSON.parse(e)}catch{return e}}function Is(e){return typeof e==`function`}function Ls(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&Is(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&Is(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function Rs(...e){let t={};for(let n of e)if(n){if(n instanceof Headers)n.forEach((e,n)=>{t[n]=e});else{let e=Array.isArray(n)?n:Object.entries(n);for(let[n,r]of e)r!=null&&(t[n]=r)}}return t}async function zs(e){let t=new Headers(Rs(e?.headers,await As(e)));if(!t.has(`content-type`)){let n=Bs(e?.body);n&&t.set(`content-type`,n)}return t}function Bs(e){return Ps(e)?`application/json`:null}function Vs(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function Hs(e,t){let{body:n}=e;return n?!Ps(n)||typeof n==`string`?n:Vs(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function Us(e,t){if(t?.method)return t.method.toUpperCase();let{method:n}=Ts(e);return n?n.toUpperCase():t?.body?`POST`:`GET`}function Ws(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var Gs=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function Ks(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new Gs(n.issues);return n.value}function qs(e){"@babel/helpers - typeof";return qs=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},qs(e)}function Js(e,t){if(qs(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(qs(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Ys(e){var t=Js(e,`string`);return qs(t)==`symbol`?t:t+``}function Xs(e,t,n){return(t=Ys(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Zs(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Qs(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Zs(Object(n),!0).forEach(function(t){Xs(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Zs(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var $s=async(e,t)=>{var n;let{hooks:r,url:i,options:a}=await bs(e,t),o=Ls(a),s=new AbortController,c=a.signal??s.signal,l=ks(i,a),u=await zs(a),d=Hs(a,u),f=Us(i,a),p=Qs(Qs({},a),{},{url:l,headers:u,body:d,method:f,signal:c});for(let e of r.onRequest)if(e){let t=await e(p);typeof t==`object`&&t&&Object.assign(p,t)}(`pipeTo`in p&&typeof p.pipeTo==`function`||typeof(t==null||(n=t.body)==null?void 0:n.pipe)==`function`)&&(`duplex`in p||(p.duplex=`half`));let{clearTimeout:m}=Ws(a,s),h=await o(p.url,p);m();let g={response:h,request:p};for(let e of r.onResponse)if(e){var _;let n=await e(Qs(Qs({},g),{},{response:t!=null&&(_=t.hookOptions)!=null&&_.cloneResponse?h.clone():h}));n instanceof Response?h=n:typeof n==`object`&&n&&(h=n.response)}if(h.ok){if(p.method===`HEAD`)return{data:``,error:null};let e=Ms(h),n={data:null,response:h,request:p};if(e===`json`||e===`text`){let e=await h.text();n.data=await(p.jsonParser??Fs)(e)}else n.data=await h[e]();p?.output&&p.output&&!p.disableValidation&&(n.data=await Ks(p.output,n.data));for(let e of r.onSuccess)if(e){var v;await e(Qs(Qs({},n),{},{response:t!=null&&(v=t.hookOptions)!=null&&v.cloneResponse?h.clone():h}))}return t?.throw?n.data:{data:n.data,error:null}}let y=t?.jsonParser??Fs,b=await h.text(),x=Ns(b),S=x?await y(b):null,C={response:h,responseText:b,request:p,error:Qs(Qs({},S),{},{status:h.status,statusText:h.statusText})};for(let e of r.onError)if(e){var w;await e(Qs(Qs({},C),{},{response:t!=null&&(w=t.hookOptions)!=null&&w.cloneResponse?h.clone():h}))}if(t?.retry){let n=Cs(t.retry),i=t.retryAttempt??0;if(await n.shouldAttemptRetry(i,h)){for(let e of r.onRetry)e&&await e(g);let a=n.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await $s(e,Qs(Qs({},t),{},{retryAttempt:i+1}))}}if(t?.throw)throw new ys(h.status,h.statusText,x?S:b);return{data:null,error:Qs(Qs({},S),{},{status:h.status,statusText:h.statusText})}},ec=new Set([301,302,303,307,308]);function tc(e){return e.type===`opaqueredirect`||ec.has(e.status)}function nc(e){return new V(`The OAuth endpoint "${e}" returned an HTTP redirect. Server-side OAuth fetches refuse redirects to prevent SSRF; configure the final endpoint URL.`)}var rc={redirect:`manual`};async function ic(e,t){let n=!1,r=t?.onError,i=await $s(e,{...t,...rc,async onError(e){tc(e.response)&&(n=!0),await r?.(e)}}).catch(t=>{throw n?nc(e):t});if(n)throw nc(e);return i}var ac=`dpop+jwt`,oc=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],sc=300,cc=512,lc=new Set([`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`k`]);function uc(e){return{reserve:({key:t,expiresAt:n})=>e.reserveVerificationValue({identifier:`dpop-proof:${t}`,value:t,expiresAt:n})}}function Y(e,t){return Object.assign(Error(t),{code:e})}function dc(e){return e instanceof Error&&`code`in e&&e.code===`invalid_dpop_proof`}function fc(e){if(!e)return;let t=e.trim();if(!t)return;let n=/^([A-Za-z][A-Za-z0-9!#$%&'*+.^_`|~-]*)\s+(.+)$/.exec(t);if(!n)return{scheme:`Unknown`,token:t};let r=n[1]??``,i=n[2]?.trim()??``;return r.toLowerCase()===`bearer`?{scheme:`Bearer`,token:i}:r.toLowerCase()===`dpop`?{scheme:`DPoP`,token:i}:{scheme:`Unknown`,token:t}}function pc(e){return fc(e)?.token??e}function mc(e){let t=new URL(e);if(t.hash)throw Error(`DPoP proof htu must not contain a fragment`);return`${t.origin}${t.pathname}`}async function hc(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return G(new Uint8Array(t))}async function gc(e){return fi(e,`sha256`)}function _c(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.jkt;return typeof t==`string`&&t.length>0?t:void 0}function vc(e){return _c(e.cnf)}function yc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function bc(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function xc(e,t){if(!e||e===`none`||e.startsWith(`HS`))throw Y(`invalid_dpop_proof`,`DPoP proof must use an asymmetric JWS algorithm`);if(!t.includes(e))throw Y(`invalid_dpop_proof`,`DPoP proof uses an unsupported JWS algorithm`)}function Sc(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Y(`invalid_dpop_proof`,`DPoP proof header must include a public jwk`);if(e.kty===`oct`)throw Y(`invalid_dpop_proof`,`DPoP proof jwk must be asymmetric`);for(let t of lc)if(t in e)throw Y(`invalid_dpop_proof`,`DPoP proof jwk must not contain private key material`)}async function Cc(e){let t=`${e.jkt}\n${e.htm}\n${e.htu}\n${e.jti}`,n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return G(new Uint8Array(n))}async function wc(e,t){if(e&&!await e.reserve(t))throw Y(`invalid_dpop_proof`,`DPoP proof jti has already been used`)}async function Tc({proofJwt:e,method:t,url:n,accessToken:r,expectedJkt:i,requireAth:a=!1,nowSeconds:o=Math.floor(Date.now()/1e3),proofMaxAgeSeconds:s=sc,signingAlgorithms:c=oc,replayStore:l}){if(!e||e.split(`.`).length!==3)throw Y(`invalid_dpop_proof`,`DPoP proof must be a compact JWT`);let u;try{u=vi(e)}catch(e){throw Y(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof header is invalid`)}if(u.typ!==`dpop+jwt`)throw Y(`invalid_dpop_proof`,`DPoP proof typ must be "dpop+jwt"`);xc(u.alg,c),Sc(u.jwk);let d;try{d=(await Vr(e,await _i(u.jwk,u.alg),{typ:ac})).payload}catch(e){throw Y(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof signature is invalid`)}let f=yc(d,`htm`),p=yc(d,`htu`),m=yc(d,`jti`),h=bc(d,`iat`);if(!f||!p||!m||h===void 0)throw Y(`invalid_dpop_proof`,`DPoP proof must include htm, htu, jti, and iat claims`);if(m.length>cc)throw Y(`invalid_dpop_proof`,`DPoP proof jti is too large`);if(f.toUpperCase()!==t.toUpperCase())throw Y(`invalid_dpop_proof`,`DPoP proof htm does not match the request method`);let g,_;try{g=mc(n),_=mc(p)}catch(e){throw Y(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof htu is invalid`)}if(_!==g)throw Y(`invalid_dpop_proof`,`DPoP proof htu does not match the request URL`);if(h>o+5||o-h>s)throw Y(`invalid_dpop_proof`,`DPoP proof iat is outside the accepted window`);let v=yc(d,`ath`);if(a&&!v)throw Y(`invalid_dpop_proof`,`DPoP proof must include an ath claim`);if(r!==void 0&&v!==await hc(r))throw Y(`invalid_dpop_proof`,`DPoP proof ath does not match the access token`);let y=await gc(u.jwk);if(i!==void 0&&y!==i)throw Y(`invalid_dpop_proof`,`DPoP proof key does not match the bound token`);let b=await Cc({jkt:y,htm:f.toUpperCase(),htu:g,jti:m}),x=new Date((h+s)*1e3);return await wc(l,{key:b,expiresAt:x,now:new Date(o*1e3)}),{jwk:u.jwk,jkt:y,jti:m,htm:f,htu:g,iat:h,ath:v,replayKey:b,expiresAt:x}}function Ec(e,t){return Object.assign(Error(t),{code:e})}function Dc(e){return e instanceof Error&&`code`in e&&(e.code===`invalid_token`||e.code===`invalid_dpop_proof`)}async function Oc({payload:e,authorization:t,proofJwt:n,method:r,url:i,replayStore:a,proofMaxAgeSeconds:o,signingAlgorithms:s}){let c=vc(e);if(c){if(t.scheme!==`DPoP`)throw Ec(`invalid_token`,`DPoP-bound access token requires the DPoP authorization scheme`);if(!n)throw Ec(`invalid_dpop_proof`,`DPoP proof header is required`);try{await Tc({proofJwt:n,method:r,url:i,accessToken:t.token,expectedJkt:c,requireAth:!0,proofMaxAgeSeconds:o,signingAlgorithms:s,replayStore:a})}catch(e){throw dc(e)?Ec(`invalid_dpop_proof`,e.message):e}}else if(t.scheme===`DPoP`)throw Ec(`invalid_token`,`DPoP authorization requires a DPoP-bound access token`)}_t.code,mt.code,gt.code;var kc=new Map,Ac=new WeakMap,jc=3e5;function Mc(e,t){if(e&&!(Date.now()-e.fetchedAt>=jc)&&(!t||e.jwks.keys.some(e=>e.kid===t)))return e.jwks}async function Nc(e){let t=typeof e==`string`?await ic(e,{headers:{Accept:`application/json`}}).then(async e=>{if(e.error)throw Error(`Jwks failed: ${e.error.message??e.error.statusText}`);return e.data}):await e();if(!t)throw Error(`No jwks found`);return t}async function Pc(e,t){return(await Fc(e,t)).jwks}async function Fc(e,t){let n;try{n=vi(e)}catch(e){throw e instanceof Error?e:Error(e)}let r=n.kid;if(typeof t.jwksFetch!=`string`){let e=t.jwksCacheKey;if(!e){let e=await t.jwksFetch();if(!e)throw Error(`No jwks found`);return{jwks:e,fromCache:!1,kid:r}}let n=Ac.get(e),i=t.forceRefresh?void 0:Mc(n,r);if(i)return{jwks:i,fromCache:!0,kid:r,noKidRefetchedAt:n?.noKidRefetchedAt};let a=await t.jwksFetch();if(!a)throw Error(`No jwks found`);let o=Date.now();return Ac.set(e,{jwks:a,fetchedAt:o,...t.forceRefresh&&!r?{noKidRefetchedAt:o}:{}}),{jwks:a,fromCache:!1,kid:r}}let i=t.jwksFetch,a=kc.get(i),o=t.forceRefresh?void 0:Mc(a,r);if(!o){let e=await Nc(t.jwksFetch),n=Date.now();return kc.set(i,{jwks:e,fetchedAt:n,...t.forceRefresh&&!r?{noKidRefetchedAt:n}:{}}),{jwks:e,fromCache:!1,kid:r}}return{jwks:o,fromCache:!0,kid:r,noKidRefetchedAt:a?.noKidRefetchedAt}}var Ic=[`authorization_code`,`client_credentials`,`refresh_token`],Lc=[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],Rc=[`none`,...Lc],zc=new Set(Rc);function Bc(e,t){if(!(t.trim().length>0))throw new V(`OAuth Provider extension ${e} cannot be empty`)}function Vc(e,t){Bc(e,t);let n;try{n=new URL(t)}catch{n=void 0}if(!n?.protocol)throw new V(`OAuth Provider extension ${e} must be an absolute URI: ${t}`)}function Hc(e){Vc(`grant type`,e)}function Uc(e){if(Bc(`token_endpoint_auth_method`,e),zc.has(e))throw new V(`OAuth Provider extension token_endpoint_auth_method is reserved: ${e}`)}function Wc(e){if(Vc(`client_assertion_type`,e),e===`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)throw new V(`OAuth Provider extension client_assertion_type is reserved: ${e}`)}function Gc(e){let t=Object.keys(e.grants??{});for(let e of t)Hc(e);let n=[],r=[];for(let[t,i]of Object.entries(e.clientAuthentication??{})){Uc(t),n.push(t);let e=i.assertionTypes??[t];if(e.length===0)throw new V(`OAuth Provider extension client_assertion_type list cannot be empty for ${t}`);for(let t of e)Wc(t),r.push(t)}let i=(e.clientDiscovery?Array.isArray(e.clientDiscovery)?e.clientDiscovery:[e.clientDiscovery]:[]).map(e=>e.id);for(let e of i)Bc(`client discovery id`,e);return{grantTypes:t,authMethods:n,assertionTypes:r,clientDiscoveryIds:i}}function Kc(e,t){let n=new Set;for(let r of t){if(n.has(r))throw new V(`OAuth Provider extensions register ${e} "${r}" more than once. Extension contributions must be disjoint.`);n.add(r)}}function qc(e){let t=(e??[]).map(Gc);Kc(`grant type`,t.flatMap(e=>e.grantTypes)),Kc(`token_endpoint_auth_method`,t.flatMap(e=>e.authMethods)),Kc(`client_assertion_type`,t.flatMap(e=>e.assertionTypes)),Kc(`client discovery id`,t.flatMap(e=>e.clientDiscoveryIds))}function Jc(e){return e.extensions??[]}function Yc(e){return Jc(e).flatMap(e=>{let t=e.clientDiscovery;return t?Array.isArray(t)?t:[t]:[]})}function Xc(e,t){let n=e.getPlugin(`oauth-provider`);if(!n)throw new V(`extendOAuthProvider requires the oauth-provider plugin.`);let r=n.options.extensions??[];if(r.includes(t))return;let i=[...r,t];qc(i),n.options.extensions=i}function Zc(e){return Jc(e).flatMap(e=>Object.keys(e.grants??{}))}function Qc(e){return Array.from(new Set([...e.grantTypes??Ic,...Zc(e)]))}function $c(e,t){for(let n of Jc(e)){let e=n.grants?.[t];if(e)return e}}function el(e){return Jc(e).flatMap(e=>Object.keys(e.clientAuthentication??{}))}function tl(e,t){return Array.from(new Set([...t?.includeNone?[`none`]:[],...Lc,...el(e)]))}function nl(e,t){return t?el(e).includes(t):!1}function rl(e,t){if(t!==`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)for(let n of Jc(e)){let e=n.clientAuthentication??{};for(let[n,r]of Object.entries(e))if((r.assertionTypes??[n]).includes(t))return{method:n,strategy:r}}}function il(e,t,n,r){let i={...r};for(let a of Jc(t)){let o=a.metadata?.({ctx:e,opts:t,type:n,document:r});for(let[e,t]of Object.entries(o??{}))e in i||(i[e]=t)}return i}async function al(e,t){let n={};for(let r of Jc(e)){let e=await t(r)??{};for(let[t,r]of Object.entries(e))t in n?_e.warn(`oauth-provider: two extensions contributed the claim "${t}"; keeping the first-registered value.`):n[t]=r}return n}function ol(e,t){return al(e,e=>e.claims?.accessToken?.(t))}function sl(e,t){return al(e,e=>e.claims?.idToken?.(t))}function cl(e,t){return al(e,e=>e.claims?.userInfo?.(t))}function ll(e){return Jc(e).some(e=>e.claims?.userInfo)}function ul(e){if(!e)return;let[t,n,...r]=e.trim().split(/\s+/);if(t?.toLowerCase()===`bearer`){if(!n||r.length>0)throw new z(`BAD_REQUEST`,{error:`invalid_request`,error_description:`Malformed Bearer Authorization header`});return n}}function dl(){let e=new Map;return{get(t){let n=e.get(t);if(n){if(n.expiresAt&&n.expiresAt<new Date)e.delete(t);else return n}},set(t,n){e.set(t,n)}}}var fl=e=>e.getPlugin(`oauth-provider`),pl=e=>{let t=e.getPlugin(`jwt`);if(!t)throw new V(`jwt_config`);return t};function ml(e){if(e!=null){if(e instanceof Date)return Number.isFinite(e.getTime())?e:void 0;if(typeof e==`number`){if(!Number.isFinite(e))return;let t=new Date(e);return Number.isFinite(t.getTime())?t:void 0}if(typeof e==`string`){let t=e.trim();if(!t.length)return;let n=Number(t);if(Number.isFinite(n)){let e=new Date(n);return Number.isFinite(e.getTime())?e:void 0}let r=new Date(t);return Number.isFinite(r.getTime())?r:void 0}}}function hl(e){if(e instanceof Date||!e||typeof e!=`object`)return ml(e);let t=ml(e.createdAt)??ml(e.created_at);if(t)return t;let n=e.session;if(n&&typeof n==`object`)return ml(n.createdAt)??ml(n.created_at)}function gl(e){if(typeof e==`string`)return[e];if(e?.length)return e}function _l(e){if(typeof e==`string`)return e;if(e?.length)return e.length===1?e.at(0):e}var vl=new WeakMap;function yl(e){let t=vl.get(e);if(t)return t;let n=dl();return vl.set(e,n),n}async function bl(e,t){let n=new URLSearchParams(e),r=n.get(`sig`),i=n.getAll(`sig`),a=Number(n.get(`exp`));n.delete(`sig`);let o=await Ga(De(n).toString(),t);return i.length===1&&!!r&&Pi(r,o)&&new Date(a*1e3)>=new Date}async function xl(e,t,n){let r=yl(t),i=r.get(n);if(i&&!i.clientDiscoveryId)return Object.assign({},i);let a=await e.context.adapter.findOne({model:t.schema?.oauthClient?.modelName??`oauthClient`,where:[{field:`clientId`,value:n}]}),o=Yc(t);if(a?.clientDiscoveryId){let t=a.clientDiscoveryId,r=o.find(e=>e.id===t);if(!r?.matches(n)||(a=await r.resolve(e,n,a),!a))return null}else if(a)return t.cachedTrustedClients?.has(n)&&r.set(n,Object.assign({},a)),a;else for(let t of o){if(!t.matches(n))continue;let r=await t.resolve(e,n,null);if(r){a=r;break}}return a}function Sl(e){return e.reduce((e,t)=>({...e,...t.discoveryMetadata??{}}),{})}var Cl=async e=>{let t=await Li(`SHA-256`).digest(new TextEncoder().encode(e));return ve.encode(new Uint8Array(t),{padding:!1})};async function wl(e,t,n){if(t===`encrypted`)return await Ua({key:e.context.secretConfig,data:n});if(typeof t==`object`&&`decrypt`in t)return await t.decrypt(n);throw new V(`Unsupported decryption storageMethod type '${t}'`)}async function Tl(e,t,n,r){let i=t.storeClientSecret??(t.disableJwtPlugin?`encrypted`:`hashed`);if(r&&t.prefix?.clientSecret){if(r.startsWith(t.prefix?.clientSecret))r=r.replace(t.prefix.clientSecret,``);else throw new z(`UNAUTHORIZED`,{error_description:`invalid client_secret`,error:`invalid_client`})}if(i===`hashed`){let e=r?await Cl(r):void 0;return!!e&&Pi(e,n)}if(typeof i==`object`&&`hash`in i){if(i.verify)return!!r&&await i.verify(r,n);{let e=r?await i.hash(r):void 0;return!!e&&Pi(e,n)}}if(i===`encrypted`)try{let t=await wl(e,i,n);return!!r&&Pi(t,r)}catch{return!1}if(typeof i==`object`&&`decrypt`in i){let t=await wl(e,i,n);return!!r&&Pi(t,r)}throw new V(`Unsupported verify storageMethod type '${i}'`)}async function El(e,t,n){let r=t.storeClientSecret??(t.disableJwtPlugin?`encrypted`:`hashed`);if(r===`encrypted`)return await Ha({key:e.context.secretConfig,data:n});if(r===`hashed`)return await Cl(n);if(typeof r==`object`&&`hash`in r)return await r.hash(n);if(typeof r==`object`&&`encrypt`in r)return await r.encrypt(n);throw new V(`Unsupported storeClientSecret type '${r}'`)}async function Dl(e=`hashed`,t,n){if(e===`hashed`)return await Cl(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new V(`storeToken: unsupported storageMethod type '${e}'`)}async function Ol(e=`hashed`,t,n){if(e===`hashed`)return await Cl(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new V(`getStoredToken: unsupported storageMethod type '${e}'`)}var kl=/^Basic +/i,Al=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?=\s|$)/;function jl(e){return e.match(Al)?.[1]}var Ml=[`client_secret`,`client_assertion`,`client_assertion_type`];function Nl(e){throw new z(`BAD_REQUEST`,{error:`invalid_request`,error_description:e})}async function Pl(e,t={}){let n;t.client_id!==void 0&&t.client_id!==``&&(typeof t.client_id!=`string`&&Nl(`client_id must be a string`),n=t.client_id);let r={},i=(e,t)=>{t!==void 0&&t!==``&&(typeof t!=`string`&&Nl(`${e} must be a string`),r[e]=t)};for(let e of Ml)Object.hasOwn(t,e)&&i(e,t[e]);let a=!!e?.headers.get(`authorization`);if(e&&(e.headers.get(`content-type`)?.toLowerCase()??``).includes(`application/x-www-form-urlencoded`)){let t=new URLSearchParams(await e.clone().text()),r=t.getAll(`client_id`).filter(e=>e.length>0);r.length>1&&Nl(`client_id must not be repeated`),n=r[0];for(let e of Ml){let n=t.getAll(e).filter(e=>e.length>0);n.length>1&&Nl(`${e} must not be repeated`),n.length===1&&i(e,n[0])}}let o=r.client_secret!==void 0,s=r.client_assertion!==void 0||r.client_assertion_type!==void 0;(a&&(o||s)||o&&s)&&Nl(`A request must use only one client authentication method`),t.client_id=n;for(let e of Ml)t[e]=r[e];return{detected:a||Object.keys(r).length>0}}function Fl(e){if(kl.test(e))try{let{clientId:t,clientSecret:n}=hs(e);return{client_id:t,client_secret:n}}catch{throw new z(`UNAUTHORIZED`,{error_description:`invalid authorization header format`,error:`invalid_client`},{"WWW-Authenticate":`Basic`})}}function Il(e,t){let n=e.grantTypes&&e.grantTypes.length>0?e.grantTypes:[`authorization_code`];return t===`refresh_token`&&n.includes(`authorization_code`)?!0:n.includes(t)}function Ll(e,t){if(!t||!e.scopes)return;let n=new Set(e.scopes);for(let e of t)if(!n.has(e))throw new z(`BAD_REQUEST`,{error_description:`client does not allow scope ${e}`,error:`invalid_scope`})}function Rl(e,t){let n=t?.method===`client_secret_basic`,r=t?.scheme??(n?`Basic`:void 0);throw new z(r?`UNAUTHORIZED`:`BAD_REQUEST`,{error_description:e,error:`invalid_client`},r?{"WWW-Authenticate":r}:void 0)}async function zl(e,t,n,r,i,a,o,s){let c=await xl(e,t,n);c||Rl(`missing client`,{method:s}),c.disabled&&Rl(`client is disabled`,{method:s});let l=c.tokenEndpointAuthMethod??`client_secret_basic`;if(s&&l!==s&&Rl(`client registered for ${l} cannot use ${s}`,{method:s}),(c.tokenEndpointAuthMethod===`private_key_jwt`||nl(t,c.tokenEndpointAuthMethod))&&!a)throw new z(`BAD_REQUEST`,{error_description:`client registered for ${c.tokenEndpointAuthMethod} must use client_assertion`,error:`invalid_client`});if(a||(c.tokenEndpointAuthMethod!==`none`&&!r&&Rl(`client secret must be provided`,{method:s}),r&&!c.clientSecret&&Rl(`public client, client secret should not be received`,{method:s}),r&&!await Tl(e,t,c.clientSecret,r)&&Rl(`invalid client_secret`,{method:s})),Ll(c,i),o&&!Il(c,o))throw new z(`BAD_REQUEST`,{error_description:`client is not authorized to use grant type ${o}`,error:`unauthorized_client`});return c}function Bl(e){if(e)return typeof e==`string`?JSON.parse(e):e}function Vl(e){return{clientId:e?.clientId,clientSecret:e?.kind===`client_secret`?e.clientSecret:void 0,preVerified:e?.kind===`pre_verified`,authMethod:e?.method,confirmation:e?.kind===`pre_verified`?e.confirmation:void 0}}async function Hl(e,t,n){let r={...e.body??{}};await Pl(e.request,r);let i=e.request?.headers.get(`authorization`)??void 0;if(r.client_assertion_type||r.client_assertion){if(!r.client_assertion||!r.client_assertion_type)throw new z(`BAD_REQUEST`,{error_description:`client_assertion and client_assertion_type must both be provided`,error:`invalid_client`});let i=r.client_assertion,a=r.client_assertion_type,o=rl(t,a);if(o){let s=await o.strategy.authenticate({ctx:e,opts:t,assertion:i,assertionType:a,clientId:r.client_id,expectedAudience:n});return{kind:`pre_verified`,method:o.method,clientId:s.clientId,confirmation:s.confirmation}}let{verifyClientAssertion:s}=await Promise.resolve().then(()=>dg).then(e=>e.o);return{kind:`pre_verified`,method:`private_key_jwt`,clientId:(await s(e,t,i,a,r.client_id,n)).clientId}}if(i&&!kl.test(i)){let e=jl(i);if(!e)throw new z(`BAD_REQUEST`,{error:`invalid_request`,error_description:`Invalid authorization header format`});Rl(`unsupported authorization scheme`,{scheme:e})}if(i&&kl.test(i)){let e=Fl(i);if(e)return{kind:`client_secret`,method:`client_secret_basic`,clientId:e.client_id,clientSecret:e.client_secret}}return r.client_id&&r.client_secret?{kind:`client_secret`,method:`client_secret_post`,clientId:r.client_id,clientSecret:r.client_secret}:r.client_id?{kind:`public`,method:`none`,clientId:r.client_id}:null}function Ul(e){let t=e.split(` `).map(e=>e.trim()),n=new Set;for(let e of t)(e===`login`||e===`consent`||e===`create`||e===`select_account`||e===`none`)&&n.add(e);return new Set(n)}function Wl(e){let t=e.redirectUris?.[0];if(!t)throw new V(`Client has no redirect URIs for sector identifier`);return new URL(t).host}async function Gl(e,t,n){return Ga(`${Wl(t)}.${e}`,n)}async function Kl(e,t,n){return t.subjectType===`pairwise`&&n.pairwiseSecret?Gl(e,t,n.pairwiseSecret):e}function ql(e){let t=Object.create(null);for(let n of new Set(e.keys())){let r=e.getAll(n);t[n]=r.length===1?r[0]:r}return t}function Jl(e,t){if(!t)return!1;let n=ml(e);return n?n.getTime()>=t.getTime():!1}function Yl(e,t){let n=new URLSearchParams(e),r=n.get(`prompt`)?.split(` `),i=r?.findIndex(e=>e===t)??-1;return i>=0&&(r?.splice(i,1),r?.length?n.set(`prompt`,r.join(` `)):n.delete(`prompt`)),n}function Xl(e){let t=new URLSearchParams(e);return t.delete(`max_age`),t}function Zl(e,t){if(e.tokenEndpointAuthMethod===`none`)return`pkce is required for public clients`;let n=t?.scopes??[],r=n.includes(`openid`),i=typeof t?.nonce==`string`&&t.nonce.length>0,a=r&&i;return n.includes(`offline_access`)&&!a?`pkce or OIDC nonce is required when requesting offline_access scope`:e.requirePKCE??!0?`pkce is required for this client`:!1}function Ql(e){return e instanceof z||e instanceof B||e?.name===`APIError`}var $l,eu=!1;function tu(){try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncLocalStorage}catch{return}}async function nu(){if($l)return $l;let e=tu();if(e)return $l??=e,$l;try{let{AsyncLocalStorage:e}=await import(`node:async_hooks`);return $l??=e,$l}catch(e){let t=globalThis.AsyncLocalStorage;if(typeof t==`function`)return $l??=t,$l;throw typeof window<`u`?Error(`getAsyncLocalStorage is only available in server code`):(eu||(eu=!0,console.warn(`[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected.`),console.warn(`[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler`),console.warn(`[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag`)),e)}}var ru=()=>O().context.endpointContextAsyncStorage,iu=async()=>{let e=ru();if(e)return e;let t=await nu(),n=O().context;return n.endpointContextAsyncStorage??=new t};function au(){return ge()}function ou(){let e=au();if(!e)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return e}async function su(e,t){return(await iu()).run(e,t)}var cu={"Cache-Control":`no-store`,Pragma:`no-cache`};function lu(e,t){Ql(t)&&e&&Object.defineProperty(t,F,{enumerable:!1,configurable:!0,value:e,writable:!1})}var uu=Co(async()=>({})),du=Co.create({use:[uu,Co(async()=>({}))]}),fu=xo.create({use:[uu]});function pu(e,t){let n=t.metadata?.noStore===!0;return async t=>{if(n)for(let[e,n]of Object.entries(cu))t.setHeader(e,n);try{return await su(t,()=>e(t))}catch(e){throw lu(t.responseHeaders,e),e}}}function X(...e){if(e.length===3){let[t,n,r]=e;return fu(t,n,pu(r,n))}let[t,n]=e;return fu(t,pu(n,t))}function mu(e){return{...e,metadata:{...e.metadata,SERVER_ONLY:!0}}}X.serverOnly=(e,t)=>X(mu(e),t);function hu(e){return e===`-`||e===`^`||e===`$`||e===`+`||e===`.`||e===`(`||e===`)`||e===`|`||e===`[`||e===`]`||e===`{`||e===`}`||e===`*`||e===`?`||e===`\\`?`\\${e}`:e}function gu(e){let t=``;for(let n=0;n<e.length;n++)t+=hu(e[n]);return t}function _u(e,t=!0){if(Array.isArray(e))return`(?:${e.map(e=>`^${_u(e,t)}$`).join(`|`)})`;let n=``,r=``,i=`.`;t===!0?(n=`/`,r=`[/\\\\]`,i=`[^/\\\\]`):t&&(n=t,r=gu(n),r.length>1?(r=`(?:${r})`,i=`((?!${r}).)`):i=`[^${r}]`);let a=t?`${r}+?`:``,o=t?`${r}*?`:``,s=t?e.split(n):[e],c=``;for(let e=0;e<s.length;e++){let n=s[e],r=s[e+1],l=``;if(!(!n&&e>0)){if(t&&(l=e===s.length-1?o:r===`**`?``:a),t&&n===`**`)l&&(c+=e===0?``:l,c+=`(?:${i}*?${l})*?`);else{for(let e=0;e<n.length;e++){let t=n[e];t===`\\`?e<n.length-1&&(c+=hu(n[e+1]),e++):c+=t===`?`?i:t===`*`?`${i}*?`:hu(t)}c+=l}}}return c}function vu(e,t){if(typeof t!=`string`)throw TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function yu(e,t){if(typeof e!=`string`&&!Array.isArray(e))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof t==`string`||typeof t==`boolean`)&&(t={separator:t}),arguments.length===2&&!(t===void 0||typeof t==`object`&&t&&!Array.isArray(t)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if(t||={},t.separator===`\\`)throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let n=_u(e,t.separator),r=RegExp(`^${n}$`,t.flags),i=vu.bind(null,r);return i.options=t,i.pattern=e,i.regexp=r,i}var bu=47;function xu(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``).toLowerCase();return t===`localhost`||t.endsWith(`.localhost`)||t===`::1`||t.startsWith(`127.`)}function Su(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===bu;)t--;return t===e.length?e:e.slice(0,t)}function Cu(e){try{return(Su(new URL(e).pathname)||`/`)!==`/`}catch{throw new V(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function wu(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new V(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof V?t:new V(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function Tu(e,t=`/api/auth`){if(wu(e),Cu(e))return e;let n=Su(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function Eu(e,t){return!e||e.trim()===``?!1:t===`proto`?e===`http`||e===`https`:t===`host`?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function Du(e,t,n,r,i){if(e)return Tu(e,t);if(r!==!1){let e=R.BETTER_AUTH_URL||R.NEXT_PUBLIC_BETTER_AUTH_URL||R.PUBLIC_BETTER_AUTH_URL||R.NUXT_PUBLIC_BETTER_AUTH_URL||R.NUXT_PUBLIC_AUTH_URL||(R.BASE_URL===`/`?void 0:R.BASE_URL);if(e)return Tu(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&Eu(o,`proto`)&&Eu(a,`host`))try{return Tu(`${o}://${a}`,t)}catch{}if(n){let e=Ou(n.url);if(!e)throw new V(`Could not get origin from request. Please provide a valid base URL.`);return Tu(e,t)}if(typeof window<`u`&&window.location)return Tu(window.location.origin,t)}function Ou(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}function ku(e){try{return new URL(e).protocol}catch{return null}}function Au(e){try{return new URL(e).host}catch{return null}}function ju(e){return typeof e==`object`&&!!e&&`allowedHosts`in e&&Array.isArray(e.allowedHosts)}function Mu(e){if(e instanceof Request)return!0;if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Request]`)return!1;let t=e;return typeof t.url==`string`&&typeof t.headers==`object`&&t.headers!==null&&typeof t.headers.get==`function`}function Nu(e,t){let n=Mu(e)?e.headers:e;if(t){let e=n.get(`x-forwarded-host`);if(e&&Eu(e,`host`))return e}let r=n.get(`host`);if(r&&Eu(r,`host`))return r;if(Mu(e))try{return new URL(e.url).host}catch{return null}return null}function Pu(e,t,n){if(t===`http`||t===`https`)return t;let r=Mu(e)?e.headers:e;if(n){let e=r.get(`x-forwarded-proto`);if(e&&Eu(e,`proto`))return e}if(Mu(e))try{let t=new URL(e.url);if(t.protocol===`http:`||t.protocol===`https:`)return t.protocol.slice(0,-1)}catch{}let i=Nu(e,n);return i&&xu(i)?`http`:`https`}var Fu=(e,t)=>{if(!e||!t)return!1;let n=e.replace(/^https?:\/\//,``).split(`/`)[0].toLowerCase(),r=t.replace(/^https?:\/\//,``).split(`/`)[0].toLowerCase();return r.includes(`*`)||r.includes(`?`)?yu(r)(n):n.toLowerCase()===r.toLowerCase()};function Iu(e,t,n,r){let i=Nu(t,r);if(!i){if(e.fallback)return Tu(e.fallback,n);throw new V(`Could not determine host from request headers. Please provide a fallback URL in your baseURL config.`)}if(e.allowedHosts.some(e=>Fu(i,e)))return Tu(`${Pu(t,e.protocol,r)}://${i}`,n);if(e.fallback)return Tu(e.fallback,n);throw new V(`Host "${i}" is not in the allowed hosts list. Allowed hosts: ${e.allowedHosts.join(`, `)}. Add this host to your allowedHosts config or provide a fallback URL.`)}function Lu(e,t,n,r,i){if(ju(e))return n?Iu(e,n,t,i):e.fallback?Tu(e.fallback,t):Du(void 0,t,void 0,r,i);let a=Mu(n)?n:void 0;return Du(typeof e==`string`?e:void 0,t,a,r,i)}function Ru(e,t){let n;try{n=new URL(e).pathname.replace(/\/+$/,``)||`/`}catch{return`/`}let r=t.replace(/\/+$/,``);return r===``?n:n===r?`/`:n.startsWith(r+`/`)?n.slice(r.length).replace(/\/+$/,``)||`/`:n}var zu=`https://better-auth.invalid`;function Bu(e,t){let n=e.startsWith(`/`);if(e.startsWith(`//`)||e.startsWith(`/\\`))throw TypeError(`Expected an absolute or root-relative URL`);let r=n?new URL(e,zu):new URL(e);if(n&&r.origin!==zu)throw TypeError(`Expected an absolute or root-relative URL`);let i=t.toString();if(!i)return e;let a=r.search.endsWith(`&`)?``:`&`;return r.search=r.search?`${r.search}${a}${i}`:i,n?r.href.slice(r.origin.length):r.href}var Vu=[`javascript:`,`data:`,`vbscript:`],Hu=m(),Uu=p();function Wu(e){return Gu(e)||Ku(e)}function Gu(e){return n(Hu,e)}function Ku(e){return n(Uu,e)}function qu(e){let t=e.toLowerCase();if(t.startsWith(`::ffff:`)){let e=t.substring(7);if(Gu(e))return e}let n=e.split(`:`);if(n.length===7&&n[5]?.toLowerCase()===`ffff`){let e=n[6];if(e&&Gu(e))return e}if(t.includes(`::ffff:`)||t.includes(`:ffff:`)){let t=Ju(e);if(t.length===8&&t[0]===`0000`&&t[1]===`0000`&&t[2]===`0000`&&t[3]===`0000`&&t[4]===`0000`&&t[5]===`ffff`&&t[6]&&t[7])return`${Number.parseInt(t[6].substring(0,2),16)}.${Number.parseInt(t[6].substring(2,4),16)}.${Number.parseInt(t[7].substring(0,2),16)}.${Number.parseInt(t[7].substring(2,4),16)}`}return null}function Ju(e){if(e.includes(`::`)){let t=e.split(`::`),n=t[0]?t[0].split(`:`):[],r=t[1]?t[1].split(`:`):[],i=8-n.length-r.length,a=Array(i).fill(`0000`),o=n.map(e=>e.padStart(4,`0`)),s=r.map(e=>e.padStart(4,`0`));return[...o,...a,...s]}return e.split(`:`).map(e=>e.padStart(4,`0`))}function Yu(e,t){let n=Ju(e);if(t!==void 0&&t<128){let e=Math.max(0,Math.floor(t));return n.map(t=>{if(e<=0)return`0000`;if(e>=16)return e-=16,t;let n=Number.parseInt(t,16)&65535<<16-e&65535;return e=0,n.toString(16).padStart(4,`0`)}).join(`:`).toLowerCase()}return n.join(`:`).toLowerCase()}function Xu(e,t={}){if(Gu(e)||!Ku(e))return e.toLowerCase();let n=qu(e);return n?n.toLowerCase():Yu(e,t.ipv6Subnet??64)}function Zu(e){if(Gu(e))return Uint8Array.from(e.split(`.`).map(e=>Number(e)));if(!Ku(e))return null;let t=qu(e);if(t)return Uint8Array.from(t.split(`.`).map(e=>Number(e)));let n=Ju(e),r=new Uint8Array(16);for(let e=0;e<8;e++){let t=Number.parseInt(n[e]??`0`,16);r[e*2]=t>>8&255,r[e*2+1]=t&255}return r}var Qu=/^\d+$/;function $u(e){let t=e.lastIndexOf(`/`),n=Zu(t===-1?e:e.slice(0,t));if(!n)return null;let r=n.length*8;if(t===-1)return{bytes:n,prefix:r};let i=e.slice(t+1);if(!Qu.test(i))return null;let a=Number(i);return a<=r?{bytes:n,prefix:a}:null}function ed(e,t){if(e.length!==t.bytes.length)return!1;let n=t.prefix;for(let r=0;r<e.length&&n>0;r++){let i=n>=8?8:n,a=i===8?255:255<<8-i&255;if(((e[r]??0)&a)!==((t.bytes[r]??0)&a))return!1;n-=8}return!0}function td(e){return e.filter(e=>$u(e)===null)}function nd(e,t={}){let n=e.split(`,`).map(e=>e.trim()).filter(Boolean);if(n.length===0)return null;let r=(t.trustedProxies??[]).map($u).filter(e=>e!==null);if(r.length>0){for(let e=n.length-1;e>=0;e--){let i=n[e],a=i?Zu(i):null;if(!i||!a)return null;if(!r.some(e=>ed(a,e)))return Xu(i,{ipv6Subnet:t.ipv6Subnet})}return null}if(n.length!==1)return null;let i=n[0];return!i||!Wu(i)?null:Xu(i,{ipv6Subnet:t.ipv6Subnet})}var rd=`127.0.0.1`,id=[`x-forwarded-for`];function ad(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let n=`headers`in e?e.headers:e,r=t.advanced?.ipAddress?.ipAddressHeaders||id;for(let e of r){let r=`get`in n?n.get(e):n[e];if(typeof r==`string`){let e=nd(r,{ipv6Subnet:t.advanced?.ipAddress?.ipv6Subnet,trustedProxies:t.advanced?.ipAddress?.trustedProxies});if(e)return e}}return L()||fe()?rd:null}function od(e,t){return`${e}|${t}`}var sd=async()=>{let e=O(),t=e.context.requestStateAsyncStorage;if(t)return t;let n=await nu();return e.context.requestStateAsyncStorage??=new n,e.context.requestStateAsyncStorage};async function cd(){return(await sd()).getStore()!==void 0}async function ld(){let e=(await sd()).getStore();if(!e)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return e}async function ud(e,t){return(await sd()).run(e,t)}function dd(e){let t=Object.freeze({});return{get ref(){return t},async get(){let n=await ld();if(!n.has(t)){let r=await e();return n.set(t,r),r}return n.get(t)},async set(e){(await ld()).set(t,e)}}}var fd=async()=>{let e=O(),t=e.context.adapterAsyncStorage;if(t)return t;let n=await nu();return e.context.adapterAsyncStorage??=new n,e.context.adapterAsyncStorage},pd=async e=>fd().then(t=>t.getStore()?.adapter||e).catch(()=>e),md=async(e,t)=>{let n=!1;return fd().then(async r=>{n=!0;let i=[],a,o,s=!1;try{a=await r.run({adapter:e,pendingHooks:i,isTransactionActive:!1},t)}catch(e){o=e,s=!0}for(let e of i)await e();if(s)throw o;return a}).catch(e=>{if(!n)return t();throw e})},hd=async(e,t,n)=>{let r=!1;return fd().then(async i=>{if(r=!0,i.getStore()?.isTransactionActive)return t();let a=ye(e)?.();a&&await a;let o=[],s,c,l=!1;try{s=await e.transaction(async e=>(o=[],i.run({adapter:e,pendingHooks:o,isTransactionActive:!0},t)))}catch(e){l=!0,c=e}let u=async e=>{for(let t of o)try{await t()}catch(t){if(!n?.onAfterCommitHookError){if(e===`throw`)throw t;try{_e.error(`Failed to run an after-commit hook for work that could not roll back`,t)}catch{}continue}try{await n.onAfterCommitHookError(t)}catch{}}};if(l)throw e.options?.adapterConfig.transaction===!1&&await u(`log`),c;return await u(`throw`),s}).catch(e=>{if(!r)return t();throw e})},gd=async(e,t)=>{let n=async()=>{try{await e()}catch(e){if(!t?.onError)throw e;await t.onError(e)}},r;try{r=await fd()}catch{return n()}let i=r.getStore();if(!i?.isTransactionActive)return n();i.pendingHooks.push(n)},{get:_d,set:vd}=dd(()=>null),yd=async()=>await _d(),{get:bd,set:xd}=dd(()=>null),Sd=async e=>{await xd({...await bd()??{},...e})},{get:Cd,set:wd}=dd(()=>!1);function Td(e){return!!e.database||!!e.secondaryStorage}function Ed(e){return!!e.database}function Dd(e){return Ed(e)}var Od=w({id:c(),createdAt:f().default(()=>new Date),updatedAt:f().default(()=>new Date)}),kd=Od.extend({userId:be(),expiresAt:f(),token:c(),ipAddress:c().nullish(),userAgent:c().nullish()}),Ad=Od.extend({email:c().transform(e=>e.toLowerCase()),emailVerified:v().default(!1),name:c(),image:c().nullish()});function jd(e,t){if(!e||!t)return e;let n=Object.entries(t).filter(([,{returned:e}])=>e===!1).map(([e])=>e);return Object.entries(structuredClone(e)).filter(([e])=>!n.includes(e)).reduce((e,[t,n])=>({...e,[t]:n}),{})}var Md=new WeakMap;function Nd(e,t,n){let r=`${t}:${n}`;Md.has(e)||Md.set(e,new Map);let i=Md.get(e);if(i.has(r))return i.get(r);let a=n===`output`?de(e)[t]?.fields??{}:{},o=t===`user`||t===`session`||t===`account`?e[t]?.additionalFields:void 0,s={...a,...o??{}};for(let n of e.plugins||[])n.schema&&n.schema[t]&&(s={...s,...n.schema[t].fields});return i.set(r,s),s}function Pd(e,t){return jd(t,Nd(e,`user`,`output`))}function Fd(e,t){let n=Nd(e,`user`,`output`),r={};for(let e in n){let i=n[e];i.returned!==!1&&(e in t&&t[e]!==void 0?r[e]=t[e]:i.defaultValue===void 0?i.required||(r[e]=null):r[e]=typeof i.defaultValue==`function`?i.defaultValue():i.defaultValue)}return`id`in t&&(r.id=t.id),r}function Id(e,t){return jd(t,Nd(e,`session`,`output`))}function Ld(e,t){let{accessToken:n,refreshToken:r,idToken:i,accessTokenExpiresAt:a,refreshTokenExpiresAt:o,password:s,...c}=jd(t,Nd(e,`account`,`output`));return c}function Rd(e,t){let n=t.action||`create`,r=t.fields,i=Object.create(null);for(let t in r)if(t in e){if(r[t].input===!1){if(r[t].defaultValue!==void 0&&n!==`update`){i[t]=r[t].defaultValue;continue}if(e[t])throw B.from(`BAD_REQUEST`,{...as.FIELD_NOT_ALLOWED,message:`${t} is not allowed to be set`});continue}if(r[t].validator?.input&&e[t]!==void 0){let n=r[t].validator.input[`~standard`].validate(e[t]);if(n instanceof Promise)throw B.from(`INTERNAL_SERVER_ERROR`,as.ASYNC_VALIDATION_NOT_SUPPORTED);if(`issues`in n&&n.issues)throw B.from(`BAD_REQUEST`,{...as.VALIDATION_ERROR,message:n.issues[0]?.message||`Validation Error`});i[t]=n.value;continue}if(r[t].transform?.input&&e[t]!==void 0){i[t]=r[t].transform?.input(e[t]);continue}i[t]=e[t]}else if(r[t].defaultValue!==void 0&&n===`create`){if(typeof r[t].defaultValue==`function`){i[t]=r[t].defaultValue();continue}i[t]=r[t].defaultValue}else if(r[t].required&&n===`create`)throw B.from(`BAD_REQUEST`,{...as.MISSING_FIELD,message:`${t} is required`});return i}function zd(e,t={},n){return Rd(t,{fields:Nd(e,`user`,`input`),action:n})}function Bd(e,t={},n){let r=Nd(e,`user`,`input`),i=Object.create(null);for(let e of Object.keys(t))r[e]?.input!==!1&&(i[e]=t[e]);return Rd(i,{fields:r,action:n})}function Vd(e,t,n){return Rd(t,{fields:Nd(e,`session`,`input`),action:n})}function Hd(e){let t=Nd(e,`session`,`input`),n={};for(let e in t)t[e].defaultValue!==void 0&&(n[e]=typeof t[e].defaultValue==`function`?t[e].defaultValue():t[e].defaultValue);return n}function Ud(e,t){if(!t)return e;for(let n in t){let r=t[n]?.modelName;r&&(e[n].modelName=r);for(let r in e[n].fields){let i=t[n]?.fields?.[r];i&&(e[n].fields[r].fieldName=i)}}return e}var Wd=(e,t=`ms`)=>new Date(Date.now()+(t===`sec`?e*1e3:e));function Gd(e){if(e.indexOf(`%`)===-1)return e;try{return decodeURIComponent(e)}catch{return e}}var Kd=`__Secure-`;function qd(e){if(!e)return[];let t=[],n=0,r=0;for(;r<e.length;){if(e[r]===`,`){let i=r+1;for(;i<e.length&&e[i]===` `;)i++;for(;i<e.length&&e[i]!==`=`&&e[i]!==`;`&&e[i]!==`,`;)i++;if(i<e.length&&e[i]===`=`){let i=e.slice(n,r).trim();for(i&&t.push(i),n=r+1;n<e.length&&e[n]===` `;)n++;r=n;continue}}r++}let i=e.slice(n).trim();return i&&t.push(i),t}function Jd(e){let t=new Map;return qd(e).forEach(e=>{let[n,...r]=e.split(`;`).map(e=>e.trim()),[i,...a]=(n||``).split(`=`),o=Zd(a.join(`=`));if(!i)return;let s={value:Gd(o)};r.forEach(e=>{let[t,...n]=e.split(`=`),r=n.join(`=`),i=t.trim().toLowerCase();switch(i){case`max-age`:s[`max-age`]=r?parseInt(r.trim(),10):void 0;break;case`expires`:s.expires=r?new Date(r.trim()):void 0;break;case`domain`:s.domain=r?r.trim():void 0;break;case`path`:s.path=r?r.trim():void 0;break;case`secure`:s.secure=!0;break;case`httponly`:s.httponly=!0;break;case`samesite`:s.samesite=r?r.trim().toLowerCase():void 0;break;case`partitioned`:s.partitioned=!0;break;default:s[i]=!r||r.trim()}}),t.set(i,s)}),t}var Yd=/^[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E\x5F\x60\x61-\x7A\x7C\x7E]+$/,Xd=/^[\x20\x21\x23-\x3A\x3C-\x5B\x5D-\x7E]*$/;function Zd(e){return e.length<2||!e.startsWith(`"`)||!e.endsWith(`"`)?e:e.slice(1,-1)}function Qd(e){let t=0,n=e.length;for(;t<n;){let n=e.charCodeAt(t);if(n!==32&&n!==9)break;t++}for(;n>t;){let t=e.charCodeAt(n-1);if(t!==32&&t!==9)break;n--}return t===0&&n===e.length?e:e.slice(t,n)}function $d(e){let t=new Map;if(e.length<2)return t;for(let n of e.split(`;`)){let e=n.indexOf(`=`);if(e===-1)continue;let r=Qd(n.slice(0,e)),i=Zd(Qd(n.slice(e+1)));Yd.test(r)&&Xd.test(i)&&t.set(r,Gd(i))}return t}var ef=4050,tf=100;function nf(e,t){return ef-co(e,``,{...t}).length}function rf(e,t){let n=`${e}.`;if(!t.startsWith(n))return null;let r=t.slice(n.length),i=Number(r);return!Number.isSafeInteger(i)||i<0||String(i)!==r?null:i}function af(e,t){let n={},r=$d(t.headers?.get(`cookie`)||``);for(let[t,i]of r)(t===e||rf(e,t)!==null)&&(n[t]=i);return n}function of(e,t,n,r){let i=nf(`${t.name}.99`,t.attributes),a=i>0?Math.ceil(t.value.length/i):1/0;if(a<=1)return n[t.name]=t.value,[t];if(a>tf)return r.warn(`${e} cookie is too large to store even after chunking, so the cookie cache was skipped. Reduce the cached data size or avoid storing this data in cookies.`),[];let o=[];for(let e=0;e<a;e++){let r=`${t.name}.${e}`,a=e*i,s=t.value.substring(a,a+i);o.push({...t,name:r,value:s}),n[r]=s}return r.debug(`CHUNKING_${e.toUpperCase()}_COOKIE`,{message:`${e} cookie exceeds the ${ef} byte limit and was split into ${a} chunks.`,valueSize:t.value.length,chunkCount:a,chunkSizes:o.map(e=>e.value.length)}),o}function sf(e,t){let n={};for(let r in e)n[r]={name:r,value:``,attributes:{...t,maxAge:0}};return n}var cf=e=>(t,n,r)=>{let i=af(t,r),a=r.context.logger,o=()=>{let e=sf(i,n);for(let e in i)delete i[e];return e};return{chunk(r,s){let c=o(),l=of(e,{name:t,value:r,attributes:{...n,...s}},i,a);for(let e of l)c[e.name]=e;return Object.values(c)},clean(){return Object.values(o())},setCookies(e){for(let t of e)r.setCookie(t.name,t.value,t.attributes)}}},lf=cf(`Session`),uf=cf(`Account`);function df(e,t){let n=e.getCookie(t);if(n)return n;let r=[],i=e.headers?.get(`cookie`);if(!i)return null;for(let[e,n]of $d(i)){let i=rf(t,e);i!==null&&r.push({index:i,value:n})}return r.length>0?(r.sort((e,t)=>e.index-t.index),r.map(e=>e.value).join(``)):null}async function ff(e,t){let n=e.context.authCookies.accountData,r={maxAge:300,...n.attributes},i=await ji(t,e.context.secretConfig,`better-auth-account`,r.maxAge),a=uf(n.name,r,e);a.setCookies(a.chunk(i,r))}async function pf(e){let t=df(e,e.context.authCookies.accountData.name);if(t){let n=ue(await Ni(t,e.context.secretConfig,`better-auth-account`));if(n)return n}return null}var mf=s(w({disableCookieCache:xe().meta({description:`Disable cookie cache and fetch session from database`}).optional(),disableRefresh:xe().meta({description:`Disable session refresh. Useful for checking session status, without updating the session`}).optional()}));function hf(e){return!!e&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}var gf=1e3,_f=gf*60,vf=_f*60,yf=vf*24,bf=yf*7,xf=yf*30,Sf=yf*365.25,Cf=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i;function wf(e){let t=Cf.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time string format: "${e}". Use formats like "7d", "30m", "1 hour", etc.`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`years`:case`year`:case`yrs`:case`yr`:case`y`:i=n*Sf;break;case`months`:case`month`:case`mo`:i=n*xf;break;case`weeks`:case`week`:case`w`:i=n*bf;break;case`days`:case`day`:case`d`:i=n*yf;break;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:i=n*vf;break;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:i=n*_f;break;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:i=n*gf;break;default:throw TypeError(`Unknown time unit: "${r}"`)}return t[1]===`-`||t[4]===`ago`?-i:i}function Tf(e){return wf(e)}function Ef(e){return Math.round(wf(e)/1e3)}var Df=C({session:kd.loose(),user:Ad.loose(),updatedAt:d(),version:c().optional()}),Of=w({session:i(c(),o()),expiresAt:d(),signature:c()});function kf(e){let t=ue(e);if(t===null)return null;let n=Df.safeParse(t);return n.success?n.data:(_e.warn(`Cookie cache payload failed schema validation`,{issues:n.error.issues.map(({code:e,path:t})=>({code:e,path:t}))}),null)}function Af(e){let t=Of.safeParse(e);return t.success?t.data:null}var jf=new Map,Mf=new TextEncoder,Nf={decode:(e,t=`utf-8`)=>(jf.has(t)||jf.set(t,new TextDecoder(t)),jf.get(t).decode(e)),encode:e=>Mf.encode(e)},Pf=(e=`SHA-256`,t=`none`)=>{let n={importKey:async(t,n)=>Ii().importKey(`raw`,D(t),{name:`HMAC`,hash:{name:e}},!1,[n]),sign:async(e,r)=>{typeof e==`string`&&(e=await n.importKey(e,`sign`));let i=await Ii().sign(`HMAC`,e,D(r));return t===`hex`?he.encode(i):t===`base64`?te.encode(i):t===`base64url`||t===`base64urlnopad`?ve.encode(i,{padding:t!==`base64urlnopad`}):i},verify:async(e,r,i)=>(typeof e==`string`&&(e=await n.importKey(e,`verify`)),t===`hex`&&(i=typeof i==`string`?he.toBytes(i):i),(t===`base64`||t===`base64url`||t===`base64urlnopad`)&&(i=await te.decode(i)),Ii().verify(`HMAC`,e,D(i),D(r)))};return n};function Ff(e){let t=typeof e.baseURL==`string`?e.baseURL:void 0,n=typeof e.baseURL==`object`&&e.baseURL!==null?e.baseURL.protocol:void 0,r=(e.advanced?.useSecureCookies===void 0?n===`https`||n!==`http`&&(t?t.startsWith(`https://`):I):e.advanced?.useSecureCookies)?Kd:``,i=!!e.advanced?.crossSubDomainCookies?.enabled,a=i?e.advanced?.crossSubDomainCookies?.domain||(t?new URL(t).hostname:void 0):void 0;if(i&&!a&&!ju(e.baseURL))throw new V(`baseURL is required when crossSubdomainCookies are enabled.`);function o(t,n={}){let o=e.advanced?.cookiePrefix||`better-auth`,s=e.advanced?.cookies?.[t]?.name||`${o}.${t}`,c=e.advanced?.cookies?.[t]?.attributes??{};return{name:`${r}${s}`,attributes:{secure:!!r,sameSite:`lax`,path:`/`,httpOnly:!0,...i?{domain:a}:{},...e.advanced?.defaultCookieAttributes,...n,...c}}}return o}function If(e){let t=Ff(e),n=t(`session_token`,{maxAge:e.session?.expiresIn||Ef(`7d`)}),r=t(`session_data`,{maxAge:e.session?.cookieCache?.maxAge||300}),i=t(`account_data`,{maxAge:e.session?.cookieCache?.maxAge||300}),a=t(`dont_remember`);return{sessionToken:{name:n.name,attributes:n.attributes},sessionData:{name:r.name,attributes:r.attributes},dontRememberToken:{name:a.name,attributes:a.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function Lf(e,t,n){if(!e.context.options.session?.cookieCache?.enabled)return;let r=jd(t.session,e.context.options.session?.additionalFields),i=Pd(e.context.options,t.user),a=e.context.options.session?.cookieCache?.version,o=`1`;if(a){if(typeof a==`string`)o=a;else if(typeof a==`function`){let e=a(t.session,t.user);o=hf(e)?await e:e}}let s={session:r,user:i,updatedAt:Date.now(),version:o},c={...e.context.authCookies.sessionData.attributes,maxAge:n?void 0:e.context.authCookies.sessionData.attributes.maxAge},l=Wd(c.maxAge||60,`sec`).getTime(),u=e.context.options.session?.cookieCache?.strategy||`compact`,d;if(u===`jwe`)d=await ji(s,e.context.secretConfig,`better-auth-session`,c.maxAge||300);else if(u===`jwt`){let t=e.context.sessionConfig.cookieCacheSigner;d=t?await t.sign(e,s,c.maxAge||300):await Si(s,e.context.secret,c.maxAge||300)}else d=ve.encode(JSON.stringify({session:s,expiresAt:l,signature:await Pf(`SHA-256`,`base64urlnopad`).sign(e.context.secret,JSON.stringify({...s,expiresAt:l}))}),{padding:!1});let f=lf(e.context.authCookies.sessionData.name,c,e);if(f.setCookies(f.chunk(d,c)),e.context.options.account?.storeAccountCookie&&!Vf(e,e.context.authCookies.accountData.name)){let n=await pf(e);if(n){if(!Dd(e.context.options)||n.userId===t.user.id)await ff(e,n);else{Hf(e,e.context.authCookies.accountData);let t=uf(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e);t.setCookies(t.clean())}}}}async function Rf(e,t){let n=e.context.options.session?.cookieCache?.strategy||`compact`;if(n===`jwe`){let n=await Ni(t,e.context.secretConfig,`better-auth-session`),r=kf(n);return r?{session:r,expiresAt:n?.exp?n.exp*1e3:Date.now()}:null}if(n===`jwt`){let n=e.context.sessionConfig.cookieCacheSigner;if(n){let r=await n.verify(e,t);return r?{session:r.payload,expiresAt:r.expiresAt}:null}let r=await Ci(t,e.context.secret),i=kf(r);return i?{session:i,expiresAt:r?.exp?r.exp*1e3:Date.now()}:null}let r=Af(ue(Nf.decode(ve.decode(t))));if(!r||!await Pf(`SHA-256`,`base64urlnopad`).verify(e.context.secret,JSON.stringify({...r.session,expiresAt:r.expiresAt}),r.signature))return null;let i=kf(r.session);return i?{session:i,expiresAt:r.expiresAt}:null}async function zf(e,t,n,r){let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);n=n===void 0?!!i:n;let a=e.context.authCookies.sessionToken.attributes,o=n?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...a,maxAge:o,...r}),n&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,`true`,e.context.secret,e.context.authCookies.dontRememberToken.attributes),await Lf(e,t,n),e.context.setNewSession(t)}function Bf(e,t){let n=e,r=new Set;n.responseHeaders&&r.add(n.responseHeaders),n.context?.responseHeaders&&r.add(n.context.responseHeaders);let i=`${t}=`,a=`${t}.`;for(let e of r){let t=typeof e.getSetCookie==`function`?e.getSetCookie():qd(e.get(`set-cookie`)||``);if(!t.length)continue;let n=t.filter(e=>!e.startsWith(i)&&!e.startsWith(a));if(n.length!==t.length){e.delete(`set-cookie`);for(let t of n)e.append(`set-cookie`,t)}}}function Vf(e,t){let n=e,r=new Set;n.responseHeaders&&r.add(n.responseHeaders),n.context?.responseHeaders&&r.add(n.context.responseHeaders);let i=`${t}=`,a=`${t}.`;for(let e of r)if((typeof e.getSetCookie==`function`?e.getSetCookie():qd(e.get(`set-cookie`)||``)).some(e=>e.startsWith(i)||e.startsWith(a)))return!0;return!1}function Hf(e,t){Bf(e,t.name),e.setCookie(t.name,``,{...t.attributes,maxAge:0})}function Uf(e,t){if(Hf(e,e.context.authCookies.sessionToken),Hf(e,e.context.authCookies.sessionData),e.context.options.account?.storeAccountCookie){Hf(e,e.context.authCookies.accountData);let t=uf(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e),n=t.clean();t.setCookies(n)}e.context.oauthConfig.storeStateStrategy===`cookie`&&Hf(e,e.context.createAuthCookie(`oauth_state`));let n=lf(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e),r=n.clean();n.setCookies(r),t||Hf(e,e.context.authCookies.dontRememberToken)}var Wf=()=>X(`/get-session`,{method:[`GET`,`POST`],operationId:`getSession`,query:mf,requireHeaders:!0,metadata:{openapi:{operationId:`getSession`,description:`Get the current session`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:[`object`,`null`],properties:{session:{$ref:`#/components/schemas/Session`},user:{$ref:`#/components/schemas/User`}},required:[`session`,`user`]}}}}}}}},async e=>{e.setHeader(`cache-control`,`no-store`),e.setHeader(`pragma`,`no-cache`);let t=e.context.options.session?.deferSessionRefresh,n=e.method===`POST`;if(n&&!t)throw B.from(`METHOD_NOT_ALLOWED`,as.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let r=e.context.options.session?.cookieCache?.enabled===!0,i=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!i&&r)return null;let a=df(e,e.context.authCookies.sessionData.name);if(a&&!r){let t=lf(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e);t.setCookies(t.clean())}if(!i)return null;let o=r&&!e.query?.disableCookieCache,s=o&&a?await Rf(e,a):null;o&&a&&!s&&Hf(e,e.context.authCookies.sessionData);let c=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(s?.session){let t=s.session,n=t.session.token!==i;if(!n){let r=e.context.options.session?.cookieCache?.version,i=`1`;if(r){if(typeof r==`string`)i=r;else if(typeof r==`function`){let e=r(t.session,t.user);i=e instanceof Promise?await e:e}}n=(t.version||`1`)!==i}if(!n){let e=Date.now(),r=new Date(t.session.expiresAt).getTime();n=s.expiresAt<e||!Number.isFinite(r)||r<e}if(n)Hf(e,e.context.authCookies.sessionData);else{let n=e.context.sessionConfig.cookieRefreshCache;if(n===!1){e.context.session=t;let n=Id(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),r=Pd(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.json({session:n,user:r})}let r=s.expiresAt-Date.now(),i=n.updateAge*1e3,a=await Cd();if(r<i&&!a){let n={session:{...t.session},user:t.user,updatedAt:Date.now()};await Lf(e,n,!1);let r=e.context.authCookies.sessionToken.attributes,i=c?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...r,maxAge:i});let a=Id(e.context.options,{...n.session,expiresAt:new Date(n.session.expiresAt),createdAt:new Date(n.session.createdAt),updatedAt:new Date(n.session.updatedAt)}),o=Pd(e.context.options,{...n.user,createdAt:new Date(n.user.createdAt),updatedAt:new Date(n.user.updatedAt)});return e.context.session={session:a,user:o},e.json({session:a,user:o})}let o=Id(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),l=Pd(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.context.session={session:o,user:l},e.json({session:o,user:l})}}let l=await e.context.internalAdapter.findSession(i);if(e.context.session=l,!l||l.session.expiresAt<new Date)return Uf(e),l&&(!t||n)&&await e.context.internalAdapter.deleteSession(l.session.token),e.json(null);if(c||e.query?.disableRefresh){let t=Id(e.context.options,l.session),n=Pd(e.context.options,l.user);return e.json({session:t,user:n})}let u=e.context.sessionConfig.expiresIn,d=e.context.sessionConfig.updateAge,f=l.session.expiresAt.valueOf()-u*1e3+d*1e3<=Date.now(),p=e.query?.disableRefresh||e.context.options.session?.disableSessionRefresh,m=await Cd(),h=f&&!p&&!m;if(t&&!n){await Lf(e,l,!!c);let t=Id(e.context.options,l.session),n=Pd(e.context.options,l.user);return e.json({session:t,user:n,needsRefresh:h})}if(h){let t=await e.context.internalAdapter.updateSession(l.session.token,{expiresAt:Wd(e.context.sessionConfig.expiresIn,`sec`),updatedAt:new Date});if(!t)throw Uf(e),B.from(`UNAUTHORIZED`,as.FAILED_TO_GET_SESSION);let n=e.context.sessionConfig.expiresIn;await zf(e,{session:t,user:l.user},!1,{maxAge:n});let r=Id(e.context.options,t),i=Pd(e.context.options,l.user);return e.json({session:r,user:i})}await Lf(e,l,!!c);let g=Id(e.context.options,l.session),_=Pd(e.context.options,l.user);return e.json({session:g,user:_})}catch(t){throw Ql(t)?t:(e.context.logger.error(`INTERNAL_SERVER_ERROR`,t),B.from(`INTERNAL_SERVER_ERROR`,as.FAILED_TO_GET_SESSION))}}),Gf=e=>Td(e.context.options),Z=async(e,t)=>{if(e.context.session)return e.context.session;let n=await Wf()({...e,method:`GET`,asResponse:!1,headers:e.headers,returnHeaders:!0,returnStatus:!1,query:{...t,...e.query,disableCookieCache:t?.disableCookieCache||e.query?.disableCookieCache,disableRefresh:t?.disableRefresh||e.query?.disableRefresh}}).catch(()=>null);return n?(n.headers&&n.headers.forEach((t,n)=>{let r=n.toLowerCase();r!==`cache-control`&&r!==`pragma`&&(r===`set-cookie`?e.responseHeaders.append(n,t):e.responseHeaders.set(n,t))}),e.context.session=n.response,n.response):(e.context.session=null,null)},Kf=async e=>Gf(e)?(e.context.session=null,Z(e,{disableCookieCache:!0})):Z(e),qf=du(async e=>{let t=await Z(e);if(!t?.session)throw B.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}}),Jf=du(async e=>{let t=await Kf(e);if(!t?.session)throw B.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}});du(async e=>{let t=await Z(e);if(!t?.session&&(e.request||e.headers))throw B.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}});var Yf=du(async e=>{let t=await Z(e);if(!t?.session)throw B.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});if(e.context.sessionConfig.freshAge!==0){let n=new Date(t.session.createdAt).getTime(),r=e.context.sessionConfig.freshAge*1e3;if(Date.now()-n>=r)throw B.from(`FORBIDDEN`,as.SESSION_NOT_FRESH)}return{session:t}}),Xf=()=>X(`/list-sessions`,{method:`GET`,operationId:`listUserSessions`,use:[Yf],requireHeaders:!0,metadata:{openapi:{operationId:`listUserSessions`,description:`List all active sessions for the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`array`,items:{$ref:`#/components/schemas/Session`}}}}}}}}},async e=>{try{let t=(await e.context.internalAdapter.listSessions(e.context.session.user.id,{onlyActiveSessions:!0})).filter(e=>e.expiresAt>new Date);return e.json(t.map(t=>Id(e.context.options,t)))}catch(t){throw e.context.logger.error(t),e.error(`INTERNAL_SERVER_ERROR`)}}),Zf=X(`/revoke-session`,{method:`POST`,body:w({token:c().meta({description:`The token to revoke`})}),use:[Jf],requireHeaders:!0,metadata:{openapi:{description:`Revoke a single session`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`,description:`The token to revoke`}},required:[`token`]}}}},responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if the session was revoked successfully`}},required:[`status`]}}}}}}}},async e=>{let t=e.body.token;if((await e.context.internalAdapter.findSession(t))?.session.userId===e.context.session.user.id)try{await e.context.internalAdapter.deleteSession(t)}catch(t){throw e.context.logger.error(t&&typeof t==`object`&&`name`in t?t.name:``,t),B.from(`INTERNAL_SERVER_ERROR`,{message:`Internal Server Error`,code:`INTERNAL_SERVER_ERROR`})}return e.json({status:!0})}),Qf=X(`/revoke-sessions`,{method:`POST`,use:[Jf],requireHeaders:!0,metadata:{openapi:{description:`Revoke all sessions for the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if all sessions were revoked successfully`}},required:[`status`]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteUserSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t==`object`&&`name`in t?t.name:``,t),B.from(`INTERNAL_SERVER_ERROR`,{message:`Internal Server Error`,code:`INTERNAL_SERVER_ERROR`})}return e.json({status:!0})}),$f=X(`/revoke-other-sessions`,{method:`POST`,requireHeaders:!0,use:[Jf],metadata:{openapi:{description:`Revoke all other sessions for the user except the current one`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if all other sessions were revoked successfully`}},required:[`status`]}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw B.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(e=>e.expiresAt>new Date).filter(t=>t.token!==e.context.session.session.token);return await Promise.all(n.map(t=>e.context.internalAdapter.deleteSession(t.token))),e.json({status:!0})}),ep=`better_auth.operation_id`,tp=`better_auth.hook.type`,np=`better_auth.context`;function rp(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function ip(e,t,n=`.`,r){if(!rp(t))return ip(e,{},n,r);let i={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let a=e[t];a!=null&&(r&&r(i,t,a,n)||(i[t]=Array.isArray(a)&&Array.isArray(i[t])?[...a,...i[t]]:rp(a)&&rp(i[t])?ip(a,i[t],(n?`${n}.`:``)+t.toString(),r):a))}return i}function ap(e){return(...t)=>t.reduce((t,n)=>ip(t,n,``,e),{})}var op=ap(),sp=new Set([`metadata.google.internal`,`metadata.goog`,`metadata`,`instance-data`,`instance-data.ec2.internal`]);function cp(e){return e.length>=2&&e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e}function lp(e){if(e.startsWith(`[`)){let t=e.indexOf(`]`);return t===-1?e:e.slice(0,t+1)}let t=e.indexOf(`:`);return t===-1||e.indexOf(`:`,t+1)!==-1?e:e.slice(0,t)}function up(e){let t=e.indexOf(`%`);return t===-1?e:e.slice(0,t)}function dp(e){return e.replace(/\.+$/,``)}function fp(e){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function pp(e){let t=e.split(`.`);return(Number(t[0])<<24|Number(t[1])<<16|Number(t[2])<<8|Number(t[3]))>>>0}function mp(e,t,n){if(n===0)return!0;let r=n===32?4294967295:-1<<32-n>>>0;return(e&r)===(t&r)}function hp(e){if(e===`0.0.0.0`)return`unspecified`;if(e===`255.255.255.255`)return`broadcast`;let t=pp(e);return mp(t,pp(`127.0.0.0`),8)?`loopback`:mp(t,pp(`10.0.0.0`),8)||mp(t,pp(`172.16.0.0`),12)||mp(t,pp(`192.168.0.0`),16)?`private`:mp(t,pp(`169.254.0.0`),16)?`linkLocal`:mp(t,pp(`100.64.0.0`),10)?`sharedAddressSpace`:mp(t,pp(`192.0.2.0`),24)||mp(t,pp(`198.51.100.0`),24)||mp(t,pp(`203.0.113.0`),24)?`documentation`:mp(t,pp(`198.18.0.0`),15)?`benchmarking`:mp(t,pp(`224.0.0.0`),4)?`multicast`:mp(t,pp(`0.0.0.0`),8)||mp(t,pp(`192.0.0.0`),24)||mp(t,pp(`192.88.99.0`),24)||mp(t,pp(`240.0.0.0`),4)?`reserved`:`public`}function gp(e,t,n={}){let r=t*5,i=Number.parseInt(e.slice(r,r+4),16),a=Number.parseInt(e.slice(r+5,r+9),16);if(!Number.isFinite(i)||!Number.isFinite(a))return null;let o=(i<<16|a)>>>0;return n.xor&&(o=(o^4294967295)>>>0),`${o>>>24&255}.${o>>>16&255}.${o>>>8&255}.${o&255}`}function _p(e){if(e===`0000:0000:0000:0000:0000:0000:0000:0000`)return`unspecified`;if(e===`0000:0000:0000:0000:0000:0000:0000:0001`)return`loopback`;let t=Number.parseInt(e.slice(0,2),16),n=Number.parseInt(e.slice(2,4),16);if(t===255)return`multicast`;if(t===254&&(n&192)==128)return`linkLocal`;if(t===254&&(n&192)==192)return`reserved`;if((t&254)==252)return`private`;if(e.startsWith(`2001:0db8:`))return`documentation`;if(e.startsWith(`2001:0002:0000:`))return`benchmarking`;if(e.startsWith(`2002:`)){let t=gp(e,1);return t&&hp(t)!==`public`?`reserved`:`public`}if(e.startsWith(`0064:ff9b:0000:0000:0000:0000:`)){let t=gp(e,6);return t&&hp(t),`reserved`}if(e.startsWith(`0064:ff9b:0001:`))return`reserved`;if(e.startsWith(`2001:0000:`)){let t=gp(e,6,{xor:!0});return t&&hp(t),`reserved`}return e.startsWith(`0100:0000:0000:0000:`)?`reserved`:e.startsWith(`3fff:0`)?`documentation`:e.startsWith(`5f00:`)||e.startsWith(`0000:0000:0000:0000:0000:0000:`)?`reserved`:`public`}function vp(e){let t=dp(up(cp(lp(e.trim())))).toLowerCase();if(t===``)return{kind:`reserved`,literal:`fqdn`,canonical:``};if(!Wu(t))return t===`localhost`||t.endsWith(`.localhost`)?{kind:`localhost`,literal:`fqdn`,canonical:t}:sp.has(t)?{kind:`cloudMetadata`,literal:`fqdn`,canonical:t}:{kind:`public`,literal:`fqdn`,canonical:t};if(fp(t))return{kind:hp(t),literal:`ipv4`,canonical:t};let n=Xu(t,{ipv6Subnet:128});return fp(n)?{kind:hp(n),literal:`ipv4`,canonical:n}:{kind:_p(n),literal:`ipv6`,canonical:n}}function yp(e){return vp(e).kind===`loopback`}function bp(e){let t=vp(e).kind;return t===`loopback`||t===`localhost`}function xp(e){return vp(e).kind===`public`}var Sp=ap((e,t,n)=>{if(Array.isArray(e[t])&&Array.isArray(n))return e[t]=n,!0}),Cp=new WeakMap;function wp(e,t){let n=e.options;return n?.operationId??n?.metadata?.openapi?.operationId??t??e.path??`/:virtual`}function Tp(e,t){t&&t.forEach((t,n)=>{e.responseHeaders?n.toLowerCase()===`set-cookie`?e.responseHeaders.append(n,t):e.responseHeaders.set(n,t):e.responseHeaders=new Headers({[n]:t})})}function Ep(e){let t=e[F],n=e.headers&&e.headers!==t?new Headers(e.headers):null;if(!t&&!n)return null;let r=new Headers;return t?.forEach((e,t)=>{r.append(t,e)}),n?.forEach((e,t)=>{t.toLowerCase()===`set-cookie`?r.append(t,e):r.set(t,e)}),r}async function Dp(e,t,n,r){let i=le(e.context.options),a={};for(let o of t){let t=!1;try{t=o.matcher(e)}catch(t){let n=Cp.get(o.handler)??`unknown`;throw e.context.logger.error(`An error occurred during ${n} hook matcher execution:`,t),new B(`INTERNAL_SERVER_ERROR`,{message:`An error occurred during hook matcher execution. Check the logs for more details.`})}if(!t)continue;let s=Cp.get(o.handler)??`unknown`,c=n.path??`/:virtual`,l=await i(`hook before ${c} ${s}`,{[tp]:`before`,[pe]:c,[np]:s,[ep]:r},()=>o.handler({...e,returnHeaders:!0})).catch(t=>{throw Ql(t)&&ne(e.context.logger.level,`debug`)&&(t.stack=t.errorStack),t});Tp(e.context,l?.headers);let u=l?.response;if(u&&typeof u==`object`){if(`context`in u&&typeof u.context==`object`){let{headers:e,...t}=u.context;e instanceof Headers&&(a.headers?e.forEach((e,t)=>{a.headers?.set(t,e)}):a.headers=e),a=Sp(t,a);continue}return u}}return{context:a}}async function Op(e,t,n,r){let i=le(e.context.options);for(let a of t){if(!a.matcher(e))continue;let t=Cp.get(a.handler)??`unknown`,o=n.path??`/:virtual`,s=await i(`hook after ${o} ${t}`,{[tp]:`after`,[pe]:o,[np]:t,[ep]:r},()=>a.handler(e)).catch(t=>{if(Ql(t))return ne(e.context.logger.level,`debug`)&&(t.stack=t.errorStack),{response:t,headers:Ep(t)};throw t});Tp(e.context,s.headers),s.response!==void 0&&(e.context.returned=s.response)}return{response:e.context.returned,headers:e.context.responseHeaders}}function kp(e){let t=e.options.plugins||[],n=[],r=[],i=e.options.hooks?.before;i&&(Cp.set(i,`user`),n.push({matcher:()=>!0,handler:i}));let a=e.options.hooks?.after;a&&(Cp.set(a,`user`),r.push({matcher:()=>!0,handler:a}));let o=t.flatMap(e=>(e.hooks?.before??[]).map(t=>(Cp.set(t.handler,`plugin:${e.id}`),t))),s=t.flatMap(e=>(e.hooks?.after??[]).map(t=>(Cp.set(t.handler,`plugin:${e.id}`),t)));return o.length&&n.push(...o),s.length&&r.push(...s),{beforeHooks:n,afterHooks:r}}async function Ap(e,t){let n=le(t.context.options),r=t.operationId??wp(e),i=e.path??`/:virtual`,a=e.options?.method,o=Array.isArray(a)?a[0]:a,s=t.method??t.request?.method??o??`?`,c=t.asResponse??Mu(t.request),l={...t,context:{...t.context,returned:void 0,responseHeaders:void 0,session:t.context.session??null},path:e.path,headers:t.headers?new Headers(t.headers):void 0};return n(`${s} ${i}`,{[pe]:i,[ep]:r},async()=>su(l,async()=>{let{beforeHooks:a,afterHooks:o}=kp(l.context),s=await Dp(l,a,e,r);if(`context`in s&&s.context&&typeof s.context==`object`){let{headers:e,...t}=s.context;if(e){l.headers||(l.headers=new Headers);let t=l.headers;e.forEach((e,n)=>{t.set(n,e)})}l=Sp(t,l)}else if(s){let e=l.context.responseHeaders;return c?bo(s,{headers:e}):t.returnHeaders?{headers:e,response:s}:s}l.asResponse=!1,l.returnHeaders=!0,l.returnStatus=!0;let u=await su(l,()=>n(`handler ${i}`,{[pe]:i,[ep]:r},()=>e(l))).catch(e=>{if(Ql(e))return{response:e,status:e.statusCode,headers:Ep(e)};throw e});if(u instanceof Response)return u;l.context.returned=u.response,l.context.responseHeaders=u.headers??void 0;let d=await Op(l,o,e,r);if(d.response!==void 0&&(u.response=d.response),u.headers=d.headers??u.headers,Ql(u.response)&&ne(l.context.logger.level,`debug`)&&(u.response.stack=u.response.errorStack),Ql(u.response)&&!c)throw u.headers&&Object.defineProperty(u.response,F,{enumerable:!1,configurable:!0,writable:!1,value:u.headers}),u.response;return c?bo(u.response,{headers:u.headers??void 0,status:u.status}):t.returnHeaders?t.returnStatus?{headers:u.headers,response:u.response,status:u.status}:{headers:u.headers,response:u.response}:t.returnStatus?{response:u.response,status:u.status}:u.response}))}var jp=/^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i,Mp=new Set([`http:`,`https:`,`ws:`,`wss:`,`file:`,`ftp:`,`mailto:`,`javascript:`,`data:`,`vbscript:`,`blob:`,`about:`,`view-source:`]);function Np(e){let t=e.protocol.slice(0,-1),n=e.href.slice(e.protocol.length);return e.protocol!==`http:`&&e.protocol!==`https:`&&e.host.length===0&&n.startsWith(`/`)&&!n.startsWith(`//`)&&jp.test(t)}function Pp(e){return Mp.has(e.protocol)||e.host.length===0?!1:e.pathname.startsWith(`/`)}function Fp(e){return Np(e)||Pp(e)}var Q=_().superRefine((e,n)=>{let r;try{r=new URL(e)}catch{return n.addIssue({code:`custom`,message:`URL must be parseable`,fatal:!0}),t}Vu.includes(r.protocol)?n.addIssue({code:`custom`,message:`URL cannot use javascript:, data:, or vbscript: scheme`}):(e.includes(`#`)&&n.addIssue({code:`custom`,message:`Redirect URI must not contain a fragment component`}),r.protocol===`http:`&&!bp(r.host)&&n.addIssue({code:`custom`,message:`Redirect URI must use HTTPS (HTTP allowed only for loopback hosts)`}))}),Ip=(e,t)=>({getAllKeys:async n=>t?.adapter?.getJwks?await t.adapter.getJwks(n):await(await pd(e)).findMany({model:`jwks`}),getLatestKey:async n=>{let r=new Date,i=e=>!e.expiresAt||e.expiresAt>r;return t?.adapter?.getJwks?(await t.adapter.getJwks(n))?.filter(i).sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())[0]:(await(await pd(e)).findMany({model:`jwks`}))?.filter(i).sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())[0]},getKeyById:async(n,r)=>t?.adapter?.getJwks?(await t.adapter.getJwks(n))?.find(e=>e.id===r):await(await pd(e)).findOne({model:`jwks`,where:[{field:`id`,value:r}]})??void 0,getLatestKeyByAlg:async(n,r)=>{let i=t?.adapter?.getJwks?await t.adapter.getJwks(n):await(await pd(e)).findMany({model:`jwks`});if(!i)return;let a=t?.jwks?.keyPairConfig?.alg??`EdDSA`,o=new Date;return i.filter(e=>e.alg===r||e.alg==null&&a===r).filter(e=>!e.expiresAt||e.expiresAt>o).sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())[0]},createJwk:async(n,r)=>t?.adapter?.createJwk?await t.adapter.createJwk(r,n):await(await pd(e)).create({model:`jwks`,data:{...r,createdAt:new Date}})});function Lp(e,t){return typeof e==`number`?e:e instanceof Date?Math.floor(e.getTime()/1e3):t+Ef(e)}async function Rp(e){let{alg:t,...n}=e?.jwks?.keyPairConfig??{alg:`EdDSA`,crv:`Ed25519`},{publicKey:r,privateKey:i}=await xi(t,{...n,extractable:!0});return{publicWebKey:await ui(r),privateWebKey:await ui(i),alg:t,cfg:n}}async function zp(e,t){let{publicWebKey:n,privateWebKey:r,alg:i,cfg:a}=await Rp(t),o=a&&`crv`in a?a.crv:void 0,s=typeof n.crv==`string`?n.crv:void 0,c=o??s,l=JSON.stringify(r),u=!t?.jwks?.disablePrivateKeyEncryption,d={alg:i,...c?{crv:c}:{},publicKey:JSON.stringify(n),privateKey:u?JSON.stringify(await Ha({key:e.context.secretConfig,data:l})):l,createdAt:new Date,...t?.jwks?.rotationInterval?{expiresAt:new Date(Date.now()+t.jwks.rotationInterval*1e3)}:{}};return await Ip(e.context.adapter,t).createJwk(e,d)}async function Bp(e,t,n){if(t?.jwt?.sign)return null;let r=Ip(e.context.adapter,t),i;if(n?.signingKeyId!==void 0){if(i=await r.getKeyById(e,n.signingKeyId),!i)throw new V(`signJWT: signingKeyId "${n.signingKeyId}" not found in JWKS. The key must be provisioned before it can be referenced.`);if(n.signingAlgorithm!==void 0){let e=t?.jwks?.keyPairConfig?.alg??`EdDSA`;if((i.alg??e)!==n.signingAlgorithm)throw new V(`signJWT: signingKeyId "${n.signingKeyId}" has alg "${i.alg??`unset (inherits keyPairConfig.alg "${e}")`}" but signingAlgorithm was set to "${n.signingAlgorithm}".`)}}else if(n?.signingAlgorithm!==void 0){if(i=await r.getLatestKeyByAlg(e,n.signingAlgorithm),!i){let r=t?.jwks?.keyPairConfig?.alg??`EdDSA`,a=t?.jwks?.keyPairConfigs?.find(e=>e.alg===n.signingAlgorithm),o=r===n.signingAlgorithm;if(a||o)i=await zp(e,{...t,jwks:{...t?.jwks,keyPairConfig:a??t?.jwks?.keyPairConfig}});else{let e=t?.jwks?.keyPairConfigs?.map(e=>e.alg).join(`, `)||`none`;throw new V(`signJWT: no key with alg "${n.signingAlgorithm}" found in JWKS. The plugin auto-mints only one key matching keyPairConfig.alg="${r}"; additional algs configured via keyPairConfigs: ${e}. Add "${n.signingAlgorithm}" to jwks.keyPairConfigs so the plugin provisions it on first use, or mint the key explicitly via createJwk().`)}}}else{let n=t?.jwks?.keyPairConfig?.alg??`EdDSA`;i=await r.getLatestKeyByAlg(e,n)??await r.getLatestKey(e)}if(!i||i.expiresAt&&i.expiresAt<new Date){if(n?.signingKeyId!==void 0||n?.signingAlgorithm!==void 0)throw new V(`signJWT: requested signing key is expired and an explicit kid/alg was provided; not auto-minting a replacement. Rotate the key explicitly.`);i=await zp(e,t)}let a=t?.jwks?.disablePrivateKeyEncryption?i.privateKey:await Ua({key:e.context.secretConfig,data:JSON.parse(i.privateKey)}).catch(()=>{throw new V(`Failed to decrypt private key. Make sure the secret currently in use is the same as the one used to encrypt the private key. If you are using a different secret, either clean up your JWKS or disable private key encryption.`)}),o=i.alg??t?.jwks?.keyPairConfig?.alg??`EdDSA`,s=await _i(JSON.parse(a),o);return{alg:o,kid:i.id,privateKey:s}}async function Vp(e,t){let{options:n}=t,r=t.payload,i=Math.floor(Date.now()/1e3),a=r.iat,o=r.exp,s=Lp(n?.jwt?.expirationTime??`15m`,a??i);o??=s;let c=r.nbf,l=typeof e.context.options.baseURL==`string`?e.context.options.baseURL:``,u=r.iss,d=n?.jwt?.issuer??l,f=r.aud,p=n?.jwt?.audience??l;if(n?.jwt?.sign){let e={...r,iat:a,exp:o,nbf:c,iss:u??d,aud:f??p};return n.jwt.sign(e,t.header,{signingKeyId:t.signingKeyId,signingAlgorithm:t.signingAlgorithm})}let{alg:m,kid:h,privateKey:g}=t.resolvedKey??await Bp(e,n,{signingKeyId:t.signingKeyId,signingAlgorithm:t.signingAlgorithm}),_=new Kr(r).setProtectedHeader({...t.header,alg:m,kid:h}).setExpirationTime(o).setIssuer(u??d).setAudience(f??p);return a&&_.setIssuedAt(a),r.sub&&_.setSubject(r.sub),r.nbf&&_.setNotBefore(r.nbf),r.jti&&_.setJti(r.jti),await _.sign(g)}async function Hp(e,t){let n=t?.jwt?.definePayload?await t.jwt.definePayload(e.context.session):e.context.session.user;return await Vp(e,{options:t,payload:{iat:Math.floor(Date.now()/1e3),...n,sub:await t?.jwt?.getSubject?.(e.context.session)??e.context.session.user.id}})}var Up=new Set([`iss`,`sub`,`aud`,`exp`,`nbf`,`iat`,`jti`,`auth_time`,`nonce`,`acr`,`amr`,`azp`,`sid`,`at_hash`,`c_hash`,`s_hash`]);function Wp(e){if(!e)return{};let t=[],n=Object.create(null);for(let[r,i]of Object.entries(e))Up.has(r)?t.push(r):n[r]=i;return t.length>0&&_e.warn(`oauth-provider: stripped reserved id-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}var Gp=i(c(),o()).nullable(),Kp=C({essential:v().optional(),value:c().optional(),values:x(c()).optional()}).nullable(),qp=w({acr:Kp.optional()}).catchall(Gp),Jp=C({userinfo:i(c(),Gp).optional(),id_token:qp.optional()});function Yp(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return}return e}function Xp(e){let t=Yp(e),n=Jp.safeParse(t);return n.success?n.data:void 0}var Zp=a([c(),i(c(),o())]),Qp=Zp,$p=Zp.refine(e=>Xp(e)!==void 0,{error:`claims must be a valid Claims request object`});function em(e){return e===void 0||Xp(e)!==void 0}function tm(e,t){let n=Xp(e)?.userinfo;if(!n)return[];let r=Object.keys(n);if(!t)return r;let i=new Set(t);return r.filter(e=>i.has(e))}function nm(e,t){let n=Xp(e);if(!n)return e===void 0;let r=n.id_token?.acr;if(!r||r.essential!==!0)return!0;let i=r.value===void 0||r.value===t,a=r.values===void 0||r.values.includes(t);return i&&a}function rm(e,t){let n=Xp(e);if(!n)return;let r=new Set(t),i=Object.fromEntries(Object.entries(n.userinfo??{}).filter(([e])=>r.has(e))),a=Object.keys(i).length?{...n,userinfo:i}:Object.fromEntries(Object.entries(n).filter(([e])=>e!==`userinfo`));return Object.keys(a).length?a:void 0}function im(e){let t=e.split(` `).filter(e=>e!==``);return t.length<=1?{}:{given:t.slice(0,-1).join(` `),family:t.at(-1)}}var am={name:{scope:`profile`,resolve:e=>e.name??void 0},picture:{scope:`profile`,resolve:e=>e.image??void 0},given_name:{scope:`profile`,resolve:e=>im(e.name).given},family_name:{scope:`profile`,resolve:e=>im(e.name).family},email:{scope:`email`,resolve:e=>e.email??void 0},email_verified:{scope:`email`,resolve:e=>e.emailVerified??!1}},om=Object.keys(am);function sm(e){return e.advertisedMetadata?.claims_supported??e.claims??[]}var cm=new Set([`iss`,`sub`,`aud`,`exp`,`iat`,`jti`,`client_id`,`scope`,`auth_time`,`acr`,`amr`,`cnf`]);function lm(e){if(!e)return{};let t=[],n={};for(let[r,i]of Object.entries(e))cm.has(r)?t.push(r):n[r]=i;return t.length>0&&_e.warn(`oauth-provider: stripped reserved access-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}async function um(e){let{ctx:t,opts:n,user:r,client:i,scopes:a,resources:o,referenceId:s,metadata:c,grantType:l,sessionId:u,perRequestClaims:d,resourcePolicyClaims:f}=e,p=await ol(n,{ctx:t,opts:n,user:r,client:i,scopes:a,grantType:l,referenceId:s,sessionId:u,resources:o,metadata:c}),m=n.customAccessTokenClaims?await n.customAccessTokenClaims({user:r,scopes:a,resources:o,referenceId:s,metadata:c}):{};return lm({...p,...d??{},...m,...f})}var dm=[`javascript:`,`data:`,`vbscript:`],fm=c().superRefine((e,n)=>{if(!URL.canParse(e))return n.addIssue({code:`custom`,message:`resource must be an absolute URI`,fatal:!0}),t;e.includes(`#`)?n.addIssue({code:`custom`,message:`resource must not contain a fragment`}):dm.includes(new URL(e).protocol)&&n.addIssue({code:`custom`,message:`resource cannot use javascript:, data:, or vbscript: scheme`})}),pm=u([`none`,`consent`,`login`,`create`,`select_account`]),mm=c().superRefine((e,t)=>{let n=e.split(` `).map(e=>e.trim()).filter(Boolean),r=new Set;if(!n.length)t.addIssue({code:`custom`,message:`prompt must include at least one value`});else{for(let e of n){let n=pm.safeParse(e);n.success?r.add(n.data):t.addIssue({code:`custom`,message:`unsupported prompt value: ${e}`})}r.has(`none`)&&r.size>1&&t.addIssue({code:`custom`,message:`prompt=none cannot be combined with other prompt values`})}}),hm=w({keys:x(i(c(),o())).min(1)}),gm=a([d(),c().trim().min(1)]).transform((e,n)=>{let r=typeof e==`number`?e:Number(e);return!Number.isInteger(r)||r<0?(n.addIssue({code:`custom`,message:`max_age must be a non-negative integer`}),t):r}),_m=c().regex(/^[A-Za-z0-9_-]{43}$/,`dpop_jkt must be a base64url-encoded SHA-256 JWK thumbprint`),vm=w({response_type:c().pipe(u([`code`])).optional(),request:c().optional(),request_uri:c().optional(),redirect_uri:Q.optional(),scope:c().optional(),state:c().optional(),client_id:c().min(1,`client_id is required`),prompt:mm.optional(),display:c().optional(),ui_locales:c().optional(),max_age:gm.optional(),acr_values:c().optional(),login_hint:c().optional(),id_token_hint:c().optional(),code_challenge:c().optional(),code_challenge_method:c().pipe(u([`S256`])).optional(),nonce:c().optional(),claims:Qp.optional(),dpop_jkt:_m.optional(),resource:a([fm,x(fm).min(1)]).optional()}).passthrough(),ym=vm.extend({redirect_uri:Q.optional(),claims:$p.optional()}),bm=w({type:l(`authorization_code`),query:ym,sessionId:c(),userId:c(),referenceId:c().optional(),authTime:d().optional(),resource:x(c()).optional()}).passthrough(),xm=w({redirect_uris:x(Q).min(1).optional(),scope:c().optional(),client_name:c().refine(e=>e.trim().length>0,`client_name cannot be empty`).optional(),client_uri:c().optional(),logo_uri:c().optional(),contacts:x(c().min(1)).min(1).optional(),tos_uri:c().optional(),policy_uri:c().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional(),post_logout_redirect_uris:x(Q).min(1).optional(),backchannel_logout_uri:Q.optional(),backchannel_logout_session_required:v().optional(),token_endpoint_auth_method:c().trim().min(1).optional(),jwks:hm.optional(),jwks_uri:c().optional(),grant_types:x(c().trim().min(1)).min(1).optional(),response_types:x(u([`code`])).optional(),application_type:u([`web`,`native`]).optional(),subject_type:u([`public`,`pairwise`]).optional(),dpop_bound_access_tokens:v().optional(),resources:x(fm).optional(),skip_consent:T({error:`skip_consent cannot be set during dynamic client registration`}).optional()});xm.omit({skip_consent:!0}).extend({client_id:c().refine(e=>e.trim().length>0,`client_id cannot be empty`),client_secret:c().optional(),client_secret_expires_at:d().int().nonnegative().optional(),client_id_issued_at:d().int().nonnegative().optional()}).loose();var Sm=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],Cm=new Set(Sm),wm=64;async function Tm(e,t){let n=e.identifierValidator;if(n)return await n(t)?{ok:!0}:{ok:!1,reason:`resource identifier ${t} failed validation`};let r=fm.safeParse(t);return r.success?{ok:!0}:{ok:!1,reason:`resource identifier ${t} is invalid: ${r.error.issues[0]?.message??`not an absolute URI`}`}}async function Em(e,t){let n=await Tm(e,t);if(!n.ok)throw new B(`BAD_REQUEST`,{error:`invalid_target`,error_description:n.reason})}var Dm=e=>`${e}/oauth2/userinfo`;async function Om(e){if(!(e.headers.get(`content-type`)?.toLowerCase()??``).includes(`application/x-www-form-urlencoded`))return;let t;try{t=await e.clone().text()}catch{return}if(!t)return;let n=new URLSearchParams(t).getAll(`resource`).filter(e=>e.length>0);return n.length>0?n:void 0}function km(e){if(e!=null){if(typeof e==`string`)return[e];if(Array.isArray(e)){let t=e.filter(e=>typeof e==`string`&&e.length>0);return t.length>0?t:void 0}}}async function Am(e,t,n,r=[]){if(n===void 0)return!0;let i=Array.isArray(n)?n:[n];if(i.length>wm)return!1;let a=new Set(r),o=new Set;for(let e of i)a.has(e)||o.add(e);return o.size===0||(await Promise.all(Array.from(o,n=>Rm(e,t,n)))).every(Boolean)}async function jm(e,t,n){let r=km(n.resource),i=n.requestedScopes.includes(`openid`),a=Dm(e.context.baseURL??``);if(!r)return{audienceClaim:void 0,accessTokenTtl:null,refreshTokenTtl:null,signingAlgorithm:null,signingKeyId:null,rawCustomClaims:{},dpopBoundAccessTokensRequired:!1,effectiveScopes:[...n.requestedScopes]};let o=[...new Set(r)],s=[];for(let n of o){if(n===a)continue;let r=await Rm(e,t,n);if(r){if(r.disabled)throw new B(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is disabled`});s.push(r)}else throw new B(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is not configured`})}let{value:c}=Fm(t);c&&s.length>0&&await Mm(e,t,n.clientId,s);let l=[...n.requestedScopes];for(let e of s){if(e.allowedScopes===null||e.allowedScopes===void 0)continue;let t=new Set(e.allowedScopes),n=l.filter(e=>t.has(e));if(n.length===0)throw new B(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`none of the requested scopes are allowed for resource ${e.identifier}`});l=n}let u=null,d=null;for(let e of s)e.accessTokenTtl!=null&&(u=u===null?e.accessTokenTtl:Math.min(u,e.accessTokenTtl)),e.refreshTokenTtl!=null&&(d=d===null?e.refreshTokenTtl:Math.min(d,e.refreshTokenTtl));let f=new Set,p=new Set;for(let e of s)e.signingAlgorithm&&f.add(e.signingAlgorithm),e.signingKeyId&&p.add(e.signingKeyId);if(f.size>1)throw new B(`BAD_REQUEST`,{error:`invalid_request`,error_description:`multi-resource request has conflicting signingAlgorithm pins; a single JWS signature cannot satisfy multiple algorithms`});if(p.size>1)throw new B(`BAD_REQUEST`,{error:`invalid_request`,error_description:`multi-resource request has conflicting signingKeyId pins; a single JWS signature cannot satisfy multiple key ids`});let m=f.values().next().value??null,h=p.values().next().value??null,g={};for(let e of s)e.customClaims&&typeof e.customClaims==`object`&&Object.assign(g,e.customClaims);let _=s.some(e=>e.dpopBoundAccessTokensRequired===!0),v=i?[...o,a]:o,y=[...new Set(v)];return{audienceClaim:y.length===1?y[0]:y,accessTokenTtl:u,refreshTokenTtl:d,signingAlgorithm:m,signingKeyId:h,rawCustomClaims:g,dpopBoundAccessTokensRequired:_,effectiveScopes:l}}async function Mm(e,t,n,r){if(r.length===0)return;let i=t.schema?.oauthClientResource?.modelName??`oauthClientResource`,a=await e.context.adapter.findMany({model:i,where:[{field:`clientId`,value:n}]}),o=new Set(a?.map(e=>e.resourceId)??[]),s=r.filter(e=>!o.has(e.identifier));if(s.length>0)throw new B(`BAD_REQUEST`,{error:`invalid_target`,error_description:`client ${n} is not linked to resource(s) ${s.map(e=>e.identifier).join(`, `)}`})}async function Nm(e,t,n,r){if(r.length===0)return!1;let i=t.schema?.oauthClientResource?.modelName??`oauthClientResource`;return((await e.context.adapter.findMany({model:i,where:[{field:`clientId`,value:n},{field:`resourceId`,operator:`in`,value:r}],limit:1}))?.length??0)>0}async function Pm(e,t,n){if(n.length===0)return{};let r=await e.context.adapter.findMany({model:t.schema?.oauthResource?.modelName??`oauthResource`,where:[{field:`identifier`,operator:`in`,value:n}]}),i=new Map(r.map(e=>[e.identifier,e])),a={};for(let e of n){let t=i.get(e);t?.customClaims&&typeof t.customClaims==`object`&&Object.assign(a,t.customClaims)}return a}function Fm(e){return e.enforcePerClientResources===void 0?{value:!0,source:`default`}:{value:e.enforcePerClientResources,source:`explicit`}}var Im=new Map;function Lm(e){e===void 0?Im.clear():Im.delete(e)}async function Rm(e,t,n){if(await Jm(e.context,t),t.cachedResources?.has(n)){let e=Im.get(n);if(e)return Object.assign({},e)}let r=await e.context.adapter.findOne({model:t.schema?.oauthResource?.modelName??`oauthResource`,where:[{field:`identifier`,value:n}]});return r&&t.cachedResources?.has(n)&&Im.set(n,Object.assign({},r)),r}function zm(e){return e.name??e.identifier}function Bm(e){let t=[];if(e.resources?.length)for(let n of e.resources)t.push(typeof n==`string`?{identifier:n}:n);return t}function Vm(e,t){return{identifier:e.identifier,name:zm(e),accessTokenTtl:e.accessTokenTtl??null,refreshTokenTtl:e.refreshTokenTtl??null,signingAlgorithm:e.signingAlgorithm??null,signingKeyId:e.signingKeyId??null,allowedScopes:e.allowedScopes??null,customClaims:e.customClaims??null,dpopBoundAccessTokensRequired:e.dpopBoundAccessTokensRequired??!1,disabled:e.disabled??!1,policyVersion:1,metadata:e.metadata??null,createdAt:t,updatedAt:t}}function Hm(e,t,n){if(t===`overwrite`){let{identifier:t,createdAt:r,...i}=Vm(e,n);return i}let r={updatedAt:n};return e.name!==void 0&&(r.name=e.name),e.accessTokenTtl!==void 0&&(r.accessTokenTtl=e.accessTokenTtl),e.refreshTokenTtl!==void 0&&(r.refreshTokenTtl=e.refreshTokenTtl),e.signingAlgorithm!==void 0&&(r.signingAlgorithm=e.signingAlgorithm),e.signingKeyId!==void 0&&(r.signingKeyId=e.signingKeyId),e.allowedScopes!==void 0&&(r.allowedScopes=e.allowedScopes),e.customClaims!==void 0&&(r.customClaims=e.customClaims),e.dpopBoundAccessTokensRequired!==void 0&&(r.dpopBoundAccessTokensRequired=e.dpopBoundAccessTokensRequired),e.disabled!==void 0&&(r.disabled=e.disabled),e.metadata!==void 0&&(r.metadata=e.metadata),r}var Um=/no such table|relation.*does not exist|table.*does(?: not|n'?t) exist|model.*(?:does not exist|was not found in the schema)/i;function Wm(e,t){let n=!1,r=t;for(let e=0;r&&!n&&e<5;e++)n=Um.test(r instanceof Error?r.message:String(r)),r=r instanceof Error?r.cause:void 0;n?e.logger.debug(`oauth-provider: oauthResource table not yet created; deferring resource seed to first access.`):e.logger.error("oauth-provider: could not seed `resources` at startup; retrying on first resource access.",t)}var Gm=new WeakMap;function Km(e,t){let n=e.adapter,r=Gm.get(n);r||(r=new WeakMap,Gm.set(n,r));let i=r.get(t);if(i)return i;let a={completed:!1,promise:null};return r.set(t,a),a}async function qm(e,t){let n=Bm(t);if(n.length===0)return;let r=t.resourceSeedMode??`insertOnly`,i=t.schema?.oauthResource?.modelName??`oauthResource`;for(let a of n){let n=await Tm(t,a.identifier);if(!n.ok){_e.warn(`oauth-provider: skipping resource seed for ${a.identifier} — ${n.reason}`);continue}let o=a;if(o.signingAlgorithm!=null&&!Cm.has(o.signingAlgorithm)){_e.warn(`oauth-provider: dropping unsupported signingAlgorithm "${o.signingAlgorithm}" for resource ${o.identifier} — must be one of ${Sm.join(`, `)}. Continuing without an algorithm override.`);let{signingAlgorithm:e,...t}=o;o=t}let s=[{field:`identifier`,value:o.identifier}],c=await e.adapter.findOne({model:i,where:s}),l=new Date;if(!c)try{await e.adapter.create({model:i,data:Vm(o,l)});continue}catch(t){if(!await e.adapter.findOne({model:i,where:s}).catch(()=>null))throw t}r!==`insertOnly`&&await e.adapter.update({model:i,where:s,update:Hm(o,r,l)})}}async function Jm(e,t){let n=Km(e,t);if(n.completed!==!0)return n.promise===null&&(n.promise=qm(e,t).then(()=>{n.completed=!0}).catch(e=>{throw n.promise=null,e})),n.promise}function Ym(e){let t=Fm(e);_e.info(`oauth-provider: enforcePerClientResources resolved to ${t.value} (${t.source})`)}function Xm(e){return e.headers?.get(`dpop`)??void 0}function Zm(e,t){return e.request?.url??`${e.context.baseURL}${t}`}var Qm=new Set([`openid`,`profile`,`email`,`offline_access`]);function $m(e){return Qm.has(e)}function eh(e){return[...new Set(e.map(e=>e.trim()).filter(Boolean))]}function th(e,t,n,r){if(e.length===0)return;if(!t.includes(`client_credentials`))throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`client_credentials_scopes requires the client_credentials grant`});if(n===`none`)throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`public clients cannot be assigned client_credentials scopes`});let i=new Set(r.scopes??[]),a=e.filter(e=>!i.has(e)||$m(e));if(a.length>0)throw new B(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`The following client_credentials scopes are invalid: ${a.join(`, `)}`})}function nh(e,t,n=[]){let r=new Set(n),i={sub:e.id??void 0};for(let[n,a]of Object.entries(am))(t.includes(a.scope)||r.has(n))&&(i[n]=a.resolve(e));return i}function rh(e,t){let n={};for(let[r,i]of Object.entries(e??{}))i!==void 0&&(t&&r in t||(n[r]=i));return n}function ih(e){let t=e.headers?.get(`authorization`),n=fc(t),r=e.request?.method===`POST`?e.body?.access_token??void 0:void 0;if(n&&r)throw new B(`BAD_REQUEST`,{error_description:`Multiple access token transport methods are not allowed`,error:`invalid_request`});let i=n??(r?{scheme:`Bearer`,token:r}:void 0);return{authorization:i,token:i?.token}}async function ah(e,t){let{authorization:n}=ih(e);if(!n?.token)throw new B(`UNAUTHORIZED`,{error_description:`access token not found`,error:`invalid_request`});let{payload:r,requestedUserInfoClaims:i}=await og(e,t,n.token);if(vc(r)&&!e.request)throw new B(`UNAUTHORIZED`,{error_description:`DPoP-bound access token requires an HTTP request context`,error:`invalid_token`});try{await Oc({payload:r,authorization:n,proofJwt:Xm(e),method:e.request?.method??`GET`,url:Zm(e,`/oauth2/userinfo`),proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:uc(e.context.internalAdapter)})}catch(e){throw Dc(e)?new B(`UNAUTHORIZED`,{error_description:e.message,error:e.code}):e}let a=r.scope?.split(` `);if(!a?.includes(`openid`))throw new B(`BAD_REQUEST`,{error_description:`Missing required scope`,error:`invalid_scope`});if(!r.sub)throw new B(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let o=await e.context.internalAdapter.findUserById(r.sub);if(!o)throw new B(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let s=nh(o,a??[],i),c=r.client_id??r.azp,l=c&&(t.pairwiseSecret||ll(t))?await xl(e,t,c):void 0;t.pairwiseSecret&&l&&(s.sub=await Kl(o.id,l,t));let u=a?.length?await cl(t,{ctx:e,opts:t,user:o,scopes:a,jwt:r,client:l??void 0,requestedClaims:i}):{},d=t.customUserInfoClaims&&a?.length?await t.customUserInfoClaims({user:o,scopes:a,jwt:r,requestedClaims:i}):{};return{...s,...rh(u,s),...rh(d),sub:s.sub}}var oh=Object.fromEntries(om.map(e=>[e,void 0]));function sh(e){return _c(e)?`DPoP`:`Bearer`}var ch=`at+jwt`;async function lh(e,t){let n=e.body.grant_type;if(!Qc(t).includes(n))throw new B(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`});switch(n){case`authorization_code`:return Uh(e,t);case`client_credentials`:return Wh(e,t);case`refresh_token`:return Gh(e,t);default:{let r=$c(t,n);if(r)return r({ctx:e,opts:t,grantType:n,provider:uh(e,t,n)});throw new B(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`})}}}function uh(e,t,n){return{getClient:n=>xl(e,t,n),authenticateClient:async r=>{let{clientId:i,clientSecret:a,preVerified:o,authMethod:s,confirmation:c}=Vl(await Hl(e,t,`${e.context.baseURL}${e.path??`/oauth2/token`}`));if(!i)throw new B(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});if(r?.requireCredentials!==!1&&!a&&!o)throw new B(`BAD_REQUEST`,{error_description:`Missing required client credentials`,error:`invalid_client`});return{clientId:i,client:await zl(e,t,i,a,r?.scopes,o,n,s),method:s,confirmation:c}},issueTokens:r=>{if(!n)throw new B(`INTERNAL_SERVER_ERROR`,{error_description:`issueTokens requires a grant type; pass it to getOAuthProviderApi(ctx, opts, grantType).`,error:`server_error`});return Vh(e,t,{...r,grantType:n})},hashToken:(e,n)=>Dl(t.storeTokens,e,n),validateAccessToken:async(n,r)=>{let{validateAccessToken:i}=await Promise.resolve().then(()=>Kh);return i(e,t,n,r)},requireActiveAccessToken:async(n,r)=>{let{requireActiveAccessToken:i}=await Promise.resolve().then(()=>Kh);return i(e,t,n,r)}}}async function dh(e,t,n,r,i,a,o){let s=o?.iat??Math.floor(Date.now()/1e3),c=o?.exp??s+(t.accessTokenExpiresIn??3600),l=pl(e.context).options,u=n?.id??r.clientId;return Vp(e,{options:l,header:{typ:ch},signingKeyId:o?.signingKeyId??void 0,signingAlgorithm:o?.signingAlgorithm??void 0,payload:{...o?.accessTokenClaims??{},sub:u,aud:_l(i),client_id:r.clientId,azp:r.clientId,scope:a.join(` `),sid:o?.sid,iss:l?.jwt?.issuer??e.context.baseURL,iat:s,exp:c,jti:Fi(32),...o?.confirmation?{cnf:o.confirmation}:{}}})}async function fh(e,t){let n;n=t===`EdDSA`?`SHA-512`:t.endsWith(`384`)?`SHA-384`:t.endsWith(`512`)?`SHA-512`:`SHA-256`;let r=new Uint8Array(await crypto.subtle.digest(n,new TextEncoder().encode(e)));return G(r.slice(0,r.length/2))}async function ph(e,t,n,r,i,a,o,s,c,l){let u=Math.floor(Date.now()/1e3),d=u+(t.idTokenExpiresIn??36e3),f=await Kl(n.id,r,t),p=s==null?void 0:Math.floor(s.getTime()/1e3),m=Wp(t.customIdTokenClaims?await t.customIdTokenClaims({user:n,scopes:i,metadata:Bl(r.metadata)}):void 0),h=t.disableJwtPlugin?void 0:pl(e.context).options,g=!t.disableJwtPlugin&&!h?.jwt?.sign?await Bp(e,h):void 0,_=t.disableJwtPlugin?`HS256`:g?.alg??h?.jwks?.keyPairConfig?.alg,v=c?await fh(c,_):void 0,y=!!(r.enableEndSession||r.backchannelLogoutUri),b={...oh,auth_time:p,acr:`0`,...m,at_hash:v,iss:h?.jwt?.issuer??e.context.baseURL,sub:f,aud:r.clientId,nonce:a,iat:u,exp:d,sid:y?o:void 0},x=Wp(l);if(Object.assign(b,rh(x,b)),t.disableJwtPlugin&&!r.clientSecret)return;let S=t.disableJwtPlugin?await new Kr(b).setProtectedHeader({alg:`HS256`}).sign(new TextEncoder().encode(await wl(e,t.storeClientSecret,r.clientSecret))):await Vp(e,{options:h,payload:b,resolvedKey:g??void 0});if(S&&v&&h?.jwt?.sign){let e=vi(S);if(e.alg!==_)throw new B(`INTERNAL_SERVER_ERROR`,{error_description:`ID token signed with "${e.alg}" but at_hash was computed for "${_}". Ensure jwt.sign uses the algorithm declared in keyPairConfig.alg.`,error:`server_error`})}return S}async function mh(e,t,n){return(e.prefix?.refreshToken??``)+(e.formatRefreshToken?.encrypt?e.formatRefreshToken.encrypt(t,n):t)}async function hh(e,t){if(e.prefix?.refreshToken){if(t.startsWith(e.prefix.refreshToken))t=t.replace(e.prefix.refreshToken,``);else throw new B(`BAD_REQUEST`,{error_description:`refresh token not found`,error:`invalid_token`})}return e.formatRefreshToken?.decrypt?e.formatRefreshToken?.decrypt(t):{token:t}}async function gh(e,t,n,r,i,a,o,s,c,l,u,d){let f=a.iat??Math.floor(Date.now()/1e3),p=a?.exp??f+(t.accessTokenExpiresIn??3600),m=t.generateOpaqueAccessToken?await t.generateOpaqueAccessToken():Fi(32,`A-Z`,`a-z`);return await e.context.adapter.create({model:`oauthAccessToken`,data:{token:await Dl(t.storeTokens,m,`access_token`),clientId:r.clientId,sessionId:a?.sid,userId:n?.id,referenceId:s,authorizationCodeId:c,resources:o,refreshId:l,confirmation:u,requestedUserInfoClaims:d?.length?d:void 0,scopes:i,createdAt:new Date(f*1e3),expiresAt:new Date(p*1e3)}}),(t.prefix?.opaqueAccessToken??``)+m}async function _h(e,t,n){let r=await e.context.adapter.findMany({model:`oauthRefreshToken`,where:[{field:`clientId`,value:t},{field:`userId`,value:n}]});r.length&&await e.context.adapter.deleteMany({model:`oauthAccessToken`,where:[{field:`refreshId`,operator:`in`,value:r.map(e=>e.id)}]}),await e.context.adapter.deleteMany({model:`oauthRefreshToken`,where:[{field:`clientId`,value:t},{field:`userId`,value:n}]})}async function vh(e,t){let n=async n=>{try{await e.context.adapter.deleteMany({model:n,where:[{field:`authorizationCodeId`,value:t}]})}catch(t){e.context.logger.error(`authorization code replay cleanup failed`,t)}};await n(`oauthAccessToken`),await n(`oauthRefreshToken`)}async function yh(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=s.iat??Math.floor(Date.now()/1e3),m=s?.exp??p+(t.refreshTokenExpiresIn??2592e3),h=t.generateRefreshToken?await t.generateRefreshToken():Fi(32,`A-Z`,`a-z`),g=s?.sid,_={token:await Dl(t.storeTokens,h,`refresh_token`),clientId:a.clientId,sessionId:g,userId:n.id,referenceId:r,authorizationCodeId:i,authTime:l,confirmation:d,requestedUserInfoClaims:f?.length?f:void 0,scopes:o,resources:u,createdAt:new Date(p*1e3),expiresAt:new Date(m*1e3)};if(!c?.id)return{id:(await e.context.adapter.create({model:`oauthRefreshToken`,data:_})).id,token:await mh(t,h,g)};let v=new Date(p*1e3),y={revoked:v,rotatedAt:v},b=t.refreshTokenReuseInterval??0;if(b>0&&(y.rotationReplayExpiresAt=new Date((p+b)*1e3)),!await e.context.adapter.incrementOne({model:`oauthRefreshToken`,where:[{field:`id`,value:c.id},{field:`revoked`,operator:`eq`,value:null}],increment:{},set:y}))throw new B(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`});return{id:(await e.context.adapter.create({model:`oauthRefreshToken`,data:_})).id,token:await mh(t,h,g)}}async function bh(e,t,n){let r=await jm(e,t,{resource:n.resources,clientId:n.clientId,requestedScopes:n.requestedScopes}),i=r.accessTokenTtl===null?n.scopeExpiresAtSeconds:n.iat+r.accessTokenTtl,a=t.refreshTokenExpiresIn??2592e3,o=r.refreshTokenTtl===null?a:Math.min(r.refreshTokenTtl,a);return{audienceClaim:r.audienceClaim,effectiveScopes:r.effectiveScopes,accessTokenExpiresAtSeconds:Math.min(n.scopeExpiresAtSeconds,i),refreshTokenExpiresAtSeconds:n.iat+o,refreshResources:n.refreshToken?.resources??n.originalResources??n.resources,signingAlgorithm:r.signingAlgorithm,signingKeyId:r.signingKeyId,resourceCustomClaims:r.rawCustomClaims,dpopBoundAccessTokensRequired:r.dpopBoundAccessTokensRequired}}function xh(e){throw new B(`BAD_REQUEST`,{error:`invalid_dpop_proof`,error_description:e})}function Sh(e){let t=Bl(e.metadata)??{};return e.dpopBoundAccessTokens===!0||t.dpop_bound_access_tokens===!0}async function Ch(e,t,n){let r=n.verificationValue?.query.dpop_jkt,i=_c(n.refreshToken?.confirmation),a=i??r,o=Xm(e),s=Sh(n.client)||n.grantIssuance.dpopBoundAccessTokensRequired||!!r||!!i;if(!o)s&&xh(`DPoP proof header is required`);else try{return{jkt:(await Tc({proofJwt:o,method:`POST`,url:Zm(e,`/oauth2/token`),expectedJkt:a,proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:uc(e.context.internalAdapter)})).jkt}}catch(e){throw dc(e)&&xh(e.message),e}}function wh(e){return e?[...new Set(e)].sort():void 0}function Th(e,t){let n=wh(e),r=wh(t);return n===void 0||r===void 0?n===r:n.length===r.length&&n.every((e,t)=>e===r[t])}function Eh(e){if(e)return`jkt`in e?`jkt:${e.jkt}`:`x5t#S256:${e[`x5t#S256`]}`}function Dh(e,t){return Eh(e)===Eh(t)}function Oh(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.jkt==`string`&&t[`x5t#S256`]===void 0||typeof t[`x5t#S256`]==`string`&&t.jkt===void 0}function kh(e){return e===`Bearer`||e===`DPoP`}function Ah(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.access_token==`string`&&typeof t.expires_in==`number`&&typeof t.expires_at==`number`&&kh(t.token_type)&&typeof t.scope==`string`&&(t.refresh_token===void 0||typeof t.refresh_token==`string`)&&(t.id_token===void 0||typeof t.id_token==`string`)}function jh(e){if(!e||typeof e!=`object`)return!1;let t=e,n=t.request;return!!n&&Array.isArray(n.effectiveScopes)&&n.effectiveScopes.every(e=>typeof e==`string`)&&(n.requestedResources===void 0||Array.isArray(n.requestedResources)&&n.requestedResources.every(e=>typeof e==`string`))&&(n.confirmation===void 0||Oh(n.confirmation))&&Ah(t.response)}function Mh(e){let t=wh(e.requestedResources);return{effectiveScopes:wh(e.effectiveScopes)??[],...t?{requestedResources:t}:{},...e.confirmation?{confirmation:e.confirmation}:{}}}function Nh(e,t){return Th(e.effectiveScopes,t.effectiveScopes)&&Th(e.requestedResources,t.requestedResources)&&Dh(e.confirmation,t.confirmation)}async function Ph(e,t){return Ha({key:e.context.secretConfig,data:JSON.stringify(t)})}async function Fh(e,t){let n=await Ua({key:e.context.secretConfig,data:t}),r=JSON.parse(n);if(jh(r))return r}function Ih(e){return!!e.rotatedAt&&!!e.rotationReplayExpiresAt&&e.rotationReplayExpiresAt>=new Date}async function Lh(e,t,n,r,i){(t.refreshTokenReuseInterval??0)<=0||await e.context.adapter.update({model:`oauthRefreshToken`,where:[{field:`id`,value:n.id}],update:{rotationReplayResponse:await Ph(e,{request:r,response:i})}})}async function Rh(e,t,n){if(Ih(t)&&t.rotationReplayResponse)try{let r=await Fh(e,t.rotationReplayResponse);return!r||!Nh(r.request,n)?void 0:r.response}catch(t){e.context.logger.error(`refresh token rotation replay failed`,t);return}}async function zh(e,t,n){let r=Math.floor(Date.now()/1e3),i=await bh(e,t,{clientId:n.client.clientId,requestedScopes:n.scopes,resources:n.resources,refreshToken:n.refreshToken,iat:r,scopeExpiresAtSeconds:r+(t.accessTokenExpiresIn??3600)}),a=await Ch(e,t,{client:n.client,grantIssuance:i,refreshToken:n.refreshToken});return Mh({effectiveScopes:i.effectiveScopes,requestedResources:n.resources,confirmation:a})}function Bh(e,t){let n=Math.floor(Date.now()/1e3);return e.json({...t,expires_in:Math.max(0,t.expires_at-n)})}async function Vh(e,t,n){let{client:r,scopes:i,user:a,grantType:o,referenceId:s,sessionId:c,nonce:l,refreshToken:u,authTime:d,verificationValue:f}=n,p=Math.floor(Date.now()/1e3),m=p+(a?t.accessTokenExpiresIn??3600:t.m2mAccessTokenExpiresIn??3600),h=t.scopeExpirations?i.map(e=>t.scopeExpirations?.[e]?Lp(t.scopeExpirations[e],p):m).reduce((e,t)=>e<t?e:t,m):m,g=await bh(e,t,{clientId:r.clientId,requestedScopes:i,resources:n.resources,originalResources:n.originalResources,refreshToken:n.refreshToken,iat:p,scopeExpiresAtSeconds:h}),_=g.audienceClaim,v=g.effectiveScopes,y=g.accessTokenExpiresAtSeconds,b=g.refreshTokenExpiresAtSeconds,x=a&&Il(r,`refresh_token`)&&(u?.scopes?.includes(`offline_access`)||i.includes(`offline_access`)),S=_&&!t.disableJwtPlugin,C=a&&v.includes(`openid`),w=Bl(r.metadata),T=C&&a?{...await sl(t,{ctx:e,opts:t,user:a,client:r,scopes:v,grantType:o,referenceId:s,sessionId:c,resources:n.resources,metadata:w}),...n.idTokenClaims??{}}:void 0,E=t.customTokenResponseFields?await t.customTokenResponseFields({grantType:o,user:a,scopes:v,metadata:w,verificationValue:f}):void 0,D=g.refreshResources,O=n.confirmation??await Ch(e,t,{client:r,grantIssuance:g,verificationValue:f,refreshToken:u}),k=n.requestedUserInfoClaims??u?.requestedUserInfoClaims??[],A=x&&a&&!S?await yh(e,t,a,s,n.authorizationCodeId,r,v,{iat:p,exp:b,sid:c},u,d,D,O,k):void 0,j=S?await um({ctx:e,opts:t,user:a,client:r,scopes:v,grantType:o,sessionId:c,resources:n.resources,referenceId:s,metadata:w,perRequestClaims:n.accessTokenClaims,resourcePolicyClaims:g.resourceCustomClaims}):void 0,[M,N]=await Promise.all([S?dh(e,t,a,r,_,v,{iat:p,exp:y,sid:c,signingAlgorithm:g.signingAlgorithm,signingKeyId:g.signingKeyId,accessTokenClaims:j,confirmation:O}):gh(e,t,a,r,v,{iat:p,exp:y,sid:c},n?.resources,s,n.authorizationCodeId,A?.id,O,k),A||(x&&a?yh(e,t,a,s,n.authorizationCodeId,r,v,{iat:p,exp:b,sid:c},u,d,D,O,k):void 0)]),P=C?await ph(e,t,a,r,v,l,c,d,M,T):void 0,F={...E,...n.tokenResponse??{},access_token:M,expires_in:y-p,expires_at:y,token_type:sh(O),refresh_token:N?.token,scope:v.join(` `),id_token:P};if(u?.id&&N?.id)try{await Lh(e,t,u,Mh({effectiveScopes:v,requestedResources:n.resources,confirmation:O}),F)}catch(t){e.context.logger.error(`failed to store refresh token rotation replay`,t)}return e.json(F)}async function Hh(e,t,n,r,i,a){let o=await Dl(t.storeTokens,n,`authorization_code`),s=await e.context.internalAdapter.consumeVerificationValue(o);if(!s)throw await vh(e,o),new B(`BAD_REQUEST`,{error_description:`invalid code`,error:`invalid_grant`});let c;try{c=JSON.parse(s.value)}catch{throw new B(`BAD_REQUEST`,{error_description:`malformed verification value`,error:`invalid_grant`})}let l=bm.safeParse(c);if(!l.success)throw new B(`BAD_REQUEST`,{error_description:`malformed verification value`,error:`invalid_grant`});let u=l.data;if(u.query.client_id!==r)throw new B(`BAD_REQUEST`,{error_description:`invalid client_id`,error:`invalid_grant`});let d=u.query.redirect_uri;if(d){if(!i)throw new B(`BAD_REQUEST`,{error_description:`redirect_uri is required`,error:`invalid_request`});if(d!==i)throw new B(`BAD_REQUEST`,{error_description:`redirect_uri mismatch`,error:`invalid_grant`})}else if(i)throw new B(`BAD_REQUEST`,{error_description:`redirect_uri mismatch`,error:`invalid_grant`});let f=gl(u.resource)??gl(u.query.resource),p=a??f;if(a&&f){let e=new Set(a),t=new Set(f);for(let n of e)if(!t.has(n))throw new B(`BAD_REQUEST`,{error_description:`requested resource not authorized`,error:`invalid_target`})}return{verificationValue:u,effectiveResources:p,authorizedResources:f,authorizationCodeId:o}}async function Uh(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=Vl(await Hl(e,t,`${e.context.baseURL}/oauth2/token`)),{code:o,code_verifier:s,redirect_uri:c,resource:l}=e.body,u=gl(l);if(!n)throw new B(`BAD_REQUEST`,{error_description:`client_id is required`,error:`invalid_request`});if(!o)throw new B(`BAD_REQUEST`,{error_description:`code is required`,error:`invalid_request`});let d=n&&r,f=n&&o&&s;if(!d&&!f&&!i)throw new B(`BAD_REQUEST`,{error_description:`Either code_verifier or client_secret is required`,error:`invalid_request`});let{verificationValue:p,effectiveResources:m,authorizedResources:h,authorizationCodeId:g}=await Hh(e,t,o,n,c,u),_=p.query.scope?.split(` `);if(!_)throw new B(`INTERNAL_SERVER_ERROR`,{error_description:`verification scope unset`,error:`invalid_scope`});let v=await zl(e,t,n,r,_,i,`authorization_code`,a);if(Zl(v,{scopes:(p.query?.scope)?.split(` `)||[],nonce:p.query?.nonce})){if(!f)throw new B(`BAD_REQUEST`,{error_description:`PKCE is required for this client`,error:`invalid_request`})}else if(!(f||d||i))throw new B(`BAD_REQUEST`,{error_description:`Either PKCE (code_verifier) or client authentication (client_secret or client_assertion) is required`,error:`invalid_request`});let y=!!p.query?.code_challenge,b=!!s;if(y||b){if(y&&!b)throw new B(`UNAUTHORIZED`,{error_description:`code_verifier required because PKCE was used in authorization`,error:`invalid_request`});if(!y&&b)throw new B(`UNAUTHORIZED`,{error_description:`code_verifier provided but PKCE was not used in authorization`,error:`invalid_request`});if((p.query?.code_challenge_method===`S256`?await us(s):void 0)!==p.query?.code_challenge)throw new B(`UNAUTHORIZED`,{error_description:`code verification failed`,error:`invalid_request`})}if(!p.userId)throw new B(`BAD_REQUEST`,{error_description:`missing user, user may have been deleted`,error:`invalid_user`});let x=await e.context.internalAdapter.findUserById(p.userId);if(!x)throw new B(`BAD_REQUEST`,{error_description:`missing user, user may have been deleted`,error:`invalid_user`});let S=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:p.sessionId}]});if(!S||S.expiresAt<new Date)throw new B(`BAD_REQUEST`,{error_description:`session no longer exists`,error:`invalid_request`});let C=p.authTime==null?hl(S):ml(p.authTime),w=tm(p.query.claims,sm(t));return Vh(e,t,{client:v,scopes:p.query.scope?.split(` `)??[],user:x,grantType:`authorization_code`,referenceId:p.referenceId,sessionId:S.id,nonce:p.query?.nonce,authTime:C,verificationValue:p,authorizationCodeId:g,requestedUserInfoClaims:w,resources:m,originalResources:h})}async function Wh(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=Vl(await Hl(e,t,`${e.context.baseURL}/oauth2/token`)),{scope:o,resource:s}=e.body,c=gl(s);if(!n)throw new B(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});let l=await zl(e,t,n,r,void 0,i,`client_credentials`,a);if(l.tokenEndpointAuthMethod===`none`)throw new B(`BAD_REQUEST`,{error_description:`public clients cannot use the client_credentials grant`,error:`unauthorized_client`});let u=l.clientCredentialsScopes;if(!u?.length)throw new B(`BAD_REQUEST`,{error_description:`client has no authorized client_credentials scopes`,error:`unauthorized_client`});let d=o?.split(` `);if(d){let e=new Set(u),t=d.filter(t=>!e.has(t)||$m(t));if(t.length)throw new B(`BAD_REQUEST`,{error_description:`The following scopes are invalid: ${t.join(`, `)}`,error:`invalid_scope`})}return d||=[...u],Vh(e,t,{client:l,scopes:d,grantType:`client_credentials`,resources:c})}async function Gh(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=Vl(await Hl(e,t,`${e.context.baseURL}/oauth2/token`)),{refresh_token:o,scope:s,resource:c}=e.body,l=gl(c);if(!n)throw new B(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});if(!o)throw new B(`BAD_REQUEST`,{error_description:`Missing a required refresh_token for refresh_token grant`,error:`invalid_request`});let u=await hh(t,o),d=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await Ol(t.storeTokens,u.token,`refresh_token`)}]});if(!d)throw new B(`BAD_REQUEST`,{error_description:`session not found`,error:`invalid_grant`});if(d.clientId!==n||d.expiresAt<new Date)throw new B(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`});if(l&&d.resources&&!l.every(e=>d.resources?.includes(e)))throw new B(`BAD_REQUEST`,{error_description:`requested resource invalid`,error:`invalid_target`});let f=d?.scopes,p=s?.split(` `);if(p){let e=new Set(f);for(let t of p)if(!e.has(t))throw new B(`BAD_REQUEST`,{error_description:`unable to issue scope ${t}`,error:`invalid_scope`})}let m=await zl(e,t,n,r,p??f,i,`refresh_token`,a);if(d.revoked){if(Ih(d)){let n=await Rh(e,d,await zh(e,t,{client:m,refreshToken:d,scopes:p??f,resources:l??d.resources}));if(n)return Bh(e,n);throw new B(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`})}throw await _h(e,n,d.userId),new B(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`})}let h=await e.context.internalAdapter.findUserById(d.userId);if(!h)throw new B(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let g=d.authTime==null?void 0:ml(d.authTime);return Vh(e,t,{client:m,scopes:p??f,user:h,grantType:`refresh_token`,referenceId:d.referenceId,authorizationCodeId:d.authorizationCodeId,sessionId:d.sessionId,refreshToken:d,resources:l??d.resources,authTime:g,requestedUserInfoClaims:d.requestedUserInfoClaims})}var Kh=Ce({introspectEndpoint:()=>cg,requireActiveAccessToken:()=>ag,requireActiveAccessTokenWithClaims:()=>og,validateAccessToken:()=>ig}),qh=`Invalid access token`,Jh=`Bearer error="invalid_token", error_description="${qh}"`;function Yh(){return{payload:{active:!1},requestedUserInfoClaims:[]}}function Xh(e,t){return e==null?[]:(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`&&e!==t)}async function Zh(e,t,n){let{introspectingClientId:r,issuerClientId:i,audienceResources:a}=n;return!r||r===i||a.length!==0&&Nm(e,t,r,a)}async function Qh(e,t,n,r){let i=t.disableJwtPlugin?void 0:pl(e.context),a=i?.options,o=`${e.context.baseURL??``}/oauth2/userinfo`,s=a?.jwt?.issuer??e.context.baseURL,c;try{c=(await Vr(n,hi(await Pc(n,{jwksFetch:a?.jwks?.remoteUrl?a.jwks.remoteUrl:async()=>(await i?.endpoints.getJwks(e))?.response,jwksCacheKey:i})),{issuer:s})).payload}catch(e){if(e instanceof Error){if(e.name===`TypeError`||e.name===`JWSInvalid`)throw new z(`BAD_REQUEST`,{error_description:`invalid JWT signature`,error:`invalid_request`});if(e.name===`JWTExpired`||e.name===`JWTInvalid`)return{active:!1};throw e}throw Error(e)}let l=c.aud;if(!await Am(e,t,l,[o])||!c.azp)return{active:!1};let u=await xl(e,t,c.azp);if(!u||u?.disabled||!await Zh(e,t,{introspectingClientId:r,issuerClientId:c.azp,audienceResources:Xh(l,o)}))return{active:!1};let d=c.sid;if(d){let t=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:d}]});if(!t||t.expiresAt<new Date)return{active:!1}}return c.client_id=c.azp,c.active=!0,c.token_type=sh(c.cnf),c}async function $h(e,t,n,r){let i=n;if(t.prefix?.opaqueAccessToken){if(i.startsWith(t.prefix.opaqueAccessToken))i=i.replace(t.prefix.opaqueAccessToken,``);else throw new z(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_request`})}let a=await e.context.adapter.findOne({model:`oauthAccessToken`,where:[{field:`token`,value:await Ol(t.storeTokens,i,`access_token`)}]});if(!a)throw new z(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_token`});if(!a.expiresAt||a.expiresAt<new Date||a.revoked)return Yh();let o=Array.isArray(a.resources)?a.resources:void 0,s;if(a.clientId&&(s=await xl(e,t,a.clientId),!s||s?.disabled||!await Zh(e,t,{introspectingClientId:r,issuerClientId:a.clientId,audienceResources:o??[]})))return Yh();let c=a.sessionId??void 0;if(c){let t=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:c}]});if(!t||t.expiresAt<new Date)return Yh()}let l;a.userId&&(l=await e.context.internalAdapter.findUserById(a?.userId));let u=`${e.context.baseURL}/oauth2/userinfo`;if(o?.length&&!await Am(e,t,o,[u]))return Yh();let d=o?[...o]:void 0;d?.length&&a.scopes?.includes(`openid`)&&(d.includes(u)||d.push(u));let f=o?.length?await Pm(e,t,o):{},p=s?await um({ctx:e,opts:t,user:l,client:s,scopes:a.scopes??[],grantType:void 0,sessionId:void 0,resources:o,referenceId:a.referenceId,metadata:Bl(s.metadata),perRequestClaims:void 0,resourcePolicyClaims:f}):{},m=(t.disableJwtPlugin?void 0:pl(e.context))?.options;return{payload:{...p,active:!0,iss:m?.jwt?.issuer??e.context.baseURL,aud:_l(d),client_id:a.clientId,azp:a.clientId,sub:l?.id,sid:c,exp:Math.floor(new Date(a.expiresAt).getTime()/1e3),iat:Math.floor(new Date(a.createdAt).getTime()/1e3),scope:a.scopes?.join(` `),token_type:sh(a.confirmation),...a.confirmation?{cnf:a.confirmation}:{}},requestedUserInfoClaims:a.requestedUserInfoClaims??[]}}async function eg(e,t,n,r){let i=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await Ol(t.storeTokens,n,`refresh_token`)}]});if(!i)throw new z(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_token`});if(!i.clientId||i.clientId!==r||!i.expiresAt||i.expiresAt<new Date||i.revoked)return{active:!1};let a=i.sessionId??void 0;if(a){let t=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:a}]});(!t||t.expiresAt<new Date)&&(a=void 0)}let o;return i.userId&&(o=await e.context.internalAdapter.findUserById(i?.userId)??void 0),{active:!0,client_id:r,iss:((t.disableJwtPlugin?void 0:pl(e.context))?.options)?.jwt?.issuer??e.context.baseURL,sub:o?.id,sid:a,exp:Math.floor(new Date(i.expiresAt).getTime()/1e3),iat:Math.floor(new Date(i.createdAt).getTime()/1e3),scope:i.scopes?.join(` `),token_type:sh(i.confirmation),...i.confirmation?{cnf:i.confirmation}:{}}}function tg(){return new z(`UNAUTHORIZED`,{error_description:qh,error:`invalid_token`},{"WWW-Authenticate":Jh})}function ng(e){return e.status===`BAD_REQUEST`||e.body?.error===`invalid_token`}async function rg(e,t,n,r){try{return{payload:await Qh(e,t,n,r),requestedUserInfoClaims:[]}}catch(e){if(!(e instanceof z))throw e instanceof Error?e:Error(e)}try{return await $h(e,t,n,r)}catch(e){if(!(e instanceof z))throw e instanceof Error?e:Error(`Unknown error validating access token`)}throw tg()}async function ig(e,t,n,r){return(await rg(e,t,n,r)).payload}async function ag(e,t,n,r){let i=await ig(e,t,n,r);if(i.active)return i;throw tg()}async function og(e,t,n,r){let{payload:i,requestedUserInfoClaims:a}=await rg(e,t,n,r);if(i.active)return{payload:i,requestedUserInfoClaims:a};throw tg()}async function sg(e,t,n,r){if(!n.active||!n.sub)return n;let i=n.client_id??n.azp;if(!i)return n;let a=i===r.clientId?r:await xl(e,t,i);if(!a)return n;let o=await Kl(n.sub,a,t);return{...n,sub:o}}async function cg(e,t){let{token:n,token_type_hint:r}=e.body;r!==`access_token`&&r!==`refresh_token`&&(r=void 0);let{clientId:i,clientSecret:a,preVerified:o,authMethod:s}=Vl(await Hl(e,t,`${e.context.baseURL}/oauth2/introspect`));if(!i||!a&&!o)throw new z(`UNAUTHORIZED`,{error_description:`missing required credentials`,error:`invalid_client`});if(n&&typeof n==`string`&&(n=pc(n)),!n?.length)throw new z(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await zl(e,t,i,a,void 0,o,void 0,s);try{if(r===void 0||r===`access_token`)try{return sg(e,t,await ig(e,t,n,c.clientId),c)}catch(e){if(e instanceof z){if(r===`access_token`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}if(r===void 0||r===`refresh_token`)try{return sg(e,t,await eg(e,t,(await hh(t,n)).token,c.clientId),c)}catch(e){if(e instanceof z){if(r===`refresh_token`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}throw new z(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`})}catch(e){if(e instanceof z){if(ng(e))return{active:!1};throw e}throw e instanceof Error?(_e.error(`Introspection error:`,e.message,e.stack),new z(`INTERNAL_SERVER_ERROR`)):(_e.error(`Introspection error:`,e),new z(`INTERNAL_SERVER_ERROR`))}}var lg=`1.7.8`;function ug(e){return e?.get(`sec-fetch-mode`)===`cors`}var dg=e({d:()=>s_,f:()=>i_,h:()=>a_,i:()=>jy,l:()=>C_,n:()=>wy,o:()=>A_,r:()=>Dy,s:()=>Y_,t:()=>Hy,u:()=>n_});async function fg(e,t,n){let r=await Ey.get(),i=r?.query;if(!i)throw new B(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let a=new URLSearchParams(i),o=a.get(`scope`)?.split(` `)??[],s=sm(t),c=tm(a.get(`claims`),s),l=a.get(`client_id`);if(!l)throw new B(`BAD_REQUEST`,{error_description:`client_id is required`,error:`invalid_client`});let u=e.body.scope?.split(` `);if(u&&!u.every(e=>o?.includes(e)))throw new B(`BAD_REQUEST`,{error_description:`Scope not originally requested`,error:`invalid_request`});let d=e.body.claims,f=d===void 0?c:tm(d,s);if(d!==void 0&&!f.every(e=>c.includes(e)))throw new B(`BAD_REQUEST`,{error_description:`Claim not originally requested`,error:`invalid_request`});if(e.body.accept!==!0)return{redirect:!0,url:Py(a.get(`redirect_uri`)??``,`access_denied`,`User denied access`,a.get(`state`)??void 0,Hy(e,t))};let p=await Z(e),m=Ul(a.get(`prompt`)??``).has(`login`),h=m&&Jl(p?.session.createdAt,r?.signedQueryIssuedAt);if(m&&!h)return e?.headers?.set(`accept`,`application/json`),e.query=ql(a),await n(e);let g=await t.postLogin?.consentReferenceId?.({user:p?.user,session:p?.session,scopes:u??o}),_=await e.context.adapter.findOne({model:`oauthConsent`,where:[{field:`clientId`,value:l},{field:`userId`,value:p?.user.id},...g?[{field:`referenceId`,value:g}]:[]]}),v=Math.floor(Date.now()/1e3),y=a.getAll(`resource`),b={clientId:l,userId:p?.user.id,scopes:u??o,requestedUserInfoClaims:f,createdAt:new Date(v*1e3),updatedAt:new Date(v*1e3),resources:y.length?y:void 0,referenceId:g};if(_?.id?await e.context.adapter.update({model:`oauthConsent`,where:[{field:`id`,value:_.id}],update:{resources:b.resources,scopes:b.scopes,requestedUserInfoClaims:b.requestedUserInfoClaims,updatedAt:new Date(v*1e3)}}):await e.context.adapter.create({model:`oauthConsent`,data:{...b,scopes:b.scopes}}),u&&a.set(`scope`,b.scopes.join(` `)),d!==void 0){let e=rm(a.get(`claims`),f);e?a.set(`claims`,JSON.stringify(e)):a.delete(`claims`)}e?.headers?.set(`accept`,`application/json`);let x=Yl(a,`consent`);return h&&(x=Yl(x,`login`),x=Xl(x)),e.query=ql(x),await n(e,{postLogin:r?.postLoginClearedForSession!==void 0&&r.postLoginClearedForSession===p?.session.id})}async function pg(e,t){if(e.body.selected===!0)return await mg(e,t);if(e.body.created===!0)return await hg(e,t);if(e.body.postLogin===!0)return await gg(e,t);throw new B(`BAD_REQUEST`,{error_description:`Missing parameters`,error:`invalid_request`})}async function mg(e,t){let n=(await Ey.get())?.query;if(!n)throw new B(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});return e.headers?.set(`accept`,`application/json`),e.query=ql(Yl(new URLSearchParams(n),`select_account`)),await t(e)}async function hg(e,t){let n=(await Ey.get())?.query;if(!n)throw new B(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let r=new URLSearchParams(n);return e.headers?.set(`accept`,`application/json`),e.query=ql(Yl(r,`create`)),await t(e)}async function gg(e,t){let n=await Ey.get(),r=n?.query;if(!r)throw new B(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let i=new URLSearchParams(r);e.headers?.set(`accept`,`application/json`),e.query=ql(i);let a=await Z(e);return await t(e,{postLogin:n?.postLoginClearedForSession!==void 0&&n.postLoginClearedForSession===a?.session.id})}var _g=`http://schemas.openid.net/event/backchannel-logout`,vg=`logout+jwt`,yg=120,bg=5e3;async function xg(e,t,n,r){return Vp(e,{options:t,payload:{...r,events:{[_g]:{}}},header:{typ:vg},resolvedKey:n??void 0})}async function Sg(e,t,n){let{sessionId:r,userId:i}=n;if(!i)return null;let a=e.context.logger;try{let n=await pd(e.context.adapter),o=[{field:`sessionId`,value:r}],[s,c]=await Promise.all([n.findMany({model:`oauthAccessToken`,where:o}),n.findMany({model:`oauthRefreshToken`,where:o})]),l=new Set;for(let e of s)l.add(e.clientId);for(let e of c)l.add(e.clientId);if(l.size===0)return null;let u=await n.findMany({model:`oauthClient`,where:[{field:`clientId`,operator:`in`,value:Array.from(l)}]}),d=s.filter(e=>!e.revoked).map(e=>e.id),f=c.filter(e=>!e.revoked&&!e.scopes?.includes(`offline_access`)).map(e=>e.id),p=t.disableJwtPlugin?[]:u.filter(e=>!!e.backchannelLogoutUri&&!e.disabled);return{accessTokenIds:d,refreshTokenIds:f,sessionId:r,targets:(await Promise.all(p.map(async e=>{try{return{client:e,sub:await Kl(i,e,t)}}catch(t){return a.warn(`back-channel logout: unable to resolve subject for client ${e.clientId}`,t),null}}))).filter(e=>e!==null)}}catch(e){return a.error(`back-channel logout planning failed`,e),null}}async function Cg(e,t){let n=new Date,r=await pd(e.context.adapter),i=await Promise.allSettled([t.accessTokenIds.length>0?r.updateMany({model:`oauthAccessToken`,where:[{field:`id`,operator:`in`,value:t.accessTokenIds}],update:{revoked:n}}):Promise.resolve(),t.refreshTokenIds.length>0?r.updateMany({model:`oauthRefreshToken`,where:[{field:`id`,operator:`in`,value:t.refreshTokenIds}],update:{revoked:n}}):Promise.resolve()]);for(let t of i)t.status===`rejected`&&e.context.logger.error(`back-channel logout: token revocation update failed`,t.reason);t.targets.length>0&&await wg(e,t)}async function wg(e,t){let n=e.context.logger,r=pl(e.context)?.options,i=r?.jwt?.issuer??e.context.baseURL,a=Math.floor(Date.now()/1e3),o=a+yg,s=r?.jwt?.sign?null:await Bp(e,r);await Promise.allSettled(t.targets.map(async({client:c,sub:l})=>{try{let u=Fi(32,`a-z`,`A-Z`,`0-9`),d=await xg(e,r,s,{iss:i,aud:c.clientId,sub:l,sid:t.sessionId,iat:a,exp:o,jti:u}),f=await fetch(c.backchannelLogoutUri,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`},body:new URLSearchParams({logout_token:d}),signal:AbortSignal.timeout(bg),redirect:`error`});f.status!==200&&f.status!==204&&n.warn(`back-channel logout to client ${c.clientId} returned ${f.status}`)}catch(e){n.warn(`back-channel logout to client ${c.clientId} failed`,e)}}))}var Tg=300,Eg=`.oauth_logout_confirmation`;function Dg(e){return e.replace(/[&<>"']/g,e=>{switch(e){case`&`:return`&amp;`;case`<`:return`&lt;`;case`>`:return`&gt;`;case`"`:return`&quot;`;case`'`:return`&#39;`;default:return e}})}function Og(e){let t=e.request?.headers??e.headers;if(!t||ug(t))return!1;let n=t.get(`accept`)??``;return t.get(`sec-fetch-mode`)===`navigate`||n.includes(`text/html`)||n.includes(`application/xhtml+xml`)}function kg(e,t,n=200){return new Response(`<!doctype html><html><head><meta charset="utf-8"><title>${Dg(e)}</title></head><body>${t}</body></html>`,{status:n,headers:{"cache-control":`no-store`,"content-security-policy":`default-src 'none'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,"content-type":`text/html; charset=utf-8`,pragma:`no-cache`,"x-content-type-options":`nosniff`}})}function Ag(e){return`${e.context.baseURL.replace(/\/$/,``)}/oauth2/end-session/confirm`}function jg(e){try{return new URL(Ag(e)).pathname}catch{return`/oauth2/end-session/confirm`}}function Mg(e){return kg(`Confirm logout`,`<main><h1>Confirm logout</h1><p>Do you want to log out of this account?</p><form method="post" data-oidc-logout-confirmation action="${Dg(Ag(e))}"><button type="submit" name="action" value="confirm">Confirm logout</button></form></main>`)}function Ng(e){return kg(`Logged out`,`<main><p data-oidc-logout-state="logged-out">${e?`Logged out. ${Dg(e)}`:`Logged out.`}</p></main>`)}function Pg(e,t){return kg(`Logout error`,`<main><h1>Logout error</h1><p data-oidc-logout-state="error">${Dg(e)}</p></main>`,t)}function Fg(e,t,n,r){if(Og(e))return Pg(r,t===`BAD_REQUEST`?400:t===`UNAUTHORIZED`?401:500);throw new z(t,{error:n,error_description:r})}function Ig(e){return`${e.context.authCookies.sessionToken.name}${Eg}`}function Lg(e,t){return{...e.context.authCookies.sessionToken.attributes,httpOnly:!0,maxAge:t,path:jg(e),sameSite:`lax`}}async function Rg(e,t,n={}){let r={...t?{sessionId:t}:{},...n,expiresAt:Date.now()+Tg*1e3};await e.setSignedCookie(Ig(e),JSON.stringify(r),e.context.secret,Lg(e,Tg))}async function zg(e){let t=await e.getSignedCookie(Ig(e),e.context.secret);if(typeof t!=`string`)return null;try{let e=JSON.parse(t);if(typeof e!=`object`||!e)return null;let n=e;return n.sessionId!==void 0&&(typeof n.sessionId!=`string`||n.sessionId.length===0)||n.clientId!==void 0&&(typeof n.clientId!=`string`||n.clientId.length===0)||n.postLogoutRedirectUri!==void 0&&(typeof n.postLogoutRedirectUri!=`string`||n.postLogoutRedirectUri.length===0)||n.state!==void 0&&typeof n.state!=`string`||n.redirectInvalid!==void 0&&typeof n.redirectInvalid!=`boolean`||n.postLogoutRedirectUri!==void 0&&n.clientId===void 0||typeof n.expiresAt!=`number`||!Number.isFinite(n.expiresAt)?null:{...typeof n.sessionId==`string`?{sessionId:n.sessionId}:{},...typeof n.clientId==`string`?{clientId:n.clientId}:{},...typeof n.postLogoutRedirectUri==`string`?{postLogoutRedirectUri:n.postLogoutRedirectUri}:{},...typeof n.state==`string`?{state:n.state}:{},...typeof n.redirectInvalid==`boolean`?{redirectInvalid:n.redirectInvalid}:{},expiresAt:n.expiresAt}}catch{return null}}function Bg(e){e.setCookie(Ig(e),``,Lg(e,0))}async function Vg(e){let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(typeof t!=`string`||t.length===0)return null;try{let n=await e.context.internalAdapter.findSession(t);return n?{session:n.session}:null}catch(t){throw e.context.logger.error(`Failed to read the current logout session`,t),new z(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to read the current session`})}}async function Hg(e,t){try{return await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:t}]})}catch(t){throw e.context.logger.error(`Failed to read the hinted logout session`,t),new z(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to read the hinted session`})}}async function Ug(e,t){if(typeof t.token!=`string`||t.token.length===0)throw new z(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to complete logout`});try{await e.context.internalAdapter.deleteSession(t.token)}catch(t){throw e.context.logger.error(`Failed to delete the logout session`,t),new z(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to complete logout`})}}async function Wg(e,t,n){try{return await xl(e,t,n)}catch(t){throw e.context.logger.error(`Failed to resolve the logout client`,t),new z(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to resolve the logout client`})}}function Gg(e){return(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`)}function Kg(e){if(typeof e.aud==`string`&&e.aud.length>0)return e.aud;if(typeof e.azp==`string`&&e.azp.length>0)return e.azp;let t=Gg(e.aud);return t.length===1?t[0]:null}async function qg(e,t,n,r){if(r)return Wg(e,t,r);let i;try{i=yi(n)}catch{return null}let a=Kg(i);return a?Wg(e,t,a):null}async function Jg(e,t,n,r){try{let i;if(t.disableJwtPlugin){if(!r.clientSecret)return null;let a=await wl(e,t.storeClientSecret,r.clientSecret),{payload:o}=await br(n,new TextEncoder().encode(a));i=JSON.parse(new TextDecoder().decode(o))}else{let t=pl(e.context).options,{payload:r}=await br(n,hi(await Pc(n,{jwksFetch:t?.jwks?.remoteUrl??`${e.context.baseURL}${t?.jwks?.jwksPath??`/jwks`}`})));i=JSON.parse(new TextDecoder().decode(r))}return i.iss!==Hy(e,t)||!Gg(i.aud).includes(r.clientId)||typeof i.sid!=`string`||i.sid.length===0||typeof i.sub!=`string`||i.sub.length===0?null:i}catch{return null}}function Yg(e,t,n){if(!t)return{invalid:!1};if(!e.postLogoutRedirectUris?.includes(t))return{invalid:!0};if(!n)return{uri:t,invalid:!1};try{let e=new URL(t);return e.searchParams.set(`state`,n),{uri:e.toString(),invalid:!1}}catch{return{invalid:!0}}}function Xg(e,t){return t.post_logout_redirect_uri?Yg(e,t.post_logout_redirect_uri,t.state).invalid?{redirectInvalid:!0}:{clientId:e.clientId,postLogoutRedirectUri:t.post_logout_redirect_uri,...t.state===void 0?{}:{state:t.state}}:{}}async function Zg(e,t,n){if(n.redirectInvalid)return{invalid:!0};if(!n.clientId||!n.postLogoutRedirectUri)return{invalid:!1};let r=await Wg(e,t,n.clientId);return!r||r.disabled||!r.enableEndSession?{invalid:!0}:Yg(r,n.postLogoutRedirectUri,n.state)}async function Qg(e,t,n={}){return t?Og(e)?(await Rg(e,t.session.id,n),Mg(e)):Fg(e,`BAD_REQUEST`,`invalid_request`,`User confirmation is required to complete logout`):Og(e)?(await Rg(e,void 0,n),Mg(e)):Fg(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`)}async function $g(e,t){let n=await zg(e),r=await Vg(e);if(!n||n.expiresAt<=Date.now())return Fg(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`);let i=await Zg(e,t,n);return r?n.sessionId&&n.sessionId!==r.session.id?Fg(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`):(await Ug(e,r.session),Uf(e),Bg(e),i.uri?$(e,i.uri):Og(e)?Ng(i.invalid?`The requested post-logout redirect was not registered.`:void 0):null):(Bg(e),i.uri?$(e,i.uri):Og(e)?Ng(i.invalid?`The requested post-logout redirect was not registered.`:void 0):Fg(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`))}async function e_(e,t){let n=e.query??{},r=e.body??{},i={...n,...r},a=await Vg(e);if(i.id_token_hint===void 0){let n={};if(i.client_id){let r=await Wg(e,t,i.client_id);if(!r)return Fg(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(r.disabled)return Fg(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!r.enableEndSession)return Fg(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);n=Xg(r,i)}return Qg(e,a,n)}let o=await qg(e,t,i.id_token_hint,i.client_id);if(!o)return a&&Og(e)?Qg(e,a):Fg(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(o.disabled)return Fg(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!o.enableEndSession)return Fg(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);let s=await Jg(e,t,i.id_token_hint,o);if(!s)return a&&Og(e)?Qg(e,a,i.client_id?Xg(o,i):{}):Fg(e,`UNAUTHORIZED`,`invalid_token`,`The id_token_hint is invalid`);let c=s.sid,l=await Hg(e,c),u=a?.session.id===c;if(a&&!u)return Qg(e,a,Xg(o,i));let d=Yg(o,i.post_logout_redirect_uri,i.state),f=l??(u?a?.session:null);return f&&await Ug(e,f),u&&Uf(e),Bg(e),d.uri?$(e,d.uri):Og(e)?Ng(d.invalid?`The requested post-logout redirect was not registered.`:void 0):null}async function t_(e,t){return $g(e,t)}function n_(e,t,n){let r=e.context.baseURL,i=!n?.jwt_disabled;return{scopes_supported:n?.scopes_supported,issuer:Vy(t?.jwt?.issuer??r),authorization_endpoint:`${r}/oauth2/authorize`,token_endpoint:`${r}/oauth2/token`,jwks_uri:n?.jwt_disabled?void 0:t?.jwks?.remoteUrl??`${r}${t?.jwks?.jwksPath??`/jwks`}`,registration_endpoint:n?.dynamic_client_registration_supported?`${r}/oauth2/register`:void 0,introspection_endpoint:`${r}/oauth2/introspect`,revocation_endpoint:`${r}/oauth2/revoke`,response_types_supported:n?.grant_types_supported&&!n.grant_types_supported.includes(`authorization_code`)?[]:[`code`],response_modes_supported:[`query`],grant_types_supported:n?.grant_types_supported??[`authorization_code`,`client_credentials`,`refresh_token`],token_endpoint_auth_methods_supported:n?.token_endpoint_auth_methods_supported??[...n?.public_client_supported?[`none`]:[],`client_secret_basic`,`client_secret_post`,`private_key_jwt`],token_endpoint_auth_signing_alg_values_supported:[...gs],introspection_endpoint_auth_methods_supported:n?.endpoint_auth_methods_supported??[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],introspection_endpoint_auth_signing_alg_values_supported:[...gs],revocation_endpoint_auth_methods_supported:n?.endpoint_auth_methods_supported??[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],revocation_endpoint_auth_signing_alg_values_supported:[...gs],code_challenge_methods_supported:[`S256`],authorization_response_iss_parameter_supported:!0,dpop_signing_alg_values_supported:n?.dpop_signing_alg_values_supported??[...oc],backchannel_logout_supported:i,backchannel_logout_session_supported:i}}function r_(e,t){let n=t.disableJwtPlugin?void 0:pl(e.context).options,r=Yc(t),i=t.allowUnauthenticatedClientRegistration||r.length>0;return{jwtPluginOptions:n,clientDiscoveries:r,authMetadata:n_(e,n,{scopes_supported:t.advertisedMetadata?.scopes_supported??t.scopes,dynamic_client_registration_supported:t.allowDynamicClientRegistration,public_client_supported:i,grant_types_supported:Qc(t),token_endpoint_auth_methods_supported:tl(t,{includeNone:i}),endpoint_auth_methods_supported:tl(t),jwt_disabled:t.disableJwtPlugin,dpop_signing_alg_values_supported:t.dpop?.signingAlgorithms})}}function i_(e,t){let{clientDiscoveries:n,authMetadata:r}=r_(e,t);return il(e,t,`oauth-authorization-server`,{...Sl(n),...r})}function a_(e,t){let n=e.context.baseURL,{jwtPluginOptions:r,clientDiscoveries:i,authMetadata:a}=r_(e,t),o={...a,claims_supported:sm(t),claims_parameter_supported:!0,userinfo_endpoint:`${n}/oauth2/userinfo`,subject_types_supported:t.pairwiseSecret?[`public`,`pairwise`]:[`public`],acr_values_supported:[`0`],id_token_signing_alg_values_supported:(()=>{if(t.disableJwtPlugin)return[`HS256`];let e=r?.jwks?.keyPairConfig?.alg??`EdDSA`,n=r?.jwks?.keyPairConfigs?.map(e=>e.alg)??[];return Array.from(new Set([e,...n]))})(),end_session_endpoint:`${n}/oauth2/end-session`,request_parameter_supported:!1,request_uri_parameter_supported:!1,prompt_values_supported:[`login`,`consent`,`create`,`select_account`,`none`]};return il(e,t,`openid-configuration`,{...Sl(i),...o})}var o_=`public, max-age=15, stale-while-revalidate=15, stale-if-error=86400`;function s_(e,t){let n=new Headers(t);return n.has(`Cache-Control`)||n.set(`Cache-Control`,o_),n.set(`Content-Type`,`application/json`),new Response(JSON.stringify(e),{status:200,headers:n})}function c_(e,t,n){let{redirectOnError:r,onValidationError:i,errorCodesByField:a,defaultError:o=`invalid_request`,...s}=t;if(!r)return X(e,{...s,onValidationError:async e=>{throw i&&await i(e),new z(`BAD_REQUEST`,{...l_(e.issues,a,o)})}},n);let c=r,{body:l,query:u,...d}=s;async function f(e,t,n){if(!n)return{ok:!0};let r=await n.safeParseAsync(e[t]??{});return r.success?(e[t]=r.data,{ok:!0}):(i&&await i({message:r.error.message,issues:r.error.issues}),{ok:!1,response:c({...l_(r.error.issues,a,o),ctx:e})})}return X(e,d,async e=>{let t=await f(e,`body`,l);if(!t.ok)return t.response;let r=await f(e,`query`,u);return r.ok?n(e):r.response})}function l_(e,t,n=`invalid_request`){let r=e[0];if(!r)return{error:n,error_description:`Invalid request.`};let i=r.path?.[0],a=typeof i==`string`?i:void 0,o=a?t?.[a]:void 0,s=r.path?.length?g(r.path):``;return{error:u_(r,o,n),error_description:f_(r,s)}}function u_(e,t,n){return typeof t==`string`?t:d_(e)?t?.missing??n:e.code===`invalid_value`?t?.invalid??n:n}function d_(e){return e.code===`invalid_type`&&e.message.endsWith(`received undefined`)}function f_(e,t){if(!t)return e.message;if(e.code===`invalid_type`)return e.message.endsWith(`received undefined`)?`${t} is required`:e.message.endsWith(`received array`)?`${t} must not appear more than once`:`${t} must be a ${e.expected??`valid value`}`;if(e.code===`invalid_value`){let n=e.values;if(Array.isArray(n)&&n.length>0)return`${t} must be one of: ${n.join(`, `)}`}return`${t}: ${e.message}`}var p_=e=>du(async t=>{if(!e.allowPublicClientPrelogin)throw new B(`BAD_REQUEST`);let n=t.body.oauth_query;if(!await bl(n,t.context.secret))throw new B(`UNAUTHORIZED`,{error:`invalid_signature`})}),m_={"P-256":`ES256`,"P-384":`ES384`,"P-521":`ES512`},h_=[`Ed25519`],g_=[`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`];function __(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function v_(e,t){return typeof e[t]==`string`&&e[t].length>0}function y_(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call(m_,e)}function b_(e){return h_.some(t=>t===e)}function x_(e){switch(e.kty){case`RSA`:return v_(e,`n`)&&v_(e,`e`);case`EC`:return y_(e.crv)&&v_(e,`x`)&&v_(e,`y`);case`OKP`:return b_(e.crv)&&v_(e,`x`);default:return!1}}function S_(e){if(e.alg===void 0)return!0;if(typeof e.alg!=`string`||!gs.some(t=>t===e.alg))return!1;switch(e.kty){case`RSA`:return e.alg.startsWith(`RS`)||e.alg.startsWith(`PS`);case`EC`:return y_(e.crv)&&m_[e.crv]===e.alg;case`OKP`:return b_(e.crv)&&e.alg===`EdDSA`;default:return!1}}function C_(e){let t=__(e)&&Array.isArray(e.keys)?e.keys:void 0;if(!t?.length)return{valid:!1,error:`jwks must be an RFC 7517 JWK Set object with a non-empty keys array`};for(let e of t){if(!__(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(e.kty===`oct`||`k`in e||g_.some(t=>t in e))return{valid:!1,error:`jwks must contain only public asymmetric keys`};if(!x_(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(!S_(e))return{valid:!1,error:`jwks key alg must be supported for private_key_jwt and compatible with its key type and signing curve`}}return{valid:!0,jwks:{keys:t}}}var w_=Object.freeze(Object.keys({clientId:!0,clientSecret:!0,clientDiscoveryId:!0,disabled:!0,scopes:!0,clientCredentialsScopes:!0,userId:!0,createdAt:!0,updatedAt:!0,expiresAt:!0,name:!0,uri:!0,icon:!0,contacts:!0,tos:!0,policy:!0,softwareId:!0,softwareVersion:!0,softwareStatement:!0,redirectUris:!0,postLogoutRedirectUris:!0,backchannelLogoutUri:!0,backchannelLogoutSessionRequired:!0,tokenEndpointAuthMethod:!0,grantTypes:!0,responseTypes:!0,applicationType:!0,jwks:!0,jwksUri:!0,requirePKCE:!0,dpopBoundAccessTokens:!0,skipConsent:!0,enableEndSession:!0,subjectType:!0,referenceId:!0,metadata:!0})),T_=`client_id.client_secret.client_secret_expires_at.scope.user_id.client_id_issued_at.client_name.client_uri.logo_uri.contacts.tos_uri.policy_uri.jwks.jwks_uri.software_id.software_version.software_statement.redirect_uris.post_logout_redirect_uris.backchannel_logout_uri.backchannel_logout_session_required.token_endpoint_auth_method.grant_types.response_types.application_type.disabled.skip_consent.enable_end_session.require_pkce.dpop_bound_access_tokens.subject_type.reference_id`.split(`.`),E_=new Set([...w_,...T_,`public`,`type`,`resources`,`client_credentials_scopes`]);function D_(e){if(e)return Object.fromEntries(Object.entries(e).filter(([e])=>!E_.has(e)))}async function O_(e,t,n,r,i){if(!t)throw new B(`UNAUTHORIZED`);if(!e.headers)throw new B(`BAD_REQUEST`);if(r===`configure-client-credentials-scopes`&&!n.clientPrivileges||n.clientPrivileges&&!await n.clientPrivileges({headers:e.headers,action:r,session:t.session,user:t.user,clientId:i}))throw new B(`UNAUTHORIZED`)}async function k_(e,t,n,r,i){if(!t)throw new B(`UNAUTHORIZED`);if(!e.headers)throw new B(`BAD_REQUEST`);if(n.resourcePrivileges&&!await n.resourcePrivileges({headers:e.headers,action:r,session:t.session,user:t.user,resourceId:i}))throw new B(`UNAUTHORIZED`)}var A_=Ce({consumeClientAssertion:()=>Y_,isPrivateHostname:()=>V_,verifyClientAssertion:()=>X_}),j_=new WeakMap,M_=3e5,N_=500,P_=5e3,F_=65536,I_=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i;function L_(e,t,n,r){if(e.set(t,{jwks:n,fetchedAt:r}),e.size>N_){let t=e.keys().next().value;t!==void 0&&e.delete(t)}}function R_(e){let t=j_.get(e);if(t)return t;let n=new Map;return j_.set(e,n),n}function z_(e){return`${e.clientDiscoveryId??`managed`}:${e.jwksUri??``}`}var B_=[...gs];function V_(e){return!xp(e)}function H_(e,t,n){let r=new URL(t);if(r.protocol!==`https:`)throw new z(`BAD_REQUEST`,{error_description:`jwks_uri must use HTTPS`,error:`invalid_client`});if(r.username||r.password)throw new z(`BAD_REQUEST`,{error_description:`jwks_uri must not contain credentials`,error:`invalid_client`});if(t.includes(`#`))throw new z(`BAD_REQUEST`,{error_description:`jwks_uri must not include a fragment component`,error:`invalid_client`});if(V_(r.hostname))throw new z(`BAD_REQUEST`,{error_description:`jwks_uri must not point to a private or reserved address`,error:`invalid_client`});if(!(n&&r.origin===n)&&!e.context.isTrustedOrigin(r.href))throw new z(`BAD_REQUEST`,{error_description:`client jwks_uri is not trusted`,error:`invalid_client`})}function U_(e){try{let t=new URL(e);return t.protocol!==`https:`&&t.protocol!==`http:`?void 0:t.origin}catch{return}}async function W_(e){let t=e.headers.get(`content-length`);if(t!==null&&Number.isFinite(Number(t))&&Number(t)>F_)throw await e.body?.cancel(),Error(`JWKS response exceeds 64 KiB`);if(!e.body)return``;let n=e.body.getReader(),r=[],i=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;if(i+=t.byteLength,i>F_)throw await n.cancel(),Error(`JWKS response exceeds 64 KiB`);r.push(t)}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return new TextDecoder().decode(a)}async function G_(e,t=globalThis.fetch){let n=new AbortController,r=setTimeout(()=>n.abort(),P_);try{let r=await t(e,{signal:n.signal,headers:{accept:`application/json`},redirect:`error`});if(r.redirected)throw Error(`JWKS fetch redirected`);if(r.status!==200)throw Error(`JWKS fetch returned ${r.status}`);let i=r.headers.get(`content-type`);if(!i||!I_.test(i))throw Error(`JWKS response must use a JSON media type`);let a=await W_(r),o;try{o=JSON.parse(a)}catch{return{valid:!1}}let s=C_(o);return s.valid?{valid:!0,jwks:s.jwks}:{valid:!1}}finally{clearTimeout(r)}}function K_(){return new z(`BAD_REQUEST`,{error_description:`failed to fetch client JWKS`,error:`invalid_client`})}async function q_(e,t,n){if(n.jwks)return JSON.parse(n.jwks);if(!n.jwksUri)throw new z(`BAD_REQUEST`,{error_description:`client has no JWKS configured`,error:`invalid_client`});let r=n.clientDiscoveryId?Yc(t).find(e=>e.id===n.clientDiscoveryId):void 0;if(n.clientDiscoveryId&&!r?.fetchClientMetadataResource)throw new z(`BAD_REQUEST`,{error_description:`client discovery does not provide a metadata resource transport`,error:`invalid_client`});H_(e,n.jwksUri,n.clientDiscoveryId?U_(n.clientId):void 0);let i=Date.now(),a=z_(n),o=R_(t),s=o.get(a);if(s&&i-s.fetchedAt<M_)return s.jwks;let c;try{c=await G_(n.jwksUri,r?.fetchClientMetadataResource)}catch{let e=M_*2;if(s&&i-s.fetchedAt<e)return s.jwks;throw K_()}if(!c.valid)throw K_();return L_(o,a,c.jwks,i),c.jwks}async function J_(e,t){if(!t.jwksUri)return null;let n=t.clientDiscoveryId?Yc(e).find(e=>e.id===t.clientDiscoveryId):void 0;if(t.clientDiscoveryId&&!n?.fetchClientMetadataResource)return null;try{let r=await G_(t.jwksUri,n?.fetchClientMetadataResource);return r.valid?(L_(R_(e),z_(t),r.jwks,Date.now()),r.jwks):null}catch{return null}}async function Y_(e,t,n){let{namespace:r,payload:i,expectedAudience:a}=n;if(!(Array.isArray(i.aud)?i.aud:i.aud==null?[]:[i.aud]).includes(a))throw new z(`BAD_REQUEST`,{error_description:`client assertion aud does not match the endpoint`,error:`invalid_client`});let o=t.assertionMaxLifetime??300,s=Math.floor(Date.now()/1e3);if(typeof i.exp!=`number`)throw new z(`BAD_REQUEST`,{error_description:`client assertion must include exp claim`,error:`invalid_client`});if(i.exp<=s)throw new z(`BAD_REQUEST`,{error_description:`client assertion has expired`,error:`invalid_client`});if(i.exp-s>o)throw new z(`BAD_REQUEST`,{error_description:`client assertion exp is too far in the future (max ${o}s)`,error:`invalid_client`});if(typeof i.iat==`number`&&s-i.iat>o)throw new z(`BAD_REQUEST`,{error_description:`client assertion iat is too far in the past (max ${o}s)`,error:`invalid_client`});if(typeof i.jti!=`string`||i.jti.length===0)throw new z(`BAD_REQUEST`,{error_description:`client assertion must include jti claim`,error:`invalid_client`});let c=await Li(`SHA-256`).digest(new TextEncoder().encode(`${r}:${i.jti}`)),l=me(new Uint8Array(c).slice(0,24),e.context.options);try{await e.context.adapter.create({model:`oauthClientAssertion`,data:{id:l,expiresAt:new Date(i.exp*1e3)},forceAllowId:!0})}catch(t){let n=!1;try{n=!!await e.context.adapter.findOne({model:`oauthClientAssertion`,where:[{field:`id`,value:l}]})}catch{}throw n?new z(`BAD_REQUEST`,{error_description:`client assertion jti has already been used`,error:`invalid_client`}):t}}async function X_(e,t,n,r,i,a){if(r!==`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)throw new z(`BAD_REQUEST`,{error_description:`unsupported client_assertion_type`,error:`invalid_client`});let o;try{o=vi(n)}catch{throw new z(`BAD_REQUEST`,{error_description:`malformed client assertion: invalid JWT header`,error:`invalid_client`})}if(!o.alg||!B_.includes(o.alg))throw new z(`BAD_REQUEST`,{error_description:`unsupported assertion signing algorithm: ${o.alg}`,error:`invalid_client`});let s;try{s=yi(n)}catch{throw new z(`BAD_REQUEST`,{error_description:`malformed client assertion: invalid JWT payload`,error:`invalid_client`})}let c=s.sub??s.iss;if(!c)throw new z(`BAD_REQUEST`,{error_description:`client assertion must contain sub or iss claim identifying the client`,error:`invalid_client`});if(i&&i!==c)throw new z(`BAD_REQUEST`,{error_description:`client_id in body does not match assertion sub/iss`,error:`invalid_client`});let l=await xl(e,t,c);if(!l)throw new z(`BAD_REQUEST`,{error_description:`unknown client`,error:`invalid_client`});if(l.disabled)throw new z(`BAD_REQUEST`,{error_description:`client is disabled`,error:`invalid_client`});if(l.tokenEndpointAuthMethod!==`private_key_jwt`)throw new z(`BAD_REQUEST`,{error_description:`client is not registered for private_key_jwt authentication`,error:`invalid_client`});let u=await q_(e,t,l),d=a??`${e.context.baseURL}/oauth2/token`,f=Hy(e,t),p=[...new Set([d,f])],m={issuer:c,subject:c,audience:p,algorithms:B_},h;try{({payload:h}=await Vr(n,hi(u),m))}catch(e){if(e instanceof Error&&/no matching key|no applicable key/i.test(e.message)){let e=await J_(t,l);if(e)try{({payload:h}=await Vr(n,hi(e),m))}catch{throw new z(`UNAUTHORIZED`,{error_description:`client assertion signature verification failed`,error:`invalid_client`})}else throw new z(`UNAUTHORIZED`,{error_description:`client assertion signature verification failed`,error:`invalid_client`})}else throw new z(`UNAUTHORIZED`,{error_description:`client assertion signature verification failed`,error:`invalid_client`})}let g=(Array.isArray(h.aud)?h.aud:[h.aud]).find(e=>typeof e==`string`&&p.includes(e));return await Y_(e,t,{namespace:`private_key_jwt:${c}`,payload:h,expectedAudience:g}),{clientId:c}}function Z_(e,t,n){return new z(e,{error:t,error_description:n},{"WWW-Authenticate":`Bearer error="${t}"`,...cu})}async function Q_(e,t,n){let r=e.headers,i;try{i=ul(r?.get(`authorization`))}catch{throw Z_(`BAD_REQUEST`,`invalid_request`,`Malformed initial access token Authorization header`)}if(!i||!r)return;if(!t.validateInitialAccessToken)throw Z_(`UNAUTHORIZED`,`invalid_token`,`Invalid initial access token`);let a;try{a=await t.validateInitialAccessToken({initialAccessToken:i,headers:r,clientMetadata:n})}catch(e){throw e instanceof z?e:new z(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Initial access token validation failed`})}if(!a)throw Z_(`UNAUTHORIZED`,`invalid_token`,`Invalid initial access token`);return a}var $_=[`authorization_code`];function ev(e){return[...new Set([...e.clientRegistrationDefaultScopes??e.scopes??[],...e.clientRegistrationAllowedScopes??[]])]}function tv(e){let t=e.grant_types??[...$_];if(t.length>0)return t;throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`grant_types must contain at least one grant type`})}function nv(e,t){return e.response_types?e.response_types:t.includes(`authorization_code`)?[`code`]:void 0}function rv(e,t=`web`){let n=tv(e);return{...e,token_endpoint_auth_method:e.token_endpoint_auth_method??`client_secret_basic`,application_type:e.application_type??(t===null?void 0:t),grant_types:n,response_types:nv(e,n)}}function iv(e){let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`&&t.host!==``}function av(e){try{let t=new URL(e).protocol;return t!==`http:`&&t!==`https:`}catch{return!1}}function ov(e,t){let n=e.clientRegistrationDefaultApplicationType??`web`;return n===`infer`?(t.redirect_uris??[]).some(av)?`native`:`web`:n}function sv(e){throw new B(`BAD_REQUEST`,{error:`invalid_redirect_uri`,error_description:e})}function cv(e){let t=/^http:\/\/([^/?#]*)/i.exec(e)?.[1];if(!t)return null;let n=t.slice(t.lastIndexOf(`@`)+1);if(n.startsWith(`[`)){let e=n.indexOf(`]`);return e<0?null:n.slice(0,e+1).toLowerCase()}return(n.split(`:`)[0]??``).toLowerCase()}function lv(e,t){let n=new Set([...e.clientRegistrationDefaultResources??[],...e.clientRegistrationAllowedResources??[]]);for(let e of t)if(!n.has(e))throw new B(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${e} is not allowed for client registration`})}async function uv(e,t,n){let r=t.clientRegistrationDefaultResources??[],i=[...new Set([...r,...n])];for(let n of i){let r=await Rm(e,t,n);if(!r)throw new B(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} does not exist`});if(r.disabled)throw new B(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is disabled`})}return i}function dv(e,t){let n;try{n=new URL(e)}catch{sv(`redirect URI must be an absolute URI: ${e}`)}(e.includes(`#`)||n.username.length>0||n.password.length>0)&&sv(`redirect URI must not include credentials or a fragment: ${e}`);let r=n.protocol===`http:`,i=n.protocol===`https:`;/^localhost\.+$/i.test(n.hostname)&&sv(`redirect URI localhost must not include trailing dots: ${e}`);let a=yp(n.hostname)||n.hostname===`localhost`,o=cv(e);t===`web`?(!i||a)&&sv(`web clients require https redirect URIs on non-loopback hosts: ${e}`):i?a&&sv(`native clients must not use https loopback redirect URIs: ${e}`):r?o===`localhost`||o===`127.0.0.1`||o===`[::1]`||sv(`native clients may use http only on the exact loopback hosts localhost, 127.0.0.1, or [::1]: ${e}`):Fp(n)||sv(`native private-use redirect URI schemes must not use a reserved scheme; they must be an authority-free reverse-domain URI or a custom-scheme URI with a host and a path: ${e}`)}function fv(e){let t=C_(e);if(!t.valid)throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:t.error})}async function pv(e,t){let n=e.body;if(!t.allowDynamicClientRegistration)throw new B(`FORBIDDEN`,{error:`access_denied`,error_description:`Client registration is disabled`});let r=await Z(e),i=r?void 0:await Q_(e,t,n),a=!!i;if(!(r||a||t.allowUnauthenticatedClientRegistration))throw new B(`UNAUTHORIZED`,{error_description:`Authentication required for client registration`},{"WWW-Authenticate":`Bearer`,...cu});if(!r&&!a&&n.grant_types?.includes(`client_credentials`))throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`client_credentials grant requires authenticated registration`});let o=Array.isArray(n.resources)?n.resources.filter(e=>typeof e==`string`&&e.length>0):[];r&&await O_(e,r,t,`create`);let s=i?.referenceId??(r&&t.clientReference?await t.clientReference({user:r.user,session:r.session}):void 0),c=await yv(e,t,{metadata:n,registrationSource:`dynamic`,userId:s?void 0:r?.session.userId,referenceId:s,requestedResources:o});return e.setStatus(201),e.json(c)}async function mv(e,t,n){let r=n?.registrationSource===`clientMetadataDocument`,i=rv(e,r?null:n?.registrationSource===`dynamic`?ov(t,e):`web`),a=i.token_endpoint_auth_method??`client_secret_basic`;if(!new Set(tl(t,{includeNone:!0})).has(a))throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`unsupported token_endpoint_auth_method ${a}`});if(i.dpop_bound_access_tokens!==void 0&&typeof i.dpop_bound_access_tokens!=`boolean`)throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`dpop_bound_access_tokens must be a boolean`});let o=i.grant_types??[],s=i.response_types,c=i.application_type;if(c!==void 0&&c!==`web`&&c!==`native`)throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`application_type must be web or native`});if(o.includes(`authorization_code`)&&(!i.redirect_uris||i.redirect_uris.length===0))throw new B(`BAD_REQUEST`,{error:`invalid_redirect_uri`,error_description:`Redirect URIs are required for authorization_code and implicit grant types`});for(let e of i.redirect_uris??[])dv(e,c??(r?`native`:`web`));let l=new Set(Qc(t));if(r){if(!o.some(e=>l.has(e)))throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`no mutually supported grant_type among ${o.join(`, `)}`})}else for(let e of o)if(!l.has(e))throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`unsupported grant_type ${e}`});if(o.includes(`authorization_code`)&&!s?.includes(`code`))throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`When 'authorization_code' grant type is used, 'code' response type must be included`});if(!o.includes(`authorization_code`)&&s?.includes(`code`))throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`When 'code' response type is used, 'authorization_code' grant type must be included`});if(i.subject_type!==void 0){if(i.subject_type!==`public`&&i.subject_type!==`pairwise`)throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`subject_type must be "public" or "pairwise"`});if(i.subject_type===`pairwise`&&!t.pairwiseSecret)throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise subject_type requires server pairwiseSecret configuration`});if(i.subject_type===`pairwise`&&i.redirect_uris?.some(iv))throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise clients cannot use custom-scheme redirect URIs that include a host`});if(i.subject_type===`pairwise`&&i.redirect_uris&&i.redirect_uris.length>1&&new Set(i.redirect_uris.map(e=>new URL(e).host)).size>1)throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise clients with redirect_uris on different hosts require a sector_identifier_uri, which is not yet supported. All redirect_uris must share the same host.`})}let u=(i?.scope)?.split(` `).filter(e=>e.length),d=n?.registrationSource===`dynamic`||n?.registrationSource===`clientMetadataDocument`,f=d?ev(t):t.scopes;if(f){let e=new Set(f);for(let t of u??[])if(!e?.has(t))throw new B(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`cannot request scope ${t}`})}if(d&&i.require_pkce===!1)throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pkce is required for registered clients.`});if(i.jwks||i.jwks_uri){if(i.jwks&&i.jwks_uri)throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks and jwks_uri are mutually exclusive`});if(i.jwks_uri)try{let e=new URL(i.jwks_uri);if(e.protocol!==`https:`)throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must use HTTPS`});if(e.username||e.password)throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not contain credentials`});if(i.jwks_uri.includes(`#`))throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not include a fragment component`});if(V_(e.hostname))throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not point to a private or reserved address`});if(n?.ctx&&!n.ctx.context.isTrustedOrigin(e.href)){let t=typeof i.client_id==`string`?i.client_id:void 0;if(!(r&&t!==void 0&&URL.canParse(t)&&new URL(t).origin===e.origin))throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must belong to a trusted origin or the Client ID Metadata Document origin`})}}catch(e){throw e instanceof B?e:new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must be a valid URL`})}i.jwks&&fv(i.jwks)}if(a===`private_key_jwt`&&!i.jwks&&!i.jwks_uri)throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`private_key_jwt requires either jwks or jwks_uri`});if(i.backchannel_logout_uri!==void 0){if(t.disableJwtPlugin)throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri requires the jwt plugin (disableJwtPlugin must be false)`});let e;try{e=new URL(i.backchannel_logout_uri)}catch{throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must be an absolute URL`})}if(i.backchannel_logout_uri.includes(`#`))throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must not include a fragment component`});if(e.protocol!==`https:`)throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must use https`});if(e.username||e.password)throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must not contain credentials`});if(V_(e.hostname))throw new B(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must not point to a private or reserved address`})}}var hv=Symbol(`client-registration-collision`);async function gv(e,t,n){let r=n.registrationSource===`dynamic`&&!n.metadata.scope?{...n.metadata,scope:(t.clientRegistrationDefaultScopes??t.scopes)?.join(` `)}:n.metadata,i=rv(r,n.registrationSource===`clientMetadataDocument`?null:n.registrationSource===`dynamic`?ov(t,r):`web`),a=i.token_endpoint_auth_method===`none`,o=i.token_endpoint_auth_method===`private_key_jwt`,s=nl(t,i.token_endpoint_auth_method);await mv(i,t,{registrationSource:n.registrationSource,ctx:e});let c=n.clientId??t.generateClientId?.()??Fi(32,`a-z`,`A-Z`),l=a||o||s?void 0:t.generateClientSecret?.()||Fi(32,`a-z`,`A-Z`),u=l?await El(e,t,l):void 0,d=n.registrationSource===`dynamic`&&!a&&t.clientRegistrationRequirePKCE===!1,f=i.require_pkce??(!d&&void 0),p=Math.floor(Date.now()/1e3),{resources:m,...h}=n.registrationSource===`dynamic`||n.registrationSource===`clientMetadataDocument`?{...i,scope:ev(t).join(` `)}:i,g=n.registrationSource===`clientMetadataDocument`?void 0:{userId:n.userId,referenceId:n.referenceId},_=Cv({...h,redirect_uris:i.redirect_uris??[],disabled:void 0,client_secret_expires_at:u?n.registrationSource===`dynamic`&&t.clientRegistrationClientSecretExpiration?Lp(t.clientRegistrationClientSecretExpiration,p):0:void 0,client_id:c,client_secret:u,client_id_issued_at:p,require_pkce:f,user_id:g?.referenceId?void 0:g?.userId,reference_id:g?.referenceId});_.clientCredentialsScopes=n.registrationSource===`clientMetadataDocument`?n.existingClient?.clientCredentialsScopes??[]:n.registrationSource===`managed`?n.clientCredentialsScopes??[]:[],_.clientDiscoveryId=n.registrationSource===`clientMetadataDocument`?n.clientDiscoveryId:null,n.registrationSource===`clientMetadataDocument`&&i.application_type===void 0&&(_.applicationType=null);let v=n.registrationSource===`clientMetadataDocument`?[]:n.requestedResources??[];n.registrationSource===`dynamic`&&lv(t,v);let y=await uv(e,t,v),b=t.schema?.oauthClient?.modelName??`oauthClient`,x=t.schema?.oauthClientResource?.modelName??`oauthClientResource`,S=n.registrationSource===`clientMetadataDocument`?n.existingClient:void 0,C=n.registrationSource===`clientMetadataDocument`?n.clientDiscoveryId:null,w=await hd(e.context.adapter,async()=>{let t=await pd(e.context.adapter),r,i=!1;if(S){let e=await t.update({model:b,where:[{field:`clientId`,value:c},{field:`clientDiscoveryId`,value:C}],update:{..._,disabled:S.disabled,skipConsent:S.skipConsent,enableEndSession:S.enableEndSession,createdAt:S.createdAt,updatedAt:new Date(p*1e3)}});if(!e)throw new B(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client no longer exists`});r=e}else{try{r=await t.create({model:b,data:{..._,createdAt:new Date(p*1e3),updatedAt:new Date(p*1e3)}})}catch(e){throw n.registrationSource===`clientMetadataDocument`&&xv(e)?{[hv]:!0,kind:`oauth-client-row-unique`,clientId:c,cause:e}:e}i=!0}let a=y.length===0?[]:await t.findMany({model:x,where:[{field:`clientId`,value:c}]}),o=new Set(a.map(e=>e.resourceId)),s=new Date;for(let e of y)if(!o.has(e))try{await t.create({model:x,data:{clientId:c,resourceId:e,createdAt:s}})}catch(t){throw n.registrationSource===`clientMetadataDocument`&&xv(t)?{[hv]:!0,kind:`oauth-client-resource-link-unique`,clientId:c,resourceId:e,cause:t}:t}return{client:r,created:i}});return{client:w.client,clientSecret:l,resources:y,created:w.created}}function _v(e,t){let n=wv({...e.client,clientSecret:e.clientSecret?(t.prefix?.clientSecret??``)+e.clientSecret:void 0});return e.resources.length>0&&(n.resources=e.resources),n}function vv(e,t){return{..._v(e,t),client_credentials_scopes:[...e.client.clientCredentialsScopes??[]]}}async function yv(e,t,n){return _v(await gv(e,t,n),t)}async function bv(e,t,n){return vv(await gv(e,t,n),t)}function xv(e){if(!e||typeof e!=`object`)return!1;let t=e,n=String(t.code??t.errno??``);return[`1062`,`11000`,`23505`,`ER_DUP_ENTRY`,`P2002`,`SQLITE_CONSTRAINT_UNIQUE`].includes(n)||t.name===`MongoServerError`&&t.code===11e3?!0:typeof t.message==`string`&&/(?:duplicate|unique constraint|unique key)/i.test(t.message)}async function Sv(e,t,n){let r=await Z(e);if(await O_(e,r,t,`create`),!r)throw new B(`UNAUTHORIZED`);let i=t.clientReference?await t.clientReference({user:r.user,session:r.session}):void 0,{client_credentials_scopes:a,...o}=e.body,s=n?.admin?eh(a??[]):[];th(s,tv(o),o.token_endpoint_auth_method,t),s.length>0&&await O_(e,r,t,`configure-client-credentials-scopes`);let c=n?.admin?o.resources:void 0;for(let n of new Set(c??[]))await k_(e,r,t,`link`,n);let l={metadata:o,registrationSource:`managed`,userId:i?void 0:r.session.userId,referenceId:i,clientCredentialsScopes:s,...c?{requestedResources:c}:{}},u=n?.admin?await bv(e,t,l):await yv(e,t,l);return e.setStatus(201),e.json(u)}function Cv(e){let{client_id:t,client_secret:n,client_secret_expires_at:r,scope:i,user_id:a,client_id_issued_at:o,client_name:s,client_uri:c,logo_uri:l,contacts:u,tos_uri:d,policy_uri:f,jwks:p,jwks_uri:m,software_id:h,software_version:g,software_statement:_,redirect_uris:v,post_logout_redirect_uris:y,backchannel_logout_uri:b,backchannel_logout_session_required:x,token_endpoint_auth_method:S,grant_types:C,response_types:w,application_type:T,disabled:E,skip_consent:D,enable_end_session:O,require_pkce:k,dpop_bound_access_tokens:A,subject_type:j,reference_id:M,metadata:N}=e,P=r?new Date(Number(r)*1e3):void 0,F=o?new Date(o*1e3):void 0,I=i?.split(` `),L=D_(N??{}),R=L&&Object.keys(L).length?JSON.stringify(L):void 0;return{clientId:t,clientSecret:n,disabled:E,scopes:I,userId:a,createdAt:F,expiresAt:P,name:s,uri:c,icon:l,contacts:u,tos:d,policy:f,softwareId:h,softwareVersion:g,softwareStatement:_,redirectUris:v,postLogoutRedirectUris:y,backchannelLogoutUri:b,backchannelLogoutSessionRequired:x,tokenEndpointAuthMethod:S,grantTypes:C,responseTypes:w,jwks:p?JSON.stringify(p):void 0,jwksUri:m,applicationType:T,skipConsent:D,enableEndSession:O,requirePKCE:k,dpopBoundAccessTokens:A,subjectType:j,referenceId:M,metadata:R}}function wv(e){let{clientId:t,clientSecret:n,disabled:r,scopes:i,userId:a,createdAt:o,updatedAt:s,expiresAt:c,name:l,uri:u,icon:d,contacts:f,tos:p,policy:m,softwareId:h,softwareVersion:g,softwareStatement:_,redirectUris:v,postLogoutRedirectUris:y,backchannelLogoutUri:b,backchannelLogoutSessionRequired:x,tokenEndpointAuthMethod:S,grantTypes:C,responseTypes:w,applicationType:T,jwks:E,jwksUri:D,skipConsent:O,enableEndSession:k,requirePKCE:A,dpopBoundAccessTokens:j,subjectType:M,referenceId:N,metadata:P}=e,F=c?Math.round(new Date(c).getTime()/1e3):void 0,I=o?Math.round(new Date(o).getTime()/1e3):void 0,L=i?.join(` `);return{...D_(Bl(P)),client_id:t,client_secret:n??void 0,client_secret_expires_at:n?F??0:void 0,scope:L??void 0,user_id:a??void 0,client_id_issued_at:I??void 0,client_name:l??void 0,client_uri:u??void 0,logo_uri:d??void 0,contacts:f??void 0,tos_uri:p??void 0,policy_uri:m??void 0,jwks:E?JSON.parse(E):void 0,jwks_uri:D??void 0,software_id:h??void 0,software_version:g??void 0,software_statement:_??void 0,redirect_uris:v??[],post_logout_redirect_uris:y??void 0,backchannel_logout_uri:b??void 0,backchannel_logout_session_required:x??void 0,token_endpoint_auth_method:S??void 0,grant_types:C??void 0,response_types:w??void 0,application_type:T??void 0,disabled:r??void 0,skip_consent:O??void 0,enable_end_session:k??void 0,require_pkce:A??void 0,dpop_bound_access_tokens:j??void 0,subject_type:M??void 0,reference_id:N??void 0}}async function Tv(e,t){let n=await Z(e);if(await O_(e,n,t,`read`,e.query.client_id),!n)throw new B(`UNAUTHORIZED`);let r=await xl(e,t,e.query.client_id);if(!r)throw new B(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(r.userId){if(r.userId!==n.user.id)throw new B(`UNAUTHORIZED`)}else if(r.referenceId&&t.clientReference){if(r.referenceId!==await t.clientReference(n))throw new B(`UNAUTHORIZED`)}else throw new B(`UNAUTHORIZED`);let i=wv(r);return i.client_secret=void 0,i}async function Ev(e,t,n){let r=await xl(e,t,n);if(!r||r.disabled)throw new B(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});return wv({clientId:r.clientId,name:r.name,uri:r.uri,contacts:r.contacts,icon:r.icon,tos:r.tos,policy:r.policy})}async function Dv(e,t){let n=await Z(e);if(await O_(e,n,t,`list`),!n)throw new B(`UNAUTHORIZED`);let r=await t.clientReference?.(n);if(r)return await e.context.adapter.findMany({model:`oauthClient`,where:[{field:`referenceId`,value:r}]}).then(e=>e?e.map(e=>{let t=wv(e);return t.client_secret=void 0,t}):null);if(n.user.id)return await e.context.adapter.findMany({model:`oauthClient`,where:[{field:`userId`,value:n.user.id}]}).then(e=>e?e.map(e=>{let t=wv(e);return t.client_secret=void 0,t}):null);throw new B(`BAD_REQUEST`,{message:`either user_id or reference_id must be provided`})}async function Ov(e,t){let n=await Z(e);if(await O_(e,n,t,`delete`,e.body.client_id),!n)throw new B(`UNAUTHORIZED`);let r=e.body.client_id;if(t.cachedTrustedClients?.has(r))throw new B(`INTERNAL_SERVER_ERROR`,{error_description:`trusted clients must be updated manually`,error:`invalid_client`});let i=await xl(e,t,r);if(!i)throw new B(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(i.userId){if(i.userId!==n.user.id)throw new B(`UNAUTHORIZED`)}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(n))throw new B(`UNAUTHORIZED`)}else throw new B(`UNAUTHORIZED`);await e.context.adapter.delete({model:`oauthClient`,where:[{field:`clientId`,value:r}]})}async function kv(e,t,n){let r=await Z(e);if(await O_(e,r,t,`update`,e.body.client_id),!r)throw new B(`UNAUTHORIZED`);let i=e.body.client_id;if(t.cachedTrustedClients?.has(i))throw new B(`INTERNAL_SERVER_ERROR`,{error_description:`trusted clients must be updated manually`,error:`invalid_client`});let a=await xl(e,t,i);if(!a)throw new B(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});let{client_credentials_scopes:o,...s}=e.body.update,c=a.userId?a.userId===r.user.id:a.referenceId&&t.clientReference?a.referenceId===await t.clientReference(r):!1,l=!c&&n?.admin&&o!==void 0&&Object.keys(s).length===0;if(!c&&!l)throw new B(`UNAUTHORIZED`);if(l&&await O_(e,r,t,`configure-client-credentials-scopes`,i),Object.keys(s).length===0&&o===void 0){let e=wv(a);return e.client_secret=void 0,n?.admin?{...e,client_credentials_scopes:[...a.clientCredentialsScopes??[]]}:e}let u=s.grant_types??a.grantTypes??[],d=s.token_endpoint_auth_method??a.tokenEndpointAuthMethod,f=o===void 0?void 0:eh(o);f!==void 0&&(th(f,u,d,t),f.length>0&&!l&&await O_(e,r,t,`configure-client-credentials-scopes`,i)),await mv({...wv(a),...s},t,{ctx:e});let p={...Cv(s)};!u.includes(`client_credentials`)||d===`none`?p.clientCredentialsScopes=[]:f!==void 0&&(p.clientCredentialsScopes=f),s.token_endpoint_auth_method&&(s.token_endpoint_auth_method===`private_key_jwt`?p.clientSecret=null:(p.jwks=null,p.jwksUri=null,p.clientSecret||=await El(e,t,t.generateClientSecret?.()||Fi(32,`a-z`,`A-Z`))));let m=await e.context.adapter.update({model:`oauthClient`,where:[{field:`clientId`,value:i}],update:{...p,updatedAt:new Date(Math.floor(Date.now()/1e3)*1e3)}});if(!m)throw new B(`INTERNAL_SERVER_ERROR`,{error_description:`unable to update client`,error:`invalid_client`});let h=wv(m);return h.client_secret=void 0,n?.admin?{...h,client_credentials_scopes:[...m.clientCredentialsScopes??[]]}:h}async function Av(e,t){let n=await Z(e);if(await O_(e,n,t,`rotate`,e.body.client_id),!n)throw new B(`UNAUTHORIZED`);let r=e.body.client_id;if(t.cachedTrustedClients?.has(r))throw new B(`INTERNAL_SERVER_ERROR`,{error_description:`trusted clients must be updated manually`,error:`invalid_client`});let i=await xl(e,t,r);if(!i)throw new B(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(i.userId){if(i.userId!==n.user.id)throw new B(`UNAUTHORIZED`)}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(n))throw new B(`UNAUTHORIZED`)}else throw new B(`UNAUTHORIZED`);if(i.tokenEndpointAuthMethod===`none`||!i.clientSecret)throw new B(`BAD_REQUEST`,{error_description:`secret rotation is only available for clients using client_secret authentication`,error:`invalid_client`});let a=t.generateClientSecret?.()||Fi(32,`a-z`,`A-Z`),o=a?await El(e,t,a):void 0,s=await e.context.adapter.update({model:`oauthClient`,where:[{field:`clientId`,value:r}],update:{clientSecret:o,updatedAt:new Date(Math.floor(Date.now()/1e3)*1e3)}});if(!s)throw new B(`INTERNAL_SERVER_ERROR`,{error_description:`unable to update client`,error:`invalid_client`});return wv({...s,clientSecret:(t.prefix?.clientSecret??``)+a})}var jv=c().trim().min(1),Mv=x(c().trim().min(1)).min(1),Nv=e=>X(`/admin/oauth2/create-client`,{method:`POST`,body:w({redirect_uris:x(Q).min(1).optional(),scope:c().optional(),client_name:c().optional(),client_uri:c().optional(),logo_uri:c().optional(),contacts:x(c().min(1)).min(1).optional(),tos_uri:c().optional(),policy_uri:c().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional(),post_logout_redirect_uris:x(Q).min(1).optional(),backchannel_logout_uri:Q.optional(),backchannel_logout_session_required:v().optional(),token_endpoint_auth_method:jv.optional(),application_type:u([`web`,`native`]).optional(),jwks:hm.optional(),jwks_uri:c().optional(),grant_types:Mv.optional(),client_credentials_scopes:x(c().trim().min(1)).optional(),resources:x(fm).optional(),response_types:x(u([`code`])).optional(),client_secret_expires_at:a([c(),d()]).optional().default(0),skip_consent:v().optional(),enable_end_session:v().optional(),require_pkce:v().optional(),dpop_bound_access_tokens:v().optional(),subject_type:u([`public`,`pairwise`]).optional(),metadata:i(c(),o()).optional()}),metadata:{noStore:!0,SERVER_ONLY:!0,openapi:{description:`Register an OAuth2 application`,responses:{201:{description:`OAuth2 application registered successfully`,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`Unique identifier for the client`},client_secret:{type:`string`,description:`Secret key for the client`},client_secret_expires_at:{type:`number`,description:`Time the client secret will expire. If 0, the client secret will never expire.`},scope:{type:`string`,description:`Space-separated scopes allowed by the client`},client_credentials_scopes:{type:`array`,items:{type:`string`},description:`Server-authorized scope ceiling for client_credentials tokens`},user_id:{type:`string`,description:`ID of the user who registered the client, null if registered anonymously`},client_id_issued_at:{type:`number`,description:`Creation timestamp of this client`},client_name:{type:`string`,description:`Name of the OAuth2 application`},client_uri:{type:`string`,description:`URI of the OAuth2 application`},logo_uri:{type:`string`,description:`Icon URI for the application`},contacts:{type:`array`,items:{type:`string`},description:`List representing ways to contact people responsible for this client, typically email addresses`},tos_uri:{type:`string`,description:`Client's terms of service uri`},policy_uri:{type:`string`,description:`Client's policy uri`},software_id:{type:`string`,description:`Unique identifier assigned by the developer to help in the dynamic registration process`},software_version:{type:`string`,description:`Version identifier for the software_id`},software_statement:{type:`string`,description:`JWT containing metadata values about the client software as claims`},redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed redirect uris`},token_endpoint_auth_method:{type:`string`,description:`Requested authentication method for the token endpoint`},grant_types:{type:`array`,items:{type:`string`},description:`Grant types the client may use at the token endpoint`},response_types:{type:`array`,items:{type:`string`,enum:[`code`]},description:`Response types the client may use at the authorization endpoint`},application_type:{type:`string`,description:`OIDC application type used to classify redirect URI policy`,enum:[`web`,`native`]},resources:{type:`array`,items:{type:`string`,format:`uri`},description:`Final server-owned resources linked to the client`},disabled:{type:`boolean`,description:`Whether the client is disabled`},require_pkce:{type:`boolean`,description:`Whether the client requires PKCE`,default:!0},metadata:{type:`object`,additionalProperties:!0,nullable:!0,description:`Additional metadata for the application`}},required:[`client_id`]}}}}}}}},async t=>Sv(t,e,{admin:!0})),Pv=e=>X(`/oauth2/create-client`,{method:`POST`,use:[qf],body:w({redirect_uris:x(Q).min(1).optional(),scope:c().optional(),client_name:c().optional(),client_uri:c().optional(),logo_uri:c().optional(),contacts:x(c().min(1)).min(1).optional(),tos_uri:c().optional(),policy_uri:c().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional(),post_logout_redirect_uris:x(Q).min(1).optional(),backchannel_logout_uri:Q.optional(),backchannel_logout_session_required:v().optional(),token_endpoint_auth_method:jv.optional(),application_type:u([`web`,`native`]).optional(),jwks:hm.optional(),jwks_uri:c().optional(),grant_types:Mv.optional(),response_types:x(u([`code`])).optional(),dpop_bound_access_tokens:v().optional()}),metadata:{noStore:!0,openapi:{description:`Register an OAuth2 application`,responses:{201:{description:`OAuth2 application registered successfully`,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`Unique identifier for the client`},client_secret:{type:`string`,description:`Secret key for the client`},client_secret_expires_at:{type:`number`,description:`Time the client secret will expire. If 0, the client secret will never expire.`},scope:{type:`string`,description:`Space-separated scopes allowed by the client`},user_id:{type:`string`,description:`ID of the user who registered the client, null if registered anonymously`},client_id_issued_at:{type:`number`,description:`Creation timestamp of this client`},client_name:{type:`string`,description:`Name of the OAuth2 application`},client_uri:{type:`string`,description:`URI of the OAuth2 application`},logo_uri:{type:`string`,description:`Icon URI for the application`},contacts:{type:`array`,items:{type:`string`},description:`List representing ways to contact people responsible for this client, typically email addresses`},tos_uri:{type:`string`,description:`Client's terms of service uri`},policy_uri:{type:`string`,description:`Client's policy uri`},software_id:{type:`string`,description:`Unique identifier assigned by the developer to help in the dynamic registration process`},software_version:{type:`string`,description:`Version identifier for the software_id`},software_statement:{type:`string`,description:`JWT containing metadata values about the client software as claims`},redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed redirect uris`},token_endpoint_auth_method:{type:`string`,description:`Requested authentication method for the token endpoint`},grant_types:{type:`array`,items:{type:`string`},description:`Grant types the client may use at the token endpoint`},response_types:{type:`array`,items:{type:`string`,enum:[`code`]},description:`Response types the client may use at the authorization endpoint`},application_type:{type:`string`,description:`OIDC application type used to classify redirect URI policy`,enum:[`web`,`native`]},resources:{type:`array`,items:{type:`string`,format:`uri`},description:`Final server-owned resources linked to the client`},disabled:{type:`boolean`,description:`Whether the client is disabled`},metadata:{type:`object`,additionalProperties:!0,nullable:!0,description:`Additional metadata for the application`}},required:[`client_id`]}}}}}}}},async t=>Sv(t,e)),Fv=e=>X(`/oauth2/get-client`,{method:`GET`,use:[qf],query:w({client_id:c()}),metadata:{openapi:{description:`Get OAuth2 formatted client details`}}},async t=>Tv(t,e)),Iv=e=>X(`/oauth2/public-client`,{method:`GET`,use:[qf],query:w({client_id:c()}),metadata:{openapi:{description:`Gets publicly available client fields`}}},async t=>{let n=t.query.client_id;return Ev(t,e,n)}),Lv=e=>X(`/oauth2/public-client-prelogin`,{method:`POST`,use:[p_(e)],body:w({client_id:c(),oauth_query:c().optional()}),metadata:{openapi:{description:`Gets publicly available client fields (prior to login)`}}},async t=>{let n=t.body.client_id;return Ev(t,e,n)}),Rv=e=>X(`/oauth2/get-clients`,{method:`GET`,use:[qf],metadata:{openapi:{description:`Get OAuth2 formatted client details for a user or organization`}}},async t=>Dv(t,e)),zv=e=>X(`/admin/oauth2/update-client`,{method:`PATCH`,body:w({client_id:c(),update:w({redirect_uris:x(Q).min(1).optional(),scope:c().optional(),client_name:c().optional(),client_uri:c().optional(),logo_uri:c().optional(),contacts:x(c().min(1)).min(1).optional(),tos_uri:c().optional(),policy_uri:c().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional(),post_logout_redirect_uris:x(Q).min(1).optional(),backchannel_logout_uri:Q.optional(),backchannel_logout_session_required:v().optional(),application_type:u([`web`,`native`]).optional(),grant_types:Mv.optional(),client_credentials_scopes:x(c().trim().min(1)).optional(),response_types:x(u([`code`])).optional(),client_secret_expires_at:a([c(),d()]).optional(),skip_consent:v().optional(),enable_end_session:v().optional(),disabled:v().optional(),dpop_bound_access_tokens:v().optional(),metadata:i(c(),o()).optional()})}),metadata:{SERVER_ONLY:!0,openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>kv(t,e,{admin:!0})),Bv=e=>X(`/oauth2/update-client`,{method:`POST`,use:[qf],body:w({client_id:c(),update:w({redirect_uris:x(Q).min(1).optional(),scope:c().optional(),client_name:c().optional(),client_uri:c().optional(),logo_uri:c().optional(),contacts:x(c().min(1)).min(1).optional(),tos_uri:c().optional(),policy_uri:c().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional(),post_logout_redirect_uris:x(Q).min(1).optional(),backchannel_logout_uri:Q.optional(),backchannel_logout_session_required:v().optional(),application_type:u([`web`,`native`]).optional(),grant_types:Mv.optional(),response_types:x(u([`code`])).optional()})}),metadata:{openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>kv(t,e)),Vv=e=>X(`/oauth2/client/rotate-secret`,{method:`POST`,use:[qf],body:w({client_id:c()}),metadata:{noStore:!0,openapi:{description:`Rotates a confidential client's secret`}}},async t=>Av(t,e)),Hv=e=>X(`/oauth2/delete-client`,{method:`POST`,use:[qf],body:w({client_id:c()}),metadata:{openapi:{description:`Deletes an oauth client`}}},async t=>Ov(t,e));async function Uv(e,t,n){return await e.context.adapter.findOne({model:`oauthConsent`,where:[{field:`id`,value:n}]})}async function Wv(e,t){let n=await Z(e);if(!n)throw new B(`UNAUTHORIZED`);let{id:r}=e.query;if(!r)throw new B(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await Uv(e,t,r);if(!i)throw new B(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new B(`UNAUTHORIZED`);return i}async function Gv(e,t){let n=await Z(e);if(!n)throw new B(`UNAUTHORIZED`);return await e.context.adapter.findMany({model:`oauthConsent`,where:[{field:`userId`,value:n.user.id}]})}async function Kv(e,t){let n=await Z(e);if(!n)throw new B(`UNAUTHORIZED`);let{id:r}=e.body;if(!r)throw new B(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await Uv(e,t,r);if(!i)throw new B(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new B(`UNAUTHORIZED`);await e.context.adapter.delete({model:`oauthConsent`,where:[{field:`id`,value:r}]})}async function qv(e,t){let n=await Z(e);if(!n)throw new B(`UNAUTHORIZED`);let{id:r}=e.body;if(!r)throw new B(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await Uv(e,t,r);if(!i)throw new B(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new B(`UNAUTHORIZED`);let a=await xl(e,t,i.clientId);if(!a)throw new B(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});let o=a?.scopes??t.scopes??[],s=e.body.update,c=s.scopes;if(c&&!c.every(e=>o?.includes(e)))throw new B(`BAD_REQUEST`,{error_description:`unable to provide scopes to ${a?.referenceId??a?.userId}`,error:`invalid_request`});let l=Math.floor(Date.now()/1e3);return await e.context.adapter.update({model:`oauthConsent`,where:[{field:`id`,value:r}],update:{...s,updatedAt:new Date(l*1e3)}})}var Jv=e=>X(`/oauth2/get-consent`,{method:`GET`,query:w({id:c()}),use:[qf],metadata:{openapi:{description:`Gets details of a specific OAuth2 consent for a user`}}},async t=>Wv(t,e)),Yv=e=>X(`/oauth2/get-consents`,{method:`GET`,use:[qf],metadata:{openapi:{description:`Gets all available OAuth2 consents for a user`}}},async t=>Gv(t,e)),Xv=e=>X(`/oauth2/update-consent`,{method:`POST`,use:[qf],body:w({id:c(),update:w({scopes:x(c())})}),metadata:{openapi:{description:`Updates consent granted to a client.`}}},async t=>qv(t,e)),Zv=e=>X(`/oauth2/delete-consent`,{method:`POST`,use:[qf],body:w({id:c()}),metadata:{openapi:{description:`Deletes consent granted to a client`}}},async t=>Kv(t,e)),Qv=e=>e.schema?.oauthResource?.modelName??`oauthResource`,$v=e=>e.schema?.oauthClientResource?.modelName??`oauthClientResource`,ey=e=>e.schema?.oauthClient?.modelName??`oauthClient`;function ty(e){try{return decodeURIComponent(e)}catch{return e}}function ny(e,t){return{identifier:e.identifier,name:e.name??e.identifier,accessTokenTtl:e.accessTokenTtl??null,refreshTokenTtl:e.refreshTokenTtl??null,signingAlgorithm:e.signingAlgorithm??null,signingKeyId:e.signingKeyId??null,allowedScopes:e.allowedScopes??null,customClaims:e.customClaims??null,dpopBoundAccessTokensRequired:e.dpopBoundAccessTokensRequired??!1,disabled:e.disabled??!1,policyVersion:1,metadata:e.metadata??null,createdAt:t,updatedAt:t}}async function ry(e,t){await k_(e,await Z(e),t,`create`);let n=e.body;if(!n?.identifier)throw new B(`BAD_REQUEST`,{error:`invalid_request`,error_description:`identifier is required`});await Em(t,n.identifier);let r=new Date,i;try{i=await e.context.adapter.create({model:Qv(t),data:ny(n,r)})}catch(e){let t=e instanceof Error?e.message:String(e);throw/unique|duplicate|UNIQUE/i.test(t)?new B(`BAD_REQUEST`,{error:`invalid_request`,error_description:`resource ${n.identifier} already exists`}):e}if(!i)throw new B(`BAD_REQUEST`,{error:`invalid_request`,error_description:`resource ${n.identifier} could not be created`});return Lm(i.identifier),e.json(i,{status:201})}async function iy(e,t){await k_(e,await Z(e),t,`list`);let n=await e.context.adapter.findMany({model:Qv(t)});return e.json(n??[])}async function ay(e,t){let n=ty(e.params.identifier);await k_(e,await Z(e),t,`read`,n);let r=await e.context.adapter.findOne({model:Qv(t),where:[{field:`identifier`,value:n}]});if(!r)throw new B(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return e.json(r)}async function oy(e,t){let n=ty(e.params.identifier);if(await k_(e,await Z(e),t,`update`,n),!await e.context.adapter.findOne({model:Qv(t),where:[{field:`identifier`,value:n}]}))throw new B(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});let r={updatedAt:new Date};for(let t of[`name`,`accessTokenTtl`,`refreshTokenTtl`,`signingAlgorithm`,`signingKeyId`,`allowedScopes`,`customClaims`,`dpopBoundAccessTokensRequired`,`disabled`,`metadata`])Object.prototype.hasOwnProperty.call(e.body,t)&&(r[t]=e.body[t]);await e.context.adapter.update({model:Qv(t),where:[{field:`identifier`,value:n}],update:r}),Lm(n);let i=await e.context.adapter.findOne({model:Qv(t),where:[{field:`identifier`,value:n}]});if(!i)throw new B(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return e.json(i)}async function sy(e,t){let n=ty(e.params.identifier);if(await k_(e,await Z(e),t,`delete`,n),!await e.context.adapter.findOne({model:Qv(t),where:[{field:`identifier`,value:n}]}))throw new B(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return await e.context.adapter.delete({model:Qv(t),where:[{field:`identifier`,value:n}]}),Lm(n),e.json({deleted:!0})}async function cy(e,t){let n=await Z(e),r=ty(e.params.identifier),i=ty(e.params.client_id);if(await k_(e,n,t,`link`,r),!await e.context.adapter.findOne({model:Qv(t),where:[{field:`identifier`,value:r}]}))throw new B(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${r} not found`});if(!await e.context.adapter.findOne({model:ey(t),where:[{field:`clientId`,value:i}]}))throw new B(`NOT_FOUND`,{error:`not_found`,error_description:`client ${i} not found`});try{await e.context.adapter.create({model:$v(t),data:{clientId:i,resourceId:r,createdAt:new Date}})}catch(t){let n=t instanceof Error?t.message:String(t);if(/unique|duplicate|UNIQUE/i.test(n))return e.json({linked:!0,alreadyLinked:!0});throw t}return e.json({linked:!0})}async function ly(e,t){let n=await Z(e),r=ty(e.params.identifier),i=ty(e.params.client_id);return await k_(e,n,t,`unlink`,r),await e.context.adapter.deleteMany({model:$v(t),where:[{field:`clientId`,value:i},{field:`resourceId`,value:r}]}),e.json({unlinked:!0})}var uy=w({identifier:c().min(1).optional(),name:c().optional(),accessTokenTtl:d().int().positive().nullable().optional(),refreshTokenTtl:d().int().positive().nullable().optional(),signingAlgorithm:u(Sm).nullable().optional(),signingKeyId:c().nullable().optional(),allowedScopes:x(c()).nullable().optional(),customClaims:i(c(),o()).nullable().optional(),dpopBoundAccessTokensRequired:v().optional(),disabled:v().optional(),metadata:i(c(),o()).nullable().optional()}),dy=e=>X(`/admin/oauth2/resources`,{method:`POST`,body:uy.required({identifier:!0}),metadata:{SERVER_ONLY:!0}},async t=>ry(t,e)),fy=e=>X(`/admin/oauth2/resources`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>iy(t,e)),py=e=>X(`/admin/oauth2/resources/:identifier`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>ay(t,e)),my=e=>X(`/admin/oauth2/resources/:identifier`,{method:`PATCH`,body:uy,metadata:{SERVER_ONLY:!0}},async t=>oy(t,e)),hy=e=>X(`/admin/oauth2/resources/:identifier`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>sy(t,e)),gy=e=>X(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`POST`,metadata:{SERVER_ONLY:!0}},async t=>cy(t,e)),_y=e=>X(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>ly(t,e));async function vy(e,t,n){let r=t.disableJwtPlugin?void 0:pl(e.context),i=r?.options;try{let a=await Vr(n,hi(await Pc(n,{jwksFetch:i?.jwks?.remoteUrl?i.jwks.remoteUrl:async()=>(await r?.endpoints.getJwks(e))?.response,jwksCacheKey:r})),{issuer:i?.jwt?.issuer??e.context.baseURL}),o=`${e.context.baseURL}/oauth2/userinfo`;if(!a.payload.azp||!await Am(e,t,a.payload.aud,[o]))return null}catch(e){if(e instanceof Error){if(e.name===`TypeError`||e.name===`JWSInvalid`)throw new z(`BAD_REQUEST`,{error_description:`invalid JWT signature`,error:`invalid_request`});if(e.name===`JWTExpired`||e.name===`JWTInvalid`)return null;throw e}throw Error(e)}throw new z(`BAD_REQUEST`,{error_description:`JWT access tokens are self-contained and cannot be revoked server-side`,error:`unsupported_token_type`})}async function yy(e,t,n,r){let i=n;if(t.prefix?.opaqueAccessToken){if(i.startsWith(t.prefix.opaqueAccessToken))i=i.replace(t.prefix.opaqueAccessToken,``);else throw new z(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_request`})}let a=await e.context.adapter.findOne({model:`oauthAccessToken`,where:[{field:`token`,value:await Ol(t.storeTokens,i,`access_token`)}]});if(!a)throw new z(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_request`});if(!a.clientId||a.clientId!==r)return null;a.id?await e.context.adapter.delete({model:`oauthAccessToken`,where:[{field:`id`,value:a.id}]}):await e.context.adapter.delete({model:`oauthAccessToken`,where:[{field:`token`,value:a.token}]})}async function by(e,t,n,r){let i=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await Ol(t.storeTokens,n,`refresh_token`)}]});if(!i)throw new z(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`});if(i.revoked)throw await _h(e,r,i.userId),new z(`BAD_REQUEST`,{error_description:`refresh token revoked`,error:`invalid_request`});if(!i.clientId||i.clientId!==r)return null;let a=Math.floor(Date.now()/1e3);if(!await e.context.adapter.incrementOne({model:`oauthRefreshToken`,where:[{field:`id`,value:i.id},{field:`revoked`,operator:`eq`,value:null}],increment:{},set:{revoked:new Date(a*1e3)}}))throw await _h(e,r,i.userId),new z(`BAD_REQUEST`,{error_description:`refresh token revoked`,error:`invalid_request`});await e.context.adapter.deleteMany({model:`oauthAccessToken`,where:[{field:`refreshId`,value:i.id}]})}async function xy(e,t,n,r){try{return await vy(e,t,r)}catch(e){if(e instanceof z){if(e.body?.error===`unsupported_token_type`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}try{return await yy(e,t,r,n)}catch(e){if(!(e instanceof z))throw e instanceof Error?e:Error(`Unknown error validating access token`)}throw new z(`BAD_REQUEST`,{error_description:`Invalid access token`,error:`invalid_request`})}async function Sy(e,t){let{token:n,token_type_hint:r}=e.body;r!==`access_token`&&r!==`refresh_token`&&(r=void 0);let{clientId:i,clientSecret:a,preVerified:o,authMethod:s}=Vl(await Hl(e,t,`${e.context.baseURL}/oauth2/revoke`));if(!i)throw new z(`UNAUTHORIZED`,{error_description:`missing required credentials`,error:`invalid_client`});if(typeof n==`string`&&(n=pc(n)),!n?.length)throw new z(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await zl(e,t,i,a,void 0,o,void 0,s);try{if(r===void 0||r===`access_token`)try{return await xy(e,t,c.clientId,n)}catch(e){if(e instanceof z){if(r===`access_token`||e.body?.error===`unsupported_token_type`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}if(r===void 0||r===`refresh_token`)try{return await by(e,t,(await hh(t,n)).token,c.clientId)}catch(e){if(e instanceof z){if(r===`refresh_token`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}throw new z(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`})}catch(e){if(e instanceof z){if(e.body?.error===`unsupported_token_type`)throw e;if(e.name===`BAD_REQUEST`)return null;throw e}throw e instanceof Error?(_e.error(`Introspection error:`,e.message,e.stack),new z(`INTERNAL_SERVER_ERROR`)):(_e.error(`Introspection error:`,e),new z(`INTERNAL_SERVER_ERROR`))}}var Cy={oauthClient:{modelName:`oauthClient`,fields:{clientId:{type:`string`,unique:!0,required:!0},clientSecret:{type:`string`,required:!1},clientDiscoveryId:{type:`string`,required:!1},disabled:{type:`boolean`,defaultValue:!1,required:!1},skipConsent:{type:`boolean`,required:!1},enableEndSession:{type:`boolean`,required:!1},subjectType:{type:`string`,required:!1},scopes:{type:`string[]`,required:!1},clientCredentialsScopes:{type:`string[]`,required:!1,defaultValue:[]},userId:{type:`string`,required:!1,references:{model:`user`,field:`id`},index:!0},createdAt:{type:`date`,required:!1},updatedAt:{type:`date`,required:!1},name:{type:`string`,required:!1},uri:{type:`string`,required:!1},icon:{type:`string`,required:!1},contacts:{type:`string[]`,required:!1},tos:{type:`string`,required:!1},policy:{type:`string`,required:!1},softwareId:{type:`string`,required:!1},softwareVersion:{type:`string`,required:!1},softwareStatement:{type:`string`,required:!1},redirectUris:{type:`string[]`,required:!0},postLogoutRedirectUris:{type:`string[]`,required:!1},backchannelLogoutUri:{type:`string`,required:!1},backchannelLogoutSessionRequired:{type:`boolean`,required:!1},tokenEndpointAuthMethod:{type:`string`,required:!1},applicationType:{type:`string`,required:!1},jwks:{type:`string`,required:!1},jwksUri:{type:`string`,required:!1},grantTypes:{type:`string[]`,required:!1},responseTypes:{type:`string[]`,required:!1},requirePKCE:{type:`boolean`,required:!1},dpopBoundAccessTokens:{type:`boolean`,required:!1,defaultValue:!1},referenceId:{type:`string`,required:!1},metadata:{type:`json`,required:!1}}},oauthResource:{modelName:`oauthResource`,fields:{identifier:{type:`string`,required:!0,unique:!0},name:{type:`string`,required:!0},accessTokenTtl:{type:`number`,required:!1},refreshTokenTtl:{type:`number`,required:!1},signingAlgorithm:{type:`string`,required:!1},signingKeyId:{type:`string`,required:!1},allowedScopes:{type:`string[]`,required:!1},customClaims:{type:`json`,required:!1},dpopBoundAccessTokensRequired:{type:`boolean`,required:!1,defaultValue:!1},disabled:{type:`boolean`,required:!1,defaultValue:!1},createdAt:{type:`date`,required:!1},updatedAt:{type:`date`,required:!1},policyVersion:{type:`number`,required:!1,defaultValue:1},metadata:{type:`json`,required:!1}}},oauthClientResource:{modelName:`oauthClientResource`,fields:{clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`,onDelete:`cascade`},index:!0},resourceId:{type:`string`,required:!0,references:{model:`oauthResource`,field:`identifier`,onDelete:`cascade`},index:!0},metadata:{type:`json`,required:!1},createdAt:{type:`date`,required:!1}},indexes:[{fields:[`clientId`,`resourceId`],unique:!0}]},oauthRefreshToken:{fields:{token:{type:`string`,required:!0,unique:!0},clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`},index:!0},sessionId:{type:`string`,required:!1,references:{model:`session`,field:`id`,onDelete:`set null`},index:!0},userId:{type:`string`,required:!0,references:{model:`user`,field:`id`},index:!0},referenceId:{type:`string`,required:!1},authorizationCodeId:{type:`string`,required:!1,index:!0},resources:{type:`string[]`,required:!1},requestedUserInfoClaims:{type:`string[]`,required:!1},expiresAt:{type:`date`},createdAt:{type:`date`},revoked:{type:`date`,required:!1},rotatedAt:{type:`date`,required:!1},rotationReplayResponse:{type:`string`,required:!1},rotationReplayExpiresAt:{type:`date`,required:!1},authTime:{type:`date`,required:!1},confirmation:{type:`json`,required:!1},scopes:{type:`string[]`,required:!0}}},oauthAccessToken:{modelName:`oauthAccessToken`,fields:{token:{type:`string`,unique:!0},clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`},index:!0},sessionId:{type:`string`,required:!1,references:{model:`session`,field:`id`,onDelete:`set null`},index:!0},userId:{type:`string`,required:!1,references:{model:`user`,field:`id`},index:!0},referenceId:{type:`string`,required:!1},authorizationCodeId:{type:`string`,required:!1,index:!0},resources:{type:`string[]`,required:!1},requestedUserInfoClaims:{type:`string[]`,required:!1},refreshId:{type:`string`,required:!1,references:{model:`oauthRefreshToken`,field:`id`},index:!0},expiresAt:{type:`date`},createdAt:{type:`date`},revoked:{type:`date`,required:!1},confirmation:{type:`json`,required:!1},scopes:{type:`string[]`,required:!0}}},oauthConsent:{modelName:`oauthConsent`,fields:{clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`},index:!0},userId:{type:`string`,required:!1,references:{model:`user`,field:`id`},index:!0},referenceId:{type:`string`,required:!1},resources:{type:`string[]`,required:!1},requestedUserInfoClaims:{type:`string[]`,required:!1},scopes:{type:`string[]`,required:!0},createdAt:{type:`date`},updatedAt:{type:`date`}}},oauthClientAssertion:{modelName:`oauthClientAssertion`,fields:{expiresAt:{type:`date`,required:!0}}}},wy=[`openid`,`profile`,`email`,`offline_access`],Ty=w({id_token_hint:c().optional(),client_id:c().optional(),post_logout_redirect_uri:Q.optional(),state:c().optional()}),Ey=dd(()=>null),Dy=Ey.get,Oy=new WeakMap,ky=`signedQueryIssuedAtMs`;function Ay(e){let t=typeof e==`number`?e:typeof e==`string`?Number(e):void 0;if(!(!t||!Number.isFinite(t)||t<=0))return new Date(t)}var jy=e=>{let t=e.clientRegistrationAllowedScopes;if(e.clientRegistrationDefaultScopes){let n=t?new Set([...t,...e.clientRegistrationDefaultScopes]):new Set([...e.clientRegistrationDefaultScopes]);t=Array.from(n)}let n=new Set((e.scopes??wy).filter(e=>e.length));if(t){for(let e of t)if(!n.has(e))throw new V(`clientRegistrationAllowedScope ${e} not found in scopes`)}for(let t of e.advertisedMetadata?.scopes_supported??[])if(!n?.has(t))throw new V(`advertisedMetadata.scopes_supported ${t} not found in scopes`);let r=new Set((e.resources??[]).map(e=>typeof e==`string`?e:e.identifier));for(let[t,n]of[[`clientRegistrationDefaultResources`,e.clientRegistrationDefaultResources],[`clientRegistrationAllowedResources`,e.clientRegistrationAllowedResources]])for(let e of n??[])if(!r.has(e))throw new V(`${t} resource ${e} not found in resources`);let i=new Set([`sub`,`iss`,`aud`,`exp`,`iat`,`sid`,`scope`,`azp`,...om.filter(e=>n.has(am[e].scope))]),o={codeExpiresIn:600,accessTokenExpiresIn:3600,m2mAccessTokenExpiresIn:3600,refreshTokenExpiresIn:2592e3,refreshTokenReuseInterval:0,allowUnauthenticatedClientRegistration:!1,allowDynamicClientRegistration:!1,disableJwtPlugin:!1,storeClientSecret:e.disableJwtPlugin?`encrypted`:`hashed`,storeTokens:`hashed`,grantTypes:[`authorization_code`,`client_credentials`,`refresh_token`],...e,scopes:Array.from(n),claims:Array.from(i),clientRegistrationAllowedScopes:t};if(qc(o.extensions),o.pairwiseSecret&&o.pairwiseSecret.length<32)throw new V(`pairwiseSecret must be at least 32 characters long for adequate HMAC-SHA256 security`);if(o.grantTypes&&o.grantTypes.includes(`refresh_token`)&&!o.grantTypes.includes(`authorization_code`))throw new V(`refresh_token grant requires authorization_code grant`);if(o.disableJwtPlugin&&(o.storeClientSecret===`hashed`||typeof o.storeClientSecret==`object`&&`hash`in o.storeClientSecret))throw new V(`unable to store hashed secrets because id tokens will be signed with secret`);if(!o.disableJwtPlugin&&(o.storeClientSecret===`encrypted`||typeof o.storeClientSecret==`object`&&(`encrypt`in o.storeClientSecret||`decrypt`in o.storeClientSecret)))throw new V(`encryption method not recommended, please use 'hashed' or the 'hash' function`);let s=async(e,t)=>{let n=new URL(e.url).pathname,r=t.options.advanced?.skipTrailingSlashes?n.replace(/\/+$/,``)||`/`:n,i=o.disableJwtPlugin?t.baseURL:pl(t)?.options?.jwt?.issuer??t.baseURL,a=`/`;try{a=new URL(i).pathname.replace(/\/$/,``)||``}catch{a=new URL(t.baseURL).pathname.replace(/\/$/,``)||``}let s={context:t},c=new Set([`/.well-known/oauth-authorization-server${a}`,`${a}/.well-known/oauth-authorization-server`]),l=`${a}/.well-known/openid-configuration`,u=c.has(r),d=o.scopes?.includes(`openid`)&&r===l,f=t=>{let n=s_(t);return e.method===`HEAD`?new Response(null,{status:n.status,headers:n.headers}):n};if((u||d)&&e.method!==`GET`&&e.method!==`HEAD`)return{response:new Response(null,{status:405,headers:{Allow:`GET, HEAD`}})};if(u)return o.scopes?.includes(`openid`)?{response:f(a_(s,o))}:{response:f(i_(s,o))};if(d)return{response:f(a_(s,o))}},u=c_(`/oauth2/authorize`,{method:[`GET`,`POST`],body:w({}).passthrough(),redirectOnError:Jy(o),metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Authorize an OAuth 2.1 request from query parameters or an application/x-www-form-urlencoded POST body`,parameters:[{name:`response_type`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth 2.1 response type (e.g., 'code')`},{name:`client_id`,in:`query`,required:!0,schema:{type:`string`},description:`OAuth 2.1 client ID`},{name:`redirect_uri`,in:`query`,required:!1,schema:{type:`string`,format:`uri`},description:`OAuth 2.1 redirect URI`},{name:`scope`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth 2.1 scopes (space-separated)`},{name:`state`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth 2.1 state parameter`},{name:`request_uri`,in:`query`,required:!1,schema:{type:`string`},description:`Pushed Authorization Request URI referencing stored parameters`},{name:`code_challenge`,in:`query`,required:!1,schema:{type:`string`},description:`PKCE code challenge`},{name:`code_challenge_method`,in:`query`,required:!1,schema:{type:`string`},description:`PKCE code challenge method`},{name:`nonce`,in:`query`,required:!1,schema:{type:`string`},description:`OpenID Connect nonce`},{name:`max_age`,in:`query`,required:!1,schema:{type:`integer`,minimum:0},description:`Maximum authentication age in seconds; forces re-authentication when exceeded`},{name:`resource`,in:`query`,required:!1,schema:{type:`array`,items:{type:`string`}},description:`Requested protected resource(s) for the access token. May be supplied multiple times as repeated 'resource' query parameters (RFC 8707) or as an array of strings.`},{name:`prompt`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth2 prompt parameter`}],responses:{302:{description:`Redirect to client with code or error`,headers:{Location:{description:`Redirect URI with code or error`,schema:{type:`string`,format:`uri`}}}},400:{description:`Invalid request`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},state:{type:`string`}},required:[`error`]}}}}}}}},async e=>Yy(e,o,e.authorizeSettings??{isAuthorize:!0})),d=(e,t)=>Ap(u,{...e,asResponse:!1,returnHeaders:!1,returnStatus:!1,authorizeSettings:t??{}});return{id:`oauth-provider`,version:lg,options:o,onRequest:s,init:async e=>{if(e.options.secondaryStorage&&e.options.session?.storeSessionInDatabase!==!0)throw new V("OAuth Provider requires `session.storeSessionInDatabase: true` when using secondaryStorage");if(await Jm(e,o).catch(t=>Wm(e,t)),Ym(o),!o.disableJwtPlugin){let t=pl(e)?.options,n=t?.jwt?.issuer??e.baseURL,r=t?.jwt?.issuer==null&&typeof e.options.baseURL==`object`&&e.options.baseURL!==null&&`allowedHosts`in e.options.baseURL;try{new URL(n)}catch(e){if(!r||n!==``)throw e}}return{options:{databaseHooks:{session:{delete:{async before(e,t){if(!t)return;let n=await Sg(t,o,{sessionId:e.id,userId:e.userId});if(!n)return;let r=Oy.get(t)??new Map;r.set(e.id,n),Oy.set(t,r)},async after(e,t){if(!t)return;let n=Oy.get(t);if(!n)return;let r=n.get(e.id);if(n.delete(e.id),n.size===0&&Oy.delete(t),!r)return;let i=Cg(t,r).catch(e=>{t.context.logger.error(`Back-channel logout failed after session deletion`,e)});await t.context.runInBackgroundOrAwait(i)}}}}}}},hooks:{before:[{matcher(e){return e.body?.oauth_query},handler:du(async e=>{let t=e.body.oauth_query;if(!await bl(t,e.context.secret))throw new B(`BAD_REQUEST`,{error:`invalid_signature`});let n=ke(t),r=new URLSearchParams(t),i=r.get(`ba_pl`)??void 0;r.delete(`sig`),r.delete(`exp`),r.delete(we),r.delete(Te),await Ey.set({query:r.toString(),signedQueryIssuedAt:n??void 0,postLoginClearedForSession:i}),e.path===`/sign-in/social`&&await Sd({query:r.toString(),...n?{[ky]:n.getTime()}:{}})})}],after:[{matcher(e){return Jd(e.context.responseHeaders?.get(`set-cookie`)||``).has(e.context.authCookies.sessionToken.name)},handler:du(async e=>{let t=Jd(e.context.responseHeaders?.get(`set-cookie`)||``).get(e.context.authCookies.sessionToken.name)?.value.split(`.`)[0];if(!t)return;let n=await Ey.get(),r=(await yd())?.serverContext,i=n?.query??r?.query;if(!i)return;let a=new URLSearchParams(i),o=await e.context.internalAdapter.findSession(t);if(!o)return;e.context.session=o;let s=e.request?.headers?.get(`sec-fetch-mode`)?.toLowerCase(),c=e.request?.headers?.get(`accept`)?.toLowerCase()??``;s===`navigate`||!s&&(c.includes(`text/html`)||c.includes(`application/xhtml+xml`))||e.headers?.set(`accept`,`application/json`);let l=n?.signedQueryIssuedAt??Ay(r?.[ky]),u=Yl(a,`login`);return Jl(o.session.createdAt,l)&&(u=Xl(u)),e.query=ql(u),await d(e)})}]},endpoints:{getOAuthServerConfig:X(`/.well-known/oauth-authorization-server`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async e=>o.scopes&&o.scopes.includes(`openid`)?a_(e,o):i_(e,o)),getOpenIdConfig:X(`/.well-known/openid-configuration`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async e=>{if(o.scopes&&!o.scopes.includes(`openid`))throw new B(`NOT_FOUND`);return a_(e,o)}),oauth2Authorize:u,oauth2Consent:X(`/oauth2/consent`,{method:`POST`,body:w({accept:v().meta({description:`Accept or deny user consent for a set of scopes`}),scope:c().optional().meta({description:`List of accept of accepted space-separated scopes. If none is provided, then all originally requested scopes are accepted.`}),claims:$p.optional().meta({description:`Accepted OIDC claims request object. If none is provided, then all originally requested claims are accepted.`}),oauth_query:c().optional().meta({description:`The redirected page's query parameters`})}),use:[qf],metadata:{openapi:{description:`Handle OAuth2 consent`,responses:{200:{description:`Consent processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{redirect_uri:{type:`string`,format:`uri`,description:`The URI to redirect to, either with an authorization code or an error`}},required:[`redirect_uri`]}}}}}}}},async e=>fg(e,o,d)),oauth2Continue:X(`/oauth2/continue`,{method:`POST`,body:w({selected:v().optional().meta({description:`Confirms an account has been selected and authorization can proceed.`}),created:v().optional().meta({description:`Confirms an account was registered`}),postLogin:v().optional().meta({description:`Confirms organization and/or team selection.`}),oauth_query:c().optional().meta({description:`The redirected page's query parameters`})}),use:[qf],metadata:{openapi:{description:`Continues OAuth2 authorization flow`,responses:{200:{description:`Consent processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{redirect_uri:{type:`string`,format:`uri`,description:`The URI to redirect to, either with an authorization code or an error`}},required:[`redirect_uri`]}}}}}}}},async e=>pg(e,d)),oauth2Token:c_(`/oauth2/token`,{method:`POST`,cloneRequest:!0,body:w({grant_type:c().trim().min(1),client_id:c().optional(),client_secret:c().optional(),client_assertion:c().optional(),client_assertion_type:c().optional(),code:c().optional(),code_verifier:c().optional(),redirect_uri:Q.optional(),refresh_token:c().optional(),resource:a([fm,x(fm).min(1)]).optional(),scope:c().optional()}).passthrough(),errorCodesByField:{grant_type:{missing:`invalid_request`,invalid:`unsupported_grant_type`},resource:{invalid:`invalid_target`}},metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Obtain an OAuth2.1 access token`,parameters:[{name:`DPoP`,in:`header`,required:!1,schema:{type:`string`},description:`RFC 9449 DPoP proof JWT for issuing DPoP-bound tokens`}],requestBody:{required:!0,content:{"application/json":{schema:{type:`object`,properties:{grant_type:{type:`string`,description:`OAuth2 grant type`},client_id:{type:`string`,description:`OAuth2 client ID`},client_secret:{type:`string`,description:`OAuth2 client secret`},code:{type:`string`,description:`Authorization code (for authorization_code grant)`},code_verifier:{type:`string`,description:`PKCE code verifier (for authorization_code grant)`},redirect_uri:{type:`string`,format:`uri`,description:`Redirect URI (for authorization_code grant)`},refresh_token:{type:`string`,description:`Refresh token (for refresh_token grant)`},resource:{oneOf:[{type:`string`,description:`Single resource (URL)`},{type:`array`,items:{type:`string`},description:`Multiple resources (URLs)`}],description:`Requested protected resource(s) for the access token`},scope:{type:`string`,description:`Requested scopes (for client_credentials grant)`}},required:[`grant_type`]}}}},responses:{200:{description:`Access token response`,content:{"application/json":{schema:{type:`object`,properties:{access_token:{type:`string`,description:`The access token issued by the authorization server`},token_type:{type:`string`,description:`The type of the token issued`,enum:[`Bearer`,`DPoP`]},expires_in:{type:`number`,description:`Lifetime in seconds of the access token`},refresh_token:{type:`string`,description:`Refresh token, if issued`},scope:{type:`string`,description:`Scopes granted by the access token`},id_token:{type:`string`,description:`ID Token (if OpenID Connect)`}},required:[`access_token`,`token_type`,`expires_in`]}}}},400:{description:`Invalid request or error response`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},error_uri:{type:`string`}},required:[`error`]}}}}}}}},async e=>{if(e.request){let t=await Om(e.request);t&&t.length>1&&(e.body.resource=t)}return lh(e,o)}),oauth2Introspect:c_(`/oauth2/introspect`,{method:`POST`,cloneRequest:!0,body:w({client_id:c().optional(),client_secret:c().optional(),client_assertion:c().optional(),client_assertion_type:c().optional(),token:c(),token_type_hint:c().optional()}),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Introspect an OAuth2 access or refresh token`,requestBody:{required:!0,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`OAuth2 client ID`},client_secret:{type:`string`,description:`OAuth2 client secret`},token:{type:`string`,description:`The token to introspect (access or refresh token)`},token_type_hint:{type:`string`,description:"Hint about the token type. Recognized values: `access_token`, `refresh_token`."}},required:[`token`]}}}},responses:{200:{description:`Token introspection response`,content:{"application/json":{schema:{type:`object`,properties:{active:{type:`boolean`,description:`Whether the token is active`},scope:{type:`string`,description:`Scopes associated with the token`},client_id:{type:`string`,description:`Client ID associated with the token`},username:{type:`string`,description:`Username associated with the token`},token_type:{type:`string`,description:`Type of the token`},exp:{type:`number`,description:`Expiration time of the token (seconds since epoch)`},iat:{type:`number`,description:`Issued at time (seconds since epoch)`},nbf:{type:`number`,description:`Not before time (seconds since epoch)`},sub:{type:`string`,description:`Subject of the token`},aud:{type:`string`,description:`Audience of the token`},iss:{type:`string`,description:`Issuer of the token`},jti:{type:`string`,description:`JWT ID`}},required:[`active`]}}}},400:{description:`Invalid request or error response`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},error_uri:{type:`string`}},required:[`error`]}}}}}}}},async e=>cg(e,o)),oauth2Revoke:c_(`/oauth2/revoke`,{method:`POST`,cloneRequest:!0,body:w({client_id:c().optional(),client_secret:c().optional(),client_assertion:c().optional(),client_assertion_type:c().optional(),token:c(),token_type_hint:c().optional()}),metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Revoke an OAuth2 access or refresh token`,requestBody:{required:!0,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`OAuth2 client ID`},client_secret:{type:`string`,description:`OAuth2 client secret`},token:{type:`string`,description:`The token to revoke (access or refresh token)`},token_type_hint:{type:`string`,description:"Hint about the token type. Recognized values: `access_token`, `refresh_token`."}},required:[`token`]}}}},responses:{200:{description:`Token revoked successfully. The response body is empty.`,content:{"application/json":{schema:{type:`object`,description:`Empty object on success`}}}},400:{description:`Invalid request or error response`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},error_uri:{type:`string`}},required:[`error`]}}}}}}}},async e=>Sy(e,o)),oauth2UserInfo:X(`/oauth2/userinfo`,{method:[`GET`,`POST`],body:w({access_token:c().optional()}).passthrough().optional(),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Get OpenID Connect user information (UserInfo endpoint)`,security:[{bearerAuth:[]},{OAuth2:[`openid`,`profile`,`email`]}],parameters:[{name:`Authorization`,in:`header`,required:!1,schema:{type:`string`},description:`Bearer or DPoP access token`},{name:`DPoP`,in:`header`,required:!1,schema:{type:`string`},description:`RFC 9449 DPoP proof JWT when using a DPoP-bound access token`}],responses:{200:{description:`User information retrieved successfully`,content:{"application/json":{schema:{type:`object`,properties:{sub:{type:`string`,description:`Subject identifier (user ID)`},email:{type:`string`,format:`email`,nullable:!0,description:`User's email address, included if 'email' scope is granted`},name:{type:`string`,nullable:!0,description:`User's full name, included if 'profile' scope is granted`},picture:{type:`string`,format:`uri`,nullable:!0,description:`User's profile picture URL, included if 'profile' scope is granted`},given_name:{type:`string`,nullable:!0,description:`User's given name, included if 'profile' scope is granted`},family_name:{type:`string`,nullable:!0,description:`User's family name, included if 'profile' scope is granted`},email_verified:{type:`boolean`,nullable:!0,description:`Whether the email is verified, included if 'email' scope is granted`}},required:[`sub`]}}}},401:{description:`Unauthorized - invalid or missing access token`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`}},required:[`error`]}}}},403:{description:`Forbidden - insufficient scope`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`}},required:[`error`]}}}}}}}},async e=>ah(e,o)),oauth2EndSession:c_(`/oauth2/end-session`,{method:[`GET`,`POST`],body:Ty.optional(),query:Ty.optional(),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`,`application/json`],$Infer:{body:{},query:{}},openapi:{description:`RP-Initiated Logout endpoint. Accepts standard logout parameters through GET or an application/x-www-form-urlencoded POST body, plus JSON for Better Auth generated-client calls. Requests without a usable id_token_hint may require explicit OP confirmation.`,responses:{200:{description:`Logout completed, or an HTML confirmation page was returned for browser navigation. A redirect is used only for an exact registered post_logout_redirect_uri.`,content:{"application/json":{schema:{type:`object`,properties:{redirect_uri:{type:`string`,format:`uri`,description:`URI to redirect to after logout (if post_logout_redirect_uri was provided)`},message:{type:`string`,description:`Success message`}}}},"text/html":{schema:{type:`string`}}}}}}}},async e=>e_(e,o)),oauth2EndSessionConfirmation:c_(`/oauth2/end-session/confirm`,{method:`POST`,body:w({action:l(`confirm`)}),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],scope:`http`}},async e=>t_(e,o)),registerOAuthClient:c_(`/oauth2/register`,{method:`POST`,body:xm,errorCodesByField:{redirect_uris:`invalid_redirect_uri`,post_logout_redirect_uris:`invalid_redirect_uri`,software_statement:`invalid_software_statement`,resources:`invalid_target`},defaultError:`invalid_client_metadata`,metadata:{noStore:!0,openapi:{description:`Register an OAuth2 application`,responses:{201:{description:`OAuth2 application registered successfully`,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`Unique identifier for the client`},client_secret:{type:`string`,description:`Secret key for the client`},client_secret_expires_at:{type:`number`,description:`Time the client secret will expire. If 0, the client secret will never expire.`},scope:{type:`string`,description:`Space-separated scopes allowed by the client`},user_id:{type:`string`,description:`ID of the user who registered the client, null if registered anonymously`},client_id_issued_at:{type:`number`,description:`Creation timestamp of this client`},client_name:{type:`string`,description:`Name of the OAuth2 application`},client_uri:{type:`string`,description:`Name of the OAuth2 application`},logo_uri:{type:`string`,description:`Icon URL for the application`},contacts:{type:`array`,items:{type:`string`},description:`List representing ways to contact people responsible for this client, typically email addresses`},tos_uri:{type:`string`,description:`Client's terms of service uri`},policy_uri:{type:`string`,description:`Client's policy uri`},software_id:{type:`string`,description:`Unique identifier assigned by the developer to help in the dynamic registration process`},software_version:{type:`string`,description:`Version identifier for the software_id`},software_statement:{type:`string`,description:`JWT containing metadata values about the client software as claims`},redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed redirect uris`},post_logout_redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed logout redirect uris`},backchannel_logout_uri:{type:`string`,format:`uri`,description:`RP URL to receive signed Logout Tokens when the end-user's OP session terminates`},backchannel_logout_session_required:{type:`boolean`,description:"Whether the RP requires a `sid` claim in every Logout Token"},token_endpoint_auth_method:{type:`string`,description:`Requested authentication method for the token endpoint`},grant_types:{type:`array`,items:{type:`string`},description:`Grant types the client may use at the token endpoint`},response_types:{type:`array`,items:{type:`string`,enum:[`code`]},description:`Response types the client may use at the authorization endpoint`},application_type:{type:`string`,description:`OIDC application type used to classify redirect URI policy`,enum:[`web`,`native`]},resources:{type:`array`,items:{type:`string`,format:`uri`},description:`Final resource identifiers linked to the registered client`},disabled:{type:`boolean`,description:`Whether the client is disabled`}},required:[`client_id`]}}}}}}}},async e=>pv(e,o)),adminCreateOAuthClient:Nv(o),createOAuthClient:Pv(o),getOAuthClient:Fv(o),getOAuthClientPublic:Iv(o),getOAuthClientPublicPrelogin:Lv(o),getOAuthClients:Rv(o),adminUpdateOAuthClient:zv(o),updateOAuthClient:Bv(o),rotateClientSecret:Vv(o),deleteOAuthClient:Hv(o),getOAuthConsent:Jv(o),getOAuthConsents:Yv(o),updateOAuthConsent:Xv(o),deleteOAuthConsent:Zv(o),adminCreateOAuthResource:dy(o),adminListOAuthResources:fy(o),adminGetOAuthResource:py(o),adminUpdateOAuthResource:my(o),adminDeleteOAuthResource:hy(o),adminLinkClientResource:gy(o),adminUnlinkClientResource:_y(o)},schema:Ud(structuredClone(Cy),o?.schema),rateLimit:[...o.rateLimit?.token===!1?[]:[{pathMatcher:e=>e===`/oauth2/token`,window:o.rateLimit?.token?.window??60,max:o.rateLimit?.token?.max??20}],...o.rateLimit?.authorize===!1?[]:[{pathMatcher:e=>e===`/oauth2/authorize`,window:o.rateLimit?.authorize?.window??60,max:o.rateLimit?.authorize?.max??30}],...o.rateLimit?.introspect===!1?[]:[{pathMatcher:e=>e===`/oauth2/introspect`,window:o.rateLimit?.introspect?.window??60,max:o.rateLimit?.introspect?.max??100}],...o.rateLimit?.revoke===!1?[]:[{pathMatcher:e=>e===`/oauth2/revoke`,window:o.rateLimit?.revoke?.window??60,max:o.rateLimit?.revoke?.max??30}],...o.rateLimit?.register===!1?[]:[{pathMatcher:e=>e===`/oauth2/register`,window:o.rateLimit?.register?.window??60,max:o.rateLimit?.register?.max??5}],...o.rateLimit?.userinfo===!1?[]:[{pathMatcher:e=>e===`/oauth2/userinfo`,window:o.rateLimit?.userinfo?.window??60,max:o.rateLimit?.userinfo?.max??60}]]}};function My(e,t,n){return t!==0&&n.getTime()-e.getTime()<=t*1e3}function Ny(e){let{max_age:t,...n}=e;return n}function Py(e,t,n,r,i,a=`query`){let o=new URLSearchParams({error:t,error_description:n});return r&&o.append(`state`,r),i&&o.append(`iss`,i),a===`fragment`?`${e}#${o.toString()}`:Bu(e,o)}function Fy(e){let t=typeof e.response_mode==`string`?e.response_mode:void 0;if(t===`fragment`)return`fragment`;if(t===`query`)return`query`;let n=typeof e.response_type==`string`?e.response_type:void 0;return n&&/\b(token|id_token)\b/.test(n)?`fragment`:`query`}var Iy={response_type:{invalid:`unsupported_response_type`},resource:{invalid:`invalid_target`}};function Ly(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ry(e){return typeof e==`string`?e:void 0}function zy(e,t){let n=e.method===`POST`&&t?.isAuthorize===!0?e.body:e.query;return{...Ly(n)?n:{}}}var $=(e,t)=>{let n=ug(e.request?.headers),r=e.headers?.get(`accept`)?.includes(`application/json`);if(n||r)return{redirect:!0,url:t.toString()};throw e.redirect(t)};function By(e,t,n,r,i){return $(e,Py(n.redirect_uri,r,i,n.state,Hy(e,t)))}function Vy(e){try{let t=new URL(e);return t.protocol!==`https:`&&!bp(t.host)&&(t.protocol=`https:`),t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}catch{return e}}function Hy(e,t){let n;if(t.disableJwtPlugin)n=e.context.baseURL;else try{n=pl(e.context).options?.jwt?.issuer??e.context.baseURL}catch{n=e.context.baseURL}return Vy(n)}function Uy(e,t,n){return Py(e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,t,n)}function Wy(e){let t;try{t=new URL(e)}catch{return}let n=yp(t.hostname)||t.hostname===`localhost`;if(t.protocol!==`http:`||!n)return;let r=e.indexOf(`://`);if(r<0)return;let i=r+3,a=e.slice(i).search(/[/?#]/u),o=e.length;a>=0&&(o=i+a);let s=e.slice(i,o),c;if(s.startsWith(`[`)){let t=s.indexOf(`]`);if(t<0)return;if(s[t+1]!==`:`)return e;c=t+1}else if(c=s.lastIndexOf(`:`),c<0)return e;let l=s.slice(c+1);if(!/^\d*$/u.test(l))return;let u=i+c;return`${e.slice(0,u)}${e.slice(o)}`}function Gy(e,t){if(!e||!t)return;let n;try{n=new URL(t)}catch{return}let r=t.includes(`#`),i=n.username.length>0||n.password.length>0;if(r||i)return;let a=Wy(t);return e.find(e=>e===t?!0:a?Wy(e)===a:!1)}function Ky(e){if(!Q.safeParse(e).success)return!1;let t=new URL(e);return t.username.length===0&&t.password.length===0}async function qy(e,t,n,r){if(!n||!r)return null;let i;try{i=await xl(e,t,n)}catch{return null}if(!i||i.disabled)return null;let a=i.redirectUris??[],o=Gy(a,r);if(t.validateRedirectUri){if(!Ky(r))return null;try{return await t.validateRedirectUri(r,a,!!o)?r:null}catch{return null}}return o?r:null}function Jy(e){return async({error:t,error_description:n,ctx:r})=>{let i=r.query??{},a=await qy(r,e,typeof i.client_id==`string`?i.client_id:void 0,typeof i.redirect_uri==`string`?i.redirect_uri:void 0);return a?$(r,Py(a,t,n,typeof i.state==`string`?i.state:void 0,Hy(r,e),Fy(i))):$(r,Uy(r,t,n))}}async function Yy(e,t,n){if(t.grantTypes&&!t.grantTypes.includes(`authorization_code`))throw new z(`NOT_FOUND`);if(!e.request)throw new z(`UNAUTHORIZED`,{error_description:`request not found`,error:`invalid_request`});let r=e.request,i=zy(e,n);e.query=i;let a=Ry(i.request),o=Ry(i.request_uri);if(a!==void 0&&o!==void 0)return Jy(t)({error:`invalid_request`,error_description:`request and request_uri cannot be used together`,ctx:e});if(a!==void 0)return Jy(t)({error:`request_not_supported`,error_description:`request object not supported`,ctx:e});if(o!==void 0){let n=Ry(i.client_id);if(!n)return Jy(t)({error:`invalid_request`,error_description:`client_id is required`,ctx:e});if(!t.requestUriResolver)return Jy(t)({error:`request_uri_not_supported`,error_description:`request_uri not supported`,ctx:e});let r=await t.requestUriResolver({requestUri:o,clientId:n,ctx:e});if(!r)return Jy(t)({error:`invalid_request_uri`,error_description:`request_uri is invalid or expired`,ctx:e});let a=i.client_id;i=r,a&&(i.client_id=a)}e.query=i;let s=vm.safeParse(i);if(!s.success){let n=l_(s.error.issues,Iy);return Jy(t)({...n,ctx:e})}if(i=s.data,e.query=i,await Ey.set({query:Xy(i).toString()}),!i.response_type)return Jy(t)({error:`invalid_request`,error_description:`response_type is required`,ctx:e});let c=e.query?.prompt?Ul(e.query?.prompt):void 0,l=c?.has(`none`)??!1;if(c?.has(`select_account`)&&!t.selectAccount?.page)return $(e,Uy(e,`unsupported_prompt_select_account`,`unsupported prompt type`));if(i.response_type!==`code`)return $(e,Uy(e,`unsupported_response_type`,`unsupported response type`));let u=await xl(e,t,i.client_id);if(!u)return $(e,Uy(e,`invalid_client`,`client_id is required`));if(u.disabled)return $(e,Uy(e,`client_disabled`,`client is disabled`));if(!Il(u,`authorization_code`))return $(e,Uy(e,`unauthorized_client`,`client is not authorized to use the authorization_code grant`));let d=u.redirectUris??[],f=!1;if(i.redirect_uri){let e=!!Gy(d,i.redirect_uri);if(t.validateRedirectUri&&Ky(i.redirect_uri))try{f=await t.validateRedirectUri(i.redirect_uri,d,e)}catch{f=!1}else t.validateRedirectUri||(f=e)}if(!f)return $(e,Uy(e,`invalid_redirect`,`invalid redirect uri`));let p=i.scope?.split(` `).filter(e=>e);if(p){let n=new Set(u.scopes??t.scopes),r=p.filter(e=>!n?.has(e));if(r.length)return $(e,Py(i.redirect_uri,`invalid_scope`,`The following scopes are invalid: ${r.join(`, `)}`,i.state,Hy(e,t)))}p||(p=u.scopes??t.scopes??[],i.scope=p.join(` `));let m=p.includes(`openid`);if(i.claims!==void 0&&!m)return $(e,Py(i.redirect_uri,`invalid_request`,`openid scope must be requested when using the claims parameter`,i.state,Hy(e,t)));if(m&&!em(i.claims))return $(e,Py(i.redirect_uri,`invalid_request`,`claims must be a valid Claims request object`,i.state,Hy(e,t)));if(m&&!nm(i.claims,`0`))return $(e,Py(i.redirect_uri,`access_denied`,`essential acr requirement cannot be met`,i.state,Hy(e,t)));let h=tm(i.claims,sm(t));if(i.resource!==void 0)try{await jm(e,t,{resource:i.resource,clientId:u.clientId,requestedScopes:p})}catch(n){if(n instanceof z){let r=n.body?.error??`invalid_target`,a=n.body?.error_description??`requested resource invalid`;return $(e,Py(i.redirect_uri,r,a,i.state,Hy(e,t)))}throw n}let g=Zl(u,{scopes:p,nonce:i.nonce});if(g&&(!i.code_challenge||!i.code_challenge_method))return $(e,Py(i.redirect_uri,`invalid_request`,g.valueOf(),i.state,Hy(e,t)));if(i.code_challenge||i.code_challenge_method){if(!i.code_challenge||!i.code_challenge_method)return $(e,Py(i.redirect_uri,`invalid_request`,`code_challenge and code_challenge_method must both be provided`,i.state,Hy(e,t)));if(![`S256`].includes(i.code_challenge_method))return $(e,Py(i.redirect_uri,`invalid_request`,`invalid code_challenge method, only S256 is supported`,i.state,Hy(e,t)))}let _=gl(i.resource)??[],v=await Z(e),y=i.max_age,b=v!=null&&y!==void 0&&My(new Date(v.session.createdAt),y,new Date);if(!v||v!=null&&y!==void 0&&!b||c?.has(`login`)||c?.has(`create`))return l?By(e,t,i,`login_required`,`authentication required`):Qy(e,t,c?.has(`create`)?`create`:`login`);if(b&&(i=Ny(i),e.query=i),n?.isAuthorize&&c?.has(`select_account`))return Qy(e,t,`select_account`);if(n?.isAuthorize&&t.selectAccount&&await t.selectAccount.shouldRedirect({headers:r.headers,user:v.user,session:v.session,scopes:p}))return l?By(e,t,i,`account_selection_required`,`End-User account selection is required`):Qy(e,t,`select_account`);if(t.signup?.shouldRedirect){let n=await t.signup.shouldRedirect({headers:r.headers,user:v.user,session:v.session,scopes:p});if(n)return l?By(e,t,i,`interaction_required`,`End-User interaction is required`):Qy(e,t,`create`,{page:typeof n==`string`?n:void 0})}if(!n?.postLogin&&t.postLogin&&await t.postLogin.shouldRedirect({headers:r.headers,user:v.user,session:v.session,scopes:p}))return l?By(e,t,i,`interaction_required`,`End-User interaction is required`):Qy(e,t,`post_login`);if(c?.has(`consent`))return Qy(e,t,`consent`,{sessionId:v.session.id});let x=await t.postLogin?.consentReferenceId?.({user:v.user,session:v.session,scopes:p});if(u.skipConsent)return Zy(e,t,{query:i,clientId:u.clientId,userId:v.user.id,sessionId:v.session.id,authTime:new Date(v.session.createdAt).getTime(),referenceId:x,resource:_});let S=await e.context.adapter.findOne({model:`oauthConsent`,where:[{field:`clientId`,value:u.clientId},{field:`userId`,value:v.user.id},...x?[{field:`referenceId`,value:x}]:[]]});if(!S||!p.every(e=>S.scopes.includes(e))||!h.every(e=>(S.requestedUserInfoClaims??[]).includes(e)))return l?By(e,t,i,`consent_required`,`End-User consent is required`):Qy(e,t,`consent`,{sessionId:v.session.id});let C=S?.resources??[];return _.some(e=>!C.includes(e))?l?By(e,t,i,`consent_required`,`End-User consent is required`):Qy(e,t,`consent`,{sessionId:v.session.id}):Zy(e,t,{query:i,clientId:u.clientId,userId:v.user.id,sessionId:v.session.id,authTime:new Date(v.session.createdAt).getTime(),referenceId:x,resource:_})}function Xy(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!=null){if(Array.isArray(r))for(let e of r)t.append(n,String(e));else n===`claims`&&typeof r==`object`?t.set(n,JSON.stringify(r)):t.set(n,String(r))}return t}async function Zy(e,t,n){let r=Fi(32,`a-z`,`A-Z`,`0-9`),i=Math.floor(Date.now()/1e3),a=i+(t.codeExpiresIn??600),o={identifier:await Dl(t.storeTokens,r,`authorization_code`),updatedAt:new Date(i*1e3),expiresAt:new Date(a*1e3),value:JSON.stringify({type:`authorization_code`,query:n.query,userId:n.userId,sessionId:n?.sessionId,referenceId:n.referenceId,authTime:n.authTime,resource:n.resource})};await e.context.internalAdapter.createVerificationValue({...o,createdAt:new Date(i*1e3)});let s=new URL(n.query.redirect_uri);return s.searchParams.set(`code`,r),n.query.state&&s.searchParams.set(`state`,n.query.state),s.searchParams.set(`iss`,Hy(e,t)),$(e,s.toString())}async function Qy(e,t,n,r){let i=await $y(e,t,{postLoginClearedForSession:n===`consent`&&t.postLogin?r?.sessionId:void 0}),a=t.loginPage;if(n===`select_account`)a=t.selectAccount?.page??t.loginPage;else if(n===`post_login`){if(!t.postLogin?.page)throw new z(`INTERNAL_SERVER_ERROR`,{error_description:`postLogin should have been defined`});a=t.postLogin?.page}else n===`consent`?a=t.consentPage:n===`create`&&(a=t.signup?.page??t.loginPage);return $(e,`${r?.page??a}?${i}`)}async function $y(e,t,n){let r=Date.now(),i=Math.floor(r/1e3)+(t.codeExpiresIn??600),a=Xy(e.query);a.set(`exp`,String(i)),a.set(we,String(r)),a.delete(`sig`),a.delete(Te),n?.postLoginClearedForSession&&a.set(Te,n.postLoginClearedForSession),Oe(a);let o=await Ga(De(a).toString(),e.context.secret);return a.set(`sig`,o),a.toString()}export{vd as $,_i as $t,Uf as A,Ll as At,Wd as B,cs as Bt,Xf as C,Ql as Ct,Jf as D,Pl as Dt,Qf as E,fl as Et,kf as F,hs as Ft,Bd as G,Ua as Gt,Hd as H,as as Ht,Tf as I,ms as It,zd as J,Fi as Jt,Vd as K,Ha as Kt,hf as L,us as Lt,If as M,ic as Mt,Lf as N,$s as Nt,qf as O,_l as Ot,zf as P,vs as Pt,bd as Q,vi as Qt,pf as R,ss as Rt,Gf as S,au as St,Zf as T,xl as Tt,Ud as U,is as Ut,Fd as V,os as Vt,Ld as W,rs as Wt,Td as X,Si as Xt,Pd as Y,Pi as Yt,Dd as Z,yi as Zt,np as _,Lu as _t,uh as a,Ct as an,ud as at,Wf as b,du as bt,Bp as c,_t as cn,ad as ct,Ip as d,ft as dn,Du as dt,gi as en,pd as et,Fp as f,qe as fn,Au as ft,op as g,Mu as gt,bp as h,ju as ht,Om as i,br as in,cd as it,Hf as j,bl as jt,Ff as k,gl as kt,Vp as l,ct as ln,Bu as lt,wp as m,be as mn,ku as mt,jy as n,Kr as nn,md as nt,jm as o,st as on,od as ot,Ap as p,Fe as pn,Ou as pt,Id as q,Li as qt,fm as r,Vr as rn,hd as rt,Hp as s,ht as sn,td as st,Dy as t,hi as tn,gd as tt,zp as u,lt as un,Ru as ut,tp as v,yu as vt,$f as w,Xc as wt,Z as x,ou as xt,Yf as y,X as yt,ff as z,ls as zt};
31
+ //# sourceMappingURL=authorize-C95F-9E1-CbESJKGU.js.map