Repository Public
1// Configuration, database, migrations, sessions, rate limits, audit chain and live events.2import crypto from "node:crypto";3import fs from "node:fs";4import path from "node:path";5import { fileURLToPath } from "node:url";6import postgres from "postgres";7import type { FastifyReply, FastifyRequest } from "fastify";8import { auditEntryInput } from "../../../packages/protocol/src/bytes.ts";910const env = (k: string, d?: string) => { const v = process.env[k] ?? d; if (v === undefined) throw new Error(`missing environment variable ${k}`); return v; };1112export const config = {13 port: Number(env("PORT", "8740")), host: env("HOST", "127.0.0.1"),14 origin: env("SPV_ORIGIN"), rpId: env("SPV_RP_ID"), rpName: "SP Vault",15 databaseUrl: env("DATABASE_URL"), dataDir: env("SPV_DATA_DIR"),16 webDir: process.env.SPV_WEB_DIR ?? "", trustProxy: (process.env.SPV_TRUST_PROXY ?? "").split(",").filter(Boolean),17 appleAppIds: (process.env.SPV_APPLE_APP_IDS ?? "").split(",").filter(Boolean),18 rateScale: Number(process.env.SPV_RATE_SCALE ?? "1"), logLevel: process.env.SPV_LOG_LEVEL ?? "info",19 breachUpstream: process.env.SPV_BREACH_UPSTREAM ?? "https://api.pwnedpasswords.com/range/",20 managedSocket: process.env.SPV_MANAGED_URL ?? "",21 secure: env("SPV_ORIGIN").startsWith("https://"),22};2324export const sql = postgres(config.databaseUrl, { onnotice: () => {}, max: 10, types: { bigint: postgres.BigInt } });25export type Sql = typeof sql | postgres.TransactionSql;2627export async function migrate() {28 const here = path.dirname(fileURLToPath(import.meta.url));29 const dir = [path.join(here, "migrations"), path.join(here, "../migrations"), path.join(process.cwd(), "services/api/migrations")].find((d) => fs.existsSync(d));30 if (!dir) throw new Error("migrations directory not found");31 await sql`create table if not exists schema_migrations (name text primary key, applied_at timestamptz not null default now())`;32 for (const f of fs.readdirSync(dir).filter((x) => x.endsWith(".sql")).sort()) {33 await sql.begin(async (tx) => {34 await tx`select pg_advisory_xact_lock(727274)`;35 if ((await tx`select 1 from schema_migrations where name = ${f}`).length) return;36 await tx.unsafe(fs.readFileSync(path.join(dir, f), "utf8"));37 await tx`insert into schema_migrations (name) values (${f})`;38 });39 }40}4142// ── errors ───────────────────────────────────────────────────────────────────────────────────────────────────43export class HttpError extends Error {44 constructor(public status: number, public code: string, message?: string, public extra?: object) { super(message ?? code); }45}46export const bad = (code: string, message?: string) => new HttpError(400, code, message);47export const forbidden = (code = "forbidden", message?: string) => new HttpError(403, code, message);48export const notFound = () => new HttpError(404, "not_found");4950// ── helpers ──────────────────────────────────────────────────────────────────────────────────────────────────51export const sha256b64u = (s: string | Uint8Array) => crypto.createHash("sha256").update(s).digest("base64url");52export const randomToken = (n = 32) => crypto.randomBytes(n).toString("base64url");53export function safeEqual(a: string, b: string): boolean {54 const x = Buffer.from(a), y = Buffer.from(b);55 return x.length === y.length && crypto.timingSafeEqual(x, y);56}5758// ── rate limiting (fixed windows, in memory; one API process) ───────────────────────────────────────────────59const buckets = new Map<string, { n: number; reset: number }>();60export function rateLimit(key: string, max: number, windowSec: number) {61 const now = Date.now(), limit = Math.ceil(max * config.rateScale);62 let b = buckets.get(key);63 if (!b || b.reset < now) { b = { n: 0, reset: now + windowSec * 1000 }; buckets.set(key, b); }64 if (++b.n > limit) throw new HttpError(429, "rate_limited", "Too many requests", { retryAfter: Math.ceil((b.reset - now) / 1000) });65}66setInterval(() => { const now = Date.now(); for (const [k, b] of buckets) if (b.reset < now) buckets.delete(k); }, 60_000).unref();6768// ── sessions ─────────────────────────────────────────────────────────────────────────────────────────────────69export interface Session { tokenHash: string; accountId: string; deviceId: string | null; kind: "pending" | "device" | "recovery"; strongAt: Date | null; platform: string | null }70export const COOKIE = () => (config.secure ? "__Host-spv" : "spv");71const TTL = { pending: 15 * 60, recovery: 15 * 60, device: 30 * 86400 } as const;72export const STRONG_WINDOW_SEC = 5 * 60;7374export async function createSession(db: Sql, accountId: string, kind: Session["kind"], deviceId: string | null, strong: boolean): Promise<string> {75 const token = randomToken();76 await db`insert into sessions (token_hash, account_id, device_id, kind, expires_at, strong_at)77 values (${sha256b64u(token)}, ${accountId}, ${deviceId}, ${kind}, now() + ${TTL[kind]} * interval '1 second', ${strong ? db`now()` : null})`;78 return token;79}8081export function setSessionCookie(reply: FastifyReply, token: string) {82 reply.setCookie(COOKIE(), token, { path: "/", httpOnly: true, secure: config.secure, sameSite: "strict", maxAge: TTL.device });83}8485export function presentedToken(req: FastifyRequest): { token: string; viaCookie: boolean } | null {86 const h = req.headers.authorization;87 if (h?.startsWith("Bearer ")) return { token: h.slice(7), viaCookie: false };88 const c = req.cookies?.[COOKIE()];89 return c ? { token: c, viaCookie: true } : null;90}9192export async function loadSession(req: FastifyRequest): Promise<Session | null> {93 const p = presentedToken(req);94 if (!p || p.token.length < 40 || p.token.length > 64) return null;95 const hash = sha256b64u(p.token);96 const [r] = await sql`97 select s.account_id, s.device_id, s.kind, s.strong_at, d.platform, d.revoked_at98 from sessions s left join devices d on d.id = s.device_id where s.token_hash = ${hash} and s.expires_at > now()`;99 if (!r || r.revoked_at) return null;100 if (r.kind === "device") {101 sql`update sessions set last_seen_at = now(), expires_at = now() + interval '30 days' where token_hash = ${hash} and (last_seen_at is null or last_seen_at < now() - interval '10 minutes')`.catch(() => {});102 sql`update devices set last_seen_at = now() where id = ${r.device_id} and (last_seen_at is null or last_seen_at < now() - interval '10 minutes')`.catch(() => {});103 }104 return { tokenHash: hash, accountId: r.account_id, deviceId: r.device_id, kind: r.kind, strongAt: r.strong_at, platform: r.platform };105}106107declare module "fastify" { interface FastifyRequest { session?: Session | null } }108109export async function need(req: FastifyRequest, ...kinds: Session["kind"][]): Promise<Session> {110 const s = (req.session ??= await loadSession(req));111 if (!s) throw new HttpError(401, "unauthenticated");112 if (!(kinds.length ? kinds : ["device"]).includes(s.kind)) throw forbidden("wrong_session_kind");113 return s;114}115/** Device session whose last strong authentication (login or step-up) is recent. */116export async function needStrong(req: FastifyRequest): Promise<Session> {117 const s = await need(req, "device");118 if (!s.strongAt || Date.now() - s.strongAt.getTime() > STRONG_WINDOW_SEC * 1000) throw new HttpError(401, "reauth_required", "Recent authentication required");119 return s;120}121122// ── audit (per-account hash chain; never contains item content) ────────────────────────────────────────────123export async function audit(db: Sql, accountId: string, kind: string, detail: Record<string, unknown> = {}, deviceId: string | null = null, actor = "user") {124 const [a] = await db`select audit_head from accounts where id = ${accountId} for update`;125 if (!a) return;126 const at = new Date();127 const hash = sha256b64u(auditEntryInput(a.audit_head, accountId, at.toISOString(), deviceId, actor, kind, detail));128 await db`insert into audit_events (account_id, at, device_id, actor, kind, detail, prev_hash, hash)129 values (${accountId}, ${at}, ${deviceId}, ${actor}, ${kind}, ${db.json(detail as any)}, ${a.audit_head}, ${hash})`;130 await db`update accounts set audit_head = ${hash} where id = ${accountId}`;131 queueMicrotask(() => publish([accountId], { type: "activity", kind }));132}133134// ── live events (SSE): pokes only, never content ───────────────────────────────────────────────────────────135const listeners = new Map<string, Set<(e: object) => void>>();136export function subscribe(accountId: string, fn: (e: object) => void): () => void {137 let set = listeners.get(accountId);138 if (!set) listeners.set(accountId, (set = new Set()));139 set.add(fn);140 return () => { set!.delete(fn); if (!set!.size) listeners.delete(accountId); };141}142export function publish(accountIds: string[], event: object) {143 for (const id of new Set(accountIds)) for (const fn of listeners.get(id) ?? []) { try { fn(event); } catch { /* closed */ } }144}145146export function clientIp(req: FastifyRequest): string { return req.ip; }147