VNOX-Web/tests/api.test.ts
loki5512344 4c06a17d7e feat(web): let users set their own photo on the account page
Pick a PNG/JPEG/WebP file, crop it to a square on a canvas (drag, wheel,
slider or keyboard), export a 256x256 PNG and send it to Hub. Adds remove
photo, error states, RU/EN copy and privacy policy text about the stored
photo and 30-day backups.
2026-10-24 21:48:05 +02:00

244 lines
8.1 KiB
TypeScript

import { test } from "bun:test";
import assert from "node:assert/strict";
import {
request,
isSession,
isInfo,
safeAvatar,
ApiError,
requestEmailCode,
verifyEmailCode,
uploadAvatar,
removeAvatar,
} from "../src/api";
import { messages, detectLanguage } from "../src/i18n";
test("catalogs match and never silently fall back to a missing translation", () => {
assert.deepEqual(
Object.keys(messages.ru).sort(),
Object.keys(messages.en).sort(),
);
for (const catalog of Object.values(messages))
for (const value of Object.values(catalog))
assert.ok(typeof value === "string" && value.length > 0);
});
test("language preference is bounded and follows the OS without storage", () => {
assert.equal(detectLanguage("en", ["ru-RU"]), "en");
assert.equal(detectLanguage("bad", ["ru-RU"]), "ru");
assert.equal(detectLanguage(undefined, ["pl-PL"]), "en");
assert.equal(detectLanguage("RU", ["en-US"]), "en");
});
test("API keeps authentication on the same origin and sends CSRF only in header", async () => {
let observed: { path: string; options: RequestInit } | undefined;
const result = await request("/v1/auth/logout", {
method: "POST",
csrf: "fixture-csrf",
fetcher: async (path, options) => {
observed = { path, options };
return new Response(null, { status: 204 });
},
});
assert.equal(result, null);
assert.ok(observed);
assert.equal(observed.path, "/v1/auth/logout");
assert.equal(observed.options.credentials, "same-origin");
assert.equal(observed.options.cache, "no-store");
assert.equal(
new Headers(observed.options.headers).get("X-CSRF-Token"),
"fixture-csrf",
);
assert.equal(observed.options.method, "POST");
await assert.rejects(
request("https://evil.example/v1/auth/session"),
TypeError,
);
await assert.rejects(request("//evil.example/v1/auth/session"), TypeError);
});
test("API failures expose a generic code and preserve status for expired sessions", async () => {
await assert.rejects(
request("/v1/auth/session", {
fetcher: async () => new Response(null, { status: 401 }),
}),
(error: unknown) =>
error instanceof ApiError &&
error.status === 401 &&
error.message === "request_failed",
);
});
test("session validation rejects malformed authenticated payloads", () => {
assert.ok(isSession({ authenticated: false }));
assert.ok(
isSession({
authenticated: true,
csrf_token: "fixture",
user: { user_id: "fixture", handle: "test", display_name: "Test" },
}),
);
assert.equal(isSession({ authenticated: true, user: {} }), false);
assert.equal(isSession({ authenticated: "true" }), false);
assert.equal(
isSession({
authenticated: true,
csrf_token: "",
user: { user_id: "fixture", handle: "test", display_name: "Test" },
}),
false,
);
});
test("avatars allow only uncredentialed HTTPS GitHub image origin", () => {
assert.equal(
safeAvatar("https://avatars.githubusercontent.com/u/1?v=4"),
"https://avatars.githubusercontent.com/u/1?v=4",
);
for (const url of [
"javascript:alert(1)",
"data:image/svg+xml,<svg/>",
"http://avatars.githubusercontent.com/u/1",
"https://avatars.githubusercontent.com.evil.example/u/1",
"https://evil@avatars.githubusercontent.com/u/1",
"https://avatars.githubusercontent.com:8443/u/1",
"https://evil.example/u/1",
null,
])
assert.equal(safeAvatar(url), null);
});
test("Hub capabilities reject malformed JSON before enabling sign-in", () => {
assert.ok(isInfo({ capabilities: { github_auth: "enabled" } }));
for (const value of [
null,
false,
{},
{ capabilities: null },
{ capabilities: { github_auth: true } },
]) {
assert.equal(isInfo(value), false);
}
});
test("email_auth capability must be a string when present", () => {
assert.ok(
isInfo({ capabilities: { github_auth: "enabled", email_auth: "enabled" } }),
);
assert.ok(isInfo({ capabilities: { github_auth: "enabled" } }));
assert.equal(
isInfo({ capabilities: { github_auth: "enabled", email_auth: true } }),
false,
);
});
test("email code requests send JSON same-origin and bound the resend delay", async () => {
let seen: { path: string; init: RequestInit } | undefined;
const result = await requestEmailCode("a@example.com", "en", {
fetcher: async (path, init) => {
seen = { path, init };
return Response.json({ resend_after: 999999 }, { status: 202 });
},
});
assert.equal(result.resendAfter, 60);
assert.ok(seen);
assert.equal(seen.path, "/v1/auth/email/start");
assert.equal(seen.init.method, "POST");
assert.equal(seen.init.credentials, "same-origin");
assert.equal(
new Headers(seen.init.headers).get("Content-Type"),
"application/json",
);
assert.deepEqual(JSON.parse(String(seen.init.body)), {
email: "a@example.com",
lang: "en",
});
const short = await requestEmailCode("a@example.com", "ru", {
fetcher: async () => Response.json({ resend_after: 30 }, { status: 202 }),
});
assert.equal(short.resendAfter, 30);
});
test("email verification accepts only an authenticated session and keeps the status", async () => {
const session = {
authenticated: true,
csrf_token: "fixture",
user: { user_id: "u", handle: "h", display_name: "n" },
};
const ok = await verifyEmailCode("a@example.com", "12345678", {
fetcher: async () => Response.json(session),
});
assert.equal(ok.authenticated, true);
await assert.rejects(
verifyEmailCode("a@example.com", "12345678", {
fetcher: async () => Response.json({ authenticated: false }),
}),
);
await assert.rejects(
verifyEmailCode("a@example.com", "12345678", {
fetcher: async () =>
Response.json({ error: "invalid_code" }, { status: 400 }),
}),
(error: unknown) => error instanceof ApiError && error.status === 400,
);
});
test("own avatars are same-origin content-hash paths only", () => {
const own = `/v1/avatars/${"a1".repeat(32)}`;
assert.equal(safeAvatar(own), own);
for (const value of [
"/v1/avatars/abc",
`/v1/avatars/${"A".repeat(64)}`,
`/v1/avatars/${"a".repeat(64)}/x`,
`//evil.example/v1/avatars/${"a".repeat(64)}`,
`https://evil.example/v1/avatars/${"a".repeat(64)}`,
"/v1/auth/session",
])
assert.equal(safeAvatar(value), null);
});
test("avatar upload sends the PNG with CSRF and keeps the Hub error code", async () => {
const own = `/v1/avatars/${"b2".repeat(32)}`;
let seen: { path: string; init: RequestInit } | undefined;
const png = new Blob([new Uint8Array([1, 2, 3])], { type: "image/png" });
const url = await uploadAvatar(png, "csrf-fixture", {
fetcher: async (path, init) => {
seen = { path, init };
return Response.json({ avatar_url: own });
},
});
assert.equal(url, own);
assert.ok(seen);
assert.equal(seen.path, "/v1/account/avatar");
assert.equal(seen.init.method, "POST");
assert.equal(seen.init.credentials, "same-origin");
assert.equal(seen.init.body, png);
const headers = new Headers(seen.init.headers);
assert.equal(headers.get("Content-Type"), "image/png");
assert.equal(headers.get("X-CSRF-Token"), "csrf-fixture");
await assert.rejects(
uploadAvatar(png, "c", {
fetcher: async () =>
Response.json({ error: "too_large" }, { status: 413 }),
}),
(error: unknown) =>
error instanceof ApiError &&
error.status === 413 &&
error.detail === "too_large",
);
await assert.rejects(
uploadAvatar(png, "c", {
fetcher: async () =>
Response.json({ avatar_url: "https://evil.example/x" }),
}),
);
});
test("avatar removal returns the provider avatar only when it is a safe URL", async () => {
const github = "https://avatars.githubusercontent.com/u/1?v=4";
let method = "";
const result = await removeAvatar("c", {
fetcher: async (_path, init) => {
method = String(init.method);
return Response.json({ avatar_url: github });
},
});
assert.equal(method, "DELETE");
assert.equal(result, github);
assert.equal(
await removeAvatar("c", {
fetcher: async () => Response.json({ avatar_url: "javascript:alert(1)" }),
}),
null,
);
});