peppa/packages/testkit/test/web.test.ts
Асель 2b0f2fd984 PEP-1: web platform with Gitea login, projects, goals, tasks, sessions
- web: Gitea OAuth2 login, signed session cookie, everything behind login;
  inbox with answers, project board (goals → tasks), task page with
  OpenSpec artifacts, questions and session controls; new project form;
  auto-refresh, light/dark, mobile
- users + projects.owner_id; tokens AES-256-GCM encrypted; owner-only access
- provisionProject (runner): new or existing Gitea repo, peppa-bot
  collaborator, template + openspec init, push, rollback; used by web and
  peppa project create (replaces scripts/bootstrap-project.sh)
- peppa web login-link, peppa project owner; Gitea OAuth app script
- bins/template resolved via PEPPA_ROOT (works inside the Next build)
- testkit: mock-gitea + 10 tests (42 e2e total, all green)
- OpenSpec: pep-1-web-platform archived into specs web-auth,
  project-provisioning, web-workspace

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:55:02 +05:00

145 lines
7.9 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.

// PEP-1: auth primitives, access control and project provisioning (mock-gitea + real git).
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, 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";
import { MockGitea } from "../src/mock-gitea.ts";
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const TMP = mkdtempSync(join(tmpdir(), "peppa-web-"));
process.env.PEPPA_SECRET = "mock-secret-for-tests";
process.env.PEPPA_WORKSPACES = join(TMP, "workspaces");
const gitea = new MockGitea(join(TMP, "gitea"));
const ALICE = { id: 11, login: "mock-alice", token: "mock-token-alice", orgs: ["mock-team"] };
const BOB = { id: 12, login: "mock-bob", token: "mock-token-bob" };
let templateUrl = "";
let alice: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let bob: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
gitea.addUser(ALICE);
gitea.addUser(BOB);
// Template repo from the real template/ dir.
const tpl = gitea.addRepo("peppa-bot", "template");
execFileSync("bash", ["-c", `cd ${JSON.stringify(join(ROOT, "template"))} && T=$(mktemp -d) && cp -R . "$T" && cd "$T" && git init -q -b main && git add -A && git -c user.name=t -c user.email=t@t commit -qm tpl && git push -q ${JSON.stringify(tpl.path)} main`]);
templateUrl = tpl.path;
alice = await core.upsertUserFromGitea(db, { id: ALICE.id, login: ALICE.login }, { access_token: ALICE.token, refresh_token: "r", expires_in: 3600 });
bob = await core.upsertUserFromGitea(db, { id: BOB.id, login: BOB.login }, { access_token: BOB.token });
});
after(async () => {
await gitea.stop();
await teardown();
});
const provision = async (over: Partial<Parameters<typeof runner.provisionProject>[1]> & { slug: string; key: string }) =>
runner.provisionProject(db, {
gitea: await core.giteaForUser(db, alice),
owner: ALICE.login,
ownerIsUser: true,
name: `Mock ${over.key}`,
ownerId: alice.id,
templateUrl,
...over,
});
describe("auth primitives", () => {
test("token encryption round-trips and tokens are not stored in clear", async () => {
const enc = core.encrypt("secret-token");
assert.notEqual(enc, "secret-token");
assert.equal(core.decrypt(enc), "secret-token");
assert.ok(!alice.accessTokenEnc?.includes(ALICE.token));
assert.equal(core.decrypt(alice.accessTokenEnc!), ALICE.token);
});
test("signed session payloads reject tampering", () => {
const t = core.sign({ uid: 1, exp: 1 });
assert.deepEqual(core.verify(t), { uid: 1, exp: 1 });
const [body, sig] = t.split(".");
const forged = Buffer.from(JSON.stringify({ uid: 2, exp: 1 })).toString("base64url");
assert.equal(core.verify(`${forged}.${sig}`), null);
assert.equal(core.verify(`${body}.AAAA`), null);
assert.equal(core.verify(undefined), null);
});
test("admin login link works once and expires", async () => {
const code = await core.createLoginLink(db, alice.id);
assert.equal(await core.consumeLoginLink(db, code), alice.id);
assert.equal(await core.consumeLoginLink(db, code), null, "single use");
const old = await core.createLoginLink(db, alice.id);
await core.setSetting(db, `web.login:${core.hashToken(old)}`, { userId: alice.id, expiresAt: Date.now() - 1 });
assert.equal(await core.consumeLoginLink(db, old), null, "expired");
});
test("OAuth code exchange + Gitea user → Peppa user", async () => {
gitea.oauthCodes.set("mock-code", BOB.token);
const tokens = await core.exchangeOAuthCode(gitea.url, "id", "secret", "mock-code", "http://x/auth/callback");
const me = await new core.GiteaClient(gitea.url, tokens.access_token).me();
const u = await core.upsertUserFromGitea(db, me, tokens);
assert.equal(u.id, bob.id, "same Gitea account → same Peppa user");
await assert.rejects(core.exchangeOAuthCode(gitea.url, "id", "secret", "mock-code", "http://x/auth/callback"), "code is single use");
});
});
describe("project provisioning", () => {
test("new repo: template + OpenSpec pushed, peppa-bot collaborator, owned by the user", async () => {
const p = await provision({ slug: "mock-demo", key: "MDEMO" });
assert.equal(p.ownerId, alice.id);
assert.equal(p.giteaOwner, ALICE.login);
const files = gitea.files(ALICE.login, "mock-demo");
for (const f of ["AGENTS.md", "CLAUDE.md", ".mcp.json", ".peppa/project.json", "openspec/config.yaml", "README.md"]) assert.ok(files.includes(f), `${f} pushed`);
assert.ok(!files.includes("RULES.md"), "RULES.md stays in the template repo");
assert.ok(files.some((f) => f.startsWith(".agents/skills/openspec-")), "openspec init ran (agent skills)");
assert.match(gitea.show(ALICE.login, "mock-demo", "openspec/config.yaml"), /Пеппа/, "template OpenSpec config kept");
assert.equal(JSON.parse(gitea.show(ALICE.login, "mock-demo", ".peppa/project.json")).key, "MDEMO");
assert.equal(gitea.repos.get(`${ALICE.login}/mock-demo`)!.collaborators["peppa-bot"], "write");
assert.match(execFileSync("git", ["-C", p.workspacePath, "config", "--get-all", "credential.helper"], { encoding: "utf8" }), /git-credential-peppa/);
});
test("project in an org the user can create repos in", async () => {
const p = await provision({ slug: "mock-team-app", key: "MTEAM", owner: "mock-team", ownerIsUser: false });
assert.equal(p.giteaOwner, "mock-team");
assert.ok(gitea.files("mock-team", "mock-team-app").includes("AGENTS.md"));
});
test("conflicts leave nothing behind in Peppa", async () => {
await assert.rejects(provision({ slug: "mock-demo", key: "MOTHER" }), /Slug "mock-demo" уже занят/);
await assert.rejects(provision({ slug: "mock-other", key: "MDEMO" }), /Ключ "MDEMO" уже занят/);
gitea.addRepo(ALICE.login, "mock-taken");
await assert.rejects(provision({ slug: "mock-taken", key: "MTAKEN" }), /уже существует/);
assert.ok(!existsSync(join(process.env.PEPPA_WORKSPACES!, "mock-taken")));
await assert.rejects(core.getProject(db, "MTAKEN"));
});
test("existing repo with code: own files kept, Peppa files added", async () => {
gitea.addRepo(ALICE.login, "mock-legacy", { files: { "AGENTS.md": "# Свои правила\n", "src/app.ts": "export {};\n" } });
const p = await provision({ slug: "mock-legacy", key: "MLEG", existing: true });
assert.equal(gitea.show(ALICE.login, "mock-legacy", "AGENTS.md"), "# Свои правила\n", "existing AGENTS.md not overwritten");
const files = gitea.files(ALICE.login, "mock-legacy");
for (const f of ["src/app.ts", ".peppa/project.json", ".mcp.json", "openspec/config.yaml"]) assert.ok(files.includes(f), f);
assert.ok(files.some((f) => f.startsWith(".agents/skills/openspec-")), "openspec init ran");
assert.ok(readFileSync(join(p.workspacePath, "src/app.ts"), "utf8"));
});
test("existing repo without admin rights is refused", async () => {
gitea.addRepo(ALICE.login, "mock-foreign", { admins: ["someone-else"], files: { "x.txt": "x" } });
await assert.rejects(provision({ slug: "mock-foreign", key: "MFOR", existing: true }), /Нет прав администратора/);
});
});
describe("access control", () => {
test("a user only reaches own projects", async () => {
const p = await core.getProject(db, "MDEMO");
assert.equal((await core.projectForUser(db, alice.id, p.id)).key, "MDEMO");
await assert.rejects(core.projectForUser(db, bob.id, p.id), /Не найдено/);
assert.deepEqual((await core.listUserProjects(db, bob.id)).map((x) => x.key), []);
assert.ok((await core.listUserProjects(db, alice.id)).some((x) => x.key === "MDEMO"));
});
});