UNPKG

better-auth

Version:

The most comprehensive authentication library for TypeScript.

370 lines (362 loc) • 12.9 kB
'use strict'; const z = require('zod/v4'); const socialProviders_index = require('../../shared/better-auth.Bafolo-S.cjs'); const betterCall = require('better-call'); const cookies_index = require('../../cookies/index.cjs'); const schema = require('../../shared/better-auth.BIMq4RPW.cjs'); require('../../shared/better-auth.DiSjtgs9.cjs'); require('../../shared/better-auth.CXhVNgXP.cjs'); require('defu'); require('../../shared/better-auth.C1hdVENX.cjs'); require('@better-auth/utils/hash'); require('@better-auth/utils/base64'); require('../../crypto/index.cjs'); require('@noble/ciphers/chacha'); require('@noble/ciphers/utils'); require('@noble/ciphers/webcrypto'); require('jose'); require('@noble/hashes/scrypt'); require('@better-auth/utils'); require('@better-auth/utils/hex'); require('@noble/hashes/utils'); require('../../shared/better-auth.CYeOI8C-.cjs'); require('@better-auth/utils/random'); require('@better-fetch/fetch'); require('../../shared/better-auth.C-R0J0n1.cjs'); require('../../shared/better-auth.ANpbi45u.cjs'); require('../../shared/better-auth.D3mtHEZg.cjs'); require('@better-auth/utils/hmac'); require('@better-auth/utils/binary'); require('jose/errors'); function _interopNamespaceCompat(e) { if (e && typeof e === 'object' && 'default' in e) return e; const n = Object.create(null); if (e) { for (const k in e) { n[k] = e[k]; } } n.default = e; return n; } const z__namespace = /*#__PURE__*/_interopNamespaceCompat(z); const getSchema = (normalizer) => { return { user: { fields: { username: { type: "string", required: false, sortable: true, unique: true, returned: true }, displayUsername: { type: "string", required: false, transform: { input(value) { return value == null ? value : normalizer(value); } } } } } }; }; const USERNAME_ERROR_CODES = { INVALID_USERNAME_OR_PASSWORD: "invalid username or password", EMAIL_NOT_VERIFIED: "email not verified", UNEXPECTED_ERROR: "unexpected error", USERNAME_IS_ALREADY_TAKEN: "username is already taken. please try another.", USERNAME_TOO_SHORT: "username is too short", USERNAME_TOO_LONG: "username is too long", INVALID_USERNAME: "username is invalid" }; function defaultUsernameValidator(username2) { return /^[a-zA-Z0-9_.]+$/.test(username2); } const username = (options) => { const normalizer = (username2) => { if (options?.usernameNormalization === false) { return username2; } if (options?.usernameNormalization) { return options.usernameNormalization(username2); } return username2.toLowerCase(); }; return { id: "username", endpoints: { signInUsername: socialProviders_index.createAuthEndpoint( "/sign-in/username", { method: "POST", body: z__namespace.object({ username: z__namespace.string().meta({ description: "The username of the user" }), password: z__namespace.string().meta({ description: "The password of the user" }), rememberMe: z__namespace.boolean().meta({ description: "Remember the user session" }).optional(), callbackURL: z__namespace.string().meta({ description: "The URL to redirect to after email verification" }).optional() }), metadata: { openapi: { summary: "Sign in with username", description: "Sign in with username", responses: { 200: { description: "Success", content: { "application/json": { schema: { type: "object", properties: { token: { type: "string", description: "Session token for the authenticated session" }, user: { $ref: "#/components/schemas/User" } }, required: ["token", "user"] } } } } } } } }, async (ctx) => { if (!ctx.body.username || !ctx.body.password) { ctx.context.logger.error("Username or password not found"); throw new betterCall.APIError("UNAUTHORIZED", { message: USERNAME_ERROR_CODES.INVALID_USERNAME_OR_PASSWORD }); } const minUsernameLength = options?.minUsernameLength || 3; const maxUsernameLength = options?.maxUsernameLength || 30; if (ctx.body.username.length < minUsernameLength) { ctx.context.logger.error("Username too short", { username: ctx.body.username }); throw new betterCall.APIError("UNPROCESSABLE_ENTITY", { message: USERNAME_ERROR_CODES.USERNAME_TOO_SHORT }); } if (ctx.body.username.length > maxUsernameLength) { ctx.context.logger.error("Username too long", { username: ctx.body.username }); throw new betterCall.APIError("UNPROCESSABLE_ENTITY", { message: USERNAME_ERROR_CODES.USERNAME_TOO_LONG }); } const validator = options?.usernameValidator || defaultUsernameValidator; if (!validator(ctx.body.username)) { throw new betterCall.APIError("UNPROCESSABLE_ENTITY", { message: USERNAME_ERROR_CODES.INVALID_USERNAME }); } const user = await ctx.context.adapter.findOne({ model: "user", where: [ { field: "username", value: normalizer(ctx.body.username) } ] }); if (!user) { await ctx.context.password.hash(ctx.body.password); ctx.context.logger.error("User not found", { username: ctx.body.username }); throw new betterCall.APIError("UNAUTHORIZED", { message: USERNAME_ERROR_CODES.INVALID_USERNAME_OR_PASSWORD }); } if (!user.emailVerified && ctx.context.options.emailAndPassword?.requireEmailVerification) { await socialProviders_index.sendVerificationEmailFn(ctx, user); throw new betterCall.APIError("FORBIDDEN", { message: USERNAME_ERROR_CODES.EMAIL_NOT_VERIFIED }); } const account = await ctx.context.adapter.findOne({ model: "account", where: [ { field: "userId", value: user.id }, { field: "providerId", value: "credential" } ] }); if (!account) { throw new betterCall.APIError("UNAUTHORIZED", { message: USERNAME_ERROR_CODES.INVALID_USERNAME_OR_PASSWORD }); } const currentPassword = account?.password; if (!currentPassword) { ctx.context.logger.error("Password not found", { username: ctx.body.username }); throw new betterCall.APIError("UNAUTHORIZED", { message: USERNAME_ERROR_CODES.INVALID_USERNAME_OR_PASSWORD }); } const validPassword = await ctx.context.password.verify({ hash: currentPassword, password: ctx.body.password }); if (!validPassword) { ctx.context.logger.error("Invalid password"); throw new betterCall.APIError("UNAUTHORIZED", { message: USERNAME_ERROR_CODES.INVALID_USERNAME_OR_PASSWORD }); } const session = await ctx.context.internalAdapter.createSession( user.id, ctx, ctx.body.rememberMe === false ); if (!session) { return ctx.json(null, { status: 500, body: { message: socialProviders_index.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION } }); } await cookies_index.setSessionCookie( ctx, { session, user }, ctx.body.rememberMe === false ); return ctx.json({ token: session.token, user: { id: user.id, email: user.email, emailVerified: user.emailVerified, username: user.username, name: user.name, image: user.image, createdAt: user.createdAt, updatedAt: user.updatedAt } }); } ), isUsernameAvailable: socialProviders_index.createAuthEndpoint( "/is-username-available", { method: "POST", body: z__namespace.object({ username: z__namespace.string().meta({ description: "The username to check" }) }) }, async (ctx) => { const username2 = ctx.body.username; if (!username2) { throw new betterCall.APIError("UNPROCESSABLE_ENTITY", { message: USERNAME_ERROR_CODES.INVALID_USERNAME }); } const user = await ctx.context.adapter.findOne({ model: "user", where: [ { field: "username", value: username2.toLowerCase() } ] }); if (user) { return ctx.json({ available: false }); } return ctx.json({ available: true }); } ) }, schema: schema.mergeSchema(getSchema(normalizer), options?.schema), hooks: { before: [ { matcher(context) { return context.path === "/sign-up/email" || context.path === "/update-user"; }, handler: socialProviders_index.createAuthMiddleware(async (ctx) => { const username2 = ctx.body.username; if (username2 !== void 0 && typeof username2 === "string") { const minUsernameLength = options?.minUsernameLength || 3; const maxUsernameLength = options?.maxUsernameLength || 30; if (username2.length < minUsernameLength) { throw new betterCall.APIError("UNPROCESSABLE_ENTITY", { message: USERNAME_ERROR_CODES.USERNAME_TOO_SHORT }); } if (username2.length > maxUsernameLength) { throw new betterCall.APIError("UNPROCESSABLE_ENTITY", { message: USERNAME_ERROR_CODES.USERNAME_TOO_LONG }); } const validator = options?.usernameValidator || defaultUsernameValidator; const valid = await validator(username2); if (!valid) { throw new betterCall.APIError("UNPROCESSABLE_ENTITY", { message: USERNAME_ERROR_CODES.INVALID_USERNAME }); } const user = await ctx.context.adapter.findOne({ model: "user", where: [ { field: "username", value: normalizer(username2) } ] }); const blockChangeSignUp = ctx.path === "/sign-up/email" && user; const blockChangeUpdateUser = ctx.path === "/update-user" && user && ctx.context.session && user.id !== ctx.context.session.session.userId; if (blockChangeSignUp || blockChangeUpdateUser) { throw new betterCall.APIError("UNPROCESSABLE_ENTITY", { message: USERNAME_ERROR_CODES.USERNAME_IS_ALREADY_TAKEN }); } } }) }, { matcher(context) { return context.path === "/sign-up/email" || context.path === "/update-user"; }, handler: socialProviders_index.createAuthMiddleware(async (ctx) => { if (ctx.body.username) { ctx.body.displayUsername ||= ctx.body.username; ctx.body.username = normalizer(ctx.body.username); } }) } ] }, $ERROR_CODES: USERNAME_ERROR_CODES }; }; exports.USERNAME_ERROR_CODES = USERNAME_ERROR_CODES; exports.username = username;