first commit
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 1m4s

This commit is contained in:
Elijah 2026-10-20 19:04:12 -07:00
commit 6fc0a01c56
51 changed files with 11319 additions and 0 deletions

175
server/app.js Normal file
View file

@ -0,0 +1,175 @@
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;
}

25
server/auth.js Normal file
View file

@ -0,0 +1,25 @@
import {
scryptSync,
randomBytes,
timingSafeEqual,
createHash,
} from "node:crypto";
export function hashPassword(password) {
const salt = randomBytes(16).toString("hex");
return `scrypt:${salt}:${scryptSync(password, salt, 64).toString("hex")}`;
}
export function checkPassword(password, hash) {
const [method, salt, hex] = hash.split(":");
if (
method !== "scrypt" ||
!/^[a-f0-9]{32}$/.test(salt) ||
!/^[a-f0-9]{128}$/.test(hex)
)
return false;
return timingSafeEqual(
scryptSync(password, salt, 64),
Buffer.from(hex, "hex"),
);
}
export const tokenHash = (token) =>
createHash("sha256").update(token).digest("hex");

24
server/backup.js Normal file
View file

@ -0,0 +1,24 @@
import { DatabaseSync } from "node:sqlite";
import { mkdirSync, existsSync } from "node:fs";
import { dirname, resolve } from "node:path";
const source = resolve(process.env.DATA_DIR || "data", "calio.sqlite");
if (!existsSync(source)) throw new Error("No Calio database found.");
const output = resolve(
process.argv[2] ||
(process.env.DATA_DIR || "data") +
"/backups/calio-" +
new Date().toISOString().replaceAll(":", "-") +
".sqlite",
);
if (output === source || existsSync(output))
throw new Error(
"Choose a new backup path. Existing files are never overwritten.",
);
mkdirSync(dirname(output), { recursive: true });
const db = new DatabaseSync(source);
try {
db.prepare("VACUUM INTO ?").run(output);
console.log(output);
} finally {
db.close();
}

50
server/db.js Normal file
View file

@ -0,0 +1,50 @@
import { DatabaseSync } from "node:sqlite";
import { compareRecords } from "../shared/domain.js";
export function openDatabase(filename) {
const db = new DatabaseSync(filename);
db.exec(
"PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON;",
);
const version = db.prepare("PRAGMA user_version").get().user_version;
if (version > 1) {
db.close();
throw new Error(
"Database was created by a newer Calio version. Refusing to downgrade.",
);
}
if (version < 1) {
db.exec(`BEGIN IMMEDIATE;
CREATE TABLE records (id TEXT PRIMARY KEY, type TEXT NOT NULL, payload TEXT NOT NULL);
CREATE TABLE sessions (token_hash TEXT PRIMARY KEY, expires INTEGER NOT NULL);
PRAGMA user_version=1;
COMMIT;`);
}
const all = () =>
db
.prepare("SELECT payload FROM records ORDER BY id")
.all()
.map((row) => JSON.parse(row.payload));
const merge = (incoming) => {
db.exec("BEGIN IMMEDIATE");
try {
for (const record of incoming) {
const row = db
.prepare("SELECT payload FROM records WHERE id=?")
.get(record.id);
if (row && JSON.parse(row.payload).type !== record.type)
throw new Error("Record type cannot change");
if (!row || compareRecords(record, JSON.parse(row.payload)) > 0)
db.prepare(
"INSERT INTO records(id,type,payload) VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload",
).run(record.id, record.type, JSON.stringify(record));
}
db.exec("COMMIT");
} catch (error) {
db.exec("ROLLBACK");
throw error;
}
return all();
};
return { db, all, merge, close: () => db.close() };
}

49
server/index.js Normal file
View file

@ -0,0 +1,49 @@
import { mkdirSync, readFileSync } from "node:fs";
import { resolve } from "node:path";
import { openDatabase } from "./db.js";
import { createApp } from "./app.js";
import { hashPassword } from "./auth.js";
const secret = (name) =>
process.env[name + "_FILE"]
? readFileSync(process.env[name + "_FILE"], "utf8").trimEnd()
: process.env[name];
const password = secret("CALIO_PASSWORD");
const passwordHash =
secret("CALIO_PASSWORD_HASH") || (password && hashPassword(password));
if (!passwordHash || !/^scrypt:[a-f0-9]{32}:[a-f0-9]{128}$/.test(passwordHash))
throw new Error(
"Configure CALIO_PASSWORD_HASH[_FILE] or CALIO_PASSWORD[_FILE]. There are no default credentials.",
);
if (password && password.length < 12)
throw new Error("CALIO_PASSWORD must be at least 12 characters.");
const origin = process.env.APP_ORIGIN || "http://localhost:3000";
if (new URL(origin).origin !== origin)
throw new Error("APP_ORIGIN must be an origin without a trailing slash");
const secureCookies = process.env.COOKIE_SECURE !== "false";
if (
!secureCookies &&
!["localhost", "127.0.0.1"].includes(new URL(origin).hostname)
)
throw new Error(
"Insecure cookies are allowed only on localhost. Use HTTPS for deployment.",
);
const dataDir = resolve(process.env.DATA_DIR || "data");
mkdirSync(dataDir, { recursive: true });
const store = openDatabase(resolve(dataDir, "calio.sqlite"));
const app = createApp({
store,
username: process.env.CALIO_USERNAME || "calio",
passwordHash,
origin,
secureCookies,
});
const server = app.listen(Number(process.env.PORT || 3000), "0.0.0.0", () =>
console.log(`Calio listening at ${origin}`),
);
for (const signal of ["SIGTERM", "SIGINT"])
process.on(signal, () =>
server.close(() => {
store.close();
process.exit(0);
}),
);