Files
gerbeur/api/test/social.test.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

313 lines
9.5 KiB
TypeScript

// Follows, feeds, notifications and invites.
import {
type ApiResponse,
count,
createUser,
db,
del,
get,
insertCategory,
insertDump,
insertPlaylist,
patch,
post,
test,
} from "./helpers.ts";
import type {
Comment,
Dump,
FollowStatus,
InviteResponse,
Notification,
PaginatedData,
Playlist,
PublicUser,
} from "../model/interfaces.ts";
import { assertEquals, assertFalse, assertMatch } from "@std/assert";
function titles(res: ApiResponse<PaginatedData<Dump>>): string[] {
return res.data.items.map((d) => d.title);
}
test("following users: status, idempotence, no self-follow, one notification", async () => {
const me = await createUser();
const them = await createUser();
assertEquals(
(await post(`/api/follows/users/${them.id}`, { auth: me.auth })).status,
204,
);
assertEquals(
(await post(`/api/follows/users/${them.id}`, { auth: me.auth })).status,
204,
);
assertEquals(
(await post(`/api/follows/users/${me.id}`, { auth: me.auth })).status,
400,
);
assertEquals(
(await get<FollowStatus>("/api/follows/status", { auth: me.auth })).data,
{ followedUserIds: [them.id], followedPlaylistIds: [] },
);
// Unfollow and follow again: still just the one notification.
await del(`/api/follows/users/${them.id}`, { auth: me.auth });
assertEquals(
(await get<FollowStatus>("/api/follows/status", { auth: me.auth })).data
.followedUserIds,
[],
);
await post(`/api/follows/users/${them.id}`, { auth: me.auth });
assertEquals(
count(
`SELECT COUNT(*) as n FROM notifications WHERE user_id = ? AND type = 'user_followed';`,
them.id,
),
1,
);
const list = await get<PaginatedData<PublicUser>>(
`/api/users/${me.username}/followed-users`,
);
assertEquals(list.data.items.map((u) => u.id), [
them.id,
]);
assertFalse("email" in list.data.items[0]);
});
test("following playlists: public ones only, and not your own notification", async () => {
const owner = await createUser();
const me = await createUser();
const pub = insertPlaylist({ userId: owner.id });
const priv = insertPlaylist({ userId: owner.id, isPublic: false });
assertEquals(
(await post(`/api/follows/playlists/${pub.id}`, { auth: me.auth })).status,
204,
);
assertEquals(
(await post(`/api/follows/playlists/${priv.id}`, { auth: me.auth })).status,
403,
);
assertEquals(
(await post(`/api/follows/playlists/${crypto.randomUUID()}`, {
auth: me.auth,
})).status,
404,
);
await post(`/api/follows/playlists/${pub.id}`, { auth: owner.auth });
assertEquals(
count(
`SELECT COUNT(*) as n FROM notifications WHERE type = 'playlist_followed';`,
),
1,
);
assertEquals(
(await get<PaginatedData<Playlist>>(
`/api/users/${me.username}/followed-playlists`,
)).data
.items[0].id,
pub.id,
);
await del(`/api/follows/playlists/${pub.id}`, { auth: me.auth });
assertEquals(
(await get<FollowStatus>("/api/follows/status", { auth: me.auth })).data
.followedPlaylistIds,
[],
);
});
test("followed-users feed: public dumps of the people I follow, newest first", async () => {
const me = await createUser();
const followed = await createUser();
const stranger = await createUser();
const music = insertCategory({ slug: "music" });
insertDump({
userId: followed.id,
title: "old",
createdAt: "2024-01-01T00:00:00Z",
});
const tagged = insertDump({
userId: followed.id,
title: "new",
createdAt: "2024-02-01T00:00:00Z",
});
db.prepare(
`INSERT INTO dump_categories (dump_id, category_id) VALUES (?, ?);`,
)
.run(tagged.id, music);
insertDump({ userId: followed.id, title: "private", isPrivate: true });
insertDump({ userId: stranger.id, title: "stranger" });
await post(`/api/follows/users/${followed.id}`, { auth: me.auth });
const feed = await get<PaginatedData<Dump>>("/api/follows/feed/users", {
auth: me.auth,
});
assertEquals(titles(feed), ["new", "old"]);
assertEquals(feed.data.items[0].categoryIds, [music]);
assertEquals(
titles(
await get("/api/follows/feed/users?category=music", { auth: me.auth }),
),
["new"],
);
// An unknown category filters everything out rather than nothing.
assertEquals(
(await get<PaginatedData<Dump>>("/api/follows/feed/users?category=nope", {
auth: me.auth,
})).data,
{ items: [], total: 0, hasMore: false },
);
assertEquals((await get("/api/follows/feed/users")).status, 401);
});
test("followed-playlists feed: each dump once, public playlists only", async () => {
const me = await createUser();
const owner = await createUser();
const p1 = insertPlaylist({ userId: owner.id });
const p2 = insertPlaylist({ userId: owner.id });
const d = insertDump({ userId: owner.id, title: "shared" });
const priv = insertDump({
userId: owner.id,
title: "private",
isPrivate: true,
});
for (const p of [p1, p2]) {
await post(`/api/follows/playlists/${p.id}`, { auth: me.auth });
await post(`/api/playlists/${p.id}/dumps/${d.id}`, { auth: owner.auth });
}
await post(`/api/playlists/${p1.id}/dumps/${priv.id}`, { auth: owner.auth });
const feed = await get<PaginatedData<Dump>>("/api/follows/feed/playlists", {
auth: me.auth,
});
assertEquals(titles(feed), ["shared"]);
assertEquals(feed.data.total, 1);
// A playlist gone private drops out of the feed.
db.prepare(`UPDATE playlists SET is_public = 0;`).run();
assertEquals(
(await get<PaginatedData<Dump>>("/api/follows/feed/playlists", {
auth: me.auth,
})).data
.total,
0,
);
});
test("notifications: listed newest first, marked read one or all, never someone else's", async () => {
const me = await createUser();
const other = await createUser();
const { id: dumpId } = insertDump({ userId: me.id, title: "Mine" });
// Two notifications for me, one for other.
await post(`/api/follows/users/${me.id}`, { auth: other.auth });
await post(`/api/dumps/${dumpId}/comments`, {
auth: other.auth,
json: { body: "hey" },
});
await post(`/api/follows/users/${other.id}`, { auth: me.auth });
const list = await get<PaginatedData<Notification>>("/api/notifications", {
auth: me.auth,
});
assertEquals(list.data.total, 2);
assertEquals(
list.data.items.map((n) => n.type),
["dump_commented", "user_followed"],
);
assertEquals(
list.data.items.every((n) => !n.read),
true,
);
const theirs = (await get<PaginatedData<Notification>>("/api/notifications", {
auth: other.auth,
})).data
.items[0].id;
assertEquals(
(await patch(`/api/notifications/${theirs}/read`, { auth: me.auth }))
.status,
204,
);
assertEquals(
(await get<PaginatedData<Notification>>("/api/notifications", {
auth: other.auth,
})).data.items[0]
.read,
false,
);
const first = list.data.items[0].id;
await patch(`/api/notifications/${first}/read`, { auth: me.auth });
const after = (await get<PaginatedData<Notification>>("/api/notifications", {
auth: me.auth,
})).data.items;
assertEquals(after.map((n) => n.read), [true, false]);
assertEquals(
(await post("/api/notifications/read-all", { auth: me.auth })).status,
204,
);
assertEquals(
count(
`SELECT COUNT(*) as n FROM notifications WHERE user_id = ? AND read = 0;`,
me.id,
),
0,
);
assertEquals((await get("/api/notifications")).status, 401);
});
test("mentions: notify the named, once per context, never the author or an email domain", async () => {
const author = await createUser();
const named = await createUser();
const { id: dumpId } = insertDump({ userId: author.id, title: "Topic" });
const body = `hi @${named.username.toUpperCase()} and @${named.username}, ` +
`me @${author.username}, mail x@${named.username}.com, ` +
`[@${named.username}](link) @nobody_known`;
const c = await post<Comment>(`/api/dumps/${dumpId}/comments`, {
auth: author.auth,
json: { body },
});
const notes = db.prepare(
`SELECT user_id, data FROM notifications WHERE type = 'user_mentioned';`,
).all() as { user_id: string; data: string }[];
assertEquals(notes.length, 1);
assertEquals(notes[0].user_id, named.id);
assertEquals(JSON.parse(notes[0].data), {
mentionerId: author.id,
mentionerUsername: author.username,
contextType: "comment",
contextId: c.data.id,
contextTitle: "Topic",
dumpId,
});
// Editing the comment doesn't notify a second time.
await patch(`/api/comments/${c.data.id}`, {
auth: author.auth,
json: { body: `again @${named.username}` },
});
assertEquals(
count(
`SELECT COUNT(*) as n FROM notifications WHERE type = 'user_mentioned';`,
),
1,
);
});
test("invites: anyone signed in can make one; it validates until used or stale", async () => {
const user = await createUser();
assertEquals((await post("/api/invites")).status, 401);
const res = await post<InviteResponse>("/api/invites", { auth: user.auth });
assertEquals(res.status, 201);
const token = res.data.token;
assertMatch(token, /^[A-Za-z0-9_-]{22}$/);
assertEquals((await get(`/api/invites/${token}`)).status, 200);
assertEquals((await get(`/api/invites/unknown`)).status, 404);
db.prepare(`UPDATE invites SET used_at = ? WHERE token = ?;`).run(
new Date().toISOString(),
token,
);
assertEquals((await get(`/api/invites/${token}`)).status, 404);
db.prepare(
`UPDATE invites SET used_at = NULL, created_at = ? WHERE token = ?;`,
)
.run(new Date(Date.now() - 8 * 86400_000).toISOString(), token);
assertEquals((await get(`/api/invites/${token}`)).status, 404);
});