mulguard 1.1.7 → 1.1.9

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 (546) hide show
  1. package/LICENSE +3 -3
  2. package/README.md +21 -582
  3. package/adapters.d.ts +2 -0
  4. package/adapters.d.ts.map +1 -0
  5. package/adapters.js +1 -0
  6. package/index.d.ts +329 -0
  7. package/index.d.ts.map +1 -0
  8. package/index.js +145 -0
  9. package/jwt.d.ts +9 -0
  10. package/jwt.d.ts.map +1 -0
  11. package/jwt.js +8 -0
  12. package/lib/actions.d.ts +13 -0
  13. package/lib/actions.d.ts.map +1 -0
  14. package/lib/actions.js +86 -0
  15. package/lib/client.d.ts +104 -0
  16. package/lib/client.d.ts.map +1 -0
  17. package/lib/client.js +95 -0
  18. package/lib/env.d.ts +12 -0
  19. package/lib/env.d.ts.map +1 -0
  20. package/lib/env.js +38 -0
  21. package/lib/index.d.ts +56 -0
  22. package/lib/index.d.ts.map +1 -0
  23. package/lib/index.js +187 -0
  24. package/lib/types.d.ts +24 -0
  25. package/lib/types.d.ts.map +1 -0
  26. package/lib/types.js +1 -0
  27. package/middleware.d.ts +9 -0
  28. package/middleware.d.ts.map +1 -0
  29. package/middleware.js +12 -0
  30. package/next.d.ts +9 -0
  31. package/next.d.ts.map +1 -0
  32. package/next.js +12 -0
  33. package/package.json +93 -102
  34. package/providers/42-school.d.ts +3 -0
  35. package/providers/42-school.d.ts.map +1 -0
  36. package/providers/42-school.js +2 -0
  37. package/providers/apple.d.ts +3 -0
  38. package/providers/apple.d.ts.map +1 -0
  39. package/providers/apple.js +2 -0
  40. package/providers/asgardeo.d.ts +3 -0
  41. package/providers/asgardeo.d.ts.map +1 -0
  42. package/providers/asgardeo.js +2 -0
  43. package/providers/atlassian.d.ts +3 -0
  44. package/providers/atlassian.d.ts.map +1 -0
  45. package/providers/atlassian.js +2 -0
  46. package/providers/auth0.d.ts +3 -0
  47. package/providers/auth0.d.ts.map +1 -0
  48. package/providers/auth0.js +2 -0
  49. package/providers/authentik.d.ts +3 -0
  50. package/providers/authentik.d.ts.map +1 -0
  51. package/providers/authentik.js +2 -0
  52. package/providers/azure-ad-b2c.d.ts +3 -0
  53. package/providers/azure-ad-b2c.d.ts.map +1 -0
  54. package/providers/azure-ad-b2c.js +2 -0
  55. package/providers/azure-ad.d.ts +3 -0
  56. package/providers/azure-ad.d.ts.map +1 -0
  57. package/providers/azure-ad.js +2 -0
  58. package/providers/azure-devops.d.ts +3 -0
  59. package/providers/azure-devops.d.ts.map +1 -0
  60. package/providers/azure-devops.js +2 -0
  61. package/providers/bankid-no.d.ts +3 -0
  62. package/providers/bankid-no.d.ts.map +1 -0
  63. package/providers/bankid-no.js +2 -0
  64. package/providers/battlenet.d.ts +3 -0
  65. package/providers/battlenet.d.ts.map +1 -0
  66. package/providers/battlenet.js +2 -0
  67. package/providers/beyondidentity.d.ts +3 -0
  68. package/providers/beyondidentity.d.ts.map +1 -0
  69. package/providers/beyondidentity.js +2 -0
  70. package/providers/bitbucket.d.ts +3 -0
  71. package/providers/bitbucket.d.ts.map +1 -0
  72. package/providers/bitbucket.js +2 -0
  73. package/providers/box.d.ts +3 -0
  74. package/providers/box.d.ts.map +1 -0
  75. package/providers/box.js +2 -0
  76. package/providers/boxyhq-saml.d.ts +3 -0
  77. package/providers/boxyhq-saml.d.ts.map +1 -0
  78. package/providers/boxyhq-saml.js +2 -0
  79. package/providers/bungie.d.ts +3 -0
  80. package/providers/bungie.d.ts.map +1 -0
  81. package/providers/bungie.js +2 -0
  82. package/providers/click-up.d.ts +3 -0
  83. package/providers/click-up.d.ts.map +1 -0
  84. package/providers/click-up.js +2 -0
  85. package/providers/cognito.d.ts +3 -0
  86. package/providers/cognito.d.ts.map +1 -0
  87. package/providers/cognito.js +2 -0
  88. package/providers/coinbase.d.ts +3 -0
  89. package/providers/coinbase.d.ts.map +1 -0
  90. package/providers/coinbase.js +2 -0
  91. package/providers/concept2.d.ts +3 -0
  92. package/providers/concept2.d.ts.map +1 -0
  93. package/providers/concept2.js +2 -0
  94. package/providers/credentials.d.ts +3 -0
  95. package/providers/credentials.d.ts.map +1 -0
  96. package/providers/credentials.js +2 -0
  97. package/providers/descope.d.ts +3 -0
  98. package/providers/descope.d.ts.map +1 -0
  99. package/providers/descope.js +2 -0
  100. package/providers/discord.d.ts +3 -0
  101. package/providers/discord.d.ts.map +1 -0
  102. package/providers/discord.js +2 -0
  103. package/providers/dribbble.d.ts +3 -0
  104. package/providers/dribbble.d.ts.map +1 -0
  105. package/providers/dribbble.js +2 -0
  106. package/providers/dropbox.d.ts +3 -0
  107. package/providers/dropbox.d.ts.map +1 -0
  108. package/providers/dropbox.js +2 -0
  109. package/providers/duende-identity-server6.d.ts +3 -0
  110. package/providers/duende-identity-server6.d.ts.map +1 -0
  111. package/providers/duende-identity-server6.js +2 -0
  112. package/providers/email.d.ts +3 -0
  113. package/providers/email.d.ts.map +1 -0
  114. package/providers/email.js +2 -0
  115. package/providers/eventbrite.d.ts +3 -0
  116. package/providers/eventbrite.d.ts.map +1 -0
  117. package/providers/eventbrite.js +2 -0
  118. package/providers/eveonline.d.ts +3 -0
  119. package/providers/eveonline.d.ts.map +1 -0
  120. package/providers/eveonline.js +2 -0
  121. package/providers/facebook.d.ts +3 -0
  122. package/providers/facebook.d.ts.map +1 -0
  123. package/providers/facebook.js +2 -0
  124. package/providers/faceit.d.ts +3 -0
  125. package/providers/faceit.d.ts.map +1 -0
  126. package/providers/faceit.js +2 -0
  127. package/providers/figma.d.ts +3 -0
  128. package/providers/figma.d.ts.map +1 -0
  129. package/providers/figma.js +2 -0
  130. package/providers/forwardemail.d.ts +3 -0
  131. package/providers/forwardemail.d.ts.map +1 -0
  132. package/providers/forwardemail.js +2 -0
  133. package/providers/foursquare.d.ts +3 -0
  134. package/providers/foursquare.d.ts.map +1 -0
  135. package/providers/foursquare.js +2 -0
  136. package/providers/freshbooks.d.ts +3 -0
  137. package/providers/freshbooks.d.ts.map +1 -0
  138. package/providers/freshbooks.js +2 -0
  139. package/providers/frontegg.d.ts +3 -0
  140. package/providers/frontegg.d.ts.map +1 -0
  141. package/providers/frontegg.js +2 -0
  142. package/providers/fusionauth.d.ts +3 -0
  143. package/providers/fusionauth.d.ts.map +1 -0
  144. package/providers/fusionauth.js +2 -0
  145. package/providers/github.d.ts +3 -0
  146. package/providers/github.d.ts.map +1 -0
  147. package/providers/github.js +2 -0
  148. package/providers/gitlab.d.ts +3 -0
  149. package/providers/gitlab.d.ts.map +1 -0
  150. package/providers/gitlab.js +2 -0
  151. package/providers/google.d.ts +3 -0
  152. package/providers/google.d.ts.map +1 -0
  153. package/providers/google.js +2 -0
  154. package/providers/hubspot.d.ts +3 -0
  155. package/providers/hubspot.d.ts.map +1 -0
  156. package/providers/hubspot.js +2 -0
  157. package/providers/huggingface.d.ts +3 -0
  158. package/providers/huggingface.d.ts.map +1 -0
  159. package/providers/huggingface.js +2 -0
  160. package/providers/identity-server4.d.ts +3 -0
  161. package/providers/identity-server4.d.ts.map +1 -0
  162. package/providers/identity-server4.js +2 -0
  163. package/providers/index.d.ts +2 -0
  164. package/providers/index.d.ts.map +1 -0
  165. package/providers/index.js +1 -0
  166. package/providers/instagram.d.ts +3 -0
  167. package/providers/instagram.d.ts.map +1 -0
  168. package/providers/instagram.js +2 -0
  169. package/providers/kakao.d.ts +3 -0
  170. package/providers/kakao.d.ts.map +1 -0
  171. package/providers/kakao.js +2 -0
  172. package/providers/keycloak.d.ts +3 -0
  173. package/providers/keycloak.d.ts.map +1 -0
  174. package/providers/keycloak.js +2 -0
  175. package/providers/kinde.d.ts +3 -0
  176. package/providers/kinde.d.ts.map +1 -0
  177. package/providers/kinde.js +2 -0
  178. package/providers/line.d.ts +3 -0
  179. package/providers/line.d.ts.map +1 -0
  180. package/providers/line.js +2 -0
  181. package/providers/linkedin.d.ts +3 -0
  182. package/providers/linkedin.d.ts.map +1 -0
  183. package/providers/linkedin.js +2 -0
  184. package/providers/logto.d.ts +3 -0
  185. package/providers/logto.d.ts.map +1 -0
  186. package/providers/logto.js +2 -0
  187. package/providers/loops.d.ts +3 -0
  188. package/providers/loops.d.ts.map +1 -0
  189. package/providers/loops.js +2 -0
  190. package/providers/mailchimp.d.ts +3 -0
  191. package/providers/mailchimp.d.ts.map +1 -0
  192. package/providers/mailchimp.js +2 -0
  193. package/providers/mailgun.d.ts +3 -0
  194. package/providers/mailgun.d.ts.map +1 -0
  195. package/providers/mailgun.js +2 -0
  196. package/providers/mailru.d.ts +3 -0
  197. package/providers/mailru.d.ts.map +1 -0
  198. package/providers/mailru.js +2 -0
  199. package/providers/mastodon.d.ts +3 -0
  200. package/providers/mastodon.d.ts.map +1 -0
  201. package/providers/mastodon.js +2 -0
  202. package/providers/mattermost.d.ts +3 -0
  203. package/providers/mattermost.d.ts.map +1 -0
  204. package/providers/mattermost.js +2 -0
  205. package/providers/medium.d.ts +3 -0
  206. package/providers/medium.d.ts.map +1 -0
  207. package/providers/medium.js +2 -0
  208. package/providers/microsoft-entra-id.d.ts +3 -0
  209. package/providers/microsoft-entra-id.d.ts.map +1 -0
  210. package/providers/microsoft-entra-id.js +2 -0
  211. package/providers/naver.d.ts +3 -0
  212. package/providers/naver.d.ts.map +1 -0
  213. package/providers/naver.js +2 -0
  214. package/providers/netlify.d.ts +3 -0
  215. package/providers/netlify.d.ts.map +1 -0
  216. package/providers/netlify.js +2 -0
  217. package/providers/netsuite.d.ts +3 -0
  218. package/providers/netsuite.d.ts.map +1 -0
  219. package/providers/netsuite.js +2 -0
  220. package/providers/nextcloud.d.ts +3 -0
  221. package/providers/nextcloud.d.ts.map +1 -0
  222. package/providers/nextcloud.js +2 -0
  223. package/providers/nodemailer.d.ts +3 -0
  224. package/providers/nodemailer.d.ts.map +1 -0
  225. package/providers/nodemailer.js +2 -0
  226. package/providers/notion.d.ts +3 -0
  227. package/providers/notion.d.ts.map +1 -0
  228. package/providers/notion.js +2 -0
  229. package/providers/okta.d.ts +3 -0
  230. package/providers/okta.d.ts.map +1 -0
  231. package/providers/okta.js +2 -0
  232. package/providers/onelogin.d.ts +3 -0
  233. package/providers/onelogin.d.ts.map +1 -0
  234. package/providers/onelogin.js +2 -0
  235. package/providers/ory-hydra.d.ts +3 -0
  236. package/providers/ory-hydra.d.ts.map +1 -0
  237. package/providers/ory-hydra.js +2 -0
  238. package/providers/osso.d.ts +3 -0
  239. package/providers/osso.d.ts.map +1 -0
  240. package/providers/osso.js +2 -0
  241. package/providers/osu.d.ts +3 -0
  242. package/providers/osu.d.ts.map +1 -0
  243. package/providers/osu.js +2 -0
  244. package/providers/passage.d.ts +3 -0
  245. package/providers/passage.d.ts.map +1 -0
  246. package/providers/passage.js +2 -0
  247. package/providers/passkey.d.ts +3 -0
  248. package/providers/passkey.d.ts.map +1 -0
  249. package/providers/passkey.js +2 -0
  250. package/providers/patreon.d.ts +3 -0
  251. package/providers/patreon.d.ts.map +1 -0
  252. package/providers/patreon.js +2 -0
  253. package/providers/ping-id.d.ts +3 -0
  254. package/providers/ping-id.d.ts.map +1 -0
  255. package/providers/ping-id.js +2 -0
  256. package/providers/pinterest.d.ts +3 -0
  257. package/providers/pinterest.d.ts.map +1 -0
  258. package/providers/pinterest.js +2 -0
  259. package/providers/pipedrive.d.ts +3 -0
  260. package/providers/pipedrive.d.ts.map +1 -0
  261. package/providers/pipedrive.js +2 -0
  262. package/providers/postmark.d.ts +3 -0
  263. package/providers/postmark.d.ts.map +1 -0
  264. package/providers/postmark.js +2 -0
  265. package/providers/reddit.d.ts +3 -0
  266. package/providers/reddit.d.ts.map +1 -0
  267. package/providers/reddit.js +2 -0
  268. package/providers/resend.d.ts +3 -0
  269. package/providers/resend.d.ts.map +1 -0
  270. package/providers/resend.js +2 -0
  271. package/providers/roblox.d.ts +3 -0
  272. package/providers/roblox.d.ts.map +1 -0
  273. package/providers/roblox.js +2 -0
  274. package/providers/salesforce.d.ts +3 -0
  275. package/providers/salesforce.d.ts.map +1 -0
  276. package/providers/salesforce.js +2 -0
  277. package/providers/sendgrid.d.ts +3 -0
  278. package/providers/sendgrid.d.ts.map +1 -0
  279. package/providers/sendgrid.js +2 -0
  280. package/providers/simplelogin.d.ts +3 -0
  281. package/providers/simplelogin.d.ts.map +1 -0
  282. package/providers/simplelogin.js +2 -0
  283. package/providers/slack.d.ts +3 -0
  284. package/providers/slack.d.ts.map +1 -0
  285. package/providers/slack.js +2 -0
  286. package/providers/spotify.d.ts +3 -0
  287. package/providers/spotify.d.ts.map +1 -0
  288. package/providers/spotify.js +2 -0
  289. package/providers/strava.d.ts +3 -0
  290. package/providers/strava.d.ts.map +1 -0
  291. package/providers/strava.js +2 -0
  292. package/providers/threads.d.ts +3 -0
  293. package/providers/threads.d.ts.map +1 -0
  294. package/providers/threads.js +2 -0
  295. package/providers/tiktok.d.ts +3 -0
  296. package/providers/tiktok.d.ts.map +1 -0
  297. package/providers/tiktok.js +2 -0
  298. package/providers/todoist.d.ts +3 -0
  299. package/providers/todoist.d.ts.map +1 -0
  300. package/providers/todoist.js +2 -0
  301. package/providers/trakt.d.ts +3 -0
  302. package/providers/trakt.d.ts.map +1 -0
  303. package/providers/trakt.js +2 -0
  304. package/providers/twitch.d.ts +3 -0
  305. package/providers/twitch.d.ts.map +1 -0
  306. package/providers/twitch.js +2 -0
  307. package/providers/twitter.d.ts +3 -0
  308. package/providers/twitter.d.ts.map +1 -0
  309. package/providers/twitter.js +2 -0
  310. package/providers/united-effects.d.ts +3 -0
  311. package/providers/united-effects.d.ts.map +1 -0
  312. package/providers/united-effects.js +2 -0
  313. package/providers/vipps.d.ts +3 -0
  314. package/providers/vipps.d.ts.map +1 -0
  315. package/providers/vipps.js +2 -0
  316. package/providers/vk.d.ts +3 -0
  317. package/providers/vk.d.ts.map +1 -0
  318. package/providers/vk.js +2 -0
  319. package/providers/webauthn.d.ts +3 -0
  320. package/providers/webauthn.d.ts.map +1 -0
  321. package/providers/webauthn.js +2 -0
  322. package/providers/webex.d.ts +3 -0
  323. package/providers/webex.d.ts.map +1 -0
  324. package/providers/webex.js +2 -0
  325. package/providers/wechat.d.ts +3 -0
  326. package/providers/wechat.d.ts.map +1 -0
  327. package/providers/wechat.js +2 -0
  328. package/providers/wikimedia.d.ts +3 -0
  329. package/providers/wikimedia.d.ts.map +1 -0
  330. package/providers/wikimedia.js +2 -0
  331. package/providers/wordpress.d.ts +3 -0
  332. package/providers/wordpress.d.ts.map +1 -0
  333. package/providers/wordpress.js +2 -0
  334. package/providers/workos.d.ts +3 -0
  335. package/providers/workos.d.ts.map +1 -0
  336. package/providers/workos.js +2 -0
  337. package/providers/yandex.d.ts +3 -0
  338. package/providers/yandex.d.ts.map +1 -0
  339. package/providers/yandex.js +2 -0
  340. package/providers/zitadel.d.ts +3 -0
  341. package/providers/zitadel.d.ts.map +1 -0
  342. package/providers/zitadel.js +2 -0
  343. package/providers/zoho.d.ts +3 -0
  344. package/providers/zoho.d.ts.map +1 -0
  345. package/providers/zoho.js +2 -0
  346. package/providers/zoom.d.ts +3 -0
  347. package/providers/zoom.d.ts.map +1 -0
  348. package/providers/zoom.js +2 -0
  349. package/react.d.ts +102 -0
  350. package/react.d.ts.map +1 -0
  351. package/react.js +361 -0
  352. package/src/adapters.ts +1 -0
  353. package/src/index.ts +430 -0
  354. package/src/jwt.ts +9 -0
  355. package/src/lib/actions.ts +144 -0
  356. package/src/lib/client.ts +245 -0
  357. package/src/lib/env.ts +36 -0
  358. package/src/lib/index.ts +313 -0
  359. package/src/lib/types.ts +30 -0
  360. package/src/middleware.ts +16 -0
  361. package/src/next.ts +16 -0
  362. package/src/providers/42-school.ts +2 -0
  363. package/src/providers/apple.ts +2 -0
  364. package/src/providers/asgardeo.ts +2 -0
  365. package/src/providers/atlassian.ts +2 -0
  366. package/src/providers/auth0.ts +2 -0
  367. package/src/providers/authentik.ts +2 -0
  368. package/src/providers/azure-ad-b2c.ts +2 -0
  369. package/src/providers/azure-ad.ts +2 -0
  370. package/src/providers/azure-devops.ts +2 -0
  371. package/src/providers/bankid-no.ts +2 -0
  372. package/src/providers/battlenet.ts +2 -0
  373. package/src/providers/beyondidentity.ts +2 -0
  374. package/src/providers/bitbucket.ts +2 -0
  375. package/src/providers/box.ts +2 -0
  376. package/src/providers/boxyhq-saml.ts +2 -0
  377. package/src/providers/bungie.ts +2 -0
  378. package/src/providers/click-up.ts +2 -0
  379. package/src/providers/cognito.ts +2 -0
  380. package/src/providers/coinbase.ts +2 -0
  381. package/src/providers/concept2.ts +2 -0
  382. package/src/providers/credentials.ts +2 -0
  383. package/src/providers/descope.ts +2 -0
  384. package/src/providers/discord.ts +2 -0
  385. package/src/providers/dribbble.ts +2 -0
  386. package/src/providers/dropbox.ts +2 -0
  387. package/src/providers/duende-identity-server6.ts +2 -0
  388. package/src/providers/email.ts +2 -0
  389. package/src/providers/eventbrite.ts +2 -0
  390. package/src/providers/eveonline.ts +2 -0
  391. package/src/providers/facebook.ts +2 -0
  392. package/src/providers/faceit.ts +2 -0
  393. package/src/providers/figma.ts +2 -0
  394. package/src/providers/forwardemail.ts +2 -0
  395. package/src/providers/foursquare.ts +2 -0
  396. package/src/providers/freshbooks.ts +2 -0
  397. package/src/providers/frontegg.ts +2 -0
  398. package/src/providers/fusionauth.ts +2 -0
  399. package/src/providers/github.ts +2 -0
  400. package/src/providers/gitlab.ts +2 -0
  401. package/src/providers/google.ts +2 -0
  402. package/src/providers/hubspot.ts +2 -0
  403. package/src/providers/huggingface.ts +2 -0
  404. package/src/providers/identity-server4.ts +2 -0
  405. package/src/providers/index.ts +1 -0
  406. package/src/providers/instagram.ts +2 -0
  407. package/src/providers/kakao.ts +2 -0
  408. package/src/providers/keycloak.ts +2 -0
  409. package/src/providers/kinde.ts +2 -0
  410. package/src/providers/line.ts +2 -0
  411. package/src/providers/linkedin.ts +2 -0
  412. package/src/providers/logto.ts +2 -0
  413. package/src/providers/loops.ts +2 -0
  414. package/src/providers/mailchimp.ts +2 -0
  415. package/src/providers/mailgun.ts +2 -0
  416. package/src/providers/mailru.ts +2 -0
  417. package/src/providers/mastodon.ts +2 -0
  418. package/src/providers/mattermost.ts +2 -0
  419. package/src/providers/medium.ts +2 -0
  420. package/src/providers/microsoft-entra-id.ts +2 -0
  421. package/src/providers/naver.ts +2 -0
  422. package/src/providers/netlify.ts +2 -0
  423. package/src/providers/netsuite.ts +2 -0
  424. package/src/providers/nextcloud.ts +2 -0
  425. package/src/providers/nodemailer.ts +2 -0
  426. package/src/providers/notion.ts +2 -0
  427. package/src/providers/okta.ts +2 -0
  428. package/src/providers/onelogin.ts +2 -0
  429. package/src/providers/ory-hydra.ts +2 -0
  430. package/src/providers/osso.ts +2 -0
  431. package/src/providers/osu.ts +2 -0
  432. package/src/providers/passage.ts +2 -0
  433. package/src/providers/passkey.ts +2 -0
  434. package/src/providers/patreon.ts +2 -0
  435. package/src/providers/ping-id.ts +2 -0
  436. package/src/providers/pinterest.ts +2 -0
  437. package/src/providers/pipedrive.ts +2 -0
  438. package/src/providers/postmark.ts +2 -0
  439. package/src/providers/reddit.ts +2 -0
  440. package/src/providers/resend.ts +2 -0
  441. package/src/providers/roblox.ts +2 -0
  442. package/src/providers/salesforce.ts +2 -0
  443. package/src/providers/sendgrid.ts +2 -0
  444. package/src/providers/simplelogin.ts +2 -0
  445. package/src/providers/slack.ts +2 -0
  446. package/src/providers/spotify.ts +2 -0
  447. package/src/providers/strava.ts +2 -0
  448. package/src/providers/threads.ts +2 -0
  449. package/src/providers/tiktok.ts +2 -0
  450. package/src/providers/todoist.ts +2 -0
  451. package/src/providers/trakt.ts +2 -0
  452. package/src/providers/twitch.ts +2 -0
  453. package/src/providers/twitter.ts +2 -0
  454. package/src/providers/united-effects.ts +2 -0
  455. package/src/providers/vipps.ts +2 -0
  456. package/src/providers/vk.ts +2 -0
  457. package/src/providers/webauthn.ts +2 -0
  458. package/src/providers/webex.ts +2 -0
  459. package/src/providers/wechat.ts +2 -0
  460. package/src/providers/wikimedia.ts +2 -0
  461. package/src/providers/wordpress.ts +2 -0
  462. package/src/providers/workos.ts +2 -0
  463. package/src/providers/yandex.ts +2 -0
  464. package/src/providers/zitadel.ts +2 -0
  465. package/src/providers/zoho.ts +2 -0
  466. package/src/providers/zoom.ts +2 -0
  467. package/src/react.tsx +546 -0
  468. package/src/webauthn.ts +152 -0
  469. package/webauthn.d.ts +9 -0
  470. package/webauthn.d.ts.map +1 -0
  471. package/webauthn.js +92 -0
  472. package/dist/actions-CMtg7FGv.js +0 -1
  473. package/dist/actions-CjQUKaXF.mjs +0 -200
  474. package/dist/client/index.js +0 -1
  475. package/dist/client/index.mjs +0 -484
  476. package/dist/components/AccountPicker.d.ts +0 -11
  477. package/dist/components/OAuthButton.d.ts +0 -11
  478. package/dist/components/PassKeyButton.d.ts +0 -11
  479. package/dist/components/PassKeyRegister.d.ts +0 -10
  480. package/dist/components/TwoFactorSetup.d.ts +0 -8
  481. package/dist/components/TwoFactorVerify.d.ts +0 -9
  482. package/dist/core/account-picker/encryption.d.ts +0 -22
  483. package/dist/core/account-picker/index.d.ts +0 -22
  484. package/dist/core/auth/email-password.d.ts +0 -145
  485. package/dist/core/auth/oauth/index.d.ts +0 -14
  486. package/dist/core/auth/oauth/oauth-handler.d.ts +0 -172
  487. package/dist/core/auth/oauth/pkce.d.ts +0 -168
  488. package/dist/core/auth/oauth/providers.d.ts +0 -198
  489. package/dist/core/auth/oauth/state-store-cookie.d.ts +0 -83
  490. package/dist/core/auth/oauth/state-store-redis.d.ts +0 -25
  491. package/dist/core/auth/oauth/state-store.d.ts +0 -48
  492. package/dist/core/auth/otp.d.ts +0 -184
  493. package/dist/core/auth/passkey.d.ts +0 -35
  494. package/dist/core/auth/password.d.ts +0 -22
  495. package/dist/core/auth/signin-unified.d.ts +0 -33
  496. package/dist/core/auth/two-factor.d.ts +0 -28
  497. package/dist/core/client/index.d.ts +0 -132
  498. package/dist/core/client/token-refresh-manager.d.ts +0 -48
  499. package/dist/core/errors/index.d.ts +0 -269
  500. package/dist/core/index.d.ts +0 -9
  501. package/dist/core/logger/index.d.ts +0 -147
  502. package/dist/core/mulguard/auth-handlers.d.ts +0 -100
  503. package/dist/core/mulguard/defaults.d.ts +0 -58
  504. package/dist/core/mulguard/index.d.ts +0 -9
  505. package/dist/core/mulguard/integration.d.ts +0 -104
  506. package/dist/core/mulguard/oauth-handler.d.ts +0 -93
  507. package/dist/core/mulguard/session-manager.d.ts +0 -94
  508. package/dist/core/security/csrf.d.ts +0 -46
  509. package/dist/core/security/headers.d.ts +0 -24
  510. package/dist/core/security/index.d.ts +0 -132
  511. package/dist/core/security/rate-limit.d.ts +0 -39
  512. package/dist/core/security/security-manager.d.ts +0 -236
  513. package/dist/core/security/validation.d.ts +0 -251
  514. package/dist/core/security/xss.d.ts +0 -20
  515. package/dist/core/session/index.d.ts +0 -35
  516. package/dist/core/session/session-manager.d.ts +0 -235
  517. package/dist/core/types/auth.d.ts +0 -290
  518. package/dist/core/types/errors.d.ts +0 -200
  519. package/dist/core/types/index.d.ts +0 -484
  520. package/dist/core/utils/auth-helpers.d.ts +0 -136
  521. package/dist/core/utils/logger.d.ts +0 -121
  522. package/dist/index/index.js +0 -1
  523. package/dist/index/index.mjs +0 -2736
  524. package/dist/index.d.ts +0 -18
  525. package/dist/mulguard.d.ts +0 -373
  526. package/dist/nextjs/client/hooks.d.ts +0 -122
  527. package/dist/nextjs/client/index.d.ts +0 -13
  528. package/dist/nextjs/client/provider.d.ts +0 -69
  529. package/dist/nextjs/client/server-actions-helper.d.ts +0 -22
  530. package/dist/nextjs/handlers/api.d.ts +0 -10
  531. package/dist/nextjs/handlers/index.d.ts +0 -9
  532. package/dist/nextjs/handlers/route.d.ts +0 -76
  533. package/dist/nextjs/index.d.ts +0 -15
  534. package/dist/nextjs/proxy/index.d.ts +0 -149
  535. package/dist/nextjs/proxy/security.d.ts +0 -9
  536. package/dist/nextjs/server/actions.d.ts +0 -30
  537. package/dist/nextjs/server/auth.d.ts +0 -65
  538. package/dist/nextjs/server/cookies.d.ts +0 -41
  539. package/dist/nextjs/server/index.d.ts +0 -18
  540. package/dist/nextjs/server/oauth-state.d.ts +0 -32
  541. package/dist/nextjs/server/session-helpers.d.ts +0 -24
  542. package/dist/nextjs/server/session.d.ts +0 -144
  543. package/dist/oauth-state-Drwz6fES.js +0 -1
  544. package/dist/oauth-state-pdypStuS.mjs +0 -210
  545. package/dist/server/index.js +0 -1
  546. package/dist/server/index.mjs +0 -29
@@ -1,2736 +0,0 @@
1
- var ve = Object.defineProperty;
2
- var Se = (e, r, t) => r in e ? ve(e, r, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[r] = t;
3
- var x = (e, r, t) => Se(e, typeof r != "symbol" ? r + "" : r, t);
4
- import { A as m, d as Ae, e as Re, c as Oe, g as Te } from "../actions-CjQUKaXF.mjs";
5
- import { a as Gt, s as Kt, b as Xt, v as Jt } from "../actions-CjQUKaXF.mjs";
6
- import { v as F } from "../oauth-state-pdypStuS.mjs";
7
- import { S as Qt, e as Zt, d as en, m as rn, g as tn, l as nn, b as sn, c as on, j as an, i as cn, f as un, h as ln, k as fn, r as dn, a as hn, s as gn } from "../oauth-state-pdypStuS.mjs";
8
- import { NextResponse as A } from "next/server";
9
- const L = typeof globalThis == "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
10
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
11
- function _e(e) {
12
- return e instanceof Uint8Array || ArrayBuffer.isView(e) && e.constructor.name === "Uint8Array";
13
- }
14
- function G(e, ...r) {
15
- if (!_e(e))
16
- throw new Error("Uint8Array expected");
17
- if (r.length > 0 && !r.includes(e.length))
18
- throw new Error("Uint8Array expected of length " + r + ", got length=" + e.length);
19
- }
20
- function Q(e, r = !0) {
21
- if (e.destroyed)
22
- throw new Error("Hash instance has been destroyed");
23
- if (r && e.finished)
24
- throw new Error("Hash#digest() has already been called");
25
- }
26
- function be(e, r) {
27
- G(e);
28
- const t = r.outputLen;
29
- if (e.length < t)
30
- throw new Error("digestInto() expects output buffer of length at least " + t);
31
- }
32
- function q(...e) {
33
- for (let r = 0; r < e.length; r++)
34
- e[r].fill(0);
35
- }
36
- function H(e) {
37
- return new DataView(e.buffer, e.byteOffset, e.byteLength);
38
- }
39
- function P(e, r) {
40
- return e << 32 - r | e >>> r;
41
- }
42
- function Ce(e) {
43
- if (typeof e != "string")
44
- throw new Error("string expected");
45
- return new Uint8Array(new TextEncoder().encode(e));
46
- }
47
- function re(e) {
48
- return typeof e == "string" && (e = Ce(e)), G(e), e;
49
- }
50
- class Ie {
51
- }
52
- function xe(e) {
53
- const r = (n) => e().update(re(n)).digest(), t = e();
54
- return r.outputLen = t.outputLen, r.blockLen = t.blockLen, r.create = () => e(), r;
55
- }
56
- function te(e = 32) {
57
- if (L && typeof L.getRandomValues == "function")
58
- return L.getRandomValues(new Uint8Array(e));
59
- if (L && typeof L.randomBytes == "function")
60
- return Uint8Array.from(L.randomBytes(e));
61
- throw new Error("crypto.getRandomValues must be defined");
62
- }
63
- class Pe {
64
- constructor(r) {
65
- x(this, "attempts", /* @__PURE__ */ new Map());
66
- x(this, "config");
67
- this.config = r;
68
- }
69
- /**
70
- * Check if request is allowed
71
- */
72
- check(r) {
73
- const t = Date.now(), n = this.attempts.get(r);
74
- return !n || n.resetAt < t ? (this.attempts.set(r, {
75
- count: 1,
76
- resetAt: t + this.config.windowMs
77
- }), {
78
- allowed: !0,
79
- remaining: this.config.maxAttempts - 1,
80
- resetAt: new Date(t + this.config.windowMs)
81
- }) : n.count >= this.config.maxAttempts ? {
82
- allowed: !1,
83
- remaining: 0,
84
- resetAt: new Date(n.resetAt)
85
- } : (n.count++, {
86
- allowed: !0,
87
- remaining: this.config.maxAttempts - n.count,
88
- resetAt: new Date(n.resetAt)
89
- });
90
- }
91
- /**
92
- * Reset rate limit for a key
93
- */
94
- reset(r) {
95
- this.attempts.delete(r);
96
- }
97
- /**
98
- * Clear all rate limits
99
- */
100
- clear() {
101
- this.attempts.clear();
102
- }
103
- }
104
- function ut(e) {
105
- return new Pe(e);
106
- }
107
- const Ne = {
108
- "X-Content-Type-Options": "nosniff",
109
- "X-Frame-Options": "DENY",
110
- "X-XSS-Protection": "1; mode=block",
111
- "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
112
- "Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';",
113
- "Referrer-Policy": "strict-origin-when-cross-origin",
114
- "Permissions-Policy": "geolocation=(), microphone=(), camera=()"
115
- };
116
- function ne(e) {
117
- return {
118
- ...Ne,
119
- ...e
120
- };
121
- }
122
- function lt(e, r) {
123
- const t = ne(r);
124
- for (const [n, s] of Object.entries(t))
125
- s && e.set(n, s);
126
- }
127
- const Ue = /^[^\s@]+@[^\s@]+\.[^\s@]+$/, De = 254;
128
- function se(e) {
129
- var t;
130
- if (typeof e != "string" || !e)
131
- return { valid: !1, error: "Email is required" };
132
- const r = e.trim().toLowerCase();
133
- return Ue.test(r) ? r.length > De ? { valid: !1, error: "Email is too long" } : r.includes("..") || r.startsWith(".") || r.endsWith(".") ? { valid: !1, error: "Invalid email format" } : (t = r.split("@")[1]) != null && t.includes("..") ? { valid: !1, error: "Invalid email format" } : { valid: !0, sanitized: r } : { valid: !1, error: "Invalid email format" };
134
- }
135
- function ie(e) {
136
- return e.valid === !0 && e.sanitized !== void 0;
137
- }
138
- const Fe = /* @__PURE__ */ new Set([
139
- "password",
140
- "12345678",
141
- "qwerty",
142
- "abc123",
143
- "password123",
144
- "123456789",
145
- "1234567890",
146
- "letmein",
147
- "welcome",
148
- "monkey",
149
- "dragon",
150
- "master",
151
- "sunshine",
152
- "princess",
153
- "football",
154
- "admin",
155
- "root",
156
- "test",
157
- "guest",
158
- "user"
159
- ]), Le = /012|123|234|345|456|567|678|789|abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz/i, Ve = 8, Me = 128;
160
- function ft(e, r = Ve) {
161
- if (typeof e != "string" || !e)
162
- return { valid: !1, error: "Password is required" };
163
- if (e.length < r)
164
- return { valid: !1, error: `Password must be at least ${r} characters` };
165
- if (e.length > Me)
166
- return { valid: !1, error: "Password is too long" };
167
- const t = e.toLowerCase();
168
- if (Fe.has(t))
169
- return { valid: !1, error: "Password is too common" };
170
- if (/(.)\1{3,}/.test(e))
171
- return { valid: !1, error: "Password contains too many repeated characters" };
172
- if (Le.test(e))
173
- return { valid: !1, error: "Password contains sequential characters" };
174
- const n = je(e);
175
- return { valid: !0, sanitized: e, strength: n };
176
- }
177
- function je(e) {
178
- let r = 0;
179
- return e.length >= 12 ? r += 2 : e.length >= 8 && (r += 1), /[a-z]/.test(e) && (r += 1), /[A-Z]/.test(e) && (r += 1), /[0-9]/.test(e) && (r += 1), /[^a-zA-Z0-9]/.test(e) && (r += 1), r >= 5 ? "strong" : r >= 3 ? "medium" : "weak";
180
- }
181
- function dt(e) {
182
- return e.valid === !0 && e.sanitized !== void 0;
183
- }
184
- const ze = 100;
185
- function ht(e) {
186
- if (typeof e != "string" || !e)
187
- return { valid: !1, error: "Name is required" };
188
- const r = e.trim();
189
- if (r.length < 1)
190
- return { valid: !1, error: "Name cannot be empty" };
191
- if (r.length > ze)
192
- return { valid: !1, error: "Name is too long" };
193
- const t = r.replace(/[<>"']/g, "");
194
- return t.length === 0 ? { valid: !1, error: "Name contains only invalid characters" } : { valid: !0, sanitized: t };
195
- }
196
- function gt(e) {
197
- return e.valid === !0 && e.sanitized !== void 0;
198
- }
199
- const Be = /* @__PURE__ */ new Set(["http:", "https:"]);
200
- function wt(e) {
201
- if (typeof e != "string" || !e)
202
- return { valid: !1, error: "URL is required" };
203
- try {
204
- const r = new URL(e);
205
- return Be.has(r.protocol) ? { valid: !0, sanitized: e } : { valid: !1, error: "URL must use http or https protocol" };
206
- } catch {
207
- return { valid: !1, error: "Invalid URL format" };
208
- }
209
- }
210
- function pt(e) {
211
- return e.valid === !0 && e.sanitized !== void 0;
212
- }
213
- const $e = 16, He = 512, qe = /^[A-Za-z0-9_-]+$/;
214
- function mt(e, r = $e) {
215
- return typeof e != "string" || !e ? { valid: !1, error: "Token is required" } : e.length < r ? { valid: !1, error: "Token is too short" } : e.length > He ? { valid: !1, error: "Token is too long" } : qe.test(e) ? /(.)\1{10,}/.test(e) ? { valid: !1, error: "Token contains suspicious pattern" } : { valid: !0, sanitized: e } : { valid: !1, error: "Invalid token format" };
216
- }
217
- function Et(e) {
218
- return e.valid === !0 && e.sanitized !== void 0;
219
- }
220
- const We = 1e3;
221
- function oe(e, r) {
222
- const { maxLength: t = We, allowHtml: n = !1, required: s = !0 } = r ?? {};
223
- if (s && (typeof e != "string" || !e || e.trim().length === 0))
224
- return { valid: !1, error: "Input is required" };
225
- if (typeof e != "string" || !e)
226
- return { valid: !0, sanitized: "" };
227
- let i = e.trim();
228
- return i.length > t ? { valid: !1, error: `Input must be less than ${t} characters` } : (n || (i = i.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;").replace(/\//g, "&#x2F;")), i = i.replace(/[\x00-\x1F\x7F]/g, ""), { valid: !0, sanitized: i });
229
- }
230
- function yt(e) {
231
- return e.valid === !0 && e.sanitized !== void 0;
232
- }
233
- class Ge {
234
- constructor() {
235
- x(this, "tokens", /* @__PURE__ */ new Map());
236
- }
237
- get(r) {
238
- const t = this.tokens.get(r);
239
- return t ? t.expiresAt < Date.now() ? (this.delete(r), null) : t.value : null;
240
- }
241
- set(r, t, n = 36e5) {
242
- this.tokens.set(r, {
243
- value: t,
244
- expiresAt: Date.now() + n
245
- });
246
- }
247
- delete(r) {
248
- this.tokens.delete(r);
249
- }
250
- clear() {
251
- this.tokens.clear();
252
- }
253
- }
254
- class Ke {
255
- constructor(r, t = 32) {
256
- x(this, "store");
257
- x(this, "tokenLength");
258
- this.store = r || new Ge(), this.tokenLength = t;
259
- }
260
- /**
261
- * Generate CSRF token
262
- */
263
- generateToken(r, t) {
264
- const n = ce(this.tokenLength);
265
- return this.store.set(r, n, t), n;
266
- }
267
- /**
268
- * Validate CSRF token
269
- */
270
- validateToken(r, t) {
271
- const n = this.store.get(r);
272
- if (!n)
273
- return !1;
274
- const s = le(t, n);
275
- return s && this.store.delete(r), s;
276
- }
277
- /**
278
- * Get stored token without validating
279
- */
280
- getToken(r) {
281
- return this.store.get(r);
282
- }
283
- /**
284
- * Delete token
285
- */
286
- deleteToken(r) {
287
- this.store.delete(r);
288
- }
289
- }
290
- function kt(e) {
291
- return new Ke(e);
292
- }
293
- function Xe(e) {
294
- if (typeof e != "string")
295
- return "";
296
- const r = {
297
- "&": "&amp;",
298
- "<": "&lt;",
299
- ">": "&gt;",
300
- '"': "&quot;",
301
- "'": "&#039;"
302
- };
303
- return e.replace(/[&<>"']/g, (t) => r[t] || t);
304
- }
305
- function vt(e) {
306
- return typeof e != "string" ? "" : e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "").replace(/on\w+\s*=\s*["'][^"']*["']/gi, "").replace(/javascript:/gi, "");
307
- }
308
- function St(e) {
309
- return typeof e != "string" ? "" : Xe(e.trim());
310
- }
311
- function At(e) {
312
- return typeof e != "string" ? !1 : [
313
- /<script/i,
314
- /javascript:/i,
315
- /on\w+\s*=/i,
316
- /<iframe/i,
317
- /<object/i,
318
- /<embed/i,
319
- /<link/i,
320
- /<meta/i,
321
- /expression\s*\(/i,
322
- /vbscript:/i
323
- ].some((t) => t.test(e));
324
- }
325
- const ae = 32;
326
- function ce(e = ae) {
327
- if (e < 1 || e > 256)
328
- throw new Error("Token length must be between 1 and 256 bytes");
329
- const r = te(e);
330
- return Buffer.from(r).toString("base64url");
331
- }
332
- function ue() {
333
- return ce(ae);
334
- }
335
- function le(e, r) {
336
- if (typeof e != "string" || typeof r != "string" || !e || !r || e.length !== r.length)
337
- return !1;
338
- let t = 0;
339
- for (let n = 0; n < e.length; n++)
340
- t |= e.charCodeAt(n) ^ r.charCodeAt(n);
341
- return t === 0;
342
- }
343
- function Rt(e, r) {
344
- return le(e, r);
345
- }
346
- function Ot(e) {
347
- return typeof e != "string" ? "" : e.trim().replace(/[<>]/g, "");
348
- }
349
- const Je = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
350
- function Tt(e) {
351
- return typeof e == "string" && Je.test(e);
352
- }
353
- function Ye(e) {
354
- return !e.success && !!e.error;
355
- }
356
- function _t(e) {
357
- return e.requires2FA === !0 || e.errorCode === m.TWO_FA_REQUIRED;
358
- }
359
- function bt(e, r) {
360
- return e.error ? e.error : r || "Authentication failed";
361
- }
362
- function Ct(e) {
363
- return e.errorCode;
364
- }
365
- function It(e) {
366
- return e.success === !0 && !!e.user;
367
- }
368
- function xt(e, r) {
369
- return e.errorCode === r;
370
- }
371
- function Pt(e) {
372
- if (!Ye(e)) return !1;
373
- const r = [
374
- m.NETWORK_ERROR,
375
- m.RATE_LIMITED,
376
- m.UNKNOWN_ERROR
377
- ];
378
- return e.errorCode ? r.includes(e.errorCode) : !1;
379
- }
380
- function Nt(e) {
381
- if (e.error) return e.error;
382
- switch (e.errorCode) {
383
- case m.INVALID_CREDENTIALS:
384
- return "Invalid email or password. Please try again.";
385
- case m.ACCOUNT_LOCKED:
386
- return "Your account has been temporarily locked. Please try again later.";
387
- case m.ACCOUNT_INACTIVE:
388
- return "Your account is inactive. Please contact support.";
389
- case m.TWO_FA_REQUIRED:
390
- return "Two-factor authentication is required. Please enter your code.";
391
- case m.INVALID_TWO_FA_CODE:
392
- return "Invalid two-factor authentication code. Please try again.";
393
- case m.SESSION_EXPIRED:
394
- return "Your session has expired. Please sign in again.";
395
- case m.UNAUTHORIZED:
396
- return "You are not authorized to perform this action.";
397
- case m.NETWORK_ERROR:
398
- return "Network error. Please check your connection and try again.";
399
- case m.VALIDATION_ERROR:
400
- return "Please check your input and try again.";
401
- case m.RATE_LIMITED:
402
- return "Too many attempts. Please try again later.";
403
- case m.UNKNOWN_ERROR:
404
- default:
405
- return "An unexpected error occurred. Please try again.";
406
- }
407
- }
408
- async function Ut(e, r, t) {
409
- return r === "credentials" ? !t || !("email" in t) || !("password" in t) ? {
410
- success: !1,
411
- error: "Credentials are required"
412
- } : e.signIn("credentials", t) : r === "otp" ? !t || !("email" in t) ? {
413
- success: !1,
414
- error: "Email is required"
415
- } : e.signIn("otp", t) : r === "passkey" ? e.signIn("passkey", t) : e.signIn(r);
416
- }
417
- const fe = {
418
- google: {
419
- authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth",
420
- tokenUrl: "https://oauth2.googleapis.com/token",
421
- userInfoUrl: "https://www.googleapis.com/oauth2/v2/userinfo",
422
- defaultScopes: ["openid", "profile", "email"]
423
- },
424
- github: {
425
- authorizationUrl: "https://github.com/login/oauth/authorize",
426
- tokenUrl: "https://github.com/login/oauth/access_token",
427
- userInfoUrl: "https://api.github.com/user",
428
- defaultScopes: ["user:email"]
429
- },
430
- apple: {
431
- authorizationUrl: "https://appleid.apple.com/auth/authorize",
432
- tokenUrl: "https://appleid.apple.com/auth/token",
433
- userInfoUrl: "https://appleid.apple.com/auth/userinfo",
434
- defaultScopes: ["name", "email"],
435
- defaultParams: {
436
- response_mode: "form_post",
437
- response_type: "code id_token"
438
- }
439
- },
440
- facebook: {
441
- authorizationUrl: "https://www.facebook.com/v18.0/dialog/oauth",
442
- tokenUrl: "https://graph.facebook.com/v18.0/oauth/access_token",
443
- userInfoUrl: "https://graph.facebook.com/v18.0/me?fields=id,name,email,picture",
444
- defaultScopes: ["email", "public_profile"]
445
- }
446
- };
447
- function K(e) {
448
- return fe[e] ?? null;
449
- }
450
- function Dt(e) {
451
- return e in fe;
452
- }
453
- function de(e, r, t, n) {
454
- const s = K(e);
455
- if (!s)
456
- throw new Error(`Unknown OAuth provider: ${e}`);
457
- if (!r.clientId)
458
- throw new Error(`OAuth provider "${e}" is missing clientId`);
459
- const i = r.redirectUri ?? `${t}/api/auth/callback/${e}`, o = r.scopes ?? s.defaultScopes, a = new URLSearchParams({
460
- client_id: r.clientId,
461
- redirect_uri: i,
462
- response_type: "code",
463
- scope: Array.isArray(o) ? o.join(" ") : String(o),
464
- state: n
465
- });
466
- if (s.defaultParams)
467
- for (const [c, u] of Object.entries(s.defaultParams))
468
- a.append(c, u);
469
- if (r.params)
470
- for (const [c, u] of Object.entries(r.params))
471
- a.set(c, u);
472
- return `${s.authorizationUrl}?${a.toString()}`;
473
- }
474
- async function he(e, r, t, n, s) {
475
- const i = K(e);
476
- if (!i)
477
- throw new Error(`Unknown OAuth provider: ${e}`);
478
- if (!t || typeof t != "string")
479
- throw new Error("Authorization code is required");
480
- if (!r.clientId)
481
- throw new Error(`OAuth provider "${e}" is missing clientId`);
482
- const o = new URLSearchParams({
483
- client_id: r.clientId,
484
- code: t,
485
- redirect_uri: n,
486
- grant_type: "authorization_code"
487
- });
488
- s && o.append("code_verifier", s), r.clientSecret && o.append("client_secret", r.clientSecret);
489
- try {
490
- const a = await fetch(i.tokenUrl, {
491
- method: "POST",
492
- headers: {
493
- "Content-Type": "application/x-www-form-urlencoded",
494
- Accept: "application/json"
495
- },
496
- body: o.toString()
497
- });
498
- if (!a.ok) {
499
- const u = await a.text();
500
- let h = `Failed to exchange code for tokens: ${u}`;
501
- try {
502
- const f = JSON.parse(u);
503
- h = f.error_description ?? f.error ?? h;
504
- } catch {
505
- }
506
- throw new Error(h);
507
- }
508
- const c = await a.json();
509
- if (!Qe(c))
510
- throw new Error("Invalid token exchange response format");
511
- return c;
512
- } catch (a) {
513
- throw a instanceof Error ? a : new Error(`OAuth token exchange failed: ${String(a)}`);
514
- }
515
- }
516
- function Qe(e) {
517
- return typeof e == "object" && e !== null && "access_token" in e && typeof e.access_token == "string";
518
- }
519
- async function ge(e, r) {
520
- const t = K(e);
521
- if (!t)
522
- throw new Error(`Unknown OAuth provider: ${e}`);
523
- if (!r || typeof r != "string")
524
- throw new Error("Access token is required");
525
- try {
526
- const n = await fetch(t.userInfoUrl, {
527
- headers: {
528
- Authorization: `Bearer ${r}`,
529
- Accept: "application/json"
530
- }
531
- });
532
- if (!n.ok) {
533
- const i = await n.text();
534
- let o = `Failed to fetch user info: ${i}`;
535
- try {
536
- const a = JSON.parse(i);
537
- o = a.error_description ?? a.error ?? o;
538
- } catch {
539
- }
540
- throw new Error(o);
541
- }
542
- const s = await n.json();
543
- return Ze(e, s, r);
544
- } catch (n) {
545
- throw n instanceof Error ? n : new Error(`OAuth user info retrieval failed: ${String(n)}`);
546
- }
547
- }
548
- async function Ze(e, r, t) {
549
- switch (e) {
550
- case "google":
551
- return er(r);
552
- case "github":
553
- return await rr(r, t);
554
- case "apple":
555
- return tr(r);
556
- case "facebook":
557
- return nr(r);
558
- default:
559
- return sr(r);
560
- }
561
- }
562
- function er(e) {
563
- return {
564
- id: String(e.sub ?? e.id ?? ""),
565
- email: String(e.email ?? ""),
566
- name: String(e.name ?? ""),
567
- avatar: typeof e.picture == "string" ? e.picture : void 0,
568
- emailVerified: !!e.email_verified,
569
- rawProfile: e
570
- };
571
- }
572
- async function rr(e, r) {
573
- let t = typeof e.email == "string" ? e.email : void 0, n = { ...e };
574
- if (!t)
575
- try {
576
- const s = await fetch("https://api.github.com/user/emails", {
577
- headers: { Authorization: `Bearer ${r}` }
578
- });
579
- if (s.ok) {
580
- const i = await s.json(), o = i.find((a) => a.primary) ?? i[0];
581
- t = (o == null ? void 0 : o.email) ?? `${String(e.login ?? "user")}@users.noreply.github.com`, n = { ...e, emails: i };
582
- } else
583
- t = `${String(e.login ?? "user")}@users.noreply.github.com`;
584
- } catch {
585
- t = `${String(e.login ?? "user")}@users.noreply.github.com`;
586
- }
587
- return {
588
- id: String(e.id ?? ""),
589
- email: t ?? "",
590
- name: String(e.name ?? e.login ?? ""),
591
- avatar: typeof e.avatar_url == "string" ? e.avatar_url : void 0,
592
- emailVerified: !!t,
593
- rawProfile: n
594
- };
595
- }
596
- function tr(e) {
597
- const r = e.name, t = r ? `${r.firstName ?? ""} ${r.lastName ?? ""}`.trim() : "";
598
- return {
599
- id: String(e.sub ?? ""),
600
- email: String(e.email ?? ""),
601
- name: t,
602
- emailVerified: !!e.email_verified,
603
- rawProfile: e
604
- };
605
- }
606
- function nr(e) {
607
- var t;
608
- const r = e.picture;
609
- return {
610
- id: String(e.id ?? ""),
611
- email: String(e.email ?? ""),
612
- name: String(e.name ?? ""),
613
- avatar: (t = r == null ? void 0 : r.data) == null ? void 0 : t.url,
614
- emailVerified: !0,
615
- rawProfile: e
616
- };
617
- }
618
- function sr(e) {
619
- return {
620
- id: String(e.id ?? e.sub ?? ""),
621
- email: String(e.email ?? ""),
622
- name: String(e.name ?? e.display_name ?? e.username ?? ""),
623
- avatar: typeof e.avatar == "string" ? e.avatar : typeof e.picture == "string" ? e.picture : typeof e.avatar_url == "string" ? e.avatar_url : void 0,
624
- emailVerified: !!(e.email_verified ?? e.emailVerified ?? !1),
625
- rawProfile: e
626
- };
627
- }
628
- function Ft(e) {
629
- return typeof e == "object" && e !== null && "clientId" in e && typeof e.clientId == "string";
630
- }
631
- function ir(e, r, t, n) {
632
- if (typeof e.setBigUint64 == "function")
633
- return e.setBigUint64(r, t, n);
634
- const s = BigInt(32), i = BigInt(4294967295), o = Number(t >> s & i), a = Number(t & i), c = n ? 4 : 0, u = n ? 0 : 4;
635
- e.setUint32(r + c, o, n), e.setUint32(r + u, a, n);
636
- }
637
- function or(e, r, t) {
638
- return e & r ^ ~e & t;
639
- }
640
- function ar(e, r, t) {
641
- return e & r ^ e & t ^ r & t;
642
- }
643
- class cr extends Ie {
644
- constructor(r, t, n, s) {
645
- super(), this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.blockLen = r, this.outputLen = t, this.padOffset = n, this.isLE = s, this.buffer = new Uint8Array(r), this.view = H(this.buffer);
646
- }
647
- update(r) {
648
- Q(this), r = re(r), G(r);
649
- const { view: t, buffer: n, blockLen: s } = this, i = r.length;
650
- for (let o = 0; o < i; ) {
651
- const a = Math.min(s - this.pos, i - o);
652
- if (a === s) {
653
- const c = H(r);
654
- for (; s <= i - o; o += s)
655
- this.process(c, o);
656
- continue;
657
- }
658
- n.set(r.subarray(o, o + a), this.pos), this.pos += a, o += a, this.pos === s && (this.process(t, 0), this.pos = 0);
659
- }
660
- return this.length += r.length, this.roundClean(), this;
661
- }
662
- digestInto(r) {
663
- Q(this), be(r, this), this.finished = !0;
664
- const { buffer: t, view: n, blockLen: s, isLE: i } = this;
665
- let { pos: o } = this;
666
- t[o++] = 128, q(this.buffer.subarray(o)), this.padOffset > s - o && (this.process(n, 0), o = 0);
667
- for (let f = o; f < s; f++)
668
- t[f] = 0;
669
- ir(n, s - 8, BigInt(this.length * 8), i), this.process(n, 0);
670
- const a = H(r), c = this.outputLen;
671
- if (c % 4)
672
- throw new Error("_sha2: outputLen should be aligned to 32bit");
673
- const u = c / 4, h = this.get();
674
- if (u > h.length)
675
- throw new Error("_sha2: outputLen bigger than state");
676
- for (let f = 0; f < u; f++)
677
- a.setUint32(4 * f, h[f], i);
678
- }
679
- digest() {
680
- const { buffer: r, outputLen: t } = this;
681
- this.digestInto(r);
682
- const n = r.slice(0, t);
683
- return this.destroy(), n;
684
- }
685
- _cloneInto(r) {
686
- r || (r = new this.constructor()), r.set(...this.get());
687
- const { blockLen: t, buffer: n, length: s, finished: i, destroyed: o, pos: a } = this;
688
- return r.destroyed = o, r.finished = i, r.length = s, r.pos = a, s % t && r.buffer.set(n), r;
689
- }
690
- clone() {
691
- return this._cloneInto();
692
- }
693
- }
694
- const N = /* @__PURE__ */ Uint32Array.from([
695
- 1779033703,
696
- 3144134277,
697
- 1013904242,
698
- 2773480762,
699
- 1359893119,
700
- 2600822924,
701
- 528734635,
702
- 1541459225
703
- ]), ur = /* @__PURE__ */ Uint32Array.from([
704
- 1116352408,
705
- 1899447441,
706
- 3049323471,
707
- 3921009573,
708
- 961987163,
709
- 1508970993,
710
- 2453635748,
711
- 2870763221,
712
- 3624381080,
713
- 310598401,
714
- 607225278,
715
- 1426881987,
716
- 1925078388,
717
- 2162078206,
718
- 2614888103,
719
- 3248222580,
720
- 3835390401,
721
- 4022224774,
722
- 264347078,
723
- 604807628,
724
- 770255983,
725
- 1249150122,
726
- 1555081692,
727
- 1996064986,
728
- 2554220882,
729
- 2821834349,
730
- 2952996808,
731
- 3210313671,
732
- 3336571891,
733
- 3584528711,
734
- 113926993,
735
- 338241895,
736
- 666307205,
737
- 773529912,
738
- 1294757372,
739
- 1396182291,
740
- 1695183700,
741
- 1986661051,
742
- 2177026350,
743
- 2456956037,
744
- 2730485921,
745
- 2820302411,
746
- 3259730800,
747
- 3345764771,
748
- 3516065817,
749
- 3600352804,
750
- 4094571909,
751
- 275423344,
752
- 430227734,
753
- 506948616,
754
- 659060556,
755
- 883997877,
756
- 958139571,
757
- 1322822218,
758
- 1537002063,
759
- 1747873779,
760
- 1955562222,
761
- 2024104815,
762
- 2227730452,
763
- 2361852424,
764
- 2428436474,
765
- 2756734187,
766
- 3204031479,
767
- 3329325298
768
- ]), U = /* @__PURE__ */ new Uint32Array(64);
769
- class lr extends cr {
770
- constructor(r = 32) {
771
- super(64, r, 8, !1), this.A = N[0] | 0, this.B = N[1] | 0, this.C = N[2] | 0, this.D = N[3] | 0, this.E = N[4] | 0, this.F = N[5] | 0, this.G = N[6] | 0, this.H = N[7] | 0;
772
- }
773
- get() {
774
- const { A: r, B: t, C: n, D: s, E: i, F: o, G: a, H: c } = this;
775
- return [r, t, n, s, i, o, a, c];
776
- }
777
- // prettier-ignore
778
- set(r, t, n, s, i, o, a, c) {
779
- this.A = r | 0, this.B = t | 0, this.C = n | 0, this.D = s | 0, this.E = i | 0, this.F = o | 0, this.G = a | 0, this.H = c | 0;
780
- }
781
- process(r, t) {
782
- for (let f = 0; f < 16; f++, t += 4)
783
- U[f] = r.getUint32(t, !1);
784
- for (let f = 16; f < 64; f++) {
785
- const y = U[f - 15], E = U[f - 2], v = P(y, 7) ^ P(y, 18) ^ y >>> 3, p = P(E, 17) ^ P(E, 19) ^ E >>> 10;
786
- U[f] = p + U[f - 7] + v + U[f - 16] | 0;
787
- }
788
- let { A: n, B: s, C: i, D: o, E: a, F: c, G: u, H: h } = this;
789
- for (let f = 0; f < 64; f++) {
790
- const y = P(a, 6) ^ P(a, 11) ^ P(a, 25), E = h + y + or(a, c, u) + ur[f] + U[f] | 0, p = (P(n, 2) ^ P(n, 13) ^ P(n, 22)) + ar(n, s, i) | 0;
791
- h = u, u = c, c = a, a = o + E | 0, o = i, i = s, s = n, n = E + p | 0;
792
- }
793
- n = n + this.A | 0, s = s + this.B | 0, i = i + this.C | 0, o = o + this.D | 0, a = a + this.E | 0, c = c + this.F | 0, u = u + this.G | 0, h = h + this.H | 0, this.set(n, s, i, o, a, c, u, h);
794
- }
795
- roundClean() {
796
- q(U);
797
- }
798
- destroy() {
799
- this.set(0, 0, 0, 0, 0, 0, 0, 0), q(this.buffer);
800
- }
801
- }
802
- const fr = /* @__PURE__ */ xe(() => new lr()), dr = fr, we = 43;
803
- function hr(e = we) {
804
- if (e < 43 || e > 128)
805
- throw new Error("Code verifier length must be between 43 and 128 characters");
806
- const r = te(Math.ceil(e * 0.75));
807
- return Buffer.from(r).toString("base64url").substring(0, e);
808
- }
809
- function pe(e) {
810
- if (!e || e.length < 43 || e.length > 128)
811
- throw new Error("Invalid code verifier");
812
- const r = dr(e);
813
- return Buffer.from(r).toString("base64url");
814
- }
815
- function gr(e = we, r = "S256") {
816
- const t = hr(e), n = r === "S256" ? pe(t) : t;
817
- return {
818
- codeVerifier: t,
819
- codeChallenge: n,
820
- codeChallengeMethod: r
821
- };
822
- }
823
- function Lt(e, r, t = "S256") {
824
- if (!e || !r)
825
- return {
826
- valid: !1,
827
- error: "Code verifier and challenge are required"
828
- };
829
- let n;
830
- if (t === "S256")
831
- try {
832
- n = pe(e);
833
- } catch (s) {
834
- return {
835
- valid: !1,
836
- error: s instanceof Error ? s.message : "Failed to generate expected challenge"
837
- };
838
- }
839
- else
840
- n = e;
841
- return wr(r, n) ? { valid: !0 } : {
842
- valid: !1,
843
- error: "Code challenge verification failed"
844
- };
845
- }
846
- function wr(e, r) {
847
- if (e.length !== r.length)
848
- return !1;
849
- let t = 0;
850
- for (let n = 0; n < e.length; n++)
851
- t |= e.charCodeAt(n) ^ r.charCodeAt(n);
852
- return t === 0;
853
- }
854
- class pr {
855
- constructor() {
856
- x(this, "storage", /* @__PURE__ */ new Map());
857
- }
858
- async set(r, t, n) {
859
- this.storage.set(r, {
860
- codeVerifier: t,
861
- expiresAt: Date.now() + n
862
- });
863
- }
864
- async get(r) {
865
- const t = this.storage.get(r);
866
- return t ? t.expiresAt < Date.now() ? (this.storage.delete(r), null) : t.codeVerifier : null;
867
- }
868
- async delete(r) {
869
- this.storage.delete(r);
870
- }
871
- }
872
- const mr = "__mulguard_oauth_state", Er = 10 * 60 * 1e3;
873
- function yr(e) {
874
- const r = e.cookieName || mr, t = e.ttl || Er, n = process.env.NODE_ENV === "production", s = e.secure ?? n, i = e.sameSite || "strict", o = e.cookieHandler, a = (c) => ({
875
- httpOnly: !0,
876
- secure: s,
877
- sameSite: i,
878
- maxAge: Math.floor(c / 1e3),
879
- // Convert to seconds
880
- path: "/"
881
- });
882
- return {
883
- async set(c, u, h) {
884
- const f = JSON.stringify({
885
- state: c,
886
- provider: u.provider,
887
- expiresAt: u.expiresAt
888
- });
889
- await Promise.resolve(
890
- o.setCookie(r, f, a(t))
891
- );
892
- },
893
- async get(c) {
894
- const u = await Promise.resolve(o.getCookie(r));
895
- if (!u)
896
- return null;
897
- try {
898
- const h = JSON.parse(u);
899
- return h.state !== c ? null : h.expiresAt < Date.now() ? (await Promise.resolve(
900
- o.deleteCookie(r, { path: "/" })
901
- ), null) : {
902
- provider: h.provider,
903
- expiresAt: h.expiresAt
904
- };
905
- } catch {
906
- return await Promise.resolve(
907
- o.deleteCookie(r, { path: "/" })
908
- ), null;
909
- }
910
- },
911
- async delete(c) {
912
- await this.get(c) && await Promise.resolve(
913
- o.deleteCookie(r, { path: "/" })
914
- );
915
- },
916
- async cleanup() {
917
- }
918
- };
919
- }
920
- function Vt() {
921
- return yr({
922
- cookieHandler: {
923
- async getCookie(e) {
924
- var r;
925
- try {
926
- const { cookies: t } = await import("next/headers");
927
- return ((r = (await t()).get(e)) == null ? void 0 : r.value) || null;
928
- } catch {
929
- return null;
930
- }
931
- },
932
- async setCookie(e, r, t) {
933
- try {
934
- const { cookies: n } = await import("next/headers");
935
- (await n()).set(e, r, {
936
- httpOnly: t.httpOnly ?? !0,
937
- secure: t.secure ?? process.env.NODE_ENV === "production",
938
- sameSite: t.sameSite || "strict",
939
- maxAge: t.maxAge,
940
- path: t.path || "/"
941
- });
942
- } catch (n) {
943
- console.warn("[Mulguard] Failed to set OAuth state cookie:", n);
944
- }
945
- },
946
- async deleteCookie(e, r) {
947
- try {
948
- const { cookies: t } = await import("next/headers");
949
- (await t()).set(e, "", {
950
- maxAge: 0,
951
- expires: /* @__PURE__ */ new Date(0),
952
- path: (r == null ? void 0 : r.path) || "/"
953
- });
954
- } catch {
955
- }
956
- }
957
- }
958
- });
959
- }
960
- function Mt(e, r = "mulguard:oauth:state:") {
961
- const t = (s) => `${r}${s}`, n = async (s) => {
962
- const i = t(s);
963
- await e.del(i);
964
- };
965
- return {
966
- async set(s, i, o) {
967
- const a = t(s), c = JSON.stringify(i);
968
- await e.set(a, c, "EX", Math.floor(o / 1e3));
969
- },
970
- async get(s) {
971
- const i = t(s), o = await e.get(i);
972
- if (!o)
973
- return null;
974
- try {
975
- const a = JSON.parse(o);
976
- return a.expiresAt < Date.now() ? (await n(s), null) : a;
977
- } catch {
978
- return await n(s), null;
979
- }
980
- },
981
- async delete(s) {
982
- await n(s);
983
- },
984
- async cleanup() {
985
- try {
986
- const s = await e.keys(`${r}*`), i = Date.now();
987
- for (const o of s) {
988
- const a = await e.get(o);
989
- if (a)
990
- try {
991
- JSON.parse(a).expiresAt < i && await e.del(o);
992
- } catch {
993
- await e.del(o);
994
- }
995
- }
996
- } catch (s) {
997
- console.warn("[Mulguard] OAuth state cleanup warning:", s);
998
- }
999
- }
1000
- };
1001
- }
1002
- class kr {
1003
- constructor() {
1004
- x(this, "states", /* @__PURE__ */ new Map());
1005
- }
1006
- set(r, t, n) {
1007
- this.states.set(r, t), this.cleanup();
1008
- }
1009
- get(r) {
1010
- const t = this.states.get(r);
1011
- return t ? t.expiresAt < Date.now() ? (this.delete(r), null) : t : null;
1012
- }
1013
- delete(r) {
1014
- this.states.delete(r);
1015
- }
1016
- cleanup() {
1017
- const r = Date.now();
1018
- for (const [t, n] of this.states.entries())
1019
- n.expiresAt < r && this.states.delete(t);
1020
- }
1021
- }
1022
- function vr() {
1023
- return new kr();
1024
- }
1025
- class Sr {
1026
- constructor(r) {
1027
- x(this, "config");
1028
- x(this, "pkceStorage");
1029
- var t, n;
1030
- this.config = {
1031
- ...r,
1032
- pkce: {
1033
- enabled: ((t = r.pkce) == null ? void 0 : t.enabled) ?? !0,
1034
- // PKCE enabled by default
1035
- storage: (n = r.pkce) == null ? void 0 : n.storage
1036
- },
1037
- stateStore: r.stateStore,
1038
- logger: r.logger
1039
- }, this.pkceStorage = this.config.pkce.enabled ? this.config.pkce.storage || new pr() : null;
1040
- }
1041
- /**
1042
- * Initiates OAuth authentication flow.
1043
- *
1044
- * Generates authorization URL with PKCE (if enabled) and CSRF state token.
1045
- *
1046
- * @param providerId - OAuth provider identifier
1047
- * @returns OAuth initiation result with authorization URL and state
1048
- *
1049
- * @example
1050
- * ```typescript
1051
- * const { url, state, codeVerifier } = await handler.initiate('google')
1052
- * // Store state and codeVerifier securely
1053
- * // Redirect user to url
1054
- * ```
1055
- */
1056
- async initiate(r) {
1057
- const t = this.config.providers[r];
1058
- if (!t)
1059
- throw new Error(`OAuth provider "${r}" is not configured`);
1060
- const n = ue();
1061
- let s, i;
1062
- if (this.config.pkce.enabled && this.pkceStorage) {
1063
- const a = gr();
1064
- s = a.codeVerifier, i = a.codeChallenge, await this.pkceStorage.set(n, s, 10 * 60 * 1e3);
1065
- }
1066
- const o = de(
1067
- r,
1068
- {
1069
- ...t,
1070
- params: {
1071
- ...t.params,
1072
- ...i && {
1073
- code_challenge: i,
1074
- code_challenge_method: "S256"
1075
- }
1076
- }
1077
- },
1078
- this.config.baseUrl,
1079
- n
1080
- );
1081
- return this.config.stateStore && await this.config.stateStore.set(n, {
1082
- provider: r,
1083
- expiresAt: Date.now() + 10 * 60 * 1e3
1084
- // 10 minutes
1085
- }, 10 * 60 * 1e3), {
1086
- url: o,
1087
- state: n,
1088
- ...s && { codeVerifier: s }
1089
- };
1090
- }
1091
- /**
1092
- * Handles OAuth callback and completes authentication.
1093
- *
1094
- * Validates state token, verifies PKCE (if enabled), exchanges code for tokens,
1095
- * retrieves user profile, and creates session.
1096
- *
1097
- * @template TUser - User type
1098
- * @template TSession - Session type
1099
- * @param providerId - OAuth provider identifier
1100
- * @param code - Authorization code from OAuth callback
1101
- * @param state - CSRF state token
1102
- * @param codeVerifier - PKCE code verifier (required if PKCE is enabled)
1103
- * @param userLookup - Function to lookup/create user from OAuth profile
1104
- * @param createSession - Function to create session (optional)
1105
- * @returns Authentication result
1106
- *
1107
- * @example
1108
- * ```typescript
1109
- * const result = await handler.handleCallback(
1110
- * 'google',
1111
- * code,
1112
- * state,
1113
- * storedCodeVerifier,
1114
- * async (userInfo) => {
1115
- * // Lookup or create user
1116
- * return await db.user.findOrCreate({ email: userInfo.email })
1117
- * }
1118
- * )
1119
- * ```
1120
- */
1121
- async handleCallback(r, t, n, s, i, o) {
1122
- try {
1123
- if (!t || !n)
1124
- return {
1125
- success: !1,
1126
- error: "Authorization code and state are required",
1127
- errorCode: m.VALIDATION_ERROR
1128
- };
1129
- if (!await this.validateState(n, r))
1130
- return {
1131
- success: !1,
1132
- error: "Invalid or expired state token",
1133
- errorCode: m.VALIDATION_ERROR
1134
- };
1135
- const c = this.config.providers[r];
1136
- if (!c)
1137
- return {
1138
- success: !1,
1139
- error: `OAuth provider "${r}" is not configured`,
1140
- errorCode: m.VALIDATION_ERROR
1141
- };
1142
- if (this.config.pkce.enabled && this.pkceStorage) {
1143
- const p = s || await this.pkceStorage.get(n);
1144
- if (!p)
1145
- return {
1146
- success: !1,
1147
- error: "PKCE code verifier not found",
1148
- errorCode: m.VALIDATION_ERROR
1149
- };
1150
- s = p;
1151
- }
1152
- const u = c.redirectUri || `${this.config.baseUrl}/api/auth/callback/${r}`;
1153
- let h;
1154
- try {
1155
- h = await he(r, c, t, u, s);
1156
- } catch (p) {
1157
- return this.config.logger && this.config.logger.error("OAuth token exchange failed", p), {
1158
- success: !1,
1159
- error: p instanceof Error ? p.message : "Token exchange failed",
1160
- errorCode: m.NETWORK_ERROR
1161
- };
1162
- }
1163
- let f;
1164
- try {
1165
- f = await ge(r, h.access_token);
1166
- } catch (p) {
1167
- return this.config.logger && this.config.logger.error("OAuth user profile retrieval failed", p), {
1168
- success: !1,
1169
- error: "Failed to retrieve user profile",
1170
- errorCode: m.NETWORK_ERROR
1171
- };
1172
- }
1173
- const y = {
1174
- id: f.id,
1175
- email: f.email,
1176
- name: f.name,
1177
- avatar: f.avatar,
1178
- emailVerified: f.emailVerified,
1179
- provider: r,
1180
- accessToken: h.access_token,
1181
- refreshToken: h.refresh_token,
1182
- tokens: h,
1183
- rawProfile: f.rawProfile
1184
- };
1185
- let E;
1186
- i ? E = await i(y) : E = {
1187
- id: y.id,
1188
- email: y.email,
1189
- name: y.name,
1190
- avatar: y.avatar,
1191
- emailVerified: y.emailVerified
1192
- };
1193
- const v = o ? await o(E, y) : {
1194
- user: E,
1195
- expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3),
1196
- // 7 days
1197
- accessToken: h.access_token,
1198
- refreshToken: h.refresh_token,
1199
- tokenType: h.token_type || "Bearer",
1200
- expiresIn: h.expires_in
1201
- };
1202
- return this.config.pkce.enabled && this.pkceStorage && await this.pkceStorage.delete(n), {
1203
- success: !0,
1204
- user: E,
1205
- session: v
1206
- };
1207
- } catch (a) {
1208
- return this.config.logger && this.config.logger.error("OAuth callback error", a), {
1209
- success: !1,
1210
- error: a instanceof Error ? a.message : "OAuth callback failed",
1211
- errorCode: m.UNKNOWN_ERROR
1212
- };
1213
- }
1214
- }
1215
- // ============================================================================
1216
- // State Validation
1217
- // ============================================================================
1218
- /**
1219
- * Validates OAuth state token.
1220
- *
1221
- * @param state - State token
1222
- * @param providerId - Provider identifier
1223
- * @returns True if state is valid
1224
- */
1225
- async validateState(r, t) {
1226
- if (this.config.stateStore) {
1227
- const n = await this.config.stateStore.get(r);
1228
- return n ? n.expiresAt < Date.now() ? (await this.config.stateStore.delete(r), !1) : n.provider !== t ? !1 : (await this.config.stateStore.delete(r), !0) : !1;
1229
- }
1230
- return !0;
1231
- }
1232
- }
1233
- function jt(e) {
1234
- return new Sr(e);
1235
- }
1236
- function M(e) {
1237
- return e.success === !0 && e.user !== void 0 && e.session !== void 0;
1238
- }
1239
- var V = /* @__PURE__ */ ((e) => (e[e.DEBUG = 0] = "DEBUG", e[e.INFO = 1] = "INFO", e[e.WARN = 2] = "WARN", e[e.ERROR = 3] = "ERROR", e))(V || {});
1240
- const Ar = process.env.NODE_ENV === "development" ? 0 : 1;
1241
- function me(e = {}) {
1242
- const {
1243
- enabled: r = process.env.NODE_ENV === "development",
1244
- level: t = Ar,
1245
- context: n,
1246
- formatter: s = Rr
1247
- } = e, i = (a) => r && a >= t, o = (a, c, u, h) => ({
1248
- level: a,
1249
- message: c,
1250
- timestamp: /* @__PURE__ */ new Date(),
1251
- context: n,
1252
- data: u ? Or(u) : void 0,
1253
- error: h
1254
- });
1255
- return {
1256
- debug: (a, c) => {
1257
- if (i(
1258
- 0
1259
- /* DEBUG */
1260
- )) {
1261
- const u = o(0, a, c);
1262
- console.debug(s(u));
1263
- }
1264
- },
1265
- info: (a, c) => {
1266
- if (i(
1267
- 1
1268
- /* INFO */
1269
- )) {
1270
- const u = o(1, a, c);
1271
- console.info(s(u));
1272
- }
1273
- },
1274
- warn: (a, c) => {
1275
- if (i(
1276
- 2
1277
- /* WARN */
1278
- )) {
1279
- const u = o(2, a, c);
1280
- console.warn(s(u));
1281
- }
1282
- },
1283
- error: (a, c) => {
1284
- if (i(
1285
- 3
1286
- /* ERROR */
1287
- )) {
1288
- const u = c instanceof Error ? c : void 0, h = c instanceof Error ? void 0 : c, f = o(3, a, h, u);
1289
- console.error(s(f)), u && console.error(u);
1290
- }
1291
- }
1292
- };
1293
- }
1294
- function Rr(e) {
1295
- const r = e.timestamp.toISOString(), t = V[e.level], n = e.context ? `[${e.context}]` : "", s = e.data ? ` ${JSON.stringify(e.data)}` : "";
1296
- return `${r} [${t}]${n} ${e.message}${s}`;
1297
- }
1298
- function Or(e) {
1299
- const r = /* @__PURE__ */ new Set(["password", "token", "secret", "key", "accessToken", "refreshToken"]), t = {};
1300
- for (const [n, s] of Object.entries(e))
1301
- if (r.has(n.toLowerCase()))
1302
- t[n] = "***REDACTED***";
1303
- else if (typeof s == "string" && n.toLowerCase().includes("email")) {
1304
- const i = s.split("@");
1305
- if (i.length === 2 && i[0]) {
1306
- const o = i[0].substring(0, 3) + "***@" + i[1];
1307
- t[n] = o;
1308
- } else
1309
- t[n] = s;
1310
- } else
1311
- t[n] = s;
1312
- return t;
1313
- }
1314
- me();
1315
- function Ee(e = {}) {
1316
- return me(e);
1317
- }
1318
- function Tr(e = {}) {
1319
- try {
1320
- const r = require("pino"), t = {
1321
- level: e.level !== void 0 ? V[e.level].toLowerCase() : "info",
1322
- base: e.context ? { context: e.context } : void 0,
1323
- timestamp: !0
1324
- }, n = r(t);
1325
- return {
1326
- debug: (s, i) => {
1327
- n.debug(i || {}, s);
1328
- },
1329
- info: (s, i) => {
1330
- n.info(i || {}, s);
1331
- },
1332
- warn: (s, i) => {
1333
- n.warn(i || {}, s);
1334
- },
1335
- error: (s, i) => {
1336
- i instanceof Error ? n.error({ err: i }, s) : n.error(i || {}, s);
1337
- }
1338
- };
1339
- } catch {
1340
- return Ee(e);
1341
- }
1342
- }
1343
- function _r(e = {}) {
1344
- const { adapter: r = "console", ...t } = e;
1345
- let n;
1346
- if (typeof r == "string")
1347
- switch (r) {
1348
- case "pino":
1349
- n = Tr(t);
1350
- break;
1351
- case "console":
1352
- default:
1353
- n = Ee(t);
1354
- break;
1355
- }
1356
- else
1357
- n = r;
1358
- return n;
1359
- }
1360
- const _ = _r({
1361
- adapter: process.env.MULGUARD_LOGGER_ADAPTER || "console",
1362
- level: process.env.NODE_ENV === "production" ? V.WARN : V.DEBUG
1363
- });
1364
- function br(e, r, t, n = {}) {
1365
- const {
1366
- enabled: s = !0,
1367
- maxRetries: i = 1,
1368
- retryDelay: o = 1e3,
1369
- rateLimit: a = 3,
1370
- autoSignOutOnFailure: c = !0,
1371
- redirectToLogin: u = "/login",
1372
- autoRedirectOnFailure: h = !0
1373
- } = n;
1374
- let f = null, y = !1;
1375
- const E = [], v = [], p = 60 * 1e3;
1376
- let w = 0, T = !1, b = null;
1377
- const j = 2, z = 60 * 1e3;
1378
- function l() {
1379
- const S = Date.now();
1380
- if (T && b) {
1381
- if (S < b)
1382
- return !1;
1383
- T = !1, b = null, w = 0;
1384
- }
1385
- for (; v.length > 0; ) {
1386
- const k = v[0];
1387
- if (k !== void 0 && k < S - p)
1388
- v.shift();
1389
- else
1390
- break;
1391
- }
1392
- return v.length >= a ? !1 : (v.push(S), !0);
1393
- }
1394
- function d() {
1395
- w++, w >= j && (T = !0, b = Date.now() + z, process.env.NODE_ENV === "development" && console.warn("[TokenRefreshManager] Circuit breaker opened - too many consecutive failures"));
1396
- }
1397
- function g() {
1398
- w = 0, T = !1, b = null;
1399
- }
1400
- async function R(S = 1) {
1401
- if (!s)
1402
- return null;
1403
- if (!l())
1404
- throw new Error("Rate limit exceeded for token refresh");
1405
- try {
1406
- const k = await e();
1407
- if (k)
1408
- return g(), C(k), n.onTokenRefreshed && await Promise.resolve(n.onTokenRefreshed(k)), k;
1409
- if (d(), S < i)
1410
- return await J(o * S), R(S + 1);
1411
- throw new Error("Token refresh failed: refresh function returned null");
1412
- } catch (k) {
1413
- if (d(), S < i && I(k))
1414
- return await J(o * S), R(S + 1);
1415
- throw k;
1416
- }
1417
- }
1418
- function I(S) {
1419
- if (S instanceof Error) {
1420
- const k = S.message.toLowerCase();
1421
- if (k.includes("rate limit") || k.includes("too many requests") || k.includes("429") || k.includes("limit:") || k.includes("requests per minute") || k.includes("token_blacklisted") || k.includes("blacklisted") || k.includes("invalid") || k.includes("401") || k.includes("unauthorized") || k.includes("session has been revoked") || k.includes("session expired"))
1422
- return !1;
1423
- if (k.includes("network") || k.includes("fetch") || k.includes("timeout"))
1424
- return !0;
1425
- }
1426
- return !1;
1427
- }
1428
- function C(S) {
1429
- const k = [...E];
1430
- E.length = 0;
1431
- for (const { resolve: D } of k)
1432
- D(S);
1433
- }
1434
- function X(S) {
1435
- const k = [...E];
1436
- E.length = 0;
1437
- for (const { reject: D } of k)
1438
- D(S);
1439
- }
1440
- function J(S) {
1441
- return new Promise((k) => setTimeout(k, S));
1442
- }
1443
- async function Y(S) {
1444
- try {
1445
- if (n.onTokenRefreshFailed && await Promise.resolve(n.onTokenRefreshFailed(S)), c && (await t(), await r(), h && typeof window < "u")) {
1446
- let k = !0;
1447
- if (n.onBeforeRedirect && (k = await Promise.resolve(n.onBeforeRedirect(S))), k) {
1448
- const D = new URL(u, window.location.origin);
1449
- D.searchParams.set("reason", "session_expired"), D.searchParams.set("redirect", window.location.pathname + window.location.search), window.location.href = D.toString();
1450
- }
1451
- }
1452
- } catch (k) {
1453
- process.env.NODE_ENV === "development" && console.error("[TokenRefreshManager] Error in handleRefreshFailure:", k);
1454
- }
1455
- }
1456
- return {
1457
- /**
1458
- * Refresh token with single refresh queue
1459
- */
1460
- async refreshToken() {
1461
- return s ? f || (y = !0, f = R().then((S) => (y = !1, f = null, S)).catch((S) => {
1462
- throw y = !1, f = null, X(S), Y(S).catch(() => {
1463
- }), S;
1464
- }), f) : null;
1465
- },
1466
- /**
1467
- * Check if refresh is in progress
1468
- */
1469
- isRefreshing() {
1470
- return y;
1471
- },
1472
- /**
1473
- * Wait for current refresh to complete
1474
- */
1475
- async waitForRefresh() {
1476
- return f ? new Promise((S, k) => {
1477
- E.push({ resolve: S, reject: k });
1478
- }) : null;
1479
- },
1480
- /**
1481
- * Clear state
1482
- */
1483
- clear() {
1484
- f = null, y = !1, v.length = 0, g(), X(new Error("Token refresh manager cleared"));
1485
- },
1486
- /**
1487
- * Handle token refresh failure
1488
- */
1489
- async handleRefreshFailure(S) {
1490
- return Y(S);
1491
- }
1492
- };
1493
- }
1494
- function Cr() {
1495
- const e = process.env.NODE_ENV === "production";
1496
- return {
1497
- cookieName: "__mulguard_session",
1498
- expiresIn: 60 * 60 * 24 * 7,
1499
- // 7 days
1500
- httpOnly: !0,
1501
- secure: e,
1502
- // HTTPS only in production
1503
- sameSite: "lax",
1504
- path: "/"
1505
- };
1506
- }
1507
- function Ir() {
1508
- return {
1509
- enabled: !0,
1510
- refreshThreshold: 300,
1511
- // 5 minutes before expiration
1512
- maxRetries: 0,
1513
- // No retries for blacklisted tokens
1514
- retryDelay: 1e3,
1515
- rateLimit: 1,
1516
- // 1 attempt per minute to prevent loops
1517
- autoSignOutOnFailure: !0,
1518
- redirectToLogin: "/login",
1519
- autoRedirectOnFailure: !0
1520
- };
1521
- }
1522
- function xr() {
1523
- return process.env.NEXT_PUBLIC_URL ?? (process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : "http://localhost:3000");
1524
- }
1525
- function Pr(e) {
1526
- const { sessionConfig: r, cacheTtl: t, getSessionAction: n, onSessionExpired: s, onError: i } = e, o = r.cookieName ?? "__mulguard_session";
1527
- let a = null;
1528
- const c = async () => {
1529
- const p = Date.now();
1530
- if (a && p - a.timestamp < t)
1531
- return a.session;
1532
- if (n)
1533
- try {
1534
- const w = await n();
1535
- if (w && F(w))
1536
- return a = { session: w, timestamp: p }, w;
1537
- w && !F(w) && (await h(), a = null);
1538
- } catch (w) {
1539
- _.debug("getSession error", { error: w }), i && await i(w instanceof Error ? w : new Error(String(w)), "getSession"), a = null;
1540
- }
1541
- try {
1542
- const w = await Te(o);
1543
- if (w)
1544
- try {
1545
- const T = JSON.parse(w);
1546
- if (F(T))
1547
- return T.expiresAt && new Date(T.expiresAt) < /* @__PURE__ */ new Date() ? (s && await s(T), await h(), a = null, null) : (a = { session: T, timestamp: p }, T);
1548
- await h(), a = null;
1549
- } catch {
1550
- await h(), a = null;
1551
- }
1552
- } catch (w) {
1553
- const T = w instanceof Error ? w.message : String(w);
1554
- !T.includes("request scope") && !T.includes("cookies") && (_.warn("getSession cookie error", { error: w }), i && await i(
1555
- w instanceof Error ? w : new Error(String(w)),
1556
- "getSession.cookie"
1557
- ));
1558
- }
1559
- return null;
1560
- }, u = async (p) => {
1561
- if (!F(p))
1562
- return {
1563
- success: !1,
1564
- error: "Invalid session structure"
1565
- };
1566
- try {
1567
- const w = typeof p == "object" && "token" in p ? String(p.token) : JSON.stringify(p), T = Re(o, w, r), b = await Oe(T);
1568
- return b.success && (a = { session: p, timestamp: Date.now() }), b;
1569
- } catch (w) {
1570
- const T = w instanceof Error ? w.message : "Failed to set session";
1571
- return _.error("setSession error", { error: w }), i && await i(w instanceof Error ? w : new Error(String(w)), "setSession"), {
1572
- success: !1,
1573
- error: T
1574
- };
1575
- }
1576
- }, h = async () => {
1577
- try {
1578
- await Ae(o, {
1579
- path: r.path,
1580
- domain: r.domain
1581
- }), a = null;
1582
- } catch (p) {
1583
- _.warn("clearSessionCookie error", { error: p });
1584
- }
1585
- }, f = async () => {
1586
- const p = await c();
1587
- return p != null && p.accessToken && typeof p.accessToken == "string" ? p.accessToken : null;
1588
- };
1589
- return {
1590
- getSession: c,
1591
- setSession: u,
1592
- clearSessionCookie: h,
1593
- getAccessToken: f,
1594
- getRefreshToken: async () => {
1595
- const p = await c();
1596
- return p != null && p.refreshToken && typeof p.refreshToken == "string" ? p.refreshToken : null;
1597
- },
1598
- hasValidTokens: async () => !!await f(),
1599
- clearCache: () => {
1600
- a = null;
1601
- },
1602
- getSessionConfig: () => ({ cookieName: o, config: r })
1603
- };
1604
- }
1605
- function Nr(e) {
1606
- return async (r) => {
1607
- try {
1608
- if (!r || typeof r != "object")
1609
- return {
1610
- success: !1,
1611
- error: "Invalid credentials",
1612
- errorCode: m.VALIDATION_ERROR
1613
- };
1614
- if (!r.email || typeof r.email != "string")
1615
- return {
1616
- success: !1,
1617
- error: "Email is required",
1618
- errorCode: m.VALIDATION_ERROR
1619
- };
1620
- const t = se(r.email);
1621
- if (!ie(t))
1622
- return {
1623
- success: !1,
1624
- error: t.error ?? "Invalid email format",
1625
- errorCode: m.VALIDATION_ERROR
1626
- };
1627
- if (!r.password || typeof r.password != "string")
1628
- return {
1629
- success: !1,
1630
- error: "Password is required",
1631
- errorCode: m.VALIDATION_ERROR
1632
- };
1633
- if (r.password.length > 128)
1634
- return {
1635
- success: !1,
1636
- error: "Invalid credentials",
1637
- errorCode: m.VALIDATION_ERROR
1638
- };
1639
- const n = {
1640
- email: t.sanitized,
1641
- password: r.password
1642
- // Don't sanitize password (needed for hashing)
1643
- }, s = await e.actions.signIn.email(n);
1644
- if (M(s)) {
1645
- const i = await e.saveSessionAfterAuth(s);
1646
- !i.success && i.warning && _.warn("Session save warning", { warning: i.warning });
1647
- }
1648
- return s.success ? _.info("Sign in successful", {
1649
- email: n.email.substring(0, 3) + "***"
1650
- }) : _.warn("Sign in failed", {
1651
- email: n.email.substring(0, 3) + "***",
1652
- errorCode: s.errorCode
1653
- }), s;
1654
- } catch (t) {
1655
- const n = t instanceof Error ? t.message : "Sign in failed";
1656
- return _.error("Sign in error", { error: n, context: "signIn.email" }), e.onError && await e.onError(
1657
- t instanceof Error ? t : new Error(String(t)),
1658
- "signIn.email"
1659
- ), {
1660
- success: !1,
1661
- error: "Sign in failed. Please try again.",
1662
- errorCode: m.UNKNOWN_ERROR
1663
- };
1664
- }
1665
- };
1666
- }
1667
- function Ur(e, r) {
1668
- return async (t) => {
1669
- if (!t || typeof t != "string")
1670
- throw new Error("Provider is required");
1671
- const n = oe(t, {
1672
- maxLength: 50,
1673
- allowHtml: !1,
1674
- required: !0
1675
- });
1676
- if (!n.valid || !n.sanitized)
1677
- throw new Error("Invalid provider");
1678
- const s = n.sanitized.toLowerCase();
1679
- if (!e.actions.signIn.oauth)
1680
- throw new Error(
1681
- "OAuth sign in is not configured. Either provide oauth action in signIn, or configure providers.oauth in config."
1682
- );
1683
- const i = await e.actions.signIn.oauth(s);
1684
- return await r(i.state, s), _.info("OAuth sign in initiated", { provider: s }), i;
1685
- };
1686
- }
1687
- function Dr(e) {
1688
- return async (r, t) => {
1689
- if (!r || typeof r != "string")
1690
- return {
1691
- success: !1,
1692
- error: "Email is required",
1693
- errorCode: m.VALIDATION_ERROR
1694
- };
1695
- const n = se(r);
1696
- if (!ie(n))
1697
- return {
1698
- success: !1,
1699
- error: n.error ?? "Invalid email format",
1700
- errorCode: m.VALIDATION_ERROR
1701
- };
1702
- if (t !== void 0 && (typeof t != "string" || t.length < 4 || t.length > 10))
1703
- return {
1704
- success: !1,
1705
- error: "Invalid OTP code format",
1706
- errorCode: m.VALIDATION_ERROR
1707
- };
1708
- if (!e.actions.signIn.otp)
1709
- return {
1710
- success: !1,
1711
- error: "OTP sign in is not configured",
1712
- errorCode: m.VALIDATION_ERROR
1713
- };
1714
- try {
1715
- const s = await e.actions.signIn.otp(n.sanitized, t);
1716
- if (M(s)) {
1717
- const i = await e.saveSessionAfterAuth(s);
1718
- !i.success && i.warning && _.warn("Session save warning", { warning: i.warning });
1719
- }
1720
- return s.success ? _.info("OTP sign in successful", {
1721
- email: n.sanitized.substring(0, 3) + "***"
1722
- }) : _.warn("OTP sign in failed", {
1723
- email: n.sanitized.substring(0, 3) + "***"
1724
- }), s;
1725
- } catch (s) {
1726
- return _.error("OTP sign in error", {
1727
- error: s instanceof Error ? s.message : "Unknown error",
1728
- context: "signIn.otp"
1729
- }), e.onError && await e.onError(
1730
- s instanceof Error ? s : new Error(String(s)),
1731
- "signIn.otp"
1732
- ), {
1733
- success: !1,
1734
- error: "OTP sign in failed. Please try again.",
1735
- errorCode: m.UNKNOWN_ERROR
1736
- };
1737
- }
1738
- };
1739
- }
1740
- function Fr(e) {
1741
- return async (r) => {
1742
- if (!e.actions.signIn.passkey)
1743
- throw new Error("PassKey sign in is not configured. Provide passkey action in signIn.");
1744
- try {
1745
- const t = await e.actions.signIn.passkey(r);
1746
- if (M(t)) {
1747
- const n = await e.saveSessionAfterAuth(t);
1748
- !n.success && n.warning && _.warn("Session save warning", { warning: n.warning });
1749
- }
1750
- return t;
1751
- } catch (t) {
1752
- return e.onError && await e.onError(
1753
- t instanceof Error ? t : new Error(String(t)),
1754
- "signIn.passkey"
1755
- ), {
1756
- success: !1,
1757
- error: t instanceof Error ? t.message : "PassKey sign in failed"
1758
- };
1759
- }
1760
- };
1761
- }
1762
- function Lr(e, r) {
1763
- const t = Nr(e), n = Ur(e, r), s = Dr(e), i = Fr(e);
1764
- return Object.assign(async (c, u) => {
1765
- if (!c || typeof c != "string")
1766
- throw new Error("Provider is required");
1767
- const h = oe(c, {
1768
- maxLength: 50,
1769
- allowHtml: !1,
1770
- required: !0
1771
- });
1772
- if (!h.valid || !h.sanitized)
1773
- throw new Error("Invalid provider");
1774
- const f = h.sanitized.toLowerCase();
1775
- if (f === "google" || f === "github" || f === "apple" || f === "facebook" || typeof f == "string" && !["credentials", "otp", "passkey"].includes(f))
1776
- return n(f);
1777
- if (f === "credentials")
1778
- return !u || !("email" in u) || !("password" in u) ? {
1779
- success: !1,
1780
- error: "Credentials are required",
1781
- errorCode: m.VALIDATION_ERROR
1782
- } : t(u);
1783
- if (f === "otp") {
1784
- if (!u || !("email" in u))
1785
- return {
1786
- success: !1,
1787
- error: "Email is required",
1788
- errorCode: m.VALIDATION_ERROR
1789
- };
1790
- const y = u;
1791
- return s(y.email, y.code);
1792
- }
1793
- return f === "passkey" ? i(u) : {
1794
- success: !1,
1795
- error: "Invalid provider",
1796
- errorCode: m.VALIDATION_ERROR
1797
- };
1798
- }, {
1799
- email: t,
1800
- oauth: e.actions.signIn.oauth ? n : void 0,
1801
- passkey: e.actions.signIn.passkey ? i : void 0,
1802
- otp: e.actions.signIn.otp ? s : void 0
1803
- });
1804
- }
1805
- function Vr(e) {
1806
- return async (r) => {
1807
- if (!e.actions.signUp)
1808
- throw new Error("Sign up is not configured. Provide signUp action in config.");
1809
- try {
1810
- const t = await e.actions.signUp(r);
1811
- if (M(t)) {
1812
- const n = await e.saveSessionAfterAuth(t);
1813
- !n.success && n.warning && _.warn("Session save warning", { warning: n.warning });
1814
- }
1815
- return t;
1816
- } catch (t) {
1817
- return e.onError && await e.onError(
1818
- t instanceof Error ? t : new Error(String(t)),
1819
- "signUp"
1820
- ), {
1821
- success: !1,
1822
- error: t instanceof Error ? t.message : "Sign up failed"
1823
- };
1824
- }
1825
- };
1826
- }
1827
- function Mr(e, r) {
1828
- return async (t, n, s) => {
1829
- const i = e.oauthProviders[t];
1830
- if (!i)
1831
- return {
1832
- success: !1,
1833
- error: `OAuth provider "${t}" is not configured`,
1834
- errorCode: m.VALIDATION_ERROR
1835
- };
1836
- try {
1837
- const o = i.redirectUri ?? `${e.baseUrl}/api/auth/callback/${t}`, a = await he(t, i, n, o), c = await ge(t, a.access_token), u = {
1838
- id: c.id,
1839
- email: c.email,
1840
- name: c.name,
1841
- avatar: c.avatar,
1842
- emailVerified: c.emailVerified,
1843
- provider: t,
1844
- accessToken: a.access_token,
1845
- refreshToken: a.refresh_token,
1846
- tokens: {
1847
- access_token: a.access_token,
1848
- refresh_token: a.refresh_token,
1849
- expires_in: a.expires_in,
1850
- token_type: a.token_type,
1851
- id_token: a.id_token
1852
- },
1853
- rawProfile: c.rawProfile
1854
- };
1855
- if (e.callbacks.onOAuthUser) {
1856
- const h = await Z(
1857
- e.callbacks.onOAuthUser,
1858
- [u, t],
1859
- e.onError
1860
- );
1861
- if (!h)
1862
- return {
1863
- success: !1,
1864
- error: "Failed to create or retrieve user",
1865
- errorCode: m.VALIDATION_ERROR
1866
- };
1867
- const f = e.createSession(h, u, a);
1868
- return await e.saveSession(f), e.callbacks.onSignIn && await Z(
1869
- e.callbacks.onSignIn,
1870
- [f.user, f],
1871
- e.onError
1872
- ), { success: !0, user: f.user, session: f };
1873
- }
1874
- return {
1875
- success: !1,
1876
- error: "OAuth user callback not implemented. Provide onOAuthUser callback or implement oauthCallback action.",
1877
- errorCode: m.VALIDATION_ERROR
1878
- };
1879
- } catch (o) {
1880
- return _.error("OAuth callback failed", { provider: t, error: o }), {
1881
- success: !1,
1882
- error: o instanceof Error ? o.message : "OAuth callback failed",
1883
- errorCode: m.NETWORK_ERROR
1884
- };
1885
- }
1886
- };
1887
- }
1888
- async function Z(e, r, t) {
1889
- if (e)
1890
- try {
1891
- return await e(...r);
1892
- } catch (n) {
1893
- throw t && await t(
1894
- n instanceof Error ? n : new Error(String(n)),
1895
- "callback"
1896
- ), n;
1897
- }
1898
- }
1899
- function jr(e, r, t, n) {
1900
- if (Object.keys(e).length !== 0)
1901
- return async (s) => {
1902
- const i = e[s];
1903
- if (!i)
1904
- throw new Error(`OAuth provider "${s}" is not configured. Add it to providers.oauth in config.`);
1905
- if (!i.clientId)
1906
- throw new Error(`OAuth provider "${s}" is missing clientId`);
1907
- const o = t();
1908
- return { url: n(s, i, r, o), state: o };
1909
- };
1910
- }
1911
- function zt(e) {
1912
- var j, z;
1913
- const r = {
1914
- ...Cr(),
1915
- ...e.session
1916
- }, t = e.actions, n = e.callbacks || {}, s = ((j = e.providers) == null ? void 0 : j.oauth) || {}, i = xr(), o = {
1917
- ...Ir(),
1918
- ...e.tokenRefresh
1919
- }, a = ((z = e.session) == null ? void 0 : z.cacheTtl) ?? e.sessionCacheTtl ?? 5e3, c = e.oauthStateStore || vr(), u = { ...t }, h = async (l, d) => {
1920
- const g = {
1921
- provider: d,
1922
- expiresAt: Date.now() + 6e5
1923
- // 10 minutes
1924
- };
1925
- await Promise.resolve(c.set(l, g, 10 * 60 * 1e3)), c.cleanup && await Promise.resolve(c.cleanup());
1926
- }, f = async (l, d) => {
1927
- let g = await Promise.resolve(c.get(l));
1928
- if (!g)
1929
- try {
1930
- const { getOAuthStateCookie: R } = await import("../oauth-state-pdypStuS.mjs").then((C) => C.o), I = await R();
1931
- if (I && I.state === l && I.provider === d)
1932
- return !0;
1933
- } catch {
1934
- }
1935
- return g ? g.expiresAt < Date.now() ? (await Promise.resolve(c.delete(l)), !1) : g.provider !== d ? !1 : (await Promise.resolve(c.delete(l)), !0) : !1;
1936
- }, y = jr(
1937
- s,
1938
- i,
1939
- ue,
1940
- de
1941
- );
1942
- if (y && !u.signIn.oauth) {
1943
- const l = u.signIn;
1944
- u.signIn = {
1945
- ...l,
1946
- oauth: async (d) => {
1947
- const g = await y(d);
1948
- return await h(g.state, d), g;
1949
- }
1950
- };
1951
- }
1952
- if (!u.signIn || !u.signIn.email)
1953
- throw new Error("mulguard: signIn.email action is required");
1954
- const E = async (l, ...d) => {
1955
- if (l)
1956
- try {
1957
- return await l(...d);
1958
- } catch (g) {
1959
- throw n.onError && await n.onError(g instanceof Error ? g : new Error(String(g)), "callback"), g;
1960
- }
1961
- }, v = Pr({
1962
- sessionConfig: r,
1963
- cacheTtl: a,
1964
- getSessionAction: t.getSession,
1965
- onSessionExpired: n.onSessionExpired,
1966
- onError: n.onError
1967
- }), p = async (l) => {
1968
- if (!M(l) || !l.session)
1969
- return { success: !0 };
1970
- const d = await v.setSession(l.session);
1971
- return l.user && n.onSignIn && await E(n.onSignIn, l.user, l.session), d;
1972
- };
1973
- if (Object.keys(s).length > 0 && !u.oauthCallback) {
1974
- const l = Mr(
1975
- {
1976
- oauthProviders: s,
1977
- baseUrl: i,
1978
- callbacks: n,
1979
- createSession: (d, g, R) => ({
1980
- user: {
1981
- ...d,
1982
- avatar: g.avatar,
1983
- emailVerified: g.emailVerified
1984
- },
1985
- expiresAt: new Date(Date.now() + (r.expiresIn || 604800) * 1e3),
1986
- accessToken: R.access_token,
1987
- refreshToken: R.refresh_token,
1988
- tokenType: "Bearer",
1989
- expiresIn: R.expires_in
1990
- }),
1991
- saveSession: async (d) => {
1992
- await v.setSession(d);
1993
- },
1994
- onError: n.onError
1995
- }
1996
- );
1997
- u.oauthCallback = l;
1998
- }
1999
- const w = Lr(
2000
- {
2001
- actions: u,
2002
- callbacks: n,
2003
- saveSessionAfterAuth: p,
2004
- onError: n.onError
2005
- },
2006
- h
2007
- ), T = Vr({
2008
- actions: u,
2009
- callbacks: n,
2010
- saveSessionAfterAuth: p,
2011
- onError: n.onError
2012
- }), b = {
2013
- /**
2014
- * Get current session
2015
- * Uses custom getSession action if provided, otherwise falls back to reading from cookie
2016
- */
2017
- async getSession() {
2018
- return await v.getSession();
2019
- },
2020
- /**
2021
- * Get access token from current session
2022
- */
2023
- async getAccessToken() {
2024
- return await v.getAccessToken();
2025
- },
2026
- /**
2027
- * Get refresh token from current session
2028
- */
2029
- async getRefreshToken() {
2030
- return await v.getRefreshToken();
2031
- },
2032
- /**
2033
- * Check if session has valid tokens
2034
- */
2035
- async hasValidTokens() {
2036
- return await v.hasValidTokens();
2037
- },
2038
- /**
2039
- * Unified sign in method - supports both unified and direct method calls
2040
- */
2041
- signIn: w,
2042
- /**
2043
- * Sign up new user
2044
- */
2045
- async signUp(l) {
2046
- if (!T)
2047
- throw new Error("Sign up is not configured. Provide signUp action in config.");
2048
- return await T(l);
2049
- },
2050
- /**
2051
- * Sign out
2052
- */
2053
- async signOut() {
2054
- try {
2055
- const l = await this.getSession(), d = l == null ? void 0 : l.user;
2056
- return t.signOut && await t.signOut(), await v.clearSessionCookie(), v.clearCache(), d && n.onSignOut && await E(n.onSignOut, d), { success: !0 };
2057
- } catch (l) {
2058
- return await v.clearSessionCookie(), v.clearCache(), n.onError && await E(n.onError, l instanceof Error ? l : new Error(String(l)), "signOut"), {
2059
- success: !1,
2060
- error: l instanceof Error ? l.message : "Sign out failed"
2061
- };
2062
- }
2063
- },
2064
- /**
2065
- * Request password reset
2066
- */
2067
- async resetPassword(l) {
2068
- if (!t.resetPassword)
2069
- throw new Error("Password reset is not configured. Provide resetPassword action in config.");
2070
- try {
2071
- return await t.resetPassword(l);
2072
- } catch (d) {
2073
- return n.onError && await E(n.onError, d instanceof Error ? d : new Error(String(d)), "resetPassword"), {
2074
- success: !1,
2075
- error: d instanceof Error ? d.message : "Password reset failed"
2076
- };
2077
- }
2078
- },
2079
- /**
2080
- * Verify email address
2081
- */
2082
- async verifyEmail(l) {
2083
- if (!t.verifyEmail)
2084
- throw new Error("Email verification is not configured. Provide verifyEmail action in config.");
2085
- try {
2086
- return await t.verifyEmail(l);
2087
- } catch (d) {
2088
- return n.onError && await E(n.onError, d instanceof Error ? d : new Error(String(d)), "verifyEmail"), {
2089
- success: !1,
2090
- error: d instanceof Error ? d.message : "Email verification failed"
2091
- };
2092
- }
2093
- },
2094
- /**
2095
- * Refresh session
2096
- * Executes custom refreshSession action with improved error handling and callbacks
2097
- */
2098
- async refreshSession() {
2099
- if (!t.refreshSession)
2100
- return this.getSession();
2101
- try {
2102
- const l = await t.refreshSession();
2103
- if (l && F(l)) {
2104
- if (await v.setSession(l), n.onSessionUpdate) {
2105
- const d = await E(n.onSessionUpdate, l);
2106
- if (d && F(d)) {
2107
- if (await v.setSession(d), n.onTokenRefresh) {
2108
- const g = await this.getSession();
2109
- g && await E(n.onTokenRefresh, g, d);
2110
- }
2111
- return d;
2112
- }
2113
- }
2114
- if (n.onTokenRefresh) {
2115
- const d = await this.getSession();
2116
- d && await E(n.onTokenRefresh, d, l);
2117
- }
2118
- return l;
2119
- } else if (l && !F(l))
2120
- return await v.clearSessionCookie(), v.clearCache(), null;
2121
- return null;
2122
- } catch (l) {
2123
- return await v.clearSessionCookie(), v.clearCache(), n.onError && await E(n.onError, l instanceof Error ? l : new Error(String(l)), "refreshSession"), null;
2124
- }
2125
- },
2126
- /**
2127
- * OAuth callback handler
2128
- * ✅ Auto-generated if providers.oauth is configured in config
2129
- */
2130
- async oauthCallback(l, d, g) {
2131
- if (!u.oauthCallback)
2132
- throw new Error(
2133
- "OAuth callback is not configured. Either provide oauthCallback action, or configure providers.oauth in config."
2134
- );
2135
- if (!d || !g)
2136
- return {
2137
- success: !1,
2138
- error: "Missing required OAuth parameters (code or state)",
2139
- errorCode: m.VALIDATION_ERROR
2140
- };
2141
- let R = l;
2142
- if (!R) {
2143
- const C = await Promise.resolve(c.get(g));
2144
- if (C && C.provider)
2145
- R = C.provider;
2146
- else
2147
- return {
2148
- success: !1,
2149
- error: "Provider is required and could not be extracted from state",
2150
- errorCode: m.VALIDATION_ERROR
2151
- };
2152
- }
2153
- if (!await f(g, R))
2154
- return {
2155
- success: !1,
2156
- error: "Invalid or expired state parameter",
2157
- errorCode: m.VALIDATION_ERROR
2158
- };
2159
- try {
2160
- return await u.oauthCallback(R, d, g);
2161
- } catch (C) {
2162
- return n.onError && await E(n.onError, C instanceof Error ? C : new Error(String(C)), "oauthCallback"), {
2163
- success: !1,
2164
- error: C instanceof Error ? C.message : "OAuth callback failed",
2165
- errorCode: m.NETWORK_ERROR
2166
- };
2167
- }
2168
- },
2169
- /**
2170
- * Verify 2FA code after initial sign in
2171
- * Used when signIn returns requires2FA: true
2172
- */
2173
- async verify2FA(l, d) {
2174
- if (!t.verify2FA)
2175
- throw new Error("2FA verification is not configured. Provide verify2FA action in config.");
2176
- try {
2177
- const g = await t.verify2FA(l);
2178
- if (g.success && g.session && !(d != null && d.skipCookieSave)) {
2179
- const R = await p(g);
2180
- R.success || (process.env.NODE_ENV === "development" && _.debug("Failed to save session cookie after verify2FA", {
2181
- error: R.error,
2182
- warning: R.warning
2183
- }), n.onError && await E(
2184
- n.onError,
2185
- new Error(R.warning || R.error || "Failed to save session cookie"),
2186
- "verify2FA.setSession"
2187
- ));
2188
- }
2189
- return g;
2190
- } catch (g) {
2191
- return n.onError && await E(n.onError, g instanceof Error ? g : new Error(String(g)), "verify2FA"), {
2192
- success: !1,
2193
- error: g instanceof Error ? g.message : "2FA verification failed",
2194
- errorCode: m.TWO_FA_REQUIRED
2195
- };
2196
- }
2197
- },
2198
- /**
2199
- * Set session directly
2200
- * Useful for Server Actions that need to save session manually
2201
- */
2202
- async setSession(l) {
2203
- return await v.setSession(l);
2204
- },
2205
- /**
2206
- * Internal method to get session config for Server Actions
2207
- * Used by verify2FAAction to save session cookie directly
2208
- * @internal
2209
- */
2210
- _getSessionConfig() {
2211
- return v.getSessionConfig();
2212
- },
2213
- _getCallbacks() {
2214
- return n;
2215
- },
2216
- /**
2217
- * Store OAuth state for validation (useful when using external backend API)
2218
- * This allows storing state generated by backend APIs in mulguard's state store
2219
- *
2220
- * @param state - OAuth state token
2221
- * @param provider - OAuth provider name
2222
- */
2223
- async storeOAuthState(l, d) {
2224
- await h(l, d);
2225
- },
2226
- /**
2227
- * PassKey methods
2228
- */
2229
- passkey: t.passkey ? {
2230
- register: t.passkey.register,
2231
- authenticate: async (l) => {
2232
- var d;
2233
- if (!((d = t.passkey) != null && d.authenticate))
2234
- throw new Error("PassKey authenticate is not configured.");
2235
- try {
2236
- const g = await t.passkey.authenticate(l);
2237
- return g.success && g.session && await p(g), g;
2238
- } catch (g) {
2239
- return n.onError && await E(n.onError, g instanceof Error ? g : new Error(String(g)), "passkey.authenticate"), {
2240
- success: !1,
2241
- error: g instanceof Error ? g.message : "PassKey authentication failed"
2242
- };
2243
- }
2244
- },
2245
- list: t.passkey.list ? async () => {
2246
- var d;
2247
- if (!((d = t.passkey) != null && d.list))
2248
- throw new Error("PassKey list is not configured.");
2249
- return [...await t.passkey.list()];
2250
- } : void 0,
2251
- remove: t.passkey.remove
2252
- } : void 0,
2253
- /**
2254
- * Two-Factor Authentication methods
2255
- */
2256
- twoFactor: t.twoFactor ? {
2257
- enable: t.twoFactor.enable,
2258
- verify: t.twoFactor.verify,
2259
- disable: t.twoFactor.disable,
2260
- generateBackupCodes: t.twoFactor.generateBackupCodes,
2261
- isEnabled: t.twoFactor.isEnabled,
2262
- verify2FA: async (l) => {
2263
- var g;
2264
- const d = ((g = t.twoFactor) == null ? void 0 : g.verify2FA) || t.verify2FA;
2265
- if (!d)
2266
- throw new Error("2FA verification is not configured. Provide verify2FA action in config.");
2267
- try {
2268
- const R = await d(l);
2269
- if (R.success && R.session) {
2270
- const I = await p(R);
2271
- I.success || (process.env.NODE_ENV === "development" && _.debug("Failed to save session cookie after twoFactor.verify2FA", {
2272
- error: I.error,
2273
- warning: I.warning
2274
- }), n.onError && await E(
2275
- n.onError,
2276
- new Error(I.warning || I.error || "Failed to save session cookie"),
2277
- "twoFactor.verify2FA.setSession"
2278
- ));
2279
- }
2280
- return R;
2281
- } catch (R) {
2282
- return n.onError && await E(n.onError, R instanceof Error ? R : new Error(String(R)), "twoFactor.verify2FA"), {
2283
- success: !1,
2284
- error: R instanceof Error ? R.message : "2FA verification failed",
2285
- errorCode: m.UNKNOWN_ERROR
2286
- };
2287
- }
2288
- }
2289
- } : void 0,
2290
- /**
2291
- * Sign in methods - alias for signIn (for backward compatibility)
2292
- */
2293
- signInMethods: {
2294
- email: (l) => w.email(l),
2295
- oauth: (l) => {
2296
- var d;
2297
- return ((d = w.oauth) == null ? void 0 : d.call(w, l)) || Promise.reject(new Error("OAuth not configured"));
2298
- },
2299
- passkey: (l) => {
2300
- var d;
2301
- return ((d = w.passkey) == null ? void 0 : d.call(w, l)) || Promise.reject(new Error("Passkey not configured"));
2302
- },
2303
- otp: (l, d) => {
2304
- var g;
2305
- return ((g = w.otp) == null ? void 0 : g.call(w, l, d)) || Promise.reject(new Error("OTP not configured"));
2306
- }
2307
- }
2308
- };
2309
- if (t.refreshSession) {
2310
- const l = br(
2311
- async () => await b.refreshSession(),
2312
- async () => await b.signOut(),
2313
- async () => {
2314
- await v.clearSessionCookie(), v.clearCache();
2315
- },
2316
- {
2317
- ...o,
2318
- onTokenRefreshed: o.onTokenRefreshed,
2319
- onTokenRefreshFailed: o.onTokenRefreshFailed,
2320
- onBeforeRedirect: o.onBeforeRedirect
2321
- }
2322
- );
2323
- b._tokenRefreshManager = l, b._getTokenRefreshManager = () => l;
2324
- }
2325
- return b;
2326
- }
2327
- function W(e) {
2328
- if (!e)
2329
- return e;
2330
- const { accessToken: r, refreshToken: t, ...n } = e;
2331
- return n;
2332
- }
2333
- function Bt(e) {
2334
- return {
2335
- GET: async (r) => ee(r, e, "GET"),
2336
- POST: async (r) => ee(r, e, "POST")
2337
- };
2338
- }
2339
- async function ee(e, r, t) {
2340
- const n = new URL(e.url), s = zr(n.pathname), i = s.split("/").filter(Boolean);
2341
- try {
2342
- return t === "GET" ? await Br(e, r, s, i, n) : t === "POST" ? await $r(e, r, s, i, n) : O("Method not allowed", 405);
2343
- } catch (o) {
2344
- return O(
2345
- o instanceof Error ? o.message : "Request failed",
2346
- 500
2347
- );
2348
- }
2349
- }
2350
- function zr(e) {
2351
- return e.replace(/^\/api\/auth/, "") || "/session";
2352
- }
2353
- async function Br(e, r, t, n, s) {
2354
- if (t === "/session" || t === "/") {
2355
- const i = await r.getSession(), o = W(i);
2356
- return A.json({ session: o });
2357
- }
2358
- return t === "/providers" ? A.json({
2359
- providers: {
2360
- email: !!r.signIn.email,
2361
- oauth: !!r.signIn.oauth,
2362
- passkey: !!r.signIn.passkey
2363
- }
2364
- }) : ye(t, n) ? await ke(e, r, t, n, s, "GET") : O("Not found", 404);
2365
- }
2366
- async function $r(e, r, t, n, s) {
2367
- const i = await Hr(e);
2368
- return t === "/sign-in" || n[0] === "sign-in" ? await Wr(r, i) : t === "/sign-up" || n[0] === "sign-up" ? await Gr(r, i) : t === "/sign-out" || n[0] === "sign-out" ? await Kr(r) : t === "/reset-password" || n[0] === "reset-password" ? await Xr(r, i) : t === "/verify-email" || n[0] === "verify-email" ? await Jr(r, i) : t === "/refresh" || n[0] === "refresh" ? await Yr(r) : ye(t, n) ? await ke(e, r, t, n, s, "POST", i) : t.startsWith("/passkey") ? await Zr(r, t, n, i) : t === "/verify-2fa" || n[0] === "verify-2fa" ? await Qr(r, i) : t.startsWith("/two-factor") ? await et(r, n, i) : O("Not found", 404);
2369
- }
2370
- async function Hr(e) {
2371
- try {
2372
- return await e.json();
2373
- } catch {
2374
- return {};
2375
- }
2376
- }
2377
- function ye(e, r) {
2378
- return e === "/callback" || e.startsWith("/oauth/callback") || r[0] === "oauth" && r[1] === "callback" || r[0] === "callback";
2379
- }
2380
- async function ke(e, r, t, n, s, i, o) {
2381
- if (!r.oauthCallback)
2382
- return i === "GET" ? B(e.url, "oauth_not_configured") : O("OAuth callback is not configured", 400);
2383
- const a = qr(n, s, o), c = (o == null ? void 0 : o.code) ?? s.searchParams.get("code"), u = (o == null ? void 0 : o.state) ?? s.searchParams.get("state");
2384
- if (!c || !u)
2385
- return i === "GET" ? B(e.url, "oauth_missing_params") : O("Missing required OAuth parameters. Code and state are required.", 400);
2386
- try {
2387
- const h = await r.oauthCallback(a ?? "", c, u);
2388
- return i === "GET" ? h.success ? tt(e.url, s.searchParams.get("callbackUrl")) : B(e.url, h.error ?? "oauth_failed") : A.json(h);
2389
- } catch (h) {
2390
- return i === "GET" ? B(e.url, h instanceof Error ? h.message : "oauth_error") : O(h instanceof Error ? h.message : "OAuth callback failed", 500);
2391
- }
2392
- }
2393
- function qr(e, r, t) {
2394
- return t != null && t.provider ? t.provider : e[0] === "callback" && e[1] ? e[1] : e[0] === "oauth" && e[1] === "callback" && e[2] ? e[2] : r.searchParams.get("provider");
2395
- }
2396
- async function Wr(e, r) {
2397
- if (r.provider === "email" && r.email && r.password) {
2398
- const t = {
2399
- email: r.email,
2400
- password: r.password
2401
- }, n = await e.signIn.email(t);
2402
- return A.json(n);
2403
- }
2404
- if (r.provider === "oauth" && r.providerName) {
2405
- if (!e.signIn.oauth)
2406
- return O("OAuth is not configured", 400);
2407
- const t = await e.signIn.oauth(r.providerName);
2408
- return A.json(t);
2409
- }
2410
- if (r.provider === "passkey") {
2411
- if (!e.signIn.passkey)
2412
- return O("PassKey is not configured", 400);
2413
- const t = await e.signIn.passkey(r.options);
2414
- return A.json(t);
2415
- }
2416
- return O("Invalid sign in request", 400);
2417
- }
2418
- async function Gr(e, r) {
2419
- if (!e.signUp)
2420
- return O("Sign up is not configured", 400);
2421
- const t = await e.signUp(r);
2422
- return A.json(t);
2423
- }
2424
- async function Kr(e) {
2425
- const r = await e.signOut();
2426
- return A.json(r);
2427
- }
2428
- async function Xr(e, r) {
2429
- if (!e.resetPassword)
2430
- return O("Password reset is not configured", 400);
2431
- if (!r.email || typeof r.email != "string")
2432
- return O("Email is required", 400);
2433
- const t = await e.resetPassword(r.email);
2434
- return A.json(t);
2435
- }
2436
- async function Jr(e, r) {
2437
- if (!e.verifyEmail)
2438
- return O("Email verification is not configured", 400);
2439
- if (!r.token || typeof r.token != "string")
2440
- return O("Token is required", 400);
2441
- const t = await e.verifyEmail(r.token);
2442
- return A.json(t);
2443
- }
2444
- async function Yr(e) {
2445
- if (!e.refreshSession) {
2446
- const n = await e.getSession(), s = W(n);
2447
- return A.json({ session: s });
2448
- }
2449
- const r = await e.refreshSession(), t = W(r);
2450
- return A.json({ session: t });
2451
- }
2452
- async function Qr(e, r) {
2453
- if (!e.verify2FA)
2454
- return O("2FA verification is not configured", 400);
2455
- if (!r.email || !r.userId || !r.code)
2456
- return O("Missing required parameters. Email, userId, and code are required.", 400);
2457
- const t = {
2458
- email: r.email,
2459
- userId: r.userId,
2460
- code: r.code
2461
- }, n = await e.verify2FA(t);
2462
- return A.json(n);
2463
- }
2464
- async function Zr(e, r, t, n) {
2465
- if (!e.passkey)
2466
- return O("PassKey is not configured", 400);
2467
- const s = t[1];
2468
- if (s === "register" && e.passkey.register) {
2469
- const i = await e.passkey.register(n.options);
2470
- return A.json(i);
2471
- }
2472
- if (s === "list" && e.passkey.list) {
2473
- const i = await e.passkey.list();
2474
- return A.json(i);
2475
- }
2476
- if (s === "remove" && e.passkey.remove) {
2477
- if (!n.passkeyId || typeof n.passkeyId != "string")
2478
- return O("Passkey ID is required", 400);
2479
- const i = await e.passkey.remove(n.passkeyId);
2480
- return A.json(i);
2481
- }
2482
- return O("Invalid Passkey request", 400);
2483
- }
2484
- async function et(e, r, t) {
2485
- if (!e.twoFactor)
2486
- return O("Two-Factor Authentication is not configured", 400);
2487
- const n = r[1];
2488
- if (n === "enable" && e.twoFactor.enable) {
2489
- const s = await e.twoFactor.enable();
2490
- return A.json(s);
2491
- }
2492
- if (n === "verify" && e.twoFactor.verify) {
2493
- if (!t.code || typeof t.code != "string")
2494
- return O("Code is required", 400);
2495
- const s = await e.twoFactor.verify(t.code);
2496
- return A.json(s);
2497
- }
2498
- if (n === "disable" && e.twoFactor.disable) {
2499
- const s = await e.twoFactor.disable();
2500
- return A.json(s);
2501
- }
2502
- if (n === "backup-codes" && e.twoFactor.generateBackupCodes) {
2503
- const s = await e.twoFactor.generateBackupCodes();
2504
- return A.json(s);
2505
- }
2506
- if (n === "is-enabled" && e.twoFactor.isEnabled) {
2507
- const s = await e.twoFactor.isEnabled();
2508
- return A.json({ enabled: s });
2509
- }
2510
- return O("Invalid two-factor request", 400);
2511
- }
2512
- function O(e, r) {
2513
- return A.json(
2514
- {
2515
- success: !1,
2516
- error: e
2517
- },
2518
- { status: r }
2519
- );
2520
- }
2521
- function B(e, r) {
2522
- return A.redirect(new URL(`/login?error=${encodeURIComponent(r)}`, e));
2523
- }
2524
- function rt(e, r) {
2525
- if (!e)
2526
- return null;
2527
- try {
2528
- const t = new URL(e, r), n = new URL(r);
2529
- return t.protocol !== n.protocol || t.hostname !== n.hostname || t.port !== n.port ? (process.env.NODE_ENV === "development" && console.warn("[Mulguard] Blocked redirect to external URL:", e), null) : t.protocol === "javascript:" || t.protocol === "data:" ? (process.env.NODE_ENV === "development" && console.warn("[Mulguard] Blocked dangerous redirect URL:", e), null) : t.pathname + t.search + t.hash;
2530
- } catch {
2531
- return null;
2532
- }
2533
- }
2534
- function tt(e, r) {
2535
- const n = rt(r, e) ?? "/";
2536
- return A.redirect(new URL(n, e));
2537
- }
2538
- function $t(e) {
2539
- return async (r) => {
2540
- const { method: t, nextUrl: n } = r, i = n.pathname.replace(/^\/api\/auth/, "") || "/";
2541
- try {
2542
- let o;
2543
- if (t !== "GET" && t !== "HEAD")
2544
- try {
2545
- o = await r.json();
2546
- } catch {
2547
- }
2548
- const a = Object.fromEntries(n.searchParams.entries()), c = await fetch(
2549
- `${process.env.NEXT_PUBLIC_API_URL || ""}/api/auth${i}${Object.keys(a).length > 0 ? `?${new URLSearchParams(a).toString()}` : ""}`,
2550
- {
2551
- method: t,
2552
- headers: {
2553
- "Content-Type": "application/json",
2554
- ...Object.fromEntries(r.headers.entries())
2555
- },
2556
- body: o ? JSON.stringify(o) : void 0
2557
- }
2558
- ), u = await c.json();
2559
- return A.json(u, {
2560
- status: c.status,
2561
- headers: {
2562
- ...Object.fromEntries(c.headers.entries())
2563
- }
2564
- });
2565
- } catch (o) {
2566
- return console.error("API handler error:", o), A.json(
2567
- {
2568
- success: !1,
2569
- error: o instanceof Error ? o.message : "Internal server error"
2570
- },
2571
- { status: 500 }
2572
- );
2573
- }
2574
- };
2575
- }
2576
- function $(e, r) {
2577
- const t = ne({
2578
- // Customize headers if needed
2579
- "X-Frame-Options": "SAMEORIGIN"
2580
- // Allow same-origin framing
2581
- });
2582
- for (const [n, s] of Object.entries(t))
2583
- s && typeof s == "string" && r.headers.set(n, s);
2584
- return r;
2585
- }
2586
- function nt(e) {
2587
- const {
2588
- auth: r,
2589
- protectedRoutes: t = [],
2590
- // publicRoutes is reserved for future use
2591
- redirectTo: n = "/login",
2592
- redirectIfAuthenticated: s,
2593
- apiPrefix: i = "/api/auth",
2594
- enableSecurityHeaders: o = !0
2595
- } = e;
2596
- return async (a) => {
2597
- const { pathname: c } = a.nextUrl;
2598
- if (c.startsWith(i)) {
2599
- const y = A.next();
2600
- return o ? $(a, y) : y;
2601
- }
2602
- if (c.startsWith("/_next/") || c.startsWith("/api/") || c.match(/\.(ico|png|jpg|jpeg|svg|gif|webp|css|js|woff|woff2|ttf|eot)$/))
2603
- return A.next();
2604
- const u = t.length > 0 ? t.some((y) => c.startsWith(y)) : !1;
2605
- let h = null;
2606
- if (u || s)
2607
- try {
2608
- h = await r.getSession();
2609
- } catch (y) {
2610
- process.env.NODE_ENV === "development" && console.error("Proxy: Failed to get session:", y);
2611
- }
2612
- if (u && !h) {
2613
- const y = a.nextUrl.clone();
2614
- y.pathname = n, y.searchParams.set("callbackUrl", c);
2615
- const E = A.redirect(y);
2616
- return o ? $(a, E) : E;
2617
- }
2618
- if (s && h && (c.startsWith("/login") || c.startsWith("/register") || c.startsWith("/signup") || c.startsWith("/sign-in"))) {
2619
- const E = a.nextUrl.clone();
2620
- E.pathname = s;
2621
- const v = A.redirect(E);
2622
- return o ? $(a, v) : v;
2623
- }
2624
- const f = A.next();
2625
- return o ? $(a, f) : f;
2626
- };
2627
- }
2628
- async function st(e, r) {
2629
- try {
2630
- const t = await e.getSession();
2631
- return t ? (t.user.roles || []).includes(r) : !1;
2632
- } catch {
2633
- return !1;
2634
- }
2635
- }
2636
- function Ht(e, r) {
2637
- const t = nt(e);
2638
- return async (n) => {
2639
- var o;
2640
- const { pathname: s } = n.nextUrl;
2641
- return ((o = e.protectedRoutes) == null ? void 0 : o.some(
2642
- (a) => s.startsWith(a)
2643
- )) && !await st(e.auth, r) ? A.json({ error: "Forbidden" }, { status: 403 }) : t(n);
2644
- };
2645
- }
2646
- export {
2647
- Ke as CSRFProtection,
2648
- Ne as DEFAULT_SECURITY_HEADERS,
2649
- Ge as MemoryCSRFStore,
2650
- kr as MemoryOAuthStateStore,
2651
- pr as MemoryPKCEStorage,
2652
- Sr as OAuthHandler,
2653
- Pe as RateLimiter,
2654
- Qt as SessionExpiredError,
2655
- lt as applySecurityHeaders,
2656
- Re as buildCookieOptions,
2657
- de as buildOAuthAuthorizationUrl,
2658
- st as checkRole,
2659
- At as containsXSSPattern,
2660
- $t as createApiHandler,
2661
- Zt as createAuthenticatedAction,
2662
- kt as createCSRFProtection,
2663
- yr as createCookieOAuthStateStore,
2664
- vr as createMemoryOAuthStateStore,
2665
- Vt as createNextJsCookieOAuthStateStore,
2666
- jt as createOAuthHandler,
2667
- nt as createProxyMiddleware,
2668
- ut as createRateLimiter,
2669
- Mt as createRedisOAuthStateStore,
2670
- Ht as createRoleBasedProxy,
2671
- en as createServerAction,
2672
- Ae as deleteCookie,
2673
- rn as deleteOAuthStateCookie,
2674
- Xe as escapeHTML,
2675
- he as exchangeOAuthCode,
2676
- ue as generateCSRFToken,
2677
- pe as generateCodeChallenge,
2678
- hr as generateCodeVerifier,
2679
- gr as generatePKCECodePair,
2680
- ce as generateToken,
2681
- Te as getCookie,
2682
- tn as getCurrentUser,
2683
- Ct as getErrorCode,
2684
- bt as getErrorMessage,
2685
- nn as getOAuthStateCookie,
2686
- ge as getOAuthUserInfo,
2687
- K as getProviderMetadata,
2688
- ne as getSecurityHeaders,
2689
- sn as getServerSession,
2690
- on as getServerUser,
2691
- an as getSessionTimeUntilExpiry,
2692
- Nt as getUserFriendlyError,
2693
- ge as getUserProfile,
2694
- xt as hasErrorCode,
2695
- Ye as isAuthError,
2696
- It as isAuthSuccess,
2697
- cn as isAuthenticated,
2698
- Ft as isOAuthProviderConfig,
2699
- Pt as isRetryableError,
2700
- un as isSessionExpiredNullable,
2701
- ln as isSessionExpiringSoon,
2702
- fn as isSessionValid,
2703
- Dt as isSupportedProvider,
2704
- _t as isTwoFactorRequired,
2705
- Rt as isValidCSRFToken,
2706
- Tt as isValidEmail,
2707
- yt as isValidInput,
2708
- gt as isValidName,
2709
- dt as isValidPassword,
2710
- Et as isValidToken,
2711
- pt as isValidURL,
2712
- zt as mulguard,
2713
- dn as requireAuth,
2714
- hn as requireRole,
2715
- vt as sanitizeHTML,
2716
- Ot as sanitizeInput,
2717
- St as sanitizeUserInput,
2718
- Oe as setCookie,
2719
- Ut as signIn,
2720
- Gt as signInEmailAction,
2721
- Kt as signOutAction,
2722
- Xt as signUpAction,
2723
- gn as storeOAuthStateCookie,
2724
- Bt as toNextJsHandler,
2725
- se as validateAndSanitizeEmail,
2726
- oe as validateAndSanitizeInput,
2727
- ht as validateAndSanitizeName,
2728
- ft as validateAndSanitizePassword,
2729
- le as validateCSRFToken,
2730
- F as validateSessionStructure,
2731
- mt as validateToken,
2732
- wt as validateURL,
2733
- Jt as verify2FAAction,
2734
- Lt as verifyPKCECode,
2735
- $ as withSecurityHeaders
2736
- };