SPB Git

Repository Public

vaults.ts 27.1 KB 357 lines typescript

1// Vaults, encrypted records, sync deltas, history, membership / key rotation, attachments, shares, audit, events.2import fs from "node:fs";3import path from "node:path";4import type { FastifyInstance, FastifyRequest } from "fastify";5import { z } from "zod";6import { audit, bad, clientIp, config, forbidden, HttpError, need, needStrong, notFound, publish, rateLimit, safeEqual, sha256b64u, sql, subscribe, type Sql } from "./core.ts";7import { createVault, envelope, grant, parse, uuid } from "./auth.ts";89const MAX_VAULTS = 50, MAX_RECORDS_PER_VAULT = 50_000, MAX_ATTACHMENT = 100 * 1024 * 1024, CHUNK = 1024 * 1024, QUOTA = 5 * 1024 * 1024 * 1024;10const HISTORY_KEEP = 20, PAGE = 500;11const p = (req: FastifyRequest) => req.params as Record<string, string>;1213type Role = "owner" | "editor" | "reader";14/** Membership is always read from the database for the session's account; nothing client-supplied is trusted. */15async function member(db: Sql, accountId: string, vaultId: string, write = false): Promise<{ role: Role; epoch: number; ownerId: string }> {16  const [m] = await db`select m.role, v.epoch, v.owner_id from vault_members m join vaults v on v.id = m.vault_id where m.vault_id = ${vaultId} and m.account_id = ${accountId} and v.deleted_at is null`;17  if (!m) throw notFound(); // same answer for "does not exist" and "not yours"18  if (write && m.role === "reader") throw forbidden("read_only");19  return { role: m.role, epoch: m.epoch, ownerId: m.owner_id };20}21const memberIds = async (db: Sql, vaultId: string) => (await db`select account_id from vault_members where vault_id = ${vaultId}`).map((r) => r.account_id as string);2223async function idempotent(req: FastifyRequest, accountId: string, run: () => Promise<{ status: number; body: object }>) {24  const key = req.headers["idempotency-key"];25  if (typeof key !== "string" || key.length < 16 || key.length > 64) return run();26  const [hit] = await sql`select status, response from idempotency where account_id = ${accountId} and key = ${key}`;27  if (hit) return { status: hit.status as number, body: hit.response as object };28  const out = await run();29  if (out.status < 500) await sql`insert into idempotency (account_id, key, status, response) values (${accountId}, ${key}, ${out.status}, ${sql.json(out.body as any)}) on conflict do nothing`;30  return out;31}3233export function vaultRoutes(app: FastifyInstance) {34  app.post("/api/v1/vaults", async (req) => {35    const s = await need(req, "device");36    const b = parse(z.object({ vaultId: uuid, grant, meta: z.object({ recordId: uuid, envelope }).strict() }).strict(), req.body);37    if (b.grant.vaultId !== b.vaultId || b.grant.memberAccountId !== s.accountId || b.grant.granterAccountId !== s.accountId || b.grant.epoch !== 1 || b.grant.role !== "owner") throw bad("invalid_request");38    await sql.begin(async (tx) => {39      const [{ n }] = await tx`select count(*)::int as n from vaults where owner_id = ${s.accountId} and deleted_at is null` as any;40      if (n >= MAX_VAULTS) throw new HttpError(413, "quota", "Vault limit reached");41      await createVault(tx, s.accountId, s.deviceId, b);42      await audit(tx, s.accountId, "vault.created", { vault: b.vaultId }, s.deviceId);43    });44    publish([s.accountId], { type: "sync" });45    return { ok: true };46  });4748  app.delete("/api/v1/vaults/:vid", async (req) => {49    const s = await needStrong(req);50    const vid = parse(uuid, p(req).vid);51    const m = await member(sql, s.accountId, vid);52    if (m.role !== "owner") throw forbidden();53    const ids = await memberIds(sql, vid);54    await sql.begin(async (tx) => {55      await tx`update vaults set deleted_at = now() where id = ${vid}`;56      for (const id of ids) await audit(tx, id, "vault.deleted", { vault: vid }, id === s.accountId ? s.deviceId : null);57    });58    publish(ids, { type: "sync" });59    return { ok: true };60  });6162  // ── sync: everything this account may see, as deltas after per-vault cursors ───────────────────────────────63  app.post("/api/v1/sync", async (req) => {64    const s = await need(req, "device");65    rateLimit(`sync:${s.accountId}`, 600, 60);66    const b = parse(z.object({ cursors: z.record(uuid, z.number().int().min(0)).default({}) }).strict(), req.body ?? {});67    const vaults = await sql`select v.id, v.epoch, v.seq, v.owner_id, m.role from vault_members m join vaults v on v.id = m.vault_id where m.account_id = ${s.accountId} and v.deleted_at is null order by v.created_at`;68    const out = [];69    for (const v of vaults) {70      const after = b.cursors[v.id] ?? 0;71      const rows = await sql`select id, type, rev, envelope, deleted, seq, updated_at, device_id, attachments from records where vault_id = ${v.id} and seq > ${after} order by seq limit ${PAGE + 1}`;72      const grants = await sql`select epoch, role, envelope, granter_id, sig from vault_grants where vault_id = ${v.id} and member_id = ${s.accountId} order by epoch`;73      const members = await sql`select m.account_id, m.role, a.handle, a.sig_pub, a.enc_pub from vault_members m join accounts a on a.id = m.account_id where m.vault_id = ${v.id} order by m.added_at`;74      out.push({75        vaultId: v.id, epoch: v.epoch, seq: Number(v.seq), ownerId: v.owner_id, role: v.role, more: rows.length > PAGE,76        grants: grants.map((g) => ({ vaultId: v.id, epoch: g.epoch, memberAccountId: s.accountId, role: g.role, envelope: g.envelope, granterAccountId: g.granter_id, sig: g.sig })),77        members: members.map((m) => ({ accountId: m.account_id, role: m.role, handle: m.handle, sigPub: m.sig_pub, encPub: m.enc_pub })),78        changes: rows.slice(0, PAGE).map((r) => ({ id: r.id, type: r.type, rev: r.rev, envelope: r.envelope, deleted: r.deleted, seq: Number(r.seq), updatedAt: r.updated_at, deviceId: r.device_id, attachments: r.attachments })),79      });80    }81    return { serverTime: new Date().toISOString(), vaults: out };82  });8384  // ── record write: optimistic concurrency, authenticated revision, idempotent ───────────────────────────────85  app.put("/api/v1/vaults/:vid/records/:rid", async (req, reply) => {86    const s = await need(req, "device");87    rateLimit(`write:${s.accountId}`, 1200, 60);88    const vid = parse(uuid, p(req).vid), rid = parse(uuid, p(req).rid);89    const b = parse(z.object({ type: z.enum(["item", "vault-meta", "collection"]), baseRev: z.number().int().min(0), envelope, deleted: z.boolean().default(false), attachments: z.array(uuid).max(50).default([]) }).strict(), req.body);90    const out = await idempotent(req, s.accountId, async () => sql.begin(async (tx) => {91      const [v] = await tx`select v.epoch, m.role from vaults v join vault_members m on m.vault_id = v.id and m.account_id = ${s.accountId} where v.id = ${vid} and v.deleted_at is null for update of v`;92      if (!v) throw notFound();93      if (v.role === "reader") throw forbidden("read_only");94      if (b.type === "vault-meta" && v.role !== "owner") throw forbidden();95      if (b.envelope.kid !== v.epoch) return { status: 409, body: { error: "stale_key", message: "The vault key was rotated; sync and retry", epoch: v.epoch } };96      const [cur] = await tx`select type, rev, envelope, deleted, seq from records where vault_id = ${vid} and id = ${rid}`;97      if ((cur?.rev ?? 0) !== b.baseRev) return { status: 409, body: { error: "conflict", current: cur ? { id: rid, type: cur.type, rev: cur.rev, envelope: cur.envelope, deleted: cur.deleted, seq: Number(cur.seq) } : null } };98      if (cur && cur.type !== b.type) throw bad("invalid_request", "record type cannot change");99      if (!cur) {100        const [{ n }] = await tx`select count(*)::int as n from records where vault_id = ${vid}` as any;101        if (n >= MAX_RECORDS_PER_VAULT) throw new HttpError(413, "quota", "Record limit reached");102      }103      if (b.attachments.length) {104        const ok = await tx`select id from attachments where id in ${tx(b.attachments)} and vault_id = ${vid} and complete`;105        if (ok.length !== new Set(b.attachments).size) throw bad("invalid_attachment", "Unknown or incomplete attachment");106      }107      const [{ seq }] = await tx`update vaults set seq = seq + 1 where id = ${vid} returning seq` as any;108      const rev = b.baseRev + 1;109      if (cur) {110        await tx`insert into record_history (vault_id, id, rev, envelope, deleted, device_id) select vault_id, id, rev, envelope, deleted, device_id from records where vault_id = ${vid} and id = ${rid}`;111        await tx`delete from record_history where vault_id = ${vid} and id = ${rid} and rev <= ${rev - 1 - HISTORY_KEEP}`;112        await tx`update records set rev = ${rev}, envelope = ${tx.json(b.envelope)}, deleted = ${b.deleted}, seq = ${seq}, attachments = ${b.attachments}, updated_at = now(), device_id = ${s.deviceId} where vault_id = ${vid} and id = ${rid}`;113      } else {114        await tx`insert into records (vault_id, id, type, rev, envelope, deleted, seq, attachments, device_id) values (${vid}, ${rid}, ${b.type}, ${rev}, ${tx.json(b.envelope)}, ${b.deleted}, ${seq}, ${b.attachments}, ${s.deviceId})`;115      }116      return { status: 200, body: { rev, seq: Number(seq) } };117    }));118    if (out.status === 200) publish(await memberIds(sql, vid), { type: "sync", vaultId: vid });119    return reply.code(out.status).send(out.body);120  });121122  app.get("/api/v1/vaults/:vid/records/:rid/history", async (req) => {123    const s = await need(req, "device");124    const vid = parse(uuid, p(req).vid), rid = parse(uuid, p(req).rid);125    await member(sql, s.accountId, vid);126    const rows = await sql`select h.rev, h.envelope, h.deleted, h.created_at, h.device_id, r.type from record_history h join records r on r.vault_id = h.vault_id and r.id = h.id where h.vault_id = ${vid} and h.id = ${rid} order by h.rev desc limit ${HISTORY_KEEP}`;127    return { history: rows.map((r) => ({ id: rid, type: r.type, rev: r.rev, envelope: r.envelope, deleted: r.deleted, at: r.created_at, deviceId: r.device_id })) };128  });129130  // ── membership and key rotation ──────────────────────────────────────────────────────────────────────────131  app.post("/api/v1/vaults/:vid/members", async (req) => {132    const s = await needStrong(req);133    const vid = parse(uuid, p(req).vid);134    const b = parse(z.object({ grants: z.array(grant).min(1).max(20) }).strict(), req.body);135    const m = await member(sql, s.accountId, vid);136    if (m.role !== "owner") throw forbidden();137    const target = b.grants[0]!.memberAccountId, role = b.grants[0]!.role;138    if (role === "owner" || target === s.accountId) throw bad("invalid_request");139    if (!(await sql`select 1 from accounts where id = ${target}`).length) throw notFound();140    const epochs = (await sql`select distinct epoch from vault_grants where vault_id = ${vid} order by epoch`).map((r) => r.epoch as number);141    // the new member receives every epoch still needed to read existing records142    if (b.grants.some((g) => g.vaultId !== vid || g.memberAccountId !== target || g.granterAccountId !== s.accountId || g.role !== role) || !b.grants.some((g) => g.epoch === m.epoch) || b.grants.some((g) => !epochs.includes(g.epoch))) throw bad("invalid_request", "grants must cover the current epoch of this vault");143    await sql.begin(async (tx) => {144      await tx`insert into vault_members (vault_id, account_id, role) values (${vid}, ${target}, ${role}) on conflict (vault_id, account_id) do update set role = excluded.role`;145      for (const g of b.grants) await tx`insert into vault_grants (vault_id, epoch, member_id, role, envelope, granter_id, sig) values (${vid}, ${g.epoch}, ${target}, ${role}, ${g.envelope}, ${s.accountId}, ${g.sig}) on conflict (vault_id, epoch, member_id) do update set role = excluded.role, envelope = excluded.envelope, sig = excluded.sig, granter_id = excluded.granter_id`;146      await audit(tx, s.accountId, "vault.member_added", { vault: vid, member: target, role }, s.deviceId);147      await audit(tx, target, "vault.shared_with_you", { vault: vid, by: s.accountId, role }, null);148    });149    publish([s.accountId, target], { type: "sync" });150    return { ok: true };151  });152153  /** New key epoch (member removal or precaution). Removed members lose their rows; remaining members get new grants. */154  app.post("/api/v1/vaults/:vid/rotate", async (req) => {155    const s = await needStrong(req);156    const vid = parse(uuid, p(req).vid);157    const b = parse(z.object({ epoch: z.number().int().min(2), grants: z.array(grant).min(1).max(100), remove: z.array(uuid).max(100).default([]) }).strict(), req.body);158    const before = await memberIds(sql, vid);159    await sql.begin(async (tx) => {160      const [v] = await tx`select epoch, owner_id from vaults where id = ${vid} and deleted_at is null for update`;161      if (!v || v.owner_id !== s.accountId) throw notFound();162      if (b.epoch !== v.epoch + 1) throw new HttpError(409, "conflict", "Vault epoch mismatch");163      if (b.remove.includes(s.accountId)) throw bad("invalid_request");164      const remaining = (await tx`select account_id, role from vault_members where vault_id = ${vid}`).filter((m) => !b.remove.includes(m.account_id));165      const byMember = new Map(b.grants.map((g) => [g.memberAccountId, g]));166      if (byMember.size !== remaining.length || remaining.some((m) => { const g = byMember.get(m.account_id); return !g || g.role !== m.role || g.epoch !== b.epoch || g.vaultId !== vid || g.granterAccountId !== s.accountId; })) throw bad("invalid_request", "one grant per remaining member is required");167      for (const id of b.remove) {168        await tx`delete from vault_members where vault_id = ${vid} and account_id = ${id}`;169        await tx`delete from vault_grants where vault_id = ${vid} and member_id = ${id}`;170        await audit(tx, id, "vault.access_removed", { vault: vid }, null);171      }172      for (const g of b.grants) await tx`insert into vault_grants (vault_id, epoch, member_id, role, envelope, granter_id, sig) values (${vid}, ${g.epoch}, ${g.memberAccountId}, ${g.role}, ${g.envelope}, ${s.accountId}, ${g.sig})`;173      await tx`update vaults set epoch = ${b.epoch} where id = ${vid}`;174      await audit(tx, s.accountId, "vault.key_rotated", { vault: vid, epoch: b.epoch, removed: b.remove.length }, s.deviceId);175    });176    publish(before, { type: "sync" });177    return { ok: true };178  });179180  // ── attachments: opaque encrypted chunks, resumable ──────────────────────────────────────────────────────181  const attDir = (id: string) => path.join(config.dataDir, "attachments", id.slice(0, 2), id);182  app.post("/api/v1/vaults/:vid/attachments", async (req) => {183    const s = await need(req, "device");184    const vid = parse(uuid, p(req).vid);185    const b = parse(z.object({ id: uuid, chunks: z.number().int().min(1).max(MAX_ATTACHMENT / CHUNK), size: z.number().int().min(0).max(MAX_ATTACHMENT) }).strict(), req.body);186    await member(sql, s.accountId, vid, true);187    if (b.chunks !== Math.max(1, Math.ceil(b.size / CHUNK))) throw bad("invalid_request");188    const [{ used }] = await sql`select coalesce(sum(size), 0)::bigint as used from attachments where account_id = ${s.accountId}` as any;189    if (Number(used) + b.size > QUOTA) throw new HttpError(413, "quota", "Storage quota exceeded");190    await sql`insert into attachments (id, vault_id, account_id, chunks, size) values (${b.id}, ${vid}, ${s.accountId}, ${b.chunks}, ${b.size}) on conflict (id) do nothing`;191    const [a] = await sql`select vault_id, account_id, chunks from attachments where id = ${b.id}`;192    if (a.vault_id !== vid || a.account_id !== s.accountId || a.chunks !== b.chunks) throw new HttpError(409, "conflict");193    fs.mkdirSync(attDir(b.id), { recursive: true, mode: 0o700 });194    return { uploaded: fs.readdirSync(attDir(b.id)).filter((f) => /^\d+$/.test(f)).map(Number).sort((x, y) => x - y) };195  });196197  async function attachmentFor(req: FastifyRequest, write: boolean) {198    const s = await need(req, "device");199    const id = parse(uuid, p(req).aid);200    const [a] = await sql`select * from attachments where id = ${id}`;201    if (!a) throw notFound();202    await member(sql, s.accountId, a.vault_id, write);203    const i = Number(p(req).i);204    if (p(req).i !== undefined && (!Number.isInteger(i) || i < 0 || i >= a.chunks)) throw notFound();205    return { s, a, i, file: path.join(attDir(id), String(i)) };206  }207208  app.put("/api/v1/attachments/:aid/chunks/:i", { bodyLimit: CHUNK + 64 }, async (req) => {209    const { s, a, i, file } = await attachmentFor(req, true);210    rateLimit(`upload:${s.accountId}`, 2000, 600);211    if (a.complete) throw new HttpError(409, "conflict", "Attachment already complete");212    const body = req.body as Buffer;213    if (!Buffer.isBuffer(body)) throw bad("invalid_request", "application/octet-stream body expected");214    const last = i === a.chunks - 1, expected = last ? Number(a.size) - CHUNK * (a.chunks - 1) + 16 : CHUNK + 16;215    if (body.length !== expected) throw bad("invalid_request", "unexpected chunk size");216    fs.writeFileSync(file + ".part", body, { mode: 0o600 });217    fs.renameSync(file + ".part", file); // atomic: a crash never leaves a short chunk under the final name218    return { ok: true };219  });220221  app.post("/api/v1/attachments/:aid/complete", async (req) => {222    const { a } = await attachmentFor(req, true);223    for (let i = 0; i < a.chunks; i++) if (!fs.existsSync(path.join(attDir(a.id), String(i)))) throw new HttpError(409, "incomplete", `chunk ${i} is missing`);224    await sql`update attachments set complete = true where id = ${a.id}`;225    return { ok: true };226  });227228  app.get("/api/v1/attachments/:aid/chunks/:i", async (req, reply) => {229    const { a, file } = await attachmentFor(req, false);230    if (!a.complete || !fs.existsSync(file)) throw notFound();231    return reply.header("content-type", "application/octet-stream").header("cache-control", "no-store").send(fs.readFileSync(file));232  });233234  // ── SP Vault Relay ───────────────────────────────────────────────────────────────────────────────────────235  app.post("/api/v1/shares", async (req) => {236    const s = await needStrong(req);237    rateLimit(`share:${s.accountId}`, 60, 3600);238    const b = parse(z.object({239      id: uuid, kind: z.enum(["account", "link"]), recipientAccountId: uuid.optional(), box: z.string().regex(/^[A-Za-z0-9_-]+$/).min(300).max(400_000),240      sig: z.string().regex(/^[A-Za-z0-9_-]{86}$/).optional(), authHash: z.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),241      expiresInSec: z.number().int().min(60).max(30 * 86400), maxViews: z.number().int().min(1).max(100).optional(),242    }).strict(), req.body);243    if (b.kind === "account" ? !(b.recipientAccountId && b.sig) : !b.authHash) throw bad("invalid_request");244    if (b.kind === "account" && !(await sql`select 1 from accounts where id = ${b.recipientAccountId!}`).length) throw notFound();245    await sql.begin(async (tx) => {246      await tx`insert into shares (id, sender_id, kind, recipient_id, box, sig, auth_hash, expires_at, max_views) values (${b.id}, ${s.accountId}, ${b.kind}, ${b.recipientAccountId ?? null}, ${b.box}, ${b.sig ?? null}, ${b.authHash ?? null}, now() + ${b.expiresInSec} * interval '1 second', ${b.maxViews ?? null})`;247      await audit(tx, s.accountId, "share.created", { share: b.id, kind: b.kind, recipient: b.recipientAccountId ?? null }, s.deviceId);248      if (b.recipientAccountId) await audit(tx, b.recipientAccountId, "share.received", { share: b.id, from: s.accountId }, null);249    });250    if (b.recipientAccountId) publish([b.recipientAccountId], { type: "shares" });251    return { ok: true };252  });253254  app.get("/api/v1/shares", async (req) => {255    const s = await need(req, "device");256    const view = (r: any) => ({ id: r.id, kind: r.kind, senderId: r.sender_id, senderHandle: r.sender_handle, recipientId: r.recipient_id, recipientHandle: r.recipient_handle, createdAt: r.created_at, expiresAt: r.expires_at, maxViews: r.max_views, views: r.views, revoked: !!r.revoked_at, expired: r.expires_at < new Date() });257    const rows = await sql`select s.*, a.handle as sender_handle, b.handle as recipient_handle from shares s join accounts a on a.id = s.sender_id left join accounts b on b.id = s.recipient_id where (s.sender_id = ${s.accountId} or s.recipient_id = ${s.accountId}) and s.created_at > now() - interval '90 days' order by s.created_at desc limit 200`;258    return { sent: rows.filter((r) => r.sender_id === s.accountId).map(view), received: rows.filter((r) => r.recipient_id === s.accountId && !r.revoked_at && r.expires_at > new Date()).map(view) };259  });260261  const takeShare = (tx: Sql, where: ReturnType<typeof sql>) => tx`update shares set views = views + 1 where ${where} and revoked_at is null and expires_at > now() and (max_views is null or views < max_views) returning *`;262263  app.post("/api/v1/shares/:id/open", async (req) => {264    const s = await need(req, "device");265    const id = parse(uuid, p(req).id);266    return sql.begin(async (tx) => {267      const [r] = await takeShare(tx, tx`id = ${id} and kind = 'account' and recipient_id = ${s.accountId}` as any);268      if (!r) throw notFound();269      const [a] = await tx`select sig_pub, handle from accounts where id = ${r.sender_id}`;270      await audit(tx, r.sender_id, "share.opened", { share: id, by: s.accountId, views: r.views }, null);271      return { box: { ct: r.box, sig: r.sig }, senderId: r.sender_id, senderHandle: a.handle, senderSigPub: a.sig_pub };272    });273  });274275  /** Public link: unauthenticated; the caller proves knowledge of the fragment secret's auth half. */276  app.post("/api/v1/public/shares/:id", async (req) => {277    rateLimit(`pubshare:${clientIp(req)}`, 30, 600);278    const id = parse(uuid, p(req).id);279    const b = parse(z.object({ auth: z.string().regex(/^[A-Za-z0-9_-]{43}$/) }).strict(), req.body);280    return sql.begin(async (tx) => {281      const [chk] = await tx`select auth_hash from shares where id = ${id} and kind = 'link'`;282      if (!safeEqual(sha256b64u(Buffer.from(b.auth, "base64url")), chk?.auth_hash ?? "x".repeat(43))) throw notFound();283      const [r] = await takeShare(tx, tx`id = ${id} and kind = 'link'` as any);284      if (!r) throw new HttpError(410, "gone", "This link expired, was revoked or reached its view limit");285      await audit(tx, r.sender_id, "share.opened", { share: id, views: r.views }, null, "public-link");286      return { box: r.box };287    });288  });289290  app.delete("/api/v1/shares/:id", async (req) => {291    const s = await need(req, "device");292    const id = parse(uuid, p(req).id);293    await sql.begin(async (tx) => {294      // the ciphertext is erased, not just flagged295      if (!(await tx`update shares set revoked_at = now(), box = '' where id = ${id} and sender_id = ${s.accountId} and revoked_at is null returning 1`).length) throw notFound();296      await audit(tx, s.accountId, "share.revoked", { share: id }, s.deviceId);297    });298    return { ok: true };299  });300301  // ── audit trail ──────────────────────────────────────────────────────────────────────────────────────────302  app.get("/api/v1/audit", async (req) => {303    const s = await need(req, "device");304    const before = Number((req.query as any).before) || Number.MAX_SAFE_INTEGER;305    const rows = await sql`select id, at, device_id, actor, kind, detail, prev_hash, hash from audit_events where account_id = ${s.accountId} and id < ${before} order by id desc limit 100`;306    return { events: rows.map((r) => ({ id: Number(r.id), at: r.at, deviceId: r.device_id, actor: r.actor, kind: r.kind, detail: r.detail, prevHash: r.prev_hash, hash: r.hash })) };307  });308309  /** Client-reported sensitive actions the server cannot observe (they happen on the device). Fresh authentication required. */310  app.post("/api/v1/audit/client", async (req) => {311    const s = await needStrong(req);312    const b = parse(z.object({ kind: z.enum(["export.plaintext", "export.backup", "import", "item.revealed-bulk"]) }).strict(), req.body);313    await sql.begin((tx) => audit(tx, s.accountId, b.kind, {}, s.deviceId));314    return { ok: true };315  });316317  // ── live pokes (SSE) ─────────────────────────────────────────────────────────────────────────────────────318  app.get("/api/v1/events", async (req, reply) => {319    const s = await need(req, "device");320    reply.hijack();321    reply.raw.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", "x-accel-buffering": "no", connection: "keep-alive" });322    reply.raw.write(": ok\n\n");323    const off = subscribe(s.accountId, (e) => reply.raw.write(`data: ${JSON.stringify(e)}\n\n`));324    const ping = setInterval(() => reply.raw.write(": ping\n\n"), 25_000);325    req.raw.on("close", () => { clearInterval(ping); off(); });326  });327328  // ── breach range proxy (k-anonymity; the upstream never sees the client) ────────────────────────────────329  app.get("/api/v1/breach/range/:prefix", async (req, reply) => {330    const s = await need(req, "device");331    rateLimit(`breach:${s.accountId}`, 3000, 3600);332    const prefix = p(req).prefix!;333    if (!/^[0-9A-F]{5}$/.test(prefix)) throw bad("invalid_request");334    const r = await fetch(config.breachUpstream + prefix, { headers: { "add-padding": "true", "user-agent": "password-manager" }, signal: AbortSignal.timeout(8000) }).catch(() => null);335    if (!r?.ok) throw new HttpError(502, "upstream_unavailable");336    return reply.header("content-type", "text/plain").header("cache-control", "no-store").send(await r.text());337  });338}339340/** Periodic maintenance: expired rows, abandoned uploads, unreferenced attachments, purged tombstones. */341export async function maintenance() {342  await sql`delete from challenges where expires_at < now()`;343  await sql`delete from sessions where expires_at < now()`;344  await sql`delete from pairings where expires_at < now() - interval '1 hour'`;345  await sql`delete from idempotency where created_at < now() - interval '2 days'`;346  await sql`delete from invites where expires_at < now() - interval '30 days'`;347  await sql`update shares set box = '' where box <> '' and (expires_at < now() or (max_views is not null and views >= max_views))`;348  await sql`delete from record_history h using records r where r.vault_id = h.vault_id and r.id = h.id and r.deleted and r.updated_at < now() - interval '30 days'`;349  const dead = await sql`350    delete from attachments a where (not complete and created_at < now() - interval '1 day')351      or (complete and created_at < now() - interval '1 day' and not exists (select 1 from records r where r.vault_id = a.vault_id and a.id = any(r.attachments)))352      or not exists (select 1 from vaults v where v.id = a.vault_id and v.deleted_at is null)353    returning id`;354  for (const d of dead) fs.rmSync(path.join(config.dataDir, "attachments", d.id.slice(0, 2), d.id), { recursive: true, force: true });355  await sql`delete from vaults where deleted_at < now() - interval '30 days'`;356}357
Files main
Menu

Theme