Calio/server/app.js
Elijah 6fc0a01c56
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 1m4s
first commit
2026-10-20 19:04:12 -07:00

175 lines
5.5 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)) {
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");
},
}),
);
app.get("/{*path}", (_, res) => res.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;
}