Двадцать задач слиты одним заходом; три правила одной задачи ломались кодом другой: - PEP-273 × PEP-250, PEP-279: три новых файла веба брали `next/link` напрямую — переведены на `@/components/Link` (сторож no-prefetch.test.ts). - PEP-281 × PEP-272: адрес аватара в health-anon.test.ts и спеке web-auth — на git.vibe42.kz (сторож old-git-cleanup.test.ts не пускает старый адрес в репозиторий). - PEP-217 × PEP-281: в observe.db миграции стали подряд (web_vitals — версия 4, монитор «Интернет» — версия 5); тест PEP-281 возвращал файл «к версии 3» и повторял чужую миграцию. Версия берётся по самой миграции (`observeMigrationIndex`). Стыки, решённые при слиянии: страница /gitea и мок `/repos/search` (PEP-273 × PEP-280; после «Сделать закрытым» страница берёт свежий список мимо кэша), импорты (PEP-250 × PEP-302, PEP-279 × PEP-291, PEP-273 × PEP-304), память — файл на задачу по раскладке PEP-306. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
106 lines
5.1 KiB
TypeScript
106 lines
5.1 KiB
TypeScript
// PEP-272: служебные данные — не анониму. /api/health без ключа отдаёт только {ok}; ключ (HMAC от
|
||
// PEPPA_SECRET) шлют внутренние проверки; без X-Powered-By, скрипты в CSP — только свои, аватар — https.
|
||
import assert from "node:assert/strict";
|
||
import { execFileSync } from "node:child_process";
|
||
import { createServer, type Server } from "node:http";
|
||
import { resolve } from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
import { after, before, describe, test } from "node:test";
|
||
import { core, db, runner, teardown } from "./helpers.ts";
|
||
|
||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||
process.env.PEPPA_SECRET = "mock-health-secret";
|
||
const full = { ok: true, version: "0.15.0", commit: "abc1234", db: { ok: true, latencyMs: 1 }, services: [{ service: "web", ok: true }], boot: "abc1234-x" };
|
||
|
||
after(teardown);
|
||
|
||
describe("PEP-272: /api/health для анонима", () => {
|
||
test("Аноним видит только «ok»", () => {
|
||
assert.deepEqual(core.healthBody(full, null), { ok: true });
|
||
assert.deepEqual(core.healthBody({ ...full, ok: false }, undefined), { ok: false });
|
||
});
|
||
|
||
test("Неверный ключ — как аноним", () => {
|
||
assert.deepEqual(core.healthBody(full, "abc"), { ok: true });
|
||
assert.deepEqual(core.healthBody(full, core.healthToken()!.slice(0, 63) + "0"), { ok: true });
|
||
});
|
||
|
||
test("Всё работает: внутренняя проверка с ключом видит сводку", () => {
|
||
const key = core.healthHeaders()[core.HEALTH_HEADER];
|
||
assert.ok(key);
|
||
assert.deepEqual(core.healthBody(full, key), full);
|
||
});
|
||
|
||
test("Ротация: ключ от PEPPA_SECRET_PREVIOUS тоже принимается", () => {
|
||
const old = core.healthToken()!;
|
||
process.env.PEPPA_SECRET_PREVIOUS = process.env.PEPPA_SECRET;
|
||
process.env.PEPPA_SECRET = "mock-health-secret-new";
|
||
try {
|
||
assert.ok(core.healthTokenOk(old));
|
||
assert.ok(core.healthTokenOk(core.healthToken()));
|
||
} finally {
|
||
process.env.PEPPA_SECRET = "mock-health-secret";
|
||
delete process.env.PEPPA_SECRET_PREVIOUS;
|
||
}
|
||
});
|
||
|
||
test("Ключ shell-скриптов выкатки совпадает с ключом ядра", () => {
|
||
const sh = execFileSync("bash", ["-c", `. "${ROOT}/scripts/lib/health-token.sh"; health_token`], { encoding: "utf8", env: { ...process.env } }).trim();
|
||
assert.equal(sh, core.healthToken());
|
||
});
|
||
|
||
describe("сторож адреса шлёт ключ", () => {
|
||
let server: Server;
|
||
before(async () => {
|
||
server = createServer((req, res) => {
|
||
const body = core.healthBody(full, req.headers[core.HEALTH_HEADER] as string | undefined);
|
||
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(body));
|
||
});
|
||
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
|
||
process.env.PEPPA_PUBLIC_HEALTH_URL = `http://127.0.0.1:${(server.address() as { port: number }).port}/api/health`;
|
||
});
|
||
after(() => {
|
||
delete process.env.PEPPA_PUBLIC_HEALTH_URL;
|
||
server.close();
|
||
});
|
||
test("публичный адрес с полной сводкой узнан как FORGE", async () => {
|
||
assert.equal(await runner.publicHealthTick(db), true);
|
||
});
|
||
});
|
||
});
|
||
|
||
describe("PEP-272: ответы веба не раскрывают служебное", () => {
|
||
test("Заголовки страницы: без X-Powered-By, script-src только свои", async () => {
|
||
const prev = process.env.NODE_ENV;
|
||
(process.env as Record<string, string>).NODE_ENV = "production";
|
||
try {
|
||
const config = ((await import(new URL("../../../apps/web/next.config.ts", import.meta.url).href)) as { default: { poweredByHeader?: boolean; headers: () => Promise<{ source: string; headers: { key: string; value: string }[] }[]> } }).default;
|
||
assert.equal(config.poweredByHeader, false);
|
||
const all = (await config.headers()).find((h) => h.source === "/:path*")!;
|
||
const csp = all.headers.find((h) => h.key === "Content-Security-Policy")!.value;
|
||
assert.match(csp, /script-src 'self' 'unsafe-inline'(;|$)/);
|
||
assert.doesNotMatch(csp, /unsafe-eval/);
|
||
assert.match(csp, /worker-src 'self'/);
|
||
assert.match(csp, /frame-ancestors 'none'/);
|
||
} finally {
|
||
(process.env as Record<string, string | undefined>).NODE_ENV = prev;
|
||
}
|
||
});
|
||
|
||
for (const [url, shown] of [
|
||
["http://git.vibe42.kz/avatars/1", "https://git.vibe42.kz/avatars/1"],
|
||
["https://git.vibe42.kz/avatars/1", "https://git.vibe42.kz/avatars/1"],
|
||
["javascript:alert(1)", null],
|
||
["", null],
|
||
] as const) {
|
||
test(`Адрес аватара: ${url || "пусто"} → ${shown ?? "нет картинки"}`, () => {
|
||
assert.equal(core.httpsAvatar(url), shown);
|
||
});
|
||
}
|
||
|
||
test("Аватар Gitea по http сохраняется как https", async () => {
|
||
const u = await core.upsertUserFromGitea(db, { id: 72001, login: "mock-avatar", avatar_url: "http://git.vibe42.kz/avatars/7" }, { access_token: "x" });
|
||
assert.equal(u.avatarUrl, "https://git.vibe42.kz/avatars/7");
|
||
});
|
||
});
|