mulguard 1.1.6 → 1.1.8

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