feat(auth): setup/login/logout, argon2id, sessions, login rate limit

This commit is contained in:
marcuspaico
2026-08-17 14:11:00 -07:00
parent 3c796da649
commit 0b8e897e31
5 changed files with 162 additions and 3 deletions

23
server/src/app.ts Normal file
View File

@@ -0,0 +1,23 @@
import { Hono } from "hono";
import { getCookie } from "hono/cookie";
import type { Db } from "./db";
import { authRoutes, isAuthenticated } from "./routes/auth";
export type Deps = { db: Db; key: Buffer };
const PUBLIC = new Set(["/api/health", "/api/me", "/api/setup", "/api/login"]);
export function createApp(deps: Deps) {
const app = new Hono();
app.get("/api/health", (c) => c.json({ ok: true }));
app.use("/api/*", async (c, next) => {
if (PUBLIC.has(c.req.path)) return next();
if (!(await isAuthenticated(deps.db, getCookie(c, "helios_session")))) {
return c.json({ error: "unauthenticated" }, 401);
}
return next();
});
app.route("/api", authRoutes({ db: deps.db }));
// Later route groups (settings, connectors, chat) mount here.
app.get("/api/settings", (c) => c.json({ error: "not implemented" }, 501)); // replaced in Task 5
return app;
}

View File

@@ -1,6 +1,8 @@
import { Hono } from "hono";
import { openDb } from "./db";
import { loadOrCreateKey } from "./lib/crypto";
import { createApp } from "./app";
const app = new Hono();
app.get("/api/health", (c) => c.json({ ok: true }));
const dataDir = process.env.DATA_DIR ?? "./data";
const app = createApp({ db: openDb(dataDir), key: loadOrCreateKey(dataDir) });
export default { port: Number(process.env.PORT ?? 3000), fetch: app.fetch };

75
server/src/routes/auth.ts Normal file
View File

@@ -0,0 +1,75 @@
import { eq } from "drizzle-orm";
import { Hono } from "hono";
import { getCookie, setCookie } from "hono/cookie";
import { randomBytes } from "node:crypto";
import { PasswordBody } from "@helios/shared";
import type { Db } from "../db";
import { sessions, settings } from "../db/schema";
const SESSION_MS = 30 * 24 * 3600 * 1000;
const WINDOW_MS = 15 * 60 * 1000;
const MAX_FAILURES = 10;
export type AuthDeps = { db: Db };
export function authRoutes({ db }: AuthDeps) {
const failures = new Map<string, { count: number; resetAt: number }>();
const app = new Hono();
const getHash = async () =>
(await db.select().from(settings).where(eq(settings.key, "password_hash"))).at(0)?.value;
app.get("/me", async (c) => {
const sid = getCookie(c, "helios_session");
let authenticated = false;
if (sid) {
const row = (await db.select().from(sessions).where(eq(sessions.id, sid))).at(0);
authenticated = !!row && row.expiresAt > Date.now();
}
return c.json({ needsSetup: !(await getHash()), authenticated });
});
app.post("/setup", async (c) => {
if (await getHash()) return c.json({ error: "already set up" }, 400);
const body = PasswordBody.safeParse(await c.req.json().catch(() => null));
if (!body.success) return c.json({ error: "password must be 8–200 chars" }, 400);
const hash = await Bun.password.hash(body.data.password, "argon2id");
await db.insert(settings).values({ key: "password_hash", value: hash });
return c.body(null, 204);
});
app.post("/login", async (c) => {
const ip = c.req.header("x-forwarded-for") ?? "local";
const f = failures.get(ip);
if (f && f.count >= MAX_FAILURES && Date.now() < f.resetAt) return c.json({ error: "too many attempts" }, 429);
const body = PasswordBody.safeParse(await c.req.json().catch(() => null));
const hash = await getHash();
const ok = body.success && !!hash && (await Bun.password.verify(body.data.password, hash));
if (!ok) {
const cur = f && Date.now() < f.resetAt ? f : { count: 0, resetAt: Date.now() + WINDOW_MS };
failures.set(ip, { count: cur.count + 1, resetAt: cur.resetAt });
return c.json({ error: "invalid password" }, 401);
}
failures.delete(ip);
const id = randomBytes(32).toString("base64url");
await db.insert(sessions).values({ id, createdAt: Date.now(), expiresAt: Date.now() + SESSION_MS });
setCookie(c, "helios_session", id, { httpOnly: true, sameSite: "Lax", path: "/", maxAge: SESSION_MS / 1000 });
return c.body(null, 204);
});
app.post("/logout", async (c) => {
const sid = getCookie(c, "helios_session");
if (sid) await db.delete(sessions).where(eq(sessions.id, sid));
setCookie(c, "helios_session", "", { httpOnly: true, path: "/", maxAge: 0 });
return c.body(null, 204);
});
return app;
}
export async function isAuthenticated(db: Db, sid: string | undefined): Promise<boolean> {
if (!sid) return false;
const row = (await db.select().from(sessions).where(eq(sessions.id, sid))).at(0);
return !!row && row.expiresAt > Date.now();
}