better-auth 0.7.0 → 0.7.1-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/api.cjs +1 -1
  2. package/dist/api.js +1 -1
  3. package/dist/{chunk-T5ZV4O5D.js → chunk-3KYGESZG.js} +1 -1
  4. package/dist/{chunk-O4235OPJ.cjs → chunk-4CXW2HSQ.cjs} +1 -1
  5. package/dist/{chunk-7GKOOVQP.js → chunk-4KD3N77Y.js} +4 -4
  6. package/dist/chunk-C4UOK2CN.js +1 -0
  7. package/dist/{chunk-OMVC24RE.js → chunk-CX4OQU4M.js} +1 -1
  8. package/dist/{chunk-XJR6RYEY.js → chunk-ECKSI3LF.js} +1 -1
  9. package/dist/{chunk-4RCA3ANL.cjs → chunk-FV4R54EK.cjs} +1 -1
  10. package/dist/chunk-HQJTAUZE.cjs +1 -0
  11. package/dist/chunk-L2NWG4J2.cjs +1 -0
  12. package/dist/chunk-LXL7WUAT.js +1 -0
  13. package/dist/{chunk-DU4AD5NF.cjs → chunk-NA5JFN3P.cjs} +1 -1
  14. package/dist/{chunk-UAH4AUYS.cjs → chunk-RTFC3YX2.cjs} +4 -4
  15. package/dist/{chunk-4O3SREZX.cjs → chunk-UOTC7PMK.cjs} +1 -1
  16. package/dist/{chunk-GEA35WSS.js → chunk-VCUBHXZJ.js} +1 -1
  17. package/dist/client/plugins.cjs +1 -1
  18. package/dist/client/plugins.js +1 -1
  19. package/dist/client.cjs +1 -1
  20. package/dist/client.js +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.js +1 -1
  23. package/dist/oauth2.cjs +1 -1
  24. package/dist/oauth2.js +1 -1
  25. package/dist/plugins.cjs +2 -2
  26. package/dist/plugins.js +1 -1
  27. package/dist/react.cjs +1 -1
  28. package/dist/react.js +1 -1
  29. package/dist/social.cjs +1 -1
  30. package/dist/social.js +1 -1
  31. package/dist/solid.cjs +1 -1
  32. package/dist/solid.js +1 -1
  33. package/dist/svelte.cjs +1 -1
  34. package/dist/svelte.js +1 -1
  35. package/dist/vue.cjs +1 -1
  36. package/dist/vue.js +1 -1
  37. package/package.json +1 -1
  38. package/dist/chunk-KIEUIIFX.js +0 -1
  39. package/dist/chunk-QGRJEIVO.cjs +0 -1
  40. package/dist/chunk-UN6PZ3HT.js +0 -1
  41. package/dist/chunk-WFO5B3ON.cjs +0 -1
package/dist/api.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkUAH4AUYScjs = require('./chunk-UAH4AUYS.cjs');require('./chunk-G6DG5D6F.cjs');require('./chunk-DU4AD5NF.cjs');require('./chunk-WFO5B3ON.cjs');require('./chunk-IYGMQ3UI.cjs');require('./chunk-2FTT4NBS.cjs');require('./chunk-QGRJEIVO.cjs');require('./chunk-V7Z635RZ.cjs');require('./chunk-JLIUR52U.cjs');require('./chunk-6BZ4ST3T.cjs');require('./chunk-J6NPEQIV.cjs');exports.APIError = _chunkUAH4AUYScjs.H; exports.callbackOAuth = _chunkUAH4AUYScjs.q; exports.changeEmail = _chunkUAH4AUYScjs.z; exports.changePassword = _chunkUAH4AUYScjs.w; exports.createAuthEndpoint = _chunkUAH4AUYScjs.c; exports.createAuthMiddleware = _chunkUAH4AUYScjs.b; exports.createEmailVerificationToken = _chunkUAH4AUYScjs.k; exports.deleteUser = _chunkUAH4AUYScjs.y; exports.error = _chunkUAH4AUYScjs.A; exports.forgetPassword = _chunkUAH4AUYScjs.s; exports.forgetPasswordCallback = _chunkUAH4AUYScjs.t; exports.getEndpoints = _chunkUAH4AUYScjs.F; exports.getSession = _chunkUAH4AUYScjs.e; exports.getSessionFromCtx = _chunkUAH4AUYScjs.f; exports.linkSocialAccount = _chunkUAH4AUYScjs.E; exports.listSessions = _chunkUAH4AUYScjs.h; exports.listUserAccounts = _chunkUAH4AUYScjs.D; exports.ok = _chunkUAH4AUYScjs.B; exports.optionsMiddleware = _chunkUAH4AUYScjs.a; exports.originCheckMiddleware = _chunkUAH4AUYScjs.d; exports.resetPassword = _chunkUAH4AUYScjs.u; exports.revokeSession = _chunkUAH4AUYScjs.i; exports.revokeSessions = _chunkUAH4AUYScjs.j; exports.router = _chunkUAH4AUYScjs.G; exports.sendVerificationEmail = _chunkUAH4AUYScjs.l; exports.sessionMiddleware = _chunkUAH4AUYScjs.g; exports.setPassword = _chunkUAH4AUYScjs.x; exports.signInEmail = _chunkUAH4AUYScjs.o; exports.signInOAuth = _chunkUAH4AUYScjs.n; exports.signOut = _chunkUAH4AUYScjs.r; exports.signUpEmail = _chunkUAH4AUYScjs.C; exports.updateUser = _chunkUAH4AUYScjs.v; exports.verifyEmail = _chunkUAH4AUYScjs.m;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkRTFC3YX2cjs = require('./chunk-RTFC3YX2.cjs');require('./chunk-G6DG5D6F.cjs');require('./chunk-NA5JFN3P.cjs');require('./chunk-HQJTAUZE.cjs');require('./chunk-IYGMQ3UI.cjs');require('./chunk-2FTT4NBS.cjs');require('./chunk-L2NWG4J2.cjs');require('./chunk-V7Z635RZ.cjs');require('./chunk-JLIUR52U.cjs');require('./chunk-6BZ4ST3T.cjs');require('./chunk-J6NPEQIV.cjs');exports.APIError = _chunkRTFC3YX2cjs.H; exports.callbackOAuth = _chunkRTFC3YX2cjs.q; exports.changeEmail = _chunkRTFC3YX2cjs.z; exports.changePassword = _chunkRTFC3YX2cjs.w; exports.createAuthEndpoint = _chunkRTFC3YX2cjs.c; exports.createAuthMiddleware = _chunkRTFC3YX2cjs.b; exports.createEmailVerificationToken = _chunkRTFC3YX2cjs.k; exports.deleteUser = _chunkRTFC3YX2cjs.y; exports.error = _chunkRTFC3YX2cjs.A; exports.forgetPassword = _chunkRTFC3YX2cjs.s; exports.forgetPasswordCallback = _chunkRTFC3YX2cjs.t; exports.getEndpoints = _chunkRTFC3YX2cjs.F; exports.getSession = _chunkRTFC3YX2cjs.e; exports.getSessionFromCtx = _chunkRTFC3YX2cjs.f; exports.linkSocialAccount = _chunkRTFC3YX2cjs.E; exports.listSessions = _chunkRTFC3YX2cjs.h; exports.listUserAccounts = _chunkRTFC3YX2cjs.D; exports.ok = _chunkRTFC3YX2cjs.B; exports.optionsMiddleware = _chunkRTFC3YX2cjs.a; exports.originCheckMiddleware = _chunkRTFC3YX2cjs.d; exports.resetPassword = _chunkRTFC3YX2cjs.u; exports.revokeSession = _chunkRTFC3YX2cjs.i; exports.revokeSessions = _chunkRTFC3YX2cjs.j; exports.router = _chunkRTFC3YX2cjs.G; exports.sendVerificationEmail = _chunkRTFC3YX2cjs.l; exports.sessionMiddleware = _chunkRTFC3YX2cjs.g; exports.setPassword = _chunkRTFC3YX2cjs.x; exports.signInEmail = _chunkRTFC3YX2cjs.o; exports.signInOAuth = _chunkRTFC3YX2cjs.n; exports.signOut = _chunkRTFC3YX2cjs.r; exports.signUpEmail = _chunkRTFC3YX2cjs.C; exports.updateUser = _chunkRTFC3YX2cjs.v; exports.verifyEmail = _chunkRTFC3YX2cjs.m;
package/dist/api.js CHANGED
@@ -1 +1 @@
1
- import{A as z,B as A,C as B,D as C,E as D,F as E,G as F,H as G,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,q as p,r as q,s as r,t as s,u as t,v as u,w as v,x as w,y as x,z as y}from"./chunk-7GKOOVQP.js";import"./chunk-GW5UFHUL.js";import"./chunk-XJR6RYEY.js";import"./chunk-UN6PZ3HT.js";import"./chunk-TCBMYTN7.js";import"./chunk-J744ED5S.js";import"./chunk-KIEUIIFX.js";import"./chunk-HZVOBC5R.js";import"./chunk-FAFRRPOC.js";import"./chunk-RBJV2U7C.js";import"./chunk-72JSMFWS.js";export{G as APIError,p as callbackOAuth,y as changeEmail,v as changePassword,c as createAuthEndpoint,b as createAuthMiddleware,k as createEmailVerificationToken,x as deleteUser,z as error,r as forgetPassword,s as forgetPasswordCallback,E as getEndpoints,e as getSession,f as getSessionFromCtx,D as linkSocialAccount,h as listSessions,C as listUserAccounts,A as ok,a as optionsMiddleware,d as originCheckMiddleware,t as resetPassword,i as revokeSession,j as revokeSessions,F as router,l as sendVerificationEmail,g as sessionMiddleware,w as setPassword,o as signInEmail,n as signInOAuth,q as signOut,B as signUpEmail,u as updateUser,m as verifyEmail};
1
+ import{A as z,B as A,C as B,D as C,E as D,F as E,G as F,H as G,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,q as p,r as q,s as r,t as s,u as t,v as u,w as v,x as w,y as x,z as y}from"./chunk-4KD3N77Y.js";import"./chunk-GW5UFHUL.js";import"./chunk-ECKSI3LF.js";import"./chunk-LXL7WUAT.js";import"./chunk-TCBMYTN7.js";import"./chunk-J744ED5S.js";import"./chunk-C4UOK2CN.js";import"./chunk-HZVOBC5R.js";import"./chunk-FAFRRPOC.js";import"./chunk-RBJV2U7C.js";import"./chunk-72JSMFWS.js";export{G as APIError,p as callbackOAuth,y as changeEmail,v as changePassword,c as createAuthEndpoint,b as createAuthMiddleware,k as createEmailVerificationToken,x as deleteUser,z as error,r as forgetPassword,s as forgetPasswordCallback,E as getEndpoints,e as getSession,f as getSessionFromCtx,D as linkSocialAccount,h as listSessions,C as listUserAccounts,A as ok,a as optionsMiddleware,d as originCheckMiddleware,t as resetPassword,i as revokeSession,j as revokeSessions,F as router,l as sendVerificationEmail,g as sessionMiddleware,w as setPassword,o as signInEmail,n as signInOAuth,q as signOut,B as signUpEmail,u as updateUser,m as verifyEmail};
@@ -1 +1 @@
1
- import{a as b}from"./chunk-KIEUIIFX.js";import"@better-fetch/fetch";import{atom as C,onMount as L}from"nanostores";var A=(e,s,u,c)=>{let n=C({data:null,error:null,isPending:!0,isRefetching:!1}),f=()=>{let a=typeof c=="function"?c({data:n.get().data,error:n.get().error,isPending:n.get().isPending}):c;return u(s,{...a,onSuccess:async i=>{n.set({data:i.data,error:null,isPending:!1,isRefetching:!1}),await a?.onSuccess?.(i)},async onError(i){n.set({error:i.error,data:null,isPending:!1,isRefetching:!1}),await a?.onError?.(i)},async onRequest(i){let r=n.get();n.set({isPending:r.data===null,data:r.data,error:null,isRefetching:!0}),await a?.onRequest?.(i)}})};e=Array.isArray(e)?e:[e];let l=!1;for(let a of e)a.subscribe(()=>{l?f():L(n,()=>(f(),l=!0,()=>{n.off(),a.off()}))});return n};import{atom as W}from"nanostores";function F(e){let s=W(!1);return{session:A(s,"/get-session",e,{method:"GET"}),$sessionSignal:s}}import{createFetch as E}from"@better-fetch/fetch";import"nanostores";import"@better-fetch/fetch";var R={id:"redirect",name:"Redirect",hooks:{onSuccess(e){e.data?.url&&e.data?.redirect&&typeof window<"u"&&window.location&&(window.location.href=e.data.url)}}},S={id:"add-current-url",name:"Add current URL",hooks:{onRequest(e){if(typeof window<"u"&&window.location){let s=new URL(e.url);s.searchParams.set("currentURL",window.location.href),e.url=s}return e}}};var Z=e=>{let s="credentials"in Request.prototype,u=b(e?.baseURL),c=e?.plugins?.flatMap(t=>t.fetchPlugins).filter(t=>t!==void 0)||[],n=E({baseURL:u,...s?{credentials:"include"}:{},method:"GET",...e?.fetchOptions,plugins:e?.disableDefaultFetchPlugins?[...e?.fetchOptions?.plugins||[],...c]:[R,S,...e?.fetchOptions?.plugins||[],...c]}),{$sessionSignal:f,session:l}=F(n),a=e?.plugins||[],i={},r={$sessionSignal:f,session:l},o={"/sign-out":"POST","/revoke-sessions":"POST"},d=[{signal:"$sessionSignal",matcher(t){return t==="/sign-out"||t==="/update-user"||t.startsWith("/sign-in")||t.startsWith("/sign-up")}}];for(let t of a)t.getAtoms&&Object.assign(r,t.getAtoms?.(n)),t.pathMethods&&Object.assign(o,t.pathMethods),t.atomListeners&&d.push(...t.atomListeners);let p={notify:t=>{r[t].set(!r[t].get())},listen:(t,h)=>{r[t].subscribe(h)},atoms:r};for(let t of a)t.getActions&&Object.assign(i,t.getActions?.(n,p));return{pluginsActions:i,pluginsAtoms:r,pluginPathMethods:o,atomListeners:d,$fetch:n,$store:p}};function U(e,s,u){let c=s[e],{fetchOptions:n,query:f,...l}=u||{};return c||(n?.method?n.method:l&&Object.keys(l).length>0?"POST":"GET")}function J(e,s,u,c,n){function f(l=[]){return new Proxy(function(){},{get(a,i){let r=[...l,i],o=e;for(let d of r)if(o&&typeof o=="object"&&d in o)o=o[d];else{o=void 0;break}return typeof o=="function"?o:f(r)},apply:async(a,i,r)=>{let o="/"+l.map(y=>y.replace(/[A-Z]/g,m=>`-${m.toLowerCase()}`)).join("/"),d=r[0]||{},p=r[1]||{},{query:t,fetchOptions:h,...B}=d,g={...p,...h},O=U(o,u,d);return await s(o,{...g,body:O==="GET"?void 0:{...B,...g?.body||{}},query:t||g?.query,method:O,async onSuccess(y){await g?.onSuccess?.(y);let m=n?.find(w=>w.matcher(o));if(!m)return;let P=c[m.signal];if(!P)return;let T=P.get();setTimeout(()=>{P.set(!T)},10)}})}})}return f()}export{A as a,Z as b,J as c};
1
+ import{a as b}from"./chunk-C4UOK2CN.js";import"@better-fetch/fetch";import{atom as C,onMount as L}from"nanostores";var A=(e,s,u,c)=>{let n=C({data:null,error:null,isPending:!0,isRefetching:!1}),f=()=>{let a=typeof c=="function"?c({data:n.get().data,error:n.get().error,isPending:n.get().isPending}):c;return u(s,{...a,onSuccess:async i=>{n.set({data:i.data,error:null,isPending:!1,isRefetching:!1}),await a?.onSuccess?.(i)},async onError(i){n.set({error:i.error,data:null,isPending:!1,isRefetching:!1}),await a?.onError?.(i)},async onRequest(i){let r=n.get();n.set({isPending:r.data===null,data:r.data,error:null,isRefetching:!0}),await a?.onRequest?.(i)}})};e=Array.isArray(e)?e:[e];let l=!1;for(let a of e)a.subscribe(()=>{l?f():L(n,()=>(f(),l=!0,()=>{n.off(),a.off()}))});return n};import{atom as W}from"nanostores";function F(e){let s=W(!1);return{session:A(s,"/get-session",e,{method:"GET"}),$sessionSignal:s}}import{createFetch as E}from"@better-fetch/fetch";import"nanostores";import"@better-fetch/fetch";var R={id:"redirect",name:"Redirect",hooks:{onSuccess(e){e.data?.url&&e.data?.redirect&&typeof window<"u"&&window.location&&(window.location.href=e.data.url)}}},S={id:"add-current-url",name:"Add current URL",hooks:{onRequest(e){if(typeof window<"u"&&window.location){let s=new URL(e.url);s.searchParams.set("currentURL",window.location.href),e.url=s}return e}}};var Z=e=>{let s="credentials"in Request.prototype,u=b(e?.baseURL),c=e?.plugins?.flatMap(t=>t.fetchPlugins).filter(t=>t!==void 0)||[],n=E({baseURL:u,...s?{credentials:"include"}:{},method:"GET",...e?.fetchOptions,plugins:e?.disableDefaultFetchPlugins?[...e?.fetchOptions?.plugins||[],...c]:[R,S,...e?.fetchOptions?.plugins||[],...c]}),{$sessionSignal:f,session:l}=F(n),a=e?.plugins||[],i={},r={$sessionSignal:f,session:l},o={"/sign-out":"POST","/revoke-sessions":"POST"},d=[{signal:"$sessionSignal",matcher(t){return t==="/sign-out"||t==="/update-user"||t.startsWith("/sign-in")||t.startsWith("/sign-up")}}];for(let t of a)t.getAtoms&&Object.assign(r,t.getAtoms?.(n)),t.pathMethods&&Object.assign(o,t.pathMethods),t.atomListeners&&d.push(...t.atomListeners);let p={notify:t=>{r[t].set(!r[t].get())},listen:(t,h)=>{r[t].subscribe(h)},atoms:r};for(let t of a)t.getActions&&Object.assign(i,t.getActions?.(n,p));return{pluginsActions:i,pluginsAtoms:r,pluginPathMethods:o,atomListeners:d,$fetch:n,$store:p}};function U(e,s,u){let c=s[e],{fetchOptions:n,query:f,...l}=u||{};return c||(n?.method?n.method:l&&Object.keys(l).length>0?"POST":"GET")}function J(e,s,u,c,n){function f(l=[]){return new Proxy(function(){},{get(a,i){let r=[...l,i],o=e;for(let d of r)if(o&&typeof o=="object"&&d in o)o=o[d];else{o=void 0;break}return typeof o=="function"?o:f(r)},apply:async(a,i,r)=>{let o="/"+l.map(y=>y.replace(/[A-Z]/g,m=>`-${m.toLowerCase()}`)).join("/"),d=r[0]||{},p=r[1]||{},{query:t,fetchOptions:h,...B}=d,g={...p,...h},O=U(o,u,d);return await s(o,{...g,body:O==="GET"?void 0:{...B,...g?.body||{}},query:t||g?.query,method:O,async onSuccess(y){await g?.onSuccess?.(y);let m=n?.find(w=>w.matcher(o));if(!m)return;let P=c[m.signal];if(!P)return;let T=P.get();setTimeout(()=>{P.set(!T)},10)}})}})}return f()}export{A as a,Z as b,J as c};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk4O3SREZXcjs = require('./chunk-4O3SREZX.cjs');var R=(t={redirect:!0,twoFactorPage:"/"})=>({id:"two-factor",$InferServerPlugin:{},atomListeners:[{matcher:e=>e.startsWith("/two-factor/"),signal:"$sessionSignal"}],pathMethods:{"/two-factor/disable":"POST","/two-factor/enable":"POST","/two-factor/send-otp":"POST","/two-factor/generate-backup-codes":"POST"},fetchPlugins:[{id:"two-factor",name:"two-factor",hooks:{async onSuccess(e){_optionalChain([e, 'access', _2 => _2.data, 'optionalAccess', _3 => _3.twoFactorRedirect])&&(t.redirect||t.twoFactorPage)&&typeof window<"u"&&(window.location.href=t.twoFactorPage)}}}]});var _browser = require('@simplewebauthn/browser');var _nanostores = require('nanostores');var h=(t,{_listPasskeys:e})=>({signIn:{passkey:async(r,n)=>{let a=await t("/passkey/generate-authenticate-options",{method:"POST",body:{email:_optionalChain([r, 'optionalAccess', _4 => _4.email])}});if(!a.data)return a;try{let s=await _browser.startAuthentication.call(void 0, a.data,_optionalChain([r, 'optionalAccess', _5 => _5.autoFill])||!1),u=await t("/passkey/verify-authentication",{body:{response:s},..._optionalChain([r, 'optionalAccess', _6 => _6.fetchOptions]),...n,method:"POST"});if(!u.data)return u}catch (e2){return{data:null,error:{message:"auth cancelled",status:400,statusText:"BAD_REQUEST"}}}}},passkey:{addPasskey:async(r,n)=>{let a=await t("/passkey/generate-register-options",{method:"GET"});if(!a.data)return a;try{let s=await _browser.startRegistration.call(void 0, a.data),u=await t("/passkey/verify-registration",{..._optionalChain([r, 'optionalAccess', _7 => _7.fetchOptions]),...n,body:{response:s,name:_optionalChain([r, 'optionalAccess', _8 => _8.name])},method:"POST"});if(!u.data)return u;e.set(Math.random())}catch(s){return s instanceof _browser.WebAuthnError?s.code==="ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED"?{data:null,error:{message:"previously registered",status:400,statusText:"BAD_REQUEST"}}:s.code==="ERROR_CEREMONY_ABORTED"?{data:null,error:{message:"registration cancelled",status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:s.message,status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:s instanceof Error?s.message:"unknown error",status:500,statusText:"INTERNAL_SERVER_ERROR"}}}}},$Infer:{}}),v= exports.d =()=>{let t=_nanostores.atom.call(void 0, );return{id:"passkey",$InferServerPlugin:{},getActions:e=>h(e,{_listPasskeys:t}),getAtoms(e){return{listPasskeys:_chunk4O3SREZXcjs.a.call(void 0, t,"/passkey/list-user-passkeys",e,{method:"GET"}),_listPasskeys:t}},pathMethods:{"/passkey/register":"POST","/passkey/authenticate":"POST"},atomListeners:[{matcher(e){return e==="/passkey/verify-registration"||e==="/passkey/delete-passkey"},signal:"_listPasskeys"}]}};var c=class extends Error{constructor(e,o){super(e),this.path=o}},p=class{constructor(e){this.s=e;this.statements=e}newRole(e){return new m(e)}},m=class t{constructor(e){this.statements=e}authorize(e,o){for(let[i,r]of Object.entries(e)){let n=this.statements[i];if(!n)return{success:!1,error:`You are not allowed to access resource: ${i}`};let a=o==="OR"?r.some(s=>n.includes(s)):r.every(s=>n.includes(s));return a?{success:a}:{success:!1,error:`unauthorized to access resource "${i}"`}}return{success:!1,error:"Not authorized"}}static fromString(e){let o=JSON.parse(e);if(typeof o!="object")throw new c("statements is not an object",".");for(let[i,r]of Object.entries(o)){if(typeof i!="string")throw new c("invalid resource identifier",i);if(!Array.isArray(r))throw new c("actions is not an array",i);for(let n=0;n<r.length;n++)if(typeof r[n]!="string")throw new c("action is not a string",`${i}[${n}]`)}return new t(o)}toString(){return JSON.stringify(this.statements)}};var w=t=>new p(t),P={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},l=w(P),T=l.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),k=l.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),O=l.newRole({organization:[],member:[],invitation:[]}),_= exports.a ={admin:T,owner:k,member:O};exports.a = _; exports.b = R; exports.c = h; exports.d = v;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkUOTC7PMKcjs = require('./chunk-UOTC7PMK.cjs');var R=(t={redirect:!0,twoFactorPage:"/"})=>({id:"two-factor",$InferServerPlugin:{},atomListeners:[{matcher:e=>e.startsWith("/two-factor/"),signal:"$sessionSignal"}],pathMethods:{"/two-factor/disable":"POST","/two-factor/enable":"POST","/two-factor/send-otp":"POST","/two-factor/generate-backup-codes":"POST"},fetchPlugins:[{id:"two-factor",name:"two-factor",hooks:{async onSuccess(e){_optionalChain([e, 'access', _2 => _2.data, 'optionalAccess', _3 => _3.twoFactorRedirect])&&(t.redirect||t.twoFactorPage)&&typeof window<"u"&&(window.location.href=t.twoFactorPage)}}}]});var _browser = require('@simplewebauthn/browser');var _nanostores = require('nanostores');var h=(t,{_listPasskeys:e})=>({signIn:{passkey:async(r,n)=>{let a=await t("/passkey/generate-authenticate-options",{method:"POST",body:{email:_optionalChain([r, 'optionalAccess', _4 => _4.email])}});if(!a.data)return a;try{let s=await _browser.startAuthentication.call(void 0, a.data,_optionalChain([r, 'optionalAccess', _5 => _5.autoFill])||!1),u=await t("/passkey/verify-authentication",{body:{response:s},..._optionalChain([r, 'optionalAccess', _6 => _6.fetchOptions]),...n,method:"POST"});if(!u.data)return u}catch (e2){return{data:null,error:{message:"auth cancelled",status:400,statusText:"BAD_REQUEST"}}}}},passkey:{addPasskey:async(r,n)=>{let a=await t("/passkey/generate-register-options",{method:"GET"});if(!a.data)return a;try{let s=await _browser.startRegistration.call(void 0, a.data),u=await t("/passkey/verify-registration",{..._optionalChain([r, 'optionalAccess', _7 => _7.fetchOptions]),...n,body:{response:s,name:_optionalChain([r, 'optionalAccess', _8 => _8.name])},method:"POST"});if(!u.data)return u;e.set(Math.random())}catch(s){return s instanceof _browser.WebAuthnError?s.code==="ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED"?{data:null,error:{message:"previously registered",status:400,statusText:"BAD_REQUEST"}}:s.code==="ERROR_CEREMONY_ABORTED"?{data:null,error:{message:"registration cancelled",status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:s.message,status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:s instanceof Error?s.message:"unknown error",status:500,statusText:"INTERNAL_SERVER_ERROR"}}}}},$Infer:{}}),v= exports.d =()=>{let t=_nanostores.atom.call(void 0, );return{id:"passkey",$InferServerPlugin:{},getActions:e=>h(e,{_listPasskeys:t}),getAtoms(e){return{listPasskeys:_chunkUOTC7PMKcjs.a.call(void 0, t,"/passkey/list-user-passkeys",e,{method:"GET"}),_listPasskeys:t}},pathMethods:{"/passkey/register":"POST","/passkey/authenticate":"POST"},atomListeners:[{matcher(e){return e==="/passkey/verify-registration"||e==="/passkey/delete-passkey"},signal:"_listPasskeys"}]}};var c=class extends Error{constructor(e,o){super(e),this.path=o}},p=class{constructor(e){this.s=e;this.statements=e}newRole(e){return new m(e)}},m=class t{constructor(e){this.statements=e}authorize(e,o){for(let[i,r]of Object.entries(e)){let n=this.statements[i];if(!n)return{success:!1,error:`You are not allowed to access resource: ${i}`};let a=o==="OR"?r.some(s=>n.includes(s)):r.every(s=>n.includes(s));return a?{success:a}:{success:!1,error:`unauthorized to access resource "${i}"`}}return{success:!1,error:"Not authorized"}}static fromString(e){let o=JSON.parse(e);if(typeof o!="object")throw new c("statements is not an object",".");for(let[i,r]of Object.entries(o)){if(typeof i!="string")throw new c("invalid resource identifier",i);if(!Array.isArray(r))throw new c("actions is not an array",i);for(let n=0;n<r.length;n++)if(typeof r[n]!="string")throw new c("action is not a string",`${i}[${n}]`)}return new t(o)}toString(){return JSON.stringify(this.statements)}};var w=t=>new p(t),P={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},l=w(P),T=l.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),k=l.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),O=l.newRole({organization:[],member:[],invitation:[]}),_= exports.a ={admin:T,owner:k,member:O};exports.a = _; exports.b = R; exports.c = h; exports.d = v;
@@ -1,6 +1,6 @@
1
- import{a as K}from"./chunk-GW5UFHUL.js";import{n as $}from"./chunk-XJR6RYEY.js";import{a as x,b as V,c as Y}from"./chunk-UN6PZ3HT.js";import{a as J,c as y,d as q}from"./chunk-TCBMYTN7.js";import{c as k,d as P}from"./chunk-FAFRRPOC.js";import{c as G}from"./chunk-RBJV2U7C.js";import{APIError as Ie,createRouter as He,statusCode as Ze}from"better-call";import{APIError as Pe}from"better-call";import{createEndpointCreator as Oe,createMiddleware as X,createMiddlewareCreator as ve}from"better-call";var ee=X(async()=>({})),N=ve({use:[ee,X(async()=>({}))]}),p=Oe({use:[ee]});var te=N(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:n}=e,o=e.headers?.get("origin")||e.headers?.get("referer")||"",s=t?.callbackURL,i=t?.redirectTo,a=r?.currentURL,l=n.trustedOrigins,d=e.headers?.has("cookie"),c=(h,f)=>{if(!l.some(A=>h?.startsWith(A)||h?.startsWith("/")&&f!=="origin"))throw y.error(`Invalid ${f}: ${h}`),y.info(`If it's a valid URL, please add ${h} to trustedOrigins in your auth config
2
- `,`Current list of trustedOrigins: ${l}`),new Pe("FORBIDDEN",{message:`Invalid ${f}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&c(o,"origin"),s&&c(s,"callbackURL"),i&&c(i,"redirectURL"),a&&c(a,"currentURL")});import{APIError as T}from"better-call";import"oslo/oauth2";import{z as U}from"zod";import{TimeSpan as xe}from"oslo";import{createJWT as Be,validateJWT as _e}from"oslo/jwt";import{z as S}from"zod";import{APIError as B}from"better-call";import{APIError as D}from"better-call";import{z as C}from"zod";var z=()=>p("/get-session",{method:"GET",query:C.optional(C.object({disableCookieCache:C.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.getSignedCookie(e.context.authCookies.sessionData.name,e.context.secret),n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(r&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let d=JSON.parse(r)?.session;if(d?.expiresAt>new Date)return e.json(d)}let o=await e.context.internalAdapter.findSession(t);if(!o||o.session.expiresAt<new Date)return P(e),o&&await e.context.internalAdapter.deleteSession(o.session.id),e.json(null,{status:401});if(n)return e.json(o);let s=e.context.sessionConfig.expiresIn,i=e.context.sessionConfig.updateAge;if(o.session.expiresAt.valueOf()-s*1e3+i*1e3<=Date.now()){let d=await e.context.internalAdapter.updateSession(o.session.id,{expiresAt:q(e.context.sessionConfig.expiresIn,"sec")});if(!d)return P(e),e.json(null,{status:401});let c=(d.expiresAt.valueOf()-Date.now())/1e3;return await k(e,{session:d,user:o.user},!1,{maxAge:c}),e.json({session:d,user:o.user})}return e.json(o)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),W=async e=>await z()({...e,_flag:"json",headers:e.headers}),R=N(async e=>{let t=await W(e);if(!t?.session)throw new D("UNAUTHORIZED");return{session:t}}),oe=()=>p("/list-sessions",{method:"GET",use:[R],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(n=>n.expiresAt>new Date);return e.json(r)}),re=p("/revoke-session",{method:"POST",body:C.object({id:C.string()}),use:[R],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new D("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new D("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(n){throw e.context.logger.error(n),new D("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ne=p("/revoke-sessions",{method:"POST",use:[R],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new D("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function O(e,t,r){return await Be("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new xe(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var se=p("/send-verification-email",{method:"POST",query:S.object({currentURL:S.string().optional()}).optional(),body:S.object({email:S.string().email(),callbackURL:S.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new B("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new B("BAD_REQUEST",{message:"User not found"});let n=await O(e.context.secret,t),o=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,o,n),e.json({status:!0})}),ie=p("/verify-email",{method:"GET",query:S.object({token:S.string(),callbackURL:S.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await _e("HS256",Buffer.from(e.context.secret),t)}catch(i){throw e.context.logger.error("Failed to verify email",i),new B("BAD_REQUEST",{message:"Invalid token"})}let o=S.object({email:S.string().email(),updateTo:S.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(o.email))throw new B("BAD_REQUEST",{message:"User not found"});if(o.updateTo){let i=await W(e);if(!i)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new B("UNAUTHORIZED",{message:"Session not found"});if(i.user.email!==o.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new B("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(o.email,{email:o.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(a,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(o.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});import{HMAC as gt,sha256 as ht}from"oslo/crypto";var ae=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:U.object({currentURL:U.string().optional()}).optional(),body:U.object({callbackURL:U.string().optional(),provider:U.enum($)})},async e=>{let t=e.context.socialProviders.find(s=>s.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new T("NOT_FOUND",{message:"Provider not found"});let{codeVerifier:r,state:n}=await V(e),o=await t.createAuthorizationURL({state:n,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:o.toString(),redirect:!0})}),de=p("/sign-in/email",{method:"POST",body:U.object({email:U.string(),password:U.string(),callbackURL:U.string().optional(),dontRememberMe:U.boolean().default(!1).optional()})},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new T("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!U.string().email().safeParse(t).success)throw new T("BAD_REQUEST",{message:"Invalid email"});if(!U.string().email().safeParse(t).success)throw new T("BAD_REQUEST",{message:"Invalid email"});let s=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!s)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new T("UNAUTHORIZED",{message:"Invalid email or password"});let i=s.accounts.find(c=>c.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new T("UNAUTHORIZED",{message:"Invalid email or password"});let a=i?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new T("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new T("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!s.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw y.error("Email verification is required but no email verification handler is provided"),new T("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await O(e.context.secret,s.user.email),h=`${e.context.options.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail(s.user,h,c),e.context.logger.error("Email not verified",{email:t}),new T("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(s.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new T("UNAUTHORIZED",{message:"Failed to create session"});return await k(e,{session:d,user:s.user},e.body.dontRememberMe),e.json({user:s.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as Q}from"zod";import{z as m}from"zod";var Bt=m.object({id:m.string(),providerId:m.string(),accountId:m.string(),userId:m.string(),accessToken:m.string().nullable().optional(),refreshToken:m.string().nullable().optional(),idToken:m.string().nullable().optional(),expiresAt:m.date().nullable().optional(),password:m.string().optional().nullable()}),ce=m.object({id:m.string(),email:m.string().transform(e=>e.toLowerCase()),emailVerified:m.boolean().default(!1),name:m.string(),image:m.string().optional(),createdAt:m.date().default(new Date),updatedAt:m.date().default(new Date)}),_t=m.object({id:m.string(),userId:m.string(),expiresAt:m.date(),ipAddress:m.string().optional(),userAgent:m.string().optional()}),Dt=m.object({id:m.string(),value:m.string(),expiresAt:m.date(),identifier:m.string()});function De(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let n of e.plugins||[])n.schema&&n.schema[t]&&(r={...r,...n.schema[t].fields});return r}function Ce(e,t){let r=t.action||"create",n=t.fields,o={};for(let s in n){if(s in e){if(n[s].input===!1){if(n[s].defaultValue){o[s]=n[s].defaultValue;continue}continue}o[s]=e[s];continue}if(n[s].defaultValue&&r==="create"){o[s]=n[s].defaultValue;continue}}return o}function M(e,t,r){let n=De(e,"user");return Ce(t||{},{fields:n,action:r})}var le=p("/callback/:id",{method:"GET",query:Q.object({state:Q.string(),code:Q.string().optional(),error:Q.string().optional()}),metadata:x},async e=>{if(!e.query.code)throw e.redirect(`${e.context.baseURL}/error?error=${e.query.error||"no_code"}`);let t=e.context.socialProviders.find(w=>w.id===e.params.id);if(!t)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:r,callbackURL:n,link:o,errorURL:s}=await Y(e),i;try{i=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(w){throw e.context.logger.error(w),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(i).then(w=>w?.user),l=J(),d=ce.safeParse({...a,id:l});if(!a||d.success===!1)throw y.error("Unable to get user info",d.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!n)throw y.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(o){if(o.email!==a.email.toLowerCase())return c("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:o.userId,providerId:t.id,accountId:a.id}))return c("unable_to_link_account");throw e.redirect(s||n||e.context.options.baseURL)}function c(w){throw e.redirect(`${s||n||`${e.context.baseURL}/error`}?error=${w}`)}let h=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(w=>{throw y.error(`Better auth was unable to query your database.
3
- Error: `,w),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),f=h?.user;if(h){let w=h.accounts.find(g=>g.providerId===t.id);if(w)await e.context.internalAdapter.updateAccount(w.id,{accessToken:i.accessToken,idToken:i.idToken,refreshToken:i.refreshToken,expiresAt:i.accessTokenExpiresAt});else{(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!a.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)&&(G&&y.warn(`User already exist but account isn't linked to ${t.id}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),c("account_not_linked"));try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:a.id.toString(),id:`${t.id}:${a.id}`,userId:h.user.id,accessToken:i.accessToken,idToken:i.idToken,refreshToken:i.refreshToken,expiresAt:i.accessTokenExpiresAt})}catch(H){y.error("Unable to link account",H),c("unable_to_link_account")}}}else try{let w=a.emailVerified||!1;if(f=await e.context.internalAdapter.createOAuthUser({...d.data,emailVerified:w},{accessToken:i.accessToken,idToken:i.idToken,refreshToken:i.refreshToken,expiresAt:i.accessTokenExpiresAt,providerId:t.id,accountId:a.id.toString()}).then(g=>g?.user),!w&&f&&e.context.options.emailVerification?.sendOnSignUp){let g=await O(e.context.secret,f.email),I=`${e.context.baseURL}/verify-email?token=${g}&callbackURL=${n}`;await e.context.options.emailVerification?.sendVerificationEmail?.(f,I,g)}}catch(w){y.error("Unable to create user",w),c("unable_to_create_user")}if(!f)return c("unable_to_create_user");let u=await e.context.internalAdapter.createSession(f.id,e.request);u||c("unable_to_create_session"),await k(e,{session:u,user:f});let A=new URL(n);throw e.redirect(A.toString())});import"zod";import{APIError as je}from"better-call";var ue=p("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new je("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),P(e),e.json({success:!0})});import{z as L}from"zod";import{APIError as F}from"better-call";var pe=p("/forget-password",{method:"POST",body:L.object({email:L.string().email(),redirectTo:L.string()})},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new F("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let o=60*60*1,s=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||o)),i=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:n.user.id,identifier:`reset-password:${i}`,expiresAt:s});let a=`${e.context.baseURL}/reset-password/${i}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(n.user,a),e.json({status:!0})}),me=p("/reset-password/:token",{method:"GET",query:L.object({callbackURL:L.string()})},async e=>{let{token:t}=e.params,r=e.query.callbackURL,n=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(`${n}?error=INVALID_TOKEN`):e.redirect(`${n}${n.includes("?")?"&":"?"}token=${t}`)}),fe=p("/reset-password",{query:L.optional(L.object({token:L.string().optional(),currentURL:L.string().optional()})),method:"POST",body:L.object({newPassword:L.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new F("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,n=`reset-password:${t}`,o=await e.context.internalAdapter.findVerificationValue(n);if(!o||o.expiresAt<new Date)throw new F("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(o.id);let s=o.value,i=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(s)).find(c=>c.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:s,providerId:"credential",password:i,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(s,i))throw new F("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as E}from"zod";import{APIError as b}from"better-call";var we=()=>p("/update-user",{method:"POST",body:E.record(E.string(),E.any()),use:[R]},async e=>{let t=e.body;if(t.email)throw new b("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:n,...o}=t,s=e.context.session;if(!n&&!r&&Object.keys(o).length===0)return e.json({user:s.user});let i=M(e.context.options,o,"update"),a=await e.context.internalAdapter.updateUserByEmail(s.user.email,{name:r,image:n,...i});return await k(e,{session:s.session,user:a}),e.json({user:a})}),ge=p("/change-password",{method:"POST",body:E.object({newPassword:E.string(),currentPassword:E.string(),revokeOtherSessions:E.boolean().optional()}),use:[R]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:n}=e.body,o=e.context.session,s=e.context.password.config.minPasswordLength;if(t.length<s)throw e.context.logger.error("Password is too short"),new b("BAD_REQUEST",{message:"Password is too short"});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new b("BAD_REQUEST",{message:"Password too long"});let l=(await e.context.internalAdapter.findAccounts(o.user.id)).find(h=>h.providerId==="credential"&&h.password);if(!l||!l.password)throw new b("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify(l.password,r))throw new b("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(l.id,{password:d}),n){await e.context.internalAdapter.deleteSessions(o.user.id);let h=await e.context.internalAdapter.createSession(o.user.id,e.headers);if(!h)throw new b("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await k(e,{session:h,user:o.user})}return e.json(o.user)}),he=p("/set-password",{method:"POST",body:E.object({newPassword:E.string()}),metadata:{SERVER_ONLY:!0},use:[R]},async e=>{let{newPassword:t}=e.body,r=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new b("BAD_REQUEST",{message:"Password is too short"});let o=e.context.password.config.maxPasswordLength;if(t.length>o)throw e.context.logger.error("Password is too long"),new b("BAD_REQUEST",{message:"Password too long"});let i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(l=>l.providerId==="credential"&&l.password),a=await e.context.password.hash(t);if(!i)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:a}),e.json(r.user);throw new b("BAD_REQUEST",{message:"user already has a password"})}),ye=p("/delete-user",{method:"POST",body:E.object({password:E.string()}),use:[R]},async e=>{let{password:t}=e.body,r=e.context.session,o=(await e.context.internalAdapter.findAccounts(r.user.id)).find(i=>i.providerId==="credential"&&i.password);if(!o||!o.password)throw new b("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(o.password,t))throw new b("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),P(e),e.json(null)}),Ae=p("/change-email",{method:"POST",query:E.object({currentURL:E.string().optional()}).optional(),body:E.object({newEmail:E.string().email(),callbackURL:E.string().optional()}),use:[R]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new b("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new b("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new b("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let o=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:o,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new b("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await O(e.context.secret,e.context.session.user.email,e.body.newEmail),n=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification(e.context.session.user,e.body.newEmail,n,r),e.json({user:null,status:!0})});var Ve=(e="Unknown")=>`<!DOCTYPE html>
1
+ import{a as K}from"./chunk-GW5UFHUL.js";import{n as $}from"./chunk-ECKSI3LF.js";import{a as x,b as V,c as Y}from"./chunk-LXL7WUAT.js";import{a as J,c as y,d as q}from"./chunk-TCBMYTN7.js";import{c as k,d as P}from"./chunk-FAFRRPOC.js";import{c as G}from"./chunk-RBJV2U7C.js";import{APIError as Ie,createRouter as He,statusCode as Ze}from"better-call";import{APIError as Pe}from"better-call";import{createEndpointCreator as Oe,createMiddleware as X,createMiddlewareCreator as ve}from"better-call";var ee=X(async()=>({})),N=ve({use:[ee,X(async()=>({}))]}),p=Oe({use:[ee]});var te=N(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:n,context:r}=e,o=e.headers?.get("origin")||e.headers?.get("referer")||"",s=t?.callbackURL,i=t?.redirectTo,a=n?.currentURL,l=r.trustedOrigins,d=e.headers?.has("cookie"),c=(h,w)=>{if(!l.some(A=>h?.startsWith(A)||h?.startsWith("/")&&w!=="origin"))throw y.error(`Invalid ${w}: ${h}`),y.info(`If it's a valid URL, please add ${h} to trustedOrigins in your auth config
2
+ `,`Current list of trustedOrigins: ${l}`),new Pe("FORBIDDEN",{message:`Invalid ${w}`})};d&&!e.context.options.advanced?.disableCSRFCheck&&c(o,"origin"),s&&c(s,"callbackURL"),i&&c(i,"redirectURL"),a&&c(a,"currentURL")});import{APIError as T}from"better-call";import"oslo/oauth2";import{z as U}from"zod";import{TimeSpan as xe}from"oslo";import{createJWT as Be,validateJWT as _e}from"oslo/jwt";import{z as S}from"zod";import{APIError as B}from"better-call";import{APIError as D}from"better-call";import{z as C}from"zod";var z=()=>p("/get-session",{method:"GET",query:C.optional(C.object({disableCookieCache:C.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let n=await e.getSignedCookie(e.context.authCookies.sessionData.name,e.context.secret),r=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(n&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let d=JSON.parse(n)?.session;if(d?.expiresAt>new Date)return e.json(d)}let o=await e.context.internalAdapter.findSession(t);if(!o||o.session.expiresAt<new Date)return P(e),o&&await e.context.internalAdapter.deleteSession(o.session.id),e.json(null,{status:401});if(r)return e.json(o);let s=e.context.sessionConfig.expiresIn,i=e.context.sessionConfig.updateAge;if(o.session.expiresAt.valueOf()-s*1e3+i*1e3<=Date.now()){let d=await e.context.internalAdapter.updateSession(o.session.id,{expiresAt:q(e.context.sessionConfig.expiresIn,"sec")});if(!d)return P(e),e.json(null,{status:401});let c=(d.expiresAt.valueOf()-Date.now())/1e3;return await k(e,{session:d,user:o.user},!1,{maxAge:c}),e.json({session:d,user:o.user})}return e.json(o)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),W=async e=>await z()({...e,_flag:"json",headers:e.headers}),b=N(async e=>{let t=await W(e);if(!t?.session)throw new D("UNAUTHORIZED");return{session:t}}),oe=()=>p("/list-sessions",{method:"GET",use:[b],requireHeaders:!0},async e=>{let n=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(r=>r.expiresAt>new Date);return e.json(n)}),re=p("/revoke-session",{method:"POST",body:C.object({id:C.string()}),use:[b],requireHeaders:!0},async e=>{let t=e.body.id,n=await e.context.internalAdapter.findSession(t);if(!n)throw new D("BAD_REQUEST",{message:"Session not found"});if(n.session.userId!==e.context.session.user.id)throw new D("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(r){throw e.context.logger.error(r),new D("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ne=p("/revoke-sessions",{method:"POST",use:[b],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new D("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function O(e,t,n){return await Be("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:n},{expiresIn:new xe(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var se=p("/send-verification-email",{method:"POST",query:S.object({currentURL:S.string().optional()}).optional(),body:S.object({email:S.string().email(),callbackURL:S.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new B("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,n=await e.context.internalAdapter.findUserByEmail(t);if(!n)throw new B("BAD_REQUEST",{message:"User not found"});let r=await O(e.context.secret,t),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(n.user,o,r),e.json({status:!0})}),ie=p("/verify-email",{method:"GET",query:S.object({token:S.string(),callbackURL:S.string().optional()})},async e=>{let{token:t}=e.query,n;try{n=await _e("HS256",Buffer.from(e.context.secret),t)}catch(i){throw e.context.logger.error("Failed to verify email",i),new B("BAD_REQUEST",{message:"Invalid token"})}let o=S.object({email:S.string().email(),updateTo:S.string().optional()}).parse(n.payload);if(!await e.context.internalAdapter.findUserByEmail(o.email))throw new B("BAD_REQUEST",{message:"User not found"});if(o.updateTo){let i=await W(e);if(!i)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new B("UNAUTHORIZED",{message:"Session not found"});if(i.user.email!==o.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new B("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(o.email,{email:o.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(a,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(o.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});import{HMAC as gt,sha256 as ht}from"oslo/crypto";var ae=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:U.object({currentURL:U.string().optional()}).optional(),body:U.object({callbackURL:U.string().optional(),provider:U.enum($)})},async e=>{let t=e.context.socialProviders.find(s=>s.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new T("NOT_FOUND",{message:"Provider not found"});let{codeVerifier:n,state:r}=await V(e),o=await t.createAuthorizationURL({state:r,codeVerifier:n,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:o.toString(),redirect:!0})}),de=p("/sign-in/email",{method:"POST",body:U.object({email:U.string(),password:U.string(),callbackURL:U.string().optional(),dontRememberMe:U.boolean().default(!1).optional()})},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new T("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:n}=e.body;if(!U.string().email().safeParse(t).success)throw new T("BAD_REQUEST",{message:"Invalid email"});if(!U.string().email().safeParse(t).success)throw new T("BAD_REQUEST",{message:"Invalid email"});let s=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!s)throw await e.context.password.hash(n),e.context.logger.error("User not found",{email:t}),new T("UNAUTHORIZED",{message:"Invalid email or password"});let i=s.accounts.find(c=>c.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new T("UNAUTHORIZED",{message:"Invalid email or password"});let a=i?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new T("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,n))throw e.context.logger.error("Invalid password"),new T("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!s.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw y.error("Email verification is required but no email verification handler is provided"),new T("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await O(e.context.secret,s.user.email),h=`${e.context.options.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail(s.user,h,c),e.context.logger.error("Email not verified",{email:t}),new T("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(s.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new T("UNAUTHORIZED",{message:"Failed to create session"});return await k(e,{session:d,user:s.user},e.body.dontRememberMe),e.json({user:s.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as Q}from"zod";import{z as f}from"zod";var Bt=f.object({id:f.string(),providerId:f.string(),accountId:f.string(),userId:f.string(),accessToken:f.string().nullable().optional(),refreshToken:f.string().nullable().optional(),idToken:f.string().nullable().optional(),expiresAt:f.date().nullable().optional(),password:f.string().optional().nullable()}),ce=f.object({id:f.string(),email:f.string().transform(e=>e.toLowerCase()),emailVerified:f.boolean().default(!1),name:f.string(),image:f.string().optional(),createdAt:f.date().default(new Date),updatedAt:f.date().default(new Date)}),_t=f.object({id:f.string(),userId:f.string(),expiresAt:f.date(),ipAddress:f.string().optional(),userAgent:f.string().optional()}),Dt=f.object({id:f.string(),value:f.string(),expiresAt:f.date(),identifier:f.string()});function De(e,t){let n={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let r of e.plugins||[])r.schema&&r.schema[t]&&(n={...n,...r.schema[t].fields});return n}function Ce(e,t){let n=t.action||"create",r=t.fields,o={};for(let s in r){if(s in e){if(r[s].input===!1){if(r[s].defaultValue){o[s]=r[s].defaultValue;continue}continue}o[s]=e[s];continue}if(r[s].defaultValue&&n==="create"){o[s]=r[s].defaultValue;continue}}return o}function M(e,t,n){let r=De(e,"user");return Ce(t||{},{fields:r,action:n})}var le=p("/callback/:id",{method:"GET",query:Q.object({state:Q.string(),code:Q.string().optional(),error:Q.string().optional()}),metadata:x},async e=>{if(!e.query.code)throw e.redirect(`${e.context.baseURL}/error?error=${e.query.error||"no_code"}`);let t=e.context.socialProviders.find(m=>m.id===e.params.id);if(!t)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:n,callbackURL:r,link:o,errorURL:s}=await Y(e),i;try{i=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:n,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(m){throw e.context.logger.error(m),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(i).then(m=>m?.user),l=J(),d=ce.safeParse({...a,id:l});if(!a||d.success===!1)throw y.error("Unable to get user info",d.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!r)throw y.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(o){if(o.email!==a.email.toLowerCase())return c("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:o.userId,providerId:t.id,accountId:a.id}))return c("unable_to_link_account");throw e.redirect(s||r||e.context.options.baseURL)}function c(m){throw e.redirect(`${s||r||`${e.context.baseURL}/error`}?error=${m}`)}let h=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(m=>{throw y.error(`Better auth was unable to query your database.
3
+ Error: `,m),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),w=h?.user;if(h){let m=h.accounts.find(g=>g.providerId===t.id);if(m)await e.context.internalAdapter.updateAccount(m.id,{accessToken:i.accessToken,idToken:i.idToken,refreshToken:i.refreshToken,expiresAt:i.accessTokenExpiresAt});else{(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!a.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)&&(G&&y.warn(`User already exist but account isn't linked to ${t.id}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),c("account_not_linked"));try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:a.id.toString(),id:`${t.id}:${a.id}`,userId:h.user.id,accessToken:i.accessToken,idToken:i.idToken,refreshToken:i.refreshToken,expiresAt:i.accessTokenExpiresAt})}catch(H){y.error("Unable to link account",H),c("unable_to_link_account")}}}else try{let m=a.emailVerified||!1;if(w=await e.context.internalAdapter.createOAuthUser({...d.data,emailVerified:m},{accessToken:i.accessToken,idToken:i.idToken,refreshToken:i.refreshToken,expiresAt:i.accessTokenExpiresAt,providerId:t.id,accountId:a.id.toString()}).then(g=>g?.user),!m&&w&&e.context.options.emailVerification?.sendOnSignUp){let g=await O(e.context.secret,w.email),I=`${e.context.baseURL}/verify-email?token=${g}&callbackURL=${r}`;await e.context.options.emailVerification?.sendVerificationEmail?.(w,I,g)}}catch(m){y.error("Unable to create user",m),c("unable_to_create_user")}if(!w)return c("unable_to_create_user");let u=await e.context.internalAdapter.createSession(w.id,e.request);u||c("unable_to_create_session"),await k(e,{session:u,user:w});let A;try{A=new URL(r).toString()}catch{A=r}throw e.redirect(A)});import"zod";import{APIError as je}from"better-call";var ue=p("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new je("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),P(e),e.json({success:!0})});import{z as L}from"zod";import{APIError as F}from"better-call";var pe=p("/forget-password",{method:"POST",body:L.object({email:L.string().email(),redirectTo:L.string()})},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new F("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:n}=e.body,r=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!r)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let o=60*60*1,s=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||o)),i=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:r.user.id,identifier:`reset-password:${i}`,expiresAt:s});let a=`${e.context.baseURL}/reset-password/${i}?callbackURL=${n}`;return await e.context.options.emailAndPassword.sendResetPassword(r.user,a),e.json({status:!0})}),me=p("/reset-password/:token",{method:"GET",query:L.object({callbackURL:L.string()})},async e=>{let{token:t}=e.params,n=e.query.callbackURL,r=n.startsWith("http")?n:`${e.context.options.baseURL}${n}`;if(!t||!n)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(`${r}?error=INVALID_TOKEN`):e.redirect(`${r}${r.includes("?")?"&":"?"}token=${t}`)}),fe=p("/reset-password",{query:L.optional(L.object({token:L.string().optional(),currentURL:L.string().optional()})),method:"POST",body:L.object({newPassword:L.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new F("BAD_REQUEST",{message:"Token not found"});let{newPassword:n}=e.body,r=`reset-password:${t}`,o=await e.context.internalAdapter.findVerificationValue(r);if(!o||o.expiresAt<new Date)throw new F("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(o.id);let s=o.value,i=await e.context.password.hash(n);if(!(await e.context.internalAdapter.findAccounts(s)).find(c=>c.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:s,providerId:"credential",password:i,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(s,i))throw new F("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as E}from"zod";import{APIError as R}from"better-call";var we=()=>p("/update-user",{method:"POST",body:E.record(E.string(),E.any()),use:[b]},async e=>{let t=e.body;if(t.email)throw new R("BAD_REQUEST",{message:"You can't update email"});let{name:n,image:r,...o}=t,s=e.context.session;if(!r&&!n&&Object.keys(o).length===0)return e.json({user:s.user});let i=M(e.context.options,o,"update"),a=await e.context.internalAdapter.updateUserByEmail(s.user.email,{name:n,image:r,...i});return await k(e,{session:s.session,user:a}),e.json({user:a})}),ge=p("/change-password",{method:"POST",body:E.object({newPassword:E.string(),currentPassword:E.string(),revokeOtherSessions:E.boolean().optional()}),use:[b]},async e=>{let{newPassword:t,currentPassword:n,revokeOtherSessions:r}=e.body,o=e.context.session,s=e.context.password.config.minPasswordLength;if(t.length<s)throw e.context.logger.error("Password is too short"),new R("BAD_REQUEST",{message:"Password is too short"});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new R("BAD_REQUEST",{message:"Password too long"});let l=(await e.context.internalAdapter.findAccounts(o.user.id)).find(h=>h.providerId==="credential"&&h.password);if(!l||!l.password)throw new R("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify(l.password,n))throw new R("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(l.id,{password:d}),r){await e.context.internalAdapter.deleteSessions(o.user.id);let h=await e.context.internalAdapter.createSession(o.user.id,e.headers);if(!h)throw new R("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await k(e,{session:h,user:o.user})}return e.json(o.user)}),he=p("/set-password",{method:"POST",body:E.object({newPassword:E.string()}),metadata:{SERVER_ONLY:!0},use:[b]},async e=>{let{newPassword:t}=e.body,n=e.context.session,r=e.context.password.config.minPasswordLength;if(t.length<r)throw e.context.logger.error("Password is too short"),new R("BAD_REQUEST",{message:"Password is too short"});let o=e.context.password.config.maxPasswordLength;if(t.length>o)throw e.context.logger.error("Password is too long"),new R("BAD_REQUEST",{message:"Password too long"});let i=(await e.context.internalAdapter.findAccounts(n.user.id)).find(l=>l.providerId==="credential"&&l.password),a=await e.context.password.hash(t);if(!i)return await e.context.internalAdapter.linkAccount({userId:n.user.id,providerId:"credential",accountId:n.user.id,password:a}),e.json(n.user);throw new R("BAD_REQUEST",{message:"user already has a password"})}),ye=p("/delete-user",{method:"POST",body:E.object({password:E.string()}),use:[b]},async e=>{let{password:t}=e.body,n=e.context.session,o=(await e.context.internalAdapter.findAccounts(n.user.id)).find(i=>i.providerId==="credential"&&i.password);if(!o||!o.password)throw new R("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(o.password,t))throw new R("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(n.user.id),await e.context.internalAdapter.deleteSessions(n.user.id),P(e),e.json(null)}),Ae=p("/change-email",{method:"POST",query:E.object({currentURL:E.string().optional()}).optional(),body:E.object({newEmail:E.string().email(),callbackURL:E.string().optional()}),use:[b]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new R("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new R("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new R("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let o=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:o,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new R("BAD_REQUEST",{message:"Verification email isn't enabled"});let n=await O(e.context.secret,e.context.session.user.email,e.body.newEmail),r=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification(e.context.session.user,e.body.newEmail,r,n),e.json({user:null,status:!0})});var Ve=(e="Unknown")=>`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
@@ -80,4 +80,4 @@ Error: `,w),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
80
80
  <div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
81
81
  </div>
82
82
  </body>
83
- </html>`,Ee=p("/error",{method:"GET",metadata:x},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Ve(t),{headers:{"Content-Type":"text/html"}})});var be=p("/ok",{method:"GET",metadata:x},async e=>e.json({ok:!0}));import{z as _}from"zod";import{APIError as v}from"better-call";var Re=()=>p("/sign-up/email",{method:"POST",query:_.object({currentURL:_.string().optional()}).optional(),body:_.record(_.string(),_.any())},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new v("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:n,password:o,image:s,callbackURL:i,...a}=t;if(!_.string().email().safeParse(n).success)throw new v("BAD_REQUEST",{message:"Invalid email"});let d=e.context.password.config.minPasswordLength;if(o.length<d)throw e.context.logger.error("Password is too short"),new v("BAD_REQUEST",{message:"Password is too short"});let c=e.context.password.config.maxPasswordLength;if(o.length>c)throw e.context.logger.error("Password is too long"),new v("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(n))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${n}`),new v("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let f=M(e.context.options,a),u;try{if(u=await e.context.internalAdapter.createUser({email:n.toLowerCase(),name:r,image:s,...f,emailVerified:!1}),!u)throw new v("BAD_REQUEST",{message:"Failed to create user"})}catch(g){throw y.error("Failed to create user",g),new v("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:g})}if(!u)throw new v("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let A=await e.context.password.hash(o);if(await e.context.internalAdapter.linkAccount({userId:u.id,providerId:"credential",accountId:u.id,password:A,expiresAt:q(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let g=await O(e.context.secret,u.email),I=`${e.context.baseURL}/verify-email?token=${g}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(u,I,g)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:u,session:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:u,session:null}});let w=await e.context.internalAdapter.createSession(u.id,e.request);if(!w)throw new v("BAD_REQUEST",{message:"Failed to create session"});return await k(e,{session:w,user:u}),e.json({user:u,session:w})});import{z as j}from"zod";import{APIError as Ue}from"better-call";import"oslo/oauth2";var ke=p("/list-accounts",{method:"GET",use:[R]},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r)}),Se=p("/link-social",{method:"POST",requireHeaders:!0,query:j.object({currentURL:j.string().optional()}).optional(),body:j.object({callbackURL:j.string().optional(),provider:j.enum($)}),use:[R]},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(a=>a.providerId===e.body.provider))throw new Ue("BAD_REQUEST",{message:"Social Account is already linked."});let o=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!o)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Ue("NOT_FOUND",{message:"Provider not found"});let s=await V(e),i=await o.createAuthorizationURL({state:s.state,codeVerifier:s.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${o.id}`});return e.json({url:i.toString(),redirect:!0})});function qe(e,t,r){let n=Date.now(),o=t*1e3;return n-r.lastRequest<o&&r.count>=e}function $e(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function Ne(e,t){let r=Date.now(),n=t*1e3;return Math.ceil((e+n-r)/1e3)}function Me(e,t){let r=t??"rateLimit",n=e.adapter;return{get:async o=>await n.findOne({model:r,where:[{field:"key",value:o}]}),set:async(o,s,i)=>{try{i?await n.update({model:t??"rateLimit",where:[{field:"key",value:o}],update:{count:s.count,lastRequest:s.lastRequest}}):await n.create({model:t??"rateLimit",data:{key:o,count:s.count,lastRequest:s.lastRequest}})}catch(a){y.error("Error setting rate limit",a)}}}}var Te=new Map;function Qe(e){return e.rateLimit.storage==="secondary-storage"?{get:async r=>{let n=await e.options.secondaryStorage?.get(r);return n?JSON.parse(n):void 0},set:async(r,n)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(n))}}:e.rateLimit.storage==="memory"?{async get(r){return Te.get(r)},async set(r,n,o){Te.set(r,n)}}:Me(e,e.rateLimit.tableName)}async function Le(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,n=e.url.replace(r,""),o=t.rateLimit.window,s=t.rateLimit.max,i=K(e)+n,l=Fe().find(f=>f.pathMatcher(n));l&&(o=l.window,s=l.max);for(let f of t.options.plugins||[])if(f.rateLimit){let u=f.rateLimit.find(A=>A.pathMatcher(n));if(u){o=u.window,s=u.max;break}}if(t.rateLimit.customRules){let f=t.rateLimit.customRules[n];f&&(o=f.window,s=f.max)}let d=Qe(t),c=await d.get(i),h=Date.now();if(!c)await d.set(i,{key:i,count:1,lastRequest:h});else{let f=h-c.lastRequest;if(qe(s,o,c)){let u=Ne(c.lastRequest,o);return $e(u)}else f>o*1e3?await d.set(i,{...c,count:1,lastRequest:h}):await d.set(i,{...c,count:c.count+1,lastRequest:h})}}function Fe(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:3}]}import{APIError as Er}from"better-call";function ze(e,t){let r=t.plugins?.reduce((a,l)=>({...a,...l.endpoints}),{}),n=t.plugins?.map(a=>a.middlewares?.map(l=>{let d=async c=>l.middleware({...c,context:{...e,...c.context}});return d.path=l.path,d.options=l.middleware.options,d.headers=l.middleware.headers,{path:l.path,middleware:d}})).filter(a=>a!==void 0).flat()||[],s={...{signInOAuth:ae,callbackOAuth:le,getSession:z(),signOut:ue,signUpEmail:Re(),signInEmail:de,forgetPassword:pe,resetPassword:fe,verifyEmail:ie,sendVerificationEmail:se,changeEmail:Ae,changePassword:ge,setPassword:he,updateUser:we(),deleteUser:ye,forgetPasswordCallback:me,listSessions:oe(),revokeSession:re,revokeSessions:ne,linkSocialAccount:Se,listUserAccounts:ke},...r,ok:be,error:Ee},i={};for(let[a,l]of Object.entries(s))i[a]=async(d={})=>{let c=await e;for(let u of t.plugins||[])if(u.hooks?.before){for(let A of u.hooks.before)if(A.matcher({...l,...d,context:c})){let g=await A.handler({...d,context:{...c,...d?.context}});g&&"context"in g&&(c={...c,...g.context})}}let h;try{h=await l({...d,context:{...c,...d.context}})}catch(u){if(u instanceof Ie){let A=t.plugins?.map(g=>{if(g.hooks?.after)return g.hooks.after}).filter(g=>g!==void 0).flat();if(!A?.length)throw u;let w=new Response(JSON.stringify(u.body),{status:Ze[u.status],headers:u.headers});for(let g of A||[])if(g.matcher(d)){let H=Object.assign(d,{context:{...e,returned:w}}),Z=await g.handler(H);Z&&"response"in Z&&(w=Z.response)}return w}throw u}let f=h;for(let u of t.plugins||[])if(u.hooks?.after){for(let A of u.hooks.after)if(A.matcher(d)){let g=Object.assign(d,{context:{...e,returned:f}}),I=await A.handler(g);I&&"response"in I&&(f=I.response)}}return f},i[a].path=l.path,i[a].method=l.method,i[a].options=l.options,i[a].headers=l.headers;return{api:i,middlewares:n}}var fr=(e,t)=>{let{api:r,middlewares:n}=ze(e,t),o=new URL(e.baseURL).pathname;return He(r,{extraContext:e,basePath:o,routerMiddleware:[{path:"/**",middleware:te},...n],async onRequest(s){for(let i of e.options.plugins||[])if(i.onRequest){let a=await i.onRequest(s,e);if(a)return a}return Le(s,e)},async onResponse(s){for(let i of e.options.plugins||[])if(i.onResponse){let a=await i.onResponse(s,e);if(a)return a.response}return s},onError(s){if(t.onAPIError?.throw)throw s;if(t.onAPIError?.onError){t.onAPIError.onError(s,e);return}let i=t.logger?.verboseLogging?y:void 0;t.logger?.disabled!==!0&&(s instanceof Ie?(s.status==="INTERNAL_SERVER_ERROR"&&y.error(s),i?.error(s.message)):y?.error(s))}})};export{ee as a,N as b,p as c,te as d,z as e,W as f,R as g,oe as h,re as i,ne as j,O as k,se as l,ie as m,ae as n,de as o,ce as p,le as q,ue as r,pe as s,me as t,fe as u,we as v,ge as w,he as x,ye as y,Ae as z,Ee as A,be as B,Re as C,ke as D,Se as E,ze as F,fr as G,Er as H};
83
+ </html>`,Ee=p("/error",{method:"GET",metadata:x},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Ve(t),{headers:{"Content-Type":"text/html"}})});var Re=p("/ok",{method:"GET",metadata:x},async e=>e.json({ok:!0}));import{z as _}from"zod";import{APIError as v}from"better-call";var be=()=>p("/sign-up/email",{method:"POST",query:_.object({currentURL:_.string().optional()}).optional(),body:_.record(_.string(),_.any())},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new v("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:n,email:r,password:o,image:s,callbackURL:i,...a}=t;if(!_.string().email().safeParse(r).success)throw new v("BAD_REQUEST",{message:"Invalid email"});let d=e.context.password.config.minPasswordLength;if(o.length<d)throw e.context.logger.error("Password is too short"),new v("BAD_REQUEST",{message:"Password is too short"});let c=e.context.password.config.maxPasswordLength;if(o.length>c)throw e.context.logger.error("Password is too long"),new v("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(r))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${r}`),new v("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let w=M(e.context.options,a),u;try{if(u=await e.context.internalAdapter.createUser({email:r.toLowerCase(),name:n,image:s,...w,emailVerified:!1}),!u)throw new v("BAD_REQUEST",{message:"Failed to create user"})}catch(g){throw y.error("Failed to create user",g),new v("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:g})}if(!u)throw new v("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let A=await e.context.password.hash(o);if(await e.context.internalAdapter.linkAccount({userId:u.id,providerId:"credential",accountId:u.id,password:A,expiresAt:q(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let g=await O(e.context.secret,u.email),I=`${e.context.baseURL}/verify-email?token=${g}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(u,I,g)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:u,session:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:u,session:null}});let m=await e.context.internalAdapter.createSession(u.id,e.request);if(!m)throw new v("BAD_REQUEST",{message:"Failed to create session"});return await k(e,{session:m,user:u}),e.json({user:u,session:m})});import{z as j}from"zod";import{APIError as Ue}from"better-call";import"oslo/oauth2";var ke=p("/list-accounts",{method:"GET",use:[b]},async e=>{let t=e.context.session,n=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(n)}),Se=p("/link-social",{method:"POST",requireHeaders:!0,query:j.object({currentURL:j.string().optional()}).optional(),body:j.object({callbackURL:j.string().optional(),provider:j.enum($)}),use:[b]},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(a=>a.providerId===e.body.provider))throw new Ue("BAD_REQUEST",{message:"Social Account is already linked."});let o=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!o)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Ue("NOT_FOUND",{message:"Provider not found"});let s=await V(e),i=await o.createAuthorizationURL({state:s.state,codeVerifier:s.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${o.id}`});return e.json({url:i.toString(),redirect:!0})});function qe(e,t,n){let r=Date.now(),o=t*1e3;return r-n.lastRequest<o&&n.count>=e}function $e(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function Ne(e,t){let n=Date.now(),r=t*1e3;return Math.ceil((e+r-n)/1e3)}function Me(e,t){let n=t??"rateLimit",r=e.adapter;return{get:async o=>await r.findOne({model:n,where:[{field:"key",value:o}]}),set:async(o,s,i)=>{try{i?await r.update({model:t??"rateLimit",where:[{field:"key",value:o}],update:{count:s.count,lastRequest:s.lastRequest}}):await r.create({model:t??"rateLimit",data:{key:o,count:s.count,lastRequest:s.lastRequest}})}catch(a){y.error("Error setting rate limit",a)}}}}var Te=new Map;function Qe(e){return e.rateLimit.storage==="secondary-storage"?{get:async n=>{let r=await e.options.secondaryStorage?.get(n);return r?JSON.parse(r):void 0},set:async(n,r)=>{await e.options.secondaryStorage?.set?.(n,JSON.stringify(r))}}:e.rateLimit.storage==="memory"?{async get(n){return Te.get(n)},async set(n,r,o){Te.set(n,r)}}:Me(e,e.rateLimit.tableName)}async function Le(e,t){if(!t.rateLimit.enabled)return;let n=t.baseURL,r=e.url.replace(n,""),o=t.rateLimit.window,s=t.rateLimit.max,i=K(e)+r,l=Fe().find(w=>w.pathMatcher(r));l&&(o=l.window,s=l.max);for(let w of t.options.plugins||[])if(w.rateLimit){let u=w.rateLimit.find(A=>A.pathMatcher(r));if(u){o=u.window,s=u.max;break}}if(t.rateLimit.customRules){let w=t.rateLimit.customRules[r];w&&(o=w.window,s=w.max)}let d=Qe(t),c=await d.get(i),h=Date.now();if(!c)await d.set(i,{key:i,count:1,lastRequest:h});else{let w=h-c.lastRequest;if(qe(s,o,c)){let u=Ne(c.lastRequest,o);return $e(u)}else w>o*1e3?await d.set(i,{...c,count:1,lastRequest:h}):await d.set(i,{...c,count:c.count+1,lastRequest:h})}}function Fe(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:3}]}import{APIError as Er}from"better-call";function ze(e,t){let n=t.plugins?.reduce((a,l)=>({...a,...l.endpoints}),{}),r=t.plugins?.map(a=>a.middlewares?.map(l=>{let d=async c=>l.middleware({...c,context:{...e,...c.context}});return d.path=l.path,d.options=l.middleware.options,d.headers=l.middleware.headers,{path:l.path,middleware:d}})).filter(a=>a!==void 0).flat()||[],s={...{signInOAuth:ae,callbackOAuth:le,getSession:z(),signOut:ue,signUpEmail:be(),signInEmail:de,forgetPassword:pe,resetPassword:fe,verifyEmail:ie,sendVerificationEmail:se,changeEmail:Ae,changePassword:ge,setPassword:he,updateUser:we(),deleteUser:ye,forgetPasswordCallback:me,listSessions:oe(),revokeSession:re,revokeSessions:ne,linkSocialAccount:Se,listUserAccounts:ke},...n,ok:Re,error:Ee},i={};for(let[a,l]of Object.entries(s))i[a]=async(d={})=>{let c=await e;for(let u of t.plugins||[])if(u.hooks?.before){for(let A of u.hooks.before)if(A.matcher({...l,...d,context:c})){let g=await A.handler({...d,context:{...c,...d?.context}});g&&"context"in g&&(c={...c,...g.context})}}let h;try{h=await l({...d,context:{...c,...d.context}})}catch(u){if(u instanceof Ie){let A=t.plugins?.map(g=>{if(g.hooks?.after)return g.hooks.after}).filter(g=>g!==void 0).flat();if(!A?.length)throw u;let m=new Response(JSON.stringify(u.body),{status:Ze[u.status],headers:u.headers});for(let g of A||[])if(g.matcher(d)){let H=Object.assign(d,{context:{...e,returned:m}}),Z=await g.handler(H);Z&&"response"in Z&&(m=Z.response)}return m}throw u}let w=h;for(let u of t.plugins||[])if(u.hooks?.after){for(let A of u.hooks.after)if(A.matcher(d)){let g=Object.assign(d,{context:{...e,returned:w}}),I=await A.handler(g);I&&"response"in I&&(w=I.response)}}return w},i[a].path=l.path,i[a].method=l.method,i[a].options=l.options,i[a].headers=l.headers;return{api:i,middlewares:r}}var fr=(e,t)=>{let{api:n,middlewares:r}=ze(e,t),o=new URL(e.baseURL).pathname;return He(n,{extraContext:e,basePath:o,routerMiddleware:[{path:"/**",middleware:te},...r],async onRequest(s){for(let i of e.options.plugins||[])if(i.onRequest){let a=await i.onRequest(s,e);if(a)return a}return Le(s,e)},async onResponse(s){for(let i of e.options.plugins||[])if(i.onResponse){let a=await i.onResponse(s,e);if(a)return a.response}return s},onError(s){if(t.onAPIError?.throw)throw s;if(t.onAPIError?.onError){t.onAPIError.onError(s,e);return}let i=t.logger?.verboseLogging?y:void 0;t.logger?.disabled!==!0&&(s instanceof Ie?(s.status==="INTERNAL_SERVER_ERROR"&&y.error(s),i?.error(s.message)):y?.error(s))}})};export{ee as a,N as b,p as c,te as d,z as e,W as f,b as g,oe as h,re as i,ne as j,O as k,se as l,ie as m,ae as n,de as o,ce as p,le as q,ue as r,pe as s,me as t,fe as u,we as v,ge as w,he as x,ye as y,Ae as z,Ee as A,Re as B,be as C,ke as D,Se as E,ze as F,fr as G,Er as H};
@@ -0,0 +1 @@
1
+ import{a as t}from"./chunk-RBJV2U7C.js";import{a as o}from"./chunk-72JSMFWS.js";function U(n){try{return new URL(n).pathname!=="/"}catch{throw new o(`Invalid base URL: ${n}. Please provide a valid base URL.`)}}function i(n,r="/api/auth"){return U(n)?n:(r=r.startsWith("/")?r:`/${r}`,`${n}${r}`)}function c(n,r){if(n)return i(n,r);let e=t.BETTER_AUTH_URL||t.NEXT_PUBLIC_BETTER_AUTH_URL||t.PUBLIC_BETTER_AUTH_URL||t.NUXT_PUBLIC_BETTER_AUTH_URL||t.NUXT_PUBLIC_AUTH_URL||(t.BASE_URL!=="/"?t.BASE_URL:void 0);if(e)return i(e,r);if(typeof window<"u")return i(window.location.origin,r)}function u(n){try{return new URL(n).origin}catch{return null}}export{c as a,u as b};
@@ -1 +1 @@
1
- import{b as r,c as s}from"./chunk-T5ZV4O5D.js";import{a as o}from"./chunk-J744ED5S.js";function C(i){let{pluginPathMethods:p,pluginsActions:f,pluginsAtoms:e,$fetch:t,atomListeners:l,$store:m}=r(i),n={};for(let[y,a]of Object.entries(e))n[`use${o(y)}`]=a;let c={...f,...n,$fetch:t,$store:m};return s(c,t,p,e,l)}export{C as a};
1
+ import{b as r,c as s}from"./chunk-3KYGESZG.js";import{a as o}from"./chunk-J744ED5S.js";function C(i){let{pluginPathMethods:p,pluginsActions:f,pluginsAtoms:e,$fetch:t,atomListeners:l,$store:m}=r(i),n={};for(let[y,a]of Object.entries(e))n[`use${o(y)}`]=a;let c={...f,...n,$fetch:t,$store:m};return s(c,t,p,e,l)}export{C as a};
@@ -1 +1 @@
1
- import{f as c,g as s}from"./chunk-UN6PZ3HT.js";import{c as p}from"./chunk-TCBMYTN7.js";import{a as f}from"./chunk-72JSMFWS.js";import{parseJWT as I}from"oslo/jwt";var h=r=>{let i="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:e,scopes:t,redirectURI:o}){let a=t||["email","name","openid"];return r.scope&&a.push(...r.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${r.clientId}&response_type=code&redirect_uri=${o||r.redirectURI}&scope=${a.join(" ")}&state=${e}`)},validateAuthorizationCode:async({code:e,codeVerifier:t,redirectURI:o})=>s({code:e,codeVerifier:t,redirectURI:r.redirectURI||o,options:r,tokenEndpoint:i}),async getUserInfo(e){if(!e.idToken)return null;let t=I(e.idToken)?.payload;return t?{user:{id:t.sub,name:t.name,email:t.email,emailVerified:t.email_verified==="true"},data:t}:null}}};import{betterFetch as R}from"@better-fetch/fetch";var _=r=>({id:"discord",name:"Discord",createAuthorizationURL({state:i,scopes:e,redirectURI:t}){let o=e||["identify","email"];return r.scope&&o.push(...r.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${o.join("+")}&response_type=code&client_id=${r.clientId}&redirect_uri=${encodeURIComponent(r.redirectURI||t)}&state=${i}`)},validateAuthorizationCode:async({code:i,redirectURI:e})=>s({code:i,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(i){let{data:e,error:t}=await R("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${i.accessToken}`}});if(t)return null;if(e.avatar===null){let o=e.discriminator==="0"?Number(BigInt(e.id)>>BigInt(22))%6:parseInt(e.discriminator)%5;e.image_url=`https://cdn.discordapp.com/embed/avatars/${o}.png`}else{let o=e.avatar.startsWith("a_")?"gif":"png";e.image_url=`https://cdn.discordapp.com/avatars/${e.id}/${e.avatar}.${o}`}return{user:{id:e.id,name:e.display_name||e.username||"",email:e.email,emailVerified:e.verified,image:e.image_url},data:e}}});import{betterFetch as T}from"@better-fetch/fetch";var b=r=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:i,scopes:e,redirectURI:t}){let o=e||["email","public_profile"];return r.scope&&o.push(...r.scope),await c({id:"facebook",options:r,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:o,state:i,redirectURI:t})},validateAuthorizationCode:async({code:i,redirectURI:e})=>s({code:i,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(i){let{data:e,error:t}=await T("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:i.accessToken}});return t?null:{user:{id:e.id,name:e.name,email:e.email,image:e.picture.data.url,emailVerified:e.email_verified},data:e}}});import{betterFetch as v}from"@better-fetch/fetch";var y=r=>{let i="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:e,scopes:t,codeVerifier:o,redirectURI:a}){let n=t||["user:email"];return r.scope&&n.push(...r.scope),c({id:"github",options:r,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:n,state:e,redirectURI:a,codeVerifier:o})},validateAuthorizationCode:async({code:e,redirectURI:t})=>s({code:e,redirectURI:r.redirectURI||t,options:r,tokenEndpoint:i}),async getUserInfo(e){let{data:t,error:o}=await v("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${e.accessToken}`}});if(o)return null;let a=!1;if(!t.email){let{data:n,error:d}=await v("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${e.accessToken}`,"User-Agent":"better-auth"}});d||(t.email=(n.find(l=>l.primary)??n[0])?.email,a=n.find(l=>l.email===t.email)?.verified??!1)}return{user:{id:t.id.toString(),name:t.name||t.login,email:t.email,image:t.avatar_url,emailVerified:a},data:t}}}};import{parseJWT as E}from"oslo/jwt";var P=r=>({id:"google",name:"Google",async createAuthorizationURL({state:i,scopes:e,codeVerifier:t,redirectURI:o}){if(!r.clientId||!r.clientSecret)throw p.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new f("CLIENT_ID_AND_SECRET_REQUIRED");if(!t)throw new f("codeVerifier is required for Google");let a=e||["email","profile","openid"];r.scope&&a.push(...r.scope);let n=await c({id:"google",options:r,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:a,state:i,codeVerifier:t,redirectURI:o});return r.accessType&&n.searchParams.set("access_type",r.accessType),r.prompt&&n.searchParams.set("prompt",r.prompt),n},validateAuthorizationCode:async({code:i,codeVerifier:e,redirectURI:t})=>s({code:i,codeVerifier:e,redirectURI:r.redirectURI||t,options:r,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(i){if(!i.idToken)return null;let e=E(i.idToken)?.payload;return{user:{id:e.sub,name:e.name,email:e.email,image:e.picture,emailVerified:e.email_verified},data:e}}});import{betterFetch as L}from"@better-fetch/fetch";import{parseJWT as $}from"oslo/jwt";var A=r=>{let i=r.tenantId||"common",e=`https://login.microsoftonline.com/${i}/oauth2/v2.0/authorize`,t=`https://login.microsoftonline.com/${i}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(o){let a=o.scopes||["openid","profile","email","User.Read"];return r.scope&&a.push(...r.scope),c({id:"microsoft",options:r,authorizationEndpoint:e,state:o.state,codeVerifier:o.codeVerifier,scopes:a,redirectURI:o.redirectURI})},validateAuthorizationCode({code:o,codeVerifier:a,redirectURI:n}){return s({code:o,codeVerifier:a,redirectURI:r.redirectURI||n,options:r,tokenEndpoint:t})},async getUserInfo(o){if(!o.idToken)return null;let a=$(o.idToken)?.payload,n=r.profilePhotoSize||48;return await L(`https://graph.microsoft.com/v1.0/me/photos/${n}x${n}/$value`,{headers:{Authorization:`Bearer ${o.accessToken}`},async onResponse(d){if(!(r.disableProfilePhoto||!d.response.ok))try{let m=await d.response.clone().arrayBuffer(),u=Buffer.from(m).toString("base64");a.picture=`data:image/jpeg;base64, ${u}`}catch(l){p.error(l)}}}),{user:{id:a.sub,name:a.name,email:a.email,image:a.picture,emailVerified:!0},data:a}}}};import{betterFetch as C}from"@better-fetch/fetch";var x=r=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:i,scopes:e,codeVerifier:t,redirectURI:o}){let a=e||["user-read-email"];return r.scope&&a.push(...r.scope),c({id:"spotify",options:r,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:a,state:i,codeVerifier:t,redirectURI:o})},validateAuthorizationCode:async({code:i,codeVerifier:e,redirectURI:t})=>s({code:i,codeVerifier:e,redirectURI:r.redirectURI||t,options:r,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(i){let{data:e,error:t}=await C("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});return t?null:{user:{id:e.id,name:e.display_name,email:e.email,image:e.images[0]?.url,emailVerified:!1},data:e}}});import"@better-fetch/fetch";import{parseJWT as G}from"oslo/jwt";var z=r=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:i,scopes:e,redirectURI:t}){let o=e||["user:read:email","openid"];return r.scope&&o.push(...r.scope),c({id:"twitch",redirectURI:t,options:r,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:i,claims:r.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:i,redirectURI:e})=>s({code:i,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(i){let e=i.idToken;if(!e)return p.error("No idToken found in token"),null;let t=G(e)?.payload;return{user:{id:t.sub,name:t.preferred_username,email:t.email,image:t.picture,emailVerified:!1},data:t}}});import{betterFetch as V}from"@better-fetch/fetch";var k=r=>({id:"twitter",name:"Twitter",createAuthorizationURL(i){let e=i.scopes||["account_info.read"];return r.scope&&e.push(...r.scope),c({id:"twitter",options:r,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:e,state:i.state,codeVerifier:i.codeVerifier,redirectURI:i.redirectURI})},validateAuthorizationCode:async({code:i,codeVerifier:e,redirectURI:t})=>s({code:i,codeVerifier:e,redirectURI:r.redirectURI||t,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(i){let{data:e,error:t}=await V("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});return t||!e.data.email?null:{user:{id:e.data.id,name:e.data.name,email:e.data.email,image:e.data.profile_image_url,emailVerified:e.data.verified||!1},data:e}}});import{betterFetch as D}from"@better-fetch/fetch";var w=r=>{let i="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:e,scopes:t,codeVerifier:o,redirectURI:a})=>{let n=t||["account_info.read"];return r.scope&&n.push(...r.scope),await c({id:"dropbox",options:r,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:n,state:e,redirectURI:a,codeVerifier:o})},validateAuthorizationCode:async({code:e,codeVerifier:t,redirectURI:o})=>await s({code:e,codeVerifier:t,redirectURI:r.redirectURI||o,options:r,tokenEndpoint:i}),async getUserInfo(e){let{data:t,error:o}=await D("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`}});return o?null:{user:{id:t.account_id,name:t.name?.display_name,email:t.email,emailVerified:t.email_verified||!1,image:t.profile_photo_url},data:t}}}};import{betterFetch as S}from"@better-fetch/fetch";var O=r=>{let i="https://www.linkedin.com/oauth/v2/authorization",e="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:t,scopes:o,redirectURI:a})=>{let n=o||["profile","email","openid"];return r.scope&&n.push(...r.scope),await c({id:"linkedin",options:r,authorizationEndpoint:i,scopes:n,state:t,redirectURI:a})},validateAuthorizationCode:async({code:t,redirectURI:o})=>await s({code:t,redirectURI:r.redirectURI||o,options:r,tokenEndpoint:e}),async getUserInfo(t){let{data:o,error:a}=await S("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return a?null:{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified||!1,image:o.picture},data:o}}}};import{betterFetch as B}from"@better-fetch/fetch";var g=(r="")=>r.split("://").map(i=>i.replace(/\/{2,}/g,"/")).join("://"),F=r=>{let i=r||"https://gitlab.com";return{authorizationEndpoint:g(`${i}/oauth/authorize`),tokenEndpoint:g(`${i}/oauth/token`),userinfoEndpoint:g(`${i}/api/v4/user`)}},U=r=>{let{authorizationEndpoint:i,tokenEndpoint:e,userinfoEndpoint:t}=F(r.issuer),o="gitlab";return{id:o,name:"Gitlab",createAuthorizationURL:async({state:n,scopes:d,codeVerifier:l,redirectURI:m})=>{let u=d||["read_user"];return r.scope&&u.push(...r.scope),await c({id:o,options:r,authorizationEndpoint:i,scopes:u,state:n,redirectURI:m,codeVerifier:l})},validateAuthorizationCode:async({code:n,redirectURI:d})=>s({code:n,redirectURI:r.redirectURI||d,options:r,tokenEndpoint:e}),async getUserInfo(n){let{data:d,error:l}=await B(t,{headers:{authorization:`Bearer ${n.accessToken}`}});return l||d.state!=="active"||d.locked?null:{user:{id:d.id.toString(),name:d.name??d.username,email:d.email,image:d.avatar_url,emailVerified:!0},data:d}}}};var j={apple:h,discord:_,facebook:b,github:y,microsoft:A,google:P,spotify:x,twitch:z,twitter:k,dropbox:w,linkedin:O,gitlab:U},Me=Object.keys(j);export{h as a,_ as b,b as c,y as d,P as e,A as f,x as g,z as h,k as i,w as j,O as k,U as l,j as m,Me as n};
1
+ import{f as c,g as s}from"./chunk-LXL7WUAT.js";import{c as p}from"./chunk-TCBMYTN7.js";import{a as f}from"./chunk-72JSMFWS.js";import{parseJWT as I}from"oslo/jwt";var h=r=>{let i="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:e,scopes:t,redirectURI:o}){let a=t||["email","name","openid"];return r.scope&&a.push(...r.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${r.clientId}&response_type=code&redirect_uri=${o||r.redirectURI}&scope=${a.join(" ")}&state=${e}`)},validateAuthorizationCode:async({code:e,codeVerifier:t,redirectURI:o})=>s({code:e,codeVerifier:t,redirectURI:r.redirectURI||o,options:r,tokenEndpoint:i}),async getUserInfo(e){if(!e.idToken)return null;let t=I(e.idToken)?.payload;return t?{user:{id:t.sub,name:t.name,email:t.email,emailVerified:t.email_verified==="true"},data:t}:null}}};import{betterFetch as R}from"@better-fetch/fetch";var _=r=>({id:"discord",name:"Discord",createAuthorizationURL({state:i,scopes:e,redirectURI:t}){let o=e||["identify","email"];return r.scope&&o.push(...r.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${o.join("+")}&response_type=code&client_id=${r.clientId}&redirect_uri=${encodeURIComponent(r.redirectURI||t)}&state=${i}`)},validateAuthorizationCode:async({code:i,redirectURI:e})=>s({code:i,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(i){let{data:e,error:t}=await R("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${i.accessToken}`}});if(t)return null;if(e.avatar===null){let o=e.discriminator==="0"?Number(BigInt(e.id)>>BigInt(22))%6:parseInt(e.discriminator)%5;e.image_url=`https://cdn.discordapp.com/embed/avatars/${o}.png`}else{let o=e.avatar.startsWith("a_")?"gif":"png";e.image_url=`https://cdn.discordapp.com/avatars/${e.id}/${e.avatar}.${o}`}return{user:{id:e.id,name:e.display_name||e.username||"",email:e.email,emailVerified:e.verified,image:e.image_url},data:e}}});import{betterFetch as T}from"@better-fetch/fetch";var b=r=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:i,scopes:e,redirectURI:t}){let o=e||["email","public_profile"];return r.scope&&o.push(...r.scope),await c({id:"facebook",options:r,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:o,state:i,redirectURI:t})},validateAuthorizationCode:async({code:i,redirectURI:e})=>s({code:i,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(i){let{data:e,error:t}=await T("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:i.accessToken}});return t?null:{user:{id:e.id,name:e.name,email:e.email,image:e.picture.data.url,emailVerified:e.email_verified},data:e}}});import{betterFetch as v}from"@better-fetch/fetch";var y=r=>{let i="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:e,scopes:t,codeVerifier:o,redirectURI:a}){let n=t||["user:email"];return r.scope&&n.push(...r.scope),c({id:"github",options:r,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:n,state:e,redirectURI:a,codeVerifier:o})},validateAuthorizationCode:async({code:e,redirectURI:t})=>s({code:e,redirectURI:r.redirectURI||t,options:r,tokenEndpoint:i}),async getUserInfo(e){let{data:t,error:o}=await v("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${e.accessToken}`}});if(o)return null;let a=!1;if(!t.email){let{data:n,error:d}=await v("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${e.accessToken}`,"User-Agent":"better-auth"}});d||(t.email=(n.find(l=>l.primary)??n[0])?.email,a=n.find(l=>l.email===t.email)?.verified??!1)}return{user:{id:t.id.toString(),name:t.name||t.login,email:t.email,image:t.avatar_url,emailVerified:a},data:t}}}};import{parseJWT as E}from"oslo/jwt";var P=r=>({id:"google",name:"Google",async createAuthorizationURL({state:i,scopes:e,codeVerifier:t,redirectURI:o}){if(!r.clientId||!r.clientSecret)throw p.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new f("CLIENT_ID_AND_SECRET_REQUIRED");if(!t)throw new f("codeVerifier is required for Google");let a=e||["email","profile","openid"];r.scope&&a.push(...r.scope);let n=await c({id:"google",options:r,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:a,state:i,codeVerifier:t,redirectURI:o});return r.accessType&&n.searchParams.set("access_type",r.accessType),r.prompt&&n.searchParams.set("prompt",r.prompt),n},validateAuthorizationCode:async({code:i,codeVerifier:e,redirectURI:t})=>s({code:i,codeVerifier:e,redirectURI:r.redirectURI||t,options:r,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(i){if(!i.idToken)return null;let e=E(i.idToken)?.payload;return{user:{id:e.sub,name:e.name,email:e.email,image:e.picture,emailVerified:e.email_verified},data:e}}});import{betterFetch as L}from"@better-fetch/fetch";import{parseJWT as $}from"oslo/jwt";var A=r=>{let i=r.tenantId||"common",e=`https://login.microsoftonline.com/${i}/oauth2/v2.0/authorize`,t=`https://login.microsoftonline.com/${i}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(o){let a=o.scopes||["openid","profile","email","User.Read"];return r.scope&&a.push(...r.scope),c({id:"microsoft",options:r,authorizationEndpoint:e,state:o.state,codeVerifier:o.codeVerifier,scopes:a,redirectURI:o.redirectURI})},validateAuthorizationCode({code:o,codeVerifier:a,redirectURI:n}){return s({code:o,codeVerifier:a,redirectURI:r.redirectURI||n,options:r,tokenEndpoint:t})},async getUserInfo(o){if(!o.idToken)return null;let a=$(o.idToken)?.payload,n=r.profilePhotoSize||48;return await L(`https://graph.microsoft.com/v1.0/me/photos/${n}x${n}/$value`,{headers:{Authorization:`Bearer ${o.accessToken}`},async onResponse(d){if(!(r.disableProfilePhoto||!d.response.ok))try{let m=await d.response.clone().arrayBuffer(),u=Buffer.from(m).toString("base64");a.picture=`data:image/jpeg;base64, ${u}`}catch(l){p.error(l)}}}),{user:{id:a.sub,name:a.name,email:a.email,image:a.picture,emailVerified:!0},data:a}}}};import{betterFetch as C}from"@better-fetch/fetch";var x=r=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:i,scopes:e,codeVerifier:t,redirectURI:o}){let a=e||["user-read-email"];return r.scope&&a.push(...r.scope),c({id:"spotify",options:r,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:a,state:i,codeVerifier:t,redirectURI:o})},validateAuthorizationCode:async({code:i,codeVerifier:e,redirectURI:t})=>s({code:i,codeVerifier:e,redirectURI:r.redirectURI||t,options:r,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(i){let{data:e,error:t}=await C("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});return t?null:{user:{id:e.id,name:e.display_name,email:e.email,image:e.images[0]?.url,emailVerified:!1},data:e}}});import"@better-fetch/fetch";import{parseJWT as G}from"oslo/jwt";var z=r=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:i,scopes:e,redirectURI:t}){let o=e||["user:read:email","openid"];return r.scope&&o.push(...r.scope),c({id:"twitch",redirectURI:t,options:r,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:i,claims:r.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:i,redirectURI:e})=>s({code:i,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(i){let e=i.idToken;if(!e)return p.error("No idToken found in token"),null;let t=G(e)?.payload;return{user:{id:t.sub,name:t.preferred_username,email:t.email,image:t.picture,emailVerified:!1},data:t}}});import{betterFetch as V}from"@better-fetch/fetch";var k=r=>({id:"twitter",name:"Twitter",createAuthorizationURL(i){let e=i.scopes||["account_info.read"];return r.scope&&e.push(...r.scope),c({id:"twitter",options:r,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:e,state:i.state,codeVerifier:i.codeVerifier,redirectURI:i.redirectURI})},validateAuthorizationCode:async({code:i,codeVerifier:e,redirectURI:t})=>s({code:i,codeVerifier:e,redirectURI:r.redirectURI||t,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(i){let{data:e,error:t}=await V("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});return t||!e.data.email?null:{user:{id:e.data.id,name:e.data.name,email:e.data.email,image:e.data.profile_image_url,emailVerified:e.data.verified||!1},data:e}}});import{betterFetch as D}from"@better-fetch/fetch";var w=r=>{let i="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:e,scopes:t,codeVerifier:o,redirectURI:a})=>{let n=t||["account_info.read"];return r.scope&&n.push(...r.scope),await c({id:"dropbox",options:r,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:n,state:e,redirectURI:a,codeVerifier:o})},validateAuthorizationCode:async({code:e,codeVerifier:t,redirectURI:o})=>await s({code:e,codeVerifier:t,redirectURI:r.redirectURI||o,options:r,tokenEndpoint:i}),async getUserInfo(e){let{data:t,error:o}=await D("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`}});return o?null:{user:{id:t.account_id,name:t.name?.display_name,email:t.email,emailVerified:t.email_verified||!1,image:t.profile_photo_url},data:t}}}};import{betterFetch as S}from"@better-fetch/fetch";var O=r=>{let i="https://www.linkedin.com/oauth/v2/authorization",e="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:t,scopes:o,redirectURI:a})=>{let n=o||["profile","email","openid"];return r.scope&&n.push(...r.scope),await c({id:"linkedin",options:r,authorizationEndpoint:i,scopes:n,state:t,redirectURI:a})},validateAuthorizationCode:async({code:t,redirectURI:o})=>await s({code:t,redirectURI:r.redirectURI||o,options:r,tokenEndpoint:e}),async getUserInfo(t){let{data:o,error:a}=await S("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return a?null:{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified||!1,image:o.picture},data:o}}}};import{betterFetch as B}from"@better-fetch/fetch";var g=(r="")=>r.split("://").map(i=>i.replace(/\/{2,}/g,"/")).join("://"),F=r=>{let i=r||"https://gitlab.com";return{authorizationEndpoint:g(`${i}/oauth/authorize`),tokenEndpoint:g(`${i}/oauth/token`),userinfoEndpoint:g(`${i}/api/v4/user`)}},U=r=>{let{authorizationEndpoint:i,tokenEndpoint:e,userinfoEndpoint:t}=F(r.issuer),o="gitlab";return{id:o,name:"Gitlab",createAuthorizationURL:async({state:n,scopes:d,codeVerifier:l,redirectURI:m})=>{let u=d||["read_user"];return r.scope&&u.push(...r.scope),await c({id:o,options:r,authorizationEndpoint:i,scopes:u,state:n,redirectURI:m,codeVerifier:l})},validateAuthorizationCode:async({code:n,redirectURI:d})=>s({code:n,redirectURI:r.redirectURI||d,options:r,tokenEndpoint:e}),async getUserInfo(n){let{data:d,error:l}=await B(t,{headers:{authorization:`Bearer ${n.accessToken}`}});return l||d.state!=="active"||d.locked?null:{user:{id:d.id.toString(),name:d.name??d.username,email:d.email,image:d.avatar_url,emailVerified:!0},data:d}}}};var j={apple:h,discord:_,facebook:b,github:y,microsoft:A,google:P,spotify:x,twitch:z,twitter:k,dropbox:w,linkedin:O,gitlab:U},Me=Object.keys(j);export{h as a,_ as b,b as c,y as d,P as e,A as f,x as g,z as h,k as i,w as j,O as k,U as l,j as m,Me as n};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk4O3SREZXcjs = require('./chunk-4O3SREZX.cjs');var _chunk2FTT4NBScjs = require('./chunk-2FTT4NBS.cjs');function C(i){let{pluginPathMethods:p,pluginsActions:f,pluginsAtoms:e,$fetch:t,atomListeners:l,$store:m}=_chunk4O3SREZXcjs.b.call(void 0, i),n={};for(let[y,a]of Object.entries(e))n[`use${_chunk2FTT4NBScjs.a.call(void 0, y)}`]=a;let c={...f,...n,$fetch:t,$store:m};return _chunk4O3SREZXcjs.c.call(void 0, c,t,p,e,l)}exports.a = C;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkUOTC7PMKcjs = require('./chunk-UOTC7PMK.cjs');var _chunk2FTT4NBScjs = require('./chunk-2FTT4NBS.cjs');function C(i){let{pluginPathMethods:p,pluginsActions:f,pluginsAtoms:e,$fetch:t,atomListeners:l,$store:m}=_chunkUOTC7PMKcjs.b.call(void 0, i),n={};for(let[y,a]of Object.entries(e))n[`use${_chunk2FTT4NBScjs.a.call(void 0, y)}`]=a;let c={...f,...n,$fetch:t,$store:m};return _chunkUOTC7PMKcjs.c.call(void 0, c,t,p,e,l)}exports.a = C;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkIYGMQ3UIcjs = require('./chunk-IYGMQ3UI.cjs');var _chunkL2NWG4J2cjs = require('./chunk-L2NWG4J2.cjs');var _crypto = require('oslo/crypto');var _encoding = require('oslo/encoding');async function h(e){let t=await _crypto.sha256.call(void 0, new TextEncoder().encode(e));return _encoding.base64url.encode(new Uint8Array(t),{includePadding:!1})}function x(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?_chunkIYGMQ3UIcjs.d.call(void 0, e.expires_in,"sec"):void 0,scopes:_optionalChain([e, 'optionalAccess', _2 => _2.scope])?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function S({id:e,options:t,authorizationEndpoint:o,state:n,codeVerifier:a,scopes:r,claims:s,disablePkce:p,redirectURI:f}){let i=new URL(o);if(i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t.clientId),i.searchParams.set("state",n),i.searchParams.set("scope",r.join(" ")),i.searchParams.set("redirect_uri",t.redirectURI||f),!p&&a){let l=await h(a);i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((m,R)=>(m[R]=null,m),{});i.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return i}var _fetch = require('@better-fetch/fetch');async function C({code:e,codeVerifier:t,redirectURI:o,options:n,tokenEndpoint:a}){let r=new URLSearchParams;r.set("grant_type","authorization_code"),r.set("code",e),t&&r.set("code_verifier",t),r.set("redirect_uri",o),r.set("client_id",n.clientId),r.set("client_secret",n.clientSecret);let{data:s,error:p}=await _fetch.betterFetch.call(void 0, a,{method:"POST",body:r,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(p)throw p;return x(s)}var _oauth2 = require('oslo/oauth2');var _zod = require('zod');var _bettercall = require('better-call');var D={isAction:!1};async function W(e){let t=_optionalChain([e, 'access', _3 => _3.body, 'optionalAccess', _4 => _4.callbackURL])||(_optionalChain([e, 'access', _5 => _5.query, 'optionalAccess', _6 => _6.currentURL])?_chunkL2NWG4J2cjs.b.call(void 0, _optionalChain([e, 'access', _7 => _7.query, 'optionalAccess', _8 => _8.currentURL])):"");if(!t)throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"callbackURL is required"});let o=_oauth2.generateCodeVerifier.call(void 0, ),n=_oauth2.generateState.call(void 0, ),a=JSON.stringify({callbackURL:t,codeVerifier:o,errorURL:_optionalChain([e, 'access', _9 => _9.query, 'optionalAccess', _10 => _10.currentURL]),expiresAt:Date.now()+10*60*1e3}),r=new Date;r.setMinutes(r.getMinutes()+10);let s=await e.context.internalAdapter.createVerificationValue({value:a,identifier:n,expiresAt:r});if(!s)throw _chunkIYGMQ3UIcjs.c.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new (0, _bettercall.APIError)("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:s.identifier,codeVerifier:o}}async function X(e){let t=e.query.state,o=await e.context.internalAdapter.findVerificationValue(t);if(!o)throw _chunkIYGMQ3UIcjs.c.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let n=_zod.z.object({callbackURL:_zod.z.string(),codeVerifier:_zod.z.string(),errorURL:_zod.z.string().optional(),expiresAt:_zod.z.number()}).parse(JSON.parse(o.value));if(n.errorURL||(n.errorURL=`${e.context.baseURL}/error`),n.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(o.id),_chunkIYGMQ3UIcjs.c.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(o.id),n}exports.a = D; exports.b = W; exports.c = X; exports.d = h; exports.e = x; exports.f = S; exports.g = C;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk6BZ4ST3Tcjs = require('./chunk-6BZ4ST3T.cjs');var _chunkJ6NPEQIVcjs = require('./chunk-J6NPEQIV.cjs');function U(n){try{return new URL(n).pathname!=="/"}catch (e2){throw new (0, _chunkJ6NPEQIVcjs.a)(`Invalid base URL: ${n}. Please provide a valid base URL.`)}}function i(n,r="/api/auth"){return U(n)?n:(r=r.startsWith("/")?r:`/${r}`,`${n}${r}`)}function c(n,r){if(n)return i(n,r);let e=_chunk6BZ4ST3Tcjs.a.BETTER_AUTH_URL||_chunk6BZ4ST3Tcjs.a.NEXT_PUBLIC_BETTER_AUTH_URL||_chunk6BZ4ST3Tcjs.a.PUBLIC_BETTER_AUTH_URL||_chunk6BZ4ST3Tcjs.a.NUXT_PUBLIC_BETTER_AUTH_URL||_chunk6BZ4ST3Tcjs.a.NUXT_PUBLIC_AUTH_URL||(_chunk6BZ4ST3Tcjs.a.BASE_URL!=="/"?_chunk6BZ4ST3Tcjs.a.BASE_URL:void 0);if(e)return i(e,r);if(typeof window<"u")return i(window.location.origin,r)}function u(n){try{return new URL(n).origin}catch (e3){return null}}exports.a = c; exports.b = u;
@@ -0,0 +1 @@
1
+ import{c as d,d as g}from"./chunk-TCBMYTN7.js";import{b as u}from"./chunk-C4UOK2CN.js";import{sha256 as _}from"oslo/crypto";import{base64url as k}from"oslo/encoding";async function h(e){let t=await _(new TextEncoder().encode(e));return k.encode(new Uint8Array(t),{includePadding:!1})}function x(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?g(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function S({id:e,options:t,authorizationEndpoint:o,state:n,codeVerifier:a,scopes:r,claims:s,disablePkce:p,redirectURI:f}){let i=new URL(o);if(i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t.clientId),i.searchParams.set("state",n),i.searchParams.set("scope",r.join(" ")),i.searchParams.set("redirect_uri",t.redirectURI||f),!p&&a){let l=await h(a);i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((m,R)=>(m[R]=null,m),{});i.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return i}import{betterFetch as U}from"@better-fetch/fetch";async function C({code:e,codeVerifier:t,redirectURI:o,options:n,tokenEndpoint:a}){let r=new URLSearchParams;r.set("grant_type","authorization_code"),r.set("code",e),t&&r.set("code_verifier",t),r.set("redirect_uri",o),r.set("client_id",n.clientId),r.set("client_secret",n.clientSecret);let{data:s,error:p}=await U(a,{method:"POST",body:r,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(p)throw p;return x(s)}import{generateCodeVerifier as b,generateState as w}from"oslo/oauth2";import{z as c}from"zod";import{APIError as y}from"better-call";var D={isAction:!1};async function W(e){let t=e.body?.callbackURL||(e.query?.currentURL?u(e.query?.currentURL):"");if(!t)throw new y("BAD_REQUEST",{message:"callbackURL is required"});let o=b(),n=w(),a=JSON.stringify({callbackURL:t,codeVerifier:o,errorURL:e.query?.currentURL,expiresAt:Date.now()+10*60*1e3}),r=new Date;r.setMinutes(r.getMinutes()+10);let s=await e.context.internalAdapter.createVerificationValue({value:a,identifier:n,expiresAt:r});if(!s)throw d.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new y("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:s.identifier,codeVerifier:o}}async function X(e){let t=e.query.state,o=await e.context.internalAdapter.findVerificationValue(t);if(!o)throw d.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let n=c.object({callbackURL:c.string(),codeVerifier:c.string(),errorURL:c.string().optional(),expiresAt:c.number()}).parse(JSON.parse(o.value));if(n.errorURL||(n.errorURL=`${e.context.baseURL}/error`),n.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(o.id),d.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(o.id),n}export{D as a,W as b,X as c,h as d,x as e,S as f,C as g};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkWFO5B3ONcjs = require('./chunk-WFO5B3ON.cjs');var _chunkIYGMQ3UIcjs = require('./chunk-IYGMQ3UI.cjs');var _chunkJ6NPEQIVcjs = require('./chunk-J6NPEQIV.cjs');var _jwt = require('oslo/jwt');var h=r=>{let i="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:e,scopes:t,redirectURI:o}){let a=t||["email","name","openid"];return r.scope&&a.push(...r.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${r.clientId}&response_type=code&redirect_uri=${o||r.redirectURI}&scope=${a.join(" ")}&state=${e}`)},validateAuthorizationCode:async({code:e,codeVerifier:t,redirectURI:o})=>_chunkWFO5B3ONcjs.g.call(void 0, {code:e,codeVerifier:t,redirectURI:r.redirectURI||o,options:r,tokenEndpoint:i}),async getUserInfo(e){if(!e.idToken)return null;let t=_optionalChain([_jwt.parseJWT.call(void 0, e.idToken), 'optionalAccess', _2 => _2.payload]);return t?{user:{id:t.sub,name:t.name,email:t.email,emailVerified:t.email_verified==="true"},data:t}:null}}};var _fetch = require('@better-fetch/fetch');var _=r=>({id:"discord",name:"Discord",createAuthorizationURL({state:i,scopes:e,redirectURI:t}){let o=e||["identify","email"];return r.scope&&o.push(...r.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${o.join("+")}&response_type=code&client_id=${r.clientId}&redirect_uri=${encodeURIComponent(r.redirectURI||t)}&state=${i}`)},validateAuthorizationCode:async({code:i,redirectURI:e})=>_chunkWFO5B3ONcjs.g.call(void 0, {code:i,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(i){let{data:e,error:t}=await _fetch.betterFetch.call(void 0, "https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${i.accessToken}`}});if(t)return null;if(e.avatar===null){let o=e.discriminator==="0"?Number(BigInt(e.id)>>BigInt(22))%6:parseInt(e.discriminator)%5;e.image_url=`https://cdn.discordapp.com/embed/avatars/${o}.png`}else{let o=e.avatar.startsWith("a_")?"gif":"png";e.image_url=`https://cdn.discordapp.com/avatars/${e.id}/${e.avatar}.${o}`}return{user:{id:e.id,name:e.display_name||e.username||"",email:e.email,emailVerified:e.verified,image:e.image_url},data:e}}});var b=r=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:i,scopes:e,redirectURI:t}){let o=e||["email","public_profile"];return r.scope&&o.push(...r.scope),await _chunkWFO5B3ONcjs.f.call(void 0, {id:"facebook",options:r,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:o,state:i,redirectURI:t})},validateAuthorizationCode:async({code:i,redirectURI:e})=>_chunkWFO5B3ONcjs.g.call(void 0, {code:i,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(i){let{data:e,error:t}=await _fetch.betterFetch.call(void 0, "https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:i.accessToken}});return t?null:{user:{id:e.id,name:e.name,email:e.email,image:e.picture.data.url,emailVerified:e.email_verified},data:e}}});var y=r=>{let i="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:e,scopes:t,codeVerifier:o,redirectURI:a}){let n=t||["user:email"];return r.scope&&n.push(...r.scope),_chunkWFO5B3ONcjs.f.call(void 0, {id:"github",options:r,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:n,state:e,redirectURI:a,codeVerifier:o})},validateAuthorizationCode:async({code:e,redirectURI:t})=>_chunkWFO5B3ONcjs.g.call(void 0, {code:e,redirectURI:r.redirectURI||t,options:r,tokenEndpoint:i}),async getUserInfo(e){let{data:t,error:o}=await _fetch.betterFetch.call(void 0, "https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${e.accessToken}`}});if(o)return null;let a=!1;if(!t.email){let{data:n,error:d}=await _fetch.betterFetch.call(void 0, "https://api.github.com/user/emails",{headers:{authorization:`Bearer ${e.accessToken}`,"User-Agent":"better-auth"}});d||(t.email=_optionalChain([(_nullishCoalesce(n.find(l=>l.primary), () => (n[0]))), 'optionalAccess', _3 => _3.email]),a=_nullishCoalesce(_optionalChain([n, 'access', _4 => _4.find, 'call', _5 => _5(l=>l.email===t.email), 'optionalAccess', _6 => _6.verified]), () => (!1)))}return{user:{id:t.id.toString(),name:t.name||t.login,email:t.email,image:t.avatar_url,emailVerified:a},data:t}}}};var P=r=>({id:"google",name:"Google",async createAuthorizationURL({state:i,scopes:e,codeVerifier:t,redirectURI:o}){if(!r.clientId||!r.clientSecret)throw _chunkIYGMQ3UIcjs.c.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new (0, _chunkJ6NPEQIVcjs.a)("CLIENT_ID_AND_SECRET_REQUIRED");if(!t)throw new (0, _chunkJ6NPEQIVcjs.a)("codeVerifier is required for Google");let a=e||["email","profile","openid"];r.scope&&a.push(...r.scope);let n=await _chunkWFO5B3ONcjs.f.call(void 0, {id:"google",options:r,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:a,state:i,codeVerifier:t,redirectURI:o});return r.accessType&&n.searchParams.set("access_type",r.accessType),r.prompt&&n.searchParams.set("prompt",r.prompt),n},validateAuthorizationCode:async({code:i,codeVerifier:e,redirectURI:t})=>_chunkWFO5B3ONcjs.g.call(void 0, {code:i,codeVerifier:e,redirectURI:r.redirectURI||t,options:r,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(i){if(!i.idToken)return null;let e=_optionalChain([_jwt.parseJWT.call(void 0, i.idToken), 'optionalAccess', _7 => _7.payload]);return{user:{id:e.sub,name:e.name,email:e.email,image:e.picture,emailVerified:e.email_verified},data:e}}});var A=r=>{let i=r.tenantId||"common",e=`https://login.microsoftonline.com/${i}/oauth2/v2.0/authorize`,t=`https://login.microsoftonline.com/${i}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(o){let a=o.scopes||["openid","profile","email","User.Read"];return r.scope&&a.push(...r.scope),_chunkWFO5B3ONcjs.f.call(void 0, {id:"microsoft",options:r,authorizationEndpoint:e,state:o.state,codeVerifier:o.codeVerifier,scopes:a,redirectURI:o.redirectURI})},validateAuthorizationCode({code:o,codeVerifier:a,redirectURI:n}){return _chunkWFO5B3ONcjs.g.call(void 0, {code:o,codeVerifier:a,redirectURI:r.redirectURI||n,options:r,tokenEndpoint:t})},async getUserInfo(o){if(!o.idToken)return null;let a=_optionalChain([_jwt.parseJWT.call(void 0, o.idToken), 'optionalAccess', _8 => _8.payload]),n=r.profilePhotoSize||48;return await _fetch.betterFetch.call(void 0, `https://graph.microsoft.com/v1.0/me/photos/${n}x${n}/$value`,{headers:{Authorization:`Bearer ${o.accessToken}`},async onResponse(d){if(!(r.disableProfilePhoto||!d.response.ok))try{let m=await d.response.clone().arrayBuffer(),u=Buffer.from(m).toString("base64");a.picture=`data:image/jpeg;base64, ${u}`}catch(l){_chunkIYGMQ3UIcjs.c.error(l)}}}),{user:{id:a.sub,name:a.name,email:a.email,image:a.picture,emailVerified:!0},data:a}}}};var x=r=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:i,scopes:e,codeVerifier:t,redirectURI:o}){let a=e||["user-read-email"];return r.scope&&a.push(...r.scope),_chunkWFO5B3ONcjs.f.call(void 0, {id:"spotify",options:r,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:a,state:i,codeVerifier:t,redirectURI:o})},validateAuthorizationCode:async({code:i,codeVerifier:e,redirectURI:t})=>_chunkWFO5B3ONcjs.g.call(void 0, {code:i,codeVerifier:e,redirectURI:r.redirectURI||t,options:r,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(i){let{data:e,error:t}=await _fetch.betterFetch.call(void 0, "https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});return t?null:{user:{id:e.id,name:e.display_name,email:e.email,image:_optionalChain([e, 'access', _9 => _9.images, 'access', _10 => _10[0], 'optionalAccess', _11 => _11.url]),emailVerified:!1},data:e}}});var z=r=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:i,scopes:e,redirectURI:t}){let o=e||["user:read:email","openid"];return r.scope&&o.push(...r.scope),_chunkWFO5B3ONcjs.f.call(void 0, {id:"twitch",redirectURI:t,options:r,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:i,claims:r.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:i,redirectURI:e})=>_chunkWFO5B3ONcjs.g.call(void 0, {code:i,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(i){let e=i.idToken;if(!e)return _chunkIYGMQ3UIcjs.c.error("No idToken found in token"),null;let t=_optionalChain([_jwt.parseJWT.call(void 0, e), 'optionalAccess', _12 => _12.payload]);return{user:{id:t.sub,name:t.preferred_username,email:t.email,image:t.picture,emailVerified:!1},data:t}}});var k=r=>({id:"twitter",name:"Twitter",createAuthorizationURL(i){let e=i.scopes||["account_info.read"];return r.scope&&e.push(...r.scope),_chunkWFO5B3ONcjs.f.call(void 0, {id:"twitter",options:r,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:e,state:i.state,codeVerifier:i.codeVerifier,redirectURI:i.redirectURI})},validateAuthorizationCode:async({code:i,codeVerifier:e,redirectURI:t})=>_chunkWFO5B3ONcjs.g.call(void 0, {code:i,codeVerifier:e,redirectURI:r.redirectURI||t,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(i){let{data:e,error:t}=await _fetch.betterFetch.call(void 0, "https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});return t||!e.data.email?null:{user:{id:e.data.id,name:e.data.name,email:e.data.email,image:e.data.profile_image_url,emailVerified:e.data.verified||!1},data:e}}});var w=r=>{let i="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:e,scopes:t,codeVerifier:o,redirectURI:a})=>{let n=t||["account_info.read"];return r.scope&&n.push(...r.scope),await _chunkWFO5B3ONcjs.f.call(void 0, {id:"dropbox",options:r,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:n,state:e,redirectURI:a,codeVerifier:o})},validateAuthorizationCode:async({code:e,codeVerifier:t,redirectURI:o})=>await _chunkWFO5B3ONcjs.g.call(void 0, {code:e,codeVerifier:t,redirectURI:r.redirectURI||o,options:r,tokenEndpoint:i}),async getUserInfo(e){let{data:t,error:o}=await _fetch.betterFetch.call(void 0, "https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`}});return o?null:{user:{id:t.account_id,name:_optionalChain([t, 'access', _13 => _13.name, 'optionalAccess', _14 => _14.display_name]),email:t.email,emailVerified:t.email_verified||!1,image:t.profile_photo_url},data:t}}}};var O=r=>{let i="https://www.linkedin.com/oauth/v2/authorization",e="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:t,scopes:o,redirectURI:a})=>{let n=o||["profile","email","openid"];return r.scope&&n.push(...r.scope),await _chunkWFO5B3ONcjs.f.call(void 0, {id:"linkedin",options:r,authorizationEndpoint:i,scopes:n,state:t,redirectURI:a})},validateAuthorizationCode:async({code:t,redirectURI:o})=>await _chunkWFO5B3ONcjs.g.call(void 0, {code:t,redirectURI:r.redirectURI||o,options:r,tokenEndpoint:e}),async getUserInfo(t){let{data:o,error:a}=await _fetch.betterFetch.call(void 0, "https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return a?null:{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified||!1,image:o.picture},data:o}}}};var g=(r="")=>r.split("://").map(i=>i.replace(/\/{2,}/g,"/")).join("://"),F=r=>{let i=r||"https://gitlab.com";return{authorizationEndpoint:g(`${i}/oauth/authorize`),tokenEndpoint:g(`${i}/oauth/token`),userinfoEndpoint:g(`${i}/api/v4/user`)}},U= exports.l =r=>{let{authorizationEndpoint:i,tokenEndpoint:e,userinfoEndpoint:t}=F(r.issuer),o="gitlab";return{id:o,name:"Gitlab",createAuthorizationURL:async({state:n,scopes:d,codeVerifier:l,redirectURI:m})=>{let u=d||["read_user"];return r.scope&&u.push(...r.scope),await _chunkWFO5B3ONcjs.f.call(void 0, {id:o,options:r,authorizationEndpoint:i,scopes:u,state:n,redirectURI:m,codeVerifier:l})},validateAuthorizationCode:async({code:n,redirectURI:d})=>_chunkWFO5B3ONcjs.g.call(void 0, {code:n,redirectURI:r.redirectURI||d,options:r,tokenEndpoint:e}),async getUserInfo(n){let{data:d,error:l}=await _fetch.betterFetch.call(void 0, t,{headers:{authorization:`Bearer ${n.accessToken}`}});return l||d.state!=="active"||d.locked?null:{user:{id:d.id.toString(),name:_nullishCoalesce(d.name, () => (d.username)),email:d.email,image:d.avatar_url,emailVerified:!0},data:d}}}};var j={apple:h,discord:_,facebook:b,github:y,microsoft:A,google:P,spotify:x,twitch:z,twitter:k,dropbox:w,linkedin:O,gitlab:U},Me= exports.n =Object.keys(j);exports.a = h; exports.b = _; exports.c = b; exports.d = y; exports.e = P; exports.f = A; exports.g = x; exports.h = z; exports.i = k; exports.j = w; exports.k = O; exports.l = U; exports.m = j; exports.n = Me;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkHQJTAUZEcjs = require('./chunk-HQJTAUZE.cjs');var _chunkIYGMQ3UIcjs = require('./chunk-IYGMQ3UI.cjs');var _chunkJ6NPEQIVcjs = require('./chunk-J6NPEQIV.cjs');var _jwt = require('oslo/jwt');var h=r=>{let i="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:e,scopes:t,redirectURI:o}){let a=t||["email","name","openid"];return r.scope&&a.push(...r.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${r.clientId}&response_type=code&redirect_uri=${o||r.redirectURI}&scope=${a.join(" ")}&state=${e}`)},validateAuthorizationCode:async({code:e,codeVerifier:t,redirectURI:o})=>_chunkHQJTAUZEcjs.g.call(void 0, {code:e,codeVerifier:t,redirectURI:r.redirectURI||o,options:r,tokenEndpoint:i}),async getUserInfo(e){if(!e.idToken)return null;let t=_optionalChain([_jwt.parseJWT.call(void 0, e.idToken), 'optionalAccess', _2 => _2.payload]);return t?{user:{id:t.sub,name:t.name,email:t.email,emailVerified:t.email_verified==="true"},data:t}:null}}};var _fetch = require('@better-fetch/fetch');var _=r=>({id:"discord",name:"Discord",createAuthorizationURL({state:i,scopes:e,redirectURI:t}){let o=e||["identify","email"];return r.scope&&o.push(...r.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${o.join("+")}&response_type=code&client_id=${r.clientId}&redirect_uri=${encodeURIComponent(r.redirectURI||t)}&state=${i}`)},validateAuthorizationCode:async({code:i,redirectURI:e})=>_chunkHQJTAUZEcjs.g.call(void 0, {code:i,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(i){let{data:e,error:t}=await _fetch.betterFetch.call(void 0, "https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${i.accessToken}`}});if(t)return null;if(e.avatar===null){let o=e.discriminator==="0"?Number(BigInt(e.id)>>BigInt(22))%6:parseInt(e.discriminator)%5;e.image_url=`https://cdn.discordapp.com/embed/avatars/${o}.png`}else{let o=e.avatar.startsWith("a_")?"gif":"png";e.image_url=`https://cdn.discordapp.com/avatars/${e.id}/${e.avatar}.${o}`}return{user:{id:e.id,name:e.display_name||e.username||"",email:e.email,emailVerified:e.verified,image:e.image_url},data:e}}});var b=r=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:i,scopes:e,redirectURI:t}){let o=e||["email","public_profile"];return r.scope&&o.push(...r.scope),await _chunkHQJTAUZEcjs.f.call(void 0, {id:"facebook",options:r,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:o,state:i,redirectURI:t})},validateAuthorizationCode:async({code:i,redirectURI:e})=>_chunkHQJTAUZEcjs.g.call(void 0, {code:i,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(i){let{data:e,error:t}=await _fetch.betterFetch.call(void 0, "https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:i.accessToken}});return t?null:{user:{id:e.id,name:e.name,email:e.email,image:e.picture.data.url,emailVerified:e.email_verified},data:e}}});var y=r=>{let i="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:e,scopes:t,codeVerifier:o,redirectURI:a}){let n=t||["user:email"];return r.scope&&n.push(...r.scope),_chunkHQJTAUZEcjs.f.call(void 0, {id:"github",options:r,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:n,state:e,redirectURI:a,codeVerifier:o})},validateAuthorizationCode:async({code:e,redirectURI:t})=>_chunkHQJTAUZEcjs.g.call(void 0, {code:e,redirectURI:r.redirectURI||t,options:r,tokenEndpoint:i}),async getUserInfo(e){let{data:t,error:o}=await _fetch.betterFetch.call(void 0, "https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${e.accessToken}`}});if(o)return null;let a=!1;if(!t.email){let{data:n,error:d}=await _fetch.betterFetch.call(void 0, "https://api.github.com/user/emails",{headers:{authorization:`Bearer ${e.accessToken}`,"User-Agent":"better-auth"}});d||(t.email=_optionalChain([(_nullishCoalesce(n.find(l=>l.primary), () => (n[0]))), 'optionalAccess', _3 => _3.email]),a=_nullishCoalesce(_optionalChain([n, 'access', _4 => _4.find, 'call', _5 => _5(l=>l.email===t.email), 'optionalAccess', _6 => _6.verified]), () => (!1)))}return{user:{id:t.id.toString(),name:t.name||t.login,email:t.email,image:t.avatar_url,emailVerified:a},data:t}}}};var P=r=>({id:"google",name:"Google",async createAuthorizationURL({state:i,scopes:e,codeVerifier:t,redirectURI:o}){if(!r.clientId||!r.clientSecret)throw _chunkIYGMQ3UIcjs.c.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new (0, _chunkJ6NPEQIVcjs.a)("CLIENT_ID_AND_SECRET_REQUIRED");if(!t)throw new (0, _chunkJ6NPEQIVcjs.a)("codeVerifier is required for Google");let a=e||["email","profile","openid"];r.scope&&a.push(...r.scope);let n=await _chunkHQJTAUZEcjs.f.call(void 0, {id:"google",options:r,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:a,state:i,codeVerifier:t,redirectURI:o});return r.accessType&&n.searchParams.set("access_type",r.accessType),r.prompt&&n.searchParams.set("prompt",r.prompt),n},validateAuthorizationCode:async({code:i,codeVerifier:e,redirectURI:t})=>_chunkHQJTAUZEcjs.g.call(void 0, {code:i,codeVerifier:e,redirectURI:r.redirectURI||t,options:r,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(i){if(!i.idToken)return null;let e=_optionalChain([_jwt.parseJWT.call(void 0, i.idToken), 'optionalAccess', _7 => _7.payload]);return{user:{id:e.sub,name:e.name,email:e.email,image:e.picture,emailVerified:e.email_verified},data:e}}});var A=r=>{let i=r.tenantId||"common",e=`https://login.microsoftonline.com/${i}/oauth2/v2.0/authorize`,t=`https://login.microsoftonline.com/${i}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(o){let a=o.scopes||["openid","profile","email","User.Read"];return r.scope&&a.push(...r.scope),_chunkHQJTAUZEcjs.f.call(void 0, {id:"microsoft",options:r,authorizationEndpoint:e,state:o.state,codeVerifier:o.codeVerifier,scopes:a,redirectURI:o.redirectURI})},validateAuthorizationCode({code:o,codeVerifier:a,redirectURI:n}){return _chunkHQJTAUZEcjs.g.call(void 0, {code:o,codeVerifier:a,redirectURI:r.redirectURI||n,options:r,tokenEndpoint:t})},async getUserInfo(o){if(!o.idToken)return null;let a=_optionalChain([_jwt.parseJWT.call(void 0, o.idToken), 'optionalAccess', _8 => _8.payload]),n=r.profilePhotoSize||48;return await _fetch.betterFetch.call(void 0, `https://graph.microsoft.com/v1.0/me/photos/${n}x${n}/$value`,{headers:{Authorization:`Bearer ${o.accessToken}`},async onResponse(d){if(!(r.disableProfilePhoto||!d.response.ok))try{let m=await d.response.clone().arrayBuffer(),u=Buffer.from(m).toString("base64");a.picture=`data:image/jpeg;base64, ${u}`}catch(l){_chunkIYGMQ3UIcjs.c.error(l)}}}),{user:{id:a.sub,name:a.name,email:a.email,image:a.picture,emailVerified:!0},data:a}}}};var x=r=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:i,scopes:e,codeVerifier:t,redirectURI:o}){let a=e||["user-read-email"];return r.scope&&a.push(...r.scope),_chunkHQJTAUZEcjs.f.call(void 0, {id:"spotify",options:r,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:a,state:i,codeVerifier:t,redirectURI:o})},validateAuthorizationCode:async({code:i,codeVerifier:e,redirectURI:t})=>_chunkHQJTAUZEcjs.g.call(void 0, {code:i,codeVerifier:e,redirectURI:r.redirectURI||t,options:r,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(i){let{data:e,error:t}=await _fetch.betterFetch.call(void 0, "https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});return t?null:{user:{id:e.id,name:e.display_name,email:e.email,image:_optionalChain([e, 'access', _9 => _9.images, 'access', _10 => _10[0], 'optionalAccess', _11 => _11.url]),emailVerified:!1},data:e}}});var z=r=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:i,scopes:e,redirectURI:t}){let o=e||["user:read:email","openid"];return r.scope&&o.push(...r.scope),_chunkHQJTAUZEcjs.f.call(void 0, {id:"twitch",redirectURI:t,options:r,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:o,state:i,claims:r.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:i,redirectURI:e})=>_chunkHQJTAUZEcjs.g.call(void 0, {code:i,redirectURI:r.redirectURI||e,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(i){let e=i.idToken;if(!e)return _chunkIYGMQ3UIcjs.c.error("No idToken found in token"),null;let t=_optionalChain([_jwt.parseJWT.call(void 0, e), 'optionalAccess', _12 => _12.payload]);return{user:{id:t.sub,name:t.preferred_username,email:t.email,image:t.picture,emailVerified:!1},data:t}}});var k=r=>({id:"twitter",name:"Twitter",createAuthorizationURL(i){let e=i.scopes||["account_info.read"];return r.scope&&e.push(...r.scope),_chunkHQJTAUZEcjs.f.call(void 0, {id:"twitter",options:r,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:e,state:i.state,codeVerifier:i.codeVerifier,redirectURI:i.redirectURI})},validateAuthorizationCode:async({code:i,codeVerifier:e,redirectURI:t})=>_chunkHQJTAUZEcjs.g.call(void 0, {code:i,codeVerifier:e,redirectURI:r.redirectURI||t,options:r,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(i){let{data:e,error:t}=await _fetch.betterFetch.call(void 0, "https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${i.accessToken}`}});return t||!e.data.email?null:{user:{id:e.data.id,name:e.data.name,email:e.data.email,image:e.data.profile_image_url,emailVerified:e.data.verified||!1},data:e}}});var w=r=>{let i="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:e,scopes:t,codeVerifier:o,redirectURI:a})=>{let n=t||["account_info.read"];return r.scope&&n.push(...r.scope),await _chunkHQJTAUZEcjs.f.call(void 0, {id:"dropbox",options:r,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:n,state:e,redirectURI:a,codeVerifier:o})},validateAuthorizationCode:async({code:e,codeVerifier:t,redirectURI:o})=>await _chunkHQJTAUZEcjs.g.call(void 0, {code:e,codeVerifier:t,redirectURI:r.redirectURI||o,options:r,tokenEndpoint:i}),async getUserInfo(e){let{data:t,error:o}=await _fetch.betterFetch.call(void 0, "https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`}});return o?null:{user:{id:t.account_id,name:_optionalChain([t, 'access', _13 => _13.name, 'optionalAccess', _14 => _14.display_name]),email:t.email,emailVerified:t.email_verified||!1,image:t.profile_photo_url},data:t}}}};var O=r=>{let i="https://www.linkedin.com/oauth/v2/authorization",e="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:t,scopes:o,redirectURI:a})=>{let n=o||["profile","email","openid"];return r.scope&&n.push(...r.scope),await _chunkHQJTAUZEcjs.f.call(void 0, {id:"linkedin",options:r,authorizationEndpoint:i,scopes:n,state:t,redirectURI:a})},validateAuthorizationCode:async({code:t,redirectURI:o})=>await _chunkHQJTAUZEcjs.g.call(void 0, {code:t,redirectURI:r.redirectURI||o,options:r,tokenEndpoint:e}),async getUserInfo(t){let{data:o,error:a}=await _fetch.betterFetch.call(void 0, "https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return a?null:{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified||!1,image:o.picture},data:o}}}};var g=(r="")=>r.split("://").map(i=>i.replace(/\/{2,}/g,"/")).join("://"),F=r=>{let i=r||"https://gitlab.com";return{authorizationEndpoint:g(`${i}/oauth/authorize`),tokenEndpoint:g(`${i}/oauth/token`),userinfoEndpoint:g(`${i}/api/v4/user`)}},U= exports.l =r=>{let{authorizationEndpoint:i,tokenEndpoint:e,userinfoEndpoint:t}=F(r.issuer),o="gitlab";return{id:o,name:"Gitlab",createAuthorizationURL:async({state:n,scopes:d,codeVerifier:l,redirectURI:m})=>{let u=d||["read_user"];return r.scope&&u.push(...r.scope),await _chunkHQJTAUZEcjs.f.call(void 0, {id:o,options:r,authorizationEndpoint:i,scopes:u,state:n,redirectURI:m,codeVerifier:l})},validateAuthorizationCode:async({code:n,redirectURI:d})=>_chunkHQJTAUZEcjs.g.call(void 0, {code:n,redirectURI:r.redirectURI||d,options:r,tokenEndpoint:e}),async getUserInfo(n){let{data:d,error:l}=await _fetch.betterFetch.call(void 0, t,{headers:{authorization:`Bearer ${n.accessToken}`}});return l||d.state!=="active"||d.locked?null:{user:{id:d.id.toString(),name:_nullishCoalesce(d.name, () => (d.username)),email:d.email,image:d.avatar_url,emailVerified:!0},data:d}}}};var j={apple:h,discord:_,facebook:b,github:y,microsoft:A,google:P,spotify:x,twitch:z,twitter:k,dropbox:w,linkedin:O,gitlab:U},Me= exports.n =Object.keys(j);exports.a = h; exports.b = _; exports.c = b; exports.d = y; exports.e = P; exports.f = A; exports.g = x; exports.h = z; exports.i = k; exports.j = w; exports.k = O; exports.l = U; exports.m = j; exports.n = Me;