Calio/server/app.js
Elijah 80fc48b9f1
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 1m2s
Add barcode and nutrition label scanning
Barcode scanning
- Scan barcode in the food sheet reads UPC-A/E and EAN-13/8 live from
  the camera with ZXing WebAssembly (bundled, precached, CSP allows
  wasm), with photo and typed-digit fallbacks
- Lookups check saved foods first (offline), then local copies of USDA
  FoodData Central Branded Foods and Open Food Facts, then the live
  Open Food Facts API; API answers and misses are cached
- Server imports refresh in a low-priority child process: USDA when a
  new archive is published, Open Food Facts weekly by streaming its CSV
  export; each import builds a new table and swaps it in atomically
- Every available nutrient is kept: foods and entries gain optional
  barcode (GTIN-14) and extra nutrients, shown under More nutrients and
  included in JSON exports
- Settings shows the size, date and any error for each product copy

Label scanning
- Scan label sends a downscaled photo to the server, read with
  PaddleOCR PP-OCRv5 (server detection, English recognition) on ONNX
  Runtime CPU, about 1.3 s median
- Parser handles US/Canadian, linear, Spanish and EU per-100 g panels,
  tilted photos, OCR misspellings and %DV cross-checks
- Models are pinned and checksum-verified at image build time

Container
- Runtime moves to Debian slim for ONNX Runtime's glibc build; other
  platforms' binaries are pruned
- Smoke tests now read a fixture label inside the container
- README and Unraid docs cover disk use, network access and refresh

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:41:44 -07:00

269 lines
8.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 { normalizeBarcode } from "../shared/barcode.js";
import { productToFood } from "../shared/products.js";
import { checkPassword, tokenHash } from "./auth.js";
import { fetchOffProduct } from "./products/off.js";
import { parseLabel } from "./ocr/label.js";
export function createApp({
store,
username,
passwordHash,
origin,
secureCookies = true,
dist = resolve("dist"),
products,
fetchProduct = fetchOffProduct,
ocr,
}) {
const app = express();
app.disable("x-powered-by");
app.use(
helmet({
contentSecurityPolicy: {
directives: {
// The barcode reader is WebAssembly, served from this origin.
"script-src": ["'self'", "'wasm-unsafe-eval'"],
"style-src": ["'self'", "'unsafe-inline'"],
"img-src": ["'self'", "data:", "blob:"],
"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.get("/api/products/:code", requireAuth, async (req, res) => {
const gtin = normalizeBarcode(req.params.code);
if (!gtin)
return res
.status(400)
.json({ error: "That isn’t a valid product barcode." });
if (!products)
return res
.status(503)
.json({ error: "The product database isn’t available." });
let product = products.lookup(gtin);
if (product === undefined) {
try {
product = await fetchProduct(gtin);
} catch {
return res.status(502).json({
error:
"This product isn’t in the local database yet, and Open Food Facts couldn’t be reached.",
gtin,
});
}
products.remember(gtin, product);
}
if (!product)
return res
.status(404)
.json({ error: "No nutrition information for this barcode.", gtin });
res.json({ food: productToFood(product) });
});
app.get("/api/products", requireAuth, (_, res) =>
res.json({ sources: products?.status() || [] }),
);
// One label at a time: recognition already uses every core.
let labelQueue = Promise.resolve();
app.post(
"/api/label",
requireAuth,
express.raw({
type: ["image/jpeg", "image/png", "image/webp"],
limit: "16mb",
}),
async (req, res) => {
if (!Buffer.isBuffer(req.body) || !req.body.length)
return res
.status(415)
.json({ error: "Send a JPEG, PNG or WebP photo of the label." });
if (!ocr)
return res
.status(503)
.json({ error: "Label scanning isn’t available on this server." });
const run = labelQueue.then(async () => parseLabel(await ocr(req.body)));
labelQueue = run.catch(() => {});
try {
const label = await run;
if (!label.found.length)
return res.status(422).json({
error:
"No nutrition facts were found. Fill the frame with the label and keep it sharp.",
});
res.json({ label });
} catch (error) {
if (error?.unavailable)
return res
.status(503)
.json({ error: "Label scanning isn’t available on this server." });
res
.status(422)
.json({ error: "That photo couldn’t be read. Try another one." });
}
},
);
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;
}