feat: email+password auth with db-backed sessions

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
ahmed mohammed
2026-09-22 07:32:07 +03:00
co-authored by Claude Opus 4.7
parent 692ffa97c5
commit 5f8746cfae
13 changed files with 199 additions and 13 deletions
+34
View File
@@ -0,0 +1,34 @@
"use server";
import { redirect } from "next/navigation";
import { revalidatePath } from "next/cache";
import { userByEmail, getSettings, renameAnalysis, deleteAnalysis } from "@/lib/db";
import { signUpNewUser, verifyPassword, startSession, endSession, requireUser, emailOk } from "@/lib/auth";
export async function signUp(_: unknown, fd: FormData) {
const r = signUpNewUser(String(fd.get("email") ?? ""), String(fd.get("password") ?? ""));
if (!r.ok) return r;
await startSession(r.id);
redirect("/setup");
}
export async function signIn(_: unknown, fd: FormData) {
const e = String(fd.get("email") ?? "").trim().toLowerCase();
const u = emailOk(e) ? userByEmail(e) : null;
if (!u || !verifyPassword(String(fd.get("password") ?? ""), u.pass))
return { ok: false, error: "Email or password is wrong." };
await startSession(u.id);
redirect(getSettings(u.id)?.onboarded === 1 ? "/app" : "/setup");
}
export async function signOut() { await endSession(); redirect("/login"); }
export async function rename(_: unknown, fd: FormData) {
const u = await requireUser();
const id = String(fd.get("id") ?? "");
const title = String(fd.get("title") ?? "").trim().slice(0, 120);
if (id && title) renameAnalysis(id, u.id, title);
revalidatePath("/app");
}
export async function remove(_: unknown, fd: FormData) {
const u = await requireUser();
deleteAnalysis(String(fd.get("id") ?? ""), u.id);
revalidatePath("/app");
}
+64
View File
@@ -0,0 +1,64 @@
import { randomBytes, scryptSync, createHash, timingSafeEqual } from "node:crypto";
import { createUser, userByEmail, userEmail, putSession, sessionUserId, dropSession, getSettings } from "./db.ts";
export const SESSION_COOKIE = "qai_s";
export const SESSION_DAYS = 30;
export const emailOk = (e: string) => /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e);
export const passwordOk = (p: string) => p.length >= 10; // trust boundary: signup + password change only
export function hashPassword(pw: string): string {
const salt = randomBytes(16);
return `${salt.toString("hex")}:${scryptSync(pw, salt, 64).toString("hex")}`;
}
export function verifyPassword(pw: string, stored: string): boolean {
const [salt, hash] = stored.split(":");
if (!salt || !hash) return false;
try {
const a = scryptSync(pw, Buffer.from(salt, "hex"), 64);
const b = Buffer.from(hash, "hex");
return a.length === b.length && timingSafeEqual(a, b);
} catch { return false; }
}
export const hashToken = (t: string) => createHash("sha256").update(t).digest("hex");
export function signUpNewUser(email: string, password: string): { ok: true; id: string } | { ok: false; error: string } {
const e = email.trim().toLowerCase();
if (!emailOk(e)) return { ok: false, error: "Enter a valid email address." };
if (!passwordOk(password)) return { ok: false, error: "Use at least 10 characters." };
if (userByEmail(e)) return { ok: false, error: "That email already has an account." };
// ponytail: no rate limiting — single-container tool. Add a token bucket before exposing this to a network.
return { ok: true, id: createUser(e, hashPassword(password)) };
}
// next/headers is imported lazily: `node --test` loads this module to test the crypto above, and the
// request-scoped binding must not be touched at import time.
const jar = async () => (await import("next/headers")).cookies();
export async function startSession(userId: string) {
const token = randomBytes(32).toString("hex");
putSession(hashToken(token), userId, Date.now() + SESSION_DAYS * 864e5);
(await jar()).set(SESSION_COOKIE, token, {
httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production",
path: "/", maxAge: SESSION_DAYS * 86400 });
}
export async function endSession() {
const store = await jar();
const t = store.get(SESSION_COOKIE)?.value;
if (t) dropSession(hashToken(t));
store.delete(SESSION_COOKIE);
}
export async function sessionUser(): Promise<{ id: string; email: string } | null> {
const t = (await jar()).get(SESSION_COOKIE)?.value;
if (!t) return null;
const id = sessionUserId(hashToken(t));
if (!id) return null;
const row = userEmail(id);
return row ? { id, email: row.email } : null;
}
export async function requireUser(): Promise<{ id: string; email: string }> {
const { redirect } = await import("next/navigation"); // lazy for the same reason as jar()
const u = await sessionUser();
if (!u) { redirect("/login"); throw new Error("redirecting to /login"); } // redirect throws; this only satisfies the type
return u;
}
export const needsOnboarding = (userId: string) => getSettings(userId)?.onboarded !== 1;
+2 -1
View File
@@ -29,7 +29,8 @@ export const db = (g.__qaiDb ??= (() => {
})());
const now = () => Date.now();
const one = <T>(sql: string, ...p: unknown[]): T | null => (db.prepare(sql).get(...p) as T) ?? null;
type Row = string | number | null;
const one = <T>(sql: string, ...p: Row[]): T | null => (db.prepare(sql).get(...p) as T | undefined) ?? null;
// node:sqlite binds null/number/string/bigint/Buffer only: pass 0/1, never booleans.
export type SettingsInput = { analyst_base_url: string; analyst_key: string; analyst_model: string;