Проверка рабочей сборки настоящим браузером (подмена действия на неизвестное серверу и ответ 500) нашла три изъяна: - ответ, набранный в карточке одного вопроса, после самообновления возвращался в поле другого: адресом поля было имя, а на Главной у каждой карточки поле «answer». Адрес теперь — собственный id поля, имя — только когда текстовое поле с таким именем на странице одно; - секрет проекта и ключ сервера вводятся в textarea и попали бы в sessionStorage: поля секретов и кодов по имени не запоминаются; - ошибка, пойманная новой границей app/error.tsx, не уходила в «Ошибки из прода» (на main уходила): Next печатает её console.error, взятым до обёртки ErrorReporter. Граница сама поднимает её через reportError. Тесты на каждый изъян падали до правки; спека, design архива, AGENTS.md и память дополнены. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
253 lines
17 KiB
TypeScript
253 lines
17 KiB
TypeScript
// PEP-324: after a deploy the buttons of a page opened before it stopped working — the server-action
|
||
// ids are salted with Next's actions key, and the platform image got a random key on every build.
|
||
// Bugsink #23: «UnrecognizedActionError: Server Action "406e…" was not found on the server».
|
||
import assert from "node:assert/strict";
|
||
import { execFileSync } from "node:child_process";
|
||
import { chmodSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
||
import { tmpdir } from "node:os";
|
||
import { join } from "node:path";
|
||
import { describe, test } from "node:test";
|
||
import { PLATFORM_SECRETS } from "@peppa/core";
|
||
|
||
const path = (p: string) => new URL(`../../../${p}`, import.meta.url).pathname;
|
||
const read = (p: string) => readFileSync(path(p), "utf8");
|
||
const lib = (await import(new URL("../../../apps/web/lib/stale-action.ts", import.meta.url).href)) as typeof import("../../../apps/web/lib/stale-action.ts");
|
||
|
||
const KEY_LINE = /^NEXT_SERVER_ACTIONS_ENCRYPTION_KEY=([A-Za-z0-9+/]{43}=)$/m;
|
||
|
||
/** Runs ensure_actions_key from scripts/lib/actions-key.sh against an .env file. */
|
||
function ensureKey(envFile: string) {
|
||
return execFileSync("bash", ["-c", `. "$1"; ensure_actions_key "$2" && printf '%s' "$NEXT_SERVER_ACTIONS_ENCRYPTION_KEY"`, "x", path("scripts/lib/actions-key.sh"), envFile], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
|
||
}
|
||
|
||
describe("PEP-324: постоянный ключ действий в сборке образа", () => {
|
||
test("Сценарий: выкатка передаёт ключ в сборку секретом, а не аргументом", () => {
|
||
const deploy = read("scripts/platform-deploy.sh");
|
||
execFileSync("bash", ["-n", path("scripts/platform-deploy.sh")]);
|
||
const build = deploy.split("\n").find((l) => l.startsWith("run docker build"))!;
|
||
assert.match(build, /--secret id=next_actions_key,env=NEXT_SERVER_ACTIONS_ENCRYPTION_KEY/);
|
||
assert.doesNotMatch(build, /--build-arg[ =]"?NEXT_SERVER_ACTIONS/, "a build-arg would show in docker history");
|
||
const ensure = deploy.indexOf("run ensure_actions_key");
|
||
assert.ok(ensure > 0 && ensure < deploy.indexOf("run docker build"), "the key exists before the build");
|
||
});
|
||
|
||
test("Сценарий: next build в образе читает ключ из секрета BuildKit", () => {
|
||
const dockerfile = read("infra/platform/Dockerfile");
|
||
const stage = dockerfile.slice(0, dockerfile.lastIndexOf("\nFROM "));
|
||
const run = stage.slice(stage.indexOf("RUN --mount=type=secret,id=next_actions_key"));
|
||
assert.ok(stage.includes("RUN --mount=type=secret,id=next_actions_key"), "the build step mounts the secret");
|
||
const cmd = run.slice(0, run.indexOf("./node_modules/.bin/next build") + "./node_modules/.bin/next build".length).replace(/\\\n/g, " ").replace(/^RUN --mount=\S+ /, "");
|
||
// Run the very shell of the step with the secret file, install and next swapped for stubs.
|
||
const dir = mkdtempSync(join(tmpdir(), "pep324-"));
|
||
execFileSync("mkdir", ["-p", join(dir, "apps/web/node_modules/.bin")]);
|
||
const next = join(dir, "apps/web/node_modules/.bin/next");
|
||
writeFileSync(next, '#!/bin/sh\nprintf "key=%s" "$NEXT_SERVER_ACTIONS_ENCRYPTION_KEY"\n');
|
||
chmodSync(next, 0o755);
|
||
const shell = (secret: string | null) => {
|
||
const file = join(dir, "secret");
|
||
if (secret !== null) writeFileSync(file, secret);
|
||
else execFileSync("rm", ["-f", file]);
|
||
const script = cmd.replace("pnpm install --frozen-lockfile", "true").replaceAll("/run/secrets/next_actions_key", file);
|
||
return execFileSync("sh", ["-c", script], { cwd: dir, encoding: "utf8", env: { PATH: process.env.PATH! } });
|
||
};
|
||
assert.match(shell("AAAAkeyAAAA"), /key=AAAAkeyAAAA$/);
|
||
// Without the secret (a hand-made local image) the build still goes, with a random key as before.
|
||
assert.match(shell(null), /key=$/);
|
||
});
|
||
|
||
test("Сценарий: ключа ещё нет — выкатка создаёт его один раз и не печатает", () => {
|
||
const dir = mkdtempSync(join(tmpdir(), "pep324-env-"));
|
||
const env = join(dir, ".env");
|
||
writeFileSync(env, "PEPPA_SECRET=x"); // no trailing newline
|
||
const out = execFileSync("bash", ["-c", `. "$1"; ensure_actions_key "$2" 2>&1`, "x", path("scripts/lib/actions-key.sh"), env], { encoding: "utf8" });
|
||
const text = readFileSync(env, "utf8");
|
||
const key = text.match(KEY_LINE)?.[1];
|
||
assert.ok(key, `a 44-char key line appears:\n${text}`);
|
||
assert.match(text, /^PEPPA_SECRET=x\n/, "the old line stays intact");
|
||
assert.ok(!out.includes(key!), "the value is not in the log");
|
||
// The second deploy keeps it and exports the same value.
|
||
assert.equal(ensureKey(env), key);
|
||
assert.equal(readFileSync(env, "utf8"), text);
|
||
});
|
||
|
||
test("Сценарий: ключ уже есть — строка не меняется", () => {
|
||
const dir = mkdtempSync(join(tmpdir(), "pep324-env-"));
|
||
const env = join(dir, ".env");
|
||
writeFileSync(env, "A=1\nNEXT_SERVER_ACTIONS_ENCRYPTION_KEY=abc\n");
|
||
assert.equal(ensureKey(env), "abc");
|
||
assert.equal(readFileSync(env, "utf8"), "A=1\nNEXT_SERVER_ACTIONS_ENCRYPTION_KEY=abc\n");
|
||
});
|
||
|
||
test("Сценарий: ключ — в ревизии секретов платформы с шагами смены", () => {
|
||
const def = PLATFORM_SECRETS.find((d) => d.name === "NEXT_SERVER_ACTIONS_ENCRYPTION_KEY");
|
||
assert.ok(def, "listed in PLATFORM_SECRETS");
|
||
assert.ok(def.steps.some((s) => s.includes("platform-deploy.sh")));
|
||
assert.ok(def.steps.some((s) => s.includes("peppa secrets rotated NEXT_SERVER_ACTIONS_ENCRYPTION_KEY")));
|
||
});
|
||
});
|
||
|
||
// Minimal DOM and storage mocks for the browser logic.
|
||
function mockStorage() {
|
||
const m = new Map<string, string>();
|
||
return { getItem: (k: string) => m.get(k) ?? null, setItem: (k: string, v: string) => void m.set(k, v), removeItem: (k: string) => void m.delete(k), m };
|
||
}
|
||
function mockField(o: { tag?: string; type?: string; name?: string; id?: string; value?: string; form?: unknown; attrs?: string[] }) {
|
||
return { tagName: o.tag ?? "TEXTAREA", type: o.type, name: o.name ?? "", id: o.id ?? "", value: o.value ?? "", form: o.form ?? null, hasAttribute: (a: string) => (o.attrs ?? []).includes(a) };
|
||
}
|
||
|
||
describe("PEP-324: неизвестное действие обновляет страницу", () => {
|
||
const BUGSINK_23 = 'Server Action "406e36ceb318b543405d508f17c1a2396a4e06ee40" was not found on the server. \nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action';
|
||
|
||
test("Сценарий: ошибка «такого действия нет» распознаётся во всех видах", async () => {
|
||
const { UnrecognizedActionError } = (await import(new URL("../../../apps/web/node_modules/next/dist/client/components/unrecognized-action-error.js", import.meta.url).href)) as { UnrecognizedActionError: new (m: string) => Error };
|
||
assert.equal(lib.isStaleAction(new UnrecognizedActionError(BUGSINK_23), (e) => e instanceof UnrecognizedActionError), true);
|
||
assert.equal(lib.isStaleAction(new Error("x"), (e) => e instanceof Error), true, "Next's own check is asked first");
|
||
const copy = Object.assign(new Error(BUGSINK_23), { name: "UnrecognizedActionError" });
|
||
assert.equal(lib.isStaleAction(copy), true, "from another copy of the module");
|
||
assert.equal(lib.isStaleAction(`Error: ${BUGSINK_23}`), true, "as console.error text");
|
||
assert.equal(lib.isStaleAction(new Error("boom")), false);
|
||
assert.equal(lib.isStaleAction(null), false);
|
||
});
|
||
|
||
test("Сценарий: кнопка открытой до выкатки вкладки — текст сохраняется и возвращается после обновления", () => {
|
||
const storage = mockStorage();
|
||
const form = {};
|
||
const t = new lib.DraftTracker();
|
||
const comment = mockField({ name: "comment", value: "Поправьте заголовок", form });
|
||
t.input(comment);
|
||
t.input(mockField({ tag: "INPUT", type: "password", name: "pw", value: "secret" }));
|
||
t.input(mockField({ tag: "INPUT", type: "hidden", name: "taskId", value: "7" }));
|
||
t.input(mockField({ value: "без имени" }));
|
||
const now = 1_000_000;
|
||
// The failing press is the submit of this very form.
|
||
t.submit(form, now);
|
||
assert.equal(lib.claimReload(storage, now), true, "the first time the page reloads itself");
|
||
lib.saveDrafts(storage, "/t/PEP-1", t.snapshot(now + 500), now + 500);
|
||
|
||
// After the reload: the field is on the page again, empty.
|
||
const fresh = mockField({ name: "comment" });
|
||
const placed: string[] = [];
|
||
const fields = lib.takeDrafts(storage, "/t/PEP-1", now + 3000);
|
||
assert.deepEqual(fields, { comment: "Поправьте заголовок" }, "no password, hidden or nameless fields");
|
||
const left = lib.restoreDrafts(fields!, (k) => (k === "comment" ? fresh : null), (el, v) => {
|
||
el.value = v;
|
||
placed.push(v);
|
||
});
|
||
assert.deepEqual(left, []);
|
||
assert.equal(fresh.value, "Поправьте заголовок");
|
||
assert.equal(lib.takeDrafts(storage, "/t/PEP-1", now + 4000), null, "restored once");
|
||
});
|
||
|
||
test("Сценарий: обновление не помогло — второй раз сама не обновляется", () => {
|
||
const storage = mockStorage();
|
||
assert.equal(lib.claimReload(storage, 0 + 1), true);
|
||
assert.equal(lib.claimReload(storage, 20_001), false, "20 s later: a button instead of a reload loop");
|
||
assert.equal(lib.claimReload(storage, 1 + lib.RELOAD_GUARD_MS + 1), true, "a minute later it may again");
|
||
});
|
||
|
||
test("Сценарий: отправленный текст не возвращается", () => {
|
||
const form = {};
|
||
const t = new lib.DraftTracker();
|
||
t.input(mockField({ name: "comment", value: "Готово", form }));
|
||
t.submit(form, 0);
|
||
// A minute later another button fails: the sent and cleared form stays empty.
|
||
assert.deepEqual(t.snapshot(60_000), {});
|
||
// A field typed after the submit is kept.
|
||
t.input(mockField({ name: "title", value: "Новое", form }));
|
||
assert.deepEqual(t.snapshot(60_000), { title: "Новое" });
|
||
});
|
||
|
||
test("Сценарий: текст другой страницы или старый — не возвращается, набранное заново не затирается", () => {
|
||
const storage = mockStorage();
|
||
lib.saveDrafts(storage, "/p/PEP", { comment: "x" }, 0);
|
||
assert.equal(lib.takeDrafts(storage, "/t/PEP-1", 1000), null);
|
||
lib.saveDrafts(storage, "/t/PEP-1", { comment: "x" }, 0);
|
||
assert.equal(lib.takeDrafts(storage, "/t/PEP-1", lib.DRAFTS_TTL_MS + 1), null);
|
||
const typed = mockField({ name: "comment", value: "уже набрано" });
|
||
lib.restoreDrafts({ comment: "x" }, () => typed, (el, v) => (el.value = v));
|
||
assert.equal(typed.value, "уже набрано");
|
||
});
|
||
|
||
// Found in a real browser on the production build: the home page has a card per question, every
|
||
// card's field is named «answer» — the text typed for one question came back in another's field.
|
||
test("Сценарий: ответ, набранный в карточке одного вопроса, не возвращается в поле другого", () => {
|
||
const storage = mockStorage();
|
||
const t = new lib.DraftTracker();
|
||
const shared = () => false; // two fields named «answer» on the page
|
||
t.input(mockField({ tag: "INPUT", type: "text", name: "answer", id: "answer-4", value: "Да, делайте так" }), shared);
|
||
assert.deepEqual(t.snapshot(0), { "#answer-4": "Да, делайте так" }, "kept under the field's own id, not the shared name");
|
||
lib.saveDrafts(storage, "/", t.snapshot(0), 0);
|
||
|
||
// After the reload both cards are on the page again.
|
||
const fresh: Record<string, ReturnType<typeof mockField>> = {
|
||
"answer-1": mockField({ tag: "INPUT", type: "text", name: "answer", id: "answer-1" }),
|
||
"answer-4": mockField({ tag: "INPUT", type: "text", name: "answer", id: "answer-4" }),
|
||
};
|
||
const find = (k: string) => (k.startsWith("#") ? fresh[k.slice(1)] ?? null : fresh["answer-1"]!);
|
||
assert.deepEqual(lib.restoreDrafts(lib.takeDrafts(storage, "/", 1000)!, find, (el, v) => (el.value = v), shared), []);
|
||
assert.equal(fresh["answer-4"]!.value, "Да, делайте так");
|
||
assert.equal(fresh["answer-1"]!.value, "", "the other question's field stays empty");
|
||
});
|
||
|
||
test("Сценарий: несколько полей с одним именем и без своего id — текст не сохраняется", () => {
|
||
const t = new lib.DraftTracker();
|
||
t.input(mockField({ name: "text", value: "Поправьте кнопку" }), () => false);
|
||
assert.deepEqual(t.snapshot(0), {}, "better lost than put into another task's field");
|
||
// The only field of its name is kept by name; an id React generated is not an address to come back to.
|
||
t.input(mockField({ name: "title", id: "_r_3_", value: "Новая задача" }), () => true);
|
||
assert.deepEqual(t.snapshot(0), { title: "Новая задача" });
|
||
// After the reload there are two fields of that name: nothing is put back.
|
||
const other = mockField({ name: "title" });
|
||
assert.deepEqual(lib.restoreDrafts({ title: "Новая задача" }, () => other, (el, v) => (el.value = v), () => false), ["title"]);
|
||
assert.equal(other.value, "");
|
||
});
|
||
|
||
test("Сценарий: секреты и коды не запоминаются, даже набранные в обычном текстовом поле", () => {
|
||
const t = new lib.DraftTracker();
|
||
const secretFields = [["TEXTAREA", "secret"], ["TEXTAREA", "value"], ["INPUT", "code"], ["INPUT", "token"], ["INPUT", "apiKey"], ["TEXTAREA", "password"]] as const;
|
||
for (const [tag, name] of secretFields) t.input(mockField({ tag, type: tag === "INPUT" ? "text" : undefined, name, value: "sk-ant-oat-0000" }));
|
||
assert.deepEqual(t.snapshot(0), {}, "nothing of it would reach sessionStorage");
|
||
// Every name the web itself treats as a secret somewhere (a `type="password"` field) is covered
|
||
// when the same name is used for a textarea (a multi-line key, a project secret).
|
||
const names = new Set<string>();
|
||
for (const dir of ["apps/web/app", "apps/web/components"])
|
||
for (const f of readdirSync(path(dir), { recursive: true, encoding: "utf8" }).filter((n) => n.endsWith(".tsx")))
|
||
for (const m of read(`${dir}/${f}`).matchAll(/<(?:Input|input)\b[^>]*>/g)) {
|
||
const name = /type="password"/.test(m[0]) ? m[0].match(/\bname="([^"]+)"/)?.[1] : undefined;
|
||
if (name) names.add(name);
|
||
}
|
||
assert.ok(names.size >= 3, `password fields found in the web: ${[...names].join(", ")}`);
|
||
for (const name of names) assert.equal(lib.fieldKey(mockField({ tag: "TEXTAREA", name })), null, `«${name}» holds a secret in a password field — in a textarea too`);
|
||
// Ordinary text is still kept.
|
||
assert.equal(lib.fieldKey(mockField({ name: "description" })), "description");
|
||
});
|
||
|
||
// Found in a real browser: Next prints an error caught by app/error.tsx with the console.error it
|
||
// took at startup, before ErrorReporter wrapped it — the boundary swallowed every page error.
|
||
test("Сценарий: ошибка, пойманная границей ошибок, уходит в «Ошибки из прода»", () => {
|
||
const raised: unknown[] = [];
|
||
const logged: unknown[] = [];
|
||
const err = new Error("boom");
|
||
lib.reportCaughtError(err, { reportError: (e: unknown) => void raised.push(e), console: { error: (...a: unknown[]) => void logged.push(...a) } });
|
||
assert.deepEqual(raised, [err], "raised the way the browser raises an uncaught error — ErrorReporter listens to those");
|
||
assert.equal(logged.length, 0);
|
||
lib.reportCaughtError(err, { console: { error: (...a: unknown[]) => void logged.push(...a) } });
|
||
assert.deepEqual(logged, [err], "a browser without reportError: through the wrapped console");
|
||
assert.match(read("apps/web/app/error.tsx"), /else reportCaughtError\(error, window\)/, "the boundary reports what is not an unknown action");
|
||
});
|
||
|
||
test("Сценарий: в «Ошибки из прода» не уходит, другие ошибки уходят", () => {
|
||
const reporter = read("apps/web/components/ErrorReporter.tsx");
|
||
const send = reporter.slice(reporter.indexOf("const send = "));
|
||
assert.ok(send.indexOf("isStaleAction(message)") > 0 && send.indexOf("isStaleAction(message)") < send.indexOf("/api/client-errors"), "skipped before sending");
|
||
const guard = read("apps/web/components/StaleActionGuard.tsx");
|
||
assert.match(guard, /isStaleAction\(e\.reason\)\) return;\s*e\.preventDefault\(\)/);
|
||
assert.match(read("apps/web/app/layout.tsx"), /<StaleActionGuard \/>/);
|
||
const boundary = read("apps/web/app/error.tsx");
|
||
assert.match(boundary, /^"use client";/);
|
||
assert.match(boundary, /isStaleAction\(error\)/);
|
||
assert.match(guard, /isStaleText\(err, unstable_isUnrecognizedActionError\)/);
|
||
assert.match(boundary, /reportStaleAction\(\)/);
|
||
});
|
||
});
|