Calio/server/app.js
Elijah 8f6981c8a2
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 29s
Apply app updates automatically and survive proxy caching
- Check for a new service worker on every return to the foreground and
  every 30 minutes; apply it in the background or just after launch,
  never with unsynced edits or an open sheet. The Update prompt remains.
- Register the worker at extension-less /sw (no-cache), so proxies that
  cache *.js regardless of headers cannot hide updates
- Return 404 for missing files instead of the HTML shell
- Tests for the static routes; smoke test covers /sw; document the Nginx
  Proxy Manager "Cache Assets" pitfall

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:19:30 -07:00

190 lines
6.2 KiB
JavaScript

import express from "express";
import helmet from "helmet";
import { rateLimit } from "express-rate-limit";
import { randomBytes, timingSafeEqual, createHash } from "node:crypto";
import { resolve, join } from "node:path";
import { existsSync } from "node:fs";
import { z } from "zod";
import { recordSchema } from "../shared/domain.js";
import { checkPassword, tokenHash } from "./auth.js";
export function createApp({
store,
username,
passwordHash,
origin,
secureCookies = true,
dist = resolve("dist"),
}) {
const app = express();
app.disable("x-powered-by");
app.use(
helmet({
contentSecurityPolicy: {
directives: {
"script-src": ["'self'"],
"style-src": ["'self'", "'unsafe-inline'"],
"img-src": ["'self'", "data:"],
"connect-src": ["'self'"],
"object-src": ["'none'"],
"upgrade-insecure-requests": secureCookies ? [] : null,
},
},
strictTransportSecurity: secureCookies ? undefined : false,
}),
);
app.use("/api", (_, res, next) => {
res.set("Cache-Control", "no-store");
next();
});
app.use("/api", (req, res, next) => {
if (
["POST", "PUT", "PATCH", "DELETE"].includes(req.method) &&
(req.get("X-Calio-Request") !== "1" || req.get("Origin") !== origin)
)
return res.status(403).json({ error: "Request origin rejected" });
next();
});
app.use(express.json({ limit: "2mb" }));
app.get("/api/health", (_, res) => res.json({ ok: true, version: "0.1.0" }));
const cookieName = secureCookies ? "__Host-calio" : "calio";
const getToken = (req) =>
req.headers.cookie
?.split(";")
.map((v) => v.trim())
.find((v) => v.startsWith(cookieName + "="))
?.slice(cookieName.length + 1) || "";
const cookie = {
httpOnly: true,
secure: secureCookies,
sameSite: "strict",
path: "/",
maxAge: 30 * 86400000,
};
const requireAuth = (req, res, next) => {
const session = store.db
.prepare("SELECT expires FROM sessions WHERE token_hash=?")
.get(tokenHash(getToken(req)));
if (!session || session.expires < Date.now())
return res.status(401).json({ error: "Sign in to sync your journal" });
next();
};
const loginLimiter = rateLimit({
windowMs: 15 * 60000,
limit: 10,
standardHeaders: "draft-8",
legacyHeaders: false,
message: { error: "Too many sign-in attempts. Try again in 15 minutes." },
});
app.post("/api/login", loginLimiter, (req, res) => {
if (
typeof req.body?.username !== "string" ||
typeof req.body?.password !== "string" ||
req.body.password.length > 1024
)
return res.status(400).json({ error: "Enter a username and password" });
const digest = (value) => createHash("sha256").update(value).digest();
const correctPassword = checkPassword(req.body.password, passwordHash);
if (
!timingSafeEqual(digest(req.body.username), digest(username)) ||
!correctPassword
)
return res.status(401).json({ error: "Incorrect username or password" });
const token = randomBytes(32).toString("hex");
store.db.prepare("DELETE FROM sessions WHERE expires < ?").run(Date.now());
store.db
.prepare("INSERT INTO sessions VALUES (?,?)")
.run(tokenHash(token), Date.now() + cookie.maxAge);
res.cookie(cookieName, token, cookie).json({ ok: true });
});
app.get("/api/session", requireAuth, (_, res) =>
res.json({ authenticated: true }),
);
app.post("/api/logout", (req, res) => {
store.db
.prepare("DELETE FROM sessions WHERE token_hash=?")
.run(tokenHash(getToken(req)));
res
.clearCookie(cookieName, { ...cookie, maxAge: undefined })
.json({ ok: true });
});
app.get("/api/records", requireAuth, (_, res) =>
res.json({ records: store.all(), serverTime: new Date().toISOString() }),
);
app.post("/api/sync", requireAuth, (req, res) => {
const parsed = z
.object({ records: z.array(recordSchema).max(1000) })
.strict()
.safeParse(req.body);
if (!parsed.success)
return res
.status(400)
.json({
error: "Invalid journal data",
details: parsed.error.flatten(),
});
if (
parsed.data.records.some(
(record) => Date.parse(record.updatedAt) > Date.now() + 300000,
)
)
return res
.status(400)
.json({
error: "Your device clock is ahead. Correct it before syncing.",
});
try {
res.json({
records: store.merge(parsed.data.records),
serverTime: new Date().toISOString(),
});
} catch {
res
.status(409)
.json({
error: "A record ID is already used for another kind of item",
});
}
});
app.use("/api", (_, res) => res.status(404).json({ error: "Not found" }));
if (existsSync(dist)) {
// The service worker is also served without a file extension. Reverse
// proxies that cache by extension (e.g. Nginx Proxy Manager's "Cache
// Assets") ignore no-cache on .js files, which hides app updates.
app.get("/sw", (_, res) =>
res
.set("Cache-Control", "no-cache")
.type("text/javascript")
.sendFile(join(dist, "sw.js")),
);
app.use(
express.static(dist, {
maxAge: 0,
setHeaders: (res, path) => {
if (path.includes(`${join("assets", "")}`))
res.set("Cache-Control", "public, max-age=31536000, immutable");
if (path.endsWith("sw.js") || path.endsWith("index.html"))
res.set("Cache-Control", "no-cache");
},
}),
);
// Only app routes fall back to the shell. A missing file (an old build's
// asset, say) must be a 404, never HTML that a cache could keep as script.
app.get("/{*path}", (req, res) => {
if (/\.[a-z0-9]+$/i.test(req.path))
return res.status(404).type("text/plain").send("Not found");
res.set("Cache-Control", "no-cache").sendFile(join(dist, "index.html"));
});
}
app.use((error, _req, res, _next) =>
res
.status(error.status || 500)
.json({
error:
error.status === 413
? "Request is too large"
: "Request could not be processed",
}),
);
return app;
}