SPB Git

Repository Public

index.ts 6.5 KB 97 lines typescript

1// SP Vault API server: security headers, CSRF defence, structured content-free logs, static web app.2import fs from "node:fs";3import path from "node:path";4import Fastify, { type FastifyInstance } from "fastify";5import cookie from "@fastify/cookie";6import fastifyStatic from "@fastify/static";7import { authRoutes } from "./auth.ts";8import { config, HttpError, migrate, presentedToken, sql } from "./core.ts";9import { maintenance, vaultRoutes } from "./vaults.ts";10import { connectRoutes } from "./connect.ts";1112export const CSP = [13  "default-src 'none'", "script-src 'self'", "style-src 'self'", "img-src 'self' data: blob:", "font-src 'self'", "connect-src 'self'",14  "manifest-src 'self'", "worker-src 'self'", "frame-ancestors 'none'", "base-uri 'none'", "form-action 'none'", "object-src 'none'",15  "require-trusted-types-for 'script'", "trusted-types 'none'",16].join("; ");1718export async function build(): Promise<FastifyInstance> {19  const app: FastifyInstance = Fastify({ logger: { level: config.logLevel }, disableRequestLogging: true, trustProxy: config.trustProxy.length ? config.trustProxy : false, bodyLimit: 2 * 1024 * 1024 });20  await app.register(cookie);21  app.removeContentTypeParser("text/plain"); // only JSON and binary chunks are accepted (anything else: 415)22  app.addContentTypeParser("application/octet-stream", { parseAs: "buffer" }, (_req, body, done) => done(null, body));23  // JSON bodies are kept verbatim as well: workload identities sign the exact bytes they sent.24  app.addContentTypeParser("application/json", { parseAs: "string" }, (req, body, done) => {25    req.rawBody = body as string;26    if (body === "") return done(null, undefined);27    try { done(null, JSON.parse(body as string)); } catch { done(Object.assign(new Error("invalid JSON"), { statusCode: 400 })); }28  });2930  app.addHook("onRequest", async (req, reply) => {31    reply.header("strict-transport-security", "max-age=63072000; includeSubDomains; preload")32      .header("x-content-type-options", "nosniff").header("x-frame-options", "DENY").header("referrer-policy", "no-referrer")33      .header("cross-origin-opener-policy", "same-origin").header("cross-origin-resource-policy", "same-origin")34      .header("permissions-policy", "camera=(self), microphone=(), geolocation=(), payment=(), usb=(), publickey-credentials-get=(self), publickey-credentials-create=(self)")35      .header("content-security-policy", CSP);36    if (req.url.startsWith("/api/")) {37      reply.header("cache-control", "no-store");38      // CSRF: cookie-authenticated state changes must come from our own origin and carry a custom header39      // (which a cross-site form cannot set). Bearer-token clients are not exposed to CSRF. No CORS headers are ever sent.40      if (req.method !== "GET" && req.method !== "HEAD") {41        const origin = req.headers.origin;42        if (origin && origin !== config.origin) throw new HttpError(403, "bad_origin");43        // /api/v1/agent/* is authenticated by a per-request signature (no ambient credential), so it is not CSRF-exposed.44        if (!req.url.startsWith("/api/v1/agent/") && presentedToken(req)?.viaCookie !== false && req.headers["x-spv"] !== "1") throw new HttpError(403, "csrf");45      }46    }47  });4849  // Logs: request id, method, route template, status, duration. Never URLs with parameters, bodies, headers or addresses of items.50  app.addHook("onResponse", async (req, reply) => {51    if (req.routeOptions?.url === "/api/health/ready") return;52    req.log.info({ m: req.method, route: req.routeOptions?.url ?? "(static)", s: reply.statusCode, ms: Math.round(reply.elapsedTime) });53  });5455  app.setErrorHandler((err: any, req, reply) => {56    if (err instanceof HttpError) {57      if (err.status === 429 && (err.extra as any)?.retryAfter) reply.header("retry-after", String((err.extra as any).retryAfter));58      return reply.code(err.status).send({ error: err.code, message: err.message, ...(err.extra ?? {}) });59    }60    if (err.code === "FST_ERR_CTP_INVALID_MEDIA_TYPE") return reply.code(415).send({ error: "unsupported_media_type" });61    if (err.validation || err.statusCode === 400 || err.code === "FST_ERR_CTP_EMPTY_JSON_BODY") return reply.code(400).send({ error: "invalid_request" });62    if (err.statusCode === 413) return reply.code(413).send({ error: "too_large" });63    if (err.statusCode === 415) return reply.code(415).send({ error: "unsupported_media_type" });64    if (err.code === "23505") return reply.code(409).send({ error: "conflict" });65    req.log.error({ route: req.routeOptions?.url, err: { name: err.name, code: err.code, message: String(err.message).slice(0, 200) } });66    return reply.code(500).send({ error: "internal" });67  });6869  app.get("/api/health/ready", async () => { await sql`select 1`; return { ok: true }; });70  app.get("/.well-known/apple-app-site-association", async (_req, reply) =>71    reply.header("content-type", "application/json").send({ webcredentials: { apps: config.appleAppIds }, applinks: { details: [] } }));7273  authRoutes(app); vaultRoutes(app); connectRoutes(app);74  app.all("/api/*", async () => { throw new HttpError(404, "not_found"); });7576  if (config.webDir && fs.existsSync(path.join(config.webDir, "index.html"))) {77    await app.register(fastifyStatic, { root: path.resolve(config.webDir), wildcard: false, index: false, cacheControl: false,78      setHeaders: (res: any, file: string) => { (res.header ?? res.setHeader).call(res, "cache-control", file.includes(`${path.sep}assets${path.sep}`) ? "public, max-age=31536000, immutable" : "no-cache"); } });79    const index = fs.readFileSync(path.join(config.webDir, "index.html"));80    app.setNotFoundHandler((req, reply) => {81      if ((req.method !== "GET" && req.method !== "HEAD") || /\.[a-z0-9]{2,5}$/i.test(req.url.split("?")[0]!)) return reply.code(404).send({ error: "not_found" });82      return reply.header("content-type", "text/html; charset=utf-8").header("cache-control", "no-cache").send(index);83    });84  }85  return app;86}8788if (process.argv[1] && /(server\.mjs|index\.ts)$/.test(process.argv[1]) && import.meta.url.endsWith(path.basename(process.argv[1]))) {89  fs.mkdirSync(path.join(config.dataDir, "attachments"), { recursive: true, mode: 0o700 });90  await migrate();91  const app = await build();92  await app.listen({ port: config.port, host: config.host });93  const tick = () => maintenance().catch((e) => app.log.error({ err: String(e.message).slice(0, 200) }, "maintenance failed"));94  setTimeout(tick, 5000).unref(); setInterval(tick, 3600_000).unref();95  for (const sig of ["SIGTERM", "SIGINT"] as const) process.on(sig, async () => { await app.close(); await sql.end({ timeout: 5 }); process.exit(0); });96}97
Files main
Menu

Theme