Branchwell

Become a Pro / website · becomeapro.ai / src / lib / biolock / session-plugin.ts

Raw 1.6 KB on 59dac1cc932d622dfc4d6c274a9ed8e9abcc5e5e
1import type { BetterAuthPlugin } from "better-auth";
2import { APIError, createAuthEndpoint } from "better-auth/api";
3import { setSessionCookie } from "better-auth/cookies";
4import * as z from "zod";
5
6// Server-only: called after a BioLock check has passed, to create the account (first device) and the session.
7export const biolockSessions = () => ({
8 id: "biolock",
9 endpoints: {
10 biolockStartSession: createAuthEndpoint("/biolock/start-session", {
11 method: "POST",
12 body: z.object({ userId: z.string().max(100).optional(), newName: z.string().min(1).max(80).optional() }),
13 metadata: { SERVER_ONLY: true },
14 }, async (ctx) => {
15 const adapter = ctx.context.internalAdapter;
16 let user = ctx.body.userId ? await adapter.findUserById(ctx.body.userId) : null;
17 if (!user && ctx.body.newName) {
18 const id = crypto.randomUUID();
19 user = await adapter.createUser({
20 name: ctx.body.newName,
21 // Accounts have no email. This placeholder only fills the required column and is never contacted.
22 email: `member-${id}@members.becomeapro.ai`,
23 emailVerified: false,
24 }, { method: "email-password" } as Parameters<typeof adapter.createUser>[1]);
25 }
26 if (!user) throw new APIError("UNAUTHORIZED", { message: "Account not found." });
27 const session = await adapter.createSession(user.id);
28 if (!session) throw new APIError("UNAUTHORIZED", { message: "Could not start a session." });
29 await setSessionCookie(ctx, { session, user });
30 return ctx.json({ userId: user.id });
31 }),
32 },
33}) satisfies BetterAuthPlugin;