Codebase audits, privacy, dark mode, palette (v1.9.0 to v1.9.4-audit) #14
11 changed files with 143 additions and 42 deletions
9
.gitignore
vendored
9
.gitignore
vendored
|
|
@ -13,15 +13,22 @@ build/
|
|||
# local databases
|
||||
*.db
|
||||
*.db-journal
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
|
||||
# editor and OS files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
nginx-dev
|
||||
|
||||
# plain txt files
|
||||
.txt
|
||||
*.txt
|
||||
|
||||
# uploaded media (local dev)
|
||||
server/uploads/
|
||||
server/clips/
|
||||
|
||||
# skills
|
||||
graphify-out/
|
||||
|
|
@ -478,6 +478,7 @@ const people = {
|
|||
key: "private",
|
||||
table: "person_private",
|
||||
idColumn: "person_id",
|
||||
readRole: "editor", // viewers don't see birth dates, addresses, phones
|
||||
touch: true, // has its own updated_at with no trigger behind it
|
||||
columns: [
|
||||
date("birth_date"),
|
||||
|
|
|
|||
|
|
@ -29,6 +29,8 @@ const SESSION_DAYS = 30;
|
|||
// Re-issue the expiry when a session is used with less than this
|
||||
// left, so an active person is never signed out mid-task.
|
||||
const REFRESH_WITHIN_DAYS = 7;
|
||||
// However active, a session ends this long after sign-in.
|
||||
const MAX_SESSION_DAYS = 90;
|
||||
|
||||
// Off only for plain-http local work. Production is behind TLS.
|
||||
export const SECURE_COOKIE = (process.env.COOKIE_SECURE ?? "true") !== "false";
|
||||
|
|
@ -95,9 +97,11 @@ export function hashIp(ip) {
|
|||
}
|
||||
|
||||
export function clientIp(c) {
|
||||
// Trustworthy only because this service binds to 127.0.0.1 and
|
||||
// nginx is the only thing that can reach it.
|
||||
return c.req.header("x-forwarded-for")?.split(",")[0].trim() ?? null;
|
||||
// The last X-Forwarded-For entry is the one nginx (or Vite in dev)
|
||||
// added from the connection itself; anything before it is whatever
|
||||
// the client sent. Trustworthy only because this service binds to
|
||||
// 127.0.0.1 and nginx is the only thing that can reach it.
|
||||
return c.req.header("x-forwarded-for")?.split(",").at(-1).trim() || null;
|
||||
}
|
||||
|
||||
/* ── Sessions ────────────────────────────────────────────────── */
|
||||
|
|
@ -160,9 +164,10 @@ export function currentUser(db, c) {
|
|||
JOIN admin_users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = ?
|
||||
AND s.expires_at > datetime('now')
|
||||
AND s.created_at > datetime('now', ?)
|
||||
AND u.is_active = 1`,
|
||||
)
|
||||
.get(tokenHash);
|
||||
.get(tokenHash, `-${MAX_SESSION_DAYS} days`);
|
||||
|
||||
if (!row) return null;
|
||||
|
||||
|
|
|
|||
|
|
@ -291,8 +291,9 @@ async function download(db, job) {
|
|||
await run(
|
||||
YTDLP,
|
||||
[
|
||||
// Our options only: no yt-dlp.conf on the box changes them.
|
||||
"--ignore-config",
|
||||
...cookies.args,
|
||||
job.source_url,
|
||||
// YouTube needs a JavaScript runtime to list formats; the one
|
||||
// running this server will do.
|
||||
"--js-runtimes",
|
||||
|
|
@ -319,6 +320,9 @@ async function download(db, job) {
|
|||
...(process.env.FFMPEG_PATH ? ["--ffmpeg-location", process.env.FFMPEG_PATH] : []),
|
||||
"-o",
|
||||
template,
|
||||
// Last, after --, so the link can never be read as an option.
|
||||
"--",
|
||||
job.source_url,
|
||||
],
|
||||
{
|
||||
onLine: (line) => {
|
||||
|
|
|
|||
|
|
@ -13,7 +13,9 @@ import { mkdir } from "node:fs/promises";
|
|||
import { serve } from "@hono/node-server";
|
||||
import { serveStatic } from "@hono/node-server/serve-static";
|
||||
import { Hono } from "hono";
|
||||
import { csrf } from "hono/csrf";
|
||||
import { logger } from "hono/logger";
|
||||
import { secureHeaders } from "hono/secure-headers";
|
||||
|
||||
import { openDatabase, migrate } from "./db.js";
|
||||
import { rateLimit } from "./rateLimit.js";
|
||||
|
|
@ -57,6 +59,39 @@ const app = new Hono();
|
|||
|
||||
app.use("*", logger());
|
||||
|
||||
/* Headers for every response. Referrer kept to the origin (YouTube
|
||||
embeds refuse to play without one); HSTS without includeSubDomains
|
||||
so a plain-http dev subdomain keeps working. No CSP yet: pages carry
|
||||
an inline window.__NGU_SITE__ script and YouTube, Facebook and Maps
|
||||
iframes, so one needs trying in Report-Only first. */
|
||||
app.use(
|
||||
"*",
|
||||
secureHeaders({
|
||||
referrerPolicy: "strict-origin-when-cross-origin",
|
||||
strictTransportSecurity: "max-age=31536000",
|
||||
}),
|
||||
);
|
||||
|
||||
/* Refuse a form-style write (text/plain, form or multipart body)
|
||||
that another site sent, including a sibling subdomain, which
|
||||
SameSite=Lax cookies don't stop. Browsers mark their own requests
|
||||
Sec-Fetch-Site: same-origin; older ones fall back to Origin, judged
|
||||
by host because nginx speaks plain http to this service. JSON
|
||||
bodies can't be sent cross-origin without a CORS preflight, which
|
||||
this API never answers. */
|
||||
app.use(
|
||||
"/api/*",
|
||||
csrf({
|
||||
origin: (origin, c) => {
|
||||
try {
|
||||
return new URL(origin).host === c.req.header("host");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
app.use("*", async (c, next) => {
|
||||
c.set("db", db);
|
||||
await next();
|
||||
|
|
|
|||
|
|
@ -40,35 +40,24 @@ const USER_AGENT = "NGU-LinkPreview/1.0 (+https://nextgenerationofunity.org)";
|
|||
|
||||
/* ── Address checks ────────────────────────────────────────── */
|
||||
|
||||
function ipv4Blocked(ip) {
|
||||
const [a, b] = ip.split(".").map(Number);
|
||||
return (
|
||||
a === 0 ||
|
||||
a === 10 ||
|
||||
a === 127 ||
|
||||
(a === 100 && b >= 64 && b <= 127) ||
|
||||
(a === 169 && b === 254) ||
|
||||
(a === 172 && b >= 16 && b <= 31) ||
|
||||
(a === 192 && b === 168) ||
|
||||
(a === 192 && b === 0) ||
|
||||
(a === 198 && (b === 18 || b === 19)) ||
|
||||
a >= 224
|
||||
);
|
||||
}
|
||||
/* Private, loopback, link-local, shared, benchmark, multicast and
|
||||
reserved ranges. BlockList also judges an IPv4-mapped IPv6 address
|
||||
(::ffff:7f00:1, however it's written) by the IPv4 inside it. The
|
||||
IPv6 ranges that embed an IPv4 some other way (NAT64, 6to4, the
|
||||
old compatible form) are refused outright. */
|
||||
const BLOCKED = new net.BlockList();
|
||||
for (const [ip, bits] of [
|
||||
["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8],
|
||||
["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.168.0.0", 16],
|
||||
["198.18.0.0", 15], ["224.0.0.0", 3],
|
||||
]) BLOCKED.addSubnet(ip, bits, "ipv4");
|
||||
for (const [ip, bits] of [
|
||||
["::", 96], ["::1", 128], ["64:ff9b::", 96], ["64:ff9b:1::", 48], ["2002::", 16],
|
||||
["fc00::", 7], ["fe80::", 10], ["ff00::", 8],
|
||||
]) BLOCKED.addSubnet(ip, bits, "ipv6");
|
||||
|
||||
function ipBlocked(ip) {
|
||||
if (net.isIPv4(ip)) return ipv4Blocked(ip);
|
||||
const lower = ip.toLowerCase();
|
||||
// An IPv4 address written as IPv6 is judged as the IPv4 it is.
|
||||
const mapped = lower.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
|
||||
if (mapped) return ipv4Blocked(mapped[1]);
|
||||
return (
|
||||
lower === "::" ||
|
||||
lower === "::1" ||
|
||||
/^f[cd]/.test(lower) || // fc00::/7 unique local
|
||||
/^fe[89ab]/.test(lower) || // fe80::/10 link-local
|
||||
/^ff/.test(lower) // multicast
|
||||
);
|
||||
return BLOCKED.check(ip, net.isIPv4(ip) ? "ipv4" : "ipv6");
|
||||
}
|
||||
|
||||
async function vet(raw) {
|
||||
|
|
|
|||
39
server/src/migrations/037_leadership_published_orgs.sql
Normal file
39
server/src/migrations/037_leadership_published_orgs.sql
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 037 LEADERSHIP VIEW: PUBLISHED HOME ORGS ONLY
|
||||
--
|
||||
-- v_org_leadership named a person's primary organization even when
|
||||
-- that organization was unpublished, so a draft org's name could
|
||||
-- show on a public leadership list. It now joins published ones
|
||||
-- only; an unpublished one reads as no primary org.
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
DROP VIEW v_org_leadership;
|
||||
|
||||
CREATE VIEW v_org_leadership AS
|
||||
SELECT
|
||||
a.org_id,
|
||||
a.team_id,
|
||||
t.name AS team_name,
|
||||
t.sort_order AS team_sort_order,
|
||||
a.person_id,
|
||||
a.title,
|
||||
a.role,
|
||||
a.is_owner,
|
||||
a.sort_order,
|
||||
p.display_name,
|
||||
p.sort_name,
|
||||
p.pronouns,
|
||||
p.tagline,
|
||||
p.photo,
|
||||
p.public_email,
|
||||
p.location_label,
|
||||
p.bio,
|
||||
o.id AS primary_org_id,
|
||||
o.name AS primary_org_name
|
||||
FROM affiliations a
|
||||
JOIN people p ON p.id = a.person_id AND p.is_published = 1
|
||||
LEFT JOIN teams t ON t.id = a.team_id
|
||||
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
|
||||
WHERE a.is_public = 1
|
||||
AND a.ended_on IS NULL
|
||||
ORDER BY a.org_id, a.is_owner DESC, a.sort_order, p.sort_name;
|
||||
|
|
@ -450,7 +450,8 @@ export function renderPage(html, meta) {
|
|||
tags.splice(2, 0, `<meta name="robots" content="noindex, nofollow">`);
|
||||
}
|
||||
|
||||
return out.replace(/<\/head>/i, ` ${tags.join("\n ")}\n </head>`);
|
||||
// A function, so a $& or $` in record text isn't read as a pattern.
|
||||
return out.replace(/<\/head>/i, () => ` ${tags.join("\n ")}\n </head>`);
|
||||
}
|
||||
|
||||
/* ── Sitemap ───────────────────────────────────────────────── */
|
||||
|
|
|
|||
|
|
@ -5,11 +5,13 @@
|
|||
the service restarts and it doesn't survive a second instance,
|
||||
both of which are fine for one systemd unit on one box.
|
||||
|
||||
The client IP comes from X-Forwarded-For, which nginx sets. That
|
||||
header is only trustworthy because nothing but nginx can reach
|
||||
this port — it binds to 127.0.0.1. Don't expose the port.
|
||||
The client IP comes from clientIp() in auth.js (the entry nginx
|
||||
adds to X-Forwarded-For). That is only trustworthy because
|
||||
nothing but nginx can reach this port — it binds to 127.0.0.1. Don't expose the port.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { clientIp } from "./auth.js";
|
||||
|
||||
export function rateLimit({ windowMs = 60_000, max = 10 } = {}) {
|
||||
const hits = new Map(); // ip → { count, resetAt }
|
||||
|
||||
|
|
@ -22,8 +24,7 @@ export function rateLimit({ windowMs = 60_000, max = 10 } = {}) {
|
|||
}, windowMs).unref();
|
||||
|
||||
return async (c, next) => {
|
||||
const ip =
|
||||
c.req.header("x-forwarded-for")?.split(",")[0].trim() ?? "unknown";
|
||||
const ip = clientIp(c) ?? "unknown";
|
||||
|
||||
const now = Date.now();
|
||||
let entry = hits.get(ip);
|
||||
|
|
|
|||
|
|
@ -52,6 +52,16 @@ function entityForWrite(c) {
|
|||
return entity;
|
||||
}
|
||||
|
||||
/* An extension can ask for more than a sign-in to be read
|
||||
(readRole): a person's private details need editor. Blanked on
|
||||
every row sent back, so a write's reply can't leak it either. */
|
||||
function visible(c, entity, row) {
|
||||
for (const ext of entity.extensions ?? []) {
|
||||
if (ext.readRole && !hasRole(c.get("user"), ext.readRole)) row[ext.key] = null;
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
/* Everything the select inputs need, in one request. Small enough
|
||||
that paging it would cost more than it saves. */
|
||||
entities.get("/options", (c) => {
|
||||
|
|
@ -71,12 +81,12 @@ entities.get("/:entity", (c) => {
|
|||
|
||||
entities.get("/:entity/:id", (c) => {
|
||||
const entity = entityOr404(c);
|
||||
return c.json({ row: readRow(c.get("db"), entity, c.req.param("id")) }, 200, NO_STORE);
|
||||
return c.json({ row: visible(c, entity, readRow(c.get("db"), entity, c.req.param("id"))) }, 200, NO_STORE);
|
||||
});
|
||||
|
||||
entities.post("/:entity", requireRole("editor"), async (c) => {
|
||||
const entity = entityForWrite(c);
|
||||
const row = createRow(c.get("db"), entity, await json(c));
|
||||
const row = visible(c, entity, createRow(c.get("db"), entity, await json(c)));
|
||||
console.log(`${entity.key} ${row[entity.idColumn]} created by ${c.get("user").email}`);
|
||||
return c.json({ row }, 201, NO_STORE);
|
||||
});
|
||||
|
|
@ -84,7 +94,7 @@ entities.post("/:entity", requireRole("editor"), async (c) => {
|
|||
entities.patch("/:entity/:id", requireRole("editor"), async (c) => {
|
||||
const entity = entityForWrite(c);
|
||||
const id = c.req.param("id");
|
||||
const row = updateRow(c.get("db"), entity, id, await json(c));
|
||||
const row = visible(c, entity, updateRow(c.get("db"), entity, id, await json(c)));
|
||||
console.log(`${entity.key} ${id} updated by ${c.get("user").email}`);
|
||||
return c.json({ row }, 200, NO_STORE);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -39,6 +39,15 @@ export function Anchor({
|
|||
className?: string
|
||||
style?: CSSProperties
|
||||
}) {
|
||||
// A stored link with some other scheme (javascript:, data:) draws
|
||||
// as plain text rather than a link.
|
||||
if (isExternalUrl(href) && !SAFE_URL.test(href)) {
|
||||
return (
|
||||
<span className={className} style={style}>
|
||||
{children}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
if (isExternalUrl(href)) {
|
||||
const app = /^(mailto|tel):/i.test(href)
|
||||
return (
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue