Files
gerbeur/api/test/helpers.ts
khannurien 364c498a24
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 51s
v3: dependencies upgraded and deno audit clean, every API response typed end to end, no explicit any left — and the site search stops handing out password hashes — deno audit reported 19 advisories (11 high); none remain. nodemailer 9 → 10.0.10 closes four of them (a quadratic address parser, two recipient-domain allow-list bypasses, resolveContent ignoring disableFileAccess/disableUrlAccess); 10's one break is Node ≥ 20, and 10.0.11 is a day too young for the minimum release age. react-router 8.0.1 → 8.4.0 closes the RSC-mode CSRF bypass. Refreshing the lockfile clears the transitive ones that came in through Vite, ESLint and Lingui: postcss, nanoid, picomatch, browserslist, brace-expansion and baseline-browser-mapping. Everything else moves to its latest too — Lingui 6.8 (its SWC plugin 6.7), React 19.3, Vite 8.3.1, react-hook-form 7.89, marked, jose, ESLint 10.11, typescript-eslint 8.70, the @types — and frimousse 0.3 → 0.4, whose declarations only add (custom emoji data resolvers, a cache). TypeScript stays on 6.0: typescript-eslint supports < 6.1, so 7.0 would stop the lint. allowScripts names @swc/core 1.16.2 and drops esbuild, which Vite 8 no longer installs.
Search: GET /api/search sent each matching user's full row — password hash and email included — to anyone, signed in or not, because searchUsersGlobal returned User[] and the route passed it through. It returns profiles only now, stripped where the rows are read, and the search test fails on the old code. Types alone wouldn't have caught it (a User is structurally a PublicUser), so the strip is explicit and tested.

Typed routes. Every JSON response is declared as APIResponse<T>, the way the typed routes already did, with the missing shapes named in api/model/interfaces.ts: PublicUser (no hash, no email) and SelfUser (your own profile, with email) plus toPublicUser/toSelfUser in place of ten hand-written destructurings, AuthTokens, AuthResponse, MediaTokenResponse, InviteResponse, AttachmentResponse, SearchResults, LinkPreview, UserSuggestion and Invitee. Request bodies are `unknown` and narrowed by the existing guards, or by a new fieldOf(obj, key) where a route reads one field — no more reading off Oak's `any` or casting to Record<string, unknown>. The password-reset routes answer `{ success: true, data: null }` rather than a bare `{ success: true }`, so every success fits the envelope; the frontend only reads `success`.

Socket protocol: routes/ws.ts had its own send() taking Record<string, unknown>, so nothing checked what it sent. It takes ServerToClientMessage now, which turned up two mismatches: `pong` was missing from the union although the server answers every client ping with one, and vote_ack carried a `success: true` no type declares and no client reads. The union has PongMessage and vote_ack lost the field.

No explicit any. The YouTube playlist parse reads ytInitialData as `unknown` through a small at(node, …path) that checks each step, instead of `type Json = any`. The backend test helpers type the response body as the server's envelope: request<T>() and get/post/put/patch/del<T>() name what `data` holds, res.data throws with the server's message when the call didn't succeed and res.error when it didn't fail, and each test says which API type it expects, so a test reading a field the route doesn't send no longer compiles. Assertions that a field is absent are `assertFalse("passwordHash" in …)` rather than reading a field the type says isn't there. The socket tests' messages are ServerToClientMessage, with next()/all() keyed by type so each returns that message's shape.

No double casts in src/ either. window.YT and onYouTubeIframeAPIReady are declared on Window; the test's fake player is a class forwarding to the spies the tests inspect. WSContext, FollowContext and PlayerContext export their defaults (defaultWSValue, defaultFollowValue, defaultPlayerValue), which the tests import instead of reading React's private _currentValue. handleMentionKeyDown takes a MentionKey — the key fields it reads — so the test builds a plain object; useUserDumpFeed declares sentinelRef as the callback ref it is. In src/test/setup.ts the IntersectionObserver fake implements IntersectionObserver, and report(isIntersecting, top?) builds complete entries in place of partial ones cast in five files; the Animation fake implements Animation; the canvas getContext stub goes in through defineProperty. The XHR fake's last request is optional behind a getter that fails if none was made, the keyframes are checked with matchers, and the roleless legacy session is built by leaving the role out. One test changes meaning slightly: "leaving the view…" relied on entries with no position at all, and now leaves and re-enters at the same height, which is what it describes. The one cast left is in api/test/ws.test.ts: deno.json's "dom" lib hides Deno's WebSocket overload that takes handshake headers, and dropping that lib would break the editor's view of src/; it's commented and names the real signature.

Also: the notifications test answered a Response-typed promise with a plain object, which failed `tsc -b`; it uses the fetch stub's deferred() now. ESLint didn't read the `deno-lint-ignore no-explicit-any` comments, so `eslint .` failed on three files; those anys are gone. `deno fmt` over api/ and src/ (not the compiled src/locales/*.js); the reflow left all 332 message ids intact, and the .po files only have their source line references updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 16:05:29 +00:00

393 lines
12 KiB
TypeScript
Raw 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.
// Must stay first: see setup.ts.
import { TEST_DIR } from "./setup.ts";
import { stub } from "@std/testing/mock";
import { app } from "../main.ts";
import { db } from "../model/db.ts";
import { createJWT, createMediaToken, hashPassword } from "../lib/jwt.ts";
import { makeSlug } from "../lib/slugify.ts";
import { canonicalizeUrl } from "../lib/canonical-url.ts";
import type { APIError, APIResponse, Role } from "../model/interfaces.ts";
export { app, db, TEST_DIR };
// ── Database ─────────────────────────────────────────────────────────────────
const TABLES = [
"dump_backlinks",
"dump_categories",
"playlist_dumps",
"comment_likes",
"comments",
"votes",
"follows",
"notifications",
"password_reset_tokens",
"invites",
"attachments",
"chat_messages",
"categories",
"playlists",
"dumps",
"users",
];
/** Empties every table, the default admin included. */
export function resetDb(): void {
db.exec("PRAGMA foreign_keys = OFF;");
for (const table of TABLES) db.exec(`DELETE FROM ${table};`);
db.exec("PRAGMA foreign_keys = ON;");
}
/**
* Wraps a test body so it starts from an empty database. Usernames and emails
* still have to be unique across the whole run where the rate limiter keys on
* them (login, password reset), since its buckets live for the process.
*/
export function test(
name: string,
fn: (t: Deno.TestContext) => void | Promise<void>,
options: Omit<Deno.TestDefinition, "name" | "fn"> = {},
): void {
Deno.test({
name,
...options,
async fn(t) {
resetDb();
await fn(t);
},
});
}
// ── Users ────────────────────────────────────────────────────────────────────
export const PASSWORD = "correct-horse";
// scrypt is deliberately slow; hash the shared password once.
let passwordHash: Promise<string> | undefined;
let seq = 0;
/** A name no other test in this process has used. */
export function uniqueName(prefix = "user"): string {
return `${prefix}_${++seq}_${crypto.randomUUID().slice(0, 6)}`;
}
export interface TestUser {
id: string;
username: string;
email: string;
role: Role;
token: string;
mediaToken: string;
/** Authorization header for this user. */
auth: { Authorization: string };
}
export async function createUser(
opts: {
username?: string;
role?: Role;
email?: string;
invitedBy?: string;
createdAt?: string;
} = {},
): Promise<TestUser> {
const id = crypto.randomUUID();
const username = opts.username ?? uniqueName();
const email = opts.email ?? `${username}@example.test`;
const role = opts.role ?? "user";
passwordHash ??= hashPassword(PASSWORD);
db.prepare(
`INSERT INTO users (id, username, password_hash, role, created_at, email, invited_by)
VALUES (?, ?, ?, ?, ?, ?, ?);`,
).run(
id,
username,
await passwordHash,
role,
opts.createdAt ?? new Date().toISOString(),
email,
opts.invitedBy ?? null,
);
const token = await createJWT({ userId: id, username, role });
return {
id,
username,
email,
role,
token,
mediaToken: await createMediaToken(id),
auth: { Authorization: `Bearer ${token}` },
};
}
// ── Content ──────────────────────────────────────────────────────────────────
export interface InsertDumpOptions {
userId: string;
title?: string;
kind?: "url" | "file";
url?: string;
comment?: string;
isPrivate?: boolean;
createdAt?: string;
fileName?: string;
fileMime?: string;
/** Bytes written to the uploads directory for a file dump. */
fileData?: Uint8Array;
richContent?: Record<string, unknown>;
}
/**
* Inserts a dump row directly, skipping the metadata fetch the create route
* does. Returns its id and slug.
*/
export function insertDump(
opts: InsertDumpOptions,
): { id: string; slug: string } {
const id = crypto.randomUUID();
const title = opts.title ?? "A dump";
const slug = makeSlug(title, id);
const kind = opts.kind ?? (opts.fileName ? "file" : "url");
const url = kind === "url" ? (opts.url ?? `https://example.com/${id}`) : null;
const data = opts.fileData ?? new TextEncoder().encode("hello");
db.prepare(
`INSERT INTO dumps (id, kind, title, slug, comment, user_id, created_at, url, url_canonical,
rich_content, file_name, file_mime, file_size, is_private)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`,
).run(
id,
kind,
title,
slug,
opts.comment ?? null,
opts.userId,
opts.createdAt ?? new Date().toISOString(),
url,
url ? canonicalizeUrl(url) : null,
opts.richContent ? JSON.stringify(opts.richContent) : null,
kind === "file" ? (opts.fileName ?? "file.txt") : null,
kind === "file" ? (opts.fileMime ?? "text/plain") : null,
kind === "file" ? data.byteLength : null,
opts.isPrivate ? 1 : 0,
);
if (kind === "file") {
Deno.mkdirSync(`${TEST_DIR}/uploads/dumps`, { recursive: true });
Deno.writeFileSync(`${TEST_DIR}/uploads/dumps/${id}`, data);
}
return { id, slug };
}
export function insertPlaylist(
opts: { userId: string; title?: string; isPublic?: boolean },
): { id: string; slug: string } {
const id = crypto.randomUUID();
const title = opts.title ?? "A playlist";
const slug = makeSlug(title, id);
db.prepare(
`INSERT INTO playlists (id, user_id, title, slug, is_public, created_at)
VALUES (?, ?, ?, ?, ?, ?);`,
).run(
id,
opts.userId,
title,
slug,
opts.isPublic === false ? 0 : 1,
new Date().toISOString(),
);
return { id, slug };
}
export function insertComment(
opts: {
dumpId: string;
userId: string;
body?: string;
parentId?: string;
createdAt?: string;
},
): string {
const id = crypto.randomUUID();
db.prepare(
`INSERT INTO comments (id, dump_id, user_id, parent_id, body, created_at)
VALUES (?, ?, ?, ?, ?, ?);`,
).run(
id,
opts.dumpId,
opts.userId,
opts.parentId ?? null,
opts.body ?? "A comment",
opts.createdAt ?? new Date().toISOString(),
);
return id;
}
export function insertCategory(
opts: { slug: string; name?: string; position?: number },
): string {
const id = crypto.randomUUID();
db.prepare(
`INSERT INTO categories (id, slug, name, position, created_at) VALUES (?, ?, ?, ?, ?);`,
).run(
id,
opts.slug,
opts.name ?? opts.slug,
opts.position ?? 0,
new Date().toISOString(),
);
return id;
}
export function count(sql: string, ...params: (string | number)[]): number {
return (db.prepare(sql).get(...params) as { n: number }).n;
}
// ── HTTP ─────────────────────────────────────────────────────────────────────
export const BASE_URL = "http://gerbeur.test";
export interface ApiResponse<T = unknown> {
status: number;
headers: Headers;
/** The parsed body when it's JSON, null otherwise. */
body: APIResponse<T> | null;
bytes: Uint8Array;
/** The body's `data`; throws if the request didn't succeed. */
readonly data: T;
/** The body's `error`; throws if the request didn't fail. */
readonly error: APIError;
}
type RequestOptions = {
auth?: { Authorization: string };
json?: unknown;
form?: FormData;
headers?: Record<string, string>;
};
/**
* Sends a request through the full middleware stack in-process — no socket.
* `json` sends a JSON body, `form` a multipart one. `T` is what the endpoint
* answers with in `data`.
*/
export async function request<T = unknown>(
method: string,
path: string,
opts: RequestOptions = {},
): Promise<ApiResponse<T>> {
const headers = new Headers({ ...opts.auth, ...opts.headers });
let body: BodyInit | undefined;
if (opts.json !== undefined) {
headers.set("Content-Type", "application/json");
body = JSON.stringify(opts.json);
} else if (opts.form) {
body = opts.form;
}
const res = await app.handle(
new Request(`${BASE_URL}${path}`, { method, headers, body }),
);
if (!res) throw new Error(`No response for ${method} ${path}`);
const bytes = new Uint8Array(await res.arrayBuffer());
const text = new TextDecoder().decode(bytes);
let parsed: APIResponse<T> | null = null;
if ((res.headers.get("content-type") ?? "").includes("json") && text) {
parsed = JSON.parse(text);
}
const what = `${method} ${path} (${res.status})`;
return {
status: res.status,
headers: res.headers,
body: parsed,
bytes,
get data() {
if (!parsed?.success) {
throw new Error(`${what} failed: ${parsed?.error.message ?? text}`);
}
return parsed.data;
},
get error() {
if (parsed?.success !== false) {
throw new Error(`${what} didn't fail`);
}
return parsed.error;
},
};
}
export const get = <T = unknown>(path: string, opts?: RequestOptions) =>
request<T>("GET", path, opts);
export const post = <T = unknown>(path: string, opts?: RequestOptions) =>
request<T>("POST", path, opts);
export const put = <T = unknown>(path: string, opts?: RequestOptions) =>
request<T>("PUT", path, opts);
export const patch = <T = unknown>(path: string, opts?: RequestOptions) =>
request<T>("PATCH", path, opts);
export const del = <T = unknown>(path: string, opts?: RequestOptions) =>
request<T>("DELETE", path, opts);
// ── Files ────────────────────────────────────────────────────────────────────
/** Smallest valid PNG: a 1×1 transparent pixel. */
export const PNG: Uint8Array<ArrayBuffer> = Uint8Array.from(
atob(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",
),
(c) => c.charCodeAt(0),
);
export function formWithFile(
bytes: Uint8Array<ArrayBuffer>,
name = "file.png",
type = "image/png",
fields: Record<string, string> = {},
): FormData {
const form = new FormData();
form.set("file", new File([bytes], name, { type }));
for (const [key, value] of Object.entries(fields)) form.set(key, value);
return form;
}
// ── Network ──────────────────────────────────────────────────────────────────
/**
* Replaces outbound fetches and DNS for the life of the returned handle
* (`using net = stubNetwork(...)`). Every hostname resolves to a public
* address unless `dns` says otherwise; `handler` answers every fetch.
*/
export function stubNetwork(
handler: (url: URL, init?: RequestInit) => Response | Promise<Response>,
dns: Record<string, string[]> = {},
): { calls: URL[] } & Disposable {
const calls: URL[] = [];
const fetchStub = stub(
globalThis,
"fetch",
(input: string | URL | Request, init?: RequestInit) => {
const url = new URL(input instanceof Request ? input.url : input);
calls.push(url);
return Promise.resolve(handler(url, init));
},
);
const dnsStub = stub(
Deno,
"resolveDns",
((host: string, type: string) =>
Promise.resolve(
dns[host] ?? (type === "A" ? ["93.184.216.34"] : []),
)) as typeof Deno.resolveDns,
);
return {
calls,
[Symbol.dispose]() {
fetchStub.restore();
dnsStub.restore();
},
};
}
export function html(body: string, status = 200): Response {
return new Response(body, {
status,
headers: { "content-type": "text/html; charset=utf-8" },
});
}