better-auth 0.7.6-beta.1 → 0.7.6-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.
- package/dist/adapters/drizzle.d.cts +2 -2
- package/dist/adapters/drizzle.d.ts +2 -2
- package/dist/adapters/kysely.d.cts +2 -2
- package/dist/adapters/kysely.d.ts +2 -2
- package/dist/adapters/mongodb.d.cts +2 -2
- package/dist/adapters/mongodb.d.ts +2 -2
- package/dist/adapters/prisma.d.cts +2 -2
- package/dist/adapters/prisma.d.ts +2 -2
- package/dist/api.cjs +1 -1
- package/dist/api.d.cts +2 -2
- package/dist/api.d.ts +2 -2
- package/dist/api.js +1 -1
- package/dist/{auth-i01HJsBT.d.ts → auth-Bwhilbe9.d.ts} +95 -95
- package/dist/{auth-DnVNaNo4.d.cts → auth-Q13brXF4.d.cts} +95 -95
- package/dist/client/plugins.cjs +1 -1
- package/dist/client/plugins.d.cts +4 -4
- package/dist/client/plugins.d.ts +4 -4
- package/dist/client/plugins.js +1 -1
- package/dist/client.d.cts +2 -2
- package/dist/client.d.ts +2 -2
- package/dist/cookies.d.cts +2 -2
- package/dist/cookies.d.ts +2 -2
- package/dist/db.d.cts +3 -3
- package/dist/db.d.ts +3 -3
- package/dist/{index-B7acmBVh.d.cts → index-B760BAOD.d.cts} +8 -8
- package/dist/{index-TBR5Nwgw.d.ts → index-BZJGb1S9.d.ts} +8 -8
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/node.d.cts +2 -2
- package/dist/node.d.ts +2 -2
- package/dist/oauth2.d.cts +4 -4
- package/dist/oauth2.d.ts +4 -4
- package/dist/plugins.d.cts +10 -10
- package/dist/plugins.d.ts +10 -10
- package/dist/react.d.cts +2 -2
- package/dist/react.d.ts +2 -2
- package/dist/social.d.cts +1 -1
- package/dist/social.d.ts +1 -1
- package/dist/solid-start.d.cts +2 -2
- package/dist/solid-start.d.ts +2 -2
- package/dist/solid.d.cts +2 -2
- package/dist/solid.d.ts +2 -2
- package/dist/{state-B-NKU7yb.d.cts → state-BNmdFZ6D.d.cts} +1 -1
- package/dist/{state-BvaftTAj.d.ts → state-BSwFbgYX.d.ts} +1 -1
- package/dist/svelte-kit.d.cts +2 -2
- package/dist/svelte-kit.d.ts +2 -2
- package/dist/svelte.d.cts +2 -2
- package/dist/svelte.d.ts +2 -2
- package/dist/types.d.cts +3 -3
- package/dist/types.d.ts +3 -3
- package/dist/vue.d.cts +2 -2
- package/dist/vue.d.ts +2 -2
- package/package.json +1 -1
- package/dist/{index-D0dedAck.d.ts → index-Bn9csJDG.d.ts} +4 -4
- package/dist/{index-BHDqo6WM.d.cts → index-DI6hwBqO.d.cts} +4 -4
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-Q13brXF4.cjs';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-
|
|
4
|
+
import '../index-DI6hwBqO.cjs';
|
|
5
5
|
import '../helper-DPDj8Nix.cjs';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-Bwhilbe9.js';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-
|
|
4
|
+
import '../index-Bn9csJDG.js';
|
|
5
5
|
import '../helper-DPDj8Nix.js';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Kysely } from 'kysely';
|
|
2
|
-
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-
|
|
2
|
+
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-Q13brXF4.cjs';
|
|
3
3
|
import 'zod';
|
|
4
|
-
import '../index-
|
|
4
|
+
import '../index-DI6hwBqO.cjs';
|
|
5
5
|
import '../helper-DPDj8Nix.cjs';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Kysely } from 'kysely';
|
|
2
|
-
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-
|
|
2
|
+
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-Bwhilbe9.js';
|
|
3
3
|
import 'zod';
|
|
4
|
-
import '../index-
|
|
4
|
+
import '../index-Bn9csJDG.js';
|
|
5
5
|
import '../helper-DPDj8Nix.js';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Db } from 'mongodb';
|
|
2
|
-
import { W as Where } from '../auth-
|
|
2
|
+
import { W as Where } from '../auth-Q13brXF4.cjs';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
|
-
import '../index-
|
|
5
|
+
import '../index-DI6hwBqO.cjs';
|
|
6
6
|
import '../helper-DPDj8Nix.cjs';
|
|
7
7
|
import 'better-call';
|
|
8
8
|
import 'better-sqlite3';
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Db } from 'mongodb';
|
|
2
|
-
import { W as Where } from '../auth-
|
|
2
|
+
import { W as Where } from '../auth-Bwhilbe9.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
|
-
import '../index-
|
|
5
|
+
import '../index-Bn9csJDG.js';
|
|
6
6
|
import '../helper-DPDj8Nix.js';
|
|
7
7
|
import 'better-call';
|
|
8
8
|
import 'better-sqlite3';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-Q13brXF4.cjs';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-
|
|
4
|
+
import '../index-DI6hwBqO.cjs';
|
|
5
5
|
import '../helper-DPDj8Nix.cjs';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-Bwhilbe9.js';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-
|
|
4
|
+
import '../index-Bn9csJDG.js';
|
|
5
5
|
import '../helper-DPDj8Nix.js';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
package/dist/api.cjs
CHANGED
|
@@ -81,4 +81,4 @@ Error: `,h),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
|
|
|
81
81
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
82
82
|
</div>
|
|
83
83
|
</body>
|
|
84
|
-
</html>`,Te=p("/error",{method:"GET",metadata:q},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Mt(t),{headers:{"Content-Type":"text/html"}})});var Oe=p("/ok",{method:"GET",metadata:q},async e=>e.json({ok:!0}));var j=require("zod");var L=require("better-call");var Se=()=>p("/sign-up/email",{method:"POST",query:j.z.object({currentURL:j.z.string().optional()}).optional(),body:j.z.record(j.z.string(),j.z.any())},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new L.APIError("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:i,image:n,callbackURL:s,...a}=t;if(!j.z.string().email().safeParse(o).success)throw new L.APIError("BAD_REQUEST",{message:"Invalid email"});let c=e.context.password.config.minPasswordLength;if(i.length<c)throw e.context.logger.error("Password is too short"),new L.APIError("BAD_REQUEST",{message:"Password is too short"});let l=e.context.password.config.maxPasswordLength;if(i.length>l)throw e.context.logger.error("Password is too long"),new L.APIError("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new L.APIError("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let m=oe(e.context.options,a),u;try{if(u=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:n,...m,emailVerified:!1}),!u)throw new L.APIError("BAD_REQUEST",{message:"Failed to create user"})}catch(w){throw f.error("Failed to create user",w),new L.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:w})}if(!u)throw new L.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let R=await e.context.password.hash(i);if(await e.context.internalAdapter.linkAccount({userId:u.id,providerId:"credential",accountId:u.id,password:R,expiresAt:N(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let w=await S(e.context.secret,u.email),k=`${e.context.baseURL}/verify-email?token=${w}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(u,k,w)}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 h=await e.context.internalAdapter.createSession(u.id,e.request);if(!h)throw new L.APIError("BAD_REQUEST",{message:"Failed to create session"});return await T(e,{session:h,user:u}),e.json({user:u,session:h})});var G=require("zod");var Le=require("better-call");var Ie=p("/list-accounts",{method:"GET",use:[v]},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(o=>({id:o.id,provider:o.providerId})))}),Ce=p("/link-social",{method:"POST",requireHeaders:!0,query:G.z.object({currentURL:G.z.string().optional()}).optional(),body:G.z.object({callbackURL:G.z.string().optional(),provider:G.z.enum(X)}),use:[v]},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 Le.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let i=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Le.APIError("NOT_FOUND",{message:"Provider not found"});let n=await K(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})});function Et(e){let t="127.0.0.1";if($e)return t;let r=["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],o=e instanceof Request?e.headers:e;for(let i of r){let n=o.get(i);if(typeof n=="string"){let s=n.split(",")[0].trim();if(s)return s}}return null}function Gt(e,t,r){let o=Date.now(),i=t*1e3;return o-r.lastRequest<i&&r.count>=e}function Ht(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 Qt(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function Zt(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async i=>await o.findOne({model:r,where:[{field:"key",value:i}]}),set:async(i,n,s)=>{try{s?await o.update({model:t??"rateLimit",where:[{field:"key",value:i}],update:{count:n.count,lastRequest:n.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:i,count:n.count,lastRequest:n.lastRequest}})}catch(a){f.error("Error setting rate limit",a)}}}}var vt=new Map;function Jt(e){return e.rateLimit.storage==="secondary-storage"?{get:async r=>{let o=await e.options.secondaryStorage?.get(r);return o?JSON.parse(o):void 0},set:async(r,o)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(o))}}:e.rateLimit.storage==="memory"?{async get(r){return vt.get(r)},async set(r,o,i){vt.set(r,o)}}:Zt(e,e.rateLimit.tableName)}async function _t(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),i=t.rateLimit.window,n=t.rateLimit.max,s=Et(e)+o,d=Wt().find(m=>m.pathMatcher(o));d&&(i=d.window,n=d.max);for(let m of t.options.plugins||[])if(m.rateLimit){let u=m.rateLimit.find(R=>R.pathMatcher(o));if(u){i=u.window,n=u.max;break}}if(t.rateLimit.customRules){let m=t.rateLimit.customRules[o];m&&(i=m.window,n=m.max)}let c=Jt(t),l=await c.get(s),b=Date.now();if(!l)await c.set(s,{key:s,count:1,lastRequest:b});else{let m=b-l.lastRequest;if(Gt(n,i,l)){let u=Qt(l.lastRequest,i);return Ht(u)}else m>i*1e3?await c.set(s,{...l,count:1,lastRequest:b}):await c.set(s,{...l,count:l.count+1,lastRequest:b})}}function Wt(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:3}]}var Pt=require("better-call");function xt(e,t){let r=t.plugins?.reduce((a,d)=>({...a,...d.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(d=>{let c=async l=>d.middleware({...l,context:{...e,...l.context}});return c.path=d.path,c.options=d.middleware.options,c.headers=d.middleware.headers,{path:d.path,middleware:c}})).filter(a=>a!==void 0).flat()||[],n={...{signInSocial:we,callbackOAuth:ye,getSession:ee(),signOut:Ae,signUpEmail:Se(),signInEmail:be,forgetPassword:Re,resetPassword:Ue,verifyEmail:he,sendVerificationEmail:ge,changeEmail:Pe,changePassword:ve,setPassword:_e,updateUser:Ee(),deleteUser:xe,forgetPasswordCallback:ke,listSessions:pe(),revokeSession:me,revokeSessions:fe,linkSocialAccount:Ce,listUserAccounts:Ie},...r,ok:Oe,error:Te},s={};for(let[a,d]of Object.entries(n))s[a]=async(c={})=>{let l=await e;for(let u of t.plugins||[])if(u.hooks?.before){for(let R of u.hooks.before)if(R.matcher({...d,...c,context:l})){let w=await R.handler({...c,context:{...l,...c?.context}});w&&"context"in w&&(l={...l,...w.context})}}let b;try{b=await d({...c,context:{...l,...c.context}})}catch(u){if(u instanceof $.APIError){let R=t.plugins?.map(k=>{if(k.hooks?.after)return k.hooks.after}).filter(k=>k!==void 0).flat();if(!R?.length)throw u;let h=new Response(JSON.stringify(u.body),{status:$.statusCode[u.status],headers:u.headers}),w;for(let k of R||[])if(k.matcher(c)){let Tt=Object.assign(c,{context:{...e,returned:h}}),ie=await k.handler(Tt);ie&&"response"in ie&&(w=ie.response)}if(w instanceof Response)return w;throw u}throw u}let m=b;for(let u of t.plugins||[])if(u.hooks?.after){for(let R of u.hooks.after)if(R.matcher(c)){let w=Object.assign(c,{context:{...e,returned:m}}),k=await R.handler(w);k&&"response"in k&&(m=k.response)}}return m},s[a].path=d.path,s[a].method=d.method,s[a].options=d.options,s[a].headers=d.headers;return{api:s,middlewares:o}}var Yt=(e,t)=>{let{api:r,middlewares:o}=xt(e,t),i=new URL(e.baseURL).pathname;return(0,$.createRouter)(r,{extraContext:e,basePath:i,routerMiddleware:[{path:"/**",middleware:ce},...o],async onRequest(n){for(let s of e.options.plugins||[])if(s.onRequest){let a=await s.onRequest(n,e);if(a&&"response"in a)return a.response}return _t(n,e)},async onResponse(n){for(let s of e.options.plugins||[])if(s.onResponse){let a=await s.onResponse(n,e);if(a)return a.response}return n},onError(n){if(t.onAPIError?.throw)throw n;if(t.onAPIError?.onError){t.onAPIError.onError(n,e);return}let s=t.logger?.verboseLogging?f:void 0;t.logger?.disabled!==!0&&(n instanceof $.APIError?(n.status==="INTERNAL_SERVER_ERROR"&&f.error(n),s?.error(n.message)):f?.error(n))}})};0&&(module.exports={APIError,callbackOAuth,changeEmail,changePassword,createAuthEndpoint,createAuthMiddleware,createEmailVerificationToken,deleteUser,error,forgetPassword,forgetPasswordCallback,getEndpoints,getSession,getSessionFromCtx,linkSocialAccount,listSessions,listUserAccounts,ok,optionsMiddleware,originCheckMiddleware,resetPassword,revokeSession,revokeSessions,router,sendVerificationEmail,sessionMiddleware,setPassword,signInEmail,signInSocial,signOut,signUpEmail,updateUser,verifyEmail});
|
|
84
|
+
</html>`,Te=p("/error",{method:"GET",metadata:q},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Mt(t),{headers:{"Content-Type":"text/html"}})});var Oe=p("/ok",{method:"GET",metadata:q},async e=>e.json({ok:!0}));var j=require("zod");var L=require("better-call");var Se=()=>p("/sign-up/email",{method:"POST",query:j.z.object({currentURL:j.z.string().optional()}).optional(),body:j.z.record(j.z.string(),j.z.any())},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new L.APIError("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:i,image:n,callbackURL:s,...a}=t;if(!j.z.string().email().safeParse(o).success)throw new L.APIError("BAD_REQUEST",{message:"Invalid email"});let c=e.context.password.config.minPasswordLength;if(i.length<c)throw e.context.logger.error("Password is too short"),new L.APIError("BAD_REQUEST",{message:"Password is too short"});let l=e.context.password.config.maxPasswordLength;if(i.length>l)throw e.context.logger.error("Password is too long"),new L.APIError("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new L.APIError("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let m=oe(e.context.options,a),u;try{if(u=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:n,...m,emailVerified:!1}),!u)throw new L.APIError("BAD_REQUEST",{message:"Failed to create user"})}catch(w){throw f.error("Failed to create user",w),new L.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:w})}if(!u)throw new L.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let R=await e.context.password.hash(i);if(await e.context.internalAdapter.linkAccount({userId:u.id,providerId:"credential",accountId:u.id,password:R,expiresAt:N(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let w=await S(e.context.secret,u.email),k=`${e.context.baseURL}/verify-email?token=${w}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(u,k,w)}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 h=await e.context.internalAdapter.createSession(u.id,e.request);if(!h)throw new L.APIError("BAD_REQUEST",{message:"Failed to create session"});return await T(e,{session:h,user:u}),e.json({user:u,session:h})});var G=require("zod");var Le=require("better-call");var Ie=p("/list-accounts",{method:"GET",use:[v]},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(o=>({id:o.id,provider:o.providerId})))}),Ce=p("/link-social",{method:"POST",requireHeaders:!0,query:G.z.object({currentURL:G.z.string().optional()}).optional(),body:G.z.object({callbackURL:G.z.string().optional(),provider:G.z.enum(X)}),use:[v]},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 Le.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let i=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Le.APIError("NOT_FOUND",{message:"Provider not found"});let n=await K(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})});function Et(e){let t="127.0.0.1";if($e)return t;let r=["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],o=e instanceof Request?e.headers:e;for(let i of r){let n=o.get(i);if(typeof n=="string"){let s=n.split(",")[0].trim();if(s)return s}}return null}function Gt(e,t,r){let o=Date.now(),i=t*1e3;return o-r.lastRequest<i&&r.count>=e}function Ht(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 Qt(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function Zt(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async i=>await o.findOne({model:r,where:[{field:"key",value:i}]}),set:async(i,n,s)=>{try{s?await o.update({model:t??"rateLimit",where:[{field:"key",value:i}],update:{count:n.count,lastRequest:n.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:i,count:n.count,lastRequest:n.lastRequest}})}catch(a){f.error("Error setting rate limit",a)}}}}var vt=new Map;function Jt(e){return e.rateLimit.storage==="secondary-storage"?{get:async r=>{let o=await e.options.secondaryStorage?.get(r);return o?JSON.parse(o):void 0},set:async(r,o)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(o))}}:e.rateLimit.storage==="memory"?{async get(r){return vt.get(r)},async set(r,o,i){vt.set(r,o)}}:Zt(e,e.rateLimit.tableName)}async function _t(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),i=t.rateLimit.window,n=t.rateLimit.max,s=Et(e)+o,d=Wt().find(m=>m.pathMatcher(o));d&&(i=d.window,n=d.max);for(let m of t.options.plugins||[])if(m.rateLimit){let u=m.rateLimit.find(R=>R.pathMatcher(o));if(u){i=u.window,n=u.max;break}}if(t.rateLimit.customRules){let m=t.rateLimit.customRules[o];m&&(i=m.window,n=m.max)}let c=Jt(t),l=await c.get(s),b=Date.now();if(!l)await c.set(s,{key:s,count:1,lastRequest:b});else{let m=b-l.lastRequest;if(Gt(n,i,l)){let u=Qt(l.lastRequest,i);return Ht(u)}else m>i*1e3?await c.set(s,{...l,count:1,lastRequest:b}):await c.set(s,{...l,count:l.count+1,lastRequest:b})}}function Wt(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")||t.startsWith("/change-password")||t.startsWith("/change-email")},window:10,max:3}]}var Pt=require("better-call");function xt(e,t){let r=t.plugins?.reduce((a,d)=>({...a,...d.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(d=>{let c=async l=>d.middleware({...l,context:{...e,...l.context}});return c.path=d.path,c.options=d.middleware.options,c.headers=d.middleware.headers,{path:d.path,middleware:c}})).filter(a=>a!==void 0).flat()||[],n={...{signInSocial:we,callbackOAuth:ye,getSession:ee(),signOut:Ae,signUpEmail:Se(),signInEmail:be,forgetPassword:Re,resetPassword:Ue,verifyEmail:he,sendVerificationEmail:ge,changeEmail:Pe,changePassword:ve,setPassword:_e,updateUser:Ee(),deleteUser:xe,forgetPasswordCallback:ke,listSessions:pe(),revokeSession:me,revokeSessions:fe,linkSocialAccount:Ce,listUserAccounts:Ie},...r,ok:Oe,error:Te},s={};for(let[a,d]of Object.entries(n))s[a]=async(c={})=>{let l=await e;for(let u of t.plugins||[])if(u.hooks?.before){for(let R of u.hooks.before)if(R.matcher({...d,...c,context:l})){let w=await R.handler({...c,context:{...l,...c?.context}});w&&"context"in w&&(l={...l,...w.context})}}let b;try{b=await d({...c,context:{...l,...c.context}})}catch(u){if(u instanceof $.APIError){let R=t.plugins?.map(k=>{if(k.hooks?.after)return k.hooks.after}).filter(k=>k!==void 0).flat();if(!R?.length)throw u;let h=new Response(JSON.stringify(u.body),{status:$.statusCode[u.status],headers:u.headers}),w;for(let k of R||[])if(k.matcher(c)){let Tt=Object.assign(c,{context:{...e,returned:h}}),ie=await k.handler(Tt);ie&&"response"in ie&&(w=ie.response)}if(w instanceof Response)return w;throw u}throw u}let m=b;for(let u of t.plugins||[])if(u.hooks?.after){for(let R of u.hooks.after)if(R.matcher(c)){let w=Object.assign(c,{context:{...e,returned:m}}),k=await R.handler(w);k&&"response"in k&&(m=k.response)}}return m},s[a].path=d.path,s[a].method=d.method,s[a].options=d.options,s[a].headers=d.headers;return{api:s,middlewares:o}}var Yt=(e,t)=>{let{api:r,middlewares:o}=xt(e,t),i=new URL(e.baseURL).pathname;return(0,$.createRouter)(r,{extraContext:e,basePath:i,routerMiddleware:[{path:"/**",middleware:ce},...o],async onRequest(n){for(let s of e.options.plugins||[])if(s.onRequest){let a=await s.onRequest(n,e);if(a&&"response"in a)return a.response}return _t(n,e)},async onResponse(n){for(let s of e.options.plugins||[])if(s.onResponse){let a=await s.onResponse(n,e);if(a)return a.response}return n},onError(n){if(t.onAPIError?.throw)throw n;if(t.onAPIError?.onError){t.onAPIError.onError(n,e);return}let s=t.logger?.verboseLogging?f:void 0;t.logger?.disabled!==!0&&(n instanceof $.APIError?(n.status==="INTERNAL_SERVER_ERROR"&&f.error(n),s?.error(n.message)):f?.error(n))}})};0&&(module.exports={APIError,callbackOAuth,changeEmail,changePassword,createAuthEndpoint,createAuthMiddleware,createEmailVerificationToken,deleteUser,error,forgetPassword,forgetPasswordCallback,getEndpoints,getSession,getSessionFromCtx,linkSocialAccount,listSessions,listUserAccounts,ok,optionsMiddleware,originCheckMiddleware,resetPassword,revokeSession,revokeSessions,router,sendVerificationEmail,sessionMiddleware,setPassword,signInEmail,signInSocial,signOut,signUpEmail,updateUser,verifyEmail});
|
package/dist/api.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { x as AuthEndpoint, y as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, w as createAuthEndpoint, v as createAuthMiddleware, ac as createEmailVerificationToken, ai as deleteUser, ak as error, a9 as forgetPassword, aa as forgetPasswordCallback, Z as getEndpoints, a2 as getSession, a3 as getSessionFromCtx, ao as linkSocialAccount, a5 as listSessions, an as listUserAccounts, al as ok, u as optionsMiddleware, ap as originCheckMiddleware, ab as resetPassword, a6 as revokeSession, a7 as revokeSessions, _ as router, ad as sendVerificationEmail, a4 as sessionMiddleware, ah as setPassword, a0 as signInEmail, $ as signInSocial, a8 as signOut, am as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-
|
|
1
|
+
export { x as AuthEndpoint, y as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, w as createAuthEndpoint, v as createAuthMiddleware, ac as createEmailVerificationToken, ai as deleteUser, ak as error, a9 as forgetPassword, aa as forgetPasswordCallback, Z as getEndpoints, a2 as getSession, a3 as getSessionFromCtx, ao as linkSocialAccount, a5 as listSessions, an as listUserAccounts, al as ok, u as optionsMiddleware, ap as originCheckMiddleware, ab as resetPassword, a6 as revokeSession, a7 as revokeSessions, _ as router, ad as sendVerificationEmail, a4 as sessionMiddleware, ah as setPassword, a0 as signInEmail, $ as signInSocial, a8 as signOut, am as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-Q13brXF4.cjs';
|
|
2
2
|
import './helper-DPDj8Nix.cjs';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import 'kysely';
|
|
6
|
-
import './index-
|
|
6
|
+
import './index-DI6hwBqO.cjs';
|
|
7
7
|
import 'better-sqlite3';
|
package/dist/api.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { x as AuthEndpoint, y as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, w as createAuthEndpoint, v as createAuthMiddleware, ac as createEmailVerificationToken, ai as deleteUser, ak as error, a9 as forgetPassword, aa as forgetPasswordCallback, Z as getEndpoints, a2 as getSession, a3 as getSessionFromCtx, ao as linkSocialAccount, a5 as listSessions, an as listUserAccounts, al as ok, u as optionsMiddleware, ap as originCheckMiddleware, ab as resetPassword, a6 as revokeSession, a7 as revokeSessions, _ as router, ad as sendVerificationEmail, a4 as sessionMiddleware, ah as setPassword, a0 as signInEmail, $ as signInSocial, a8 as signOut, am as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-
|
|
1
|
+
export { x as AuthEndpoint, y as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, w as createAuthEndpoint, v as createAuthMiddleware, ac as createEmailVerificationToken, ai as deleteUser, ak as error, a9 as forgetPassword, aa as forgetPasswordCallback, Z as getEndpoints, a2 as getSession, a3 as getSessionFromCtx, ao as linkSocialAccount, a5 as listSessions, an as listUserAccounts, al as ok, u as optionsMiddleware, ap as originCheckMiddleware, ab as resetPassword, a6 as revokeSession, a7 as revokeSessions, _ as router, ad as sendVerificationEmail, a4 as sessionMiddleware, ah as setPassword, a0 as signInEmail, $ as signInSocial, a8 as signOut, am as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-Bwhilbe9.js';
|
|
2
2
|
import './helper-DPDj8Nix.js';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import 'kysely';
|
|
6
|
-
import './index-
|
|
6
|
+
import './index-Bn9csJDG.js';
|
|
7
7
|
import 'better-sqlite3';
|
package/dist/api.js
CHANGED
|
@@ -81,4 +81,4 @@ Error: `,g),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
|
|
|
81
81
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
82
82
|
</div>
|
|
83
83
|
</body>
|
|
84
|
-
</html>`,Ze=m("/error",{method:"GET",metadata:z},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Vt(t),{headers:{"Content-Type":"text/html"}})});var Je=m("/ok",{method:"GET",metadata:z},async e=>e.json({ok:!0}));import{z as $}from"zod";import{APIError as L}from"better-call";var We=()=>m("/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 L("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:i,image:n,callbackURL:s,...a}=t;if(!$.string().email().safeParse(o).success)throw new L("BAD_REQUEST",{message:"Invalid email"});let c=e.context.password.config.minPasswordLength;if(i.length<c)throw e.context.logger.error("Password is too short"),new L("BAD_REQUEST",{message:"Password is too short"});let l=e.context.password.config.maxPasswordLength;if(i.length>l)throw e.context.logger.error("Password is too long"),new L("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new L("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let p=J(e.context.options,a),u;try{if(u=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:n,...p,emailVerified:!1}),!u)throw new L("BAD_REQUEST",{message:"Failed to create user"})}catch(w){throw f.error("Failed to create user",w),new L("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:w})}if(!u)throw new L("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let R=await e.context.password.hash(i);if(await e.context.internalAdapter.linkAccount({userId:u.id,providerId:"credential",accountId:u.id,password:R,expiresAt:V(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let w=await S(e.context.secret,u.email),k=`${e.context.baseURL}/verify-email?token=${w}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(u,k,w)}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 g=await e.context.internalAdapter.createSession(u.id,e.request);if(!g)throw new L("BAD_REQUEST",{message:"Failed to create session"});return await _(e,{session:g,user:u}),e.json({user:u,session:g})});import{z as M}from"zod";import{APIError as Ye}from"better-call";var Ke=m("/list-accounts",{method:"GET",use:[v]},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(o=>({id:o.id,provider:o.providerId})))}),Xe=m("/link-social",{method:"POST",requireHeaders:!0,query:M.object({currentURL:M.string().optional()}).optional(),body:M.object({callbackURL:M.string().optional(),provider:M.enum(Z)}),use:[v]},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 Ye("BAD_REQUEST",{message:"Social Account is already linked."});let i=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Ye("NOT_FOUND",{message:"Provider not found"});let n=await Q(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})});function et(e){let t="127.0.0.1";if(ce)return t;let r=["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],o=e instanceof Request?e.headers:e;for(let i of r){let n=o.get(i);if(typeof n=="string"){let s=n.split(",")[0].trim();if(s)return s}}return null}function jt(e,t,r){let o=Date.now(),i=t*1e3;return o-r.lastRequest<i&&r.count>=e}function $t(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 qt(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function Nt(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async i=>await o.findOne({model:r,where:[{field:"key",value:i}]}),set:async(i,n,s)=>{try{s?await o.update({model:t??"rateLimit",where:[{field:"key",value:i}],update:{count:n.count,lastRequest:n.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:i,count:n.count,lastRequest:n.lastRequest}})}catch(a){f.error("Error setting rate limit",a)}}}}var tt=new Map;function Ft(e){return e.rateLimit.storage==="secondary-storage"?{get:async r=>{let o=await e.options.secondaryStorage?.get(r);return o?JSON.parse(o):void 0},set:async(r,o)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(o))}}:e.rateLimit.storage==="memory"?{async get(r){return tt.get(r)},async set(r,o,i){tt.set(r,o)}}:Nt(e,e.rateLimit.tableName)}async function rt(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),i=t.rateLimit.window,n=t.rateLimit.max,s=et(e)+o,d=Mt().find(p=>p.pathMatcher(o));d&&(i=d.window,n=d.max);for(let p of t.options.plugins||[])if(p.rateLimit){let u=p.rateLimit.find(R=>R.pathMatcher(o));if(u){i=u.window,n=u.max;break}}if(t.rateLimit.customRules){let p=t.rateLimit.customRules[o];p&&(i=p.window,n=p.max)}let c=Ft(t),l=await c.get(s),b=Date.now();if(!l)await c.set(s,{key:s,count:1,lastRequest:b});else{let p=b-l.lastRequest;if(jt(n,i,l)){let u=qt(l.lastRequest,i);return $t(u)}else p>i*1e3?await c.set(s,{...l,count:1,lastRequest:b}):await c.set(s,{...l,count:l.count+1,lastRequest:b})}}function Mt(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:3}]}import{APIError as hs}from"better-call";function Qt(e,t){let r=t.plugins?.reduce((a,d)=>({...a,...d.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(d=>{let c=async l=>d.middleware({...l,context:{...e,...l.context}});return c.path=d.path,c.options=d.middleware.options,c.headers=d.middleware.headers,{path:d.path,middleware:c}})).filter(a=>a!==void 0).flat()||[],n={...{signInSocial:Ce,callbackOAuth:ze,getSession:te(),signOut:Ve,signUpEmail:We(),signInEmail:De,forgetPassword:$e,resetPassword:Ne,verifyEmail:Ie,sendVerificationEmail:Le,changeEmail:Qe,changePassword:Me,setPassword:Ge,updateUser:Fe(),deleteUser:He,forgetPasswordCallback:qe,listSessions:Te(),revokeSession:Oe,revokeSessions:Se,linkSocialAccount:Xe,listUserAccounts:Ke},...r,ok:Je,error:Ze},s={};for(let[a,d]of Object.entries(n))s[a]=async(c={})=>{let l=await e;for(let u of t.plugins||[])if(u.hooks?.before){for(let R of u.hooks.before)if(R.matcher({...d,...c,context:l})){let w=await R.handler({...c,context:{...l,...c?.context}});w&&"context"in w&&(l={...l,...w.context})}}let b;try{b=await d({...c,context:{...l,...c.context}})}catch(u){if(u instanceof ot){let R=t.plugins?.map(k=>{if(k.hooks?.after)return k.hooks.after}).filter(k=>k!==void 0).flat();if(!R?.length)throw u;let g=new Response(JSON.stringify(u.body),{status:Ht[u.status],headers:u.headers}),w;for(let k of R||[])if(k.matcher(c)){let it=Object.assign(c,{context:{...e,returned:g}}),K=await k.handler(it);K&&"response"in K&&(w=K.response)}if(w instanceof Response)return w;throw u}throw u}let p=b;for(let u of t.plugins||[])if(u.hooks?.after){for(let R of u.hooks.after)if(R.matcher(c)){let w=Object.assign(c,{context:{...e,returned:p}}),k=await R.handler(w);k&&"response"in k&&(p=k.response)}}return p},s[a].path=d.path,s[a].method=d.method,s[a].options=d.options,s[a].headers=d.headers;return{api:s,middlewares:o}}var ls=(e,t)=>{let{api:r,middlewares:o}=Qt(e,t),i=new URL(e.baseURL).pathname;return Gt(r,{extraContext:e,basePath:i,routerMiddleware:[{path:"/**",middleware:me},...o],async onRequest(n){for(let s of e.options.plugins||[])if(s.onRequest){let a=await s.onRequest(n,e);if(a&&"response"in a)return a.response}return rt(n,e)},async onResponse(n){for(let s of e.options.plugins||[])if(s.onResponse){let a=await s.onResponse(n,e);if(a)return a.response}return n},onError(n){if(t.onAPIError?.throw)throw n;if(t.onAPIError?.onError){t.onAPIError.onError(n,e);return}let s=t.logger?.verboseLogging?f:void 0;t.logger?.disabled!==!0&&(n instanceof ot?(n.status==="INTERNAL_SERVER_ERROR"&&f.error(n),s?.error(n.message)):f?.error(n))}})};export{hs as APIError,ze as callbackOAuth,Qe as changeEmail,Me as changePassword,m as createAuthEndpoint,G as createAuthMiddleware,S as createEmailVerificationToken,He as deleteUser,Ze as error,$e as forgetPassword,qe as forgetPasswordCallback,Qt as getEndpoints,te as getSession,re as getSessionFromCtx,Xe as linkSocialAccount,Te as listSessions,Ke as listUserAccounts,Je as ok,ne as optionsMiddleware,me as originCheckMiddleware,Ne as resetPassword,Oe as revokeSession,Se as revokeSessions,ls as router,Le as sendVerificationEmail,v as sessionMiddleware,Ge as setPassword,De as signInEmail,Ce as signInSocial,Ve as signOut,We as signUpEmail,Fe as updateUser,Ie as verifyEmail};
|
|
84
|
+
</html>`,Ze=m("/error",{method:"GET",metadata:z},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Vt(t),{headers:{"Content-Type":"text/html"}})});var Je=m("/ok",{method:"GET",metadata:z},async e=>e.json({ok:!0}));import{z as $}from"zod";import{APIError as L}from"better-call";var We=()=>m("/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 L("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:i,image:n,callbackURL:s,...a}=t;if(!$.string().email().safeParse(o).success)throw new L("BAD_REQUEST",{message:"Invalid email"});let c=e.context.password.config.minPasswordLength;if(i.length<c)throw e.context.logger.error("Password is too short"),new L("BAD_REQUEST",{message:"Password is too short"});let l=e.context.password.config.maxPasswordLength;if(i.length>l)throw e.context.logger.error("Password is too long"),new L("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new L("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let p=J(e.context.options,a),u;try{if(u=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:n,...p,emailVerified:!1}),!u)throw new L("BAD_REQUEST",{message:"Failed to create user"})}catch(w){throw f.error("Failed to create user",w),new L("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:w})}if(!u)throw new L("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let R=await e.context.password.hash(i);if(await e.context.internalAdapter.linkAccount({userId:u.id,providerId:"credential",accountId:u.id,password:R,expiresAt:V(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let w=await S(e.context.secret,u.email),k=`${e.context.baseURL}/verify-email?token=${w}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(u,k,w)}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 g=await e.context.internalAdapter.createSession(u.id,e.request);if(!g)throw new L("BAD_REQUEST",{message:"Failed to create session"});return await _(e,{session:g,user:u}),e.json({user:u,session:g})});import{z as M}from"zod";import{APIError as Ye}from"better-call";var Ke=m("/list-accounts",{method:"GET",use:[v]},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(o=>({id:o.id,provider:o.providerId})))}),Xe=m("/link-social",{method:"POST",requireHeaders:!0,query:M.object({currentURL:M.string().optional()}).optional(),body:M.object({callbackURL:M.string().optional(),provider:M.enum(Z)}),use:[v]},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 Ye("BAD_REQUEST",{message:"Social Account is already linked."});let i=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Ye("NOT_FOUND",{message:"Provider not found"});let n=await Q(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})});function et(e){let t="127.0.0.1";if(ce)return t;let r=["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],o=e instanceof Request?e.headers:e;for(let i of r){let n=o.get(i);if(typeof n=="string"){let s=n.split(",")[0].trim();if(s)return s}}return null}function jt(e,t,r){let o=Date.now(),i=t*1e3;return o-r.lastRequest<i&&r.count>=e}function $t(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 qt(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function Nt(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async i=>await o.findOne({model:r,where:[{field:"key",value:i}]}),set:async(i,n,s)=>{try{s?await o.update({model:t??"rateLimit",where:[{field:"key",value:i}],update:{count:n.count,lastRequest:n.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:i,count:n.count,lastRequest:n.lastRequest}})}catch(a){f.error("Error setting rate limit",a)}}}}var tt=new Map;function Ft(e){return e.rateLimit.storage==="secondary-storage"?{get:async r=>{let o=await e.options.secondaryStorage?.get(r);return o?JSON.parse(o):void 0},set:async(r,o)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(o))}}:e.rateLimit.storage==="memory"?{async get(r){return tt.get(r)},async set(r,o,i){tt.set(r,o)}}:Nt(e,e.rateLimit.tableName)}async function rt(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),i=t.rateLimit.window,n=t.rateLimit.max,s=et(e)+o,d=Mt().find(p=>p.pathMatcher(o));d&&(i=d.window,n=d.max);for(let p of t.options.plugins||[])if(p.rateLimit){let u=p.rateLimit.find(R=>R.pathMatcher(o));if(u){i=u.window,n=u.max;break}}if(t.rateLimit.customRules){let p=t.rateLimit.customRules[o];p&&(i=p.window,n=p.max)}let c=Ft(t),l=await c.get(s),b=Date.now();if(!l)await c.set(s,{key:s,count:1,lastRequest:b});else{let p=b-l.lastRequest;if(jt(n,i,l)){let u=qt(l.lastRequest,i);return $t(u)}else p>i*1e3?await c.set(s,{...l,count:1,lastRequest:b}):await c.set(s,{...l,count:l.count+1,lastRequest:b})}}function Mt(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")||t.startsWith("/change-password")||t.startsWith("/change-email")},window:10,max:3}]}import{APIError as hs}from"better-call";function Qt(e,t){let r=t.plugins?.reduce((a,d)=>({...a,...d.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(d=>{let c=async l=>d.middleware({...l,context:{...e,...l.context}});return c.path=d.path,c.options=d.middleware.options,c.headers=d.middleware.headers,{path:d.path,middleware:c}})).filter(a=>a!==void 0).flat()||[],n={...{signInSocial:Ce,callbackOAuth:ze,getSession:te(),signOut:Ve,signUpEmail:We(),signInEmail:De,forgetPassword:$e,resetPassword:Ne,verifyEmail:Ie,sendVerificationEmail:Le,changeEmail:Qe,changePassword:Me,setPassword:Ge,updateUser:Fe(),deleteUser:He,forgetPasswordCallback:qe,listSessions:Te(),revokeSession:Oe,revokeSessions:Se,linkSocialAccount:Xe,listUserAccounts:Ke},...r,ok:Je,error:Ze},s={};for(let[a,d]of Object.entries(n))s[a]=async(c={})=>{let l=await e;for(let u of t.plugins||[])if(u.hooks?.before){for(let R of u.hooks.before)if(R.matcher({...d,...c,context:l})){let w=await R.handler({...c,context:{...l,...c?.context}});w&&"context"in w&&(l={...l,...w.context})}}let b;try{b=await d({...c,context:{...l,...c.context}})}catch(u){if(u instanceof ot){let R=t.plugins?.map(k=>{if(k.hooks?.after)return k.hooks.after}).filter(k=>k!==void 0).flat();if(!R?.length)throw u;let g=new Response(JSON.stringify(u.body),{status:Ht[u.status],headers:u.headers}),w;for(let k of R||[])if(k.matcher(c)){let it=Object.assign(c,{context:{...e,returned:g}}),K=await k.handler(it);K&&"response"in K&&(w=K.response)}if(w instanceof Response)return w;throw u}throw u}let p=b;for(let u of t.plugins||[])if(u.hooks?.after){for(let R of u.hooks.after)if(R.matcher(c)){let w=Object.assign(c,{context:{...e,returned:p}}),k=await R.handler(w);k&&"response"in k&&(p=k.response)}}return p},s[a].path=d.path,s[a].method=d.method,s[a].options=d.options,s[a].headers=d.headers;return{api:s,middlewares:o}}var ls=(e,t)=>{let{api:r,middlewares:o}=Qt(e,t),i=new URL(e.baseURL).pathname;return Gt(r,{extraContext:e,basePath:i,routerMiddleware:[{path:"/**",middleware:me},...o],async onRequest(n){for(let s of e.options.plugins||[])if(s.onRequest){let a=await s.onRequest(n,e);if(a&&"response"in a)return a.response}return rt(n,e)},async onResponse(n){for(let s of e.options.plugins||[])if(s.onResponse){let a=await s.onResponse(n,e);if(a)return a.response}return n},onError(n){if(t.onAPIError?.throw)throw n;if(t.onAPIError?.onError){t.onAPIError.onError(n,e);return}let s=t.logger?.verboseLogging?f:void 0;t.logger?.disabled!==!0&&(n instanceof ot?(n.status==="INTERNAL_SERVER_ERROR"&&f.error(n),s?.error(n.message)):f?.error(n))}})};export{hs as APIError,ze as callbackOAuth,Qe as changeEmail,Me as changePassword,m as createAuthEndpoint,G as createAuthMiddleware,S as createEmailVerificationToken,He as deleteUser,Ze as error,$e as forgetPassword,qe as forgetPasswordCallback,Qt as getEndpoints,te as getSession,re as getSessionFromCtx,Xe as linkSocialAccount,Te as listSessions,Ke as listUserAccounts,Je as ok,ne as optionsMiddleware,me as originCheckMiddleware,Ne as resetPassword,Oe as revokeSession,Se as revokeSessions,ls as router,Le as sendVerificationEmail,v as sessionMiddleware,Ge as setPassword,De as signInEmail,Ce as signInSocial,Ve as signOut,We as signUpEmail,Fe as updateUser,Ie as verifyEmail};
|