Files
runners-calendar/backend/test/app.test.ts
admin 1ce43495dd
CI / build-and-test (pull_request) Has been cancelled
fix(auth): address PR 51 review findings
2026-09-25 20:15:24 +03:00

960 lines
34 KiB
TypeScript

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { after, test } from "node:test";
import request from "supertest";
import { buildHelmetOptions, createApp } from "../src/app";
import { backfillRaceCovers } from "../src/backfillRaceCovers";
import {
cleanupExpiredAuthRows,
createResetToken,
createVerificationToken,
requestPasswordReset,
resendVerification,
resetPassword,
verifyEmailToken,
} from "../src/authService";
import { requireSmtpInProduction, resolveTurnstileBypassToken } from "../src/config";
import { pool } from "../src/db";
import { extractRaceCoverImage, extractRaceCoverImageFromHtml } from "../src/raceCoverImage";
import { hashPassword, normalizeEmail } from "../src/security";
const app = createApp();
let userCounter = 0;
after(() => pool.end());
async function authAgent() {
userCounter += 1;
const email = normalizeEmail(`runner${userCounter}@example.com`);
const password = "correct horse battery staple";
const passwordHash = await hashPassword(password);
const inserted = await pool.query<{ id: string }>(
`INSERT INTO users (email, password_hash)
VALUES ($1, $2)
RETURNING id`,
[email, passwordHash],
);
await pool.query("UPDATE users SET email_verified_at = COALESCE(email_verified_at, NOW()) WHERE id = $1", [
inserted.rows[0].id,
]);
const agent = request.agent(app);
const login = await agent.post("/api/auth/login").send({ email, password }).expect(200);
return { agent, csrfToken: login.body.csrfToken as string };
}
async function createVerifiedUser(email: string, password: string) {
return createUser(email, password, true);
}
async function createUnverifiedUser(email: string, password: string) {
return createUser(email, password, false);
}
async function createUser(email: string, password: string, verified: boolean) {
const passwordHash = await hashPassword(password);
const inserted = await pool.query<{ id: string }>(
`INSERT INTO users (email, password_hash)
VALUES ($1, $2)
RETURNING id`,
[normalizeEmail(email), passwordHash],
);
if (verified) {
await pool.query("UPDATE users SET email_verified_at = COALESCE(email_verified_at, NOW()) WHERE id = $1", [
inserted.rows[0].id,
]);
}
return inserted.rows[0].id;
}
async function loginAgent(email: string, password: string) {
const agent = request.agent(app);
const login = await agent.post("/api/auth/login").send({ email, password }).expect(200);
return { agent, csrfToken: login.body.csrfToken as string };
}
async function countByTokenHash(table: "sessions" | "email_verification_tokens" | "password_reset_tokens", tokenHash: string) {
const { rows } = await pool.query<{ count: string }>(
`SELECT COUNT(*)::text AS count FROM ${table} WHERE token_hash = $1`,
[tokenHash],
);
return Number(rows[0]?.count ?? "0");
}
test("GET /api/health returns ok", async () => {
const res = await request(app).get("/api/health").expect(200);
assert.equal(res.body.status, "ok");
assert.equal(typeof res.body.version, "string");
assert.ok(res.body.version.length > 0);
});
test("GET /api/meta returns version for UI footer", async () => {
const res = await request(app).get("/api/meta").expect(200);
assert.equal(typeof res.body.version, "string");
assert.ok(res.body.version.length > 0);
});
test("GET /api/ready succeeds with PostgreSQL", async () => {
const res = await request(app).get("/api/ready").expect(200);
assert.equal(res.body.status, "ready");
assert.equal(res.body.db, "connected");
});
test("production config rejects Turnstile bypass token", () => {
assert.throws(
() =>
resolveTurnstileBypassToken({
rawBypassToken: "unsafe-bypass",
securityProfile: "production",
}),
/TURNSTILE_BYPASS_TOKEN/,
);
assert.equal(
resolveTurnstileBypassToken({
rawBypassToken: "dev-bypass",
securityProfile: "development",
}),
"dev-bypass",
);
});
test("production config requires SMTP for account email delivery", () => {
assert.throws(() => requireSmtpInProduction({ securityProfile: "production", smtpHost: null }), /SMTP_HOST/);
assert.doesNotThrow(() => requireSmtpInProduction({ securityProfile: "development", smtpHost: null }));
});
test("production CSP allows Turnstile without unsafe script directives", () => {
const options = buildHelmetOptions("production") as any;
const directives = options.contentSecurityPolicy.directives;
assert.ok(directives.scriptSrc.includes("https://challenges.cloudflare.com"));
assert.ok(directives.frameSrc.includes("https://challenges.cloudflare.com"));
assert.ok(directives.connectSrc.includes("https://challenges.cloudflare.com"));
assert.ok(!directives.scriptSrc.includes("'unsafe-inline'"));
assert.ok(!directives.scriptSrc.includes("'unsafe-eval'"));
assert.deepEqual(directives.frameAncestors, ["'none'"]);
assert.deepEqual(directives.objectSrc, ["'none'"]);
});
test("duplicate registration keeps generic accepted response", async () => {
const payload = {
email: "duplicate-register@example.com",
password: "correct horse battery staple",
turnstileToken: "mock-turnstile-token",
};
const first = await request(app).post("/api/auth/register").send(payload).expect(202);
const second = await request(app).post("/api/auth/register").send(payload).expect(202);
assert.deepEqual(first.body, { ok: true });
assert.deepEqual(second.body, { ok: true });
});
test("GET /api/races rejects invalid year", async () => {
const { agent } = await authAgent();
const res = await agent.get("/api/races?year=bad").expect(400);
assert.equal(res.body.error, "validation_error");
assert.ok(Array.isArray(res.body.details));
});
test("GET /api/races rejects month out of range", async () => {
const { agent } = await authAgent();
const res = await agent.get("/api/races?month=13").expect(400);
assert.equal(res.body.error, "validation_error");
});
test("GET /api/races accepts year and month", async () => {
const { agent } = await authAgent();
const res = await agent.get("/api/races?year=2026&month=5").expect(200);
assert.ok(Array.isArray(res.body));
});
test("GET /api/races filters by status, date and distance", async () => {
const { agent, csrfToken } = await authAgent();
await agent.post("/api/races").set("X-CSRF-Token", csrfToken).send({
slug: "2026-05-01-filter-planned", date: "2026-05-01", title: "Planned 5", distanceKm: 5, status: "planned",
}).expect(201);
await agent.post("/api/races").set("X-CSRF-Token", csrfToken).send({
slug: "2026-06-01-filter-completed", date: "2026-06-01", title: "Completed 10", distanceKm: 10, status: "completed",
}).expect(201);
await agent.post("/api/races").set("X-CSRF-Token", csrfToken).send({
slug: "2026-07-01-filter-completed", date: "2026-07-01", title: "Completed 21", distanceKm: 21.1, status: "completed",
}).expect(201);
const res = await agent.get("/api/races?status=completed&dateFrom=2026-06-01&dateTo=2026-06-30&distanceMax=10").expect(200);
assert.deepEqual(res.body.map((race: { title: string }) => race.title), ["Completed 10"]);
});
test("GET /api/races rejects inverted filter ranges", async () => {
const { agent } = await authAgent();
const res = await agent.get("/api/races?dateFrom=2026-07-01&dateTo=2026-06-01").expect(400);
assert.equal(res.body.error, "validation_error");
assert.ok(res.body.details.some((detail: string) => detail.includes("dateFrom")));
});
test("GET /api/races/:id rejects a non-UUID id", async () => {
const { agent } = await authAgent();
const res = await agent.get("/api/races/does-not-exist").expect(400);
assert.equal(res.body.error, "validation_error");
assert.ok(Array.isArray(res.body.details));
});
test("GET /api/races requires authentication", async () => {
const res = await request(app).get("/api/races").expect(401);
assert.equal(res.body.error, "unauthorized");
});
test("public profile uses its username and separate visibility settings", async () => {
const { agent } = await authAgent();
const user = await agent.get("/api/auth/me").expect(200);
await agent
.post("/api/races")
.set("X-CSRF-Token", user.body.csrfToken as string)
.send({
slug: "2026-08-01-planned-race",
date: "2026-08-01",
title: "Planned Race",
distanceKm: 10,
})
.expect(201);
await agent
.post("/api/races")
.set("X-CSRF-Token", user.body.csrfToken as string)
.send({
slug: "2026-07-01-completed-race",
date: "2026-07-01",
title: "Completed Race",
distanceKm: 10,
status: "completed",
finishTime: "00:40:00",
finishPlace: "12",
notes: "Private note",
})
.expect(201);
await request(app).get("/api/users/public-runner/races").expect(404);
await agent
.patch("/api/auth/profile")
.set("X-CSRF-Token", user.body.csrfToken as string)
.send({ profileUsername: "public-runner", isFutureRacesPublic: true, isCompletedRacesPublic: false })
.expect(200);
const futureRaces = await request(app).get("/api/users/public-runner/races").expect(200);
assert.deepEqual(futureRaces.body, [{
date: "2026-08-01",
title: "Planned Race",
distanceKm: 10,
status: null,
coverImageUrl: null,
finishTime: null,
finishPlace: null,
}]);
await agent
.patch("/api/auth/profile")
.set("X-CSRF-Token", user.body.csrfToken as string)
.send({ isFutureRacesPublic: false, isCompletedRacesPublic: true })
.expect(200);
const completedRaces = await request(app).get("/api/users/public-runner/races").expect(200);
assert.deepEqual(completedRaces.body, [{
date: "2026-07-01",
title: "Completed Race",
distanceKm: 10,
status: "completed",
coverImageUrl: null,
finishTime: "00:40:00",
finishPlace: "12",
}]);
});
test("login uses generic response for missing user and wrong password", async () => {
const password = "correct horse battery staple";
await createVerifiedUser("generic@example.com", password);
const wrongPassword = await request(app)
.post("/api/auth/login")
.send({ email: "generic@example.com", password: "wrong password" })
.expect(401);
const missingUser = await request(app)
.post("/api/auth/login")
.send({ email: "missing@example.com", password })
.expect(401);
assert.deepEqual(missingUser.body, wrongPassword.body);
});
test("admin user management is restricted and covers list, reset, edit and cascade delete", async () => {
const password = "correct horse battery staple";
const adminId = await createVerifiedUser("av_sports@mail.ru", password);
const targetId = await createVerifiedUser("admin-target@example.com", password);
const duplicateId = await createVerifiedUser("admin-duplicate@example.com", password);
const unverifiedId = await createUnverifiedUser("admin-unverified@example.com", password);
const admin = await loginAgent("av_sports@mail.ru", password);
const target = await loginAgent("admin-target@example.com", password);
const adminMe = await admin.agent.get("/api/auth/me").expect(200);
assert.equal(adminMe.body.user.isAdmin, true);
const adminCsrfToken = adminMe.body.csrfToken as string;
const targetMe = await target.agent.get("/api/auth/me").expect(200);
assert.equal(targetMe.body.user.isAdmin, false);
const targetCsrfToken = targetMe.body.csrfToken as string;
await request(app).get("/api/admin/users").expect(401);
await target.agent.get("/api/admin/users").expect(403);
await target.agent
.patch(`/api/admin/users/${duplicateId}`)
.set("X-CSRF-Token", targetCsrfToken)
.send({ profileUsername: "forbidden-edit" })
.expect(403);
await target.agent
.post(`/api/admin/users/${duplicateId}/password-reset`)
.set("X-CSRF-Token", targetCsrfToken)
.expect(403);
await target.agent
.delete(`/api/admin/users/${duplicateId}`)
.set("X-CSRF-Token", targetCsrfToken)
.expect(403);
await target.agent.post("/api/races").set("X-CSRF-Token", targetCsrfToken).send({
slug: "admin-count-planned",
date: "2026-09-01",
title: "Admin count planned",
distanceKm: 5,
status: "planned",
}).expect(201);
await target.agent.post("/api/races").set("X-CSRF-Token", targetCsrfToken).send({
slug: "admin-count-completed",
date: "2026-09-02",
title: "Admin count completed",
distanceKm: 10,
status: "completed",
}).expect(201);
const listed = await admin.agent.get("/api/admin/users").expect(200);
assert.ok(Array.isArray(listed.body));
const listedTarget = listed.body.find((user: { id: string }) => user.id === targetId);
assert.ok(listedTarget);
assert.deepEqual(Object.keys(listedTarget).sort(), [
"completedRacesCount",
"createdAt",
"email",
"emailVerifiedAt",
"id",
"isCompletedRacesPublic",
"isFutureRacesPublic",
"lastLoginAt",
"profileUsername",
"racesCount",
]);
assert.equal(listedTarget.email, "admin-target@example.com");
assert.equal(typeof listedTarget.createdAt, "string");
assert.equal(typeof listedTarget.lastLoginAt, "string");
assert.equal(listedTarget.racesCount, 2);
assert.equal(listedTarget.completedRacesCount, 1);
await admin.agent
.patch(`/api/admin/users/${targetId}`)
.send({ profileUsername: "missing-csrf" })
.expect(403)
.then((res) => assert.equal(res.body.error, "csrf_error"));
await admin.agent
.patch(`/api/admin/users/${targetId}`)
.set("X-CSRF-Token", adminCsrfToken)
.send({ unexpected: true })
.expect(400);
await admin.agent
.patch("/api/admin/users/00000000-0000-4000-8000-000000000000")
.set("X-CSRF-Token", adminCsrfToken)
.send({ profileUsername: "missing-user" })
.expect(404);
await admin.agent
.patch(`/api/admin/users/${unverifiedId}`)
.set("X-CSRF-Token", adminCsrfToken)
.send({ email: "admin-unverified@example.com", profileUsername: "unverified-edit" })
.expect(204);
const unchangedEmailTokens = await pool.query<{ count: string }>(
"SELECT COUNT(*)::text AS count FROM email_verification_tokens WHERE user_id = $1 AND used_at IS NULL",
[unverifiedId],
);
assert.equal(Number(unchangedEmailTokens.rows[0]?.count ?? "0"), 0);
await admin.agent
.patch(`/api/admin/users/${targetId}`)
.set("X-CSRF-Token", adminCsrfToken)
.send({
email: "admin-target-edited@example.com",
profileUsername: "admin-edited",
isFutureRacesPublic: true,
isCompletedRacesPublic: true,
})
.expect(204);
const edited = await pool.query<{
email: string;
profile_username: string;
is_future_races_public: boolean;
is_completed_races_public: boolean;
}>(
`SELECT email, profile_username, is_future_races_public, is_completed_races_public
FROM users WHERE id = $1`,
[targetId],
);
assert.deepEqual(edited.rows[0], {
email: "admin-target-edited@example.com",
profile_username: "admin-edited",
is_future_races_public: true,
is_completed_races_public: true,
});
await admin.agent
.patch(`/api/admin/users/${duplicateId}`)
.set("X-CSRF-Token", adminCsrfToken)
.send({ email: "admin-target-edited@example.com" })
.expect(409);
await admin.agent
.patch(`/api/admin/users/${adminId}`)
.set("X-CSRF-Token", adminCsrfToken)
.send({ email: "former-admin@example.com" })
.expect(409);
await admin.agent
.delete(`/api/admin/users/${adminId}`)
.set("X-CSRF-Token", adminCsrfToken)
.expect(409);
const reset = await admin.agent
.post(`/api/admin/users/${targetId}/password-reset`)
.set("X-CSRF-Token", adminCsrfToken)
.expect(202);
assert.deepEqual(reset.body, { ok: true });
assert.equal("token" in reset.body, false);
const resetTokens = await pool.query<{ count: string }>(
"SELECT COUNT(*)::text AS count FROM password_reset_tokens WHERE user_id = $1 AND used_at IS NULL",
[targetId],
);
assert.equal(Number(resetTokens.rows[0]?.count ?? "0"), 1);
await admin.agent
.delete(`/api/admin/users/${targetId}`)
.set("X-CSRF-Token", adminCsrfToken)
.expect(204);
const deleted = await pool.query<{ users: string; races: string }>(
`SELECT
(SELECT COUNT(*)::text FROM users WHERE id = $1) AS users,
(SELECT COUNT(*)::text FROM races WHERE owner_user_id = $1) AS races`,
[targetId],
);
assert.deepEqual(deleted.rows[0], { users: "0", races: "0" });
});
test("account session endpoints list and revoke only the current user's sessions", async () => {
userCounter += 1;
const email = `sessions${userCounter}@example.com`;
const password = "correct horse battery staple";
await createVerifiedUser(email, password);
const first = await loginAgent(email, password);
const second = await loginAgent(email, password);
const listed = await first.agent.get("/api/auth/sessions").expect(200);
assert.equal(listed.body.sessions.length, 2);
assert.ok(listed.body.sessions.every((session: { tokenHash?: unknown }) => session.tokenHash === undefined));
const other = listed.body.sessions.find((session: { current: boolean }) => !session.current);
assert.ok(other);
const outsider = await authAgent();
const foreign = (await outsider.agent.get("/api/auth/sessions").expect(200)).body.sessions[0];
await first.agent
.delete(`/api/auth/sessions/${foreign.id}`)
.set("X-CSRF-Token", first.csrfToken)
.expect(404);
await first.agent
.delete(`/api/auth/sessions/${other.id}`)
.set("X-CSRF-Token", first.csrfToken)
.expect(204);
await second.agent.get("/api/auth/me").expect(401);
await first.agent.get("/api/auth/sessions").expect(200).then((res) => assert.equal(res.body.sessions.length, 1));
});
test("password change checks the current password and revokes other sessions", async () => {
userCounter += 1;
const email = `password${userCounter}@example.com`;
const password = "correct horse battery staple";
const nextPassword = "another correct horse battery staple";
await createVerifiedUser(email, password);
const first = await loginAgent(email, password);
const second = await loginAgent(email, password);
await first.agent
.post("/api/auth/password")
.set("X-CSRF-Token", first.csrfToken)
.send({ currentPassword: "wrong password", newPassword: nextPassword })
.expect(400);
await first.agent
.post("/api/auth/password")
.set("X-CSRF-Token", first.csrfToken)
.send({ currentPassword: password, newPassword: nextPassword })
.expect(200);
await second.agent.get("/api/auth/me").expect(401);
await request(app).post("/api/auth/login").send({ email, password }).expect(401);
await request(app).post("/api/auth/login").send({ email, password: nextPassword }).expect(200);
});
test("revoke other sessions retains the current session", async () => {
userCounter += 1;
const email = `revoke-others${userCounter}@example.com`;
const password = "correct horse battery staple";
await createVerifiedUser(email, password);
const first = await loginAgent(email, password);
const second = await loginAgent(email, password);
await first.agent
.post("/api/auth/sessions/revoke-others")
.set("X-CSRF-Token", first.csrfToken)
.expect(200);
await first.agent.get("/api/auth/me").expect(200);
await second.agent.get("/api/auth/me").expect(401);
});
test("GET /api/races/:id returns not_found for another user's race", async () => {
const first = await authAgent();
const created = await first.agent
.post("/api/races")
.set("X-CSRF-Token", first.csrfToken)
.send({
slug: "2026-07-01-private-race",
date: "2026-07-01",
title: "Private Race",
distanceKm: 10,
})
.expect(201);
const second = await authAgent();
const res = await second.agent.get(`/api/races/${created.body.id}`).expect(404);
assert.equal(res.body.error, "not_found");
});
test("new password reset token invalidates previous token", async () => {
const userId = await createVerifiedUser("reset@example.com", "correct horse battery staple");
const client = await pool.connect();
const first = await createResetToken(client, userId);
const second = await createResetToken(client, userId);
client.release();
assert.equal(await resetPassword(first, "new correct horse battery staple"), false);
assert.equal(await resetPassword(second, "new correct horse battery staple"), true);
assert.equal(await resetPassword(second, "new correct horse battery staple"), false);
});
test("email verification token is single use", async () => {
const userId = await createUnverifiedUser("verify-once@example.com", "correct horse battery staple");
const client = await pool.connect();
const token = await createVerificationToken(client, userId);
client.release();
assert.equal(await verifyEmailToken(token), true);
assert.equal(await verifyEmailToken(token), false);
});
test("email changes serialize password reset and verification token issuance", async () => {
for (const [email, issueToken] of [
["reset-race@example.com", requestPasswordReset],
["verify-race@example.com", resendVerification],
] as const) {
const userId = await createUnverifiedUser(email, "correct horse battery staple");
const locker = await pool.connect();
await locker.query("BEGIN");
await locker.query("SELECT id FROM users WHERE id = $1 FOR UPDATE", [userId]);
const issuing = issueToken(email);
await new Promise((resolve) => setTimeout(resolve, 20));
await locker.query("UPDATE users SET email = $2, email_verified_at = NULL WHERE id = $1", [
userId,
email.replace("@", ".changed@"),
]);
await locker.query("COMMIT");
locker.release();
await issuing;
const table = issueToken === requestPasswordReset ? "password_reset_tokens" : "email_verification_tokens";
const { rows } = await pool.query<{ count: string }>(
`SELECT COUNT(*)::text AS count FROM ${table} WHERE user_id = $1 AND used_at IS NULL`,
[userId],
);
assert.equal(rows[0]?.count, "0");
}
});
test("auth cleanup removes expired rows and keeps active rows", async () => {
const userId = await createVerifiedUser("cleanup@example.com", "correct horse battery staple");
const past = new Date(Date.now() - 60_000);
const future = new Date(Date.now() + 60_000);
const expiredSession = "expired-session-token-hash";
const activeSession = "active-session-token-hash";
const expiredVerify = "expired-verify-token-hash";
const activeVerify = "active-verify-token-hash";
const expiredReset = "expired-reset-token-hash";
const activeReset = "active-reset-token-hash";
await pool.query(
"INSERT INTO sessions (user_id, token_hash, csrf_token_hash, expires_at) VALUES ($1, $2, $3, $4)",
[userId, expiredSession, "expired-csrf", past],
);
await pool.query(
"INSERT INTO sessions (user_id, token_hash, csrf_token_hash, expires_at) VALUES ($1, $2, $3, $4)",
[userId, activeSession, "active-csrf", future],
);
await pool.query(
"INSERT INTO email_verification_tokens (user_id, token_hash, expires_at) VALUES ($1, $2, $3)",
[userId, expiredVerify, past],
);
await pool.query(
"INSERT INTO email_verification_tokens (user_id, token_hash, expires_at) VALUES ($1, $2, $3)",
[userId, activeVerify, future],
);
await pool.query(
"INSERT INTO password_reset_tokens (user_id, token_hash, expires_at) VALUES ($1, $2, $3)",
[userId, expiredReset, past],
);
await pool.query(
"INSERT INTO password_reset_tokens (user_id, token_hash, expires_at) VALUES ($1, $2, $3)",
[userId, activeReset, future],
);
await cleanupExpiredAuthRows();
assert.equal(await countByTokenHash("sessions", expiredSession), 0);
assert.equal(await countByTokenHash("sessions", activeSession), 1);
assert.equal(await countByTokenHash("email_verification_tokens", expiredVerify), 0);
assert.equal(await countByTokenHash("email_verification_tokens", activeVerify), 1);
assert.equal(await countByTokenHash("password_reset_tokens", expiredReset), 0);
assert.equal(await countByTokenHash("password_reset_tokens", activeReset), 1);
});
test("extractRaceCoverImageFromHtml prefers runc.run intro image", () => {
const html = `
<meta property="og:image" content="https://example.com/og.jpg">
<div class="run-intro__image">
<div class="run-intro__image-left-shadow"></div>
<img src="/uploads/race_landing_header_backgrounds/header.jpg" alt="">
<div class="run-intro__image-right-shadow"></div>
</div>
`;
assert.equal(
extractRaceCoverImageFromHtml(html, "https://aprilrun5km.runc.run/"),
"https://aprilrun5km.runc.run/uploads/race_landing_header_backgrounds/header.jpg",
);
});
test("extractRaceCoverImageFromHtml reads Open Graph and Twitter images", () => {
assert.equal(
extractRaceCoverImageFromHtml(
'<meta property="og:image" content="/cover.png">',
"https://example.com/race",
),
"https://example.com/cover.png",
);
assert.equal(
extractRaceCoverImageFromHtml(
'<meta name="twitter:image" content="https://cdn.example.com/twitter.jpg">',
"https://example.com/race",
),
"https://cdn.example.com/twitter.jpg",
);
});
test("POST /api/races stores manual coverImageUrl", async () => {
const { agent, csrfToken } = await authAgent();
const coverImageUrl = "https://example.com/manual.jpg";
const res = await agent
.post("/api/races")
.set("X-CSRF-Token", csrfToken)
.send({
slug: "2026-06-01-manual-cover",
date: "2026-06-01",
title: "Manual Cover",
distanceKm: 10,
officialUrl: "https://example.com/race",
coverImageUrl,
})
.expect(201);
assert.equal(res.body.coverImageUrl, coverImageUrl);
});
test("PATCH /api/races refreshes an automatic cover but preserves a manual cover", async () => {
const originalFetch = globalThis.fetch;
let imageName = "first.jpg";
globalThis.fetch = async () => new Response(`<meta property="og:image" content="/${imageName}">`, {
status: 200,
headers: { "content-type": "text/html" },
});
try {
const { agent, csrfToken } = await authAgent();
const created = await agent.post("/api/races").set("X-CSRF-Token", csrfToken).send({
slug: "2026-06-06-auto-refresh", date: "2026-06-06", title: "Auto Refresh", distanceKm: 10, officialUrl: "https://example.com/first",
}).expect(201);
imageName = "second.jpg";
const refreshed = await agent.patch(`/api/races/${created.body.id}`).set("X-CSRF-Token", csrfToken).send({
officialUrl: "https://example.com/second",
}).expect(200);
assert.equal(refreshed.body.coverImageUrl, "https://example.com/second.jpg");
const manual = await agent.patch(`/api/races/${created.body.id}`).set("X-CSRF-Token", csrfToken).send({
officialUrl: "https://example.com/third", coverImageUrl: "https://example.com/manual.jpg",
}).expect(200);
imageName = "fourth.jpg";
const preserved = await agent.patch(`/api/races/${created.body.id}`).set("X-CSRF-Token", csrfToken).send({
officialUrl: "https://example.com/fourth",
}).expect(200);
assert.equal(manual.body.coverImageUrl, "https://example.com/manual.jpg");
assert.equal(preserved.body.coverImageUrl, "https://example.com/manual.jpg");
} finally {
globalThis.fetch = originalFetch;
}
});
test("POST /api/races rejects unknown and malformed fields", async () => {
const { agent, csrfToken } = await authAgent();
const res = await agent
.post("/api/races")
.set("X-CSRF-Token", csrfToken)
.send({
slug: "invalid-race",
date: "2026-02-30",
title: "Invalid Race",
distanceKm: 10,
startTime: "24:00",
unexpected: true,
})
.expect(400);
assert.equal(res.body.error, "validation_error");
assert.ok(res.body.details.some((detail: string) => detail.includes("date")));
assert.ok(res.body.details.some((detail: string) => detail.includes("startTime")));
assert.ok(res.body.details.some((detail: string) => detail.includes("Unrecognized")));
});
test("POST /api/races accepts a seconds-only finish time", async () => {
const { agent, csrfToken } = await authAgent();
const res = await agent
.post("/api/races")
.set("X-CSRF-Token", csrfToken)
.send({
slug: "2026-06-01-seconds-only",
date: "2026-06-01",
title: "Seconds Only",
distanceKm: 1,
finishTime: "05",
})
.expect(201);
assert.equal(res.body.finishTime, "05");
});
test("POST /api/races auto extracts coverImageUrl from officialUrl", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () =>
new Response('<meta property="og:image" content="/auto.jpg">', {
status: 200,
headers: { "content-type": "text/html" },
});
try {
const { agent, csrfToken } = await authAgent();
const res = await agent
.post("/api/races")
.set("X-CSRF-Token", csrfToken)
.send({
slug: "2026-06-02-auto-cover",
date: "2026-06-02",
title: "Auto Cover",
distanceKm: 21.1,
officialUrl: "https://example.com/race",
})
.expect(201);
assert.equal(res.body.coverImageUrl, "https://example.com/auto.jpg");
} finally {
globalThis.fetch = originalFetch;
}
});
test("PATCH /api/races auto extracts a missing cover when officialUrl changes", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => new Response("", { status: 404 });
try {
const { agent, csrfToken } = await authAgent();
const created = await agent
.post("/api/races")
.set("X-CSRF-Token", csrfToken)
.send({ slug: "2026-06-04-patch-cover", date: "2026-06-04", title: "Patch Cover", distanceKm: 10 })
.expect(201);
globalThis.fetch = async () => new Response('<meta property="og:image" content="/patched.jpg">', {
status: 200,
headers: { "content-type": "text/html" },
});
const updated = await agent
.patch(`/api/races/${created.body.id}`)
.set("X-CSRF-Token", csrfToken)
.send({ officialUrl: "https://example.com/patched" })
.expect(200);
assert.equal(updated.body.coverImageUrl, "https://example.com/patched.jpg");
} finally {
globalThis.fetch = originalFetch;
}
});
test("cover backfill restores only races without a cover", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => new Response('<meta property="og:image" content="/backfill.jpg">', {
status: 200,
headers: { "content-type": "text/html" },
});
try {
const { agent, csrfToken } = await authAgent();
await agent.post("/api/races").set("X-CSRF-Token", csrfToken).send({
slug: "2026-06-05-backfill", date: "2026-06-05", title: "Backfill", distanceKm: 10,
}).expect(201);
await pool.query("UPDATE races SET official_url = $1 WHERE slug = $2", ["https://example.com/backfill", "2026-06-05-backfill"]);
const stats = await backfillRaceCovers();
assert.ok(stats.candidates >= 1);
assert.ok(stats.restored >= 1);
const result = await pool.query<{ cover_image_url: string }>("SELECT cover_image_url FROM races WHERE slug = $1", ["2026-06-05-backfill"]);
assert.equal(result.rows[0]?.cover_image_url, "https://example.com/backfill.jpg");
} finally {
globalThis.fetch = originalFetch;
}
});
test("POST /api/races succeeds when cover extraction fails", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => {
throw new Error("network down");
};
try {
const { agent, csrfToken } = await authAgent();
const res = await agent
.post("/api/races")
.set("X-CSRF-Token", csrfToken)
.send({
slug: "2026-06-03-cover-fail",
date: "2026-06-03",
title: "Cover Fail",
distanceKm: 5,
officialUrl: "https://example.com/race",
})
.expect(201);
assert.equal(res.body.coverImageUrl, null);
} finally {
globalThis.fetch = originalFetch;
}
});
test("cover extraction never fetches loopback URLs", async () => {
const originalFetch = globalThis.fetch;
let calls = 0;
globalThis.fetch = async () => {
calls += 1;
return new Response("");
};
try {
assert.equal(await extractRaceCoverImage("http://127.0.0.1/private"), null);
assert.equal(calls, 0);
} finally {
globalThis.fetch = originalFetch;
}
});
test("cover extraction rejects a redirect to a private URL", async () => {
const originalFetch = globalThis.fetch;
let calls = 0;
globalThis.fetch = async () => {
calls += 1;
return new Response(null, { status: 302, headers: { location: "http://127.0.0.1/private" } });
};
try {
assert.equal(await extractRaceCoverImage("https://8.8.8.8/race"), null);
assert.equal(calls, 1);
} finally {
globalThis.fetch = originalFetch;
}
});
test("PATCH /api/races/:id updates coverImageUrl explicitly", async () => {
const { agent, csrfToken } = await authAgent();
const created = await agent
.post("/api/races")
.set("X-CSRF-Token", csrfToken)
.send({
slug: "2026-06-04-patch-cover",
date: "2026-06-04",
title: "Patch Cover",
distanceKm: 10,
})
.expect(201);
const coverImageUrl = "https://example.com/patched.jpg";
const res = await agent
.patch(`/api/races/${created.body.id}`)
.set("X-CSRF-Token", csrfToken)
.send({ coverImageUrl })
.expect(200);
assert.equal(res.body.coverImageUrl, coverImageUrl);
});
test("004 migrates legacy text race ids to UUIDs", async () => {
const client = await pool.connect();
try {
await client.query("BEGIN");
await client.query("DROP TABLE races");
await client.query(`
CREATE TABLE races (
id TEXT PRIMARY KEY,
race_date DATE NOT NULL,
title TEXT NOT NULL,
distance_km NUMERIC(6,3) NOT NULL,
status TEXT CHECK (status IS NULL OR status IN ('planned', 'registered', 'completed')),
official_url TEXT,
start_time TEXT,
cluster_schedule TEXT,
bib_pickup TEXT,
bib_number TEXT,
finish_time TEXT,
notes TEXT,
finish_place TEXT,
cover_image_url TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ
)
`);
await client.query(
"INSERT INTO races (id, race_date, title, distance_km) VALUES ($1, $2, $3, $4)",
["legacy-race", "2026-01-01", "Legacy Race", 10],
);
const migration = fs.readFileSync(path.resolve(__dirname, "../migrations/004_auth_and_race_ownership.sql"), "utf8");
await client.query(migration);
const { rows } = await client.query<{ id: string; slug: string; source: string }>(
"SELECT id, slug, source FROM races WHERE slug = $1",
["legacy-race"],
);
assert.equal(rows[0]?.slug, "legacy-race");
assert.equal(rows[0]?.source, "user");
assert.match(rows[0]?.id ?? "", /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);
} finally {
await client.query("ROLLBACK");
client.release();
}
});