import type { BetterAuthPlugin } from "better-auth"; import { APIError, createAuthEndpoint } from "better-auth/api"; import { setSessionCookie } from "better-auth/cookies"; import * as z from "zod"; // Server-only: called after a BioLock check has passed, to create the account (first device) and the session. export const biolockSessions = () => ({ id: "biolock", endpoints: { biolockStartSession: createAuthEndpoint("/biolock/start-session", { method: "POST", body: z.object({ userId: z.string().max(100).optional(), newName: z.string().min(1).max(80).optional() }), metadata: { SERVER_ONLY: true }, }, async (ctx) => { const adapter = ctx.context.internalAdapter; let user = ctx.body.userId ? await adapter.findUserById(ctx.body.userId) : null; if (!user && ctx.body.newName) { const id = crypto.randomUUID(); user = await adapter.createUser({ name: ctx.body.newName, // Accounts have no email. This placeholder only fills the required column and is never contacted. email: `member-${id}@members.becomeapro.ai`, emailVerified: false, }, { method: "email-password" } as Parameters[1]); } if (!user) throw new APIError("UNAUTHORIZED", { message: "Account not found." }); const session = await adapter.createSession(user.id); if (!session) throw new APIError("UNAUTHORIZED", { message: "Could not start a session." }); await setSessionCookie(ctx, { session, user }); return ctx.json({ userId: user.id }); }), }, }) satisfies BetterAuthPlugin;