@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 @@
1
+ {"version":3,"file":"authorize-C95F-9E1-CbESJKGU.js","names":["core._coercedString","schemas.ZodString","core._coercedBoolean","schemas.ZodBoolean","hmac","hmac","createView","encoder","encode","encoder","encode","cache","encode","b64u","transform","b64u","encode","encode","verifySignature","REGEX","encoder","b64u","encode","encoder","b64u","encode","b64u","decodeBase64URL","b64u","signJWT","base64url.encode","algorithm","getCryptoKey","makeSignature","getBody","isAPIError","tryDecode","parseCookies","tryDecode","ValidationError","parseCookies","isJSONSerializable","isAPIError","ValidationError","isAPIError","isAPIError","getBody","isAPIError","base64url.encode","JWKS_CACHE_TTL_MS","makeSignature","z.ipv4","z.ipv6","z.validate","ensureAsyncStorage","z.object","z.string","z.date","z.coerce.string","z.date","z.string","z.string","z.boolean","APIError","z.optional","z.object","z.coerce.boolean","z.looseObject","z.number","z.string","z.object","z.record","z.unknown","signJWT","APIError","z.object","z.string","APIError","z.url","z.NEVER","z.record","z.string","z.unknown","z.looseObject","z.boolean","z.array","z.object","z.union","z.NEVER","z.enum","z.number","z.literal","z.never","APIError","base64url.encode","APIError$1","APIError","APIError$1","z.core.toDotPath","z.string","z.array","z.object","z.boolean","z.enum","z.union","z.number","z.record","z.unknown","z.literal","makeSignature","__exportAll$1","NEVER","validate","_coercedString","record","union","unknown","optional","string$1","literal","_enum","number","ipv6","ipv4","ZodString","toDotPath","url","boolean$1","ZodObject","ZodOptional","array","ZodBoolean","looseObject","object","never","_coercedBoolean","toBufferSource","__getBetterAuthGlobal","BetterCallError","anumber$1","abytes$1","ValidationError$1","clean$1","aoutput$1","kAPIErrorHeaderSymbol","isProduction","isTest","env","APIError","rotr","base64","shouldPublishLog","aexists$1","createRandomStringGenerator","ahash","createView$1","createHasher","oidNist","APIError$1","createWithSpan","safeJSONParse","getAuthTables","isDevelopment","ATTR_HTTP_ROUTE","encodeDeterministicId","hex","BetterAuthError","__getCurrentEndpointContext","logger","base64Url","runtimeSchemaCheckFor","string","params","boolean","__defProp","__exportAll","target","name","all","no_symbols","signedQueryIssuedAtParam","postLoginClearedParam","signedQueryParameterNameParam","canonicalizeOAuthQueryParams","canonicalParams","entries","keyA","valueA","keyB","valueB","key","value","setSignedOAuthQueryParameterNames","signedParameterNames","parameterName","getSignedQueryIssuedAt","raw","oauthQuery","issuedAt","_HMAC","hash","blockLen","pad","i","buf","out","to","finished","destroyed","outputLen","canXOF","oHash","iHash","hmac$1","hmac_","message","HKDF_COUNTER","EMPTY_BUFFER","expand","length","prk","olen","blocks","info","_recycled","okm","T","worker","counter","iWork","res","hkdf","salt","HMAC","ikm","fromNumH","n","fromNumL","setU64FromNum","h","l","view","byteOffset","isLE","Chi","a","b","c","Maj","HashMD","padOffset","data","len","processed","pos","take","dataView","buffer","oview","outLen","state","SHA256_IV","SHA256_K","SHA256_W","SHA2_32B","IV","A","B","C","D","E","F","G","H","offset","W15","W2","s0","s1","sigma1","T1","T2","_SHA256","sha256","encoder$1","decoder","strictDecoder","MAX_INT32","concat","buffers","size","acc","writeUInt32BE","uint64be","high","low","uint32be","NON_ASCII","encode$1","bytes","code","encodeBase64","input","CHUNK_SIZE","arr","encoded","decodeBase64","binary","digest","subtleDigest","algorithm","JOSEError","options","JWTClaimValidationFailed","claim","reason","payload","JWTExpired","JOSEAlgNotAllowed","JOSENotSupported","JWEDecryptionFailed","JWEInvalid","JWSInvalid","JWTInvalid","JWKInvalid","JWKSInvalid","JWKSNoMatchingKey","JWKSMultipleMatchingKeys","JWKSTimeout","JWSSignatureVerificationFailed","invalid","decode","cause","encode","assertUint8Array","label","isObject","prototype","isJwkSet","isDisjoint","headers","parameters","header","parameter","assertNotSet","decodeBase64url","ErrorClass","encodeBase64url","parseJoseHeader","parsed","b64","JWS_RECOGNIZED","JWE_RECOGNIZED","validateAlgorithms","algorithms","s","option","validateCritDuplicates","protectedHeader","crit","Err","validateCrit","joseHeader","recognized","recognizedOption","recognizedDefault","validateB64","extensions","serializeJoseHeader","serialized","tag","jwkMatchesOp","entry","expected","usage","alg","expectedKeyOp","prepareKey","privateKey","secret","normalized","keyObject","normalizeJwk","invalidKeyType","key_ops","isKeyLike","expectedType","isCryptoKey","cacheKey","cached","cache$1","isPublic","crv","nist","jwkToKey","assertCryptoKey","isKeyObject","types","last","actual","msg","invalidKeyInput","unusable","prop","checkUsage","checkModulusLength","modulusLength","checkCryptoKey","snapshotJwk","jwk","keyOps","operation","validateExtractableOption","extractable","isPrivate","keyData","rawKey","generateCek","enc","checkCekLength","cek","generateIv","checkIvLength","iv","cbcKeySetup","keySize","cbcHmacTag","macKey","macData","cbcEncrypt","encKey","ciphertext","plaintext","aad","timingSafeEqual","aHmac","cbcDecrypt","expectedTag","encrypt","encrypted","decrypt","table","wrap","derive","none","rsaes","bits","ecdh","asymmetricKeyType","kty","aeskw","gcm","pbes2","JWE","contentOps","contentEncryption","cbc","ENC","unsupported","jweAlgorithm","isJWECEKTransport","jweEncryption","checkEcdhCryptoKey","aeskwWrap","cryptoKey","cryptoKeyCek","aeskwUnwrap","encryptedKey","checkRsaKey","deriveKey","p2s","p2c","keylen","subtleAlg","lengthAndInput","concatKdf","dkLen","L","reps","dk","hashResult","Z","OtherInfo","ecdhesDeriveKey","publicKey","otherInfo","apu","apv","keyLength","assertEcdhKey","curve","partyInfo","checkPartyInfo","assertEncryptedKey","assertNoEncryptedKey","validateMaxPBES2Count","decryptKeyManagement","mode","direct","epk","ephemeralPublicKey","partyUInfo","partyVInfo","sharedSecret","maxPBES2Count","p2cLimit","encryptKeyManagement","transport","providedCek","inputKey","providedApu","providedApv","providedParameters","ephemeralKey","subtle","exportableEpk","y","wrapped","validateZip","supported","transform$1","writer","stream","chunks","reader","done","maxLength","compress","decompress","shareJWE","encodedProtected","jwe","parsedProt","prepareDecrypt","decryptJWE","additionalData","token","unprotected","keyManagementAlgorithms","contentEncryptionAlgorithms","maxDecompressedLength","shared","encodedKey","selected","integrated","encEntry","error","resolvedKey","algEntry","k","encryption","err","decompressionLimit","decryptCompact","checkDisjoint","unprotectedHeader","sharedUnprotectedHeader","checkEncryptHeaders","keyManagementParameters","sharedHeadersNormalized","encryptJWE","checked","inputPlaintext","inputProtectedHeader","inputUnprotectedHeader","inputIv","unprotectedParameters","protectedHeaderS","aadMember","createJWE","compactJWE","sig","hmac","rsa","saltLength","ecdsa","eddsa","mldsa","JWS","jwsAlgorithm","prepareVerify","parseProtectedHeader","encodeCompactUnencodedPayload","verifySignature$1","inputPayload","jws","parsedProtected","signingPayload","encodeUnencodedPayload","signature","verified","result","verifyCompact","compactVerify","epoch","date","multipliers","REGEX$1","checkFailed","invalidDuration","secs","str","matched","numericDate2","validateInput","validateStringClaim","validateAudienceClaim","member","numericDate","normalizeTyp","checkAudiencePresence","audPayload","audOption","aud","validateNumericDate","required","unexpectedClaim","validateClaimsSet","encodedPayload","typ","presenceCheck","requiredClaims","maxTokenAge","audience","subject","issuer","tolerance","clockTolerance","now","currentDate","iat","nbf","exp","age","max","producerPayloads","producerPayload","producer","jwtData","jwtClaim","JWTClaimsBuilder","jwtVerify","jwt","jwtDecrypt","createSignature","protectedHeaderString","rejectUnencoded","payloadS","payloadB","createCompactSignature","SignJWT_base","SignJWT","#protectedHeader","EncryptJWT_base","EncryptJWT","#input","#replicateIssuerAsHeader","#replicateSubjectAsHeader","#replicateAudienceAsHeader","algArgument","unsupportedAlg","source","keyAlgorithm","bytesEqual","createASN1State","readByte","byte","parseLength","first","lengthOfLen","expectTag","errorMessage","getSubarray","parseAlgorithmOID","parseKeyHeader","keyFormat","parseECAlgorithmIdentifier","algOid","curveOid","genericImport","processPEMData","pem","pattern","fromSPKI","exportJWK","check","description","calculateJwkThumbprint","digestAlgorithm","components","isUsableJWK","jwkKid","jwkAlg","ext","index","kid","use","importWithAlgCache","cache","pending","createLocalJWKSet","snapshot","jwks","metadata","candidates","jwk2","importSPKI","spki","importJWK","decodeProtectedHeader","protectedB64u","parts","decodeJwt","decoded","getModulusLengthOption","generateKeyPair","signJWT$1","expiresIn","verifyJWT","deriveEncryptionSecret","getCurrentSecret","getAllSecrets","version","symmetricEncodeJWT","encryptionSecret","thumbprint","jwtDecryptOpts","symmetricDecodeJWT","hasKid","secrets","constantTimeEqual","aBuffer","bBuffer","generateRandomString","getWebcryptoSubtle","cr","createHash","hashBuffer","encoding","isBytes","atitle","title","abool","anumber","abytes","ofLen","got","aobject","aexists","instance","checkFinished","aoutput","min","u32","clean","arrays","createView","byteSwap","word","byteSwap32","swap32IfBE","u","hasHexBuiltin","hexes","bytesToHex","asciiToBase16","ch","hexToBytes","hl","al","ai","hi","n1","n2","char","utf8ToBytes","overlapBytes","complexOverlapBytes","output","concatBytes","sum","checkOpts","defaults","opts","equalBytes","diff","wrapMacConstructor","mac","macCons","getArgs","fromMsg","macC","tmp","keyLen","args","wrapCipher","wrappedCipher","nonce","tagl","aadStart","cipher","constructor","checkOutput","fnLength","called","getOutput","expectedLength","onlyAligned","isAligned32","u64Lengths","dataLength","aadLength","num","copyBytes","randomBytes","bytesLength","managedNonce","fn","randomBytes_","nonceLength","addNonce","ct","decrypted","encodeStr","sigma16_32","sigma32_32","rotl","BLOCK_LEN","BLOCK_LEN32","MAX_COUNTER","U32_EMPTY","runCipher","block","b32","isAligned","d32","o32","core","sigma","rounds","pos32","j","posj","createCipher","counterLength","counterRight","allowShortKeys","hasOutput","toClean","k32","extendNonceFn","n16","sigmaRaw","nonceNcLen","nc","n32","u8to16","Poly1305","t0","t1","t2","t3","t4","t5","t6","t7","hibit","isLast","r0","r","r1","r2","r3","r4","r5","r6","r7","r8","r9","h0","h1","h2","h3","h4","h5","h6","h7","h8","h9","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","g","mask","f","opos","poly1305","chachaCore","y00","y01","y02","y03","y04","y05","y06","y07","y08","y09","y10","y11","y12","cnt","y13","y14","y15","x00","x01","x02","x03","x04","x05","x06","x07","x08","x09","x10","x11","x12","x13","x14","x15","oi","hchacha","s2","k2","i2","t","xchacha20","ZEROS16","updatePadded","leftover","ZEROS32","computeTag","AAD","authKey","lengths","xchacha20poly1305","plength","oPlain","xorStream","passedTag","algorithm$1","ENVELOPE_PREFIX","parseEnvelope","secondSep","formatEnvelope","rawEncrypt","keyAsBytes","dataAsBytes","rawDecrypt","chacha","symmetricEncrypt","symmetricDecrypt","envelope","getCryptoKey$1","secretBuf","makeSignature$1","getCryptoKey","verifySignature","signatureBinStr","base64Signature","makeSignature","signCookieValue","jsonContentTypeRegex","getBody$1","contentType","request","normalizedContentType","allowedMediaTypes","normalizedContentTypeBase","normalizedAllowed","allowed","formData","isAPIError$1","tryDecode$1","tryCatch","promise","isRequest","obj","COOKIE_PREFIXES","getCookieKey","prefix","parseCookies$1","cookies","eqIdx","endIdx","val","resolveCookie","resolvedName","resolvedOptions","lowerName","serializeCookieValue","cookie","serializeCookie","opt","serializeSignedCookie","runValidation","context","fromError","validating","x","createInternalContext","responseStatus","requestHeaders","requestCookies","parsedCookies","internalContext","path","finalKey","signatureStartPos","signedValue","status","body","routerResponse","json","middleware","response","isJSONSerializable$1","safeStringify","parents","ids","id","isAncestor","curr","holder","isJSONResponse","REQUEST_ONLY_HEADERS","stripRequestOnlyHeaders","copyHeaders","toResponse","init","safeHeaders","statusText","createEndpoint","pathOrOptions","handlerOrOptions","handler","handlerOrNever","internalHandler","inputCtx","validationError","onAPIError","combineMiddleware","local","configured","createConfiguredEndpoint","createMiddleware","_handler","optionsOrHandler","paths","getTypeFromZodType","zodType","getParameters","getRequestBody","shape","properties","getResponse","responses","generator","endpoints","_","config","getHTML","apiReference","NullProtoObj","createRouter","scanFirstGroup","depth","mod","hasMod","expandGroupDelimiters","group","pre","suf","UNNAMED_GROUP_PREFIX","ESCAPED_GROUP_PREFIX","toUnnamedGroupKey","toGroupName","fromGroupName","hasSegmentWildcard","segment","replaceSegmentWildcards","nextIndex","unnamedStart","replaced","toGroupKey","encodeEscapes","segmentKey","expandModifiers","segments","m","wc","without","normalizePath","splitPath","splitRoute","getMatchParams","paramsMap","match","addRoute","method","groupExpanded","expandedPath","ctx","expanded","p","node","_unnamedParamIndex","paramsRegexp","regexp","getParamRegexp","child","staticNode","hasParams","methods","_i","_s","_d","regex","findRoute","staticMatch","_lookupTree","_selectMatcher","staticChild","optionalOnly","pMap","best","bestWeight","lastOptional","weight","dynamicTerminal","regexps","findAllRoutes","matches","_findAll","pushSorted","start","w","rx","pm","createRouter$1","openapi","\"openapi\"","schema","router","middlewareRouter","endpoint","basePath","processRequest","pathname","route","query","middlewareRoutes","errorResponse","onReq","req","onRes","defineErrorCodes","codes","BASE_ERROR_CODES","parseScopeField","scope","getOAuth2Tokens","getDate","seconds","mergeScopes","existing","stored","next","incoming","getPrimaryClientId","clientId","generateCodeChallenge","codeVerifier","BASIC_AUTHORIZATION_PATTERN","formUrlEncode","formUrlDecode","encodeBasicCredentials","clientSecret","decodeBasicCredentials","authorization","separatorIndex","rawClientId","rawClientSecret","PRIVATE_KEY_JWT_SIGNING_ALGORITHMS","CLIENT_ASSERTION_TYPE","resolveClientAssertionParams","getClientAssertion","BetterFetchError","initializePlugins","hooks","plugin","pluginRes","LinearRetryStrategy","attempt","ExponentialRetryStrategy","createRetryStrategy","parseMethodModifier","separator","isReservedPathSegment","encodeLiteralPathSegment","part","resolvePathSegment","pathParam","pathParams","getURL$1","baseURL","requestPath","urlQuery","queryParams","serializedValue","paramPaths","queryParamString","getAuthHeader","getValue","\"authorization\"","username","password","JSON_RE","detectResponseType","_contentType","textTypes","isJSONParsable","isJSONSerializable","jsonParse","text","isFunction","getFetch","mergeHeaders","sources","merged","getHeaders","detectContentType","getMediaType","getBody","getMethod","getTimeout","abortTimeout","controller","ValidationError","issues","parseStandardSchema","_typeof","o","toPrimitive","e","toPropertyKey","_defineProperty","ownKeys","_objectSpread2","betterFetch","_options$body","__url","fetch","signal","_url","onRequest","clearTimeout","responseContext","onResponse","_options$hookOptions","responseType","successContext","onSuccess","_options$hookOptions2","parser","responseText","errorObject","errorContext","onError","_options$hookOptions3","retryStrategy","_retryAttempt","onRetry","delay","resolve","httpRedirectStatuses","isRedirectResponse","redirectRefused","noFollowRedirect","fetchRefusingRedirects","redirected","DPOP_PROOF_TYPE","DPOP_SIGNING_ALGORITHMS","DEFAULT_DPOP_PROOF_MAX_AGE_SECONDS","MAX_DPOP_JTI_LENGTH","JWK_PRIVATE_FIELDS","createDpopReplayStore","reservations","createDpopProofError","isDpopProofError","parseAccessTokenAuthorization","scheme","stripAccessTokenAuthorizationScheme","normalizeDpopHtu","deriveDpopAth","accessToken","deriveDpopJkt","getConfirmationJkt","confirmation","jkt","getDpopJktFromPayload","getStringClaim","getNumberClaim","assertSupportedDpopAlgorithm","signingAlgorithms","assertPublicJwk","field","deriveDpopReplayKey","reserveDpopReplay","replayStore","reservation","verifyDpopProof","proofJwt","htm","htu","jti","normalizedHtu","proofHtu","nowSeconds","proofMaxAgeSeconds","ath","requireAth","expectedJkt","replayKey","expiresAt","createDpopBindingError","isDpopBindingError","enforceDpopBinding","dpopJkt","jwksCache","functionJwksCache","JWKS_CACHE_TTL_MS$1","getFreshJwksWithKid","fetchJwks","jwksFetch","getJwks","getJwksForVerification","jwtHeaders","cachedJwks","fetchedAt","DEFAULT_GRANT_TYPES","BUILT_IN_CONFIDENTIAL_AUTH_METHODS","RESERVED_TOKEN_ENDPOINT_AUTH_METHODS","RESERVED_TOKEN_ENDPOINT_AUTH_METHOD_SET","assertNonEmptyExtensionValue","assertAbsoluteUri","assertExtensionGrantType","grantType","assertExtensionTokenEndpointAuthMethod","assertExtensionClientAssertionType","assertionType","collectExtensionKeys","grantTypes","extension","authMethods","assertionTypes","strategy","methodAssertionTypes","clientDiscoveryIds","discovery","clientDiscoveryId","assertNoDuplicateAcrossExtensions","seen","values","validateOAuthProviderExtensions","keys","getOAuthProviderExtensions","getClientDiscoveries","extendOAuthProvider","provider","getExtensionGrantTypes","getSupportedGrantTypes","getExtensionGrantHandler","getExtensionTokenEndpointAuthMethods","getSupportedAuthMethods","settings","isExtensionTokenEndpointAuthMethod","getExtensionClientAuthenticationStrategy","strategies","applyOAuthProviderMetadataExtensions","document","contribution","collectClaims","claims","run","collectExtensionAccessTokenClaims","collectExtensionIdTokenClaims","collectExtensionUserInfoClaims","hasUserInfoClaimExtension","parseBearerToken","credentials","extraParts","createTTLCache","getOAuthProviderPlugin","getJwtPlugin","normalizeTimestampValue","trimmed","numeric","resolveSessionAuthTime","nested","toResourceList","toAudienceClaim","trustedClientCaches","getTrustedClientCache","existingCache","verifyOAuthQueryParams","oauth_query","sigs","verifySig","getClient","trustedClientCache","trustedClient","dbClient","discoveries","candidate","resolved","mergeDiscoveryMetadata","d","defaultHasher","decryptStoredClientSecret","storageMethod","storedClientSecret","verifyStoredClientSecret","hashedClientSecret","decryptedClientSecret","storeClientSecret","storeToken","type","getStoredToken","BASIC_SCHEME_PREFIX","AUTH_SCHEME_TOKEN","parseAuthorizationScheme","CLIENT_AUTHENTICATION_FIELDS","throwInvalidAuthenticationRequest","errorDescription","normalizeClientAuthenticationParameters","fields","setEffectiveField","hasAuthorizationHeader","clientIds","hasClientSecret","hasClientAssertion","basicToClientCredentials","clientAllowsGrant","allowedGrants","client","validateClientScopes","scopes","validScopes","throwInvalidClient","attemptedBasicAuthentication","authentication","challengeScheme","validateClientCredentials","authMethod","registeredAuthMethod","preVerified","parseClientMetadata","destructureCredentials","extractClientCredentials","assertion","extensionStrategy","verify","authorize_C95F_9E1_exports","expectedAudience","authorizationScheme","parsePrompt","prompts","prompt","set","getSectorIdentifier","uri","computePairwiseSub","userId","resolveSubjectIdentifier","searchParamsToQuery","isSessionFreshForSignedQuery","signedQueryIssuedAt","sessionCreatedAt","removePromptFromQuery","nextQuery","foundPrompt","v","removeMaxAgeFromQuery","isPKCERequired","requestScopes","isOpenIdRequest","hasNonce","hasOidcNonce","isAPIError","cachedAsyncLocalStorageConstructor","availabilityWarningLogged","getBuiltinAsyncLocalStorage","getAsyncLocalStorage","builtinConstructor","getExistingEndpointContextStorage","getOrCreateEndpointContextStorage","AsyncLocalStorage","globalContext","tryGetCurrentAuthEndpointContext","getCurrentAuthEndpointContext","authEndpointContext","runWithEndpointContext","NO_STORE_HEADERS","attachResponseHeadersToAPIError","responseHeaders","optionsMiddleware","createAuthMiddleware","createEndpointWithAuthContext","wrapEndpointHandler","noStore","createAuthEndpoint","withServerOnly","escapeRegExpChar","escapeRegExpString","transform","separatorSplitter","separatorMatcher","wildcard","requiredSeparator","optionalSeparator","nextSegment","currentSeparator","isMatch","sample","wildcardMatch","regexpPattern","SLASH_CHAR_CODE","isLoopbackForDevScheme","hostname","host","trimTrailingSlashes","end","checkHasPath","assertHasProtocol","parsedUrl","withPath","trimmedUrl","validateProxyHeader","getBaseURL","loadEnv","fromEnv","fromRequest","fromRequestProto","trustedProxyHeaders","getOrigin","getProtocol","getHost","isDynamicBaseURLConfig","isRequestLike","getHostFromSource","forwardedHost","getProtocolFromSource","configProtocol","forwardedProto","matchesHostPattern","normalizedHost","normalizedPattern","resolveDynamicBaseURL","resolveBaseURL","normalizePathname","requestUrl","normalizedBasePath","URL_REFERENCE_ORIGIN","appendQueryParams","relative","parsedURL","DANGEROUS_URL_SCHEMES","ipv4Schema","ipv6Schema","isValidIP","isIPv4","ip","isIPv6","extractIPv4FromMapped","lower","ipv4Part","groups","expandIPv6","sides","left","right","missingGroups","zeros","paddedLeft","paddedRight","normalizeIPv6","subnetPrefix","bitsRemaining","masked","normalizeIP","ipToBytes","octet","mapped","CIDR_PREFIX_PATTERN","parseCIDR","slash","maxBits","prefixPart","matchesCIDR","ipBytes","net","findInvalidTrustedProxies","getIPFromHeader","forwardedIps","trustedProxies","proxy","selectedIp","LOCALHOST_IP","DEFAULT_IP_HEADERS","getIP","ipHeaders","createRateLimitKey","ensureAsyncStorage$1","betterAuthGlobal","hasRequestState","getCurrentRequestState","store","runWithRequestState","defineRequestState","ref","initialValue","initFn","ensureAsyncStorage","getCurrentAdapter","als","fallback","runWithAdapter","pendingHooks","hasError","hook","runWithTransaction","pendingSchemaCheck","adapter","trx","runPendingHooks","hookError","unhandledErrors","queueAfterTransactionHook","executeHook","storage","getRawOAuthState","setOAuthState","getOAuthState","getOAuthServerContext","setOAuthServerContext","addOAuthServerContext","getShouldSkipSessionRefresh","setShouldSkipSessionRefresh","hasServerSessionStore","hasServerAccountStore","shouldBindAccountCookieToSessionUser","coreSchema","sessionSchema","userSchema","filterOutputFields","additionalFields","returnFiltered","returned","getFields","modelName","tableCache","parseUserOutput","user","buildSyntheticUserOutput","fieldAttr","parseSessionOutput","session","parseAccountOutput","_accessToken","_refreshToken","_idToken","_accessTokenExpiresAt","_refreshTokenExpiresAt","_password","rest","account","parseInputData","action","parsedData","parseUserInput","parseAdditionalUserInputFromProviderProfile","allowedProfileFields","profile","parseSessionInput","getSessionDefaultFields","mergeSchema","newSchema","newModelName","newField","unit","span","tryDecode","SECURE_COOKIE_PREFIX","splitSetCookieHeader","setCookie","parseSetCookieHeader","nameValue","attributes","cookieString","valueParts","unquoteCookieValue","attrObj","attrName","attrValueParts","attribute","attrValue","normalizedAttrName","cookieNameRegex","cookieValueRegex","trimOWS","parseCookies","cookieMap","chunk","eq","MAX_COOKIE_SIZE","MAX_COOKIE_CHUNKS","getMaxCookieValueSize","parseCookieChunkIndex","cookieName","suffix","readExistingChunks","chunkCookie","chunkSize","chunkCount","storeName","getCleanCookies","cleanedChunks","cookieOptions","storeFactory","expireExistingChunks","expired","chunked","createSessionStore","createAccountStore","getChunkedCookie","cookieHeader","setAccountCookie","accountDataCookie","accountData","accountStore","getAccountCookie","accountCookie","getSessionQuerySchema","isPromise","SEC","MIN","HOUR","DAY","WEEK","MONTH","YEAR","REGEX","parse","ms","sec","cookieCachePayloadSchema","compactCookieCacheSchema","parseCookieCachePayload","parseCompactCookieCache","decoders","encoder","createHMAC","keyUsage","hmacKey","createCookieGetter","baseURLString","dynamicProtocol","secureCookiePrefix","crossSubdomainEnabled","domain","createCookie","overrideAttributes","getCookies","sessionToken","sessionData","dontRememberToken","setCookieCache","filteredSession","filteredUser","versionConfig","dontRememberMe","expiresAtDate","cookieCacheSigner","sessionStore","hasPendingSetCookie","expireCookie","decodeCookieCache","setSessionCookie","dontRememberMeCookie","maxAge","overrides","removeSetCookieEntries","scoped","targets","exact","survivors","deleteSessionCookie","cleanCookies","skipDontRememberMe","getSession","deferSessionRefresh","isPostRequest","cookieCacheEnabled","sessionCookieToken","sessionDataCookie","shouldUseCookieCache","sessionDataPayload","shouldExpireCookieCache","expectedVersion","cachedSessionExpiresAt","cookieRefreshCache","parsedSession","parsedUser","timeUntilExpiry","updateAge","shouldSkipSessionRefresh","refreshedSession","sessionTokenOptions","sessionTokenMaxAge","parsedRefreshedSession","parsedRefreshedUser","shouldBeUpdated","disableRefresh","needsRefresh","updatedSession","parsedUpdatedSession","isStateful","getSessionFromCtx","lowerKey","getAuthoritativeSessionFromCtx","sessionMiddleware","sensitiveSessionMiddleware","freshSessionMiddleware","createdAt","freshAge","listSessions","activeSessions","revokeSession","revokeSessions","revokeOtherSessions","otherSessions","ATTR_OPERATION_ID","ATTR_HOOK_TYPE","ATTR_CONTEXT","isPlainObject","_defu","baseObject","namespace","merger","createDefu","arguments_","defu","CLOUD_METADATA_HOSTS","stripBrackets","stripPort","firstColon","stripZoneId","zone","stripTrailingDot","looksLikeIPv4","ipv4ToUint32","inIPv4Range","classifyIPv4","extractEmbeddedIPv4","startGroup","g1","g2","combined","classifyIPv6","firstByte","secondByte","embedded","classifyHost","lowered","canonical","isLoopbackIP","isLoopbackHost","kind","isPublicRoutableHost","defuReplaceArrays","hooksSourceWeakMap","getOperationId","mergeResponseHeaders","mergeAPIErrorHeaders","ctxHeaders","errHeaders","runBeforeHooks","withSpan","modifiedContext","hookSource","operationId","hookReturn","runAfterHooks","getHooks","plugins","authContext","beforeHooks","afterHooks","beforeHookHandler","afterHookHandler","pluginBeforeHooks","pluginAfterHooks","dispatchAuthEndpoint","endpointMethod","defaultMethod","methodName","shouldReturnResponse","before","after","REVERSE_DOMAIN_PRIVATE_USE_SCHEME","NON_PRIVATE_USE_SCHEMES","isReverseDomainPrivateUseRedirectUri","schemeSpecificPart","isHostBearingPrivateUseRedirectUri","isNativePrivateUseRedirectUri","SafeUrlSchema","getJwksAdapter","baseAdapter","isLive","configAlg","webKey","toExpJWT","expirationTime","generateExportedKeyPair","cfg","createJwk","explicitCrv","derivedCrv","publicWebKey","stringifiedPrivateWebKey","privateWebKey","privateKeyEncryptionEnabled","resolveSigningKey","primaryAlg","preconfig","isPrimary","advertisedExtra","signJWT","defaultExp","baseURLOrigin","iss","defaultIss","defaultAud","jwtPayload","getJwtToken","RESERVED_ID_TOKEN_CLAIMS","stripReservedIdTokenClaims","stripped","safeClaims","claimRequestMemberSchema","acrClaimRequestMemberSchema","idTokenClaimsRequestSchema","oidcClaimsRequestObjectSchema","parseClaimsRequestValue","parseOidcClaimsRequestObject","claimsRequestParameterValueSchema","claimsRequestInputSchema","claimsRequestParameterSchema","isValidOidcClaimsRequest","getRequestedUserInfoClaims","userInfoClaims","names","supportedClaims","canSatisfyEssentialAcrRequest","claimsRequest","acrRequest","valueMatches","currentAcr","valuesMatch","filterClaimsRequestUserInfoClaims","allowedClaimSet","allowedUserInfoClaims","filteredClaimsRequest","splitDisplayName","STANDARD_CLAIMS","STANDARD_CLAIM_NAMES","getSupportedClaims","RESERVED_ACCESS_TOKEN_CLAIMS","stripReservedClaims","safe","resolveAccessTokenClaims","extensionClaims","pluginClaims","perRequestClaims","resourcePolicyClaims","DANGEROUS_SCHEMES","ResourceUriSchema","authorizationPromptTokenSchema","authorizationPromptSchema","promptTokens","promptSet","clientJwksSchema","maxAgeSchema","dpopJktSchema","authorizationQuerySchema","storedAuthorizationQuerySchema","verificationValueSchema","clientRegistrationRequestSchema","JWS_ALGORITHMS","JWS_ALGORITHM_SET","MAX_AUD_VALUES","checkIdentifier","customValidator","identifier","assertIdentifierValid","userInfoResource","extractRepeatedResourceFromForm","normalizeResourceParam","resource","isAudienceClaimAllowed","audienceClaim","audienceValues","implicitAudienceSet","implicitAudiences","resourcesToLookup","audienceValue","getResource","resolveResourcePolicy","requestedResources","includesOpenid","userInfoResourceIdentifier","uniqueRequestedResources","row","enforcePerClient","resolveEnforcePerClientResources","assertClientLinkedToResources","effectiveScopes","intersection","accessTokenTtl","refreshTokenTtl","uniqueSigningAlgs","uniqueSigningKids","signingAlgorithm","signingKeyId","mergedClaims","dpopBoundAccessTokensRequired","audienceIdentifiers","audClaim","resources","links","linkedSet","unlinked","isClientLinkedToAnyResource","resourceIdentifiers","getResourceCustomClaims","rows","rowByIdentifier","resourceCache","invalidateResourceCache","seedResourcesOnce","dbResource","defaultName","collectResourceInputs","inputs","buildSeedRow","buildSeedUpdate","_identifier","_createdAt","update","MISSING_TABLE_PATTERN","logStartupSeedFailure","missingTable","current","seedStates","getSeedState","adapterKey","byOptions","created","seedResources","rawInput","where","logEnforcePerClientResourcesResolution","getDpopProofJwt","getEndpointUrl","USER_DELEGATED_SCOPES","isUserDelegatedScope","normalizeClientCredentialsScopes","validateClientCredentialsScopes","tokenEndpointAuthMethod","providerScopes","invalidScopes","userNormalClaims","requested","requestedClaims","definition","pickClaims","base","getUserInfoAccessToken","headerAccessTokenAuthorization","bodyToken","accessTokenAuthorization","userInfoEndpoint","requireActiveAccessTokenWithClaims","baseUserClaims","extensionUserClaims","additionalInfoUserClaims","ID_TOKEN_SCOPE_CLAIM_GUARDS","confirmationTokenType","JWT_ACCESS_TOKEN_TYPE","tokenEndpoint","handleAuthorizationCodeGrant","handleClientCredentialsGrant","handleRefreshTokenGrant","getOAuthProviderApi","createUserTokens","introspect_exports","validateAccessToken","requireActiveAccessToken","createJwtAccessToken","jwtPluginOptions","computeOidcHash","hashAlg","signingAlg","createIdToken","resolvedSub","authTimeSec","authTime","customClaims","atHash","emitSid","sessionId","additiveClaims","extraClaims","idToken","encodeRefreshToken","decodeRefreshToken","createOpaqueAccessToken","requestedUserInfoClaims","invalidateRefreshFamily","refreshTokens","revokeTokensIssuedForAuthorizationCode","deleteIssuedTokens","authorizationCodeId","createRefreshToken","newRow","originalRefresh","rotatedAt","rotationUpdate","reuseInterval","resolveResourceGrantIssuance","resourcePolicy","resourceExpiresAtSeconds","refreshTokenDefaultTtl","throwInvalidDpopProof","clientRequiresDpopBoundAccessTokens","resolveDpopTokenBinding","authCodeDpopJkt","refreshJkt","dpopProofJwt","dpopRequired","normalizeReplayValues","sameReplayValues","normalizedLeft","normalizedRight","confirmationReplayKey","sameConfirmation","isConfirmation","isTokenType","isOAuthTokenResponse","isRefreshTokenRotationReplay","replay","buildRefreshTokenRotationReplayRequest","sameRefreshTokenRotationReplayRequest","encryptRefreshTokenRotationReplay","decryptRefreshTokenRotationReplay","isWithinRefreshTokenReuseInterval","refreshToken","storeRefreshTokenRotationReplay","getRefreshTokenRotationReplay","resolveRefreshTokenRotationReplayRequest","grantIssuance","replayRefreshTokenRotationResponse","existingRefreshToken","scopeExp","sc","prev","refreshTokenExp","isRefreshToken","isJwtAccessToken","isIdToken","additionalIdTokenClaims","customFields","refreshResources","earlyRefreshToken","referenceId","accessTokenClaims","responseBody","checkVerificationValue","verification","rawValue","verificationValue","client_id","boundRedirectUri","redirect_uri","storedResources","effectiveResources","requestedSet","authorizedSet","client_secret","isAuthCodeWithSecret","isAuthCodeWithPkce","code_verifier","pkceUsedInAuth","pkceUsedInToken","authorizedResources","clientCredentialsScopes","requestedScopes","refresh_token","decodedRefresh","requestedScope","introspectEndpoint","INVALID_ACCESS_TOKEN_ERROR_DESCRIPTION","INVALID_ACCESS_TOKEN_WWW_AUTHENTICATE","inactiveAccessToken","audienceResourceIdentifiers","userInfoAud","isIntrospectionAuthorized","introspectingClientId","issuerClientId","audienceResources","validateJwtAccessToken","jwtPlugin","expectedIssuer","rawAud","validateOpaqueAccessToken","tokenValue","validateRefreshToken","createInvalidAccessTokenError","isInactiveTokenError","resolveAccessTokenValidation","resolveIntrospectionSub","issuingClient","introspectingClient","token_type_hint","PACKAGE_VERSION","isBrowserFetchRequest","metadataResponse","oauthAuthorizationServerMetadata","oidcServerMetadata","oauthProvider","validatePublicClientJwks","DEFAULT_OAUTH_SCOPES","client_assertion_exports","getOAuthProviderState","consumeClientAssertion","getIssuer","authServerMetadata","consentEndpoint","oauthRequest","oAuthState","_query","originalRequestedScopes","originalRequestedUserInfoClaims","acceptedClaims","acceptedUserInfoClaims","formatErrorURL","hasLoginPrompt","hasSatisfiedLoginPrompt","authorize","foundConsent","consent","authorizationQuery","continueEndpoint","postLogin","BACKCHANNEL_LOGOUT_EVENT_URI","LOGOUT_TOKEN_JWT_TYP","LOGOUT_TOKEN_LIFETIME_SECONDS","BACKCHANNEL_DISPATCH_TIMEOUT_MS","signLogoutToken","prepareBackchannelLogoutPlan","accessTokens","affectedClientIds","clients","accessToRevokeIds","refreshToRevokeIds","eligibleClients","applyBackchannelLogoutPlan","revokedAt","revocations","plan","deliverBackchannelLogoutTokens","LOGOUT_CONFIRMATION_TTL_SECONDS","LOGOUT_CONFIRMATION_COOKIE_SUFFIX","escapeHtml","character","isBrowserNavigation","accept","logoutPage","logoutConfirmationPath","logoutConfirmationCookiePath","logoutConfirmationPage","logoutSuccessPage","note","logoutErrorPage","logoutProtocolError","logoutConfirmationCookieName","logoutConfirmationCookieOptions","setLogoutConfirmationState","getLogoutConfirmationState","clearLogoutConfirmationState","getCurrentBrowserSession","findHintedSession","deleteLogoutSession","getLogoutClient","normalizeLogoutAudiences","getHintClientId","audiences","resolveHintClient","hint","verifyLogoutHint","verifiedPayload","getRegisteredLogoutRedirect","requestedURI","redirectURI","getLogoutConfirmationContext","getConfirmedLogoutRedirect","confirmationRequired","currentSession","completeConfirmedLogout","redirect","handleRedirect","rpInitiatedLogoutEndpoint","idTokenPayload","hintedSession","matchesCurrentSession","sessionToDelete","rpInitiatedLogoutConfirmationEndpoint","backchannelSupported","validateIssuerUrl","buildAuthServerMetadata","clientDiscoveries","publicClientSupported","authMetadata","primary","extras","METADATA_CACHE_CONTROL","extraHeaders","createOAuthEndpoint","userHook","redirectOnError","mapIssuesToOAuthError","errorCodesByField","defaultError","bodySchema","querySchema","forwarded","validateSlot","slot","issue","fieldKey","mapping","resolveErrorCode","describeIssue","isMissingValueIssue","publicSessionMiddleware","EC_PRIVATE_KEY_JWT_ALGORITHM_BY_CURVE","OKP_PRIVATE_KEY_JWT_SIGNING_CURVES","PRIVATE_JWK_MEMBER_NAMES","isRecord$1","hasStringMember","memberName","isSupportedEcSigningCurve","isSupportedOkpSigningCurve","signingCurve","isSupportedPublicJwk","hasSupportedPrivateKeyJwtAlgorithm","OAUTH_CLIENT_RECORD_FIELD_NAMES","OAUTH_CLIENT_WIRE_FIELD_NAMES","OPAQUE_METADATA_RESERVED_FIELDS","stripReservedOAuthClientMetadataExtensions","assertClientPrivileges","assertResourcePrivileges","isPrivateHostname","verifyClientAssertion","jwksCaches","JWKS_CACHE_TTL_MS","JWKS_CACHE_MAX_ENTRIES","JWKS_FETCH_TIMEOUT_MS","MAX_JWKS_RESPONSE_BYTES","JSON_CONTENT_TYPE","setJwksCache","oldest","getJwksCache","getJwksCacheKey","ALGORITHMS_LIST","validateJwksUri","jwksUri","clientIdUrlOrigin","urlClientIdOrigin","readBoundedResponseBody","contentLength","totalBytes","fetchJwksFromUri","timeout","fetchClientMetadataResource","parsedBody","createClientJwksFetchError","fetchClientJwks","staleLimitMs","refetchClientJwks","maxLifetime","jtiDigest","jtiId","createErr","alreadyUsed","clientAssertionType","clientAssertion","unverified","clientIdHint","endpointAudience","issuerAudience","acceptedAudiences","verifyOpts","verifyErr","refreshed","acceptedAudience","registrationBearerError","authorizeInitialAccessToken","initialAccessToken","DEFAULT_REGISTRATION_GRANT_TYPES","resolveClientRegistrationScopes","resolveRegistrationGrantTypes","resolveRegistrationResponseTypes","applyOAuthClientRegistrationDefaults","defaultApplicationType","isCustomSchemeWithHost","redirectUri","isNonHttpRedirectUri","protocol","resolveDynamicRegistrationDefaultApplicationType","invalidRedirectUri","getRawHttpHostname","authority","hostAndPort","bracketEnd","assertDynamicRegistrationResourcesAllowed","allowedResources","resolveClientRegistrationResources","defaultResources","validateClientRedirectUri","isHttp","isHttps","isRedirectLoopback","rawHttpHostname","applicationType","assertValidRegistrationJwks","registerEndpoint","tokenAuthorization","isTokenAuthorized","createOAuthClientRegistration","checkOAuthClient","isClientMetadataDocument","clientWithDefaults","responseTypes","supportedGrantTypes","validatesRegistrationMetadata","allowedScopes","CLIENT_REGISTRATION_COLLISION","persistOAuthClientRegistration","registrationMetadata","isPrivateKeyJwt","isExtensionAuthMethod","isPKCEOptionalForRegisteredClient","requirePKCE","_requestedResources","persistableBody","owner","oauthToSchema","clientModel","clientResourceModel","existingClient","persistenceResult","storedClient","updatedClient","isUniqueConstraintError","linkedResources","linkedResourceIds","link","resourceId","createOAuthClientRegistrationResponse","schemaToOAuth","createOAuthClientAdministrativeResponse","createOAuthClientAdministrativeRegistration","createOAuthClientEndpoint","rawClientCredentialsScopes","registrationInput","_expiresAt","_scope","icon","tos","policy","inputJwks","softwareId","softwareVersion","softwareStatement","redirectUris","postLogoutRedirectUris","backchannelLogoutUri","backchannelLogoutSessionRequired","skipConsent","enableEndSession","dpopBoundAccessTokens","subjectType","inputMetadata","metadataObj","_updatedAt","_scopes","contacts","disabled","getClientEndpoint","getClientPublicEndpoint","getClientsEndpoint","deleteClientEndpoint","updateClientEndpoint","updates","ownsClient","isCrossOwnerScopeConfiguration","finalGrantTypes","finalTokenEndpointAuthMethod","schemaUpdates","rotateClientSecretEndpoint","tokenEndpointAuthMethodSchema","grantTypesSchema","adminCreateOAuthClient","createOAuthClient","getOAuthClient","getOAuthClientPublic","getOAuthClientPublicPrelogin","getOAuthClients","adminUpdateOAuthClient","updateOAuthClient","rotateClientSecret","deleteOAuthClient","getConsent","getConsentEndpoint","getConsentsEndpoint","deleteConsentEndpoint","updateConsentEndpoint","getOAuthConsent","getOAuthConsents","updateOAuthConsent","deleteOAuthConsent","resourceModel","linkModel","decodePathParam","buildResourceRow","createResourceEndpoint","listResourcesEndpoint","getResourceByIdentifierEndpoint","updateResourceEndpoint","deleteResourceEndpoint","linkClientResourceEndpoint","unlinkClientResourceEndpoint","resourceBodySchema","adminCreateOAuthResource","adminListOAuthResources","adminGetOAuthResource","adminUpdateOAuthResource","adminDeleteOAuthResource","adminLinkClientResource","adminUnlinkClientResource","revokeJwtAccessToken","userInfoAudience","revokeOpaqueAccessToken","revokeRefreshToken","revokeAccessToken","revokeEndpoint","rpInitiatedLogoutRequestSchema","backchannelLogoutPlansByContext","signedQueryIssuedAtMsKey","getServerContextSignedQueryIssuedAt","issuedAtMs","clientRegistrationAllowedScopes","_allowedScopes","configuredResourceIdentifiers","optionName","identifiers","handleIssuerMetadataRequest","requestPathname","issuerPath","endpointCtx","authServerMetadataPaths","openIdConfigPath","isAuthServerMetadataRequest","isOpenIdConfigRequest","createMetadataResponse","oauth2AuthorizeEndpoint","authorizeRedirectOnError","authorizeEndpoint","runOAuth2Authorize","isDynamicBaseURLInit","hookCtx","logoutPlanBySessionId","logoutTask","postLoginClearedForSession","serverContext","secFetchMode","acceptHeader","repeated","isWithinMaxAge","maxAgeSeconds","removeMaxAgeFromAuthorizationQuery","_maxAge","queryWithoutMaxAge","searchParams","deriveResponseMode","responseMode","authorizationQueryErrorCodesByField","isRecord","getStringParameter","getAuthorizationRequestParameters","fromFetch","acceptJson","redirectWithPromptNoneError","getErrorURL","stripLoopbackRedirectPort","isLoopback","schemeSeparatorIndex","authorityStart","authorityEndOffset","authorityEnd","portStart","closingBracket","port","portStartInUri","findRegisteredRedirectUri","registered","requestedUrl","hasFragment","hasUserinfo","requestedWithoutPort","isSafeCustomRedirectUri","resolveTrustedRedirectUri","registeredUris","trusted","error_description","requestObject","requestUri","resolvedParams","urlClientId","parsedQuery","mappedError","serializeAuthorizationQuery","promptNone","isValidRedirectUri","defaultResult","openidRequested","pkceRequired","hasSatisfiedMaxAge","redirectWithPromptCode","signupRedirect","redirectWithAuthorizationCode","consentedResources","requestedResource","redirectUriWithCode","signParams","flags"],"sources":["../../../../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/coerce.js","../../../../../node_modules/.pnpm/@better-auth+oauth-provider@1.7.8_@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@bet_a9f2bc837da41095445a0377e1cf646a/node_modules/@better-auth/oauth-provider/dist/rolldown-runtime-wcPFST8Q.mjs","../../../../../node_modules/.pnpm/@better-auth+oauth-provider@1.7.8_@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@bet_a9f2bc837da41095445a0377e1cf646a/node_modules/@better-auth/oauth-provider/dist/signed-query-Df1MNiSH.mjs","../../../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/hmac.js","../../../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/hkdf.js","../../../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_u64.js","../../../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_md.js","../../../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha2.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/buffer_utils.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/errors.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/base64url.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/validate.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/key.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/content_encryption.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/key_descriptor.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jwe_algorithms.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/key_management.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/deflate.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jwe_decrypt.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jwe_encrypt.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jws_algorithms.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jws_verify.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jws/compact/verify.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jwt_claims_set.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwt/verify.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwt/decrypt.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/jws_sign.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwt/sign.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwt/encrypt.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/key_algorithm.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/lib/asn1.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/key/export.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwk/thumbprint.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/jwks/local.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/key/import.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/decode_protected_header.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/util/decode_jwt.js","../../../../../node_modules/.pnpm/jose@6.2.12/node_modules/jose/dist/webapi/key/generate_key_pair.js","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/crypto/jwt.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/crypto/buffer.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/crypto/random.mjs","../../../../../node_modules/.pnpm/@better-auth+utils@0.5.0/node_modules/@better-auth/utils/dist/index.mjs","../../../../../node_modules/.pnpm/@better-auth+utils@0.5.0/node_modules/@better-auth/utils/dist/hash.mjs","../../../../../node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/utils.js","../../../../../node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/_arx.js","../../../../../node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/_poly1305.js","../../../../../node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/chacha.js","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/crypto/index.mjs","../../../../../node_modules/.pnpm/better-call@1.4.2_zod@4.6.7/node_modules/better-call/dist/crypto.mjs","../../../../../node_modules/.pnpm/better-call@1.4.2_zod@4.6.7/node_modules/better-call/dist/utils.mjs","../../../../../node_modules/.pnpm/better-call@1.4.2_zod@4.6.7/node_modules/better-call/dist/cookies.mjs","../../../../../node_modules/.pnpm/better-call@1.4.2_zod@4.6.7/node_modules/better-call/dist/validator.mjs","../../../../../node_modules/.pnpm/better-call@1.4.2_zod@4.6.7/node_modules/better-call/dist/context.mjs","../../../../../node_modules/.pnpm/better-call@1.4.2_zod@4.6.7/node_modules/better-call/dist/to-response.mjs","../../../../../node_modules/.pnpm/better-call@1.4.2_zod@4.6.7/node_modules/better-call/dist/endpoint.mjs","../../../../../node_modules/.pnpm/better-call@1.4.2_zod@4.6.7/node_modules/better-call/dist/middleware.mjs","../../../../../node_modules/.pnpm/better-call@1.4.2_zod@4.6.7/node_modules/better-call/dist/openapi.mjs","../../../../../node_modules/.pnpm/rou3@0.9.2/node_modules/rou3/dist/index.mjs","../../../../../node_modules/.pnpm/better-call@1.4.2_zod@4.6.7/node_modules/better-call/dist/router.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/utils/error-codes.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/error/codes.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/oauth2/utils.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/oauth2/basic-credentials.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/oauth2/client-assertion.mjs","../../../../../node_modules/.pnpm/@better-fetch+fetch@1.3.2/node_modules/@better-fetch/fetch/dist/index.js","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/oauth2/reject-redirects.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/oauth2/dpop.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/oauth2/verify.mjs","../../../../../node_modules/.pnpm/@better-auth+oauth-provider@1.7.8_@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@bet_a9f2bc837da41095445a0377e1cf646a/node_modules/@better-auth/oauth-provider/dist/utils-CGIZS-Da.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/utils/is-api-error.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/async_hooks/index.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/context/endpoint-context.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/api/index.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/utils/wildcard.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/utils/url.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/utils/url.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/utils/ip.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/context/request-state.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/context/transaction.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/api/state/oauth.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/api/state/should-session-refresh.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/context/store-capabilities.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/db/schema/shared.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/db/schema/session.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/db/schema/user.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/utils/db.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/db/schema.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/utils/date.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/cookies/cookie-utils.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/cookies/session-store.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/utils/is-promise.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/utils/time.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/cookies/cache.mjs","../../../../../node_modules/.pnpm/@better-auth+utils@0.5.0/node_modules/@better-auth/utils/dist/binary.mjs","../../../../../node_modules/.pnpm/@better-auth+utils@0.5.0/node_modules/@better-auth/utils/dist/hmac.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/cookies/index.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/api/routes/session.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/instrumentation/attributes.mjs","../../../../../node_modules/.pnpm/defu@6.1.7/node_modules/defu/dist/defu.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/utils/host.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/api/dispatch.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/utils/redirect-uri.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/plugins/jwt/adapter.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/plugins/jwt/utils.mjs","../../../../../node_modules/.pnpm/better-auth@1.7.8_@tanstack+react-start@1.168.60_@voidzero-dev+vite-plus-core@1.2.0_@ty_d7f44717d4a32b4e04105c42076a65b3/node_modules/better-auth/dist/plugins/jwt/sign.mjs","../../../../../node_modules/.pnpm/@better-auth+oauth-provider@1.7.8_@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@bet_a9f2bc837da41095445a0377e1cf646a/node_modules/@better-auth/oauth-provider/dist/introspect-H3uoUiuS.mjs","../../../../../node_modules/.pnpm/@better-auth+oauth-provider@1.7.8_@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@bet_a9f2bc837da41095445a0377e1cf646a/node_modules/@better-auth/oauth-provider/dist/version-BPS0os17.mjs","../../../../../node_modules/.pnpm/@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@better-fetch+fetch@1.3.2_better-call@_e244494d16af5cbfc2a915ab801404c3/node_modules/@better-auth/core/dist/utils/fetch-metadata.mjs","../../../../../node_modules/.pnpm/@better-auth+oauth-provider@1.7.8_@better-auth+core@1.7.8_@better-auth+utils@0.5.0_@bet_a9f2bc837da41095445a0377e1cf646a/node_modules/@better-auth/oauth-provider/dist/authorize-C95F-9E1.mjs"],"sourcesContent":["import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport function string(params) {\n return core._coercedString(schemas.ZodString, params);\n}\nexport function number(params) {\n return core._coercedNumber(schemas.ZodNumber, params);\n}\nexport function boolean(params) {\n return core._coercedBoolean(schemas.ZodBoolean, params);\n}\nexport function bigint(params) {\n return core._coercedBigint(schemas.ZodBigInt, params);\n}\nexport function date(params) {\n return core._coercedDate(schemas.ZodDate, params);\n}\n","//#region \\0rolldown/runtime.js\nvar __defProp = Object.defineProperty;\nvar __exportAll = (all, no_symbols) => {\n\tlet target = {};\n\tfor (var name in all) __defProp(target, name, {\n\t\tget: all[name],\n\t\tenumerable: true\n\t});\n\tif (!no_symbols) __defProp(target, Symbol.toStringTag, { value: \"Module\" });\n\treturn target;\n};\n//#endregion\nexport { __exportAll as t };\n","//#region src/signed-query.ts\nconst signedQueryIssuedAtParam = \"ba_iat\";\nconst postLoginClearedParam = \"ba_pl\";\nconst signedQueryParameterNameParam = \"ba_param\";\nfunction canonicalizeOAuthQueryParams(params) {\n\tconst canonicalParams = new URLSearchParams();\n\tconst entries = [...params.entries()].sort(([keyA, valueA], [keyB, valueB]) => {\n\t\tif (keyA < keyB) return -1;\n\t\tif (keyA > keyB) return 1;\n\t\tif (valueA < valueB) return -1;\n\t\tif (valueA > valueB) return 1;\n\t\treturn 0;\n\t});\n\tfor (const [key, value] of entries) canonicalParams.append(key, value);\n\treturn canonicalParams;\n}\nfunction setSignedOAuthQueryParameterNames(params) {\n\tparams.delete(signedQueryParameterNameParam);\n\tconst signedParameterNames = [...new Set([...params.keys(), signedQueryParameterNameParam])].sort();\n\tfor (const parameterName of signedParameterNames) params.append(signedQueryParameterNameParam, parameterName);\n}\nfunction getSignedOAuthQueryParameterNames(params) {\n\tconst signedParameterNames = params.getAll(signedQueryParameterNameParam);\n\tif (!signedParameterNames.length) return;\n\treturn new Set(signedParameterNames);\n}\nfunction buildSignedOAuthQuery(search) {\n\tconst params = new URLSearchParams(search);\n\tif (!params.has(\"sig\")) return;\n\tconst signedParameterNames = getSignedOAuthQueryParameterNames(params);\n\tif (!signedParameterNames) return;\n\tconst signedParams = new URLSearchParams();\n\tfor (const [key, value] of params.entries()) if (key === \"sig\" || key === signedQueryParameterNameParam || signedParameterNames.has(key)) signedParams.append(key, value);\n\treturn signedParams.toString();\n}\nfunction getSignedQueryIssuedAt(oauthQuery) {\n\tconst raw = new URLSearchParams(oauthQuery).get(signedQueryIssuedAtParam);\n\tif (!raw) return null;\n\tconst issuedAt = Number(raw);\n\tif (!Number.isFinite(issuedAt) || issuedAt <= 0) return null;\n\treturn new Date(issuedAt);\n}\n//#endregion\nexport { setSignedOAuthQueryParameterNames as a, postLoginClearedParam as i, canonicalizeOAuthQueryParams as n, signedQueryIssuedAtParam as o, getSignedQueryIssuedAt as r, buildSignedOAuthQuery as t };\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, aoutput, clean, } from \"./utils.js\";\n/**\n * Internal class for HMAC.\n * Accepts any byte key, although RFC 2104 §3 recommends keys at least\n * `HashLen` bytes long.\n */\nexport class _HMAC {\n oHash;\n iHash;\n blockLen;\n outputLen;\n canXOF = false;\n finished = false;\n destroyed = false;\n constructor(hash, key) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('expected Hash instance');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of the first block) of the outer hash here,\n // we can re-use it between multiple calls via clone.\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const buf = out.subarray(0, this.outputLen);\n // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before\n // overwriting that same prefix with the final tag, leaving any oversized tail untouched.\n this.iHash.digestInto(buf);\n this.oHash.update(buf);\n this.oHash.digestInto(buf);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since the key\n // is already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.canXOF = canXOF;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\nexport const hmac = /* @__PURE__ */ (() => {\n const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());\n hmac_.create = (hash, key) => new _HMAC(hash, key);\n return hmac_;\n})();\n","/**\n * HKDF (RFC 5869): extract + expand in one step.\n * See {@link https://soatok.blog/2021/11/17/understanding-hkdf/}.\n * @module\n */\nimport { hmac } from \"./hmac.js\";\nimport { abytes, ahash, anumber, clean } from \"./utils.js\";\n/**\n * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * Local validation only checks `hash`; `ikm` / `salt` byte validation is delegated to `hmac()`.\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @returns Pseudorandom key derived from input keying material.\n * @example\n * Run the HKDF extract step.\n * ```ts\n * import { extract } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * extract(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));\n * ```\n */\nexport function extract(hash, ikm, salt) {\n ahash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen);\n return hmac(hash, salt, ikm);\n}\n// Shared mutable scratch byte for the RFC 5869 block counter `N`.\n// Safe to reuse because `expand()` is synchronous and resets it with `clean(...)` before returning.\nconst HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);\n// Shared RFC 5869 empty string for both `info === undefined` and the first-block `T(0)` input.\nconst EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();\n/**\n * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`\n * @param hash - hash function that would be used (e.g. sha256)\n * @param prk - a pseudorandom key of at least HashLen octets\n * (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes.\n * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM.\n * @param _recycled - Internal destroyed extract hashes owned by the combined `hkdf()` call.\n * @returns Output keying material with the requested length.\n * @throws If the requested output length exceeds the HKDF limit\n * for the selected hash. {@link Error}\n * @example\n * Run the HKDF expand step.\n * ```ts\n * import { expand } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16);\n * ```\n */\nexport function expand(hash, prk, info, length = 32, _recycled) {\n ahash(hash);\n anumber(length, 'length');\n abytes(prk, undefined, 'prk');\n const olen = hash.outputLen;\n // RFC 5869 §2.3: PRK is \"a pseudorandom key of at least HashLen octets\".\n if (prk.length < olen)\n throw new Error('\"prk\" must be at least HashLen octets');\n // RFC 5869 §2.3 only bounds `L` by `<= 255*HashLen`; `L=0` is valid and yields empty OKM.\n if (length > 255 * olen)\n throw new Error('Length must be <= 255*HashLen');\n const blocks = Math.ceil(length / olen);\n if (info === undefined)\n info = EMPTY_BUFFER;\n else\n abytes(info, undefined, 'info');\n if (!blocks) {\n if (_recycled)\n clean(prk); // Full hkdf() owns this intermediate PRK.\n return new Uint8Array();\n }\n // first L(ength) octets of T\n // The private PRK can become both T and a one-block result after HMAC consumes the key.\n const okm = _recycled && blocks === 1 ? prk : new Uint8Array(blocks * olen);\n const { iHash, oHash } = hmac.create(hash, prk);\n // Driving them directly also skips `_HMAC.digestInto`'s per-digest destroy.\n const T = _recycled ? prk : new Uint8Array(olen);\n // Full hkdf() donates one destroyed extract hash; standalone creates one alternating worker.\n const worker = blocks > 1 ? _recycled?.iHash || hash.create() : undefined;\n for (let counter = 0; counter < blocks - 1; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n const iWork = iHash._cloneInto(worker);\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n if (counter)\n iWork.update(T);\n iWork.update(info).update(HKDF_COUNTER).digestInto(T);\n oHash._cloneInto(worker).update(T).digestInto(T);\n okm.set(T, olen * counter);\n }\n // Midstates are key-equivalent: they allow computing HMAC(prk, ...) for any message.\n HKDF_COUNTER[0] = blocks; // Final block consumes them; retain worker for cleanup.\n if (blocks > 1)\n iHash.update(T);\n iHash.update(info).update(HKDF_COUNTER).digestInto(T);\n oHash.update(T).digestInto(T);\n okm.set(T, olen * (blocks - 1));\n iHash.destroy(); // Raw digests may leave key-derived base/worker state; wipe all explicitly.\n oHash.destroy();\n worker?.destroy();\n if (T !== okm)\n clean(T); // Wipe private T/PRK; standalone preserves caller-owned PRK.\n clean(HKDF_COUNTER);\n // Exact fit: return without the extra copy.\n if (length === okm.length)\n return okm;\n // Copy the requested prefix, then wipe the full buffer: its tail holds\n // up to HashLen-1 bytes of derived key material past `length`.\n const res = okm.slice(0, length);\n clean(okm);\n return res;\n}\n/**\n * HKDF (RFC 5869): derive keys from an initial input.\n * Combines hkdf_extract + hkdf_expand in one step\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information bytes\n * @param length - length of output keying material in bytes.\n * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM.\n * @returns Output keying material derived from the input key.\n * @throws If the requested output length exceeds the HKDF limit\n * for the selected hash. {@link Error}\n * @example\n * HKDF (RFC 5869): derive keys from an initial input.\n * ```ts\n * import { hkdf } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';\n * const inputKey = randomBytes(32);\n * const salt = randomBytes(32);\n * const info = utf8ToBytes('application-key');\n * const okm = hkdf(sha256, inputKey, salt, info, 32);\n * ```\n */\nexport const hkdf = (hash, ikm, salt, info, length) => {\n ahash(hash);\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen);\n const HMAC = hmac.create(hash, salt).update(ikm);\n // The intermediate PRK is secret key material; wipe it instead of\n // leaving it for GC.\n return expand(hash, HMAC.digest(), info, length, HMAC); // expand() owns and consumes it.\n};\n","const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers\n// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below\n// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).\nconst fromNumH = (n) => (n / 2 ** 32) | 0;\nconst fromNumL = (n) => n >>> 0;\n// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call\n// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.\nfunction setU64FromNum(view, byteOffset, n, isLE) {\n const h = fromNumH(n);\n const l = fromNumL(n);\n view.setUint32(byteOffset, isLE ? l : h, isLE);\n view.setUint32(byteOffset + 4, isLE ? h : l, isLE);\n}\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps\n// local copies so V8 inlines them into keccakP.\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { setU64FromNum } from \"./_u64.js\";\nimport { abytes, aexists, aoutput, createView } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n let processed = false;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n processed = true;\n continue;\n }\n // When the whole input is buffered in one go (common for short messages), passing `data`\n // directly avoids allocating a subarray view.\n buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n processed = true;\n }\n }\n this.length += data.length;\n // Shared schedule buffers only pick up input-derived words inside process(); if everything\n // was buffered without processing, there is nothing to zero.\n if (processed)\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message, then zero-pad the rest of the block\n buffer[pos++] = 0b10000000;\n buffer.fill(0, pos);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n buffer.fill(0);\n }\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an\n // integer below 2**53, so the split inside the helper stays exact).\n setU64FromNum(view, blockLen - 8, this.length * 8, isLE);\n this.process(view, 0);\n // The final block above is processed outside update(), so the shared message-schedule\n // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().\n this.roundClean();\n // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.\n const oview = out === buffer ? view : createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n const outLen = len / 4;\n const state = this.get();\n // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.\n if (len % 4 || outLen > state.length)\n throw new Error('invalid outputLen');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneIntoMeta(to) {\n const { buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (pos)\n to.buffer.set(buffer); // Avoid a hot modulo guard.\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nclass SHA2_32B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and makes sha256 3x slower (measured).\n A = 0;\n B = 0;\n C = 0;\n D = 0;\n E = 0;\n F = 0;\n G = 0;\n H = 0;\n constructor(outputLen, IV) {\n super(64, outputLen, 8, false);\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B {\n constructor() {\n super(32, SHA256_IV);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B {\n constructor() {\n super(28, SHA224_IV);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nclass SHA2_64B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and slows hashing down (measured on sha256).\n Ah = 0;\n Al = 0;\n Bh = 0;\n Bl = 0;\n Ch = 0;\n Cl = 0;\n Dh = 0;\n Dl = 0;\n Eh = 0;\n El = 0;\n Fh = 0;\n Fl = 0;\n Gh = 0;\n Gl = 0;\n Hh = 0;\n Hl = 0;\n constructor(outputLen, IV) {\n super(128, outputLen, 16, false);\n this.Ah = IV[0] | 0;\n this.Al = IV[1] | 0;\n this.Bh = IV[2] | 0;\n this.Bl = IV[3] | 0;\n this.Ch = IV[4] | 0;\n this.Cl = IV[5] | 0;\n this.Dh = IV[6] | 0;\n this.Dl = IV[7] | 0;\n this.Eh = IV[8] | 0;\n this.El = IV[9] | 0;\n this.Fh = IV[10] | 0;\n this.Fl = IV[11] | 0;\n this.Gh = IV[12] | 0;\n this.Gl = IV[13] | 0;\n this.Hh = IV[14] | 0;\n this.Hl = IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B {\n constructor() {\n super(64, SHA512_IV);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B {\n constructor() {\n super(48, SHA384_IV);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n constructor() {\n super(28, T224_IV);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n constructor() {\n super(32, T256_IV);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n","const encoder = new TextEncoder(), decoder = new TextDecoder(), strictDecoder = new TextDecoder(\"utf-8\", { fatal: !0 }), MAX_INT32 = 2 ** 32;\nfunction concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0), buf = new Uint8Array(size);\n let i = 0;\n for (const buffer of buffers)\n buf.set(buffer, i), i += buffer.length;\n return buf;\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= MAX_INT32)\n throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset);\n}\nfunction uint64be(value) {\n const high = Math.floor(value / MAX_INT32), low = value % MAX_INT32, buf = new Uint8Array(8);\n return writeUInt32BE(buf, high, 0), writeUInt32BE(buf, low, 4), buf;\n}\nfunction uint32be(value) {\n const buf = new Uint8Array(4);\n return writeUInt32BE(buf, value), buf;\n}\nconst NON_ASCII = /[^\\x00-\\x7f]/;\nfunction encode(string) {\n if (typeof string == \"string\" && string.length >= 128) {\n if (NON_ASCII.test(string))\n throw new TypeError(\"non-ASCII string encountered in encode()\");\n return encoder.encode(string);\n }\n const bytes = new Uint8Array(string.length);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code > 127)\n throw new TypeError(\"non-ASCII string encountered in encode()\");\n bytes[i] = code;\n }\n return bytes;\n}\nfunction encodeBase64(input, url = !1) {\n if (Uint8Array.prototype.toBase64)\n return input.toBase64({ alphabet: url ? \"base64url\" : \"base64\", omitPadding: url });\n const CHUNK_SIZE = 32768, arr = [];\n for (let i = 0; i < input.length; i += CHUNK_SIZE)\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n const encoded = btoa(arr.join(\"\"));\n return url ? encoded.replace(/=/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\") : encoded;\n}\nfunction decodeBase64(encoded, url = !1) {\n if (Uint8Array.fromBase64)\n return Uint8Array.fromBase64(encoded, { alphabet: url ? \"base64url\" : \"base64\" });\n if (url) {\n if (encoded.includes(\"+\") || encoded.includes(\"/\"))\n throw new TypeError(\"Invalid base64url\");\n encoded = encoded.replace(/-/g, \"+\").replace(/_/g, \"/\");\n }\n const binary = atob(encoded), bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\nasync function digest(algorithm, data) {\n const subtleDigest = `SHA-${algorithm.slice(-3)}`;\n return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));\n}\nexport {\n concat,\n decodeBase64,\n decoder,\n digest,\n encode,\n encodeBase64,\n encoder,\n strictDecoder,\n uint32be,\n uint64be\n};\n","class JOSEError extends Error {\n static code = \"ERR_JOSE_GENERIC\";\n code = \"ERR_JOSE_GENERIC\";\n constructor(message, options) {\n super(message, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);\n }\n}\nclass JWTClaimValidationFailed extends JOSEError {\n static code = \"ERR_JWT_CLAIM_VALIDATION_FAILED\";\n code = \"ERR_JWT_CLAIM_VALIDATION_FAILED\";\n claim;\n reason;\n payload;\n constructor(message, payload, claim = \"unspecified\", reason = \"unspecified\") {\n super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;\n }\n}\nclass JWTExpired extends JOSEError {\n static code = \"ERR_JWT_EXPIRED\";\n code = \"ERR_JWT_EXPIRED\";\n claim;\n reason;\n payload;\n constructor(message, payload, claim = \"unspecified\", reason = \"unspecified\") {\n super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;\n }\n}\nclass JOSEAlgNotAllowed extends JOSEError {\n static code = \"ERR_JOSE_ALG_NOT_ALLOWED\";\n code = \"ERR_JOSE_ALG_NOT_ALLOWED\";\n}\nclass JOSENotSupported extends JOSEError {\n static code = \"ERR_JOSE_NOT_SUPPORTED\";\n code = \"ERR_JOSE_NOT_SUPPORTED\";\n}\nclass JWEDecryptionFailed extends JOSEError {\n static code = \"ERR_JWE_DECRYPTION_FAILED\";\n code = \"ERR_JWE_DECRYPTION_FAILED\";\n constructor(message = \"decryption operation failed\", options) {\n super(message, options);\n }\n}\nclass JWEInvalid extends JOSEError {\n static code = \"ERR_JWE_INVALID\";\n code = \"ERR_JWE_INVALID\";\n}\nclass JWSInvalid extends JOSEError {\n static code = \"ERR_JWS_INVALID\";\n code = \"ERR_JWS_INVALID\";\n}\nclass JWTInvalid extends JOSEError {\n static code = \"ERR_JWT_INVALID\";\n code = \"ERR_JWT_INVALID\";\n}\nclass JWKInvalid extends JOSEError {\n static code = \"ERR_JWK_INVALID\";\n code = \"ERR_JWK_INVALID\";\n}\nclass JWKSInvalid extends JOSEError {\n static code = \"ERR_JWKS_INVALID\";\n code = \"ERR_JWKS_INVALID\";\n}\nclass JWKSNoMatchingKey extends JOSEError {\n static code = \"ERR_JWKS_NO_MATCHING_KEY\";\n code = \"ERR_JWKS_NO_MATCHING_KEY\";\n constructor(message = \"no applicable key found in the JSON Web Key Set\", options) {\n super(message, options);\n }\n}\nclass JWKSMultipleMatchingKeys extends JOSEError {\n [Symbol.asyncIterator] = async function* () {\n };\n static code = \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\";\n code = \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\";\n constructor(message = \"multiple matching keys found in the JSON Web Key Set\", options) {\n super(message, options);\n }\n}\nclass JWKSTimeout extends JOSEError {\n static code = \"ERR_JWKS_TIMEOUT\";\n code = \"ERR_JWKS_TIMEOUT\";\n constructor(message = \"request timed out\", options) {\n super(message, options);\n }\n}\nclass JWSSignatureVerificationFailed extends JOSEError {\n static code = \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\";\n code = \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\";\n constructor(message = \"signature verification failed\", options) {\n super(message, options);\n }\n}\nexport {\n JOSEAlgNotAllowed,\n JOSEError,\n JOSENotSupported,\n JWEDecryptionFailed,\n JWEInvalid,\n JWKInvalid,\n JWKSInvalid,\n JWKSMultipleMatchingKeys,\n JWKSNoMatchingKey,\n JWKSTimeout,\n JWSInvalid,\n JWSSignatureVerificationFailed,\n JWTClaimValidationFailed,\n JWTExpired,\n JWTInvalid\n};\n","import { encoder, decoder, encodeBase64, decodeBase64 } from \"../lib/buffer_utils.js\";\nconst invalid = \"The input to be decoded is not correctly encoded.\";\nfunction decode(input) {\n try {\n return decodeBase64(typeof input == \"string\" ? input : decoder.decode(input), !0);\n } catch (cause) {\n throw new TypeError(invalid, { cause });\n }\n}\nfunction encode(input) {\n return encodeBase64(typeof input == \"string\" ? encoder.encode(input) : input, !0);\n}\nexport {\n decode,\n encode\n};\n","import { JOSENotSupported, JWSInvalid } from \"../util/errors.js\";\nimport { decode } from \"../util/base64url.js\";\nimport { encode, strictDecoder } from \"./buffer_utils.js\";\nfunction assertUint8Array(input, label) {\n if (!(input instanceof Uint8Array))\n throw new TypeError(`${label} must be an instance of Uint8Array`);\n}\nfunction isObject(input) {\n if (typeof input != \"object\" || input === null || Object.prototype.toString.call(input) !== \"[object Object]\")\n return !1;\n const prototype = Object.getPrototypeOf(input);\n return prototype === null || Object.getPrototypeOf(prototype) === null;\n}\nfunction isJwkSet(input) {\n return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject);\n}\nfunction isDisjoint(...headers) {\n const parameters = /* @__PURE__ */ new Set();\n for (const header of headers)\n if (header)\n for (const parameter of Object.keys(header)) {\n if (parameters.has(parameter))\n return !1;\n parameters.add(parameter);\n }\n return !0;\n}\nfunction assertNotSet(value, name) {\n if (value !== void 0)\n throw new TypeError(`${name} can only be called once`);\n}\nfunction decodeBase64url(value, label, ErrorClass) {\n try {\n return decode(value);\n } catch {\n throw new ErrorClass(`Failed to base64url decode the ${label}`);\n }\n}\nfunction encodeBase64url(value, label, ErrorClass) {\n try {\n return encode(value);\n } catch {\n throw new ErrorClass(`The ${label} is not a valid base64url string`);\n }\n}\nfunction parseJoseHeader(b64, ErrorClass, message) {\n let parsed;\n try {\n parsed = JSON.parse(strictDecoder.decode(decode(b64)));\n } catch {\n throw new ErrorClass(message);\n }\n if (!isObject(parsed))\n throw new ErrorClass(message);\n return parsed;\n}\nconst JWS_RECOGNIZED = { __proto__: null, b64: !0 }, JWE_RECOGNIZED = { __proto__: null };\nfunction validateAlgorithms(option, algorithms) {\n if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != \"string\")))\n throw new TypeError(`\"${option}\" option must be an array of strings`);\n return algorithms === void 0 ? void 0 : new Set(algorithms);\n}\nfunction validateCritDuplicates(Err, protectedHeader) {\n const { crit } = protectedHeader ?? {};\n if (Array.isArray(crit) && new Set(crit).size !== crit.length)\n throw new Err('\"crit\" (Critical) Header Parameter MUST NOT contain duplicate values');\n}\nfunction validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0)\n throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n if (!protectedHeader || protectedHeader.crit === void 0)\n return [];\n if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != \"string\" || input.length === 0))\n throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };\n for (const parameter of protectedHeader.crit) {\n if (!(parameter in recognized))\n throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0)\n throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0))\n throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n }\n return protectedHeader.crit;\n}\nfunction validateB64(protectedHeader, extensions) {\n if (extensions.includes(\"b64\")) {\n const b64 = protectedHeader.b64;\n if (typeof b64 != \"boolean\")\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n return b64;\n }\n return !0;\n}\nfunction serializeJoseHeader(Err, header) {\n let serialized, parsed;\n try {\n serialized = JSON.stringify(header), parsed = JSON.parse(serialized);\n } catch (cause) {\n throw new Err(\"JOSE Header is not valid JSON\", { cause });\n }\n if (!isObject(parsed))\n throw new Err(\"JOSE Header is not a JSON object\");\n return [parsed, serialized];\n}\nexport {\n JWE_RECOGNIZED,\n JWS_RECOGNIZED,\n assertNotSet,\n assertUint8Array,\n decodeBase64url,\n encodeBase64url,\n isDisjoint,\n isJwkSet,\n isObject,\n parseJoseHeader,\n serializeJoseHeader,\n validateAlgorithms,\n validateB64,\n validateCrit,\n validateCritDuplicates\n};\n","import { isObject } from \"./validate.js\";\nimport { decode } from \"../util/base64url.js\";\nimport { JOSENotSupported } from \"../util/errors.js\";\nconst tag = (key) => key[Symbol.toStringTag], jwkMatchesOp = (entry, key, usage) => {\n const { alg } = entry;\n if (key.use !== void 0) {\n const expected = usage === \"sign\" || usage === \"verify\" ? \"sig\" : \"enc\";\n if (key.use !== expected)\n throw new TypeError(`Invalid key for this operation, its \"use\" must be \"${expected}\" when present`);\n }\n if (key.alg !== void 0 && key.alg !== alg)\n throw new TypeError(`Invalid key for this operation, its \"alg\" must be \"${alg}\" when present`);\n if (Array.isArray(key.key_ops)) {\n const expectedKeyOp = usage === \"encrypt\" || usage === \"decrypt\" ? entry.ops?.[usage === \"encrypt\" ? 0 : 1] : usage;\n if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp))\n throw new TypeError(`Invalid key for this operation, its \"key_ops\" must include \"${expectedKeyOp}\" when present`);\n }\n};\nasync function prepareKey(entry, key, usage) {\n const { alg, secret } = entry, privateKey = usage === \"decrypt\" || usage === \"sign\";\n if (secret && key instanceof Uint8Array)\n return key;\n let normalized, keyObject;\n if (isObject(key)) {\n if (normalized = normalizeJwk(key), typeof normalized.kty != \"string\")\n throw invalidKeyType(alg, key, secret);\n if (!(secret ? normalized.kty === \"oct\" && typeof normalized.k == \"string\" : normalized.kty !== \"oct\" && (privateKey ? normalized.kty === \"AKP\" && typeof normalized.priv == \"string\" || typeof normalized.d == \"string\" : normalized.d === void 0 && normalized.priv === void 0)))\n throw new TypeError(secret ? '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 ${privateKey ? \"private\" : \"public\"} JWK`);\n if (jwkMatchesOp(entry, normalized, usage), normalized.kty === \"oct\")\n return decode(normalized.k);\n if (!Object.isFrozen(key)) {\n const { key_ops } = key;\n Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);\n }\n } else {\n if (!isKeyLike(key))\n throw invalidKeyType(alg, key, secret);\n const expectedType = secret ? \"secret\" : privateKey ? \"private\" : \"public\";\n if (key.type !== expectedType && (secret || [\"secret\", \"public\", \"private\"].includes(key.type)))\n throw new TypeError(`${tag(key)} instances must be of type \"${expectedType}\" for the ${alg} algorithm`);\n if (isCryptoKey(key))\n return key;\n if (keyObject = key, keyObject.type === \"secret\")\n return keyObject.export();\n }\n cache ||= /* @__PURE__ */ new WeakMap();\n const cacheKey = key;\n let cached = cache.get(cacheKey);\n if (cached?.[alg])\n return cached[alg];\n if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == \"function\") {\n const isPublic = keyObject.type === \"public\", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({ crv, asymmetricKeyType: keyObject.asymmetricKeyType }) ?? entry.subtle;\n return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);\n }\n return normalized ??= keyObject.export({ format: \"jwk\" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized);\n}\nlet cache;\nconst nist = {\n __proto__: null,\n prime256v1: \"P-256\",\n secp384r1: \"P-384\",\n secp521r1: \"P-521\"\n};\nfunction assertCryptoKey(key) {\n if (!isCryptoKey(key))\n throw new Error(\"CryptoKey instance expected\");\n}\nconst isCryptoKey = (key) => {\n if (key?.[Symbol.toStringTag] === \"CryptoKey\")\n return !0;\n try {\n return key instanceof CryptoKey;\n } catch {\n return !1;\n }\n}, isKeyObject = (key) => key?.[Symbol.toStringTag] === \"KeyObject\", isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);\nfunction message(msg, actual, ...types) {\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(\", \")}, or ${last}.`;\n } else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;\n return actual == null ? msg += ` Received ${actual}` : typeof actual == \"function\" && actual.name ? msg += ` Received function ${actual.name}` : typeof actual == \"object\" && actual != null && actual.constructor?.name && (msg += ` Received an instance of ${actual.constructor.name}`), msg;\n}\nconst invalidKeyInput = (actual, ...types) => message(\"Key must be \", actual, ...types);\nfunction invalidKeyType(alg, actual, secret) {\n const types = [\"CryptoKey\", \"KeyObject\", \"JSON Web Key\"];\n return secret && types.push(\"Uint8Array\"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));\n}\nconst unusable = (name, prop = \"algorithm.name\") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\nfunction checkUsage(key, usage) {\n if (usage && !key.usages.includes(usage))\n throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);\n}\nfunction checkModulusLength(alg, key) {\n const { modulusLength } = key.algorithm;\n if (typeof modulusLength != \"number\" || modulusLength < 2048)\n throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n}\nfunction checkCryptoKey(key, expected, usage) {\n const algorithm = key.algorithm;\n if (algorithm.name !== expected.name)\n throw unusable(expected.name);\n if (expected.hash && algorithm.hash?.name !== expected.hash)\n throw unusable(expected.hash, \"algorithm.hash\");\n if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve)\n throw unusable(expected.namedCurve, \"algorithm.namedCurve\");\n if (expected.length !== void 0 && algorithm.length !== expected.length)\n throw unusable(expected.length, \"algorithm.length\");\n checkUsage(key, usage);\n}\nfunction snapshotJwk(jwk) {\n return { __proto__: null, ...jwk };\n}\nfunction normalizeJwk(jwk) {\n const normalized = snapshotJwk(jwk);\n if (normalized.ext !== void 0 && typeof normalized.ext != \"boolean\")\n throw new TypeError('\"ext\" (Extractable) Parameter must be a boolean');\n if (normalized.key_ops !== void 0) {\n const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;\n if (!keyOps || keyOps.some((operation) => typeof operation != \"string\") || new Set(keyOps).size !== keyOps.length)\n throw new TypeError('\"key_ops\" (Key Operations) Parameter must be an array of unique strings');\n normalized.key_ops = keyOps;\n }\n return normalized;\n}\nfunction validateExtractableOption(extractable) {\n if (extractable !== void 0 && typeof extractable != \"boolean\")\n throw new TypeError('\"extractable\" option must be a boolean');\n return extractable;\n}\nasync function jwkToKey(entry, jwk, extractable) {\n if (!entry.kty.includes(jwk.kty))\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = { ...jwk, ext: extractable ?? jwk.ext };\n return keyData.kty !== \"AKP\" && delete keyData.alg, delete keyData.use, crypto.subtle.importKey(\"jwk\", keyData, algorithm, keyData.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);\n}\nasync function rawKey(key, expected, usage, extractable = !1) {\n return key instanceof Uint8Array && (key = await crypto.subtle.importKey(\"raw\", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;\n}\nexport {\n assertCryptoKey,\n checkCryptoKey,\n checkModulusLength,\n checkUsage,\n invalidKeyInput,\n isCryptoKey,\n isKeyLike,\n isKeyObject,\n jwkToKey,\n normalizeJwk,\n prepareKey,\n rawKey,\n snapshotJwk,\n validateExtractableOption\n};\n","import { concat, uint64be } from \"./buffer_utils.js\";\nimport { rawKey, invalidKeyInput, isCryptoKey } from \"./key.js\";\nimport { JWEDecryptionFailed, JWEInvalid } from \"../util/errors.js\";\nconst generateCek = (enc) => crypto.getRandomValues(new Uint8Array(enc.cekBits >> 3));\nfunction checkCekLength(cek, expected) {\n const actual = cek.byteLength << 3;\n if (actual !== expected)\n throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);\n}\nconst generateIv = (enc) => crypto.getRandomValues(new Uint8Array(enc.ivBits >> 3));\nfunction checkIvLength(enc, iv) {\n if (iv.length << 3 !== enc.ivBits)\n throw new JWEInvalid(\"Invalid Initialization Vector length\");\n}\nasync function cbcKeySetup(enc, cek, usage) {\n if (!(cek instanceof Uint8Array))\n throw new TypeError(invalidKeyInput(cek, \"Uint8Array\"));\n const keySize = enc.cekBits >> 1, encKey = await crypto.subtle.importKey(\"raw\", cek.subarray(keySize >> 3), \"AES-CBC\", !1, [usage]), macKey = await crypto.subtle.importKey(\"raw\", cek.subarray(0, keySize >> 3), {\n hash: `SHA-${keySize << 1}`,\n name: \"HMAC\"\n }, !1, [\"sign\"]);\n return [encKey, macKey, keySize];\n}\nasync function cbcHmacTag(macKey, macData, keySize) {\n return new Uint8Array((await crypto.subtle.sign(\"HMAC\", macKey, macData)).slice(0, keySize >> 3));\n}\nasync function cbcEncrypt(enc, plaintext, cek, iv, aad) {\n const [encKey, macKey, keySize] = await cbcKeySetup(enc, cek, \"encrypt\"), ciphertext = new Uint8Array(await crypto.subtle.encrypt({\n iv,\n name: \"AES-CBC\"\n }, encKey, plaintext)), macData = concat(aad, iv, ciphertext, uint64be(aad.length * 8)), tag = await cbcHmacTag(macKey, macData, keySize);\n return { ciphertext, tag, iv };\n}\nasync function timingSafeEqual(a, b) {\n const algorithm = { name: \"HMAC\", hash: \"SHA-256\" }, key = await crypto.subtle.generateKey(algorithm, !1, [\"sign\", \"verify\"]), aHmac = await crypto.subtle.sign(algorithm, key, a);\n return crypto.subtle.verify(algorithm, key, aHmac, b);\n}\nasync function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {\n const [encKey, macKey, keySize] = await cbcKeySetup(enc, cek, \"decrypt\"), macData = concat(aad, iv, ciphertext, uint64be(aad.length * 8)), expectedTag = await cbcHmacTag(macKey, macData, keySize);\n try {\n if (await timingSafeEqual(tag, expectedTag))\n return new Uint8Array(await crypto.subtle.decrypt({ iv, name: \"AES-CBC\" }, encKey, ciphertext));\n } catch {\n }\n throw new JWEDecryptionFailed();\n}\nasync function encrypt(enc, plaintext, cek, iv, aad) {\n if (!isCryptoKey(cek) && !(cek instanceof Uint8Array))\n throw new TypeError(invalidKeyInput(cek, \"CryptoKey\", \"KeyObject\", \"Uint8Array\", \"JSON Web Key\"));\n if (iv ? checkIvLength(enc, iv) : iv = generateIv(enc), cek instanceof Uint8Array && checkCekLength(cek, enc.cekBits), enc.cbc)\n return cbcEncrypt(enc, plaintext, cek, iv, aad);\n const encKey = await rawKey(cek, enc.subtle, \"encrypt\"), encrypted = new Uint8Array(await crypto.subtle.encrypt({\n additionalData: aad,\n iv,\n name: \"AES-GCM\",\n tagLength: 128\n }, encKey, plaintext));\n return { ciphertext: encrypted.subarray(0, -16), tag: encrypted.subarray(-16), iv };\n}\nasync function decrypt(enc, cek, ciphertext, iv, tag, aad) {\n if (!isCryptoKey(cek) && !(cek instanceof Uint8Array))\n throw new TypeError(invalidKeyInput(cek, \"CryptoKey\", \"KeyObject\", \"Uint8Array\", \"JSON Web Key\"));\n if (!iv)\n throw new JWEInvalid(\"JWE Initialization Vector missing\");\n if (!tag)\n throw new JWEInvalid(\"JWE Authentication Tag missing\");\n if (!enc.cbc && tag.length !== 16)\n throw new JWEInvalid(\"Invalid Authentication Tag length\");\n if (checkIvLength(enc, iv), cek instanceof Uint8Array && checkCekLength(cek, enc.cekBits), enc.cbc)\n return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad);\n const encKey = await rawKey(cek, enc.subtle, \"decrypt\");\n try {\n return new Uint8Array(await crypto.subtle.decrypt({\n additionalData: aad,\n iv,\n name: \"AES-GCM\",\n tagLength: 128\n }, encKey, concat(ciphertext, tag)));\n } catch {\n throw new JWEDecryptionFailed();\n }\n}\nexport {\n checkCekLength,\n checkIvLength,\n decrypt,\n encrypt,\n generateCek,\n generateIv\n};\n","function table(entries) {\n const out = { __proto__: null };\n for (const alg in entries)\n out[alg] = { ...entries[alg], alg };\n return out;\n}\nexport {\n table\n};\n","import { JOSENotSupported } from \"../util/errors.js\";\nimport { table } from \"./key_descriptor.js\";\nconst wrap = [\n [\"encrypt\", \"wrapKey\"],\n [\"decrypt\", \"unwrapKey\"]\n], derive = [[], [\"deriveBits\"]], none = [[], []];\nfunction rsaes(bits) {\n return {\n kty: [\"RSA\"],\n mode: \"key-encryption\",\n subtle: { name: \"RSA-OAEP\", hash: `SHA-${bits}` },\n usages: wrap,\n ops: [\"wrapKey\", \"unwrapKey\"]\n };\n}\nfunction ecdh(mode) {\n return {\n kty: [\"EC\", \"OKP\"],\n mode,\n subtle: { name: \"ECDH\" },\n resolve: ({ kty, crv, asymmetricKeyType }) => {\n if (crv === \"X25519\" || asymmetricKeyType === \"x25519\")\n return { name: \"X25519\" };\n if (kty === \"OKP\")\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n return { name: \"ECDH\", namedCurve: crv };\n },\n usages: derive,\n ops: [void 0, \"deriveBits\"]\n };\n}\nfunction aeskw(bits, gcm = !1) {\n return {\n kty: [\"oct\"],\n mode: \"key-wrapping\",\n secret: !0,\n subtle: { name: gcm ? \"AES-GCM\" : \"AES-KW\", length: bits },\n usages: none,\n ops: gcm ? [\"encrypt\", \"decrypt\"] : [\"wrapKey\", \"unwrapKey\"]\n };\n}\nfunction pbes2() {\n return {\n kty: [\"oct\"],\n mode: \"key-wrapping\",\n secret: !0,\n subtle: { name: \"PBKDF2\" },\n usages: none,\n ops: [\"deriveBits\", \"deriveBits\"]\n };\n}\nconst JWE = table({\n dir: {\n kty: [\"oct\"],\n mode: \"direct-encryption\",\n secret: !0,\n subtle: { name: \"AES-GCM\" },\n usages: none,\n ops: [\"encrypt\", \"decrypt\"]\n },\n \"RSA-OAEP\": rsaes(1),\n \"RSA-OAEP-256\": rsaes(256),\n \"RSA-OAEP-384\": rsaes(384),\n \"RSA-OAEP-512\": rsaes(512),\n \"ECDH-ES\": ecdh(\"direct-key-agreement\"),\n \"ECDH-ES+A128KW\": ecdh(\"key-agreement-with-key-wrapping\"),\n \"ECDH-ES+A192KW\": ecdh(\"key-agreement-with-key-wrapping\"),\n \"ECDH-ES+A256KW\": ecdh(\"key-agreement-with-key-wrapping\"),\n A128KW: aeskw(128),\n A192KW: aeskw(192),\n A256KW: aeskw(256),\n A128GCMKW: aeskw(128, !0),\n A192GCMKW: aeskw(192, !0),\n A256GCMKW: aeskw(256, !0),\n \"PBES2-HS256+A128KW\": pbes2(),\n \"PBES2-HS384+A192KW\": pbes2(),\n \"PBES2-HS512+A256KW\": pbes2()\n}), contentOps = [\"encrypt\", \"decrypt\"];\nfunction contentEncryption(bits, cbc = !1) {\n return {\n kty: [\"oct\"],\n secret: !0,\n subtle: { name: cbc ? \"AES-CBC\" : \"AES-GCM\", length: bits },\n usages: none,\n ops: contentOps,\n cekBits: bits,\n ivBits: cbc ? 128 : 96,\n cbc\n };\n}\nconst ENC = table({\n A128GCM: contentEncryption(128),\n A192GCM: contentEncryption(192),\n A256GCM: contentEncryption(256),\n \"A128CBC-HS256\": contentEncryption(256, !0),\n \"A192CBC-HS384\": contentEncryption(384, !0),\n \"A256CBC-HS512\": contentEncryption(512, !0)\n});\nfunction unsupported(parameter, name) {\n throw new JOSENotSupported(`Invalid or unsupported \"${parameter}\" (JWE ${name}) header value`);\n}\nfunction jweAlgorithm(alg) {\n return (typeof alg == \"string\" ? JWE[alg] : void 0) ?? unsupported(\"alg\", \"Algorithm\");\n}\nfunction isJWECEKTransport(algorithm) {\n return algorithm.mode === \"key-wrapping\" || algorithm.mode === \"key-encryption\" || algorithm.mode === \"key-agreement-with-key-wrapping\";\n}\nfunction jweEncryption(enc) {\n return (typeof enc == \"string\" ? ENC[enc] : void 0) ?? unsupported(\"enc\", \"Encryption Algorithm\");\n}\nexport {\n JWE,\n isJWECEKTransport,\n jweAlgorithm,\n jweEncryption\n};\n","import { encode as b64u } from \"../util/base64url.js\";\nimport { prepareKey, rawKey, jwkToKey, checkCryptoKey, checkModulusLength, checkUsage, assertCryptoKey } from \"./key.js\";\nimport { jweAlgorithm, jweEncryption, isJWECEKTransport } from \"./jwe_algorithms.js\";\nimport { JOSENotSupported, JWEInvalid } from \"../util/errors.js\";\nimport { decodeBase64url, assertUint8Array, isObject } from \"./validate.js\";\nimport { digest, concat, encode, uint32be } from \"./buffer_utils.js\";\nimport { checkCekLength, generateCek, encrypt, decrypt } from \"./content_encryption.js\";\nfunction checkEcdhCryptoKey(key, usage) {\n if (key.algorithm.name !== \"ECDH\" && key.algorithm.name !== \"X25519\")\n throw new TypeError(\"CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519\");\n checkUsage(key, usage);\n}\nasync function aeskwWrap(alg, key, cek) {\n const cryptoKey = await rawKey(key, jweAlgorithm(alg).subtle, \"wrapKey\", !0), cryptoKeyCek = await crypto.subtle.importKey(\"raw\", cek, { hash: \"SHA-256\", name: \"HMAC\" }, !0, [\"sign\"]);\n return new Uint8Array(await crypto.subtle.wrapKey(\"raw\", cryptoKeyCek, cryptoKey, \"AES-KW\"));\n}\nasync function aeskwUnwrap(alg, key, encryptedKey) {\n const cryptoKey = await rawKey(key, jweAlgorithm(alg).subtle, \"unwrapKey\", !0), cryptoKeyCek = await crypto.subtle.unwrapKey(\"raw\", encryptedKey, cryptoKey, \"AES-KW\", { hash: \"SHA-256\", name: \"HMAC\" }, !0, [\"sign\"]);\n return new Uint8Array(await crypto.subtle.exportKey(\"raw\", cryptoKeyCek));\n}\nfunction checkRsaKey(alg, key, usage) {\n checkCryptoKey(key, jweAlgorithm(alg).subtle, usage), checkModulusLength(alg, key);\n}\nasync function deriveKey(p2s, alg, p2c, key) {\n if (!(p2s instanceof Uint8Array) || p2s.length < 8)\n throw new JWEInvalid(\"PBES2 Salt Input must be 8 or more octets\");\n if (!Number.isSafeInteger(p2c) || Math.sign(p2c) !== 1)\n throw new JWEInvalid(\"PBES2 Count Input must be a positive integer\");\n const salt = concat(encode(alg), Uint8Array.of(0), p2s), keylen = parseInt(alg.slice(13, 16), 10), subtleAlg = {\n hash: `SHA-${alg.slice(8, 11)}`,\n iterations: p2c,\n name: \"PBKDF2\",\n salt\n }, cryptoKey = await rawKey(key, jweAlgorithm(alg).subtle, \"deriveBits\");\n return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));\n}\nfunction lengthAndInput(input) {\n return concat(uint32be(input.length), input);\n}\nasync function concatKdf(Z, L, OtherInfo) {\n const dkLen = L >> 3, hashLen = 32, reps = Math.ceil(dkLen / hashLen), dk = new Uint8Array(reps * hashLen);\n for (let i = 1; i <= reps; i++) {\n const hashResult = await digest(\"sha256\", concat(uint32be(i), Z, OtherInfo));\n dk.set(hashResult, (i - 1) * hashLen);\n }\n return dk.slice(0, dkLen);\n}\nasync function ecdhesDeriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) {\n checkEcdhCryptoKey(publicKey), checkEcdhCryptoKey(privateKey, \"deriveBits\");\n const otherInfo = concat(lengthAndInput(encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength)), Z = new Uint8Array(await crypto.subtle.deriveBits({\n name: publicKey.algorithm.name,\n public: publicKey\n }, privateKey, publicKey.algorithm.name === \"X25519\" ? 256 : Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3));\n return concatKdf(Z, keyLength, otherInfo);\n}\nfunction assertEcdhKey(key) {\n assertCryptoKey(key);\n const curve = key.algorithm.namedCurve;\n if (curve !== \"P-256\" && curve !== \"P-384\" && curve !== \"P-521\" && key.algorithm.name !== \"X25519\")\n throw new JOSENotSupported(\"ECDH with the provided key is not allowed or not supported by your javascript runtime\");\n}\nfunction partyInfo(joseHeader, name) {\n const value = joseHeader[name];\n if (value !== void 0) {\n if (typeof value != \"string\")\n throw new JWEInvalid(`JOSE Header \"${name}\" (Agreement Party${name === \"apu\" ? \"U\" : \"V\"}Info) invalid`);\n return decodeBase64url(value, name, JWEInvalid);\n }\n}\nfunction checkPartyInfo(apu, apv) {\n if (!(apu === void 0 || apv === void 0 || apu.byteLength !== apv.byteLength)) {\n for (let i = 0; i < apu.byteLength; i++)\n if (apu[i] !== apv[i])\n return;\n throw new JWEInvalid('JOSE Header \"apu\" and \"apv\" values must be distinct');\n }\n}\nfunction assertEncryptedKey(encryptedKey) {\n if (encryptedKey === void 0)\n throw new JWEInvalid(\"JWE Encrypted Key missing\");\n}\nfunction assertNoEncryptedKey(encryptedKey) {\n if (encryptedKey !== void 0)\n throw new JWEInvalid(\"Encountered unexpected JWE Encrypted Key\");\n}\nfunction validateMaxPBES2Count(value) {\n if (value !== void 0 && value !== 1 / 0 && (!Number.isSafeInteger(value) || value < 1))\n throw new TypeError(\"maxPBES2Count must be a positive safe integer or Infinity\");\n}\nasync function decryptKeyManagement(entry, enc, key, encryptedKey, joseHeader, maxPBES2Count) {\n const { alg } = entry, mode = entry.mode;\n if (mode === \"direct-encryption\")\n return assertNoEncryptedKey(encryptedKey), key;\n const direct = mode === \"direct-key-agreement\";\n switch (direct ? assertNoEncryptedKey(encryptedKey) : assertEncryptedKey(encryptedKey), entry.subtle.name) {\n case \"ECDH\": {\n const { epk } = joseHeader;\n if (!isObject(epk) || [\"d\", \"k\", \"p\", \"q\", \"dp\", \"dq\", \"qi\", \"oth\", \"priv\"].some((parameter) => Object.hasOwn(epk, parameter)))\n throw new JWEInvalid('JOSE Header \"epk\" (Ephemeral Public Key) missing or invalid');\n assertEcdhKey(key);\n const ephemeralPublicKey = await jwkToKey(entry, epk), partyUInfo = partyInfo(joseHeader, \"apu\"), partyVInfo = partyInfo(joseHeader, \"apv\");\n checkPartyInfo(partyUInfo, partyVInfo);\n const sharedSecret = await ecdhesDeriveKey(ephemeralPublicKey, key, direct ? enc.alg : alg, direct ? enc.cekBits : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);\n if (direct)\n return sharedSecret;\n key = sharedSecret;\n break;\n }\n case \"RSA-OAEP\":\n return assertCryptoKey(key), checkRsaKey(alg, key, \"decrypt\"), new Uint8Array(await crypto.subtle.decrypt(\"RSA-OAEP\", key, encryptedKey));\n case \"PBKDF2\": {\n if (typeof joseHeader.p2c != \"number\")\n throw new JWEInvalid('JOSE Header \"p2c\" (PBES2 Count) missing or invalid');\n validateMaxPBES2Count(maxPBES2Count);\n const p2cLimit = maxPBES2Count ?? 1e4;\n if (joseHeader.p2c > p2cLimit)\n throw new JWEInvalid('JOSE Header \"p2c\" (PBES2 Count) out is of acceptable bounds');\n if (typeof joseHeader.p2s != \"string\")\n throw new JWEInvalid('JOSE Header \"p2s\" (PBES2 Salt) missing or invalid');\n const p2s = decodeBase64url(joseHeader.p2s, \"p2s\", JWEInvalid);\n key = await deriveKey(p2s, alg, joseHeader.p2c, key);\n break;\n }\n case \"AES-GCM\": {\n if (typeof joseHeader.iv != \"string\")\n throw new JWEInvalid('JOSE Header \"iv\" (Initialization Vector) missing or invalid');\n if (typeof joseHeader.tag != \"string\")\n throw new JWEInvalid('JOSE Header \"tag\" (Authentication Tag) missing or invalid');\n const iv = decodeBase64url(joseHeader.iv, \"iv\", JWEInvalid), tag = decodeBase64url(joseHeader.tag, \"tag\", JWEInvalid);\n if (iv.byteLength !== 12)\n throw new JWEInvalid(\"Invalid Initialization Vector length\");\n if (tag.byteLength !== 16)\n throw new JWEInvalid(\"Invalid Authentication Tag length\");\n return decrypt(jweEncryption(alg.slice(0, -2)), key, encryptedKey, iv, tag, new Uint8Array());\n }\n }\n return aeskwUnwrap(alg.slice(-6), key, encryptedKey);\n}\nasync function encryptKeyManagement(entry, enc, inputKey, joseHeader, providedCek, providedParameters = {}) {\n const { alg, mode } = entry, transport = isJWECEKTransport(entry);\n if (providedCek !== void 0 && !transport)\n throw new TypeError(`setContentEncryptionKey cannot be called with JWE \"alg\" (Algorithm) Header ${alg}`);\n let key = await prepareKey(mode === \"direct-encryption\" ? enc : entry, inputKey, \"encrypt\");\n if (mode === \"direct-encryption\")\n return [key, void 0, void 0];\n const cek = transport ? providedCek ?? generateCek(enc) : void 0;\n cek && checkCekLength(cek, enc.cekBits);\n let encryptedKey, parameters;\n switch (entry.subtle.name) {\n case \"ECDH\": {\n assertEcdhKey(key);\n const { apu: providedApu, apv: providedApv } = providedParameters;\n providedApu !== void 0 && assertUint8Array(providedApu, '\"apu\"'), providedApv !== void 0 && assertUint8Array(providedApv, '\"apv\"');\n const apu = providedApu ?? partyInfo(joseHeader, \"apu\"), apv = providedApv ?? partyInfo(joseHeader, \"apv\");\n checkPartyInfo(apu, apv);\n let ephemeralKey;\n providedParameters.epk !== void 0 ? ephemeralKey = await prepareKey(entry, providedParameters.epk, \"decrypt\") : ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, !0, [\"deriveBits\"])).privateKey;\n const subtle = crypto.subtle;\n let exportableEpk = ephemeralKey;\n if (!exportableEpk.extractable) {\n if (typeof subtle.getPublicKey != \"function\")\n throw new TypeError('CryptoKey for \"epk\" must be extractable');\n exportableEpk = await subtle.getPublicKey(ephemeralKey, []);\n }\n const { x, y, crv, kty } = await subtle.exportKey(\"jwk\", exportableEpk), direct = mode === \"direct-key-agreement\", sharedSecret = await ecdhesDeriveKey(key, ephemeralKey, direct ? enc.alg : alg, direct ? enc.cekBits : parseInt(alg.slice(-5, -2), 10), apu, apv), epk = { x, crv, kty };\n if (kty === \"EC\" && (epk.y = y), parameters = { epk }, providedApu !== void 0 && (parameters.apu = b64u(providedApu)), providedApv !== void 0 && (parameters.apv = b64u(providedApv)), direct)\n return [sharedSecret, void 0, parameters];\n key = sharedSecret;\n break;\n }\n case \"RSA-OAEP\": {\n assertCryptoKey(key), checkRsaKey(alg, key, \"encrypt\"), encryptedKey = new Uint8Array(await crypto.subtle.encrypt(\"RSA-OAEP\", key, cek));\n break;\n }\n case \"PBKDF2\": {\n const { p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16)) } = providedParameters;\n key = await deriveKey(p2s, alg, p2c, key), parameters = { p2c, p2s: b64u(p2s) };\n break;\n }\n case \"AES-GCM\": {\n const iv = providedParameters.iv === void 0 ? crypto.getRandomValues(new Uint8Array(12)) : providedParameters.iv;\n if (!(iv instanceof Uint8Array))\n throw new TypeError('\"iv\" must be an instance of Uint8Array');\n const wrapped = await encrypt(jweEncryption(alg.slice(0, -2)), cek, key, iv, new Uint8Array());\n encryptedKey = wrapped.ciphertext, parameters = { iv: b64u(wrapped.iv), tag: b64u(wrapped.tag) };\n }\n }\n if (encryptedKey ??= await aeskwWrap(alg.slice(-6), key, cek), !(encryptedKey instanceof Uint8Array) || !encryptedKey.byteLength)\n throw new TypeError(\"JWE key management algorithm did not produce an Encrypted Key\");\n return [cek, encryptedKey, parameters];\n}\nexport {\n decryptKeyManagement,\n encryptKeyManagement,\n validateMaxPBES2Count\n};\n","import { JOSENotSupported, JWEInvalid } from \"../util/errors.js\";\nimport { concat } from \"./buffer_utils.js\";\nfunction validateZip(joseHeader, protectedHeader) {\n if (joseHeader.zip !== void 0 && joseHeader.zip !== \"DEF\")\n throw new JOSENotSupported('Unsupported JWE \"zip\" (Compression Algorithm) Header Parameter value.');\n if (joseHeader.zip !== void 0 && !protectedHeader?.zip)\n throw new JWEInvalid('JWE \"zip\" (Compression Algorithm) Header Parameter MUST be in a protected header.');\n}\nfunction supported(name) {\n if (typeof globalThis[name] > \"u\")\n throw new JOSENotSupported(`JWE \"zip\" (Compression Algorithm) Header Parameter requires the ${name} API.`);\n}\nasync function transform(stream, input, maxLength = 1 / 0) {\n const writer = stream.writable.getWriter();\n writer.write(input).catch(() => {\n }), writer.close().catch(() => {\n });\n const chunks = [];\n let length = 0;\n const reader = stream.readable.getReader();\n for (; ; ) {\n const { value, done } = await reader.read();\n if (done)\n break;\n if (chunks.push(value), length += value.byteLength, maxLength !== 1 / 0 && length > maxLength)\n throw new JWEInvalid(\"Decompressed plaintext exceeded the configured limit\");\n }\n return concat(...chunks);\n}\nasync function compress(input) {\n return supported(\"CompressionStream\"), transform(new CompressionStream(\"deflate-raw\"), input);\n}\nasync function decompress(input, maxLength) {\n return supported(\"DecompressionStream\"), transform(new DecompressionStream(\"deflate-raw\"), input, maxLength);\n}\nexport {\n compress,\n decompress,\n validateZip\n};\n","import { decrypt, generateCek } from \"./content_encryption.js\";\nimport { decodeBase64url, encodeBase64url, parseJoseHeader, isDisjoint, isObject, validateCrit, validateAlgorithms, JWE_RECOGNIZED } from \"./validate.js\";\nimport { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from \"../util/errors.js\";\nimport { decryptKeyManagement } from \"./key_management.js\";\nimport { decoder } from \"./buffer_utils.js\";\nimport { prepareKey } from \"./key.js\";\nimport { JWE, isJWECEKTransport, jweAlgorithm, jweEncryption } from \"./jwe_algorithms.js\";\nimport { decompress, validateZip } from \"./deflate.js\";\nfunction snapshotSharedJWE(jwe) {\n const { aad, ciphertext, iv, protected: encodedProtected, tag, unprotected } = jwe;\n if (iv !== void 0 && (typeof iv != \"string\" || !iv))\n throw new JWEInvalid(\"JWE Initialization Vector incorrect type\");\n if (typeof ciphertext != \"string\")\n throw new JWEInvalid(\"JWE Ciphertext missing or incorrect type\");\n if (tag !== void 0 && (typeof tag != \"string\" || !tag))\n throw new JWEInvalid(\"JWE Authentication Tag incorrect type\");\n if (encodedProtected !== void 0 && typeof encodedProtected != \"string\")\n throw new JWEInvalid(\"JWE Protected Header incorrect type\");\n if (aad !== void 0 && (typeof aad != \"string\" || !aad))\n throw new JWEInvalid(\"JWE AAD incorrect type\");\n if (unprotected !== void 0 && !isObject(unprotected))\n throw new JWEInvalid(\"JWE Shared Unprotected Header incorrect type\");\n return {\n aad,\n ciphertext,\n iv,\n protected: encodedProtected,\n tag,\n unprotected: unprotected === void 0 ? void 0 : { ...unprotected }\n };\n}\nfunction snapshotRecipientJWE(recipient) {\n let header, headerAlg;\n try {\n const { header: inputHeader } = recipient;\n if (isObject(inputHeader)) {\n headerAlg = inputHeader.alg;\n const parameters = Object.keys(inputHeader);\n parameters.includes(\"alg\") || (headerAlg = void 0), header = Object.fromEntries(parameters.map((parameter) => [\n parameter,\n parameter === \"alg\" ? headerAlg : inputHeader[parameter]\n ]));\n } else\n header = inputHeader;\n const { encrypted_key: encryptedKey } = recipient;\n return [{ encrypted_key: encryptedKey, header }, headerAlg];\n } catch (error) {\n return [void 0, headerAlg, error];\n }\n}\nfunction checkRecipient(jwe) {\n const { encrypted_key: encryptedKey, header } = jwe;\n if (encryptedKey !== void 0 && typeof encryptedKey != \"string\")\n throw new JWEInvalid(\"JWE Encrypted Key incorrect type\");\n if (header !== void 0 && !isObject(header))\n throw new JWEInvalid(\"JWE Per-Recipient Unprotected Header incorrect type\");\n if (jwe.protected === void 0 && header === void 0 && jwe.unprotected === void 0)\n throw new JWEInvalid(\"JOSE Header missing\");\n}\nfunction shareJWE(jwe) {\n const { protected: encodedProtected, ciphertext, iv, tag, aad } = jwe;\n let parsedProt;\n return encodedProtected !== void 0 && (parsedProt = parseJoseHeader(encodedProtected, JWEInvalid, \"JWE Protected Header is invalid\")), [\n parsedProt,\n decodeBase64url(ciphertext, \"ciphertext\", JWEInvalid),\n iv !== void 0 ? decodeBase64url(iv, \"iv\", JWEInvalid) : void 0,\n tag !== void 0 ? decodeBase64url(tag, \"tag\", JWEInvalid) : void 0,\n encodeBase64url((encodedProtected ?? \"\") + (aad !== void 0 ? `.${aad}` : \"\"), \"aad\", JWEInvalid)\n ];\n}\nfunction prepareDecrypt(options) {\n return [\n options && validateAlgorithms(\"keyManagementAlgorithms\", options.keyManagementAlgorithms),\n options && validateAlgorithms(\"contentEncryptionAlgorithms\", options.contentEncryptionAlgorithms),\n options?.crit,\n options?.maxPBES2Count,\n options?.maxDecompressedLength\n ];\n}\nasync function decryptJWE(jwe, shared, key, token = shareJWE(jwe)) {\n const [parsedProt, ciphertext, iv, tag, additionalData] = token, { header, unprotected, aad } = jwe;\n let joseHeader;\n if (header !== void 0 || unprotected !== void 0) {\n if (!isDisjoint(parsedProt, header, unprotected))\n throw new JWEInvalid(\"JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint\");\n joseHeader = { ...parsedProt, ...header, ...unprotected };\n } else\n joseHeader = parsedProt ?? {};\n const [keyManagementAlgorithms, contentEncryptionAlgorithms, crit, maxPBES2Count, maxDecompressedLength] = shared, { encrypted_key: encodedKey } = jwe;\n validateCrit(JWEInvalid, JWE_RECOGNIZED, crit, parsedProt, joseHeader), validateZip(joseHeader, parsedProt);\n const { alg, enc } = joseHeader;\n if (typeof alg != \"string\" || !alg)\n throw new JWEInvalid(\"missing JWE Algorithm (alg) in JWE Header\");\n const selected = JWE[alg];\n if (encodedKey === \"\" && (!selected || !isJWECEKTransport(selected)))\n throw new JWEInvalid(\"JWE Encrypted Key incorrect type\");\n const integrated = selected?.mode === \"integrated-encryption\";\n if (!integrated && (typeof enc != \"string\" || !enc))\n throw new JWEInvalid(\"missing JWE Encryption Algorithm (enc) in JWE Header\");\n if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg) || !keyManagementAlgorithms && alg.startsWith(\"PBES2\"))\n throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter value not allowed');\n let encEntry;\n if (integrated) {\n if (enc !== void 0)\n throw new JWEInvalid('JWE \"enc\" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');\n if (iv?.byteLength)\n throw new JWEInvalid(\"JWE Initialization Vector must be empty for integrated encryption\");\n if (tag?.byteLength)\n throw new JWEInvalid(\"JWE Authentication Tag must be empty for integrated encryption\");\n } else {\n if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc))\n throw new JOSEAlgNotAllowed('\"enc\" (Encryption Algorithm) Header Parameter value not allowed');\n encEntry = jweEncryption(enc);\n }\n let encryptedKey;\n if (encodedKey !== void 0)\n try {\n encryptedKey = decodeBase64url(encodedKey, \"encrypted_key\", JWEInvalid);\n } catch (error) {\n if (!selected || !isJWECEKTransport(selected))\n throw error;\n encryptedKey = new Uint8Array();\n }\n let resolvedKey = !1;\n typeof key == \"function\" && (key = await key(parsedProt, jwe), resolvedKey = !0);\n const algEntry = selected ?? jweAlgorithm(alg);\n isJWECEKTransport(algEntry) && encryptedKey === void 0 && (encryptedKey = new Uint8Array());\n const k = await prepareKey(algEntry.mode === \"direct-encryption\" ? encEntry : algEntry, key, \"decrypt\");\n let plaintext;\n if (algEntry.mode === \"integrated-encryption\")\n plaintext = await algEntry.decrypt(k, encryptedKey, ciphertext, additionalData, parsedProt, joseHeader);\n else {\n const encryption = encEntry;\n let cek;\n try {\n cek = await decryptKeyManagement(algEntry, encryption, k, encryptedKey, joseHeader, maxPBES2Count), isJWECEKTransport(algEntry) && cek instanceof Uint8Array && cek.byteLength << 3 !== encryption.cekBits && (cek = generateCek(encryption));\n } catch (err) {\n if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported)\n throw err;\n cek = generateCek(encryption);\n }\n plaintext = await decrypt(encryption, cek, ciphertext, iv, tag, additionalData);\n }\n if (joseHeader.zip === \"DEF\") {\n const decompressionLimit = maxDecompressedLength ?? 25e4;\n if (decompressionLimit === 0)\n throw new JOSENotSupported('JWE \"zip\" (Compression Algorithm) Header Parameter is not supported.');\n if (decompressionLimit !== 1 / 0 && (!Number.isSafeInteger(decompressionLimit) || decompressionLimit < 1))\n throw new TypeError(\"maxDecompressedLength must be 0, a positive safe integer, or Infinity\");\n plaintext = await decompress(plaintext, decompressionLimit).catch((cause) => {\n throw cause instanceof JWEInvalid ? cause : new JWEInvalid(\"Failed to decompress plaintext\", { cause });\n });\n }\n return {\n plaintext,\n ...parsedProt && { protectedHeader: parsedProt },\n ...aad !== void 0 && {\n additionalAuthenticatedData: decodeBase64url(aad, \"aad\", JWEInvalid)\n },\n ...unprotected && { sharedUnprotectedHeader: unprotected },\n ...header && { unprotectedHeader: header },\n ...resolvedKey && { key: k }\n };\n}\nasync function decryptCompact(jwe, shared, key) {\n if (jwe instanceof Uint8Array && (jwe = decoder.decode(jwe)), typeof jwe != \"string\")\n throw new JWEInvalid(\"Compact JWE must be a string or Uint8Array\");\n const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length } = jwe.split(\".\");\n if (length !== 5)\n throw new JWEInvalid(\"Invalid Compact JWE\");\n return decryptJWE({\n ciphertext,\n iv: iv || void 0,\n protected: protectedHeader,\n tag: tag || void 0,\n encrypted_key: encryptedKey || void 0\n }, shared, key);\n}\nexport {\n checkRecipient,\n decryptCompact,\n decryptJWE,\n prepareDecrypt,\n shareJWE,\n snapshotRecipientJWE,\n snapshotSharedJWE\n};\n","import { encode as b64u } from \"../util/base64url.js\";\nimport { encrypt } from \"./content_encryption.js\";\nimport { encryptKeyManagement } from \"./key_management.js\";\nimport { JWEInvalid } from \"../util/errors.js\";\nimport { assertUint8Array, isDisjoint, isObject, serializeJoseHeader, validateCrit, validateCritDuplicates, JWE_RECOGNIZED } from \"./validate.js\";\nimport { encode } from \"./buffer_utils.js\";\nimport { prepareKey } from \"./key.js\";\nimport { JWE, jweAlgorithm, jweEncryption } from \"./jwe_algorithms.js\";\nimport { compress, validateZip } from \"./deflate.js\";\nfunction checkDisjoint(protectedHeader, unprotectedHeader, sharedUnprotectedHeader) {\n if (!isDisjoint(protectedHeader, unprotectedHeader, sharedUnprotectedHeader))\n throw new JWEInvalid(\"JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint\");\n}\nfunction checkEncryptHeaders(input, options, sharedHeadersNormalized = !1) {\n if (!input[1] && !input[2] && !input[3])\n throw new JWEInvalid(\"either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()\");\n options !== void 0 && (input[8] = options?.crit);\n let [, protectedHeader, unprotectedHeader, sharedUnprotectedHeader, aad, cek, iv, keyManagementParameters, crit] = input;\n if (aad !== void 0 && assertUint8Array(aad, \"JWE Additional Authenticated Data\"), cek !== void 0 && assertUint8Array(cek, \"JWE Content Encryption Key\"), iv !== void 0 && assertUint8Array(iv, \"JWE Initialization Vector\"), !sharedHeadersNormalized && protectedHeader !== void 0 && (protectedHeader = serializeJoseHeader(JWEInvalid, protectedHeader)[0], input[1] = protectedHeader), unprotectedHeader !== void 0 && (unprotectedHeader = serializeJoseHeader(JWEInvalid, unprotectedHeader)[0], input[2] = unprotectedHeader), !sharedHeadersNormalized && sharedUnprotectedHeader !== void 0 && (sharedUnprotectedHeader = serializeJoseHeader(JWEInvalid, sharedUnprotectedHeader)[0], input[3] = sharedUnprotectedHeader), keyManagementParameters !== void 0 && !isObject(keyManagementParameters))\n throw new TypeError(\"JWE Key Management Parameters must be an object\");\n checkDisjoint(protectedHeader, unprotectedHeader, sharedUnprotectedHeader);\n const joseHeader = {\n ...protectedHeader,\n ...unprotectedHeader,\n ...sharedUnprotectedHeader\n };\n validateCritDuplicates(JWEInvalid, protectedHeader), validateCrit(JWEInvalid, JWE_RECOGNIZED, crit, protectedHeader, joseHeader), validateZip(joseHeader, protectedHeader);\n const { alg, enc } = joseHeader;\n if (typeof alg != \"string\" || !alg)\n throw new JWEInvalid('JWE \"alg\" (Algorithm) Header Parameter missing or invalid');\n const algEntry = JWE[alg];\n if (algEntry?.mode === \"integrated-encryption\") {\n if (enc !== void 0)\n throw new JWEInvalid('JWE \"enc\" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');\n if (cek !== void 0)\n throw new TypeError(`setContentEncryptionKey cannot be called with JWE \"alg\" (Algorithm) Header ${alg}`);\n if (iv !== void 0)\n throw new TypeError(`setInitializationVector cannot be called with JWE \"alg\" (Algorithm) Header ${alg}`);\n return [joseHeader, void 0, algEntry];\n }\n if (typeof enc != \"string\" || !enc)\n throw new JWEInvalid('JWE \"enc\" (Encryption Algorithm) Header Parameter missing or invalid');\n return [joseHeader, jweEncryption(enc), algEntry];\n}\nasync function encryptJWE(input, checked, key) {\n const [joseHeader, encEntry, selected] = checked, [inputPlaintext, inputProtectedHeader, inputUnprotectedHeader, sharedUnprotectedHeader, aad, providedCek, inputIv, keyManagementParameters, , unprotectedParameters] = input;\n let protectedHeader = inputProtectedHeader, unprotectedHeader = inputUnprotectedHeader;\n const algEntry = selected ?? jweAlgorithm(joseHeader.alg);\n let encryptedKey, parameters, cek;\n algEntry.mode === \"integrated-encryption\" ? cek = await prepareKey(algEntry, key, \"encrypt\") : [cek, encryptedKey, parameters] = await encryptKeyManagement(algEntry, encEntry, key, joseHeader, providedCek, keyManagementParameters), parameters && (unprotectedParameters ? unprotectedHeader = unprotectedHeader ? { ...unprotectedHeader, ...parameters } : parameters : protectedHeader = protectedHeader ? { ...protectedHeader, ...parameters } : parameters, checkDisjoint(protectedHeader, unprotectedHeader, sharedUnprotectedHeader));\n const protectedHeaderS = protectedHeader ? b64u(JSON.stringify(protectedHeader)) : \"\", aadMember = aad?.byteLength ? b64u(aad) : void 0, additionalData = encode(aadMember ? `${protectedHeaderS}.${aadMember}` : protectedHeaderS);\n let plaintext = inputPlaintext;\n joseHeader.zip === \"DEF\" && (plaintext = await compress(plaintext).catch((cause) => {\n throw new JWEInvalid(\"Failed to compress plaintext\", { cause });\n }));\n let ciphertext, tag, iv;\n algEntry.mode === \"integrated-encryption\" ? [encryptedKey, ciphertext] = await algEntry.encrypt(cek, plaintext, additionalData, protectedHeader, joseHeader, keyManagementParameters) : { ciphertext, tag, iv } = await encrypt(encEntry, plaintext, cek, inputIv, additionalData);\n const jwe = {\n ciphertext: b64u(ciphertext)\n };\n return iv && (jwe.iv = b64u(iv)), tag && (jwe.tag = b64u(tag)), encryptedKey?.byteLength && (jwe.encrypted_key = b64u(encryptedKey)), aadMember && (jwe.aad = aadMember), protectedHeader && (jwe.protected = protectedHeaderS), sharedUnprotectedHeader && (jwe.unprotected = sharedUnprotectedHeader), unprotectedHeader && (jwe.header = unprotectedHeader), jwe;\n}\nasync function createJWE(input, key, options) {\n return encryptJWE(input, checkEncryptHeaders(input, options), key);\n}\nfunction compactJWE(jwe) {\n return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join(\".\");\n}\nexport {\n checkDisjoint,\n checkEncryptHeaders,\n compactJWE,\n createJWE,\n encryptJWE\n};\n","import { JOSENotSupported } from \"../util/errors.js\";\nimport { table } from \"./key_descriptor.js\";\nconst sig = [[\"verify\"], [\"sign\"]];\nfunction hmac(bits) {\n const subtle = { name: \"HMAC\", hash: `SHA-${bits}` };\n return { kty: [\"oct\"], secret: !0, subtle, signing: subtle, usages: sig };\n}\nfunction rsa(bits, saltLength) {\n const subtle = { name: saltLength ? \"RSA-PSS\" : \"RSASSA-PKCS1-v1_5\", hash: `SHA-${bits}` };\n return {\n kty: [\"RSA\"],\n subtle,\n signing: saltLength ? { ...subtle, saltLength } : subtle,\n usages: sig,\n minRsaBits: 2048\n };\n}\nfunction ecdsa(crv, bits) {\n return {\n kty: [\"EC\"],\n crv,\n subtle: { name: \"ECDSA\", namedCurve: crv },\n signing: { name: \"ECDSA\", hash: `SHA-${bits}` },\n usages: sig\n };\n}\nfunction eddsa() {\n const subtle = { name: \"Ed25519\" };\n return {\n kty: [\"OKP\"],\n crv: \"Ed25519\",\n subtle,\n signing: subtle,\n usages: sig\n };\n}\nfunction mldsa(bits) {\n const subtle = { name: `ML-DSA-${bits}` };\n return {\n kty: [\"AKP\"],\n subtle,\n signing: subtle,\n usages: sig\n };\n}\nconst JWS = table({\n HS256: hmac(256),\n HS384: hmac(384),\n HS512: hmac(512),\n RS256: rsa(256),\n RS384: rsa(384),\n RS512: rsa(512),\n PS256: rsa(256, 32),\n PS384: rsa(384, 48),\n PS512: rsa(512, 64),\n ES256: ecdsa(\"P-256\", 256),\n ES384: ecdsa(\"P-384\", 384),\n ES512: ecdsa(\"P-521\", 512),\n EdDSA: eddsa(),\n Ed25519: eddsa(),\n \"ML-DSA-44\": mldsa(44),\n \"ML-DSA-65\": mldsa(65),\n \"ML-DSA-87\": mldsa(87)\n});\nfunction jwsAlgorithm(alg) {\n const entry = typeof alg == \"string\" ? JWS[alg] : void 0;\n if (!entry)\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n return entry;\n}\nexport {\n JWS,\n jwsAlgorithm\n};\n","import { jwsAlgorithm } from \"./jws_algorithms.js\";\nimport { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from \"../util/errors.js\";\nimport { concat, decoder, encoder, encode } from \"./buffer_utils.js\";\nimport { decodeBase64url, encodeBase64url, parseJoseHeader, isDisjoint, isObject, validateB64, validateCrit, validateAlgorithms, JWS_RECOGNIZED } from \"./validate.js\";\nimport { prepareKey, rawKey, checkModulusLength } from \"./key.js\";\nfunction snapshotJws(jws, sharedPayload) {\n const encodedProtected = jws.protected, inputHeader = jws.header, header = isObject(inputHeader) ? { ...inputHeader } : inputHeader;\n let payload = sharedPayload ? sharedPayload[0] : jws.payload;\n !sharedPayload && payload instanceof Uint8Array && (payload = new Uint8Array(payload));\n const signature = jws.signature, snapshot = { payload, signature };\n if (encodedProtected !== void 0 && (snapshot.protected = encodedProtected), inputHeader !== void 0 && (snapshot.header = header), encodedProtected === void 0 && header === void 0)\n throw new JWSInvalid('Flattened JWS must have either of the \"protected\" or \"header\" members');\n if (encodedProtected !== void 0 && typeof encodedProtected != \"string\")\n throw new JWSInvalid(\"JWS Protected Header incorrect type\");\n if (payload === void 0)\n throw new JWSInvalid(\"JWS Payload missing\");\n if (typeof signature != \"string\")\n throw new JWSInvalid(\"JWS Signature missing or incorrect type\");\n if (header !== void 0 && !isObject(header))\n throw new JWSInvalid(\"JWS Unprotected Header incorrect type\");\n return snapshot;\n}\nfunction prepareVerify(options) {\n return [options && validateAlgorithms(\"algorithms\", options.algorithms), options?.crit];\n}\nfunction parseProtectedHeader(encodedProtected) {\n return encodedProtected === void 0 ? {} : parseJoseHeader(encodedProtected, JWSInvalid, \"JWS Protected Header is invalid\");\n}\nfunction encodeJsonUnencodedPayload(payload) {\n const invalid = /[\\p{Cs}\\p{Cn}]/u.exec(payload)?.[0];\n if (invalid !== void 0)\n throw new JWSInvalid(/\\p{Cs}/u.test(invalid) ? \"JWS Payload must be a well-formed Unicode string\" : \"JWS Payload must not contain unassigned Unicode code points\");\n return encoder.encode(payload);\n}\nfunction encodeCompactUnencodedPayload(payload) {\n try {\n return encode(payload);\n } catch {\n throw new JWSInvalid(\"JWS Compact Serialization payload must use only ASCII characters\");\n }\n}\nasync function verifySignature(jws, shared, key, encodeUnencodedPayload, parsedProtected) {\n const { protected: encodedProtected, header, payload: inputPayload } = jws, parsedProt = parsedProtected ?? parseProtectedHeader(encodedProtected);\n if (!isDisjoint(parsedProt, header))\n throw new JWSInvalid(\"JWS Protected and JWS Unprotected Header Parameter names must be disjoint\");\n const joseHeader = { ...parsedProt, ...header }, b64 = validateB64(parsedProt, validateCrit(JWSInvalid, JWS_RECOGNIZED, shared[1], parsedProt, joseHeader)), { alg } = joseHeader;\n if (typeof alg != \"string\" || !alg)\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n if (shared[0] && !shared[0].has(alg))\n throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter value not allowed');\n if (b64) {\n if (typeof inputPayload != \"string\")\n throw new JWSInvalid(\"JWS Payload must be a string\");\n } else if (typeof inputPayload != \"string\" && !(inputPayload instanceof Uint8Array))\n throw new JWSInvalid(\"JWS Payload must be a string or an Uint8Array instance\");\n const signingPayload = b64 || typeof inputPayload != \"string\" ? inputPayload : encodeUnencodedPayload(inputPayload);\n let resolvedKey = !1;\n typeof key == \"function\" && (key = await key(parsedProt, jws), resolvedKey = !0);\n const entry = jwsAlgorithm(alg), data = concat(encodedProtected !== void 0 ? encode(encodedProtected) : new Uint8Array(), encode(\".\"), typeof signingPayload == \"string\" ? shared[2] ??= encodeBase64url(signingPayload, \"payload\", JWSInvalid) : signingPayload), signature = decodeBase64url(jws.signature, \"signature\", JWSInvalid), k = await prepareKey(entry, key, \"verify\"), cryptoKey = await rawKey(k, entry.subtle, \"verify\");\n entry.minRsaBits && checkModulusLength(entry.alg, cryptoKey);\n let verified = !1;\n try {\n verified = await crypto.subtle.verify(entry.signing, cryptoKey, signature, data);\n } catch {\n }\n if (!verified)\n throw new JWSSignatureVerificationFailed();\n const result = { payload: typeof signingPayload == \"string\" ? decodeBase64url(signingPayload, \"payload\", JWSInvalid) : signingPayload };\n return encodedProtected !== void 0 && (result.protectedHeader = parsedProt), header !== void 0 && (result.unprotectedHeader = header), resolvedKey ? [{ ...result, key: k }, b64] : [result, b64];\n}\nasync function verifyCompact(jws, shared, key) {\n if (jws instanceof Uint8Array && (jws = decoder.decode(jws)), typeof jws != \"string\")\n throw new JWSInvalid(\"Compact JWS must be a string or Uint8Array\");\n const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(\".\");\n if (length !== 3)\n throw new JWSInvalid(\"Invalid Compact JWS\");\n return verifySignature({ payload, protected: protectedHeader, signature }, shared, key, encodeCompactUnencodedPayload);\n}\nexport {\n encodeJsonUnencodedPayload,\n parseProtectedHeader,\n prepareVerify,\n snapshotJws,\n verifyCompact,\n verifySignature\n};\n","import { prepareVerify, verifyCompact } from \"../../lib/jws_verify.js\";\nasync function compactVerify(jws, key, options) {\n const [result] = await verifyCompact(jws, prepareVerify(options), key);\n return result;\n}\nexport {\n compactVerify\n};\n","import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from \"../util/errors.js\";\nimport { encoder, strictDecoder } from \"./buffer_utils.js\";\nimport { isObject } from \"./validate.js\";\nconst epoch = (date) => Math.floor(date.getTime() / 1e3), multipliers = {\n s: 1,\n m: 60,\n h: 3600,\n d: 86400,\n w: 604800,\n y: 31557600\n}, REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i, checkFailed = \"check_failed\";\nfunction invalidDuration() {\n throw new TypeError(\"Invalid time period format\");\n}\nfunction secs(str) {\n typeof str != \"string\" && invalidDuration();\n const matched = REGEX.exec(str);\n (!matched || matched[4] && matched[1]) && invalidDuration();\n const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]);\n return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === \"-\" || matched[4] === \"ago\" ? -numericDate2 : numericDate2;\n}\nfunction validateInput(label, input) {\n if (!Number.isFinite(input))\n throw new TypeError(`Invalid ${label} input`);\n return input;\n}\nfunction validateStringClaim(claim, value) {\n if (typeof value != \"string\")\n throw new TypeError(`\"${claim}\" claim must be a string`);\n}\nfunction validateAudienceClaim(value) {\n if (typeof value != \"string\" && (!Array.isArray(value) || Array.from(value).some((member) => typeof member != \"string\")))\n throw new TypeError('\"aud\" claim must be a string or an array of strings');\n}\nfunction numericDate(value, label) {\n return typeof value == \"number\" ? validateInput(label, value) : value instanceof Date ? validateInput(label, epoch(value)) : epoch(/* @__PURE__ */ new Date()) + secs(value);\n}\nconst normalizeTyp = (value) => {\n const normalized = value.toLowerCase();\n return value.includes(\"/\") ? normalized : `application/${normalized}`;\n}, checkAudiencePresence = (audPayload, audOption) => typeof audPayload == \"string\" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : !1;\nfunction validateNumericDate(payload, claim, required = !1) {\n const value = payload[claim];\n if (!(value === void 0 && !required)) {\n if (typeof value != \"number\")\n throw new JWTClaimValidationFailed(`\"${claim}\" claim must be a number`, payload, claim, \"invalid\");\n return value;\n }\n}\nfunction unexpectedClaim(payload, claim) {\n throw new JWTClaimValidationFailed(`unexpected \"${claim}\" claim value`, payload, claim, checkFailed);\n}\nfunction validateClaimsSet(protectedHeader, encodedPayload, options = {}) {\n let payload;\n try {\n payload = JSON.parse(strictDecoder.decode(encodedPayload));\n } catch {\n }\n if (!isObject(payload))\n throw new JWTInvalid(\"JWT Claims Set must be a top-level JSON object\");\n const { typ } = options;\n if (typ !== void 0 && (typeof protectedHeader.typ != \"string\" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ)))\n throw new JWTClaimValidationFailed('unexpected \"typ\" JWT header value', payload, \"typ\", checkFailed);\n const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims];\n maxTokenAge !== void 0 && presenceCheck.push(\"iat\"), audience !== void 0 && presenceCheck.push(\"aud\"), subject !== void 0 && presenceCheck.push(\"sub\"), issuer !== void 0 && presenceCheck.push(\"iss\");\n for (const claim of new Set(presenceCheck.reverse()))\n if (!Object.hasOwn(payload, claim))\n throw new JWTClaimValidationFailed(`missing required \"${claim}\" claim`, payload, claim, \"missing\");\n issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, \"iss\"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, \"sub\"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == \"string\" ? [audience] : audience) && unexpectedClaim(payload, \"aud\");\n const { clockTolerance } = options;\n let tolerance = 0;\n if (typeof clockTolerance == \"string\")\n tolerance = secs(clockTolerance);\n else if (clockTolerance !== void 0) {\n if (typeof clockTolerance != \"number\")\n throw new TypeError(\"Invalid clockTolerance option type\");\n tolerance = clockTolerance;\n }\n validateInput(\"clockTolerance option\", tolerance);\n const { currentDate } = options, now = validateInput(\"currentDate option\", epoch(currentDate === void 0 ? /* @__PURE__ */ new Date() : currentDate)), iat = validateNumericDate(payload, \"iat\", maxTokenAge !== void 0), nbf = validateNumericDate(payload, \"nbf\");\n if (nbf !== void 0 && nbf > now + tolerance)\n throw new JWTClaimValidationFailed('\"nbf\" claim timestamp check failed', payload, \"nbf\", checkFailed);\n const exp = validateNumericDate(payload, \"exp\");\n if (exp !== void 0 && exp <= now - tolerance)\n throw new JWTExpired('\"exp\" claim timestamp check failed', payload, \"exp\", checkFailed);\n if (maxTokenAge !== void 0) {\n const age = now - iat, max = validateInput(\"maxTokenAge option\", typeof maxTokenAge == \"number\" ? maxTokenAge : secs(maxTokenAge));\n if (age - tolerance > max)\n throw new JWTExpired('\"iat\" claim timestamp check failed (too far in the past)', payload, \"iat\", checkFailed);\n if (age < -tolerance)\n throw new JWTClaimValidationFailed('\"iat\" claim timestamp check failed (it should be in the past)', payload, \"iat\", checkFailed);\n }\n return payload;\n}\nlet producerPayloads;\nfunction producerPayload(producer) {\n return producerPayloads.get(producer);\n}\nfunction jwtData(producer) {\n const payload = producerPayload(producer);\n for (const claim of [\"iat\", \"nbf\", \"exp\"]) {\n const value = payload[claim];\n if (typeof value == \"number\" && !Number.isFinite(value))\n throw new TypeError(`\"${claim}\" claim must be a finite number`);\n }\n return encoder.encode(JSON.stringify(payload));\n}\nfunction jwtClaim(producer, claim) {\n return producerPayload(producer)[claim];\n}\nclass JWTClaimsBuilder {\n constructor(payload = {}) {\n if (!isObject(payload))\n throw new TypeError(\"JWT Claims Set MUST be an object\");\n (producerPayloads ||= /* @__PURE__ */ new WeakMap()).set(this, structuredClone(payload));\n }\n setIssuer(value) {\n return validateStringClaim(\"iss\", value), producerPayload(this).iss = value, this;\n }\n setSubject(value) {\n return validateStringClaim(\"sub\", value), producerPayload(this).sub = value, this;\n }\n setAudience(value) {\n return validateAudienceClaim(value), producerPayload(this).aud = value, this;\n }\n setJti(value) {\n return validateStringClaim(\"jti\", value), producerPayload(this).jti = value, this;\n }\n setNotBefore(value) {\n return producerPayload(this).nbf = numericDate(value, \"setNotBefore\"), this;\n }\n setExpirationTime(value) {\n return producerPayload(this).exp = numericDate(value, \"setExpirationTime\"), this;\n }\n setIssuedAt(value) {\n const payload = producerPayload(this);\n return value === void 0 ? payload.iat = epoch(/* @__PURE__ */ new Date()) : typeof value == \"string\" ? payload.iat = validateInput(\"setIssuedAt\", epoch(/* @__PURE__ */ new Date()) + secs(value)) : payload.iat = numericDate(value, \"setIssuedAt\"), this;\n }\n}\nexport {\n JWTClaimsBuilder,\n jwtClaim,\n jwtData,\n secs,\n validateClaimsSet\n};\n","import { prepareVerify, verifyCompact } from \"../lib/jws_verify.js\";\nimport { validateClaimsSet } from \"../lib/jwt_claims_set.js\";\nimport { JWTInvalid } from \"../util/errors.js\";\nasync function jwtVerify(jwt, key, options) {\n const [verified, b64] = await verifyCompact(jwt, prepareVerify(options), key);\n if (!b64)\n throw new JWTInvalid(\"JWTs MUST NOT use unencoded payload\");\n const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);\n return { ...verified, payload };\n}\nexport {\n jwtVerify\n};\n","import { prepareDecrypt, decryptCompact } from \"../lib/jwe_decrypt.js\";\nimport { validateClaimsSet } from \"../lib/jwt_claims_set.js\";\nimport { JWTClaimValidationFailed } from \"../util/errors.js\";\nasync function jwtDecrypt(jwt, key, options) {\n const { plaintext, ...result } = await decryptCompact(jwt, prepareDecrypt(options), key), { protectedHeader } = result, payload = validateClaimsSet(protectedHeader, plaintext, options);\n for (const claim of [\"iss\", \"sub\", \"aud\"])\n if (protectedHeader[claim] !== void 0 && (claim === \"aud\" ? JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud) : protectedHeader[claim] !== payload[claim]))\n throw new JWTClaimValidationFailed(`replicated \"${claim}\" claim header parameter mismatch`, payload, claim, \"mismatch\");\n return { payload, ...result };\n}\nexport {\n jwtDecrypt\n};\n","import { encode as b64u } from \"../util/base64url.js\";\nimport { jwsAlgorithm } from \"./jws_algorithms.js\";\nimport { isDisjoint, serializeJoseHeader, validateB64, validateCrit, validateCritDuplicates, JWS_RECOGNIZED } from \"./validate.js\";\nimport { JWSInvalid } from \"../util/errors.js\";\nimport { concat, encode, encoder } from \"./buffer_utils.js\";\nimport { prepareKey, rawKey, checkModulusLength } from \"./key.js\";\nasync function createSignature(input, key, rejectUnencoded) {\n let [payload, protectedHeader, unprotectedHeader, crit] = input, protectedHeaderString = \"\";\n if (protectedHeader !== void 0) {\n const normalized = serializeJoseHeader(JWSInvalid, protectedHeader);\n protectedHeader = normalized[0], protectedHeaderString = b64u(normalized[1]);\n }\n if (unprotectedHeader !== void 0 && (unprotectedHeader = serializeJoseHeader(JWSInvalid, unprotectedHeader)[0]), !protectedHeader && !unprotectedHeader)\n throw new JWSInvalid(\"either setProtectedHeader or setUnprotectedHeader must be called before #sign()\");\n if (!isDisjoint(protectedHeader, unprotectedHeader))\n throw new JWSInvalid(\"JWS Protected and JWS Unprotected Header Parameter names must be disjoint\");\n const joseHeader = { ...protectedHeader, ...unprotectedHeader };\n validateCritDuplicates(JWSInvalid, protectedHeader);\n const b64 = validateB64(protectedHeader, validateCrit(JWSInvalid, JWS_RECOGNIZED, crit, protectedHeader, joseHeader));\n b64 || rejectUnencoded?.();\n const { alg } = joseHeader;\n if (typeof alg != \"string\" || !alg)\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n const entry = jwsAlgorithm(alg);\n let payloadS = \"\", payloadB = payload, data;\n if (b64) {\n const encoded = input[4];\n encoded ? (payloadS = encoded[0] ??= b64u(payload), payloadB = encoded[1] ??= encode(payloadS)) : (payloadS = b64u(payload), data = encoder.encode(`${protectedHeaderString}.${payloadS}`));\n }\n data ??= concat(encode(protectedHeaderString), encode(\".\"), payloadB);\n const k = await rawKey(await prepareKey(entry, key, \"sign\"), entry.subtle, \"sign\");\n entry.minRsaBits && checkModulusLength(entry.alg, k);\n const jws = {\n signature: b64u(new Uint8Array(await crypto.subtle.sign(entry.signing, k, data))),\n payload: payloadS\n };\n return protectedHeader && (jws.protected = protectedHeaderString), unprotectedHeader && (jws.header = unprotectedHeader), [jws, b64];\n}\nasync function createCompactSignature(payload, protectedHeader, crit, key, rejectUnencoded) {\n const [jws] = await createSignature([payload, protectedHeader, void 0, crit], key, rejectUnencoded);\n return `${jws.protected}.${jws.payload}.${jws.signature}`;\n}\nexport {\n createCompactSignature,\n createSignature\n};\n","import { createCompactSignature } from \"../lib/jws_sign.js\";\nimport { JWTInvalid } from \"../util/errors.js\";\nimport { JWTClaimsBuilder, jwtData } from \"../lib/jwt_claims_set.js\";\nimport { assertNotSet } from \"../lib/validate.js\";\nconst SignJWT_base = JWTClaimsBuilder;\nclass SignJWT extends SignJWT_base {\n #protectedHeader;\n setProtectedHeader(protectedHeader) {\n return assertNotSet(this.#protectedHeader, \"setProtectedHeader\"), this.#protectedHeader = protectedHeader, this;\n }\n async sign(key, options) {\n return createCompactSignature(jwtData(this), this.#protectedHeader, options?.crit, key, () => {\n throw new JWTInvalid(\"JWTs MUST NOT use unencoded payload\");\n });\n }\n}\nexport {\n SignJWT\n};\n","import { compactJWE, createJWE } from \"../lib/jwe_encrypt.js\";\nimport { JWTClaimsBuilder, jwtClaim, jwtData } from \"../lib/jwt_claims_set.js\";\nimport { assertNotSet } from \"../lib/validate.js\";\nconst EncryptJWT_base = JWTClaimsBuilder;\nclass EncryptJWT extends EncryptJWT_base {\n #input = [void 0];\n #replicateIssuerAsHeader;\n #replicateSubjectAsHeader;\n #replicateAudienceAsHeader;\n setProtectedHeader(protectedHeader) {\n return assertNotSet(this.#input[1], \"setProtectedHeader\"), this.#input[1] = protectedHeader, this;\n }\n setKeyManagementParameters(parameters) {\n return assertNotSet(this.#input[7], \"setKeyManagementParameters\"), this.#input[7] = parameters, this;\n }\n setContentEncryptionKey(cek) {\n return assertNotSet(this.#input[5], \"setContentEncryptionKey\"), this.#input[5] = cek, this;\n }\n setInitializationVector(iv) {\n return assertNotSet(this.#input[6], \"setInitializationVector\"), this.#input[6] = iv, this;\n }\n replicateIssuerAsHeader() {\n return this.#replicateIssuerAsHeader = !0, this;\n }\n replicateSubjectAsHeader() {\n return this.#replicateSubjectAsHeader = !0, this;\n }\n replicateAudienceAsHeader() {\n return this.#replicateAudienceAsHeader = !0, this;\n }\n async encrypt(key, options) {\n const plaintext = jwtData(this);\n this.#input[1] && (this.#replicateIssuerAsHeader || this.#replicateSubjectAsHeader || this.#replicateAudienceAsHeader) && (this.#input[1] = {\n ...this.#input[1],\n iss: this.#replicateIssuerAsHeader ? jwtClaim(this, \"iss\") : void 0,\n sub: this.#replicateSubjectAsHeader ? jwtClaim(this, \"sub\") : void 0,\n aud: this.#replicateAudienceAsHeader ? jwtClaim(this, \"aud\") : void 0\n });\n const input = [...this.#input];\n return input[0] = plaintext, compactJWE(await createJWE(input, key, options));\n }\n}\nexport {\n EncryptJWT\n};\n","import { JOSENotSupported } from \"../util/errors.js\";\nimport { JWS } from \"./jws_algorithms.js\";\nimport { JWE } from \"./jwe_algorithms.js\";\nconst algArgument = '\"alg\" (Algorithm)';\nfunction unsupportedAlg(source = 'JWK \"alg\" (Algorithm) Parameter') {\n throw new JOSENotSupported(`Invalid or unsupported ${source} value`);\n}\nfunction keyAlgorithm(alg, source) {\n return (typeof alg == \"string\" ? JWS[alg] ?? JWE[alg] : void 0) ?? unsupportedAlg(source);\n}\nexport {\n algArgument,\n keyAlgorithm,\n unsupportedAlg\n};\n","import { invalidKeyInput, isCryptoKey, isKeyObject, validateExtractableOption } from \"./key.js\";\nimport { encodeBase64, decodeBase64 } from \"./buffer_utils.js\";\nimport { JOSENotSupported } from \"../util/errors.js\";\nimport { keyAlgorithm, unsupportedAlg, algArgument } from \"./key_algorithm.js\";\nconst formatPEM = (b64, descriptor) => {\n const newlined = (b64.match(/.{1,64}/g) || []).join(`\n`);\n return `-----BEGIN ${descriptor}-----\n${newlined}\n-----END ${descriptor}-----`;\n}, genericExport = async (keyType, keyFormat, key) => {\n if (isKeyObject(key)) {\n if (key.type !== keyType)\n throw new TypeError(`key is not a ${keyType} key`);\n return key.export({ format: \"pem\", type: keyFormat });\n }\n if (!isCryptoKey(key))\n throw new TypeError(invalidKeyInput(key, \"CryptoKey\", \"KeyObject\"));\n if (!key.extractable)\n throw new TypeError(\"CryptoKey is not extractable\");\n if (key.type !== keyType)\n throw new TypeError(`key is not a ${keyType} key`);\n return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);\n}, toSPKI = (key) => genericExport(\"public\", \"spki\", key), toPKCS8 = (key) => genericExport(\"private\", \"pkcs8\", key), bytesEqual = (a, b) => {\n if (a.byteLength !== b.length)\n return !1;\n for (let i = 0; i < a.byteLength; i++)\n if (a[i] !== b[i])\n return !1;\n return !0;\n}, createASN1State = (data) => ({ data, pos: 0 }), readByte = (state) => {\n const byte = state.data[state.pos++];\n if (byte === void 0)\n throw new Error(\"Unexpected end of ASN.1 input\");\n return byte;\n}, parseLength = (state) => {\n const first = readByte(state);\n if (first & 128) {\n const lengthOfLen = first & 127;\n let length = 0;\n for (let i = 0; i < lengthOfLen; i++)\n length = length << 8 | readByte(state);\n return length;\n }\n return first;\n}, skipElement = (state, count = 1) => {\n for (; count-- > 0; ) {\n state.pos++;\n const length = parseLength(state);\n state.pos += length;\n }\n}, expectTag = (state, expectedTag, errorMessage) => {\n if (readByte(state) !== expectedTag)\n throw new Error(errorMessage);\n}, getSubarray = (state, length) => {\n if (length < 0 || state.pos + length > state.data.length)\n throw new Error(\"Unexpected end of ASN.1 input\");\n const result = state.data.subarray(state.pos, state.pos + length);\n return state.pos += length, result;\n}, parseAlgorithmOID = (state) => {\n expectTag(state, 6, \"Expected algorithm OID\");\n const oidLen = parseLength(state);\n return getSubarray(state, oidLen);\n};\nfunction parseKeyHeader(state, keyFormat) {\n if (expectTag(state, 48, `Invalid ${keyFormat === \"spki\" ? \"SPKI\" : \"PKCS#8\"} structure`), parseLength(state), keyFormat === \"pkcs8\") {\n expectTag(state, 2, \"Expected version field\");\n const length = parseLength(state);\n state.pos += length;\n }\n expectTag(state, 48, \"Expected algorithm identifier\"), parseLength(state);\n}\nconst parseECAlgorithmIdentifier = (state) => {\n const algOid = parseAlgorithmOID(state);\n if (bytesEqual(algOid, [43, 101, 110]))\n return \"X25519\";\n if (!bytesEqual(algOid, [42, 134, 72, 206, 61, 2, 1]))\n throw new Error(\"Unsupported key algorithm\");\n expectTag(state, 6, \"Expected curve OID\");\n const curveOidLen = parseLength(state), curveOid = getSubarray(state, curveOidLen);\n if (bytesEqual(curveOid, [42, 134, 72, 206, 61, 3, 1, 7]))\n return \"P-256\";\n if (bytesEqual(curveOid, [43, 129, 4, 0, 34]))\n return \"P-384\";\n if (bytesEqual(curveOid, [43, 129, 4, 0, 35]))\n return \"P-521\";\n throw new Error(\"Unsupported named curve\");\n}, genericImport = async (keyFormat, keyData, alg, options) => {\n const extractable = validateExtractableOption(options?.extractable), entry = keyAlgorithm(alg, algArgument);\n entry.secret && unsupportedAlg(algArgument);\n const isPublic = keyFormat === \"spki\";\n let algorithm;\n if (entry.resolve)\n try {\n const state = createASN1State(keyData);\n parseKeyHeader(state, keyFormat), algorithm = entry.resolve({ crv: parseECAlgorithmIdentifier(state) });\n } catch {\n throw new JOSENotSupported(\"Invalid or unsupported key format\");\n }\n else\n algorithm = entry.subtle;\n return crypto.subtle.importKey(keyFormat, keyData, algorithm, extractable ?? isPublic, entry.usages[isPublic ? 0 : 1]);\n}, processPEMData = (pem, pattern) => decodeBase64(pem.replace(pattern, \"\")), fromPKCS8 = (pem, alg, options) => {\n const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\\s)/g);\n return genericImport(\"pkcs8\", keyData, alg, options);\n}, fromSPKI = (pem, alg, options) => {\n const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PUBLIC KEY-----|\\s)/g);\n return genericImport(\"spki\", keyData, alg, options);\n};\nfunction spkiFromX509(buf) {\n const state = createASN1State(buf);\n expectTag(state, 48, \"Invalid certificate structure\");\n const certificateLength = parseLength(state);\n if (certificateLength < 0 || state.pos + certificateLength > state.data.length)\n throw new Error(\"Unexpected end of ASN.1 input\");\n expectTag(state, 48, \"Invalid tbsCertificate structure\"), parseLength(state), buf[state.pos] === 160 ? skipElement(state, 6) : skipElement(state, 5);\n const spkiStart = state.pos;\n expectTag(state, 48, \"Invalid SPKI structure\");\n const spkiContentLen = parseLength(state);\n return buf.subarray(spkiStart, spkiStart + spkiContentLen + (state.pos - spkiStart));\n}\nconst fromX509 = (pem, alg, options) => {\n let spki;\n try {\n const certificate = processPEMData(pem, /(?:-----(?:BEGIN|END) CERTIFICATE-----|\\s)/g);\n spki = spkiFromX509(certificate);\n } catch (cause) {\n throw new TypeError(\"Failed to parse the X.509 certificate\", { cause });\n }\n return genericImport(\"spki\", spki, alg, options);\n};\nexport {\n fromPKCS8,\n fromSPKI,\n fromX509,\n toPKCS8,\n toSPKI\n};\n","import { toSPKI as exportPublic, toPKCS8 as exportPrivate } from \"../lib/asn1.js\";\nimport { invalidKeyInput, isCryptoKey, isKeyObject } from \"../lib/key.js\";\nimport { encode as b64u } from \"../util/base64url.js\";\nfunction exportSPKI(key) {\n return exportPublic(key);\n}\nfunction exportPKCS8(key) {\n return exportPrivate(key);\n}\nasync function exportJWK(key) {\n if (isKeyObject(key))\n if (key.type === \"secret\")\n key = key.export();\n else\n return key.export({ format: \"jwk\" });\n if (key instanceof Uint8Array)\n return {\n kty: \"oct\",\n k: b64u(key)\n };\n if (!isCryptoKey(key))\n throw new TypeError(invalidKeyInput(key, \"CryptoKey\", \"KeyObject\", \"Uint8Array\"));\n if (!key.extractable)\n throw new TypeError(\"non-extractable CryptoKey cannot be exported as a JWK\");\n const jwk = await crypto.subtle.exportKey(\"jwk\", key);\n delete jwk.ext, delete jwk.key_ops, delete jwk.use, jwk.kty !== \"AKP\" && delete jwk.alg;\n for (const parameter of Object.keys(jwk))\n jwk[parameter] === void 0 && delete jwk[parameter];\n return jwk;\n}\nexport {\n exportJWK,\n exportPKCS8,\n exportSPKI\n};\n","import { digest, encode } from \"../lib/buffer_utils.js\";\nimport { encode as b64u } from \"../util/base64url.js\";\nimport { JOSENotSupported, JWKInvalid } from \"../util/errors.js\";\nimport { isKeyLike, invalidKeyInput, snapshotJwk } from \"../lib/key.js\";\nimport { isObject } from \"../lib/validate.js\";\nimport { exportJWK } from \"../key/export.js\";\nconst check = (value, description) => {\n if (typeof value != \"string\" || !value)\n throw new JWKInvalid(`${description} missing or invalid`);\n};\nasync function calculateJwkThumbprint(key, digestAlgorithm) {\n let jwk;\n if (isObject(key)) {\n if (jwk = snapshotJwk(key), typeof jwk.kty != \"string\")\n throw new TypeError(invalidKeyInput(key, \"CryptoKey\", \"KeyObject\", \"JSON Web Key\"));\n } else if (isKeyLike(key))\n jwk = snapshotJwk(await exportJWK(key));\n else\n throw new TypeError(invalidKeyInput(key, \"CryptoKey\", \"KeyObject\", \"JSON Web Key\"));\n if (digestAlgorithm ??= \"sha256\", digestAlgorithm !== \"sha256\" && digestAlgorithm !== \"sha384\" && digestAlgorithm !== \"sha512\")\n throw new TypeError('digestAlgorithm must one of \"sha256\", \"sha384\", or \"sha512\"');\n let components;\n switch (jwk.kty) {\n case \"AKP\":\n check(jwk.alg, '\"alg\" (Algorithm) Parameter'), check(jwk.pub, '\"pub\" (Public key) Parameter'), components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub };\n break;\n case \"EC\":\n check(jwk.crv, '\"crv\" (Curve) Parameter'), check(jwk.x, '\"x\" (X Coordinate) Parameter'), check(jwk.y, '\"y\" (Y Coordinate) Parameter'), components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };\n break;\n case \"OKP\":\n check(jwk.crv, '\"crv\" (Subtype of Key Pair) Parameter'), check(jwk.x, '\"x\" (Public Key) Parameter'), components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };\n break;\n case \"RSA\":\n check(jwk.e, '\"e\" (Exponent) Parameter'), check(jwk.n, '\"n\" (Modulus) Parameter'), components = { e: jwk.e, kty: jwk.kty, n: jwk.n };\n break;\n case \"oct\":\n if (typeof jwk.k != \"string\")\n throw new JWKInvalid('\"k\" (Key Value) Parameter missing or invalid');\n components = { k: jwk.k, kty: jwk.kty };\n break;\n default:\n throw new JOSENotSupported('\"kty\" (Key Type) Parameter missing or unsupported');\n }\n const data = encode(JSON.stringify(components));\n return b64u(await digest(digestAlgorithm, data));\n}\nasync function calculateJwkThumbprintUri(key, digestAlgorithm) {\n digestAlgorithm ??= \"sha256\";\n const thumbprint = await calculateJwkThumbprint(key, digestAlgorithm);\n return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;\n}\nexport {\n calculateJwkThumbprint,\n calculateJwkThumbprintUri\n};\n","import { jwkToKey, snapshotJwk } from \"../lib/key.js\";\nimport { JWS } from \"../lib/jws_algorithms.js\";\nimport { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys } from \"../util/errors.js\";\nimport { isJwkSet } from \"../lib/validate.js\";\nfunction isUsableJWK(jwk, entry, alg, kid) {\n const { kty, key_ops: keyOps, ext, kid: jwkKid, alg: jwkAlg, use, crv } = jwk;\n return (ext === void 0 || typeof ext == \"boolean\") && (keyOps === void 0 || Array.isArray(keyOps) && keyOps.every((operation, index) => typeof operation == \"string\" && keyOps.indexOf(operation) === index) && keyOps.includes(\"verify\")) && entry.kty.includes(kty) && (kid === void 0 || typeof kid == \"string\" && kid === jwkKid) && (jwkAlg === void 0 ? kty !== \"AKP\" : alg === jwkAlg) && (use === void 0 || use === \"sig\") && (!entry.crv || crv === entry.crv);\n}\nasync function importWithAlgCache(cache, jwk, entry) {\n const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk), { alg } = entry;\n if (cached[alg] === void 0) {\n const pending = jwkToKey(entry, jwk, !0).then((key) => {\n if (key.type !== \"public\")\n throw new JWKSInvalid(\"JSON Web Key Set members must be public keys\");\n return cached[alg] = key, key;\n }).catch((error) => {\n throw cached[alg] === pending && delete cached[alg], error;\n });\n cached[alg] = pending;\n }\n return cached[alg];\n}\nfunction createLocalJWKSet(jwks) {\n let snapshot;\n try {\n snapshot = structuredClone(jwks);\n } catch {\n }\n if (!isJwkSet(snapshot))\n throw new JWKSInvalid(\"JSON Web Key Set malformed\");\n const metadata = snapshot.keys.map((jwk) => {\n const normalized = snapshotJwk(jwk);\n return Array.isArray(normalized.key_ops) && (normalized.key_ops = [...normalized.key_ops]), normalized;\n }), cached = /* @__PURE__ */ new WeakMap();\n return Object.defineProperty(async (protectedHeader, token) => {\n const { alg, kid } = { ...protectedHeader, ...token?.header }, entry = typeof alg == \"string\" ? JWS[alg] : void 0;\n if (!entry || entry.secret)\n throw new JOSENotSupported('Unsupported \"alg\" value for a JSON Web Key Set');\n const candidates = snapshot.keys.filter((_, index) => isUsableJWK(metadata[index], entry, alg, kid)), { 0: jwk, length } = candidates;\n if (!length)\n throw new JWKSNoMatchingKey();\n if (length !== 1) {\n const error = new JWKSMultipleMatchingKeys();\n throw error[Symbol.asyncIterator] = async function* () {\n for (const jwk2 of candidates)\n try {\n yield await importWithAlgCache(cached, jwk2, entry);\n } catch {\n }\n }, error;\n }\n return importWithAlgCache(cached, jwk, entry);\n }, \"jwks\", {\n value: () => structuredClone(snapshot)\n });\n}\nexport {\n createLocalJWKSet\n};\n","import { decode as decodeBase64URL } from \"../util/base64url.js\";\nimport { fromSPKI, fromPKCS8, fromX509 } from \"../lib/asn1.js\";\nimport { jwkToKey, validateExtractableOption, normalizeJwk } from \"../lib/key.js\";\nimport { keyAlgorithm } from \"../lib/key_algorithm.js\";\nimport { JOSENotSupported } from \"../util/errors.js\";\nimport { isObject } from \"../lib/validate.js\";\nasync function importSPKI(spki, alg, options) {\n if (typeof spki != \"string\" || spki.indexOf(\"-----BEGIN PUBLIC KEY-----\") !== 0)\n throw new TypeError('\"spki\" must be SPKI formatted string');\n return fromSPKI(spki, alg, options);\n}\nasync function importX509(x509, alg, options) {\n if (typeof x509 != \"string\" || x509.indexOf(\"-----BEGIN CERTIFICATE-----\") !== 0)\n throw new TypeError('\"x509\" must be X.509 formatted string');\n return fromX509(x509, alg, options);\n}\nasync function importPKCS8(pkcs8, alg, options) {\n if (typeof pkcs8 != \"string\" || pkcs8.indexOf(\"-----BEGIN PRIVATE KEY-----\") !== 0)\n throw new TypeError('\"pkcs8\" must be PKCS#8 formatted string');\n return fromPKCS8(pkcs8, alg, options);\n}\nasync function importJWK(jwk, alg, options) {\n if (!isObject(jwk))\n throw new TypeError(\"JWK must be an object\");\n const normalized = normalizeJwk(jwk), extractable = validateExtractableOption(options?.extractable), { alg: jwkAlg } = normalized;\n if (alg ??= jwkAlg, normalized.kty !== \"oct\" && !alg)\n throw new TypeError('\"alg\" argument is required when \"jwk.alg\" is not present');\n switch (normalized.kty) {\n case \"oct\":\n if (typeof normalized.k != \"string\")\n throw new TypeError('missing \"k\" (Key Value) Parameter value');\n return decodeBase64URL(normalized.k);\n case \"AKP\": {\n if (typeof jwkAlg != \"string\" || !jwkAlg)\n throw new TypeError('missing \"alg\" (Algorithm) Parameter value');\n if (alg !== jwkAlg)\n throw new TypeError(\"JWK alg and alg option value mismatch\");\n return jwkToKey(keyAlgorithm(alg), normalized, extractable);\n }\n case \"RSA\":\n case \"EC\":\n case \"OKP\":\n return jwkToKey(keyAlgorithm(alg), normalized, extractable);\n default:\n throw new JOSENotSupported('Unsupported \"kty\" (Key Type) Parameter value');\n }\n}\nexport {\n importJWK,\n importPKCS8,\n importSPKI,\n importX509\n};\n","import { parseJoseHeader } from \"../lib/validate.js\";\nfunction decodeProtectedHeader(token) {\n let protectedB64u;\n if (typeof token == \"string\") {\n const parts = token.split(\".\");\n (parts.length === 3 || parts.length === 5) && ([protectedB64u] = parts);\n } else if (typeof token == \"object\" && token)\n if (\"protected\" in token)\n protectedB64u = token.protected;\n else\n throw new TypeError(\"Token does not contain a Protected Header\");\n const invalid = \"Invalid Token or Protected Header formatting\";\n if (typeof protectedB64u != \"string\" || !protectedB64u)\n throw new TypeError(invalid);\n return parseJoseHeader(protectedB64u, TypeError, invalid);\n}\nexport {\n decodeProtectedHeader\n};\n","import { decode as b64u } from \"./base64url.js\";\nimport { strictDecoder } from \"../lib/buffer_utils.js\";\nimport { isObject } from \"../lib/validate.js\";\nimport { JWTInvalid } from \"./errors.js\";\nfunction decodeJwt(jwt) {\n if (typeof jwt != \"string\")\n throw new JWTInvalid(\"JWTs must use Compact JWS serialization, JWT must be a string\");\n const { 1: payload, length } = jwt.split(\".\");\n if (length === 5)\n throw new JWTInvalid(\"Only JWTs using Compact JWS serialization can be decoded\");\n if (length !== 3)\n throw new JWTInvalid(\"Invalid JWT\");\n if (!payload)\n throw new JWTInvalid(\"JWTs must contain a payload\");\n let decoded;\n try {\n decoded = b64u(payload);\n } catch {\n throw new JWTInvalid(\"Failed to base64url decode the payload\");\n }\n let result;\n try {\n result = JSON.parse(strictDecoder.decode(decoded));\n } catch {\n throw new JWTInvalid(\"Failed to parse the decoded payload as JSON\");\n }\n if (!isObject(result))\n throw new JWTInvalid(\"Invalid JWT Claims Set\");\n return result;\n}\nexport {\n decodeJwt\n};\n","import { JOSENotSupported } from \"../util/errors.js\";\nimport { validateExtractableOption } from \"../lib/key.js\";\nimport { keyAlgorithm, unsupportedAlg, algArgument } from \"../lib/key_algorithm.js\";\nfunction getModulusLengthOption(options) {\n const modulusLength = options?.modulusLength ?? 2048;\n if (typeof modulusLength != \"number\" || !Number.isInteger(modulusLength) || modulusLength < 2048)\n throw new JOSENotSupported(\"Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used\");\n return modulusLength;\n}\nasync function generateKeyPair(alg, options) {\n const extractable = validateExtractableOption(options?.extractable), entry = keyAlgorithm(alg, algArgument);\n entry.secret && unsupportedAlg(algArgument);\n let algorithm;\n if (entry.resolve) {\n const crv = options?.crv ?? \"P-256\";\n if (![\"P-256\", \"P-384\", \"P-521\", \"X25519\"].includes(crv))\n throw new JOSENotSupported(\"Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519\");\n algorithm = entry.resolve({ crv });\n } else {\n if (entry.crv !== void 0 && options?.crv !== void 0 && options.crv !== entry.crv)\n throw new JOSENotSupported(`Invalid or unsupported crv option provided, the only supported value for ${alg} is ${entry.crv}`);\n algorithm = entry.kty[0] === \"RSA\" ? {\n ...entry.subtle,\n publicExponent: Uint8Array.of(1, 0, 1),\n modulusLength: getModulusLengthOption(options)\n } : entry.subtle;\n }\n return crypto.subtle.generateKey(algorithm, extractable ?? !1, [\n ...entry.usages[1],\n ...entry.usages[0]\n ]);\n}\nexport {\n generateKeyPair\n};\n","import { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { EncryptJWT, SignJWT, base64url, calculateJwkThumbprint, decodeProtectedHeader, jwtDecrypt, jwtVerify } from \"jose\";\n//#region src/crypto/jwt.ts\nasync function signJWT(payload, secret, expiresIn = 3600) {\n\treturn await new SignJWT(payload).setProtectedHeader({ alg: \"HS256\" }).setIssuedAt().setExpirationTime(Math.floor(Date.now() / 1e3) + expiresIn).sign(new TextEncoder().encode(secret));\n}\nasync function verifyJWT(token, secret) {\n\ttry {\n\t\treturn (await jwtVerify(token, new TextEncoder().encode(secret))).payload;\n\t} catch {\n\t\treturn null;\n\t}\n}\nconst info = new Uint8Array([\n\t66,\n\t101,\n\t116,\n\t116,\n\t101,\n\t114,\n\t65,\n\t117,\n\t116,\n\t104,\n\t46,\n\t106,\n\t115,\n\t32,\n\t71,\n\t101,\n\t110,\n\t101,\n\t114,\n\t97,\n\t116,\n\t101,\n\t100,\n\t32,\n\t69,\n\t110,\n\t99,\n\t114,\n\t121,\n\t112,\n\t116,\n\t105,\n\t111,\n\t110,\n\t32,\n\t75,\n\t101,\n\t121\n]);\nconst now = () => Date.now() / 1e3 | 0;\nconst alg = \"dir\";\nconst enc = \"A256CBC-HS512\";\nfunction deriveEncryptionSecret(secret, salt) {\n\treturn hkdf(sha256, new TextEncoder().encode(secret), new TextEncoder().encode(salt), info, 64);\n}\nfunction getCurrentSecret(secret) {\n\tif (typeof secret === \"string\") return secret;\n\tconst value = secret.keys.get(secret.currentVersion);\n\tif (!value) throw new Error(`Secret version ${secret.currentVersion} not found in keys`);\n\treturn value;\n}\nfunction getAllSecrets(secret) {\n\tif (typeof secret === \"string\") return [{\n\t\tversion: 0,\n\t\tvalue: secret\n\t}];\n\tconst result = [];\n\tfor (const [version, value] of secret.keys) result.push({\n\t\tversion,\n\t\tvalue\n\t});\n\tif (secret.legacySecret && !result.some((s) => s.value === secret.legacySecret)) result.push({\n\t\tversion: -1,\n\t\tvalue: secret.legacySecret\n\t});\n\treturn result;\n}\nasync function symmetricEncodeJWT(payload, secret, salt, expiresIn = 3600) {\n\tconst encryptionSecret = deriveEncryptionSecret(getCurrentSecret(secret), salt);\n\tconst thumbprint = await calculateJwkThumbprint({\n\t\tkty: \"oct\",\n\t\tk: base64url.encode(encryptionSecret)\n\t}, \"sha256\");\n\treturn await new EncryptJWT(payload).setProtectedHeader({\n\t\talg,\n\t\tenc,\n\t\tkid: thumbprint\n\t}).setIssuedAt().setExpirationTime(now() + expiresIn).setJti(crypto.randomUUID()).encrypt(encryptionSecret);\n}\nconst jwtDecryptOpts = {\n\tclockTolerance: 15,\n\tkeyManagementAlgorithms: [alg],\n\tcontentEncryptionAlgorithms: [enc, \"A256GCM\"]\n};\nasync function symmetricDecodeJWT(token, secret, salt) {\n\tif (!token) return null;\n\tlet hasKid = false;\n\ttry {\n\t\thasKid = decodeProtectedHeader(token).kid !== void 0;\n\t} catch {\n\t\treturn null;\n\t}\n\ttry {\n\t\tconst secrets = getAllSecrets(secret);\n\t\tconst { payload } = await jwtDecrypt(token, async (protectedHeader) => {\n\t\t\tconst kid = protectedHeader.kid;\n\t\t\tif (kid !== void 0) {\n\t\t\t\tfor (const s of secrets) {\n\t\t\t\t\tconst encryptionSecret = deriveEncryptionSecret(s.value, salt);\n\t\t\t\t\tif (kid === await calculateJwkThumbprint({\n\t\t\t\t\t\tkty: \"oct\",\n\t\t\t\t\t\tk: base64url.encode(encryptionSecret)\n\t\t\t\t\t}, \"sha256\")) return encryptionSecret;\n\t\t\t\t}\n\t\t\t\tthrow new Error(\"no matching decryption secret\");\n\t\t\t}\n\t\t\tif (secrets.length === 1) return deriveEncryptionSecret(secrets[0].value, salt);\n\t\t\treturn deriveEncryptionSecret(secrets[0].value, salt);\n\t\t}, jwtDecryptOpts);\n\t\treturn payload;\n\t} catch {\n\t\tif (hasKid) return null;\n\t\tconst secrets = getAllSecrets(secret);\n\t\tif (secrets.length <= 1) return null;\n\t\tfor (let i = 1; i < secrets.length; i++) try {\n\t\t\tconst s = secrets[i];\n\t\t\tconst { payload } = await jwtDecrypt(token, deriveEncryptionSecret(s.value, salt), jwtDecryptOpts);\n\t\t\treturn payload;\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\treturn null;\n\t}\n}\n//#endregion\nexport { signJWT, symmetricDecodeJWT, symmetricEncodeJWT, verifyJWT };\n","//#region src/crypto/buffer.ts\n/**\n* Compare two buffers in constant time.\n*/\nfunction constantTimeEqual(a, b) {\n\tif (typeof a === \"string\") a = new TextEncoder().encode(a);\n\tif (typeof b === \"string\") b = new TextEncoder().encode(b);\n\tconst aBuffer = new Uint8Array(a);\n\tconst bBuffer = new Uint8Array(b);\n\tlet c = aBuffer.length ^ bBuffer.length;\n\tconst length = Math.max(aBuffer.length, bBuffer.length);\n\tfor (let i = 0; i < length; i++) c |= (i < aBuffer.length ? aBuffer[i] : 0) ^ (i < bBuffer.length ? bBuffer[i] : 0);\n\treturn c === 0;\n}\n//#endregion\nexport { constantTimeEqual };\n","import { createRandomStringGenerator } from \"@better-auth/utils/random\";\n//#region src/crypto/random.ts\nconst generateRandomString = createRandomStringGenerator(\"a-z\", \"0-9\", \"A-Z\", \"-_\");\n//#endregion\nexport { generateRandomString };\n","//#region src/index.ts\nfunction getWebcryptoSubtle() {\n\tconst cr = typeof globalThis !== \"undefined\" && globalThis.crypto;\n\tif (cr && typeof cr.subtle === \"object\" && cr.subtle != null) return cr.subtle;\n\tthrow new Error(\"crypto.subtle must be defined\");\n}\n//#endregion\nexport { getWebcryptoSubtle };\n","import { getWebcryptoSubtle } from \"./index.mjs\";\nimport { toBufferSource } from \"./bytes.mjs\";\nimport { base64, base64Url } from \"./base64.mjs\";\n//#region src/hash.ts\nfunction createHash(algorithm, encoding) {\n\treturn { digest: async (input) => {\n\t\tconst data = toBufferSource(input);\n\t\tconst hashBuffer = await getWebcryptoSubtle().digest(algorithm, data);\n\t\tif (encoding === \"hex\") return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n\t\tif (encoding === \"base64\" || encoding === \"base64url\" || encoding === \"base64urlnopad\") {\n\t\t\tif (encoding.includes(\"url\")) return base64Url.encode(hashBuffer, { padding: encoding !== \"base64urlnopad\" });\n\t\t\treturn base64.encode(hashBuffer);\n\t\t}\n\t\treturn hashBuffer;\n\t} };\n}\n//#endregion\nexport { createHash };\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nexport function aarray(item, title, inner = () => { }) {\n if (!Array.isArray(item))\n throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n for (let i = 0; i < item.length; i++)\n inner(item[i], `${title}[${i}]`);\n return item;\n}\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - Value to inspect.\n * @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.\n * @example\n * Guards a value before treating it as raw key material.\n *\n * ```ts\n * isBytes(new Uint8Array());\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy /\n // cross-realm cases. The fallback still requires a real ArrayBuffer view\n // so plain JSON-deserialized `{ constructor: ... }`\n // spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is boolean.\n * @param value - Value to validate.\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validates a boolean option before branching on it.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Asserts something is a non-negative safe integer.\n * @param n - Value to validate.\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validates a non-negative length or counter.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - Value to validate.\n * @param length - Expected byte length.\n * @param title - Optional label used in error messages.\n * @returns The validated byte array.\n * On Node, `Buffer` is accepted too because it is a Uint8Array view.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument lengths. {@link RangeError}\n * @example\n * Validates a fixed-length nonce or key buffer.\n *\n * ```ts\n * abytes(new Uint8Array([1, 2]), 2);\n * ```\n */\nexport function abytes(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError(label === 'object'\n ? 'expected valid options object'\n : `\"${label}\" expected object, got type=${typeof value}`);\n};\n/**\n * Asserts a hash- or MAC-like instance has not been destroyed or finished.\n * @param instance - Stateful instance to validate.\n * @param checkFinished - Whether to reject finished instances.\n * When `false`, only `destroyed` is checked.\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Guards against calling `update()` or `digest()` on a finished hash.\n *\n * ```ts\n * aexists({ destroyed: false, finished: false });\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - Output buffer to validate.\n * @param instance - Hash-like instance providing `outputLen`.\n * This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,\n * unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong output buffer lengths. {@link RangeError}\n * @example\n * Verifies that a caller-provided output buffer is large enough.\n *\n * ```ts\n * aoutput(new Uint8Array(16), { outputLen: 16 });\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\n}\n/**\n * Asserts output is a sufficiently-sized, 4-byte-aligned byte array.\n * {@link aoutput} plus an {@link isAligned32} check, for `digestInto()` paths\n * that write through zero-allocation `u32` word views.\n * @param out - Output buffer to validate.\n * @param instance - Hash-like instance providing `outputLen`.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong output buffer lengths. {@link RangeError}\n * @throws On wrong output buffer alignment. {@link Error}\n * @example\n * Verifies that a caller-provided output buffer is large enough and aligned.\n *\n * ```ts\n * aoutput32(new Uint8Array(16), { outputLen: 16 });\n * ```\n */\nexport function aoutput32(out, instance) {\n aoutput(out, instance);\n if (!isAligned32(out))\n throw new Error('invalid output, must be aligned');\n}\n/**\n * Casts a typed-array view to Uint8Array.\n * @param arr - Typed-array view to reinterpret.\n * @returns Uint8Array view over the same bytes.\n * @example\n * Views 32-bit words as raw bytes without copying.\n *\n * ```ts\n * u8(new Uint32Array([1]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed-array view to Uint32Array.\n * @param arr - Typed-array view to reinterpret.\n * @returns Uint32Array view over the same bytes. Callers are expected to provide a\n * 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.\n * @example\n * Views a byte buffer as 32-bit words for block processing.\n *\n * ```ts\n * u32(new Uint8Array(4));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place.\n * Warning: JS provides no guarantees.\n * @param arrays - Arrays to wipe.\n * @example\n * Wipes a temporary key buffer after use.\n *\n * ```ts\n * const bytes = new Uint8Array([1]);\n * clean(bytes);\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - Typed-array view to wrap.\n * @returns DataView over the same bytes.\n * @example\n * Creates an endian-aware view for length encoding.\n *\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Whether the current platform is little-endian.\n * Most are; some IBM systems are not.\n */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Reverses byte order of one 32-bit word.\n * @param word - Unsigned 32-bit word to swap.\n * @returns The same word with bytes reversed.\n * @example\n * Swaps a big-endian word into little-endian byte order.\n *\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Normalizes one 32-bit word to the little-endian representation expected by cipher cores.\n * @param n - Unsigned 32-bit word to normalize.\n * @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.\n * @example\n * Normalizes a host-endian word before passing it into an ARX/AES core.\n *\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - Uint32Array whose words should be swapped.\n * @returns The same array after in-place byte swapping.\n * @example\n * Swaps every 32-bit word in a word-view buffer.\n *\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.\n * @param u - Word view to normalize in place.\n * @returns Little-endian normalized word view.\n * @example\n * Normalizes a word-view buffer before block processing.\n *\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion:\n// {@link https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex | caniuse entry}\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Formats ciphertext bytes for logs or test vectors.\n *\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n}\nconst _0n = /* @__PURE__ */ BigInt(0);\n// Used in ff1, via bytesToNumberBE\n/**\n * Converts a big-endian hex string into bigint.\n * @param hex - Hexadecimal string without `0x`.\n * @returns Parsed bigint value. The empty string is treated as `0n`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parses a big-endian field element or counter from hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n // Numeric parser, not byte-hex decoder: odd-length forms like 'f' are valid,\n // and malformed syntax follows BigInt's native error behavior.\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// Used in ff1\n// BE: Big Endian, LE: Little Endian\n/**\n * Converts big-endian bytes into bigint.\n * @param bytes - Big-endian bytes.\n * @returns Parsed bigint value. Empty input is treated as `0n`.\n * @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}\n * @example\n * Reads a big-endian integer from serialized bytes.\n *\n * ```ts\n * bytesToNumberBE(new Uint8Array([1, 0]));\n * ```\n */\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n */\nfunction abignumber(n) {\n if (typeof n === 'bigint') {\n if (!(_0n <= n))\n throw new RangeError('positive bigint expected, got ' + n);\n }\n else\n anumber(n);\n return n;\n}\n// Used in ff1\n/**\n * Converts a number into big-endian bytes of fixed length.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian bytes padded to `len`.\n * Negative values, `len = 0`, and values that do not fit are rejected before\n * downstream hex parsing.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Encodes a counter as fixed-width big-endian bytes.\n *\n * ```ts\n * numberToBytesBE(1, 2);\n * ```\n */\nexport function numberToBytesBE(n, len) {\n anumber(len);\n if (len === 0)\n throw new Error('zero output length is invalid');\n n = abignumber(n);\n const expectedLen = len * 2;\n const hex = n.toString(16);\n // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n if (hex.length > expectedLen)\n throw new RangeError('number is too large');\n return hexToBytes(hex.padStart(expectedLen, '0'));\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @param str - String to encode.\n * @returns UTF-8 bytes in a detached fresh Uint8Array copy.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encodes application text before encryption or MACing.\n *\n * ```ts\n * utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // {@link https://bugzil.la/1681809 | Firefox bug 1681809}\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @param bytes - UTF-8 bytes.\n * @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed\n * UTF-8 is replacement-decoded instead of rejected.\n * @example\n * Decodes UTF-8 plaintext back into a string.\n *\n * ```ts\n * bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'\n * ```\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Checks if two U8A use same underlying buffer and overlaps.\n * This is invalid and can corrupt data.\n * @param a - First byte view.\n * @param b - Second byte view.\n * @returns `true` when the views overlap in memory.\n * @example\n * Detects whether two slices alias the same backing buffer.\n *\n * ```ts\n * overlapBytes(new Uint8Array(4), new Uint8Array(4));\n * ```\n */\nexport function overlapBytes(a, b) {\n // Zero-length views cannot overwrite anything, even if their offset sits inside another range.\n if (!a.byteLength || !b.byteLength)\n return false;\n return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy\n a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end\n b.byteOffset < a.byteOffset + a.byteLength // b starts before a end\n );\n}\n/**\n * If input and output overlap and input starts before output, we will overwrite end of input before\n * we start processing it, so this is not supported by forward-processing ciphers.\n * @param input - Input bytes.\n * @param output - Output bytes.\n * @throws If the output view would overwrite unread input bytes. {@link Error}\n * @example\n * Rejects an in-place layout that would overwrite unread input bytes.\n *\n * ```ts\n * const buffer = new Uint8Array(8);\n * complexOverlapBytes(buffer.subarray(0, 4), buffer.subarray(2, 6));\n * ```\n */\nexport function complexOverlapBytes(input, output) {\n // This is very cursed. It works somehow, but I'm completely unsure,\n // reasoning about overlapping aligned windows is very hard.\n if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)\n throw new Error('complex overlap of input and output is not supported');\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - Byte arrays to concatenate.\n * @returns Combined byte array.\n * @throws On wrong argument types inside the byte-array list. {@link TypeError}\n * @example\n * Builds a `nonce || ciphertext` style buffer.\n *\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Merges user options into defaults.\n * @param defaults - Default option values.\n * @param opts - User-provided overrides.\n * @returns Combined options object.\n * `defaults` is a library-owned mutable object; user-provided `opts` only need to be\n * object-shaped, since \"plain object\" checks reject valid proxy/cross-realm containers.\n * The merge mutates `defaults` in place and returns the same object, so direct callers\n * should pass a fresh defaults object unless they intentionally want shared state updated.\n * @throws If options are missing or not an object. {@link Error}\n * @example\n * Applies user overrides to the default cipher options.\n *\n * ```ts\n * checkOpts({ rounds: 20 }, { rounds: 8 });\n * ```\n */\nexport function checkOpts(defaults, opts) {\n aobject(defaults, 'defaults');\n aobject(opts, 'opts');\n // Mutates defaults by design. __proto__ follows Object.assign semantics here and can only\n // affect this local option object; callers already control this low-level options surface.\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/**\n * Compares two byte arrays in kinda constant time once lengths already match.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns `true` when the arrays contain the same bytes. Different lengths still return early.\n * @example\n * Compares an expected authentication tag with the received one.\n *\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a, b) {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Wraps a keyed MAC constructor into a one-shot helper with `.create()`.\n * @param keyLen - Valid probe-key length used to read static metadata once.\n * The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes\n * can pass any representative size as long as those values stay fixed.\n * @param macCons - Keyed MAC constructor or factory.\n * @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.\n * @returns Callable MAC helper with `.create()`.\n */\nexport function wrapMacConstructor(keyLen, macCons, fromMsg) {\n const mac = macCons;\n const getArgs = (fromMsg || (() => []));\n const macC = (msg, key) => mac(key, ...getArgs(msg))\n .update(msg)\n .digest();\n const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));\n macC.outputLen = tmp.outputLen;\n macC.blockLen = tmp.blockLen;\n macC.create = (key, ...args) => mac(key, ...args);\n return macC;\n}\n/**\n * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * Used internally by the exported cipher constructors.\n * Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`\n * arity (`fn.length === 2`), so wrapped output-capable methods must use a normal\n * second parameter, not a default/rest parameter. AAD support is explicit in\n * `params.withAAD`; optional AAD starts after the nonce slot when one is present.\n * @__NO_SIDE_EFFECTS__\n * @param params - Static cipher metadata. See {@link CipherParams}.\n * @param constructor - Cipher constructor.\n * @returns Wrapped constructor with validation.\n */\nexport const wrapCipher = (params, constructor) => {\n function wrappedCipher(key, ...args) {\n // Validate key\n abytes(key, undefined, 'key');\n // Validate nonce if nonceLength is present\n if (params.nonceLength !== undefined) {\n const nonce = args[0];\n abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce');\n }\n // Keep tag length available for decrypt-size checks after constructor validation.\n const tagl = params.tagLength;\n const aadStart = params.nonceLength !== undefined ? 1 : 0;\n // No-AAD constructors otherwise silently ignore byte args meant as AAD.\n if (!params.withAAD) {\n for (let i = aadStart; i < args.length; i++)\n if (isBytes(args[i]))\n throw new Error('AAD not supported');\n }\n // Validate the first AAD slot early; rest-arg AAD constructors validate the tail themselves.\n if (params.withAAD && args[aadStart] !== undefined)\n abytes(args[aadStart], undefined, 'AAD');\n const cipher = constructor(key, ...args);\n const checkOutput = (fnLength, output) => {\n if (output !== undefined) {\n if (fnLength !== 2)\n throw new Error('cipher output not supported');\n abytes(output, undefined, 'output');\n }\n };\n // Create wrapped cipher with validation and single-use encryption\n let called = false;\n const wrCipher = {\n encrypt(data, output) {\n if (called)\n throw new Error('cannot encrypt() twice with same key + nonce');\n // Any encrypt attempt consumes the instance, even if validation rejects below.\n called = true;\n abytes(data, undefined, 'data');\n checkOutput(cipher.encrypt.length, output);\n return cipher.encrypt(data, output);\n },\n decrypt(data, output) {\n abytes(data, undefined, 'data');\n if (tagl && data.length < tagl)\n throw new Error('\"ciphertext\" expected length >= tagLength=' + tagl);\n checkOutput(cipher.decrypt.length, output);\n return cipher.decrypt(data, output);\n },\n };\n return wrCipher;\n }\n Object.assign(wrappedCipher, params);\n return wrappedCipher;\n};\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n * @param expectedLength - Required output length.\n * @param out - Optional destination buffer.\n * @param onlyAligned - Whether `out` must be 4-byte aligned.\n * @returns Output buffer ready for writing.\n * @throws On wrong argument types. {@link TypeError}\n * @throws If the provided output buffer has the wrong size. {@link RangeError}\n * @throws If the provided output buffer has the wrong alignment. {@link Error}\n * @example\n * Reuses a caller-provided output buffer when lengths match.\n *\n * ```ts\n * getOutput(16, new Uint8Array(16));\n * ```\n */\nexport function getOutput(expectedLength, out, onlyAligned = true) {\n if (out === undefined)\n return new Uint8Array(expectedLength);\n // Keep Buffer/cross-realm Uint8Array support here instead of trusting a shape-compatible object.\n abytes(out, expectedLength, 'output');\n if (onlyAligned && !isAligned32(out))\n throw new Error('invalid output, must be aligned');\n return out;\n}\n/**\n * Encodes data and AAD lengths into a 16-byte buffer.\n * @param dataLength - Data length. Units are caller-defined: GCM passes bit\n * lengths, ChaCha20-Poly1305 passes byte lengths — the helper writes the raw values.\n * @param aadLength - AAD length, same unit convention as `dataLength`.\n * The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305\n * conventions even though the helper parameter order is `(dataLength, aadLength)`.\n * @param isLE - Whether to encode lengths as little-endian.\n * @returns 16-byte length block.\n * @throws On wrong argument types passed to the endian validator. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Builds the length block appended by GCM and Poly1305.\n *\n * ```ts\n * u64Lengths(16, 8, true);\n * ```\n */\nexport function u64Lengths(dataLength, aadLength, isLE) {\n // Reject coercible non-number lengths like '10' and true before BigInt(...) accepts them.\n anumber(dataLength);\n anumber(aadLength);\n abool(isLE);\n const num = new Uint8Array(16);\n const view = createView(num);\n view.setBigUint64(0, BigInt(aadLength), isLE);\n view.setBigUint64(8, BigInt(dataLength), isLE);\n return num;\n}\n/**\n * Checks whether a byte array is aligned to a 4-byte offset.\n * @param bytes - Byte array to inspect.\n * @returns `true` when the view is 4-byte aligned.\n * @example\n * Checks whether a buffer can be safely viewed as Uint32Array.\n *\n * ```ts\n * isAligned32(new Uint8Array(4));\n * ```\n */\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n/**\n * Copies bytes into a new Uint8Array.\n * @param bytes - Bytes to copy.\n * @returns Copied byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Copies input into an aligned Uint8Array before block processing.\n *\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Uses CSPRNG for nonce, nonce injected in ciphertext.\n * For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and\n * prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext\n * are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`\n * buffer on encrypt and intentionally does not support caller-provided destination buffers.\n * Too-short decrypt inputs are split into short/empty nonce views and then delegated\n * to the wrapped cipher instead of being rejected here first.\n *\n * NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha\n * should be limited to `2**23` (8M) messages to get a collision chance of\n * `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to\n * `2**-33`, still negligible but creeping up.\n * @param fn - Cipher constructor that expects a nonce.\n * @param randomBytes_ - Random-byte source used for nonce generation.\n * @returns Cipher constructor that prepends the nonce to ciphertext.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}\n * @example\n * Prepends a fresh random nonce to every ciphertext.\n *\n * ```ts\n * import { gcm } from '@noble/ciphers/aes.js';\n * import { managedNonce, randomBytes } from '@noble/ciphers/utils.js';\n * const wrapped = managedNonce(gcm);\n * const key = randomBytes(16);\n * const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));\n * wrapped(key).decrypt(ciphertext);\n * ```\n */\nexport function managedNonce(fn, randomBytes_ = randomBytes) {\n if (typeof fn !== 'function')\n throw new TypeError('\"fn\" expected cipher constructor, got type=' + typeof fn);\n if (typeof randomBytes_ !== 'function')\n throw new TypeError('\"randomBytes_\" expected function, got type=' + typeof randomBytes_);\n const { nonceLength } = fn;\n anumber(nonceLength, 'fn.nonceLength');\n const addNonce = (nonce, ciphertext, plaintext) => {\n const out = concatBytes(nonce, ciphertext);\n // Wrapped ciphers may alias caller plaintext on encrypt(); never zero\n // caller-owned buffers here.\n if (!overlapBytes(plaintext, ciphertext))\n ciphertext.fill(0);\n return out;\n };\n // NOTE: we cannot support DST here, it would be mistake:\n // - we don't know how much dst length cipher requires\n // - nonce may unalign dst and break everything\n // - we create new u8a anyway (concatBytes)\n // - previously we passed all args to cipher, but that was mistake!\n const res = ((key, ...args) => ({\n encrypt(plaintext) {\n abytes(plaintext, undefined, 'data');\n const nonce = randomBytes_(nonceLength);\n const encrypted = fn(key, nonce, ...args).encrypt(plaintext);\n // @ts-ignore\n if (encrypted instanceof Promise)\n return encrypted.then((ct) => addNonce(nonce, ct, plaintext));\n return addNonce(nonce, encrypted, plaintext);\n },\n decrypt(ciphertext) {\n abytes(ciphertext, undefined, 'data');\n const nonce = ciphertext.subarray(0, nonceLength);\n const decrypted = ciphertext.subarray(nonceLength);\n return fn(key, nonce, ...args).decrypt(decrypted);\n },\n }));\n // Auto-nonce wrappers still preserve the wrapped payload geometry.\n if ('blockSize' in fn)\n res.blockSize = fn.blockSize;\n if ('tagLength' in fn)\n res.tagLength = fn.tagLength;\n if ('withAAD' in fn)\n res.withAAD = fn.withAAD;\n return res;\n}\n","/**\n * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\n\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | cnt(1) | nonce(3)\n chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).\nCounter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.\nCurrent noble policy is strict non-wrap for the shared 32-bit counter path:\nexported ARX ciphers reject initial `0xffffffff` and stop before any implicit\nwrap back to zero.\nSee {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.\n\n * @module\n */\nimport { abool, abytes, anumber, checkOpts, clean, complexOverlapBytes, copyBytes, getOutput, isAligned32, isLE, randomBytes, swap32IfBE, u32, } from \"./utils.js\";\n// Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants.\n// Non-ASCII input would not match UTF-8 `TextEncoder` output.\nconst encodeStr = (str) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0));\n// Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly.\n// Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path.\n// RFC 8439 §2.3 / RFC 7539 §2.3 only define the 256-bit-key constants; this 16-byte sigma is\n// kept for legacy allowShortKeys Salsa/ChaCha variants.\nconst sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 16-byte k'))))();\n// RFC 8439 §2.3 / RFC 7539 §2.3 define words 0-3 as\n// `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`.\nconst sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 32-byte k'))))();\n/**\n * Rotates a 32-bit word left.\n * @param a - Input word.\n * @param b - Rotation count in bits.\n * @returns Rotated 32-bit word.\n * @example\n * Moves the top byte of `0x12345678` into the low byte position.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(a, b) {\n return (a << b) | (a >>> (32 - b));\n}\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\n// RFC 8439 §2.2 / RFC 7539 §2.2: the ChaCha state has 16 32-bit words.\nconst BLOCK_LEN32 = 16;\n// Counter policy for the shared public `counter` argument:\n// - RFC/IETF ChaCha20 uses a 32-bit counter.\n// - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit\n// counter state and carry into the next word.\n// - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium\n// and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max\n// boundary instead of carrying.\n// - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from\n// block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset.\n// Noble intentionally throws instead of silently picking one wrap model for users. In the default\n// path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically\n// unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement\n// whatever wider carry / wrap policy they need on top.\nconst MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();\nconst U32_EMPTY = /* @__PURE__ */ Uint32Array.of();\nfunction runCipher(core, sigma, key, nonce, data, output, counter, rounds) {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isLE && isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n // RFC 8439 §2.4.1 / RFC 7539 §2.4.1 allow XORing one keystream block at a time and\n // truncating the final partial block instead of materializing the whole keystream.\n if (!isLE) {\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n // RFC 8439 §2.4 / RFC 7539 §2.4 serialize keystream words in little-endian order.\n swap32IfBE(b32);\n if (counter >= MAX_COUNTER)\n throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n return;\n }\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n // See MAX_COUNTER policy note above: never silently wrap the shared public counter.\n if (counter >= MAX_COUNTER)\n throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0)\n throw new Error('arx: invalid block position');\n for (let j = 0, posj; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\n/**\n * Creates an ARX stream cipher from a 32-bit core permutation.\n * Used internally to build the exported Salsa and ChaCha stream ciphers.\n * @param core - Core function that fills one keystream block.\n * @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.\n * @returns Stream cipher function over byte arrays.\n * @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}\n */\nexport function createCipher(core, opts) {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);\n if (typeof core !== 'function')\n throw new Error('core must be a function');\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (key, nonce, data, output, counter = 0) => {\n abytes(key, undefined, 'key');\n abytes(nonce, undefined, 'nonce');\n abytes(data, undefined, 'data');\n const len = data.length;\n // Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs\n // must match the logical result length exactly instead of returning an oversized workspace.\n const hasOutput = output !== undefined;\n output = getOutput(len, output, false);\n if (hasOutput)\n complexOverlapBytes(data, output);\n anumber(counter);\n // See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap.\n if (counter < 0 || counter >= MAX_COUNTER)\n throw new Error('arx: counter overflow');\n const toClean = [];\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n let l = key.length;\n let k;\n let sigma;\n if (l === 32) {\n // Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and\n // final clean(...) all mutate or wipe the temporary buffer in place.\n toClean.push((k = copyBytes(key)));\n sigma = sigma32_32;\n }\n else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n }\n else {\n abytes(key, 32, 'arx key');\n throw new Error('invalid key size');\n // throw new Error(`\"arx key\" expected Uint8Array of length 32, got length=${l}`);\n }\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Copy before taking u32(...) views on misaligned inputs, and on big-endian so later\n // swap32IfBE(...) never mutates caller nonce bytes in place.\n if (!isLE || !isAligned32(nonce))\n toClean.push((nonce = copyBytes(nonce)));\n let k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24)\n throw new Error('arx: extended nonce must be 24 bytes');\n const n16 = nonce.subarray(0, 16);\n if (isLE)\n extendNonceFn(sigma, k32, u32(n16), k32);\n else {\n const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));\n extendNonceFn(sigmaRaw, k32, u32(n16), k32);\n clean(sigmaRaw);\n swap32IfBE(k32);\n }\n nonce = nonce.subarray(16);\n }\n else if (!isLE)\n swap32IfBE(k32);\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length)\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n // Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero\n // counter bytes, while Salsa/XSalsa append them after the nonce words.\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = swap32IfBE(u32(nonce));\n // Ensure temporary key/nonce copies are wiped even if the remaining\n // runtime guard in runCipher(...) throws on counter overflow.\n try {\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n return output;\n }\n finally {\n clean(...toClean);\n }\n };\n}\n/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */\nexport class _XorStreamPRG {\n blockLen;\n keyLen;\n nonceLen;\n state;\n buf;\n key;\n nonce;\n pos;\n ctr;\n cipher;\n destroyed = false;\n constructor(cipher, blockLen, keyLen, nonceLen, seed) {\n this.cipher = cipher;\n this.blockLen = blockLen;\n this.keyLen = keyLen;\n this.nonceLen = nonceLen;\n this.state = new Uint8Array(this.keyLen + this.nonceLen);\n this.reseed(seed);\n this.ctr = 0;\n this.pos = this.blockLen;\n this.buf = new Uint8Array(this.blockLen);\n // Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher\n // inputs in place through these subarray views.\n this.key = this.state.subarray(0, this.keyLen);\n this.nonce = this.state.subarray(this.keyLen);\n }\n reseed(seed) {\n abytes(seed, undefined, 'seed');\n if (!seed || seed.length === 0)\n throw new Error('entropy required');\n // Mix variable-length entropy cyclically across the whole key||nonce state, then restart the\n // keystream so buffered leftovers from the previous state are never reused.\n for (let i = 0; i < seed.length; i++)\n this.state[i % this.state.length] ^= seed[i];\n this.ctr = 0;\n this.pos = this.blockLen;\n }\n addEntropy(seed) {\n if (this.destroyed)\n throw new Error('cannot use destroyed PRG');\n // Reject empty entropy before re-keying, otherwise a throwing call would still advance state.\n abytes(seed, undefined, 'seed');\n if (seed.length === 0)\n throw new Error('entropy required');\n // Re-key from the current stream first, then mix external entropy into the fresh key||nonce\n // state through reseed() so stale buffered bytes are discarded.\n this.state.set(this.randomBytes(this.state.length));\n this.reseed(seed);\n }\n randomBytes(len) {\n if (this.destroyed)\n throw new Error('cannot use destroyed PRG');\n anumber(len);\n if (len === 0)\n return new Uint8Array(0);\n const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0;\n const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen);\n // Preflight overflow so failed reads don't partially consume keystream\n // and leave the PRG repeating blocks.\n if (blocks > 0 && this.ctr > MAX_COUNTER - blocks)\n throw new Error('arx: counter overflow');\n const out = new Uint8Array(len);\n let outPos = 0;\n // `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream\n // ciphers then emit raw keystream bytes directly into those buffers.\n // Serve buffered leftovers first so split reads stay identical to one larger read.\n if (this.pos < this.blockLen) {\n const take = Math.min(len, this.blockLen - this.pos);\n out.set(this.buf.subarray(this.pos, this.pos + take), 0);\n this.pos += take;\n outPos += take;\n if (outPos === len)\n return out; // fast path\n }\n // Full blocks directly to out\n const full = Math.floor((len - outPos) / this.blockLen);\n if (full > 0) {\n const blockBytes = full * this.blockLen;\n const b = out.subarray(outPos, outPos + blockBytes);\n this.cipher(this.key, this.nonce, b, b, this.ctr);\n this.ctr += full;\n outPos += blockBytes;\n }\n // Save leftovers\n const left = len - outPos;\n if (left > 0) {\n this.buf.fill(0);\n // NOTE: cipher will handle overflow\n this.cipher(this.key, this.nonce, this.buf, this.buf, this.ctr++);\n out.set(this.buf.subarray(0, left), outPos);\n this.pos = left;\n }\n return out;\n }\n // Clone seeds the new instance from this stream, so the source PRG advances too.\n clone() {\n if (this.destroyed)\n throw new Error('cannot use destroyed PRG');\n return new _XorStreamPRG(this.cipher, this.blockLen, this.keyLen, this.nonceLen, this.randomBytes(this.state.length));\n }\n // Zeroes the current state, leftover buffer, and marks the instance destroyed.\n // The instance fails closed: any later randomBytes()/addEntropy()/clone() throws instead\n // of silently continuing from zero key||nonce state (which would yield predictable output).\n clean() {\n this.pos = 0;\n this.ctr = 0;\n this.buf.fill(0);\n this.state.fill(0);\n this.destroyed = true;\n }\n}\n/**\n * Creates a PRG constructor from a stream cipher.\n * @param cipher - Stream cipher used to fill output blocks.\n * @param blockLen - Keystream block length in bytes.\n * @param keyLen - Internal key length in bytes.\n * @param nonceLen - Internal nonce length in bytes.\n * @returns PRG factory for seeded concrete `_XorStreamPRG` instances.\n * @example\n * Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.\n * ```ts\n * import { xchacha20 } from '@noble/ciphers/chacha.js';\n * import { createPRG } from '@noble/ciphers/_arx.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const init = createPRG(xchacha20, 64, 32, 24);\n * const prg = init(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const createPRG = (cipher, blockLen, keyLen, nonceLen) => {\n return ((seed = randomBytes(32)) => new _XorStreamPRG(cipher, blockLen, keyLen, nonceLen, seed));\n};\n","/**\n * Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},\n * {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})\n * is a fast and parallel secret-key message-authentication code suitable for\n * a wide variety of applications. It was standardized in\n * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.\n *\n * Polynomial MACs are not perfect for every situation:\n * they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.\n * See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.\n * To combat invisible salamanders, `hash(key)` can be included in ciphertext,\n * however, this would violate ciphertext indistinguishability:\n * an attacker would know which key was used - so `HKDF(key, i)`\n * could be used instead.\n *\n * Check out the {@link https://cr.yp.to/mac.html | original website}.\n * Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.\n * @module\n */\n// prettier-ignore\nimport { abytes, aexists, aoutput, clean, copyBytes, wrapMacConstructor } from \"./utils.js\";\n// A simple-loop reference version (`poly1305_small`) lives in\n// `test/misc/micro-ciphers.ts`, provided for auditability.\n// Little-endian 2-byte load used by the Poly1305 limb decomposition.\nfunction u8to16(a, i) {\n return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\n}\n/**\n * Incremental Poly1305 MAC state.\n * Prefer `poly1305()` for one-shot use.\n * @param key - 32-byte Poly1305 one-time key.\n * @example\n * Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.\n *\n * ```ts\n * import { Poly1305 } from '@noble/ciphers/_poly1305.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const mac = new Poly1305(key);\n * mac.update(new Uint8Array([1, 2, 3]));\n * mac.digest();\n * ```\n */\nexport class Poly1305 {\n blockLen = 16;\n outputLen = 16;\n buffer = new Uint8Array(16);\n r = new Uint16Array(10); // Allocating 1 array with .subarray() here is slower than 3\n h = new Uint16Array(10);\n pad = new Uint16Array(8);\n pos = 0;\n finished = false;\n destroyed = false;\n // Can be speed-up using BigUint64Array, at the cost of complexity\n constructor(key) {\n key = copyBytes(abytes(key, 32, 'key'));\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n // RFC 8439 §2.5.1 / RFC 7539 §2.5.1 clamp r before multiplication.\n // These masks unpack that clamped value into 13-bit limbs, while pad\n // keeps the raw s half for finalize().\n // {@link https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 | poly1305-donna reference}\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++)\n this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n process(data, offset, isLast = false) {\n // RFC 8439 §2.5 / §2.5.1 and RFC 7539 §2.5 / §2.5.1 add an extra high\n // bit to every full 16-byte block. The final partial block gets its\n // explicit `1` byte during digestInto(), so `hibit` stays zero there.\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n let h0 = h[0] + (t0 & 0x1fff);\n let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n let h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n let h9 = h[9] + ((t7 >>> 5) | hibit);\n let c = 0;\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n // RFC 8439 §2.5 / RFC 7539 §2.5 reduce modulo 2^130-5 before repacking\n // to 16-bit words and adding the raw s half.\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++)\n g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++)\n h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n clean(g);\n }\n update(data) {\n aexists(this);\n abytes(data);\n data = copyBytes(data);\n const { buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(data, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy() {\n // `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.\n this.destroyed = true;\n clean(this.h, this.r, this.buffer, this.pad);\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n // RFC 8439 §2.5 / RFC 7539 §2.5: the final short block appends a\n // single `0x01` byte and zero-fills the remaining bytes before the\n // last multiplication step.\n buffer[pos++] = 1;\n for (; pos < 16; pos++)\n buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy out before destroy() zeroes the internal buffer.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n}\n/**\n * Poly1305 MAC from RFC 8439.\n * @param msg - Message bytes to authenticate.\n * @param key - 32-byte Poly1305 one-time key.\n * @returns 16-byte authentication tag.\n * @example\n * Authenticates one message with a one-shot Poly1305 call and a fresh key.\n *\n * ```ts\n * import { poly1305 } from '@noble/ciphers/_poly1305.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * poly1305(new Uint8Array(), key);\n * ```\n */\nexport const poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key));\n","/**\n * ChaCha stream cipher, released\n * in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.\n * It was standardized in\n * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and\n * is now used in TLS 1.3.\n *\n * {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20}\n * extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with\n * randomly-generated nonces.\n *\n * Check out\n * {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF},\n * {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and\n * {@link https://cr.yp.to/chacha.html | website}.\n *\n * @module\n */\nimport { createCipher, createPRG, rotl } from \"./_arx.js\";\nimport { poly1305 } from \"./_poly1305.js\";\nimport { abytes, clean, equalBytes, getOutput, isLE, swap32IfBE, u64Lengths, wrapCipher, } from \"./utils.js\";\n/**\n * ChaCha core function. Uses an unrolled loop (chachaCore, hchacha) - 4x\n * faster than a simple loop, but larger & harder to read. A simple-loop\n * reference version lives in `test/misc/micro-ciphers.ts`;\n * `test/arx.test.ts` keeps the two aligned.\n * The specific implementation is selected in `createCipher` below.\n */\n/** RFC 8439 §2.3 block core for `state = constants | key | counter | nonce`. */\n// prettier-ignore\nfunction chachaCore(s, k, n, out, cnt, rounds = 20) {\n let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Nonce Nonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 7);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 7);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 7);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 8);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 7);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 7);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 7);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 7);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 16);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 7);\n }\n // RFC 8439 §2.3 / §2.3.1: add the original state words back in state order.\n let oi = 0;\n out[oi++] = (y00 + x00) | 0;\n out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0;\n out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0;\n out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0;\n out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0;\n out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0;\n out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0;\n out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0;\n out[oi++] = (y15 + x15) | 0;\n}\n/**\n * hchacha hashes key and nonce into key' and nonce' for xchacha20.\n * Algorithmically identical to `hchacha_small` from `test/misc/micro-ciphers.ts`,\n * but this exported path normalizes word order on big-endian hosts.\n * Reuses `chachaCore` and subtracts its feed-forward, keeping the hot per-block\n * path untouched.\n * @param s - Sigma constants as 32-bit words.\n * @param k - Key words.\n * @param i - Nonce-prefix words.\n * @param out - Output buffer for the derived subkey.\n * @example\n * Derives the XChaCha subkey from sigma, key, and nonce-prefix words.\n *\n * ```ts\n * const sigma = new Uint32Array(4);\n * const key = new Uint32Array(8);\n * const nonce = new Uint32Array(4);\n * const out = new Uint32Array(8);\n * hchacha(sigma, key, nonce, out);\n * ```\n */\n// prettier-ignore\nexport function hchacha(s, k, i, out) {\n // Runs the shared chachaCore permutation, then subtracts the RFC 8439 feed-forward\n // it applies, recovering the raw permutation words hchacha needs.\n // LE hosts read the caller arrays in place (no copies); BE hosts get\n // byte-swapped scratch copies, wiped before returning.\n const s2 = isLE ? s : swap32IfBE(s.slice(0, 4));\n const k2 = isLE ? k : swap32IfBE(k.slice(0, 8));\n const i2 = isLE ? i : swap32IfBE(i.slice(0, 4));\n const t = new Uint32Array(16);\n chachaCore(s2, k2, i2.subarray(1), t, i2[0]);\n let oi = 0;\n out[oi++] = (t[0] - s2[0]) | 0;\n out[oi++] = (t[1] - s2[1]) | 0;\n out[oi++] = (t[2] - s2[2]) | 0;\n out[oi++] = (t[3] - s2[3]) | 0;\n out[oi++] = (t[12] - i2[0]) | 0;\n out[oi++] = (t[13] - i2[1]) | 0;\n out[oi++] = (t[14] - i2[2]) | 0;\n out[oi++] = (t[15] - i2[3]) | 0;\n swap32IfBE(out);\n if (!isLE)\n clean(s2, k2, i2);\n clean(t);\n}\n/**\n * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.\n * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public\n * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`\n * near `MAX_COUNTER` for the full counter-policy rationale.\n * @param key - 16-byte or 32-byte key.\n * @param nonce - 8-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce.\n *\n * ```ts\n * import { chacha20orig } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(8);\n * chacha20orig(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n allowShortKeys: true,\n});\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce.\n *\n * ```ts\n * import { chacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha20(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\n/**\n * XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).\n * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.\n * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public\n * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`\n * near `MAX_COUNTER` for the full counter-policy rationale.\n * @param key - 32-byte key.\n * @param nonce - 24-byte extended nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce.\n *\n * ```ts\n * import { xchacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(24);\n * xchacha20(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n extendNonceFn: hchacha,\n allowShortKeys: false,\n});\n/**\n * Reduced 8-round chacha, described in original paper.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce.\n *\n * ```ts\n * import { chacha8 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha8(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 8,\n});\n/**\n * Reduced 12-round chacha, described in original paper.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param data - Input bytes to xor with the keystream.\n * @param output - Optional destination buffer.\n * @param counter - Initial block counter.\n * @returns Encrypted or decrypted bytes.\n * @example\n * Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce.\n *\n * ```ts\n * import { chacha12 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * chacha12(key, nonce, new Uint8Array(4));\n * ```\n */\nexport const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 12,\n});\n// Test-only hook: exposes the unrolled production core so tests can compare it\n// with the simple/reference core from `test/misc/micro-ciphers.ts`.\nexport const __TESTS = /* @__PURE__ */ Object.freeze({ chachaCore });\n// RFC 8439 §2.8.1 pad16(x): shared zero block for AAD/ciphertext padding.\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// RFC 8439 §2.8 / §2.8.1: aligned inputs add nothing, otherwise append 16-(len%16) zero bytes.\nconst updatePadded = (h, msg) => {\n h.update(msg);\n const leftover = msg.length % 16;\n if (leftover)\n h.update(ZEROS16.subarray(leftover));\n};\n// RFC 8439 §2.6.1 poly1305_key_gen returns `block[0..31]`, so AEAD key\n// generation only needs 32 zero bytes.\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(fn, key, nonce, ciphertext, AAD) {\n if (AAD !== undefined)\n abytes(AAD, undefined, 'AAD');\n // RFC 8439 §2.6 / §2.8: derive the Poly1305 one-time key from counter 0,\n // then MAC AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || len(AAD) || len(ciphertext).\n const authKey = fn(key, nonce, ZEROS32);\n const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);\n // Methods below can be replaced with\n // `return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)`\n // from `test/misc/micro-ciphers.ts`.\n const h = poly1305.create(authKey);\n if (AAD)\n updatePadded(h, AAD);\n updatePadded(h, ciphertext);\n h.update(lengths);\n const res = h.digest();\n clean(authKey, lengths);\n return res;\n}\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them, but it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {\n // This borrows caller key/nonce/AAD buffers by reference; mutating them after construction\n // changes future encrypt/decrypt results.\n const tagLength = 16;\n return {\n encrypt(plaintext, output) {\n const plength = plaintext.length;\n output = getOutput(plength + tagLength, output, false);\n output.set(plaintext);\n const oPlain = output.subarray(0, -tagLength);\n // RFC 8439 §2.8: payload encryption starts at counter 1 because counter 0 produced the OTK.\n xorStream(key, nonce, oPlain, oPlain, 1);\n const tag = computeTag(xorStream, key, nonce, oPlain, AAD);\n output.set(tag, plength); // append tag\n clean(tag);\n return output;\n },\n decrypt(ciphertext, output) {\n output = getOutput(ciphertext.length - tagLength, output, false);\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n // RFC 8439 §2.8 / §4: authenticate ciphertext before decrypting it, and compare tags with\n // the constant-time equalBytes() helper rather than decrypting speculative plaintext first.\n if (!equalBytes(passedTag, tag)) {\n clean(tag);\n throw new Error('invalid tag');\n }\n output.set(ciphertext.subarray(0, -tagLength));\n // Actual decryption\n xorStream(key, nonce, output, output, 1); // start stream with i=1\n clean(tag);\n return output;\n },\n };\n};\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n *\n * Unsafe to use random nonces under the same key, due to collision chance.\n * Prefer XChaCha instead.\n * @param key - 32-byte key.\n * @param nonce - 12-byte nonce.\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and nonce.\n *\n * ```ts\n * import { chacha20poly1305 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(12);\n * const aad = new TextEncoder().encode('session metadata');\n * const cipher = chacha20poly1305(key, nonce, aad);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16, withAAD: true }, \n/* @__PURE__ */ _poly1305_aead(chacha20));\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n *\n * Can be safely used with random nonces (CSPRNG).\n * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.\n * @param key - 32-byte key.\n * @param nonce - 24-byte nonce.\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce.\n *\n * ```ts\n * import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const nonce = randomBytes(24);\n * const aad = new TextEncoder().encode('session metadata');\n * const cipher = xchacha20poly1305(key, nonce, aad);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16, withAAD: true }, \n/* @__PURE__ */ _poly1305_aead(xchacha20));\n/**\n * Chacha20 CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is.\n * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,\n * only 32 random bytes are mixed into the 40-byte state.\n * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.\n * @example\n * Seeds the test-only ChaCha20 DRBG from fresh entropy.\n *\n * ```ts\n * import { rngChacha20 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const prg = rngChacha20(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngChacha20 = /* @__PURE__ */ createPRG(chacha20orig, 64, 32, 8);\n/**\n * Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * Faster than `rngChacha20`.\n * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,\n * only 32 random bytes are mixed into the 44-byte state.\n * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.\n * @example\n * Seeds the faster test-only ChaCha8 DRBG from fresh entropy.\n *\n * ```ts\n * import { rngChacha8 } from '@noble/ciphers/chacha.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const prg = rngChacha8(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngChacha8 = /* @__PURE__ */ createPRG(chacha8, 64, 32, 12);\n","import { signJWT, symmetricDecodeJWT, symmetricEncodeJWT, verifyJWT } from \"./jwt.mjs\";\nimport { constantTimeEqual } from \"./buffer.mjs\";\nimport { hashPassword, verifyPassword } from \"./password.mjs\";\nimport { generateRandomString } from \"./random.mjs\";\nimport { getWebcryptoSubtle } from \"@better-auth/utils\";\nimport { createHash } from \"@better-auth/utils/hash\";\nimport { xchacha20poly1305 } from \"@noble/ciphers/chacha.js\";\nimport { bytesToHex, hexToBytes, managedNonce, utf8ToBytes } from \"@noble/ciphers/utils.js\";\n//#region src/crypto/index.ts\nconst algorithm = {\n\tname: \"HMAC\",\n\thash: \"SHA-256\"\n};\nconst ENVELOPE_PREFIX = \"$ba$\";\nfunction parseEnvelope(data) {\n\tif (!data.startsWith(ENVELOPE_PREFIX)) return null;\n\tconst firstSep = 4;\n\tconst secondSep = data.indexOf(\"$\", firstSep);\n\tif (secondSep === -1) return null;\n\tconst version = parseInt(data.slice(firstSep, secondSep), 10);\n\tif (!Number.isInteger(version) || version < 0) return null;\n\treturn {\n\t\tversion,\n\t\tciphertext: data.slice(secondSep + 1)\n\t};\n}\nfunction formatEnvelope(version, ciphertext) {\n\treturn `${ENVELOPE_PREFIX}${version}$${ciphertext}`;\n}\nasync function rawEncrypt(secret, data) {\n\tconst keyAsBytes = await createHash(\"SHA-256\").digest(secret);\n\tconst dataAsBytes = utf8ToBytes(data);\n\treturn bytesToHex(managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes)).encrypt(dataAsBytes));\n}\nasync function rawDecrypt(secret, hex) {\n\tconst keyAsBytes = await createHash(\"SHA-256\").digest(secret);\n\tconst dataAsBytes = hexToBytes(hex);\n\tconst chacha = managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes));\n\treturn new TextDecoder().decode(chacha.decrypt(dataAsBytes));\n}\nconst symmetricEncrypt = async ({ key, data }) => {\n\tif (typeof key === \"string\") return rawEncrypt(key, data);\n\tconst secret = key.keys.get(key.currentVersion);\n\tif (!secret) throw new Error(`Secret version ${key.currentVersion} not found in keys`);\n\tconst ciphertext = await rawEncrypt(secret, data);\n\treturn formatEnvelope(key.currentVersion, ciphertext);\n};\nconst symmetricDecrypt = async ({ key, data }) => {\n\tif (typeof key === \"string\") return rawDecrypt(key, data);\n\tconst envelope = parseEnvelope(data);\n\tif (envelope) {\n\t\tconst secret = key.keys.get(envelope.version);\n\t\tif (!secret) throw new Error(`Secret version ${envelope.version} not found in keys (key may have been retired)`);\n\t\treturn rawDecrypt(secret, envelope.ciphertext);\n\t}\n\tif (key.legacySecret) return rawDecrypt(key.legacySecret, data);\n\tthrow new Error(\"Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.\");\n};\nconst getCryptoKey = async (secret) => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await getWebcryptoSubtle().importKey(\"raw\", secretBuf, algorithm, false, [\"sign\", \"verify\"]);\n};\nconst makeSignature = async (value, secret) => {\n\tconst key = await getCryptoKey(secret);\n\tconst signature = await getWebcryptoSubtle().sign(algorithm.name, key, new TextEncoder().encode(value));\n\treturn btoa(String.fromCharCode(...new Uint8Array(signature)));\n};\n//#endregion\nexport { constantTimeEqual, formatEnvelope, generateRandomString, getCryptoKey, hashPassword, makeSignature, parseEnvelope, signJWT, symmetricDecodeJWT, symmetricDecrypt, symmetricEncodeJWT, symmetricEncrypt, verifyJWT, verifyPassword };\n","import { getWebcryptoSubtle } from \"@better-auth/utils\";\n//#region src/crypto.ts\nconst algorithm = {\n\tname: \"HMAC\",\n\thash: \"SHA-256\"\n};\nconst getCryptoKey = async (secret) => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await getWebcryptoSubtle().importKey(\"raw\", secretBuf, algorithm, false, [\"sign\", \"verify\"]);\n};\nconst verifySignature = async (base64Signature, value, secret) => {\n\ttry {\n\t\tconst signatureBinStr = atob(base64Signature);\n\t\tconst signature = new Uint8Array(signatureBinStr.length);\n\t\tfor (let i = 0, len = signatureBinStr.length; i < len; i++) signature[i] = signatureBinStr.charCodeAt(i);\n\t\treturn await getWebcryptoSubtle().verify(algorithm, secret, signature, new TextEncoder().encode(value));\n\t} catch {\n\t\treturn false;\n\t}\n};\nconst makeSignature = async (value, secret) => {\n\tconst key = await getCryptoKey(secret);\n\tconst signature = await getWebcryptoSubtle().sign(algorithm.name, key, new TextEncoder().encode(value));\n\treturn btoa(String.fromCharCode(...new Uint8Array(signature)));\n};\nconst signCookieValue = async (value, secret) => {\n\tconst signature = await makeSignature(value, secret);\n\tvalue = `${value}.${signature}`;\n\tvalue = encodeURIComponent(value);\n\treturn value;\n};\n//#endregion\nexport { getCryptoKey, signCookieValue, verifySignature };\n\n//# sourceMappingURL=crypto.mjs.map","import { APIError } from \"./error.mjs\";\n//#region src/utils.ts\nconst jsonContentTypeRegex = /^application\\/([a-z0-9.+-]*\\+)?json/i;\nasync function getBody(request, allowedMediaTypes) {\n\tconst contentType = request.headers.get(\"content-type\") || \"\";\n\tconst normalizedContentType = contentType.toLowerCase();\n\tif (!request.body) return;\n\tif (allowedMediaTypes && allowedMediaTypes.length > 0) {\n\t\tif (!allowedMediaTypes.some((allowed) => {\n\t\t\tconst normalizedContentTypeBase = normalizedContentType.split(\";\")[0].trim();\n\t\t\tconst normalizedAllowed = allowed.toLowerCase().trim();\n\t\t\treturn normalizedContentTypeBase === normalizedAllowed || normalizedContentTypeBase.includes(normalizedAllowed);\n\t\t})) {\n\t\t\tif (!normalizedContentType) throw new APIError(415, {\n\t\t\t\tmessage: `Content-Type is required. Allowed types: ${allowedMediaTypes.join(\", \")}`,\n\t\t\t\tcode: \"UNSUPPORTED_MEDIA_TYPE\"\n\t\t\t});\n\t\t\tthrow new APIError(415, {\n\t\t\t\tmessage: `Content-Type \"${contentType}\" is not allowed. Allowed types: ${allowedMediaTypes.join(\", \")}`,\n\t\t\t\tcode: \"UNSUPPORTED_MEDIA_TYPE\"\n\t\t\t});\n\t\t}\n\t}\n\tif (jsonContentTypeRegex.test(normalizedContentType)) try {\n\t\treturn await request.json();\n\t} catch (e) {\n\t\tif (e instanceof SyntaxError) throw new APIError(400, {\n\t\t\tmessage: \"Invalid JSON in request body\",\n\t\t\tcode: \"BAD_REQUEST\"\n\t\t});\n\t\tthrow e;\n\t}\n\tif (normalizedContentType.includes(\"application/x-www-form-urlencoded\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value.toString();\n\t\t});\n\t\treturn result;\n\t}\n\tif (normalizedContentType.includes(\"multipart/form-data\")) {\n\t\tconst formData = await request.formData();\n\t\tconst result = {};\n\t\tformData.forEach((value, key) => {\n\t\t\tresult[key] = value;\n\t\t});\n\t\treturn result;\n\t}\n\tif (normalizedContentType.includes(\"text/plain\")) return await request.text();\n\tif (normalizedContentType.includes(\"application/octet-stream\")) return await request.arrayBuffer();\n\tif (normalizedContentType.includes(\"application/pdf\") || normalizedContentType.includes(\"image/\") || normalizedContentType.includes(\"video/\")) return await request.blob();\n\tif (normalizedContentType.includes(\"application/stream\") || request.body instanceof ReadableStream) return request.body;\n\treturn await request.text();\n}\nfunction isAPIError(error) {\n\treturn error instanceof APIError || error?.name === \"APIError\";\n}\nfunction tryDecode(str) {\n\ttry {\n\t\treturn str.includes(\"%\") ? decodeURIComponent(str) : str;\n\t} catch {\n\t\treturn str;\n\t}\n}\nasync function tryCatch(promise) {\n\ttry {\n\t\treturn {\n\t\t\tdata: await promise,\n\t\t\terror: null\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tdata: null,\n\t\t\terror\n\t\t};\n\t}\n}\n/**\n* Check if an object is a `Request`\n* - `instanceof`: works for native Request instances\n* - `toString`: handles where instanceof check fails but the object is still a valid Request\n*/\nfunction isRequest(obj) {\n\treturn obj instanceof Request || Object.prototype.toString.call(obj) === \"[object Request]\";\n}\n//#endregion\nexport { getBody, isAPIError, isRequest, tryCatch, tryDecode };\n\n//# sourceMappingURL=utils.mjs.map","import { signCookieValue } from \"./crypto.mjs\";\nimport { tryDecode } from \"./utils.mjs\";\n//#region src/cookies.ts\nconst COOKIE_PREFIXES = {\n\tsecure: \"__Secure-\",\n\thost: \"__Host-\"\n};\nconst getCookieKey = (key, prefix) => {\n\tif (!prefix) return key;\n\tif (prefix !== \"secure\" && prefix !== \"host\") return void 0;\n\treturn COOKIE_PREFIXES[prefix] + key;\n};\n/**\n* Parse an HTTP Cookie header string and returning an object of all cookie\n* name-value pairs.\n*\n* Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts\n*\n* @param str the string representing a `Cookie` header value\n*/\nfunction parseCookies(str) {\n\tif (typeof str !== \"string\") throw new TypeError(\"argument str must be a string\");\n\tconst cookies = /* @__PURE__ */ new Map();\n\tlet index = 0;\n\twhile (index < str.length) {\n\t\tconst eqIdx = str.indexOf(\"=\", index);\n\t\tif (eqIdx === -1) break;\n\t\tlet endIdx = str.indexOf(\";\", index);\n\t\tif (endIdx === -1) endIdx = str.length;\n\t\telse if (endIdx < eqIdx) {\n\t\t\tindex = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tconst key = str.slice(index, eqIdx).trim();\n\t\tif (!cookies.has(key)) {\n\t\t\tlet val = str.slice(eqIdx + 1, endIdx).trim();\n\t\t\tif (val.codePointAt(0) === 34) val = val.slice(1, -1);\n\t\t\tcookies.set(key, tryDecode(val));\n\t\t}\n\t\tindex = endIdx + 1;\n\t}\n\treturn cookies;\n}\nfunction resolveCookie(name, value, options = {}) {\n\tconst resolvedName = getCookieKey(name, options.prefix) ?? name;\n\tconst resolvedOptions = { ...options };\n\tconst lowerName = resolvedName.toLowerCase();\n\tif (lowerName.startsWith(\"__host-\")) {\n\t\tresolvedOptions.secure = true;\n\t\tresolvedOptions.path = \"/\";\n\t\tresolvedOptions.domain = void 0;\n\t} else if (lowerName.startsWith(\"__secure-\")) resolvedOptions.secure = true;\n\tif (resolvedOptions.partitioned === true || resolvedOptions.sameSite?.toLowerCase() === \"none\") resolvedOptions.secure = true;\n\treturn {\n\t\tname: resolvedName,\n\t\tvalue,\n\t\toptions: resolvedOptions\n\t};\n}\nfunction serializeCookieValue({ name, value, options }) {\n\tlet cookie = `${name}=${value}`;\n\tif (typeof options.maxAge === \"number\" && options.maxAge >= 0) {\n\t\tif (options.maxAge > 3456e4) throw new Error(\"Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.\");\n\t\tcookie += `; Max-Age=${Math.floor(options.maxAge)}`;\n\t}\n\tif (options.domain) cookie += `; Domain=${options.domain}`;\n\tif (options.path) cookie += `; Path=${options.path}`;\n\tif (options.expires) {\n\t\tif (options.expires.getTime() - Date.now() > 3456e7) throw new Error(\"Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.\");\n\t\tcookie += `; Expires=${options.expires.toUTCString()}`;\n\t}\n\tif (options.httpOnly) cookie += \"; HttpOnly\";\n\tif (options.secure) cookie += \"; Secure\";\n\tif (options.sameSite) cookie += `; SameSite=${options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1)}`;\n\tif (options.partitioned) cookie += \"; Partitioned\";\n\treturn cookie;\n}\nconst serializeCookie = (key, value, opt) => {\n\tvalue = encodeURIComponent(value);\n\treturn serializeCookieValue(resolveCookie(key, value, opt));\n};\nconst serializeSignedCookie = async (key, value, secret, opt) => {\n\tvalue = await signCookieValue(value, secret);\n\treturn serializeCookieValue(resolveCookie(key, value, opt));\n};\n//#endregion\nexport { getCookieKey, parseCookies, serializeCookie, serializeSignedCookie };\n\n//# sourceMappingURL=cookies.mjs.map","//#region src/validator.ts\n/**\n* Runs validation on body and query\n* @returns error and data object\n*/\nasync function runValidation(options, context = {}) {\n\tconst request = {\n\t\tbody: context.body,\n\t\tquery: context.query\n\t};\n\tif (options.body) {\n\t\tconst result = await options.body[\"~standard\"].validate(context.body);\n\t\tif (result.issues) return {\n\t\t\tdata: null,\n\t\t\terror: fromError(result.issues, \"body\")\n\t\t};\n\t\trequest.body = result.value;\n\t}\n\tif (options.query) {\n\t\tconst result = await options.query[\"~standard\"].validate(context.query);\n\t\tif (result.issues) return {\n\t\t\tdata: null,\n\t\t\terror: fromError(result.issues, \"query\")\n\t\t};\n\t\trequest.query = result.value;\n\t}\n\tif (options.requireHeaders && !context.headers) return {\n\t\tdata: null,\n\t\terror: {\n\t\t\tmessage: \"Headers is required\",\n\t\t\tissues: []\n\t\t}\n\t};\n\tif (options.requireRequest && !context.request) return {\n\t\tdata: null,\n\t\terror: {\n\t\t\tmessage: \"Request is required\",\n\t\t\tissues: []\n\t\t}\n\t};\n\treturn {\n\t\tdata: request,\n\t\terror: null\n\t};\n}\nfunction fromError(error, validating) {\n\treturn {\n\t\tmessage: error.map((e) => {\n\t\t\treturn `[${e.path?.length ? `${validating}.` + e.path.map((x) => typeof x === \"object\" ? x.key : x).join(\".\") : validating}] ${e.message}`;\n\t\t}).join(\"; \"),\n\t\tissues: error\n\t};\n}\n//#endregion\nexport { runValidation };\n\n//# sourceMappingURL=validator.mjs.map","import { getCryptoKey, verifySignature } from \"./crypto.mjs\";\nimport { APIError, ValidationError } from \"./error.mjs\";\nimport { isRequest } from \"./utils.mjs\";\nimport { getCookieKey, parseCookies, serializeCookie, serializeSignedCookie } from \"./cookies.mjs\";\nimport { runValidation } from \"./validator.mjs\";\n//#region src/context.ts\nconst createInternalContext = async (context, { options, path }) => {\n\tconst headers = new Headers();\n\tlet responseStatus = void 0;\n\tconst { data, error } = await runValidation(options, context);\n\tif (error) throw new ValidationError(error.message, error.issues);\n\tconst requestHeaders = context.headers !== void 0 ? context.headers instanceof Headers ? context.headers : new Headers(context.headers) : \"request\" in context && isRequest(context.request) ? context.request.headers : null;\n\tconst requestCookies = requestHeaders?.get(\"cookie\");\n\tconst parsedCookies = requestCookies ? parseCookies(requestCookies) : void 0;\n\tconst internalContext = {\n\t\t...context,\n\t\tbody: data.body,\n\t\tquery: data.query,\n\t\tpath: context.path || path || \"virtual:\",\n\t\tcontext: \"context\" in context && context.context ? context.context : {},\n\t\treturned: void 0,\n\t\theaders: context?.headers,\n\t\trequest: context?.request,\n\t\tparams: \"params\" in context ? context.params : void 0,\n\t\tmethod: context.method ?? (Array.isArray(options.method) ? options.method[0] : options.method === \"*\" ? \"GET\" : options.method),\n\t\tsetHeader: (key, value) => {\n\t\t\theaders.set(key, value);\n\t\t},\n\t\tgetHeader: (key) => {\n\t\t\tif (!requestHeaders) return null;\n\t\t\treturn requestHeaders.get(key);\n\t\t},\n\t\tgetCookie: (key, prefix) => {\n\t\t\tconst finalKey = getCookieKey(key, prefix);\n\t\t\tif (!finalKey) return null;\n\t\t\treturn parsedCookies?.get(finalKey) || null;\n\t\t},\n\t\tgetSignedCookie: async (key, secret, prefix) => {\n\t\t\tconst finalKey = getCookieKey(key, prefix);\n\t\t\tif (!finalKey) return null;\n\t\t\tconst value = parsedCookies?.get(finalKey);\n\t\t\tif (!value) return null;\n\t\t\tconst signatureStartPos = value.lastIndexOf(\".\");\n\t\t\tif (signatureStartPos < 1) return null;\n\t\t\tconst signedValue = value.substring(0, signatureStartPos);\n\t\t\tconst signature = value.substring(signatureStartPos + 1);\n\t\t\tif (signature.length !== 44 || !signature.endsWith(\"=\")) return null;\n\t\t\treturn await verifySignature(signature, signedValue, await getCryptoKey(secret)) ? signedValue : false;\n\t\t},\n\t\tsetCookie: (key, value, options) => {\n\t\t\tconst cookie = serializeCookie(key, value, options);\n\t\t\theaders.append(\"set-cookie\", cookie);\n\t\t\treturn cookie;\n\t\t},\n\t\tsetSignedCookie: async (key, value, secret, options) => {\n\t\t\tconst cookie = await serializeSignedCookie(key, value, secret, options);\n\t\t\theaders.append(\"set-cookie\", cookie);\n\t\t\treturn cookie;\n\t\t},\n\t\tredirect: (url) => {\n\t\t\theaders.set(\"location\", url);\n\t\t\treturn new APIError(\"FOUND\", void 0, headers);\n\t\t},\n\t\terror: (status, body, headers) => {\n\t\t\treturn new APIError(status, body, headers);\n\t\t},\n\t\tsetStatus: (status) => {\n\t\t\tresponseStatus = status;\n\t\t},\n\t\tjson: (json, routerResponse) => {\n\t\t\tif (!context.asResponse) return json;\n\t\t\treturn {\n\t\t\t\tbody: routerResponse?.body || json,\n\t\t\t\trouterResponse,\n\t\t\t\t_flag: \"json\"\n\t\t\t};\n\t\t},\n\t\tresponseHeaders: headers,\n\t\tget responseStatus() {\n\t\t\treturn responseStatus;\n\t\t}\n\t};\n\tfor (const middleware of options.use || []) {\n\t\tconst response = await middleware({\n\t\t\t...internalContext,\n\t\t\treturnHeaders: true,\n\t\t\tasResponse: false\n\t\t});\n\t\tif (response.response) Object.assign(internalContext.context, response.response);\n\t\t/**\n\t\t* Apply headers from the middleware to the endpoint headers\n\t\t*/\n\t\tif (response.headers) response.headers.forEach((value, key) => {\n\t\t\tinternalContext.responseHeaders.set(key, value);\n\t\t});\n\t}\n\treturn internalContext;\n};\n//#endregion\nexport { createInternalContext };\n\n//# sourceMappingURL=context.mjs.map","import { isAPIError } from \"./utils.mjs\";\n//#region src/to-response.ts\nfunction isJSONSerializable(value) {\n\tif (value === void 0) return false;\n\tconst t = typeof value;\n\tif (t === \"string\" || t === \"number\" || t === \"boolean\" || t === null) return true;\n\tif (t !== \"object\") return false;\n\tif (Array.isArray(value)) return true;\n\tif (value.buffer) return false;\n\treturn value.constructor && value.constructor.name === \"Object\" || typeof value.toJSON === \"function\";\n}\nfunction safeStringify(obj) {\n\tconst parents = /* @__PURE__ */ new WeakMap();\n\tconst ids = /* @__PURE__ */ new WeakMap();\n\tlet id = 0;\n\tconst isAncestor = (value, holder) => {\n\t\tlet curr = holder;\n\t\twhile (curr) {\n\t\t\tif (curr === value) return true;\n\t\t\tcurr = parents.get(curr);\n\t\t}\n\t\treturn false;\n\t};\n\treturn JSON.stringify(obj, function(_key, value) {\n\t\tif (typeof value === \"bigint\") return value.toString();\n\t\tif (typeof value === \"object\" && value !== null) {\n\t\t\tif (isAncestor(value, this)) return `[Circular ref-${ids.get(value)}]`;\n\t\t\tparents.set(value, this);\n\t\t\tif (!ids.has(value)) ids.set(value, id++);\n\t\t}\n\t\treturn value;\n\t});\n}\nfunction isJSONResponse(value) {\n\tif (!value || typeof value !== \"object\") return false;\n\treturn \"_flag\" in value && value._flag === \"json\";\n}\n/**\n* Headers that MUST be stripped when building an HTTP response from\n* arbitrary header input. These are request-only, hop-by-hop, or\n* transport-managed headers that cause protocol violations when present\n* on responses (e.g. Content-Length mismatch → net::ERR_CONTENT_LENGTH_MISMATCH).\n*\n* Sources:\n* - RFC 9110 §10.1 (Request Context Fields)\n* - RFC 9110 §7.6.1 (Connection / hop-by-hop)\n* - RFC 9110 §11.6-7 (Authentication credentials)\n* - RFC 9110 §12.5 (Content negotiation)\n* - RFC 9110 §13.1 (Conditional request headers)\n* - RFC 9110 §14.2 (Range requests)\n* - RFC 6265 §5.4 (Cookie)\n* - RFC 6454 (Origin)\n*/\nconst REQUEST_ONLY_HEADERS = /* @__PURE__ */ new Set([\n\t\"host\",\n\t\"user-agent\",\n\t\"referer\",\n\t\"from\",\n\t\"expect\",\n\t\"authorization\",\n\t\"proxy-authorization\",\n\t\"cookie\",\n\t\"origin\",\n\t\"accept-charset\",\n\t\"accept-encoding\",\n\t\"accept-language\",\n\t\"if-match\",\n\t\"if-none-match\",\n\t\"if-modified-since\",\n\t\"if-unmodified-since\",\n\t\"if-range\",\n\t\"range\",\n\t\"max-forwards\",\n\t\"connection\",\n\t\"keep-alive\",\n\t\"transfer-encoding\",\n\t\"te\",\n\t\"upgrade\",\n\t\"trailer\",\n\t\"proxy-connection\",\n\t\"content-length\"\n]);\nfunction stripRequestOnlyHeaders(headers) {\n\tfor (const name of REQUEST_ONLY_HEADERS) headers.delete(name);\n}\n/**\n* Copy headers from `source` into `target`. `Set-Cookie` is appended (one\n* header per cookie) because RFC 9110 §5.3 notes it cannot be combined\n* into a single comma-separated value; other headers are set (replace).\n*/\nfunction copyHeaders(target, source) {\n\tif (!source) return;\n\tfor (const [key, value] of new Headers(source).entries()) if (key.toLowerCase() === \"set-cookie\") target.append(key, value);\n\telse target.set(key, value);\n}\nfunction toResponse(data, init) {\n\tif (data instanceof Response) {\n\t\tif (init?.headers) {\n\t\t\tconst safeHeaders = new Headers(init.headers);\n\t\t\tstripRequestOnlyHeaders(safeHeaders);\n\t\t\tcopyHeaders(data.headers, safeHeaders);\n\t\t}\n\t\treturn data;\n\t}\n\tif (isJSONResponse(data)) {\n\t\tconst body = data.body;\n\t\tconst routerResponse = data.routerResponse;\n\t\tif (routerResponse instanceof Response) return routerResponse;\n\t\tconst headers = new Headers();\n\t\tcopyHeaders(headers, routerResponse?.headers);\n\t\tcopyHeaders(headers, data.headers);\n\t\tif (init?.headers) {\n\t\t\tconst safeHeaders = new Headers(init.headers);\n\t\t\tstripRequestOnlyHeaders(safeHeaders);\n\t\t\tcopyHeaders(headers, safeHeaders);\n\t\t}\n\t\theaders.set(\"Content-Type\", \"application/json\");\n\t\tconst status = data.status ?? init?.status ?? routerResponse?.status;\n\t\tconst statusText = init?.statusText ?? routerResponse?.statusText;\n\t\treturn new Response(JSON.stringify(body), {\n\t\t\t...routerResponse,\n\t\t\theaders,\n\t\t\t...status === void 0 ? {} : { status },\n\t\t\t...statusText === void 0 ? {} : { statusText }\n\t\t});\n\t}\n\tif (isAPIError(data)) return toResponse(data.body, {\n\t\tstatus: init?.status ?? data.statusCode,\n\t\tstatusText: data.status.toString(),\n\t\theaders: init?.headers || data.headers\n\t});\n\tlet body = data;\n\tconst headers = new Headers(init?.headers);\n\tstripRequestOnlyHeaders(headers);\n\tif (!data) {\n\t\tif (data === null) body = JSON.stringify(null);\n\t\theaders.set(\"content-type\", \"application/json\");\n\t} else if (typeof data === \"string\") {\n\t\tbody = data;\n\t\theaders.set(\"Content-Type\", \"text/plain\");\n\t} else if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {\n\t\tbody = data;\n\t\theaders.set(\"Content-Type\", \"application/octet-stream\");\n\t} else if (data instanceof Blob) {\n\t\tbody = data;\n\t\theaders.set(\"Content-Type\", data.type || \"application/octet-stream\");\n\t} else if (data instanceof FormData) body = data;\n\telse if (data instanceof URLSearchParams) {\n\t\tbody = data;\n\t\theaders.set(\"Content-Type\", \"application/x-www-form-urlencoded\");\n\t} else if (data instanceof ReadableStream) {\n\t\tbody = data;\n\t\theaders.set(\"Content-Type\", \"application/octet-stream\");\n\t} else if (isJSONSerializable(data)) {\n\t\tbody = safeStringify(data);\n\t\theaders.set(\"Content-Type\", \"application/json\");\n\t}\n\treturn new Response(body, {\n\t\t...init,\n\t\theaders\n\t});\n}\n//#endregion\nexport { toResponse };\n\n//# sourceMappingURL=to-response.mjs.map","import { APIError, BetterCallError, ValidationError } from \"./error.mjs\";\nimport { isAPIError, tryCatch } from \"./utils.mjs\";\nimport { createInternalContext } from \"./context.mjs\";\nimport { toResponse } from \"./to-response.mjs\";\n//#region src/endpoint.ts\nfunction createEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) {\n\tconst path = typeof pathOrOptions === \"string\" ? pathOrOptions : void 0;\n\tconst options = typeof handlerOrOptions === \"object\" ? handlerOrOptions : pathOrOptions;\n\tconst handler = typeof handlerOrOptions === \"function\" ? handlerOrOptions : handlerOrNever;\n\tif ((options.method === \"GET\" || options.method === \"HEAD\") && options.body) throw new BetterCallError(\"Body is not allowed with GET or HEAD methods\");\n\tif (path && /\\/{2,}/.test(path)) throw new BetterCallError(\"Path cannot contain consecutive slashes\");\n\tconst internalHandler = async (...inputCtx) => {\n\t\tconst context = inputCtx[0] || {};\n\t\tconst { data: internalContext, error: validationError } = await tryCatch(createInternalContext(context, {\n\t\t\toptions,\n\t\t\tpath\n\t\t}));\n\t\tif (validationError) {\n\t\t\tif (!(validationError instanceof ValidationError)) throw validationError;\n\t\t\tif (options.onValidationError) await options.onValidationError({\n\t\t\t\tmessage: validationError.message,\n\t\t\t\tissues: validationError.issues\n\t\t\t});\n\t\t\tthrow new APIError(400, {\n\t\t\t\tmessage: validationError.message,\n\t\t\t\tcode: \"VALIDATION_ERROR\"\n\t\t\t});\n\t\t}\n\t\tconst response = await handler(internalContext).catch(async (e) => {\n\t\t\tif (isAPIError(e)) {\n\t\t\t\tconst onAPIError = options.onAPIError;\n\t\t\t\tif (onAPIError) await onAPIError(e);\n\t\t\t\tif (context.asResponse) return e;\n\t\t\t}\n\t\t\tthrow e;\n\t\t});\n\t\tconst headers = internalContext.responseHeaders;\n\t\tconst status = internalContext.responseStatus;\n\t\treturn context.asResponse ? toResponse(response, status === void 0 ? { headers } : {\n\t\t\theaders,\n\t\t\tstatus\n\t\t}) : context.returnHeaders ? context.returnStatus ? {\n\t\t\theaders,\n\t\t\tresponse,\n\t\t\tstatus\n\t\t} : {\n\t\t\theaders,\n\t\t\tresponse\n\t\t} : context.returnStatus ? {\n\t\t\tresponse,\n\t\t\tstatus\n\t\t} : response;\n\t};\n\tinternalHandler.options = options;\n\tinternalHandler.path = path;\n\treturn internalHandler;\n}\nfunction combineMiddleware(local, configured) {\n\treturn [...local ?? [], ...configured ?? []];\n}\ncreateEndpoint.create = (opts) => {\n\tfunction createConfiguredEndpoint(...args) {\n\t\tif (args.length === 3) {\n\t\t\tconst [path, options, handler] = args;\n\t\t\treturn createEndpoint(path, {\n\t\t\t\t...options,\n\t\t\t\tuse: combineMiddleware(options.use, opts?.use)\n\t\t\t}, handler);\n\t\t}\n\t\tconst [options, handler] = args;\n\t\treturn createEndpoint({\n\t\t\t...options,\n\t\t\tuse: combineMiddleware(options.use, opts?.use)\n\t\t}, handler);\n\t}\n\treturn createConfiguredEndpoint;\n};\n//#endregion\nexport { createEndpoint };\n\n//# sourceMappingURL=endpoint.mjs.map","import { kAPIErrorHeaderSymbol } from \"./error.mjs\";\nimport { isAPIError } from \"./utils.mjs\";\nimport { createInternalContext } from \"./context.mjs\";\n//#region src/middleware.ts\nfunction createMiddleware(optionsOrHandler, handler) {\n\tconst internalHandler = async (inputCtx) => {\n\t\tconst context = inputCtx;\n\t\tconst _handler = typeof optionsOrHandler === \"function\" ? optionsOrHandler : handler;\n\t\tconst internalContext = await createInternalContext(context, {\n\t\t\toptions: typeof optionsOrHandler === \"function\" ? {} : optionsOrHandler,\n\t\t\tpath: \"/\"\n\t\t});\n\t\tif (!_handler) throw new Error(\"handler must be defined\");\n\t\ttry {\n\t\t\tconst response = await _handler(internalContext);\n\t\t\tconst headers = internalContext.responseHeaders;\n\t\t\treturn context.returnHeaders ? {\n\t\t\t\theaders,\n\t\t\t\tresponse\n\t\t\t} : response;\n\t\t} catch (e) {\n\t\t\tif (isAPIError(e)) Object.defineProperty(e, kAPIErrorHeaderSymbol, {\n\t\t\t\tenumerable: false,\n\t\t\t\tconfigurable: true,\n\t\t\t\tget() {\n\t\t\t\t\treturn internalContext.responseHeaders;\n\t\t\t\t}\n\t\t\t});\n\t\t\tthrow e;\n\t\t}\n\t};\n\tinternalHandler.options = typeof optionsOrHandler === \"function\" ? {} : optionsOrHandler;\n\treturn internalHandler;\n}\ncreateMiddleware.create = (opts) => {\n\tfunction fn(optionsOrHandler, handler) {\n\t\tif (typeof optionsOrHandler === \"function\") return createMiddleware({ use: opts?.use }, optionsOrHandler);\n\t\tif (!handler) throw new Error(\"Middleware handler is required\");\n\t\treturn createMiddleware({\n\t\t\t...optionsOrHandler,\n\t\t\tmethod: \"*\",\n\t\t\tuse: [...opts?.use || [], ...optionsOrHandler.use || []]\n\t\t}, handler);\n\t}\n\treturn fn;\n};\n//#endregion\nexport { createMiddleware };\n\n//# sourceMappingURL=middleware.mjs.map","import { ZodObject, ZodOptional } from \"zod\";\n//#region src/openapi.ts\nconst paths = {};\nfunction getTypeFromZodType(zodType) {\n\tswitch (zodType.constructor.name) {\n\t\tcase \"ZodString\": return \"string\";\n\t\tcase \"ZodNumber\": return \"number\";\n\t\tcase \"ZodBoolean\": return \"boolean\";\n\t\tcase \"ZodObject\": return \"object\";\n\t\tcase \"ZodArray\": return \"array\";\n\t\tdefault: return \"string\";\n\t}\n}\nfunction getParameters(options) {\n\tconst parameters = [];\n\tif (options.metadata?.openapi?.parameters) {\n\t\tparameters.push(...options.metadata.openapi.parameters);\n\t\treturn parameters;\n\t}\n\tif (options.query instanceof ZodObject) Object.entries(options.query.shape).forEach(([key, value]) => {\n\t\tif (value instanceof ZodObject) parameters.push({\n\t\t\tname: key,\n\t\t\tin: \"query\",\n\t\t\tschema: {\n\t\t\t\ttype: getTypeFromZodType(value),\n\t\t\t\t...\"minLength\" in value && value.minLength ? { minLength: value.minLength } : {},\n\t\t\t\tdescription: value.description\n\t\t\t}\n\t\t});\n\t});\n\treturn parameters;\n}\nfunction getRequestBody(options) {\n\tif (options.metadata?.openapi?.requestBody) return options.metadata.openapi.requestBody;\n\tif (!options.body) return void 0;\n\tif (options.body instanceof ZodObject || options.body instanceof ZodOptional) {\n\t\tconst shape = options.body.shape;\n\t\tif (!shape) return void 0;\n\t\tconst properties = {};\n\t\tconst required = [];\n\t\tObject.entries(shape).forEach(([key, value]) => {\n\t\t\tif (value instanceof ZodObject) {\n\t\t\t\tproperties[key] = {\n\t\t\t\t\ttype: getTypeFromZodType(value),\n\t\t\t\t\tdescription: value.description\n\t\t\t\t};\n\t\t\t\tif (!(value instanceof ZodOptional)) required.push(key);\n\t\t\t}\n\t\t});\n\t\treturn {\n\t\t\trequired: options.body instanceof ZodOptional ? false : options.body ? true : false,\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties,\n\t\t\t\trequired\n\t\t\t} } }\n\t\t};\n\t}\n}\nfunction getResponse(responses) {\n\treturn {\n\t\t\"400\": {\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { message: { type: \"string\" } },\n\t\t\t\trequired: [\"message\"]\n\t\t\t} } },\n\t\t\tdescription: \"Bad Request. Usually due to missing parameters, or invalid parameters.\"\n\t\t},\n\t\t\"401\": {\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { message: { type: \"string\" } },\n\t\t\t\trequired: [\"message\"]\n\t\t\t} } },\n\t\t\tdescription: \"Unauthorized. Due to missing or invalid authentication.\"\n\t\t},\n\t\t\"403\": {\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { message: { type: \"string\" } }\n\t\t\t} } },\n\t\t\tdescription: \"Forbidden. You do not have permission to access this resource or to perform this action.\"\n\t\t},\n\t\t\"404\": {\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { message: { type: \"string\" } }\n\t\t\t} } },\n\t\t\tdescription: \"Not Found. The requested resource was not found.\"\n\t\t},\n\t\t\"429\": {\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { message: { type: \"string\" } }\n\t\t\t} } },\n\t\t\tdescription: \"Too Many Requests. You have exceeded the rate limit. Try again later.\"\n\t\t},\n\t\t\"500\": {\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { message: { type: \"string\" } }\n\t\t\t} } },\n\t\t\tdescription: \"Internal Server Error. This is a problem with the server that you cannot fix.\"\n\t\t},\n\t\t...responses\n\t};\n}\nasync function generator(endpoints, config) {\n\tconst components = { schemas: {} };\n\tObject.entries(endpoints).forEach(([_, value]) => {\n\t\tconst options = value.options;\n\t\tif (!value.path || options.metadata?.SERVER_ONLY) return;\n\t\tif (options.method === \"GET\") paths[value.path] = { get: {\n\t\t\ttags: [\"Default\", ...options.metadata?.openapi?.tags || []],\n\t\t\tdescription: options.metadata?.openapi?.description,\n\t\t\toperationId: options.metadata?.openapi?.operationId,\n\t\t\tsecurity: [{ bearerAuth: [] }],\n\t\t\tparameters: getParameters(options),\n\t\t\tresponses: getResponse(options.metadata?.openapi?.responses)\n\t\t} };\n\t\tif (options.method === \"POST\") {\n\t\t\tconst body = getRequestBody(options);\n\t\t\tpaths[value.path] = { post: {\n\t\t\t\ttags: [\"Default\", ...options.metadata?.openapi?.tags || []],\n\t\t\t\tdescription: options.metadata?.openapi?.description,\n\t\t\t\toperationId: options.metadata?.openapi?.operationId,\n\t\t\t\tsecurity: [{ bearerAuth: [] }],\n\t\t\t\tparameters: getParameters(options),\n\t\t\t\t...body ? { requestBody: body } : { requestBody: { content: { \"application/json\": { schema: {\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {}\n\t\t\t\t} } } } },\n\t\t\t\tresponses: getResponse(options.metadata?.openapi?.responses)\n\t\t\t} };\n\t\t}\n\t});\n\treturn {\n\t\topenapi: \"3.1.1\",\n\t\tinfo: {\n\t\t\ttitle: \"Better Auth\",\n\t\t\tdescription: \"API Reference for your Better Auth Instance\",\n\t\t\tversion: \"1.1.0\"\n\t\t},\n\t\tcomponents,\n\t\tsecurity: [{ apiKeyCookie: [] }],\n\t\tservers: [{ url: config?.url }],\n\t\ttags: [{\n\t\t\tname: \"Default\",\n\t\t\tdescription: \"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin.\"\n\t\t}],\n\t\tpaths\n\t};\n}\nconst getHTML = (apiReference, config) => `<!doctype html>\n<html>\n <head>\n <title>Scalar API Reference</title>\n <meta charset=\"utf-8\" />\n <meta\n name=\"viewport\"\n content=\"width=device-width, initial-scale=1\" />\n </head>\n <body>\n <script\n id=\"api-reference\"\n type=\"application/json\">\n ${JSON.stringify(apiReference)}\n <\\/script>\n\t <script>\n var configuration = {\n\t \tfavicon: ${config?.logo ? `data:image/svg+xml;utf8,${encodeURIComponent(config.logo)}` : void 0} ,\n\t \ttheme: ${config?.theme || \"saturn\"},\n metaData: {\n\t\t\ttitle: ${config?.title || \"Open API Reference\"},\n\t\t\tdescription: ${config?.description || \"Better Call Open API\"},\n\t\t}\n }\n document.getElementById('api-reference').dataset.configuration =\n JSON.stringify(configuration)\n <\\/script>\n\t <script src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\"><\\/script>\n </body>\n</html>`;\n//#endregion\nexport { generator, getHTML };\n\n//# sourceMappingURL=openapi.mjs.map","const NullProtoObj = /* @__PURE__ */ (() => {\n\tconst e = function() {};\n\treturn e.prototype = Object.create(null), Object.freeze(e.prototype), e;\n})();\nfunction createRouter() {\n\treturn {\n\t\troot: { key: \"\" },\n\t\tstatic: new NullProtoObj()\n\t};\n}\nfunction scanFirstGroup(path) {\n\tlet i = 0;\n\tlet depth = 0;\n\tfor (; i < path.length; i++) {\n\t\tconst c = path.charCodeAt(i);\n\t\tif (c === 92) i++;\n\t\telse if (c === 40) depth++;\n\t\telse if (c === 41 && depth > 0) depth--;\n\t\telse if (c === 123 && depth === 0) break;\n\t}\n\tif (i >= path.length) return;\n\tlet j = i + 1;\n\tdepth = 0;\n\tfor (; j < path.length; j++) {\n\t\tconst c = path.charCodeAt(j);\n\t\tif (c === 92) j++;\n\t\telse if (c === 40) depth++;\n\t\telse if (c === 41 && depth > 0) depth--;\n\t\telse if (c === 125 && depth === 0) break;\n\t}\n\tif (j >= path.length) return;\n\tconst mod = path[j + 1];\n\tconst hasMod = mod === \"?\" || mod === \"+\" || mod === \"*\";\n\treturn [\n\t\tpath.slice(0, i),\n\t\tpath.slice(i + 1, j),\n\t\tpath.slice(j + (hasMod ? 2 : 1)),\n\t\thasMod ? mod : void 0\n\t];\n}\nfunction expandGroupDelimiters(path) {\n\tif (!path.includes(\"{\")) return;\n\tconst group = scanFirstGroup(path);\n\tif (!group) return;\n\tconst [pre, body, suf, mod] = group;\n\tif (!mod) return [pre + body + suf];\n\tif (mod === \"?\") return [pre + body + suf, pre + suf];\n\tif (body.includes(\"/\")) throw new Error(\"unsupported group repetition across segments\");\n\treturn [`${pre}(?:${body})${mod}${suf}`];\n}\nconst UNNAMED_GROUP_PREFIX = \"__rou3_unnamed_\";\nconst ESCAPED_GROUP_PREFIX = \"__rou3_esc_\";\nfunction toUnnamedGroupKey(index) {\n\treturn `${UNNAMED_GROUP_PREFIX}${index}`;\n}\nfunction toGroupName(name) {\n\treturn /^(?!__rou3_|_\\d)[A-Za-z_]\\w*$/.test(name) ? name : ESCAPED_GROUP_PREFIX + name.replace(/[_-]/g, (c) => c === \"_\" ? \"__\" : \"_h\");\n}\nfunction fromGroupName(key) {\n\tif (key.charCodeAt(0) !== 95) return key;\n\tif (key.startsWith(\"__rou3_esc_\")) return key.slice(11).replace(/__|_h/g, (c) => c === \"__\" ? \"_\" : \"-\");\n\treturn key.startsWith(\"__rou3_unnamed_\") ? key.slice(15) : key;\n}\nfunction hasSegmentWildcard(segment) {\n\tlet depth = 0;\n\tfor (let i = 0; i < segment.length; i++) {\n\t\tconst ch = segment.charCodeAt(i);\n\t\tif (ch === 92) {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === 40) {\n\t\t\tdepth++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === 41 && depth > 0) {\n\t\t\tdepth--;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === 42 && depth === 0) return true;\n\t}\n\treturn false;\n}\nfunction replaceSegmentWildcards(segment, unnamedStart, toGroupKey = toUnnamedGroupKey) {\n\tlet depth = 0;\n\tlet nextIndex = unnamedStart;\n\tlet replaced = \"\";\n\tfor (let i = 0; i < segment.length; i++) {\n\t\tconst ch = segment.charCodeAt(i);\n\t\tif (ch === 92) {\n\t\t\treplaced += segment[i];\n\t\t\tif (i + 1 < segment.length) replaced += segment[++i];\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === 40) {\n\t\t\tdepth++;\n\t\t\treplaced += segment[i];\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === 41 && depth > 0) {\n\t\t\tdepth--;\n\t\t\treplaced += segment[i];\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === 42 && depth === 0) {\n\t\t\treplaced += `(?<${toGroupKey(nextIndex++)}>[^/]*)`;\n\t\t\tcontinue;\n\t\t}\n\t\treplaced += segment[i];\n\t}\n\treturn [replaced, nextIndex];\n}\nfunction encodeEscapes(path) {\n\tif (!path.includes(\"\\\\\")) return path;\n\treturn path.replace(/\\\\([:(){}])/g, (_, c) => \"�\" + \"ABCDE\"[\":(){}\".indexOf(c)]);\n}\nfunction segmentKey(segment) {\n\tif (segment.startsWith(\"**\")) return 2;\n\tif (segment === \"*\" || segment.includes(\":\") || segment.includes(\"(\") || hasSegmentWildcard(segment)) return 1;\n\tif (segment === \"\\\\*\") return \"*\";\n\tif (segment === \"\\\\*\\\\*\") return \"**\";\n\tif (!segment.includes(\"�\")) return segment;\n\treturn segment.replace(/\\uFFFD([A-E])/g, (_, c) => c === \"A\" ? \":\" : c === \"B\" ? \"(\" : c === \"C\" ? \")\" : c === \"D\" ? \"{\" : \"}\");\n}\nfunction expandModifiers(segments) {\n\tfor (let i = 0; i < segments.length; i++) {\n\t\tconst last = segments[i].charCodeAt(segments[i].length - 1);\n\t\tif (last !== 63 && last !== 43 && last !== 42) continue;\n\t\tconst m = segments[i].match(/^(.*:[\\w-]+(?:\\([^)]*\\))?)([?+*])$/);\n\t\tif (!m) continue;\n\t\tconst pre = segments.slice(0, i);\n\t\tconst suf = segments.slice(i + 1);\n\t\tif (m[2] === \"?\") return [\"/\" + pre.concat(m[1]).concat(suf).join(\"/\"), \"/\" + pre.concat(suf).join(\"/\")];\n\t\tconst name = m[1].match(/:([\\w-]+)/)?.[1] || \"_\";\n\t\tconst wc = \"/\" + [\n\t\t\t...pre,\n\t\t\t`**:${name}`,\n\t\t\t...suf\n\t\t].join(\"/\");\n\t\tconst without = \"/\" + [...pre, ...suf].join(\"/\");\n\t\treturn m[2] === \"+\" ? [wc] : [wc, without];\n\t}\n}\nfunction normalizePath(path) {\n\tif (!path.includes(\"/.\")) return path;\n\tconst r = [];\n\tfor (const s of path.split(\"/\")) if (s === \".\") continue;\n\telse if (s === \"..\" && r.length > 1) r.pop();\n\telse r.push(s);\n\treturn r.join(\"/\") || \"/\";\n}\nfunction splitPath(path) {\n\tconst s = path.split(\"/\");\n\ts.shift();\n\tif (s[s.length - 1] === \"\") s.pop();\n\treturn s;\n}\nfunction splitRoute(path) {\n\tconst s = splitPath(path);\n\twhile (s[s.length - 1] === \"\") s.pop();\n\treturn s;\n}\nfunction getMatchParams(segments, paramsMap) {\n\tconst params = new NullProtoObj();\n\tfor (const [index, name] of paramsMap) {\n\t\tconst segment = index < 0 ? segments.slice(-(index + 1)).join(\"/\") : segments[index];\n\t\tif (typeof name === \"string\") params[name] = segment;\n\t\telse {\n\t\t\tconst match = segment.match(name);\n\t\t\tif (match) for (const key in match.groups) params[fromGroupName(key)] = match.groups[key];\n\t\t}\n\t}\n\treturn params;\n}\nfunction addRoute(ctx, method = \"\", path, data) {\n\tmethod = method.toUpperCase();\n\tif (path.charCodeAt(0) !== 47) path = `/${path}`;\n\tconst groupExpanded = expandGroupDelimiters(path);\n\tif (groupExpanded) {\n\t\tfor (const expandedPath of groupExpanded) addRoute(ctx, method, expandedPath, data);\n\t\treturn;\n\t}\n\tpath = encodeEscapes(path);\n\tconst segments = splitRoute(path);\n\tconst expanded = expandModifiers(segments);\n\tif (expanded) {\n\t\tfor (const p of expanded) addRoute(ctx, method, p, data);\n\t\treturn;\n\t}\n\tlet node = ctx.root;\n\tlet _unnamedParamIndex = 0;\n\tconst paramsMap = [];\n\tconst paramsRegexp = [];\n\tfor (let i = 0; i < segments.length; i++) {\n\t\tlet segment = segments[i];\n\t\tconst key = segmentKey(segment);\n\t\tif (key === 2) {\n\t\t\tif (!node.wildcard) node.wildcard = { key: \"**\" };\n\t\t\tnode = node.wildcard;\n\t\t\tparamsMap.push([\n\t\t\t\t-(i + 1),\n\t\t\t\tsegment.split(\":\")[1] || \"_\",\n\t\t\t\tsegment.length === 2\n\t\t\t]);\n\t\t\tbreak;\n\t\t}\n\t\tif (key === 1) {\n\t\t\tif (!node.param) node.param = { key: \"*\" };\n\t\t\tnode = node.param;\n\t\t\tif (segment === \"*\") paramsMap.push([\n\t\t\t\ti,\n\t\t\t\tString(_unnamedParamIndex++),\n\t\t\t\ttrue\n\t\t\t]);\n\t\t\telse if (segment.includes(\"(\") || segment.includes(\":\", 1) || !/^:[\\w-]+$/.test(segment)) {\n\t\t\t\tconst [regexp, nextIndex] = getParamRegexp(segment, _unnamedParamIndex);\n\t\t\t\t_unnamedParamIndex = nextIndex;\n\t\t\t\tparamsRegexp[i] = regexp;\n\t\t\t\tnode.hasRegexParam = true;\n\t\t\t\tparamsMap.push([\n\t\t\t\t\ti,\n\t\t\t\t\tregexp,\n\t\t\t\t\tfalse\n\t\t\t\t]);\n\t\t\t} else paramsMap.push([\n\t\t\t\ti,\n\t\t\t\tsegment.slice(1),\n\t\t\t\tfalse\n\t\t\t]);\n\t\t\tcontinue;\n\t\t}\n\t\tsegment = segments[i] = key;\n\t\tconst child = node.static?.[segment];\n\t\tif (child) node = child;\n\t\telse {\n\t\t\tconst staticNode = { key: segment };\n\t\t\tif (!node.static) node.static = new NullProtoObj();\n\t\t\tnode.static[segment] = staticNode;\n\t\t\tnode = staticNode;\n\t\t}\n\t}\n\tconst hasParams = paramsMap.length > 0;\n\tconst methods = node.methods ??= new NullProtoObj();\n\t(methods[method] ??= []).push({\n\t\tdata: data || null,\n\t\tparamsRegexp,\n\t\tparamsMap: hasParams ? paramsMap : void 0\n\t});\n\tif (!hasParams) ctx.static[\"/\" + segments.join(\"/\")] = node;\n}\nfunction getParamRegexp(segment, unnamedStart = 0) {\n\tlet _i = unnamedStart;\n\tlet _s = \"\", _d = 0;\n\tfor (let j = 0; j < segment.length; j++) {\n\t\tconst c = segment.charCodeAt(j);\n\t\tif (c === 40) _d++;\n\t\telse if (c === 41 && _d > 0) _d--;\n\t\telse if (c === 92 && _d === 0 && j + 1 < segment.length) {\n\t\t\tconst n = segment[j + 1];\n\t\t\tif (n !== \":\" && n !== \"(\" && n !== \"*\" && n !== \"\\\\\") {\n\t\t\t\t_s += \"￾\" + n;\n\t\t\t\tj++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} else if (c === 46 && _d === 0) {\n\t\t\t_s += \"\\\\.\";\n\t\t\tcontinue;\n\t\t}\n\t\t_s += segment[j];\n\t}\n\t[_s, _i] = replaceSegmentWildcards(_s, _i);\n\tconst regex = _s.replace(/:([\\w-]+)(?:\\(([^)]*)\\))?/g, (_, id, p) => `(?<${toGroupName(id)}>${p || \"[^/]+\"})`).replace(/\\((?![?<])/g, () => `(?<${toUnnamedGroupKey(_i++)}>`).replace(/\\uFFFE(.)/g, (_, c) => /[.*+?^${}()|[\\]\\\\]/.test(c) ? `\\\\${c}` : c);\n\treturn [new RegExp(`^${regex}$`), _i];\n}\nfunction findRoute(ctx, method = \"\", path, opts) {\n\tif (opts?.normalize) path = normalizePath(path);\n\tif (path.charCodeAt(path.length - 1) === 47) path = path.slice(0, -1);\n\tconst staticNode = ctx.static[path];\n\tif (staticNode && staticNode.methods) {\n\t\tconst staticMatch = staticNode.methods[method] || staticNode.methods[\"\"];\n\t\tif (staticMatch !== void 0) return staticMatch[0];\n\t}\n\tconst segments = splitPath(path);\n\tconst match = _lookupTree(ctx.root, method, segments, 0);\n\tif (match === void 0) return;\n\tif (opts?.params === false) return match;\n\treturn {\n\t\tdata: match.data,\n\t\tparams: match.paramsMap ? getMatchParams(segments, match.paramsMap) : void 0\n\t};\n}\nfunction _lookupTree(node, method, segments, index) {\n\tif (index === segments.length) {\n\t\tif (node.methods) {\n\t\t\tconst match = _selectMatcher(node.methods, method, segments, node.key === \"*\", false);\n\t\t\tif (match) return match;\n\t\t}\n\t\treturn node.param?.methods && _selectMatcher(node.param.methods, method, segments, true, true) || node.wildcard?.methods && _selectMatcher(node.wildcard.methods, method, segments, true, true) || void 0;\n\t}\n\tconst segment = segments[index];\n\tif (node.static) {\n\t\tconst staticChild = node.static[segment];\n\t\tif (staticChild) {\n\t\t\tconst match = _lookupTree(staticChild, method, segments, index + 1);\n\t\t\tif (match) return match;\n\t\t}\n\t}\n\tif (node.param) {\n\t\tconst match = _lookupTree(node.param, method, segments, index + 1);\n\t\tif (match) return match;\n\t}\n\tif (node.wildcard && node.wildcard.methods) return _selectMatcher(node.wildcard.methods, method, segments, true, false);\n}\nfunction _selectMatcher(methods, method, segments, dynamicTerminal, optionalOnly) {\n\tconst match = methods[method] || methods[\"\"];\n\tif (!match) return;\n\tconst first = match[0];\n\tif (match.length === 1 && first.paramsRegexp.length === 0) {\n\t\tif (!optionalOnly) return first;\n\t\tconst pMap = first.paramsMap;\n\t\treturn pMap?.[pMap.length - 1]?.[2] ? first : void 0;\n\t}\n\tlet best;\n\tlet bestWeight = -1;\n\tfor (const m of match) {\n\t\tconst pMap = m.paramsMap;\n\t\tconst lastOptional = pMap?.[pMap.length - 1]?.[2];\n\t\tif (optionalOnly && !lastOptional) continue;\n\t\tlet weight = dynamicTerminal && pMap && !lastOptional ? 1 : 0;\n\t\tconst regexps = m.paramsRegexp;\n\t\tfor (let i = 0; i < regexps.length; i++) if (regexps[i]) {\n\t\t\tif (!regexps[i].test(segments[i])) {\n\t\t\t\tweight = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tweight++;\n\t\t}\n\t\tif (weight > bestWeight) {\n\t\t\tbest = m;\n\t\t\tbestWeight = weight;\n\t\t}\n\t}\n\treturn best;\n}\nfunction removeRoute(ctx, method = \"\", path) {\n\tmethod = method.toUpperCase();\n\tif (path.charCodeAt(0) !== 47) path = `/${path}`;\n\tconst groupExpanded = expandGroupDelimiters(path);\n\tif (groupExpanded) {\n\t\tfor (const expandedPath of groupExpanded) removeRoute(ctx, method, expandedPath);\n\t\treturn;\n\t}\n\tpath = encodeEscapes(path);\n\tconst segments = splitRoute(path);\n\tconst modExpanded = expandModifiers(segments);\n\tif (modExpanded) {\n\t\tfor (const expandedPath of modExpanded) removeRoute(ctx, method, expandedPath);\n\t\treturn;\n\t}\n\t_remove(ctx.root, method, segments, 0);\n}\nfunction _remove(node, method, segments, index) {\n\tif (index === segments.length) {\n\t\tif (node.methods && method in node.methods) {\n\t\t\tdelete node.methods[method];\n\t\t\tif (Object.keys(node.methods).length === 0) node.methods = void 0;\n\t\t}\n\t\treturn;\n\t}\n\tconst segment = segments[index];\n\tconst key = segmentKey(segment);\n\tif (key === 2) {\n\t\tif (node.wildcard) {\n\t\t\t_remove(node.wildcard, method, segments, segments.length);\n\t\t\tif (_isEmptyNode(node.wildcard)) node.wildcard = void 0;\n\t\t}\n\t\treturn;\n\t}\n\tif (key === 1) {\n\t\tif (node.param) {\n\t\t\t_remove(node.param, method, segments, index + 1);\n\t\t\tif (_isEmptyNode(node.param)) node.param = void 0;\n\t\t}\n\t\treturn;\n\t}\n\tconst childNode = node.static?.[key];\n\tif (childNode) {\n\t\t_remove(childNode, method, segments, index + 1);\n\t\tif (_isEmptyNode(childNode)) {\n\t\t\tdelete node.static[key];\n\t\t\tif (Object.keys(node.static).length === 0) node.static = void 0;\n\t\t}\n\t}\n}\nfunction _isEmptyNode(node) {\n\treturn node.methods === void 0 && node.static === void 0 && node.param === void 0 && node.wildcard === void 0;\n}\nfunction findAllRoutes(ctx, method = \"\", path, opts) {\n\tif (opts?.normalize) path = normalizePath(path);\n\tif (path.charCodeAt(path.length - 1) === 47) path = path.slice(0, -1);\n\tconst segments = splitPath(path);\n\tconst matches = _findAll(ctx.root, method, segments, 0);\n\tif (opts?.params === false) return matches;\n\treturn matches.map((m) => {\n\t\treturn {\n\t\t\tdata: m.data,\n\t\t\tparams: m.paramsMap ? getMatchParams(segments, m.paramsMap) : void 0\n\t\t};\n\t});\n}\nfunction _findAll(node, method, segments, index, matches = []) {\n\tconst segment = segments[index];\n\tif (node.wildcard && node.wildcard.methods) {\n\t\tconst match = node.wildcard.methods[method] || node.wildcard.methods[\"\"];\n\t\tif (match) if (index < segments.length) pushSorted(matches, match, true);\n\t\telse {\n\t\t\tconst optional = [];\n\t\t\tfor (const m of match) {\n\t\t\t\tconst pMap = m.paramsMap;\n\t\t\t\tif (pMap?.[pMap.length - 1]?.[2]) optional.push(m);\n\t\t\t}\n\t\t\tpushSorted(matches, optional, true);\n\t\t}\n\t}\n\tif (node.param) {\n\t\tif (index < segments.length) {\n\t\t\tconst start = matches.length;\n\t\t\t_findAll(node.param, method, segments, index + 1, matches);\n\t\t\tif (node.param.hasRegexParam) {\n\t\t\t\tfor (let r = matches.length - 1; r >= start; r--) if (matches[r].paramsRegexp[index]?.test(segment) === false) matches.splice(r, 1);\n\t\t\t}\n\t\t} else if (node.param.methods) {\n\t\t\tconst match = node.param.methods[method] || node.param.methods[\"\"];\n\t\t\tif (match) {\n\t\t\t\tconst optional = [];\n\t\t\t\tfor (const m of match) {\n\t\t\t\t\tconst pMap = m.paramsMap;\n\t\t\t\t\tif (pMap?.[pMap.length - 1]?.[2]) optional.push(m);\n\t\t\t\t}\n\t\t\t\tpushSorted(matches, optional, true);\n\t\t\t}\n\t\t}\n\t}\n\tif (index < segments.length) {\n\t\tconst staticChild = node.static?.[segment];\n\t\tif (staticChild) _findAll(staticChild, method, segments, index + 1, matches);\n\t}\n\tif (index === segments.length && node.methods) {\n\t\tconst match = node.methods[method] || node.methods[\"\"];\n\t\tif (match) pushSorted(matches, match, node.key === \"*\");\n\t}\n\treturn matches;\n}\nfunction pushSorted(matches, match, dynamicTerminal) {\n\tif (match.length > 1) match = match.map((m) => {\n\t\tlet w = 0;\n\t\tconst { paramsRegexp: rx, paramsMap: pm } = m;\n\t\tfor (let i = 0; i < rx.length; i++) if (rx[i]) w++;\n\t\tif (dynamicTerminal && pm && !pm[pm.length - 1][2]) w++;\n\t\treturn [m, w];\n\t}).sort((a, b) => a[1] - b[1]).map((e) => e[0]);\n\tfor (const m of match) matches.push(m);\n}\nfunction shapeSubsumes(a, b) {\n\tconst fa = a.fixed.length;\n\tconst fb = b.fixed.length;\n\tif (fa + a.tailMin > fb + b.tailMin || fa + a.tailMax < fb + b.tailMax) return false;\n\tconst common = fa < fb ? fa : fb;\n\tfor (let k = 0; k < common; k++) if (!_segmentSubsumes(a.fixed[k], b.fixed[k])) return false;\n\tfor (let k = fb; k < fa; k++) if (a.fixed[k] !== void 0) return false;\n\treturn true;\n}\nfunction mergeShapes(shapes) {\n\tfor (let i = 0; i < shapes.length; i++) for (let j = i + 1; j < shapes.length; j++) {\n\t\tconst a = shapes[i];\n\t\tconst b = shapes[j];\n\t\tif (_sameFixed(a.fixed, b.fixed) && a.tailMin <= b.tailMax + 1 && b.tailMin <= a.tailMax + 1) {\n\t\t\ta.tailMin = Math.min(a.tailMin, b.tailMin);\n\t\t\ta.tailMax = Math.max(a.tailMax, b.tailMax);\n\t\t\tshapes.splice(j, 1);\n\t\t\tj = i;\n\t\t}\n\t}\n\treturn shapes;\n}\nfunction _sameFixed(a, b) {\n\tif (a.length !== b.length) return false;\n\tfor (let k = 0; k < a.length; k++) if (!_segmentEqual(a[k], b[k])) return false;\n\treturn true;\n}\nfunction _segmentEqual(x, y) {\n\treturn x === y || x instanceof RegExp && y instanceof RegExp && x.flags === y.flags && _regExpKey(x) === _regExpKey(y);\n}\nfunction _segmentSubsumes(x, y) {\n\tif (x === void 0) return true;\n\tif (typeof x === \"string\") return x === y;\n\tif (typeof y === \"string\") return x.test(y);\n\treturn y instanceof RegExp && x.flags === y.flags && _regExpKey(x) === _regExpKey(y);\n}\nconst _regExpKeys = /* @__PURE__ */ new WeakMap();\nfunction _regExpKey(r) {\n\tlet key = _regExpKeys.get(r);\n\tif (key === void 0) {\n\t\tconst s = r.source;\n\t\tkey = \"\";\n\t\tfor (let i = 0; i < s.length; i++) {\n\t\t\tconst c = s[i];\n\t\t\tif (c === \"\\\\\") key += c + s[++i];\n\t\t\telse if (c === \"[\") {\n\t\t\t\tlet j = i + 1;\n\t\t\t\twhile (j < s.length && s[j] !== \"]\") j += s[j] === \"\\\\\" ? 2 : 1;\n\t\t\t\tkey += s.slice(i, j + 1);\n\t\t\t\ti = j;\n\t\t\t} else if (c === \"(\" && s[i + 1] === \"?\" && s[i + 2] === \"<\" && s[i + 3] !== \"=\" && s[i + 3] !== \"!\") {\n\t\t\t\tconst end = s.indexOf(\">\", i + 3);\n\t\t\t\tkey += \"(\";\n\t\t\t\ti = end === -1 ? i : end;\n\t\t\t} else key += c;\n\t\t}\n\t\t_regExpKeys.set(r, key);\n\t}\n\treturn key;\n}\nfunction routeToShapes(pattern) {\n\tlet shapes = _patternShapes.get(pattern);\n\tif (shapes === void 0) {\n\t\tconst ctx = createRouter();\n\t\taddRoute(ctx, \"\", pattern);\n\t\tshapes = [];\n\t\t_collectShapes(ctx.root, [], shapes);\n\t\tshapes = mergeShapes(shapes);\n\t\tif (_patternShapes.size >= 1024) _patternShapes.clear();\n\t\t_patternShapes.set(pattern, shapes);\n\t}\n\treturn shapes;\n}\nfunction shapeOf(edges, entry) {\n\tlet shape = _shapeCache.get(entry);\n\tif (!shape) _shapeCache.set(entry, shape = _computeShape(edges, entry));\n\treturn shape;\n}\nfunction shapesOverlap(a, b) {\n\tconst fa = a.fixed.length;\n\tconst fb = b.fixed.length;\n\tconst common = fa < fb ? fa : fb;\n\tfor (let k = 0; k < common; k++) if (!_segmentsCanOverlap(a.fixed[k], b.fixed[k])) return false;\n\treturn Math.max(fa + a.tailMin, fb + b.tailMin) <= Math.min(fa + a.tailMax, fb + b.tailMax);\n}\nfunction mayMatchAt(query, depth, key) {\n\tfor (const q of query) if (depth < q.fixed.length) {\n\t\tconst m = q.fixed[depth];\n\t\tif (m === void 0 || (typeof m === \"string\" ? m === key : m.test(key))) return true;\n\t} else if (depth - q.fixed.length < q.tailMax) return true;\n\treturn false;\n}\nconst _shapeCache = /* @__PURE__ */ new WeakMap();\nconst _patternShapes = /* @__PURE__ */ new Map();\nfunction _collectShapes(node, edges, shapes) {\n\tif (node.methods) for (const entry of node.methods[\"\"] || []) shapes.push(_computeShape(edges, entry));\n\tif (node.static) for (const key in node.static) {\n\t\tedges.push(key);\n\t\t_collectShapes(node.static[key], edges, shapes);\n\t\tedges.pop();\n\t}\n\tif (node.param) {\n\t\tedges.push(0);\n\t\t_collectShapes(node.param, edges, shapes);\n\t\tedges.pop();\n\t}\n\tif (node.wildcard) {\n\t\tedges.push(1);\n\t\t_collectShapes(node.wildcard, edges, shapes);\n\t\tedges.pop();\n\t}\n}\nfunction _computeShape(edges, entry) {\n\tconst fixed = [];\n\tlet tailMin = 0;\n\tlet tailMax = 0;\n\tconst pMap = entry.paramsMap;\n\tfor (let d = 0; d < edges.length; d++) {\n\t\tconst edge = edges[d];\n\t\tif (typeof edge === \"string\") fixed.push(edge);\n\t\telse if (edge === 1) {\n\t\t\ttailMin = pMap[pMap.length - 1][2] ? 0 : 1;\n\t\t\ttailMax = Number.POSITIVE_INFINITY;\n\t\t} else if (pMap) {\n\t\t\tconst p = pMap.find((e) => e[0] === d);\n\t\t\tif (p[1] instanceof RegExp) fixed.push(p[1]);\n\t\t\telse if (p[2] && d === edges.length - 1) tailMax = 1;\n\t\t\telse fixed.push(void 0);\n\t\t}\n\t}\n\tlet f = fixed.length;\n\twhile (f > 0 && fixed[f - 1] === void 0) f--;\n\tif (f < fixed.length) {\n\t\ttailMin += fixed.length - f;\n\t\ttailMax += fixed.length - f;\n\t\tfixed.length = f;\n\t}\n\treturn {\n\t\tfixed,\n\t\ttailMin,\n\t\ttailMax\n\t};\n}\nfunction _segmentsCanOverlap(x, y) {\n\tif (typeof x === \"string\") return typeof y === \"string\" ? x === y : y instanceof RegExp ? y.test(x) : true;\n\tif (x instanceof RegExp && typeof y === \"string\") return x.test(y);\n\treturn true;\n}\nfunction routesOverlap(patternA, patternB) {\n\treturn _anyOverlap(routeToShapes(patternA), routeToShapes(patternB));\n}\nfunction compareRoutes(patternA, patternB) {\n\tconst a = routeToShapes(patternA);\n\tconst b = routeToShapes(patternB);\n\tconst aCoversB = _covers(a, b);\n\tconst bCoversA = _covers(b, a);\n\tif (aCoversB && bCoversA) return \"equal\";\n\tif (aCoversB) return \"superset\";\n\tif (bCoversA) return \"subset\";\n\treturn _anyOverlap(a, b) ? \"partial\" : \"disjoint\";\n}\nfunction findOverlappingRoutes(ctx, method = \"\", pattern) {\n\tconst query = routeToShapes(pattern);\n\tconst matches = [];\n\t_collectOverlaps(ctx.root, method, query, [], /* @__PURE__ */ new Set(), matches);\n\treturn matches;\n}\nfunction _anyOverlap(a, b) {\n\tfor (const x of a) for (const y of b) if (shapesOverlap(x, y)) return true;\n\treturn false;\n}\nfunction _covers(sup, sub) {\n\treturn sub.every((s) => sup.some((x) => shapeSubsumes(x, s)));\n}\nfunction _collectOverlaps(node, method, query, edges, seen, matches) {\n\tif (node.wildcard) {\n\t\tedges.push(1);\n\t\t_collectOverlaps(node.wildcard, method, query, edges, seen, matches);\n\t\tedges.pop();\n\t}\n\tif (node.param) {\n\t\tedges.push(0);\n\t\t_collectOverlaps(node.param, method, query, edges, seen, matches);\n\t\tedges.pop();\n\t}\n\tif (node.static) {\n\t\tfor (const key in node.static) if (mayMatchAt(query, edges.length, key)) {\n\t\t\tedges.push(key);\n\t\t\t_collectOverlaps(node.static[key], method, query, edges, seen, matches);\n\t\t\tedges.pop();\n\t\t}\n\t}\n\tif (node.methods) {\n\t\tconst data = node.methods[method] || node.methods[\"\"];\n\t\tif (data) for (const entry of data) {\n\t\t\tconst d = entry.data;\n\t\t\tconst isRef = d !== null && (typeof d === \"object\" || typeof d === \"function\");\n\t\t\tif (isRef && seen.has(d)) continue;\n\t\t\tconst shape = shapeOf(edges, entry);\n\t\t\tif (query.some((q) => shapesOverlap(q, shape))) {\n\t\t\t\tif (isRef) seen.add(d);\n\t\t\t\tmatches.push({ data: d });\n\t\t\t}\n\t\t}\n\t}\n}\nfunction routeNodeKeys(pattern) {\n\tlet keys = _patternKeys.get(pattern);\n\tif (keys === void 0) {\n\t\tconst ctx = createRouter();\n\t\taddRoute(ctx, \"\", pattern);\n\t\tkeys = [];\n\t\t_collectKeys(ctx.root, \"\", keys);\n\t\tif (_patternKeys.size >= 1024) _patternKeys.clear();\n\t\t_patternKeys.set(pattern, keys);\n\t}\n\treturn keys.slice();\n}\nconst _patternKeys = /* @__PURE__ */ new Map();\nfunction _collectKeys(node, prefix, keys) {\n\tif (node.methods) keys.push(prefix || \"/\");\n\tif (node.static) for (const key in node.static) _collectKeys(node.static[key], prefix + \"/\" + _escapeKey(key), keys);\n\tif (node.param) _collectKeys(node.param, prefix + \"/*\", keys);\n\tif (node.wildcard) _collectKeys(node.wildcard, prefix + \"/**\", keys);\n}\nfunction _escapeKey(key) {\n\tif (key === \"*\") return \"\\\\*\";\n\tif (key === \"**\") return \"\\\\*\\\\*\";\n\treturn key.replace(/[:(){}]/g, \"\\\\$&\");\n}\nconst _P = \"￾\";\nfunction replaceEscapesOutsideGroups(segment) {\n\tlet r = \"\", d = 0;\n\tfor (let i = 0; i < segment.length; i++) {\n\t\tconst c = segment.charCodeAt(i);\n\t\tif (c === 40) d++;\n\t\telse if (c === 41 && d > 0) d--;\n\t\telse if (c === 92 && d === 0 && i + 1 < segment.length) {\n\t\t\tconst n = segment[i + 1];\n\t\t\tif (n !== \":\" && n !== \"(\" && n !== \"*\" && n !== \"\\\\\") {\n\t\t\t\tr += _P + n;\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tr += segment[i];\n\t}\n\treturn r;\n}\nfunction resolveEscapePlaceholders(str) {\n\treturn str.replace(/\\uFFFE(.)/g, (_, c) => /[.*+?^${}()|[\\]\\\\]/.test(c) ? `\\\\${c}` : c);\n}\nfunction escapeBareDots(str) {\n\tlet r = \"\", d = 0;\n\tfor (let i = 0; i < str.length; i++) {\n\t\tconst c = str.charCodeAt(i);\n\t\tif (c === 92 || c === 65534) {\n\t\t\tr += str[i] + (str[i + 1] || \"\");\n\t\t\ti++;\n\t\t} else if (c === 40) {\n\t\t\td++;\n\t\t\tr += str[i];\n\t\t} else if (c === 41) {\n\t\t\tif (d > 0) d--;\n\t\t\tr += str[i];\n\t\t} else if (c === 46 && d === 0) r += \"\\\\.\";\n\t\telse r += str[i];\n\t}\n\treturn r;\n}\nfunction routeToRegExp(route = \"/\") {\n\tif (route.charCodeAt(0) !== 47) route = `/${route}`;\n\tconst inlineOptional = inlineOptionalGroup(route);\n\tif (inlineOptional) return inlineOptional;\n\tconst groupExpanded = expandGroupDelimiters(route);\n\tif (groupExpanded) {\n\t\tconst sources = groupExpanded.map((expandedRoute) => routeToRegExp(expandedRoute).source.slice(1, -1));\n\t\treturn new RegExp(`^(?:${sources.join(\"|\")})$`);\n\t}\n\treturn _routeToRegExp(route);\n}\nfunction inlineOptionalGroup(route) {\n\tconst group = scanFirstGroup(route);\n\tif (!group) return;\n\tconst [pre, body, suf, mod] = group;\n\tif (mod !== \"?\" || suf !== \"\" || body === \"\" || scanFirstGroup(pre) || scanFirstGroup(body)) return;\n\tconst baseSegs = routeToRegExpSegments(pre);\n\tconst fullSegs = routeToRegExpSegments(pre + body);\n\tconst baseLen = baseSegs.length;\n\tif (baseLen === 0 || fullSegs.length < baseLen) return;\n\tconst midSegment = fullSegs.length === baseLen;\n\tconst sharedLen = midSegment ? baseLen - 1 : baseLen;\n\tfor (let i = 0; i < sharedLen; i++) if (fullSegs[i] !== baseSegs[i]) return;\n\tif (midSegment) {\n\t\tconst prefix = baseSegs[baseLen - 1];\n\t\tconst last = fullSegs[baseLen - 1];\n\t\tif (!last.startsWith(prefix)) return;\n\t\tif (/(?:\\[\\^\\/\\]|\\.)[*+]\\)?$/.test(prefix)) return;\n\t\tconst k = prefix.length;\n\t\tconst inlineSegs = fullSegs.slice(0, baseLen - 1);\n\t\tinlineSegs.push(`${last.slice(0, k)}(?:${last.slice(k)})?`);\n\t\treturn new RegExp(`^/${inlineSegs.join(\"/\")}/?$`);\n\t}\n\tconst head = fullSegs.slice(0, baseLen).join(\"/\");\n\tconst tail = fullSegs.slice(baseLen).join(\"/\");\n\treturn new RegExp(`^/${head}(?:/${tail})?/?$`);\n}\nfunction _routeToRegExp(route) {\n\treturn new RegExp(`^/${routeToRegExpSegments(route).join(\"/\")}/?$`);\n}\nfunction routeToRegExpSegments(route) {\n\tconst reSegments = [];\n\tlet idCtr = 0;\n\tfor (const segment of splitRoute(route)) {\n\t\tif (!segment) {\n\t\t\treSegments.push(\"\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment === \"*\") reSegments.push(`(?<${toRegExpUnnamedKey(idCtr++)}>[^/]*)`);\n\t\telse if (segment.startsWith(\"**\")) reSegments.push(segment === \"**\" ? \"?(?<_>.*)\" : `?(?<${toGroupName(segment.slice(3))}>.+)`);\n\t\telse if (segment.includes(\":\") || /(^|[^\\\\])\\(/.test(segment) || hasSegmentWildcard(segment)) {\n\t\t\tconst modMatch = segment.match(/^(.*:[\\w-]+(?:\\([^)]*\\))?)([?+*])$/);\n\t\t\tif (modMatch) {\n\t\t\t\tconst [, base, mod] = modMatch;\n\t\t\t\tconst name = toGroupName(base.match(/:([\\w-]+)/)?.[1] || `_${idCtr++}`);\n\t\t\t\tif (mod === \"?\") {\n\t\t\t\t\tconst inner = escapeBareDots(base.replace(/:([\\w-]+)(?:\\(([^)]*)\\))?/g, (_, id, pattern) => `(?<${toGroupName(id)}>${pattern || \"[^/]+\"})`));\n\t\t\t\t\tif (reSegments.length > 0) {\n\t\t\t\t\t\tconst prevQ = reSegments.pop();\n\t\t\t\t\t\treSegments.push(`${prevQ}(?:/${inner})?`);\n\t\t\t\t\t} else reSegments.push(`?${inner}?`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst pattern = base.match(/:([\\w-]+)(?:\\(([^)]*)\\))?/)?.[2];\n\t\t\t\tif (reSegments.length > 0) {\n\t\t\t\t\tconst prevMod = reSegments.pop();\n\t\t\t\t\tif (pattern) {\n\t\t\t\t\t\tconst repeated = `${pattern}(?:/${pattern})*`;\n\t\t\t\t\t\treSegments.push(mod === \"+\" ? `${prevMod}/(?<${name}>${repeated})` : `${prevMod}(?:/(?<${name}>${repeated}))?`);\n\t\t\t\t\t} else reSegments.push(mod === \"+\" ? `${prevMod}/(?<${name}>.+)` : `${prevMod}(?:/(?<${name}>.*))?`);\n\t\t\t\t} else if (pattern) {\n\t\t\t\t\tconst repeated = `${pattern}(?:/${pattern})*`;\n\t\t\t\t\treSegments.push(mod === \"+\" ? `?(?<${name}>${repeated})` : `?(?<${name}>${repeated})?`);\n\t\t\t\t} else reSegments.push(mod === \"+\" ? `?(?<${name}>.+)` : `?(?<${name}>.*)`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet dynamicSegment = replaceEscapesOutsideGroups(segment);\n\t\t\t[dynamicSegment, idCtr] = replaceSegmentWildcards(dynamicSegment, idCtr, toRegExpUnnamedKey);\n\t\t\treSegments.push(resolveEscapePlaceholders(escapeBareDots(dynamicSegment.replace(/:([\\w-]+)(?:\\(([^)]*)\\))?/g, (_, id, pattern) => `(?<${toGroupName(id)}>${pattern || \"[^/]+\"})`).replace(/(^|[^\\\\])\\((?![?<])/g, (_, p) => `${p}(?<${toRegExpUnnamedKey(idCtr++)}>`))));\n\t\t} else reSegments.push(segment.replace(/\\\\(.)/g, \"$1\").replace(/[.*+?^${}()|[\\]]/g, \"\\\\$&\"));\n\t}\n\treturn reSegments;\n}\nfunction toRegExpUnnamedKey(index) {\n\treturn `_${index}`;\n}\nconst ROUTE_SPECIAL = /* @__PURE__ */ new Set([\n\t\":\",\n\t\"(\",\n\t\")\",\n\t\"{\",\n\t\"}\",\n\t\"*\",\n\t\"\\\\\",\n\t\"?\",\n\t\"+\",\n\t\"|\",\n\t\"^\",\n\t\"$\",\n\t\"[\",\n\t\"]\"\n]);\nfunction regExpToRoute(regexp) {\n\tif (typeof regexp !== \"string\" && /[ims]/.test(regexp.flags)) throw new Error(`rou3: cannot represent regexp flag(s) \"${regexp.flags}\" as a route`);\n\tlet src = typeof regexp === \"string\" ? regexp : regexp.source;\n\tif (src.startsWith(\"^\")) src = src.slice(1);\n\tif (src.endsWith(\"$\")) src = src.slice(0, -1);\n\tif (src.endsWith(\"\\\\/?\")) src = src.slice(0, -3);\n\tif (src === \"\" || src === \"\\\\/\") return \"/\";\n\tconst segments = [];\n\tconst n = src.length;\n\tlet i = 0;\n\twhile (i < n) {\n\t\tif (src.startsWith(\"(?:\", i)) {\n\t\t\tconst end = readGroup(src, i);\n\t\t\tif (src[end] !== \"?\") throw new Error(`rou3: unsupported non-optional group in \"${src}\"`);\n\t\t\tapplyOptional(segments, src.slice(i + 3, end - 1));\n\t\t\ti = end + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (src.startsWith(\"\\\\/?\", i)) {\n\t\t\tconst g = matchNamedGroup(src, i + 3);\n\t\t\tif (g && g.end === n && (g.body === \".*\" || g.body === \".+\")) {\n\t\t\t\tsegments.push(g.name === \"_\" ? \"**\" : `**:${g.name}`);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (src.startsWith(\"\\\\/\", i)) {\n\t\t\tconst end = segmentEnd(src, i + 2);\n\t\t\tsegments.push(reverseSegment(src.slice(i + 2, end)));\n\t\t\ti = end;\n\t\t\tcontinue;\n\t\t}\n\t\tthrow new Error(`rou3: cannot parse \"${src}\" at index ${i}`);\n\t}\n\treturn \"/\" + segments.join(\"/\");\n}\nfunction reverseSegment(seg) {\n\tconst whole = matchNamedGroup(seg, 0);\n\tif (whole && whole.end === seg.length) {\n\t\tif (whole.body === \".+\") return `:${whole.name}+`;\n\t\tconst rep = matchRepeat(whole.body);\n\t\tif (rep) return `:${whole.name}${constraint(rep)}+`;\n\t}\n\tlet out = \"\";\n\tlet i = 0;\n\twhile (i < seg.length) {\n\t\tconst c = seg[i];\n\t\tif (c === \"(\") {\n\t\t\tconst g = matchNamedGroup(seg, i);\n\t\t\tif (g) {\n\t\t\t\tout += paramToken(g.name, g.body);\n\t\t\t\ti = g.end;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!seg.startsWith(\"(?\", i)) {\n\t\t\t\tconst end = readGroup(seg, i);\n\t\t\t\tout += paramToken(\"_0\", seg.slice(i + 1, end - 1));\n\t\t\t\ti = end;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow new Error(`rou3: unsupported group construct in \"${seg}\"`);\n\t\t}\n\t\tif (c === \"\\\\\") {\n\t\t\tconst next = seg[i + 1];\n\t\t\tif (next === void 0) throw new Error(`rou3: dangling escape in \"${seg}\"`);\n\t\t\tif (/[a-z0-9]/i.test(next)) throw new Error(`rou3: unsupported escape \"\\\\${next}\" in \"${seg}\"`);\n\t\t\tout += escapeLiteral(next);\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (BARE_META.has(c)) throw new Error(`rou3: unsupported metacharacter \"${c}\" in \"${seg}\"`);\n\t\tout += escapeLiteral(c);\n\t\ti += 1;\n\t}\n\treturn out;\n}\nconst BARE_META = /* @__PURE__ */ new Set([\n\t\".\",\n\t\"^\",\n\t\"$\",\n\t\"*\",\n\t\"+\",\n\t\"?\",\n\t\"|\",\n\t\"[\",\n\t\"]\",\n\t\"{\",\n\t\"}\",\n\t\")\"\n]);\nfunction applyOptional(segments, inner) {\n\tif (inner.startsWith(\"\\\\/\")) {\n\t\tconst rest = inner.slice(2);\n\t\tconst g = matchNamedGroup(rest, 0);\n\t\tif (g && g.end === rest.length) {\n\t\t\tsegments.push(optionalParam(g.name, g.body));\n\t\t\treturn;\n\t\t}\n\t\tmergeGroup(segments, `/${reverseSegment(rest)}`);\n\t\treturn;\n\t}\n\tmergeGroup(segments, reverseSegment(inner));\n}\nfunction mergeGroup(segments, body) {\n\tif (segments.length === 0) throw new Error(`rou3: optional group \"{${body}}?\" has no preceding segment`);\n\tsegments[segments.length - 1] += `{${body}}?`;\n}\nfunction paramToken(name, body) {\n\tconst unnamed = /^_\\d+$/.test(name);\n\tif (unnamed && body === \"[^/]*\") return \"*\";\n\tif (!unnamed && body === \"[^/]+\") return `:${name}`;\n\treturn unnamed ? constraint(body) : `:${name}${constraint(body)}`;\n}\nfunction optionalParam(name, body) {\n\tif (body === \"[^/]+\") return `:${name}?`;\n\tif (body === \".*\") return `:${name}*`;\n\tconst rep = matchRepeat(body);\n\tif (rep) return `:${name}${constraint(rep)}*`;\n\treturn `:${name}${constraint(body)}?`;\n}\nfunction matchRepeat(body) {\n\tconst m = body.match(/^(.+)\\(\\?:\\\\\\/(.+)\\)\\*$/);\n\treturn m && m[1] === m[2] ? m[1] : void 0;\n}\nfunction constraint(body) {\n\tif (body.includes(\"/\")) throw new Error(`rou3: param constraint \"(${body})\" cannot contain \"/\"`);\n\treturn `(${body})`;\n}\nfunction escapeLiteral(ch) {\n\treturn ROUTE_SPECIAL.has(ch) ? `\\\\${ch}` : ch;\n}\nfunction matchNamedGroup(src, start) {\n\tif (!src.startsWith(\"(?<\", start)) return;\n\tconst after = src[start + 3];\n\tif (after === \"=\" || after === \"!\") return;\n\tconst gt = src.indexOf(\">\", start);\n\tif (gt === -1) return;\n\tconst end = readGroup(src, start);\n\treturn {\n\t\tname: fromGroupName(src.slice(start + 3, gt)),\n\t\tbody: src.slice(gt + 1, end - 1),\n\t\tend\n\t};\n}\nfunction readGroup(src, start) {\n\tlet depth = 0;\n\tlet inClass = false;\n\tfor (let i = start; i < src.length; i++) {\n\t\tconst c = src[i];\n\t\tif (inClass) {\n\t\t\tif (c === \"\\\\\") i++;\n\t\t\telse if (c === \"]\") inClass = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (c === \"\\\\\") i++;\n\t\telse if (c === \"[\") inClass = true;\n\t\telse if (c === \"(\") depth++;\n\t\telse if (c === \")\" && --depth === 0) return i + 1;\n\t}\n\tthrow new Error(`rou3: unbalanced group in \"${src}\"`);\n}\nfunction segmentEnd(src, start) {\n\tlet depth = 0;\n\tlet inClass = false;\n\tlet i = start;\n\twhile (i < src.length) {\n\t\tif (inClass) {\n\t\t\tif (src[i] === \"\\\\\") i++;\n\t\t\telse if (src[i] === \"]\") inClass = false;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (depth === 0 && (src.startsWith(\"\\\\/\", i) || src.startsWith(\"(?:\", i))) break;\n\t\tconst c = src[i];\n\t\tif (c === \"\\\\\") i += 2;\n\t\telse if (c === \"[\") {\n\t\t\tinClass = true;\n\t\t\ti++;\n\t\t} else {\n\t\t\tif (c === \"(\") depth++;\n\t\t\telse if (c === \")\") depth--;\n\t\t\ti++;\n\t\t}\n\t}\n\treturn i;\n}\nexport { NullProtoObj, addRoute, compareRoutes, createRouter, findAllRoutes, findOverlappingRoutes, findRoute, regExpToRoute, removeRoute, routeNodeKeys, routeToRegExp, routesOverlap };\n","import { getBody, isAPIError, isRequest } from \"./utils.mjs\";\nimport { toResponse } from \"./to-response.mjs\";\nimport { createEndpoint } from \"./endpoint.mjs\";\nimport { generator, getHTML } from \"./openapi.mjs\";\nimport { addRoute, createRouter, findAllRoutes, findRoute } from \"rou3\";\n//#region src/router.ts\nconst createRouter$1 = (endpoints, config) => {\n\tif (!config?.openapi?.disabled) {\n\t\tconst openapi = {\n\t\t\tpath: \"/api/reference\",\n\t\t\t...config?.openapi\n\t\t};\n\t\tendpoints[\"openapi\"] = createEndpoint(openapi.path, { method: \"GET\" }, async (c) => {\n\t\t\tconst schema = await generator(endpoints);\n\t\t\treturn new Response(getHTML(schema, openapi.scalar), { headers: { \"Content-Type\": \"text/html\" } });\n\t\t});\n\t}\n\tconst router = createRouter();\n\tconst middlewareRouter = createRouter();\n\tfor (const endpoint of Object.values(endpoints)) {\n\t\tif (!endpoint.options || !endpoint.path) continue;\n\t\tif (endpoint.options?.metadata?.SERVER_ONLY) continue;\n\t\tconst methods = Array.isArray(endpoint.options?.method) ? endpoint.options.method : [endpoint.options?.method];\n\t\tfor (const method of methods) addRoute(router, method, endpoint.path, endpoint);\n\t}\n\tif (config?.routerMiddleware?.length) for (const { path, middleware } of config.routerMiddleware) addRoute(middlewareRouter, \"*\", path, middleware);\n\tconst basePath = config?.basePath && config.basePath !== \"/\" ? config.basePath.replace(/\\/+$/, \"\") : \"\";\n\tconst processRequest = async (request) => {\n\t\tconst url = new URL(request.url);\n\t\tconst pathname = url.pathname;\n\t\tlet path;\n\t\tif (basePath) {\n\t\t\tif (!pathname.startsWith(`${basePath}/`)) return new Response(null, {\n\t\t\t\tstatus: 404,\n\t\t\t\tstatusText: \"Not Found\"\n\t\t\t});\n\t\t\tpath = pathname.slice(basePath.length);\n\t\t} else path = pathname;\n\t\tif (path.length === 0 || /\\/{2,}/.test(path)) return new Response(null, {\n\t\t\tstatus: 404,\n\t\t\tstatusText: \"Not Found\"\n\t\t});\n\t\tconst route = findRoute(router, request.method, path);\n\t\tif (path.endsWith(\"/\") !== route?.data?.path?.endsWith(\"/\") && !config?.skipTrailingSlashes) return new Response(null, {\n\t\t\tstatus: 404,\n\t\t\tstatusText: \"Not Found\"\n\t\t});\n\t\tif (!route?.data) return new Response(null, {\n\t\t\tstatus: 404,\n\t\t\tstatusText: \"Not Found\"\n\t\t});\n\t\tconst query = {};\n\t\turl.searchParams.forEach((value, key) => {\n\t\t\tif (key in query) if (Array.isArray(query[key])) query[key].push(value);\n\t\t\telse query[key] = [query[key], value];\n\t\t\telse query[key] = value;\n\t\t});\n\t\tconst handler = route.data;\n\t\ttry {\n\t\t\tconst allowedMediaTypes = handler.options.metadata?.allowedMediaTypes || config?.allowedMediaTypes;\n\t\t\tconst context = {\n\t\t\t\tpath,\n\t\t\t\tmethod: request.method,\n\t\t\t\theaders: request.headers,\n\t\t\t\tparams: route.params ? { ...route.params } : {},\n\t\t\t\trequest,\n\t\t\t\tbody: handler.options.disableBody ? void 0 : await getBody(handler.options.cloneRequest ? request.clone() : request, allowedMediaTypes),\n\t\t\t\tquery,\n\t\t\t\t_flag: \"router\",\n\t\t\t\tasResponse: true,\n\t\t\t\tcontext: config?.routerContext\n\t\t\t};\n\t\t\tconst middlewareRoutes = findAllRoutes(middlewareRouter, \"*\", path);\n\t\t\tif (middlewareRoutes?.length) for (const { data: middleware, params } of middlewareRoutes) {\n\t\t\t\tconst res = await middleware({\n\t\t\t\t\t...context,\n\t\t\t\t\tparams: params ? { ...params } : {},\n\t\t\t\t\tasResponse: false\n\t\t\t\t});\n\t\t\t\tif (res instanceof Response) return res;\n\t\t\t}\n\t\t\treturn await handler(context);\n\t\t} catch (error) {\n\t\t\tif (config?.onError) try {\n\t\t\t\tconst errorResponse = await config.onError(error, request);\n\t\t\t\tif (errorResponse instanceof Response) return toResponse(errorResponse);\n\t\t\t} catch (error) {\n\t\t\t\tif (isAPIError(error)) return toResponse(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (config?.throwError) throw error;\n\t\t\tif (isAPIError(error)) return toResponse(error);\n\t\t\tconsole.error(`# SERVER_ERROR: `, error);\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 500,\n\t\t\t\tstatusText: \"Internal Server Error\"\n\t\t\t});\n\t\t}\n\t};\n\treturn {\n\t\thandler: async (request) => {\n\t\t\tconst onReq = await config?.onRequest?.(request);\n\t\t\tif (onReq instanceof Response) return onReq;\n\t\t\tconst req = isRequest(onReq) ? onReq : request;\n\t\t\tconst res = await processRequest(req);\n\t\t\tconst onRes = await config?.onResponse?.(res, req);\n\t\t\tif (onRes instanceof Response) return onRes;\n\t\t\treturn res;\n\t\t},\n\t\tendpoints\n\t};\n};\n//#endregion\nexport { createRouter$1 as createRouter };\n\n//# sourceMappingURL=router.mjs.map","//#region src/utils/error-codes.ts\nfunction defineErrorCodes(codes) {\n\treturn Object.fromEntries(Object.entries(codes).map(([key, value]) => [key, {\n\t\tcode: key,\n\t\tmessage: value,\n\t\ttoString: () => key\n\t}]));\n}\n//#endregion\nexport { defineErrorCodes };\n","import { defineErrorCodes } from \"../utils/error-codes.mjs\";\n//#region src/error/codes.ts\nconst BASE_ERROR_CODES = defineErrorCodes({\n\tUSER_NOT_FOUND: \"User not found\",\n\tFAILED_TO_CREATE_USER: \"Failed to create user\",\n\tFAILED_TO_CREATE_SESSION: \"Failed to create session\",\n\tFAILED_TO_UPDATE_USER: \"Failed to update user\",\n\tFAILED_TO_GET_SESSION: \"Failed to get session\",\n\tINVALID_PASSWORD: \"Invalid password\",\n\tINVALID_EMAIL: \"Invalid email\",\n\tINVALID_EMAIL_OR_PASSWORD: \"Invalid email or password\",\n\tINVALID_USER: \"Invalid user\",\n\tSOCIAL_ACCOUNT_ALREADY_LINKED: \"Social account already linked\",\n\tPROVIDER_NOT_FOUND: \"Provider not found\",\n\tINVALID_TOKEN: \"Invalid token\",\n\tTOKEN_EXPIRED: \"Token expired\",\n\tID_TOKEN_NOT_SUPPORTED: \"id_token not supported\",\n\tFAILED_TO_GET_USER_INFO: \"Failed to get user info\",\n\tUSER_EMAIL_NOT_FOUND: \"User email not found\",\n\tEMAIL_NOT_VERIFIED: \"Email not verified\",\n\tPASSWORD_TOO_SHORT: \"Password too short\",\n\tPASSWORD_TOO_LONG: \"Password too long\",\n\tUSER_ALREADY_EXISTS: \"User already exists.\",\n\tUSER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: \"User already exists. Use another email.\",\n\tEMAIL_CAN_NOT_BE_UPDATED: \"Email can not be updated\",\n\tCHANGE_EMAIL_DISABLED: \"Change email is disabled\",\n\tCREDENTIAL_ACCOUNT_NOT_FOUND: \"Credential account not found\",\n\tSESSION_EXPIRED: \"Session expired. Re-authenticate to perform this action.\",\n\tFAILED_TO_UNLINK_LAST_ACCOUNT: \"You can't unlink your last account\",\n\tACCOUNT_NOT_FOUND: \"Account not found\",\n\tUSER_ALREADY_HAS_PASSWORD: \"User already has a password. Provide that to delete the account.\",\n\tCROSS_SITE_NAVIGATION_LOGIN_BLOCKED: \"Cross-site navigation login blocked. This request appears to be a CSRF attack.\",\n\tVERIFICATION_EMAIL_NOT_ENABLED: \"Verification email isn't enabled\",\n\tEMAIL_ALREADY_VERIFIED: \"Email is already verified\",\n\tEMAIL_MISMATCH: \"Email mismatch\",\n\tSESSION_NOT_FRESH: \"Session is not fresh\",\n\tLINKED_ACCOUNT_ALREADY_EXISTS: \"Linked account already exists\",\n\tINVALID_ORIGIN: \"Invalid origin\",\n\tINVALID_CALLBACK_URL: \"Invalid callbackURL\",\n\tINVALID_REDIRECT_URL: \"Invalid redirectURL\",\n\tINVALID_ERROR_CALLBACK_URL: \"Invalid errorCallbackURL\",\n\tINVALID_NEW_USER_CALLBACK_URL: \"Invalid newUserCallbackURL\",\n\tMISSING_OR_NULL_ORIGIN: \"Missing or null Origin\",\n\tCALLBACK_URL_REQUIRED: \"callbackURL is required\",\n\tFAILED_TO_CREATE_VERIFICATION: \"Unable to create verification\",\n\tFIELD_NOT_ALLOWED: \"Field not allowed to be set\",\n\tASYNC_VALIDATION_NOT_SUPPORTED: \"Async validation is not supported\",\n\tVALIDATION_ERROR: \"Validation Error\",\n\tMISSING_FIELD: \"Field is required\",\n\tMETHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED: \"POST method requires deferSessionRefresh to be enabled in session config\",\n\tBODY_MUST_BE_AN_OBJECT: \"Body must be an object\",\n\tPASSWORD_ALREADY_SET: \"User already has a password set\"\n});\n//#endregion\nexport { BASE_ERROR_CODES };\n","import { base64Url } from \"@better-auth/utils/base64\";\n//#region src/oauth2/utils.ts\n/**\n* Parse a provider's `scope` token-response field into a string array.\n*\n* RFC 6749 Section 3.3 defines `scope` as a space-delimited string, but\n* providers vary: some return an already-split array. Accept both forms and\n* drop empty or non-string entries.\n*\n* @see https://github.com/better-auth/better-auth/issues/9076\n*/\nfunction parseScopeField(scope) {\n\tif (Array.isArray(scope)) return scope.map((s) => typeof s === \"string\" ? s.trim() : \"\").filter(Boolean);\n\tif (typeof scope === \"string\") return scope.trim().split(/\\s+/).filter(Boolean);\n\treturn [];\n}\nfunction getOAuth2Tokens(data) {\n\tconst getDate = (seconds) => {\n\t\treturn new Date((/* @__PURE__ */ new Date()).getTime() + seconds * 1e3);\n\t};\n\treturn {\n\t\ttokenType: data.token_type,\n\t\taccessToken: data.access_token,\n\t\trefreshToken: data.refresh_token,\n\t\taccessTokenExpiresAt: data.expires_in ? getDate(data.expires_in) : void 0,\n\t\trefreshTokenExpiresAt: data.refresh_token_expires_in ? getDate(data.refresh_token_expires_in) : void 0,\n\t\tscopes: parseScopeField(data.scope),\n\t\tidToken: data.id_token,\n\t\traw: data\n\t};\n}\n/**\n* Fill in `accessTokenExpiresAt` from the provider's configured\n* `accessTokenExpiresIn` when the token response omitted `expires_in`. Without a\n* known expiry, `getAccessToken` cannot tell the token is expired and never\n* refreshes it. No-op when the provider already supplied an expiry or no\n* fallback is configured.\n*/\nfunction applyDefaultAccessTokenExpiry(tokens, accessTokenExpiresIn) {\n\tif (!tokens.accessTokenExpiresAt && accessTokenExpiresIn) tokens.accessTokenExpiresAt = new Date(Date.now() + accessTokenExpiresIn * 1e3);\n\treturn tokens;\n}\n/**\n* Compute the union of stored and incoming OAuth scopes, preserving\n* stored insertion order and dropping duplicates.\n*/\nfunction mergeScopes(stored, incoming) {\n\tconst existing = stored ? stored.split(\",\").map((scope) => scope.trim()).filter(Boolean) : [];\n\tconst next = (incoming ?? []).map((scope) => scope.trim()).filter(Boolean);\n\treturn [...new Set([...existing, ...next])].join(\",\");\n}\n/**\n* Return the provider's primary Client ID: the single string, or the entry at\n* array index 0 for the cross-platform form used by ID token audience\n* verification. Index 0 is the designated primary and pairs with\n* `clientSecret` for the authorization code flow; later array entries are\n* only used as additional accepted audiences. Returns `undefined` when the\n* primary value is missing or an empty string.\n*/\nfunction getPrimaryClientId(clientId) {\n\tconst value = Array.isArray(clientId) ? clientId[0] : clientId;\n\treturn typeof value === \"string\" && value.length > 0 ? value : void 0;\n}\nasync function generateCodeChallenge(codeVerifier) {\n\tconst data = new TextEncoder().encode(codeVerifier);\n\tconst hash = await crypto.subtle.digest(\"SHA-256\", data);\n\treturn base64Url.encode(new Uint8Array(hash), { padding: false });\n}\n//#endregion\nexport { applyDefaultAccessTokenExpiry, generateCodeChallenge, getOAuth2Tokens, getPrimaryClientId, mergeScopes, parseScopeField };\n","import { base64 } from \"@better-auth/utils/base64\";\n//#region src/oauth2/basic-credentials.ts\nconst BASIC_AUTHORIZATION_PATTERN = /^Basic +(.*)$/i;\n/**\n* Encodes a value using `application/x-www-form-urlencoded` per the URL\n* Living Standard. Differs from `encodeURIComponent` in two ways: it escapes\n* `!`, `'`, `(`, and `)`, and it represents space as `+` rather than `%20`.\n* `*` is left unescaped, matching the URL Standard's percent-encode set.\n*/\nfunction formUrlEncode(value) {\n\treturn new URLSearchParams({ v: value }).toString().slice(2);\n}\n/**\n* Inverse of `formUrlEncode`: decodes a single `application/x-www-form-urlencoded`\n* value, handling both `+` and `%20` as space.\n*/\nfunction formUrlDecode(value) {\n\tconst decoded = new URLSearchParams(`v=${value}`).get(\"v\");\n\tif (decoded === null) throw new Error(\"form-url-encoded value could not be decoded\");\n\treturn decoded;\n}\n/**\n* Encodes an OAuth client id and secret as an HTTP Basic credential string.\n*\n* Follows RFC 6749 §2.3.1: both values are `application/x-www-form-urlencoded`\n* prior to base64 encoding. The returned string is the full value of the\n* `Authorization` header, including the `Basic ` prefix.\n*/\nfunction encodeBasicCredentials(clientId, clientSecret) {\n\tconst payload = `${formUrlEncode(clientId)}:${formUrlEncode(clientSecret)}`;\n\treturn `Basic ${base64.encode(payload)}`;\n}\n/**\n* Decodes an `Authorization: Basic …` header value into its OAuth client id\n* and secret.\n*\n* Scheme matching is case-insensitive and tolerates one or more spaces\n* between the scheme and credentials per RFC 7235 §2.1. The base64 payload\n* is split on the first `:` only, so secrets containing colons round-trip\n* correctly. Each half is form-url-decoded per RFC 6749 §2.3.1, accepting\n* both `+` and `%20` as space. Per the URL Living Standard, invalid\n* percent-escapes pass through as-is; downstream client lookup will fail\n* with `invalid_client` for malformed credentials.\n*\n* Throws when the header is not a Basic credential, when the base64 payload\n* contains no `:`, or when either half is empty.\n*/\nfunction decodeBasicCredentials(authorization) {\n\tconst match = authorization.match(BASIC_AUTHORIZATION_PATTERN);\n\tif (!match) throw new Error(\"Authorization header is not a Basic credential\");\n\tconst encoded = match[1] ?? \"\";\n\tconst decoded = new TextDecoder().decode(base64.decode(encoded));\n\tconst separatorIndex = decoded.indexOf(\":\");\n\tif (separatorIndex === -1) throw new Error(\"Basic credential is missing the client id/secret separator\");\n\tconst rawClientId = decoded.slice(0, separatorIndex);\n\tconst rawClientSecret = decoded.slice(separatorIndex + 1);\n\tif (!rawClientId || !rawClientSecret) throw new Error(\"Basic credential client id and secret must both be non-empty\");\n\treturn {\n\t\tclientId: formUrlDecode(rawClientId),\n\t\tclientSecret: formUrlDecode(rawClientSecret)\n\t};\n}\n//#endregion\nexport { decodeBasicCredentials, encodeBasicCredentials };\n","import { SignJWT, importJWK, importPKCS8 } from \"jose\";\n//#region src/oauth2/client-assertion.ts\n/** Asymmetric signing algorithms compatible with private_key_jwt (RFC 7523). */\nconst PRIVATE_KEY_JWT_SIGNING_ALGORITHMS = [\n\t\"RS256\",\n\t\"RS384\",\n\t\"RS512\",\n\t\"PS256\",\n\t\"PS384\",\n\t\"PS512\",\n\t\"ES256\",\n\t\"ES384\",\n\t\"ES512\",\n\t\"EdDSA\"\n];\nfunction assertSupportedPrivateKeyJwtAlgorithm(candidate) {\n\tif (!PRIVATE_KEY_JWT_SIGNING_ALGORITHMS.includes(candidate)) throw new Error(`Unsupported private_key_jwt signing algorithm: ${candidate}. Use one of ${PRIVATE_KEY_JWT_SIGNING_ALGORITHMS.join(\", \")}.`);\n}\n/**\n* Validates `private_key_jwt` options eagerly and returns the algorithm to\n* use for signing.\n*\n* Asserts that key material is configured, that any explicit `algorithm` is\n* supported, that any JWK-embedded `alg` is supported, and that the two\n* agree when both are set.\n*/\nfunction resolveValidPrivateKeyJwtOptions(options) {\n\tif (!options.privateKeyJwk && !options.privateKeyPem) throw new Error(\"private_key_jwt requires either privateKeyJwk or privateKeyPem\");\n\tif (options.algorithm) assertSupportedPrivateKeyJwtAlgorithm(options.algorithm);\n\tconst jwkAlg = options.privateKeyJwk?.alg;\n\tif (typeof jwkAlg === \"string\") assertSupportedPrivateKeyJwtAlgorithm(jwkAlg);\n\tif (options.algorithm && typeof jwkAlg === \"string\" && options.algorithm !== jwkAlg) throw new Error(`JWK alg \"${jwkAlg}\" does not match configured algorithm \"${options.algorithm}\". Remove the JWK alg field, or pass an algorithm that matches the JWK.`);\n\treturn options.algorithm ?? (typeof jwkAlg === \"string\" ? jwkAlg : \"RS256\");\n}\nconst CLIENT_ASSERTION_TYPE = \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\";\n/**\n* Signs an RFC 7523 client assertion JWT for `private_key_jwt` authentication.\n*\n* The JWT contains these claims:\n*\n* - iss=clientId\n* - sub=clientId\n* - aud=tokenEndpoint\n* - exp=now + 120s\n* - jti=unique\n* - iat=now\n*/\nasync function signPrivateKeyJwtClientAssertion({ clientId, tokenEndpoint, privateKeyJwk, privateKeyPem, kid, algorithm, expiresIn = 120 }) {\n\tconst resolvedAlg = resolveValidPrivateKeyJwtOptions({\n\t\tprivateKeyJwk,\n\t\tprivateKeyPem,\n\t\talgorithm\n\t});\n\tconst resolvedKid = kid ?? privateKeyJwk?.kid;\n\tconst key = privateKeyJwk ? await importJWK(privateKeyJwk, resolvedAlg) : await importPKCS8(privateKeyPem, resolvedAlg);\n\tconst now = Math.floor(Date.now() / 1e3);\n\tconst jti = crypto.randomUUID();\n\tconst header = {\n\t\talg: resolvedAlg,\n\t\ttyp: \"JWT\"\n\t};\n\tif (resolvedKid) header.kid = resolvedKid;\n\treturn new SignJWT({}).setProtectedHeader(header).setIssuer(clientId).setSubject(clientId).setAudience(tokenEndpoint).setIssuedAt(now).setExpirationTime(now + expiresIn).setJti(jti).sign(key);\n}\n/**\n* Creates a client assertion getter for `private_key_jwt` authentication.\n*\n* Validates options eagerly (key material, supported algorithm, JWK alg\n* agreement) so misconfiguration surfaces at construction rather than on the\n* first token request. The returned function signs a fresh RFC 7523 JWT\n* assertion for every token endpoint request.\n*/\nfunction createPrivateKeyJwtClientAssertionGetter(options) {\n\tresolveValidPrivateKeyJwtOptions({\n\t\tprivateKeyJwk: options.privateKeyJwk,\n\t\tprivateKeyPem: options.privateKeyPem,\n\t\talgorithm: options.algorithm\n\t});\n\treturn ({ clientId, tokenEndpoint }) => signPrivateKeyJwtClientAssertion({\n\t\tclientId,\n\t\ttokenEndpoint,\n\t\tprivateKeyJwk: options.privateKeyJwk,\n\t\tprivateKeyPem: options.privateKeyPem,\n\t\tkid: options.kid,\n\t\talgorithm: options.algorithm,\n\t\texpiresIn: options.expiresIn\n\t});\n}\n/**\n* Resolves a client assertion getter into `client_assertion` + `client_assertion_type` params for injection into a token request body.\n*/\nasync function resolveClientAssertionParams({ getClientAssertion, context }) {\n\treturn {\n\t\tclient_assertion: await getClientAssertion(context),\n\t\tclient_assertion_type: CLIENT_ASSERTION_TYPE\n\t};\n}\n//#endregion\nexport { CLIENT_ASSERTION_TYPE, PRIVATE_KEY_JWT_SIGNING_ALGORITHMS, createPrivateKeyJwtClientAssertionGetter, resolveClientAssertionParams, signPrivateKeyJwtClientAssertion };\n","//#region src/error.ts\nvar BetterFetchError = class extends Error {\n\tconstructor(status, statusText, error) {\n\t\tsuper(statusText || status.toString(), { cause: error });\n\t\tthis.status = status;\n\t\tthis.statusText = statusText;\n\t\tthis.error = error;\n\t\tError.captureStackTrace(this, this.constructor);\n\t}\n};\n//#endregion\n//#region src/plugins.ts\nconst initializePlugins = async (url, options) => {\n\tlet opts = options || {};\n\tconst hooks = {\n\t\tonRequest: [options === null || options === void 0 ? void 0 : options.onRequest],\n\t\tonResponse: [options === null || options === void 0 ? void 0 : options.onResponse],\n\t\tonSuccess: [options === null || options === void 0 ? void 0 : options.onSuccess],\n\t\tonError: [options === null || options === void 0 ? void 0 : options.onError],\n\t\tonRetry: [options === null || options === void 0 ? void 0 : options.onRetry]\n\t};\n\tif (!options || !(options === null || options === void 0 ? void 0 : options.plugins)) return {\n\t\turl,\n\t\toptions: opts,\n\t\thooks\n\t};\n\tfor (const plugin of (options === null || options === void 0 ? void 0 : options.plugins) || []) {\n\t\tvar _plugin$hooks, _plugin$hooks2, _plugin$hooks3, _plugin$hooks4, _plugin$hooks5;\n\t\tif (plugin.init) {\n\t\t\tvar _plugin$init;\n\t\t\tconst pluginRes = await ((_plugin$init = plugin.init) === null || _plugin$init === void 0 ? void 0 : _plugin$init.call(plugin, url.toString(), opts));\n\t\t\topts = pluginRes.options || opts;\n\t\t\turl = pluginRes.url;\n\t\t}\n\t\thooks.onRequest.push((_plugin$hooks = plugin.hooks) === null || _plugin$hooks === void 0 ? void 0 : _plugin$hooks.onRequest);\n\t\thooks.onResponse.push((_plugin$hooks2 = plugin.hooks) === null || _plugin$hooks2 === void 0 ? void 0 : _plugin$hooks2.onResponse);\n\t\thooks.onSuccess.push((_plugin$hooks3 = plugin.hooks) === null || _plugin$hooks3 === void 0 ? void 0 : _plugin$hooks3.onSuccess);\n\t\thooks.onError.push((_plugin$hooks4 = plugin.hooks) === null || _plugin$hooks4 === void 0 ? void 0 : _plugin$hooks4.onError);\n\t\thooks.onRetry.push((_plugin$hooks5 = plugin.hooks) === null || _plugin$hooks5 === void 0 ? void 0 : _plugin$hooks5.onRetry);\n\t}\n\treturn {\n\t\turl,\n\t\toptions: opts,\n\t\thooks\n\t};\n};\n//#endregion\n//#region src/retry.ts\nvar LinearRetryStrategy = class {\n\tconstructor(options) {\n\t\tthis.options = options;\n\t}\n\tshouldAttemptRetry(attempt, response) {\n\t\tif (this.options.shouldRetry) return Promise.resolve(attempt < this.options.attempts && this.options.shouldRetry(response));\n\t\treturn Promise.resolve(attempt < this.options.attempts);\n\t}\n\tgetDelay() {\n\t\treturn this.options.delay;\n\t}\n};\nvar ExponentialRetryStrategy = class {\n\tconstructor(options) {\n\t\tthis.options = options;\n\t}\n\tshouldAttemptRetry(attempt, response) {\n\t\tif (this.options.shouldRetry) return Promise.resolve(attempt < this.options.attempts && this.options.shouldRetry(response));\n\t\treturn Promise.resolve(attempt < this.options.attempts);\n\t}\n\tgetDelay(attempt) {\n\t\treturn Math.min(this.options.maxDelay, this.options.baseDelay * 2 ** attempt);\n\t}\n};\nfunction createRetryStrategy(options) {\n\tif (typeof options === \"number\") return new LinearRetryStrategy({\n\t\ttype: \"linear\",\n\t\tattempts: options,\n\t\tdelay: 1e3\n\t});\n\tswitch (options.type) {\n\t\tcase \"linear\": return new LinearRetryStrategy(options);\n\t\tcase \"exponential\": return new ExponentialRetryStrategy(options);\n\t\tdefault: throw new Error(\"Invalid retry strategy\");\n\t}\n}\n//#endregion\n//#region src/create-fetch/schema.ts\nconst methods = [\n\t\"get\",\n\t\"post\",\n\t\"put\",\n\t\"patch\",\n\t\"delete\"\n];\nconst createSchema = (schema, config) => {\n\treturn {\n\t\tschema,\n\t\tconfig\n\t};\n};\n//#endregion\n//#region src/method.ts\nfunction parseMethodModifier(path) {\n\tif (!path.startsWith(\"@\")) return {\n\t\tmethod: void 0,\n\t\tpath\n\t};\n\tconst separator = path.indexOf(\"/\");\n\tconst method = path.slice(1, separator === -1 ? void 0 : separator);\n\tif (!methods.includes(method)) return {\n\t\tmethod: void 0,\n\t\tpath\n\t};\n\treturn {\n\t\tmethod,\n\t\tpath: separator === -1 ? path : path.slice(separator + 1)\n\t};\n}\n//#endregion\n//#region src/url.ts\nconst isReservedPathSegment = (value) => value === \".\" || value === \"..\";\nconst encodeLiteralPathSegment = (segment) => segment.split(\":\").map((part) => encodeURIComponent(part)).join(\":\");\nfunction resolvePathSegment(segment, pathParams) {\n\tconst pathParam = pathParams.get(segment);\n\tif (pathParam === void 0) return encodeLiteralPathSegment(segment);\n\tif (isReservedPathSegment(pathParam)) throw new TypeError(\"Path parameters cannot be reserved path segments\");\n\treturn encodeURIComponent(pathParam);\n}\n/**\n* Normalize URL\n*/\nfunction getURL$1(url, option) {\n\tconst { baseURL, params, query } = option || {\n\t\tquery: {},\n\t\tparams: {},\n\t\tbaseURL: \"\"\n\t};\n\tlet basePath = url.startsWith(\"http\") ? url.split(\"/\").slice(0, 3).join(\"/\") : baseURL || \"\";\n\tconst { path: requestPath } = parseMethodModifier(url);\n\tif (requestPath !== url) url = `/${requestPath}`;\n\tif (!basePath.endsWith(\"/\")) basePath += \"/\";\n\tlet [path, urlQuery] = url.replace(basePath, \"\").split(\"?\");\n\tconst queryParams = new URLSearchParams(urlQuery);\n\tfor (const [key, value] of Object.entries(query || {})) {\n\t\tif (value == null) continue;\n\t\tlet serializedValue;\n\t\tif (typeof value === \"string\") serializedValue = value;\n\t\telse if (Array.isArray(value)) {\n\t\t\tfor (const val of value) queryParams.append(key, val);\n\t\t\tcontinue;\n\t\t} else serializedValue = JSON.stringify(value);\n\t\tqueryParams.set(key, serializedValue);\n\t}\n\tconst pathParams = /* @__PURE__ */ new Map();\n\tif (params) if (Array.isArray(params)) {\n\t\tconst paramPaths = path.split(\"/\").filter((p) => p.startsWith(\":\"));\n\t\tfor (const [index, key] of paramPaths.entries()) {\n\t\t\tconst value = params[index];\n\t\t\tpathParams.set(key, String(value));\n\t\t}\n\t} else for (const [key, value] of Object.entries(params)) pathParams.set(`:${key}`, String(value));\n\tpath = path.split(\"/\").map((segment) => resolvePathSegment(segment, pathParams)).join(\"/\");\n\tpath = path.replace(/^\\/+/, \"\");\n\tlet queryParamString = queryParams.toString();\n\tqueryParamString = queryParamString.length > 0 ? `?${queryParamString}`.replace(/\\+/g, \"%20\") : \"\";\n\tif (!basePath.startsWith(\"http\")) return `${basePath}${path}${queryParamString}`;\n\treturn new URL(`${path}${queryParamString}`, basePath);\n}\n//#endregion\n//#region src/auth.ts\nconst getAuthHeader = async (options) => {\n\tconst headers = {};\n\tconst getValue = async (value) => typeof value === \"function\" ? await value() : value;\n\tif (options === null || options === void 0 ? void 0 : options.auth) {\n\t\tif (options.auth.type === \"Bearer\") {\n\t\t\tconst token = await getValue(options.auth.token);\n\t\t\tif (!token) return headers;\n\t\t\theaders[\"authorization\"] = `Bearer ${token}`;\n\t\t} else if (options.auth.type === \"Basic\") {\n\t\t\tconst [username, password] = await Promise.all([getValue(options.auth.username), getValue(options.auth.password)]);\n\t\t\tif (!username || !password) return headers;\n\t\t\theaders[\"authorization\"] = `Basic ${btoa(`${username}:${password}`)}`;\n\t\t} else if (options.auth.type === \"Custom\") {\n\t\t\tconst [prefix, value] = await Promise.all([getValue(options.auth.prefix), getValue(options.auth.value)]);\n\t\t\tif (!value) return headers;\n\t\t\theaders[\"authorization\"] = `${prefix !== null && prefix !== void 0 ? prefix : \"\"} ${value}`;\n\t\t}\n\t}\n\treturn headers;\n};\n//#endregion\n//#region src/utils.ts\nconst JSON_RE = /^application\\/(?:[\\w!#$%&*.^`~-]*\\+)?json(;.+)?$/i;\nfunction detectResponseType(request) {\n\tconst _contentType = request.headers.get(\"content-type\");\n\tconst textTypes = /* @__PURE__ */ new Set([\n\t\t\"image/svg\",\n\t\t\"application/xml\",\n\t\t\"application/xhtml\",\n\t\t\"application/html\"\n\t]);\n\tif (!_contentType) return \"json\";\n\tconst contentType = _contentType.split(\";\").shift() || \"\";\n\tif (JSON_RE.test(contentType)) return \"json\";\n\tif (textTypes.has(contentType) || contentType.startsWith(\"text/\")) return \"text\";\n\treturn \"blob\";\n}\nfunction isJSONParsable(value) {\n\ttry {\n\t\tJSON.parse(value);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn false;\n\t}\n}\nfunction isJSONSerializable(value) {\n\tif (value === void 0) return false;\n\tconst t = typeof value;\n\tif (t === \"string\" || t === \"number\" || t === \"boolean\" || t === null) return true;\n\tif (t !== \"object\") return false;\n\tif (Array.isArray(value)) return true;\n\tif (value.buffer) return false;\n\treturn value.constructor && value.constructor.name === \"Object\" || typeof value.toJSON === \"function\";\n}\nfunction jsonParse(text) {\n\ttry {\n\t\treturn JSON.parse(text);\n\t} catch (error) {\n\t\treturn text;\n\t}\n}\nfunction isFunction(value) {\n\treturn typeof value === \"function\";\n}\nfunction getFetch(options) {\n\tif (options === null || options === void 0 ? void 0 : options.customFetchImpl) return options.customFetchImpl;\n\tif (typeof globalThis !== \"undefined\" && isFunction(globalThis.fetch)) return globalThis.fetch;\n\tif (typeof window !== \"undefined\" && isFunction(window.fetch)) return window.fetch;\n\tthrow new Error(\"No fetch implementation found\");\n}\nfunction isPayloadMethod(method) {\n\tif (!method) return false;\n\treturn [\n\t\t\"POST\",\n\t\t\"PUT\",\n\t\t\"PATCH\",\n\t\t\"DELETE\"\n\t].includes(method.toUpperCase());\n}\nfunction isRouteMethod(method) {\n\tconst routeMethod = [\n\t\t\"GET\",\n\t\t\"POST\",\n\t\t\"PUT\",\n\t\t\"PATCH\",\n\t\t\"DELETE\"\n\t];\n\tif (!method) return false;\n\treturn routeMethod.includes(method.toUpperCase());\n}\nfunction mergeHeaders(...sources) {\n\tconst merged = {};\n\tfor (const source of sources) {\n\t\tif (!source) continue;\n\t\tif (source instanceof Headers) source.forEach((value, key) => {\n\t\t\tmerged[key] = value;\n\t\t});\n\t\telse {\n\t\t\tconst entries = Array.isArray(source) ? source : Object.entries(source);\n\t\t\tfor (const [key, value] of entries) if (value !== null && value !== void 0) merged[key] = value;\n\t\t}\n\t}\n\treturn merged;\n}\nasync function getHeaders(opts) {\n\tconst headers = new Headers(mergeHeaders(opts === null || opts === void 0 ? void 0 : opts.headers, await getAuthHeader(opts)));\n\tif (!headers.has(\"content-type\")) {\n\t\tconst contentType = detectContentType(opts === null || opts === void 0 ? void 0 : opts.body);\n\t\tif (contentType) headers.set(\"content-type\", contentType);\n\t}\n\treturn headers;\n}\nfunction getURL(url, options) {\n\tconst { path } = parseMethodModifier(url);\n\tif (path !== url) url = `/${path}`;\n\tlet _url;\n\ttry {\n\t\tif (url.startsWith(\"http\")) _url = url;\n\t\telse {\n\t\t\tlet baseURL = options === null || options === void 0 ? void 0 : options.baseURL;\n\t\t\tif (baseURL && !(baseURL === null || baseURL === void 0 ? void 0 : baseURL.endsWith(\"/\"))) baseURL = baseURL + \"/\";\n\t\t\tif (url.startsWith(\"/\")) _url = new URL(url.substring(1), baseURL);\n\t\t\telse _url = new URL(url, options === null || options === void 0 ? void 0 : options.baseURL);\n\t\t}\n\t} catch (e) {\n\t\tif (e instanceof TypeError) {\n\t\t\tif (!(options === null || options === void 0 ? void 0 : options.baseURL)) throw TypeError(`Invalid URL ${url}. Are you passing in a relative url but not setting the baseURL?`);\n\t\t\tthrow TypeError(`Invalid URL ${url}. Please validate that you are passing the correct input.`);\n\t\t}\n\t\tthrow e;\n\t}\n\t/**\n\t* Dynamic Parameters.\n\t*/\n\tif (options === null || options === void 0 ? void 0 : options.params) if (Array.isArray(options === null || options === void 0 ? void 0 : options.params)) {\n\t\tconst params = (options === null || options === void 0 ? void 0 : options.params) ? Array.isArray(options.params) ? `/${options.params.join(\"/\")}` : `/${Object.values(options.params).join(\"/\")}` : \"\";\n\t\t_url = _url.toString().split(\"/:\")[0];\n\t\t_url = `${_url.toString()}${params}`;\n\t} else for (const [key, value] of Object.entries(options === null || options === void 0 ? void 0 : options.params)) _url = _url.toString().replace(`:${key}`, String(value));\n\tconst __url = new URL(_url);\n\t/**\n\t* Query Parameters\n\t*/\n\tconst queryParams = options === null || options === void 0 ? void 0 : options.query;\n\tif (queryParams) for (const [key, value] of Object.entries(queryParams)) __url.searchParams.append(key, String(value));\n\treturn __url;\n}\nfunction detectContentType(body) {\n\tif (isJSONSerializable(body)) return \"application/json\";\n\treturn null;\n}\nfunction getMediaType(headers) {\n\tconst contentType = headers.get(\"content-type\");\n\treturn contentType ? contentType.split(\";\")[0].trim().toLowerCase() : null;\n}\nfunction getBody(options, headers) {\n\tconst { body } = options;\n\tif (!body) return null;\n\tif (!isJSONSerializable(body)) return body;\n\tif (typeof body === \"string\") return body;\n\tif (getMediaType(headers) === \"application/x-www-form-urlencoded\") return new URLSearchParams(body).toString();\n\treturn JSON.stringify(body);\n}\nfunction getMethod(url, options) {\n\tif (options === null || options === void 0 ? void 0 : options.method) return options.method.toUpperCase();\n\tconst { method } = parseMethodModifier(url);\n\tif (method) return method.toUpperCase();\n\treturn (options === null || options === void 0 ? void 0 : options.body) ? \"POST\" : \"GET\";\n}\nfunction getTimeout(options, controller) {\n\tlet abortTimeout;\n\tif (!(options === null || options === void 0 ? void 0 : options.signal) && (options === null || options === void 0 ? void 0 : options.timeout)) abortTimeout = setTimeout(() => controller === null || controller === void 0 ? void 0 : controller.abort(), options === null || options === void 0 ? void 0 : options.timeout);\n\treturn {\n\t\tabortTimeout,\n\t\tclearTimeout: () => {\n\t\t\tif (abortTimeout) clearTimeout(abortTimeout);\n\t\t}\n\t};\n}\nfunction bodyParser(data, responseType) {\n\tif (responseType === \"json\") return JSON.parse(data);\n\treturn data;\n}\nvar ValidationError = class ValidationError extends Error {\n\tconstructor(issues, message) {\n\t\tsuper(message || JSON.stringify(issues, null, 2));\n\t\tthis.issues = issues;\n\t\tObject.setPrototypeOf(this, ValidationError.prototype);\n\t}\n};\nasync function parseStandardSchema(schema, input) {\n\tconst result = await schema[\"~standard\"].validate(input);\n\tif (result.issues) throw new ValidationError(result.issues);\n\treturn result.value;\n}\n//#endregion\n//#region \\0@oxc-project+runtime@0.140.0/helpers/esm/typeof.js\nfunction _typeof(o) {\n\t\"@babel/helpers - typeof\";\n\treturn _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function(o) {\n\t\treturn typeof o;\n\t} : function(o) {\n\t\treturn o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n\t}, _typeof(o);\n}\n//#endregion\n//#region \\0@oxc-project+runtime@0.140.0/helpers/esm/toPrimitive.js\nfunction toPrimitive(t, r) {\n\tif (\"object\" != _typeof(t) || !t) return t;\n\tvar e = t[Symbol.toPrimitive];\n\tif (void 0 !== e) {\n\t\tvar i = e.call(t, r || \"default\");\n\t\tif (\"object\" != _typeof(i)) return i;\n\t\tthrow new TypeError(\"@@toPrimitive must return a primitive value.\");\n\t}\n\treturn (\"string\" === r ? String : Number)(t);\n}\n//#endregion\n//#region \\0@oxc-project+runtime@0.140.0/helpers/esm/toPropertyKey.js\nfunction toPropertyKey(t) {\n\tvar i = toPrimitive(t, \"string\");\n\treturn \"symbol\" == _typeof(i) ? i : i + \"\";\n}\n//#endregion\n//#region \\0@oxc-project+runtime@0.140.0/helpers/esm/defineProperty.js\nfunction _defineProperty(e, r, t) {\n\treturn (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n\t\tvalue: t,\n\t\tenumerable: !0,\n\t\tconfigurable: !0,\n\t\twritable: !0\n\t}) : e[r] = t, e;\n}\n//#endregion\n//#region \\0@oxc-project+runtime@0.140.0/helpers/esm/objectSpread2.js\nfunction ownKeys(e, r) {\n\tvar t = Object.keys(e);\n\tif (Object.getOwnPropertySymbols) {\n\t\tvar o = Object.getOwnPropertySymbols(e);\n\t\tr && (o = o.filter(function(r) {\n\t\t\treturn Object.getOwnPropertyDescriptor(e, r).enumerable;\n\t\t})), t.push.apply(t, o);\n\t}\n\treturn t;\n}\nfunction _objectSpread2(e) {\n\tfor (var r = 1; r < arguments.length; r++) {\n\t\tvar t = null != arguments[r] ? arguments[r] : {};\n\t\tr % 2 ? ownKeys(Object(t), !0).forEach(function(r) {\n\t\t\t_defineProperty(e, r, t[r]);\n\t\t}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {\n\t\t\tObject.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n\t\t});\n\t}\n\treturn e;\n}\n//#endregion\n//#region src/fetch.ts\nconst betterFetch = async (url, options) => {\n\tvar _opts$signal, _options$body, _options$jsonParser;\n\tconst { hooks, url: __url, options: opts } = await initializePlugins(url, options);\n\tconst fetch = getFetch(opts);\n\tconst controller = new AbortController();\n\tconst signal = (_opts$signal = opts.signal) !== null && _opts$signal !== void 0 ? _opts$signal : controller.signal;\n\tconst _url = getURL$1(__url, opts);\n\tconst headers = await getHeaders(opts);\n\tconst body = getBody(opts, headers);\n\tconst method = getMethod(__url, opts);\n\tconst context = _objectSpread2(_objectSpread2({}, opts), {}, {\n\t\turl: _url,\n\t\theaders,\n\t\tbody,\n\t\tmethod,\n\t\tsignal\n\t});\n\t/**\n\t* Run all on request hooks\n\t*/\n\tfor (const onRequest of hooks.onRequest) if (onRequest) {\n\t\tconst res = await onRequest(context);\n\t\tif (typeof res === \"object\" && res !== null) Object.assign(context, res);\n\t}\n\tif (\"pipeTo\" in context && typeof context.pipeTo === \"function\" || typeof (options === null || options === void 0 || (_options$body = options.body) === null || _options$body === void 0 ? void 0 : _options$body.pipe) === \"function\") {\n\t\tif (!(\"duplex\" in context)) context.duplex = \"half\";\n\t}\n\tconst { clearTimeout } = getTimeout(opts, controller);\n\tlet response = await fetch(context.url, context);\n\tclearTimeout();\n\tconst responseContext = {\n\t\tresponse,\n\t\trequest: context\n\t};\n\tfor (const onResponse of hooks.onResponse) if (onResponse) {\n\t\tvar _options$hookOptions;\n\t\tconst r = await onResponse(_objectSpread2(_objectSpread2({}, responseContext), {}, { response: (options === null || options === void 0 || (_options$hookOptions = options.hookOptions) === null || _options$hookOptions === void 0 ? void 0 : _options$hookOptions.cloneResponse) ? response.clone() : response }));\n\t\tif (r instanceof Response) response = r;\n\t\telse if (typeof r === \"object\" && r !== null) response = r.response;\n\t}\n\t/**\n\t* OK Branch\n\t*/\n\tif (response.ok) {\n\t\tif (!(context.method !== \"HEAD\")) return {\n\t\t\tdata: \"\",\n\t\t\terror: null\n\t\t};\n\t\tconst responseType = detectResponseType(response);\n\t\tconst successContext = {\n\t\t\tdata: null,\n\t\t\tresponse,\n\t\t\trequest: context\n\t\t};\n\t\tif (responseType === \"json\" || responseType === \"text\") {\n\t\t\tvar _context$jsonParser;\n\t\t\tconst text = await response.text();\n\t\t\tsuccessContext.data = await ((_context$jsonParser = context.jsonParser) !== null && _context$jsonParser !== void 0 ? _context$jsonParser : jsonParse)(text);\n\t\t} else successContext.data = await response[responseType]();\n\t\t/**\n\t\t* Parse the data if the output schema is defined\n\t\t*/\n\t\tif (context === null || context === void 0 ? void 0 : context.output) {\n\t\t\tif (context.output && !context.disableValidation) successContext.data = await parseStandardSchema(context.output, successContext.data);\n\t\t}\n\t\tfor (const onSuccess of hooks.onSuccess) if (onSuccess) {\n\t\t\tvar _options$hookOptions2;\n\t\t\tawait onSuccess(_objectSpread2(_objectSpread2({}, successContext), {}, { response: (options === null || options === void 0 || (_options$hookOptions2 = options.hookOptions) === null || _options$hookOptions2 === void 0 ? void 0 : _options$hookOptions2.cloneResponse) ? response.clone() : response }));\n\t\t}\n\t\tif (options === null || options === void 0 ? void 0 : options.throw) return successContext.data;\n\t\treturn {\n\t\t\tdata: successContext.data,\n\t\t\terror: null\n\t\t};\n\t}\n\tconst parser = (_options$jsonParser = options === null || options === void 0 ? void 0 : options.jsonParser) !== null && _options$jsonParser !== void 0 ? _options$jsonParser : jsonParse;\n\tconst responseText = await response.text();\n\tconst isJSONResponse = isJSONParsable(responseText);\n\tconst errorObject = isJSONResponse ? await parser(responseText) : null;\n\t/**\n\t* Error Branch\n\t*/\n\tconst errorContext = {\n\t\tresponse,\n\t\tresponseText,\n\t\trequest: context,\n\t\terror: _objectSpread2(_objectSpread2({}, errorObject), {}, {\n\t\t\tstatus: response.status,\n\t\t\tstatusText: response.statusText\n\t\t})\n\t};\n\tfor (const onError of hooks.onError) if (onError) {\n\t\tvar _options$hookOptions3;\n\t\tawait onError(_objectSpread2(_objectSpread2({}, errorContext), {}, { response: (options === null || options === void 0 || (_options$hookOptions3 = options.hookOptions) === null || _options$hookOptions3 === void 0 ? void 0 : _options$hookOptions3.cloneResponse) ? response.clone() : response }));\n\t}\n\tif (options === null || options === void 0 ? void 0 : options.retry) {\n\t\tvar _options$retryAttempt;\n\t\tconst retryStrategy = createRetryStrategy(options.retry);\n\t\tconst _retryAttempt = (_options$retryAttempt = options.retryAttempt) !== null && _options$retryAttempt !== void 0 ? _options$retryAttempt : 0;\n\t\tif (await retryStrategy.shouldAttemptRetry(_retryAttempt, response)) {\n\t\t\tfor (const onRetry of hooks.onRetry) if (onRetry) await onRetry(responseContext);\n\t\t\tconst delay = retryStrategy.getDelay(_retryAttempt);\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, delay));\n\t\t\treturn await betterFetch(url, _objectSpread2(_objectSpread2({}, options), {}, { retryAttempt: _retryAttempt + 1 }));\n\t\t}\n\t}\n\tif (options === null || options === void 0 ? void 0 : options.throw) throw new BetterFetchError(response.status, response.statusText, isJSONResponse ? errorObject : responseText);\n\treturn {\n\t\tdata: null,\n\t\terror: _objectSpread2(_objectSpread2({}, errorObject), {}, {\n\t\t\tstatus: response.status,\n\t\t\tstatusText: response.statusText\n\t\t})\n\t};\n};\n//#endregion\n//#region src/create-fetch/index.ts\nconst applySchemaPlugin = (config) => ({\n\tid: \"apply-schema\",\n\tname: \"Apply Schema\",\n\tversion: \"1.0.0\",\n\tasync init(url, options) {\n\t\tvar _config$plugins;\n\t\tlet opts = _objectSpread2(_objectSpread2({}, options), config.query !== void 0 && { query: _objectSpread2(_objectSpread2({}, config.query), options === null || options === void 0 ? void 0 : options.query) });\n\t\tconst schema = ((_config$plugins = config.plugins) === null || _config$plugins === void 0 || (_config$plugins = _config$plugins.find((plugin) => {\n\t\t\tvar _plugin$schema;\n\t\t\treturn ((_plugin$schema = plugin.schema) === null || _plugin$schema === void 0 ? void 0 : _plugin$schema.config) ? url.startsWith(plugin.schema.config.baseURL || \"\") || url.startsWith(plugin.schema.config.prefix || \"\") : false;\n\t\t})) === null || _config$plugins === void 0 ? void 0 : _config$plugins.schema) || config.schema;\n\t\tif (schema) {\n\t\t\tvar _schema$config, _schema$config2;\n\t\t\tlet urlKey = url;\n\t\t\tif ((_schema$config = schema.config) === null || _schema$config === void 0 ? void 0 : _schema$config.prefix) {\n\t\t\t\tif (urlKey.startsWith(schema.config.prefix)) {\n\t\t\t\t\turlKey = urlKey.replace(schema.config.prefix, \"\");\n\t\t\t\t\tif (schema.config.baseURL) url = url.replace(schema.config.prefix, schema.config.baseURL);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ((_schema$config2 = schema.config) === null || _schema$config2 === void 0 ? void 0 : _schema$config2.baseURL) {\n\t\t\t\tif (urlKey.startsWith(schema.config.baseURL)) urlKey = urlKey.replace(schema.config.baseURL, \"\");\n\t\t\t}\n\t\t\tif (urlKey.startsWith(\"/\") && urlKey.charAt(1) === \"@\") urlKey = urlKey.substring(1);\n\t\t\tconst keySchema = schema.schema[urlKey];\n\t\t\tif (keySchema) {\n\t\t\t\tvar _keySchema$method;\n\t\t\t\tconst { method: schemaMethod, path } = parseMethodModifier(urlKey);\n\t\t\t\tif (schemaMethod) url = url.slice(0, url.length - urlKey.length) + path;\n\t\t\t\tlet validatedHeaders = options === null || options === void 0 ? void 0 : options.headers;\n\t\t\t\tif (keySchema.headers && !(options === null || options === void 0 ? void 0 : options.disableValidation)) {\n\t\t\t\t\tconst normalizedHeaders = {};\n\t\t\t\t\tif (options === null || options === void 0 ? void 0 : options.headers) {\n\t\t\t\t\t\tif (options.headers instanceof Headers) options.headers.forEach((value, key) => {\n\t\t\t\t\t\t\tnormalizedHeaders[key.toLowerCase()] = value;\n\t\t\t\t\t\t});\n\t\t\t\t\t\telse if (typeof options.headers === \"object\") {\n\t\t\t\t\t\t\tfor (const [key, value] of Object.entries(options.headers)) if (value !== null && value !== void 0) normalizedHeaders[key.toLowerCase()] = value;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst validated = await parseStandardSchema(keySchema.headers, normalizedHeaders);\n\t\t\t\t\tconst finalHeaders = {};\n\t\t\t\t\tfor (const [key, value] of Object.entries(validated)) finalHeaders[key.toLowerCase()] = value;\n\t\t\t\t\tvalidatedHeaders = finalHeaders;\n\t\t\t\t}\n\t\t\t\tconst method = (_keySchema$method = keySchema.method) !== null && _keySchema$method !== void 0 ? _keySchema$method : schemaMethod;\n\t\t\t\topts = _objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({}, opts), method !== void 0 && { method }), keySchema.output !== void 0 && { output: keySchema.output }), validatedHeaders !== void 0 && { headers: validatedHeaders });\n\t\t\t\tif (!(options === null || options === void 0 ? void 0 : options.disableValidation)) {\n\t\t\t\t\tif (keySchema.query) {\n\t\t\t\t\t\topts.query = await parseStandardSchema(keySchema.query, options === null || options === void 0 ? void 0 : options.query);\n\t\t\t\t\t\tif (opts.query !== null && typeof opts.query === \"object\") {\n\t\t\t\t\t\t\tconst defaults = _objectSpread2({}, config.query);\n\t\t\t\t\t\t\tfor (const key of Object.keys(defaults)) if ((options === null || options === void 0 ? void 0 : options.query) && Object.prototype.hasOwnProperty.call(options.query, key)) defaults[key] = options.query[key];\n\t\t\t\t\t\t\topts.query = _objectSpread2(_objectSpread2({}, defaults), opts.query);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\topts = _objectSpread2(_objectSpread2({}, opts), {}, {\n\t\t\t\t\t\tbody: keySchema.input ? await parseStandardSchema(keySchema.input, options === null || options === void 0 ? void 0 : options.body) : options === null || options === void 0 ? void 0 : options.body,\n\t\t\t\t\t\tparams: keySchema.params ? await parseStandardSchema(keySchema.params, options === null || options === void 0 ? void 0 : options.params) : options === null || options === void 0 ? void 0 : options.params\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\turl,\n\t\t\t\t\toptions: opts\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn _objectSpread2({ url }, (options !== void 0 || config.query !== void 0) && { options: opts });\n\t}\n});\nconst createFetch = (config) => {\n\tasync function $fetch(url, options) {\n\t\tconst opts = _objectSpread2(_objectSpread2(_objectSpread2({}, config), options), {}, {\n\t\t\theaders: mergeHeaders(config === null || config === void 0 ? void 0 : config.headers, options === null || options === void 0 ? void 0 : options.headers),\n\t\t\tplugins: [\n\t\t\t\t...(config === null || config === void 0 ? void 0 : config.plugins) || [],\n\t\t\t\tapplySchemaPlugin(config || {}),\n\t\t\t\t...(options === null || options === void 0 ? void 0 : options.plugins) || []\n\t\t\t]\n\t\t});\n\t\tif (config === null || config === void 0 ? void 0 : config.catchAllError) try {\n\t\t\treturn await betterFetch(url, opts);\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tdata: null,\n\t\t\t\terror: {\n\t\t\t\t\tstatus: 500,\n\t\t\t\t\tstatusText: \"Fetch Error\",\n\t\t\t\t\tmessage: \"Fetch related error. Captured by catchAllError option. See error property for more details.\",\n\t\t\t\t\terror\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\treturn await betterFetch(url, opts);\n\t}\n\treturn $fetch;\n};\n//#endregion\nexport { BetterFetchError, ValidationError, applySchemaPlugin, betterFetch, bodyParser, createFetch, createRetryStrategy, createSchema, detectContentType, detectResponseType, getBody, getFetch, getHeaders, getMethod, getTimeout, getURL, initializePlugins, isFunction, isJSONParsable, isJSONSerializable, isPayloadMethod, isRouteMethod, jsonParse, mergeHeaders, methods, parseStandardSchema };\n\n//# sourceMappingURL=index.js.map","import { BetterAuthError } from \"../error/index.mjs\";\nimport { betterFetch } from \"@better-fetch/fetch\";\n//#region src/oauth2/reject-redirects.ts\nconst httpRedirectStatuses = new Set([\n\t301,\n\t302,\n\t303,\n\t307,\n\t308\n]);\n/**\n* Whether a response from a `redirect: \"manual\"` fetch is a redirect.\n*\n* Node/undici exposes the real 3xx status. Spec-compliant runtimes (Cloudflare\n* Workers, Deno, browsers) return an opaque-redirect filtered response with\n* status 0 and type `\"opaqueredirect\"`, so the status alone is not enough.\n*/\nfunction isRedirectResponse(response) {\n\treturn response.type === \"opaqueredirect\" || httpRedirectStatuses.has(response.status);\n}\nfunction redirectRefused(endpoint) {\n\treturn new BetterAuthError(`The OAuth endpoint \"${endpoint}\" returned an HTTP redirect. Server-side OAuth fetches refuse redirects to prevent SSRF; configure the final endpoint URL.`);\n}\n/**\n* Fetch option that refuses HTTP redirects portably.\n*\n* Cloudflare Workers (workerd) rejects `redirect: \"error\"`, so manual mode is\n* used and the resolved response is checked with {@link assertResponseNotRedirect}\n* (or, for betterFetch, with {@link fetchRefusingRedirects}).\n*/\nconst noFollowRedirect = { redirect: \"manual\" };\n/**\n* Throw when a native-`fetch` response (e.g. jose's JWKS loader) resolved to a\n* redirect, so an attacker-influenced endpoint cannot bounce a server-side\n* request to an internal address.\n*/\nfunction assertResponseNotRedirect(endpoint, response) {\n\tif (isRedirectResponse(response)) throw redirectRefused(endpoint);\n}\n/**\n* betterFetch that refuses HTTP redirects on a server-side OAuth fetch.\n*\n* Returns the betterFetch result and throws if the endpoint redirected, on both\n* undici (real 3xx status) and spec-compliant runtimes (opaque redirect, where\n* the error status is 0). The redirect is never followed on any runtime.\n*/\nasync function fetchRefusingRedirects(url, options) {\n\tlet redirected = false;\n\tconst onError = options?.onError;\n\tconst result = await betterFetch(url, {\n\t\t...options,\n\t\t...noFollowRedirect,\n\t\tasync onError(context) {\n\t\t\tif (isRedirectResponse(context.response)) redirected = true;\n\t\t\tawait onError?.(context);\n\t\t}\n\t}).catch((error) => {\n\t\tif (redirected) throw redirectRefused(url);\n\t\tthrow error;\n\t});\n\tif (redirected) throw redirectRefused(url);\n\treturn result;\n}\n//#endregion\nexport { assertResponseNotRedirect, fetchRefusingRedirects, noFollowRedirect };\n","import { base64url, calculateJwkThumbprint, decodeProtectedHeader, importJWK, jwtVerify } from \"jose\";\n//#region src/oauth2/dpop.ts\nconst DPOP_AUTHORIZATION_SCHEME = \"DPoP\";\nconst BEARER_AUTHORIZATION_SCHEME = \"Bearer\";\nconst DPOP_PROOF_TYPE = \"dpop+jwt\";\nconst DPOP_SIGNING_ALGORITHMS = [\n\t\"EdDSA\",\n\t\"ES256\",\n\t\"ES512\",\n\t\"PS256\",\n\t\"RS256\"\n];\nconst DEFAULT_DPOP_PROOF_MAX_AGE_SECONDS = 300;\nconst MAX_DPOP_JTI_LENGTH = 512;\nconst JWK_PRIVATE_FIELDS = new Set([\n\t\"d\",\n\t\"p\",\n\t\"q\",\n\t\"dp\",\n\t\"dq\",\n\t\"qi\",\n\t\"oth\",\n\t\"k\"\n]);\nfunction createInMemoryDpopReplayStore() {\n\tconst reservations = /* @__PURE__ */ new Map();\n\treturn { reserve({ key, expiresAt, now }) {\n\t\tconst nowMs = now.getTime();\n\t\tfor (const [storedKey, expiresAtMs] of reservations) if (expiresAtMs <= nowMs) reservations.delete(storedKey);\n\t\tif (reservations.has(key)) return false;\n\t\treservations.set(key, expiresAt.getTime());\n\t\treturn true;\n\t} };\n}\n/**\n* Database-backed DPoP proof replay store built on the auth context's\n* verification reservation primitive (`internalAdapter.reserveVerificationValue`),\n* the same atomic single-use mechanism that guards SAML assertion ids and other\n* one-time tokens. A replayed proof collides on the deterministic reservation id\n* so `reserve` returns `false`, giving cross-instance anti-replay. Prefer this\n* over {@link createInMemoryDpopReplayStore} for any multi-instance or serverless\n* resource server. Requires database-backed verification storage; a\n* secondary-storage-only deployment rejects the proof (fails closed).\n*/\nfunction createDpopReplayStore(reservations) {\n\treturn { reserve: ({ key, expiresAt }) => reservations.reserveVerificationValue({\n\t\tidentifier: `dpop-proof:${key}`,\n\t\tvalue: key,\n\t\texpiresAt\n\t}) };\n}\nfunction createDpopProofError(code, message) {\n\treturn Object.assign(new Error(message), { code });\n}\nfunction isDpopProofError(error) {\n\treturn error instanceof Error && \"code\" in error && error.code === \"invalid_dpop_proof\";\n}\nfunction parseAccessTokenAuthorization(authorization) {\n\tif (!authorization) return void 0;\n\tconst value = authorization.trim();\n\tif (!value) return void 0;\n\tconst match = /^([A-Za-z][A-Za-z0-9!#$%&'*+.^_`|~-]*)\\s+(.+)$/.exec(value);\n\tif (!match) return {\n\t\tscheme: \"Unknown\",\n\t\ttoken: value\n\t};\n\tconst scheme = match[1] ?? \"\";\n\tconst token = match[2]?.trim() ?? \"\";\n\tif (scheme.toLowerCase() === \"bearer\") return {\n\t\tscheme: \"Bearer\",\n\t\ttoken\n\t};\n\tif (scheme.toLowerCase() === \"dpop\") return {\n\t\tscheme: \"DPoP\",\n\t\ttoken\n\t};\n\treturn {\n\t\tscheme: \"Unknown\",\n\t\ttoken: value\n\t};\n}\nfunction stripAccessTokenAuthorizationScheme(token) {\n\treturn parseAccessTokenAuthorization(token)?.token ?? token;\n}\nfunction normalizeDpopHtu(url) {\n\tconst parsed = new URL(url);\n\tif (parsed.hash) throw new Error(\"DPoP proof htu must not contain a fragment\");\n\treturn `${parsed.origin}${parsed.pathname}`;\n}\nasync function deriveDpopAth(accessToken) {\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(accessToken));\n\treturn base64url.encode(new Uint8Array(digest));\n}\nasync function deriveDpopJkt(jwk) {\n\treturn calculateJwkThumbprint(jwk, \"sha256\");\n}\n/**\n* Extracts the DPoP key thumbprint from an RFC 7800 `cnf` confirmation. The\n* input is untrusted (a JWT claim, a JSON column), so any shape other than an\n* object carrying a non-empty string `jkt` (a primitive, an array, a different\n* confirmation method such as mTLS `x5t#S256`) yields `undefined` instead of\n* throwing.\n*/\nfunction getConfirmationJkt(confirmation) {\n\tif (!confirmation || typeof confirmation !== \"object\" || Array.isArray(confirmation)) return;\n\tconst jkt = confirmation.jkt;\n\treturn typeof jkt === \"string\" && jkt.length > 0 ? jkt : void 0;\n}\nfunction getDpopJktFromPayload(payload) {\n\treturn getConfirmationJkt(payload.cnf);\n}\nfunction getStringClaim(payload, claim) {\n\tconst value = payload[claim];\n\treturn typeof value === \"string\" && value.length > 0 ? value : void 0;\n}\nfunction getNumberClaim(payload, claim) {\n\tconst value = payload[claim];\n\treturn typeof value === \"number\" && Number.isFinite(value) ? value : void 0;\n}\nfunction assertSupportedDpopAlgorithm(alg, signingAlgorithms) {\n\tif (!alg || alg === \"none\" || alg.startsWith(\"HS\")) throw createDpopProofError(\"invalid_dpop_proof\", \"DPoP proof must use an asymmetric JWS algorithm\");\n\tif (!signingAlgorithms.includes(alg)) throw createDpopProofError(\"invalid_dpop_proof\", \"DPoP proof uses an unsupported JWS algorithm\");\n}\nfunction assertPublicJwk(jwk) {\n\tif (!jwk || typeof jwk !== \"object\" || Array.isArray(jwk)) throw createDpopProofError(\"invalid_dpop_proof\", \"DPoP proof header must include a public jwk\");\n\tif (jwk.kty === \"oct\") throw createDpopProofError(\"invalid_dpop_proof\", \"DPoP proof jwk must be asymmetric\");\n\tfor (const field of JWK_PRIVATE_FIELDS) if (field in jwk) throw createDpopProofError(\"invalid_dpop_proof\", \"DPoP proof jwk must not contain private key material\");\n}\nasync function deriveDpopReplayKey(params) {\n\tconst input = `${params.jkt}\\n${params.htm}\\n${params.htu}\\n${params.jti}`;\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(input));\n\treturn base64url.encode(new Uint8Array(digest));\n}\nasync function reserveDpopReplay(replayStore, reservation) {\n\tif (!replayStore) return;\n\tif (!await replayStore.reserve(reservation)) throw createDpopProofError(\"invalid_dpop_proof\", \"DPoP proof jti has already been used\");\n}\nasync function verifyDpopProof({ proofJwt, method, url, accessToken, expectedJkt, requireAth = false, nowSeconds = Math.floor(Date.now() / 1e3), proofMaxAgeSeconds = DEFAULT_DPOP_PROOF_MAX_AGE_SECONDS, signingAlgorithms = DPOP_SIGNING_ALGORITHMS, replayStore }) {\n\tif (!proofJwt || proofJwt.split(\".\").length !== 3) throw createDpopProofError(\"invalid_dpop_proof\", \"DPoP proof must be a compact JWT\");\n\tlet protectedHeader;\n\ttry {\n\t\tprotectedHeader = decodeProtectedHeader(proofJwt);\n\t} catch (error) {\n\t\tthrow createDpopProofError(\"invalid_dpop_proof\", error instanceof Error ? error.message : \"DPoP proof header is invalid\");\n\t}\n\tif (protectedHeader.typ !== \"dpop+jwt\") throw createDpopProofError(\"invalid_dpop_proof\", \"DPoP proof typ must be \\\"dpop+jwt\\\"\");\n\tassertSupportedDpopAlgorithm(protectedHeader.alg, signingAlgorithms);\n\tassertPublicJwk(protectedHeader.jwk);\n\tlet payload;\n\ttry {\n\t\tpayload = (await jwtVerify(proofJwt, await importJWK(protectedHeader.jwk, protectedHeader.alg), { typ: DPOP_PROOF_TYPE })).payload;\n\t} catch (error) {\n\t\tthrow createDpopProofError(\"invalid_dpop_proof\", error instanceof Error ? error.message : \"DPoP proof signature is invalid\");\n\t}\n\tconst htm = getStringClaim(payload, \"htm\");\n\tconst htu = getStringClaim(payload, \"htu\");\n\tconst jti = getStringClaim(payload, \"jti\");\n\tconst iat = getNumberClaim(payload, \"iat\");\n\tif (!htm || !htu || !jti || iat === void 0) throw createDpopProofError(\"invalid_dpop_proof\", \"DPoP proof must include htm, htu, jti, and iat claims\");\n\tif (jti.length > MAX_DPOP_JTI_LENGTH) throw createDpopProofError(\"invalid_dpop_proof\", \"DPoP proof jti is too large\");\n\tif (htm.toUpperCase() !== method.toUpperCase()) throw createDpopProofError(\"invalid_dpop_proof\", \"DPoP proof htm does not match the request method\");\n\tlet normalizedHtu;\n\tlet proofHtu;\n\ttry {\n\t\tnormalizedHtu = normalizeDpopHtu(url);\n\t\tproofHtu = normalizeDpopHtu(htu);\n\t} catch (error) {\n\t\tthrow createDpopProofError(\"invalid_dpop_proof\", error instanceof Error ? error.message : \"DPoP proof htu is invalid\");\n\t}\n\tif (proofHtu !== normalizedHtu) throw createDpopProofError(\"invalid_dpop_proof\", \"DPoP proof htu does not match the request URL\");\n\tif (iat > nowSeconds + 5 || nowSeconds - iat > proofMaxAgeSeconds) throw createDpopProofError(\"invalid_dpop_proof\", \"DPoP proof iat is outside the accepted window\");\n\tconst ath = getStringClaim(payload, \"ath\");\n\tif (requireAth && !ath) throw createDpopProofError(\"invalid_dpop_proof\", \"DPoP proof must include an ath claim\");\n\tif (accessToken !== void 0) {\n\t\tif (ath !== await deriveDpopAth(accessToken)) throw createDpopProofError(\"invalid_dpop_proof\", \"DPoP proof ath does not match the access token\");\n\t}\n\tconst jkt = await deriveDpopJkt(protectedHeader.jwk);\n\tif (expectedJkt !== void 0 && jkt !== expectedJkt) throw createDpopProofError(\"invalid_dpop_proof\", \"DPoP proof key does not match the bound token\");\n\tconst replayKey = await deriveDpopReplayKey({\n\t\tjkt,\n\t\thtm: htm.toUpperCase(),\n\t\thtu: normalizedHtu,\n\t\tjti\n\t});\n\tconst expiresAt = /* @__PURE__ */ new Date((iat + proofMaxAgeSeconds) * 1e3);\n\tawait reserveDpopReplay(replayStore, {\n\t\tkey: replayKey,\n\t\texpiresAt,\n\t\tnow: /* @__PURE__ */ new Date(nowSeconds * 1e3)\n\t});\n\treturn {\n\t\tjwk: protectedHeader.jwk,\n\t\tjkt,\n\t\tjti,\n\t\thtm,\n\t\thtu: normalizedHtu,\n\t\tiat,\n\t\tath,\n\t\treplayKey,\n\t\texpiresAt\n\t};\n}\nfunction createDpopBindingError(code, message) {\n\treturn Object.assign(new Error(message), { code });\n}\nfunction isDpopBindingError(error) {\n\treturn error instanceof Error && \"code\" in error && (error.code === \"invalid_token\" || error.code === \"invalid_dpop_proof\");\n}\n/**\n* Enforces the RFC 9449 §7.1 sender-constraint check for a resource request,\n* given an access-token payload that has already been validated (by JWKS or\n* introspection). This is the single source of truth for the\n* \"is the token DPoP-bound? then require the DPoP scheme, a proof, and a\n* matching key\" decision, shared by every resource-server entry point.\n*\n* Throws a {@link DpopBindingError} on any mismatch so callers map the\n* `invalid_token` / `invalid_dpop_proof` code into their own transport. Returns\n* normally for a valid bearer token (no `cnf.jkt`, no DPoP scheme).\n*/\nasync function enforceDpopBinding({ payload, authorization, proofJwt, method, url, replayStore, proofMaxAgeSeconds, signingAlgorithms }) {\n\tconst dpopJkt = getDpopJktFromPayload(payload);\n\tif (!dpopJkt) {\n\t\tif (authorization.scheme === \"DPoP\") throw createDpopBindingError(\"invalid_token\", \"DPoP authorization requires a DPoP-bound access token\");\n\t\treturn;\n\t}\n\tif (authorization.scheme !== \"DPoP\") throw createDpopBindingError(\"invalid_token\", \"DPoP-bound access token requires the DPoP authorization scheme\");\n\tif (!proofJwt) throw createDpopBindingError(\"invalid_dpop_proof\", \"DPoP proof header is required\");\n\ttry {\n\t\tawait verifyDpopProof({\n\t\t\tproofJwt,\n\t\t\tmethod,\n\t\t\turl,\n\t\t\taccessToken: authorization.token,\n\t\t\texpectedJkt: dpopJkt,\n\t\t\trequireAth: true,\n\t\t\tproofMaxAgeSeconds,\n\t\t\tsigningAlgorithms,\n\t\t\treplayStore\n\t\t});\n\t} catch (error) {\n\t\tif (isDpopProofError(error)) throw createDpopBindingError(\"invalid_dpop_proof\", error.message);\n\t\tthrow error;\n\t}\n}\n//#endregion\nexport { BEARER_AUTHORIZATION_SCHEME, DPOP_AUTHORIZATION_SCHEME, DPOP_PROOF_TYPE, DPOP_SIGNING_ALGORITHMS, createDpopBindingError, createDpopProofError, createDpopReplayStore, createInMemoryDpopReplayStore, deriveDpopAth, deriveDpopJkt, enforceDpopBinding, getConfirmationJkt, getDpopJktFromPayload, isDpopBindingError, isDpopProofError, normalizeDpopHtu, parseAccessTokenAuthorization, stripAccessTokenAuthorizationScheme, verifyDpopProof };\n","import { logger } from \"../env/logger.mjs\";\nimport { fetchRefusingRedirects } from \"./reject-redirects.mjs\";\nimport { createInMemoryDpopReplayStore, enforceDpopBinding, getDpopJktFromPayload, isDpopBindingError, parseAccessTokenAuthorization } from \"./dpop.mjs\";\nimport { APIError } from \"better-call\";\nimport { UnsecuredJWT, createLocalJWKSet, decodeProtectedHeader, errors, jwtVerify } from \"jose\";\n//#region src/oauth2/verify.ts\nconst joseInfrastructureErrorCodes = new Set([\n\terrors.JWKSTimeout.code,\n\terrors.JWKSInvalid.code,\n\terrors.JWKSMultipleMatchingKeys.code\n]);\nfunction isJoseInfrastructureError(error) {\n\treturn joseInfrastructureErrorCodes.has(error.code);\n}\n/**\n* @internal\n*/\nconst jwksCache = /* @__PURE__ */ new Map();\n/**\n* Cache for function jwks sources, keyed by a caller-provided stable object.\n* Entries are released with their key, so per-request keys cannot accumulate.\n*/\nconst functionJwksCache = /* @__PURE__ */ new WeakMap();\n/**\n* How long a cached JWKS is trusted before it is refetched\n*\n* @internal\n*/\nconst JWKS_CACHE_TTL_MS = 300 * 1e3;\nconst JWKS_NO_KID_REFETCH_COOLDOWN_MS = 30 * 1e3;\n/**\n* Returns the cached key set when it is within the TTL. When the token carries\n* `kid`, the cached set must contain that key id; without `kid`, key selection\n* is deferred to JOSE because RFC 7515 makes the header parameter optional.\n*/\nfunction getFreshJwksWithKid(cached, kid) {\n\tif (!cached) return void 0;\n\tif (Date.now() - cached.fetchedAt >= JWKS_CACHE_TTL_MS) return void 0;\n\tif (kid && !cached.jwks.keys.some((jwk) => jwk.kid === kid)) return;\n\treturn cached.jwks;\n}\nfunction shouldRefetchCachedJwksWithoutKid(error, resolved) {\n\tif (!(resolved.fromCache && !resolved.kid && (error instanceof errors.JWKSNoMatchingKey || error instanceof errors.JWSSignatureVerificationFailed))) return false;\n\tif (!resolved.noKidRefetchedAt) return true;\n\treturn Date.now() - resolved.noKidRefetchedAt >= JWKS_NO_KID_REFETCH_COOLDOWN_MS;\n}\nasync function fetchJwks(jwksFetch) {\n\tconst jwks = typeof jwksFetch === \"string\" ? await fetchRefusingRedirects(jwksFetch, { headers: { Accept: \"application/json\" } }).then(async (res) => {\n\t\tif (res.error) throw new Error(`Jwks failed: ${res.error.message ?? res.error.statusText}`);\n\t\treturn res.data;\n\t}) : await jwksFetch();\n\tif (!jwks) throw new Error(\"No jwks found\");\n\treturn jwks;\n}\n/**\n* Builds a {@link ResourceRequestInput} from a standard `Request`, reading the\n* `Authorization` and `DPoP` headers and the request method and URL. Resource\n* servers share this so every entry point maps the wire request the same way.\n*/\nfunction requestToResourceInput(request) {\n\treturn {\n\t\tauthorizationHeader: request.headers.get(\"authorization\"),\n\t\tdpopProofJwt: request.headers.get(\"dpop\"),\n\t\tmethod: request.method,\n\t\turl: request.url\n\t};\n}\n/**\n* Process-local, single-instance replay store. See the warning on\n* {@link VerifyAccessTokenRequestOptions.dpop.replayStore}; multi-instance\n* resource servers must pass their own shared store.\n*/\nconst defaultDpopReplayStore = createInMemoryDpopReplayStore();\n/**\n* Performs local verification of an access token for your APIs.\n*\n* Can also be configured for remote verification.\n*/\nasync function verifyJwsAccessToken(token, opts) {\n\ttry {\n\t\tconst resolved = await getJwksForVerification(token, opts);\n\t\tlet jwt;\n\t\ttry {\n\t\t\tjwt = await jwtVerify(token, createLocalJWKSet(resolved.jwks), opts.verifyOptions);\n\t\t} catch (error) {\n\t\t\tif (shouldRefetchCachedJwksWithoutKid(error, resolved)) jwt = await jwtVerify(token, createLocalJWKSet((await getJwksForVerification(token, {\n\t\t\t\t...opts,\n\t\t\t\tforceRefresh: true\n\t\t\t})).jwks), opts.verifyOptions);\n\t\t\telse throw error;\n\t\t}\n\t\tif (jwt.payload.azp) jwt.payload.client_id = jwt.payload.azp;\n\t\treturn jwt.payload;\n\t} catch (error) {\n\t\tif (error instanceof Error) throw error;\n\t\tthrow new Error(error);\n\t}\n}\nasync function getJwks(token, opts) {\n\treturn (await getJwksForVerification(token, opts)).jwks;\n}\nasync function getJwksForVerification(token, opts) {\n\tlet jwtHeaders;\n\ttry {\n\t\tjwtHeaders = decodeProtectedHeader(token);\n\t} catch (error) {\n\t\tif (error instanceof Error) throw error;\n\t\tthrow new Error(error);\n\t}\n\tconst kid = jwtHeaders.kid;\n\tif (typeof opts.jwksFetch !== \"string\") {\n\t\tconst cacheKey = opts.jwksCacheKey;\n\t\tif (!cacheKey) {\n\t\t\tconst jwks = await opts.jwksFetch();\n\t\t\tif (!jwks) throw new Error(\"No jwks found\");\n\t\t\treturn {\n\t\t\t\tjwks,\n\t\t\t\tfromCache: false,\n\t\t\t\tkid\n\t\t\t};\n\t\t}\n\t\tconst cached = functionJwksCache.get(cacheKey);\n\t\tconst cachedJwks = opts.forceRefresh ? void 0 : getFreshJwksWithKid(cached, kid);\n\t\tif (cachedJwks) return {\n\t\t\tjwks: cachedJwks,\n\t\t\tfromCache: true,\n\t\t\tkid,\n\t\t\tnoKidRefetchedAt: cached?.noKidRefetchedAt\n\t\t};\n\t\tconst jwks = await opts.jwksFetch();\n\t\tif (!jwks) throw new Error(\"No jwks found\");\n\t\tconst fetchedAt = Date.now();\n\t\tfunctionJwksCache.set(cacheKey, {\n\t\t\tjwks,\n\t\t\tfetchedAt,\n\t\t\t...opts.forceRefresh && !kid ? { noKidRefetchedAt: fetchedAt } : {}\n\t\t});\n\t\treturn {\n\t\t\tjwks,\n\t\t\tfromCache: false,\n\t\t\tkid\n\t\t};\n\t}\n\tconst cacheKey = opts.jwksFetch;\n\tconst cached = jwksCache.get(cacheKey);\n\tconst cachedJwks = opts.forceRefresh ? void 0 : getFreshJwksWithKid(cached, kid);\n\tif (!cachedJwks) {\n\t\tconst jwks = await fetchJwks(opts.jwksFetch);\n\t\tconst fetchedAt = Date.now();\n\t\tjwksCache.set(cacheKey, {\n\t\t\tjwks,\n\t\t\tfetchedAt,\n\t\t\t...opts.forceRefresh && !kid ? { noKidRefetchedAt: fetchedAt } : {}\n\t\t});\n\t\treturn {\n\t\t\tjwks,\n\t\t\tfromCache: false,\n\t\t\tkid\n\t\t};\n\t}\n\treturn {\n\t\tjwks: cachedJwks,\n\t\tfromCache: true,\n\t\tkid,\n\t\tnoKidRefetchedAt: cached?.noKidRefetchedAt\n\t};\n}\nasync function verifyAccessTokenPayload(token, opts) {\n\tlet payload;\n\tif (opts.jwksUrl && !opts?.remoteVerify?.force) try {\n\t\tpayload = await verifyJwsAccessToken(token, {\n\t\t\tjwksFetch: opts.jwksUrl,\n\t\t\tverifyOptions: opts.verifyOptions\n\t\t});\n\t} catch (error) {\n\t\tif (error instanceof Error) if (error.name === \"TypeError\" || error.name === \"JWSInvalid\") {} else if (error instanceof errors.JWTExpired) throw new APIError(\"UNAUTHORIZED\", { message: \"token expired\" });\n\t\telse if (error instanceof errors.JOSEError) {\n\t\t\tif (isJoseInfrastructureError(error)) throw error;\n\t\t\tthrow new APIError(\"UNAUTHORIZED\", { message: \"invalid access token\" });\n\t\t} else throw error;\n\t\telse throw new Error(error);\n\t}\n\tif (opts?.remoteVerify) {\n\t\tconst { data: introspect, error: introspectError } = await fetchRefusingRedirects(opts.remoteVerify.introspectUrl, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\"\n\t\t\t},\n\t\t\tbody: new URLSearchParams({\n\t\t\t\tclient_id: opts.remoteVerify.clientId,\n\t\t\t\tclient_secret: opts.remoteVerify.clientSecret,\n\t\t\t\ttoken,\n\t\t\t\ttoken_type_hint: \"access_token\"\n\t\t\t}).toString()\n\t\t});\n\t\tif (introspectError) logger.error(`Introspection failed: ${introspectError.message ?? introspectError.statusText}`);\n\t\tif (!introspect) throw new APIError(\"INTERNAL_SERVER_ERROR\", { message: \"introspection failed\" });\n\t\tif (!introspect.active) throw new APIError(\"UNAUTHORIZED\", { message: \"token inactive\" });\n\t\ttry {\n\t\t\tconst unsecuredJwt = new UnsecuredJWT(introspect).encode();\n\t\t\tconst { audience: _audience, ...verifyOptionsNoAudience } = opts.verifyOptions;\n\t\t\tconst skipAudience = !introspect.aud && opts.remoteVerify.allowMissingAudience === true;\n\t\t\tpayload = UnsecuredJWT.decode(unsecuredJwt, skipAudience ? verifyOptionsNoAudience : opts.verifyOptions).payload;\n\t\t} catch (error) {\n\t\t\tthrow new Error(error);\n\t\t}\n\t}\n\tif (!payload) throw new APIError(\"UNAUTHORIZED\", { message: `no token payload` });\n\tconst grantedScopes = parseGrantedScopes(payload.scope);\n\tif (opts.requiredScopes) {\n\t\tconst isScopeSatisfied = opts.isScopeSatisfied ?? ((requiredScope, scopes) => scopes.has(requiredScope));\n\t\tconst missingScopes = opts.requiredScopes.filter((scope) => !isScopeSatisfied(scope, grantedScopes));\n\t\tif (missingScopes.length > 0) throw createInsufficientScopeError(missingScopes);\n\t}\n\treturn payload;\n}\n/**\n* Build the RFC 6750 §3.1 insufficient-scope failure: the access token is valid\n* but lacks scopes the operation needs.\n*\n* Resource-server challenge builders turn this into a `403` carrying a\n* `WWW-Authenticate: Bearer error=\"insufficient_scope\"` challenge that names\n* `scopes`, so the client knows what to request when it re-authorizes. Throw it\n* from a route handler to challenge for scopes only that operation needs; a\n* plain `FORBIDDEN` stays a plain `403`, since a permission denial the client\n* cannot fix by re-authorizing must not send the user through consent again.\n*\n* @param requiredScopes - Every scope the operation requires but the token lacks.\n* @param description - RFC 6750 `error_description` text. It must use the\n* printable ASCII character set allowed by the specification.\n*/\nconst OAUTH_SCOPE_TOKEN_PATTERN = /^[\\x21\\x23-\\x5b\\x5d-\\x7e]+$/;\nconst OAUTH_ERROR_DESCRIPTION_PATTERN = /^[\\x20-\\x21\\x23-\\x5b\\x5d-\\x7e]+$/;\nconst insufficientScopeErrors = /* @__PURE__ */ new WeakSet();\nfunction isOAuthScopeToken(value) {\n\treturn OAUTH_SCOPE_TOKEN_PATTERN.test(value);\n}\nfunction validateScopeTokens(scopes, label) {\n\tfor (const scope of scopes) if (!isOAuthScopeToken(scope)) throw new TypeError(`invalid ${label}: ${JSON.stringify(scope)}`);\n}\nfunction validateRequiredScopes(opts) {\n\tif (opts.requiredScopes) validateScopeTokens(opts.requiredScopes, \"required scope\");\n}\nfunction parseGrantedScopes(scope) {\n\tif (scope === void 0) return /* @__PURE__ */ new Set();\n\tif (typeof scope !== \"string\" || scope.length === 0 || scope.split(\" \").some((token) => !isOAuthScopeToken(token))) throw new APIError(\"UNAUTHORIZED\", {\n\t\tmessage: \"access token scope claim is invalid\",\n\t\terror: \"invalid_token\",\n\t\terror_description: \"access token scope claim is invalid\"\n\t});\n\treturn new Set(scope.split(\" \"));\n}\nfunction createInsufficientScopeError(requiredScopes, description = `access token is missing required scope: ${requiredScopes.join(\" \")}`) {\n\tif (requiredScopes.length === 0) throw new TypeError(\"requiredScopes must contain at least one scope\");\n\tvalidateScopeTokens(requiredScopes, \"required scope\");\n\tif (typeof description !== \"string\" || !OAUTH_ERROR_DESCRIPTION_PATTERN.test(description)) throw new TypeError(\"invalid error_description\");\n\tconst error = new APIError(\"FORBIDDEN\", {\n\t\tmessage: description,\n\t\terror: \"insufficient_scope\",\n\t\terror_description: description,\n\t\tscope: [...new Set(requiredScopes)].join(\" \")\n\t});\n\tinsufficientScopeErrors.add(error);\n\treturn error;\n}\n/**\n* Returns whether an error is a typed RFC 6750 insufficient-scope failure.\n*/\nfunction isInsufficientScopeError(error) {\n\tif (!(error instanceof APIError) || !insufficientScopeErrors.has(error) || error.status !== \"FORBIDDEN\") return false;\n\tconst body = error.body;\n\tif (body?.error !== \"insufficient_scope\" || typeof body.scope !== \"string\") return false;\n\tconst scopes = body.scope.split(\" \");\n\treturn scopes.length > 0 && scopes.every(isOAuthScopeToken);\n}\nfunction throwDpopUnauthorized(message, error) {\n\tthrow new APIError(\"UNAUTHORIZED\", error ? {\n\t\tmessage,\n\t\terror,\n\t\terror_description: message\n\t} : { message });\n}\n/**\n* Performs local verification of a bearer access token for your API.\n*\n* Can also be configured for remote verification. DPoP-bound access tokens\n* require {@link verifyAccessTokenRequest}, because sender-constraining cannot\n* be verified without the HTTP method, URL, Authorization scheme, DPoP proof,\n* and access-token hash. This function rejects DPoP-bound tokens; reach for it\n* only when you hold a raw token string and intentionally accept bearer tokens\n* alone.\n*/\nasync function verifyBearerToken(token, opts) {\n\tvalidateRequiredScopes(opts);\n\tconst payload = await verifyAccessTokenPayload(token, opts);\n\tif (getDpopJktFromPayload(payload)) throwDpopUnauthorized(\"DPoP-bound access token requires verifyAccessTokenRequest\", \"invalid_token\");\n\treturn payload;\n}\n/**\n* Verifies an HTTP resource request carrying an OAuth access token. This is the\n* recommended resource-server entry point: it handles both bearer and\n* DPoP-bound tokens, the bearer case being the request with no DPoP proof.\n*\n* It performs the same token validation as {@link verifyBearerToken}, then adds\n* the RFC 9449 sender-constraint checks that need request context: authorization\n* scheme, method, URL, DPoP proof, `ath`, and `cnf.jkt` binding.\n*/\nasync function verifyAccessTokenRequest(request, opts) {\n\tvalidateRequiredScopes(opts);\n\tconst authorization = parseAccessTokenAuthorization(request.authorizationHeader);\n\tif (!authorization?.token) throwDpopUnauthorized(\"missing authorization header\");\n\tif (authorization.scheme === \"Unknown\") throwDpopUnauthorized(\"authorization scheme must be Bearer or DPoP\", \"invalid_token\");\n\tconst payload = await verifyAccessTokenPayload(authorization.token, opts);\n\ttry {\n\t\tawait enforceDpopBinding({\n\t\t\tpayload,\n\t\t\tauthorization,\n\t\t\tproofJwt: request.dpopProofJwt,\n\t\t\tmethod: request.method,\n\t\t\turl: request.url,\n\t\t\treplayStore: opts.dpop?.replayStore ?? defaultDpopReplayStore,\n\t\t\tproofMaxAgeSeconds: opts.dpop?.proofMaxAgeSeconds,\n\t\t\tsigningAlgorithms: opts.dpop?.signingAlgorithms\n\t\t});\n\t} catch (error) {\n\t\tif (isDpopBindingError(error)) throwDpopUnauthorized(error.message, error.code);\n\t\tthrow error;\n\t}\n\treturn payload;\n}\n//#endregion\nexport { createInsufficientScopeError, getJwks, isInsufficientScopeError, requestToResourceInput, verifyAccessTokenRequest, verifyBearerToken, verifyJwsAccessToken };\n","import { n as canonicalizeOAuthQueryParams } from \"./signed-query-Df1MNiSH.mjs\";\nimport { constantTimeEqual, makeSignature, symmetricDecrypt, symmetricEncrypt } from \"better-auth/crypto\";\nimport { APIError } from \"better-call\";\nimport { logger } from \"@better-auth/core/env\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\nimport { CLIENT_ASSERTION_TYPE, decodeBasicCredentials } from \"@better-auth/core/oauth2\";\nimport { base64Url } from \"@better-auth/utils/base64\";\nimport { createHash } from \"@better-auth/utils/hash\";\n//#region src/extensions.ts\nconst DEFAULT_GRANT_TYPES = [\n\t\"authorization_code\",\n\t\"client_credentials\",\n\t\"refresh_token\"\n];\nconst BUILT_IN_CONFIDENTIAL_AUTH_METHODS = [\n\t\"client_secret_basic\",\n\t\"client_secret_post\",\n\t\"private_key_jwt\"\n];\nconst RESERVED_TOKEN_ENDPOINT_AUTH_METHODS = [\"none\", ...BUILT_IN_CONFIDENTIAL_AUTH_METHODS];\nconst RESERVED_TOKEN_ENDPOINT_AUTH_METHOD_SET = new Set(RESERVED_TOKEN_ENDPOINT_AUTH_METHODS);\nfunction assertNonEmptyExtensionValue(name, value) {\n\tif (value.trim().length > 0) return;\n\tthrow new BetterAuthError(`OAuth Provider extension ${name} cannot be empty`);\n}\nfunction assertAbsoluteUri(name, value) {\n\tassertNonEmptyExtensionValue(name, value);\n\tlet url;\n\ttry {\n\t\turl = new URL(value);\n\t} catch {\n\t\turl = void 0;\n\t}\n\tif (url?.protocol) return;\n\tthrow new BetterAuthError(`OAuth Provider extension ${name} must be an absolute URI: ${value}`);\n}\nfunction assertExtensionGrantType(grantType) {\n\tassertAbsoluteUri(\"grant type\", grantType);\n}\nfunction assertExtensionTokenEndpointAuthMethod(method) {\n\tassertNonEmptyExtensionValue(\"token_endpoint_auth_method\", method);\n\tif (!RESERVED_TOKEN_ENDPOINT_AUTH_METHOD_SET.has(method)) return;\n\tthrow new BetterAuthError(`OAuth Provider extension token_endpoint_auth_method is reserved: ${method}`);\n}\nfunction assertExtensionClientAssertionType(assertionType) {\n\tassertAbsoluteUri(\"client_assertion_type\", assertionType);\n\tif (assertionType !== CLIENT_ASSERTION_TYPE) return;\n\tthrow new BetterAuthError(`OAuth Provider extension client_assertion_type is reserved: ${assertionType}`);\n}\n/**\n* Validates one extension's dispatched keys (grant types, auth methods,\n* assertion types) and returns them for the cross-extension disjointness check.\n* Throws on a non-absolute grant/assertion URI, a reserved auth-method name, or\n* an empty assertion-type list.\n*/\nfunction collectExtensionKeys(extension) {\n\tconst grantTypes = Object.keys(extension.grants ?? {});\n\tfor (const grantType of grantTypes) assertExtensionGrantType(grantType);\n\tconst authMethods = [];\n\tconst assertionTypes = [];\n\tfor (const [method, strategy] of Object.entries(extension.clientAuthentication ?? {})) {\n\t\tassertExtensionTokenEndpointAuthMethod(method);\n\t\tauthMethods.push(method);\n\t\tconst methodAssertionTypes = strategy.assertionTypes ?? [method];\n\t\tif (methodAssertionTypes.length === 0) throw new BetterAuthError(`OAuth Provider extension client_assertion_type list cannot be empty for ${method}`);\n\t\tfor (const assertionType of methodAssertionTypes) {\n\t\t\tassertExtensionClientAssertionType(assertionType);\n\t\t\tassertionTypes.push(assertionType);\n\t\t}\n\t}\n\tconst clientDiscoveryIds = (extension.clientDiscovery ? Array.isArray(extension.clientDiscovery) ? extension.clientDiscovery : [extension.clientDiscovery] : []).map((discovery) => discovery.id);\n\tfor (const clientDiscoveryId of clientDiscoveryIds) assertNonEmptyExtensionValue(\"client discovery id\", clientDiscoveryId);\n\treturn {\n\t\tgrantTypes,\n\t\tauthMethods,\n\t\tassertionTypes,\n\t\tclientDiscoveryIds\n\t};\n}\nfunction assertNoDuplicateAcrossExtensions(label, values) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tfor (const value of values) {\n\t\tif (seen.has(value)) throw new BetterAuthError(`OAuth Provider extensions register ${label} \"${value}\" more than once. Extension contributions must be disjoint.`);\n\t\tseen.add(value);\n\t}\n}\n/**\n* Validates every extension and rejects two extensions registering the same\n* grant type, auth method, assertion type, or client discovery identifier:\n* otherwise the first would win and the second be silently unreachable. Runs at\n* setup over the whole list; extensions number in the single digits, so a full\n* re-scan per registration is cheaper than the bookkeeping to cache it.\n*/\nfunction validateOAuthProviderExtensions(extensions) {\n\tconst keys = (extensions ?? []).map(collectExtensionKeys);\n\tassertNoDuplicateAcrossExtensions(\"grant type\", keys.flatMap((k) => k.grantTypes));\n\tassertNoDuplicateAcrossExtensions(\"token_endpoint_auth_method\", keys.flatMap((k) => k.authMethods));\n\tassertNoDuplicateAcrossExtensions(\"client_assertion_type\", keys.flatMap((k) => k.assertionTypes));\n\tassertNoDuplicateAcrossExtensions(\"client discovery id\", keys.flatMap((k) => k.clientDiscoveryIds));\n}\nfunction getOAuthProviderExtensions(opts) {\n\treturn opts.extensions ?? [];\n}\n/**\n* Flattens the client-id discovery sources contributed by every registered\n* extension into a single ordered list. `getClient()` consults them in order;\n* the metadata endpoints merge their `discoveryMetadata`.\n*/\nfunction getClientDiscoveries(opts) {\n\treturn getOAuthProviderExtensions(opts).flatMap((extension) => {\n\t\tconst discovery = extension.clientDiscovery;\n\t\tif (!discovery) return [];\n\t\treturn Array.isArray(discovery) ? discovery : [discovery];\n\t});\n}\n/**\n* Registers an {@link OAuthProviderExtension} with the OAuth Provider plugin\n* from a companion plugin's `init()` hook. An extension can add token grants,\n* assertion-based client authentication methods, additive discovery metadata,\n* access-token / ID-token / UserInfo claims, and client-id discovery, without\n* forking provider core.\n*\n* Call this once, at `init()` time. It is idempotent in the same `extension`\n* object, so re-running a plugin's `init()` (for example when one plugin factory\n* result is shared across two `betterAuth()` instances) does not register it\n* twice. It throws if the oauth-provider plugin is not installed, if a grant\n* type or assertion type is not an absolute URI, if a client authentication\n* method reuses a built-in name, or if the extension registers a grant type,\n* auth method, assertion type, or client discovery identifier that another\n* extension already registered (contributions must be disjoint).\n*\n* @example\n* ```ts\n* init(ctx) {\n* extendOAuthProvider(ctx, {\n* grants: { \"urn:example:grant\": async ({ provider }) => provider.issueTokens(...) },\n* });\n* }\n* ```\n*/\nfunction extendOAuthProvider(ctx, extension) {\n\tconst provider = ctx.getPlugin(\"oauth-provider\");\n\tif (!provider) throw new BetterAuthError(\"extendOAuthProvider requires the oauth-provider plugin.\");\n\tconst existing = provider.options.extensions ?? [];\n\tif (existing.includes(extension)) return;\n\tconst extensions = [...existing, extension];\n\tvalidateOAuthProviderExtensions(extensions);\n\tprovider.options.extensions = extensions;\n}\nfunction getExtensionGrantTypes(opts) {\n\treturn getOAuthProviderExtensions(opts).flatMap((extension) => Object.keys(extension.grants ?? {}));\n}\nfunction getSupportedGrantTypes(opts) {\n\treturn Array.from(new Set([...opts.grantTypes ?? DEFAULT_GRANT_TYPES, ...getExtensionGrantTypes(opts)]));\n}\nfunction getExtensionGrantHandler(opts, grantType) {\n\tfor (const extension of getOAuthProviderExtensions(opts)) {\n\t\tconst handler = extension.grants?.[grantType];\n\t\tif (handler) return handler;\n\t}\n}\nfunction getExtensionTokenEndpointAuthMethods(opts) {\n\treturn getOAuthProviderExtensions(opts).flatMap((extension) => Object.keys(extension.clientAuthentication ?? {}));\n}\n/**\n* Confidential and extension client-authentication methods the provider\n* supports. Pass `includeNone` to prepend `\"none\"` for the token endpoint and\n* DCR, where public clients are allowed; the introspection and revocation\n* endpoints, which never accept public clients, omit it (the default).\n*/\nfunction getSupportedAuthMethods(opts, settings) {\n\treturn Array.from(new Set([\n\t\t...settings?.includeNone ? [\"none\"] : [],\n\t\t...BUILT_IN_CONFIDENTIAL_AUTH_METHODS,\n\t\t...getExtensionTokenEndpointAuthMethods(opts)\n\t]));\n}\nfunction isExtensionTokenEndpointAuthMethod(opts, method) {\n\treturn method ? getExtensionTokenEndpointAuthMethods(opts).includes(method) : false;\n}\nfunction getExtensionClientAuthenticationStrategy(opts, assertionType) {\n\tif (assertionType === CLIENT_ASSERTION_TYPE) return void 0;\n\tfor (const extension of getOAuthProviderExtensions(opts)) {\n\t\tconst strategies = extension.clientAuthentication ?? {};\n\t\tfor (const [method, strategy] of Object.entries(strategies)) if ((strategy.assertionTypes ?? [method]).includes(assertionType)) return {\n\t\t\tmethod,\n\t\t\tstrategy\n\t\t};\n\t}\n}\n/**\n* Merges each registered extension's `metadata()` contribution into `document`,\n* first-wins: the provider owns every key it already wrote, so an extension can\n* add fields but never override core. Each contributor sees the base `document`,\n* not the running accumulation, so contributions stay order-independent.\n*/\nfunction applyOAuthProviderMetadataExtensions(ctx, opts, type, document) {\n\tconst next = { ...document };\n\tfor (const extension of getOAuthProviderExtensions(opts)) {\n\t\tconst contribution = extension.metadata?.({\n\t\t\tctx,\n\t\t\topts,\n\t\t\ttype,\n\t\t\tdocument\n\t\t});\n\t\tfor (const [key, value] of Object.entries(contribution ?? {})) if (!(key in next)) next[key] = value;\n\t}\n\treturn next;\n}\nasync function collectClaims(opts, run) {\n\tconst claims = {};\n\tfor (const extension of getOAuthProviderExtensions(opts)) {\n\t\tconst contribution = await run(extension) ?? {};\n\t\tfor (const [key, value] of Object.entries(contribution)) {\n\t\t\tif (key in claims) {\n\t\t\t\tlogger.warn(`oauth-provider: two extensions contributed the claim \"${key}\"; keeping the first-registered value.`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tclaims[key] = value;\n\t\t}\n\t}\n\treturn claims;\n}\nfunction collectExtensionAccessTokenClaims(opts, input) {\n\treturn collectClaims(opts, (extension) => extension.claims?.accessToken?.(input));\n}\nfunction collectExtensionIdTokenClaims(opts, input) {\n\treturn collectClaims(opts, (extension) => extension.claims?.idToken?.(input));\n}\nfunction collectExtensionUserInfoClaims(opts, input) {\n\treturn collectClaims(opts, (extension) => extension.claims?.userInfo?.(input));\n}\n/**\n* Whether any registered extension contributes UserInfo claims. Lets the\n* UserInfo endpoint skip loading the client when nothing needs it.\n*/\nfunction hasUserInfoClaimExtension(opts) {\n\treturn getOAuthProviderExtensions(opts).some((extension) => extension.claims?.userInfo);\n}\n//#endregion\n//#region src/utils/index.ts\n/**\n* Extracts the credentials from an `Authorization: Bearer <token>` header.\n*\n* Returns `undefined` when the header is absent or carries a non-Bearer scheme,\n* leaving the caller to decide whether that is an error. Throws an\n* `invalid_request` `APIError` when the Bearer scheme is present but the\n* credentials are missing or the header carries extra parts. The scheme match\n* is case-insensitive and the credentials are the single token after it.\n*\n* @see https://datatracker.ietf.org/doc/html/rfc6750#section-2.1\n* @see https://datatracker.ietf.org/doc/html/rfc7235#section-2.1\n*/\nfunction parseBearerToken(authorization) {\n\tif (!authorization) return void 0;\n\tconst [scheme, credentials, ...extraParts] = authorization.trim().split(/\\s+/);\n\tif (scheme?.toLowerCase() !== \"bearer\") return void 0;\n\tif (!credentials || extraParts.length > 0) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_request\",\n\t\terror_description: \"Malformed Bearer Authorization header\"\n\t});\n\treturn credentials;\n}\nfunction createTTLCache() {\n\tconst cache = /* @__PURE__ */ new Map();\n\treturn {\n\t\tget(key) {\n\t\t\tconst entry = cache.get(key);\n\t\t\tif (!entry) return void 0;\n\t\t\tif (entry.expiresAt && entry.expiresAt < /* @__PURE__ */ new Date()) {\n\t\t\t\tcache.delete(key);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn entry;\n\t\t},\n\t\tset(key, value) {\n\t\t\tcache.set(key, value);\n\t\t}\n\t};\n}\n/**\n* Gets the oAuth Provider Plugin\n* @internal\n*/\nconst getOAuthProviderPlugin = (ctx) => {\n\treturn ctx.getPlugin(\"oauth-provider\");\n};\n/**\n* Gets the JWT Plugin\n* @internal\n*/\nconst getJwtPlugin = (ctx) => {\n\tconst plugin = ctx.getPlugin(\"jwt\");\n\tif (!plugin) throw new BetterAuthError(\"jwt_config\");\n\treturn plugin;\n};\n/**\n* Normalizes timestamp-like values returned by adapters.\n*\n* Accepts Date instances, epoch milliseconds as numbers, and strings that are\n* either ISO dates or numeric millisecond values such as \"1774295570569.0\".\n*/\nfunction normalizeTimestampValue(value) {\n\tif (value == null) return;\n\tif (value instanceof Date) return Number.isFinite(value.getTime()) ? value : void 0;\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) return;\n\t\tconst parsed = new Date(value);\n\t\treturn Number.isFinite(parsed.getTime()) ? parsed : void 0;\n\t}\n\tif (typeof value === \"string\") {\n\t\tconst trimmed = value.trim();\n\t\tif (!trimmed.length) return;\n\t\tconst numeric = Number(trimmed);\n\t\tif (Number.isFinite(numeric)) {\n\t\t\tconst parsed = new Date(numeric);\n\t\t\treturn Number.isFinite(parsed.getTime()) ? parsed : void 0;\n\t\t}\n\t\tconst parsed = new Date(trimmed);\n\t\treturn Number.isFinite(parsed.getTime()) ? parsed : void 0;\n\t}\n}\n/**\n* Resolves a session auth time from common adapter return shapes.\n*/\nfunction resolveSessionAuthTime(value) {\n\tif (value instanceof Date) return normalizeTimestampValue(value);\n\tif (!value || typeof value !== \"object\") return normalizeTimestampValue(value);\n\tconst direct = normalizeTimestampValue(value.createdAt) ?? normalizeTimestampValue(value.created_at);\n\tif (direct) return direct;\n\tconst nested = value.session;\n\tif (!nested || typeof nested !== \"object\") return;\n\treturn normalizeTimestampValue(nested.createdAt) ?? normalizeTimestampValue(nested.created_at);\n}\n/**\n* Normalizes OAuth resource values into a non-empty string array.\n*/\nfunction toResourceList(value) {\n\tif (typeof value === \"string\") return [value];\n\tif (!value?.length) return void 0;\n\treturn value;\n}\n/**\n* Normalizes audience values for JWT claims.\n*/\nfunction toAudienceClaim(audience) {\n\tif (typeof audience === \"string\") return audience;\n\tif (!audience?.length) return void 0;\n\treturn audience.length === 1 ? audience.at(0) : audience;\n}\nconst trustedClientCaches = /* @__PURE__ */ new WeakMap();\nfunction getTrustedClientCache(options) {\n\tconst existingCache = trustedClientCaches.get(options);\n\tif (existingCache) return existingCache;\n\tconst cache = createTTLCache();\n\ttrustedClientCaches.set(options, cache);\n\treturn cache;\n}\n/**\n* Verify the signature and expiration of an OAuth query issued by this provider.\n* Use the provider's current auth secret on the server before displaying a\n* consent page. A valid signature does not replace client or session checks.\n*/\nasync function verifyOAuthQueryParams(oauth_query, secret) {\n\tconst queryParams = new URLSearchParams(oauth_query);\n\tconst sig = queryParams.get(\"sig\");\n\tconst sigs = queryParams.getAll(\"sig\");\n\tconst exp = Number(queryParams.get(\"exp\"));\n\tqueryParams.delete(\"sig\");\n\tconst verifySig = await makeSignature(canonicalizeOAuthQueryParams(queryParams).toString(), secret);\n\treturn sigs.length === 1 && !!sig && constantTimeEqual(sig, verifySig) && /* @__PURE__ */ new Date(exp * 1e3) >= /* @__PURE__ */ new Date();\n}\n/**\n* Get a client by ID, checking trusted clients first, then database\n*/\nasync function getClient(ctx, options, clientId) {\n\tconst trustedClientCache = getTrustedClientCache(options);\n\tconst trustedClient = trustedClientCache.get(clientId);\n\tif (trustedClient && !trustedClient.clientDiscoveryId) return Object.assign({}, trustedClient);\n\tlet dbClient = await ctx.context.adapter.findOne({\n\t\tmodel: options.schema?.oauthClient?.modelName ?? \"oauthClient\",\n\t\twhere: [{\n\t\t\tfield: \"clientId\",\n\t\t\tvalue: clientId\n\t\t}]\n\t});\n\tconst discoveries = getClientDiscoveries(options);\n\tif (dbClient?.clientDiscoveryId) {\n\t\tconst clientDiscoveryId = dbClient.clientDiscoveryId;\n\t\tconst discovery = discoveries.find((candidate) => candidate.id === clientDiscoveryId);\n\t\tif (!discovery?.matches(clientId)) return null;\n\t\tdbClient = await discovery.resolve(ctx, clientId, dbClient);\n\t\tif (!dbClient) return null;\n\t} else if (dbClient) {\n\t\tif (options.cachedTrustedClients?.has(clientId)) trustedClientCache.set(clientId, Object.assign({}, dbClient));\n\t\treturn dbClient;\n\t} else for (const discovery of discoveries) {\n\t\tif (!discovery.matches(clientId)) continue;\n\t\tconst resolved = await discovery.resolve(ctx, clientId, null);\n\t\tif (resolved) {\n\t\t\tdbClient = resolved;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn dbClient;\n}\n/**\n* Merge `discoveryMetadata` from every contributed {@link ClientDiscovery}\n* into a single object. Entries are spread in order; later entries override\n* earlier ones on key collisions.\n*\n* @internal\n*/\nfunction mergeDiscoveryMetadata(discoveries) {\n\treturn discoveries.reduce((acc, d) => ({\n\t\t...acc,\n\t\t...d.discoveryMetadata ?? {}\n\t}), {});\n}\n/**\n* Default client secret hasher using SHA-256\n*\n* @internal\n*/\nconst defaultHasher = async (value) => {\n\tconst hash = await createHash(\"SHA-256\").digest(new TextEncoder().encode(value));\n\treturn base64Url.encode(new Uint8Array(hash), { padding: false });\n};\n/**\n* Decrypts a storedClientSecret for signing\n*\n* @internal\n*/\nasync function decryptStoredClientSecret(ctx, storageMethod, storedClientSecret) {\n\tif (storageMethod === \"encrypted\") return await symmetricDecrypt({\n\t\tkey: ctx.context.secretConfig,\n\t\tdata: storedClientSecret\n\t});\n\telse if (typeof storageMethod === \"object\" && \"decrypt\" in storageMethod) return await storageMethod.decrypt(storedClientSecret);\n\tthrow new BetterAuthError(`Unsupported decryption storageMethod type '${storageMethod}'`);\n}\n/**\n* Verify stored client secret against provided client secret\n*\n* @internal\n*/\nasync function verifyStoredClientSecret(ctx, opts, storedClientSecret, clientSecret) {\n\tconst storageMethod = opts.storeClientSecret ?? (opts.disableJwtPlugin ? \"encrypted\" : \"hashed\");\n\tif (clientSecret && opts.prefix?.clientSecret) if (clientSecret.startsWith(opts.prefix?.clientSecret)) clientSecret = clientSecret.replace(opts.prefix.clientSecret, \"\");\n\telse throw new APIError(\"UNAUTHORIZED\", {\n\t\terror_description: \"invalid client_secret\",\n\t\terror: \"invalid_client\"\n\t});\n\tif (storageMethod === \"hashed\") {\n\t\tconst hashedClientSecret = clientSecret ? await defaultHasher(clientSecret) : void 0;\n\t\treturn !!hashedClientSecret && constantTimeEqual(hashedClientSecret, storedClientSecret);\n\t} else if (typeof storageMethod === \"object\" && \"hash\" in storageMethod) if (storageMethod.verify) return !!clientSecret && await storageMethod.verify(clientSecret, storedClientSecret);\n\telse {\n\t\tconst hashedClientSecret = clientSecret ? await storageMethod.hash(clientSecret) : void 0;\n\t\treturn !!hashedClientSecret && constantTimeEqual(hashedClientSecret, storedClientSecret);\n\t}\n\telse if (storageMethod === \"encrypted\") try {\n\t\tconst decryptedClientSecret = await decryptStoredClientSecret(ctx, storageMethod, storedClientSecret);\n\t\treturn !!clientSecret && constantTimeEqual(decryptedClientSecret, clientSecret);\n\t} catch {\n\t\treturn false;\n\t}\n\telse if (typeof storageMethod === \"object\" && \"decrypt\" in storageMethod) {\n\t\tconst decryptedClientSecret = await decryptStoredClientSecret(ctx, storageMethod, storedClientSecret);\n\t\treturn !!clientSecret && constantTimeEqual(decryptedClientSecret, clientSecret);\n\t}\n\tthrow new BetterAuthError(`Unsupported verify storageMethod type '${storageMethod}'`);\n}\n/**\n* Store client secret according to the configured storage method\n*\n* @internal\n*/\nasync function storeClientSecret(ctx, opts, clientSecret) {\n\tconst storageMethod = opts.storeClientSecret ?? (opts.disableJwtPlugin ? \"encrypted\" : \"hashed\");\n\tif (storageMethod === \"encrypted\") return await symmetricEncrypt({\n\t\tkey: ctx.context.secretConfig,\n\t\tdata: clientSecret\n\t});\n\telse if (storageMethod === \"hashed\") return await defaultHasher(clientSecret);\n\telse if (typeof storageMethod === \"object\" && \"hash\" in storageMethod) return await storageMethod.hash(clientSecret);\n\telse if (typeof storageMethod === \"object\" && \"encrypt\" in storageMethod) return await storageMethod.encrypt(clientSecret);\n\tthrow new BetterAuthError(`Unsupported storeClientSecret type '${storageMethod}'`);\n}\n/**\n* Stores a token value (ie opaque tokens, refresh tokens, transaction tokens, verification codes)\n* on the database in a secure hashed format.\n*\n* @internal\n*/\nasync function storeToken(storageMethod = \"hashed\", token, type) {\n\tif (storageMethod === \"hashed\") return await defaultHasher(token);\n\telse if (typeof storageMethod === \"object\" && \"hash\" in storageMethod) return await storageMethod.hash(token, type);\n\tthrow new BetterAuthError(`storeToken: unsupported storageMethod type '${storageMethod}'`);\n}\n/**\n* Gets a hashed token value to find on the database.\n*\n* @internal\n*/\nasync function getStoredToken(storageMethod = \"hashed\", token, type) {\n\tif (storageMethod === \"hashed\") return await defaultHasher(token);\n\telse if (typeof storageMethod === \"object\" && \"hash\" in storageMethod) return await storageMethod.hash(token, type);\n\tthrow new BetterAuthError(`getStoredToken: unsupported storageMethod type '${storageMethod}'`);\n}\n/**\n* Converts a BASIC authorization header\n* into its client_id and client_secret representation\n*\n* @internal\n*/\nconst BASIC_SCHEME_PREFIX = /^Basic +/i;\nconst AUTH_SCHEME_TOKEN = /^([!#$%&'*+\\-.^_`|~0-9A-Za-z]+)(?=\\s|$)/;\nfunction parseAuthorizationScheme(authorization) {\n\treturn authorization.match(AUTH_SCHEME_TOKEN)?.[1];\n}\nconst CLIENT_AUTHENTICATION_FIELDS = [\n\t\"client_secret\",\n\t\"client_assertion\",\n\t\"client_assertion_type\"\n];\nfunction throwInvalidAuthenticationRequest(errorDescription) {\n\tthrow new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_request\",\n\t\terror_description: errorDescription\n\t});\n}\n/**\n* Normalizes client identification and authentication parameters while\n* enforcing RFC 6749 §2.3 and RFC 8628 §3.1 cardinality. Empty values are\n* omitted. Client identification remains separate from authentication-method\n* detection so a public `client_id` does not count as an authentication attempt.\n* Repeated `resource` parameters are intentionally outside this parser because\n* RFC 8707 §2 explicitly permits them.\n*\n* Credential and assertion verification remain the responsibility of\n* `extractClientCredentials`.\n*\n* @internal\n*/\nasync function normalizeClientAuthenticationParameters(request, body = {}) {\n\tlet clientId;\n\tif (body.client_id !== void 0 && body.client_id !== \"\") {\n\t\tif (typeof body.client_id !== \"string\") throwInvalidAuthenticationRequest(\"client_id must be a string\");\n\t\tclientId = body.client_id;\n\t}\n\tconst fields = {};\n\tconst setEffectiveField = (field, value) => {\n\t\tif (value === void 0 || value === \"\") return;\n\t\tif (typeof value !== \"string\") throwInvalidAuthenticationRequest(`${field} must be a string`);\n\t\tfields[field] = value;\n\t};\n\tfor (const field of CLIENT_AUTHENTICATION_FIELDS) if (Object.hasOwn(body, field)) setEffectiveField(field, body[field]);\n\tconst authorization = request?.headers.get(\"authorization\");\n\tconst hasAuthorizationHeader = Boolean(authorization);\n\tif (request) {\n\t\tif ((request.headers.get(\"content-type\")?.toLowerCase() ?? \"\").includes(\"application/x-www-form-urlencoded\")) {\n\t\t\tconst params = new URLSearchParams(await request.clone().text());\n\t\t\tconst clientIds = params.getAll(\"client_id\").filter((value) => value.length > 0);\n\t\t\tif (clientIds.length > 1) throwInvalidAuthenticationRequest(\"client_id must not be repeated\");\n\t\t\tclientId = clientIds[0];\n\t\t\tfor (const field of CLIENT_AUTHENTICATION_FIELDS) {\n\t\t\t\tconst values = params.getAll(field).filter((value) => value.length > 0);\n\t\t\t\tif (values.length > 1) throwInvalidAuthenticationRequest(`${field} must not be repeated`);\n\t\t\t\tif (values.length === 1) setEffectiveField(field, values[0]);\n\t\t\t}\n\t\t}\n\t}\n\tconst hasClientSecret = fields.client_secret !== void 0;\n\tconst hasClientAssertion = fields.client_assertion !== void 0 || fields.client_assertion_type !== void 0;\n\tif (hasAuthorizationHeader && (hasClientSecret || hasClientAssertion) || hasClientSecret && hasClientAssertion) throwInvalidAuthenticationRequest(\"A request must use only one client authentication method\");\n\tbody.client_id = clientId;\n\tfor (const field of CLIENT_AUTHENTICATION_FIELDS) body[field] = fields[field];\n\treturn { detected: hasAuthorizationHeader || Object.keys(fields).length > 0 };\n}\nfunction basicToClientCredentials(authorization) {\n\tif (!BASIC_SCHEME_PREFIX.test(authorization)) return;\n\ttry {\n\t\tconst { clientId, clientSecret } = decodeBasicCredentials(authorization);\n\t\treturn {\n\t\t\tclient_id: clientId,\n\t\t\tclient_secret: clientSecret\n\t\t};\n\t} catch {\n\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\terror_description: \"invalid authorization header format\",\n\t\t\terror: \"invalid_client\"\n\t\t}, { \"WWW-Authenticate\": \"Basic\" });\n\t}\n}\n/**\n* Whether a client is allowed to use a given grant type.\n*\n* A client's registered `grantTypes` defaults to the documented default\n* `[\"authorization_code\"]` when unset (see client registration). Refresh tokens\n* are only ever issued through the authorization_code flow, so a client allowed\n* to use `authorization_code` is implicitly allowed to use `refresh_token`.\n*\n* @internal\n*/\nfunction clientAllowsGrant(client, grantType) {\n\tconst allowedGrants = client.grantTypes && client.grantTypes.length > 0 ? client.grantTypes : [\"authorization_code\"];\n\tif (grantType === \"refresh_token\" && allowedGrants.includes(\"authorization_code\")) return true;\n\treturn allowedGrants.includes(grantType);\n}\n/**\n* Validates requested scopes against a registered client's allowed scopes.\n*\n* @internal\n*/\nfunction validateClientScopes(client, scopes) {\n\tif (!scopes || !client.scopes) return;\n\tconst validScopes = new Set(client.scopes);\n\tfor (const scope of scopes) if (!validScopes.has(scope)) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: `client does not allow scope ${scope}`,\n\t\terror: \"invalid_scope\"\n\t});\n}\nfunction throwInvalidClient(errorDescription, authentication) {\n\tconst attemptedBasicAuthentication = authentication?.method === \"client_secret_basic\";\n\tconst challengeScheme = authentication?.scheme ?? (attemptedBasicAuthentication ? \"Basic\" : void 0);\n\tthrow new APIError(challengeScheme ? \"UNAUTHORIZED\" : \"BAD_REQUEST\", {\n\t\terror_description: errorDescription,\n\t\terror: \"invalid_client\"\n\t}, challengeScheme ? { \"WWW-Authenticate\": challengeScheme } : void 0);\n}\n/**\n* Resolves the registered client by id and authorizes it: existence, disabled\n* state, registered auth method, requested scopes, and grant type. The record is\n* always resolved here via `getClient`, so a client-auth strategy proves the\n* caller controls `clientId` but never supplies the record. `preVerified` marks\n* that an assertion already proved control, so the client-secret check is skipped.\n*\n* @internal\n*/\nasync function validateClientCredentials(ctx, options, clientId, clientSecret, scopes, preVerified, grantType, authMethod) {\n\tconst client = await getClient(ctx, options, clientId);\n\tif (!client) throwInvalidClient(\"missing client\", { method: authMethod });\n\tif (client.disabled) throwInvalidClient(\"client is disabled\", { method: authMethod });\n\tconst registeredAuthMethod = client.tokenEndpointAuthMethod ?? \"client_secret_basic\";\n\tif (authMethod && registeredAuthMethod !== authMethod) throwInvalidClient(`client registered for ${registeredAuthMethod} cannot use ${authMethod}`, { method: authMethod });\n\tif ((client.tokenEndpointAuthMethod === \"private_key_jwt\" || isExtensionTokenEndpointAuthMethod(options, client.tokenEndpointAuthMethod)) && !preVerified) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: `client registered for ${client.tokenEndpointAuthMethod} must use client_assertion`,\n\t\terror: \"invalid_client\"\n\t});\n\tif (!preVerified) {\n\t\tif (client.tokenEndpointAuthMethod !== \"none\" && !clientSecret) throwInvalidClient(\"client secret must be provided\", { method: authMethod });\n\t\tif (clientSecret && !client.clientSecret) throwInvalidClient(\"public client, client secret should not be received\", { method: authMethod });\n\t\tif (clientSecret && !await verifyStoredClientSecret(ctx, options, client.clientSecret, clientSecret)) throwInvalidClient(\"invalid client_secret\", { method: authMethod });\n\t}\n\tvalidateClientScopes(client, scopes);\n\tif (grantType && !clientAllowsGrant(client, grantType)) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: `client is not authorized to use grant type ${grantType}`,\n\t\terror: \"unauthorized_client\"\n\t});\n\treturn client;\n}\n/**\n* Parse client metadata that may be stored as JSON string or already parsed object.\n* Handles database adapters that auto-parse JSON columns.\n*\n* @internal\n*/\nfunction parseClientMetadata(metadata) {\n\tif (!metadata) return void 0;\n\treturn typeof metadata === \"string\" ? JSON.parse(metadata) : metadata;\n}\n/** Unwraps ExtractedCredentials into the fields each grant handler needs. */\nfunction destructureCredentials(credentials) {\n\treturn {\n\t\tclientId: credentials?.clientId,\n\t\tclientSecret: credentials?.kind === \"client_secret\" ? credentials.clientSecret : void 0,\n\t\tpreVerified: credentials?.kind === \"pre_verified\",\n\t\tauthMethod: credentials?.method,\n\t\tconfirmation: credentials?.kind === \"pre_verified\" ? credentials.confirmation : void 0\n\t};\n}\n/**\n* Extracts and resolves client credentials from the request.\n* Supports: client_secret_basic, client_secret_post, private_key_jwt, and none (public).\n*/\nasync function extractClientCredentials(ctx, opts, expectedAudience) {\n\tconst body = { ...ctx.body ?? {} };\n\tawait normalizeClientAuthenticationParameters(ctx.request, body);\n\tconst authorization = ctx.request?.headers.get(\"authorization\") ?? void 0;\n\tif (body.client_assertion_type || body.client_assertion) {\n\t\tif (!body.client_assertion || !body.client_assertion_type) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror_description: \"client_assertion and client_assertion_type must both be provided\",\n\t\t\terror: \"invalid_client\"\n\t\t});\n\t\tconst assertion = body.client_assertion;\n\t\tconst assertionType = body.client_assertion_type;\n\t\tconst extensionStrategy = getExtensionClientAuthenticationStrategy(opts, assertionType);\n\t\tif (extensionStrategy) {\n\t\t\tconst result = await extensionStrategy.strategy.authenticate({\n\t\t\t\tctx,\n\t\t\t\topts,\n\t\t\t\tassertion,\n\t\t\t\tassertionType,\n\t\t\t\tclientId: body.client_id,\n\t\t\t\texpectedAudience\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tkind: \"pre_verified\",\n\t\t\t\tmethod: extensionStrategy.method,\n\t\t\t\tclientId: result.clientId,\n\t\t\t\tconfirmation: result.confirmation\n\t\t\t};\n\t\t}\n\t\tconst { verifyClientAssertion: verify } = await import(\"./authorize-C95F-9E1.mjs\").then((n) => n.o);\n\t\treturn {\n\t\t\tkind: \"pre_verified\",\n\t\t\tmethod: \"private_key_jwt\",\n\t\t\tclientId: (await verify(ctx, opts, assertion, assertionType, body.client_id, expectedAudience)).clientId\n\t\t};\n\t}\n\tif (authorization && !BASIC_SCHEME_PREFIX.test(authorization)) {\n\t\tconst authorizationScheme = parseAuthorizationScheme(authorization);\n\t\tif (!authorizationScheme) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_request\",\n\t\t\terror_description: \"Invalid authorization header format\"\n\t\t});\n\t\tthrowInvalidClient(\"unsupported authorization scheme\", { scheme: authorizationScheme });\n\t}\n\tif (authorization && BASIC_SCHEME_PREFIX.test(authorization)) {\n\t\tconst res = basicToClientCredentials(authorization);\n\t\tif (res) return {\n\t\t\tkind: \"client_secret\",\n\t\t\tmethod: \"client_secret_basic\",\n\t\t\tclientId: res.client_id,\n\t\t\tclientSecret: res.client_secret\n\t\t};\n\t}\n\tif (body.client_id && body.client_secret) return {\n\t\tkind: \"client_secret\",\n\t\tmethod: \"client_secret_post\",\n\t\tclientId: body.client_id,\n\t\tclientSecret: body.client_secret\n\t};\n\tif (body.client_id) return {\n\t\tkind: \"public\",\n\t\tmethod: \"none\",\n\t\tclientId: body.client_id\n\t};\n\treturn null;\n}\n/**\n* Parse space-separated prompt string into a set of prompts\n*\n* @param prompt\n*/\nfunction parsePrompt(prompt) {\n\tconst prompts = prompt.split(\" \").map((p) => p.trim());\n\tconst set = /* @__PURE__ */ new Set();\n\tfor (const p of prompts) if (p === \"login\" || p === \"consent\" || p === \"create\" || p === \"select_account\" || p === \"none\") set.add(p);\n\treturn new Set(set);\n}\n/**\n* Extracts the sector identifier (hostname) from a client's first redirect URI.\n*\n* @see https://openid.net/specs/openid-connect-core-1_0.html#PairwiseAlg\n* @internal\n*/\nfunction getSectorIdentifier(client) {\n\tconst uri = client.redirectUris?.[0];\n\tif (!uri) throw new BetterAuthError(\"Client has no redirect URIs for sector identifier\");\n\treturn new URL(uri).host;\n}\n/**\n* Computes a pairwise subject identifier using HMAC-SHA256.\n*\n* @see https://openid.net/specs/openid-connect-core-1_0.html#PairwiseAlg\n* @internal\n*/\nasync function computePairwiseSub(userId, client, secret) {\n\treturn makeSignature(`${getSectorIdentifier(client)}.${userId}`, secret);\n}\n/**\n* Returns the appropriate subject identifier for a user+client pair.\n* Uses pairwise when the client opts in and the server has a secret configured.\n*\n* @internal\n*/\nasync function resolveSubjectIdentifier(userId, client, opts) {\n\tif (client.subjectType === \"pairwise\" && opts.pairwiseSecret) return computePairwiseSub(userId, client, opts.pairwiseSecret);\n\treturn userId;\n}\n/**\n* Converts URLSearchParams to a plain object, preserving\n* multi-valued keys as arrays instead of discarding duplicates.\n*/\nfunction searchParamsToQuery(params) {\n\tconst result = Object.create(null);\n\tfor (const key of new Set(params.keys())) {\n\t\tconst values = params.getAll(key);\n\t\tresult[key] = values.length === 1 ? values[0] : values;\n\t}\n\treturn result;\n}\nfunction isSessionFreshForSignedQuery(sessionCreatedAt, signedQueryIssuedAt) {\n\tif (!signedQueryIssuedAt) return false;\n\tconst normalized = normalizeTimestampValue(sessionCreatedAt);\n\tif (!normalized) return false;\n\treturn normalized.getTime() >= signedQueryIssuedAt.getTime();\n}\nfunction removePromptFromQuery(query, prompt) {\n\tconst nextQuery = new URLSearchParams(query);\n\tconst prompts = nextQuery.get(\"prompt\")?.split(\" \");\n\tconst foundPrompt = prompts?.findIndex((v) => v === prompt) ?? -1;\n\tif (foundPrompt >= 0) {\n\t\tprompts?.splice(foundPrompt, 1);\n\t\tprompts?.length ? nextQuery.set(\"prompt\", prompts.join(\" \")) : nextQuery.delete(\"prompt\");\n\t}\n\treturn nextQuery;\n}\nfunction removeMaxAgeFromQuery(query) {\n\tconst nextQuery = new URLSearchParams(query);\n\tnextQuery.delete(\"max_age\");\n\treturn nextQuery;\n}\n/**\n* Determines if PKCE is required for a given client and authorization request.\n*\n* PKCE is always required for:\n* 1. Public clients (cannot securely store client_secret)\n* 2. Requests with offline_access scope unless a confidential OIDC request\n* already uses nonce as its authorization-code injection countermeasure.\n*\n* For confidential clients:\n* - Uses client.requirePKCE if set (defaults to true)\n*\n* Returns false if PKCE is not required, or the reason it is required.\n*\n* @internal\n*/\nfunction isPKCERequired(client, request) {\n\tif (client.tokenEndpointAuthMethod === \"none\") return \"pkce is required for public clients\";\n\tconst requestScopes = request?.scopes ?? [];\n\tconst isOpenIdRequest = requestScopes.includes(\"openid\");\n\tconst hasNonce = typeof request?.nonce === \"string\" && request.nonce.length > 0;\n\tconst hasOidcNonce = isOpenIdRequest && hasNonce;\n\tif (requestScopes.includes(\"offline_access\") && !hasOidcNonce) return \"pkce or OIDC nonce is required when requesting offline_access scope\";\n\tif (client.requirePKCE ?? true) return \"pkce is required for this client\";\n\treturn false;\n}\n//#endregion\nexport { collectExtensionAccessTokenClaims as A, validateOAuthProviderExtensions as B, storeToken as C, validateClientScopes as D, validateClientCredentials as E, getExtensionGrantHandler as F, getSupportedAuthMethods as I, getSupportedGrantTypes as L, collectExtensionUserInfoClaims as M, extendOAuthProvider as N, verifyOAuthQueryParams as O, getClientDiscoveries as P, hasUserInfoClaimExtension as R, storeClientSecret as S, toResourceList as T, removeMaxAgeFromQuery as _, getClient as a, resolveSubjectIdentifier as b, getStoredToken as c, mergeDiscoveryMetadata as d, normalizeClientAuthenticationParameters as f, parsePrompt as g, parseClientMetadata as h, extractClientCredentials as i, collectExtensionIdTokenClaims as j, applyOAuthProviderMetadataExtensions as k, isPKCERequired as l, parseBearerToken as m, decryptStoredClientSecret as n, getJwtPlugin as o, normalizeTimestampValue as p, destructureCredentials as r, getOAuthProviderPlugin as s, clientAllowsGrant as t, isSessionFreshForSignedQuery as u, removePromptFromQuery as v, toAudienceClaim as w, searchParamsToQuery as x, resolveSessionAuthTime as y, isExtensionTokenEndpointAuthMethod as z };\n","import { APIError as APIError$1 } from \"../error/index.mjs\";\nimport { APIError } from \"better-call\";\n//#region src/utils/is-api-error.ts\nfunction isAPIError(error) {\n\treturn error instanceof APIError || error instanceof APIError$1 || error?.name === \"APIError\";\n}\n//#endregion\nexport { isAPIError };\n","//#region src/async_hooks/index.ts\nlet cachedAsyncLocalStorageConstructor;\nlet availabilityWarningLogged = false;\nfunction getBuiltinAsyncLocalStorage() {\n\ttry {\n\t\treturn globalThis.process?.getBuiltinModule?.(\"node:async_hooks\")?.AsyncLocalStorage;\n\t} catch {\n\t\treturn;\n\t}\n}\nasync function getAsyncLocalStorage() {\n\tif (cachedAsyncLocalStorageConstructor) return cachedAsyncLocalStorageConstructor;\n\tconst builtinConstructor = getBuiltinAsyncLocalStorage();\n\tif (builtinConstructor) {\n\t\tcachedAsyncLocalStorageConstructor ??= builtinConstructor;\n\t\treturn cachedAsyncLocalStorageConstructor;\n\t}\n\ttry {\n\t\tconst { AsyncLocalStorage: constructor } = await import(\n\t\t\t/* @vite-ignore */\n\t\t\t/* webpackIgnore: true */\n\t\t\t\"node:async_hooks\"\n);\n\t\tcachedAsyncLocalStorageConstructor ??= constructor;\n\t\treturn cachedAsyncLocalStorageConstructor;\n\t} catch (err) {\n\t\tconst constructor = globalThis.AsyncLocalStorage;\n\t\tif (typeof constructor === \"function\") {\n\t\t\tcachedAsyncLocalStorageConstructor ??= constructor;\n\t\t\treturn cachedAsyncLocalStorageConstructor;\n\t\t}\n\t\tif (typeof window !== \"undefined\") throw new Error(\"getAsyncLocalStorage is only available in server code\");\n\t\tif (!availabilityWarningLogged) {\n\t\t\tavailabilityWarningLogged = true;\n\t\t\tconsole.warn(\"[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected.\");\n\t\t\tconsole.warn(\"[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler\");\n\t\t\tconsole.warn(\"[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag\");\n\t\t}\n\t\tthrow err;\n\t}\n}\n//#endregion\nexport { getAsyncLocalStorage };\n","import { __getBetterAuthGlobal, __getCurrentEndpointContext } from \"./global.mjs\";\nimport { getAsyncLocalStorage } from \"@better-auth/core/async_hooks\";\n//#region src/context/endpoint-context.ts\nconst getExistingEndpointContextStorage = () => {\n\treturn __getBetterAuthGlobal().context.endpointContextAsyncStorage;\n};\nconst getOrCreateEndpointContextStorage = async () => {\n\tconst existing = getExistingEndpointContextStorage();\n\tif (existing) return existing;\n\tconst AsyncLocalStorage = await getAsyncLocalStorage();\n\tconst globalContext = __getBetterAuthGlobal().context;\n\treturn globalContext.endpointContextAsyncStorage ??= new AsyncLocalStorage();\n};\n/**\n* @deprecated Use `getCurrentAuthEndpointContext`,\n* `tryGetCurrentAuthEndpointContext`, or `runWithEndpointContext` instead.\n*/\nasync function getCurrentAuthContextAsyncLocalStorage() {\n\treturn getOrCreateEndpointContextStorage();\n}\n/**\n* Returns the current auth endpoint context, or `undefined` when called outside\n* of `runWithEndpointContext`.\n*/\nfunction tryGetCurrentAuthEndpointContext() {\n\treturn __getCurrentEndpointContext();\n}\n/**\n* Returns the current auth endpoint context.\n*\n* @throws When called outside of `runWithEndpointContext`.\n*/\nfunction getCurrentAuthEndpointContext() {\n\tconst authEndpointContext = tryGetCurrentAuthEndpointContext();\n\tif (!authEndpointContext) throw new Error(\"No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.\");\n\treturn authEndpointContext;\n}\n/**\n* @deprecated Use `getCurrentAuthEndpointContext` instead.\n*/\nasync function getCurrentAuthContext() {\n\treturn getCurrentAuthEndpointContext();\n}\nasync function runWithEndpointContext(authEndpointContext, fn) {\n\treturn (await getOrCreateEndpointContextStorage()).run(authEndpointContext, fn);\n}\n//#endregion\nexport { getCurrentAuthContext, getCurrentAuthContextAsyncLocalStorage, getCurrentAuthEndpointContext, runWithEndpointContext, tryGetCurrentAuthEndpointContext };\n","import { runWithEndpointContext } from \"../context/endpoint-context.mjs\";\nimport { isAPIError } from \"../utils/is-api-error.mjs\";\nimport { createEndpoint, createMiddleware, kAPIErrorHeaderSymbol } from \"better-call\";\n//#region src/api/index.ts\n/**\n* Response headers that forbid any intermediary (proxy, CDN, browser) from\n* caching a response body. Credential-bearing responses (access/refresh tokens,\n* ID tokens, client secrets, device codes) must carry them.\n*\n* Set `metadata: { noStore: true }` on an endpoint and {@link createAuthEndpoint}\n* applies these to the responses its handler produces: the success body and any\n* error the handler throws. A request rejected by schema or media-type\n* validation before the handler runs is not covered, and carries no credentials\n* to protect. Spread them into a hand-built `Response` or `APIError`'s headers\n* for the rare endpoint that constructs its own response.\n*\n* @see https://datatracker.ietf.org/doc/html/rfc6749#section-5.1\n*/\nconst NO_STORE_HEADERS = {\n\t\"Cache-Control\": \"no-store\",\n\tPragma: \"no-cache\"\n};\n/**\n* Better-call's createEndpoint re-throws APIError without exposing the headers\n* accumulated on ctx.responseHeaders (e.g. Set-Cookie from deleteSessionCookie\n* before throw). Attach them to the error via kAPIErrorHeaderSymbol — matching\n* better-call's createMiddleware contract so the outer pipeline can merge them\n* into the response.\n*/\nfunction attachResponseHeadersToAPIError(responseHeaders, e) {\n\tif (!isAPIError(e) || !responseHeaders) return;\n\tObject.defineProperty(e, kAPIErrorHeaderSymbol, {\n\t\tenumerable: false,\n\t\tconfigurable: true,\n\t\tvalue: responseHeaders,\n\t\twritable: false\n\t});\n}\nconst optionsMiddleware = createMiddleware(async () => {\n\t/**\n\t* This will be passed on the instance of\n\t* the context. Used to infer the type\n\t* here.\n\t*/\n\treturn {};\n});\nconst createAuthMiddleware = createMiddleware.create({ use: [optionsMiddleware, createMiddleware(async () => {\n\treturn {};\n})] });\nconst createEndpointWithAuthContext = createEndpoint.create({ use: [optionsMiddleware] });\nfunction wrapEndpointHandler(handler, options) {\n\tconst noStore = options.metadata?.noStore === true;\n\treturn async (context) => {\n\t\tif (noStore) for (const [name, value] of Object.entries(NO_STORE_HEADERS)) context.setHeader(name, value);\n\t\ttry {\n\t\t\treturn await runWithEndpointContext(context, () => handler(context));\n\t\t} catch (error) {\n\t\t\tattachResponseHeadersToAPIError(context.responseHeaders, error);\n\t\t\tthrow error;\n\t\t}\n\t};\n}\nfunction createAuthEndpoint(...args) {\n\tif (args.length === 3) {\n\t\tconst [path, options, handler] = args;\n\t\treturn createEndpointWithAuthContext(path, options, wrapEndpointHandler(handler, options));\n\t}\n\tconst [options, handler] = args;\n\treturn createEndpointWithAuthContext(options, wrapEndpointHandler(handler, options));\n}\n/**\n* Set `metadata.SERVER_ONLY` while preserving any existing metadata\n* (`$Infer`, `openapi`, ...).\n*/\nfunction withServerOnly(options) {\n\treturn {\n\t\t...options,\n\t\tmetadata: {\n\t\t\t...options.metadata,\n\t\t\tSERVER_ONLY: true\n\t\t}\n\t};\n}\n/**\n* Declare a **server-only** endpoint.\n*\n* The endpoint is callable through `auth.api.*` from trusted server code but is\n* never registered on the HTTP router and never emitted into the OpenAPI\n* schema. It takes no path because it has no URL to be reached at.\n*\n* Prefer this over the path-less `createAuthEndpoint({ ... }, handler)` form.\n* Setting `metadata.SERVER_ONLY` makes the intent explicit at the call site and\n* keeps the endpoint off the HTTP surface even if a path is later added by\n* mistake: better-call's router skips an endpoint when its path is missing *or*\n* when `SERVER_ONLY` is set, so the two together are defense in depth. Relying\n* on path omission alone is invisible and one keystroke away from exposure.\n*\n* @example\n* ```ts\n* viewBackupCodes: createAuthEndpoint.serverOnly(\n* \t{ method: \"POST\", body: schema },\n* \tasync (ctx) => { ... },\n* )\n* ```\n*/\ncreateAuthEndpoint.serverOnly = (options, handler) => createAuthEndpoint(withServerOnly(options), handler);\n//#endregion\nexport { NO_STORE_HEADERS, createAuthEndpoint, createAuthMiddleware, optionsMiddleware };\n","//#region src/utils/wildcard.ts\n/**\n* Escapes a character if it has a special meaning in regular expressions\n* and returns the character as is if it doesn't\n*/\nfunction escapeRegExpChar(char) {\n\tif (char === \"-\" || char === \"^\" || char === \"$\" || char === \"+\" || char === \".\" || char === \"(\" || char === \")\" || char === \"|\" || char === \"[\" || char === \"]\" || char === \"{\" || char === \"}\" || char === \"*\" || char === \"?\" || char === \"\\\\\") return `\\\\${char}`;\n\telse return char;\n}\n/**\n* Escapes all characters in a given string that have a special meaning in regular expressions\n*/\nfunction escapeRegExpString(str) {\n\tlet result = \"\";\n\tfor (let i = 0; i < str.length; i++) result += escapeRegExpChar(str[i]);\n\treturn result;\n}\n/**\n* Transforms one or more glob patterns into a RegExp pattern\n*/\nfunction transform(pattern, separator = true) {\n\tif (Array.isArray(pattern)) return `(?:${pattern.map((p) => `^${transform(p, separator)}$`).join(\"|\")})`;\n\tlet separatorSplitter = \"\";\n\tlet separatorMatcher = \"\";\n\tlet wildcard = \".\";\n\tif (separator === true) {\n\t\tseparatorSplitter = \"/\";\n\t\tseparatorMatcher = \"[/\\\\\\\\]\";\n\t\twildcard = \"[^/\\\\\\\\]\";\n\t} else if (separator) {\n\t\tseparatorSplitter = separator;\n\t\tseparatorMatcher = escapeRegExpString(separatorSplitter);\n\t\tif (separatorMatcher.length > 1) {\n\t\t\tseparatorMatcher = `(?:${separatorMatcher})`;\n\t\t\twildcard = `((?!${separatorMatcher}).)`;\n\t\t} else wildcard = `[^${separatorMatcher}]`;\n\t}\n\tconst requiredSeparator = separator ? `${separatorMatcher}+?` : \"\";\n\tconst optionalSeparator = separator ? `${separatorMatcher}*?` : \"\";\n\tconst segments = separator ? pattern.split(separatorSplitter) : [pattern];\n\tlet result = \"\";\n\tfor (let s = 0; s < segments.length; s++) {\n\t\tconst segment = segments[s];\n\t\tconst nextSegment = segments[s + 1];\n\t\tlet currentSeparator = \"\";\n\t\tif (!segment && s > 0) continue;\n\t\tif (separator) if (s === segments.length - 1) currentSeparator = optionalSeparator;\n\t\telse if (nextSegment !== \"**\") currentSeparator = requiredSeparator;\n\t\telse currentSeparator = \"\";\n\t\tif (separator && segment === \"**\") {\n\t\t\tif (currentSeparator) {\n\t\t\t\tresult += s === 0 ? \"\" : currentSeparator;\n\t\t\t\tresult += `(?:${wildcard}*?${currentSeparator})*?`;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tfor (let c = 0; c < segment.length; c++) {\n\t\t\tconst char = segment[c];\n\t\t\tif (char === \"\\\\\") {\n\t\t\t\tif (c < segment.length - 1) {\n\t\t\t\t\tresult += escapeRegExpChar(segment[c + 1]);\n\t\t\t\t\tc++;\n\t\t\t\t}\n\t\t\t} else if (char === \"?\") result += wildcard;\n\t\t\telse if (char === \"*\") result += `${wildcard}*?`;\n\t\t\telse result += escapeRegExpChar(char);\n\t\t}\n\t\tresult += currentSeparator;\n\t}\n\treturn result;\n}\nfunction isMatch(regexp, sample) {\n\tif (typeof sample !== \"string\") throw new TypeError(`Sample must be a string, but ${typeof sample} given`);\n\treturn regexp.test(sample);\n}\n/**\n* Compiles one or more glob patterns into a RegExp and returns an isMatch function.\n* The isMatch function takes a sample string as its only argument and returns `true`\n* if the string matches the pattern(s).\n*\n* ```js\n* wildcardMatch('src/*.js')('src/index.js') //=> true\n* ```\n*\n* ```js\n* const isMatch = wildcardMatch('*.example.com', '.')\n* isMatch('foo.example.com') //=> true\n* isMatch('foo.bar.com') //=> false\n* ```\n*/\nfunction wildcardMatch(pattern, options) {\n\tif (typeof pattern !== \"string\" && !Array.isArray(pattern)) throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof pattern} given`);\n\tif (typeof options === \"string\" || typeof options === \"boolean\") options = { separator: options };\n\tif (arguments.length === 2 && !(typeof options === \"undefined\" || typeof options === \"object\" && options !== null && !Array.isArray(options))) throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof options} given`);\n\toptions = options || {};\n\tif (options.separator === \"\\\\\") throw new Error(\"\\\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead\");\n\tconst regexpPattern = transform(pattern, options.separator);\n\tconst regexp = new RegExp(`^${regexpPattern}$`, options.flags);\n\tconst fn = isMatch.bind(null, regexp);\n\tfn.options = options;\n\tfn.pattern = pattern;\n\tfn.regexp = regexp;\n\treturn fn;\n}\n//#endregion\nexport { wildcardMatch };\n","import { wildcardMatch } from \"./wildcard.mjs\";\nimport { env } from \"@better-auth/core/env\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\n//#region src/utils/url.ts\nconst SLASH_CHAR_CODE = \"/\".charCodeAt(0);\n/**\n* Minimal loopback check for dev scheme inference only. Reachable from\n* `client/config.ts` via `getBaseURL`, so we MUST NOT import the full\n* `@better-auth/core/utils/host` classifier here: its `utils/ip` dependency\n* on zod would leak into the client bundle (see `e2e/smoke/test/vite.spec.ts`).\n*\n* Server-side SSRF/loopback checks (oauth redirect matching, trusted-origin\n* resolution, electron fetch gate) continue to use the authoritative\n* `isLoopbackHost` from `@better-auth/core/utils/host`. This helper's only\n* job is picking `http` vs `https` for dev ergonomics.\n*/\nfunction isLoopbackForDevScheme(host) {\n\tconst hostname = host.replace(/:\\d+$/, \"\").replace(/^\\[|\\]$/g, \"\").toLowerCase();\n\treturn hostname === \"localhost\" || hostname.endsWith(\".localhost\") || hostname === \"::1\" || hostname.startsWith(\"127.\");\n}\nfunction trimTrailingSlashes(value) {\n\tlet end = value.length;\n\twhile (end > 0 && value.charCodeAt(end - 1) === SLASH_CHAR_CODE) end--;\n\treturn end === value.length ? value : value.slice(0, end);\n}\nfunction checkHasPath(url) {\n\ttry {\n\t\treturn (trimTrailingSlashes(new URL(url).pathname) || \"/\") !== \"/\";\n\t} catch {\n\t\tthrow new BetterAuthError(`Invalid base URL: ${url}. Please provide a valid base URL.`);\n\t}\n}\nfunction assertHasProtocol(url) {\n\ttry {\n\t\tconst parsedUrl = new URL(url);\n\t\tif (parsedUrl.protocol !== \"http:\" && parsedUrl.protocol !== \"https:\") throw new BetterAuthError(`Invalid base URL: ${url}. URL must include 'http://' or 'https://'`);\n\t} catch (error) {\n\t\tif (error instanceof BetterAuthError) throw error;\n\t\tthrow new BetterAuthError(`Invalid base URL: ${url}. Please provide a valid base URL.`, { cause: error });\n\t}\n}\nfunction withPath(url, path = \"/api/auth\") {\n\tassertHasProtocol(url);\n\tif (checkHasPath(url)) return url;\n\tconst trimmedUrl = trimTrailingSlashes(url);\n\tif (!path || path === \"/\") return trimmedUrl;\n\tpath = path.startsWith(\"/\") ? path : `/${path}`;\n\treturn `${trimmedUrl}${path}`;\n}\nfunction validateProxyHeader(header, type) {\n\tif (!header || header.trim() === \"\") return false;\n\tif (type === \"proto\") return header === \"http\" || header === \"https\";\n\tif (type === \"host\") {\n\t\tif ([\n\t\t\t/\\.\\./,\n\t\t\t/\\0/,\n\t\t\t/[\\s]/,\n\t\t\t/^[.]/,\n\t\t\t/[<>'\"]/,\n\t\t\t/javascript:/i,\n\t\t\t/file:/i,\n\t\t\t/data:/i\n\t\t].some((pattern) => pattern.test(header))) return false;\n\t\treturn /^[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(header) || /^(\\d{1,3}\\.){3}\\d{1,3}(:[0-9]{1,5})?$/.test(header) || /^\\[[0-9a-fA-F:]+\\](:[0-9]{1,5})?$/.test(header) || /^localhost(:[0-9]{1,5})?$/i.test(header);\n\t}\n\treturn false;\n}\nfunction getBaseURL(url, path, request, loadEnv, trustedProxyHeaders) {\n\tif (url) return withPath(url, path);\n\tif (loadEnv !== false) {\n\t\tconst fromEnv = env.BETTER_AUTH_URL || env.NEXT_PUBLIC_BETTER_AUTH_URL || env.PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_AUTH_URL || (env.BASE_URL !== \"/\" ? env.BASE_URL : void 0);\n\t\tif (fromEnv) return withPath(fromEnv, path);\n\t}\n\tconst fromRequest = request?.headers.get(\"x-forwarded-host\");\n\tconst fromRequestProto = request?.headers.get(\"x-forwarded-proto\");\n\tif (fromRequest && fromRequestProto && trustedProxyHeaders) {\n\t\tif (validateProxyHeader(fromRequestProto, \"proto\") && validateProxyHeader(fromRequest, \"host\")) try {\n\t\t\treturn withPath(`${fromRequestProto}://${fromRequest}`, path);\n\t\t} catch (_error) {}\n\t}\n\tif (request) {\n\t\tconst url = getOrigin(request.url);\n\t\tif (!url) throw new BetterAuthError(\"Could not get origin from request. Please provide a valid base URL.\");\n\t\treturn withPath(url, path);\n\t}\n\tif (typeof window !== \"undefined\" && window.location) return withPath(window.location.origin, path);\n}\nfunction getOrigin(url) {\n\ttry {\n\t\tconst parsedUrl = new URL(url);\n\t\treturn parsedUrl.origin === \"null\" ? null : parsedUrl.origin;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction getProtocol(url) {\n\ttry {\n\t\treturn new URL(url).protocol;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction getHost(url) {\n\ttry {\n\t\treturn new URL(url).host;\n\t} catch {\n\t\treturn null;\n\t}\n}\n/**\n* Checks if the baseURL config is a dynamic config object\n*/\nfunction isDynamicBaseURLConfig(config) {\n\treturn typeof config === \"object\" && config !== null && \"allowedHosts\" in config && Array.isArray(config.allowedHosts);\n}\n/**\n* Check if a value is a `Request`\n* - `instanceof`: works for native Request instances\n* - `toString`: handles where instanceof check fails but the object is still a\n* valid Request (e.g. cross-realm, polyfills). Paired with a shape check so\n* an object that only spoofs `Symbol.toStringTag` without the real shape is\n* rejected before downstream code tries to read `.headers` / `.url`.\n*\n* @param value The value to check\n* @returns `true` if the value is a Request instance\n*/\nfunction isRequestLike(value) {\n\tif (value instanceof Request) return true;\n\tif (typeof value !== \"object\" || value === null || Object.prototype.toString.call(value) !== \"[object Request]\") return false;\n\tconst v = value;\n\treturn typeof v.url === \"string\" && typeof v.headers === \"object\" && v.headers !== null && typeof v.headers.get === \"function\";\n}\n/**\n* Extracts the host from a `Request` or `Headers`.\n* Honors `x-forwarded-host` only when `trustedProxyHeaders` is enabled,\n* then falls back to the `host` header and finally the request URL.\n*/\nfunction getHostFromSource(source, trustedProxyHeaders) {\n\tconst headers = isRequestLike(source) ? source.headers : source;\n\tif (trustedProxyHeaders) {\n\t\tconst forwardedHost = headers.get(\"x-forwarded-host\");\n\t\tif (forwardedHost && validateProxyHeader(forwardedHost, \"host\")) return forwardedHost;\n\t}\n\tconst host = headers.get(\"host\");\n\tif (host && validateProxyHeader(host, \"host\")) return host;\n\tif (isRequestLike(source)) try {\n\t\treturn new URL(source.url).host;\n\t} catch {\n\t\treturn null;\n\t}\n\treturn null;\n}\n/**\n* Extracts the protocol from a `Request` or `Headers`.\n* Honors `x-forwarded-proto` only when `trustedProxyHeaders` is enabled,\n* then falls back to the request URL, then to \"https\".\n*/\nfunction getProtocolFromSource(source, configProtocol, trustedProxyHeaders) {\n\tif (configProtocol === \"http\" || configProtocol === \"https\") return configProtocol;\n\tconst headers = isRequestLike(source) ? source.headers : source;\n\tif (trustedProxyHeaders) {\n\t\tconst forwardedProto = headers.get(\"x-forwarded-proto\");\n\t\tif (forwardedProto && validateProxyHeader(forwardedProto, \"proto\")) return forwardedProto;\n\t}\n\tif (isRequestLike(source)) try {\n\t\tconst url = new URL(source.url);\n\t\tif (url.protocol === \"http:\" || url.protocol === \"https:\") return url.protocol.slice(0, -1);\n\t} catch {}\n\tconst host = getHostFromSource(source, trustedProxyHeaders);\n\tif (host && isLoopbackForDevScheme(host)) return \"http\";\n\treturn \"https\";\n}\n/**\n* Matches a hostname against a host pattern.\n* Supports wildcard patterns like `*.vercel.app` or `preview-*.myapp.com`.\n*\n* @param host The hostname to test (e.g., \"myapp.com\", \"preview-123.vercel.app\")\n* @param pattern The host pattern (e.g., \"myapp.com\", \"*.vercel.app\")\n* @returns {boolean} true if the host matches the pattern, false otherwise.\n*\n* @example\n* ```ts\n* matchesHostPattern(\"myapp.com\", \"myapp.com\") // true\n* matchesHostPattern(\"preview-123.vercel.app\", \"*.vercel.app\") // true\n* matchesHostPattern(\"preview-123.myapp.com\", \"preview-*.myapp.com\") // true\n* matchesHostPattern(\"evil.com\", \"myapp.com\") // false\n* ```\n*/\nconst matchesHostPattern = (host, pattern) => {\n\tif (!host || !pattern) return false;\n\tconst normalizedHost = host.replace(/^https?:\\/\\//, \"\").split(\"/\")[0].toLowerCase();\n\tconst normalizedPattern = pattern.replace(/^https?:\\/\\//, \"\").split(\"/\")[0].toLowerCase();\n\tif (normalizedPattern.includes(\"*\") || normalizedPattern.includes(\"?\")) return wildcardMatch(normalizedPattern)(normalizedHost);\n\treturn normalizedHost.toLowerCase() === normalizedPattern.toLowerCase();\n};\n/**\n* Resolves the base URL from a dynamic config based on the incoming request.\n* Validates the derived host against the allowedHosts allowlist.\n*\n* @param config The dynamic base URL config\n* @param request The incoming request\n* @param basePath The base path to append\n* @returns The resolved base URL with path\n* @throws BetterAuthError if host is not in allowedHosts and no fallback is set\n*/\nfunction resolveDynamicBaseURL(config, source, basePath, trustedProxyHeaders) {\n\tconst host = getHostFromSource(source, trustedProxyHeaders);\n\tif (!host) {\n\t\tif (config.fallback) return withPath(config.fallback, basePath);\n\t\tthrow new BetterAuthError(\"Could not determine host from request headers. Please provide a fallback URL in your baseURL config.\");\n\t}\n\tif (config.allowedHosts.some((pattern) => matchesHostPattern(host, pattern))) return withPath(`${getProtocolFromSource(source, config.protocol, trustedProxyHeaders)}://${host}`, basePath);\n\tif (config.fallback) return withPath(config.fallback, basePath);\n\tthrow new BetterAuthError(`Host \"${host}\" is not in the allowed hosts list. Allowed hosts: ${config.allowedHosts.join(\", \")}. Add this host to your allowedHosts config or provide a fallback URL.`);\n}\n/**\n* Resolves the base URL from any config type (static string or dynamic object).\n* This is the main entry point for base URL resolution.\n*\n* @param config The base URL config (string or object)\n* @param basePath The base path to append\n* @param request Optional request for dynamic resolution\n* @param loadEnv Whether to load from environment variables\n* @param trustedProxyHeaders Whether to trust proxy headers (for legacy behavior)\n* @returns The resolved base URL with path\n*/\nfunction resolveBaseURL(config, basePath, source, loadEnv, trustedProxyHeaders) {\n\tif (isDynamicBaseURLConfig(config)) {\n\t\tif (source) return resolveDynamicBaseURL(config, source, basePath, trustedProxyHeaders);\n\t\tif (config.fallback) return withPath(config.fallback, basePath);\n\t\treturn getBaseURL(void 0, basePath, void 0, loadEnv, trustedProxyHeaders);\n\t}\n\tconst request = isRequestLike(source) ? source : void 0;\n\tif (typeof config === \"string\") return getBaseURL(config, basePath, request, loadEnv, trustedProxyHeaders);\n\treturn getBaseURL(void 0, basePath, request, loadEnv, trustedProxyHeaders);\n}\n//#endregion\nexport { getBaseURL, getHost, getHostFromSource, getOrigin, getProtocol, getProtocolFromSource, isDynamicBaseURLConfig, isRequestLike, matchesHostPattern, resolveBaseURL, resolveDynamicBaseURL, trimTrailingSlashes };\n","//#region src/utils/url.ts\n/**\n* Normalizes a request pathname by removing the basePath prefix and trailing slashes.\n* This is useful for matching paths against configured path lists.\n*\n* @param requestUrl - The full request URL\n* @param basePath - The base path of the auth API (e.g., \"/api/auth\")\n* @returns The normalized path without basePath prefix or trailing slashes,\n* or \"/\" if URL parsing fails\n*\n* @example\n* normalizePathname(\"http://localhost:3000/api/auth/sso/saml2/callback/provider1\", \"/api/auth\")\n* // Returns: \"/sso/saml2/callback/provider1\"\n*\n* normalizePathname(\"http://localhost:3000/sso/saml2/callback/provider1/\", \"/\")\n* // Returns: \"/sso/saml2/callback/provider1\"\n*/\nfunction normalizePathname(requestUrl, basePath) {\n\tlet pathname;\n\ttry {\n\t\tpathname = new URL(requestUrl).pathname.replace(/\\/+$/, \"\") || \"/\";\n\t} catch {\n\t\treturn \"/\";\n\t}\n\tconst normalizedBasePath = basePath.replace(/\\/+$/, \"\");\n\tif (normalizedBasePath === \"\") return pathname;\n\tif (pathname === normalizedBasePath) return \"/\";\n\tif (pathname.startsWith(normalizedBasePath + \"/\")) return pathname.slice(normalizedBasePath.length).replace(/\\/+$/, \"\") || \"/\";\n\treturn pathname;\n}\nconst URL_REFERENCE_ORIGIN = \"https://better-auth.invalid\";\n/**\n* Appends query parameters before the fragment of an absolute or root-relative URL.\n* Existing query text is retained without parsing it into name-value pairs.\n*\n* This function only composes URLs. Callers must validate untrusted input.\n*\n* @throws TypeError if parsing fails or a relative input changes authority.\n*/\nfunction appendQueryParams(input, params) {\n\tconst relative = input.startsWith(\"/\");\n\tif (input.startsWith(\"//\") || input.startsWith(\"/\\\\\")) throw new TypeError(\"Expected an absolute or root-relative URL\");\n\tconst parsedURL = relative ? new URL(input, URL_REFERENCE_ORIGIN) : new URL(input);\n\tif (relative && parsedURL.origin !== URL_REFERENCE_ORIGIN) throw new TypeError(\"Expected an absolute or root-relative URL\");\n\tconst query = params.toString();\n\tif (!query) return input;\n\tconst separator = parsedURL.search.endsWith(\"&\") ? \"\" : \"&\";\n\tparsedURL.search = parsedURL.search ? `${parsedURL.search}${separator}${query}` : query;\n\treturn relative ? parsedURL.href.slice(parsedURL.origin.length) : parsedURL.href;\n}\n/**\n* Schemes that execute or embed code when navigated to or accepted as a\n* redirect target. These are never safe as an OAuth `redirect_uri` or as a\n* client-side navigation target (`window.location.href`, `location.assign`, ...).\n*/\nconst DANGEROUS_URL_SCHEMES = [\n\t\"javascript:\",\n\t\"data:\",\n\t\"vbscript:\"\n];\n/**\n* Returns `false` only when `value` is an absolute URL using a dangerous scheme\n* (`javascript:`, `data:`, `vbscript:`). Relative URLs (e.g. `/dashboard`) and\n* safe absolute schemes (`http`, `https`, custom app schemes such as\n* `myapp://`) return `true`.\n*\n* Use this to guard browser navigation sinks and any redirect target that may\n* originate from untrusted input. It is intentionally narrow: it blocks code\n* execution schemes without rejecting relative paths or mobile deep links.\n*/\nfunction isSafeUrlScheme(value) {\n\tlet parsed;\n\ttry {\n\t\tparsed = new URL(value);\n\t} catch {\n\t\treturn true;\n\t}\n\treturn !DANGEROUS_URL_SCHEMES.includes(parsed.protocol);\n}\n//#endregion\nexport { DANGEROUS_URL_SCHEMES, appendQueryParams, isSafeUrlScheme, normalizePathname };\n","import { isDevelopment, isTest } from \"../env/env-impl.mjs\";\nimport * as z from \"zod\";\n//#region src/utils/ip.ts\nconst ipv4Schema = z.ipv4();\nconst ipv6Schema = z.ipv6();\n/**\n* Checks if an IP is valid IPv4 or IPv6\n*/\nfunction isValidIP(ip) {\n\treturn isIPv4(ip) || isIPv6(ip);\n}\nfunction isIPv4(ip) {\n\treturn z.validate(ipv4Schema, ip);\n}\nfunction isIPv6(ip) {\n\treturn z.validate(ipv6Schema, ip);\n}\n/**\n* Converts IPv4-mapped IPv6 address to IPv4\n* e.g., \"::ffff:192.0.2.1\" -> \"192.0.2.1\"\n*/\nfunction extractIPv4FromMapped(ipv6) {\n\tconst lower = ipv6.toLowerCase();\n\tif (lower.startsWith(\"::ffff:\")) {\n\t\tconst ipv4Part = lower.substring(7);\n\t\tif (isIPv4(ipv4Part)) return ipv4Part;\n\t}\n\tconst parts = ipv6.split(\":\");\n\tif (parts.length === 7 && parts[5]?.toLowerCase() === \"ffff\") {\n\t\tconst ipv4Part = parts[6];\n\t\tif (ipv4Part && isIPv4(ipv4Part)) return ipv4Part;\n\t}\n\tif (lower.includes(\"::ffff:\") || lower.includes(\":ffff:\")) {\n\t\tconst groups = expandIPv6(ipv6);\n\t\tif (groups.length === 8 && groups[0] === \"0000\" && groups[1] === \"0000\" && groups[2] === \"0000\" && groups[3] === \"0000\" && groups[4] === \"0000\" && groups[5] === \"ffff\" && groups[6] && groups[7]) return `${Number.parseInt(groups[6].substring(0, 2), 16)}.${Number.parseInt(groups[6].substring(2, 4), 16)}.${Number.parseInt(groups[7].substring(0, 2), 16)}.${Number.parseInt(groups[7].substring(2, 4), 16)}`;\n\t}\n\treturn null;\n}\n/**\n* Expands a compressed IPv6 address to full form\n* e.g., \"2001:db8::1\" -> [\"2001\", \"0db8\", \"0000\", \"0000\", \"0000\", \"0000\", \"0000\", \"0001\"]\n*/\nfunction expandIPv6(ipv6) {\n\tif (ipv6.includes(\"::\")) {\n\t\tconst sides = ipv6.split(\"::\");\n\t\tconst left = sides[0] ? sides[0].split(\":\") : [];\n\t\tconst right = sides[1] ? sides[1].split(\":\") : [];\n\t\tconst missingGroups = 8 - left.length - right.length;\n\t\tconst zeros = Array(missingGroups).fill(\"0000\");\n\t\tconst paddedLeft = left.map((g) => g.padStart(4, \"0\"));\n\t\tconst paddedRight = right.map((g) => g.padStart(4, \"0\"));\n\t\treturn [\n\t\t\t...paddedLeft,\n\t\t\t...zeros,\n\t\t\t...paddedRight\n\t\t];\n\t}\n\treturn ipv6.split(\":\").map((g) => g.padStart(4, \"0\"));\n}\n/**\n* Normalizes an IPv6 address to canonical form\n* e.g., \"2001:DB8::1\" -> \"2001:0db8:0000:0000:0000:0000:0000:0001\"\n*/\nfunction normalizeIPv6(ipv6, subnetPrefix) {\n\tconst groups = expandIPv6(ipv6);\n\tif (subnetPrefix !== void 0 && subnetPrefix < 128) {\n\t\tlet bitsRemaining = Math.max(0, Math.floor(subnetPrefix));\n\t\treturn groups.map((group) => {\n\t\t\tif (bitsRemaining <= 0) return \"0000\";\n\t\t\tif (bitsRemaining >= 16) {\n\t\t\t\tbitsRemaining -= 16;\n\t\t\t\treturn group;\n\t\t\t}\n\t\t\tconst masked = Number.parseInt(group, 16) & (65535 << 16 - bitsRemaining & 65535);\n\t\t\tbitsRemaining = 0;\n\t\t\treturn masked.toString(16).padStart(4, \"0\");\n\t\t}).join(\":\").toLowerCase();\n\t}\n\treturn groups.join(\":\").toLowerCase();\n}\n/**\n* Normalizes an IP address (IPv4 or IPv6) for consistent rate limiting.\n*\n* @param ip - The IP address to normalize\n* @param options - Normalization options\n* @returns Normalized IP address\n*\n* @example\n* normalizeIP(\"2001:DB8::1\")\n* // -> \"2001:0db8:0000:0000:0000:0000:0000:0000\"\n*\n* @example\n* normalizeIP(\"::ffff:192.0.2.1\")\n* // -> \"192.0.2.1\" (converted to IPv4)\n*\n* @example\n* normalizeIP(\"2001:db8::1\", { ipv6Subnet: 64 })\n* // -> \"2001:0db8:0000:0000:0000:0000:0000:0000\" (subnet /64)\n*/\nfunction normalizeIP(ip, options = {}) {\n\tif (isIPv4(ip)) return ip.toLowerCase();\n\tif (!isIPv6(ip)) return ip.toLowerCase();\n\tconst ipv4 = extractIPv4FromMapped(ip);\n\tif (ipv4) return ipv4.toLowerCase();\n\treturn normalizeIPv6(ip, options.ipv6Subnet ?? 64);\n}\n/**\n* Raw bytes of an IP for CIDR comparison. Returns `null` for an invalid IP.\n*/\nfunction ipToBytes(ip) {\n\tif (isIPv4(ip)) return Uint8Array.from(ip.split(\".\").map((octet) => Number(octet)));\n\tif (!isIPv6(ip)) return null;\n\tconst mapped = extractIPv4FromMapped(ip);\n\tif (mapped) return Uint8Array.from(mapped.split(\".\").map((octet) => Number(octet)));\n\tconst groups = expandIPv6(ip);\n\tconst bytes = new Uint8Array(16);\n\tfor (let i = 0; i < 8; i++) {\n\t\tconst group = Number.parseInt(groups[i] ?? \"0\", 16);\n\t\tbytes[i * 2] = group >> 8 & 255;\n\t\tbytes[i * 2 + 1] = group & 255;\n\t}\n\treturn bytes;\n}\nconst CIDR_PREFIX_PATTERN = /^\\d+$/;\n/**\n* Parses an IP or `IP/prefix` string into network bytes and a prefix length.\n* The prefix must be digits only and within the address family. `null` if the\n* value is not a valid IP or CIDR range, which keeps a malformed entry from\n* silently behaving like a non-match.\n*/\nfunction parseCIDR(value) {\n\tconst slash = value.lastIndexOf(\"/\");\n\tconst bytes = ipToBytes(slash === -1 ? value : value.slice(0, slash));\n\tif (!bytes) return null;\n\tconst maxBits = bytes.length * 8;\n\tif (slash === -1) return {\n\t\tbytes,\n\t\tprefix: maxBits\n\t};\n\tconst prefixPart = value.slice(slash + 1);\n\tif (!CIDR_PREFIX_PATTERN.test(prefixPart)) return null;\n\tconst prefix = Number(prefixPart);\n\treturn prefix <= maxBits ? {\n\t\tbytes,\n\t\tprefix\n\t} : null;\n}\n/**\n* Whether `ipBytes` falls inside an already-parsed CIDR network.\n*/\nfunction matchesCIDR(ipBytes, net) {\n\tif (ipBytes.length !== net.bytes.length) return false;\n\tlet bitsRemaining = net.prefix;\n\tfor (let i = 0; i < ipBytes.length && bitsRemaining > 0; i++) {\n\t\tconst take = bitsRemaining >= 8 ? 8 : bitsRemaining;\n\t\tconst mask = take === 8 ? 255 : 255 << 8 - take & 255;\n\t\tif (((ipBytes[i] ?? 0) & mask) !== ((net.bytes[i] ?? 0) & mask)) return false;\n\t\tbitsRemaining -= 8;\n\t}\n\treturn true;\n}\n/**\n* Trusted-proxy entries that are not a valid IP address or CIDR range.\n*/\nfunction findInvalidTrustedProxies(entries) {\n\treturn entries.filter((entry) => parseCIDR(entry) === null);\n}\n/**\n* Resolves the client IP from a forwarded header. The leftmost token is spoofable,\n* so with `trustedProxies` the chain is stripped from the right to the first\n* untrusted hop. Otherwise only a single-value header is trusted. Returns `null`\n* when no trustworthy client IP can be resolved.\n*/\nfunction getIPFromHeader(value, options = {}) {\n\tconst forwardedIps = value.split(\",\").map((ip) => ip.trim()).filter(Boolean);\n\tif (forwardedIps.length === 0) return null;\n\tconst trustedProxies = (options.trustedProxies ?? []).map(parseCIDR).filter((proxy) => {\n\t\treturn proxy !== null;\n\t});\n\tif (trustedProxies.length > 0) {\n\t\tfor (let i = forwardedIps.length - 1; i >= 0; i--) {\n\t\t\tconst ip = forwardedIps[i];\n\t\t\tconst ipBytes = ip ? ipToBytes(ip) : null;\n\t\t\tif (!ip || !ipBytes) return null;\n\t\t\tif (trustedProxies.some((proxy) => matchesCIDR(ipBytes, proxy))) continue;\n\t\t\treturn normalizeIP(ip, { ipv6Subnet: options.ipv6Subnet });\n\t\t}\n\t\treturn null;\n\t}\n\tif (forwardedIps.length !== 1) return null;\n\tconst selectedIp = forwardedIps[0];\n\tif (!selectedIp || !isValidIP(selectedIp)) return null;\n\treturn normalizeIP(selectedIp, { ipv6Subnet: options.ipv6Subnet });\n}\nconst LOCALHOST_IP = \"127.0.0.1\";\nconst DEFAULT_IP_HEADERS = [\"x-forwarded-for\"];\n/**\n* Resolves the client IP for a request from the configured IP headers.\n* Honors `disableIpTracking`, walks `ipAddressHeaders` in order (default\n* `x-forwarded-for`), and falls back to localhost in development and test.\n* Returns `null` when tracking is disabled or no trustworthy IP can be resolved.\n*/\nfunction getIP(req, options) {\n\tif (options.advanced?.ipAddress?.disableIpTracking) return null;\n\tconst headers = \"headers\" in req ? req.headers : req;\n\tconst ipHeaders = options.advanced?.ipAddress?.ipAddressHeaders || DEFAULT_IP_HEADERS;\n\tfor (const key of ipHeaders) {\n\t\tconst value = \"get\" in headers ? headers.get(key) : headers[key];\n\t\tif (typeof value === \"string\") {\n\t\t\tconst ip = getIPFromHeader(value, {\n\t\t\t\tipv6Subnet: options.advanced?.ipAddress?.ipv6Subnet,\n\t\t\t\ttrustedProxies: options.advanced?.ipAddress?.trustedProxies\n\t\t\t});\n\t\t\tif (ip) return ip;\n\t\t}\n\t}\n\tif (isTest() || isDevelopment()) return LOCALHOST_IP;\n\treturn null;\n}\n/**\n* Creates a rate limit key from IP and path\n* Uses a separator to prevent collision attacks\n*\n* @param ip - The IP address (should be normalized)\n* @param path - The request path\n* @returns Rate limit key\n*/\nfunction createRateLimitKey(ip, path) {\n\treturn `${ip}|${path}`;\n}\n//#endregion\nexport { createRateLimitKey, findInvalidTrustedProxies, getIP, getIPFromHeader, isValidIP, normalizeIP };\n","import { __getBetterAuthGlobal } from \"./global.mjs\";\nimport { getAsyncLocalStorage } from \"@better-auth/core/async_hooks\";\n//#region src/context/request-state.ts\nconst ensureAsyncStorage = async () => {\n\tconst betterAuthGlobal = __getBetterAuthGlobal();\n\tconst existing = betterAuthGlobal.context.requestStateAsyncStorage;\n\tif (existing) return existing;\n\tconst AsyncLocalStorage = await getAsyncLocalStorage();\n\tbetterAuthGlobal.context.requestStateAsyncStorage ??= new AsyncLocalStorage();\n\treturn betterAuthGlobal.context.requestStateAsyncStorage;\n};\nasync function getRequestStateAsyncLocalStorage() {\n\treturn ensureAsyncStorage();\n}\nasync function hasRequestState() {\n\treturn (await ensureAsyncStorage()).getStore() !== void 0;\n}\nasync function getCurrentRequestState() {\n\tconst store = (await ensureAsyncStorage()).getStore();\n\tif (!store) throw new Error(\"No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.\");\n\treturn store;\n}\nasync function runWithRequestState(store, fn) {\n\treturn (await ensureAsyncStorage()).run(store, fn);\n}\nfunction defineRequestState(initFn) {\n\tconst ref = Object.freeze({});\n\treturn {\n\t\tget ref() {\n\t\t\treturn ref;\n\t\t},\n\t\tasync get() {\n\t\t\tconst store = await getCurrentRequestState();\n\t\t\tif (!store.has(ref)) {\n\t\t\t\tconst initialValue = await initFn();\n\t\t\t\tstore.set(ref, initialValue);\n\t\t\t\treturn initialValue;\n\t\t\t}\n\t\t\treturn store.get(ref);\n\t\t},\n\t\tasync set(value) {\n\t\t\t(await getCurrentRequestState()).set(ref, value);\n\t\t}\n\t};\n}\n//#endregion\nexport { defineRequestState, getCurrentRequestState, getRequestStateAsyncLocalStorage, hasRequestState, runWithRequestState };\n","import { __getBetterAuthGlobal } from \"./global.mjs\";\nimport { runtimeSchemaCheckFor } from \"../db/schema-check.mjs\";\nimport { logger } from \"../env/logger.mjs\";\nimport { getAsyncLocalStorage } from \"@better-auth/core/async_hooks\";\n//#region src/context/transaction.ts\nconst ensureAsyncStorage = async () => {\n\tconst betterAuthGlobal = __getBetterAuthGlobal();\n\tconst existing = betterAuthGlobal.context.adapterAsyncStorage;\n\tif (existing) return existing;\n\tconst AsyncLocalStorage = await getAsyncLocalStorage();\n\tbetterAuthGlobal.context.adapterAsyncStorage ??= new AsyncLocalStorage();\n\treturn betterAuthGlobal.context.adapterAsyncStorage;\n};\n/**\n* This is for internal use only. Most users should use `getCurrentAdapter` instead.\n*\n* It is exposed for advanced use cases where you need direct access to the AsyncLocalStorage instance.\n*/\nconst getCurrentDBAdapterAsyncLocalStorage = async () => {\n\treturn ensureAsyncStorage();\n};\nconst getCurrentAdapter = async (fallback) => {\n\treturn ensureAsyncStorage().then((als) => {\n\t\treturn als.getStore()?.adapter || fallback;\n\t}).catch(() => {\n\t\treturn fallback;\n\t});\n};\nconst runWithAdapter = async (adapter, fn) => {\n\tlet called = false;\n\treturn ensureAsyncStorage().then(async (als) => {\n\t\tcalled = true;\n\t\tconst pendingHooks = [];\n\t\tlet result;\n\t\tlet error;\n\t\tlet hasError = false;\n\t\ttry {\n\t\t\tresult = await als.run({\n\t\t\t\tadapter,\n\t\t\t\tpendingHooks,\n\t\t\t\tisTransactionActive: false\n\t\t\t}, fn);\n\t\t} catch (err) {\n\t\t\terror = err;\n\t\t\thasError = true;\n\t\t}\n\t\tfor (const hook of pendingHooks) await hook();\n\t\tif (hasError) throw error;\n\t\treturn result;\n\t}).catch((err) => {\n\t\tif (!called) return fn();\n\t\tthrow err;\n\t});\n};\n/**\n* Runs `fn` in a transaction on `adapter`, joining the current one when\n* already inside it, then runs the hooks queued with\n* `queueAfterTransactionHook` once the work commits.\n*\n* When the adapter has no real transaction (`transaction: false`), writes are\n* applied as they happen and cannot roll back, so queued hooks also run when\n* `fn` throws. The original error is still rethrown; a hook failure on that\n* path goes to `onAfterCommitHookError`, or is logged when none is given.\n*/\nconst runWithTransaction = async (adapter, fn, options) => {\n\tlet called = false;\n\treturn ensureAsyncStorage().then(async (als) => {\n\t\tcalled = true;\n\t\tif (als.getStore()?.isTransactionActive) return fn();\n\t\tconst pendingSchemaCheck = runtimeSchemaCheckFor(adapter)?.();\n\t\tif (pendingSchemaCheck) await pendingSchemaCheck;\n\t\tlet pendingHooks = [];\n\t\tlet result;\n\t\tlet error;\n\t\tlet hasError = false;\n\t\ttry {\n\t\t\tresult = await adapter.transaction(async (trx) => {\n\t\t\t\tpendingHooks = [];\n\t\t\t\treturn als.run({\n\t\t\t\t\tadapter: trx,\n\t\t\t\t\tpendingHooks,\n\t\t\t\t\tisTransactionActive: true\n\t\t\t\t}, fn);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\thasError = true;\n\t\t\terror = e;\n\t\t}\n\t\tconst runPendingHooks = async (unhandledErrors) => {\n\t\t\tfor (const hook of pendingHooks) try {\n\t\t\t\tawait hook();\n\t\t\t} catch (hookError) {\n\t\t\t\tif (!options?.onAfterCommitHookError) {\n\t\t\t\t\tif (unhandledErrors === \"throw\") throw hookError;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tlogger.error(\"Failed to run an after-commit hook for work that could not roll back\", hookError);\n\t\t\t\t\t} catch {}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait options.onAfterCommitHookError(hookError);\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t};\n\t\tif (hasError) {\n\t\t\tif (adapter.options?.adapterConfig.transaction === false) await runPendingHooks(\"log\");\n\t\t\tthrow error;\n\t\t}\n\t\tawait runPendingHooks(\"throw\");\n\t\treturn result;\n\t}).catch((err) => {\n\t\tif (!called) return fn();\n\t\tthrow err;\n\t});\n};\n/**\n* Queue a hook to be executed after the current transaction commits.\n* If not in a transaction, the hook will execute immediately.\n*\n* When the adapter has no real transaction (`transaction: false`), the hook\n* also runs if the surrounding work fails, since its writes were kept.\n*/\nconst queueAfterTransactionHook = async (hook, options) => {\n\tconst executeHook = async () => {\n\t\ttry {\n\t\t\tawait hook();\n\t\t} catch (error) {\n\t\t\tif (!options?.onError) throw error;\n\t\t\tawait options.onError(error);\n\t\t}\n\t};\n\tlet storage;\n\ttry {\n\t\tstorage = await ensureAsyncStorage();\n\t} catch {\n\t\treturn executeHook();\n\t}\n\tconst store = storage.getStore();\n\tif (!store?.isTransactionActive) return executeHook();\n\tstore.pendingHooks.push(executeHook);\n};\n//#endregion\nexport { getCurrentAdapter, getCurrentDBAdapterAsyncLocalStorage, queueAfterTransactionHook, runWithAdapter, runWithTransaction };\n","import { defineRequestState } from \"@better-auth/core/context\";\n//#region src/api/state/oauth.ts\nconst { get: getRawOAuthState, set: setOAuthState } = defineRequestState(() => null);\n/**\n* Reads the OAuth state for the current request. During a callback it holds the\n* state parsed from the provider redirect; during sign-in it holds the state\n* just generated.\n*\n* Top-level keys beyond the documented fields are client-supplied\n* (`additionalData`) and must not be trusted. Server-trusted values live under\n* {@link OAuthState.serverContext}.\n*/\nconst getOAuthState = async () => {\n\treturn await getRawOAuthState();\n};\n/**\n* @internal Read accumulated server context to embed during state generation.\n*/\nconst { get: getOAuthServerContext, set: setOAuthServerContext } = defineRequestState(() => null);\n/**\n* Attaches server-trusted data to the current OAuth flow so it survives the\n* provider redirect. Call this from a `before` hook on an OAuth sign-in path\n* (for example `/sign-in/social` or `/sign-in/oauth2`). `generateState` embeds\n* the accumulated values into the state, and they become readable on the\n* callback via `getOAuthState().serverContext`.\n*\n* Unlike the request body's `additionalData`, values set here cannot be spoofed\n* by the client. Multiple callers merge: each call adds its own keys. Values are\n* stored as `unknown`, so narrow their shape when reading them back.\n*/\nconst addOAuthServerContext = async (values) => {\n\tawait setOAuthServerContext({\n\t\t...await getOAuthServerContext() ?? {},\n\t\t...values\n\t});\n};\n//#endregion\nexport { addOAuthServerContext, getOAuthServerContext, getOAuthState, setOAuthState };\n","import { defineRequestState } from \"@better-auth/core/context\";\n//#region src/api/state/should-session-refresh.ts\n/**\n* State for skipping session refresh\n*\n* In some cases, such as when using server-side rendering (SSR) or when dealing with\n* certain types of requests, it may be necessary to skip session refresh to prevent\n* potential inconsistencies between the session data in the database and the session\n* data stored in cookies.\n*/\nconst { get: getShouldSkipSessionRefresh, set: setShouldSkipSessionRefresh } = defineRequestState(() => false);\n//#endregion\nexport { getShouldSkipSessionRefresh, setShouldSkipSessionRefresh };\n","//#region src/context/store-capabilities.ts\nfunction hasServerSessionStore(options) {\n\treturn !!options.database || !!options.secondaryStorage;\n}\nfunction hasServerAccountStore(options) {\n\treturn !!options.database;\n}\nfunction shouldBindAccountCookieToSessionUser(options) {\n\treturn hasServerAccountStore(options);\n}\n//#endregion\nexport { hasServerSessionStore, shouldBindAccountCookieToSessionUser };\n","import * as z from \"zod\";\n//#region src/db/schema/shared.ts\nconst coreSchema = z.object({\n\tid: z.string(),\n\tcreatedAt: z.date().default(() => /* @__PURE__ */ new Date()),\n\tupdatedAt: z.date().default(() => /* @__PURE__ */ new Date())\n});\n//#endregion\nexport { coreSchema };\n","import { coreSchema } from \"./shared.mjs\";\nimport * as z from \"zod\";\n//#region src/db/schema/session.ts\nconst sessionSchema = coreSchema.extend({\n\tuserId: z.coerce.string(),\n\texpiresAt: z.date(),\n\ttoken: z.string(),\n\tipAddress: z.string().nullish(),\n\tuserAgent: z.string().nullish()\n});\n//#endregion\nexport { sessionSchema };\n","import { coreSchema } from \"./shared.mjs\";\nimport * as z from \"zod\";\n//#region src/db/schema/user.ts\nconst userSchema = coreSchema.extend({\n\temail: z.string().transform((val) => val.toLowerCase()),\n\temailVerified: z.boolean().default(false),\n\tname: z.string(),\n\timage: z.string().nullish()\n});\n//#endregion\nexport { userSchema };\n","//#region src/utils/db.ts\n/**\n* Filters output data by removing fields with the `returned: false` attribute.\n* This ensures sensitive fields are not exposed in API responses.\n*/\nfunction filterOutputFields(data, additionalFields) {\n\tif (!data || !additionalFields) return data;\n\tconst returnFiltered = Object.entries(additionalFields).filter(([, { returned }]) => returned === false).map(([key]) => key);\n\treturn Object.entries(structuredClone(data)).filter(([key]) => !returnFiltered.includes(key)).reduce((acc, [key, value]) => ({\n\t\t...acc,\n\t\t[key]: value\n\t}), {});\n}\n//#endregion\nexport { filterOutputFields };\n","import { getAuthTables } from \"@better-auth/core/db\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { filterOutputFields } from \"@better-auth/core/utils/db\";\n//#region src/db/schema.ts\nconst cache = /* @__PURE__ */ new WeakMap();\nfunction getFields(options, modelName, mode) {\n\tconst cacheKey = `${modelName}:${mode}`;\n\tif (!cache.has(options)) cache.set(options, /* @__PURE__ */ new Map());\n\tconst tableCache = cache.get(options);\n\tif (tableCache.has(cacheKey)) return tableCache.get(cacheKey);\n\tconst coreSchema = mode === \"output\" ? getAuthTables(options)[modelName]?.fields ?? {} : {};\n\tconst additionalFields = modelName === \"user\" || modelName === \"session\" || modelName === \"account\" ? options[modelName]?.additionalFields : void 0;\n\tlet schema = {\n\t\t...coreSchema,\n\t\t...additionalFields ?? {}\n\t};\n\tfor (const plugin of options.plugins || []) if (plugin.schema && plugin.schema[modelName]) schema = {\n\t\t...schema,\n\t\t...plugin.schema[modelName].fields\n\t};\n\ttableCache.set(cacheKey, schema);\n\treturn schema;\n}\nfunction parseUserOutput(options, user) {\n\treturn filterOutputFields(user, getFields(options, \"user\", \"output\"));\n}\n/**\n* Builds a synthetic user object that matches the shape of a real user\n* returned from the database. This ensures enumeration protection works\n* correctly by making synthetic and real user responses indistinguishable.\n*\n* The function iterates over the user output schema and:\n* - Includes all fields that should be returned (returned !== false)\n* - Uses provided values when available\n* - Sets optional fields to null when no value is provided\n* - Applies default values where defined\n* - Always includes the 'id' field (not part of schema but always present)\n*/\nfunction buildSyntheticUserOutput(options, data) {\n\tconst schema = getFields(options, \"user\", \"output\");\n\tconst result = {};\n\tfor (const key in schema) {\n\t\tconst fieldAttr = schema[key];\n\t\tif (fieldAttr.returned === false) continue;\n\t\tif (key in data && data[key] !== void 0) result[key] = data[key];\n\t\telse if (fieldAttr.defaultValue !== void 0) result[key] = typeof fieldAttr.defaultValue === \"function\" ? fieldAttr.defaultValue() : fieldAttr.defaultValue;\n\t\telse if (!fieldAttr.required) result[key] = null;\n\t}\n\tif (\"id\" in data) result.id = data.id;\n\treturn result;\n}\nfunction parseSessionOutput(options, session) {\n\treturn filterOutputFields(session, getFields(options, \"session\", \"output\"));\n}\nfunction parseAccountOutput(options, account) {\n\tconst { accessToken: _accessToken, refreshToken: _refreshToken, idToken: _idToken, accessTokenExpiresAt: _accessTokenExpiresAt, refreshTokenExpiresAt: _refreshTokenExpiresAt, password: _password, ...rest } = filterOutputFields(account, getFields(options, \"account\", \"output\"));\n\treturn rest;\n}\nfunction parseInputData(data, schema) {\n\tconst action = schema.action || \"create\";\n\tconst fields = schema.fields;\n\tconst parsedData = Object.create(null);\n\tfor (const key in fields) {\n\t\tif (key in data) {\n\t\t\tif (fields[key].input === false) {\n\t\t\t\tif (fields[key].defaultValue !== void 0) {\n\t\t\t\t\tif (action !== \"update\") {\n\t\t\t\t\t\tparsedData[key] = fields[key].defaultValue;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (data[key]) throw APIError.from(\"BAD_REQUEST\", {\n\t\t\t\t\t...BASE_ERROR_CODES.FIELD_NOT_ALLOWED,\n\t\t\t\t\tmessage: `${key} is not allowed to be set`\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (fields[key].validator?.input && data[key] !== void 0) {\n\t\t\t\tconst result = fields[key].validator.input[\"~standard\"].validate(data[key]);\n\t\t\t\tif (result instanceof Promise) throw APIError.from(\"INTERNAL_SERVER_ERROR\", BASE_ERROR_CODES.ASYNC_VALIDATION_NOT_SUPPORTED);\n\t\t\t\tif (\"issues\" in result && result.issues) throw APIError.from(\"BAD_REQUEST\", {\n\t\t\t\t\t...BASE_ERROR_CODES.VALIDATION_ERROR,\n\t\t\t\t\tmessage: result.issues[0]?.message || \"Validation Error\"\n\t\t\t\t});\n\t\t\t\tparsedData[key] = result.value;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (fields[key].transform?.input && data[key] !== void 0) {\n\t\t\t\tparsedData[key] = fields[key].transform?.input(data[key]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tparsedData[key] = data[key];\n\t\t\tcontinue;\n\t\t}\n\t\tif (fields[key].defaultValue !== void 0 && action === \"create\") {\n\t\t\tif (typeof fields[key].defaultValue === \"function\") {\n\t\t\t\tparsedData[key] = fields[key].defaultValue();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tparsedData[key] = fields[key].defaultValue;\n\t\t\tcontinue;\n\t\t}\n\t\tif (fields[key].required && action === \"create\") throw APIError.from(\"BAD_REQUEST\", {\n\t\t\t...BASE_ERROR_CODES.MISSING_FIELD,\n\t\t\tmessage: `${key} is required`\n\t\t});\n\t}\n\treturn parsedData;\n}\nfunction parseUserInput(options, user = {}, action) {\n\treturn parseInputData(user, {\n\t\tfields: getFields(options, \"user\", \"input\"),\n\t\taction\n\t});\n}\nfunction parseAdditionalUserInputFromProviderProfile(options, profile = {}, action) {\n\tconst schema = getFields(options, \"user\", \"input\");\n\tconst allowedProfileFields = Object.create(null);\n\tfor (const key of Object.keys(profile)) {\n\t\tif (schema[key]?.input === false) continue;\n\t\tallowedProfileFields[key] = profile[key];\n\t}\n\treturn parseInputData(allowedProfileFields, {\n\t\tfields: schema,\n\t\taction\n\t});\n}\nfunction parseAdditionalUserInput(options, user) {\n\tconst schema = getFields(options, \"user\", \"input\");\n\treturn parseInputData(user || {}, { fields: schema });\n}\nfunction parseAccountInput(options, account) {\n\treturn parseInputData(account, { fields: getFields(options, \"account\", \"input\") });\n}\nfunction parseSessionInput(options, session, action) {\n\treturn parseInputData(session, {\n\t\tfields: getFields(options, \"session\", \"input\"),\n\t\taction\n\t});\n}\nfunction getSessionDefaultFields(options) {\n\tconst fields = getFields(options, \"session\", \"input\");\n\tconst defaults = {};\n\tfor (const key in fields) if (fields[key].defaultValue !== void 0) defaults[key] = typeof fields[key].defaultValue === \"function\" ? fields[key].defaultValue() : fields[key].defaultValue;\n\treturn defaults;\n}\nfunction mergeSchema(schema, newSchema) {\n\tif (!newSchema) return schema;\n\tfor (const table in newSchema) {\n\t\tconst newModelName = newSchema[table]?.modelName;\n\t\tif (newModelName) schema[table].modelName = newModelName;\n\t\tfor (const field in schema[table].fields) {\n\t\t\tconst newField = newSchema[table]?.fields?.[field];\n\t\t\tif (!newField) continue;\n\t\t\tschema[table].fields[field].fieldName = newField;\n\t\t}\n\t}\n\treturn schema;\n}\n//#endregion\nexport { buildSyntheticUserOutput, getSessionDefaultFields, mergeSchema, parseAccountInput, parseAccountOutput, parseAdditionalUserInput, parseAdditionalUserInputFromProviderProfile, parseInputData, parseSessionInput, parseSessionOutput, parseUserInput, parseUserOutput };\n","//#region src/utils/date.ts\nconst getDate = (span, unit = \"ms\") => {\n\treturn new Date(Date.now() + (unit === \"sec\" ? span * 1e3 : span));\n};\n//#endregion\nexport { getDate };\n","//#region src/cookies/cookie-utils.ts\nfunction tryDecode(str) {\n\tif (str.indexOf(\"%\") === -1) return str;\n\ttry {\n\t\treturn decodeURIComponent(str);\n\t} catch {\n\t\treturn str;\n\t}\n}\nconst SECURE_COOKIE_PREFIX = \"__Secure-\";\nconst HOST_COOKIE_PREFIX = \"__Host-\";\n/**\n* Remove __Secure- or __Host- prefix from cookie name.\n*/\nfunction stripSecureCookiePrefix(cookieName) {\n\tif (cookieName.startsWith(\"__Secure-\")) return cookieName.slice(9);\n\tif (cookieName.startsWith(\"__Host-\")) return cookieName.slice(7);\n\treturn cookieName;\n}\n/**\n* Split a comma-joined `Set-Cookie` header string into individual cookies.\n*/\nfunction splitSetCookieHeader(setCookie) {\n\tif (!setCookie) return [];\n\tconst result = [];\n\tlet start = 0;\n\tlet i = 0;\n\twhile (i < setCookie.length) {\n\t\tif (setCookie[i] === \",\") {\n\t\t\tlet j = i + 1;\n\t\t\twhile (j < setCookie.length && setCookie[j] === \" \") j++;\n\t\t\twhile (j < setCookie.length && setCookie[j] !== \"=\" && setCookie[j] !== \";\" && setCookie[j] !== \",\") j++;\n\t\t\tif (j < setCookie.length && setCookie[j] === \"=\") {\n\t\t\t\tconst part = setCookie.slice(start, i).trim();\n\t\t\t\tif (part) result.push(part);\n\t\t\t\tstart = i + 1;\n\t\t\t\twhile (start < setCookie.length && setCookie[start] === \" \") start++;\n\t\t\t\ti = start;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n\tconst last = setCookie.slice(start).trim();\n\tif (last) result.push(last);\n\treturn result;\n}\nfunction parseSetCookieHeader(setCookie) {\n\tconst cookies = /* @__PURE__ */ new Map();\n\tsplitSetCookieHeader(setCookie).forEach((cookieString) => {\n\t\tconst [nameValue, ...attributes] = cookieString.split(\";\").map((part) => part.trim());\n\t\tconst [name, ...valueParts] = (nameValue || \"\").split(\"=\");\n\t\tconst value = unquoteCookieValue(valueParts.join(\"=\"));\n\t\tif (!name) return;\n\t\tconst attrObj = { value: tryDecode(value) };\n\t\tattributes.forEach((attribute) => {\n\t\t\tconst [attrName, ...attrValueParts] = attribute.split(\"=\");\n\t\t\tconst attrValue = attrValueParts.join(\"=\");\n\t\t\tconst normalizedAttrName = attrName.trim().toLowerCase();\n\t\t\tswitch (normalizedAttrName) {\n\t\t\t\tcase \"max-age\":\n\t\t\t\t\tattrObj[\"max-age\"] = attrValue ? parseInt(attrValue.trim(), 10) : void 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"expires\":\n\t\t\t\t\tattrObj.expires = attrValue ? new Date(attrValue.trim()) : void 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"domain\":\n\t\t\t\t\tattrObj.domain = attrValue ? attrValue.trim() : void 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"path\":\n\t\t\t\t\tattrObj.path = attrValue ? attrValue.trim() : void 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"secure\":\n\t\t\t\t\tattrObj.secure = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"httponly\":\n\t\t\t\t\tattrObj.httponly = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"samesite\":\n\t\t\t\t\tattrObj.samesite = attrValue ? attrValue.trim().toLowerCase() : void 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"partitioned\":\n\t\t\t\t\tattrObj.partitioned = true;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tattrObj[normalizedAttrName] = attrValue ? attrValue.trim() : true;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t\tcookies.set(name, attrObj);\n\t});\n\treturn cookies;\n}\nfunction toCookieOptions(attributes) {\n\treturn {\n\t\tmaxAge: attributes[\"max-age\"],\n\t\texpires: attributes.expires,\n\t\tdomain: attributes.domain,\n\t\tpath: attributes.path,\n\t\tsecure: attributes.secure,\n\t\thttpOnly: attributes.httponly,\n\t\tsameSite: attributes.samesite,\n\t\tpartitioned: attributes.partitioned\n\t};\n}\n/**\n* Cookie-name token char set per RFC 7230 §3.2.6.\n*\n* @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.6\n*/\nconst cookieNameRegex = /^[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2E\\x30-\\x39\\x41-\\x5A\\x5E\\x5F\\x60\\x61-\\x7A\\x7C\\x7E]+$/;\n/**\n* Cookie-value char set per RFC 6265 §4.1.1, plus space and comma.\n*\n* @see https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1\n* @see https://github.com/golang/go/issues/7243\n*/\nconst cookieValueRegex = /^[\\x20\\x21\\x23-\\x3A\\x3C-\\x5B\\x5D-\\x7E]*$/;\n/**\n* Strip surrounding double-quotes per RFC 6265 §4.1.1 quoted-string form.\n*\n* @see https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1\n*/\nfunction unquoteCookieValue(value) {\n\tif (value.length < 2 || !value.startsWith(\"\\\"\") || !value.endsWith(\"\\\"\")) return value;\n\treturn value.slice(1, -1);\n}\n/**\n* Trim leading/trailing OWS (space / horizontal tab) per RFC 7230 §3.2.3.\n* Narrower than `String.prototype.trim()`, which strips CR/LF and other\n* whitespace and would let CTLs escape `cookieValueRegex`.\n*\n* @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.3\n*/\nfunction trimOWS(s) {\n\tlet start = 0;\n\tlet end = s.length;\n\twhile (start < end) {\n\t\tconst c = s.charCodeAt(start);\n\t\tif (c !== 32 && c !== 9) break;\n\t\tstart++;\n\t}\n\twhile (end > start) {\n\t\tconst c = s.charCodeAt(end - 1);\n\t\tif (c !== 32 && c !== 9) break;\n\t\tend--;\n\t}\n\treturn start === 0 && end === s.length ? s : s.slice(start, end);\n}\n/**\n* Tolerates `;` separators without the SP that RFC 6265 §4.2.1 mandates,\n* since proxies and runtimes commonly strip it. Silently drops entries\n* whose name violates RFC 7230 token or whose value violates RFC 6265\n* cookie-octet (plus space and comma). Strips optional surrounding\n* double-quotes per RFC 6265 §4.1.1.\n*/\nfunction parseCookies(cookie) {\n\tconst cookieMap = /* @__PURE__ */ new Map();\n\tif (cookie.length < 2) return cookieMap;\n\tfor (const chunk of cookie.split(\";\")) {\n\t\tconst eq = chunk.indexOf(\"=\");\n\t\tif (eq === -1) continue;\n\t\tconst key = trimOWS(chunk.slice(0, eq));\n\t\tconst val = unquoteCookieValue(trimOWS(chunk.slice(eq + 1)));\n\t\tif (cookieNameRegex.test(key) && cookieValueRegex.test(val)) cookieMap.set(key, tryDecode(val));\n\t}\n\treturn cookieMap;\n}\n/**\n* Add or replace a cookie in the request `Cookie` header.\n*\n* Cookie pairs are joined with `; `, but `headers.append(\"cookie\", ...)`\n* joins with `, ` in some runtimes (e.g. Deno, Cloudflare Workers) and\n* breaks downstream cookie parsing. This builds the header value via\n* parse-mutate-serialize.\n*/\nfunction setRequestCookie(headers, name, value) {\n\tconst cookieMap = parseCookies(headers.get(\"cookie\") || \"\");\n\tif (cookieNameRegex.test(name)) cookieMap.set(name, value);\n\theaders.set(\"cookie\", Array.from(cookieMap, ([k, v]) => `${k}=${encodeURIComponent(v)}`).join(\"; \"));\n}\n/**\n* Merge `Set-Cookie` header values into the target's `Cookie` header.\n* Mutates `target`.\n*\n* Name/value-level merge only. RFC 6265 §5 user-agent semantics\n* (expiration, domain/path scoping, ordering) are out of scope. Suitable\n* for single-request proxy, middleware, and test contexts.\n*/\nfunction applySetCookies(target, setCookieValues) {\n\tconst cookieMap = parseCookies(target.get(\"cookie\") || \"\");\n\tfor (const setCookie of setCookieValues) for (const [name, attr] of parseSetCookieHeader(setCookie)) if (cookieNameRegex.test(name)) cookieMap.set(name, attr.value);\n\ttarget.set(\"cookie\", Array.from(cookieMap, ([k, v]) => `${k}=${encodeURIComponent(v)}`).join(\"; \"));\n}\nfunction setCookieToHeader(headers) {\n\treturn (context) => {\n\t\tconst setCookieHeader = context.response.headers.get(\"set-cookie\");\n\t\tif (!setCookieHeader) return;\n\t\tapplySetCookies(headers, [setCookieHeader]);\n\t};\n}\n//#endregion\nexport { HOST_COOKIE_PREFIX, SECURE_COOKIE_PREFIX, applySetCookies, cookieNameRegex, parseCookies, parseSetCookieHeader, setCookieToHeader, setRequestCookie, splitSetCookieHeader, stripSecureCookiePrefix, toCookieOptions };\n","import { symmetricDecodeJWT, symmetricEncodeJWT } from \"../crypto/jwt.mjs\";\nimport { parseCookies } from \"./cookie-utils.mjs\";\nimport { safeJSONParse } from \"@better-auth/core/utils/json\";\nimport { serializeCookie } from \"better-call\";\nimport * as z from \"zod\";\n//#region src/cookies/session-store.ts\n/**\n* Per-cookie byte ceiling.\n* Safari's ~4093 floor is the lowest among browsers.\n* Kept a little under it for attributes added after sizing.\n*\n* @see https://datatracker.ietf.org/doc/html/rfc6265#section-6.1\n* @see https://github.com/dotnet/aspnetcore/blob/aa5493528640932601bb82ef3295e4d8ca7e11c5/src/Shared/ChunkingCookieManager/ChunkingCookieManager.cs#L40\n*/\nconst MAX_COOKIE_SIZE = 4050;\n/**\n* Max chunks per cookie.\n* A larger value does not belong in a cookie.\n*/\nconst MAX_COOKIE_CHUNKS = 100;\n/**\n* Largest value that keeps the serialized cookie within {@link MAX_COOKIE_SIZE},\n* measured with the real `serializeCookie` writer so it stays in sync with the\n* wire. Non-positive when the name and attributes alone overflow.\n*/\nfunction getMaxCookieValueSize(name, options) {\n\treturn MAX_COOKIE_SIZE - serializeCookie(name, \"\", { ...options }).length;\n}\nfunction parseCookieChunkIndex(cookieName, name) {\n\tconst prefix = `${cookieName}.`;\n\tif (!name.startsWith(prefix)) return null;\n\tconst suffix = name.slice(prefix.length);\n\tconst index = Number(suffix);\n\tif (!Number.isSafeInteger(index) || index < 0 || String(index) !== suffix) return null;\n\treturn index;\n}\n/**\n* Read all existing chunks from cookies\n*/\nfunction readExistingChunks(cookieName, ctx) {\n\tconst chunks = {};\n\tconst cookies = parseCookies(ctx.headers?.get(\"cookie\") || \"\");\n\tfor (const [name, value] of cookies) {\n\t\tif (name !== cookieName && parseCookieChunkIndex(cookieName, name) === null) continue;\n\t\tchunks[name] = value;\n\t}\n\treturn chunks;\n}\n/**\n* Split a cookie value into chunks if needed\n*/\nfunction chunkCookie(storeName, cookie, chunks, logger) {\n\tconst chunkSize = getMaxCookieValueSize(`${cookie.name}.${MAX_COOKIE_CHUNKS - 1}`, cookie.attributes);\n\tconst chunkCount = chunkSize > 0 ? Math.ceil(cookie.value.length / chunkSize) : Infinity;\n\tif (chunkCount <= 1) {\n\t\tchunks[cookie.name] = cookie.value;\n\t\treturn [cookie];\n\t}\n\tif (chunkCount > MAX_COOKIE_CHUNKS) {\n\t\tlogger.warn(`${storeName} 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.`);\n\t\treturn [];\n\t}\n\tconst cookies = [];\n\tfor (let i = 0; i < chunkCount; i++) {\n\t\tconst name = `${cookie.name}.${i}`;\n\t\tconst start = i * chunkSize;\n\t\tconst value = cookie.value.substring(start, start + chunkSize);\n\t\tcookies.push({\n\t\t\t...cookie,\n\t\t\tname,\n\t\t\tvalue\n\t\t});\n\t\tchunks[name] = value;\n\t}\n\tlogger.debug(`CHUNKING_${storeName.toUpperCase()}_COOKIE`, {\n\t\tmessage: `${storeName} cookie exceeds the ${MAX_COOKIE_SIZE} byte limit and was split into ${chunkCount} chunks.`,\n\t\tvalueSize: cookie.value.length,\n\t\tchunkCount,\n\t\tchunkSizes: cookies.map((c) => c.value.length)\n\t});\n\treturn cookies;\n}\n/**\n* Get all cookies that should be cleaned (removed)\n*/\nfunction getCleanCookies(chunks, cookieOptions) {\n\tconst cleanedChunks = {};\n\tfor (const name in chunks) cleanedChunks[name] = {\n\t\tname,\n\t\tvalue: \"\",\n\t\tattributes: {\n\t\t\t...cookieOptions,\n\t\t\tmaxAge: 0\n\t\t}\n\t};\n\treturn cleanedChunks;\n}\n/**\n* Store that splits a cookie into numbered chunks when its serialized form\n* would exceed the per-cookie byte limit, expiring stale chunks as needed.\n*\n* @see https://github.com/nextauthjs/next-auth/blob/27b2519b84b8eb9cf053775dea29d577d2aa0098/packages/next-auth/src/core/lib/cookie.ts\n*/\nconst storeFactory = (storeName) => (cookieName, cookieOptions, ctx) => {\n\tconst chunks = readExistingChunks(cookieName, ctx);\n\tconst logger = ctx.context.logger;\n\tconst expireExistingChunks = () => {\n\t\tconst expired = getCleanCookies(chunks, cookieOptions);\n\t\tfor (const name in chunks) delete chunks[name];\n\t\treturn expired;\n\t};\n\treturn {\n\t\tchunk(value, options) {\n\t\t\tconst cookies = expireExistingChunks();\n\t\t\tconst chunked = chunkCookie(storeName, {\n\t\t\t\tname: cookieName,\n\t\t\t\tvalue,\n\t\t\t\tattributes: {\n\t\t\t\t\t...cookieOptions,\n\t\t\t\t\t...options\n\t\t\t\t}\n\t\t\t}, chunks, logger);\n\t\t\tfor (const chunk of chunked) cookies[chunk.name] = chunk;\n\t\t\treturn Object.values(cookies);\n\t\t},\n\t\tclean() {\n\t\t\treturn Object.values(expireExistingChunks());\n\t\t},\n\t\tsetCookies(cookies) {\n\t\t\tfor (const cookie of cookies) ctx.setCookie(cookie.name, cookie.value, cookie.attributes);\n\t\t}\n\t};\n};\nconst createSessionStore = storeFactory(\"Session\");\nconst createAccountStore = storeFactory(\"Account\");\nfunction getChunkedCookie(ctx, cookieName) {\n\tconst value = ctx.getCookie(cookieName);\n\tif (value) return value;\n\tconst chunks = [];\n\tconst cookieHeader = ctx.headers?.get(\"cookie\");\n\tif (!cookieHeader) return null;\n\tfor (const [name, val] of parseCookies(cookieHeader)) {\n\t\tconst index = parseCookieChunkIndex(cookieName, name);\n\t\tif (index === null) continue;\n\t\tchunks.push({\n\t\t\tindex,\n\t\t\tvalue: val\n\t\t});\n\t}\n\tif (chunks.length > 0) {\n\t\tchunks.sort((a, b) => a.index - b.index);\n\t\treturn chunks.map((c) => c.value).join(\"\");\n\t}\n\treturn null;\n}\nasync function setAccountCookie(c, accountData) {\n\tconst accountDataCookie = c.context.authCookies.accountData;\n\tconst options = {\n\t\tmaxAge: 300,\n\t\t...accountDataCookie.attributes\n\t};\n\tconst data = await symmetricEncodeJWT(accountData, c.context.secretConfig, \"better-auth-account\", options.maxAge);\n\tconst accountStore = createAccountStore(accountDataCookie.name, options, c);\n\taccountStore.setCookies(accountStore.chunk(data, options));\n}\nasync function getAccountCookie(c) {\n\tconst accountCookie = getChunkedCookie(c, c.context.authCookies.accountData.name);\n\tif (accountCookie) {\n\t\tconst accountData = safeJSONParse(await symmetricDecodeJWT(accountCookie, c.context.secretConfig, \"better-auth-account\"));\n\t\tif (accountData) return accountData;\n\t}\n\treturn null;\n}\nconst getSessionQuerySchema = z.optional(z.object({\n\t/**\n\t* If cookie cache is enabled, it will disable the cache\n\t* and fetch the session from the database\n\t*/\n\tdisableCookieCache: z.coerce.boolean().meta({ description: \"Disable cookie cache and fetch session from database\" }).optional(),\n\tdisableRefresh: z.coerce.boolean().meta({ description: \"Disable session refresh. Useful for checking session status, without updating the session\" }).optional()\n}));\n//#endregion\nexport { createAccountStore, createSessionStore, getAccountCookie, getChunkedCookie, getSessionQuerySchema, setAccountCookie };\n","//#region src/utils/is-promise.ts\nfunction isPromise(obj) {\n\treturn !!obj && (typeof obj === \"object\" || typeof obj === \"function\") && typeof obj.then === \"function\";\n}\n//#endregion\nexport { isPromise };\n","//#region src/utils/time.ts\nconst SEC = 1e3;\nconst MIN = SEC * 60;\nconst HOUR = MIN * 60;\nconst DAY = HOUR * 24;\nconst WEEK = DAY * 7;\nconst MONTH = DAY * 30;\nconst YEAR = DAY * 365.25;\nconst REGEX = /^(\\+|\\-)? ?(\\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;\nfunction parse(value) {\n\tconst match = REGEX.exec(value);\n\tif (!match || match[4] && match[1]) throw new TypeError(`Invalid time string format: \"${value}\". Use formats like \"7d\", \"30m\", \"1 hour\", etc.`);\n\tconst n = parseFloat(match[2]);\n\tconst unit = match[3].toLowerCase();\n\tlet result;\n\tswitch (unit) {\n\t\tcase \"years\":\n\t\tcase \"year\":\n\t\tcase \"yrs\":\n\t\tcase \"yr\":\n\t\tcase \"y\":\n\t\t\tresult = n * YEAR;\n\t\t\tbreak;\n\t\tcase \"months\":\n\t\tcase \"month\":\n\t\tcase \"mo\":\n\t\t\tresult = n * MONTH;\n\t\t\tbreak;\n\t\tcase \"weeks\":\n\t\tcase \"week\":\n\t\tcase \"w\":\n\t\t\tresult = n * WEEK;\n\t\t\tbreak;\n\t\tcase \"days\":\n\t\tcase \"day\":\n\t\tcase \"d\":\n\t\t\tresult = n * DAY;\n\t\t\tbreak;\n\t\tcase \"hours\":\n\t\tcase \"hour\":\n\t\tcase \"hrs\":\n\t\tcase \"hr\":\n\t\tcase \"h\":\n\t\t\tresult = n * HOUR;\n\t\t\tbreak;\n\t\tcase \"minutes\":\n\t\tcase \"minute\":\n\t\tcase \"mins\":\n\t\tcase \"min\":\n\t\tcase \"m\":\n\t\t\tresult = n * MIN;\n\t\t\tbreak;\n\t\tcase \"seconds\":\n\t\tcase \"second\":\n\t\tcase \"secs\":\n\t\tcase \"sec\":\n\t\tcase \"s\":\n\t\t\tresult = n * SEC;\n\t\t\tbreak;\n\t\tdefault: throw new TypeError(`Unknown time unit: \"${unit}\"`);\n\t}\n\tif (match[1] === \"-\" || match[4] === \"ago\") return -result;\n\treturn result;\n}\n/**\n* Parse a time string and return the value in milliseconds.\n*\n* @param value - A time string like \"7d\", \"30m\", \"1 hour\", \"2 hours ago\"\n* @returns The parsed value in milliseconds\n* @throws TypeError if the string format is invalid\n*\n* @example\n* ms(\"1d\") // 86400000\n* ms(\"2 hours\") // 7200000\n* ms(\"30s\") // 30000\n* ms(\"2 hours ago\") // -7200000\n*/\nfunction ms(value) {\n\treturn parse(value);\n}\n/**\n* Parse a time string and return the value in seconds.\n*\n* @param value - A time string like \"7d\", \"30m\", \"1 hour\", \"2 hours ago\"\n* @returns The parsed value in seconds (rounded)\n* @throws TypeError if the string format is invalid\n*\n* @example\n* sec(\"1d\") // 86400\n* sec(\"2 hours\") // 7200\n* sec(\"-30s\") // -30\n* sec(\"2 hours ago\") // -7200\n*/\nfunction sec(value) {\n\treturn Math.round(parse(value) / 1e3);\n}\n//#endregion\nexport { ms, sec };\n","import { sessionSchema, userSchema } from \"@better-auth/core/db\";\nimport { logger } from \"@better-auth/core/env\";\nimport { safeJSONParse } from \"@better-auth/core/utils/json\";\nimport * as z from \"zod\";\n//#region src/cookies/cache.ts\nconst cookieCachePayloadSchema = z.looseObject({\n\tsession: sessionSchema.loose(),\n\tuser: userSchema.loose(),\n\tupdatedAt: z.number(),\n\tversion: z.string().optional()\n});\nconst compactCookieCacheSchema = z.object({\n\tsession: z.record(z.string(), z.unknown()),\n\texpiresAt: z.number(),\n\tsignature: z.string()\n});\nfunction parseCookieCachePayload(value) {\n\tconst parsed = safeJSONParse(value);\n\tif (parsed === null) return null;\n\tconst result = cookieCachePayloadSchema.safeParse(parsed);\n\tif (result.success) return result.data;\n\tlogger.warn(\"Cookie cache payload failed schema validation\", { issues: result.error.issues.map(({ code, path }) => ({\n\t\tcode,\n\t\tpath\n\t})) });\n\treturn null;\n}\nfunction parseCompactCookieCache(value) {\n\tconst result = compactCookieCacheSchema.safeParse(value);\n\treturn result.success ? result.data : null;\n}\n//#endregion\nexport { parseCompactCookieCache, parseCookieCachePayload };\n","//#region src/binary.ts\nconst decoders = /* @__PURE__ */ new Map();\nconst encoder = new TextEncoder();\nconst binary = {\n\tdecode: (data, encoding = \"utf-8\") => {\n\t\tif (!decoders.has(encoding)) decoders.set(encoding, new TextDecoder(encoding));\n\t\treturn decoders.get(encoding).decode(data);\n\t},\n\tencode: (input) => encoder.encode(input)\n};\n//#endregion\nexport { binary };\n","import { getWebcryptoSubtle } from \"./index.mjs\";\nimport { toBufferSource } from \"./bytes.mjs\";\nimport { base64, base64Url } from \"./base64.mjs\";\nimport { hex } from \"./hex.mjs\";\n//#region src/hmac.ts\nconst createHMAC = (algorithm = \"SHA-256\", encoding = \"none\") => {\n\tconst hmac = {\n\t\timportKey: async (key, keyUsage) => {\n\t\t\treturn getWebcryptoSubtle().importKey(\"raw\", toBufferSource(key), {\n\t\t\t\tname: \"HMAC\",\n\t\t\t\thash: { name: algorithm }\n\t\t\t}, false, [keyUsage]);\n\t\t},\n\t\tsign: async (hmacKey, data) => {\n\t\t\tif (typeof hmacKey === \"string\") hmacKey = await hmac.importKey(hmacKey, \"sign\");\n\t\t\tconst signature = await getWebcryptoSubtle().sign(\"HMAC\", hmacKey, toBufferSource(data));\n\t\t\tif (encoding === \"hex\") return hex.encode(signature);\n\t\t\tif (encoding === \"base64\") return base64.encode(signature);\n\t\t\tif (encoding === \"base64url\" || encoding === \"base64urlnopad\") return base64Url.encode(signature, { padding: encoding !== \"base64urlnopad\" });\n\t\t\treturn signature;\n\t\t},\n\t\tverify: async (hmacKey, data, signature) => {\n\t\t\tif (typeof hmacKey === \"string\") hmacKey = await hmac.importKey(hmacKey, \"verify\");\n\t\t\tif (encoding === \"hex\") signature = typeof signature === \"string\" ? hex.toBytes(signature) : signature;\n\t\t\tif (encoding === \"base64\" || encoding === \"base64url\" || encoding === \"base64urlnopad\") signature = await base64.decode(signature);\n\t\t\treturn getWebcryptoSubtle().verify(\"HMAC\", hmacKey, toBufferSource(signature), toBufferSource(data));\n\t\t}\n\t};\n\treturn hmac;\n};\n//#endregion\nexport { createHMAC };\n","import { isDynamicBaseURLConfig } from \"../utils/url.mjs\";\nimport { shouldBindAccountCookieToSessionUser } from \"../context/store-capabilities.mjs\";\nimport { signJWT, symmetricDecodeJWT, symmetricEncodeJWT, verifyJWT } from \"../crypto/jwt.mjs\";\nimport { parseUserOutput } from \"../db/schema.mjs\";\nimport { getDate } from \"../utils/date.mjs\";\nimport { isPromise } from \"../utils/is-promise.mjs\";\nimport { sec } from \"../utils/time.mjs\";\nimport { parseCompactCookieCache, parseCookieCachePayload } from \"./cache.mjs\";\nimport { HOST_COOKIE_PREFIX, SECURE_COOKIE_PREFIX, applySetCookies, cookieNameRegex, parseCookies, parseSetCookieHeader, setCookieToHeader, setRequestCookie, splitSetCookieHeader, stripSecureCookiePrefix, toCookieOptions } from \"./cookie-utils.mjs\";\nimport { verifySessionCookieJwtWithJwks } from \"./jwt.mjs\";\nimport { createAccountStore, createSessionStore, getAccountCookie, getChunkedCookie, setAccountCookie } from \"./session-store.mjs\";\nimport { env, isProduction } from \"@better-auth/core/env\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\nimport { safeJSONParse } from \"@better-auth/core/utils/json\";\nimport { filterOutputFields } from \"@better-auth/core/utils/db\";\nimport { base64Url } from \"@better-auth/utils/base64\";\nimport { binary } from \"@better-auth/utils/binary\";\nimport { createHMAC } from \"@better-auth/utils/hmac\";\n//#region src/cookies/index.ts\nfunction createCookieGetter(options) {\n\tconst baseURLString = typeof options.baseURL === \"string\" ? options.baseURL : void 0;\n\tconst dynamicProtocol = typeof options.baseURL === \"object\" && options.baseURL !== null ? options.baseURL.protocol : void 0;\n\tconst secureCookiePrefix = (options.advanced?.useSecureCookies !== void 0 ? options.advanced?.useSecureCookies : dynamicProtocol === \"https\" ? true : dynamicProtocol === \"http\" ? false : baseURLString ? baseURLString.startsWith(\"https://\") : isProduction) ? SECURE_COOKIE_PREFIX : \"\";\n\tconst crossSubdomainEnabled = !!options.advanced?.crossSubDomainCookies?.enabled;\n\tconst domain = crossSubdomainEnabled ? options.advanced?.crossSubDomainCookies?.domain || (baseURLString ? new URL(baseURLString).hostname : void 0) : void 0;\n\tif (crossSubdomainEnabled && !domain && !isDynamicBaseURLConfig(options.baseURL)) throw new BetterAuthError(\"baseURL is required when crossSubdomainCookies are enabled.\");\n\tfunction createCookie(cookieName, overrideAttributes = {}) {\n\t\tconst prefix = options.advanced?.cookiePrefix || \"better-auth\";\n\t\tconst name = options.advanced?.cookies?.[cookieName]?.name || `${prefix}.${cookieName}`;\n\t\tconst attributes = options.advanced?.cookies?.[cookieName]?.attributes ?? {};\n\t\treturn {\n\t\t\tname: `${secureCookiePrefix}${name}`,\n\t\t\tattributes: {\n\t\t\t\tsecure: !!secureCookiePrefix,\n\t\t\t\tsameSite: \"lax\",\n\t\t\t\tpath: \"/\",\n\t\t\t\thttpOnly: true,\n\t\t\t\t...crossSubdomainEnabled ? { domain } : {},\n\t\t\t\t...options.advanced?.defaultCookieAttributes,\n\t\t\t\t...overrideAttributes,\n\t\t\t\t...attributes\n\t\t\t}\n\t\t};\n\t}\n\treturn createCookie;\n}\nfunction getCookies(options) {\n\tconst createCookie = createCookieGetter(options);\n\tconst sessionToken = createCookie(\"session_token\", { maxAge: options.session?.expiresIn || sec(\"7d\") });\n\tconst sessionData = createCookie(\"session_data\", { maxAge: options.session?.cookieCache?.maxAge || 300 });\n\tconst accountData = createCookie(\"account_data\", { maxAge: options.session?.cookieCache?.maxAge || 300 });\n\tconst dontRememberToken = createCookie(\"dont_remember\");\n\treturn {\n\t\tsessionToken: {\n\t\t\tname: sessionToken.name,\n\t\t\tattributes: sessionToken.attributes\n\t\t},\n\t\t/**\n\t\t* This cookie is used to store the session data in the cookie\n\t\t* This is useful for when you want to cache the session in the cookie\n\t\t*/\n\t\tsessionData: {\n\t\t\tname: sessionData.name,\n\t\t\tattributes: sessionData.attributes\n\t\t},\n\t\tdontRememberToken: {\n\t\t\tname: dontRememberToken.name,\n\t\t\tattributes: dontRememberToken.attributes\n\t\t},\n\t\taccountData: {\n\t\t\tname: accountData.name,\n\t\t\tattributes: accountData.attributes\n\t\t}\n\t};\n}\nasync function setCookieCache(ctx, session, dontRememberMe) {\n\tif (!ctx.context.options.session?.cookieCache?.enabled) return;\n\tconst filteredSession = filterOutputFields(session.session, ctx.context.options.session?.additionalFields);\n\tconst filteredUser = parseUserOutput(ctx.context.options, session.user);\n\tconst versionConfig = ctx.context.options.session?.cookieCache?.version;\n\tlet version = \"1\";\n\tif (versionConfig) {\n\t\tif (typeof versionConfig === \"string\") version = versionConfig;\n\t\telse if (typeof versionConfig === \"function\") {\n\t\t\tconst result = versionConfig(session.session, session.user);\n\t\t\tversion = isPromise(result) ? await result : result;\n\t\t}\n\t}\n\tconst sessionData = {\n\t\tsession: filteredSession,\n\t\tuser: filteredUser,\n\t\tupdatedAt: Date.now(),\n\t\tversion\n\t};\n\tconst options = {\n\t\t...ctx.context.authCookies.sessionData.attributes,\n\t\tmaxAge: dontRememberMe ? void 0 : ctx.context.authCookies.sessionData.attributes.maxAge\n\t};\n\tconst expiresAtDate = getDate(options.maxAge || 60, \"sec\").getTime();\n\tconst strategy = ctx.context.options.session?.cookieCache?.strategy || \"compact\";\n\tlet data;\n\tif (strategy === \"jwe\") data = await symmetricEncodeJWT(sessionData, ctx.context.secretConfig, \"better-auth-session\", options.maxAge || 300);\n\telse if (strategy === \"jwt\") {\n\t\tconst cookieCacheSigner = ctx.context.sessionConfig.cookieCacheSigner;\n\t\tdata = cookieCacheSigner ? await cookieCacheSigner.sign(ctx, sessionData, options.maxAge || 300) : await signJWT(sessionData, ctx.context.secret, options.maxAge || 300);\n\t} else data = base64Url.encode(JSON.stringify({\n\t\tsession: sessionData,\n\t\texpiresAt: expiresAtDate,\n\t\tsignature: await createHMAC(\"SHA-256\", \"base64urlnopad\").sign(ctx.context.secret, JSON.stringify({\n\t\t\t...sessionData,\n\t\t\texpiresAt: expiresAtDate\n\t\t}))\n\t}), { padding: false });\n\tconst sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, options, ctx);\n\tsessionStore.setCookies(sessionStore.chunk(data, options));\n\tif (ctx.context.options.account?.storeAccountCookie && !hasPendingSetCookie(ctx, ctx.context.authCookies.accountData.name)) {\n\t\tconst accountData = await getAccountCookie(ctx);\n\t\tif (accountData) if (!shouldBindAccountCookieToSessionUser(ctx.context.options) || accountData.userId === session.user.id) await setAccountCookie(ctx, accountData);\n\t\telse {\n\t\t\texpireCookie(ctx, ctx.context.authCookies.accountData);\n\t\t\tconst accountStore = createAccountStore(ctx.context.authCookies.accountData.name, ctx.context.authCookies.accountData.attributes, ctx);\n\t\t\taccountStore.setCookies(accountStore.clean());\n\t\t}\n\t}\n}\nasync function decodeCookieCache(ctx, value) {\n\tconst strategy = ctx.context.options.session?.cookieCache?.strategy || \"compact\";\n\tif (strategy === \"jwe\") {\n\t\tconst decoded = await symmetricDecodeJWT(value, ctx.context.secretConfig, \"better-auth-session\");\n\t\tconst payload = parseCookieCachePayload(decoded);\n\t\tif (!payload) return null;\n\t\treturn {\n\t\t\tsession: payload,\n\t\t\texpiresAt: decoded?.exp ? decoded.exp * 1e3 : Date.now()\n\t\t};\n\t}\n\tif (strategy === \"jwt\") {\n\t\tconst cookieCacheSigner = ctx.context.sessionConfig.cookieCacheSigner;\n\t\tif (cookieCacheSigner) {\n\t\t\tconst verified = await cookieCacheSigner.verify(ctx, value);\n\t\t\tif (!verified) return null;\n\t\t\treturn {\n\t\t\t\tsession: verified.payload,\n\t\t\t\texpiresAt: verified.expiresAt\n\t\t\t};\n\t\t}\n\t\tconst decoded = await verifyJWT(value, ctx.context.secret);\n\t\tconst payload = parseCookieCachePayload(decoded);\n\t\tif (!payload) return null;\n\t\treturn {\n\t\t\tsession: payload,\n\t\t\texpiresAt: decoded?.exp ? decoded.exp * 1e3 : Date.now()\n\t\t};\n\t}\n\tconst parsed = parseCompactCookieCache(safeJSONParse(binary.decode(base64Url.decode(value))));\n\tif (!parsed) return null;\n\tif (!await createHMAC(\"SHA-256\", \"base64urlnopad\").verify(ctx.context.secret, JSON.stringify({\n\t\t...parsed.session,\n\t\texpiresAt: parsed.expiresAt\n\t}), parsed.signature)) return null;\n\tconst payload = parseCookieCachePayload(parsed.session);\n\treturn payload ? {\n\t\tsession: payload,\n\t\texpiresAt: parsed.expiresAt\n\t} : null;\n}\nasync function setSessionCookie(ctx, session, dontRememberMe, overrides) {\n\tconst dontRememberMeCookie = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret);\n\tdontRememberMe = dontRememberMe !== void 0 ? dontRememberMe : !!dontRememberMeCookie;\n\tconst options = ctx.context.authCookies.sessionToken.attributes;\n\tconst maxAge = dontRememberMe ? void 0 : ctx.context.sessionConfig.expiresIn;\n\tawait ctx.setSignedCookie(ctx.context.authCookies.sessionToken.name, session.session.token, ctx.context.secret, {\n\t\t...options,\n\t\tmaxAge,\n\t\t...overrides\n\t});\n\tif (dontRememberMe) await ctx.setSignedCookie(ctx.context.authCookies.dontRememberToken.name, \"true\", ctx.context.secret, ctx.context.authCookies.dontRememberToken.attributes);\n\tawait setCookieCache(ctx, session, dontRememberMe);\n\tctx.context.setNewSession(session);\n}\n/**\n* Remove any prior `Set-Cookie` entries on the current response whose cookie\n* name matches `cookieName` or any chunked variant (`${cookieName}.0`, etc.).\n*\n* Prevents a valid cookie value from leaking on the wire when the same cookie\n* is set and then expired within a single request (e.g. `/sign-in/email`\n* writes credential session cookies and the 2FA after-hook expires them).\n* Browsers honor the expiring entry, but anything reading the raw response\n* headers — proxy/LB logs, server-side SDK consumers, observability tools —\n* sees the earlier valid value and could replay it (bypassing the 2FA gate\n* when the cookie cache is enabled).\n*\n* Scrubs both the local middleware scope's `responseHeaders` and the outer\n* endpoint scope's `ctx.context.responseHeaders`, because plugin after-hooks\n* run in a fresh local scope while accumulated response headers live on the\n* outer one. `scoped.context` is required by {@link GenericEndpointContext}\n* but unit-test mocks pass a minimal object via `as any`, so we use optional\n* chaining defensively. The `Set` collapses the case where both scopes\n* reference the same `Headers`.\n*/\nfunction removeSetCookieEntries(ctx, cookieName) {\n\tconst scoped = ctx;\n\tconst targets = /* @__PURE__ */ new Set();\n\tif (scoped.responseHeaders) targets.add(scoped.responseHeaders);\n\tif (scoped.context?.responseHeaders) targets.add(scoped.context.responseHeaders);\n\tconst exact = `${cookieName}=`;\n\tconst chunk = `${cookieName}.`;\n\tfor (const headers of targets) {\n\t\tconst existing = typeof headers.getSetCookie === \"function\" ? headers.getSetCookie() : splitSetCookieHeader(headers.get(\"set-cookie\") || \"\");\n\t\tif (!existing.length) continue;\n\t\tconst survivors = existing.filter((entry) => !entry.startsWith(exact) && !entry.startsWith(chunk));\n\t\tif (survivors.length === existing.length) continue;\n\t\theaders.delete(\"set-cookie\");\n\t\tfor (const entry of survivors) headers.append(\"set-cookie\", entry);\n\t}\n}\n/**\n* Whether the response already has a pending `Set-Cookie` for `cookieName`\n* or a chunked variant.\n*/\nfunction hasPendingSetCookie(ctx, cookieName) {\n\tconst scoped = ctx;\n\tconst targets = /* @__PURE__ */ new Set();\n\tif (scoped.responseHeaders) targets.add(scoped.responseHeaders);\n\tif (scoped.context?.responseHeaders) targets.add(scoped.context.responseHeaders);\n\tconst exact = `${cookieName}=`;\n\tconst chunk = `${cookieName}.`;\n\tfor (const headers of targets) if ((typeof headers.getSetCookie === \"function\" ? headers.getSetCookie() : splitSetCookieHeader(headers.get(\"set-cookie\") || \"\")).some((entry) => entry.startsWith(exact) || entry.startsWith(chunk))) return true;\n\treturn false;\n}\n/**\n* Expires a cookie by setting `maxAge: 0` while preserving its attributes\n*/\nfunction expireCookie(ctx, cookie) {\n\tremoveSetCookieEntries(ctx, cookie.name);\n\tctx.setCookie(cookie.name, \"\", {\n\t\t...cookie.attributes,\n\t\tmaxAge: 0\n\t});\n}\nfunction deleteSessionCookie(ctx, skipDontRememberMe) {\n\texpireCookie(ctx, ctx.context.authCookies.sessionToken);\n\texpireCookie(ctx, ctx.context.authCookies.sessionData);\n\tif (ctx.context.options.account?.storeAccountCookie) {\n\t\texpireCookie(ctx, ctx.context.authCookies.accountData);\n\t\tconst accountStore = createAccountStore(ctx.context.authCookies.accountData.name, ctx.context.authCookies.accountData.attributes, ctx);\n\t\tconst cleanCookies = accountStore.clean();\n\t\taccountStore.setCookies(cleanCookies);\n\t}\n\tif (ctx.context.oauthConfig.storeStateStrategy === \"cookie\") expireCookie(ctx, ctx.context.createAuthCookie(\"oauth_state\"));\n\tconst sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, ctx.context.authCookies.sessionData.attributes, ctx);\n\tconst cleanCookies = sessionStore.clean();\n\tsessionStore.setCookies(cleanCookies);\n\tif (!skipDontRememberMe) expireCookie(ctx, ctx.context.authCookies.dontRememberToken);\n}\nfunction isEmbeddedSessionExpired(session) {\n\tif (!session?.expiresAt) return false;\n\tconst expiresAt = new Date(session.expiresAt).getTime();\n\treturn Number.isFinite(expiresAt) && expiresAt < Date.now();\n}\nconst getSessionCookie = (request, config) => {\n\tconst cookies = (request instanceof Headers || !(\"headers\" in request) ? request : request.headers).get(\"cookie\");\n\tif (!cookies) return null;\n\tconst { cookieName = \"session_token\", cookiePrefix = \"better-auth\" } = config || {};\n\tconst parsedCookie = parseCookies(cookies);\n\tconst getCookie = (name) => parsedCookie.get(`__Secure-${name}`) ?? parsedCookie.get(name);\n\tconst sessionToken = getCookie(`${cookiePrefix}.${cookieName}`) || getCookie(`${cookiePrefix}-${cookieName}`);\n\tif (sessionToken) return sessionToken;\n\treturn null;\n};\nasync function matchesVersion(payload, version) {\n\tconst expectedVersion = typeof version === \"string\" ? version : await version(payload.session, payload.user);\n\treturn (payload.version || \"1\") === expectedVersion;\n}\nconst getCookieCache = async (request, config) => {\n\tconst cookies = (request instanceof Headers || !(\"headers\" in request) ? request : request.headers).get(\"cookie\");\n\tif (!cookies) return null;\n\tconst { cookieName = \"session_data\", cookiePrefix = \"better-auth\" } = config || {};\n\tconst name = config?.isSecure !== void 0 ? config.isSecure ? `${SECURE_COOKIE_PREFIX}${cookiePrefix}.${cookieName}` : `${cookiePrefix}.${cookieName}` : isProduction ? `${SECURE_COOKIE_PREFIX}${cookiePrefix}.${cookieName}` : `${cookiePrefix}.${cookieName}`;\n\tconst parsedCookie = parseCookies(cookies);\n\tlet sessionData = parsedCookie.get(name);\n\tif (!sessionData) {\n\t\tconst chunks = [];\n\t\tfor (const [cookieName, value] of parsedCookie.entries()) if (cookieName.startsWith(name + \".\")) {\n\t\t\tconst parts = cookieName.split(\".\");\n\t\t\tconst indexStr = parts[parts.length - 1];\n\t\t\tconst index = parseInt(indexStr || \"0\", 10);\n\t\t\tif (!isNaN(index)) chunks.push({\n\t\t\t\tindex,\n\t\t\t\tvalue\n\t\t\t});\n\t\t}\n\t\tif (chunks.length > 0) {\n\t\t\tchunks.sort((a, b) => a.index - b.index);\n\t\t\tsessionData = chunks.map((c) => c.value).join(\"\");\n\t\t}\n\t}\n\tif (sessionData) {\n\t\tconst strategy = config?.strategy || \"compact\";\n\t\tif (strategy === \"jwe\") {\n\t\t\tconst secret = config?.secret || env.BETTER_AUTH_SECRET;\n\t\t\tif (!secret) throw new BetterAuthError(\"getCookieCache requires a secret to be provided. Either pass it as an option or set the BETTER_AUTH_SECRET environment variable\");\n\t\t\tconst payload = parseCookieCachePayload(await symmetricDecodeJWT(sessionData, secret, \"better-auth-session\"));\n\t\t\tif (!payload) return null;\n\t\t\tif (config?.version) {\n\t\t\t\tif (!await matchesVersion(payload, config.version)) return null;\n\t\t\t}\n\t\t\tif (isEmbeddedSessionExpired(payload.session)) return null;\n\t\t\treturn payload;\n\t\t} else if (strategy === \"jwt\") {\n\t\t\tconst jwks = config?.jwt?.jwks;\n\t\t\tlet payload;\n\t\t\tif (jwks) payload = await verifySessionCookieJwtWithJwks(sessionData, jwks, {\n\t\t\t\tissuer: config?.jwt?.issuer,\n\t\t\t\taudience: config?.jwt?.audience\n\t\t\t});\n\t\t\telse {\n\t\t\t\tconst secret = config?.secret || env.BETTER_AUTH_SECRET;\n\t\t\t\tif (!secret) throw new BetterAuthError(\"getCookieCache requires a secret to be provided. Either pass it as an option or set the BETTER_AUTH_SECRET environment variable\");\n\t\t\t\tpayload = parseCookieCachePayload(await verifyJWT(sessionData, secret));\n\t\t\t}\n\t\t\tif (!payload) return null;\n\t\t\tif (config?.version) {\n\t\t\t\tif (!await matchesVersion(payload, config.version)) return null;\n\t\t\t}\n\t\t\tif (isEmbeddedSessionExpired(payload.session)) return null;\n\t\t\treturn payload;\n\t\t} else {\n\t\t\tconst secret = config?.secret || env.BETTER_AUTH_SECRET;\n\t\t\tif (!secret) throw new BetterAuthError(\"getCookieCache requires a secret to be provided. Either pass it as an option or set the BETTER_AUTH_SECRET environment variable\");\n\t\t\tconst sessionDataPayload = parseCompactCookieCache(safeJSONParse(binary.decode(base64Url.decode(sessionData))));\n\t\t\tif (!sessionDataPayload) return null;\n\t\t\tif (!await createHMAC(\"SHA-256\", \"base64urlnopad\").verify(secret, JSON.stringify({\n\t\t\t\t...sessionDataPayload.session,\n\t\t\t\texpiresAt: sessionDataPayload.expiresAt\n\t\t\t}), sessionDataPayload.signature)) return null;\n\t\t\tconst payload = parseCookieCachePayload(sessionDataPayload.session);\n\t\t\tif (!payload) return null;\n\t\t\tif (config?.version) {\n\t\t\t\tif (!await matchesVersion(payload, config.version)) return null;\n\t\t\t}\n\t\t\tif (typeof sessionDataPayload.expiresAt === \"number\" && sessionDataPayload.expiresAt < Date.now()) return null;\n\t\t\tif (isEmbeddedSessionExpired(payload.session)) return null;\n\t\t\treturn payload;\n\t\t}\n\t}\n\treturn null;\n};\n//#endregion\nexport { HOST_COOKIE_PREFIX, SECURE_COOKIE_PREFIX, applySetCookies, cookieNameRegex, createCookieGetter, createSessionStore, decodeCookieCache, deleteSessionCookie, expireCookie, getAccountCookie, getChunkedCookie, getCookieCache, getCookies, getSessionCookie, parseCookies, parseSetCookieHeader, setAccountCookie, setCookieCache, setCookieToHeader, setRequestCookie, setSessionCookie, splitSetCookieHeader, stripSecureCookiePrefix, toCookieOptions };\n","import { isAPIError } from \"../../utils/is-api-error.mjs\";\nimport { hasServerSessionStore } from \"../../context/store-capabilities.mjs\";\nimport { parseSessionOutput, parseUserOutput } from \"../../db/schema.mjs\";\nimport { getDate } from \"../../utils/date.mjs\";\nimport { createSessionStore, getChunkedCookie, getSessionQuerySchema } from \"../../cookies/session-store.mjs\";\nimport { decodeCookieCache, deleteSessionCookie, expireCookie, setCookieCache, setSessionCookie } from \"../../cookies/index.mjs\";\nimport { getShouldSkipSessionRefresh } from \"../state/should-session-refresh.mjs\";\nimport { APIError, BASE_ERROR_CODES } from \"@better-auth/core/error\";\nimport { createAuthEndpoint, createAuthMiddleware } from \"@better-auth/core/api\";\nimport * as z from \"zod\";\n//#region src/api/routes/session.ts\nconst getSession = () => createAuthEndpoint(\"/get-session\", {\n\tmethod: [\"GET\", \"POST\"],\n\toperationId: \"getSession\",\n\tquery: getSessionQuerySchema,\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\toperationId: \"getSession\",\n\t\tdescription: \"Get the current session\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: [\"object\", \"null\"],\n\t\t\t\tproperties: {\n\t\t\t\t\tsession: { $ref: \"#/components/schemas/Session\" },\n\t\t\t\t\tuser: { $ref: \"#/components/schemas/User\" }\n\t\t\t\t},\n\t\t\t\trequired: [\"session\", \"user\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tctx.setHeader(\"cache-control\", \"no-store\");\n\tctx.setHeader(\"pragma\", \"no-cache\");\n\tconst deferSessionRefresh = ctx.context.options.session?.deferSessionRefresh;\n\tconst isPostRequest = ctx.method === \"POST\";\n\tif (isPostRequest && !deferSessionRefresh) throw APIError.from(\"METHOD_NOT_ALLOWED\", BASE_ERROR_CODES.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);\n\ttry {\n\t\tconst cookieCacheEnabled = ctx.context.options.session?.cookieCache?.enabled === true;\n\t\tconst sessionCookieToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret);\n\t\tif (!sessionCookieToken && cookieCacheEnabled) return null;\n\t\tconst sessionDataCookie = getChunkedCookie(ctx, ctx.context.authCookies.sessionData.name);\n\t\tif (sessionDataCookie && !cookieCacheEnabled) {\n\t\t\tconst sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, ctx.context.authCookies.sessionData.attributes, ctx);\n\t\t\tsessionStore.setCookies(sessionStore.clean());\n\t\t}\n\t\tif (!sessionCookieToken) return null;\n\t\tconst shouldUseCookieCache = cookieCacheEnabled && !ctx.query?.disableCookieCache;\n\t\tconst sessionDataPayload = shouldUseCookieCache && sessionDataCookie ? await decodeCookieCache(ctx, sessionDataCookie) : null;\n\t\tif (shouldUseCookieCache && sessionDataCookie && !sessionDataPayload) expireCookie(ctx, ctx.context.authCookies.sessionData);\n\t\tconst dontRememberMe = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret);\n\t\t/**\n\t\t* If session data is present in the cookie, check if it should be used or refreshed\n\t\t*/\n\t\tif (sessionDataPayload?.session) {\n\t\t\tconst session = sessionDataPayload.session;\n\t\t\tlet shouldExpireCookieCache = session.session.token !== sessionCookieToken;\n\t\t\tif (!shouldExpireCookieCache) {\n\t\t\t\tconst versionConfig = ctx.context.options.session?.cookieCache?.version;\n\t\t\t\tlet expectedVersion = \"1\";\n\t\t\t\tif (versionConfig) {\n\t\t\t\t\tif (typeof versionConfig === \"string\") expectedVersion = versionConfig;\n\t\t\t\t\telse if (typeof versionConfig === \"function\") {\n\t\t\t\t\t\tconst result = versionConfig(session.session, session.user);\n\t\t\t\t\t\texpectedVersion = result instanceof Promise ? await result : result;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tshouldExpireCookieCache = (session.version || \"1\") !== expectedVersion;\n\t\t\t}\n\t\t\tif (!shouldExpireCookieCache) {\n\t\t\t\tconst now = Date.now();\n\t\t\t\tconst cachedSessionExpiresAt = new Date(session.session.expiresAt).getTime();\n\t\t\t\tshouldExpireCookieCache = sessionDataPayload.expiresAt < now || !Number.isFinite(cachedSessionExpiresAt) || cachedSessionExpiresAt < now;\n\t\t\t}\n\t\t\tif (shouldExpireCookieCache) expireCookie(ctx, ctx.context.authCookies.sessionData);\n\t\t\telse {\n\t\t\t\tconst cookieRefreshCache = ctx.context.sessionConfig.cookieRefreshCache;\n\t\t\t\tif (cookieRefreshCache === false) {\n\t\t\t\t\tctx.context.session = session;\n\t\t\t\t\tconst parsedSession = parseSessionOutput(ctx.context.options, {\n\t\t\t\t\t\t...session.session,\n\t\t\t\t\t\texpiresAt: new Date(session.session.expiresAt),\n\t\t\t\t\t\tcreatedAt: new Date(session.session.createdAt),\n\t\t\t\t\t\tupdatedAt: new Date(session.session.updatedAt)\n\t\t\t\t\t});\n\t\t\t\t\tconst parsedUser = parseUserOutput(ctx.context.options, {\n\t\t\t\t\t\t...session.user,\n\t\t\t\t\t\tcreatedAt: new Date(session.user.createdAt),\n\t\t\t\t\t\tupdatedAt: new Date(session.user.updatedAt)\n\t\t\t\t\t});\n\t\t\t\t\treturn ctx.json({\n\t\t\t\t\t\tsession: parsedSession,\n\t\t\t\t\t\tuser: parsedUser\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst timeUntilExpiry = sessionDataPayload.expiresAt - Date.now();\n\t\t\t\tconst updateAge = cookieRefreshCache.updateAge * 1e3;\n\t\t\t\tconst shouldSkipSessionRefresh = await getShouldSkipSessionRefresh();\n\t\t\t\tif (timeUntilExpiry < updateAge && !shouldSkipSessionRefresh) {\n\t\t\t\t\tconst refreshedSession = {\n\t\t\t\t\t\tsession: { ...session.session },\n\t\t\t\t\t\tuser: session.user,\n\t\t\t\t\t\tupdatedAt: Date.now()\n\t\t\t\t\t};\n\t\t\t\t\tawait setCookieCache(ctx, refreshedSession, false);\n\t\t\t\t\tconst sessionTokenOptions = ctx.context.authCookies.sessionToken.attributes;\n\t\t\t\t\tconst sessionTokenMaxAge = dontRememberMe ? void 0 : ctx.context.sessionConfig.expiresIn;\n\t\t\t\t\tawait ctx.setSignedCookie(ctx.context.authCookies.sessionToken.name, session.session.token, ctx.context.secret, {\n\t\t\t\t\t\t...sessionTokenOptions,\n\t\t\t\t\t\tmaxAge: sessionTokenMaxAge\n\t\t\t\t\t});\n\t\t\t\t\tconst parsedRefreshedSession = parseSessionOutput(ctx.context.options, {\n\t\t\t\t\t\t...refreshedSession.session,\n\t\t\t\t\t\texpiresAt: new Date(refreshedSession.session.expiresAt),\n\t\t\t\t\t\tcreatedAt: new Date(refreshedSession.session.createdAt),\n\t\t\t\t\t\tupdatedAt: new Date(refreshedSession.session.updatedAt)\n\t\t\t\t\t});\n\t\t\t\t\tconst parsedRefreshedUser = parseUserOutput(ctx.context.options, {\n\t\t\t\t\t\t...refreshedSession.user,\n\t\t\t\t\t\tcreatedAt: new Date(refreshedSession.user.createdAt),\n\t\t\t\t\t\tupdatedAt: new Date(refreshedSession.user.updatedAt)\n\t\t\t\t\t});\n\t\t\t\t\tctx.context.session = {\n\t\t\t\t\t\tsession: parsedRefreshedSession,\n\t\t\t\t\t\tuser: parsedRefreshedUser\n\t\t\t\t\t};\n\t\t\t\t\treturn ctx.json({\n\t\t\t\t\t\tsession: parsedRefreshedSession,\n\t\t\t\t\t\tuser: parsedRefreshedUser\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst parsedSession = parseSessionOutput(ctx.context.options, {\n\t\t\t\t\t...session.session,\n\t\t\t\t\texpiresAt: new Date(session.session.expiresAt),\n\t\t\t\t\tcreatedAt: new Date(session.session.createdAt),\n\t\t\t\t\tupdatedAt: new Date(session.session.updatedAt)\n\t\t\t\t});\n\t\t\t\tconst parsedUser = parseUserOutput(ctx.context.options, {\n\t\t\t\t\t...session.user,\n\t\t\t\t\tcreatedAt: new Date(session.user.createdAt),\n\t\t\t\t\tupdatedAt: new Date(session.user.updatedAt)\n\t\t\t\t});\n\t\t\t\tctx.context.session = {\n\t\t\t\t\tsession: parsedSession,\n\t\t\t\t\tuser: parsedUser\n\t\t\t\t};\n\t\t\t\treturn ctx.json({\n\t\t\t\t\tsession: parsedSession,\n\t\t\t\t\tuser: parsedUser\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tconst session = await ctx.context.internalAdapter.findSession(sessionCookieToken);\n\t\tctx.context.session = session;\n\t\tif (!session || session.session.expiresAt < /* @__PURE__ */ new Date()) {\n\t\t\tdeleteSessionCookie(ctx);\n\t\t\tif (session) {\n\t\t\t\t/**\n\t\t\t\t* if session expired clean up the session\n\t\t\t\t* Only delete on POST when deferSessionRefresh is enabled\n\t\t\t\t*/\n\t\t\t\tif (!deferSessionRefresh || isPostRequest) await ctx.context.internalAdapter.deleteSession(session.session.token);\n\t\t\t}\n\t\t\treturn ctx.json(null);\n\t\t}\n\t\t/**\n\t\t* We don't need to update the session if the user doesn't want to be remembered\n\t\t* or if the session refresh is disabled\n\t\t*/\n\t\tif (dontRememberMe || ctx.query?.disableRefresh) {\n\t\t\tconst parsedSession = parseSessionOutput(ctx.context.options, session.session);\n\t\t\tconst parsedUser = parseUserOutput(ctx.context.options, session.user);\n\t\t\treturn ctx.json({\n\t\t\t\tsession: parsedSession,\n\t\t\t\tuser: parsedUser\n\t\t\t});\n\t\t}\n\t\tconst expiresIn = ctx.context.sessionConfig.expiresIn;\n\t\tconst updateAge = ctx.context.sessionConfig.updateAge;\n\t\tconst shouldBeUpdated = session.session.expiresAt.valueOf() - expiresIn * 1e3 + updateAge * 1e3 <= Date.now();\n\t\tconst disableRefresh = ctx.query?.disableRefresh || ctx.context.options.session?.disableSessionRefresh;\n\t\tconst shouldSkipSessionRefresh = await getShouldSkipSessionRefresh();\n\t\tconst needsRefresh = shouldBeUpdated && !disableRefresh && !shouldSkipSessionRefresh;\n\t\t/**\n\t\t* When deferSessionRefresh is enabled and this is a GET request,\n\t\t* return the session without performing writes, but include needsRefresh flag\n\t\t*/\n\t\tif (deferSessionRefresh && !isPostRequest) {\n\t\t\tawait setCookieCache(ctx, session, !!dontRememberMe);\n\t\t\tconst parsedSession = parseSessionOutput(ctx.context.options, session.session);\n\t\t\tconst parsedUser = parseUserOutput(ctx.context.options, session.user);\n\t\t\treturn ctx.json({\n\t\t\t\tsession: parsedSession,\n\t\t\t\tuser: parsedUser,\n\t\t\t\tneedsRefresh\n\t\t\t});\n\t\t}\n\t\tif (needsRefresh) {\n\t\t\tconst updatedSession = await ctx.context.internalAdapter.updateSession(session.session.token, {\n\t\t\t\texpiresAt: getDate(ctx.context.sessionConfig.expiresIn, \"sec\"),\n\t\t\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t\t\t});\n\t\t\tif (!updatedSession) {\n\t\t\t\t/**\n\t\t\t\t* Handle case where session update fails (e.g., concurrent deletion)\n\t\t\t\t*/\n\t\t\t\tdeleteSessionCookie(ctx);\n\t\t\t\tthrow APIError.from(\"UNAUTHORIZED\", BASE_ERROR_CODES.FAILED_TO_GET_SESSION);\n\t\t\t}\n\t\t\tconst maxAge = ctx.context.sessionConfig.expiresIn;\n\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\tsession: updatedSession,\n\t\t\t\tuser: session.user\n\t\t\t}, false, { maxAge });\n\t\t\tconst parsedUpdatedSession = parseSessionOutput(ctx.context.options, updatedSession);\n\t\t\tconst parsedUser = parseUserOutput(ctx.context.options, session.user);\n\t\t\treturn ctx.json({\n\t\t\t\tsession: parsedUpdatedSession,\n\t\t\t\tuser: parsedUser\n\t\t\t});\n\t\t}\n\t\tawait setCookieCache(ctx, session, !!dontRememberMe);\n\t\tconst parsedSession = parseSessionOutput(ctx.context.options, session.session);\n\t\tconst parsedUser = parseUserOutput(ctx.context.options, session.user);\n\t\treturn ctx.json({\n\t\t\tsession: parsedSession,\n\t\t\tuser: parsedUser\n\t\t});\n\t} catch (error) {\n\t\tif (isAPIError(error)) throw error;\n\t\tctx.context.logger.error(\"INTERNAL_SERVER_ERROR\", error);\n\t\tthrow APIError.from(\"INTERNAL_SERVER_ERROR\", BASE_ERROR_CODES.FAILED_TO_GET_SESSION);\n\t}\n});\n/**\n* Whether the deployment keeps sessions in a durable server-side store\n* (a database or secondary storage) rather than only in the signed cookie.\n*\n* Sensitive operations use this to decide whether the cookie cache is merely an\n* optimization that must be bypassed for an authoritative read (`true`), or the\n* only place the session lives and therefore the authority itself (`false`, for\n* stateless / DB-less deployments). Pass the result as `disableCookieCache` so a\n* revoked-but-cached session cannot authorize a sensitive action.\n*/\nconst isStateful = (ctx) => hasServerSessionStore(ctx.context.options);\nconst getSessionFromCtx = async (ctx, config) => {\n\tif (ctx.context.session) return ctx.context.session;\n\tconst session = await getSession()({\n\t\t...ctx,\n\t\tmethod: \"GET\",\n\t\tasResponse: false,\n\t\theaders: ctx.headers,\n\t\treturnHeaders: true,\n\t\treturnStatus: false,\n\t\tquery: {\n\t\t\t...config,\n\t\t\t...ctx.query,\n\t\t\tdisableCookieCache: config?.disableCookieCache || ctx.query?.disableCookieCache,\n\t\t\tdisableRefresh: config?.disableRefresh || ctx.query?.disableRefresh\n\t\t}\n\t}).catch(() => {\n\t\treturn null;\n\t});\n\tif (!session) {\n\t\tctx.context.session = null;\n\t\treturn null;\n\t}\n\tif (session.headers) session.headers.forEach((value, key) => {\n\t\tconst lowerKey = key.toLowerCase();\n\t\tif (lowerKey === \"cache-control\" || lowerKey === \"pragma\") return;\n\t\tif (lowerKey === \"set-cookie\") ctx.responseHeaders.append(key, value);\n\t\telse ctx.responseHeaders.set(key, value);\n\t});\n\tctx.context.session = session.response;\n\treturn session.response;\n};\n/**\n* Reads the session from the source that can authorize sensitive work.\n*\n* Stateful deployments must re-read the server-side session store because an\n* earlier hook may have populated `ctx.context.session` from cookie cache.\n* Stateless deployments keep the signed cookie as the session record.\n*/\nconst getAuthoritativeSessionFromCtx = async (ctx) => {\n\tif (!isStateful(ctx)) return getSessionFromCtx(ctx);\n\tctx.context.session = null;\n\treturn getSessionFromCtx(ctx, { disableCookieCache: true });\n};\n/**\n* The middleware forces the endpoint to require a valid session.\n*/\nconst sessionMiddleware = createAuthMiddleware(async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session?.session) throw APIError.from(\"UNAUTHORIZED\", {\n\t\tmessage: \"Unauthorized\",\n\t\tcode: \"UNAUTHORIZED\"\n\t});\n\treturn { session };\n});\n/**\n* This middleware forces the endpoint to require a valid authoritative session.\n* This should be used for sensitive operations like password changes, account deletion, etc.\n*/\nconst sensitiveSessionMiddleware = createAuthMiddleware(async (ctx) => {\n\tconst session = await getAuthoritativeSessionFromCtx(ctx);\n\tif (!session?.session) throw APIError.from(\"UNAUTHORIZED\", {\n\t\tmessage: \"Unauthorized\",\n\t\tcode: \"UNAUTHORIZED\"\n\t});\n\treturn { session };\n});\n/**\n* This middleware allows you to call the endpoint on the client if session is valid.\n* However, if called on the server, no session is required.\n*/\nconst requestOnlySessionMiddleware = createAuthMiddleware(async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session?.session && (ctx.request || ctx.headers)) throw APIError.from(\"UNAUTHORIZED\", {\n\t\tmessage: \"Unauthorized\",\n\t\tcode: \"UNAUTHORIZED\"\n\t});\n\treturn { session };\n});\n/**\n* This middleware forces the endpoint to require a valid session,\n* as well as making sure the session is fresh before proceeding.\n*\n* Session freshness check will be skipped if the session config's freshAge\n* is set to 0\n*/\nconst freshSessionMiddleware = createAuthMiddleware(async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session?.session) throw APIError.from(\"UNAUTHORIZED\", {\n\t\tmessage: \"Unauthorized\",\n\t\tcode: \"UNAUTHORIZED\"\n\t});\n\tif (ctx.context.sessionConfig.freshAge !== 0) {\n\t\tconst createdAt = new Date(session.session.createdAt).getTime();\n\t\tconst freshAge = ctx.context.sessionConfig.freshAge * 1e3;\n\t\tif (Date.now() - createdAt >= freshAge) throw APIError.from(\"FORBIDDEN\", BASE_ERROR_CODES.SESSION_NOT_FRESH);\n\t}\n\treturn { session };\n});\n/**\n* user active sessions list\n*/\nconst listSessions = () => createAuthEndpoint(\"/list-sessions\", {\n\tmethod: \"GET\",\n\toperationId: \"listUserSessions\",\n\tuse: [freshSessionMiddleware],\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\toperationId: \"listUserSessions\",\n\t\tdescription: \"List all active sessions for the user\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: { $ref: \"#/components/schemas/Session\" }\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\ttry {\n\t\tconst activeSessions = (await ctx.context.internalAdapter.listSessions(ctx.context.session.user.id, { onlyActiveSessions: true })).filter((session) => {\n\t\t\treturn session.expiresAt > /* @__PURE__ */ new Date();\n\t\t});\n\t\treturn ctx.json(activeSessions.map((session) => parseSessionOutput(ctx.context.options, session)));\n\t} catch (e) {\n\t\tctx.context.logger.error(e);\n\t\tthrow ctx.error(\"INTERNAL_SERVER_ERROR\");\n\t}\n});\n/**\n* revoke a single session\n*/\nconst revokeSession = createAuthEndpoint(\"/revoke-session\", {\n\tmethod: \"POST\",\n\tbody: z.object({ token: z.string().meta({ description: \"The token to revoke\" }) }),\n\tuse: [sensitiveSessionMiddleware],\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\tdescription: \"Revoke a single session\",\n\t\trequestBody: { content: { \"application/json\": { schema: {\n\t\t\ttype: \"object\",\n\t\t\tproperties: { token: {\n\t\t\t\ttype: \"string\",\n\t\t\t\tdescription: \"The token to revoke\"\n\t\t\t} },\n\t\t\trequired: [\"token\"]\n\t\t} } } },\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { status: {\n\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\tdescription: \"Indicates if the session was revoked successfully\"\n\t\t\t\t} },\n\t\t\t\trequired: [\"status\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst token = ctx.body.token;\n\tif ((await ctx.context.internalAdapter.findSession(token))?.session.userId === ctx.context.session.user.id) try {\n\t\tawait ctx.context.internalAdapter.deleteSession(token);\n\t} catch (error) {\n\t\tctx.context.logger.error(error && typeof error === \"object\" && \"name\" in error ? error.name : \"\", error);\n\t\tthrow APIError.from(\"INTERNAL_SERVER_ERROR\", {\n\t\t\tmessage: \"Internal Server Error\",\n\t\t\tcode: \"INTERNAL_SERVER_ERROR\"\n\t\t});\n\t}\n\treturn ctx.json({ status: true });\n});\n/**\n* revoke all user sessions\n*/\nconst revokeSessions = createAuthEndpoint(\"/revoke-sessions\", {\n\tmethod: \"POST\",\n\tuse: [sensitiveSessionMiddleware],\n\trequireHeaders: true,\n\tmetadata: { openapi: {\n\t\tdescription: \"Revoke all sessions for the user\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { status: {\n\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\tdescription: \"Indicates if all sessions were revoked successfully\"\n\t\t\t\t} },\n\t\t\t\trequired: [\"status\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\ttry {\n\t\tawait ctx.context.internalAdapter.deleteUserSessions(ctx.context.session.user.id);\n\t} catch (error) {\n\t\tctx.context.logger.error(error && typeof error === \"object\" && \"name\" in error ? error.name : \"\", error);\n\t\tthrow APIError.from(\"INTERNAL_SERVER_ERROR\", {\n\t\t\tmessage: \"Internal Server Error\",\n\t\t\tcode: \"INTERNAL_SERVER_ERROR\"\n\t\t});\n\t}\n\treturn ctx.json({ status: true });\n});\nconst revokeOtherSessions = createAuthEndpoint(\"/revoke-other-sessions\", {\n\tmethod: \"POST\",\n\trequireHeaders: true,\n\tuse: [sensitiveSessionMiddleware],\n\tmetadata: { openapi: {\n\t\tdescription: \"Revoke all other sessions for the user except the current one\",\n\t\tresponses: { \"200\": {\n\t\t\tdescription: \"Success\",\n\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { status: {\n\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\tdescription: \"Indicates if all other sessions were revoked successfully\"\n\t\t\t\t} },\n\t\t\t\trequired: [\"status\"]\n\t\t\t} } }\n\t\t} }\n\t} }\n}, async (ctx) => {\n\tconst session = ctx.context.session;\n\tif (!session.user) throw APIError.from(\"UNAUTHORIZED\", {\n\t\tmessage: \"Unauthorized\",\n\t\tcode: \"UNAUTHORIZED\"\n\t});\n\tconst otherSessions = (await ctx.context.internalAdapter.listSessions(session.user.id)).filter((session) => {\n\t\treturn session.expiresAt > /* @__PURE__ */ new Date();\n\t}).filter((session) => session.token !== ctx.context.session.session.token);\n\tawait Promise.all(otherSessions.map((session) => ctx.context.internalAdapter.deleteSession(session.token)));\n\treturn ctx.json({ status: true });\n});\n//#endregion\nexport { freshSessionMiddleware, getAuthoritativeSessionFromCtx, getSession, getSessionFromCtx, isStateful, listSessions, requestOnlySessionMiddleware, revokeOtherSessions, revokeSession, revokeSessions, sensitiveSessionMiddleware, sessionMiddleware };\n","import { ATTR_DB_COLLECTION_NAME, ATTR_DB_OPERATION_NAME, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_HTTP_ROUTE } from \"@opentelemetry/semantic-conventions\";\n//#region src/instrumentation/attributes.ts\n/** Operation identifier (e.g. getSession, signUpWithEmailAndPassword). Uses endpoint operationId when set, otherwise the endpoint key. */\nconst ATTR_OPERATION_ID = \"better_auth.operation_id\";\n/** Hook type (e.g. before, after, create.before). */\nconst ATTR_HOOK_TYPE = \"better_auth.hook.type\";\n/** Execution context (e.g. user, plugin:id). */\nconst ATTR_CONTEXT = \"better_auth.context\";\n//#endregion\nexport { ATTR_CONTEXT, ATTR_DB_COLLECTION_NAME, ATTR_DB_OPERATION_NAME, ATTR_HOOK_TYPE, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_HTTP_ROUTE, ATTR_OPERATION_ID };\n","function isPlainObject(value) {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {\n return false;\n }\n if (Symbol.iterator in value) {\n return false;\n }\n if (Symbol.toStringTag in value) {\n return Object.prototype.toString.call(value) === \"[object Module]\";\n }\n return true;\n}\n\nfunction _defu(baseObject, defaults, namespace = \".\", merger) {\n if (!isPlainObject(defaults)) {\n return _defu(baseObject, {}, namespace, merger);\n }\n const object = { ...defaults };\n for (const key of Object.keys(baseObject)) {\n if (key === \"__proto__\" || key === \"constructor\") {\n continue;\n }\n const value = baseObject[key];\n if (value === null || value === void 0) {\n continue;\n }\n if (merger && merger(object, key, value, namespace)) {\n continue;\n }\n if (Array.isArray(value) && Array.isArray(object[key])) {\n object[key] = [...value, ...object[key]];\n } else if (isPlainObject(value) && isPlainObject(object[key])) {\n object[key] = _defu(\n value,\n object[key],\n (namespace ? `${namespace}.` : \"\") + key.toString(),\n merger\n );\n } else {\n object[key] = value;\n }\n }\n return object;\n}\nfunction createDefu(merger) {\n return (...arguments_) => (\n // eslint-disable-next-line unicorn/no-array-reduce\n arguments_.reduce((p, c) => _defu(p, c, \"\", merger), {})\n );\n}\nconst defu = createDefu();\nconst defuFn = createDefu((object, key, currentValue) => {\n if (object[key] !== void 0 && typeof currentValue === \"function\") {\n object[key] = currentValue(object[key]);\n return true;\n }\n});\nconst defuArrayFn = createDefu((object, key, currentValue) => {\n if (Array.isArray(object[key]) && typeof currentValue === \"function\") {\n object[key] = currentValue(object[key]);\n return true;\n }\n});\n\nexport { createDefu, defu as default, defu, defuArrayFn, defuFn };\n","import { isValidIP, normalizeIP } from \"./ip.mjs\";\n//#region src/utils/host.ts\n/**\n* Cloud provider instance metadata service FQDNs. These resolve to link-local\n* IPs (usually `169.254.169.254`) inside their respective clouds and are\n* prime SSRF targets.\n*\n* The IPs themselves are already caught by the `linkLocal` kind; this set\n* only exists for the FQDN form that a naive server-side fetch might resolve\n* via its own resolver.\n*/\nconst CLOUD_METADATA_HOSTS = new Set([\n\t\"metadata.google.internal\",\n\t\"metadata.goog\",\n\t\"metadata\",\n\t\"instance-data\",\n\t\"instance-data.ec2.internal\"\n]);\n/** Strip `[...]` if the entire input is bracketed (IPv6 literal form). */\nfunction stripBrackets(host) {\n\tif (host.length >= 2 && host.startsWith(\"[\") && host.endsWith(\"]\")) return host.slice(1, -1);\n\treturn host;\n}\n/**\n* Strip trailing `:port` from host-with-port strings.\n*\n* - Bracketed IPv6 with port: `[::1]:8080` → `[::1]`\n* - IPv4/FQDN with port: `127.0.0.1:3000` / `example.com:443` → base form\n* - Bare IPv6: `::1` / `fe80::1` → unchanged (multiple colons means no port)\n*/\nfunction stripPort(host) {\n\tif (host.startsWith(\"[\")) {\n\t\tconst end = host.indexOf(\"]\");\n\t\tif (end === -1) return host;\n\t\treturn host.slice(0, end + 1);\n\t}\n\tconst firstColon = host.indexOf(\":\");\n\tif (firstColon === -1) return host;\n\tif (host.indexOf(\":\", firstColon + 1) !== -1) return host;\n\treturn host.slice(0, firstColon);\n}\n/** Strip IPv6 zone identifier: `fe80::1%eth0` → `fe80::1`. */\nfunction stripZoneId(host) {\n\tconst zone = host.indexOf(\"%\");\n\tif (zone === -1) return host;\n\treturn host.slice(0, zone);\n}\n/**\n* Strip trailing dots (RFC 1034 absolute DNS form): `localhost.` → `localhost`.\n* Without this, `metadata.google.internal.` would fall through to `public` and\n* bypass the cloud-metadata / `.localhost` checks, since WHATWG URL parsing\n* preserves the trailing dot in `url.hostname`.\n*/\nfunction stripTrailingDot(host) {\n\treturn host.replace(/\\.+$/, \"\");\n}\n/** Fast dotted-decimal shape check. Does NOT validate octet bounds. */\nfunction looksLikeIPv4(host) {\n\treturn /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(host);\n}\n/** Pack a validated dotted-decimal IPv4 into a 32-bit unsigned integer. */\nfunction ipv4ToUint32(ip) {\n\tconst parts = ip.split(\".\");\n\treturn (Number(parts[0]) << 24 | Number(parts[1]) << 16 | Number(parts[2]) << 8 | Number(parts[3])) >>> 0;\n}\n/** Check whether a 32-bit value matches `prefix/length` (both unsigned). */\nfunction inIPv4Range(value, prefix, length) {\n\tif (length === 0) return true;\n\tconst mask = length === 32 ? 4294967295 : -1 << 32 - length >>> 0;\n\treturn (value & mask) === (prefix & mask);\n}\nfunction classifyIPv4(ip) {\n\tif (ip === \"0.0.0.0\") return \"unspecified\";\n\tif (ip === \"255.255.255.255\") return \"broadcast\";\n\tconst n = ipv4ToUint32(ip);\n\tif (inIPv4Range(n, ipv4ToUint32(\"127.0.0.0\"), 8)) return \"loopback\";\n\tif (inIPv4Range(n, ipv4ToUint32(\"10.0.0.0\"), 8)) return \"private\";\n\tif (inIPv4Range(n, ipv4ToUint32(\"172.16.0.0\"), 12)) return \"private\";\n\tif (inIPv4Range(n, ipv4ToUint32(\"192.168.0.0\"), 16)) return \"private\";\n\tif (inIPv4Range(n, ipv4ToUint32(\"169.254.0.0\"), 16)) return \"linkLocal\";\n\tif (inIPv4Range(n, ipv4ToUint32(\"100.64.0.0\"), 10)) return \"sharedAddressSpace\";\n\tif (inIPv4Range(n, ipv4ToUint32(\"192.0.2.0\"), 24)) return \"documentation\";\n\tif (inIPv4Range(n, ipv4ToUint32(\"198.51.100.0\"), 24)) return \"documentation\";\n\tif (inIPv4Range(n, ipv4ToUint32(\"203.0.113.0\"), 24)) return \"documentation\";\n\tif (inIPv4Range(n, ipv4ToUint32(\"198.18.0.0\"), 15)) return \"benchmarking\";\n\tif (inIPv4Range(n, ipv4ToUint32(\"224.0.0.0\"), 4)) return \"multicast\";\n\tif (inIPv4Range(n, ipv4ToUint32(\"0.0.0.0\"), 8)) return \"reserved\";\n\tif (inIPv4Range(n, ipv4ToUint32(\"192.0.0.0\"), 24)) return \"reserved\";\n\tif (inIPv4Range(n, ipv4ToUint32(\"192.88.99.0\"), 24)) return \"reserved\";\n\tif (inIPv4Range(n, ipv4ToUint32(\"240.0.0.0\"), 4)) return \"reserved\";\n\treturn \"public\";\n}\n/**\n* Extract an IPv4 address embedded in an expanded IPv6 literal.\n*\n* Used to recurse into tunnel/translation forms (6to4, NAT64, Teredo) so a\n* private destination cannot be smuggled behind a syntactically-public IPv6\n* literal. `startGroup` is the index of the first of two 16-bit groups in the\n* expanded form (`0000:0000:...`). With `xor: true`, the 32-bit value is XORed\n* with `0xffffffff` before decoding (Teredo obfuscates the client IPv4 this\n* way).\n*/\nfunction extractEmbeddedIPv4(expanded, startGroup, options = {}) {\n\tconst offset = startGroup * 5;\n\tconst g1 = Number.parseInt(expanded.slice(offset, offset + 4), 16);\n\tconst g2 = Number.parseInt(expanded.slice(offset + 5, offset + 9), 16);\n\tif (!Number.isFinite(g1) || !Number.isFinite(g2)) return null;\n\tlet combined = (g1 << 16 | g2) >>> 0;\n\tif (options.xor) combined = (combined ^ 4294967295) >>> 0;\n\treturn `${combined >>> 24 & 255}.${combined >>> 16 & 255}.${combined >>> 8 & 255}.${combined & 255}`;\n}\n/**\n* Classify an expanded, full-form, lowercase IPv6 address (no IPv4-mapped\n* input — those are unmapped to IPv4 before reaching here).\n*\n* 6to4 (`2002::/16`), NAT64 (`64:ff9b::/96`) and Teredo (`2001:0000::/32`)\n* embed an IPv4 that can route to private/loopback space. If the embedded\n* IPv4 classifies as non-`public`, return `reserved` — blocks SSRF without\n* advertising the address as a loopback literal for RFC 8252 §7.3 matching.\n*/\nfunction classifyIPv6(expanded) {\n\tif (expanded === \"0000:0000:0000:0000:0000:0000:0000:0000\") return \"unspecified\";\n\tif (expanded === \"0000:0000:0000:0000:0000:0000:0000:0001\") return \"loopback\";\n\tconst firstByte = Number.parseInt(expanded.slice(0, 2), 16);\n\tconst secondByte = Number.parseInt(expanded.slice(2, 4), 16);\n\tif (firstByte === 255) return \"multicast\";\n\tif (firstByte === 254 && (secondByte & 192) === 128) return \"linkLocal\";\n\tif (firstByte === 254 && (secondByte & 192) === 192) return \"reserved\";\n\tif ((firstByte & 254) === 252) return \"private\";\n\tif (expanded.startsWith(\"2001:0db8:\")) return \"documentation\";\n\tif (expanded.startsWith(\"2001:0002:0000:\")) return \"benchmarking\";\n\tif (expanded.startsWith(\"2002:\")) {\n\t\tconst embedded = extractEmbeddedIPv4(expanded, 1);\n\t\tif (embedded && classifyIPv4(embedded) !== \"public\") return \"reserved\";\n\t\treturn \"public\";\n\t}\n\tif (expanded.startsWith(\"0064:ff9b:0000:0000:0000:0000:\")) {\n\t\tconst embedded = extractEmbeddedIPv4(expanded, 6);\n\t\tif (embedded && classifyIPv4(embedded) !== \"public\") return \"reserved\";\n\t\treturn \"reserved\";\n\t}\n\tif (expanded.startsWith(\"0064:ff9b:0001:\")) return \"reserved\";\n\tif (expanded.startsWith(\"2001:0000:\")) {\n\t\tconst embedded = extractEmbeddedIPv4(expanded, 6, { xor: true });\n\t\tif (embedded && classifyIPv4(embedded) !== \"public\") return \"reserved\";\n\t\treturn \"reserved\";\n\t}\n\tif (expanded.startsWith(\"0100:0000:0000:0000:\")) return \"reserved\";\n\tif (expanded.startsWith(\"3fff:0\")) return \"documentation\";\n\tif (expanded.startsWith(\"5f00:\")) return \"reserved\";\n\tif (expanded.startsWith(\"0000:0000:0000:0000:0000:0000:\")) return \"reserved\";\n\treturn \"public\";\n}\n/**\n* Classify a host string according to RFC 6890 / RFC 6761.\n*\n* Accepts inputs in any of these shapes and normalizes before classifying:\n*\n* - Bare IPv4: `127.0.0.1`\n* - Bare IPv6: `::1`, `fe80::1%eth0`\n* - Bracketed IPv6: `[::1]`\n* - Host with port: `localhost:3000`, `127.0.0.1:443`, `[::1]:8080`\n* - FQDN: `example.com`, `tenant.localhost`\n* - IPv4-mapped IPv6: `::ffff:192.0.2.1` (reported as `literal: \"ipv4\"`)\n*\n* Invalid or non-resolvable FQDNs are returned as `{ kind: \"public\", literal: \"fqdn\" }`\n* — this function never throws. Callers that need structural validation must\n* combine this with a URL/hostname validator upstream.\n*\n* @example\n* classifyHost(\"127.0.0.1\")\n* // { kind: \"loopback\", literal: \"ipv4\", canonical: \"127.0.0.1\" }\n*\n* @example\n* classifyHost(\"[::1]:8080\")\n* // { kind: \"loopback\", literal: \"ipv6\", canonical: \"0000:0000:...:0001\" }\n*\n* @example\n* classifyHost(\"::ffff:192.0.2.1\")\n* // { kind: \"documentation\", literal: \"ipv4\", canonical: \"192.0.2.1\" }\n*\n* @example\n* classifyHost(\"tenant-a.localhost\")\n* // { kind: \"localhost\", literal: \"fqdn\", canonical: \"tenant-a.localhost\" }\n*/\nfunction classifyHost(host) {\n\tconst lowered = stripTrailingDot(stripZoneId(stripBrackets(stripPort(host.trim())))).toLowerCase();\n\tif (lowered === \"\") return {\n\t\tkind: \"reserved\",\n\t\tliteral: \"fqdn\",\n\t\tcanonical: \"\"\n\t};\n\tif (!isValidIP(lowered)) {\n\t\tif (lowered === \"localhost\" || lowered.endsWith(\".localhost\")) return {\n\t\t\tkind: \"localhost\",\n\t\t\tliteral: \"fqdn\",\n\t\t\tcanonical: lowered\n\t\t};\n\t\tif (CLOUD_METADATA_HOSTS.has(lowered)) return {\n\t\t\tkind: \"cloudMetadata\",\n\t\t\tliteral: \"fqdn\",\n\t\t\tcanonical: lowered\n\t\t};\n\t\treturn {\n\t\t\tkind: \"public\",\n\t\t\tliteral: \"fqdn\",\n\t\t\tcanonical: lowered\n\t\t};\n\t}\n\tif (looksLikeIPv4(lowered)) return {\n\t\tkind: classifyIPv4(lowered),\n\t\tliteral: \"ipv4\",\n\t\tcanonical: lowered\n\t};\n\tconst canonical = normalizeIP(lowered, { ipv6Subnet: 128 });\n\tif (looksLikeIPv4(canonical)) return {\n\t\tkind: classifyIPv4(canonical),\n\t\tliteral: \"ipv4\",\n\t\tcanonical\n\t};\n\treturn {\n\t\tkind: classifyIPv6(canonical),\n\t\tliteral: \"ipv6\",\n\t\tcanonical\n\t};\n}\n/**\n* Strict loopback-IP-literal check per RFC 8252 §7.3.\n*\n* Returns true ONLY for IPv4 `127.0.0.0/8` or IPv6 `::1`. The DNS name\n* `localhost` returns false — RFC 8252 §8.3 explicitly recommends against\n* relying on name resolution for loopback redirect URIs.\n*\n* Use this for OAuth redirect URI matching.\n*\n* @example\n* isLoopbackIP(\"127.0.0.1\") // true\n* isLoopbackIP(\"::1\") // true\n* isLoopbackIP(\"[::1]:8080\") // true\n* isLoopbackIP(\"localhost\") // false (use isLoopbackHost for DNS names)\n* isLoopbackIP(\"0.0.0.0\") // false (unspecified, not loopback)\n*/\nfunction isLoopbackIP(host) {\n\treturn classifyHost(host).kind === \"loopback\";\n}\n/**\n* Permissive loopback check for developer-ergonomics code paths.\n*\n* Returns true for IPv4 `127.0.0.0/8`, IPv6 `::1`, the literal name `localhost`,\n* and any RFC 6761 `.localhost` subdomain (`tenant.localhost`, `app.localhost`).\n*\n* Use this for things like: allowing HTTP for dev servers, skipping Secure\n* cookie requirements, browser-trust heuristics. Do NOT use this for OAuth\n* redirect URI matching — use {@link isLoopbackIP} there.\n*\n* @example\n* isLoopbackHost(\"localhost\") // true\n* isLoopbackHost(\"tenant.localhost\") // true (RFC 6761)\n* isLoopbackHost(\"127.0.0.1\") // true\n* isLoopbackHost(\"0.0.0.0\") // false (unspecified, NOT loopback)\n*/\nfunction isLoopbackHost(host) {\n\tconst kind = classifyHost(host).kind;\n\treturn kind === \"loopback\" || kind === \"localhost\";\n}\n/**\n* First-line SSRF gate: returns true ONLY for hosts that classify as `public`.\n*\n* Every RFC 6890 special-purpose range (loopback, private, link-local,\n* unspecified, documentation, multicast, broadcast, reserved, shared address\n* space, benchmarking) and cloud-metadata FQDN returns false.\n*\n* Use this BEFORE issuing a server-side fetch to a user-supplied URL, e.g.\n* OAuth introspection endpoints, webhook targets, or metadata-document\n* fetches (CIMD).\n*\n* Limitations (this is a syntactic check, not a complete SSRF mitigation):\n* - No DNS resolution: a public-looking FQDN that resolves to a private IP\n* passes this check. Re-verify the resolved address before connecting, or\n* pin the socket to the resolved IP.\n* - No DNS-rebinding defense: attackers can return a public IP on the first\n* lookup and a private IP on the second. Resolve once and reuse the IP.\n* - No redirect following: HTTP 3xx responses can redirect to private hosts.\n* Re-run this check on every redirect target, or disable auto-follow.\n*\n* @example\n* isPublicRoutableHost(\"example.com\") // true\n* isPublicRoutableHost(\"127.0.0.1\") // false (loopback)\n* isPublicRoutableHost(\"169.254.169.254\") // false (linkLocal / AWS IMDS)\n* isPublicRoutableHost(\"metadata.google.internal\") // false (cloudMetadata)\n* isPublicRoutableHost(\"10.0.0.1\") // false (private)\n* isPublicRoutableHost(\"::ffff:127.0.0.1\") // false (mapped loopback)\n*/\nfunction isPublicRoutableHost(host) {\n\treturn classifyHost(host).kind === \"public\";\n}\n//#endregion\nexport { classifyHost, isLoopbackHost, isLoopbackIP, isPublicRoutableHost };\n","import { isAPIError } from \"../utils/is-api-error.mjs\";\nimport { isRequestLike } from \"../utils/url.mjs\";\nimport { runWithEndpointContext } from \"@better-auth/core/context\";\nimport { shouldPublishLog } from \"@better-auth/core/env\";\nimport { APIError } from \"@better-auth/core/error\";\nimport { createDefu } from \"defu\";\nimport { ATTR_CONTEXT, ATTR_HOOK_TYPE, ATTR_HTTP_ROUTE, ATTR_OPERATION_ID, createWithSpan } from \"@better-auth/core/instrumentation\";\nimport { kAPIErrorHeaderSymbol, toResponse } from \"better-call\";\n//#region src/api/dispatch.ts\nconst defuReplaceArrays = createDefu((obj, key, value) => {\n\tif (Array.isArray(obj[key]) && Array.isArray(value)) {\n\t\tobj[key] = value;\n\t\treturn true;\n\t}\n});\nconst hooksSourceWeakMap = /* @__PURE__ */ new WeakMap();\n/**\n* Resolves the operation id used for spans, preferring an explicit\n* `operationId`, then the OpenAPI one, then the caller's `fallback` (the\n* `auth.api.*` map key), and finally the route path.\n*/\nfunction getOperationId(endpoint, fallback) {\n\tconst opts = endpoint.options;\n\treturn opts?.operationId ?? opts?.metadata?.openapi?.operationId ?? fallback ?? endpoint.path ?? \"/:virtual\";\n}\n/**\n* Merge a set of response headers onto the dispatch's accumulator, appending\n* `set-cookie` (multiple cookies are legal) and replacing everything else.\n*/\nfunction mergeResponseHeaders(context, headers) {\n\tif (!headers) return;\n\theaders.forEach((value, key) => {\n\t\tif (!context.responseHeaders) context.responseHeaders = new Headers({ [key]: value });\n\t\telse if (key.toLowerCase() === \"set-cookie\") context.responseHeaders.append(key, value);\n\t\telse context.responseHeaders.set(key, value);\n\t});\n}\n/**\n* Combine the two header sources an `APIError` can carry into one set:\n* - `kAPIErrorHeaderSymbol`: `ctx.responseHeaders` accumulated via\n* `c.setCookie` / `c.setHeader` before the throw.\n* - `e.headers`: explicit headers on the error (e.g. `location` from\n* `c.redirect`).\n*\n* `c.redirect()` reuses `ctx.responseHeaders` as `e.headers`, so when both\n* point at the same object iterating each would duplicate every `set-cookie`;\n* the identity check skips that copy. Explicit error headers override\n* accumulated ones, while cookies from both accumulate.\n*/\nfunction mergeAPIErrorHeaders(error) {\n\tconst ctxHeaders = error[kAPIErrorHeaderSymbol];\n\tconst errHeaders = error.headers && error.headers !== ctxHeaders ? new Headers(error.headers) : null;\n\tif (!ctxHeaders && !errHeaders) return null;\n\tconst headers = new Headers();\n\tctxHeaders?.forEach((value, key) => {\n\t\theaders.append(key, value);\n\t});\n\terrHeaders?.forEach((value, key) => {\n\t\tif (key.toLowerCase() === \"set-cookie\") headers.append(key, value);\n\t\telse headers.set(key, value);\n\t});\n\treturn headers;\n}\nasync function runBeforeHooks(context, hooks, endpoint, operationId) {\n\tconst withSpan = createWithSpan(context.context.options);\n\tlet modifiedContext = {};\n\tfor (const hook of hooks) {\n\t\tlet matched = false;\n\t\ttry {\n\t\t\tmatched = hook.matcher(context);\n\t\t} catch (error) {\n\t\t\tconst hookSource = hooksSourceWeakMap.get(hook.handler) ?? \"unknown\";\n\t\t\tcontext.context.logger.error(`An error occurred during ${hookSource} hook matcher execution:`, error);\n\t\t\tthrow new APIError(\"INTERNAL_SERVER_ERROR\", { message: \"An error occurred during hook matcher execution. Check the logs for more details.\" });\n\t\t}\n\t\tif (!matched) continue;\n\t\tconst hookSource = hooksSourceWeakMap.get(hook.handler) ?? \"unknown\";\n\t\tconst route = endpoint.path ?? \"/:virtual\";\n\t\tconst result = await withSpan(`hook before ${route} ${hookSource}`, {\n\t\t\t[ATTR_HOOK_TYPE]: \"before\",\n\t\t\t[ATTR_HTTP_ROUTE]: route,\n\t\t\t[ATTR_CONTEXT]: hookSource,\n\t\t\t[ATTR_OPERATION_ID]: operationId\n\t\t}, () => hook.handler({\n\t\t\t...context,\n\t\t\treturnHeaders: true\n\t\t})).catch((e) => {\n\t\t\tif (isAPIError(e) && shouldPublishLog(context.context.logger.level, \"debug\")) e.stack = e.errorStack;\n\t\t\tthrow e;\n\t\t});\n\t\tmergeResponseHeaders(context.context, result?.headers);\n\t\tconst hookReturn = result?.response;\n\t\tif (hookReturn && typeof hookReturn === \"object\") {\n\t\t\tif (\"context\" in hookReturn && typeof hookReturn.context === \"object\") {\n\t\t\t\tconst { headers, ...rest } = hookReturn.context;\n\t\t\t\tif (headers instanceof Headers) if (modifiedContext.headers) headers.forEach((value, key) => {\n\t\t\t\t\tmodifiedContext.headers?.set(key, value);\n\t\t\t\t});\n\t\t\t\telse modifiedContext.headers = headers;\n\t\t\t\tmodifiedContext = defuReplaceArrays(rest, modifiedContext);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn hookReturn;\n\t\t}\n\t}\n\treturn { context: modifiedContext };\n}\nasync function runAfterHooks(context, hooks, endpoint, operationId) {\n\tconst withSpan = createWithSpan(context.context.options);\n\tfor (const hook of hooks) {\n\t\tif (!hook.matcher(context)) continue;\n\t\tconst hookSource = hooksSourceWeakMap.get(hook.handler) ?? \"unknown\";\n\t\tconst route = endpoint.path ?? \"/:virtual\";\n\t\tconst result = await withSpan(`hook after ${route} ${hookSource}`, {\n\t\t\t[ATTR_HOOK_TYPE]: \"after\",\n\t\t\t[ATTR_HTTP_ROUTE]: route,\n\t\t\t[ATTR_CONTEXT]: hookSource,\n\t\t\t[ATTR_OPERATION_ID]: operationId\n\t\t}, () => hook.handler(context)).catch((e) => {\n\t\t\tif (isAPIError(e)) {\n\t\t\t\tif (shouldPublishLog(context.context.logger.level, \"debug\")) e.stack = e.errorStack;\n\t\t\t\treturn {\n\t\t\t\t\tresponse: e,\n\t\t\t\t\theaders: mergeAPIErrorHeaders(e)\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow e;\n\t\t});\n\t\tmergeResponseHeaders(context.context, result.headers);\n\t\tif (result.response !== void 0) context.context.returned = result.response;\n\t}\n\treturn {\n\t\tresponse: context.context.returned,\n\t\theaders: context.context.responseHeaders\n\t};\n}\nfunction getHooks(authContext) {\n\tconst plugins = authContext.options.plugins || [];\n\tconst beforeHooks = [];\n\tconst afterHooks = [];\n\tconst beforeHookHandler = authContext.options.hooks?.before;\n\tif (beforeHookHandler) {\n\t\thooksSourceWeakMap.set(beforeHookHandler, \"user\");\n\t\tbeforeHooks.push({\n\t\t\tmatcher: () => true,\n\t\t\thandler: beforeHookHandler\n\t\t});\n\t}\n\tconst afterHookHandler = authContext.options.hooks?.after;\n\tif (afterHookHandler) {\n\t\thooksSourceWeakMap.set(afterHookHandler, \"user\");\n\t\tafterHooks.push({\n\t\t\tmatcher: () => true,\n\t\t\thandler: afterHookHandler\n\t\t});\n\t}\n\tconst pluginBeforeHooks = plugins.flatMap((plugin) => (plugin.hooks?.before ?? []).map((h) => {\n\t\thooksSourceWeakMap.set(h.handler, `plugin:${plugin.id}`);\n\t\treturn h;\n\t}));\n\tconst pluginAfterHooks = plugins.flatMap((plugin) => (plugin.hooks?.after ?? []).map((h) => {\n\t\thooksSourceWeakMap.set(h.handler, `plugin:${plugin.id}`);\n\t\treturn h;\n\t}));\n\tif (pluginBeforeHooks.length) beforeHooks.push(...pluginBeforeHooks);\n\tif (pluginAfterHooks.length) afterHooks.push(...pluginAfterHooks);\n\treturn {\n\t\tbeforeHooks,\n\t\tafterHooks\n\t};\n}\n/**\n* Run a single endpoint through the configured `hooks.before` / `hooks.after`\n* pipeline, normalizing the response, headers, and `APIError`s the same way a\n* router or `auth.api.*` dispatch does.\n*\n* This is the canonical hook runner. The HTTP router and `auth.api.*` reach it\n* through {@link toAuthEndpoints}. Plugins call it directly when they need to\n* re-enter the pipeline on purpose, such as resuming `/oauth2/authorize` after\n* a fresh sign-in. Calling an endpoint as a plain function deliberately skips\n* hooks; `dispatchAuthEndpoint` is the supported way to opt back in.\n*\n* @param endpoint The endpoint to dispatch.\n* @param input Input context whose `context` is an already-resolved `AuthContext`.\n*/\nasync function dispatchAuthEndpoint(endpoint, input) {\n\tconst withSpan = createWithSpan(input.context.options);\n\tconst operationId = input.operationId ?? getOperationId(endpoint);\n\tconst route = endpoint.path ?? \"/:virtual\";\n\tconst endpointMethod = endpoint.options?.method;\n\tconst defaultMethod = Array.isArray(endpointMethod) ? endpointMethod[0] : endpointMethod;\n\tconst methodName = input.method ?? input.request?.method ?? defaultMethod ?? \"?\";\n\tconst shouldReturnResponse = input.asResponse ?? isRequestLike(input.request);\n\tlet internalContext = {\n\t\t...input,\n\t\tcontext: {\n\t\t\t...input.context,\n\t\t\treturned: void 0,\n\t\t\tresponseHeaders: void 0,\n\t\t\tsession: input.context.session ?? null\n\t\t},\n\t\tpath: endpoint.path,\n\t\theaders: input.headers ? new Headers(input.headers) : void 0\n\t};\n\treturn withSpan(`${methodName} ${route}`, {\n\t\t[ATTR_HTTP_ROUTE]: route,\n\t\t[ATTR_OPERATION_ID]: operationId\n\t}, async () => runWithEndpointContext(internalContext, async () => {\n\t\tconst { beforeHooks, afterHooks } = getHooks(internalContext.context);\n\t\tconst before = await runBeforeHooks(internalContext, beforeHooks, endpoint, operationId);\n\t\tif (\"context\" in before && before.context && typeof before.context === \"object\") {\n\t\t\tconst { headers, ...rest } = before.context;\n\t\t\tif (headers) {\n\t\t\t\tif (!internalContext.headers) internalContext.headers = new Headers();\n\t\t\t\tconst requestHeaders = internalContext.headers;\n\t\t\t\theaders.forEach((value, key) => {\n\t\t\t\t\trequestHeaders.set(key, value);\n\t\t\t\t});\n\t\t\t}\n\t\t\tinternalContext = defuReplaceArrays(rest, internalContext);\n\t\t} else if (before) {\n\t\t\tconst responseHeaders = internalContext.context.responseHeaders;\n\t\t\treturn shouldReturnResponse ? toResponse(before, { headers: responseHeaders }) : input.returnHeaders ? {\n\t\t\t\theaders: responseHeaders,\n\t\t\t\tresponse: before\n\t\t\t} : before;\n\t\t}\n\t\tinternalContext.asResponse = false;\n\t\tinternalContext.returnHeaders = true;\n\t\tinternalContext.returnStatus = true;\n\t\tconst result = await runWithEndpointContext(internalContext, () => withSpan(`handler ${route}`, {\n\t\t\t[ATTR_HTTP_ROUTE]: route,\n\t\t\t[ATTR_OPERATION_ID]: operationId\n\t\t}, () => endpoint(internalContext))).catch((e) => {\n\t\t\tif (isAPIError(e)) return {\n\t\t\t\tresponse: e,\n\t\t\t\tstatus: e.statusCode,\n\t\t\t\theaders: mergeAPIErrorHeaders(e)\n\t\t\t};\n\t\t\tthrow e;\n\t\t});\n\t\tif (result instanceof Response) return result;\n\t\tinternalContext.context.returned = result.response;\n\t\tinternalContext.context.responseHeaders = result.headers ?? void 0;\n\t\tconst after = await runAfterHooks(internalContext, afterHooks, endpoint, operationId);\n\t\tif (after.response !== void 0) result.response = after.response;\n\t\tresult.headers = after.headers ?? result.headers;\n\t\tif (isAPIError(result.response) && shouldPublishLog(internalContext.context.logger.level, \"debug\")) result.response.stack = result.response.errorStack;\n\t\tif (isAPIError(result.response) && !shouldReturnResponse) {\n\t\t\tif (result.headers) Object.defineProperty(result.response, kAPIErrorHeaderSymbol, {\n\t\t\t\tenumerable: false,\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: false,\n\t\t\t\tvalue: result.headers\n\t\t\t});\n\t\t\tthrow result.response;\n\t\t}\n\t\treturn shouldReturnResponse ? toResponse(result.response, {\n\t\t\theaders: result.headers ?? void 0,\n\t\t\tstatus: result.status\n\t\t}) : input.returnHeaders ? input.returnStatus ? {\n\t\t\theaders: result.headers,\n\t\t\tresponse: result.response,\n\t\t\tstatus: result.status\n\t\t} : {\n\t\t\theaders: result.headers,\n\t\t\tresponse: result.response\n\t\t} : input.returnStatus ? {\n\t\t\tresponse: result.response,\n\t\t\tstatus: result.status\n\t\t} : result.response;\n\t}));\n}\n//#endregion\nexport { dispatchAuthEndpoint, getOperationId };\n","import { isLoopbackHost } from \"./host.mjs\";\nimport { DANGEROUS_URL_SCHEMES } from \"./url.mjs\";\nimport * as z from \"zod\";\n//#region src/utils/redirect-uri.ts\nconst REVERSE_DOMAIN_PRIVATE_USE_SCHEME = /^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i;\nconst NON_PRIVATE_USE_SCHEMES = new Set([\n\t\"http:\",\n\t\"https:\",\n\t\"ws:\",\n\t\"wss:\",\n\t\"file:\",\n\t\"ftp:\",\n\t\"mailto:\",\n\t\"javascript:\",\n\t\"data:\",\n\t\"vbscript:\",\n\t\"blob:\",\n\t\"about:\",\n\t\"view-source:\"\n]);\n/**\n* Returns whether a parsed redirect URI uses an authority-free, reverse-domain\n* private-use scheme as recommended by RFC 8252 §7.1.\n*/\nfunction isReverseDomainPrivateUseRedirectUri(uri) {\n\tconst scheme = uri.protocol.slice(0, -1);\n\tconst schemeSpecificPart = uri.href.slice(uri.protocol.length);\n\treturn uri.protocol !== \"http:\" && uri.protocol !== \"https:\" && uri.host.length === 0 && schemeSpecificPart.startsWith(\"/\") && !schemeSpecificPart.startsWith(\"//\") && REVERSE_DOMAIN_PRIVATE_USE_SCHEME.test(scheme);\n}\n/**\n* Returns whether a parsed redirect URI uses a non-reserved custom scheme with\n* an authority component and a path (for example\n* `cursor://anysphere.cursor-mcp/oauth/callback`).\n*\n* RFC 8252 §7.1 recommends the authority-free reverse-domain form, and §8.4\n* says authorization servers SHOULD reject schemes without a period. Better\n* Auth deliberately does not enforce either, because native MCP clients such\n* as Cursor register host-bearing, period-free URIs. Bare-authority forms\n* (`cursor://host`, `cursor://host?x=1`) are rejected because non-special\n* schemes parse an empty pathname. Web, script, and browser-internal schemes\n* in `NON_PRIVATE_USE_SCHEMES` are rejected; any other scheme is accepted.\n*\n* @see https://github.com/better-auth/better-auth/issues/10946\n*/\nfunction isHostBearingPrivateUseRedirectUri(uri) {\n\tif (NON_PRIVATE_USE_SCHEMES.has(uri.protocol)) return false;\n\tif (uri.host.length === 0) return false;\n\treturn uri.pathname.startsWith(\"/\");\n}\n/** RFC 8252 recommended form or a host-bearing non-reserved custom scheme. */\nfunction isNativePrivateUseRedirectUri(uri) {\n\treturn isReverseDomainPrivateUseRedirectUri(uri) || isHostBearingPrivateUseRedirectUri(uri);\n}\n/**\n* Zod schema for OAuth redirect URIs and other developer-supplied URLs that the\n* server stores and later hands back to a browser.\n*\n* - Rejects dangerous schemes (`javascript:`, `data:`, `vbscript:`).\n* - Rejects URIs with a fragment component (`#...`) per RFC 6749 §3.1.2.\n* - Requires HTTPS, except for loopback hosts (`127.0.0.0/8`, `[::1]`,\n* `*.localhost` per RFC 6761), where HTTP is allowed for local development.\n* - Allows custom schemes for mobile apps (e.g. `myapp://callback`).\n*\n* This is the single source of truth for redirect-URI validation across the\n* OAuth provider plugins. Consume it from `@better-auth/core/utils/redirect-uri`\n* rather than re-implementing the scheme policy per plugin.\n*/\nconst SafeUrlSchema = z.url().superRefine((val, ctx) => {\n\tlet u;\n\ttry {\n\t\tu = new URL(val);\n\t} catch {\n\t\tctx.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tmessage: \"URL must be parseable\",\n\t\t\tfatal: true\n\t\t});\n\t\treturn z.NEVER;\n\t}\n\tif (DANGEROUS_URL_SCHEMES.includes(u.protocol)) {\n\t\tctx.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tmessage: \"URL cannot use javascript:, data:, or vbscript: scheme\"\n\t\t});\n\t\treturn;\n\t}\n\tif (val.includes(\"#\")) ctx.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"Redirect URI must not contain a fragment component\"\n\t});\n\tif (u.protocol === \"http:\" && !isLoopbackHost(u.host)) ctx.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"Redirect URI must use HTTPS (HTTP allowed only for loopback hosts)\"\n\t});\n});\n//#endregion\nexport { SafeUrlSchema, isNativePrivateUseRedirectUri, isReverseDomainPrivateUseRedirectUri };\n","import { getCurrentAdapter } from \"@better-auth/core/context\";\n//#region src/plugins/jwt/adapter.ts\nconst getJwksAdapter = (baseAdapter, options) => {\n\treturn {\n\t\tgetAllKeys: async (ctx) => {\n\t\t\tif (options?.adapter?.getJwks) return await options.adapter.getJwks(ctx);\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).findMany({ model: \"jwks\" });\n\t\t},\n\t\tgetLatestKey: async (ctx) => {\n\t\t\tconst now = /* @__PURE__ */ new Date();\n\t\t\tconst isLive = (k) => !k.expiresAt || k.expiresAt > now;\n\t\t\tif (options?.adapter?.getJwks) return (await options.adapter.getJwks(ctx))?.filter(isLive).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())[0];\n\t\t\treturn (await (await getCurrentAdapter(baseAdapter)).findMany({ model: \"jwks\" }))?.filter(isLive).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())[0];\n\t\t},\n\t\t/**\n\t\t* Look up a key by its `id` (matches the JWS `kid` header). Returns\n\t\t* `undefined` when no key with that id exists.\n\t\t*\n\t\t* When `options.adapter.getJwks` is configured (custom keyring),\n\t\t* filters in-memory after fetching the full set — the custom adapter\n\t\t* isn't required to implement an id index.\n\t\t*/\n\t\tgetKeyById: async (ctx, id) => {\n\t\t\tif (options?.adapter?.getJwks) return (await options.adapter.getJwks(ctx))?.find((k) => k.id === id);\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).findOne({\n\t\t\t\tmodel: \"jwks\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: id\n\t\t\t\t}]\n\t\t\t}) ?? void 0;\n\t\t},\n\t\t/**\n\t\t* Find the most recent key matching a specific algorithm. Used when\n\t\t* a caller (e.g. an OAuth audience) specifies `signingAlgorithm` but\n\t\t* not a specific `kid`. Returns `undefined` if no key with the alg\n\t\t* exists — callers decide whether to mint one or reject.\n\t\t*\n\t\t* Legacy rows persisted before the `alg` column existed have\n\t\t* `alg: null`. Per `schema.ts`, those rows are treated as the\n\t\t* configured default alg (`options.jwks.keyPairConfig.alg ?? \"EdDSA\"`),\n\t\t* so deployments that have only legacy rows can still satisfy an\n\t\t* audience-pinned `signingAlgorithm` matching the default.\n\t\t*\n\t\t* Expired keys are filtered out here — see `getLatestKey` for\n\t\t* rationale.\n\t\t*/\n\t\tgetLatestKeyByAlg: async (ctx, alg) => {\n\t\t\tconst candidates = options?.adapter?.getJwks ? await options.adapter.getJwks(ctx) : await (await getCurrentAdapter(baseAdapter)).findMany({ model: \"jwks\" });\n\t\t\tif (!candidates) return void 0;\n\t\t\tconst configAlg = options?.jwks?.keyPairConfig?.alg ?? \"EdDSA\";\n\t\t\tconst now = /* @__PURE__ */ new Date();\n\t\t\treturn candidates.filter((k) => k.alg === alg || k.alg == null && configAlg === alg).filter((k) => !k.expiresAt || k.expiresAt > now).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())[0];\n\t\t},\n\t\tcreateJwk: async (ctx, webKey) => {\n\t\t\tif (options?.adapter?.createJwk) return await options.adapter.createJwk(webKey, ctx);\n\t\t\treturn await (await getCurrentAdapter(baseAdapter)).create({\n\t\t\t\tmodel: \"jwks\",\n\t\t\t\tdata: {\n\t\t\t\t\t...webKey,\n\t\t\t\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t};\n};\n//#endregion\nexport { getJwksAdapter };\n","import { sec } from \"../../utils/time.mjs\";\nimport { symmetricEncrypt } from \"../../crypto/index.mjs\";\nimport { getJwksAdapter } from \"./adapter.mjs\";\nimport { exportJWK, generateKeyPair } from \"jose\";\n//#region src/plugins/jwt/utils.ts\n/**\n* Converts an expirationTime to ISO seconds expiration time (the format of JWT exp)\n*\n* See https://github.com/panva/jose/blob/main/src/lib/jwt_claims_set.ts#L245\n*\n* @param expirationTime - see options.jwt.expirationTime\n* @param iat - the iat time to consolidate on\n* @returns\n*/\nfunction toExpJWT(expirationTime, iat) {\n\tif (typeof expirationTime === \"number\") return expirationTime;\n\telse if (expirationTime instanceof Date) return Math.floor(expirationTime.getTime() / 1e3);\n\telse return iat + sec(expirationTime);\n}\nasync function generateExportedKeyPair(options) {\n\tconst { alg, ...cfg } = options?.jwks?.keyPairConfig ?? {\n\t\talg: \"EdDSA\",\n\t\tcrv: \"Ed25519\"\n\t};\n\tconst { publicKey, privateKey } = await generateKeyPair(alg, {\n\t\t...cfg,\n\t\textractable: true\n\t});\n\treturn {\n\t\tpublicWebKey: await exportJWK(publicKey),\n\t\tprivateWebKey: await exportJWK(privateKey),\n\t\talg,\n\t\tcfg\n\t};\n}\n/**\n* Creates a Jwk on the database\n*\n* @param ctx\n* @param options\n* @returns\n*/\nasync function createJwk(ctx, options) {\n\tconst { publicWebKey, privateWebKey, alg, cfg } = await generateExportedKeyPair(options);\n\tconst explicitCrv = cfg && \"crv\" in cfg ? cfg.crv : void 0;\n\tconst derivedCrv = typeof publicWebKey.crv === \"string\" ? publicWebKey.crv : void 0;\n\tconst crv = explicitCrv ?? derivedCrv;\n\tconst stringifiedPrivateWebKey = JSON.stringify(privateWebKey);\n\tconst privateKeyEncryptionEnabled = !options?.jwks?.disablePrivateKeyEncryption;\n\tconst jwk = {\n\t\talg,\n\t\t...crv ? { crv } : {},\n\t\tpublicKey: JSON.stringify(publicWebKey),\n\t\tprivateKey: privateKeyEncryptionEnabled ? JSON.stringify(await symmetricEncrypt({\n\t\t\tkey: ctx.context.secretConfig,\n\t\t\tdata: stringifiedPrivateWebKey\n\t\t})) : stringifiedPrivateWebKey,\n\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\t...options?.jwks?.rotationInterval ? { expiresAt: new Date(Date.now() + options.jwks.rotationInterval * 1e3) } : {}\n\t};\n\treturn await getJwksAdapter(ctx.context.adapter, options).createJwk(ctx, jwk);\n}\n//#endregion\nexport { createJwk, generateExportedKeyPair, toExpJWT };\n","import { symmetricDecrypt } from \"../../crypto/index.mjs\";\nimport { getJwksAdapter } from \"./adapter.mjs\";\nimport { createJwk, toExpJWT } from \"./utils.mjs\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\nimport { SignJWT, importJWK } from \"jose\";\n//#region src/plugins/jwt/sign.ts\n/**\n* Resolves the JWKS signing key, decrypts it, and imports it\n* for use with jose's SignJWT. Returns null when signing is\n* delegated to a custom jwt.sign callback.\n*\n* Callers that need the signing algorithm before constructing\n* the JWT payload (e.g. for OIDC at_hash) should call this\n* first, read `.alg`, then pass the result to `signJWT` via\n* the `resolvedKey` option to avoid a redundant DB lookup.\n*\n* When `overrides.signingKeyId` or `overrides.signingAlgorithm` is set, key\n* selection follows the contract documented on {@link SigningKeyOverrides};\n* without overrides this returns the most recently created live key, falling\n* back to the primary `keyPairConfig.alg` when even that's absent so unpinned\n* tokens stay on the configured default algorithm even after extra algorithms\n* have been lazy-minted for audience pinning.\n*/\nasync function resolveSigningKey(ctx, options, overrides) {\n\tif (options?.jwt?.sign) return null;\n\tconst adapter = getJwksAdapter(ctx.context.adapter, options);\n\tlet key;\n\tif (overrides?.signingKeyId !== void 0) {\n\t\tkey = await adapter.getKeyById(ctx, overrides.signingKeyId);\n\t\tif (!key) throw new BetterAuthError(`signJWT: signingKeyId \"${overrides.signingKeyId}\" not found in JWKS. The key must be provisioned before it can be referenced.`);\n\t\tif (overrides.signingAlgorithm !== void 0) {\n\t\t\tconst configAlg = options?.jwks?.keyPairConfig?.alg ?? \"EdDSA\";\n\t\t\tif ((key.alg ?? configAlg) !== overrides.signingAlgorithm) throw new BetterAuthError(`signJWT: signingKeyId \"${overrides.signingKeyId}\" has alg \"${key.alg ?? `unset (inherits keyPairConfig.alg \"${configAlg}\")`}\" but signingAlgorithm was set to \"${overrides.signingAlgorithm}\".`);\n\t\t}\n\t} else if (overrides?.signingAlgorithm !== void 0) {\n\t\tkey = await adapter.getLatestKeyByAlg(ctx, overrides.signingAlgorithm);\n\t\tif (!key) {\n\t\t\tconst primaryAlg = options?.jwks?.keyPairConfig?.alg ?? \"EdDSA\";\n\t\t\tconst preconfig = options?.jwks?.keyPairConfigs?.find((c) => c.alg === overrides.signingAlgorithm);\n\t\t\tconst isPrimary = primaryAlg === overrides.signingAlgorithm;\n\t\t\tif (preconfig || isPrimary) key = await createJwk(ctx, {\n\t\t\t\t...options,\n\t\t\t\tjwks: {\n\t\t\t\t\t...options?.jwks,\n\t\t\t\t\tkeyPairConfig: preconfig ?? options?.jwks?.keyPairConfig\n\t\t\t\t}\n\t\t\t});\n\t\t\telse {\n\t\t\t\tconst advertisedExtra = options?.jwks?.keyPairConfigs?.map((c) => c.alg).join(\", \") || \"none\";\n\t\t\t\tthrow new BetterAuthError(`signJWT: no key with alg \"${overrides.signingAlgorithm}\" found in JWKS. The plugin auto-mints only one key matching keyPairConfig.alg=\"${primaryAlg}\"; additional algs configured via keyPairConfigs: ${advertisedExtra}. Add \"${overrides.signingAlgorithm}\" to jwks.keyPairConfigs so the plugin provisions it on first use, or mint the key explicitly via createJwk().`);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tconst primaryAlg = options?.jwks?.keyPairConfig?.alg ?? \"EdDSA\";\n\t\tkey = await adapter.getLatestKeyByAlg(ctx, primaryAlg) ?? await adapter.getLatestKey(ctx);\n\t}\n\tif (!key || key.expiresAt && key.expiresAt < /* @__PURE__ */ new Date()) {\n\t\tif (overrides?.signingKeyId !== void 0 || overrides?.signingAlgorithm !== void 0) throw new BetterAuthError(\"signJWT: requested signing key is expired and an explicit kid/alg was provided; not auto-minting a replacement. Rotate the key explicitly.\");\n\t\tkey = await createJwk(ctx, options);\n\t}\n\tconst privateWebKey = !options?.jwks?.disablePrivateKeyEncryption ? await symmetricDecrypt({\n\t\tkey: ctx.context.secretConfig,\n\t\tdata: JSON.parse(key.privateKey)\n\t}).catch(() => {\n\t\tthrow new BetterAuthError(\"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.\");\n\t}) : key.privateKey;\n\tconst alg = key.alg ?? options?.jwks?.keyPairConfig?.alg ?? \"EdDSA\";\n\tconst privateKey = await importJWK(JSON.parse(privateWebKey), alg);\n\treturn {\n\t\talg,\n\t\tkid: key.id,\n\t\tprivateKey\n\t};\n}\nasync function signJWT(ctx, config) {\n\tconst { options } = config;\n\tconst payload = config.payload;\n\tconst nowSeconds = Math.floor(Date.now() / 1e3);\n\tconst iat = payload.iat;\n\tlet exp = payload.exp;\n\tconst defaultExp = toExpJWT(options?.jwt?.expirationTime ?? \"15m\", iat ?? nowSeconds);\n\texp = exp ?? defaultExp;\n\tconst nbf = payload.nbf;\n\tconst baseURLOrigin = typeof ctx.context.options.baseURL === \"string\" ? ctx.context.options.baseURL : \"\";\n\tconst iss = payload.iss;\n\tconst defaultIss = options?.jwt?.issuer ?? baseURLOrigin;\n\tconst aud = payload.aud;\n\tconst defaultAud = options?.jwt?.audience ?? baseURLOrigin;\n\tif (options?.jwt?.sign) {\n\t\tconst jwtPayload = {\n\t\t\t...payload,\n\t\t\tiat,\n\t\t\texp,\n\t\t\tnbf,\n\t\t\tiss: iss ?? defaultIss,\n\t\t\taud: aud ?? defaultAud\n\t\t};\n\t\treturn options.jwt.sign(jwtPayload, config.header, {\n\t\t\tsigningKeyId: config.signingKeyId,\n\t\t\tsigningAlgorithm: config.signingAlgorithm\n\t\t});\n\t}\n\tconst { alg, kid, privateKey } = config.resolvedKey ?? await resolveSigningKey(ctx, options, {\n\t\tsigningKeyId: config.signingKeyId,\n\t\tsigningAlgorithm: config.signingAlgorithm\n\t});\n\tconst jwt = new SignJWT(payload).setProtectedHeader({\n\t\t...config.header,\n\t\talg,\n\t\tkid\n\t}).setExpirationTime(exp).setIssuer(iss ?? defaultIss).setAudience(aud ?? defaultAud);\n\tif (iat) jwt.setIssuedAt(iat);\n\tif (payload.sub) jwt.setSubject(payload.sub);\n\tif (payload.nbf) jwt.setNotBefore(payload.nbf);\n\tif (payload.jti) jwt.setJti(payload.jti);\n\treturn await jwt.sign(privateKey);\n}\nasync function getJwtToken(ctx, options) {\n\tconst payload = !options?.jwt?.definePayload ? ctx.context.session.user : await options.jwt.definePayload(ctx.context.session);\n\treturn await signJWT(ctx, {\n\t\toptions,\n\t\tpayload: {\n\t\t\tiat: Math.floor(Date.now() / 1e3),\n\t\t\t...payload,\n\t\t\tsub: await options?.jwt?.getSubject?.(ctx.context.session) ?? ctx.context.session.user.id\n\t\t}\n\t});\n}\n//#endregion\nexport { getJwtToken, resolveSigningKey, signJWT };\n","import { t as __exportAll } from \"./rolldown-runtime-wcPFST8Q.mjs\";\nimport { A as collectExtensionAccessTokenClaims, C as storeToken, E as validateClientCredentials, F as getExtensionGrantHandler, L as getSupportedGrantTypes, M as collectExtensionUserInfoClaims, R as hasUserInfoClaimExtension, T as toResourceList, a as getClient, b as resolveSubjectIdentifier, c as getStoredToken, h as parseClientMetadata, i as extractClientCredentials, j as collectExtensionIdTokenClaims, l as isPKCERequired, n as decryptStoredClientSecret, o as getJwtPlugin, p as normalizeTimestampValue, r as destructureCredentials, t as clientAllowsGrant, w as toAudienceClaim, y as resolveSessionAuthTime } from \"./utils-CGIZS-Da.mjs\";\nimport { APIError } from \"better-auth/api\";\nimport { generateRandomString, symmetricDecrypt, symmetricEncrypt } from \"better-auth/crypto\";\nimport { APIError as APIError$1 } from \"better-call\";\nimport { logger } from \"@better-auth/core/env\";\nimport * as z from \"zod\";\nimport { createDpopReplayStore, enforceDpopBinding, generateCodeChallenge, getConfirmationJkt, getDpopJktFromPayload, getJwks, isDpopBindingError, isDpopProofError, parseAccessTokenAuthorization, stripAccessTokenAuthorizationScheme, verifyDpopProof } from \"better-auth/oauth2\";\nimport { SignJWT, base64url, createLocalJWKSet, decodeProtectedHeader, jwtVerify } from \"jose\";\nimport { SafeUrlSchema } from \"@better-auth/core/utils/redirect-uri\";\nimport { resolveSigningKey, signJWT, toExpJWT } from \"better-auth/plugins\";\n//#region src/authentication-context.ts\nconst RESERVED_ID_TOKEN_CLAIMS = new Set([\n\t\"iss\",\n\t\"sub\",\n\t\"aud\",\n\t\"exp\",\n\t\"nbf\",\n\t\"iat\",\n\t\"jti\",\n\t\"auth_time\",\n\t\"nonce\",\n\t\"acr\",\n\t\"amr\",\n\t\"azp\",\n\t\"sid\",\n\t\"at_hash\",\n\t\"c_hash\",\n\t\"s_hash\"\n]);\n/**\n* Removes provider-owned ID token claim names from custom claims.\n*\n* `customIdTokenClaims` is an extension point for additional claims. It must not\n* replace the issuer, subject, audience, lifetime, nonce, authorized party,\n* token-binding hashes, session binding, or authentication context that the\n* provider owns.\n*/\nfunction stripReservedIdTokenClaims(claims) {\n\tif (!claims) return {};\n\tconst stripped = [];\n\tconst safeClaims = Object.create(null);\n\tfor (const [key, value] of Object.entries(claims)) {\n\t\tif (RESERVED_ID_TOKEN_CLAIMS.has(key)) {\n\t\t\tstripped.push(key);\n\t\t\tcontinue;\n\t\t}\n\t\tsafeClaims[key] = value;\n\t}\n\tif (stripped.length > 0) logger.warn(`oauth-provider: stripped reserved id-token claim name(s): ${stripped.join(\", \")}. The AS owns these claim values.`);\n\treturn safeClaims;\n}\n//#endregion\n//#region src/claims-request.ts\nconst claimRequestMemberSchema = z.record(z.string(), z.unknown()).nullable();\nconst acrClaimRequestMemberSchema = z.looseObject({\n\tessential: z.boolean().optional(),\n\tvalue: z.string().optional(),\n\tvalues: z.array(z.string()).optional()\n}).nullable();\nconst idTokenClaimsRequestSchema = z.object({ acr: acrClaimRequestMemberSchema.optional() }).catchall(claimRequestMemberSchema);\nconst oidcClaimsRequestObjectSchema = z.looseObject({\n\tuserinfo: z.record(z.string(), claimRequestMemberSchema).optional(),\n\tid_token: idTokenClaimsRequestSchema.optional()\n});\nfunction parseClaimsRequestValue(value) {\n\tif (typeof value === \"string\") try {\n\t\treturn JSON.parse(value);\n\t} catch {\n\t\treturn;\n\t}\n\treturn value;\n}\nfunction parseOidcClaimsRequestObject(value) {\n\tconst parsed = parseClaimsRequestValue(value);\n\tconst result = oidcClaimsRequestObjectSchema.safeParse(parsed);\n\treturn result.success ? result.data : void 0;\n}\nconst claimsRequestParameterValueSchema = z.union([z.string(), z.record(z.string(), z.unknown())]);\nconst claimsRequestInputSchema = claimsRequestParameterValueSchema;\nconst claimsRequestParameterSchema = claimsRequestParameterValueSchema.refine((value) => parseOidcClaimsRequestObject(value) !== void 0, { error: \"claims must be a valid Claims request object\" });\nfunction isValidOidcClaimsRequest(value) {\n\treturn value === void 0 || parseOidcClaimsRequestObject(value) !== void 0;\n}\nfunction getRequestedUserInfoClaims(value, supportedClaims) {\n\tconst userInfoClaims = parseOidcClaimsRequestObject(value)?.userinfo;\n\tif (!userInfoClaims) return [];\n\tconst names = Object.keys(userInfoClaims);\n\tif (!supportedClaims) return names;\n\tconst allowed = new Set(supportedClaims);\n\treturn names.filter((name) => allowed.has(name));\n}\nfunction canSatisfyEssentialAcrRequest(value, currentAcr) {\n\tconst claimsRequest = parseOidcClaimsRequestObject(value);\n\tif (!claimsRequest) return value === void 0;\n\tconst acrRequest = claimsRequest.id_token?.acr;\n\tif (!acrRequest || acrRequest.essential !== true) return true;\n\tconst valueMatches = acrRequest.value === void 0 || acrRequest.value === currentAcr;\n\tconst valuesMatch = acrRequest.values === void 0 || acrRequest.values.includes(currentAcr);\n\treturn valueMatches && valuesMatch;\n}\nfunction filterClaimsRequestUserInfoClaims(value, allowedUserInfoClaims) {\n\tconst claimsRequest = parseOidcClaimsRequestObject(value);\n\tif (!claimsRequest) return void 0;\n\tconst allowedClaimSet = new Set(allowedUserInfoClaims);\n\tconst userInfoClaims = Object.fromEntries(Object.entries(claimsRequest.userinfo ?? {}).filter(([claim]) => allowedClaimSet.has(claim)));\n\tconst filteredClaimsRequest = Object.keys(userInfoClaims).length ? {\n\t\t...claimsRequest,\n\t\tuserinfo: userInfoClaims\n\t} : Object.fromEntries(Object.entries(claimsRequest).filter(([key]) => key !== \"userinfo\"));\n\treturn Object.keys(filteredClaimsRequest).length ? filteredClaimsRequest : void 0;\n}\n//#endregion\n//#region src/standard-claims.ts\nfunction splitDisplayName(name) {\n\tconst parts = name.split(\" \").filter((part) => part !== \"\");\n\tif (parts.length <= 1) return {};\n\treturn {\n\t\tgiven: parts.slice(0, -1).join(\" \"),\n\t\tfamily: parts.at(-1)\n\t};\n}\n/**\n* The OIDC Standard Claims (OIDC Core §5.1) that Better Auth resolves from its\n* own user model, each paired with the scope that requests it (§5.4).\n*\n* This is the single source for UserInfo scope-claim resolution, individual\n* `claims.userinfo` resolution, the discovery `claims_supported` advertisement,\n* and the bound on requested claim names. Adding a standard claim Better Auth\n* can resolve means adding one entry here, not editing UserInfo, the metadata,\n* and the plugin init separately.\n*\n* These claims are delivered only at the UserInfo endpoint, never the ID token:\n* the authorization code flow always issues an access token, so §5.4 routes\n* scope-requested claims to UserInfo. Deployments that support further standard\n* profile claims (such as `birthdate` or `zoneinfo`) supply them through\n* `customUserInfoClaims` and advertise them in `claims_supported`.\n*/\nconst STANDARD_CLAIMS = {\n\tname: {\n\t\tscope: \"profile\",\n\t\tresolve: (user) => user.name ?? void 0\n\t},\n\tpicture: {\n\t\tscope: \"profile\",\n\t\tresolve: (user) => user.image ?? void 0\n\t},\n\tgiven_name: {\n\t\tscope: \"profile\",\n\t\tresolve: (user) => splitDisplayName(user.name).given\n\t},\n\tfamily_name: {\n\t\tscope: \"profile\",\n\t\tresolve: (user) => splitDisplayName(user.name).family\n\t},\n\temail: {\n\t\tscope: \"email\",\n\t\tresolve: (user) => user.email ?? void 0\n\t},\n\temail_verified: {\n\t\tscope: \"email\",\n\t\tresolve: (user) => user.emailVerified ?? false\n\t}\n};\nconst STANDARD_CLAIM_NAMES = Object.keys(STANDARD_CLAIMS);\n/**\n* The claim names this provider advertises it can supply (discovery\n* `claims_supported`): the operator's `advertisedMetadata.claims_supported`\n* override when set, otherwise the scope-derived standard set computed at plugin\n* init. Used both to advertise and to bound requested `claims.userinfo` names so\n* a client cannot pin arbitrary attacker-controlled strings onto stored tokens.\n*/\nfunction getSupportedClaims(opts) {\n\treturn opts.advertisedMetadata?.claims_supported ?? opts.claims ?? [];\n}\n//#endregion\n//#region src/claims.ts\n/**\n* Claim names the authorization server owns on a JWT access token, which no\n* claim source (the `customAccessTokenClaims` plugin option, an extension\n* contributor, or a resource row's `customClaims`) may override. The AS is the\n* only source of truth for issuer identity, subject, audience, lifetime, scope,\n* authentication context, the token's stable ID, and its sender-constraint\n* (`cnf`).\n*\n* @see RFC 9068 §2.2 (registered access-token claims)\n* @see RFC 7800 / RFC 9449 §6 (`cnf` confirmation — the token's bound key)\n*/\nconst RESERVED_ACCESS_TOKEN_CLAIMS = new Set([\n\t\"iss\",\n\t\"sub\",\n\t\"aud\",\n\t\"exp\",\n\t\"iat\",\n\t\"jti\",\n\t\"client_id\",\n\t\"scope\",\n\t\"auth_time\",\n\t\"acr\",\n\t\"amr\",\n\t\"cnf\"\n]);\n/**\n* Returns a copy of `claims` with reserved AS-owned names removed. Emits a\n* `warn` naming the stripped keys when any were present (never silently\n* dropped: surfacing the override attempt matters more than minimizing log\n* noise). Stable iteration order (`Object.entries`) is preserved so token-debug\n* logs stay reproducible across runs.\n*/\nfunction stripReservedClaims(claims) {\n\tif (!claims) return {};\n\tconst stripped = [];\n\tconst safe = {};\n\tfor (const [key, value] of Object.entries(claims)) {\n\t\tif (RESERVED_ACCESS_TOKEN_CLAIMS.has(key)) {\n\t\t\tstripped.push(key);\n\t\t\tcontinue;\n\t\t}\n\t\tsafe[key] = value;\n\t}\n\tif (stripped.length > 0) logger.warn(`oauth-provider: stripped reserved access-token claim name(s): ${stripped.join(\", \")}. The AS owns these claim values.`);\n\treturn safe;\n}\n/**\n* The single authority for the enriched (non-AS-owned) claim set an access\n* token carries. Both the JWT mint and the opaque-token introspection\n* re-derive path call this function, so the two formats cannot drift, and\n* reserved RFC 9068 names are stripped unconditionally here so no caller can\n* forget to.\n*\n* Precedence, lowest to highest: extension contributors < per-issuance\n* `accessTokenClaims` < plugin `customAccessTokenClaims` < per-resource\n* `customClaims`. Reserved names are removed from the merged result.\n*\n* Returns only the enriched claims; the caller stamps the AS-owned claims\n* (`iss`/`sub`/`aud`/`exp`/`iat`/`jti`/`client_id`/`scope`/...) itself, so they\n* always win.\n*/\nasync function resolveAccessTokenClaims(input) {\n\tconst { ctx, opts, user, client, scopes, resources, referenceId, metadata, grantType, sessionId, perRequestClaims, resourcePolicyClaims } = input;\n\tconst extensionClaims = await collectExtensionAccessTokenClaims(opts, {\n\t\tctx,\n\t\topts,\n\t\tuser,\n\t\tclient,\n\t\tscopes,\n\t\tgrantType,\n\t\treferenceId,\n\t\tsessionId,\n\t\tresources,\n\t\tmetadata\n\t});\n\tconst pluginClaims = opts.customAccessTokenClaims ? await opts.customAccessTokenClaims({\n\t\tuser,\n\t\tscopes,\n\t\tresources,\n\t\treferenceId,\n\t\tmetadata\n\t}) : {};\n\treturn stripReservedClaims({\n\t\t...extensionClaims,\n\t\t...perRequestClaims ?? {},\n\t\t...pluginClaims,\n\t\t...resourcePolicyClaims\n\t});\n}\n//#endregion\n//#region src/types/zod.ts\nconst DANGEROUS_SCHEMES = [\n\t\"javascript:\",\n\t\"data:\",\n\t\"vbscript:\"\n];\n/**\n* Validates an RFC 8707 resource indicator. The value must be an absolute URI\n* with no fragment (RFC 8707 §2). Unlike a redirect URI it is not restricted to\n* HTTPS, because a resource server identifier may use any absolute URI scheme;\n* configured OAuth resources are the authoritative control over\n* which resources a token may target.\n*/\nconst ResourceUriSchema = z.string().superRefine((val, ctx) => {\n\tif (!URL.canParse(val)) {\n\t\tctx.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tmessage: \"resource must be an absolute URI\",\n\t\t\tfatal: true\n\t\t});\n\t\treturn z.NEVER;\n\t}\n\tif (val.includes(\"#\")) {\n\t\tctx.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tmessage: \"resource must not contain a fragment\"\n\t\t});\n\t\treturn;\n\t}\n\tif (DANGEROUS_SCHEMES.includes(new URL(val).protocol)) ctx.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"resource cannot use javascript:, data:, or vbscript: scheme\"\n\t});\n});\nconst authorizationPromptTokenSchema = z.enum([\n\t\"none\",\n\t\"consent\",\n\t\"login\",\n\t\"create\",\n\t\"select_account\"\n]);\nconst authorizationPromptSchema = z.string().superRefine((value, ctx) => {\n\tconst promptTokens = value.split(\" \").map((token) => token.trim()).filter(Boolean);\n\tconst promptSet = /* @__PURE__ */ new Set();\n\tif (!promptTokens.length) {\n\t\tctx.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tmessage: \"prompt must include at least one value\"\n\t\t});\n\t\treturn;\n\t}\n\tfor (const token of promptTokens) {\n\t\tconst result = authorizationPromptTokenSchema.safeParse(token);\n\t\tif (!result.success) {\n\t\t\tctx.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tmessage: `unsupported prompt value: ${token}`\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tpromptSet.add(result.data);\n\t}\n\tif (promptSet.has(\"none\") && promptSet.size > 1) ctx.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"prompt=none cannot be combined with other prompt values\"\n\t});\n});\n/** Canonical RFC 7517 JWK Set metadata for an OAuth client. */\nconst clientJwksSchema = z.object({ keys: z.array(z.record(z.string(), z.unknown())).min(1) });\nconst maxAgeSchema = z.union([z.number(), z.string().trim().min(1)]).transform((value, ctx) => {\n\tconst maxAge = typeof value === \"number\" ? value : Number(value);\n\tif (!Number.isInteger(maxAge) || maxAge < 0) {\n\t\tctx.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tmessage: \"max_age must be a non-negative integer\"\n\t\t});\n\t\treturn z.NEVER;\n\t}\n\treturn maxAge;\n});\nconst dpopJktSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/, \"dpop_jkt must be a base64url-encoded SHA-256 JWK thumbprint\");\n/**\n* Runtime schema for OAuthAuthorizationQuery.\n* Uses passthrough to tolerate fields added by future extensions (PAR, FPA, etc.)\n*/\nconst authorizationQuerySchema = z.object({\n\tresponse_type: z.string().pipe(z.enum([\"code\"])).optional(),\n\trequest: z.string().optional(),\n\trequest_uri: z.string().optional(),\n\tredirect_uri: SafeUrlSchema.optional(),\n\tscope: z.string().optional(),\n\tstate: z.string().optional(),\n\tclient_id: z.string().min(1, \"client_id is required\"),\n\tprompt: authorizationPromptSchema.optional(),\n\tdisplay: z.string().optional(),\n\tui_locales: z.string().optional(),\n\tmax_age: maxAgeSchema.optional(),\n\tacr_values: z.string().optional(),\n\tlogin_hint: z.string().optional(),\n\tid_token_hint: z.string().optional(),\n\tcode_challenge: z.string().optional(),\n\tcode_challenge_method: z.string().pipe(z.enum([\"S256\"])).optional(),\n\tnonce: z.string().optional(),\n\tclaims: claimsRequestInputSchema.optional(),\n\tdpop_jkt: dpopJktSchema.optional(),\n\tresource: z.union([ResourceUriSchema, z.array(ResourceUriSchema).min(1)]).optional()\n}).passthrough();\nconst storedAuthorizationQuerySchema = authorizationQuerySchema.extend({\n\tredirect_uri: SafeUrlSchema.optional(),\n\tclaims: claimsRequestParameterSchema.optional()\n});\n/**\n* Runtime schema for the authorization code verification value.\n* Validates structure on deserialization from the JSON blob stored in the DB.\n* Uses passthrough so future fields (e.g. from authorization challenge) don't break parsing.\n*/\nconst verificationValueSchema = z.object({\n\ttype: z.literal(\"authorization_code\"),\n\tquery: storedAuthorizationQuerySchema,\n\tsessionId: z.string(),\n\tuserId: z.string(),\n\treferenceId: z.string().optional(),\n\tauthTime: z.number().optional(),\n\tresource: z.array(z.string()).optional()\n}).passthrough();\n/**\n* Request body accepted at `POST /oauth2/register` (RFC 7591 §2 client\n* metadata). This is the single source of truth for the registration contract:\n* the endpoint validates against it and {@link ClientRegistrationRequest} is\n* inferred from it, so the type a `validateInitialAccessToken` callback receives\n* always matches what is actually validated. `grant_types` and\n* `token_endpoint_auth_method` are open strings because extensions can register\n* custom values. Server-assigned fields (`client_id`, `client_secret`, the\n* issued/expiry timestamps) and internal state (`disabled`, `reference_id`) are\n* never part of a registration request.\n*\n* @see https://datatracker.ietf.org/doc/html/rfc7591#section-2\n*/\nconst clientRegistrationRequestSchema = z.object({\n\tredirect_uris: z.array(SafeUrlSchema).min(1).optional(),\n\tscope: z.string().optional(),\n\tclient_name: z.string().refine((value) => value.trim().length > 0, \"client_name cannot be empty\").optional(),\n\tclient_uri: z.string().optional(),\n\tlogo_uri: z.string().optional(),\n\tcontacts: z.array(z.string().min(1)).min(1).optional(),\n\ttos_uri: z.string().optional(),\n\tpolicy_uri: z.string().optional(),\n\tsoftware_id: z.string().optional(),\n\tsoftware_version: z.string().optional(),\n\tsoftware_statement: z.string().optional(),\n\tpost_logout_redirect_uris: z.array(SafeUrlSchema).min(1).optional(),\n\tbackchannel_logout_uri: SafeUrlSchema.optional(),\n\tbackchannel_logout_session_required: z.boolean().optional(),\n\ttoken_endpoint_auth_method: z.string().trim().min(1).optional(),\n\tjwks: clientJwksSchema.optional(),\n\tjwks_uri: z.string().optional(),\n\tgrant_types: z.array(z.string().trim().min(1)).min(1).optional(),\n\tresponse_types: z.array(z.enum([\"code\"])).optional(),\n\tapplication_type: z.enum([\"web\", \"native\"]).optional(),\n\tsubject_type: z.enum([\"public\", \"pairwise\"]).optional(),\n\tdpop_bound_access_tokens: z.boolean().optional(),\n\tresources: z.array(ResourceUriSchema).optional(),\n\tskip_consent: z.never({ error: \"skip_consent cannot be set during dynamic client registration\" }).optional()\n});\n/**\n* Complete OAuth client metadata document schema shared by registration and\n* verified client-discovery integrations.\n*\n* Unlike {@link clientRegistrationRequestSchema}, a metadata document carries\n* its own identifier and may contain the server-assigned secret fields that a\n* discovery profile must explicitly prohibit. Keeping those fields in the\n* parsed shape lets profile validation distinguish a forbidden value from an\n* unknown extension without unsafe casts or ad-hoc allowlists.\n*/\nconst oauthClientMetadataSchema = clientRegistrationRequestSchema.omit({ skip_consent: true }).extend({\n\tclient_id: z.string().refine((value) => value.trim().length > 0, \"client_id cannot be empty\"),\n\tclient_secret: z.string().optional(),\n\tclient_secret_expires_at: z.number().int().nonnegative().optional(),\n\tclient_id_issued_at: z.number().int().nonnegative().optional()\n}).loose();\n//#endregion\n//#region src/resources.ts\n/**\n* Source-of-truth list of asymmetric JWS algorithms supported by the JWT\n* plugin. Mirrors the {@link JWSAlgorithms} literal-union type from\n* `packages/better-auth/src/plugins/jwt/types.ts`. Kept as a runtime const\n* so the admin-CRUD zod schema AND the seed-config validator can reject\n* bad values up-front rather than surfacing opaque jose errors at issuance.\n*\n* MUST stay in sync with `JWSAlgorithms`. The type-level guard immediately\n* below fails the typecheck if the two drift.\n*/\nconst JWS_ALGORITHMS = [\n\t\"EdDSA\",\n\t\"ES256\",\n\t\"ES512\",\n\t\"PS256\",\n\t\"RS256\"\n];\nconst JWS_ALGORITHM_SET = new Set(JWS_ALGORITHMS);\n/**\n* Upper bound on how many entries are accepted in a JWT's `aud` claim during\n* introspection / revocation validation. Without a cap, a hostile or replayed\n* token can supply hundreds of fake resource identifiers and amplify load on\n* the resource table (one DB lookup per unique unrecognized entry). Real-world\n* deployments use single-digit resource lists; 64 is a generous ceiling that\n* stays well clear of any legitimate use and bounds the per-request DB fan-out.\n*\n* RFC 7519 §4.1.3 does not specify a maximum, so this is a defensive limit,\n* not a spec one. Tokens that exceed it are treated as invalid (introspect →\n* `active: false`, revoke → no-op) rather than triggering the lookup path.\n*\n* @internal\n*/\nconst MAX_AUD_VALUES = 64;\n/**\n* Validates a resource `identifier` per RFC 8707 §2 (absolute URI, no\n* fragment), honoring {@link OAuthOptions.identifierValidator} when provided.\n*\n* Returns a structured result so callers can decide whether to throw\n* (admin CRUD / DCR) or warn-and-skip (config seed path).\n*\n* @internal\n*/\nasync function checkIdentifier(opts, identifier) {\n\tconst customValidator = opts.identifierValidator;\n\tif (customValidator) {\n\t\tif (!await customValidator(identifier)) return {\n\t\t\tok: false,\n\t\t\treason: `resource identifier ${identifier} failed validation`\n\t\t};\n\t\treturn { ok: true };\n\t}\n\tconst parsed = ResourceUriSchema.safeParse(identifier);\n\tif (!parsed.success) return {\n\t\tok: false,\n\t\treason: `resource identifier ${identifier} is invalid: ${parsed.error.issues[0]?.message ?? \"not an absolute URI\"}`\n\t};\n\treturn { ok: true };\n}\n/**\n* Variant of {@link checkIdentifier} that throws `invalid_target` on failure.\n* Used by admin CRUD endpoints where validation failure is a client error.\n*\n* @internal\n*/\nasync function assertIdentifierValid(opts, identifier) {\n\tconst result = await checkIdentifier(opts, identifier);\n\tif (!result.ok) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_target\",\n\t\terror_description: result.reason\n\t});\n}\n/**\n* The OIDC userinfo endpoint's resource identifier. Always accepted as an\n* implicit `aud` value when `openid` is in scope — not looked up against\n* `oauthResource` rows.\n*/\nconst userInfoResource = (baseURL) => `${baseURL}/oauth2/userinfo`;\n/**\n* Re-parses a request's raw `application/x-www-form-urlencoded` body to\n* recover every value of the repeated `resource` parameter (RFC 8707 §2).\n*\n* Workaround for better-call's form-body parser (better-call ≤1.3.5), which\n* collapses repeated form keys with last-write-wins. A client sending\n* `resource=https://a&resource=https://b` would otherwise arrive in the\n* handler as `{ resource: \"https://b\" }`, silently narrowing the issued\n* token's `aud` to a single resource.\n*\n* Returns the full ordered list when the body is form-encoded and contains\n* any `resource` entries; `undefined` otherwise. Caller MUST enable\n* `cloneRequest: true` on the endpoint — the body stream is read here a\n* second time, and that only works when better-call cloned the request\n* before its own parse.\n*\n* Note: the URL-encoded body path is the only one affected. The query-string\n* path (e.g. `/oauth2/authorize?resource=…&resource=…`) is parsed by the\n* router itself, which DOES array-promote duplicate keys correctly.\n*\n* @internal\n*/\nasync function extractRepeatedResourceFromForm(request) {\n\tif (!(request.headers.get(\"content-type\")?.toLowerCase() ?? \"\").includes(\"application/x-www-form-urlencoded\")) return;\n\tlet text;\n\ttry {\n\t\ttext = await request.clone().text();\n\t} catch {\n\t\treturn;\n\t}\n\tif (!text) return void 0;\n\tconst values = new URLSearchParams(text).getAll(\"resource\").filter((value) => value.length > 0);\n\treturn values.length > 0 ? values : void 0;\n}\n/**\n* Normalizes a `resource` parameter into an array. Accepts the RFC 8707\n* forms: a single string, a string[], or undefined.\n*\n* @internal\n*/\nfunction normalizeResourceParam(resource) {\n\tif (resource === void 0 || resource === null) return void 0;\n\tif (typeof resource === \"string\") return [resource];\n\tif (Array.isArray(resource)) {\n\t\tconst result = resource.filter((r) => typeof r === \"string\" && r.length > 0);\n\t\treturn result.length > 0 ? result : void 0;\n\t}\n}\n/**\n* Validates a JWT `aud` claim against the OAuth resource model.\n*\n* Every non-implicit audience value must resolve to an `oauthResource` row.\n* Disabled rows still pass because disabling blocks new issuance; deleting the\n* row is the operation that invalidates already-issued tokens.\n*\n* @internal\n*/\nasync function isAudienceClaimAllowed(ctx, opts, audienceClaim, implicitAudiences = []) {\n\tif (audienceClaim === void 0) return true;\n\tconst audienceValues = Array.isArray(audienceClaim) ? audienceClaim : [audienceClaim];\n\tif (audienceValues.length > MAX_AUD_VALUES) return false;\n\tconst implicitAudienceSet = new Set(implicitAudiences);\n\tconst resourcesToLookup = /* @__PURE__ */ new Set();\n\tfor (const audienceValue of audienceValues) {\n\t\tif (implicitAudienceSet.has(audienceValue)) continue;\n\t\tresourcesToLookup.add(audienceValue);\n\t}\n\tif (resourcesToLookup.size === 0) return true;\n\treturn (await Promise.all(Array.from(resourcesToLookup, (resource) => getResource(ctx, opts, resource)))).every(Boolean);\n}\n/**\n* Resolves the resource policy for a request.\n*\n* Validation steps (RFC 8707 §3 + per-resource policy):\n*\n* 1. Resolve `resource` parameter to a list of identifiers.\n* 2. For each identifier, look up the {@link OAuthResource} row.\n* - Missing → `invalid_target`.\n* - `disabled` → `invalid_target` (no new issuance).\n* 3. If {@link OAuthOptions.enforcePerClientResources} resolves to true,\n* confirm the client is linked to every requested resource via\n* `oauthClientResource`. Unlinked → `invalid_target`.\n* 4. Intersect `requestedScopes` with each resource's `allowedScopes`.\n* Empty intersection → `invalid_scope`.\n* 5. Pick the minimum `accessTokenTtl` across requested resources.\n* 6. Pick signing config — only honored for single-resource requests\n* (a JWT can only have one signature).\n* 7. Merge per-resource `customClaims` (returned raw; reserved-claim\n* stripping is owned by `resolveAccessTokenClaims`).\n*\n* When no `resource` param is present, returns an empty policy: no `aud`\n* claim and no resource-specific overrides.\n*\n* @internal\n*/\nasync function resolveResourcePolicy(ctx, opts, params) {\n\tconst requestedResources = normalizeResourceParam(params.resource);\n\tconst includesOpenid = params.requestedScopes.includes(\"openid\");\n\tconst userInfoResourceIdentifier = userInfoResource(ctx.context.baseURL ?? \"\");\n\tif (!requestedResources) return {\n\t\taudienceClaim: void 0,\n\t\taccessTokenTtl: null,\n\t\trefreshTokenTtl: null,\n\t\tsigningAlgorithm: null,\n\t\tsigningKeyId: null,\n\t\trawCustomClaims: {},\n\t\tdpopBoundAccessTokensRequired: false,\n\t\teffectiveScopes: [...params.requestedScopes]\n\t};\n\tconst uniqueRequestedResources = [...new Set(requestedResources)];\n\tconst resolved = [];\n\tfor (const identifier of uniqueRequestedResources) {\n\t\tif (identifier === userInfoResourceIdentifier) continue;\n\t\tconst row = await getResource(ctx, opts, identifier);\n\t\tif (row) {\n\t\t\tif (row.disabled) throw new APIError(\"BAD_REQUEST\", {\n\t\t\t\terror: \"invalid_target\",\n\t\t\t\terror_description: `requested resource ${identifier} is disabled`\n\t\t\t});\n\t\t\tresolved.push(row);\n\t\t\tcontinue;\n\t\t}\n\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_target\",\n\t\t\terror_description: `requested resource ${identifier} is not configured`\n\t\t});\n\t}\n\tconst { value: enforcePerClient } = resolveEnforcePerClientResources(opts);\n\tif (enforcePerClient && resolved.length > 0) await assertClientLinkedToResources(ctx, opts, params.clientId, resolved);\n\tlet effectiveScopes = [...params.requestedScopes];\n\tfor (const row of resolved) {\n\t\tif (row.allowedScopes === null || row.allowedScopes === void 0) continue;\n\t\tconst allowed = new Set(row.allowedScopes);\n\t\tconst intersection = effectiveScopes.filter((s) => allowed.has(s));\n\t\tif (intersection.length === 0) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_scope\",\n\t\t\terror_description: `none of the requested scopes are allowed for resource ${row.identifier}`\n\t\t});\n\t\teffectiveScopes = intersection;\n\t}\n\tlet accessTokenTtl = null;\n\tlet refreshTokenTtl = null;\n\tfor (const row of resolved) {\n\t\tif (row.accessTokenTtl != null) accessTokenTtl = accessTokenTtl === null ? row.accessTokenTtl : Math.min(accessTokenTtl, row.accessTokenTtl);\n\t\tif (row.refreshTokenTtl != null) refreshTokenTtl = refreshTokenTtl === null ? row.refreshTokenTtl : Math.min(refreshTokenTtl, row.refreshTokenTtl);\n\t}\n\tconst uniqueSigningAlgs = /* @__PURE__ */ new Set();\n\tconst uniqueSigningKids = /* @__PURE__ */ new Set();\n\tfor (const row of resolved) {\n\t\tif (row.signingAlgorithm) uniqueSigningAlgs.add(row.signingAlgorithm);\n\t\tif (row.signingKeyId) uniqueSigningKids.add(row.signingKeyId);\n\t}\n\tif (uniqueSigningAlgs.size > 1) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_request\",\n\t\terror_description: \"multi-resource request has conflicting signingAlgorithm pins; a single JWS signature cannot satisfy multiple algorithms\"\n\t});\n\tif (uniqueSigningKids.size > 1) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_request\",\n\t\terror_description: \"multi-resource request has conflicting signingKeyId pins; a single JWS signature cannot satisfy multiple key ids\"\n\t});\n\tconst signingAlgorithm = uniqueSigningAlgs.values().next().value ?? null;\n\tconst signingKeyId = uniqueSigningKids.values().next().value ?? null;\n\tconst mergedClaims = {};\n\tfor (const row of resolved) if (row.customClaims && typeof row.customClaims === \"object\") Object.assign(mergedClaims, row.customClaims);\n\tconst dpopBoundAccessTokensRequired = resolved.some((row) => row.dpopBoundAccessTokensRequired === true);\n\tconst audienceIdentifiers = includesOpenid ? [...uniqueRequestedResources, userInfoResourceIdentifier] : uniqueRequestedResources;\n\tconst audClaim = [...new Set(audienceIdentifiers)];\n\treturn {\n\t\taudienceClaim: audClaim.length === 1 ? audClaim[0] : audClaim,\n\t\taccessTokenTtl,\n\t\trefreshTokenTtl,\n\t\tsigningAlgorithm,\n\t\tsigningKeyId,\n\t\trawCustomClaims: mergedClaims,\n\t\tdpopBoundAccessTokensRequired,\n\t\teffectiveScopes\n\t};\n}\n/**\n* Throws `invalid_target` if the client isn't linked to every resource via\n* the `oauthClientResource` join table. Issues one `findMany` per call.\n*\n* @internal\n*/\nasync function assertClientLinkedToResources(ctx, opts, clientId, resources) {\n\tif (resources.length === 0) return;\n\tconst modelName = opts.schema?.oauthClientResource?.modelName ?? \"oauthClientResource\";\n\tconst links = await ctx.context.adapter.findMany({\n\t\tmodel: modelName,\n\t\twhere: [{\n\t\t\tfield: \"clientId\",\n\t\t\tvalue: clientId\n\t\t}]\n\t});\n\tconst linkedSet = new Set(links?.map((l) => l.resourceId) ?? []);\n\tconst unlinked = resources.filter((resource) => !linkedSet.has(resource.identifier));\n\tif (unlinked.length > 0) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_target\",\n\t\terror_description: `client ${clientId} is not linked to resource(s) ${unlinked.map((resource) => resource.identifier).join(\", \")}`\n\t});\n}\n/**\n* Returns `true` when `clientId` is linked, via the `oauthClientResource` join\n* table, to at least one of `resourceIdentifiers`. Authorizes cross-client token\n* introspection (RFC 7662 §2.1/§4): a resource server may introspect a token\n* whose audience it serves, even when a different client issued the token.\n*\n* @internal\n*/\nasync function isClientLinkedToAnyResource(ctx, opts, clientId, resourceIdentifiers) {\n\tif (resourceIdentifiers.length === 0) return false;\n\tconst modelName = opts.schema?.oauthClientResource?.modelName ?? \"oauthClientResource\";\n\treturn ((await ctx.context.adapter.findMany({\n\t\tmodel: modelName,\n\t\twhere: [{\n\t\t\tfield: \"clientId\",\n\t\t\tvalue: clientId\n\t\t}, {\n\t\t\tfield: \"resourceId\",\n\t\t\toperator: \"in\",\n\t\t\tvalue: resourceIdentifiers\n\t\t}],\n\t\tlimit: 1\n\t}))?.length ?? 0) > 0;\n}\n/**\n* Merges `customClaims` from the existing rows of `resourceIdentifiers` in\n* order (later resources win on collision). Missing rows are skipped; disabled\n* rows are included, since an already-issued token keeps its claims until it\n* expires. Returned raw; `resolveAccessTokenClaims` strips reserved names.\n*\n* Unlike {@link resolveResourcePolicy}, this applies none of the new-issuance\n* gates (disabled, scope allowlist, client linkage), so it is the right way to\n* re-derive claims for an already-issued token at introspection.\n*\n* @internal\n*/\nasync function getResourceCustomClaims(ctx, opts, resourceIdentifiers) {\n\tif (resourceIdentifiers.length === 0) return {};\n\tconst rows = await ctx.context.adapter.findMany({\n\t\tmodel: opts.schema?.oauthResource?.modelName ?? \"oauthResource\",\n\t\twhere: [{\n\t\t\tfield: \"identifier\",\n\t\t\toperator: \"in\",\n\t\t\tvalue: resourceIdentifiers\n\t\t}]\n\t});\n\tconst rowByIdentifier = new Map(rows.map((row) => [row.identifier, row]));\n\tconst merged = {};\n\tfor (const identifier of resourceIdentifiers) {\n\t\tconst row = rowByIdentifier.get(identifier);\n\t\tif (row?.customClaims && typeof row.customClaims === \"object\") Object.assign(merged, row.customClaims);\n\t}\n\treturn merged;\n}\n/**\n* Resolves the effective {@link OAuthOptions.enforcePerClientResources} value.\n*\n* - Explicit `true | false` always wins (`source: \"explicit\"`).\n* - Otherwise resolve to `true` (`source: \"default\"`). RFC 8707 §3 per-client\n* validation is the secure default.\n*\n* Deterministic and pure — safe to call on every validation pass.\n*/\nfunction resolveEnforcePerClientResources(opts) {\n\tif (opts.enforcePerClientResources !== void 0) return {\n\t\tvalue: opts.enforcePerClientResources,\n\t\tsource: \"explicit\"\n\t};\n\treturn {\n\t\tvalue: true,\n\t\tsource: \"default\"\n\t};\n}\n/**\n* In-process cache of {@link OAuthResource} rows, keyed by `identifier`.\n*\n* Opt-in via {@link OAuthOptions.cachedResources} (same membership-Set pattern\n* as `cachedTrustedClients`). Resources outside the set are looked up from the\n* DB on every request — the safe default for deployments that edit rows\n* through external tooling.\n*\n* Module-scoped so admin CRUD handlers can invalidate from anywhere via\n* {@link invalidateResourceCache}.\n*/\nconst resourceCache = /* @__PURE__ */ new Map();\n/**\n* Removes an entry from the resource cache. Called by admin CRUD handlers\n* after every write. Pass no argument to clear the entire cache.\n*\n* @internal\n*/\nfunction invalidateResourceCache(identifier) {\n\tif (identifier === void 0) {\n\t\tresourceCache.clear();\n\t\treturn;\n\t}\n\tresourceCache.delete(identifier);\n}\n/**\n* Looks up an {@link OAuthResource} by `identifier`, consulting the in-process\n* cache when the identifier is in {@link OAuthOptions.cachedResources}.\n*\n* Triggers the lazy seed via {@link seedResourcesOnce} on first call — the\n* retry path when the startup seed failed (database unreachable, or\n* migrations run after plugin init). The seed is idempotent and coalesced,\n* so the cost is paid only once per process.\n*\n* Returns a defensive copy so callers can't mutate cached state.\n*\n* @internal\n*/\nasync function getResource(ctx, opts, identifier) {\n\tawait seedResourcesOnce(ctx.context, opts);\n\tif (opts.cachedResources?.has(identifier)) {\n\t\tconst cached = resourceCache.get(identifier);\n\t\tif (cached) return Object.assign({}, cached);\n\t}\n\tconst dbResource = await ctx.context.adapter.findOne({\n\t\tmodel: opts.schema?.oauthResource?.modelName ?? \"oauthResource\",\n\t\twhere: [{\n\t\t\tfield: \"identifier\",\n\t\t\tvalue: identifier\n\t\t}]\n\t});\n\tif (dbResource && opts.cachedResources?.has(identifier)) resourceCache.set(identifier, Object.assign({}, dbResource));\n\treturn dbResource;\n}\n/**\n* Default `name` value when an input doesn't provide one. Mirrors what most\n* admin UIs would show.\n*/\nfunction defaultName(input) {\n\treturn input.name ?? input.identifier;\n}\n/**\n* Coerces seed-config `resources` entries — string or object form — into a\n* normalized list of {@link OAuthResourceInput}.\n*\n* @internal\n*/\nfunction collectResourceInputs(opts) {\n\tconst inputs = [];\n\tif (opts.resources?.length) for (const entry of opts.resources) inputs.push(typeof entry === \"string\" ? { identifier: entry } : entry);\n\treturn inputs;\n}\n/**\n* Builds the row payload sent to the adapter for a seed insert. All policy\n* columns default to `null` (= inherit plugin default at issuance time)\n* when the input doesn't specify a value.\n*/\nfunction buildSeedRow(input, now) {\n\treturn {\n\t\tidentifier: input.identifier,\n\t\tname: defaultName(input),\n\t\taccessTokenTtl: input.accessTokenTtl ?? null,\n\t\trefreshTokenTtl: input.refreshTokenTtl ?? null,\n\t\tsigningAlgorithm: input.signingAlgorithm ?? null,\n\t\tsigningKeyId: input.signingKeyId ?? null,\n\t\tallowedScopes: input.allowedScopes ?? null,\n\t\tcustomClaims: input.customClaims ?? null,\n\t\tdpopBoundAccessTokensRequired: input.dpopBoundAccessTokensRequired ?? false,\n\t\tdisabled: input.disabled ?? false,\n\t\tpolicyVersion: 1,\n\t\tmetadata: input.metadata ?? null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t};\n}\n/**\n* Builds the partial update payload when re-seeding an existing row.\n*\n* - `overwrite` mode replaces every policy column with the input value\n* (omitted fields fall back to `null` to clear stale state).\n* - `merge` mode updates only fields present in the input — admin edits to\n* other fields are preserved.\n*/\nfunction buildSeedUpdate(input, mode, now) {\n\tif (mode === \"overwrite\") {\n\t\tconst { identifier: _identifier, createdAt: _createdAt, ...rest } = buildSeedRow(input, now);\n\t\treturn rest;\n\t}\n\tconst update = { updatedAt: now };\n\tif (input.name !== void 0) update.name = input.name;\n\tif (input.accessTokenTtl !== void 0) update.accessTokenTtl = input.accessTokenTtl;\n\tif (input.refreshTokenTtl !== void 0) update.refreshTokenTtl = input.refreshTokenTtl;\n\tif (input.signingAlgorithm !== void 0) update.signingAlgorithm = input.signingAlgorithm;\n\tif (input.signingKeyId !== void 0) update.signingKeyId = input.signingKeyId;\n\tif (input.allowedScopes !== void 0) update.allowedScopes = input.allowedScopes;\n\tif (input.customClaims !== void 0) update.customClaims = input.customClaims;\n\tif (input.dpopBoundAccessTokensRequired !== void 0) update.dpopBoundAccessTokensRequired = input.dpopBoundAccessTokensRequired;\n\tif (input.disabled !== void 0) update.disabled = input.disabled;\n\tif (input.metadata !== void 0) update.metadata = input.metadata;\n\treturn update;\n}\n/**\n* Pattern matched against adapter errors to detect the \"table not yet\n* created\" case — i.e. migrations or `auth generate` haven't run. Only\n* used to keep the expected startup seed failure quiet.\n*\n* Covers SQLite (\"no such table\"), Postgres (\"relation X does not exist\"),\n* MySQL (\"Table X does not exist\" / contracted form), and the Drizzle and\n* Prisma adapters' missing-model errors.\n*/\nconst MISSING_TABLE_PATTERN = /no such table|relation.*does not exist|table.*does(?: not|n'?t) exist|model.*(?:does not exist|was not found in the schema)/i;\n/**\n* Logs a failed startup seed. Missing tables are expected before migrations\n* and stay quiet; anything else is an error worth seeing.\n*\n* @internal\n*/\nfunction logStartupSeedFailure(ctx, error) {\n\tlet missingTable = false;\n\tlet current = error;\n\tfor (let depth = 0; current && !missingTable && depth < 5; depth++) {\n\t\tmissingTable = MISSING_TABLE_PATTERN.test(current instanceof Error ? current.message : String(current));\n\t\tcurrent = current instanceof Error ? current.cause : void 0;\n\t}\n\tif (missingTable) {\n\t\tctx.logger.debug(\"oauth-provider: oauthResource table not yet created; deferring resource seed to first access.\");\n\t\treturn;\n\t}\n\tctx.logger.error(\"oauth-provider: could not seed `resources` at startup; retrying on first resource access.\", error);\n}\n/**\n* Lazy-seed state per adapter and plugin options. A module-level boolean would\n* let one Better Auth instance suppress seeding for every later instance in the\n* same process. Endpoint `AuthContext` objects are not guaranteed to be stable\n* across requests, so the adapter identifies the backing store, and the options\n* object separates instances that share an adapter but configure different\n* `resources`.\n*/\nlet seedStates = /* @__PURE__ */ new WeakMap();\nfunction getSeedState(ctx, opts) {\n\tconst adapterKey = ctx.adapter;\n\tlet byOptions = seedStates.get(adapterKey);\n\tif (!byOptions) {\n\t\tbyOptions = /* @__PURE__ */ new WeakMap();\n\t\tseedStates.set(adapterKey, byOptions);\n\t}\n\tconst existing = byOptions.get(opts);\n\tif (existing) return existing;\n\tconst created = {\n\t\tcompleted: false,\n\t\tpromise: null\n\t};\n\tbyOptions.set(opts, created);\n\treturn created;\n}\n/**\n* Seeds `oauthResource` rows from plugin config.\n*\n* Behavior is controlled by {@link OAuthOptions.resourceSeedMode}:\n*\n* - `\"insertOnly\"` (default, safe): inserts rows whose `identifier` is not\n* already present. Existing rows are untouched — admin edits via CRUD\n* are never reverted on restart.\n* - `\"merge\"`: inserts missing rows; updates only specified fields for\n* existing rows. Useful when config holds the \"preferred defaults\" but\n* admins customize per-row.\n* - `\"overwrite\"`: inserts missing rows; replaces every policy column on\n* existing rows with the config value (omitted fields → null). Use only\n* when config is the single source of truth.\n*\n* Race-safety: the `identifier` column carries a UNIQUE constraint, so two\n* processes booting simultaneously can each attempt the insert — one wins,\n* the other re-reads the row and treats the failed insert as a no-op.\n*\n* Throws on storage errors, including a missing table. Callers go through\n* {@link seedResourcesOnce}, which resets so the next resource access\n* retries (e.g. after migrations run).\n*\n* Idempotent: safe to call multiple times.\n*\n* @internal\n*/\nasync function seedResources(ctx, opts) {\n\tconst inputs = collectResourceInputs(opts);\n\tif (inputs.length === 0) return;\n\tconst mode = opts.resourceSeedMode ?? \"insertOnly\";\n\tconst modelName = opts.schema?.oauthResource?.modelName ?? \"oauthResource\";\n\tfor (const rawInput of inputs) {\n\t\tconst check = await checkIdentifier(opts, rawInput.identifier);\n\t\tif (!check.ok) {\n\t\t\tlogger.warn(`oauth-provider: skipping resource seed for ${rawInput.identifier} — ${check.reason}`);\n\t\t\tcontinue;\n\t\t}\n\t\tlet input = rawInput;\n\t\tif (input.signingAlgorithm != null && !JWS_ALGORITHM_SET.has(input.signingAlgorithm)) {\n\t\t\tlogger.warn(`oauth-provider: dropping unsupported signingAlgorithm \"${input.signingAlgorithm}\" for resource ${input.identifier} — must be one of ${JWS_ALGORITHMS.join(\", \")}. Continuing without an algorithm override.`);\n\t\t\tconst { signingAlgorithm: _, ...rest } = input;\n\t\t\tinput = rest;\n\t\t}\n\t\tconst where = [{\n\t\t\tfield: \"identifier\",\n\t\t\tvalue: input.identifier\n\t\t}];\n\t\tconst existing = await ctx.adapter.findOne({\n\t\t\tmodel: modelName,\n\t\t\twhere\n\t\t});\n\t\tconst now = /* @__PURE__ */ new Date();\n\t\tif (!existing) try {\n\t\t\tawait ctx.adapter.create({\n\t\t\t\tmodel: modelName,\n\t\t\t\tdata: buildSeedRow(input, now)\n\t\t\t});\n\t\t\tcontinue;\n\t\t} catch (err) {\n\t\t\tif (!await ctx.adapter.findOne({\n\t\t\t\tmodel: modelName,\n\t\t\t\twhere\n\t\t\t}).catch(() => null)) throw err;\n\t\t}\n\t\tif (mode === \"insertOnly\") continue;\n\t\tawait ctx.adapter.update({\n\t\t\tmodel: modelName,\n\t\t\twhere,\n\t\t\tupdate: buildSeedUpdate(input, mode, now)\n\t\t});\n\t}\n}\n/**\n* Idempotent, coalesced wrapper around {@link seedResources}, called from\n* plugin `init` and from every resource lookup. The first call runs the\n* seed, concurrent calls await the same promise, and calls after a success\n* are no-ops. A failure resets the state so the next call retries.\n*\n* @internal\n*/\nasync function seedResourcesOnce(ctx, opts) {\n\tconst state = getSeedState(ctx, opts);\n\tif (state.completed === true) return;\n\tif (state.promise !== null) return state.promise;\n\tstate.promise = seedResources(ctx, opts).then(() => {\n\t\tstate.completed = true;\n\t}).catch((err) => {\n\t\tstate.promise = null;\n\t\tthrow err;\n\t});\n\treturn state.promise;\n}\n/**\n* Logs the resolved value of {@link OAuthOptions.enforcePerClientResources}\n* so deployment admins see which default applied at init. Separated from\n* {@link resolveEnforcePerClientResources} so the latter stays pure and\n* cheap to call from validation flow.\n*\n* @internal\n*/\nfunction logEnforcePerClientResourcesResolution(opts) {\n\tconst resolved = resolveEnforcePerClientResources(opts);\n\tlogger.info(`oauth-provider: enforcePerClientResources resolved to ${resolved.value} (${resolved.source})`);\n}\n//#endregion\n//#region src/dpop.ts\nfunction getDpopProofJwt(ctx) {\n\treturn ctx.headers?.get(\"dpop\") ?? void 0;\n}\nfunction getEndpointUrl(ctx, path) {\n\treturn ctx.request?.url ?? `${ctx.context.baseURL}${path}`;\n}\n//#endregion\n//#region src/oauthClient/client-credentials.ts\nconst USER_DELEGATED_SCOPES = new Set([\n\t\"openid\",\n\t\"profile\",\n\t\"email\",\n\t\"offline_access\"\n]);\nfunction isUserDelegatedScope(scope) {\n\treturn USER_DELEGATED_SCOPES.has(scope);\n}\nfunction normalizeClientCredentialsScopes(scopes) {\n\treturn [...new Set(scopes.map((scope) => scope.trim()).filter(Boolean))];\n}\nfunction validateClientCredentialsScopes(scopes, grantTypes, tokenEndpointAuthMethod, opts) {\n\tif (scopes.length === 0) return;\n\tif (!grantTypes.includes(\"client_credentials\")) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_client_metadata\",\n\t\terror_description: \"client_credentials_scopes requires the client_credentials grant\"\n\t});\n\tif (tokenEndpointAuthMethod === \"none\") throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_client_metadata\",\n\t\terror_description: \"public clients cannot be assigned client_credentials scopes\"\n\t});\n\tconst providerScopes = new Set(opts.scopes ?? []);\n\tconst invalidScopes = scopes.filter((scope) => !providerScopes.has(scope) || isUserDelegatedScope(scope));\n\tif (invalidScopes.length > 0) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_scope\",\n\t\terror_description: `The following client_credentials scopes are invalid: ${invalidScopes.join(\", \")}`\n\t});\n}\n//#endregion\n//#region src/userinfo.ts\n/**\n* Builds the standard OIDC claims (OIDC Core §5.1) for the UserInfo response.\n*\n* A claim is included when its backing scope was granted, or when it was named\n* individually through the `claims.userinfo` request parameter (§5.4, §5.5).\n* `sub` is always present. Values come from the one claim registry, so the\n* advertisement, the scope mapping, and the resolution cannot drift apart.\n*\n* @see https://openid.net/specs/openid-connect-core-1_0.html#NormalClaims\n*/\nfunction userNormalClaims(user, scopes, requestedClaims = []) {\n\tconst requested = new Set(requestedClaims);\n\tconst claims = { sub: user.id ?? void 0 };\n\tfor (const [name, definition] of Object.entries(STANDARD_CLAIMS)) if (scopes.includes(definition.scope) || requested.has(name)) claims[name] = definition.resolve(user);\n\treturn claims;\n}\n/**\n* Returns the defined-valued entries of `claims`, dropping any key already\n* present in `base` when given.\n*\n* This is the two-tier claim authority shared by the /userinfo response and the\n* ID token:\n* - Called WITH `base` (the provider's own claims): the additive rule for\n* third-party extension claims. A contributor may add new keys but never\n* replace a claim the provider already owns.\n* - Called WITHOUT `base`: the deliberate first-party override path for the\n* operator's own `customUserInfoClaims` / `customIdTokenClaims`, which is\n* trusted to override identity claims (for example a formatted `name`). The\n* caller re-pins `sub` afterwards, so subject integrity holds either way\n* (OIDC Core §5.3.2: UserInfo `sub` MUST match the ID Token `sub`).\n*/\nfunction pickClaims(claims, base) {\n\tconst next = {};\n\tfor (const [key, value] of Object.entries(claims ?? {})) {\n\t\tif (value === void 0) continue;\n\t\tif (base && key in base) continue;\n\t\tnext[key] = value;\n\t}\n\treturn next;\n}\nfunction getUserInfoAccessToken(ctx) {\n\tconst authorization = ctx.headers?.get(\"authorization\");\n\tconst headerAccessTokenAuthorization = parseAccessTokenAuthorization(authorization);\n\tconst bodyToken = ctx.request?.method === \"POST\" ? ctx.body?.access_token ?? void 0 : void 0;\n\tif (headerAccessTokenAuthorization && bodyToken) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"Multiple access token transport methods are not allowed\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst accessTokenAuthorization = headerAccessTokenAuthorization ?? (bodyToken ? {\n\t\tscheme: \"Bearer\",\n\t\ttoken: bodyToken\n\t} : void 0);\n\treturn {\n\t\tauthorization: accessTokenAuthorization,\n\t\ttoken: accessTokenAuthorization?.token\n\t};\n}\n/**\n* Handles the /oauth2/userinfo endpoint\n*/\nasync function userInfoEndpoint(ctx, opts) {\n\tconst { authorization: accessTokenAuthorization } = getUserInfoAccessToken(ctx);\n\tif (!accessTokenAuthorization?.token) throw new APIError(\"UNAUTHORIZED\", {\n\t\terror_description: \"access token not found\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst { payload: jwt, requestedUserInfoClaims: requestedClaims } = await requireActiveAccessTokenWithClaims(ctx, opts, accessTokenAuthorization.token);\n\tif (getDpopJktFromPayload(jwt) && !ctx.request) throw new APIError(\"UNAUTHORIZED\", {\n\t\terror_description: \"DPoP-bound access token requires an HTTP request context\",\n\t\terror: \"invalid_token\"\n\t});\n\ttry {\n\t\tawait enforceDpopBinding({\n\t\t\tpayload: jwt,\n\t\t\tauthorization: accessTokenAuthorization,\n\t\t\tproofJwt: getDpopProofJwt(ctx),\n\t\t\tmethod: ctx.request?.method ?? \"GET\",\n\t\t\turl: getEndpointUrl(ctx, \"/oauth2/userinfo\"),\n\t\t\tproofMaxAgeSeconds: opts.dpop?.proofMaxAgeSeconds,\n\t\t\tsigningAlgorithms: opts.dpop?.signingAlgorithms,\n\t\t\treplayStore: createDpopReplayStore(ctx.context.internalAdapter)\n\t\t});\n\t} catch (error) {\n\t\tif (isDpopBindingError(error)) throw new APIError(\"UNAUTHORIZED\", {\n\t\t\terror_description: error.message,\n\t\t\terror: error.code\n\t\t});\n\t\tthrow error;\n\t}\n\tconst scopes = jwt.scope?.split(\" \");\n\tif (!scopes?.includes(\"openid\")) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"Missing required scope\",\n\t\terror: \"invalid_scope\"\n\t});\n\tif (!jwt.sub) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"user not found\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst user = await ctx.context.internalAdapter.findUserById(jwt.sub);\n\tif (!user) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"user not found\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst baseUserClaims = userNormalClaims(user, scopes ?? [], requestedClaims);\n\tconst clientId = jwt.client_id ?? jwt.azp;\n\tconst client = clientId && (opts.pairwiseSecret || hasUserInfoClaimExtension(opts)) ? await getClient(ctx, opts, clientId) : void 0;\n\tif (opts.pairwiseSecret && client) baseUserClaims.sub = await resolveSubjectIdentifier(user.id, client, opts);\n\tconst extensionUserClaims = scopes?.length ? await collectExtensionUserInfoClaims(opts, {\n\t\tctx,\n\t\topts,\n\t\tuser,\n\t\tscopes,\n\t\tjwt,\n\t\tclient: client ?? void 0,\n\t\trequestedClaims\n\t}) : {};\n\tconst additionalInfoUserClaims = opts.customUserInfoClaims && scopes?.length ? await opts.customUserInfoClaims({\n\t\tuser,\n\t\tscopes,\n\t\tjwt,\n\t\trequestedClaims\n\t}) : {};\n\treturn {\n\t\t...baseUserClaims,\n\t\t...pickClaims(extensionUserClaims, baseUserClaims),\n\t\t...pickClaims(additionalInfoUserClaims),\n\t\tsub: baseUserClaims.sub\n\t};\n}\n//#endregion\n//#region src/token.ts\nconst ID_TOKEN_SCOPE_CLAIM_GUARDS = Object.fromEntries(STANDARD_CLAIM_NAMES.map((name) => [name, void 0]));\n/**\n* Token presentation scheme implied by a confirmation: a DPoP key thumbprint\n* (`jkt`) yields `\"DPoP\"`; any other confirmation (including mTLS `x5t#S256`)\n* keeps `\"Bearer\"`, since that constraint lives at the TLS layer.\n*/\nfunction confirmationTokenType(confirmation) {\n\treturn getConfirmationJkt(confirmation) ? \"DPoP\" : \"Bearer\";\n}\nconst JWT_ACCESS_TOKEN_TYPE = \"at+jwt\";\n/**\n* Handles the /oauth2/token endpoint by delegating\n* the grant types\n*/\nasync function tokenEndpoint(ctx, opts) {\n\tconst grantType = ctx.body.grant_type;\n\tif (!getSupportedGrantTypes(opts).includes(grantType)) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: `unsupported grant_type ${grantType}`,\n\t\terror: \"unsupported_grant_type\"\n\t});\n\tswitch (grantType) {\n\t\tcase \"authorization_code\": return handleAuthorizationCodeGrant(ctx, opts);\n\t\tcase \"client_credentials\": return handleClientCredentialsGrant(ctx, opts);\n\t\tcase \"refresh_token\": return handleRefreshTokenGrant(ctx, opts);\n\t\tdefault: {\n\t\t\tconst handler = getExtensionGrantHandler(opts, grantType);\n\t\t\tif (handler) return handler({\n\t\t\t\tctx,\n\t\t\t\topts,\n\t\t\t\tgrantType,\n\t\t\t\tprovider: getOAuthProviderApi(ctx, opts, grantType)\n\t\t\t});\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\terror_description: `unsupported grant_type ${grantType}`,\n\t\t\t\terror: \"unsupported_grant_type\"\n\t\t\t});\n\t\t}\n\t}\n}\n/**\n* Returns the OAuth Provider's server-side capability surface bound to `ctx`.\n* The token endpoint passes one (pre-bound to the dispatched grant) to each\n* extension grant handler; a companion plugin's own endpoint calls this directly\n* with its grant type. `grantType` is bound here, not per issuance, so a handler\n* cannot mislabel the grant; omit it for capabilities that do not issue tokens\n* (`getClient`, `validateAccessToken`, `requireActiveAccessToken`), and\n* `issueTokens` then throws.\n*/\nfunction getOAuthProviderApi(ctx, opts, grantType) {\n\treturn {\n\t\tgetClient: (clientId) => getClient(ctx, opts, clientId),\n\t\tauthenticateClient: async (request) => {\n\t\t\tconst { clientId, clientSecret, preVerified, authMethod, confirmation } = destructureCredentials(await extractClientCredentials(ctx, opts, `${ctx.context.baseURL}${ctx.path ?? \"/oauth2/token\"}`));\n\t\t\tif (!clientId) throw new APIError(\"BAD_REQUEST\", {\n\t\t\t\terror_description: \"Missing required client_id\",\n\t\t\t\terror: \"invalid_request\"\n\t\t\t});\n\t\t\tif (request?.requireCredentials !== false && !clientSecret && !preVerified) throw new APIError(\"BAD_REQUEST\", {\n\t\t\t\terror_description: \"Missing required client credentials\",\n\t\t\t\terror: \"invalid_client\"\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tclientId,\n\t\t\t\tclient: await validateClientCredentials(ctx, opts, clientId, clientSecret, request?.scopes, preVerified, grantType, authMethod),\n\t\t\t\tmethod: authMethod,\n\t\t\t\tconfirmation\n\t\t\t};\n\t\t},\n\t\tissueTokens: (params) => {\n\t\t\tif (!grantType) throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n\t\t\t\terror_description: \"issueTokens requires a grant type; pass it to getOAuthProviderApi(ctx, opts, grantType).\",\n\t\t\t\terror: \"server_error\"\n\t\t\t});\n\t\t\treturn createUserTokens(ctx, opts, {\n\t\t\t\t...params,\n\t\t\t\tgrantType\n\t\t\t});\n\t\t},\n\t\thashToken: (token, type) => storeToken(opts.storeTokens, token, type),\n\t\tvalidateAccessToken: async (token, clientId) => {\n\t\t\tconst { validateAccessToken } = await Promise.resolve().then(() => introspect_exports);\n\t\t\treturn validateAccessToken(ctx, opts, token, clientId);\n\t\t},\n\t\trequireActiveAccessToken: async (token, clientId) => {\n\t\t\tconst { requireActiveAccessToken } = await Promise.resolve().then(() => introspect_exports);\n\t\t\treturn requireActiveAccessToken(ctx, opts, token, clientId);\n\t\t}\n\t};\n}\nasync function createJwtAccessToken(ctx, opts, user, client, audienceClaim, scopes, overrides) {\n\tconst iat = overrides?.iat ?? Math.floor(Date.now() / 1e3);\n\tconst exp = overrides?.exp ?? iat + (opts.accessTokenExpiresIn ?? 3600);\n\tconst jwtPluginOptions = getJwtPlugin(ctx.context).options;\n\tconst subject = user?.id ?? client.clientId;\n\treturn signJWT(ctx, {\n\t\toptions: jwtPluginOptions,\n\t\theader: { typ: JWT_ACCESS_TOKEN_TYPE },\n\t\tsigningKeyId: overrides?.signingKeyId ?? void 0,\n\t\tsigningAlgorithm: overrides?.signingAlgorithm ?? void 0,\n\t\tpayload: {\n\t\t\t...overrides?.accessTokenClaims ?? {},\n\t\t\tsub: subject,\n\t\t\taud: toAudienceClaim(audienceClaim),\n\t\t\tclient_id: client.clientId,\n\t\t\tazp: client.clientId,\n\t\t\tscope: scopes.join(\" \"),\n\t\t\tsid: overrides?.sid,\n\t\t\tiss: jwtPluginOptions?.jwt?.issuer ?? ctx.context.baseURL,\n\t\t\tiat,\n\t\t\texp,\n\t\t\tjti: generateRandomString(32),\n\t\t\t...overrides?.confirmation ? { cnf: overrides.confirmation } : {}\n\t\t}\n\t});\n}\n/**\n* Computes an OIDC hash (at_hash, c_hash) per OIDC Core §3.1.3.6.\n* Hashes the token, takes the left half, and base64url-encodes it.\n*/\nasync function computeOidcHash(token, signingAlg) {\n\tlet hashAlg;\n\tif (signingAlg === \"EdDSA\") hashAlg = \"SHA-512\";\n\telse if (signingAlg.endsWith(\"384\")) hashAlg = \"SHA-384\";\n\telse if (signingAlg.endsWith(\"512\")) hashAlg = \"SHA-512\";\n\telse hashAlg = \"SHA-256\";\n\tconst digest = new Uint8Array(await crypto.subtle.digest(hashAlg, new TextEncoder().encode(token)));\n\treturn base64url.encode(digest.slice(0, digest.length / 2));\n}\n/**\n* Creates a user id token in code_authorization with scope of 'openid'\n* and hybrid/implicit (not yet implemented) flows\n*/\nasync function createIdToken(ctx, opts, user, client, scopes, nonce, sessionId, authTime, accessToken, extraClaims) {\n\tconst iat = Math.floor(Date.now() / 1e3);\n\tconst exp = iat + (opts.idTokenExpiresIn ?? 36e3);\n\tconst resolvedSub = await resolveSubjectIdentifier(user.id, client, opts);\n\tconst authTimeSec = authTime != null ? Math.floor(authTime.getTime() / 1e3) : void 0;\n\tconst customClaims = stripReservedIdTokenClaims(opts.customIdTokenClaims ? await opts.customIdTokenClaims({\n\t\tuser,\n\t\tscopes,\n\t\tmetadata: parseClientMetadata(client.metadata)\n\t}) : void 0);\n\tconst jwtPluginOptions = opts.disableJwtPlugin ? void 0 : getJwtPlugin(ctx.context).options;\n\tconst resolvedKey = !opts.disableJwtPlugin && !jwtPluginOptions?.jwt?.sign ? await resolveSigningKey(ctx, jwtPluginOptions) : void 0;\n\tconst signingAlg = opts.disableJwtPlugin ? \"HS256\" : resolvedKey?.alg ?? jwtPluginOptions?.jwks?.keyPairConfig?.alg;\n\tconst atHash = accessToken ? await computeOidcHash(accessToken, signingAlg) : void 0;\n\tconst emitSid = Boolean(client.enableEndSession || client.backchannelLogoutUri);\n\tconst payload = {\n\t\t...ID_TOKEN_SCOPE_CLAIM_GUARDS,\n\t\tauth_time: authTimeSec,\n\t\tacr: \"0\",\n\t\t...customClaims,\n\t\tat_hash: atHash,\n\t\tiss: jwtPluginOptions?.jwt?.issuer ?? ctx.context.baseURL,\n\t\tsub: resolvedSub,\n\t\taud: client.clientId,\n\t\tnonce,\n\t\tiat,\n\t\texp,\n\t\tsid: emitSid ? sessionId : void 0\n\t};\n\tconst additiveClaims = stripReservedIdTokenClaims(extraClaims);\n\tObject.assign(payload, pickClaims(additiveClaims, payload));\n\tif (opts.disableJwtPlugin && !client.clientSecret) return;\n\tconst idToken = opts.disableJwtPlugin ? await new SignJWT(payload).setProtectedHeader({ alg: \"HS256\" }).sign(new TextEncoder().encode(await decryptStoredClientSecret(ctx, opts.storeClientSecret, client.clientSecret))) : await signJWT(ctx, {\n\t\toptions: jwtPluginOptions,\n\t\tpayload,\n\t\tresolvedKey: resolvedKey ?? void 0\n\t});\n\tif (idToken && atHash && jwtPluginOptions?.jwt?.sign) {\n\t\tconst header = decodeProtectedHeader(idToken);\n\t\tif (header.alg !== signingAlg) throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n\t\t\terror_description: `ID token signed with \"${header.alg}\" but at_hash was computed for \"${signingAlg}\". Ensure jwt.sign uses the algorithm declared in keyPairConfig.alg.`,\n\t\t\terror: \"server_error\"\n\t\t});\n\t}\n\treturn idToken;\n}\n/**\n* Encodes a refresh token for a client\n*/\nasync function encodeRefreshToken(opts, token, sessionId) {\n\treturn (opts.prefix?.refreshToken ?? \"\") + (opts.formatRefreshToken?.encrypt ? opts.formatRefreshToken.encrypt(token, sessionId) : token);\n}\n/**\n* Decodes a refresh token for a client\n*\n* @internal\n*/\nasync function decodeRefreshToken(opts, token) {\n\tif (opts.prefix?.refreshToken) if (token.startsWith(opts.prefix.refreshToken)) token = token.replace(opts.prefix.refreshToken, \"\");\n\telse throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"refresh token not found\",\n\t\terror: \"invalid_token\"\n\t});\n\treturn opts.formatRefreshToken?.decrypt ? opts.formatRefreshToken?.decrypt(token) : { token };\n}\nasync function createOpaqueAccessToken(ctx, opts, user, client, scopes, payload, resources, referenceId, authorizationCodeId, refreshId, confirmation, requestedUserInfoClaims) {\n\tconst iat = payload.iat ?? Math.floor(Date.now() / 1e3);\n\tconst exp = payload?.exp ?? iat + (opts.accessTokenExpiresIn ?? 3600);\n\tconst token = opts.generateOpaqueAccessToken ? await opts.generateOpaqueAccessToken() : generateRandomString(32, \"A-Z\", \"a-z\");\n\tawait ctx.context.adapter.create({\n\t\tmodel: \"oauthAccessToken\",\n\t\tdata: {\n\t\t\ttoken: await storeToken(opts.storeTokens, token, \"access_token\"),\n\t\t\tclientId: client.clientId,\n\t\t\tsessionId: payload?.sid,\n\t\t\tuserId: user?.id,\n\t\t\treferenceId,\n\t\t\tauthorizationCodeId,\n\t\t\tresources,\n\t\t\trefreshId,\n\t\t\tconfirmation,\n\t\t\trequestedUserInfoClaims: requestedUserInfoClaims?.length ? requestedUserInfoClaims : void 0,\n\t\t\tscopes,\n\t\t\tcreatedAt: /* @__PURE__ */ new Date(iat * 1e3),\n\t\t\texpiresAt: /* @__PURE__ */ new Date(exp * 1e3)\n\t\t}\n\t});\n\treturn (opts.prefix?.opaqueAccessToken ?? \"\") + token;\n}\n/**\n* Tear down the entire refresh-token family for a (client, user) pair, plus\n* any access tokens that reference those refresh rows, per RFC 9700 §4.14.\n* Access tokens are deleted first so the parent rows' foreign-key children\n* do not block the refresh-row delete.\n*\n* TODO(invalidate-family-race): the two `deleteMany` calls are not atomic\n* with respect to each other. Between them, a concurrent rotation in a\n* different worker can `create` a fresh refresh row (and, immediately after,\n* an access-token row referencing it) for the same (client, user) pair,\n* leaving the family partially rebuilt and the new refresh row orphaned of\n* any deletion. Closing this window requires the same transactional adapter\n* contract tracked under FIXME(strict-family-invalidation) in\n* `createRefreshToken`.\n*\n* @internal\n*/\nasync function invalidateRefreshFamily(ctx, clientId, userId) {\n\tconst refreshTokens = await ctx.context.adapter.findMany({\n\t\tmodel: \"oauthRefreshToken\",\n\t\twhere: [{\n\t\t\tfield: \"clientId\",\n\t\t\tvalue: clientId\n\t\t}, {\n\t\t\tfield: \"userId\",\n\t\t\tvalue: userId\n\t\t}]\n\t});\n\tif (refreshTokens.length) await ctx.context.adapter.deleteMany({\n\t\tmodel: \"oauthAccessToken\",\n\t\twhere: [{\n\t\t\tfield: \"refreshId\",\n\t\t\toperator: \"in\",\n\t\t\tvalue: refreshTokens.map((r) => r.id)\n\t\t}]\n\t});\n\tawait ctx.context.adapter.deleteMany({\n\t\tmodel: \"oauthRefreshToken\",\n\t\twhere: [{\n\t\t\tfield: \"clientId\",\n\t\t\tvalue: clientId\n\t\t}, {\n\t\t\tfield: \"userId\",\n\t\t\tvalue: userId\n\t\t}]\n\t});\n}\nasync function revokeTokensIssuedForAuthorizationCode(ctx, authorizationCodeId) {\n\tconst deleteIssuedTokens = async (model) => {\n\t\ttry {\n\t\t\tawait ctx.context.adapter.deleteMany({\n\t\t\t\tmodel,\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"authorizationCodeId\",\n\t\t\t\t\tvalue: authorizationCodeId\n\t\t\t\t}]\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tctx.context.logger.error(\"authorization code replay cleanup failed\", error);\n\t\t}\n\t};\n\tawait deleteIssuedTokens(\"oauthAccessToken\");\n\tawait deleteIssuedTokens(\"oauthRefreshToken\");\n}\nasync function createRefreshToken(ctx, opts, user, referenceId, authorizationCodeId, client, scopes, payload, originalRefresh, authTime, resources, confirmation, requestedUserInfoClaims) {\n\tconst iat = payload.iat ?? Math.floor(Date.now() / 1e3);\n\tconst exp = payload?.exp ?? iat + (opts.refreshTokenExpiresIn ?? 2592e3);\n\tconst token = opts.generateRefreshToken ? await opts.generateRefreshToken() : generateRandomString(32, \"A-Z\", \"a-z\");\n\tconst sessionId = payload?.sid;\n\tconst newRow = {\n\t\ttoken: await storeToken(opts.storeTokens, token, \"refresh_token\"),\n\t\tclientId: client.clientId,\n\t\tsessionId,\n\t\tuserId: user.id,\n\t\treferenceId,\n\t\tauthorizationCodeId,\n\t\tauthTime,\n\t\tconfirmation,\n\t\trequestedUserInfoClaims: requestedUserInfoClaims?.length ? requestedUserInfoClaims : void 0,\n\t\tscopes,\n\t\tresources,\n\t\tcreatedAt: /* @__PURE__ */ new Date(iat * 1e3),\n\t\texpiresAt: /* @__PURE__ */ new Date(exp * 1e3)\n\t};\n\tif (!originalRefresh?.id) return {\n\t\tid: (await ctx.context.adapter.create({\n\t\t\tmodel: \"oauthRefreshToken\",\n\t\t\tdata: newRow\n\t\t})).id,\n\t\ttoken: await encodeRefreshToken(opts, token, sessionId)\n\t};\n\tconst rotatedAt = /* @__PURE__ */ new Date(iat * 1e3);\n\tconst rotationUpdate = {\n\t\trevoked: rotatedAt,\n\t\trotatedAt\n\t};\n\tconst reuseInterval = opts.refreshTokenReuseInterval ?? 0;\n\tif (reuseInterval > 0) rotationUpdate.rotationReplayExpiresAt = /* @__PURE__ */ new Date((iat + reuseInterval) * 1e3);\n\tif (!await ctx.context.adapter.incrementOne({\n\t\tmodel: \"oauthRefreshToken\",\n\t\twhere: [{\n\t\t\tfield: \"id\",\n\t\t\tvalue: originalRefresh.id\n\t\t}, {\n\t\t\tfield: \"revoked\",\n\t\t\toperator: \"eq\",\n\t\t\tvalue: null\n\t\t}],\n\t\tincrement: {},\n\t\tset: rotationUpdate\n\t})) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"invalid refresh token\",\n\t\terror: \"invalid_grant\"\n\t});\n\treturn {\n\t\tid: (await ctx.context.adapter.create({\n\t\t\tmodel: \"oauthRefreshToken\",\n\t\t\tdata: newRow\n\t\t})).id,\n\t\ttoken: await encodeRefreshToken(opts, token, sessionId)\n\t};\n}\nasync function resolveResourceGrantIssuance(ctx, opts, params) {\n\tconst resourcePolicy = await resolveResourcePolicy(ctx, opts, {\n\t\tresource: params.resources,\n\t\tclientId: params.clientId,\n\t\trequestedScopes: params.requestedScopes\n\t});\n\tconst resourceExpiresAtSeconds = resourcePolicy.accessTokenTtl !== null ? params.iat + resourcePolicy.accessTokenTtl : params.scopeExpiresAtSeconds;\n\tconst refreshTokenDefaultTtl = opts.refreshTokenExpiresIn ?? 2592e3;\n\tconst refreshTokenTtl = resourcePolicy.refreshTokenTtl !== null ? Math.min(resourcePolicy.refreshTokenTtl, refreshTokenDefaultTtl) : refreshTokenDefaultTtl;\n\treturn {\n\t\taudienceClaim: resourcePolicy.audienceClaim,\n\t\teffectiveScopes: resourcePolicy.effectiveScopes,\n\t\taccessTokenExpiresAtSeconds: Math.min(params.scopeExpiresAtSeconds, resourceExpiresAtSeconds),\n\t\trefreshTokenExpiresAtSeconds: params.iat + refreshTokenTtl,\n\t\trefreshResources: params.refreshToken?.resources ?? params.originalResources ?? params.resources,\n\t\tsigningAlgorithm: resourcePolicy.signingAlgorithm,\n\t\tsigningKeyId: resourcePolicy.signingKeyId,\n\t\tresourceCustomClaims: resourcePolicy.rawCustomClaims,\n\t\tdpopBoundAccessTokensRequired: resourcePolicy.dpopBoundAccessTokensRequired\n\t};\n}\nfunction throwInvalidDpopProof(errorDescription) {\n\tthrow new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_dpop_proof\",\n\t\terror_description: errorDescription\n\t});\n}\nfunction clientRequiresDpopBoundAccessTokens(client) {\n\tconst metadata = parseClientMetadata(client.metadata) ?? {};\n\treturn client.dpopBoundAccessTokens === true || metadata.dpop_bound_access_tokens === true;\n}\nasync function resolveDpopTokenBinding(ctx, opts, params) {\n\tconst authCodeDpopJkt = params.verificationValue?.query.dpop_jkt;\n\tconst refreshJkt = getConfirmationJkt(params.refreshToken?.confirmation);\n\tconst expectedJkt = refreshJkt ?? authCodeDpopJkt;\n\tconst dpopProofJwt = getDpopProofJwt(ctx);\n\tconst dpopRequired = clientRequiresDpopBoundAccessTokens(params.client) || params.grantIssuance.dpopBoundAccessTokensRequired || !!authCodeDpopJkt || !!refreshJkt;\n\tif (!dpopProofJwt) {\n\t\tif (dpopRequired) throwInvalidDpopProof(\"DPoP proof header is required\");\n\t\treturn;\n\t}\n\ttry {\n\t\treturn { jkt: (await verifyDpopProof({\n\t\t\tproofJwt: dpopProofJwt,\n\t\t\tmethod: \"POST\",\n\t\t\turl: getEndpointUrl(ctx, \"/oauth2/token\"),\n\t\t\texpectedJkt,\n\t\t\tproofMaxAgeSeconds: opts.dpop?.proofMaxAgeSeconds,\n\t\t\tsigningAlgorithms: opts.dpop?.signingAlgorithms,\n\t\t\treplayStore: createDpopReplayStore(ctx.context.internalAdapter)\n\t\t})).jkt };\n\t} catch (error) {\n\t\tif (isDpopProofError(error)) throwInvalidDpopProof(error.message);\n\t\tthrow error;\n\t}\n}\nfunction normalizeReplayValues(values) {\n\treturn values ? [...new Set(values)].sort() : void 0;\n}\nfunction sameReplayValues(left, right) {\n\tconst normalizedLeft = normalizeReplayValues(left);\n\tconst normalizedRight = normalizeReplayValues(right);\n\tif (normalizedLeft === void 0 || normalizedRight === void 0) return normalizedLeft === normalizedRight;\n\tif (normalizedLeft.length !== normalizedRight.length) return false;\n\treturn normalizedLeft.every((value, index) => value === normalizedRight[index]);\n}\nfunction confirmationReplayKey(confirmation) {\n\tif (!confirmation) return;\n\tif (\"jkt\" in confirmation) return `jkt:${confirmation.jkt}`;\n\treturn `x5t#S256:${confirmation[\"x5t#S256\"]}`;\n}\nfunction sameConfirmation(left, right) {\n\treturn confirmationReplayKey(left) === confirmationReplayKey(right);\n}\nfunction isConfirmation(value) {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst confirmation = value;\n\treturn typeof confirmation.jkt === \"string\" && confirmation[\"x5t#S256\"] === void 0 || typeof confirmation[\"x5t#S256\"] === \"string\" && confirmation.jkt === void 0;\n}\nfunction isTokenType(value) {\n\treturn value === \"Bearer\" || value === \"DPoP\";\n}\nfunction isOAuthTokenResponse(value) {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst response = value;\n\treturn typeof response.access_token === \"string\" && typeof response.expires_in === \"number\" && typeof response.expires_at === \"number\" && isTokenType(response.token_type) && typeof response.scope === \"string\" && (response.refresh_token === void 0 || typeof response.refresh_token === \"string\") && (response.id_token === void 0 || typeof response.id_token === \"string\");\n}\nfunction isRefreshTokenRotationReplay(value) {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst replay = value;\n\tconst request = replay.request;\n\treturn !!request && Array.isArray(request.effectiveScopes) && request.effectiveScopes.every((scope) => typeof scope === \"string\") && (request.requestedResources === void 0 || Array.isArray(request.requestedResources) && request.requestedResources.every((resource) => typeof resource === \"string\")) && (request.confirmation === void 0 || isConfirmation(request.confirmation)) && isOAuthTokenResponse(replay.response);\n}\nfunction buildRefreshTokenRotationReplayRequest(params) {\n\tconst requestedResources = normalizeReplayValues(params.requestedResources);\n\treturn {\n\t\teffectiveScopes: normalizeReplayValues(params.effectiveScopes) ?? [],\n\t\t...requestedResources ? { requestedResources } : {},\n\t\t...params.confirmation ? { confirmation: params.confirmation } : {}\n\t};\n}\nfunction sameRefreshTokenRotationReplayRequest(left, right) {\n\treturn sameReplayValues(left.effectiveScopes, right.effectiveScopes) && sameReplayValues(left.requestedResources, right.requestedResources) && sameConfirmation(left.confirmation, right.confirmation);\n}\nasync function encryptRefreshTokenRotationReplay(ctx, replay) {\n\treturn symmetricEncrypt({\n\t\tkey: ctx.context.secretConfig,\n\t\tdata: JSON.stringify(replay)\n\t});\n}\nasync function decryptRefreshTokenRotationReplay(ctx, value) {\n\tconst decrypted = await symmetricDecrypt({\n\t\tkey: ctx.context.secretConfig,\n\t\tdata: value\n\t});\n\tconst parsed = JSON.parse(decrypted);\n\tif (!isRefreshTokenRotationReplay(parsed)) return;\n\treturn parsed;\n}\nfunction isWithinRefreshTokenReuseInterval(refreshToken) {\n\treturn !!refreshToken.rotatedAt && !!refreshToken.rotationReplayExpiresAt && refreshToken.rotationReplayExpiresAt >= /* @__PURE__ */ new Date();\n}\nasync function storeRefreshTokenRotationReplay(ctx, opts, refreshToken, request, response) {\n\tif ((opts.refreshTokenReuseInterval ?? 0) <= 0) return;\n\tawait ctx.context.adapter.update({\n\t\tmodel: \"oauthRefreshToken\",\n\t\twhere: [{\n\t\t\tfield: \"id\",\n\t\t\tvalue: refreshToken.id\n\t\t}],\n\t\tupdate: { rotationReplayResponse: await encryptRefreshTokenRotationReplay(ctx, {\n\t\t\trequest,\n\t\t\tresponse\n\t\t}) }\n\t});\n}\nasync function getRefreshTokenRotationReplay(ctx, refreshToken, request) {\n\tif (!isWithinRefreshTokenReuseInterval(refreshToken)) return;\n\tif (!refreshToken.rotationReplayResponse) return;\n\ttry {\n\t\tconst replay = await decryptRefreshTokenRotationReplay(ctx, refreshToken.rotationReplayResponse);\n\t\tif (!replay || !sameRefreshTokenRotationReplayRequest(replay.request, request)) return;\n\t\treturn replay.response;\n\t} catch (error) {\n\t\tctx.context.logger.error(\"refresh token rotation replay failed\", error);\n\t\treturn;\n\t}\n}\nasync function resolveRefreshTokenRotationReplayRequest(ctx, opts, params) {\n\tconst iat = Math.floor(Date.now() / 1e3);\n\tconst grantIssuance = await resolveResourceGrantIssuance(ctx, opts, {\n\t\tclientId: params.client.clientId,\n\t\trequestedScopes: params.scopes,\n\t\tresources: params.resources,\n\t\trefreshToken: params.refreshToken,\n\t\tiat,\n\t\tscopeExpiresAtSeconds: iat + (opts.accessTokenExpiresIn ?? 3600)\n\t});\n\tconst confirmation = await resolveDpopTokenBinding(ctx, opts, {\n\t\tclient: params.client,\n\t\tgrantIssuance,\n\t\trefreshToken: params.refreshToken\n\t});\n\treturn buildRefreshTokenRotationReplayRequest({\n\t\teffectiveScopes: grantIssuance.effectiveScopes,\n\t\trequestedResources: params.resources,\n\t\tconfirmation\n\t});\n}\nfunction replayRefreshTokenRotationResponse(ctx, response) {\n\tconst now = Math.floor(Date.now() / 1e3);\n\treturn ctx.json({\n\t\t...response,\n\t\texpires_in: Math.max(0, response.expires_at - now)\n\t});\n}\nasync function createUserTokens(ctx, opts, params) {\n\tconst { client, scopes, user, grantType, referenceId, sessionId, nonce, refreshToken: existingRefreshToken, authTime, verificationValue } = params;\n\tconst iat = Math.floor(Date.now() / 1e3);\n\tconst defaultExp = iat + (user ? opts.accessTokenExpiresIn ?? 3600 : opts.m2mAccessTokenExpiresIn ?? 3600);\n\tconst scopeExp = opts.scopeExpirations ? scopes.map((sc) => opts.scopeExpirations?.[sc] ? toExpJWT(opts.scopeExpirations[sc], iat) : defaultExp).reduce((prev, curr) => {\n\t\treturn prev < curr ? prev : curr;\n\t}, defaultExp) : defaultExp;\n\tconst grantIssuance = await resolveResourceGrantIssuance(ctx, opts, {\n\t\tclientId: client.clientId,\n\t\trequestedScopes: scopes,\n\t\tresources: params.resources,\n\t\toriginalResources: params.originalResources,\n\t\trefreshToken: params.refreshToken,\n\t\tiat,\n\t\tscopeExpiresAtSeconds: scopeExp\n\t});\n\tconst audienceClaim = grantIssuance.audienceClaim;\n\tconst effectiveScopes = grantIssuance.effectiveScopes;\n\tconst exp = grantIssuance.accessTokenExpiresAtSeconds;\n\tconst refreshTokenExp = grantIssuance.refreshTokenExpiresAtSeconds;\n\tconst isRefreshToken = user && clientAllowsGrant(client, \"refresh_token\") && (existingRefreshToken?.scopes?.includes(\"offline_access\") || scopes.includes(\"offline_access\"));\n\tconst isJwtAccessToken = audienceClaim && !opts.disableJwtPlugin;\n\tconst isIdToken = user && effectiveScopes.includes(\"openid\");\n\tconst metadata = parseClientMetadata(client.metadata);\n\tconst additionalIdTokenClaims = isIdToken && user ? {\n\t\t...await collectExtensionIdTokenClaims(opts, {\n\t\t\tctx,\n\t\t\topts,\n\t\t\tuser,\n\t\t\tclient,\n\t\t\tscopes: effectiveScopes,\n\t\t\tgrantType,\n\t\t\treferenceId,\n\t\t\tsessionId,\n\t\t\tresources: params.resources,\n\t\t\tmetadata\n\t\t}),\n\t\t...params.idTokenClaims ?? {}\n\t} : void 0;\n\tconst customFields = opts.customTokenResponseFields ? await opts.customTokenResponseFields({\n\t\tgrantType,\n\t\tuser,\n\t\tscopes: effectiveScopes,\n\t\tmetadata,\n\t\tverificationValue\n\t}) : void 0;\n\tconst refreshResources = grantIssuance.refreshResources;\n\tconst confirmation = params.confirmation ?? await resolveDpopTokenBinding(ctx, opts, {\n\t\tclient,\n\t\tgrantIssuance,\n\t\tverificationValue,\n\t\trefreshToken: existingRefreshToken\n\t});\n\tconst requestedUserInfoClaims = params.requestedUserInfoClaims ?? existingRefreshToken?.requestedUserInfoClaims ?? [];\n\tconst earlyRefreshToken = isRefreshToken && user && !isJwtAccessToken ? await createRefreshToken(ctx, opts, user, referenceId, params.authorizationCodeId, client, effectiveScopes, {\n\t\tiat,\n\t\texp: refreshTokenExp,\n\t\tsid: sessionId\n\t}, existingRefreshToken, authTime, refreshResources, confirmation, requestedUserInfoClaims) : void 0;\n\tconst accessTokenClaims = isJwtAccessToken ? await resolveAccessTokenClaims({\n\t\tctx,\n\t\topts,\n\t\tuser,\n\t\tclient,\n\t\tscopes: effectiveScopes,\n\t\tgrantType,\n\t\tsessionId,\n\t\tresources: params.resources,\n\t\treferenceId,\n\t\tmetadata,\n\t\tperRequestClaims: params.accessTokenClaims,\n\t\tresourcePolicyClaims: grantIssuance.resourceCustomClaims\n\t}) : void 0;\n\tconst [accessToken, refreshToken] = await Promise.all([isJwtAccessToken ? createJwtAccessToken(ctx, opts, user, client, audienceClaim, effectiveScopes, {\n\t\tiat,\n\t\texp,\n\t\tsid: sessionId,\n\t\tsigningAlgorithm: grantIssuance.signingAlgorithm,\n\t\tsigningKeyId: grantIssuance.signingKeyId,\n\t\taccessTokenClaims,\n\t\tconfirmation\n\t}) : createOpaqueAccessToken(ctx, opts, user, client, effectiveScopes, {\n\t\tiat,\n\t\texp,\n\t\tsid: sessionId\n\t}, params?.resources, referenceId, params.authorizationCodeId, earlyRefreshToken?.id, confirmation, requestedUserInfoClaims), earlyRefreshToken ? earlyRefreshToken : isRefreshToken && user ? createRefreshToken(ctx, opts, user, referenceId, params.authorizationCodeId, client, effectiveScopes, {\n\t\tiat,\n\t\texp: refreshTokenExp,\n\t\tsid: sessionId\n\t}, existingRefreshToken, authTime, refreshResources, confirmation, requestedUserInfoClaims) : void 0]);\n\tconst idToken = isIdToken ? await createIdToken(ctx, opts, user, client, effectiveScopes, nonce, sessionId, authTime, accessToken, additionalIdTokenClaims) : void 0;\n\tconst responseBody = {\n\t\t...customFields,\n\t\t...params.tokenResponse ?? {},\n\t\taccess_token: accessToken,\n\t\texpires_in: exp - iat,\n\t\texpires_at: exp,\n\t\ttoken_type: confirmationTokenType(confirmation),\n\t\trefresh_token: refreshToken?.token,\n\t\tscope: effectiveScopes.join(\" \"),\n\t\tid_token: idToken\n\t};\n\tif (existingRefreshToken?.id && refreshToken?.id) try {\n\t\tawait storeRefreshTokenRotationReplay(ctx, opts, existingRefreshToken, buildRefreshTokenRotationReplayRequest({\n\t\t\teffectiveScopes,\n\t\t\trequestedResources: params.resources,\n\t\t\tconfirmation\n\t\t}), responseBody);\n\t} catch (error) {\n\t\tctx.context.logger.error(\"failed to store refresh token rotation replay\", error);\n\t}\n\treturn ctx.json(responseBody);\n}\n/** Checks verification value */\nasync function checkVerificationValue(ctx, opts, code, client_id, redirect_uri, resource) {\n\tconst authorizationCodeId = await storeToken(opts.storeTokens, code, \"authorization_code\");\n\tconst verification = await ctx.context.internalAdapter.consumeVerificationValue(authorizationCodeId);\n\tif (!verification) {\n\t\tawait revokeTokensIssuedForAuthorizationCode(ctx, authorizationCodeId);\n\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\terror_description: \"invalid code\",\n\t\t\terror: \"invalid_grant\"\n\t\t});\n\t}\n\tlet rawValue;\n\ttry {\n\t\trawValue = JSON.parse(verification.value);\n\t} catch {\n\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\terror_description: \"malformed verification value\",\n\t\t\terror: \"invalid_grant\"\n\t\t});\n\t}\n\tconst parsed = verificationValueSchema.safeParse(rawValue);\n\tif (!parsed.success) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"malformed verification value\",\n\t\terror: \"invalid_grant\"\n\t});\n\tconst verificationValue = parsed.data;\n\tif (verificationValue.query.client_id !== client_id) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"invalid client_id\",\n\t\terror: \"invalid_grant\"\n\t});\n\tconst boundRedirectUri = verificationValue.query.redirect_uri;\n\tif (boundRedirectUri) {\n\t\tif (!redirect_uri) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror_description: \"redirect_uri is required\",\n\t\t\terror: \"invalid_request\"\n\t\t});\n\t\tif (boundRedirectUri !== redirect_uri) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror_description: \"redirect_uri mismatch\",\n\t\t\terror: \"invalid_grant\"\n\t\t});\n\t} else if (redirect_uri) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"redirect_uri mismatch\",\n\t\terror: \"invalid_grant\"\n\t});\n\tconst storedResources = toResourceList(verificationValue.resource) ?? toResourceList(verificationValue.query.resource);\n\tconst effectiveResources = resource ?? storedResources;\n\tif (resource && storedResources) {\n\t\tconst requestedSet = new Set(resource);\n\t\tconst authorizedSet = new Set(storedResources);\n\t\tfor (const r of requestedSet) if (!authorizedSet.has(r)) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror_description: \"requested resource not authorized\",\n\t\t\terror: \"invalid_target\"\n\t\t});\n\t}\n\treturn {\n\t\tverificationValue,\n\t\teffectiveResources,\n\t\tauthorizedResources: storedResources,\n\t\tauthorizationCodeId\n\t};\n}\n/**\n* Obtains new Session Jwt and Refresh Tokens using a code\n*/\nasync function handleAuthorizationCodeGrant(ctx, opts) {\n\tconst { clientId: client_id, clientSecret: client_secret, preVerified, authMethod } = destructureCredentials(await extractClientCredentials(ctx, opts, `${ctx.context.baseURL}/oauth2/token`));\n\tconst { code, code_verifier, redirect_uri, resource } = ctx.body;\n\tconst resources = toResourceList(resource);\n\tif (!client_id) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"client_id is required\",\n\t\terror: \"invalid_request\"\n\t});\n\tif (!code) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"code is required\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst isAuthCodeWithSecret = client_id && client_secret;\n\tconst isAuthCodeWithPkce = client_id && code && code_verifier;\n\tif (!isAuthCodeWithSecret && !isAuthCodeWithPkce && !preVerified) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"Either code_verifier or client_secret is required\",\n\t\terror: \"invalid_request\"\n\t});\n\t/** Get and check Verification Value */\n\tconst { verificationValue, effectiveResources, authorizedResources, authorizationCodeId } = await checkVerificationValue(ctx, opts, code, client_id, redirect_uri, resources);\n\tconst scopes = verificationValue.query.scope?.split(\" \");\n\tif (!scopes) throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n\t\terror_description: \"verification scope unset\",\n\t\terror: \"invalid_scope\"\n\t});\n\t/** Verify Client */\n\tconst client = await validateClientCredentials(ctx, opts, client_id, client_secret, scopes, preVerified, \"authorization_code\", authMethod);\n\tif (isPKCERequired(client, {\n\t\tscopes: (verificationValue.query?.scope)?.split(\" \") || [],\n\t\tnonce: verificationValue.query?.nonce\n\t})) {\n\t\tif (!isAuthCodeWithPkce) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror_description: \"PKCE is required for this client\",\n\t\t\terror: \"invalid_request\"\n\t\t});\n\t} else if (!(isAuthCodeWithPkce || isAuthCodeWithSecret || preVerified)) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"Either PKCE (code_verifier) or client authentication (client_secret or client_assertion) is required\",\n\t\terror: \"invalid_request\"\n\t});\n\t/** Check PKCE challenge if verifier is provided */\n\tconst pkceUsedInAuth = !!verificationValue.query?.code_challenge;\n\tconst pkceUsedInToken = !!code_verifier;\n\tif (pkceUsedInAuth || pkceUsedInToken) {\n\t\tif (pkceUsedInAuth && !pkceUsedInToken) throw new APIError(\"UNAUTHORIZED\", {\n\t\t\terror_description: \"code_verifier required because PKCE was used in authorization\",\n\t\t\terror: \"invalid_request\"\n\t\t});\n\t\tif (!pkceUsedInAuth && pkceUsedInToken) throw new APIError(\"UNAUTHORIZED\", {\n\t\t\terror_description: \"code_verifier provided but PKCE was not used in authorization\",\n\t\t\terror: \"invalid_request\"\n\t\t});\n\t\tif ((verificationValue.query?.code_challenge_method === \"S256\" ? await generateCodeChallenge(code_verifier) : void 0) !== verificationValue.query?.code_challenge) throw new APIError(\"UNAUTHORIZED\", {\n\t\t\terror_description: \"code verification failed\",\n\t\t\terror: \"invalid_request\"\n\t\t});\n\t}\n\t/** Get user */\n\tif (!verificationValue.userId) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"missing user, user may have been deleted\",\n\t\terror: \"invalid_user\"\n\t});\n\tconst user = await ctx.context.internalAdapter.findUserById(verificationValue.userId);\n\tif (!user) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"missing user, user may have been deleted\",\n\t\terror: \"invalid_user\"\n\t});\n\tconst session = await ctx.context.adapter.findOne({\n\t\tmodel: \"session\",\n\t\twhere: [{\n\t\t\tfield: \"id\",\n\t\t\tvalue: verificationValue.sessionId\n\t\t}]\n\t});\n\tif (!session || session.expiresAt < /* @__PURE__ */ new Date()) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"session no longer exists\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst authTime = verificationValue.authTime != null ? normalizeTimestampValue(verificationValue.authTime) : resolveSessionAuthTime(session);\n\tconst requestedUserInfoClaims = getRequestedUserInfoClaims(verificationValue.query.claims, getSupportedClaims(opts));\n\treturn createUserTokens(ctx, opts, {\n\t\tclient,\n\t\tscopes: verificationValue.query.scope?.split(\" \") ?? [],\n\t\tuser,\n\t\tgrantType: \"authorization_code\",\n\t\treferenceId: verificationValue.referenceId,\n\t\tsessionId: session.id,\n\t\tnonce: verificationValue.query?.nonce,\n\t\tauthTime,\n\t\tverificationValue,\n\t\tauthorizationCodeId,\n\t\trequestedUserInfoClaims,\n\t\tresources: effectiveResources,\n\t\toriginalResources: authorizedResources\n\t});\n}\n/**\n* Grant that allows direct access to an API using the application's credentials\n* This grant is for M2M so the concept of a user id does not exist on the token.\n*\n* MUST follow https://datatracker.ietf.org/doc/html/rfc6749#section-4.4\n*/\nasync function handleClientCredentialsGrant(ctx, opts) {\n\tconst { clientId: client_id, clientSecret: client_secret, preVerified, authMethod } = destructureCredentials(await extractClientCredentials(ctx, opts, `${ctx.context.baseURL}/oauth2/token`));\n\tconst { scope, resource } = ctx.body;\n\tconst resources = toResourceList(resource);\n\tif (!client_id) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"Missing required client_id\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst client = await validateClientCredentials(ctx, opts, client_id, client_secret, void 0, preVerified, \"client_credentials\", authMethod);\n\tif (client.tokenEndpointAuthMethod === \"none\") throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"public clients cannot use the client_credentials grant\",\n\t\terror: \"unauthorized_client\"\n\t});\n\tconst clientCredentialsScopes = client.clientCredentialsScopes;\n\tif (!clientCredentialsScopes?.length) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"client has no authorized client_credentials scopes\",\n\t\terror: \"unauthorized_client\"\n\t});\n\tlet requestedScopes = scope?.split(\" \");\n\tif (requestedScopes) {\n\t\tconst validScopes = new Set(clientCredentialsScopes);\n\t\tconst invalidScopes = requestedScopes.filter((scope) => {\n\t\t\treturn !validScopes.has(scope) || isUserDelegatedScope(scope);\n\t\t});\n\t\tif (invalidScopes.length) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror_description: `The following scopes are invalid: ${invalidScopes.join(\", \")}`,\n\t\t\terror: \"invalid_scope\"\n\t\t});\n\t}\n\tif (!requestedScopes) requestedScopes = [...clientCredentialsScopes];\n\treturn createUserTokens(ctx, opts, {\n\t\tclient,\n\t\tscopes: requestedScopes,\n\t\tgrantType: \"client_credentials\",\n\t\tresources\n\t});\n}\n/**\n* Obtains new Session Jwt and Refresh Tokens using a refresh token\n*\n* Refresh tokens will only allow the same or lesser scopes as the initial authorize request.\n* To add scopes, you must restart the authorize process again.\n*/\nasync function handleRefreshTokenGrant(ctx, opts) {\n\tconst { clientId: client_id, clientSecret: client_secret, preVerified, authMethod } = destructureCredentials(await extractClientCredentials(ctx, opts, `${ctx.context.baseURL}/oauth2/token`));\n\tconst { refresh_token, scope, resource } = ctx.body;\n\tconst resources = toResourceList(resource);\n\tif (!client_id) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"Missing required client_id\",\n\t\terror: \"invalid_request\"\n\t});\n\tif (!refresh_token) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"Missing a required refresh_token for refresh_token grant\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst decodedRefresh = await decodeRefreshToken(opts, refresh_token);\n\tconst refreshToken = await ctx.context.adapter.findOne({\n\t\tmodel: \"oauthRefreshToken\",\n\t\twhere: [{\n\t\t\tfield: \"token\",\n\t\t\tvalue: await getStoredToken(opts.storeTokens, decodedRefresh.token, \"refresh_token\")\n\t\t}]\n\t});\n\tif (!refreshToken) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"session not found\",\n\t\terror: \"invalid_grant\"\n\t});\n\tif (refreshToken.clientId !== client_id) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"invalid refresh token\",\n\t\terror: \"invalid_grant\"\n\t});\n\tif (refreshToken.expiresAt < /* @__PURE__ */ new Date()) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"invalid refresh token\",\n\t\terror: \"invalid_grant\"\n\t});\n\tif (resources && refreshToken.resources && !resources.every((v) => refreshToken.resources?.includes(v))) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"requested resource invalid\",\n\t\terror: \"invalid_target\"\n\t});\n\tconst scopes = refreshToken?.scopes;\n\tconst requestedScopes = scope?.split(\" \");\n\tif (requestedScopes) {\n\t\tconst validScopes = new Set(scopes);\n\t\tfor (const requestedScope of requestedScopes) if (!validScopes.has(requestedScope)) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror_description: `unable to issue scope ${requestedScope}`,\n\t\t\terror: \"invalid_scope\"\n\t\t});\n\t}\n\tconst client = await validateClientCredentials(ctx, opts, client_id, client_secret, requestedScopes ?? scopes, preVerified, \"refresh_token\", authMethod);\n\tif (refreshToken.revoked) {\n\t\tif (isWithinRefreshTokenReuseInterval(refreshToken)) {\n\t\t\tconst replay = await getRefreshTokenRotationReplay(ctx, refreshToken, await resolveRefreshTokenRotationReplayRequest(ctx, opts, {\n\t\t\t\tclient,\n\t\t\t\trefreshToken,\n\t\t\t\tscopes: requestedScopes ?? scopes,\n\t\t\t\tresources: resources ?? refreshToken.resources\n\t\t\t}));\n\t\t\tif (replay) return replayRefreshTokenRotationResponse(ctx, replay);\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\terror_description: \"invalid refresh token\",\n\t\t\t\terror: \"invalid_grant\"\n\t\t\t});\n\t\t}\n\t\tawait invalidateRefreshFamily(ctx, client_id, refreshToken.userId);\n\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\terror_description: \"invalid refresh token\",\n\t\t\terror: \"invalid_grant\"\n\t\t});\n\t}\n\tconst user = await ctx.context.internalAdapter.findUserById(refreshToken.userId);\n\tif (!user) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"user not found\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst authTime = refreshToken.authTime != null ? normalizeTimestampValue(refreshToken.authTime) : void 0;\n\treturn createUserTokens(ctx, opts, {\n\t\tclient,\n\t\tscopes: requestedScopes ?? scopes,\n\t\tuser,\n\t\tgrantType: \"refresh_token\",\n\t\treferenceId: refreshToken.referenceId,\n\t\tauthorizationCodeId: refreshToken.authorizationCodeId,\n\t\tsessionId: refreshToken.sessionId,\n\t\trefreshToken,\n\t\tresources: resources ?? refreshToken.resources,\n\t\tauthTime,\n\t\trequestedUserInfoClaims: refreshToken.requestedUserInfoClaims\n\t});\n}\n//#endregion\n//#region src/introspect.ts\nvar introspect_exports = /* @__PURE__ */ __exportAll({\n\tintrospectEndpoint: () => introspectEndpoint,\n\trequireActiveAccessToken: () => requireActiveAccessToken,\n\trequireActiveAccessTokenWithClaims: () => requireActiveAccessTokenWithClaims,\n\tvalidateAccessToken: () => validateAccessToken\n});\nconst INVALID_ACCESS_TOKEN_ERROR_DESCRIPTION = \"Invalid access token\";\nconst INVALID_ACCESS_TOKEN_WWW_AUTHENTICATE = `Bearer error=\"invalid_token\", error_description=\"${INVALID_ACCESS_TOKEN_ERROR_DESCRIPTION}\"`;\nfunction inactiveAccessToken() {\n\treturn {\n\t\tpayload: { active: false },\n\t\trequestedUserInfoClaims: []\n\t};\n}\n/**\n* IMPORTANT NOTES:\n* Introspection follows RFC7662\n* https://datatracker.ietf.org/doc/html/rfc7662\n* - APIError: Continue catches (returnable to client)\n* - Error: Should immediately stop catches (internal error)\n*/\n/**\n* Resource identifiers in a token's audience, excluding the implicit\n* `/oauth2/userinfo` audience (which is not a configured resource server).\n*/\nfunction audienceResourceIdentifiers(aud, userInfoAud) {\n\tif (aud == null) return [];\n\treturn (Array.isArray(aud) ? aud : [aud]).filter((value) => typeof value === \"string\" && value !== userInfoAud);\n}\n/**\n* Authorizes an introspection request (RFC 7662 §2.1/§4). The caller is already\n* authenticated as a registered client; it may introspect the token when it\n* issued the token, or when it is a resource server linked to one of the token's\n* audience resources. Tokens with no resource audience stay issuer-only. An\n* unauthorized caller receives `{active:false}` (indistinguishable from an\n* expired or unknown token), preserving the §4 anti-scanning property.\n*/\nasync function isIntrospectionAuthorized(ctx, opts, params) {\n\tconst { introspectingClientId, issuerClientId, audienceResources } = params;\n\tif (!introspectingClientId) return true;\n\tif (introspectingClientId === issuerClientId) return true;\n\tif (audienceResources.length === 0) return false;\n\treturn isClientLinkedToAnyResource(ctx, opts, introspectingClientId, audienceResources);\n}\n/**\n* Validates a JWT access token against the configured JWKs.\n*\n* @returns RFC7662 introspection format\n*/\nasync function validateJwtAccessToken(ctx, opts, token, clientId) {\n\tconst jwtPlugin = opts.disableJwtPlugin ? void 0 : getJwtPlugin(ctx.context);\n\tconst jwtPluginOptions = jwtPlugin?.options;\n\tconst userInfoAud = `${ctx.context.baseURL ?? \"\"}/oauth2/userinfo`;\n\tconst expectedIssuer = jwtPluginOptions?.jwt?.issuer ?? ctx.context.baseURL;\n\tlet jwtPayload;\n\ttry {\n\t\tjwtPayload = (await jwtVerify(token, createLocalJWKSet(await getJwks(token, {\n\t\t\tjwksFetch: jwtPluginOptions?.jwks?.remoteUrl ? jwtPluginOptions.jwks.remoteUrl : async () => {\n\t\t\t\treturn (await jwtPlugin?.endpoints.getJwks(ctx))?.response;\n\t\t\t},\n\t\t\tjwksCacheKey: jwtPlugin\n\t\t})), { issuer: expectedIssuer })).payload;\n\t} catch (error) {\n\t\tif (error instanceof Error) {\n\t\t\tif (error.name === \"TypeError\" || error.name === \"JWSInvalid\") throw new APIError$1(\"BAD_REQUEST\", {\n\t\t\t\terror_description: \"invalid JWT signature\",\n\t\t\t\terror: \"invalid_request\"\n\t\t\t});\n\t\t\telse if (error.name === \"JWTExpired\") return { active: false };\n\t\t\telse if (error.name === \"JWTInvalid\") return { active: false };\n\t\t\tthrow error;\n\t\t}\n\t\tthrow new Error(error);\n\t}\n\tconst rawAud = jwtPayload.aud;\n\tif (!await isAudienceClaimAllowed(ctx, opts, rawAud, [userInfoAud])) return { active: false };\n\tif (!jwtPayload.azp) return { active: false };\n\tconst client = await getClient(ctx, opts, jwtPayload.azp);\n\tif (!client || client?.disabled) return { active: false };\n\tif (!await isIntrospectionAuthorized(ctx, opts, {\n\t\tintrospectingClientId: clientId,\n\t\tissuerClientId: jwtPayload.azp,\n\t\taudienceResources: audienceResourceIdentifiers(rawAud, userInfoAud)\n\t})) return { active: false };\n\tconst sessionId = jwtPayload.sid;\n\tif (sessionId) {\n\t\tconst session = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"session\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"id\",\n\t\t\t\tvalue: sessionId\n\t\t\t}]\n\t\t});\n\t\tif (!session || session.expiresAt < /* @__PURE__ */ new Date()) return { active: false };\n\t}\n\tjwtPayload.client_id = jwtPayload.azp;\n\tjwtPayload.active = true;\n\tjwtPayload.token_type = confirmationTokenType(jwtPayload.cnf);\n\treturn jwtPayload;\n}\n/**\n* Searches for an opaque access token in the database and validates it\n*\n* @returns RFC7662 introspection format\n*/\nasync function validateOpaqueAccessToken(ctx, opts, token, clientId) {\n\tlet tokenValue = token;\n\tif (opts.prefix?.opaqueAccessToken) if (tokenValue.startsWith(opts.prefix.opaqueAccessToken)) tokenValue = tokenValue.replace(opts.prefix.opaqueAccessToken, \"\");\n\telse throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"opaque access token not found\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst accessToken = await ctx.context.adapter.findOne({\n\t\tmodel: \"oauthAccessToken\",\n\t\twhere: [{\n\t\t\tfield: \"token\",\n\t\t\tvalue: await getStoredToken(opts.storeTokens, tokenValue, \"access_token\")\n\t\t}]\n\t});\n\tif (!accessToken) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"opaque access token not found\",\n\t\terror: \"invalid_token\"\n\t});\n\tif (!accessToken.expiresAt || accessToken.expiresAt < /* @__PURE__ */ new Date()) return inactiveAccessToken();\n\tif (accessToken.revoked) return inactiveAccessToken();\n\tconst resources = Array.isArray(accessToken.resources) ? accessToken.resources : void 0;\n\tlet client;\n\tif (accessToken.clientId) {\n\t\tclient = await getClient(ctx, opts, accessToken.clientId);\n\t\tif (!client || client?.disabled) return inactiveAccessToken();\n\t\tif (!await isIntrospectionAuthorized(ctx, opts, {\n\t\t\tintrospectingClientId: clientId,\n\t\t\tissuerClientId: accessToken.clientId,\n\t\t\taudienceResources: resources ?? []\n\t\t})) return inactiveAccessToken();\n\t}\n\tconst sessionId = accessToken.sessionId ?? void 0;\n\tif (sessionId) {\n\t\tconst session = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"session\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"id\",\n\t\t\t\tvalue: sessionId\n\t\t\t}]\n\t\t});\n\t\tif (!session || session.expiresAt < /* @__PURE__ */ new Date()) return inactiveAccessToken();\n\t}\n\tlet user;\n\tif (accessToken.userId) user = await ctx.context.internalAdapter.findUserById(accessToken?.userId);\n\tconst userInfoEndpoint = `${ctx.context.baseURL}/oauth2/userinfo`;\n\tif (resources?.length && !await isAudienceClaimAllowed(ctx, opts, resources, [userInfoEndpoint])) return inactiveAccessToken();\n\tconst audienceClaim = resources ? [...resources] : void 0;\n\tif (audienceClaim?.length && accessToken.scopes?.includes(\"openid\")) {\n\t\tif (!audienceClaim.includes(userInfoEndpoint)) audienceClaim.push(userInfoEndpoint);\n\t}\n\tconst resourcePolicyClaims = resources?.length ? await getResourceCustomClaims(ctx, opts, resources) : {};\n\tconst accessTokenClaims = client ? await resolveAccessTokenClaims({\n\t\tctx,\n\t\topts,\n\t\tuser,\n\t\tclient,\n\t\tscopes: accessToken.scopes ?? [],\n\t\tgrantType: void 0,\n\t\tsessionId: void 0,\n\t\tresources,\n\t\treferenceId: accessToken.referenceId,\n\t\tmetadata: parseClientMetadata(client.metadata),\n\t\tperRequestClaims: void 0,\n\t\tresourcePolicyClaims\n\t}) : {};\n\tconst jwtPluginOptions = (opts.disableJwtPlugin ? void 0 : getJwtPlugin(ctx.context))?.options;\n\treturn {\n\t\tpayload: {\n\t\t\t...accessTokenClaims,\n\t\t\tactive: true,\n\t\t\tiss: jwtPluginOptions?.jwt?.issuer ?? ctx.context.baseURL,\n\t\t\taud: toAudienceClaim(audienceClaim),\n\t\t\tclient_id: accessToken.clientId,\n\t\t\tazp: accessToken.clientId,\n\t\t\tsub: user?.id,\n\t\t\tsid: sessionId,\n\t\t\texp: Math.floor(new Date(accessToken.expiresAt).getTime() / 1e3),\n\t\t\tiat: Math.floor(new Date(accessToken.createdAt).getTime() / 1e3),\n\t\t\tscope: accessToken.scopes?.join(\" \"),\n\t\t\ttoken_type: confirmationTokenType(accessToken.confirmation),\n\t\t\t...accessToken.confirmation ? { cnf: accessToken.confirmation } : {}\n\t\t},\n\t\trequestedUserInfoClaims: accessToken.requestedUserInfoClaims ?? []\n\t};\n}\n/**\n* Validates a refresh token in the session store.\n*\n* @returns payload in RFC7662 introspection format\n*/\nasync function validateRefreshToken(ctx, opts, token, clientId) {\n\tconst refreshToken = await ctx.context.adapter.findOne({\n\t\tmodel: \"oauthRefreshToken\",\n\t\twhere: [{\n\t\t\tfield: \"token\",\n\t\t\tvalue: await getStoredToken(opts.storeTokens, token, \"refresh_token\")\n\t\t}]\n\t});\n\tif (!refreshToken) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"token not found\",\n\t\terror: \"invalid_token\"\n\t});\n\tif (!refreshToken.clientId || refreshToken.clientId !== clientId) return { active: false };\n\tif (!refreshToken.expiresAt || refreshToken.expiresAt < /* @__PURE__ */ new Date()) return { active: false };\n\tif (refreshToken.revoked) return { active: false };\n\tlet sessionId = refreshToken.sessionId ?? void 0;\n\tif (sessionId) {\n\t\tconst session = await ctx.context.adapter.findOne({\n\t\t\tmodel: \"session\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"id\",\n\t\t\t\tvalue: sessionId\n\t\t\t}]\n\t\t});\n\t\tif (!session || session.expiresAt < /* @__PURE__ */ new Date()) sessionId = void 0;\n\t}\n\tlet user = void 0;\n\tif (refreshToken.userId) user = await ctx.context.internalAdapter.findUserById(refreshToken?.userId) ?? void 0;\n\treturn {\n\t\tactive: true,\n\t\tclient_id: clientId,\n\t\tiss: ((opts.disableJwtPlugin ? void 0 : getJwtPlugin(ctx.context))?.options)?.jwt?.issuer ?? ctx.context.baseURL,\n\t\tsub: user?.id,\n\t\tsid: sessionId,\n\t\texp: Math.floor(new Date(refreshToken.expiresAt).getTime() / 1e3),\n\t\tiat: Math.floor(new Date(refreshToken.createdAt).getTime() / 1e3),\n\t\tscope: refreshToken.scopes?.join(\" \"),\n\t\ttoken_type: confirmationTokenType(refreshToken.confirmation),\n\t\t...refreshToken.confirmation ? { cnf: refreshToken.confirmation } : {}\n\t};\n}\nfunction createInvalidAccessTokenError() {\n\treturn new APIError$1(\"UNAUTHORIZED\", {\n\t\terror_description: INVALID_ACCESS_TOKEN_ERROR_DESCRIPTION,\n\t\terror: \"invalid_token\"\n\t}, { \"WWW-Authenticate\": INVALID_ACCESS_TOKEN_WWW_AUTHENTICATE });\n}\nfunction isInactiveTokenError(error) {\n\treturn error.status === \"BAD_REQUEST\" || error.body?.error === \"invalid_token\";\n}\n/**\n* We don't know the access token format so we try to validate it as a JWT\n* first, then as an opaque token. Returns the RFC 7662 introspection payload\n* alongside the per-issuance UserInfo claims the opaque row persisted (empty for\n* a JWT access token, which resolves UserInfo claims by scope).\n*/\nasync function resolveAccessTokenValidation(ctx, opts, token, clientId) {\n\ttry {\n\t\treturn {\n\t\t\tpayload: await validateJwtAccessToken(ctx, opts, token, clientId),\n\t\t\trequestedUserInfoClaims: []\n\t\t};\n\t} catch (err) {\n\t\tif (err instanceof APIError$1) {} else if (err instanceof Error) throw err;\n\t\telse throw new Error(err);\n\t}\n\ttry {\n\t\treturn await validateOpaqueAccessToken(ctx, opts, token, clientId);\n\t} catch (err) {\n\t\tif (err instanceof APIError$1) {} else if (err instanceof Error) throw err;\n\t\telse throw new Error(\"Unknown error validating access token\");\n\t}\n\tthrow createInvalidAccessTokenError();\n}\n/**\n* Validates an access token (JWT or opaque) and returns its RFC 7662\n* introspection-format payload.\n*\n* @internal\n*/\nasync function validateAccessToken(ctx, opts, token, clientId) {\n\treturn (await resolveAccessTokenValidation(ctx, opts, token, clientId)).payload;\n}\nasync function requireActiveAccessToken(ctx, opts, token, clientId) {\n\tconst payload = await validateAccessToken(ctx, opts, token, clientId);\n\tif (payload.active) return payload;\n\tthrow createInvalidAccessTokenError();\n}\n/**\n* UserInfo entry point: validates the access token, requires it active, and\n* returns the introspection payload together with the OIDC `claims.userinfo`\n* names persisted for the token. Opaque tokens carry the names on their row;\n* JWT access tokens return an empty list and resolve UserInfo claims by scope.\n*/\nasync function requireActiveAccessTokenWithClaims(ctx, opts, token, clientId) {\n\tconst { payload, requestedUserInfoClaims } = await resolveAccessTokenValidation(ctx, opts, token, clientId);\n\tif (payload.active) return {\n\t\tpayload,\n\t\trequestedUserInfoClaims\n\t};\n\tthrow createInvalidAccessTokenError();\n}\n/**\n* Resolves pairwise sub on an introspection payload.\n* Applied at the presentation layer so internal validation functions\n* keep real user.id (needed for user lookup in /userinfo).\n*/\nasync function resolveIntrospectionSub(ctx, opts, payload, introspectingClient) {\n\tif (!payload.active || !payload.sub) return payload;\n\tconst issuerClientId = payload.client_id ?? payload.azp;\n\tif (!issuerClientId) return payload;\n\tconst issuingClient = issuerClientId === introspectingClient.clientId ? introspectingClient : await getClient(ctx, opts, issuerClientId);\n\tif (!issuingClient) return payload;\n\tconst resolvedSub = await resolveSubjectIdentifier(payload.sub, issuingClient, opts);\n\treturn {\n\t\t...payload,\n\t\tsub: resolvedSub\n\t};\n}\nasync function introspectEndpoint(ctx, opts) {\n\tlet { token, token_type_hint } = ctx.body;\n\tif (token_type_hint !== \"access_token\" && token_type_hint !== \"refresh_token\") token_type_hint = void 0;\n\tconst { clientId: client_id, clientSecret: client_secret, preVerified, authMethod } = destructureCredentials(await extractClientCredentials(ctx, opts, `${ctx.context.baseURL}/oauth2/introspect`));\n\tif (!client_id || !client_secret && !preVerified) throw new APIError$1(\"UNAUTHORIZED\", {\n\t\terror_description: \"missing required credentials\",\n\t\terror: \"invalid_client\"\n\t});\n\tif (token && typeof token === \"string\") token = stripAccessTokenAuthorizationScheme(token);\n\tif (!token?.length) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"missing a required token for introspection\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst client = await validateClientCredentials(ctx, opts, client_id, client_secret, void 0, preVerified, void 0, authMethod);\n\ttry {\n\t\tif (token_type_hint === void 0 || token_type_hint === \"access_token\") try {\n\t\t\treturn resolveIntrospectionSub(ctx, opts, await validateAccessToken(ctx, opts, token, client.clientId), client);\n\t\t} catch (error) {\n\t\t\tif (error instanceof APIError$1) {\n\t\t\t\tif (token_type_hint === \"access_token\") throw error;\n\t\t\t} else if (error instanceof Error) throw error;\n\t\t\telse throw new Error(error);\n\t\t}\n\t\tif (token_type_hint === void 0 || token_type_hint === \"refresh_token\") try {\n\t\t\treturn resolveIntrospectionSub(ctx, opts, await validateRefreshToken(ctx, opts, (await decodeRefreshToken(opts, token)).token, client.clientId), client);\n\t\t} catch (error) {\n\t\t\tif (error instanceof APIError$1) {\n\t\t\t\tif (token_type_hint === \"refresh_token\") throw error;\n\t\t\t} else if (error instanceof Error) throw error;\n\t\t\telse throw new Error(error);\n\t\t}\n\t\tthrow new APIError$1(\"BAD_REQUEST\", {\n\t\t\terror_description: \"token not found\",\n\t\t\terror: \"invalid_request\"\n\t\t});\n\t} catch (error) {\n\t\tif (error instanceof APIError$1) {\n\t\t\tif (isInactiveTokenError(error)) return { active: false };\n\t\t\tthrow error;\n\t\t} else if (error instanceof Error) {\n\t\t\tlogger.error(\"Introspection error:\", error.message, error.stack);\n\t\t\tthrow new APIError$1(\"INTERNAL_SERVER_ERROR\");\n\t\t} else {\n\t\t\tlogger.error(\"Introspection error:\", error);\n\t\t\tthrow new APIError$1(\"INTERNAL_SERVER_ERROR\");\n\t\t}\n\t}\n}\n//#endregion\nexport { claimsRequestParameterSchema as A, clientJwksSchema as C, STANDARD_CLAIM_NAMES as D, STANDARD_CLAIMS as E, getRequestedUserInfoClaims as M, isValidOidcClaimsRequest as N, getSupportedClaims as O, authorizationQuerySchema as S, oauthClientMetadataSchema as T, logStartupSeedFailure as _, invalidateRefreshFamily as a, ResourceUriSchema as b, normalizeClientCredentialsScopes as c, assertIdentifierValid as d, extractRepeatedResourceFromForm as f, logEnforcePerClientResourcesResolution as g, isAudienceClaimAllowed as h, getOAuthProviderApi as i, filterClaimsRequestUserInfoClaims as j, canSatisfyEssentialAcrRequest as k, validateClientCredentialsScopes as l, invalidateResourceCache as m, introspect_exports as n, tokenEndpoint as o, getResource as p, decodeRefreshToken as r, userInfoEndpoint as s, introspectEndpoint as t, JWS_ALGORITHMS as u, resolveResourcePolicy as v, clientRegistrationRequestSchema as w, SafeUrlSchema as x, seedResourcesOnce as y };\n","//#endregion\n//#region src/version.ts\nconst PACKAGE_VERSION = \"1.7.8\";\n//#endregion\nexport { PACKAGE_VERSION as t };\n","//#region src/utils/fetch-metadata.ts\nfunction isBrowserFetchRequest(headers) {\n\treturn headers?.get(\"sec-fetch-mode\") === \"cors\";\n}\n//#endregion\nexport { isBrowserFetchRequest };\n","import { t as __exportAll } from \"./rolldown-runtime-wcPFST8Q.mjs\";\nimport { A as claimsRequestParameterSchema, C as clientJwksSchema, D as STANDARD_CLAIM_NAMES, E as STANDARD_CLAIMS, M as getRequestedUserInfoClaims, N as isValidOidcClaimsRequest, O as getSupportedClaims, S as authorizationQuerySchema, _ as logStartupSeedFailure, a as invalidateRefreshFamily, b as ResourceUriSchema, c as normalizeClientCredentialsScopes, d as assertIdentifierValid, f as extractRepeatedResourceFromForm, g as logEnforcePerClientResourcesResolution, h as isAudienceClaimAllowed, j as filterClaimsRequestUserInfoClaims, k as canSatisfyEssentialAcrRequest, l as validateClientCredentialsScopes, m as invalidateResourceCache, o as tokenEndpoint, p as getResource, r as decodeRefreshToken, s as userInfoEndpoint, t as introspectEndpoint, u as JWS_ALGORITHMS, v as resolveResourcePolicy, w as clientRegistrationRequestSchema, x as SafeUrlSchema, y as seedResourcesOnce } from \"./introspect-H3uoUiuS.mjs\";\nimport { B as validateOAuthProviderExtensions, C as storeToken, E as validateClientCredentials, I as getSupportedAuthMethods, L as getSupportedGrantTypes, O as verifyOAuthQueryParams, P as getClientDiscoveries, S as storeClientSecret, T as toResourceList, _ as removeMaxAgeFromQuery, a as getClient, b as resolveSubjectIdentifier, c as getStoredToken, d as mergeDiscoveryMetadata, g as parsePrompt, h as parseClientMetadata, i as extractClientCredentials, k as applyOAuthProviderMetadataExtensions, l as isPKCERequired, m as parseBearerToken, n as decryptStoredClientSecret, o as getJwtPlugin, r as destructureCredentials, t as clientAllowsGrant, u as isSessionFreshForSignedQuery, v as removePromptFromQuery, x as searchParamsToQuery, z as isExtensionTokenEndpointAuthMethod } from \"./utils-CGIZS-Da.mjs\";\nimport { a as setSignedOAuthQueryParameterNames, i as postLoginClearedParam, n as canonicalizeOAuthQueryParams, o as signedQueryIssuedAtParam, r as getSignedQueryIssuedAt } from \"./signed-query-Df1MNiSH.mjs\";\nimport { t as PACKAGE_VERSION } from \"./version-BPS0os17.mjs\";\nimport { isBrowserFetchRequest } from \"@better-auth/core/utils/fetch-metadata\";\nimport { isLoopbackHost, isLoopbackIP, isPublicRoutableHost } from \"@better-auth/core/utils/host\";\nimport { appendQueryParams } from \"@better-auth/core/utils/url\";\nimport { APIError, NO_STORE_HEADERS, addOAuthServerContext, createAuthEndpoint, createAuthMiddleware, dispatchAuthEndpoint, getOAuthState, getSessionFromCtx, sessionMiddleware } from \"better-auth/api\";\nimport { generateRandomString, makeSignature } from \"better-auth/crypto\";\nimport { APIError as APIError$1 } from \"better-call\";\nimport { logger } from \"@better-auth/core/env\";\nimport * as z from \"zod\";\nimport { defineRequestState, getCurrentAdapter, runWithTransaction } from \"@better-auth/core/context\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\nimport { deleteSessionCookie, parseSetCookieHeader } from \"better-auth/cookies\";\nimport { mergeSchema } from \"better-auth/db\";\nimport { CLIENT_ASSERTION_TYPE, DPOP_SIGNING_ALGORITHMS, PRIVATE_KEY_JWT_SIGNING_ALGORITHMS } from \"@better-auth/core/oauth2\";\nimport { createHash } from \"@better-auth/utils/hash\";\nimport { getJwks, stripAccessTokenAuthorizationScheme } from \"better-auth/oauth2\";\nimport { compactVerify, createLocalJWKSet, decodeJwt, decodeProtectedHeader, jwtVerify } from \"jose\";\nimport { isNativePrivateUseRedirectUri } from \"@better-auth/core/utils/redirect-uri\";\nimport { resolveSigningKey, signJWT, toExpJWT } from \"better-auth/plugins\";\nimport { encodeDeterministicId } from \"@better-auth/core/db/internal\";\n//#region src/consent.ts\nasync function consentEndpoint(ctx, opts, authorize) {\n\tconst oauthRequest = await oAuthState.get();\n\tconst _query = oauthRequest?.query;\n\tif (!_query) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"missing oauth query\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst query = new URLSearchParams(_query);\n\tconst originalRequestedScopes = query.get(\"scope\")?.split(\" \") ?? [];\n\tconst supportedClaims = getSupportedClaims(opts);\n\tconst originalRequestedUserInfoClaims = getRequestedUserInfoClaims(query.get(\"claims\"), supportedClaims);\n\tconst clientId = query.get(\"client_id\");\n\tif (!clientId) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"client_id is required\",\n\t\terror: \"invalid_client\"\n\t});\n\tconst requestedScopes = ctx.body.scope?.split(\" \");\n\tif (requestedScopes) {\n\t\tif (!requestedScopes.every((sc) => originalRequestedScopes?.includes(sc))) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror_description: \"Scope not originally requested\",\n\t\t\terror: \"invalid_request\"\n\t\t});\n\t}\n\tconst acceptedClaims = ctx.body.claims;\n\tconst acceptedUserInfoClaims = acceptedClaims !== void 0 ? getRequestedUserInfoClaims(acceptedClaims, supportedClaims) : originalRequestedUserInfoClaims;\n\tif (acceptedClaims !== void 0 && !acceptedUserInfoClaims.every((claim) => originalRequestedUserInfoClaims.includes(claim))) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"Claim not originally requested\",\n\t\terror: \"invalid_request\"\n\t});\n\tif (!(ctx.body.accept === true)) return {\n\t\tredirect: true,\n\t\turl: formatErrorURL(query.get(\"redirect_uri\") ?? \"\", \"access_denied\", \"User denied access\", query.get(\"state\") ?? void 0, getIssuer(ctx, opts))\n\t};\n\tconst session = await getSessionFromCtx(ctx);\n\tconst hasLoginPrompt = parsePrompt(query.get(\"prompt\") ?? \"\").has(\"login\");\n\tconst hasSatisfiedLoginPrompt = hasLoginPrompt && isSessionFreshForSignedQuery(session?.session.createdAt, oauthRequest?.signedQueryIssuedAt);\n\tif (hasLoginPrompt && !hasSatisfiedLoginPrompt) {\n\t\tctx?.headers?.set(\"accept\", \"application/json\");\n\t\tctx.query = searchParamsToQuery(query);\n\t\treturn await authorize(ctx);\n\t}\n\tconst referenceId = await opts.postLogin?.consentReferenceId?.({\n\t\tuser: session?.user,\n\t\tsession: session?.session,\n\t\tscopes: requestedScopes ?? originalRequestedScopes\n\t});\n\tconst foundConsent = await ctx.context.adapter.findOne({\n\t\tmodel: \"oauthConsent\",\n\t\twhere: [\n\t\t\t{\n\t\t\t\tfield: \"clientId\",\n\t\t\t\tvalue: clientId\n\t\t\t},\n\t\t\t{\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: session?.user.id\n\t\t\t},\n\t\t\t...referenceId ? [{\n\t\t\t\tfield: \"referenceId\",\n\t\t\t\tvalue: referenceId\n\t\t\t}] : []\n\t\t]\n\t});\n\tconst iat = Math.floor(Date.now() / 1e3);\n\tconst resource = query.getAll(\"resource\");\n\tconst consent = {\n\t\tclientId,\n\t\tuserId: session?.user.id,\n\t\tscopes: requestedScopes ?? originalRequestedScopes,\n\t\trequestedUserInfoClaims: acceptedUserInfoClaims,\n\t\tcreatedAt: /* @__PURE__ */ new Date(iat * 1e3),\n\t\tupdatedAt: /* @__PURE__ */ new Date(iat * 1e3),\n\t\tresources: resource.length ? resource : void 0,\n\t\treferenceId\n\t};\n\tfoundConsent?.id ? await ctx.context.adapter.update({\n\t\tmodel: \"oauthConsent\",\n\t\twhere: [{\n\t\t\tfield: \"id\",\n\t\t\tvalue: foundConsent.id\n\t\t}],\n\t\tupdate: {\n\t\t\tresources: consent.resources,\n\t\t\tscopes: consent.scopes,\n\t\t\trequestedUserInfoClaims: consent.requestedUserInfoClaims,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date(iat * 1e3)\n\t\t}\n\t}) : await ctx.context.adapter.create({\n\t\tmodel: \"oauthConsent\",\n\t\tdata: {\n\t\t\t...consent,\n\t\t\tscopes: consent.scopes\n\t\t}\n\t});\n\tif (requestedScopes) query.set(\"scope\", consent.scopes.join(\" \"));\n\tif (acceptedClaims !== void 0) {\n\t\tconst claimsRequest = filterClaimsRequestUserInfoClaims(query.get(\"claims\"), acceptedUserInfoClaims);\n\t\tif (claimsRequest) query.set(\"claims\", JSON.stringify(claimsRequest));\n\t\telse query.delete(\"claims\");\n\t}\n\tctx?.headers?.set(\"accept\", \"application/json\");\n\tlet authorizationQuery = removePromptFromQuery(query, \"consent\");\n\tif (hasSatisfiedLoginPrompt) {\n\t\tauthorizationQuery = removePromptFromQuery(authorizationQuery, \"login\");\n\t\tauthorizationQuery = removeMaxAgeFromQuery(authorizationQuery);\n\t}\n\tctx.query = searchParamsToQuery(authorizationQuery);\n\treturn await authorize(ctx, { postLogin: oauthRequest?.postLoginClearedForSession !== void 0 && oauthRequest.postLoginClearedForSession === session?.session.id });\n}\n//#endregion\n//#region src/continue.ts\nasync function continueEndpoint(ctx, authorize) {\n\tif (ctx.body.selected === true) return await selected(ctx, authorize);\n\telse if (ctx.body.created === true) return await created(ctx, authorize);\n\telse if (ctx.body.postLogin === true) return await postLogin(ctx, authorize);\n\telse throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"Missing parameters\",\n\t\terror: \"invalid_request\"\n\t});\n}\nasync function selected(ctx, authorize) {\n\tconst _query = (await oAuthState.get())?.query;\n\tif (!_query) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"missing oauth query\",\n\t\terror: \"invalid_request\"\n\t});\n\tctx.headers?.set(\"accept\", \"application/json\");\n\tctx.query = searchParamsToQuery(removePromptFromQuery(new URLSearchParams(_query), \"select_account\"));\n\treturn await authorize(ctx);\n}\nasync function created(ctx, authorize) {\n\tconst _query = (await oAuthState.get())?.query;\n\tif (!_query) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"missing oauth query\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst query = new URLSearchParams(_query);\n\tctx.headers?.set(\"accept\", \"application/json\");\n\tctx.query = searchParamsToQuery(removePromptFromQuery(query, \"create\"));\n\treturn await authorize(ctx);\n}\nasync function postLogin(ctx, authorize) {\n\tconst state = await oAuthState.get();\n\tconst _query = state?.query;\n\tif (!_query) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"missing oauth query\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst query = new URLSearchParams(_query);\n\tctx.headers?.set(\"accept\", \"application/json\");\n\tctx.query = searchParamsToQuery(query);\n\tconst session = await getSessionFromCtx(ctx);\n\treturn await authorize(ctx, { postLogin: state?.postLoginClearedForSession !== void 0 && state.postLoginClearedForSession === session?.session.id });\n}\n//#endregion\n//#region src/logout.ts\nconst BACKCHANNEL_LOGOUT_EVENT_URI = \"http://schemas.openid.net/event/backchannel-logout\";\nconst LOGOUT_TOKEN_JWT_TYP = \"logout+jwt\";\nconst LOGOUT_TOKEN_LIFETIME_SECONDS = 120;\nconst BACKCHANNEL_DISPATCH_TIMEOUT_MS = 5e3;\n/**\n* Signs a Back-Channel Logout Token per OIDC Back-Channel Logout 1.0 §2.4.\n*\n* The token reuses the ID Token signing key so any RP that validates ID Tokens\n* from this OP can validate Logout Tokens without extra configuration. The\n* caller resolves that key once and passes it in so a fan-out to many RPs does\n* not re-read it per target.\n*\n* §2.4 mandates `iss`, `aud`, `iat`, `exp`, `jti`, `events`, and at least one\n* of `sub` / `sid` (we send both). A `nonce` claim MUST NOT be present, and\n* `alg: none` is forbidden (§2.6).\n*/\nasync function signLogoutToken(ctx, options, resolvedKey, claims) {\n\treturn signJWT(ctx, {\n\t\toptions,\n\t\tpayload: {\n\t\t\t...claims,\n\t\t\tevents: { [BACKCHANNEL_LOGOUT_EVENT_URI]: {} }\n\t\t},\n\t\theader: { typ: LOGOUT_TOKEN_JWT_TYP },\n\t\tresolvedKey: resolvedKey ?? void 0\n\t});\n}\n/**\n* Build the immutable work plan before a session is deleted. This phase only\n* reads database state because a later delete hook may still veto the mutation.\n* Token identifiers must be captured here because their `sessionId` foreign key\n* is cleared when the session row disappears.\n*\n* Revocation is the stored backstop, not the primary enforcement: introspection\n* and `/userinfo` already treat a token whose session has ended as inactive\n* (see `validateOpaqueAccessToken` / `validateJwtAccessToken`), so a missed\n* `revoked` write cannot keep a session-bound token alive on its own. Access\n* tokens bound to the session are revoked as OP hardening. Refresh tokens\n* follow OIDC Back-Channel Logout 1.0 §2.7: those without `offline_access` are\n* revoked; `offline_access` refresh tokens survive so long-lived API access can\n* outlive the browser session.\n*\n* Token revocation runs regardless of the JWT plugin (refresh-token revocation\n* has no dependency on signing). Only Logout Token delivery needs the JWT\n* plugin, so a plan may contain token identifiers with no delivery targets.\n*\n* Returns `null` when there is nothing to do, so the caller can skip the\n* background handoff entirely.\n*/\nasync function prepareBackchannelLogoutPlan(ctx, opts, input) {\n\tconst { sessionId, userId } = input;\n\tif (!userId) return null;\n\tconst logger = ctx.context.logger;\n\ttry {\n\t\tconst adapter = await getCurrentAdapter(ctx.context.adapter);\n\t\tconst where = [{\n\t\t\tfield: \"sessionId\",\n\t\t\tvalue: sessionId\n\t\t}];\n\t\tconst [accessTokens, refreshTokens] = await Promise.all([adapter.findMany({\n\t\t\tmodel: \"oauthAccessToken\",\n\t\t\twhere\n\t\t}), adapter.findMany({\n\t\t\tmodel: \"oauthRefreshToken\",\n\t\t\twhere\n\t\t})]);\n\t\tconst affectedClientIds = /* @__PURE__ */ new Set();\n\t\tfor (const t of accessTokens) affectedClientIds.add(t.clientId);\n\t\tfor (const t of refreshTokens) affectedClientIds.add(t.clientId);\n\t\tif (affectedClientIds.size === 0) return null;\n\t\tconst clients = await adapter.findMany({\n\t\t\tmodel: \"oauthClient\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"clientId\",\n\t\t\t\toperator: \"in\",\n\t\t\t\tvalue: Array.from(affectedClientIds)\n\t\t\t}]\n\t\t});\n\t\tconst accessToRevokeIds = accessTokens.filter((t) => !t.revoked).map((t) => t.id);\n\t\tconst refreshToRevokeIds = refreshTokens.filter((t) => !t.revoked && !t.scopes?.includes(\"offline_access\")).map((t) => t.id);\n\t\tconst eligibleClients = opts.disableJwtPlugin ? [] : clients.filter((c) => Boolean(c.backchannelLogoutUri) && !c.disabled);\n\t\treturn {\n\t\t\taccessTokenIds: accessToRevokeIds,\n\t\t\trefreshTokenIds: refreshToRevokeIds,\n\t\t\tsessionId,\n\t\t\ttargets: (await Promise.all(eligibleClients.map(async (client) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tclient,\n\t\t\t\t\t\tsub: await resolveSubjectIdentifier(userId, client, opts)\n\t\t\t\t\t};\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.warn(`back-channel logout: unable to resolve subject for client ${client.clientId}`, error);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t}))).filter((target) => target !== null)\n\t\t};\n\t} catch (error) {\n\t\tlogger.error(\"back-channel logout planning failed\", error);\n\t\treturn null;\n\t}\n}\n/**\n* Apply a prepared logout plan after the session deletion succeeds. Core runs\n* `session.delete.after` after the row is consumed and, for transactional\n* callers, only after the transaction commits.\n*/\nasync function applyBackchannelLogoutPlan(ctx, plan) {\n\tconst revokedAt = /* @__PURE__ */ new Date();\n\tconst adapter = await getCurrentAdapter(ctx.context.adapter);\n\tconst revocations = await Promise.allSettled([plan.accessTokenIds.length > 0 ? adapter.updateMany({\n\t\tmodel: \"oauthAccessToken\",\n\t\twhere: [{\n\t\t\tfield: \"id\",\n\t\t\toperator: \"in\",\n\t\t\tvalue: plan.accessTokenIds\n\t\t}],\n\t\tupdate: { revoked: revokedAt }\n\t}) : Promise.resolve(), plan.refreshTokenIds.length > 0 ? adapter.updateMany({\n\t\tmodel: \"oauthRefreshToken\",\n\t\twhere: [{\n\t\t\tfield: \"id\",\n\t\t\toperator: \"in\",\n\t\t\tvalue: plan.refreshTokenIds\n\t\t}],\n\t\tupdate: { revoked: revokedAt }\n\t}) : Promise.resolve()]);\n\tfor (const result of revocations) if (result.status === \"rejected\") ctx.context.logger.error(\"back-channel logout: token revocation update failed\", result.reason);\n\tif (plan.targets.length > 0) await deliverBackchannelLogoutTokens(ctx, plan);\n}\n/**\n* Asynchronous phase: sign one Logout Token per target client and POST it to\n* the registered `backchannel_logout_uri`. The caller hands this to\n* `runInBackgroundOrAwait`, so when a background handler is configured (Vercel\n* `waitUntil`, Cloudflare `ctx.waitUntil`) it runs after the response; without\n* one it completes inline so delivery is not lost on request teardown.\n*\n* Spec §2.5: \"the OP SHOULD NOT retransmit\", so each RP gets a single attempt\n* within `BACKCHANNEL_DISPATCH_TIMEOUT_MS`. Every per-client failure (fetch\n* error, non-2xx response, signing error, subject resolution error) is\n* logged; none of them can reject the outer promise.\n*/\nasync function deliverBackchannelLogoutTokens(ctx, plan) {\n\tconst logger = ctx.context.logger;\n\tconst jwtPluginOptions = getJwtPlugin(ctx.context)?.options;\n\tconst iss = jwtPluginOptions?.jwt?.issuer ?? ctx.context.baseURL;\n\tconst iat = Math.floor(Date.now() / 1e3);\n\tconst exp = iat + LOGOUT_TOKEN_LIFETIME_SECONDS;\n\tconst resolvedKey = jwtPluginOptions?.jwt?.sign ? null : await resolveSigningKey(ctx, jwtPluginOptions);\n\tawait Promise.allSettled(plan.targets.map(async ({ client, sub }) => {\n\t\ttry {\n\t\t\tconst jti = generateRandomString(32, \"a-z\", \"A-Z\", \"0-9\");\n\t\t\tconst token = await signLogoutToken(ctx, jwtPluginOptions, resolvedKey, {\n\t\t\t\tiss,\n\t\t\t\taud: client.clientId,\n\t\t\t\tsub,\n\t\t\t\tsid: plan.sessionId,\n\t\t\t\tiat,\n\t\t\t\texp,\n\t\t\t\tjti\n\t\t\t});\n\t\t\tconst response = await fetch(client.backchannelLogoutUri, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\t\t\tAccept: \"application/json\"\n\t\t\t\t},\n\t\t\t\tbody: new URLSearchParams({ logout_token: token }),\n\t\t\t\tsignal: AbortSignal.timeout(BACKCHANNEL_DISPATCH_TIMEOUT_MS),\n\t\t\t\tredirect: \"error\"\n\t\t\t});\n\t\t\tif (response.status !== 200 && response.status !== 204) logger.warn(`back-channel logout to client ${client.clientId} returned ${response.status}`);\n\t\t} catch (error) {\n\t\t\tlogger.warn(`back-channel logout to client ${client.clientId} failed`, error);\n\t\t}\n\t}));\n}\nconst LOGOUT_CONFIRMATION_TTL_SECONDS = 300;\nconst LOGOUT_CONFIRMATION_COOKIE_SUFFIX = \".oauth_logout_confirmation\";\nfunction escapeHtml(value) {\n\treturn value.replace(/[&<>\"']/g, (character) => {\n\t\tswitch (character) {\n\t\t\tcase \"&\": return \"&amp;\";\n\t\t\tcase \"<\": return \"&lt;\";\n\t\t\tcase \">\": return \"&gt;\";\n\t\t\tcase \"\\\"\": return \"&quot;\";\n\t\t\tcase \"'\": return \"&#39;\";\n\t\t\tdefault: return character;\n\t\t}\n\t});\n}\nfunction isBrowserNavigation(ctx) {\n\tconst headers = ctx.request?.headers ?? ctx.headers;\n\tif (!headers || isBrowserFetchRequest(headers)) return false;\n\tconst accept = headers.get(\"accept\") ?? \"\";\n\treturn headers.get(\"sec-fetch-mode\") === \"navigate\" || accept.includes(\"text/html\") || accept.includes(\"application/xhtml+xml\");\n}\nfunction logoutPage(title, body, status = 200) {\n\treturn new Response(`<!doctype html><html><head><meta charset=\"utf-8\"><title>${escapeHtml(title)}</title></head><body>${body}</body></html>`, {\n\t\tstatus,\n\t\theaders: {\n\t\t\t\"cache-control\": \"no-store\",\n\t\t\t\"content-security-policy\": \"default-src 'none'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'\",\n\t\t\t\"content-type\": \"text/html; charset=utf-8\",\n\t\t\tpragma: \"no-cache\",\n\t\t\t\"x-content-type-options\": \"nosniff\"\n\t\t}\n\t});\n}\nfunction logoutConfirmationPath(ctx) {\n\treturn `${ctx.context.baseURL.replace(/\\/$/, \"\")}/oauth2/end-session/confirm`;\n}\nfunction logoutConfirmationCookiePath(ctx) {\n\ttry {\n\t\treturn new URL(logoutConfirmationPath(ctx)).pathname;\n\t} catch {\n\t\treturn \"/oauth2/end-session/confirm\";\n\t}\n}\nfunction logoutConfirmationPage(ctx) {\n\treturn logoutPage(\"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=\"${escapeHtml(logoutConfirmationPath(ctx))}\"><button type=\"submit\" name=\"action\" value=\"confirm\">Confirm logout</button></form></main>`);\n}\nfunction logoutSuccessPage(note) {\n\treturn logoutPage(\"Logged out\", `<main><p data-oidc-logout-state=\"logged-out\">${note ? `Logged out. ${escapeHtml(note)}` : \"Logged out.\"}</p></main>`);\n}\nfunction logoutErrorPage(description, status) {\n\treturn logoutPage(\"Logout error\", `<main><h1>Logout error</h1><p data-oidc-logout-state=\"error\">${escapeHtml(description)}</p></main>`, status);\n}\nfunction logoutProtocolError(ctx, status, error, description) {\n\tif (isBrowserNavigation(ctx)) return logoutErrorPage(description, status === \"BAD_REQUEST\" ? 400 : status === \"UNAUTHORIZED\" ? 401 : 500);\n\tthrow new APIError$1(status, {\n\t\terror,\n\t\terror_description: description\n\t});\n}\nfunction logoutConfirmationCookieName(ctx) {\n\treturn `${ctx.context.authCookies.sessionToken.name}${LOGOUT_CONFIRMATION_COOKIE_SUFFIX}`;\n}\nfunction logoutConfirmationCookieOptions(ctx, maxAge) {\n\treturn {\n\t\t...ctx.context.authCookies.sessionToken.attributes,\n\t\thttpOnly: true,\n\t\tmaxAge,\n\t\tpath: logoutConfirmationCookiePath(ctx),\n\t\tsameSite: \"lax\"\n\t};\n}\nasync function setLogoutConfirmationState(ctx, sessionId, confirmation = {}) {\n\tconst state = {\n\t\t...sessionId ? { sessionId } : {},\n\t\t...confirmation,\n\t\texpiresAt: Date.now() + LOGOUT_CONFIRMATION_TTL_SECONDS * 1e3\n\t};\n\tawait ctx.setSignedCookie(logoutConfirmationCookieName(ctx), JSON.stringify(state), ctx.context.secret, logoutConfirmationCookieOptions(ctx, LOGOUT_CONFIRMATION_TTL_SECONDS));\n}\nasync function getLogoutConfirmationState(ctx) {\n\tconst value = await ctx.getSignedCookie(logoutConfirmationCookieName(ctx), ctx.context.secret);\n\tif (typeof value !== \"string\") return null;\n\ttry {\n\t\tconst parsed = JSON.parse(value);\n\t\tif (typeof parsed !== \"object\" || parsed === null) return null;\n\t\tconst record = parsed;\n\t\tif (record.sessionId !== void 0 && (typeof record.sessionId !== \"string\" || record.sessionId.length === 0) || record.clientId !== void 0 && (typeof record.clientId !== \"string\" || record.clientId.length === 0) || record.postLogoutRedirectUri !== void 0 && (typeof record.postLogoutRedirectUri !== \"string\" || record.postLogoutRedirectUri.length === 0) || record.state !== void 0 && typeof record.state !== \"string\" || record.redirectInvalid !== void 0 && typeof record.redirectInvalid !== \"boolean\" || record.postLogoutRedirectUri !== void 0 && record.clientId === void 0 || typeof record.expiresAt !== \"number\" || !Number.isFinite(record.expiresAt)) return null;\n\t\treturn {\n\t\t\t...typeof record.sessionId === \"string\" ? { sessionId: record.sessionId } : {},\n\t\t\t...typeof record.clientId === \"string\" ? { clientId: record.clientId } : {},\n\t\t\t...typeof record.postLogoutRedirectUri === \"string\" ? { postLogoutRedirectUri: record.postLogoutRedirectUri } : {},\n\t\t\t...typeof record.state === \"string\" ? { state: record.state } : {},\n\t\t\t...typeof record.redirectInvalid === \"boolean\" ? { redirectInvalid: record.redirectInvalid } : {},\n\t\t\texpiresAt: record.expiresAt\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction clearLogoutConfirmationState(ctx) {\n\tctx.setCookie(logoutConfirmationCookieName(ctx), \"\", logoutConfirmationCookieOptions(ctx, 0));\n}\nasync function getCurrentBrowserSession(ctx) {\n\tconst token = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret);\n\tif (typeof token !== \"string\" || token.length === 0) return null;\n\ttry {\n\t\tconst result = await ctx.context.internalAdapter.findSession(token);\n\t\treturn result ? { session: result.session } : null;\n\t} catch (error) {\n\t\tctx.context.logger.error(\"Failed to read the current logout session\", error);\n\t\tthrow new APIError$1(\"INTERNAL_SERVER_ERROR\", {\n\t\t\terror: \"server_error\",\n\t\t\terror_description: \"Unable to read the current session\"\n\t\t});\n\t}\n}\nasync function findHintedSession(ctx, sessionId) {\n\ttry {\n\t\treturn await ctx.context.adapter.findOne({\n\t\t\tmodel: \"session\",\n\t\t\twhere: [{\n\t\t\t\tfield: \"id\",\n\t\t\t\tvalue: sessionId\n\t\t\t}]\n\t\t});\n\t} catch (error) {\n\t\tctx.context.logger.error(\"Failed to read the hinted logout session\", error);\n\t\tthrow new APIError$1(\"INTERNAL_SERVER_ERROR\", {\n\t\t\terror: \"server_error\",\n\t\t\terror_description: \"Unable to read the hinted session\"\n\t\t});\n\t}\n}\nasync function deleteLogoutSession(ctx, session) {\n\tif (typeof session.token !== \"string\" || session.token.length === 0) throw new APIError$1(\"INTERNAL_SERVER_ERROR\", {\n\t\terror: \"server_error\",\n\t\terror_description: \"Unable to complete logout\"\n\t});\n\ttry {\n\t\tawait ctx.context.internalAdapter.deleteSession(session.token);\n\t} catch (error) {\n\t\tctx.context.logger.error(\"Failed to delete the logout session\", error);\n\t\tthrow new APIError$1(\"INTERNAL_SERVER_ERROR\", {\n\t\t\terror: \"server_error\",\n\t\t\terror_description: \"Unable to complete logout\"\n\t\t});\n\t}\n}\nasync function getLogoutClient(ctx, opts, clientId) {\n\ttry {\n\t\treturn await getClient(ctx, opts, clientId);\n\t} catch (error) {\n\t\tctx.context.logger.error(\"Failed to resolve the logout client\", error);\n\t\tthrow new APIError$1(\"INTERNAL_SERVER_ERROR\", {\n\t\t\terror: \"server_error\",\n\t\t\terror_description: \"Unable to resolve the logout client\"\n\t\t});\n\t}\n}\nfunction normalizeLogoutAudiences(value) {\n\treturn (Array.isArray(value) ? value : [value]).filter((candidate) => typeof candidate === \"string\");\n}\nfunction getHintClientId(payload) {\n\tif (typeof payload.aud === \"string\" && payload.aud.length > 0) return payload.aud;\n\tif (typeof payload.azp === \"string\" && payload.azp.length > 0) return payload.azp;\n\tconst audiences = normalizeLogoutAudiences(payload.aud);\n\treturn audiences.length === 1 ? audiences[0] : null;\n}\nasync function resolveHintClient(ctx, opts, hint, clientId) {\n\tif (clientId) return getLogoutClient(ctx, opts, clientId);\n\tlet decoded;\n\ttry {\n\t\tdecoded = decodeJwt(hint);\n\t} catch {\n\t\treturn null;\n\t}\n\tconst candidate = getHintClientId(decoded);\n\treturn candidate ? getLogoutClient(ctx, opts, candidate) : null;\n}\nasync function verifyLogoutHint(ctx, opts, hint, client) {\n\ttry {\n\t\tlet payload;\n\t\tif (opts.disableJwtPlugin) {\n\t\t\tif (!client.clientSecret) return null;\n\t\t\tconst secret = await decryptStoredClientSecret(ctx, opts.storeClientSecret, client.clientSecret);\n\t\t\tconst { payload: verifiedPayload } = await compactVerify(hint, new TextEncoder().encode(secret));\n\t\t\tpayload = JSON.parse(new TextDecoder().decode(verifiedPayload));\n\t\t} else {\n\t\t\tconst jwtPluginOptions = getJwtPlugin(ctx.context).options;\n\t\t\tconst { payload: verifiedPayload } = await compactVerify(hint, createLocalJWKSet(await getJwks(hint, { jwksFetch: jwtPluginOptions?.jwks?.remoteUrl ?? `${ctx.context.baseURL}${jwtPluginOptions?.jwks?.jwksPath ?? \"/jwks\"}` })));\n\t\t\tpayload = JSON.parse(new TextDecoder().decode(verifiedPayload));\n\t\t}\n\t\tif (payload.iss !== getIssuer(ctx, opts)) return null;\n\t\tif (!normalizeLogoutAudiences(payload.aud).includes(client.clientId)) return null;\n\t\tif (typeof payload.sid !== \"string\" || payload.sid.length === 0 || typeof payload.sub !== \"string\" || payload.sub.length === 0) return null;\n\t\treturn payload;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction getRegisteredLogoutRedirect(client, requestedURI, state) {\n\tif (!requestedURI) return { invalid: false };\n\tif (!client.postLogoutRedirectUris?.includes(requestedURI)) return { invalid: true };\n\tif (!state) return {\n\t\turi: requestedURI,\n\t\tinvalid: false\n\t};\n\ttry {\n\t\tconst redirectURI = new URL(requestedURI);\n\t\tredirectURI.searchParams.set(\"state\", state);\n\t\treturn {\n\t\t\turi: redirectURI.toString(),\n\t\t\tinvalid: false\n\t\t};\n\t} catch {\n\t\treturn { invalid: true };\n\t}\n}\nfunction getLogoutConfirmationContext(client, request) {\n\tif (!request.post_logout_redirect_uri) return {};\n\tif (getRegisteredLogoutRedirect(client, request.post_logout_redirect_uri, request.state).invalid) return { redirectInvalid: true };\n\treturn {\n\t\tclientId: client.clientId,\n\t\tpostLogoutRedirectUri: request.post_logout_redirect_uri,\n\t\t...request.state !== void 0 ? { state: request.state } : {}\n\t};\n}\nasync function getConfirmedLogoutRedirect(ctx, opts, state) {\n\tif (state.redirectInvalid) return { invalid: true };\n\tif (!state.clientId || !state.postLogoutRedirectUri) return { invalid: false };\n\tconst client = await getLogoutClient(ctx, opts, state.clientId);\n\tif (!client || client.disabled || !client.enableEndSession) return { invalid: true };\n\treturn getRegisteredLogoutRedirect(client, state.postLogoutRedirectUri, state.state);\n}\nasync function confirmationRequired(ctx, currentSession, confirmation = {}) {\n\tif (!currentSession) {\n\t\tif (isBrowserNavigation(ctx)) {\n\t\t\tawait setLogoutConfirmationState(ctx, void 0, confirmation);\n\t\t\treturn logoutConfirmationPage(ctx);\n\t\t}\n\t\treturn logoutProtocolError(ctx, \"BAD_REQUEST\", \"invalid_request\", \"No active session is available for logout\");\n\t}\n\tif (!isBrowserNavigation(ctx)) return logoutProtocolError(ctx, \"BAD_REQUEST\", \"invalid_request\", \"User confirmation is required to complete logout\");\n\tawait setLogoutConfirmationState(ctx, currentSession.session.id, confirmation);\n\treturn logoutConfirmationPage(ctx);\n}\nasync function completeConfirmedLogout(ctx, opts) {\n\tconst state = await getLogoutConfirmationState(ctx);\n\tconst currentSession = await getCurrentBrowserSession(ctx);\n\tif (!state || state.expiresAt <= Date.now()) return logoutProtocolError(ctx, \"BAD_REQUEST\", \"invalid_request\", \"The logout confirmation is invalid or expired\");\n\tconst redirect = await getConfirmedLogoutRedirect(ctx, opts, state);\n\tif (!currentSession) {\n\t\tclearLogoutConfirmationState(ctx);\n\t\tif (redirect.uri) return handleRedirect(ctx, redirect.uri);\n\t\treturn isBrowserNavigation(ctx) ? logoutSuccessPage(redirect.invalid ? \"The requested post-logout redirect was not registered.\" : void 0) : logoutProtocolError(ctx, \"BAD_REQUEST\", \"invalid_request\", \"No active session is available for logout\");\n\t}\n\tif (state.sessionId && state.sessionId !== currentSession.session.id) return logoutProtocolError(ctx, \"BAD_REQUEST\", \"invalid_request\", \"The logout confirmation is invalid or expired\");\n\tawait deleteLogoutSession(ctx, currentSession.session);\n\tdeleteSessionCookie(ctx);\n\tclearLogoutConfirmationState(ctx);\n\tif (redirect.uri) return handleRedirect(ctx, redirect.uri);\n\treturn isBrowserNavigation(ctx) ? logoutSuccessPage(redirect.invalid ? \"The requested post-logout redirect was not registered.\" : void 0) : null;\n}\n/**\n* RP-Initiated Logout (OIDC RP-Initiated Logout 1.0). The RP presents a signed\n* `id_token_hint`; after verification, the OP terminates the matching session\n* and optionally redirects to `post_logout_redirect_uri`. Requests without a\n* usable hint, and hints that do not identify the current browser session, use\n* a signed, short-lived OP confirmation state before terminating that session.\n*\n* Session termination goes through `internalAdapter.deleteSession`, which fires\n* `session.delete.after` so the hook drives revocation and back-channel\n* notifications to every RP with tokens on the session.\n*\n* @see https://openid.net/specs/openid-connect-rpinitiated-1_0.html\n*/\nasync function rpInitiatedLogoutEndpoint(ctx, opts) {\n\tconst query = ctx.query ?? {};\n\tconst body = ctx.body ?? {};\n\tconst request = {\n\t\t...query,\n\t\t...body\n\t};\n\tconst currentSession = await getCurrentBrowserSession(ctx);\n\tif (!(request.id_token_hint !== void 0)) {\n\t\tlet confirmation = {};\n\t\tif (request.client_id) {\n\t\t\tconst client = await getLogoutClient(ctx, opts, request.client_id);\n\t\t\tif (!client) return logoutProtocolError(ctx, \"BAD_REQUEST\", \"invalid_client\", \"The logout client does not exist\");\n\t\t\tif (client.disabled) return logoutProtocolError(ctx, \"BAD_REQUEST\", \"invalid_client\", \"The logout client is disabled\");\n\t\t\tif (!client.enableEndSession) return logoutProtocolError(ctx, \"UNAUTHORIZED\", \"invalid_client\", \"The client is not allowed to initiate logout\");\n\t\t\tconfirmation = getLogoutConfirmationContext(client, request);\n\t\t}\n\t\treturn confirmationRequired(ctx, currentSession, confirmation);\n\t}\n\tconst client = await resolveHintClient(ctx, opts, request.id_token_hint, request.client_id);\n\tif (!client) {\n\t\tif (currentSession && isBrowserNavigation(ctx)) return confirmationRequired(ctx, currentSession);\n\t\treturn logoutProtocolError(ctx, \"BAD_REQUEST\", \"invalid_client\", \"The logout client does not exist\");\n\t}\n\tif (client.disabled) return logoutProtocolError(ctx, \"BAD_REQUEST\", \"invalid_client\", \"The logout client is disabled\");\n\tif (!client.enableEndSession) return logoutProtocolError(ctx, \"UNAUTHORIZED\", \"invalid_client\", \"The client is not allowed to initiate logout\");\n\tconst idTokenPayload = await verifyLogoutHint(ctx, opts, request.id_token_hint, client);\n\tif (!idTokenPayload) {\n\t\tif (currentSession && isBrowserNavigation(ctx)) return confirmationRequired(ctx, currentSession, request.client_id ? getLogoutConfirmationContext(client, request) : {});\n\t\treturn logoutProtocolError(ctx, \"UNAUTHORIZED\", \"invalid_token\", \"The id_token_hint is invalid\");\n\t}\n\tconst sessionId = idTokenPayload.sid;\n\tconst hintedSession = await findHintedSession(ctx, sessionId);\n\tconst matchesCurrentSession = currentSession?.session.id === sessionId;\n\tif (currentSession && !matchesCurrentSession) return confirmationRequired(ctx, currentSession, getLogoutConfirmationContext(client, request));\n\tconst redirect = getRegisteredLogoutRedirect(client, request.post_logout_redirect_uri, request.state);\n\tconst sessionToDelete = hintedSession ?? (matchesCurrentSession ? currentSession?.session : null);\n\tif (sessionToDelete) await deleteLogoutSession(ctx, sessionToDelete);\n\tif (matchesCurrentSession) deleteSessionCookie(ctx);\n\tclearLogoutConfirmationState(ctx);\n\tif (redirect.uri) return handleRedirect(ctx, redirect.uri);\n\treturn isBrowserNavigation(ctx) ? logoutSuccessPage(redirect.invalid ? \"The requested post-logout redirect was not registered.\" : void 0) : null;\n}\n/**\n* Completes the browser confirmation flow for RP-Initiated Logout. This route\n* is intentionally scoped to HTTP delivery so it does not become a generated\n* client action; the signed cookie is the only confirmation context it accepts.\n*/\nasync function rpInitiatedLogoutConfirmationEndpoint(ctx, opts) {\n\treturn completeConfirmedLogout(ctx, opts);\n}\n//#endregion\n//#region src/metadata.ts\nfunction authServerMetadata(ctx, opts, overrides) {\n\tconst baseURL = ctx.context.baseURL;\n\tconst backchannelSupported = !overrides?.jwt_disabled;\n\treturn {\n\t\tscopes_supported: overrides?.scopes_supported,\n\t\tissuer: validateIssuerUrl(opts?.jwt?.issuer ?? baseURL),\n\t\tauthorization_endpoint: `${baseURL}/oauth2/authorize`,\n\t\ttoken_endpoint: `${baseURL}/oauth2/token`,\n\t\tjwks_uri: overrides?.jwt_disabled ? void 0 : opts?.jwks?.remoteUrl ?? `${baseURL}${opts?.jwks?.jwksPath ?? \"/jwks\"}`,\n\t\tregistration_endpoint: overrides?.dynamic_client_registration_supported ? `${baseURL}/oauth2/register` : void 0,\n\t\tintrospection_endpoint: `${baseURL}/oauth2/introspect`,\n\t\trevocation_endpoint: `${baseURL}/oauth2/revoke`,\n\t\tresponse_types_supported: overrides?.grant_types_supported && !overrides.grant_types_supported.includes(\"authorization_code\") ? [] : [\"code\"],\n\t\tresponse_modes_supported: [\"query\"],\n\t\tgrant_types_supported: overrides?.grant_types_supported ?? [\n\t\t\t\"authorization_code\",\n\t\t\t\"client_credentials\",\n\t\t\t\"refresh_token\"\n\t\t],\n\t\ttoken_endpoint_auth_methods_supported: overrides?.token_endpoint_auth_methods_supported ?? [\n\t\t\t...overrides?.public_client_supported ? [\"none\"] : [],\n\t\t\t\"client_secret_basic\",\n\t\t\t\"client_secret_post\",\n\t\t\t\"private_key_jwt\"\n\t\t],\n\t\ttoken_endpoint_auth_signing_alg_values_supported: [...PRIVATE_KEY_JWT_SIGNING_ALGORITHMS],\n\t\tintrospection_endpoint_auth_methods_supported: overrides?.endpoint_auth_methods_supported ?? [\n\t\t\t\"client_secret_basic\",\n\t\t\t\"client_secret_post\",\n\t\t\t\"private_key_jwt\"\n\t\t],\n\t\tintrospection_endpoint_auth_signing_alg_values_supported: [...PRIVATE_KEY_JWT_SIGNING_ALGORITHMS],\n\t\trevocation_endpoint_auth_methods_supported: overrides?.endpoint_auth_methods_supported ?? [\n\t\t\t\"client_secret_basic\",\n\t\t\t\"client_secret_post\",\n\t\t\t\"private_key_jwt\"\n\t\t],\n\t\trevocation_endpoint_auth_signing_alg_values_supported: [...PRIVATE_KEY_JWT_SIGNING_ALGORITHMS],\n\t\tcode_challenge_methods_supported: [\"S256\"],\n\t\tauthorization_response_iss_parameter_supported: true,\n\t\tdpop_signing_alg_values_supported: overrides?.dpop_signing_alg_values_supported ?? [...DPOP_SIGNING_ALGORITHMS],\n\t\tbackchannel_logout_supported: backchannelSupported,\n\t\tbackchannel_logout_session_supported: backchannelSupported\n\t};\n}\n/**\n* Builds the authorization-server metadata shared by the\n* `/.well-known/oauth-authorization-server` and `/.well-known/openid-configuration`\n* responses, plus the inputs both need to finish their own document.\n*/\nfunction buildAuthServerMetadata(ctx, opts) {\n\tconst jwtPluginOptions = opts.disableJwtPlugin ? void 0 : getJwtPlugin(ctx.context).options;\n\tconst clientDiscoveries = getClientDiscoveries(opts);\n\tconst publicClientSupported = opts.allowUnauthenticatedClientRegistration || clientDiscoveries.length > 0;\n\treturn {\n\t\tjwtPluginOptions,\n\t\tclientDiscoveries,\n\t\tauthMetadata: authServerMetadata(ctx, jwtPluginOptions, {\n\t\t\tscopes_supported: opts.advertisedMetadata?.scopes_supported ?? opts.scopes,\n\t\t\tdynamic_client_registration_supported: opts.allowDynamicClientRegistration,\n\t\t\tpublic_client_supported: publicClientSupported,\n\t\t\tgrant_types_supported: getSupportedGrantTypes(opts),\n\t\t\ttoken_endpoint_auth_methods_supported: getSupportedAuthMethods(opts, { includeNone: publicClientSupported }),\n\t\t\tendpoint_auth_methods_supported: getSupportedAuthMethods(opts),\n\t\t\tjwt_disabled: opts.disableJwtPlugin,\n\t\t\tdpop_signing_alg_values_supported: opts.dpop?.signingAlgorithms\n\t\t})\n\t};\n}\nfunction oauthAuthorizationServerMetadata(ctx, opts) {\n\tconst { clientDiscoveries, authMetadata } = buildAuthServerMetadata(ctx, opts);\n\treturn applyOAuthProviderMetadataExtensions(ctx, opts, \"oauth-authorization-server\", {\n\t\t...mergeDiscoveryMetadata(clientDiscoveries),\n\t\t...authMetadata\n\t});\n}\nfunction oidcServerMetadata(ctx, opts) {\n\tconst baseURL = ctx.context.baseURL;\n\tconst { jwtPluginOptions, clientDiscoveries, authMetadata } = buildAuthServerMetadata(ctx, opts);\n\tconst metadata = {\n\t\t...authMetadata,\n\t\tclaims_supported: getSupportedClaims(opts),\n\t\tclaims_parameter_supported: true,\n\t\tuserinfo_endpoint: `${baseURL}/oauth2/userinfo`,\n\t\tsubject_types_supported: opts.pairwiseSecret ? [\"public\", \"pairwise\"] : [\"public\"],\n\t\tacr_values_supported: [\"0\"],\n\t\tid_token_signing_alg_values_supported: (() => {\n\t\t\tif (opts.disableJwtPlugin) return [\"HS256\"];\n\t\t\tconst primary = jwtPluginOptions?.jwks?.keyPairConfig?.alg ?? \"EdDSA\";\n\t\t\tconst extras = jwtPluginOptions?.jwks?.keyPairConfigs?.map((c) => c.alg) ?? [];\n\t\t\treturn Array.from(new Set([primary, ...extras]));\n\t\t})(),\n\t\tend_session_endpoint: `${baseURL}/oauth2/end-session`,\n\t\trequest_parameter_supported: false,\n\t\trequest_uri_parameter_supported: false,\n\t\tprompt_values_supported: [\n\t\t\t\"login\",\n\t\t\t\"consent\",\n\t\t\t\"create\",\n\t\t\t\"select_account\",\n\t\t\t\"none\"\n\t\t]\n\t};\n\treturn applyOAuthProviderMetadataExtensions(ctx, opts, \"openid-configuration\", {\n\t\t...mergeDiscoveryMetadata(clientDiscoveries),\n\t\t...metadata\n\t});\n}\nconst METADATA_CACHE_CONTROL = \"public, max-age=15, stale-while-revalidate=15, stale-if-error=86400\";\nfunction metadataResponse(body, extraHeaders) {\n\tconst headers = new Headers(extraHeaders);\n\tif (!headers.has(\"Cache-Control\")) headers.set(\"Cache-Control\", METADATA_CACHE_CONTROL);\n\theaders.set(\"Content-Type\", \"application/json\");\n\treturn new Response(JSON.stringify(body), {\n\t\tstatus: 200,\n\t\theaders\n\t});\n}\n/**\n* Provides an exportable `/.well-known/oauth-authorization-server`.\n*\n* Useful when basePath prevents the endpoint from being located at the root\n* and must be provided manually.\n*\n* @external\n*/\nconst oauthProviderAuthServerMetadata = (auth, opts) => {\n\treturn async (request) => {\n\t\treturn metadataResponse(await auth.api.getOAuthServerConfig({\n\t\t\trequest,\n\t\t\tasResponse: false\n\t\t}), opts?.headers);\n\t};\n};\n/**\n* Provides an exportable `/.well-known/openid-configuration`.\n*\n* Useful when basePath prevents the endpoint from being located at the root\n* and must be provided manually.\n*\n* @external\n*/\nconst oauthProviderOpenIdConfigMetadata = (auth, opts) => {\n\treturn async (request) => {\n\t\treturn metadataResponse(await auth.api.getOpenIdConfig({\n\t\t\trequest,\n\t\t\tasResponse: false\n\t\t}), opts?.headers);\n\t};\n};\n//#endregion\n//#region src/oauth-endpoint.ts\n/**\n* Wraps `createAuthEndpoint` so zod schemas stay the single source of truth\n* for body/query shape while validation failures serialize as the RFC 6749\n* §5.2 error envelope `{ error, error_description }`.\n*\n* A failing issue is routed by its first path segment via `errorCodesByField`:\n* - missing required (`invalid_type` + \"received undefined\") → `.missing`\n* - unsupported value (`invalid_value`) → `.invalid`\n* - anything else (wrong type, duplicated params, bad format) → `defaultError`\n*\n* For enum fields that need to distinguish missing from unsupported, compose\n* as `z.string().pipe(z.enum([...]))` so duplicated params fail the outer\n* `z.string()` as `invalid_type` instead of masquerading as an unsupported\n* enum value.\n*/\nfunction createOAuthEndpoint(path, options, handler) {\n\tconst { redirectOnError, onValidationError: userHook, errorCodesByField, defaultError = \"invalid_request\", ...rest } = options;\n\tif (!redirectOnError) return createAuthEndpoint(path, {\n\t\t...rest,\n\t\tonValidationError: async (args) => {\n\t\t\tif (userHook) await userHook(args);\n\t\t\tthrow new APIError$1(\"BAD_REQUEST\", { ...mapIssuesToOAuthError(args.issues, errorCodesByField, defaultError) });\n\t\t}\n\t}, handler);\n\tconst redirect = redirectOnError;\n\tconst { body: bodySchema, query: querySchema, ...forwarded } = rest;\n\tasync function validateSlot(ctx, slot, schema) {\n\t\tif (!schema) return { ok: true };\n\t\tconst result = await schema.safeParseAsync(ctx[slot] ?? {});\n\t\tif (result.success) {\n\t\t\tctx[slot] = result.data;\n\t\t\treturn { ok: true };\n\t\t}\n\t\tif (userHook) await userHook({\n\t\t\tmessage: result.error.message,\n\t\t\tissues: result.error.issues\n\t\t});\n\t\treturn {\n\t\t\tok: false,\n\t\t\tresponse: redirect({\n\t\t\t\t...mapIssuesToOAuthError(result.error.issues, errorCodesByField, defaultError),\n\t\t\t\tctx\n\t\t\t})\n\t\t};\n\t}\n\treturn createAuthEndpoint(path, forwarded, async (ctx) => {\n\t\tconst body = await validateSlot(ctx, \"body\", bodySchema);\n\t\tif (!body.ok) return body.response;\n\t\tconst query = await validateSlot(ctx, \"query\", querySchema);\n\t\tif (!query.ok) return query.response;\n\t\treturn handler(ctx);\n\t});\n}\nfunction mapIssuesToOAuthError(issues, errorCodesByField, defaultError = \"invalid_request\") {\n\tconst issue = issues[0];\n\tif (!issue) return {\n\t\terror: defaultError,\n\t\terror_description: \"Invalid request.\"\n\t};\n\tconst first = issue.path?.[0];\n\tconst fieldKey = typeof first === \"string\" ? first : void 0;\n\tconst mapping = fieldKey ? errorCodesByField?.[fieldKey] : void 0;\n\tconst field = issue.path?.length ? z.core.toDotPath(issue.path) : \"\";\n\treturn {\n\t\terror: resolveErrorCode(issue, mapping, defaultError),\n\t\terror_description: describeIssue(issue, field)\n\t};\n}\nfunction resolveErrorCode(issue, mapping, defaultError) {\n\tif (typeof mapping === \"string\") return mapping;\n\tif (isMissingValueIssue(issue)) return mapping?.missing ?? defaultError;\n\tif (issue.code === \"invalid_value\") return mapping?.invalid ?? defaultError;\n\treturn defaultError;\n}\n/**\n* Returns `true` for issues that represent an absent required value. Zod v4\n* strips `input` from published issues, so the signal is the `invalid_type`\n* code combined with a message suffix of \"received undefined\". The suffix is\n* pinned by a regression test so a zod rephrase fails the test instead of\n* silently reclassifying missing fields.\n*\n* Assumes the default zod error map. Consumers that install a localized map\n* via `z.setErrorMap()` will break this check, collapsing missing-field\n* failures to `defaultError`.\n*/\nfunction isMissingValueIssue(issue) {\n\treturn issue.code === \"invalid_type\" && issue.message.endsWith(\"received undefined\");\n}\nfunction describeIssue(issue, field) {\n\tif (!field) return issue.message;\n\tif (issue.code === \"invalid_type\") {\n\t\tif (issue.message.endsWith(\"received undefined\")) return `${field} is required`;\n\t\tif (issue.message.endsWith(\"received array\")) return `${field} must not appear more than once`;\n\t\treturn `${field} must be a ${issue.expected ?? \"valid value\"}`;\n\t}\n\tif (issue.code === \"invalid_value\") {\n\t\tconst values = issue.values;\n\t\tif (Array.isArray(values) && values.length > 0) return `${field} must be one of: ${values.join(\", \")}`;\n\t}\n\treturn `${field}: ${issue.message}`;\n}\n//#endregion\n//#region src/middleware/index.ts\nconst publicSessionMiddleware = (opts) => createAuthMiddleware(async (ctx) => {\n\tif (!opts.allowPublicClientPrelogin) throw new APIError(\"BAD_REQUEST\");\n\tconst query = ctx.body.oauth_query;\n\tif (!await verifyOAuthQueryParams(query, ctx.context.secret)) throw new APIError(\"UNAUTHORIZED\", { error: \"invalid_signature\" });\n});\n//#endregion\n//#region src/client-jwks.ts\nconst EC_PRIVATE_KEY_JWT_ALGORITHM_BY_CURVE = {\n\t\"P-256\": \"ES256\",\n\t\"P-384\": \"ES384\",\n\t\"P-521\": \"ES512\"\n};\nconst OKP_PRIVATE_KEY_JWT_SIGNING_CURVES = [\"Ed25519\"];\nconst PRIVATE_JWK_MEMBER_NAMES = [\n\t\"d\",\n\t\"p\",\n\t\"q\",\n\t\"dp\",\n\t\"dq\",\n\t\"qi\",\n\t\"oth\"\n];\nfunction isRecord$1(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction hasStringMember(key, memberName) {\n\treturn typeof key[memberName] === \"string\" && key[memberName].length > 0;\n}\nfunction isSupportedEcSigningCurve(curve) {\n\treturn typeof curve === \"string\" && Object.prototype.hasOwnProperty.call(EC_PRIVATE_KEY_JWT_ALGORITHM_BY_CURVE, curve);\n}\nfunction isSupportedOkpSigningCurve(curve) {\n\treturn OKP_PRIVATE_KEY_JWT_SIGNING_CURVES.some((signingCurve) => signingCurve === curve);\n}\nfunction isSupportedPublicJwk(key) {\n\tswitch (key.kty) {\n\t\tcase \"RSA\": return hasStringMember(key, \"n\") && hasStringMember(key, \"e\");\n\t\tcase \"EC\": return isSupportedEcSigningCurve(key.crv) && hasStringMember(key, \"x\") && hasStringMember(key, \"y\");\n\t\tcase \"OKP\": return isSupportedOkpSigningCurve(key.crv) && hasStringMember(key, \"x\");\n\t\tdefault: return false;\n\t}\n}\nfunction hasSupportedPrivateKeyJwtAlgorithm(key) {\n\tif (key.alg === void 0) return true;\n\tif (typeof key.alg !== \"string\" || !PRIVATE_KEY_JWT_SIGNING_ALGORITHMS.some((algorithm) => algorithm === key.alg)) return false;\n\tswitch (key.kty) {\n\t\tcase \"RSA\": return key.alg.startsWith(\"RS\") || key.alg.startsWith(\"PS\");\n\t\tcase \"EC\": return isSupportedEcSigningCurve(key.crv) && EC_PRIVATE_KEY_JWT_ALGORITHM_BY_CURVE[key.crv] === key.alg;\n\t\tcase \"OKP\": return isSupportedOkpSigningCurve(key.crv) && key.alg === \"EdDSA\";\n\t\tdefault: return false;\n\t}\n}\n/**\n* Validates an OAuth client's public asymmetric JWK set.\n*\n* This boundary accepts only the RFC 7517 `{ keys: [...] }` representation.\n* It performs no I/O and returns the validated set for downstream JOSE\n* verification.\n*\n* @internal\n*/\nfunction validatePublicClientJwks(input) {\n\tconst keys = isRecord$1(input) && Array.isArray(input.keys) ? input.keys : void 0;\n\tif (!keys?.length) return {\n\t\tvalid: false,\n\t\terror: \"jwks must be an RFC 7517 JWK Set object with a non-empty keys array\"\n\t};\n\tfor (const key of keys) {\n\t\tif (!isRecord$1(key)) return {\n\t\t\tvalid: false,\n\t\t\terror: \"jwks keys must be supported public JWKs with required key parameters\"\n\t\t};\n\t\tif (key.kty === \"oct\" || \"k\" in key || PRIVATE_JWK_MEMBER_NAMES.some((name) => name in key)) return {\n\t\t\tvalid: false,\n\t\t\terror: \"jwks must contain only public asymmetric keys\"\n\t\t};\n\t\tif (!isSupportedPublicJwk(key)) return {\n\t\t\tvalid: false,\n\t\t\terror: \"jwks keys must be supported public JWKs with required key parameters\"\n\t\t};\n\t\tif (!hasSupportedPrivateKeyJwtAlgorithm(key)) return {\n\t\t\tvalid: false,\n\t\t\terror: \"jwks key alg must be supported for private_key_jwt and compatible with its key type and signing curve\"\n\t\t};\n\t}\n\treturn {\n\t\tvalid: true,\n\t\tjwks: { keys }\n\t};\n}\n//#endregion\n//#region src/client-metadata.ts\nconst OAUTH_CLIENT_RECORD_FIELD_NAMES = Object.freeze(Object.keys({\n\tclientId: true,\n\tclientSecret: true,\n\tclientDiscoveryId: true,\n\tdisabled: true,\n\tscopes: true,\n\tclientCredentialsScopes: true,\n\tuserId: true,\n\tcreatedAt: true,\n\tupdatedAt: true,\n\texpiresAt: true,\n\tname: true,\n\turi: true,\n\ticon: true,\n\tcontacts: true,\n\ttos: true,\n\tpolicy: true,\n\tsoftwareId: true,\n\tsoftwareVersion: true,\n\tsoftwareStatement: true,\n\tredirectUris: true,\n\tpostLogoutRedirectUris: true,\n\tbackchannelLogoutUri: true,\n\tbackchannelLogoutSessionRequired: true,\n\ttokenEndpointAuthMethod: true,\n\tgrantTypes: true,\n\tresponseTypes: true,\n\tapplicationType: true,\n\tjwks: true,\n\tjwksUri: true,\n\trequirePKCE: true,\n\tdpopBoundAccessTokens: true,\n\tskipConsent: true,\n\tenableEndSession: true,\n\tsubjectType: true,\n\treferenceId: true,\n\tmetadata: true\n}));\n/**\n* Canonical wire fields emitted by schemaToOAuth. They are mapped explicitly\n* and therefore must never also survive inside the opaque metadata envelope.\n*/\nconst OAUTH_CLIENT_WIRE_FIELD_NAMES = [\n\t\"client_id\",\n\t\"client_secret\",\n\t\"client_secret_expires_at\",\n\t\"scope\",\n\t\"user_id\",\n\t\"client_id_issued_at\",\n\t\"client_name\",\n\t\"client_uri\",\n\t\"logo_uri\",\n\t\"contacts\",\n\t\"tos_uri\",\n\t\"policy_uri\",\n\t\"jwks\",\n\t\"jwks_uri\",\n\t\"software_id\",\n\t\"software_version\",\n\t\"software_statement\",\n\t\"redirect_uris\",\n\t\"post_logout_redirect_uris\",\n\t\"backchannel_logout_uri\",\n\t\"backchannel_logout_session_required\",\n\t\"token_endpoint_auth_method\",\n\t\"grant_types\",\n\t\"response_types\",\n\t\"application_type\",\n\t\"disabled\",\n\t\"skip_consent\",\n\t\"enable_end_session\",\n\t\"require_pkce\",\n\t\"dpop_bound_access_tokens\",\n\t\"subject_type\",\n\t\"reference_id\"\n];\nconst OPAQUE_METADATA_RESERVED_FIELDS = new Set([\n\t...OAUTH_CLIENT_RECORD_FIELD_NAMES,\n\t...OAUTH_CLIENT_WIRE_FIELD_NAMES,\n\t\"public\",\n\t\"type\",\n\t\"resources\",\n\t\"client_credentials_scopes\"\n]);\nconst CIMD_FORBIDDEN_SERVER_FIELD_NAMES = new Set([\n\t\"disabled\",\n\t\"client_secret\",\n\t\"client_secret_expires_at\",\n\t\"client_id_issued_at\",\n\t\"skip_consent\",\n\t\"enable_end_session\",\n\t\"require_pkce\",\n\t\"reference_id\",\n\t\"user_id\",\n\t\"resources\",\n\t\"clientSecret\",\n\t\"clientDiscoveryId\",\n\t\"skipConsent\",\n\t\"enableEndSession\",\n\t\"requirePKCE\",\n\t\"referenceId\",\n\t\"userId\",\n\t\"clientId\",\n\t\"applicationType\",\n\t\"tokenEndpointAuthMethod\",\n\t\"redirectUris\",\n\t\"postLogoutRedirectUris\",\n\t\"grantTypes\",\n\t\"responseTypes\",\n\t\"scopes\",\n\t\"expiresAt\",\n\t\"createdAt\",\n\t\"updatedAt\",\n\t\"softwareId\",\n\t\"softwareVersion\",\n\t\"softwareStatement\",\n\t\"backchannelLogoutUri\",\n\t\"backchannelLogoutSessionRequired\",\n\t\"jwksUri\",\n\t\"dpopBoundAccessTokens\",\n\t\"subjectType\"\n]);\nfunction isForbiddenCimdClientMetadataField(field) {\n\treturn CIMD_FORBIDDEN_SERVER_FIELD_NAMES.has(field);\n}\nfunction stripReservedOAuthClientMetadataExtensions(metadata) {\n\tif (!metadata) return void 0;\n\treturn Object.fromEntries(Object.entries(metadata).filter(([field]) => !OPAQUE_METADATA_RESERVED_FIELDS.has(field)));\n}\n//#endregion\n//#region src/oauthClient/privileges.ts\n/**\n* Authorizes a client action against the configured `clientPrivileges` hook.\n*\n* This is the single authorization helper for every OAuth client mutation. The\n* create path enforces it at the shared creation chokepoint so that no\n* registration route can reach client persistence without it.\n*\n* @throws APIError UNAUTHORIZED when there is no session or the hook denies the action.\n* @throws APIError BAD_REQUEST when the request carries no headers.\n*/\nasync function assertClientPrivileges(ctx, session, opts, action, clientId) {\n\tif (!session) throw new APIError(\"UNAUTHORIZED\");\n\tif (!ctx.headers) throw new APIError(\"BAD_REQUEST\");\n\tif (action === \"configure-client-credentials-scopes\" && !opts.clientPrivileges) throw new APIError(\"UNAUTHORIZED\");\n\tif (opts.clientPrivileges && !await opts.clientPrivileges({\n\t\theaders: ctx.headers,\n\t\taction,\n\t\tsession: session.session,\n\t\tuser: session.user,\n\t\tclientId\n\t})) throw new APIError(\"UNAUTHORIZED\");\n}\n//#endregion\n//#region src/oauthResource/privileges.ts\n/**\n* Authorizes a resource action against the configured `resourcePrivileges`\n* hook. Gates every admin resource endpoint and the resource links selected\n* during managed client registration. Mirrors `assertClientPrivileges`:\n* a missing session → 401; a defined `resourcePrivileges` callback that\n* returns falsy → 401 with the original action context preserved.\n*\n* When `resourcePrivileges` is undefined, the gate degrades to \"any\n* authenticated session can manage resources\" — same forgiving default\n* as `clientPrivileges`. Operators who care about RBAC must define the\n* callback.\n*\n* @internal\n*/\nasync function assertResourcePrivileges(ctx, session, opts, action, resourceId) {\n\tif (!session) throw new APIError(\"UNAUTHORIZED\");\n\tif (!ctx.headers) throw new APIError(\"BAD_REQUEST\");\n\tif (!opts.resourcePrivileges) return;\n\tif (!await opts.resourcePrivileges({\n\t\theaders: ctx.headers,\n\t\taction,\n\t\tsession: session.session,\n\t\tuser: session.user,\n\t\tresourceId\n\t})) throw new APIError(\"UNAUTHORIZED\");\n}\n//#endregion\n//#region src/utils/client-assertion.ts\nvar client_assertion_exports = /* @__PURE__ */ __exportAll({\n\tconsumeClientAssertion: () => consumeClientAssertion,\n\tisPrivateHostname: () => isPrivateHostname,\n\tverifyClientAssertion: () => verifyClientAssertion\n});\nconst jwksCaches = /* @__PURE__ */ new WeakMap();\nconst JWKS_CACHE_TTL_MS = 300 * 1e3;\nconst JWKS_CACHE_MAX_ENTRIES = 500;\nconst JWKS_FETCH_TIMEOUT_MS = 5e3;\nconst MAX_JWKS_RESPONSE_BYTES = 64 * 1024;\nconst JSON_CONTENT_TYPE = /^application\\/(?:[-\\w.]+\\+)?json\\s*(?:;|$)/i;\nfunction setJwksCache(jwksCache, cacheKey, jwks, fetchedAt) {\n\tjwksCache.set(cacheKey, {\n\t\tjwks,\n\t\tfetchedAt\n\t});\n\tif (jwksCache.size > JWKS_CACHE_MAX_ENTRIES) {\n\t\tconst oldest = jwksCache.keys().next().value;\n\t\tif (oldest !== void 0) jwksCache.delete(oldest);\n\t}\n}\nfunction getJwksCache(opts) {\n\tconst existingCache = jwksCaches.get(opts);\n\tif (existingCache) return existingCache;\n\tconst cache = /* @__PURE__ */ new Map();\n\tjwksCaches.set(opts, cache);\n\treturn cache;\n}\nfunction getJwksCacheKey(client) {\n\treturn `${client.clientDiscoveryId ?? \"managed\"}:${client.jwksUri ?? \"\"}`;\n}\nconst ALGORITHMS_LIST = [...PRIVATE_KEY_JWT_SIGNING_ALGORITHMS];\n/**\n* SSRF gate for user-supplied server-side fetch targets (`jwks_uri`,\n* `backchannel_logout_uri`): returns true when the host is NOT publicly\n* routable. That covers loopback, RFC 1918 private, link-local (including AWS\n* IMDS `169.254.169.254`), shared-address-space (carrier-grade NAT),\n* IPv4-mapped IPv6, 6to4/NAT64/Teredo tunnels, every other RFC 6890\n* special-purpose range, and cloud-metadata FQDNs.\n*\n* Delegates to the audited single source of truth so this check cannot drift\n* into the kind of encoding bypass that bespoke regexes invite. This is a\n* syntactic check only: it does not resolve DNS, so a public name that\n* resolves to a private address at fetch time is not caught here.\n*/\nfunction isPrivateHostname(hostname) {\n\treturn !isPublicRoutableHost(hostname);\n}\nfunction validateJwksUri(ctx, jwksUri, clientIdUrlOrigin) {\n\tconst parsed = new URL(jwksUri);\n\tif (parsed.protocol !== \"https:\") throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"jwks_uri must use HTTPS\",\n\t\terror: \"invalid_client\"\n\t});\n\tif (parsed.username || parsed.password) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"jwks_uri must not contain credentials\",\n\t\terror: \"invalid_client\"\n\t});\n\tif (jwksUri.includes(\"#\")) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"jwks_uri must not include a fragment component\",\n\t\terror: \"invalid_client\"\n\t});\n\tif (isPrivateHostname(parsed.hostname)) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"jwks_uri must not point to a private or reserved address\",\n\t\terror: \"invalid_client\"\n\t});\n\tif (clientIdUrlOrigin && parsed.origin === clientIdUrlOrigin) return;\n\tif (!ctx.context.isTrustedOrigin(parsed.href)) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"client jwks_uri is not trusted\",\n\t\terror: \"invalid_client\"\n\t});\n}\nfunction urlClientIdOrigin(clientId) {\n\ttry {\n\t\tconst parsed = new URL(clientId);\n\t\tif (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") return;\n\t\treturn parsed.origin;\n\t} catch {\n\t\treturn;\n\t}\n}\nasync function readBoundedResponseBody(response) {\n\tconst contentLength = response.headers.get(\"content-length\");\n\tif (contentLength !== null && Number.isFinite(Number(contentLength)) && Number(contentLength) > MAX_JWKS_RESPONSE_BYTES) {\n\t\tawait response.body?.cancel();\n\t\tthrow new Error(\"JWKS response exceeds 64 KiB\");\n\t}\n\tif (!response.body) return \"\";\n\tconst reader = response.body.getReader();\n\tconst chunks = [];\n\tlet totalBytes = 0;\n\twhile (true) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (done) break;\n\t\ttotalBytes += value.byteLength;\n\t\tif (totalBytes > MAX_JWKS_RESPONSE_BYTES) {\n\t\t\tawait reader.cancel();\n\t\t\tthrow new Error(\"JWKS response exceeds 64 KiB\");\n\t\t}\n\t\tchunks.push(value);\n\t}\n\tconst bytes = new Uint8Array(totalBytes);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tbytes.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\treturn new TextDecoder().decode(bytes);\n}\nasync function fetchJwksFromUri(jwksUri, fetchClientMetadataResource = globalThis.fetch) {\n\tconst controller = new AbortController();\n\tconst timeout = setTimeout(() => controller.abort(), JWKS_FETCH_TIMEOUT_MS);\n\ttry {\n\t\tconst response = await fetchClientMetadataResource(jwksUri, {\n\t\t\tsignal: controller.signal,\n\t\t\theaders: { accept: \"application/json\" },\n\t\t\tredirect: \"error\"\n\t\t});\n\t\tif (response.redirected) throw new Error(\"JWKS fetch redirected\");\n\t\tif (response.status !== 200) throw new Error(`JWKS fetch returned ${response.status}`);\n\t\tconst contentType = response.headers.get(\"content-type\");\n\t\tif (!contentType || !JSON_CONTENT_TYPE.test(contentType)) throw new Error(\"JWKS response must use a JSON media type\");\n\t\tconst responseBody = await readBoundedResponseBody(response);\n\t\tlet parsedBody;\n\t\ttry {\n\t\t\tparsedBody = JSON.parse(responseBody);\n\t\t} catch {\n\t\t\treturn { valid: false };\n\t\t}\n\t\tconst result = validatePublicClientJwks(parsedBody);\n\t\tif (!result.valid) return { valid: false };\n\t\treturn {\n\t\t\tvalid: true,\n\t\t\tjwks: result.jwks\n\t\t};\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n}\nfunction createClientJwksFetchError() {\n\treturn new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"failed to fetch client JWKS\",\n\t\terror: \"invalid_client\"\n\t});\n}\nasync function fetchClientJwks(ctx, opts, client) {\n\tif (client.jwks) return JSON.parse(client.jwks);\n\tif (!client.jwksUri) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"client has no JWKS configured\",\n\t\terror: \"invalid_client\"\n\t});\n\tconst discovery = client.clientDiscoveryId ? getClientDiscoveries(opts).find((candidate) => candidate.id === client.clientDiscoveryId) : void 0;\n\tif (client.clientDiscoveryId && !discovery?.fetchClientMetadataResource) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"client discovery does not provide a metadata resource transport\",\n\t\terror: \"invalid_client\"\n\t});\n\tvalidateJwksUri(ctx, client.jwksUri, client.clientDiscoveryId ? urlClientIdOrigin(client.clientId) : void 0);\n\tconst now = Date.now();\n\tconst cacheKey = getJwksCacheKey(client);\n\tconst jwksCache = getJwksCache(opts);\n\tconst cached = jwksCache.get(cacheKey);\n\tif (cached && now - cached.fetchedAt < JWKS_CACHE_TTL_MS) return cached.jwks;\n\tlet result;\n\ttry {\n\t\tresult = await fetchJwksFromUri(client.jwksUri, discovery?.fetchClientMetadataResource);\n\t} catch {\n\t\tconst staleLimitMs = JWKS_CACHE_TTL_MS * 2;\n\t\tif (cached && now - cached.fetchedAt < staleLimitMs) return cached.jwks;\n\t\tthrow createClientJwksFetchError();\n\t}\n\tif (!result.valid) throw createClientJwksFetchError();\n\tsetJwksCache(jwksCache, cacheKey, result.jwks, now);\n\treturn result.jwks;\n}\n/**\n* Refetch JWKS from jwks_uri when signature verification fails with cached keys.\n* Handles key rotation: the client may have published a new key that isn't in our cache yet.\n*/\nasync function refetchClientJwks(opts, client) {\n\tif (!client.jwksUri) return null;\n\tconst discovery = client.clientDiscoveryId ? getClientDiscoveries(opts).find((candidate) => candidate.id === client.clientDiscoveryId) : void 0;\n\tif (client.clientDiscoveryId && !discovery?.fetchClientMetadataResource) return null;\n\ttry {\n\t\tconst result = await fetchJwksFromUri(client.jwksUri, discovery?.fetchClientMetadataResource);\n\t\tif (!result.valid) return null;\n\t\tsetJwksCache(getJwksCache(opts), getJwksCacheKey(client), result.jwks, Date.now());\n\t\treturn result.jwks;\n\t} catch {\n\t\treturn null;\n\t}\n}\n/**\n* Enforces the assertion-hygiene claims every client-assertion authentication\n* method must check, independent of how the signature is verified or where the\n* verification keys come from:\n* - `aud` MUST include `expectedAudience` (RFC 7523 §3 rule 3),\n* - `exp` MUST be present, unexpired, and at most `assertionMaxLifetime`\n* seconds away (RFC 7523 §3 rule 4),\n* - `iat`, when present, MUST be within `assertionMaxLifetime`,\n* - `jti` MUST be present and single-use; this consumes a replay tombstone keyed\n* by `` `${namespace}:${jti}` ``, inserted under the adapter's primary key so a\n* replay across workers fails atomically.\n*\n* A custom {@link OAuthClientAuthenticationStrategy} should call this after\n* verifying the assertion signature, so an extension method inherits the same\n* replay, lifetime, and audience guarantees as the built-in `private_key_jwt`\n* path, which calls it too.\n*\n* @param params.namespace Scopes the replay tombstone to the method and client,\n* e.g. `` `${method}:${clientId}` ``, so the same `jti` can recur across\n* distinct methods or clients but never within one.\n*/\nasync function consumeClientAssertion(ctx, opts, params) {\n\tconst { namespace, payload, expectedAudience } = params;\n\tif (!(Array.isArray(payload.aud) ? payload.aud : payload.aud != null ? [payload.aud] : []).includes(expectedAudience)) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"client assertion aud does not match the endpoint\",\n\t\terror: \"invalid_client\"\n\t});\n\tconst maxLifetime = opts.assertionMaxLifetime ?? 300;\n\tconst now = Math.floor(Date.now() / 1e3);\n\tif (typeof payload.exp !== \"number\") throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"client assertion must include exp claim\",\n\t\terror: \"invalid_client\"\n\t});\n\tif (payload.exp <= now) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"client assertion has expired\",\n\t\terror: \"invalid_client\"\n\t});\n\tif (payload.exp - now > maxLifetime) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: `client assertion exp is too far in the future (max ${maxLifetime}s)`,\n\t\terror: \"invalid_client\"\n\t});\n\tif (typeof payload.iat === \"number\" && now - payload.iat > maxLifetime) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: `client assertion iat is too far in the past (max ${maxLifetime}s)`,\n\t\terror: \"invalid_client\"\n\t});\n\tif (typeof payload.jti !== \"string\" || payload.jti.length === 0) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"client assertion must include jti claim\",\n\t\terror: \"invalid_client\"\n\t});\n\tconst jtiDigest = await createHash(\"SHA-256\").digest(new TextEncoder().encode(`${namespace}:${payload.jti}`));\n\tconst jtiId = encodeDeterministicId(new Uint8Array(jtiDigest).slice(0, 24), ctx.context.options);\n\ttry {\n\t\tawait ctx.context.adapter.create({\n\t\t\tmodel: \"oauthClientAssertion\",\n\t\t\tdata: {\n\t\t\t\tid: jtiId,\n\t\t\t\texpiresAt: /* @__PURE__ */ new Date(payload.exp * 1e3)\n\t\t\t},\n\t\t\tforceAllowId: true\n\t\t});\n\t} catch (createErr) {\n\t\tlet alreadyUsed = false;\n\t\ttry {\n\t\t\talreadyUsed = Boolean(await ctx.context.adapter.findOne({\n\t\t\t\tmodel: \"oauthClientAssertion\",\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tvalue: jtiId\n\t\t\t\t}]\n\t\t\t}));\n\t\t} catch {}\n\t\tif (alreadyUsed) throw new APIError$1(\"BAD_REQUEST\", {\n\t\t\terror_description: \"client assertion jti has already been used\",\n\t\t\terror: \"invalid_client\"\n\t\t});\n\t\tthrow createErr;\n\t}\n}\n/**\n* Verifies a client assertion JWT for `private_key_jwt` authentication.\n*\n* Validates: signature, iss=client_id, sub=client_id, aud=the endpoint serving\n* the assertion or the normalized OP issuer, exp, assertion max lifetime,\n* jti uniqueness (replay prevention).\n*/\nasync function verifyClientAssertion(ctx, opts, clientAssertion, clientAssertionType, clientIdHint, expectedAudience) {\n\tif (clientAssertionType !== CLIENT_ASSERTION_TYPE) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"unsupported client_assertion_type\",\n\t\terror: \"invalid_client\"\n\t});\n\tlet header;\n\ttry {\n\t\theader = decodeProtectedHeader(clientAssertion);\n\t} catch {\n\t\tthrow new APIError$1(\"BAD_REQUEST\", {\n\t\t\terror_description: \"malformed client assertion: invalid JWT header\",\n\t\t\terror: \"invalid_client\"\n\t\t});\n\t}\n\tif (!header.alg || !ALGORITHMS_LIST.includes(header.alg)) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: `unsupported assertion signing algorithm: ${header.alg}`,\n\t\terror: \"invalid_client\"\n\t});\n\tlet unverified;\n\ttry {\n\t\tunverified = decodeJwt(clientAssertion);\n\t} catch {\n\t\tthrow new APIError$1(\"BAD_REQUEST\", {\n\t\t\terror_description: \"malformed client assertion: invalid JWT payload\",\n\t\t\terror: \"invalid_client\"\n\t\t});\n\t}\n\tconst clientId = unverified.sub ?? unverified.iss;\n\tif (!clientId) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"client assertion must contain sub or iss claim identifying the client\",\n\t\terror: \"invalid_client\"\n\t});\n\tif (clientIdHint && clientIdHint !== clientId) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"client_id in body does not match assertion sub/iss\",\n\t\terror: \"invalid_client\"\n\t});\n\tconst client = await getClient(ctx, opts, clientId);\n\tif (!client) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"unknown client\",\n\t\terror: \"invalid_client\"\n\t});\n\tif (client.disabled) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"client is disabled\",\n\t\terror: \"invalid_client\"\n\t});\n\tif (client.tokenEndpointAuthMethod !== \"private_key_jwt\") throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"client is not registered for private_key_jwt authentication\",\n\t\terror: \"invalid_client\"\n\t});\n\tconst jwks = await fetchClientJwks(ctx, opts, client);\n\tconst endpointAudience = expectedAudience ?? `${ctx.context.baseURL}/oauth2/token`;\n\tconst issuerAudience = getIssuer(ctx, opts);\n\tconst acceptedAudiences = [...new Set([endpointAudience, issuerAudience])];\n\tconst verifyOpts = {\n\t\tissuer: clientId,\n\t\tsubject: clientId,\n\t\taudience: acceptedAudiences,\n\t\talgorithms: ALGORITHMS_LIST\n\t};\n\tlet payload;\n\ttry {\n\t\t({payload} = await jwtVerify(clientAssertion, createLocalJWKSet(jwks), verifyOpts));\n\t} catch (verifyErr) {\n\t\tif (verifyErr instanceof Error && /no matching key|no applicable key/i.test(verifyErr.message)) {\n\t\t\tconst refreshed = await refetchClientJwks(opts, client);\n\t\t\tif (refreshed) try {\n\t\t\t\t({payload} = await jwtVerify(clientAssertion, createLocalJWKSet(refreshed), verifyOpts));\n\t\t\t} catch {\n\t\t\t\tthrow new APIError$1(\"UNAUTHORIZED\", {\n\t\t\t\t\terror_description: \"client assertion signature verification failed\",\n\t\t\t\t\terror: \"invalid_client\"\n\t\t\t\t});\n\t\t\t}\n\t\t\telse throw new APIError$1(\"UNAUTHORIZED\", {\n\t\t\t\terror_description: \"client assertion signature verification failed\",\n\t\t\t\terror: \"invalid_client\"\n\t\t\t});\n\t\t} else throw new APIError$1(\"UNAUTHORIZED\", {\n\t\t\terror_description: \"client assertion signature verification failed\",\n\t\t\terror: \"invalid_client\"\n\t\t});\n\t}\n\tconst acceptedAudience = (Array.isArray(payload.aud) ? payload.aud : [payload.aud]).find((value) => typeof value === \"string\" && acceptedAudiences.includes(value));\n\tawait consumeClientAssertion(ctx, opts, {\n\t\tnamespace: `private_key_jwt:${clientId}`,\n\t\tpayload,\n\t\texpectedAudience: acceptedAudience\n\t});\n\treturn { clientId };\n}\n//#endregion\n//#region src/utils/initial-access-token.ts\n/**\n* Builds an RFC 6750 §3 Bearer challenge for the registration endpoint. The\n* `error` code maps to the status per RFC 6750 §3.1 (`invalid_request` → 400,\n* `invalid_token` → 401) and is echoed in both the `WWW-Authenticate` challenge\n* and the JSON body.\n*\n* @see https://datatracker.ietf.org/doc/html/rfc6750#section-3\n*/\nfunction registrationBearerError(status, error, errorDescription) {\n\treturn new APIError$1(status, {\n\t\terror,\n\t\terror_description: errorDescription\n\t}, {\n\t\t\"WWW-Authenticate\": `Bearer error=\"${error}\"`,\n\t\t...NO_STORE_HEADERS\n\t});\n}\n/**\n* Resolves an RFC 7591 initial access token from the request and authorizes it\n* against the deployment-supplied validator.\n*\n* Returns the authorization (optionally carrying a `referenceId`) when a valid\n* token is present, or `undefined` when no Bearer credentials were sent so the\n* caller can fall back to session or open registration. Throws an RFC 6750\n* Bearer challenge when the header is malformed, no validator is configured, or\n* the token is rejected.\n*\n* @see https://datatracker.ietf.org/doc/html/rfc7591#section-3\n*/\nasync function authorizeInitialAccessToken(ctx, opts, clientMetadata) {\n\tconst headers = ctx.headers;\n\tlet initialAccessToken;\n\ttry {\n\t\tinitialAccessToken = parseBearerToken(headers?.get(\"authorization\"));\n\t} catch {\n\t\tthrow registrationBearerError(\"BAD_REQUEST\", \"invalid_request\", \"Malformed initial access token Authorization header\");\n\t}\n\tif (!initialAccessToken || !headers) return;\n\tif (!opts.validateInitialAccessToken) throw registrationBearerError(\"UNAUTHORIZED\", \"invalid_token\", \"Invalid initial access token\");\n\tlet authorization;\n\ttry {\n\t\tauthorization = await opts.validateInitialAccessToken({\n\t\t\tinitialAccessToken,\n\t\t\theaders,\n\t\t\tclientMetadata\n\t\t});\n\t} catch (error) {\n\t\tif (error instanceof APIError$1) throw error;\n\t\tthrow new APIError$1(\"INTERNAL_SERVER_ERROR\", {\n\t\t\terror: \"server_error\",\n\t\t\terror_description: \"Initial access token validation failed\"\n\t\t});\n\t}\n\tif (!authorization) throw registrationBearerError(\"UNAUTHORIZED\", \"invalid_token\", \"Invalid initial access token\");\n\treturn authorization;\n}\n//#endregion\n//#region src/register.ts\nconst DEFAULT_REGISTRATION_GRANT_TYPES = [\"authorization_code\"];\nfunction resolveClientRegistrationScopes(opts) {\n\treturn [...new Set([...opts.clientRegistrationDefaultScopes ?? opts.scopes ?? [], ...opts.clientRegistrationAllowedScopes ?? []])];\n}\nfunction resolveRegistrationGrantTypes(client) {\n\tconst grantTypes = client.grant_types ?? [...DEFAULT_REGISTRATION_GRANT_TYPES];\n\tif (grantTypes.length > 0) return grantTypes;\n\tthrow new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_client_metadata\",\n\t\terror_description: \"grant_types must contain at least one grant type\"\n\t});\n}\nfunction resolveRegistrationResponseTypes(client, grantTypes) {\n\tif (client.response_types) return client.response_types;\n\treturn grantTypes.includes(\"authorization_code\") ? [\"code\"] : void 0;\n}\nfunction applyOAuthClientRegistrationDefaults(client, defaultApplicationType = \"web\") {\n\tconst grantTypes = resolveRegistrationGrantTypes(client);\n\treturn {\n\t\t...client,\n\t\ttoken_endpoint_auth_method: client.token_endpoint_auth_method ?? \"client_secret_basic\",\n\t\tapplication_type: client.application_type ?? (defaultApplicationType === null ? void 0 : defaultApplicationType),\n\t\tgrant_types: grantTypes,\n\t\tresponse_types: resolveRegistrationResponseTypes(client, grantTypes)\n\t};\n}\nfunction isCustomSchemeWithHost(redirectUri) {\n\tconst url = new URL(redirectUri);\n\treturn url.protocol !== \"http:\" && url.protocol !== \"https:\" && url.host !== \"\";\n}\nfunction isNonHttpRedirectUri(redirectUri) {\n\ttry {\n\t\tconst protocol = new URL(redirectUri).protocol;\n\t\treturn protocol !== \"http:\" && protocol !== \"https:\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Server-owned default for dynamic registrations that omit `application_type`.\n* `\"infer\"` classifies as native when any redirect URI uses a non-http(s)\n* scheme, because a web client can never register one. Every URI is then\n* validated against the native rules. A sent `application_type` is never\n* overridden because `applyOAuthClientRegistrationDefaults` only fills the\n* absent field.\n*/\nfunction resolveDynamicRegistrationDefaultApplicationType(opts, client) {\n\tconst configured = opts.clientRegistrationDefaultApplicationType ?? \"web\";\n\tif (configured !== \"infer\") return configured;\n\treturn (client.redirect_uris ?? []).some(isNonHttpRedirectUri) ? \"native\" : \"web\";\n}\nfunction invalidRedirectUri(description) {\n\tthrow new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_redirect_uri\",\n\t\terror_description: description\n\t});\n}\nfunction getRawHttpHostname(redirectUri) {\n\tconst authority = /^http:\\/\\/([^/?#]*)/i.exec(redirectUri)?.[1];\n\tif (!authority) return null;\n\tconst hostAndPort = authority.slice(authority.lastIndexOf(\"@\") + 1);\n\tif (hostAndPort.startsWith(\"[\")) {\n\t\tconst bracketEnd = hostAndPort.indexOf(\"]\");\n\t\treturn bracketEnd < 0 ? null : hostAndPort.slice(0, bracketEnd + 1).toLowerCase();\n\t}\n\treturn (hostAndPort.split(\":\")[0] ?? \"\").toLowerCase();\n}\nfunction assertDynamicRegistrationResourcesAllowed(opts, requestedResources) {\n\tconst allowedResources = new Set([...opts.clientRegistrationDefaultResources ?? [], ...opts.clientRegistrationAllowedResources ?? []]);\n\tfor (const identifier of requestedResources) if (!allowedResources.has(identifier)) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_target\",\n\t\terror_description: `requested resource ${identifier} is not allowed for client registration`\n\t});\n}\nasync function resolveClientRegistrationResources(ctx, opts, requestedResources) {\n\tconst defaultResources = opts.clientRegistrationDefaultResources ?? [];\n\tconst resources = [...new Set([...defaultResources, ...requestedResources])];\n\tfor (const identifier of resources) {\n\t\tconst row = await getResource(ctx, opts, identifier);\n\t\tif (!row) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_target\",\n\t\t\terror_description: `requested resource ${identifier} does not exist`\n\t\t});\n\t\tif (row.disabled) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_target\",\n\t\t\terror_description: `requested resource ${identifier} is disabled`\n\t\t});\n\t}\n\treturn resources;\n}\nfunction validateClientRedirectUri(redirectUri, applicationType) {\n\tlet url;\n\ttry {\n\t\turl = new URL(redirectUri);\n\t} catch {\n\t\tinvalidRedirectUri(`redirect URI must be an absolute URI: ${redirectUri}`);\n\t}\n\tif (redirectUri.includes(\"#\") || url.username.length > 0 || url.password.length > 0) invalidRedirectUri(`redirect URI must not include credentials or a fragment: ${redirectUri}`);\n\tconst isHttp = url.protocol === \"http:\";\n\tconst isHttps = url.protocol === \"https:\";\n\tif (/^localhost\\.+$/i.test(url.hostname)) invalidRedirectUri(`redirect URI localhost must not include trailing dots: ${redirectUri}`);\n\tconst isRedirectLoopback = isLoopbackIP(url.hostname) || url.hostname === \"localhost\";\n\tconst rawHttpHostname = getRawHttpHostname(redirectUri);\n\tconst isAllowedNativeHttpLoopback = rawHttpHostname === \"localhost\" || rawHttpHostname === \"127.0.0.1\" || rawHttpHostname === \"[::1]\";\n\tif (applicationType === \"web\") {\n\t\tif (!isHttps || isRedirectLoopback) invalidRedirectUri(`web clients require https redirect URIs on non-loopback hosts: ${redirectUri}`);\n\t\treturn;\n\t}\n\tif (isHttps) {\n\t\tif (isRedirectLoopback) invalidRedirectUri(`native clients must not use https loopback redirect URIs: ${redirectUri}`);\n\t\treturn;\n\t}\n\tif (isHttp) {\n\t\tif (!isAllowedNativeHttpLoopback) invalidRedirectUri(`native clients may use http only on the exact loopback hosts localhost, 127.0.0.1, or [::1]: ${redirectUri}`);\n\t\treturn;\n\t}\n\tif (!isNativePrivateUseRedirectUri(url)) invalidRedirectUri(`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: ${redirectUri}`);\n}\nfunction assertValidRegistrationJwks(jwks) {\n\tconst result = validatePublicClientJwks(jwks);\n\tif (!result.valid) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_client_metadata\",\n\t\terror_description: result.error\n\t});\n}\nasync function registerEndpoint(ctx, opts) {\n\tconst body = ctx.body;\n\tif (!opts.allowDynamicClientRegistration) throw new APIError(\"FORBIDDEN\", {\n\t\terror: \"access_denied\",\n\t\terror_description: \"Client registration is disabled\"\n\t});\n\tconst session = await getSessionFromCtx(ctx);\n\tconst tokenAuthorization = session ? void 0 : await authorizeInitialAccessToken(ctx, opts, body);\n\tconst isTokenAuthorized = Boolean(tokenAuthorization);\n\tif (!(session || isTokenAuthorized || opts.allowUnauthenticatedClientRegistration)) throw new APIError(\"UNAUTHORIZED\", { error_description: \"Authentication required for client registration\" }, {\n\t\t\"WWW-Authenticate\": \"Bearer\",\n\t\t...NO_STORE_HEADERS\n\t});\n\tif (!session && !isTokenAuthorized) {\n\t\tif (body.grant_types?.includes(\"client_credentials\")) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_client_metadata\",\n\t\t\terror_description: \"client_credentials grant requires authenticated registration\"\n\t\t});\n\t}\n\tconst requestedResources = Array.isArray(body.resources) ? body.resources.filter((resource) => typeof resource === \"string\" && resource.length > 0) : [];\n\tif (session) await assertClientPrivileges(ctx, session, opts, \"create\");\n\tconst referenceId = tokenAuthorization?.referenceId ?? (session && opts.clientReference ? await opts.clientReference({\n\t\tuser: session.user,\n\t\tsession: session.session\n\t}) : void 0);\n\tconst response = await createOAuthClientRegistration(ctx, opts, {\n\t\tmetadata: body,\n\t\tregistrationSource: \"dynamic\",\n\t\tuserId: referenceId ? void 0 : session?.session.userId,\n\t\treferenceId,\n\t\trequestedResources\n\t});\n\tctx.setStatus(201);\n\treturn ctx.json(response);\n}\nasync function checkOAuthClient(client, opts, settings) {\n\tconst isClientMetadataDocument = settings?.registrationSource === \"clientMetadataDocument\";\n\tconst clientWithDefaults = applyOAuthClientRegistrationDefaults(client, isClientMetadataDocument ? null : settings?.registrationSource === \"dynamic\" ? resolveDynamicRegistrationDefaultApplicationType(opts, client) : \"web\");\n\tconst tokenEndpointAuthMethod = clientWithDefaults.token_endpoint_auth_method ?? \"client_secret_basic\";\n\tif (!new Set(getSupportedAuthMethods(opts, { includeNone: true })).has(tokenEndpointAuthMethod)) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_client_metadata\",\n\t\terror_description: `unsupported token_endpoint_auth_method ${tokenEndpointAuthMethod}`\n\t});\n\tif (clientWithDefaults.dpop_bound_access_tokens !== void 0 && typeof clientWithDefaults.dpop_bound_access_tokens !== \"boolean\") throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_client_metadata\",\n\t\terror_description: \"dpop_bound_access_tokens must be a boolean\"\n\t});\n\tconst grantTypes = clientWithDefaults.grant_types ?? [];\n\tconst responseTypes = clientWithDefaults.response_types;\n\tconst applicationType = clientWithDefaults.application_type;\n\tif (applicationType !== void 0 && applicationType !== \"web\" && applicationType !== \"native\") throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_client_metadata\",\n\t\terror_description: \"application_type must be web or native\"\n\t});\n\tif (grantTypes.includes(\"authorization_code\") && (!clientWithDefaults.redirect_uris || clientWithDefaults.redirect_uris.length === 0)) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_redirect_uri\",\n\t\terror_description: \"Redirect URIs are required for authorization_code and implicit grant types\"\n\t});\n\tfor (const uri of clientWithDefaults.redirect_uris ?? []) validateClientRedirectUri(uri, applicationType ?? (isClientMetadataDocument ? \"native\" : \"web\"));\n\tconst supportedGrantTypes = new Set(getSupportedGrantTypes(opts));\n\tif (isClientMetadataDocument) {\n\t\tif (!grantTypes.some((grantType) => supportedGrantTypes.has(grantType))) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_client_metadata\",\n\t\t\terror_description: `no mutually supported grant_type among ${grantTypes.join(\", \")}`\n\t\t});\n\t} else for (const grantType of grantTypes) if (!supportedGrantTypes.has(grantType)) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_client_metadata\",\n\t\terror_description: `unsupported grant_type ${grantType}`\n\t});\n\tif (grantTypes.includes(\"authorization_code\") && !responseTypes?.includes(\"code\")) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_client_metadata\",\n\t\terror_description: \"When 'authorization_code' grant type is used, 'code' response type must be included\"\n\t});\n\tif (!grantTypes.includes(\"authorization_code\") && responseTypes?.includes(\"code\")) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_client_metadata\",\n\t\terror_description: \"When 'code' response type is used, 'authorization_code' grant type must be included\"\n\t});\n\tif (clientWithDefaults.subject_type !== void 0) {\n\t\tif (clientWithDefaults.subject_type !== \"public\" && clientWithDefaults.subject_type !== \"pairwise\") throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_client_metadata\",\n\t\t\terror_description: `subject_type must be \"public\" or \"pairwise\"`\n\t\t});\n\t\tif (clientWithDefaults.subject_type === \"pairwise\" && !opts.pairwiseSecret) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_client_metadata\",\n\t\t\terror_description: \"pairwise subject_type requires server pairwiseSecret configuration\"\n\t\t});\n\t\tif (clientWithDefaults.subject_type === \"pairwise\" && clientWithDefaults.redirect_uris?.some(isCustomSchemeWithHost)) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_client_metadata\",\n\t\t\terror_description: \"pairwise clients cannot use custom-scheme redirect URIs that include a host\"\n\t\t});\n\t\tif (clientWithDefaults.subject_type === \"pairwise\" && clientWithDefaults.redirect_uris && clientWithDefaults.redirect_uris.length > 1) {\n\t\t\tif (new Set(clientWithDefaults.redirect_uris.map((uri) => new URL(uri).host)).size > 1) throw new APIError(\"BAD_REQUEST\", {\n\t\t\t\terror: \"invalid_client_metadata\",\n\t\t\t\terror_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.\"\n\t\t\t});\n\t\t}\n\t}\n\tconst requestedScopes = (clientWithDefaults?.scope)?.split(\" \").filter((v) => v.length);\n\tconst validatesRegistrationMetadata = settings?.registrationSource === \"dynamic\" || settings?.registrationSource === \"clientMetadataDocument\";\n\tconst allowedScopes = validatesRegistrationMetadata ? resolveClientRegistrationScopes(opts) : opts.scopes;\n\tif (allowedScopes) {\n\t\tconst validScopes = new Set(allowedScopes);\n\t\tfor (const requestedScope of requestedScopes ?? []) if (!validScopes?.has(requestedScope)) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_scope\",\n\t\t\terror_description: `cannot request scope ${requestedScope}`\n\t\t});\n\t}\n\tif (validatesRegistrationMetadata && clientWithDefaults.require_pkce === false) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_client_metadata\",\n\t\terror_description: `pkce is required for registered clients.`\n\t});\n\tif (clientWithDefaults.jwks || clientWithDefaults.jwks_uri) {\n\t\tif (clientWithDefaults.jwks && clientWithDefaults.jwks_uri) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_client_metadata\",\n\t\t\terror_description: \"jwks and jwks_uri are mutually exclusive\"\n\t\t});\n\t\tif (clientWithDefaults.jwks_uri) try {\n\t\t\tconst uri = new URL(clientWithDefaults.jwks_uri);\n\t\t\tif (uri.protocol !== \"https:\") throw new APIError(\"BAD_REQUEST\", {\n\t\t\t\terror: \"invalid_client_metadata\",\n\t\t\t\terror_description: \"jwks_uri must use HTTPS\"\n\t\t\t});\n\t\t\tif (uri.username || uri.password) throw new APIError(\"BAD_REQUEST\", {\n\t\t\t\terror: \"invalid_client_metadata\",\n\t\t\t\terror_description: \"jwks_uri must not contain credentials\"\n\t\t\t});\n\t\t\tif (clientWithDefaults.jwks_uri.includes(\"#\")) throw new APIError(\"BAD_REQUEST\", {\n\t\t\t\terror: \"invalid_client_metadata\",\n\t\t\t\terror_description: \"jwks_uri must not include a fragment component\"\n\t\t\t});\n\t\t\tif (isPrivateHostname(uri.hostname)) throw new APIError(\"BAD_REQUEST\", {\n\t\t\t\terror: \"invalid_client_metadata\",\n\t\t\t\terror_description: \"jwks_uri must not point to a private or reserved address\"\n\t\t\t});\n\t\t\tif (settings?.ctx && !settings.ctx.context.isTrustedOrigin(uri.href)) {\n\t\t\t\tconst clientId = typeof clientWithDefaults.client_id === \"string\" ? clientWithDefaults.client_id : void 0;\n\t\t\t\tif (!(isClientMetadataDocument && clientId !== void 0 && URL.canParse(clientId) && new URL(clientId).origin === uri.origin)) throw new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\terror: \"invalid_client_metadata\",\n\t\t\t\t\terror_description: \"jwks_uri must belong to a trusted origin or the Client ID Metadata Document origin\"\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof APIError) throw e;\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\terror: \"invalid_client_metadata\",\n\t\t\t\terror_description: \"jwks_uri must be a valid URL\"\n\t\t\t});\n\t\t}\n\t\tif (clientWithDefaults.jwks) assertValidRegistrationJwks(clientWithDefaults.jwks);\n\t}\n\tif (tokenEndpointAuthMethod === \"private_key_jwt\" && !clientWithDefaults.jwks && !clientWithDefaults.jwks_uri) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_client_metadata\",\n\t\terror_description: \"private_key_jwt requires either jwks or jwks_uri\"\n\t});\n\tif (clientWithDefaults.backchannel_logout_uri !== void 0) {\n\t\tif (opts.disableJwtPlugin) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_client_metadata\",\n\t\t\terror_description: \"backchannel_logout_uri requires the jwt plugin (disableJwtPlugin must be false)\"\n\t\t});\n\t\tlet url;\n\t\ttry {\n\t\t\turl = new URL(clientWithDefaults.backchannel_logout_uri);\n\t\t} catch {\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\terror: \"invalid_client_metadata\",\n\t\t\t\terror_description: \"backchannel_logout_uri must be an absolute URL\"\n\t\t\t});\n\t\t}\n\t\tif (clientWithDefaults.backchannel_logout_uri.includes(\"#\")) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_client_metadata\",\n\t\t\terror_description: \"backchannel_logout_uri must not include a fragment component\"\n\t\t});\n\t\tif (url.protocol !== \"https:\") throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_client_metadata\",\n\t\t\terror_description: \"backchannel_logout_uri must use https\"\n\t\t});\n\t\tif (url.username || url.password) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_client_metadata\",\n\t\t\terror_description: \"backchannel_logout_uri must not contain credentials\"\n\t\t});\n\t\tif (isPrivateHostname(url.hostname)) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_client_metadata\",\n\t\t\terror_description: \"backchannel_logout_uri must not point to a private or reserved address\"\n\t\t});\n\t}\n}\nconst CLIENT_REGISTRATION_COLLISION = Symbol(\"client-registration-collision\");\nfunction isClientRegistrationCollision(error) {\n\tif (!error || typeof error !== \"object\") return false;\n\tconst candidate = error;\n\treturn candidate[CLIENT_REGISTRATION_COLLISION] === true && (candidate.kind === \"oauth-client-row-unique\" || candidate.kind === \"oauth-client-resource-link-unique\") && \"cause\" in candidate;\n}\n/**\n* Creates and persists one canonical OAuth client registration.\n*\n* Authorization and ownership resolution belong to endpoint adapters. This\n* operation owns metadata normalization, validation, credentials, persistence,\n* and resource links so canonical creation paths share one transactional\n* boundary.\n*/\nasync function persistOAuthClientRegistration(ctx, opts, input) {\n\tconst registrationMetadata = input.registrationSource === \"dynamic\" && !input.metadata.scope ? {\n\t\t...input.metadata,\n\t\tscope: (opts.clientRegistrationDefaultScopes ?? opts.scopes)?.join(\" \")\n\t} : input.metadata;\n\tconst body = applyOAuthClientRegistrationDefaults(registrationMetadata, input.registrationSource === \"clientMetadataDocument\" ? null : input.registrationSource === \"dynamic\" ? resolveDynamicRegistrationDefaultApplicationType(opts, registrationMetadata) : \"web\");\n\tconst isPublic = body.token_endpoint_auth_method === \"none\";\n\tconst isPrivateKeyJwt = body.token_endpoint_auth_method === \"private_key_jwt\";\n\tconst isExtensionAuthMethod = isExtensionTokenEndpointAuthMethod(opts, body.token_endpoint_auth_method);\n\tawait checkOAuthClient(body, opts, {\n\t\tregistrationSource: input.registrationSource,\n\t\tctx\n\t});\n\tconst clientId = input.clientId ?? opts.generateClientId?.() ?? generateRandomString(32, \"a-z\", \"A-Z\");\n\tconst clientSecret = isPublic || isPrivateKeyJwt || isExtensionAuthMethod ? void 0 : opts.generateClientSecret?.() || generateRandomString(32, \"a-z\", \"A-Z\");\n\tconst storedClientSecret = clientSecret ? await storeClientSecret(ctx, opts, clientSecret) : void 0;\n\tconst isPKCEOptionalForRegisteredClient = input.registrationSource === \"dynamic\" && !isPublic && opts.clientRegistrationRequirePKCE === false;\n\tconst requirePKCE = body.require_pkce ?? (isPKCEOptionalForRegisteredClient ? false : void 0);\n\tconst iat = Math.floor(Date.now() / 1e3);\n\tconst { resources: _requestedResources, ...persistableBody } = input.registrationSource === \"dynamic\" || input.registrationSource === \"clientMetadataDocument\" ? {\n\t\t...body,\n\t\tscope: resolveClientRegistrationScopes(opts).join(\" \")\n\t} : body;\n\tconst owner = input.registrationSource === \"clientMetadataDocument\" ? void 0 : {\n\t\tuserId: input.userId,\n\t\treferenceId: input.referenceId\n\t};\n\tconst schema = oauthToSchema({\n\t\t...persistableBody,\n\t\tredirect_uris: body.redirect_uris ?? [],\n\t\tdisabled: void 0,\n\t\tclient_secret_expires_at: storedClientSecret ? input.registrationSource === \"dynamic\" && opts.clientRegistrationClientSecretExpiration ? toExpJWT(opts.clientRegistrationClientSecretExpiration, iat) : 0 : void 0,\n\t\tclient_id: clientId,\n\t\tclient_secret: storedClientSecret,\n\t\tclient_id_issued_at: iat,\n\t\trequire_pkce: requirePKCE,\n\t\tuser_id: owner?.referenceId ? void 0 : owner?.userId,\n\t\treference_id: owner?.referenceId\n\t});\n\tschema.clientCredentialsScopes = input.registrationSource === \"clientMetadataDocument\" ? input.existingClient?.clientCredentialsScopes ?? [] : input.registrationSource === \"managed\" ? input.clientCredentialsScopes ?? [] : [];\n\tschema.clientDiscoveryId = input.registrationSource === \"clientMetadataDocument\" ? input.clientDiscoveryId : null;\n\tif (input.registrationSource === \"clientMetadataDocument\" && body.application_type === void 0) schema.applicationType = null;\n\tconst requestedResources = input.registrationSource === \"clientMetadataDocument\" ? [] : input.requestedResources ?? [];\n\tif (input.registrationSource === \"dynamic\") assertDynamicRegistrationResourcesAllowed(opts, requestedResources);\n\tconst resources = await resolveClientRegistrationResources(ctx, opts, requestedResources);\n\tconst clientModel = opts.schema?.oauthClient?.modelName ?? \"oauthClient\";\n\tconst clientResourceModel = opts.schema?.oauthClientResource?.modelName ?? \"oauthClientResource\";\n\tconst existingClient = input.registrationSource === \"clientMetadataDocument\" ? input.existingClient : void 0;\n\tconst clientDiscoveryId = input.registrationSource === \"clientMetadataDocument\" ? input.clientDiscoveryId : null;\n\tconst persistenceResult = await runWithTransaction(ctx.context.adapter, async () => {\n\t\tconst adapter = await getCurrentAdapter(ctx.context.adapter);\n\t\tlet storedClient;\n\t\tlet created = false;\n\t\tif (existingClient) {\n\t\t\tconst updatedClient = await adapter.update({\n\t\t\t\tmodel: clientModel,\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"clientId\",\n\t\t\t\t\tvalue: clientId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"clientDiscoveryId\",\n\t\t\t\t\tvalue: clientDiscoveryId\n\t\t\t\t}],\n\t\t\t\tupdate: {\n\t\t\t\t\t...schema,\n\t\t\t\t\tdisabled: existingClient.disabled,\n\t\t\t\t\tskipConsent: existingClient.skipConsent,\n\t\t\t\t\tenableEndSession: existingClient.enableEndSession,\n\t\t\t\t\tcreatedAt: existingClient.createdAt,\n\t\t\t\t\tupdatedAt: /* @__PURE__ */ new Date(iat * 1e3)\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (!updatedClient) throw new APIError(\"BAD_REQUEST\", {\n\t\t\t\terror: \"invalid_client\",\n\t\t\t\terror_description: \"client no longer exists\"\n\t\t\t});\n\t\t\tstoredClient = updatedClient;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tstoredClient = await adapter.create({\n\t\t\t\t\tmodel: clientModel,\n\t\t\t\t\tdata: {\n\t\t\t\t\t\t...schema,\n\t\t\t\t\t\tcreatedAt: /* @__PURE__ */ new Date(iat * 1e3),\n\t\t\t\t\t\tupdatedAt: /* @__PURE__ */ new Date(iat * 1e3)\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (input.registrationSource === \"clientMetadataDocument\" && isUniqueConstraintError(error)) throw {\n\t\t\t\t\t[CLIENT_REGISTRATION_COLLISION]: true,\n\t\t\t\t\tkind: \"oauth-client-row-unique\",\n\t\t\t\t\tclientId,\n\t\t\t\t\tcause: error\n\t\t\t\t};\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tcreated = true;\n\t\t}\n\t\tconst linkedResources = resources.length === 0 ? [] : await adapter.findMany({\n\t\t\tmodel: clientResourceModel,\n\t\t\twhere: [{\n\t\t\t\tfield: \"clientId\",\n\t\t\t\tvalue: clientId\n\t\t\t}]\n\t\t});\n\t\tconst linkedResourceIds = new Set(linkedResources.map((link) => link.resourceId));\n\t\tconst now = /* @__PURE__ */ new Date();\n\t\tfor (const resourceId of resources) {\n\t\t\tif (linkedResourceIds.has(resourceId)) continue;\n\t\t\ttry {\n\t\t\t\tawait adapter.create({\n\t\t\t\t\tmodel: clientResourceModel,\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tclientId,\n\t\t\t\t\t\tresourceId,\n\t\t\t\t\t\tcreatedAt: now\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (input.registrationSource === \"clientMetadataDocument\" && isUniqueConstraintError(error)) throw {\n\t\t\t\t\t[CLIENT_REGISTRATION_COLLISION]: true,\n\t\t\t\t\tkind: \"oauth-client-resource-link-unique\",\n\t\t\t\t\tclientId,\n\t\t\t\t\tresourceId,\n\t\t\t\t\tcause: error\n\t\t\t\t};\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tclient: storedClient,\n\t\t\tcreated\n\t\t};\n\t});\n\treturn {\n\t\tclient: persistenceResult.client,\n\t\tclientSecret,\n\t\tresources,\n\t\tcreated: persistenceResult.created\n\t};\n}\nfunction createOAuthClientRegistrationResponse(result, opts) {\n\tconst responseBody = schemaToOAuth({\n\t\t...result.client,\n\t\tclientSecret: result.clientSecret ? (opts.prefix?.clientSecret ?? \"\") + result.clientSecret : void 0\n\t});\n\tif (result.resources.length > 0) responseBody.resources = result.resources;\n\treturn responseBody;\n}\nfunction createOAuthClientAdministrativeResponse(result, opts) {\n\treturn {\n\t\t...createOAuthClientRegistrationResponse(result, opts),\n\t\tclient_credentials_scopes: [...result.client.clientCredentialsScopes ?? []]\n\t};\n}\n/**\n* Creates and persists one canonical OAuth client registration.\n*/\nasync function createOAuthClientRegistration(ctx, opts, input) {\n\treturn createOAuthClientRegistrationResponse(await persistOAuthClientRegistration(ctx, opts, input), opts);\n}\nasync function createOAuthClientAdministrativeRegistration(ctx, opts, input) {\n\treturn createOAuthClientAdministrativeResponse(await persistOAuthClientRegistration(ctx, opts, input), opts);\n}\nfunction assertClientDiscoveryOwnership(client, clientDiscoveryId) {\n\tif (!client || client.clientDiscoveryId === clientDiscoveryId) return;\n\tthrow new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_client\",\n\t\terror_description: \"client_id is already owned by a different registration source\"\n\t});\n}\n/**\n* First-party persistence seam for a validated Client ID Metadata Document.\n*\n* This operation owns both initial creation and atomic replacement. It never\n* generates a client secret, preserves operator-controlled flags on\n* replacement, and ensures server-default resource links in the same\n* transaction.\n*\n* @internal\n*/\nasync function registerClientMetadataDocument(ctx, opts, input) {\n\tassertClientDiscoveryOwnership(input.existingClient, input.clientDiscoveryId);\n\tif (input.metadata.backchannel_logout_uri !== void 0 || input.metadata.backchannel_logout_session_required !== void 0) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_client_metadata\",\n\t\terror_description: \"Client ID Metadata Documents cannot register a back-channel logout target\"\n\t});\n\tif ((input.metadata.token_endpoint_auth_method ?? \"none\") !== \"none\" && input.metadata.token_endpoint_auth_method !== \"private_key_jwt\") throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_client_metadata\",\n\t\terror_description: \"Client ID Metadata Document clients cannot use a shared secret\"\n\t});\n\tconst registrationInput = {\n\t\t...input,\n\t\tmetadata: {\n\t\t\t...input.metadata,\n\t\t\ttoken_endpoint_auth_method: input.metadata.token_endpoint_auth_method ?? \"none\",\n\t\t\tclient_secret: void 0,\n\t\t\tclient_secret_expires_at: void 0\n\t\t},\n\t\tregistrationSource: \"clientMetadataDocument\"\n\t};\n\ttry {\n\t\treturn await persistOAuthClientRegistration(ctx, opts, registrationInput);\n\t} catch (error) {\n\t\tif (!isClientRegistrationCollision(error)) throw error;\n\t\tconst clientModel = opts.schema?.oauthClient?.modelName ?? \"oauthClient\";\n\t\tconst clientResourceModel = opts.schema?.oauthClientResource?.modelName ?? \"oauthClientResource\";\n\t\tconst currentClient = await ctx.context.adapter.findOne({\n\t\t\tmodel: clientModel,\n\t\t\twhere: [{\n\t\t\t\tfield: \"clientId\",\n\t\t\t\tvalue: input.clientId\n\t\t\t}]\n\t\t});\n\t\tif (error.clientId !== input.clientId || !currentClient || currentClient.clientDiscoveryId !== input.clientDiscoveryId) throw error.cause;\n\t\tif (error.kind === \"oauth-client-resource-link-unique\") {\n\t\t\tif (!await ctx.context.adapter.findOne({\n\t\t\t\tmodel: clientResourceModel,\n\t\t\t\twhere: [{\n\t\t\t\t\tfield: \"clientId\",\n\t\t\t\t\tvalue: error.clientId\n\t\t\t\t}, {\n\t\t\t\t\tfield: \"resourceId\",\n\t\t\t\t\tvalue: error.resourceId\n\t\t\t\t}]\n\t\t\t})) throw error.cause;\n\t\t}\n\t\ttry {\n\t\t\treturn await persistOAuthClientRegistration(ctx, opts, {\n\t\t\t\t...registrationInput,\n\t\t\t\texistingClient: currentClient\n\t\t\t});\n\t\t} catch (retryError) {\n\t\t\tif (isClientRegistrationCollision(retryError)) throw retryError.cause;\n\t\t\tthrow retryError;\n\t\t}\n\t}\n}\nfunction isUniqueConstraintError(error) {\n\tif (!error || typeof error !== \"object\") return false;\n\tconst candidate = error;\n\tconst code = String(candidate.code ?? candidate.errno ?? \"\");\n\tif ([\n\t\t\"1062\",\n\t\t\"11000\",\n\t\t\"23505\",\n\t\t\"ER_DUP_ENTRY\",\n\t\t\"P2002\",\n\t\t\"SQLITE_CONSTRAINT_UNIQUE\"\n\t].includes(code)) return true;\n\tif (candidate.name === \"MongoServerError\" && candidate.code === 11e3) return true;\n\treturn typeof candidate.message === \"string\" && /(?:duplicate|unique constraint|unique key)/i.test(candidate.message);\n}\nasync function createOAuthClientEndpoint(ctx, opts, settings) {\n\tconst session = await getSessionFromCtx(ctx);\n\tawait assertClientPrivileges(ctx, session, opts, \"create\");\n\tif (!session) throw new APIError(\"UNAUTHORIZED\");\n\tconst referenceId = opts.clientReference ? await opts.clientReference({\n\t\tuser: session.user,\n\t\tsession: session.session\n\t}) : void 0;\n\tconst { client_credentials_scopes: rawClientCredentialsScopes, ...metadata } = ctx.body;\n\tconst clientCredentialsScopes = settings?.admin ? normalizeClientCredentialsScopes(rawClientCredentialsScopes ?? []) : [];\n\tvalidateClientCredentialsScopes(clientCredentialsScopes, resolveRegistrationGrantTypes(metadata), metadata.token_endpoint_auth_method, opts);\n\tif (clientCredentialsScopes.length > 0) await assertClientPrivileges(ctx, session, opts, \"configure-client-credentials-scopes\");\n\tconst requestedResources = settings?.admin ? metadata.resources : void 0;\n\tfor (const identifier of new Set(requestedResources ?? [])) await assertResourcePrivileges(ctx, session, opts, \"link\", identifier);\n\tconst registrationInput = {\n\t\tmetadata,\n\t\tregistrationSource: \"managed\",\n\t\tuserId: referenceId ? void 0 : session.session.userId,\n\t\treferenceId,\n\t\tclientCredentialsScopes,\n\t\t...requestedResources ? { requestedResources } : {}\n\t};\n\tconst responseBody = settings?.admin ? await createOAuthClientAdministrativeRegistration(ctx, opts, registrationInput) : await createOAuthClientRegistration(ctx, opts, registrationInput);\n\tctx.setStatus(201);\n\treturn ctx.json(responseBody);\n}\nfunction oauthToSchema(input) {\n\tconst { client_id: clientId, client_secret: clientSecret, client_secret_expires_at: _expiresAt, scope: _scope, user_id: userId, client_id_issued_at: _createdAt, client_name: name, client_uri: uri, logo_uri: icon, contacts, tos_uri: tos, policy_uri: policy, jwks: inputJwks, jwks_uri: jwksUri, software_id: softwareId, software_version: softwareVersion, software_statement: softwareStatement, redirect_uris: redirectUris, post_logout_redirect_uris: postLogoutRedirectUris, backchannel_logout_uri: backchannelLogoutUri, backchannel_logout_session_required: backchannelLogoutSessionRequired, token_endpoint_auth_method: tokenEndpointAuthMethod, grant_types: grantTypes, response_types: responseTypes, application_type: applicationType, disabled, skip_consent: skipConsent, enable_end_session: enableEndSession, require_pkce: requirePKCE, dpop_bound_access_tokens: dpopBoundAccessTokens, subject_type: subjectType, reference_id: referenceId, metadata: inputMetadata } = input;\n\tconst expiresAt = _expiresAt ? /* @__PURE__ */ new Date(Number(_expiresAt) * 1e3) : void 0;\n\tconst createdAt = _createdAt ? /* @__PURE__ */ new Date(_createdAt * 1e3) : void 0;\n\tconst scopes = _scope?.split(\" \");\n\tconst metadataObj = stripReservedOAuthClientMetadataExtensions(inputMetadata ?? {});\n\tconst metadata = metadataObj && Object.keys(metadataObj).length ? JSON.stringify(metadataObj) : void 0;\n\treturn {\n\t\tclientId,\n\t\tclientSecret,\n\t\tdisabled,\n\t\tscopes,\n\t\tuserId,\n\t\tcreatedAt,\n\t\texpiresAt,\n\t\tname,\n\t\turi,\n\t\ticon,\n\t\tcontacts,\n\t\ttos,\n\t\tpolicy,\n\t\tsoftwareId,\n\t\tsoftwareVersion,\n\t\tsoftwareStatement,\n\t\tredirectUris,\n\t\tpostLogoutRedirectUris,\n\t\tbackchannelLogoutUri,\n\t\tbackchannelLogoutSessionRequired,\n\t\ttokenEndpointAuthMethod,\n\t\tgrantTypes,\n\t\tresponseTypes,\n\t\tjwks: inputJwks ? JSON.stringify(inputJwks) : void 0,\n\t\tjwksUri,\n\t\tapplicationType,\n\t\tskipConsent,\n\t\tenableEndSession,\n\t\trequirePKCE,\n\t\tdpopBoundAccessTokens,\n\t\tsubjectType,\n\t\treferenceId,\n\t\tmetadata\n\t};\n}\n/**\n* Converts a Database Schema to an OAuth 2.0 Dynamic Client Schema\n* @param input\n* @param cleaned - default true, determines if the output has only Oauth 2.0 compatible data\n* @returns\n*/\nfunction schemaToOAuth(input) {\n\tconst { clientId, clientSecret, disabled, scopes, userId, createdAt, updatedAt: _updatedAt, expiresAt, name, uri, icon, contacts, tos, policy, softwareId, softwareVersion, softwareStatement, redirectUris, postLogoutRedirectUris, backchannelLogoutUri, backchannelLogoutSessionRequired, tokenEndpointAuthMethod, grantTypes, responseTypes, applicationType, jwks, jwksUri, skipConsent, enableEndSession, requirePKCE, dpopBoundAccessTokens, subjectType, referenceId, metadata } = input;\n\tconst _expiresAt = expiresAt ? Math.round(new Date(expiresAt).getTime() / 1e3) : void 0;\n\tconst _createdAt = createdAt ? Math.round(new Date(createdAt).getTime() / 1e3) : void 0;\n\tconst _scopes = scopes?.join(\" \");\n\treturn {\n\t\t...stripReservedOAuthClientMetadataExtensions(parseClientMetadata(metadata)),\n\t\tclient_id: clientId,\n\t\tclient_secret: clientSecret ?? void 0,\n\t\tclient_secret_expires_at: clientSecret ? _expiresAt ?? 0 : void 0,\n\t\tscope: _scopes ?? void 0,\n\t\tuser_id: userId ?? void 0,\n\t\tclient_id_issued_at: _createdAt ?? void 0,\n\t\tclient_name: name ?? void 0,\n\t\tclient_uri: uri ?? void 0,\n\t\tlogo_uri: icon ?? void 0,\n\t\tcontacts: contacts ?? void 0,\n\t\ttos_uri: tos ?? void 0,\n\t\tpolicy_uri: policy ?? void 0,\n\t\tjwks: jwks ? JSON.parse(jwks) : void 0,\n\t\tjwks_uri: jwksUri ?? void 0,\n\t\tsoftware_id: softwareId ?? void 0,\n\t\tsoftware_version: softwareVersion ?? void 0,\n\t\tsoftware_statement: softwareStatement ?? void 0,\n\t\tredirect_uris: redirectUris ?? [],\n\t\tpost_logout_redirect_uris: postLogoutRedirectUris ?? void 0,\n\t\tbackchannel_logout_uri: backchannelLogoutUri ?? void 0,\n\t\tbackchannel_logout_session_required: backchannelLogoutSessionRequired ?? void 0,\n\t\ttoken_endpoint_auth_method: tokenEndpointAuthMethod ?? void 0,\n\t\tgrant_types: grantTypes ?? void 0,\n\t\tresponse_types: responseTypes ?? void 0,\n\t\tapplication_type: applicationType ?? void 0,\n\t\tdisabled: disabled ?? void 0,\n\t\tskip_consent: skipConsent ?? void 0,\n\t\tenable_end_session: enableEndSession ?? void 0,\n\t\trequire_pkce: requirePKCE ?? void 0,\n\t\tdpop_bound_access_tokens: dpopBoundAccessTokens ?? void 0,\n\t\tsubject_type: subjectType ?? void 0,\n\t\treference_id: referenceId ?? void 0\n\t};\n}\n//#endregion\n//#region src/oauthClient/endpoints.ts\nasync function getClientEndpoint(ctx, opts) {\n\tconst session = await getSessionFromCtx(ctx);\n\tawait assertClientPrivileges(ctx, session, opts, \"read\", ctx.query.client_id);\n\tif (!session) throw new APIError(\"UNAUTHORIZED\");\n\tconst client = await getClient(ctx, opts, ctx.query.client_id);\n\tif (!client) throw new APIError(\"NOT_FOUND\", {\n\t\terror_description: \"client not found\",\n\t\terror: \"not_found\"\n\t});\n\tif (client.userId) {\n\t\tif (client.userId !== session.user.id) throw new APIError(\"UNAUTHORIZED\");\n\t} else if (client.referenceId && opts.clientReference) {\n\t\tif (client.referenceId !== await opts.clientReference(session)) throw new APIError(\"UNAUTHORIZED\");\n\t} else throw new APIError(\"UNAUTHORIZED\");\n\tconst res = schemaToOAuth(client);\n\tres.client_secret = void 0;\n\treturn res;\n}\n/**\n* Provides public client fields for any logged-in user.\n* This is commonly used to display information on login flow pages.\n*/\nasync function getClientPublicEndpoint(ctx, opts, clientId) {\n\tconst client = await getClient(ctx, opts, clientId);\n\tif (!client) throw new APIError(\"NOT_FOUND\", {\n\t\terror_description: \"client not found\",\n\t\terror: \"not_found\"\n\t});\n\tif (client.disabled) throw new APIError(\"NOT_FOUND\", {\n\t\terror_description: \"client not found\",\n\t\terror: \"not_found\"\n\t});\n\treturn schemaToOAuth({\n\t\tclientId: client.clientId,\n\t\tname: client.name,\n\t\turi: client.uri,\n\t\tcontacts: client.contacts,\n\t\ticon: client.icon,\n\t\ttos: client.tos,\n\t\tpolicy: client.policy\n\t});\n}\nasync function getClientsEndpoint(ctx, opts) {\n\tconst session = await getSessionFromCtx(ctx);\n\tawait assertClientPrivileges(ctx, session, opts, \"list\");\n\tif (!session) throw new APIError(\"UNAUTHORIZED\");\n\tconst referenceId = await opts.clientReference?.(session);\n\tif (referenceId) return await ctx.context.adapter.findMany({\n\t\tmodel: \"oauthClient\",\n\t\twhere: [{\n\t\t\tfield: \"referenceId\",\n\t\t\tvalue: referenceId\n\t\t}]\n\t}).then((res) => {\n\t\tif (!res) return null;\n\t\treturn res.map((v) => {\n\t\t\tconst res = schemaToOAuth(v);\n\t\t\tres.client_secret = void 0;\n\t\t\treturn res;\n\t\t});\n\t});\n\telse if (session.user.id) return await ctx.context.adapter.findMany({\n\t\tmodel: \"oauthClient\",\n\t\twhere: [{\n\t\t\tfield: \"userId\",\n\t\t\tvalue: session.user.id\n\t\t}]\n\t}).then((res) => {\n\t\tif (!res) return null;\n\t\treturn res.map((v) => {\n\t\t\tconst res = schemaToOAuth(v);\n\t\t\tres.client_secret = void 0;\n\t\t\treturn res;\n\t\t});\n\t});\n\telse throw new APIError(\"BAD_REQUEST\", { message: \"either user_id or reference_id must be provided\" });\n}\nasync function deleteClientEndpoint(ctx, opts) {\n\tconst session = await getSessionFromCtx(ctx);\n\tawait assertClientPrivileges(ctx, session, opts, \"delete\", ctx.body.client_id);\n\tif (!session) throw new APIError(\"UNAUTHORIZED\");\n\tconst clientId = ctx.body.client_id;\n\tif (opts.cachedTrustedClients?.has(clientId)) throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n\t\terror_description: \"trusted clients must be updated manually\",\n\t\terror: \"invalid_client\"\n\t});\n\tconst client = await getClient(ctx, opts, clientId);\n\tif (!client) throw new APIError(\"NOT_FOUND\", {\n\t\terror_description: \"client not found\",\n\t\terror: \"not_found\"\n\t});\n\tif (client.userId) {\n\t\tif (client.userId !== session.user.id) throw new APIError(\"UNAUTHORIZED\");\n\t} else if (client.referenceId && opts.clientReference) {\n\t\tif (client.referenceId !== await opts.clientReference(session)) throw new APIError(\"UNAUTHORIZED\");\n\t} else throw new APIError(\"UNAUTHORIZED\");\n\tawait ctx.context.adapter.delete({\n\t\tmodel: \"oauthClient\",\n\t\twhere: [{\n\t\t\tfield: \"clientId\",\n\t\t\tvalue: clientId\n\t\t}]\n\t});\n}\nasync function updateClientEndpoint(ctx, opts, settings) {\n\tconst session = await getSessionFromCtx(ctx);\n\tawait assertClientPrivileges(ctx, session, opts, \"update\", ctx.body.client_id);\n\tif (!session) throw new APIError(\"UNAUTHORIZED\");\n\tconst clientId = ctx.body.client_id;\n\tif (opts.cachedTrustedClients?.has(clientId)) throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n\t\terror_description: \"trusted clients must be updated manually\",\n\t\terror: \"invalid_client\"\n\t});\n\tconst client = await getClient(ctx, opts, clientId);\n\tif (!client) throw new APIError(\"NOT_FOUND\", {\n\t\terror_description: \"client not found\",\n\t\terror: \"not_found\"\n\t});\n\tconst { client_credentials_scopes: rawClientCredentialsScopes, ...updates } = ctx.body.update;\n\tconst ownsClient = client.userId ? client.userId === session.user.id : client.referenceId && opts.clientReference ? client.referenceId === await opts.clientReference(session) : false;\n\tconst isCrossOwnerScopeConfiguration = !ownsClient && settings?.admin && rawClientCredentialsScopes !== void 0 && Object.keys(updates).length === 0;\n\tif (!ownsClient && !isCrossOwnerScopeConfiguration) throw new APIError(\"UNAUTHORIZED\");\n\tif (isCrossOwnerScopeConfiguration) await assertClientPrivileges(ctx, session, opts, \"configure-client-credentials-scopes\", clientId);\n\tif (Object.keys(updates).length === 0 && rawClientCredentialsScopes === void 0) {\n\t\tconst res = schemaToOAuth(client);\n\t\tres.client_secret = void 0;\n\t\tif (settings?.admin) return {\n\t\t\t...res,\n\t\t\tclient_credentials_scopes: [...client.clientCredentialsScopes ?? []]\n\t\t};\n\t\treturn res;\n\t}\n\tconst finalGrantTypes = updates.grant_types ?? client.grantTypes ?? [];\n\tconst finalTokenEndpointAuthMethod = updates.token_endpoint_auth_method ?? client.tokenEndpointAuthMethod;\n\tconst clientCredentialsScopes = rawClientCredentialsScopes === void 0 ? void 0 : normalizeClientCredentialsScopes(rawClientCredentialsScopes);\n\tif (clientCredentialsScopes !== void 0) {\n\t\tvalidateClientCredentialsScopes(clientCredentialsScopes, finalGrantTypes, finalTokenEndpointAuthMethod, opts);\n\t\tif (clientCredentialsScopes.length > 0 && !isCrossOwnerScopeConfiguration) await assertClientPrivileges(ctx, session, opts, \"configure-client-credentials-scopes\", clientId);\n\t}\n\tawait checkOAuthClient({\n\t\t...schemaToOAuth(client),\n\t\t...updates\n\t}, opts, { ctx });\n\tconst schemaUpdates = { ...oauthToSchema(updates) };\n\tif (!finalGrantTypes.includes(\"client_credentials\") || finalTokenEndpointAuthMethod === \"none\") schemaUpdates.clientCredentialsScopes = [];\n\telse if (clientCredentialsScopes !== void 0) schemaUpdates.clientCredentialsScopes = clientCredentialsScopes;\n\tif (updates.token_endpoint_auth_method) if (updates.token_endpoint_auth_method === \"private_key_jwt\") schemaUpdates.clientSecret = null;\n\telse {\n\t\tschemaUpdates.jwks = null;\n\t\tschemaUpdates.jwksUri = null;\n\t\tif (!schemaUpdates.clientSecret) schemaUpdates.clientSecret = await storeClientSecret(ctx, opts, opts.generateClientSecret?.() || generateRandomString(32, \"a-z\", \"A-Z\"));\n\t}\n\tconst updatedClient = await ctx.context.adapter.update({\n\t\tmodel: \"oauthClient\",\n\t\twhere: [{\n\t\t\tfield: \"clientId\",\n\t\t\tvalue: clientId\n\t\t}],\n\t\tupdate: {\n\t\t\t...schemaUpdates,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date(Math.floor(Date.now() / 1e3) * 1e3)\n\t\t}\n\t});\n\tif (!updatedClient) throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n\t\terror_description: \"unable to update client\",\n\t\terror: \"invalid_client\"\n\t});\n\tconst res = schemaToOAuth(updatedClient);\n\tres.client_secret = void 0;\n\tif (settings?.admin) return {\n\t\t...res,\n\t\tclient_credentials_scopes: [...updatedClient.clientCredentialsScopes ?? []]\n\t};\n\treturn res;\n}\nasync function rotateClientSecretEndpoint(ctx, opts) {\n\tconst session = await getSessionFromCtx(ctx);\n\tawait assertClientPrivileges(ctx, session, opts, \"rotate\", ctx.body.client_id);\n\tif (!session) throw new APIError(\"UNAUTHORIZED\");\n\tconst clientId = ctx.body.client_id;\n\tif (opts.cachedTrustedClients?.has(clientId)) throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n\t\terror_description: \"trusted clients must be updated manually\",\n\t\terror: \"invalid_client\"\n\t});\n\tconst client = await getClient(ctx, opts, clientId);\n\tif (!client) throw new APIError(\"NOT_FOUND\", {\n\t\terror_description: \"client not found\",\n\t\terror: \"not_found\"\n\t});\n\tif (client.userId) {\n\t\tif (client.userId !== session.user.id) throw new APIError(\"UNAUTHORIZED\");\n\t} else if (client.referenceId && opts.clientReference) {\n\t\tif (client.referenceId !== await opts.clientReference(session)) throw new APIError(\"UNAUTHORIZED\");\n\t} else throw new APIError(\"UNAUTHORIZED\");\n\tif (client.tokenEndpointAuthMethod === \"none\" || !client.clientSecret) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: \"secret rotation is only available for clients using client_secret authentication\",\n\t\terror: \"invalid_client\"\n\t});\n\tconst clientSecret = opts.generateClientSecret?.() || generateRandomString(32, \"a-z\", \"A-Z\");\n\tconst storedClientSecret = clientSecret ? await storeClientSecret(ctx, opts, clientSecret) : void 0;\n\tconst updatedClient = await ctx.context.adapter.update({\n\t\tmodel: \"oauthClient\",\n\t\twhere: [{\n\t\t\tfield: \"clientId\",\n\t\t\tvalue: clientId\n\t\t}],\n\t\tupdate: {\n\t\t\tclientSecret: storedClientSecret,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date(Math.floor(Date.now() / 1e3) * 1e3)\n\t\t}\n\t});\n\tif (!updatedClient) throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n\t\terror_description: \"unable to update client\",\n\t\terror: \"invalid_client\"\n\t});\n\treturn schemaToOAuth({\n\t\t...updatedClient,\n\t\tclientSecret: (opts.prefix?.clientSecret ?? \"\") + clientSecret\n\t});\n}\n//#endregion\n//#region src/oauthClient/index.ts\nconst tokenEndpointAuthMethodSchema = z.string().trim().min(1);\nconst grantTypesSchema = z.array(z.string().trim().min(1)).min(1);\nconst adminCreateOAuthClient = (opts) => createAuthEndpoint(\"/admin/oauth2/create-client\", {\n\tmethod: \"POST\",\n\tbody: z.object({\n\t\tredirect_uris: z.array(SafeUrlSchema).min(1).optional(),\n\t\tscope: z.string().optional(),\n\t\tclient_name: z.string().optional(),\n\t\tclient_uri: z.string().optional(),\n\t\tlogo_uri: z.string().optional(),\n\t\tcontacts: z.array(z.string().min(1)).min(1).optional(),\n\t\ttos_uri: z.string().optional(),\n\t\tpolicy_uri: z.string().optional(),\n\t\tsoftware_id: z.string().optional(),\n\t\tsoftware_version: z.string().optional(),\n\t\tsoftware_statement: z.string().optional(),\n\t\tpost_logout_redirect_uris: z.array(SafeUrlSchema).min(1).optional(),\n\t\tbackchannel_logout_uri: SafeUrlSchema.optional(),\n\t\tbackchannel_logout_session_required: z.boolean().optional(),\n\t\ttoken_endpoint_auth_method: tokenEndpointAuthMethodSchema.optional(),\n\t\tapplication_type: z.enum([\"web\", \"native\"]).optional(),\n\t\tjwks: clientJwksSchema.optional(),\n\t\tjwks_uri: z.string().optional(),\n\t\tgrant_types: grantTypesSchema.optional(),\n\t\tclient_credentials_scopes: z.array(z.string().trim().min(1)).optional(),\n\t\tresources: z.array(ResourceUriSchema).optional(),\n\t\tresponse_types: z.array(z.enum([\"code\"])).optional(),\n\t\tclient_secret_expires_at: z.union([z.string(), z.number()]).optional().default(0),\n\t\tskip_consent: z.boolean().optional(),\n\t\tenable_end_session: z.boolean().optional(),\n\t\trequire_pkce: z.boolean().optional(),\n\t\tdpop_bound_access_tokens: z.boolean().optional(),\n\t\tsubject_type: z.enum([\"public\", \"pairwise\"]).optional(),\n\t\tmetadata: z.record(z.string(), z.unknown()).optional()\n\t}),\n\tmetadata: {\n\t\tnoStore: true,\n\t\tSERVER_ONLY: true,\n\t\topenapi: {\n\t\t\tdescription: \"Register an OAuth2 application\",\n\t\t\tresponses: { \"201\": {\n\t\t\t\tdescription: \"OAuth2 application registered successfully\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t/** @returns {OauthClient} */\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tclient_id: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Unique identifier for the client\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclient_secret: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Secret key for the client\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclient_secret_expires_at: {\n\t\t\t\t\t\t\ttype: \"number\",\n\t\t\t\t\t\t\tdescription: \"Time the client secret will expire. If 0, the client secret will never expire.\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tscope: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Space-separated scopes allowed by the client\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclient_credentials_scopes: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\tdescription: \"Server-authorized scope ceiling for client_credentials tokens\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tuser_id: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"ID of the user who registered the client, null if registered anonymously\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclient_id_issued_at: {\n\t\t\t\t\t\t\ttype: \"number\",\n\t\t\t\t\t\t\tdescription: \"Creation timestamp of this client\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclient_name: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Name of the OAuth2 application\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclient_uri: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"URI of the OAuth2 application\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tlogo_uri: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Icon URI for the application\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcontacts: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\tdescription: \"List representing ways to contact people responsible for this client, typically email addresses\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttos_uri: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Client's terms of service uri\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tpolicy_uri: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Client's policy uri\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsoftware_id: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Unique identifier assigned by the developer to help in the dynamic registration process\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsoftware_version: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Version identifier for the software_id\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsoftware_statement: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"JWT containing metadata values about the client software as claims\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tredirect_uris: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"uri\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tdescription: \"List of allowed redirect uris\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttoken_endpoint_auth_method: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Requested authentication method for the token endpoint\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tgrant_types: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\tdescription: \"Grant types the client may use at the token endpoint\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tresponse_types: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tenum: [\"code\"]\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tdescription: \"Response types the client may use at the authorization endpoint\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tapplication_type: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"OIDC application type used to classify redirect URI policy\",\n\t\t\t\t\t\t\tenum: [\"web\", \"native\"]\n\t\t\t\t\t\t},\n\t\t\t\t\t\tresources: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"uri\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tdescription: \"Final server-owned resources linked to the client\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdisabled: {\n\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\tdescription: \"Whether the client is disabled\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequire_pkce: {\n\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\tdescription: \"Whether the client requires PKCE\",\n\t\t\t\t\t\t\tdefault: true\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tadditionalProperties: true,\n\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\tdescription: \"Additional metadata for the application\"\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"client_id\"]\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t}\n}, async (ctx) => {\n\treturn createOAuthClientEndpoint(ctx, opts, { admin: true });\n});\nconst createOAuthClient = (opts) => createAuthEndpoint(\"/oauth2/create-client\", {\n\tmethod: \"POST\",\n\tuse: [sessionMiddleware],\n\tbody: z.object({\n\t\tredirect_uris: z.array(SafeUrlSchema).min(1).optional(),\n\t\tscope: z.string().optional(),\n\t\tclient_name: z.string().optional(),\n\t\tclient_uri: z.string().optional(),\n\t\tlogo_uri: z.string().optional(),\n\t\tcontacts: z.array(z.string().min(1)).min(1).optional(),\n\t\ttos_uri: z.string().optional(),\n\t\tpolicy_uri: z.string().optional(),\n\t\tsoftware_id: z.string().optional(),\n\t\tsoftware_version: z.string().optional(),\n\t\tsoftware_statement: z.string().optional(),\n\t\tpost_logout_redirect_uris: z.array(SafeUrlSchema).min(1).optional(),\n\t\tbackchannel_logout_uri: SafeUrlSchema.optional(),\n\t\tbackchannel_logout_session_required: z.boolean().optional(),\n\t\ttoken_endpoint_auth_method: tokenEndpointAuthMethodSchema.optional(),\n\t\tapplication_type: z.enum([\"web\", \"native\"]).optional(),\n\t\tjwks: clientJwksSchema.optional(),\n\t\tjwks_uri: z.string().optional(),\n\t\tgrant_types: grantTypesSchema.optional(),\n\t\tresponse_types: z.array(z.enum([\"code\"])).optional(),\n\t\tdpop_bound_access_tokens: z.boolean().optional()\n\t}),\n\tmetadata: {\n\t\tnoStore: true,\n\t\topenapi: {\n\t\t\tdescription: \"Register an OAuth2 application\",\n\t\t\tresponses: { \"201\": {\n\t\t\t\tdescription: \"OAuth2 application registered successfully\",\n\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t/** @returns {OauthClient} */\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tclient_id: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Unique identifier for the client\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclient_secret: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Secret key for the client\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclient_secret_expires_at: {\n\t\t\t\t\t\t\ttype: \"number\",\n\t\t\t\t\t\t\tdescription: \"Time the client secret will expire. If 0, the client secret will never expire.\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tscope: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Space-separated scopes allowed by the client\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tuser_id: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"ID of the user who registered the client, null if registered anonymously\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclient_id_issued_at: {\n\t\t\t\t\t\t\ttype: \"number\",\n\t\t\t\t\t\t\tdescription: \"Creation timestamp of this client\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclient_name: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Name of the OAuth2 application\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclient_uri: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"URI of the OAuth2 application\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tlogo_uri: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Icon URI for the application\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcontacts: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\tdescription: \"List representing ways to contact people responsible for this client, typically email addresses\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttos_uri: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Client's terms of service uri\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tpolicy_uri: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Client's policy uri\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsoftware_id: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Unique identifier assigned by the developer to help in the dynamic registration process\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsoftware_version: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Version identifier for the software_id\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsoftware_statement: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"JWT containing metadata values about the client software as claims\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tredirect_uris: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"uri\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tdescription: \"List of allowed redirect uris\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttoken_endpoint_auth_method: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"Requested authentication method for the token endpoint\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tgrant_types: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\tdescription: \"Grant types the client may use at the token endpoint\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tresponse_types: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tenum: [\"code\"]\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tdescription: \"Response types the client may use at the authorization endpoint\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tapplication_type: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tdescription: \"OIDC application type used to classify redirect URI policy\",\n\t\t\t\t\t\t\tenum: [\"web\", \"native\"]\n\t\t\t\t\t\t},\n\t\t\t\t\t\tresources: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"uri\"\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tdescription: \"Final server-owned resources linked to the client\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdisabled: {\n\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\tdescription: \"Whether the client is disabled\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tadditionalProperties: true,\n\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\tdescription: \"Additional metadata for the application\"\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\trequired: [\"client_id\"]\n\t\t\t\t} } }\n\t\t\t} }\n\t\t}\n\t}\n}, async (ctx) => {\n\treturn createOAuthClientEndpoint(ctx, opts);\n});\nconst getOAuthClient = (opts) => createAuthEndpoint(\"/oauth2/get-client\", {\n\tmethod: \"GET\",\n\tuse: [sessionMiddleware],\n\tquery: z.object({ client_id: z.string() }),\n\tmetadata: { openapi: { description: \"Get OAuth2 formatted client details\" } }\n}, async (ctx) => {\n\treturn getClientEndpoint(ctx, opts);\n});\nconst getOAuthClientPublic = (opts) => createAuthEndpoint(\"/oauth2/public-client\", {\n\tmethod: \"GET\",\n\tuse: [sessionMiddleware],\n\tquery: z.object({ client_id: z.string() }),\n\tmetadata: { openapi: { description: \"Gets publicly available client fields\" } }\n}, async (ctx) => {\n\tconst clientId = ctx.query.client_id;\n\treturn getClientPublicEndpoint(ctx, opts, clientId);\n});\nconst getOAuthClientPublicPrelogin = (opts) => createAuthEndpoint(\"/oauth2/public-client-prelogin\", {\n\tmethod: \"POST\",\n\tuse: [publicSessionMiddleware(opts)],\n\tbody: z.object({\n\t\tclient_id: z.string(),\n\t\toauth_query: z.string().optional()\n\t}),\n\tmetadata: { openapi: { description: \"Gets publicly available client fields (prior to login)\" } }\n}, async (ctx) => {\n\tconst clientId = ctx.body.client_id;\n\treturn getClientPublicEndpoint(ctx, opts, clientId);\n});\nconst getOAuthClients = (opts) => createAuthEndpoint(\"/oauth2/get-clients\", {\n\tmethod: \"GET\",\n\tuse: [sessionMiddleware],\n\tmetadata: { openapi: { description: \"Get OAuth2 formatted client details for a user or organization\" } }\n}, async (ctx) => {\n\treturn getClientsEndpoint(ctx, opts);\n});\nconst adminUpdateOAuthClient = (opts) => createAuthEndpoint(\"/admin/oauth2/update-client\", {\n\tmethod: \"PATCH\",\n\tbody: z.object({\n\t\tclient_id: z.string(),\n\t\tupdate: z.object({\n\t\t\tredirect_uris: z.array(SafeUrlSchema).min(1).optional(),\n\t\t\tscope: z.string().optional(),\n\t\t\tclient_name: z.string().optional(),\n\t\t\tclient_uri: z.string().optional(),\n\t\t\tlogo_uri: z.string().optional(),\n\t\t\tcontacts: z.array(z.string().min(1)).min(1).optional(),\n\t\t\ttos_uri: z.string().optional(),\n\t\t\tpolicy_uri: z.string().optional(),\n\t\t\tsoftware_id: z.string().optional(),\n\t\t\tsoftware_version: z.string().optional(),\n\t\t\tsoftware_statement: z.string().optional(),\n\t\t\tpost_logout_redirect_uris: z.array(SafeUrlSchema).min(1).optional(),\n\t\t\tbackchannel_logout_uri: SafeUrlSchema.optional(),\n\t\t\tbackchannel_logout_session_required: z.boolean().optional(),\n\t\t\tapplication_type: z.enum([\"web\", \"native\"]).optional(),\n\t\t\tgrant_types: grantTypesSchema.optional(),\n\t\t\tclient_credentials_scopes: z.array(z.string().trim().min(1)).optional(),\n\t\t\tresponse_types: z.array(z.enum([\"code\"])).optional(),\n\t\t\tclient_secret_expires_at: z.union([z.string(), z.number()]).optional(),\n\t\t\tskip_consent: z.boolean().optional(),\n\t\t\tenable_end_session: z.boolean().optional(),\n\t\t\tdisabled: z.boolean().optional(),\n\t\t\tdpop_bound_access_tokens: z.boolean().optional(),\n\t\t\tmetadata: z.record(z.string(), z.unknown()).optional()\n\t\t})\n\t}),\n\tmetadata: {\n\t\tSERVER_ONLY: true,\n\t\topenapi: { description: \"Updates OAuth2 formatted client details.\" }\n\t}\n}, async (ctx) => {\n\treturn updateClientEndpoint(ctx, opts, { admin: true });\n});\nconst updateOAuthClient = (opts) => createAuthEndpoint(\"/oauth2/update-client\", {\n\tmethod: \"POST\",\n\tuse: [sessionMiddleware],\n\tbody: z.object({\n\t\tclient_id: z.string(),\n\t\tupdate: z.object({\n\t\t\tredirect_uris: z.array(SafeUrlSchema).min(1).optional(),\n\t\t\tscope: z.string().optional(),\n\t\t\tclient_name: z.string().optional(),\n\t\t\tclient_uri: z.string().optional(),\n\t\t\tlogo_uri: z.string().optional(),\n\t\t\tcontacts: z.array(z.string().min(1)).min(1).optional(),\n\t\t\ttos_uri: z.string().optional(),\n\t\t\tpolicy_uri: z.string().optional(),\n\t\t\tsoftware_id: z.string().optional(),\n\t\t\tsoftware_version: z.string().optional(),\n\t\t\tsoftware_statement: z.string().optional(),\n\t\t\tpost_logout_redirect_uris: z.array(SafeUrlSchema).min(1).optional(),\n\t\t\tbackchannel_logout_uri: SafeUrlSchema.optional(),\n\t\t\tbackchannel_logout_session_required: z.boolean().optional(),\n\t\t\tapplication_type: z.enum([\"web\", \"native\"]).optional(),\n\t\t\tgrant_types: grantTypesSchema.optional(),\n\t\t\tresponse_types: z.array(z.enum([\"code\"])).optional()\n\t\t})\n\t}),\n\tmetadata: { openapi: { description: \"Updates OAuth2 formatted client details.\" } }\n}, async (ctx) => {\n\treturn updateClientEndpoint(ctx, opts);\n});\nconst rotateClientSecret = (opts) => createAuthEndpoint(\"/oauth2/client/rotate-secret\", {\n\tmethod: \"POST\",\n\tuse: [sessionMiddleware],\n\tbody: z.object({ client_id: z.string() }),\n\tmetadata: {\n\t\tnoStore: true,\n\t\topenapi: { description: \"Rotates a confidential client's secret\" }\n\t}\n}, async (ctx) => {\n\treturn rotateClientSecretEndpoint(ctx, opts);\n});\nconst deleteOAuthClient = (opts) => createAuthEndpoint(\"/oauth2/delete-client\", {\n\tmethod: \"POST\",\n\tuse: [sessionMiddleware],\n\tbody: z.object({ client_id: z.string() }),\n\tmetadata: { openapi: { description: \"Deletes an oauth client\" } }\n}, async (ctx) => {\n\treturn deleteClientEndpoint(ctx, opts);\n});\n//#endregion\n//#region src/oauthConsent/endpoints.ts\nasync function getConsent(ctx, opts, id) {\n\treturn await ctx.context.adapter.findOne({\n\t\tmodel: \"oauthConsent\",\n\t\twhere: [{\n\t\t\tfield: \"id\",\n\t\t\tvalue: id\n\t\t}]\n\t});\n}\nasync function getConsentEndpoint(ctx, opts) {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session) throw new APIError(\"UNAUTHORIZED\");\n\tconst { id } = ctx.query;\n\tif (!id) throw new APIError(\"NOT_FOUND\", {\n\t\terror_description: \"missing id parameter\",\n\t\terror: \"not_found\"\n\t});\n\tconst consent = await getConsent(ctx, opts, id);\n\tif (!consent) throw new APIError(\"NOT_FOUND\", {\n\t\terror_description: \"no consent\",\n\t\terror: \"not_found\"\n\t});\n\tif (consent.userId !== session.user.id) throw new APIError(\"UNAUTHORIZED\");\n\treturn consent;\n}\nasync function getConsentsEndpoint(ctx, opts) {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session) throw new APIError(\"UNAUTHORIZED\");\n\treturn await ctx.context.adapter.findMany({\n\t\tmodel: \"oauthConsent\",\n\t\twhere: [{\n\t\t\tfield: \"userId\",\n\t\t\tvalue: session.user.id\n\t\t}]\n\t});\n}\nasync function deleteConsentEndpoint(ctx, opts) {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session) throw new APIError(\"UNAUTHORIZED\");\n\tconst { id } = ctx.body;\n\tif (!id) throw new APIError(\"NOT_FOUND\", {\n\t\terror_description: \"missing id parameter\",\n\t\terror: \"not_found\"\n\t});\n\tconst consent = await getConsent(ctx, opts, id);\n\tif (!consent) throw new APIError(\"NOT_FOUND\", {\n\t\terror_description: \"no consent\",\n\t\terror: \"not_found\"\n\t});\n\tif (consent.userId !== session.user.id) throw new APIError(\"UNAUTHORIZED\");\n\tawait ctx.context.adapter.delete({\n\t\tmodel: \"oauthConsent\",\n\t\twhere: [{\n\t\t\tfield: \"id\",\n\t\t\tvalue: id\n\t\t}]\n\t});\n}\nasync function updateConsentEndpoint(ctx, opts) {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session) throw new APIError(\"UNAUTHORIZED\");\n\tconst { id } = ctx.body;\n\tif (!id) throw new APIError(\"NOT_FOUND\", {\n\t\terror_description: \"missing id parameter\",\n\t\terror: \"not_found\"\n\t});\n\tconst consent = await getConsent(ctx, opts, id);\n\tif (!consent) throw new APIError(\"NOT_FOUND\", {\n\t\terror_description: \"no consent\",\n\t\terror: \"not_found\"\n\t});\n\tif (consent.userId !== session.user.id) throw new APIError(\"UNAUTHORIZED\");\n\tconst client = await getClient(ctx, opts, consent.clientId);\n\tif (!client) throw new APIError(\"NOT_FOUND\", {\n\t\terror_description: \"client not found\",\n\t\terror: \"not_found\"\n\t});\n\tconst allowedScopes = client?.scopes ?? opts.scopes ?? [];\n\tconst updates = ctx.body.update;\n\tconst scopes = updates.scopes;\n\tif (scopes && !scopes.every((val) => allowedScopes?.includes(val))) throw new APIError(\"BAD_REQUEST\", {\n\t\terror_description: `unable to provide scopes to ${client?.referenceId ?? client?.userId}`,\n\t\terror: \"invalid_request\"\n\t});\n\tconst iat = Math.floor(Date.now() / 1e3);\n\treturn await ctx.context.adapter.update({\n\t\tmodel: \"oauthConsent\",\n\t\twhere: [{\n\t\t\tfield: \"id\",\n\t\t\tvalue: id\n\t\t}],\n\t\tupdate: {\n\t\t\t...updates,\n\t\t\tupdatedAt: /* @__PURE__ */ new Date(iat * 1e3)\n\t\t}\n\t});\n}\n//#endregion\n//#region src/oauthConsent/index.ts\nconst getOAuthConsent = (opts) => createAuthEndpoint(\"/oauth2/get-consent\", {\n\tmethod: \"GET\",\n\tquery: z.object({ id: z.string() }),\n\tuse: [sessionMiddleware],\n\tmetadata: { openapi: { description: \"Gets details of a specific OAuth2 consent for a user\" } }\n}, async (ctx) => {\n\treturn getConsentEndpoint(ctx, opts);\n});\nconst getOAuthConsents = (opts) => createAuthEndpoint(\"/oauth2/get-consents\", {\n\tmethod: \"GET\",\n\tuse: [sessionMiddleware],\n\tmetadata: { openapi: { description: \"Gets all available OAuth2 consents for a user\" } }\n}, async (ctx) => {\n\treturn getConsentsEndpoint(ctx, opts);\n});\nconst updateOAuthConsent = (opts) => createAuthEndpoint(\"/oauth2/update-consent\", {\n\tmethod: \"POST\",\n\tuse: [sessionMiddleware],\n\tbody: z.object({\n\t\tid: z.string(),\n\t\tupdate: z.object({ scopes: z.array(z.string()) })\n\t}),\n\tmetadata: { openapi: { description: \"Updates consent granted to a client.\" } }\n}, async (ctx) => {\n\treturn updateConsentEndpoint(ctx, opts);\n});\nconst deleteOAuthConsent = (opts) => createAuthEndpoint(\"/oauth2/delete-consent\", {\n\tmethod: \"POST\",\n\tuse: [sessionMiddleware],\n\tbody: z.object({ id: z.string() }),\n\tmetadata: { openapi: { description: \"Deletes consent granted to a client\" } }\n}, async (ctx) => {\n\treturn deleteConsentEndpoint(ctx, opts);\n});\n//#endregion\n//#region src/oauthResource/endpoints.ts\nconst resourceModel = (opts) => opts.schema?.oauthResource?.modelName ?? \"oauthResource\";\nconst linkModel = (opts) => opts.schema?.oauthClientResource?.modelName ?? \"oauthClientResource\";\nconst clientModel = (opts) => opts.schema?.oauthClient?.modelName ?? \"oauthClient\";\n/**\n* Decode a URL path-segment parameter.\n*\n* better-call's router (better-call@1.3.5) does NOT decode path params —\n* `tryDecode` is wired into cookie parsing only. So a raw HTTP caller hitting\n* `/admin/oauth2/resources/https%3A%2F%2Fapi.example.com` lands here with\n* `ctx.params.identifier === \"https%3A%2F%2Fapi.example.com\"`, which never\n* matches the stored `https://api.example.com` row. Decode every path\n* segment that holds a URI-valued identifier so the admin handlers behave\n* identically to in-process `auth.api.*` calls (which pass already-decoded\n* JS strings).\n*\n* Falls back to the raw string when decode fails so a malformed identifier\n* surfaces as a clean NOT_FOUND from the row lookup rather than a 500.\n*\n* @internal\n*/\nfunction decodePathParam(value) {\n\ttry {\n\t\treturn decodeURIComponent(value);\n\t} catch {\n\t\treturn value;\n\t}\n}\n/**\n* Builds the create-payload from a normalized input. Fills in defaults\n* for the fields seedResources uses so the admin-CRUD and seed paths\n* write identical rows.\n*\n* @internal\n*/\nfunction buildResourceRow(input, now) {\n\treturn {\n\t\tidentifier: input.identifier,\n\t\tname: input.name ?? input.identifier,\n\t\taccessTokenTtl: input.accessTokenTtl ?? null,\n\t\trefreshTokenTtl: input.refreshTokenTtl ?? null,\n\t\tsigningAlgorithm: input.signingAlgorithm ?? null,\n\t\tsigningKeyId: input.signingKeyId ?? null,\n\t\tallowedScopes: input.allowedScopes ?? null,\n\t\tcustomClaims: input.customClaims ?? null,\n\t\tdpopBoundAccessTokensRequired: input.dpopBoundAccessTokensRequired ?? false,\n\t\tdisabled: input.disabled ?? false,\n\t\tpolicyVersion: 1,\n\t\tmetadata: input.metadata ?? null,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t};\n}\nasync function createResourceEndpoint(ctx, opts) {\n\tawait assertResourcePrivileges(ctx, await getSessionFromCtx(ctx), opts, \"create\");\n\tconst input = ctx.body;\n\tif (!input?.identifier) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_request\",\n\t\terror_description: \"identifier is required\"\n\t});\n\tawait assertIdentifierValid(opts, input.identifier);\n\tconst now = /* @__PURE__ */ new Date();\n\tlet created;\n\ttry {\n\t\tcreated = await ctx.context.adapter.create({\n\t\t\tmodel: resourceModel(opts),\n\t\t\tdata: buildResourceRow(input, now)\n\t\t});\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tif (/unique|duplicate|UNIQUE/i.test(message)) throw new APIError(\"BAD_REQUEST\", {\n\t\t\terror: \"invalid_request\",\n\t\t\terror_description: `resource ${input.identifier} already exists`\n\t\t});\n\t\tthrow err;\n\t}\n\tif (!created) throw new APIError(\"BAD_REQUEST\", {\n\t\terror: \"invalid_request\",\n\t\terror_description: `resource ${input.identifier} could not be created`\n\t});\n\tinvalidateResourceCache(created.identifier);\n\treturn ctx.json(created, { status: 201 });\n}\nasync function listResourcesEndpoint(ctx, opts) {\n\tawait assertResourcePrivileges(ctx, await getSessionFromCtx(ctx), opts, \"list\");\n\tconst rows = await ctx.context.adapter.findMany({ model: resourceModel(opts) });\n\treturn ctx.json(rows ?? []);\n}\nasync function getResourceByIdentifierEndpoint(ctx, opts) {\n\tconst identifier = decodePathParam(ctx.params.identifier);\n\tawait assertResourcePrivileges(ctx, await getSessionFromCtx(ctx), opts, \"read\", identifier);\n\tconst row = await ctx.context.adapter.findOne({\n\t\tmodel: resourceModel(opts),\n\t\twhere: [{\n\t\t\tfield: \"identifier\",\n\t\t\tvalue: identifier\n\t\t}]\n\t});\n\tif (!row) throw new APIError(\"NOT_FOUND\", {\n\t\terror: \"not_found\",\n\t\terror_description: `resource ${identifier} not found`\n\t});\n\treturn ctx.json(row);\n}\nasync function updateResourceEndpoint(ctx, opts) {\n\tconst identifier = decodePathParam(ctx.params.identifier);\n\tawait assertResourcePrivileges(ctx, await getSessionFromCtx(ctx), opts, \"update\", identifier);\n\tif (!await ctx.context.adapter.findOne({\n\t\tmodel: resourceModel(opts),\n\t\twhere: [{\n\t\t\tfield: \"identifier\",\n\t\t\tvalue: identifier\n\t\t}]\n\t})) throw new APIError(\"NOT_FOUND\", {\n\t\terror: \"not_found\",\n\t\terror_description: `resource ${identifier} not found`\n\t});\n\tconst update = { updatedAt: /* @__PURE__ */ new Date() };\n\tfor (const key of [\n\t\t\"name\",\n\t\t\"accessTokenTtl\",\n\t\t\"refreshTokenTtl\",\n\t\t\"signingAlgorithm\",\n\t\t\"signingKeyId\",\n\t\t\"allowedScopes\",\n\t\t\"customClaims\",\n\t\t\"dpopBoundAccessTokensRequired\",\n\t\t\"disabled\",\n\t\t\"metadata\"\n\t]) if (Object.prototype.hasOwnProperty.call(ctx.body, key)) update[key] = ctx.body[key];\n\tawait ctx.context.adapter.update({\n\t\tmodel: resourceModel(opts),\n\t\twhere: [{\n\t\t\tfield: \"identifier\",\n\t\t\tvalue: identifier\n\t\t}],\n\t\tupdate\n\t});\n\tinvalidateResourceCache(identifier);\n\tconst refreshed = await ctx.context.adapter.findOne({\n\t\tmodel: resourceModel(opts),\n\t\twhere: [{\n\t\t\tfield: \"identifier\",\n\t\t\tvalue: identifier\n\t\t}]\n\t});\n\tif (!refreshed) throw new APIError(\"NOT_FOUND\", {\n\t\terror: \"not_found\",\n\t\terror_description: `resource ${identifier} not found`\n\t});\n\treturn ctx.json(refreshed);\n}\nasync function deleteResourceEndpoint(ctx, opts) {\n\tconst identifier = decodePathParam(ctx.params.identifier);\n\tawait assertResourcePrivileges(ctx, await getSessionFromCtx(ctx), opts, \"delete\", identifier);\n\tif (!await ctx.context.adapter.findOne({\n\t\tmodel: resourceModel(opts),\n\t\twhere: [{\n\t\t\tfield: \"identifier\",\n\t\t\tvalue: identifier\n\t\t}]\n\t})) throw new APIError(\"NOT_FOUND\", {\n\t\terror: \"not_found\",\n\t\terror_description: `resource ${identifier} not found`\n\t});\n\tawait ctx.context.adapter.delete({\n\t\tmodel: resourceModel(opts),\n\t\twhere: [{\n\t\t\tfield: \"identifier\",\n\t\t\tvalue: identifier\n\t\t}]\n\t});\n\tinvalidateResourceCache(identifier);\n\treturn ctx.json({ deleted: true });\n}\n/**\n* Link a client to a resource.\n*\n* Route: `POST /admin/oauth2/resources/:identifier/clients/:client_id`.\n* Path params carry the identifiers (RESTful linkage) — no body required.\n* Used by admins when {@link OAuthOptions.enforcePerClientResources} is on.\n*/\nasync function linkClientResourceEndpoint(ctx, opts) {\n\tconst session = await getSessionFromCtx(ctx);\n\tconst resourceId = decodePathParam(ctx.params.identifier);\n\tconst clientId = decodePathParam(ctx.params.client_id);\n\tawait assertResourcePrivileges(ctx, session, opts, \"link\", resourceId);\n\tif (!await ctx.context.adapter.findOne({\n\t\tmodel: resourceModel(opts),\n\t\twhere: [{\n\t\t\tfield: \"identifier\",\n\t\t\tvalue: resourceId\n\t\t}]\n\t})) throw new APIError(\"NOT_FOUND\", {\n\t\terror: \"not_found\",\n\t\terror_description: `resource ${resourceId} not found`\n\t});\n\tif (!await ctx.context.adapter.findOne({\n\t\tmodel: clientModel(opts),\n\t\twhere: [{\n\t\t\tfield: \"clientId\",\n\t\t\tvalue: clientId\n\t\t}]\n\t})) throw new APIError(\"NOT_FOUND\", {\n\t\terror: \"not_found\",\n\t\terror_description: `client ${clientId} not found`\n\t});\n\ttry {\n\t\tawait ctx.context.adapter.create({\n\t\t\tmodel: linkModel(opts),\n\t\t\tdata: {\n\t\t\t\tclientId,\n\t\t\t\tresourceId,\n\t\t\t\tcreatedAt: /* @__PURE__ */ new Date()\n\t\t\t}\n\t\t});\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tif (/unique|duplicate|UNIQUE/i.test(message)) return ctx.json({\n\t\t\tlinked: true,\n\t\t\talreadyLinked: true\n\t\t});\n\t\tthrow err;\n\t}\n\treturn ctx.json({ linked: true });\n}\n/**\n* Unlink a client from a resource.\n*\n* Route: `DELETE /admin/oauth2/resources/:identifier/clients/:client_id`.\n* Path params carry the identifiers (RESTful linkage) — no body required.\n*/\nasync function unlinkClientResourceEndpoint(ctx, opts) {\n\tconst session = await getSessionFromCtx(ctx);\n\tconst resourceId = decodePathParam(ctx.params.identifier);\n\tconst clientId = decodePathParam(ctx.params.client_id);\n\tawait assertResourcePrivileges(ctx, session, opts, \"unlink\", resourceId);\n\tawait ctx.context.adapter.deleteMany({\n\t\tmodel: linkModel(opts),\n\t\twhere: [{\n\t\t\tfield: \"clientId\",\n\t\t\tvalue: clientId\n\t\t}, {\n\t\t\tfield: \"resourceId\",\n\t\t\tvalue: resourceId\n\t\t}]\n\t});\n\treturn ctx.json({ unlinked: true });\n}\n//#endregion\n//#region src/oauthResource/index.ts\n/**\n* Shared body schema for create/update — every field is optional except\n* `identifier` on create (validated in the handler). Update accepts a\n* subset; the handler only writes fields that are explicitly present.\n*/\nconst resourceBodySchema = z.object({\n\tidentifier: z.string().min(1).optional(),\n\tname: z.string().optional(),\n\taccessTokenTtl: z.number().int().positive().nullable().optional(),\n\trefreshTokenTtl: z.number().int().positive().nullable().optional(),\n\tsigningAlgorithm: z.enum(JWS_ALGORITHMS).nullable().optional(),\n\tsigningKeyId: z.string().nullable().optional(),\n\tallowedScopes: z.array(z.string()).nullable().optional(),\n\tcustomClaims: z.record(z.string(), z.unknown()).nullable().optional(),\n\tdpopBoundAccessTokensRequired: z.boolean().optional(),\n\tdisabled: z.boolean().optional(),\n\tmetadata: z.record(z.string(), z.unknown()).nullable().optional()\n});\nconst adminCreateOAuthResource = (opts) => createAuthEndpoint(\"/admin/oauth2/resources\", {\n\tmethod: \"POST\",\n\tbody: resourceBodySchema.required({ identifier: true }),\n\tmetadata: { SERVER_ONLY: true }\n}, async (ctx) => createResourceEndpoint(ctx, opts));\nconst adminListOAuthResources = (opts) => createAuthEndpoint(\"/admin/oauth2/resources\", {\n\tmethod: \"GET\",\n\tmetadata: { SERVER_ONLY: true }\n}, async (ctx) => listResourcesEndpoint(ctx, opts));\nconst adminGetOAuthResource = (opts) => createAuthEndpoint(\"/admin/oauth2/resources/:identifier\", {\n\tmethod: \"GET\",\n\tmetadata: { SERVER_ONLY: true }\n}, async (ctx) => getResourceByIdentifierEndpoint(ctx, opts));\nconst adminUpdateOAuthResource = (opts) => createAuthEndpoint(\"/admin/oauth2/resources/:identifier\", {\n\tmethod: \"PATCH\",\n\tbody: resourceBodySchema,\n\tmetadata: { SERVER_ONLY: true }\n}, async (ctx) => updateResourceEndpoint(ctx, opts));\nconst adminDeleteOAuthResource = (opts) => createAuthEndpoint(\"/admin/oauth2/resources/:identifier\", {\n\tmethod: \"DELETE\",\n\tmetadata: { SERVER_ONLY: true }\n}, async (ctx) => deleteResourceEndpoint(ctx, opts));\nconst adminLinkClientResource = (opts) => createAuthEndpoint(\"/admin/oauth2/resources/:identifier/clients/:client_id\", {\n\tmethod: \"POST\",\n\tmetadata: { SERVER_ONLY: true }\n}, async (ctx) => linkClientResourceEndpoint(ctx, opts));\nconst adminUnlinkClientResource = (opts) => createAuthEndpoint(\"/admin/oauth2/resources/:identifier/clients/:client_id\", {\n\tmethod: \"DELETE\",\n\tmetadata: { SERVER_ONLY: true }\n}, async (ctx) => unlinkClientResourceEndpoint(ctx, opts));\n//#endregion\n//#region src/revoke.ts\n/**\n* IMPORTANT NOTES:\n* Revocation follows RFC7009\n* https://datatracker.ietf.org/doc/html/rfc7009\n* - APIError: Continue catches (returnable to client)\n* - Error: Should immediately stop catches (internal error)\n*/\n/**\n* Revokes a JWT access token against the configured JWKs.\n*\n* A JWT access token is self-contained and never stored, so there is nothing to\n* delete. Once the token is confirmed to be a valid JWT for this server, the\n* endpoint reports `unsupported_token_type` (RFC 7009 §2.2.1) instead of a\n* silent success, so callers can tell that no server-side revocation happened.\n* An expired JWT or a JWT with an audience rejected by the OAuth resource model\n* is already inactive and still resolves as a successful no-op. Session-bound\n* tokens (carrying `sid`) are cut off early by the session-liveness check in\n* introspection and userinfo.\n*/\nasync function revokeJwtAccessToken(ctx, opts, token) {\n\tconst jwtPlugin = opts.disableJwtPlugin ? void 0 : getJwtPlugin(ctx.context);\n\tconst jwtPluginOptions = jwtPlugin?.options;\n\ttry {\n\t\tconst verified = await jwtVerify(token, createLocalJWKSet(await getJwks(token, {\n\t\t\tjwksFetch: jwtPluginOptions?.jwks?.remoteUrl ? jwtPluginOptions.jwks.remoteUrl : async () => {\n\t\t\t\treturn (await jwtPlugin?.endpoints.getJwks(ctx))?.response;\n\t\t\t},\n\t\t\tjwksCacheKey: jwtPlugin\n\t\t})), { issuer: jwtPluginOptions?.jwt?.issuer ?? ctx.context.baseURL });\n\t\tconst userInfoAudience = `${ctx.context.baseURL}/oauth2/userinfo`;\n\t\tif (!verified.payload.azp || !await isAudienceClaimAllowed(ctx, opts, verified.payload.aud, [userInfoAudience])) return null;\n\t} catch (error) {\n\t\tif (error instanceof Error) {\n\t\t\tif (error.name === \"TypeError\" || error.name === \"JWSInvalid\") throw new APIError$1(\"BAD_REQUEST\", {\n\t\t\t\terror_description: \"invalid JWT signature\",\n\t\t\t\terror: \"invalid_request\"\n\t\t\t});\n\t\t\telse if (error.name === \"JWTExpired\") return null;\n\t\t\telse if (error.name === \"JWTInvalid\") return null;\n\t\t\tthrow error;\n\t\t}\n\t\tthrow new Error(error);\n\t}\n\tthrow new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"JWT access tokens are self-contained and cannot be revoked server-side\",\n\t\terror: \"unsupported_token_type\"\n\t});\n}\n/**\n* Searches for an opaque access token in the database and validates it\n*/\nasync function revokeOpaqueAccessToken(ctx, opts, token, clientId) {\n\tlet tokenValue = token;\n\tif (opts.prefix?.opaqueAccessToken) if (tokenValue.startsWith(opts.prefix.opaqueAccessToken)) tokenValue = tokenValue.replace(opts.prefix.opaqueAccessToken, \"\");\n\telse throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"opaque access token not found\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst accessToken = await ctx.context.adapter.findOne({\n\t\tmodel: \"oauthAccessToken\",\n\t\twhere: [{\n\t\t\tfield: \"token\",\n\t\t\tvalue: await getStoredToken(opts.storeTokens, tokenValue, \"access_token\")\n\t\t}]\n\t});\n\tif (!accessToken) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"opaque access token not found\",\n\t\terror: \"invalid_request\"\n\t});\n\tif (!accessToken.clientId || accessToken.clientId !== clientId) return null;\n\taccessToken.id ? await ctx.context.adapter.delete({\n\t\tmodel: \"oauthAccessToken\",\n\t\twhere: [{\n\t\t\tfield: \"id\",\n\t\t\tvalue: accessToken.id\n\t\t}]\n\t}) : await ctx.context.adapter.delete({\n\t\tmodel: \"oauthAccessToken\",\n\t\twhere: [{\n\t\t\tfield: \"token\",\n\t\t\tvalue: accessToken.token\n\t\t}]\n\t});\n}\n/**\n* Validates a refresh token in the session store.\n*/\nasync function revokeRefreshToken(ctx, opts, token, clientId) {\n\tconst refreshToken = await ctx.context.adapter.findOne({\n\t\tmodel: \"oauthRefreshToken\",\n\t\twhere: [{\n\t\t\tfield: \"token\",\n\t\t\tvalue: await getStoredToken(opts.storeTokens, token, \"refresh_token\")\n\t\t}]\n\t});\n\tif (!refreshToken) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"token not found\",\n\t\terror: \"invalid_request\"\n\t});\n\tif (refreshToken.revoked) {\n\t\tawait invalidateRefreshFamily(ctx, clientId, refreshToken.userId);\n\t\tthrow new APIError$1(\"BAD_REQUEST\", {\n\t\t\terror_description: \"refresh token revoked\",\n\t\t\terror: \"invalid_request\"\n\t\t});\n\t}\n\tif (!refreshToken.clientId || refreshToken.clientId !== clientId) return null;\n\tconst iat = Math.floor(Date.now() / 1e3);\n\tif (!await ctx.context.adapter.incrementOne({\n\t\tmodel: \"oauthRefreshToken\",\n\t\twhere: [{\n\t\t\tfield: \"id\",\n\t\t\tvalue: refreshToken.id\n\t\t}, {\n\t\t\tfield: \"revoked\",\n\t\t\toperator: \"eq\",\n\t\t\tvalue: null\n\t\t}],\n\t\tincrement: {},\n\t\tset: { revoked: /* @__PURE__ */ new Date(iat * 1e3) }\n\t})) {\n\t\tawait invalidateRefreshFamily(ctx, clientId, refreshToken.userId);\n\t\tthrow new APIError$1(\"BAD_REQUEST\", {\n\t\t\terror_description: \"refresh token revoked\",\n\t\t\terror: \"invalid_request\"\n\t\t});\n\t}\n\tawait ctx.context.adapter.deleteMany({\n\t\tmodel: \"oauthAccessToken\",\n\t\twhere: [{\n\t\t\tfield: \"refreshId\",\n\t\t\tvalue: refreshToken.id\n\t\t}]\n\t});\n}\n/**\n* We don't know the access token format so we try to validate it\n* as a JWT first, then as an opaque token.\n*/\nasync function revokeAccessToken(ctx, opts, clientId, token) {\n\ttry {\n\t\treturn await revokeJwtAccessToken(ctx, opts, token);\n\t} catch (err) {\n\t\tif (err instanceof APIError$1) {\n\t\t\tif (err.body?.error === \"unsupported_token_type\") throw err;\n\t\t} else if (err instanceof Error) throw err;\n\t\telse throw new Error(err);\n\t}\n\ttry {\n\t\treturn await revokeOpaqueAccessToken(ctx, opts, token, clientId);\n\t} catch (err) {\n\t\tif (err instanceof APIError$1) {} else if (err instanceof Error) throw err;\n\t\telse throw new Error(\"Unknown error validating access token\");\n\t}\n\tthrow new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"Invalid access token\",\n\t\terror: \"invalid_request\"\n\t});\n}\nasync function revokeEndpoint(ctx, opts) {\n\tlet { token, token_type_hint } = ctx.body;\n\tif (token_type_hint !== \"access_token\" && token_type_hint !== \"refresh_token\") token_type_hint = void 0;\n\tconst { clientId: client_id, clientSecret: client_secret, preVerified, authMethod } = destructureCredentials(await extractClientCredentials(ctx, opts, `${ctx.context.baseURL}/oauth2/revoke`));\n\tif (!client_id) throw new APIError$1(\"UNAUTHORIZED\", {\n\t\terror_description: \"missing required credentials\",\n\t\terror: \"invalid_client\"\n\t});\n\tif (typeof token === \"string\") token = stripAccessTokenAuthorizationScheme(token);\n\tif (!token?.length) throw new APIError$1(\"BAD_REQUEST\", {\n\t\terror_description: \"missing a required token for introspection\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst client = await validateClientCredentials(ctx, opts, client_id, client_secret, void 0, preVerified, void 0, authMethod);\n\ttry {\n\t\tif (token_type_hint === void 0 || token_type_hint === \"access_token\") try {\n\t\t\treturn await revokeAccessToken(ctx, opts, client.clientId, token);\n\t\t} catch (error) {\n\t\t\tif (error instanceof APIError$1) {\n\t\t\t\tif (token_type_hint === \"access_token\" || error.body?.error === \"unsupported_token_type\") throw error;\n\t\t\t} else if (error instanceof Error) throw error;\n\t\t\telse throw new Error(error);\n\t\t}\n\t\tif (token_type_hint === void 0 || token_type_hint === \"refresh_token\") try {\n\t\t\treturn await revokeRefreshToken(ctx, opts, (await decodeRefreshToken(opts, token)).token, client.clientId);\n\t\t} catch (error) {\n\t\t\tif (error instanceof APIError$1) {\n\t\t\t\tif (token_type_hint === \"refresh_token\") throw error;\n\t\t\t} else if (error instanceof Error) throw error;\n\t\t\telse throw new Error(error);\n\t\t}\n\t\tthrow new APIError$1(\"BAD_REQUEST\", {\n\t\t\terror_description: \"token not found\",\n\t\t\terror: \"invalid_request\"\n\t\t});\n\t} catch (error) {\n\t\tif (error instanceof APIError$1) {\n\t\t\tif (error.body?.error === \"unsupported_token_type\") throw error;\n\t\t\tif (error.name === \"BAD_REQUEST\") return null;\n\t\t\tthrow error;\n\t\t} else if (error instanceof Error) {\n\t\t\tlogger.error(\"Introspection error:\", error.message, error.stack);\n\t\t\tthrow new APIError$1(\"INTERNAL_SERVER_ERROR\");\n\t\t} else {\n\t\t\tlogger.error(\"Introspection error:\", error);\n\t\t\tthrow new APIError$1(\"INTERNAL_SERVER_ERROR\");\n\t\t}\n\t}\n}\n//#endregion\n//#region src/schema.ts\nconst schema = {\n\toauthClient: {\n\t\tmodelName: \"oauthClient\",\n\t\tfields: {\n\t\t\tclientId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\tunique: true,\n\t\t\t\trequired: true\n\t\t\t},\n\t\t\tclientSecret: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tclientDiscoveryId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tdisabled: {\n\t\t\t\ttype: \"boolean\",\n\t\t\t\tdefaultValue: false,\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tskipConsent: {\n\t\t\t\ttype: \"boolean\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tenableEndSession: {\n\t\t\t\ttype: \"boolean\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tsubjectType: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tscopes: {\n\t\t\t\ttype: \"string[]\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tclientCredentialsScopes: {\n\t\t\t\ttype: \"string[]\",\n\t\t\t\trequired: false,\n\t\t\t\tdefaultValue: []\n\t\t\t},\n\t\t\tuserId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false,\n\t\t\t\treferences: {\n\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\tfield: \"id\"\n\t\t\t\t},\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\tcreatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tupdatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tname: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\turi: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\ticon: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tcontacts: {\n\t\t\t\ttype: \"string[]\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\ttos: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tpolicy: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tsoftwareId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tsoftwareVersion: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tsoftwareStatement: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tredirectUris: {\n\t\t\t\ttype: \"string[]\",\n\t\t\t\trequired: true\n\t\t\t},\n\t\t\tpostLogoutRedirectUris: {\n\t\t\t\ttype: \"string[]\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tbackchannelLogoutUri: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tbackchannelLogoutSessionRequired: {\n\t\t\t\ttype: \"boolean\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\ttokenEndpointAuthMethod: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tapplicationType: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tjwks: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tjwksUri: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tgrantTypes: {\n\t\t\t\ttype: \"string[]\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tresponseTypes: {\n\t\t\t\ttype: \"string[]\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\trequirePKCE: {\n\t\t\t\ttype: \"boolean\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tdpopBoundAccessTokens: {\n\t\t\t\ttype: \"boolean\",\n\t\t\t\trequired: false,\n\t\t\t\tdefaultValue: false\n\t\t\t},\n\t\t\treferenceId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tmetadata: {\n\t\t\t\ttype: \"json\",\n\t\t\t\trequired: false\n\t\t\t}\n\t\t}\n\t},\n\t/**\n\t* A protected resource the AS issues access tokens for.\n\t*\n\t* Promotes protected resources into a first-class persisted entity with\n\t* per-resource token policy. A null value\n\t* on any policy column means \"inherit the plugin-level default at token\n\t* issuance time\" — admins can later override without re-seeding.\n\t*\n\t* @see RFC 8707 (Resource Indicators) — `identifier` is the `resource` parameter value\n\t* @see RFC 9068 §2.2 — `customClaims` cannot override reserved JWT claims (enforced server-side)\n\t*/\n\toauthResource: {\n\t\tmodelName: \"oauthResource\",\n\t\tfields: {\n\t\t\tidentifier: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\tunique: true\n\t\t\t},\n\t\t\tname: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true\n\t\t\t},\n\t\t\taccessTokenTtl: {\n\t\t\t\ttype: \"number\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\trefreshTokenTtl: {\n\t\t\t\ttype: \"number\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tsigningAlgorithm: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tsigningKeyId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tallowedScopes: {\n\t\t\t\ttype: \"string[]\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tcustomClaims: {\n\t\t\t\ttype: \"json\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tdpopBoundAccessTokensRequired: {\n\t\t\t\ttype: \"boolean\",\n\t\t\t\trequired: false,\n\t\t\t\tdefaultValue: false\n\t\t\t},\n\t\t\tdisabled: {\n\t\t\t\ttype: \"boolean\",\n\t\t\t\trequired: false,\n\t\t\t\tdefaultValue: false\n\t\t\t},\n\t\t\tcreatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tupdatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tpolicyVersion: {\n\t\t\t\ttype: \"number\",\n\t\t\t\trequired: false,\n\t\t\t\tdefaultValue: 1\n\t\t\t},\n\t\t\tmetadata: {\n\t\t\t\ttype: \"json\",\n\t\t\t\trequired: false\n\t\t\t}\n\t\t}\n\t},\n\t/**\n\t* Join table — which clients are allowed to request which resources.\n\t*\n\t* Authoritative only when `enforcePerClientResources: true` on plugin options.\n\t* When the flag is off, clients implicitly have access to all enabled resources\n\t* (preserves pre-entity behavior).\n\t*\n\t* Composite uniqueness on `(clientId, resourceId)` is load-bearing — the\n\t* `enforcePerClientResources` linkage check assumes one row per pair.\n\t*\n\t* Concurrent inserts of the same pair surface as a UNIQUE-constraint\n\t* error which the endpoint catches and converts to a 200 \"alreadyLinked\"\n\t* response (idempotency).\n\t*/\n\toauthClientResource: {\n\t\tmodelName: \"oauthClientResource\",\n\t\tfields: {\n\t\t\tclientId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\treferences: {\n\t\t\t\t\tmodel: \"oauthClient\",\n\t\t\t\t\tfield: \"clientId\",\n\t\t\t\t\tonDelete: \"cascade\"\n\t\t\t\t},\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\tresourceId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\treferences: {\n\t\t\t\t\tmodel: \"oauthResource\",\n\t\t\t\t\tfield: \"identifier\",\n\t\t\t\t\tonDelete: \"cascade\"\n\t\t\t\t},\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\tmetadata: {\n\t\t\t\ttype: \"json\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tcreatedAt: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: false\n\t\t\t}\n\t\t},\n\t\tindexes: [{\n\t\t\tfields: [\"clientId\", \"resourceId\"],\n\t\t\tunique: true\n\t\t}]\n\t},\n\t/**\n\t* An opaque refresh token created with \"offline_access\"\n\t*\n\t* Refresh tokens are linked to a session.\n\t*/\n\toauthRefreshToken: { fields: {\n\t\ttoken: {\n\t\t\ttype: \"string\",\n\t\t\trequired: true,\n\t\t\tunique: true\n\t\t},\n\t\tclientId: {\n\t\t\ttype: \"string\",\n\t\t\trequired: true,\n\t\t\treferences: {\n\t\t\t\tmodel: \"oauthClient\",\n\t\t\t\tfield: \"clientId\"\n\t\t\t},\n\t\t\tindex: true\n\t\t},\n\t\tsessionId: {\n\t\t\ttype: \"string\",\n\t\t\trequired: false,\n\t\t\treferences: {\n\t\t\t\tmodel: \"session\",\n\t\t\t\tfield: \"id\",\n\t\t\t\tonDelete: \"set null\"\n\t\t\t},\n\t\t\tindex: true\n\t\t},\n\t\tuserId: {\n\t\t\ttype: \"string\",\n\t\t\trequired: true,\n\t\t\treferences: {\n\t\t\t\tmodel: \"user\",\n\t\t\t\tfield: \"id\"\n\t\t\t},\n\t\t\tindex: true\n\t\t},\n\t\treferenceId: {\n\t\t\ttype: \"string\",\n\t\t\trequired: false\n\t\t},\n\t\tauthorizationCodeId: {\n\t\t\ttype: \"string\",\n\t\t\trequired: false,\n\t\t\tindex: true\n\t\t},\n\t\tresources: {\n\t\t\ttype: \"string[]\",\n\t\t\trequired: false\n\t\t},\n\t\trequestedUserInfoClaims: {\n\t\t\ttype: \"string[]\",\n\t\t\trequired: false\n\t\t},\n\t\texpiresAt: { type: \"date\" },\n\t\tcreatedAt: { type: \"date\" },\n\t\trevoked: {\n\t\t\ttype: \"date\",\n\t\t\trequired: false\n\t\t},\n\t\trotatedAt: {\n\t\t\ttype: \"date\",\n\t\t\trequired: false\n\t\t},\n\t\trotationReplayResponse: {\n\t\t\ttype: \"string\",\n\t\t\trequired: false\n\t\t},\n\t\trotationReplayExpiresAt: {\n\t\t\ttype: \"date\",\n\t\t\trequired: false\n\t\t},\n\t\tauthTime: {\n\t\t\ttype: \"date\",\n\t\t\trequired: false\n\t\t},\n\t\tconfirmation: {\n\t\t\ttype: \"json\",\n\t\t\trequired: false\n\t\t},\n\t\tscopes: {\n\t\t\ttype: \"string[]\",\n\t\t\trequired: true\n\t\t}\n\t} },\n\t/**\n\t* An opaque access token sent when there is no resource audience claim\n\t* to assigned to the JWT.\n\t*\n\t* Access tokens are linked to a session, better-auth\n\t* authors SHALL always check for valid session!\n\t*\n\t* AccessTokens SHALL only be created at refresh,\n\t* destroyed at revoke, and read at introspection.\n\t* NEVER update an access token! Typically a refresh and\n\t* revoke (if not expired) may want to occur at the same time.\n\t*/\n\toauthAccessToken: {\n\t\tmodelName: \"oauthAccessToken\",\n\t\tfields: {\n\t\t\ttoken: {\n\t\t\t\ttype: \"string\",\n\t\t\t\tunique: true\n\t\t\t},\n\t\t\tclientId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\treferences: {\n\t\t\t\t\tmodel: \"oauthClient\",\n\t\t\t\t\tfield: \"clientId\"\n\t\t\t\t},\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\tsessionId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false,\n\t\t\t\treferences: {\n\t\t\t\t\tmodel: \"session\",\n\t\t\t\t\tfield: \"id\",\n\t\t\t\t\tonDelete: \"set null\"\n\t\t\t\t},\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\tuserId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false,\n\t\t\t\treferences: {\n\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\tfield: \"id\"\n\t\t\t\t},\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\treferenceId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tauthorizationCodeId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false,\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\tresources: {\n\t\t\t\ttype: \"string[]\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\trequestedUserInfoClaims: {\n\t\t\t\ttype: \"string[]\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\trefreshId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false,\n\t\t\t\treferences: {\n\t\t\t\t\tmodel: \"oauthRefreshToken\",\n\t\t\t\t\tfield: \"id\"\n\t\t\t\t},\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\texpiresAt: { type: \"date\" },\n\t\t\tcreatedAt: { type: \"date\" },\n\t\t\trevoked: {\n\t\t\t\ttype: \"date\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tconfirmation: {\n\t\t\t\ttype: \"json\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tscopes: {\n\t\t\t\ttype: \"string[]\",\n\t\t\t\trequired: true\n\t\t\t}\n\t\t}\n\t},\n\toauthConsent: {\n\t\tmodelName: \"oauthConsent\",\n\t\tfields: {\n\t\t\tclientId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: true,\n\t\t\t\treferences: {\n\t\t\t\t\tmodel: \"oauthClient\",\n\t\t\t\t\tfield: \"clientId\"\n\t\t\t\t},\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\tuserId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false,\n\t\t\t\treferences: {\n\t\t\t\t\tmodel: \"user\",\n\t\t\t\t\tfield: \"id\"\n\t\t\t\t},\n\t\t\t\tindex: true\n\t\t\t},\n\t\t\treferenceId: {\n\t\t\t\ttype: \"string\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tresources: {\n\t\t\t\ttype: \"string[]\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\trequestedUserInfoClaims: {\n\t\t\t\ttype: \"string[]\",\n\t\t\t\trequired: false\n\t\t\t},\n\t\t\tscopes: {\n\t\t\t\ttype: \"string[]\",\n\t\t\t\trequired: true\n\t\t\t},\n\t\t\tcreatedAt: { type: \"date\" },\n\t\t\tupdatedAt: { type: \"date\" }\n\t\t}\n\t},\n\t/**\n\t* Single-use record for `private_key_jwt` client assertion `jti` values. The\n\t* row id is a digest of the per-client assertion identifier, so a replayed or\n\t* concurrent assertion collides on the primary key and the insert fails\n\t* atomically on every adapter (SQL primary key, MongoDB `_id`), including\n\t* across multiple server processes.\n\t*\n\t* A row keeps blocking its id until deleted; `expiresAt` marks when removal\n\t* is safe, since the assertion it guards has expired and is rejected earlier.\n\t* TODO: no scheduled job prunes expired rows yet; like the verification\n\t* table, they accumulate until a deployment-level sweep removes them.\n\t*/\n\toauthClientAssertion: {\n\t\tmodelName: \"oauthClientAssertion\",\n\t\tfields: { expiresAt: {\n\t\t\ttype: \"date\",\n\t\t\trequired: true\n\t\t} }\n\t}\n};\n//#endregion\n//#region src/oauth.ts\n/**\n* Default scopes advertised and accepted when a configuration sets none. Shared\n* with the MCP preset so the resource metadata it serves matches what the\n* authorization-server metadata advertises.\n*/\nconst DEFAULT_OAUTH_SCOPES = [\n\t\"openid\",\n\t\"profile\",\n\t\"email\",\n\t\"offline_access\"\n];\nconst rpInitiatedLogoutRequestSchema = z.object({\n\tid_token_hint: z.string().optional(),\n\tclient_id: z.string().optional(),\n\tpost_logout_redirect_uri: SafeUrlSchema.optional(),\n\tstate: z.string().optional()\n});\nconst oAuthState = defineRequestState(() => null);\nconst getOAuthProviderState = oAuthState.get;\nconst backchannelLogoutPlansByContext = /* @__PURE__ */ new WeakMap();\nconst signedQueryIssuedAtMsKey = \"signedQueryIssuedAtMs\";\nfunction getServerContextSignedQueryIssuedAt(value) {\n\tconst issuedAtMs = typeof value === \"number\" ? value : typeof value === \"string\" ? Number(value) : void 0;\n\tif (!issuedAtMs || !Number.isFinite(issuedAtMs) || issuedAtMs <= 0) return;\n\treturn new Date(issuedAtMs);\n}\n/**\n* oAuth 2.1 provider plugin for Better Auth.\n*\n* @see https://better-auth.com/docs/plugins/oauth-provider\n* @param options - The options for the oAuth Provider plugin.\n* @returns A Better Auth plugin.\n*/\nconst oauthProvider = (options) => {\n\tlet clientRegistrationAllowedScopes = options.clientRegistrationAllowedScopes;\n\tif (options.clientRegistrationDefaultScopes) {\n\t\tconst _allowedScopes = clientRegistrationAllowedScopes ? new Set([...clientRegistrationAllowedScopes, ...options.clientRegistrationDefaultScopes]) : new Set([...options.clientRegistrationDefaultScopes]);\n\t\tclientRegistrationAllowedScopes = Array.from(_allowedScopes);\n\t}\n\tconst scopes = new Set((options.scopes ?? DEFAULT_OAUTH_SCOPES).filter((val) => val.length));\n\tif (clientRegistrationAllowedScopes) {\n\t\tfor (const sc of clientRegistrationAllowedScopes) if (!scopes.has(sc)) throw new BetterAuthError(`clientRegistrationAllowedScope ${sc} not found in scopes`);\n\t}\n\tfor (const sc of options.advertisedMetadata?.scopes_supported ?? []) if (!scopes?.has(sc)) throw new BetterAuthError(`advertisedMetadata.scopes_supported ${sc} not found in scopes`);\n\tconst configuredResourceIdentifiers = new Set((options.resources ?? []).map((resource) => typeof resource === \"string\" ? resource : resource.identifier));\n\tfor (const [optionName, identifiers] of [[\"clientRegistrationDefaultResources\", options.clientRegistrationDefaultResources], [\"clientRegistrationAllowedResources\", options.clientRegistrationAllowedResources]]) for (const identifier of identifiers ?? []) if (!configuredResourceIdentifiers.has(identifier)) throw new BetterAuthError(`${optionName} resource ${identifier} not found in resources`);\n\tconst claims = new Set([\n\t\t\"sub\",\n\t\t\"iss\",\n\t\t\"aud\",\n\t\t\"exp\",\n\t\t\"iat\",\n\t\t\"sid\",\n\t\t\"scope\",\n\t\t\"azp\",\n\t\t...STANDARD_CLAIM_NAMES.filter((name) => scopes.has(STANDARD_CLAIMS[name].scope))\n\t]);\n\tconst opts = {\n\t\tcodeExpiresIn: 600,\n\t\taccessTokenExpiresIn: 3600,\n\t\tm2mAccessTokenExpiresIn: 3600,\n\t\trefreshTokenExpiresIn: 2592e3,\n\t\trefreshTokenReuseInterval: 0,\n\t\tallowUnauthenticatedClientRegistration: false,\n\t\tallowDynamicClientRegistration: false,\n\t\tdisableJwtPlugin: false,\n\t\tstoreClientSecret: options.disableJwtPlugin ? \"encrypted\" : \"hashed\",\n\t\tstoreTokens: \"hashed\",\n\t\tgrantTypes: [\n\t\t\t\"authorization_code\",\n\t\t\t\"client_credentials\",\n\t\t\t\"refresh_token\"\n\t\t],\n\t\t...options,\n\t\tscopes: Array.from(scopes),\n\t\tclaims: Array.from(claims),\n\t\tclientRegistrationAllowedScopes\n\t};\n\tvalidateOAuthProviderExtensions(opts.extensions);\n\tif (opts.pairwiseSecret && opts.pairwiseSecret.length < 32) throw new BetterAuthError(\"pairwiseSecret must be at least 32 characters long for adequate HMAC-SHA256 security\");\n\tif (opts.grantTypes && opts.grantTypes.includes(\"refresh_token\") && !opts.grantTypes.includes(\"authorization_code\")) throw new BetterAuthError(\"refresh_token grant requires authorization_code grant\");\n\tif (opts.disableJwtPlugin && (opts.storeClientSecret === \"hashed\" || typeof opts.storeClientSecret === \"object\" && \"hash\" in opts.storeClientSecret)) throw new BetterAuthError(\"unable to store hashed secrets because id tokens will be signed with secret\");\n\tif (!opts.disableJwtPlugin && (opts.storeClientSecret === \"encrypted\" || typeof opts.storeClientSecret === \"object\" && (\"encrypt\" in opts.storeClientSecret || \"decrypt\" in opts.storeClientSecret))) throw new BetterAuthError(\"encryption method not recommended, please use 'hashed' or the 'hash' function\");\n\tconst handleIssuerMetadataRequest = async (request, ctx) => {\n\t\tconst requestPathname = new URL(request.url).pathname;\n\t\tconst requestPath = ctx.options.advanced?.skipTrailingSlashes ? requestPathname.replace(/\\/+$/, \"\") || \"/\" : requestPathname;\n\t\tconst issuer = opts.disableJwtPlugin ? ctx.baseURL : getJwtPlugin(ctx)?.options?.jwt?.issuer ?? ctx.baseURL;\n\t\tlet issuerPath = \"/\";\n\t\ttry {\n\t\t\tissuerPath = new URL(issuer).pathname.replace(/\\/$/, \"\") || \"\";\n\t\t} catch {\n\t\t\tissuerPath = new URL(ctx.baseURL).pathname.replace(/\\/$/, \"\") || \"\";\n\t\t}\n\t\tconst endpointCtx = { context: ctx };\n\t\tconst authServerMetadataPaths = new Set([`/.well-known/oauth-authorization-server${issuerPath}`, `${issuerPath}/.well-known/oauth-authorization-server`]);\n\t\tconst openIdConfigPath = `${issuerPath}/.well-known/openid-configuration`;\n\t\tconst isAuthServerMetadataRequest = authServerMetadataPaths.has(requestPath);\n\t\tconst isOpenIdConfigRequest = opts.scopes?.includes(\"openid\") && requestPath === openIdConfigPath;\n\t\tconst createMetadataResponse = (metadata) => {\n\t\t\tconst response = metadataResponse(metadata);\n\t\t\tif (request.method === \"HEAD\") return new Response(null, {\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers\n\t\t\t});\n\t\t\treturn response;\n\t\t};\n\t\tif (isAuthServerMetadataRequest || isOpenIdConfigRequest) {\n\t\t\tif (request.method !== \"GET\" && request.method !== \"HEAD\") return { response: new Response(null, {\n\t\t\t\tstatus: 405,\n\t\t\t\theaders: { Allow: \"GET, HEAD\" }\n\t\t\t}) };\n\t\t}\n\t\tif (isAuthServerMetadataRequest) {\n\t\t\tif (opts.scopes?.includes(\"openid\")) return { response: createMetadataResponse(oidcServerMetadata(endpointCtx, opts)) };\n\t\t\treturn { response: createMetadataResponse(oauthAuthorizationServerMetadata(endpointCtx, opts)) };\n\t\t}\n\t\tif (isOpenIdConfigRequest) return { response: createMetadataResponse(oidcServerMetadata(endpointCtx, opts)) };\n\t};\n\tconst oauth2AuthorizeEndpoint = createOAuthEndpoint(\"/oauth2/authorize\", {\n\t\tmethod: [\"GET\", \"POST\"],\n\t\tbody: z.object({}).passthrough(),\n\t\tredirectOnError: authorizeRedirectOnError(opts),\n\t\tmetadata: {\n\t\t\tallowedMediaTypes: [\"application/x-www-form-urlencoded\"],\n\t\t\topenapi: {\n\t\t\t\tdescription: \"Authorize an OAuth 2.1 request from query parameters or an application/x-www-form-urlencoded POST body\",\n\t\t\t\tparameters: [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"response_type\",\n\t\t\t\t\t\tin: \"query\",\n\t\t\t\t\t\trequired: false,\n\t\t\t\t\t\tschema: { type: \"string\" },\n\t\t\t\t\t\tdescription: \"OAuth 2.1 response type (e.g., 'code')\"\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"client_id\",\n\t\t\t\t\t\tin: \"query\",\n\t\t\t\t\t\trequired: true,\n\t\t\t\t\t\tschema: { type: \"string\" },\n\t\t\t\t\t\tdescription: \"OAuth 2.1 client ID\"\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"redirect_uri\",\n\t\t\t\t\t\tin: \"query\",\n\t\t\t\t\t\trequired: false,\n\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\tformat: \"uri\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdescription: \"OAuth 2.1 redirect URI\"\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"scope\",\n\t\t\t\t\t\tin: \"query\",\n\t\t\t\t\t\trequired: false,\n\t\t\t\t\t\tschema: { type: \"string\" },\n\t\t\t\t\t\tdescription: \"OAuth 2.1 scopes (space-separated)\"\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"state\",\n\t\t\t\t\t\tin: \"query\",\n\t\t\t\t\t\trequired: false,\n\t\t\t\t\t\tschema: { type: \"string\" },\n\t\t\t\t\t\tdescription: \"OAuth 2.1 state parameter\"\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"request_uri\",\n\t\t\t\t\t\tin: \"query\",\n\t\t\t\t\t\trequired: false,\n\t\t\t\t\t\tschema: { type: \"string\" },\n\t\t\t\t\t\tdescription: \"Pushed Authorization Request URI referencing stored parameters\"\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"code_challenge\",\n\t\t\t\t\t\tin: \"query\",\n\t\t\t\t\t\trequired: false,\n\t\t\t\t\t\tschema: { type: \"string\" },\n\t\t\t\t\t\tdescription: \"PKCE code challenge\"\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"code_challenge_method\",\n\t\t\t\t\t\tin: \"query\",\n\t\t\t\t\t\trequired: false,\n\t\t\t\t\t\tschema: { type: \"string\" },\n\t\t\t\t\t\tdescription: \"PKCE code challenge method\"\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"nonce\",\n\t\t\t\t\t\tin: \"query\",\n\t\t\t\t\t\trequired: false,\n\t\t\t\t\t\tschema: { type: \"string\" },\n\t\t\t\t\t\tdescription: \"OpenID Connect nonce\"\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"max_age\",\n\t\t\t\t\t\tin: \"query\",\n\t\t\t\t\t\trequired: false,\n\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\ttype: \"integer\",\n\t\t\t\t\t\t\tminimum: 0\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdescription: \"Maximum authentication age in seconds; forces re-authentication when exceeded\"\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"resource\",\n\t\t\t\t\t\tin: \"query\",\n\t\t\t\t\t\trequired: false,\n\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\titems: { type: \"string\" }\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdescription: \"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.\"\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"prompt\",\n\t\t\t\t\t\tin: \"query\",\n\t\t\t\t\t\trequired: false,\n\t\t\t\t\t\tschema: { type: \"string\" },\n\t\t\t\t\t\tdescription: \"OAuth2 prompt parameter\"\n\t\t\t\t\t}\n\t\t\t\t],\n\t\t\t\tresponses: {\n\t\t\t\t\t\"302\": {\n\t\t\t\t\t\tdescription: \"Redirect to client with code or error\",\n\t\t\t\t\t\theaders: { Location: {\n\t\t\t\t\t\t\tdescription: \"Redirect URI with code or error\",\n\t\t\t\t\t\t\tschema: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"uri\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} }\n\t\t\t\t\t},\n\t\t\t\t\t\"400\": {\n\t\t\t\t\t\tdescription: \"Invalid request\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\terror: { type: \"string\" },\n\t\t\t\t\t\t\t\terror_description: { type: \"string\" },\n\t\t\t\t\t\t\t\tstate: { type: \"string\" }\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\trequired: [\"error\"]\n\t\t\t\t\t\t} } }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}, async (ctx) => {\n\t\treturn authorizeEndpoint(ctx, opts, ctx.authorizeSettings ?? { isAuthorize: true });\n\t});\n\tconst runOAuth2Authorize = (ctx, settings) => dispatchAuthEndpoint(oauth2AuthorizeEndpoint, {\n\t\t...ctx,\n\t\tasResponse: false,\n\t\treturnHeaders: false,\n\t\treturnStatus: false,\n\t\tauthorizeSettings: settings ?? {}\n\t});\n\treturn {\n\t\tid: \"oauth-provider\",\n\t\tversion: PACKAGE_VERSION,\n\t\toptions: opts,\n\t\tonRequest: handleIssuerMetadataRequest,\n\t\tinit: async (ctx) => {\n\t\t\tif (ctx.options.secondaryStorage && ctx.options.session?.storeSessionInDatabase !== true) throw new BetterAuthError(\"OAuth Provider requires `session.storeSessionInDatabase: true` when using secondaryStorage\");\n\t\t\tawait seedResourcesOnce(ctx, opts).catch((error) => logStartupSeedFailure(ctx, error));\n\t\t\tlogEnforcePerClientResourcesResolution(opts);\n\t\t\tif (!opts.disableJwtPlugin) {\n\t\t\t\tconst jwtPluginOptions = getJwtPlugin(ctx)?.options;\n\t\t\t\tconst issuer = jwtPluginOptions?.jwt?.issuer ?? ctx.baseURL;\n\t\t\t\tconst isDynamicBaseURLInit = jwtPluginOptions?.jwt?.issuer == null && typeof ctx.options.baseURL === \"object\" && ctx.options.baseURL !== null && \"allowedHosts\" in ctx.options.baseURL;\n\t\t\t\ttry {\n\t\t\t\t\tnew URL(issuer);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!isDynamicBaseURLInit || issuer !== \"\") throw error;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { options: { databaseHooks: { session: { delete: {\n\t\t\t\tasync before(session, hookCtx) {\n\t\t\t\t\tif (!hookCtx) return;\n\t\t\t\t\tconst plan = await prepareBackchannelLogoutPlan(hookCtx, opts, {\n\t\t\t\t\t\tsessionId: session.id,\n\t\t\t\t\t\tuserId: session.userId\n\t\t\t\t\t});\n\t\t\t\t\tif (!plan) return;\n\t\t\t\t\tconst logoutPlanBySessionId = backchannelLogoutPlansByContext.get(hookCtx) ?? /* @__PURE__ */ new Map();\n\t\t\t\t\tlogoutPlanBySessionId.set(session.id, plan);\n\t\t\t\t\tbackchannelLogoutPlansByContext.set(hookCtx, logoutPlanBySessionId);\n\t\t\t\t},\n\t\t\t\tasync after(session, hookCtx) {\n\t\t\t\t\tif (!hookCtx) return;\n\t\t\t\t\tconst logoutPlanBySessionId = backchannelLogoutPlansByContext.get(hookCtx);\n\t\t\t\t\tif (!logoutPlanBySessionId) return;\n\t\t\t\t\tconst plan = logoutPlanBySessionId.get(session.id);\n\t\t\t\t\tlogoutPlanBySessionId.delete(session.id);\n\t\t\t\t\tif (logoutPlanBySessionId.size === 0) backchannelLogoutPlansByContext.delete(hookCtx);\n\t\t\t\t\tif (!plan) return;\n\t\t\t\t\tconst logoutTask = applyBackchannelLogoutPlan(hookCtx, plan).catch((error) => {\n\t\t\t\t\t\thookCtx.context.logger.error(\"Back-channel logout failed after session deletion\", error);\n\t\t\t\t\t});\n\t\t\t\t\tawait hookCtx.context.runInBackgroundOrAwait(logoutTask);\n\t\t\t\t}\n\t\t\t} } } } };\n\t\t},\n\t\thooks: {\n\t\t\tbefore: [{\n\t\t\t\tmatcher(ctx) {\n\t\t\t\t\treturn ctx.body?.oauth_query;\n\t\t\t\t},\n\t\t\t\thandler: createAuthMiddleware(async (ctx) => {\n\t\t\t\t\tconst query = ctx.body.oauth_query;\n\t\t\t\t\tif (!await verifyOAuthQueryParams(query, ctx.context.secret)) throw new APIError(\"BAD_REQUEST\", { error: \"invalid_signature\" });\n\t\t\t\t\tconst signedQueryIssuedAt = getSignedQueryIssuedAt(query);\n\t\t\t\t\tconst queryParams = new URLSearchParams(query);\n\t\t\t\t\tconst postLoginClearedForSession = queryParams.get(\"ba_pl\") ?? void 0;\n\t\t\t\t\tqueryParams.delete(\"sig\");\n\t\t\t\t\tqueryParams.delete(\"exp\");\n\t\t\t\t\tqueryParams.delete(signedQueryIssuedAtParam);\n\t\t\t\t\tqueryParams.delete(postLoginClearedParam);\n\t\t\t\t\tawait oAuthState.set({\n\t\t\t\t\t\tquery: queryParams.toString(),\n\t\t\t\t\t\tsignedQueryIssuedAt: signedQueryIssuedAt ?? void 0,\n\t\t\t\t\t\tpostLoginClearedForSession\n\t\t\t\t\t});\n\t\t\t\t\tif (ctx.path === \"/sign-in/social\") await addOAuthServerContext({\n\t\t\t\t\t\tquery: queryParams.toString(),\n\t\t\t\t\t\t...signedQueryIssuedAt ? { [signedQueryIssuedAtMsKey]: signedQueryIssuedAt.getTime() } : {}\n\t\t\t\t\t});\n\t\t\t\t})\n\t\t\t}],\n\t\t\tafter: [{\n\t\t\t\tmatcher(ctx) {\n\t\t\t\t\treturn parseSetCookieHeader(ctx.context.responseHeaders?.get(\"set-cookie\") || \"\").has(ctx.context.authCookies.sessionToken.name);\n\t\t\t\t},\n\t\t\t\thandler: createAuthMiddleware(async (ctx) => {\n\t\t\t\t\tconst sessionToken = parseSetCookieHeader(ctx.context.responseHeaders?.get(\"set-cookie\") || \"\").get(ctx.context.authCookies.sessionToken.name)?.value.split(\".\")[0];\n\t\t\t\t\tif (!sessionToken) return;\n\t\t\t\t\tconst oauthRequest = await oAuthState.get();\n\t\t\t\t\tconst serverContext = (await getOAuthState())?.serverContext;\n\t\t\t\t\tconst _query = oauthRequest?.query ?? serverContext?.query;\n\t\t\t\t\tif (!_query) return;\n\t\t\t\t\tconst query = new URLSearchParams(_query);\n\t\t\t\t\tconst session = await ctx.context.internalAdapter.findSession(sessionToken);\n\t\t\t\t\tif (!session) return;\n\t\t\t\t\tctx.context.session = session;\n\t\t\t\t\tconst secFetchMode = ctx.request?.headers?.get(\"sec-fetch-mode\")?.toLowerCase();\n\t\t\t\t\tconst acceptHeader = ctx.request?.headers?.get(\"accept\")?.toLowerCase() ?? \"\";\n\t\t\t\t\tif (!(secFetchMode === \"navigate\" || !secFetchMode && (acceptHeader.includes(\"text/html\") || acceptHeader.includes(\"application/xhtml+xml\")))) ctx.headers?.set(\"accept\", \"application/json\");\n\t\t\t\t\tconst signedQueryIssuedAt = oauthRequest?.signedQueryIssuedAt ?? getServerContextSignedQueryIssuedAt(serverContext?.[signedQueryIssuedAtMsKey]);\n\t\t\t\t\tlet authorizationQuery = removePromptFromQuery(query, \"login\");\n\t\t\t\t\tif (isSessionFreshForSignedQuery(session.session.createdAt, signedQueryIssuedAt)) authorizationQuery = removeMaxAgeFromQuery(authorizationQuery);\n\t\t\t\t\tctx.query = searchParamsToQuery(authorizationQuery);\n\t\t\t\t\treturn await runOAuth2Authorize(ctx);\n\t\t\t\t})\n\t\t\t}]\n\t\t},\n\t\tendpoints: {\n\t\t\t/**\n\t\t\t* A server-only endpoint that helps provide the\n\t\t\t* oAuth Server configuration at the well-known endpoint.\n\t\t\t*\n\t\t\t* Provided at /.well-known/oauth-authorization-server/[issuer-path]\n\t\t\t* (root if no issuer-path).\n\t\t\t*/\n\t\t\tgetOAuthServerConfig: createAuthEndpoint(\"/.well-known/oauth-authorization-server\", {\n\t\t\t\tmethod: \"GET\",\n\t\t\t\tmetadata: { SERVER_ONLY: true }\n\t\t\t}, async (ctx) => {\n\t\t\t\tif (opts.scopes && opts.scopes.includes(\"openid\")) return oidcServerMetadata(ctx, opts);\n\t\t\t\telse return oauthAuthorizationServerMetadata(ctx, opts);\n\t\t\t}),\n\t\t\t/**\n\t\t\t* A server-only endpoint that helps provide the\n\t\t\t* OpenId configuration at the well-known endpoint.\n\t\t\t*\n\t\t\t* Provided at [issuer-path]/.well-known/openid-configuration\n\t\t\t* (root if no issuer-path).\n\t\t\t*/\n\t\t\tgetOpenIdConfig: createAuthEndpoint(\"/.well-known/openid-configuration\", {\n\t\t\t\tmethod: \"GET\",\n\t\t\t\tmetadata: { SERVER_ONLY: true }\n\t\t\t}, async (ctx) => {\n\t\t\t\tif (opts.scopes && !opts.scopes.includes(\"openid\")) throw new APIError(\"NOT_FOUND\");\n\t\t\t\treturn oidcServerMetadata(ctx, opts);\n\t\t\t}),\n\t\t\toauth2Authorize: oauth2AuthorizeEndpoint,\n\t\t\toauth2Consent: createAuthEndpoint(\"/oauth2/consent\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: z.object({\n\t\t\t\t\taccept: z.boolean().meta({ description: \"Accept or deny user consent for a set of scopes\" }),\n\t\t\t\t\tscope: z.string().optional().meta({ description: \"List of accept of accepted space-separated scopes. If none is provided, then all originally requested scopes are accepted.\" }),\n\t\t\t\t\tclaims: claimsRequestParameterSchema.optional().meta({ description: \"Accepted OIDC claims request object. If none is provided, then all originally requested claims are accepted.\" }),\n\t\t\t\t\toauth_query: z.string().optional().meta({ description: \"The redirected page's query parameters\" })\n\t\t\t\t}),\n\t\t\t\tuse: [sessionMiddleware],\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tdescription: \"Handle OAuth2 consent\",\n\t\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\t\tdescription: \"Consent processed successfully\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: { redirect_uri: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"uri\",\n\t\t\t\t\t\t\t\tdescription: \"The URI to redirect to, either with an authorization code or an error\"\n\t\t\t\t\t\t\t} },\n\t\t\t\t\t\t\trequired: [\"redirect_uri\"]\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\treturn consentEndpoint(ctx, opts, runOAuth2Authorize);\n\t\t\t}),\n\t\t\toauth2Continue: createAuthEndpoint(\"/oauth2/continue\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: z.object({\n\t\t\t\t\tselected: z.boolean().optional().meta({ description: \"Confirms an account has been selected and authorization can proceed.\" }),\n\t\t\t\t\tcreated: z.boolean().optional().meta({ description: \"Confirms an account was registered\" }),\n\t\t\t\t\tpostLogin: z.boolean().optional().meta({ description: \"Confirms organization and/or team selection.\" }),\n\t\t\t\t\toauth_query: z.string().optional().meta({ description: \"The redirected page's query parameters\" })\n\t\t\t\t}),\n\t\t\t\tuse: [sessionMiddleware],\n\t\t\t\tmetadata: { openapi: {\n\t\t\t\t\tdescription: \"Continues OAuth2 authorization flow\",\n\t\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\t\tdescription: \"Consent processed successfully\",\n\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tproperties: { redirect_uri: {\n\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\tformat: \"uri\",\n\t\t\t\t\t\t\t\tdescription: \"The URI to redirect to, either with an authorization code or an error\"\n\t\t\t\t\t\t\t} },\n\t\t\t\t\t\t\trequired: [\"redirect_uri\"]\n\t\t\t\t\t\t} } }\n\t\t\t\t\t} }\n\t\t\t\t} }\n\t\t\t}, async (ctx) => {\n\t\t\t\treturn continueEndpoint(ctx, runOAuth2Authorize);\n\t\t\t}),\n\t\t\toauth2Token: createOAuthEndpoint(\"/oauth2/token\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tcloneRequest: true,\n\t\t\t\tbody: z.object({\n\t\t\t\t\tgrant_type: z.string().trim().min(1),\n\t\t\t\t\tclient_id: z.string().optional(),\n\t\t\t\t\tclient_secret: z.string().optional(),\n\t\t\t\t\tclient_assertion: z.string().optional(),\n\t\t\t\t\tclient_assertion_type: z.string().optional(),\n\t\t\t\t\tcode: z.string().optional(),\n\t\t\t\t\tcode_verifier: z.string().optional(),\n\t\t\t\t\tredirect_uri: SafeUrlSchema.optional(),\n\t\t\t\t\trefresh_token: z.string().optional(),\n\t\t\t\t\tresource: z.union([ResourceUriSchema, z.array(ResourceUriSchema).min(1)]).optional(),\n\t\t\t\t\tscope: z.string().optional()\n\t\t\t\t}).passthrough(),\n\t\t\t\terrorCodesByField: {\n\t\t\t\t\tgrant_type: {\n\t\t\t\t\t\tmissing: \"invalid_request\",\n\t\t\t\t\t\tinvalid: \"unsupported_grant_type\"\n\t\t\t\t\t},\n\t\t\t\t\tresource: { invalid: \"invalid_target\" }\n\t\t\t\t},\n\t\t\t\tmetadata: {\n\t\t\t\t\tnoStore: true,\n\t\t\t\t\tallowedMediaTypes: [\"application/x-www-form-urlencoded\"],\n\t\t\t\t\topenapi: {\n\t\t\t\t\t\tdescription: \"Obtain an OAuth2.1 access token\",\n\t\t\t\t\t\tparameters: [{\n\t\t\t\t\t\t\tname: \"DPoP\",\n\t\t\t\t\t\t\tin: \"header\",\n\t\t\t\t\t\t\trequired: false,\n\t\t\t\t\t\t\tschema: { type: \"string\" },\n\t\t\t\t\t\t\tdescription: \"RFC 9449 DPoP proof JWT for issuing DPoP-bound tokens\"\n\t\t\t\t\t\t}],\n\t\t\t\t\t\trequestBody: {\n\t\t\t\t\t\t\trequired: true,\n\t\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\tgrant_type: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"OAuth2 grant type\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tclient_id: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"OAuth2 client ID\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tclient_secret: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"OAuth2 client secret\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tcode: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Authorization code (for authorization_code grant)\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tcode_verifier: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"PKCE code verifier (for authorization_code grant)\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tredirect_uri: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tformat: \"uri\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Redirect URI (for authorization_code grant)\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trefresh_token: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Refresh token (for refresh_token grant)\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tresource: {\n\t\t\t\t\t\t\t\t\t\toneOf: [{\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Single resource (URL)\"\n\t\t\t\t\t\t\t\t\t\t}, {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Multiple resources (URLs)\"\n\t\t\t\t\t\t\t\t\t\t}],\n\t\t\t\t\t\t\t\t\t\tdescription: \"Requested protected resource(s) for the access token\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tscope: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Requested scopes (for client_credentials grant)\"\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\trequired: [\"grant_type\"]\n\t\t\t\t\t\t\t} } }\n\t\t\t\t\t\t},\n\t\t\t\t\t\tresponses: {\n\t\t\t\t\t\t\t\"200\": {\n\t\t\t\t\t\t\t\tdescription: \"Access token response\",\n\t\t\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\taccess_token: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"The access token issued by the authorization server\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\ttoken_type: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"The type of the token issued\",\n\t\t\t\t\t\t\t\t\t\t\tenum: [\"Bearer\", \"DPoP\"]\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\texpires_in: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"number\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Lifetime in seconds of the access token\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\trefresh_token: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Refresh token, if issued\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tscope: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Scopes granted by the access token\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tid_token: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"ID Token (if OpenID Connect)\"\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trequired: [\n\t\t\t\t\t\t\t\t\t\t\"access_token\",\n\t\t\t\t\t\t\t\t\t\t\"token_type\",\n\t\t\t\t\t\t\t\t\t\t\"expires_in\"\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t} } }\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\"400\": {\n\t\t\t\t\t\t\t\tdescription: \"Invalid request or error response\",\n\t\t\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\terror: { type: \"string\" },\n\t\t\t\t\t\t\t\t\t\terror_description: { type: \"string\" },\n\t\t\t\t\t\t\t\t\t\terror_uri: { type: \"string\" }\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trequired: [\"error\"]\n\t\t\t\t\t\t\t\t} } }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, async (ctx) => {\n\t\t\t\tif (ctx.request) {\n\t\t\t\t\tconst repeated = await extractRepeatedResourceFromForm(ctx.request);\n\t\t\t\t\tif (repeated && repeated.length > 1) ctx.body.resource = repeated;\n\t\t\t\t}\n\t\t\t\treturn tokenEndpoint(ctx, opts);\n\t\t\t}),\n\t\t\toauth2Introspect: createOAuthEndpoint(\"/oauth2/introspect\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tcloneRequest: true,\n\t\t\t\tbody: z.object({\n\t\t\t\t\tclient_id: z.string().optional(),\n\t\t\t\t\tclient_secret: z.string().optional(),\n\t\t\t\t\tclient_assertion: z.string().optional(),\n\t\t\t\t\tclient_assertion_type: z.string().optional(),\n\t\t\t\t\ttoken: z.string(),\n\t\t\t\t\ttoken_type_hint: z.string().optional()\n\t\t\t\t}),\n\t\t\t\tmetadata: {\n\t\t\t\t\tnoStore: true,\n\t\t\t\t\tallowedMediaTypes: [\"application/x-www-form-urlencoded\"],\n\t\t\t\t\topenapi: {\n\t\t\t\t\t\tdescription: \"Introspect an OAuth2 access or refresh token\",\n\t\t\t\t\t\trequestBody: {\n\t\t\t\t\t\t\trequired: true,\n\t\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\tclient_id: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"OAuth2 client ID\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tclient_secret: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"OAuth2 client secret\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\ttoken: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"The token to introspect (access or refresh token)\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\ttoken_type_hint: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Hint about the token type. Recognized values: `access_token`, `refresh_token`.\"\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\trequired: [\"token\"]\n\t\t\t\t\t\t\t} } }\n\t\t\t\t\t\t},\n\t\t\t\t\t\tresponses: {\n\t\t\t\t\t\t\t\"200\": {\n\t\t\t\t\t\t\t\tdescription: \"Token introspection response\",\n\t\t\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\tactive: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Whether the token is active\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tscope: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Scopes associated with the token\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tclient_id: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Client ID associated with the token\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tusername: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Username associated with the token\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\ttoken_type: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Type of the token\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\texp: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"number\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Expiration time of the token (seconds since epoch)\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tiat: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"number\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Issued at time (seconds since epoch)\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tnbf: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"number\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Not before time (seconds since epoch)\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tsub: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Subject of the token\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\taud: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Audience of the token\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tiss: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Issuer of the token\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tjti: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"JWT ID\"\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trequired: [\"active\"]\n\t\t\t\t\t\t\t\t} } }\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\"400\": {\n\t\t\t\t\t\t\t\tdescription: \"Invalid request or error response\",\n\t\t\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\terror: { type: \"string\" },\n\t\t\t\t\t\t\t\t\t\terror_description: { type: \"string\" },\n\t\t\t\t\t\t\t\t\t\terror_uri: { type: \"string\" }\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trequired: [\"error\"]\n\t\t\t\t\t\t\t\t} } }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, async (ctx) => {\n\t\t\t\treturn introspectEndpoint(ctx, opts);\n\t\t\t}),\n\t\t\toauth2Revoke: createOAuthEndpoint(\"/oauth2/revoke\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tcloneRequest: true,\n\t\t\t\tbody: z.object({\n\t\t\t\t\tclient_id: z.string().optional(),\n\t\t\t\t\tclient_secret: z.string().optional(),\n\t\t\t\t\tclient_assertion: z.string().optional(),\n\t\t\t\t\tclient_assertion_type: z.string().optional(),\n\t\t\t\t\ttoken: z.string(),\n\t\t\t\t\ttoken_type_hint: z.string().optional()\n\t\t\t\t}),\n\t\t\t\tmetadata: {\n\t\t\t\t\tallowedMediaTypes: [\"application/x-www-form-urlencoded\"],\n\t\t\t\t\topenapi: {\n\t\t\t\t\t\tdescription: \"Revoke an OAuth2 access or refresh token\",\n\t\t\t\t\t\trequestBody: {\n\t\t\t\t\t\t\trequired: true,\n\t\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\tclient_id: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"OAuth2 client ID\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tclient_secret: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"OAuth2 client secret\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\ttoken: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"The token to revoke (access or refresh token)\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\ttoken_type_hint: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Hint about the token type. Recognized values: `access_token`, `refresh_token`.\"\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\trequired: [\"token\"]\n\t\t\t\t\t\t\t} } }\n\t\t\t\t\t\t},\n\t\t\t\t\t\tresponses: {\n\t\t\t\t\t\t\t\"200\": {\n\t\t\t\t\t\t\t\tdescription: \"Token revoked successfully. The response body is empty.\",\n\t\t\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tdescription: \"Empty object on success\"\n\t\t\t\t\t\t\t\t} } }\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\"400\": {\n\t\t\t\t\t\t\t\tdescription: \"Invalid request or error response\",\n\t\t\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\terror: { type: \"string\" },\n\t\t\t\t\t\t\t\t\t\terror_description: { type: \"string\" },\n\t\t\t\t\t\t\t\t\t\terror_uri: { type: \"string\" }\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trequired: [\"error\"]\n\t\t\t\t\t\t\t\t} } }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, async (ctx) => {\n\t\t\t\treturn revokeEndpoint(ctx, opts);\n\t\t\t}),\n\t\t\toauth2UserInfo: createAuthEndpoint(\"/oauth2/userinfo\", {\n\t\t\t\tmethod: [\"GET\", \"POST\"],\n\t\t\t\tbody: z.object({ access_token: z.string().optional() }).passthrough().optional(),\n\t\t\t\tmetadata: {\n\t\t\t\t\tnoStore: true,\n\t\t\t\t\tallowedMediaTypes: [\"application/x-www-form-urlencoded\"],\n\t\t\t\t\topenapi: {\n\t\t\t\t\t\tdescription: \"Get OpenID Connect user information (UserInfo endpoint)\",\n\t\t\t\t\t\tsecurity: [{ bearerAuth: [] }, { OAuth2: [\n\t\t\t\t\t\t\t\"openid\",\n\t\t\t\t\t\t\t\"profile\",\n\t\t\t\t\t\t\t\"email\"\n\t\t\t\t\t\t] }],\n\t\t\t\t\t\tparameters: [{\n\t\t\t\t\t\t\tname: \"Authorization\",\n\t\t\t\t\t\t\tin: \"header\",\n\t\t\t\t\t\t\trequired: false,\n\t\t\t\t\t\t\tschema: { type: \"string\" },\n\t\t\t\t\t\t\tdescription: \"Bearer or DPoP access token\"\n\t\t\t\t\t\t}, {\n\t\t\t\t\t\t\tname: \"DPoP\",\n\t\t\t\t\t\t\tin: \"header\",\n\t\t\t\t\t\t\trequired: false,\n\t\t\t\t\t\t\tschema: { type: \"string\" },\n\t\t\t\t\t\t\tdescription: \"RFC 9449 DPoP proof JWT when using a DPoP-bound access token\"\n\t\t\t\t\t\t}],\n\t\t\t\t\t\tresponses: {\n\t\t\t\t\t\t\t\"200\": {\n\t\t\t\t\t\t\t\tdescription: \"User information retrieved successfully\",\n\t\t\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\tsub: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Subject identifier (user ID)\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\temail: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"email\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's email address, included if 'email' scope is granted\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tname: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's full name, included if 'profile' scope is granted\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tpicture: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"uri\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's profile picture URL, included if 'profile' scope is granted\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tgiven_name: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's given name, included if 'profile' scope is granted\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tfamily_name: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"User's family name, included if 'profile' scope is granted\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\temail_verified: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\t\t\t\t\tnullable: true,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Whether the email is verified, included if 'email' scope is granted\"\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trequired: [\"sub\"]\n\t\t\t\t\t\t\t\t} } }\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\"401\": {\n\t\t\t\t\t\t\t\tdescription: \"Unauthorized - invalid or missing access token\",\n\t\t\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\terror: { type: \"string\" },\n\t\t\t\t\t\t\t\t\t\terror_description: { type: \"string\" }\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trequired: [\"error\"]\n\t\t\t\t\t\t\t\t} } }\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\"403\": {\n\t\t\t\t\t\t\t\tdescription: \"Forbidden - insufficient scope\",\n\t\t\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\terror: { type: \"string\" },\n\t\t\t\t\t\t\t\t\t\terror_description: { type: \"string\" }\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\trequired: [\"error\"]\n\t\t\t\t\t\t\t\t} } }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, async (ctx) => {\n\t\t\t\treturn userInfoEndpoint(ctx, opts);\n\t\t\t}),\n\t\t\toauth2EndSession: createOAuthEndpoint(\"/oauth2/end-session\", {\n\t\t\t\tmethod: [\"GET\", \"POST\"],\n\t\t\t\tbody: rpInitiatedLogoutRequestSchema.optional(),\n\t\t\t\tquery: rpInitiatedLogoutRequestSchema.optional(),\n\t\t\t\tmetadata: {\n\t\t\t\t\tnoStore: true,\n\t\t\t\t\tallowedMediaTypes: [\"application/x-www-form-urlencoded\", \"application/json\"],\n\t\t\t\t\t$Infer: {\n\t\t\t\t\t\tbody: {},\n\t\t\t\t\t\tquery: {}\n\t\t\t\t\t},\n\t\t\t\t\topenapi: {\n\t\t\t\t\t\tdescription: \"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.\",\n\t\t\t\t\t\tresponses: { \"200\": {\n\t\t\t\t\t\t\tdescription: \"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.\",\n\t\t\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\t\t\"application/json\": { schema: {\n\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\t\tredirect_uri: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"uri\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"URI to redirect to after logout (if post_logout_redirect_uri was provided)\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tmessage: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Success message\"\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} },\n\t\t\t\t\t\t\t\t\"text/html\": { schema: { type: \"string\" } }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, async (ctx) => {\n\t\t\t\treturn rpInitiatedLogoutEndpoint(ctx, opts);\n\t\t\t}),\n\t\t\toauth2EndSessionConfirmation: createOAuthEndpoint(\"/oauth2/end-session/confirm\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: z.object({ action: z.literal(\"confirm\") }),\n\t\t\t\tmetadata: {\n\t\t\t\t\tnoStore: true,\n\t\t\t\t\tallowedMediaTypes: [\"application/x-www-form-urlencoded\"],\n\t\t\t\t\tscope: \"http\"\n\t\t\t\t}\n\t\t\t}, async (ctx) => {\n\t\t\t\treturn rpInitiatedLogoutConfirmationEndpoint(ctx, opts);\n\t\t\t}),\n\t\t\tregisterOAuthClient: createOAuthEndpoint(\"/oauth2/register\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: clientRegistrationRequestSchema,\n\t\t\t\terrorCodesByField: {\n\t\t\t\t\tredirect_uris: \"invalid_redirect_uri\",\n\t\t\t\t\tpost_logout_redirect_uris: \"invalid_redirect_uri\",\n\t\t\t\t\tsoftware_statement: \"invalid_software_statement\",\n\t\t\t\t\tresources: \"invalid_target\"\n\t\t\t\t},\n\t\t\t\tdefaultError: \"invalid_client_metadata\",\n\t\t\t\tmetadata: {\n\t\t\t\t\tnoStore: true,\n\t\t\t\t\topenapi: {\n\t\t\t\t\t\tdescription: \"Register an OAuth2 application\",\n\t\t\t\t\t\tresponses: { \"201\": {\n\t\t\t\t\t\t\tdescription: \"OAuth2 application registered successfully\",\n\t\t\t\t\t\t\tcontent: { \"application/json\": { schema: {\n\t\t\t\t\t\t\t\t/** @returns {OauthClient} */\n\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\t\t\tclient_id: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Unique identifier for the client\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tclient_secret: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Secret key for the client\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tclient_secret_expires_at: {\n\t\t\t\t\t\t\t\t\t\ttype: \"number\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Time the client secret will expire. If 0, the client secret will never expire.\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tscope: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Space-separated scopes allowed by the client\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tuser_id: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"ID of the user who registered the client, null if registered anonymously\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tclient_id_issued_at: {\n\t\t\t\t\t\t\t\t\t\ttype: \"number\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Creation timestamp of this client\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tclient_name: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Name of the OAuth2 application\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tclient_uri: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Name of the OAuth2 application\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tlogo_uri: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Icon URL for the application\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tcontacts: {\n\t\t\t\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\t\t\t\tdescription: \"List representing ways to contact people responsible for this client, typically email addresses\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\ttos_uri: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Client's terms of service uri\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tpolicy_uri: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Client's policy uri\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tsoftware_id: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Unique identifier assigned by the developer to help in the dynamic registration process\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tsoftware_version: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Version identifier for the software_id\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tsoftware_statement: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"JWT containing metadata values about the client software as claims\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tredirect_uris: {\n\t\t\t\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"uri\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tdescription: \"List of allowed redirect uris\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tpost_logout_redirect_uris: {\n\t\t\t\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"uri\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tdescription: \"List of allowed logout redirect uris\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tbackchannel_logout_uri: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tformat: \"uri\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"RP URL to receive signed Logout Tokens when the end-user's OP session terminates\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tbackchannel_logout_session_required: {\n\t\t\t\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Whether the RP requires a `sid` claim in every Logout Token\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\ttoken_endpoint_auth_method: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Requested authentication method for the token endpoint\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tgrant_types: {\n\t\t\t\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\t\t\t\titems: { type: \"string\" },\n\t\t\t\t\t\t\t\t\t\tdescription: \"Grant types the client may use at the token endpoint\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tresponse_types: {\n\t\t\t\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tenum: [\"code\"]\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tdescription: \"Response types the client may use at the authorization endpoint\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tapplication_type: {\n\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"OIDC application type used to classify redirect URI policy\",\n\t\t\t\t\t\t\t\t\t\tenum: [\"web\", \"native\"]\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tresources: {\n\t\t\t\t\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"string\",\n\t\t\t\t\t\t\t\t\t\t\tformat: \"uri\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tdescription: \"Final resource identifiers linked to the registered client\"\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tdisabled: {\n\t\t\t\t\t\t\t\t\t\ttype: \"boolean\",\n\t\t\t\t\t\t\t\t\t\tdescription: \"Whether the client is disabled\"\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\trequired: [\"client_id\"]\n\t\t\t\t\t\t\t} } }\n\t\t\t\t\t\t} }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, async (ctx) => {\n\t\t\t\treturn registerEndpoint(ctx, opts);\n\t\t\t}),\n\t\t\tadminCreateOAuthClient: adminCreateOAuthClient(opts),\n\t\t\tcreateOAuthClient: createOAuthClient(opts),\n\t\t\tgetOAuthClient: getOAuthClient(opts),\n\t\t\tgetOAuthClientPublic: getOAuthClientPublic(opts),\n\t\t\tgetOAuthClientPublicPrelogin: getOAuthClientPublicPrelogin(opts),\n\t\t\tgetOAuthClients: getOAuthClients(opts),\n\t\t\tadminUpdateOAuthClient: adminUpdateOAuthClient(opts),\n\t\t\tupdateOAuthClient: updateOAuthClient(opts),\n\t\t\trotateClientSecret: rotateClientSecret(opts),\n\t\t\tdeleteOAuthClient: deleteOAuthClient(opts),\n\t\t\tgetOAuthConsent: getOAuthConsent(opts),\n\t\t\tgetOAuthConsents: getOAuthConsents(opts),\n\t\t\tupdateOAuthConsent: updateOAuthConsent(opts),\n\t\t\tdeleteOAuthConsent: deleteOAuthConsent(opts),\n\t\t\tadminCreateOAuthResource: adminCreateOAuthResource(opts),\n\t\t\tadminListOAuthResources: adminListOAuthResources(opts),\n\t\t\tadminGetOAuthResource: adminGetOAuthResource(opts),\n\t\t\tadminUpdateOAuthResource: adminUpdateOAuthResource(opts),\n\t\t\tadminDeleteOAuthResource: adminDeleteOAuthResource(opts),\n\t\t\tadminLinkClientResource: adminLinkClientResource(opts),\n\t\t\tadminUnlinkClientResource: adminUnlinkClientResource(opts)\n\t\t},\n\t\tschema: mergeSchema(structuredClone(schema), opts?.schema),\n\t\trateLimit: [\n\t\t\t...opts.rateLimit?.token !== false ? [{\n\t\t\t\tpathMatcher: (path) => path === \"/oauth2/token\",\n\t\t\t\twindow: opts.rateLimit?.token?.window ?? 60,\n\t\t\t\tmax: opts.rateLimit?.token?.max ?? 20\n\t\t\t}] : [],\n\t\t\t...opts.rateLimit?.authorize !== false ? [{\n\t\t\t\tpathMatcher: (path) => path === \"/oauth2/authorize\",\n\t\t\t\twindow: opts.rateLimit?.authorize?.window ?? 60,\n\t\t\t\tmax: opts.rateLimit?.authorize?.max ?? 30\n\t\t\t}] : [],\n\t\t\t...opts.rateLimit?.introspect !== false ? [{\n\t\t\t\tpathMatcher: (path) => path === \"/oauth2/introspect\",\n\t\t\t\twindow: opts.rateLimit?.introspect?.window ?? 60,\n\t\t\t\tmax: opts.rateLimit?.introspect?.max ?? 100\n\t\t\t}] : [],\n\t\t\t...opts.rateLimit?.revoke !== false ? [{\n\t\t\t\tpathMatcher: (path) => path === \"/oauth2/revoke\",\n\t\t\t\twindow: opts.rateLimit?.revoke?.window ?? 60,\n\t\t\t\tmax: opts.rateLimit?.revoke?.max ?? 30\n\t\t\t}] : [],\n\t\t\t...opts.rateLimit?.register !== false ? [{\n\t\t\t\tpathMatcher: (path) => path === \"/oauth2/register\",\n\t\t\t\twindow: opts.rateLimit?.register?.window ?? 60,\n\t\t\t\tmax: opts.rateLimit?.register?.max ?? 5\n\t\t\t}] : [],\n\t\t\t...opts.rateLimit?.userinfo !== false ? [{\n\t\t\t\tpathMatcher: (path) => path === \"/oauth2/userinfo\",\n\t\t\t\twindow: opts.rateLimit?.userinfo?.window ?? 60,\n\t\t\t\tmax: opts.rateLimit?.userinfo?.max ?? 60\n\t\t\t}] : []\n\t\t]\n\t};\n};\n//#endregion\n//#region src/authorize.ts\n/**\n* Whether a past authentication is still fresh enough for an OIDC `max_age`\n* request: true when no more than `maxAge` seconds have elapsed since the user\n* last authenticated. The caller supplies `now`, keeping this pure.\n*/\nfunction isWithinMaxAge(sessionCreatedAt, maxAgeSeconds, now) {\n\tif (maxAgeSeconds === 0) return false;\n\treturn now.getTime() - sessionCreatedAt.getTime() <= maxAgeSeconds * 1e3;\n}\nfunction removeMaxAgeFromAuthorizationQuery(query) {\n\tconst { max_age: _maxAge, ...queryWithoutMaxAge } = query;\n\treturn queryWithoutMaxAge;\n}\n/**\n* Formats an error url. Per OIDC Core 1.0 §5 / RFC 6749 §4.2.2.1, errors on\n* implicit and hybrid flows are delivered in the URL fragment, not the query.\n* Callers on the code flow (default) omit `mode` and get query delivery.\n*/\nfunction formatErrorURL(url, error, description, state, iss, mode = \"query\") {\n\tconst searchParams = new URLSearchParams({\n\t\terror,\n\t\terror_description: description\n\t});\n\tstate && searchParams.append(\"state\", state);\n\tiss && searchParams.append(\"iss\", iss);\n\tif (mode === \"fragment\") return `${url}#${searchParams.toString()}`;\n\treturn appendQueryParams(url, searchParams);\n}\n/**\n* Selects the response mode for an error redirect to the RP. OIDC Core 1.0 §5\n* defines defaults based on response_type: `code` → query, types containing\n* `token` / `id_token` → fragment. An explicit `response_mode` overrides.\n*\n* When `response_type` is duplicated (array) or absent, we can't trust the\n* caller's intent, so we default to query — the safer channel for\n* unrecognized shapes.\n*/\nfunction deriveResponseMode(raw) {\n\tconst responseMode = typeof raw.response_mode === \"string\" ? raw.response_mode : void 0;\n\tif (responseMode === \"fragment\") return \"fragment\";\n\tif (responseMode === \"query\") return \"query\";\n\tconst responseType = typeof raw.response_type === \"string\" ? raw.response_type : void 0;\n\tif (responseType && /\\b(token|id_token)\\b/.test(responseType)) return \"fragment\";\n\treturn \"query\";\n}\nconst authorizationQueryErrorCodesByField = {\n\tresponse_type: { invalid: \"unsupported_response_type\" },\n\tresource: { invalid: \"invalid_target\" }\n};\nfunction isRecord(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction getStringParameter(value) {\n\treturn typeof value === \"string\" ? value : void 0;\n}\nfunction getAuthorizationRequestParameters(ctx, settings) {\n\tconst source = ctx.method === \"POST\" && settings?.isAuthorize === true ? ctx.body : ctx.query;\n\treturn { ...isRecord(source) ? source : {} };\n}\nconst handleRedirect = (ctx, uri) => {\n\tconst fromFetch = isBrowserFetchRequest(ctx.request?.headers);\n\tconst acceptJson = ctx.headers?.get(\"accept\")?.includes(\"application/json\");\n\tif (fromFetch || acceptJson) return {\n\t\tredirect: true,\n\t\turl: uri.toString()\n\t};\n\telse throw ctx.redirect(uri);\n};\nfunction redirectWithPromptNoneError(ctx, opts, query, error, description) {\n\treturn handleRedirect(ctx, formatErrorURL(query.redirect_uri, error, description, query.state, getIssuer(ctx, opts)));\n}\n/**\n* Validates that the issuer URL\n* - MUST use HTTPS scheme (HTTP allowed for localhost in dev)\n* - MUST NOT contain query components\n* - MUST NOT contain fragment components\n*\n* @returns The validated issuer URL, or a sanitized version if invalid\n*/\nfunction validateIssuerUrl(issuer) {\n\ttry {\n\t\tconst url = new URL(issuer);\n\t\tif (url.protocol !== \"https:\" && !isLoopbackHost(url.host)) url.protocol = \"https:\";\n\t\turl.search = \"\";\n\t\turl.hash = \"\";\n\t\treturn url.toString().replace(/\\/$/, \"\");\n\t} catch {\n\t\treturn issuer;\n\t}\n}\n/**\n* Gets the issuer identifier\n*/\nfunction getIssuer(ctx, opts) {\n\tlet issuer;\n\tif (opts.disableJwtPlugin) issuer = ctx.context.baseURL;\n\telse try {\n\t\tissuer = getJwtPlugin(ctx.context).options?.jwt?.issuer ?? ctx.context.baseURL;\n\t} catch {\n\t\tissuer = ctx.context.baseURL;\n\t}\n\treturn validateIssuerUrl(issuer);\n}\n/**\n* Error page url if redirect_uri has not been verified yet\n* Generates Url for custom error page\n*/\nfunction getErrorURL(ctx, error, description) {\n\treturn formatErrorURL(ctx.context.options.onAPIError?.errorURL || `${ctx.context.baseURL}/error`, error, description);\n}\n/**\n* Based on the loopback port matching approach in node-oidc-provider.\n*\n* @see https://github.com/panva/node-oidc-provider/blob/ea1456f987de7750b6af8a89a1881e70c70827fe/lib/models/client.js#L36-L76\n*/\nfunction stripLoopbackRedirectPort(uri) {\n\tlet parsed;\n\ttry {\n\t\tparsed = new URL(uri);\n\t} catch {\n\t\treturn;\n\t}\n\tconst isLoopback = isLoopbackIP(parsed.hostname) || parsed.hostname === \"localhost\";\n\tif (parsed.protocol !== \"http:\" || !isLoopback) return;\n\tconst schemeSeparatorIndex = uri.indexOf(\"://\");\n\tif (schemeSeparatorIndex < 0) return void 0;\n\tconst authorityStart = schemeSeparatorIndex + 3;\n\tconst authorityEndOffset = uri.slice(authorityStart).search(/[/?#]/u);\n\tlet authorityEnd = uri.length;\n\tif (authorityEndOffset >= 0) authorityEnd = authorityStart + authorityEndOffset;\n\tconst authority = uri.slice(authorityStart, authorityEnd);\n\tlet portStart;\n\tif (authority.startsWith(\"[\")) {\n\t\tconst closingBracket = authority.indexOf(\"]\");\n\t\tif (closingBracket < 0) return void 0;\n\t\tif (authority[closingBracket + 1] !== \":\") return uri;\n\t\tportStart = closingBracket + 1;\n\t} else {\n\t\tportStart = authority.lastIndexOf(\":\");\n\t\tif (portStart < 0) return uri;\n\t}\n\tconst port = authority.slice(portStart + 1);\n\tif (!/^\\d*$/u.test(port)) return;\n\tconst portStartInUri = authorityStart + portStart;\n\treturn `${uri.slice(0, portStartInUri)}${uri.slice(authorityEnd)}`;\n}\n/**\n* Finds the matching entry in a client's registered redirect URIs.\n*\n* Registration limits loopback redirects to native-compatible HTTP forms.\n* Within that boundary, only the port may vary; every other character must\n* match the registered URI.\n*\n* @see https://www.rfc-editor.org/rfc/rfc9700.html#section-4.1.3\n* @see https://www.rfc-editor.org/rfc/rfc8252.html#section-8.3\n*/\nfunction findRegisteredRedirectUri(registered, requested) {\n\tif (!registered || !requested) return void 0;\n\tlet requestedUrl;\n\ttry {\n\t\trequestedUrl = new URL(requested);\n\t} catch {\n\t\treturn;\n\t}\n\t/**\n\t* A trailing `#` yields an empty `URL.hash` but still defines a fragment.\n\t*/\n\tconst hasFragment = requested.includes(\"#\");\n\tconst hasUserinfo = requestedUrl.username.length > 0 || requestedUrl.password.length > 0;\n\tif (hasFragment || hasUserinfo) return;\n\tconst requestedWithoutPort = stripLoopbackRedirectPort(requested);\n\treturn registered.find((url) => {\n\t\tif (url === requested) return true;\n\t\tif (!requestedWithoutPort) return false;\n\t\treturn stripLoopbackRedirectPort(url) === requestedWithoutPort;\n\t});\n}\n/** Keep URI syntax and credential checks outside the custom trust decision. */\nfunction isSafeCustomRedirectUri(uri) {\n\tif (!SafeUrlSchema.safeParse(uri).success) return false;\n\tconst parsed = new URL(uri);\n\treturn parsed.username.length === 0 && parsed.password.length === 0;\n}\n/**\n* Loads the client, verifies it's enabled, and returns the requested\n* redirect_uri when it matches a registered entry (or is accepted by the\n* custom `validateRedirectUri` option, mirroring the authorize endpoint's\n* validation). Returns null whenever the RP cannot be safely reached, so\n* callers can fall back to the server error page (avoiding open-redirect\n* risk on validation failures).\n*/\nasync function resolveTrustedRedirectUri(ctx, opts, clientId, redirectUri) {\n\tif (!clientId || !redirectUri) return null;\n\tlet client;\n\ttry {\n\t\tclient = await getClient(ctx, opts, clientId);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (!client || client.disabled) return null;\n\tconst registeredUris = client.redirectUris ?? [];\n\tconst matched = findRegisteredRedirectUri(registeredUris, redirectUri);\n\tif (opts.validateRedirectUri) {\n\t\tif (!isSafeCustomRedirectUri(redirectUri)) return null;\n\t\ttry {\n\t\t\treturn await opts.validateRedirectUri(redirectUri, registeredUris, Boolean(matched)) ? redirectUri : null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\treturn matched ? redirectUri : null;\n}\n/**\n* `redirectOnError` callback for `/oauth2/authorize`. Per RFC 6749 §4.1.2.1,\n* authorize errors MUST be delivered to the client's `redirect_uri` with\n* `error`, `error_description`, `state`, and (RFC 9207) `iss`. The clause\n* carves out one case: a missing/invalid `redirect_uri` or `client_id` MUST\n* NOT redirect to the requested URI. We implement the carve-out via\n* `resolveTrustedRedirectUri`, falling back to the server error page.\n*\n* Channel (query vs fragment) follows OIDC Core §5 via `deriveResponseMode`.\n*/\nfunction authorizeRedirectOnError(opts) {\n\treturn async ({ error, error_description, ctx }) => {\n\t\tconst raw = ctx.query ?? {};\n\t\tconst trusted = await resolveTrustedRedirectUri(ctx, opts, typeof raw.client_id === \"string\" ? raw.client_id : void 0, typeof raw.redirect_uri === \"string\" ? raw.redirect_uri : void 0);\n\t\tif (trusted) return handleRedirect(ctx, formatErrorURL(trusted, error, error_description, typeof raw.state === \"string\" ? raw.state : void 0, getIssuer(ctx, opts), deriveResponseMode(raw)));\n\t\treturn handleRedirect(ctx, getErrorURL(ctx, error, error_description));\n\t};\n}\nasync function authorizeEndpoint(ctx, opts, settings) {\n\tif (opts.grantTypes && !opts.grantTypes.includes(\"authorization_code\")) throw new APIError$1(\"NOT_FOUND\");\n\tif (!ctx.request) throw new APIError$1(\"UNAUTHORIZED\", {\n\t\terror_description: \"request not found\",\n\t\terror: \"invalid_request\"\n\t});\n\tconst request = ctx.request;\n\tlet query = getAuthorizationRequestParameters(ctx, settings);\n\tctx.query = query;\n\tconst requestObject = getStringParameter(query.request);\n\tconst requestUri = getStringParameter(query.request_uri);\n\tif (requestObject !== void 0 && requestUri !== void 0) return authorizeRedirectOnError(opts)({\n\t\terror: \"invalid_request\",\n\t\terror_description: \"request and request_uri cannot be used together\",\n\t\tctx\n\t});\n\tif (requestObject !== void 0) return authorizeRedirectOnError(opts)({\n\t\terror: \"request_not_supported\",\n\t\terror_description: \"request object not supported\",\n\t\tctx\n\t});\n\tif (requestUri !== void 0) {\n\t\tconst clientId = getStringParameter(query.client_id);\n\t\tif (!clientId) return authorizeRedirectOnError(opts)({\n\t\t\terror: \"invalid_request\",\n\t\t\terror_description: \"client_id is required\",\n\t\t\tctx\n\t\t});\n\t\tif (!opts.requestUriResolver) return authorizeRedirectOnError(opts)({\n\t\t\terror: \"request_uri_not_supported\",\n\t\t\terror_description: \"request_uri not supported\",\n\t\t\tctx\n\t\t});\n\t\tconst resolvedParams = await opts.requestUriResolver({\n\t\t\trequestUri,\n\t\t\tclientId,\n\t\t\tctx\n\t\t});\n\t\tif (!resolvedParams) return authorizeRedirectOnError(opts)({\n\t\t\terror: \"invalid_request_uri\",\n\t\t\terror_description: \"request_uri is invalid or expired\",\n\t\t\tctx\n\t\t});\n\t\tconst urlClientId = query.client_id;\n\t\tquery = resolvedParams;\n\t\tif (urlClientId) query.client_id = urlClientId;\n\t}\n\tctx.query = query;\n\tconst parsedQuery = authorizationQuerySchema.safeParse(query);\n\tif (!parsedQuery.success) {\n\t\tconst mappedError = mapIssuesToOAuthError(parsedQuery.error.issues, authorizationQueryErrorCodesByField);\n\t\treturn authorizeRedirectOnError(opts)({\n\t\t\t...mappedError,\n\t\t\tctx\n\t\t});\n\t}\n\tquery = parsedQuery.data;\n\tctx.query = query;\n\tawait oAuthState.set({ query: serializeAuthorizationQuery(query).toString() });\n\tif (!query.response_type) return authorizeRedirectOnError(opts)({\n\t\terror: \"invalid_request\",\n\t\terror_description: \"response_type is required\",\n\t\tctx\n\t});\n\tconst promptSet = ctx.query?.prompt ? parsePrompt(ctx.query?.prompt) : void 0;\n\tconst promptNone = promptSet?.has(\"none\") ?? false;\n\tif (promptSet?.has(\"select_account\") && !opts.selectAccount?.page) return handleRedirect(ctx, getErrorURL(ctx, `unsupported_prompt_select_account`, \"unsupported prompt type\"));\n\tif (!(query.response_type === \"code\")) return handleRedirect(ctx, getErrorURL(ctx, \"unsupported_response_type\", \"unsupported response type\"));\n\tconst client = await getClient(ctx, opts, query.client_id);\n\tif (!client) return handleRedirect(ctx, getErrorURL(ctx, \"invalid_client\", \"client_id is required\"));\n\tif (client.disabled) return handleRedirect(ctx, getErrorURL(ctx, \"client_disabled\", \"client is disabled\"));\n\tif (!clientAllowsGrant(client, \"authorization_code\")) return handleRedirect(ctx, getErrorURL(ctx, \"unauthorized_client\", \"client is not authorized to use the authorization_code grant\"));\n\tconst registeredUris = client.redirectUris ?? [];\n\tlet isValidRedirectUri = false;\n\tif (query.redirect_uri) {\n\t\tconst defaultResult = Boolean(findRegisteredRedirectUri(registeredUris, query.redirect_uri));\n\t\tif (opts.validateRedirectUri && isSafeCustomRedirectUri(query.redirect_uri)) try {\n\t\t\tisValidRedirectUri = await opts.validateRedirectUri(query.redirect_uri, registeredUris, defaultResult);\n\t\t} catch {\n\t\t\tisValidRedirectUri = false;\n\t\t}\n\t\telse if (!opts.validateRedirectUri) isValidRedirectUri = defaultResult;\n\t}\n\tif (!isValidRedirectUri) return handleRedirect(ctx, getErrorURL(ctx, \"invalid_redirect\", \"invalid redirect uri\"));\n\tlet requestedScopes = query.scope?.split(\" \").filter((s) => s);\n\tif (requestedScopes) {\n\t\tconst validScopes = new Set(client.scopes ?? opts.scopes);\n\t\tconst invalidScopes = requestedScopes.filter((scope) => {\n\t\t\treturn !validScopes?.has(scope);\n\t\t});\n\t\tif (invalidScopes.length) return handleRedirect(ctx, formatErrorURL(query.redirect_uri, \"invalid_scope\", `The following scopes are invalid: ${invalidScopes.join(\", \")}`, query.state, getIssuer(ctx, opts)));\n\t}\n\tif (!requestedScopes) {\n\t\trequestedScopes = client.scopes ?? opts.scopes ?? [];\n\t\tquery.scope = requestedScopes.join(\" \");\n\t}\n\tconst openidRequested = requestedScopes.includes(\"openid\");\n\tif (query.claims !== void 0 && !openidRequested) return handleRedirect(ctx, formatErrorURL(query.redirect_uri, \"invalid_request\", \"openid scope must be requested when using the claims parameter\", query.state, getIssuer(ctx, opts)));\n\tif (openidRequested && !isValidOidcClaimsRequest(query.claims)) return handleRedirect(ctx, formatErrorURL(query.redirect_uri, \"invalid_request\", \"claims must be a valid Claims request object\", query.state, getIssuer(ctx, opts)));\n\tif (openidRequested && !canSatisfyEssentialAcrRequest(query.claims, \"0\")) return handleRedirect(ctx, formatErrorURL(query.redirect_uri, \"access_denied\", \"essential acr requirement cannot be met\", query.state, getIssuer(ctx, opts)));\n\tconst requestedUserInfoClaims = getRequestedUserInfoClaims(query.claims, getSupportedClaims(opts));\n\tif (query.resource !== void 0) try {\n\t\tawait resolveResourcePolicy(ctx, opts, {\n\t\t\tresource: query.resource,\n\t\t\tclientId: client.clientId,\n\t\t\trequestedScopes\n\t\t});\n\t} catch (err) {\n\t\tif (err instanceof APIError$1) {\n\t\t\tconst error = err.body?.error ?? \"invalid_target\";\n\t\t\tconst description = err.body?.error_description ?? \"requested resource invalid\";\n\t\t\treturn handleRedirect(ctx, formatErrorURL(query.redirect_uri, error, description, query.state, getIssuer(ctx, opts)));\n\t\t}\n\t\tthrow err;\n\t}\n\tconst pkceRequired = isPKCERequired(client, {\n\t\tscopes: requestedScopes,\n\t\tnonce: query.nonce\n\t});\n\tif (pkceRequired) {\n\t\tif (!query.code_challenge || !query.code_challenge_method) return handleRedirect(ctx, formatErrorURL(query.redirect_uri, \"invalid_request\", pkceRequired.valueOf(), query.state, getIssuer(ctx, opts)));\n\t}\n\tif (query.code_challenge || query.code_challenge_method) {\n\t\tif (!query.code_challenge || !query.code_challenge_method) return handleRedirect(ctx, formatErrorURL(query.redirect_uri, \"invalid_request\", \"code_challenge and code_challenge_method must both be provided\", query.state, getIssuer(ctx, opts)));\n\t\tif (![\"S256\"].includes(query.code_challenge_method)) return handleRedirect(ctx, formatErrorURL(query.redirect_uri, \"invalid_request\", \"invalid code_challenge method, only S256 is supported\", query.state, getIssuer(ctx, opts)));\n\t}\n\tconst requestedResources = toResourceList(query.resource) ?? [];\n\tconst session = await getSessionFromCtx(ctx);\n\tconst maxAgeSeconds = query.max_age;\n\tconst hasSatisfiedMaxAge = session != null && maxAgeSeconds !== void 0 && isWithinMaxAge(new Date(session.session.createdAt), maxAgeSeconds, /* @__PURE__ */ new Date());\n\tif (!session || session != null && maxAgeSeconds !== void 0 && !hasSatisfiedMaxAge || promptSet?.has(\"login\") || promptSet?.has(\"create\")) {\n\t\tif (promptNone) return redirectWithPromptNoneError(ctx, opts, query, \"login_required\", \"authentication required\");\n\t\treturn redirectWithPromptCode(ctx, opts, promptSet?.has(\"create\") ? \"create\" : \"login\");\n\t}\n\tif (hasSatisfiedMaxAge) {\n\t\tquery = removeMaxAgeFromAuthorizationQuery(query);\n\t\tctx.query = query;\n\t}\n\tif (settings?.isAuthorize && promptSet?.has(\"select_account\")) return redirectWithPromptCode(ctx, opts, \"select_account\");\n\tif (settings?.isAuthorize && opts.selectAccount) {\n\t\tif (await opts.selectAccount.shouldRedirect({\n\t\t\theaders: request.headers,\n\t\t\tuser: session.user,\n\t\t\tsession: session.session,\n\t\t\tscopes: requestedScopes\n\t\t})) {\n\t\t\tif (promptNone) return redirectWithPromptNoneError(ctx, opts, query, \"account_selection_required\", \"End-User account selection is required\");\n\t\t\treturn redirectWithPromptCode(ctx, opts, \"select_account\");\n\t\t}\n\t}\n\tif (opts.signup?.shouldRedirect) {\n\t\tconst signupRedirect = await opts.signup.shouldRedirect({\n\t\t\theaders: request.headers,\n\t\t\tuser: session.user,\n\t\t\tsession: session.session,\n\t\t\tscopes: requestedScopes\n\t\t});\n\t\tif (signupRedirect) {\n\t\t\tif (promptNone) return redirectWithPromptNoneError(ctx, opts, query, \"interaction_required\", \"End-User interaction is required\");\n\t\t\treturn redirectWithPromptCode(ctx, opts, \"create\", { page: typeof signupRedirect === \"string\" ? signupRedirect : void 0 });\n\t\t}\n\t}\n\tif (!settings?.postLogin && opts.postLogin) {\n\t\tif (await opts.postLogin.shouldRedirect({\n\t\t\theaders: request.headers,\n\t\t\tuser: session.user,\n\t\t\tsession: session.session,\n\t\t\tscopes: requestedScopes\n\t\t})) {\n\t\t\tif (promptNone) return redirectWithPromptNoneError(ctx, opts, query, \"interaction_required\", \"End-User interaction is required\");\n\t\t\treturn redirectWithPromptCode(ctx, opts, \"post_login\");\n\t\t}\n\t}\n\tif (promptSet?.has(\"consent\")) return redirectWithPromptCode(ctx, opts, \"consent\", { sessionId: session.session.id });\n\tconst referenceId = await opts.postLogin?.consentReferenceId?.({\n\t\tuser: session.user,\n\t\tsession: session.session,\n\t\tscopes: requestedScopes\n\t});\n\tif (client.skipConsent) return redirectWithAuthorizationCode(ctx, opts, {\n\t\tquery,\n\t\tclientId: client.clientId,\n\t\tuserId: session.user.id,\n\t\tsessionId: session.session.id,\n\t\tauthTime: new Date(session.session.createdAt).getTime(),\n\t\treferenceId,\n\t\tresource: requestedResources\n\t});\n\tconst consent = await ctx.context.adapter.findOne({\n\t\tmodel: \"oauthConsent\",\n\t\twhere: [\n\t\t\t{\n\t\t\t\tfield: \"clientId\",\n\t\t\t\tvalue: client.clientId\n\t\t\t},\n\t\t\t{\n\t\t\t\tfield: \"userId\",\n\t\t\t\tvalue: session.user.id\n\t\t\t},\n\t\t\t...referenceId ? [{\n\t\t\t\tfield: \"referenceId\",\n\t\t\t\tvalue: referenceId\n\t\t\t}] : []\n\t\t]\n\t});\n\tif (!consent || !requestedScopes.every((val) => consent.scopes.includes(val)) || !requestedUserInfoClaims.every((claim) => (consent.requestedUserInfoClaims ?? []).includes(claim))) {\n\t\tif (promptNone) return redirectWithPromptNoneError(ctx, opts, query, \"consent_required\", \"End-User consent is required\");\n\t\treturn redirectWithPromptCode(ctx, opts, \"consent\", { sessionId: session.session.id });\n\t}\n\tconst consentedResources = consent?.resources ?? [];\n\tif (requestedResources.some((requestedResource) => !consentedResources.includes(requestedResource))) {\n\t\tif (promptNone) return redirectWithPromptNoneError(ctx, opts, query, \"consent_required\", \"End-User consent is required\");\n\t\treturn redirectWithPromptCode(ctx, opts, \"consent\", { sessionId: session.session.id });\n\t}\n\treturn redirectWithAuthorizationCode(ctx, opts, {\n\t\tquery,\n\t\tclientId: client.clientId,\n\t\tuserId: session.user.id,\n\t\tsessionId: session.session.id,\n\t\tauthTime: new Date(session.session.createdAt).getTime(),\n\t\treferenceId,\n\t\tresource: requestedResources\n\t});\n}\nfunction serializeAuthorizationQuery(query) {\n\tconst params = new URLSearchParams();\n\tfor (const [key, value] of Object.entries(query)) {\n\t\tif (value == null) continue;\n\t\tif (Array.isArray(value)) for (const v of value) params.append(key, String(v));\n\t\telse if (key === \"claims\" && typeof value === \"object\") params.set(key, JSON.stringify(value));\n\t\telse params.set(key, String(value));\n\t}\n\treturn params;\n}\nasync function redirectWithAuthorizationCode(ctx, opts, verificationValue) {\n\tconst code = generateRandomString(32, \"a-z\", \"A-Z\", \"0-9\");\n\tconst iat = Math.floor(Date.now() / 1e3);\n\tconst exp = iat + (opts.codeExpiresIn ?? 600);\n\tconst data = {\n\t\tidentifier: await storeToken(opts.storeTokens, code, \"authorization_code\"),\n\t\tupdatedAt: /* @__PURE__ */ new Date(iat * 1e3),\n\t\texpiresAt: /* @__PURE__ */ new Date(exp * 1e3),\n\t\tvalue: JSON.stringify({\n\t\t\ttype: \"authorization_code\",\n\t\t\tquery: verificationValue.query,\n\t\t\tuserId: verificationValue.userId,\n\t\t\tsessionId: verificationValue?.sessionId,\n\t\t\treferenceId: verificationValue.referenceId,\n\t\t\tauthTime: verificationValue.authTime,\n\t\t\tresource: verificationValue.resource\n\t\t})\n\t};\n\tawait ctx.context.internalAdapter.createVerificationValue({\n\t\t...data,\n\t\tcreatedAt: /* @__PURE__ */ new Date(iat * 1e3)\n\t});\n\tconst redirectUriWithCode = new URL(verificationValue.query.redirect_uri);\n\tredirectUriWithCode.searchParams.set(\"code\", code);\n\tif (verificationValue.query.state) redirectUriWithCode.searchParams.set(\"state\", verificationValue.query.state);\n\tredirectUriWithCode.searchParams.set(\"iss\", getIssuer(ctx, opts));\n\treturn handleRedirect(ctx, redirectUriWithCode.toString());\n}\nasync function redirectWithPromptCode(ctx, opts, type, options) {\n\tconst queryParams = await signParams(ctx, opts, { postLoginClearedForSession: type === \"consent\" && opts.postLogin ? options?.sessionId : void 0 });\n\tlet path = opts.loginPage;\n\tif (type === \"select_account\") path = opts.selectAccount?.page ?? opts.loginPage;\n\telse if (type === \"post_login\") {\n\t\tif (!opts.postLogin?.page) throw new APIError$1(\"INTERNAL_SERVER_ERROR\", { error_description: \"postLogin should have been defined\" });\n\t\tpath = opts.postLogin?.page;\n\t} else if (type === \"consent\") path = opts.consentPage;\n\telse if (type === \"create\") path = opts.signup?.page ?? opts.loginPage;\n\treturn handleRedirect(ctx, `${options?.page ?? path}?${queryParams}`);\n}\nasync function signParams(ctx, opts, flags) {\n\tconst issuedAt = Date.now();\n\tconst exp = Math.floor(issuedAt / 1e3) + (opts.codeExpiresIn ?? 600);\n\tconst params = serializeAuthorizationQuery(ctx.query);\n\tparams.set(\"exp\", String(exp));\n\tparams.set(signedQueryIssuedAtParam, String(issuedAt));\n\tparams.delete(\"sig\");\n\tparams.delete(postLoginClearedParam);\n\tif (flags?.postLoginClearedForSession) params.set(postLoginClearedParam, flags.postLoginClearedForSession);\n\tsetSignedOAuthQueryParameterNames(params);\n\tconst signature = await makeSignature(canonicalizeOAuthQueryParams(params).toString(), ctx.context.secret);\n\tparams.set(\"sig\", signature);\n\treturn params.toString();\n}\n//#endregion\nexport { registerClientMetadataDocument as a, isForbiddenCimdClientMetadataField as c, metadataResponse as d, oauthAuthorizationServerMetadata as f, oidcServerMetadata as h, oauthProvider as i, validatePublicClientJwks as l, oauthProviderOpenIdConfigMetadata as m, DEFAULT_OAUTH_SCOPES as n, client_assertion_exports as o, oauthProviderAuthServerMetadata as p, getOAuthProviderState as r, consumeClientAssertion as s, getIssuer as t, authServerMetadata as u };\n"],"ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108],"mappings":"moBAEA,SAAgB2K,GAAO,EAAQ,CAC3B,OAAO3K,EAAoBC,EAAmB2K,CAAM,CACxD,CAIA,SAAgBC,GAAQ,EAAQ,CAC5B,OAAO3K,EAAqBC,EAAoByK,CAAM,CAC1D,CCTA,IAAIE,GAAY,OAAO,eACnBC,IAAe,EAAK,IAAe,CACtC,IAAIC,EAAS,CAAC,EACd,IAAK,IAAIC,KAAQC,EAAKJ,GAAUE,EAAQC,EAAM,CAC7C,IAAKC,EAAID,GACT,WAAY,EACb,CAAC,EAED,OADKE,GAAYL,GAAUE,EAAQ,OAAO,YAAa,CAAE,MAAO,QAAS,CAAC,EACnEA,CACR,ECTMI,GAA2B,SAC3BC,GAAwB,QACxBC,GAAgC,WACtC,SAASC,GAA6B,EAAQ,CAC7C,IAAMC,EAAkB,IAAI,gBACtBC,EAAU,CAAC,GAAGb,EAAO,QAAQ,CAAC,CAAC,CAAC,MAAM,CAACc,EAAMC,GAAS,CAACC,EAAMC,KAC9DH,EAAOE,EAAa,GACpBF,EAAOE,EAAa,EACpBD,EAASE,EAAe,GAC5B,EAAIF,EAASE,EAEb,EACD,IAAK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C,CACD,CAGA,IAAMuiC,GAAS,CACd,YAAa,CACZ,UAAW,cACX,OAAQ,CACP,SAAU,CACT,KAAM,SACN,OAAQ,GACR,SAAU,EACX,EACA,aAAc,CACb,KAAM,SACN,SAAU,EACX,EACA,kBAAmB,CAClB,KAAM,SACN,SAAU,EACX,EACA,SAAU,CACT,KAAM,UACN,aAAc,GACd,SAAU,EACX,EACA,YAAa,CACZ,KAAM,UACN,SAAU,EACX,EACA,iBAAkB,CACjB,KAAM,UACN,SAAU,EACX,EACA,YAAa,CACZ,KAAM,SACN,SAAU,EACX,EACA,OAAQ,CACP,KAAM,WACN,SAAU,EACX,EACA,wBAAyB,CACxB,KAAM,WACN,SAAU,GACV,aAAc,CAAC,CAChB,EACA,OAAQ,CACP,KAAM,SACN,SAAU,GACV,WAAY,CACX,MAAO,OACP,MAAO,IACR,EACA,MAAO,EACR,EACA,UAAW,CACV,KAAM,OACN,SAAU,EACX,EACA,UAAW,CACV,KAAM,OACN,SAAU,EACX,EACA,KAAM,CACL,KAAM,SACN,SAAU,EACX,EACA,IAAK,CACJ,KAAM,SACN,SAAU,EACX,EACA,KAAM,CACL,KAAM,SACN,SAAU,EACX,EACA,SAAU,CACT,KAAM,WACN,SAAU,EACX,EACA,IAAK,CACJ,KAAM,SACN,SAAU,EACX,EACA,OAAQ,CACP,KAAM,SACN,SAAU,EACX,EACA,WAAY,CACX,KAAM,SACN,SAAU,EACX,EACA,gBAAiB,CAChB,KAAM,SACN,SAAU,EACX,EACA,kBAAmB,CAClB,KAAM,SACN,SAAU,EACX,EACA,aAAc,CACb,KAAM,WACN,SAAU,EACX,EACA,uBAAwB,CACvB,KAAM,WACN,SAAU,EACX,EACA,qBAAsB,CACrB,KAAM,SACN,SAAU,EACX,EACA,iCAAkC,CACjC,KAAM,UACN,SAAU,EACX,EACA,wBAAyB,CACxB,KAAM,SACN,SAAU,EACX,EACA,gBAAiB,CAChB,KAAM,SACN,SAAU,EACX,EACA,KAAM,CACL,KAAM,SACN,SAAU,EACX,EACA,QAAS,CACR,KAAM,SACN,SAAU,EACX,EACA,WAAY,CACX,KAAM,WACN,SAAU,EACX,EACA,cAAe,CACd,KAAM,WACN,SAAU,EACX,EACA,YAAa,CACZ,KAAM,UACN,SAAU,EACX,EACA,sBAAuB,CACtB,KAAM,UACN,SAAU,GACV,aAAc,EACf,EACA,YAAa,CACZ,KAAM,SACN,SAAU,EACX,EACA,SAAU,CACT,KAAM,OACN,SAAU,EACX,CACD,CACD,EAYA,cAAe,CACd,UAAW,gBACX,OAAQ,CACP,WAAY,CACX,KAAM,SACN,SAAU,GACV,OAAQ,EACT,EACA,KAAM,CACL,KAAM,SACN,SAAU,EACX,EACA,eAAgB,CACf,KAAM,SACN,SAAU,EACX,EACA,gBAAiB,CAChB,KAAM,SACN,SAAU,EACX,EACA,iBAAkB,CACjB,KAAM,SACN,SAAU,EACX,EACA,aAAc,CACb,KAAM,SACN,SAAU,EACX,EACA,cAAe,CACd,KAAM,WACN,SAAU,EACX,EACA,aAAc,CACb,KAAM,OACN,SAAU,EACX,EACA,8BAA+B,CAC9B,KAAM,UACN,SAAU,GACV,aAAc,EACf,EACA,SAAU,CACT,KAAM,UACN,SAAU,GACV,aAAc,EACf,EACA,UAAW,CACV,KAAM,OACN,SAAU,EACX,EACA,UAAW,CACV,KAAM,OACN,SAAU,EACX,EACA,cAAe,CACd,KAAM,SACN,SAAU,GACV,aAAc,CACf,EACA,SAAU,CACT,KAAM,OACN,SAAU,EACX,CACD,CACD,EAeA,oBAAqB,CACpB,UAAW,sBACX,OAAQ,CACP,SAAU,CACT,KAAM,SACN,SAAU,GACV,WAAY,CACX,MAAO,cACP,MAAO,WACP,SAAU,SACX,EACA,MAAO,EACR,EACA,WAAY,CACX,KAAM,SACN,SAAU,GACV,WAAY,CACX,MAAO,gBACP,MAAO,aACP,SAAU,SACX,EACA,MAAO,EACR,EACA,SAAU,CACT,KAAM,OACN,SAAU,EACX,EACA,UAAW,CACV,KAAM,OACN,SAAU,EACX,C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