254 lines
16 KiB
TypeScript
254 lines
16 KiB
TypeScript
// PEP-67: agent subscriptions (Claude Code / Codex / OpenCode), pools and the subscription a
|
||
// runner starts on. Sign-in and trial runs go through the mock CLIs (mock-claude, mock-codex,
|
||
// mock-opencode) with the real contracts: setup-token, device auth, --with-api-key, -p/exec/run.
|
||
import assert from "node:assert/strict";
|
||
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
||
import { join, resolve } from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
import { after, before, describe, test } from "node:test";
|
||
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
|
||
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||
|
||
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let asel: User;
|
||
let dana: User;
|
||
before(async () => {
|
||
asel = await core.upsertUserFromGitea(db, { id: 41, login: "asel" }, { access_token: "x" });
|
||
dana = await core.upsertUserFromGitea(db, { id: 42, login: "mock-dana" }, { access_token: "x" });
|
||
await core.setPlatformAdmins(db, ["asel", "admin"]);
|
||
});
|
||
after(teardown);
|
||
|
||
const TOKEN = (tag: string) => `sk-ant-oat01-mock${"x".repeat(24)}${tag.replace(/[^A-Za-z0-9]/g, "")}`;
|
||
const claudeSub = (name: string, tag = name) =>
|
||
runner.addSubscription(db, { provider: "claude", name, method: "token", secret: TOKEN(tag), createdBy: asel.id });
|
||
const sub = (id: number) => core.getSubscription(db, id);
|
||
|
||
describe("Раздел «Подписки» только для суперадмина", () => {
|
||
test("суперадмин — логин из platform.admins, остальным раздела нет", async () => {
|
||
assert.equal(await core.isSuperadmin(db, asel), true);
|
||
assert.equal(await core.isSuperadmin(db, { login: "ADMIN" }), true);
|
||
assert.equal(await core.isSuperadmin(db, dana), false);
|
||
assert.equal(await core.isSuperadmin(db, null), false);
|
||
await assert.rejects(core.requireSuperadmin(db, dana), /Не найдено/);
|
||
await core.requireSuperadmin(db, asel);
|
||
});
|
||
});
|
||
|
||
describe("Подписка агента", () => {
|
||
test("суперадмин добавляет подписку Claude: ссылка → код → активна, токен зашифрован", async () => {
|
||
const s = await runner.addSubscription(db, { provider: "claude", name: "Claude Max — asel", method: "login", createdBy: asel.id });
|
||
assert.equal(s.status, "pending");
|
||
const login = await runner.pendingLogin(db, s.id);
|
||
assert.match(login!.url, /^https:\/\/claude\.com\/cai\/oauth\/authorize\?/);
|
||
await runner.finishClaudeLogin(db, s.id, "mock-good-1");
|
||
const got = await sub(s.id);
|
||
assert.equal(got.status, "active");
|
||
assert.ok(got.secretEnc && !got.secretEnc.includes("sk-ant"), "stored encrypted");
|
||
assert.match(core.decrypt(got.secretEnc), /^sk-ant-oat01-mock/);
|
||
assert.equal(await runner.pendingLogin(db, s.id), null);
|
||
const listed = (await core.listSubscriptions(db)).find((x) => x.id === s.id)!;
|
||
assert.equal(listed.createdByLogin, "asel");
|
||
assert.equal(listed.activeSessions, 0);
|
||
});
|
||
|
||
test("неверный код Claude: ошибка, подписка не активна; отмена удаляет новую подписку", async () => {
|
||
const s = await runner.addSubscription(db, { provider: "claude", name: "Claude bad", method: "login", createdBy: asel.id });
|
||
await assert.rejects(runner.finishClaudeLogin(db, s.id, "mock-bad-code"), /не принял код/);
|
||
assert.equal((await sub(s.id)).status, "pending");
|
||
assert.equal((await sub(s.id)).secretEnc, null);
|
||
await assert.rejects(runner.finishClaudeLogin(db, s.id, "mock-good-1"), /не начат/);
|
||
await runner.cancelLogin(db, s.id);
|
||
await assert.rejects(sub(s.id), /не найдена/);
|
||
});
|
||
|
||
test("Codex через ChatGPT: ссылка и одноразовый код, вход в собственном CODEX_HOME", async () => {
|
||
const s = await runner.addSubscription(db, { provider: "codex", name: "ChatGPT Pro", method: "device", createdBy: asel.id });
|
||
const login = (await runner.pendingLogin(db, s.id))!;
|
||
assert.equal(login.url, "https://auth.openai.com/codex/device");
|
||
assert.match(login.code!, /^MOCK-[A-Z0-9]{4}$/);
|
||
assert.equal(await runner.pollCodexLogin(db, s.id), "pending");
|
||
writeFileSync(join(runner.codexHome(s.id), "mock-device-approved"), "");
|
||
await waitFor("codex login done", async () => (await runner.pollCodexLogin(db, s.id)) === "active");
|
||
assert.equal((await sub(s.id)).status, "active");
|
||
assert.ok(existsSync(join(runner.codexHome(s.id), "auth.json")));
|
||
assert.ok(runner.codexHome(s.id).startsWith(process.env.PEPPA_HOME!));
|
||
});
|
||
|
||
test("Codex: отказ на устройстве → ошибка входа", async () => {
|
||
const s = await runner.addSubscription(db, { provider: "codex", name: "ChatGPT denied", method: "device", createdBy: asel.id });
|
||
writeFileSync(join(runner.codexHome(s.id), "mock-device-denied"), "");
|
||
await waitFor("codex login failed", async () => (await runner.pollCodexLogin(db, s.id)) === "failed");
|
||
const got = await sub(s.id);
|
||
assert.equal(got.status, "auth_error");
|
||
assert.match(got.lastError!, /denied/);
|
||
});
|
||
|
||
test("Codex по API-ключу: неверный ключ отклонён, верный — активна, ключа нет в БД", async () => {
|
||
await assert.rejects(
|
||
runner.addSubscription(db, { provider: "codex", name: "Codex bad key", method: "api_key", secret: "mock-bad-key-123", createdBy: asel.id }),
|
||
/не принял ключ/,
|
||
);
|
||
assert.equal((await core.listSubscriptions(db)).some((x) => x.name === "Codex bad key"), false);
|
||
const s = await runner.addSubscription(db, { provider: "codex", name: "Codex key", method: "api_key", secret: "mock-openai-key-123", createdBy: asel.id });
|
||
assert.equal(s.status, "active");
|
||
assert.equal(s.secretEnc, null);
|
||
assert.match(readFileSync(join(runner.codexHome(s.id), "auth.json"), "utf8"), /mock-openai-key-123/);
|
||
});
|
||
|
||
test("OpenCode по ключу провайдера: активна, ключ зашифрован", async () => {
|
||
await assert.rejects(runner.addSubscription(db, { provider: "opencode", name: "OC", method: "api_key", secret: "k", keyProvider: "nope", createdBy: asel.id }), /провайдера/);
|
||
const s = await runner.addSubscription(db, { provider: "opencode", name: "OpenCode Anthropic", method: "api_key", secret: "mock-anthropic-key-1", keyProvider: "anthropic", createdBy: asel.id });
|
||
assert.equal(s.status, "active");
|
||
assert.equal(core.subscriptionSecret(s), "mock-anthropic-key-1");
|
||
assert.ok(!s.secretEnc!.includes("mock-anthropic"));
|
||
});
|
||
});
|
||
|
||
describe("Проверка подписки", () => {
|
||
test("лимит → «лимит до …», отозванный вход → «ошибка входа» без секрета, рабочая → активна", async () => {
|
||
const now = new Date("2026-11-14T10:00:00");
|
||
const limited = await claudeSub("Claude limited", "limit");
|
||
const r1 = await runner.checkSubscription(db, limited.id, now);
|
||
assert.equal(r1.status, "limited");
|
||
const l = await sub(limited.id);
|
||
assert.equal(l.status, "limited");
|
||
assert.equal(l.limitedUntil!.getHours(), 17, "reset time from the banner (5pm)");
|
||
|
||
const bad = await claudeSub("Claude revoked", "bad");
|
||
assert.equal((await runner.checkSubscription(db, bad.id, now)).status, "auth_error");
|
||
const b = await sub(bad.id);
|
||
assert.match(b.lastError!, /Invalid API key/);
|
||
assert.ok(!b.lastError!.includes(TOKEN("bad")));
|
||
|
||
const ok = await claudeSub("Claude ok", "fine");
|
||
assert.equal((await runner.checkSubscription(db, ok.id, now)).status, "active");
|
||
|
||
const codexLimited = await runner.addSubscription(db, { provider: "codex", name: "Codex limited", method: "api_key", secret: "mock-limit-key-1", createdBy: asel.id });
|
||
assert.equal((await runner.checkSubscription(db, codexLimited.id, now)).status, "limited");
|
||
const oc = await runner.addSubscription(db, { provider: "opencode", name: "OC bad", method: "api_key", secret: "mock-bad-oc-key", keyProvider: "openai", createdBy: asel.id });
|
||
assert.equal((await runner.checkSubscription(db, oc.id, now)).status, "auth_error");
|
||
});
|
||
});
|
||
|
||
describe("Пулы и подписка сессии", () => {
|
||
test("пул для ротации: раннеры проекта стартуют на свободной подписке пула", async () => {
|
||
const a = await claudeSub("Claude A");
|
||
const b = await claudeSub("Claude B");
|
||
const c = await runner.addSubscription(db, { provider: "codex", name: "Codex C", method: "api_key", secret: "mock-openai-key-c", createdBy: asel.id });
|
||
const pool = await core.createPool(db, { name: "Основной", subscriptionIds: [a.id, b.id, c.id], createdBy: asel.id });
|
||
assert.deepEqual((await core.listPools(db)).find((p) => p.id === pool.id)!.subscriptionIds, [a.id, b.id, c.id]);
|
||
|
||
const p1 = await project({ turns: [[{ say: "ok" }]] });
|
||
const p2 = await project({ turns: [[{ say: "ok" }]] });
|
||
for (const p of [p1, p2]) await core.setProjectPool(db, (await core.getProject(db, p.key)).id, pool.id);
|
||
|
||
const s1 = await p1.start();
|
||
assert.equal((await p1.session(s1)).subscriptionId, a.id);
|
||
assert.equal((await p1.session(s1)).subscriptionName, "Claude A");
|
||
assert.equal((await p1.waitLog("started", (e) => e.ev === "start")).oauthToken, `…${TOKEN("Claude A").slice(-4)}`);
|
||
const s2 = await p2.start();
|
||
assert.equal((await p2.session(s2)).subscriptionId, b.id, "A is busy → B");
|
||
assert.equal((await core.listSubscriptions(db)).find((x) => x.id === a.id)!.activeSessions, 1);
|
||
|
||
// Provider asked explicitly: only the pool's Codex subscription, with its CODEX_HOME.
|
||
const p3 = await project({ turns: [[{ say: "ok" }]] });
|
||
await core.setProjectPool(db, (await core.getProject(db, p3.key)).id, pool.id);
|
||
const s3 = await p3.start({ provider: "codex" });
|
||
assert.equal((await p3.session(s3)).provider, "codex");
|
||
assert.equal((await p3.waitLog("started", (e) => e.ev === "start")).codexHome, runner.codexHome(c.id));
|
||
|
||
// Resume stays on the session's subscription.
|
||
await runner.stopSession(db, s1);
|
||
await runner.resumeSession(db, s1);
|
||
await waitFor("resumed run", async () => p1.log().filter((e) => e.ev === "start").length === 2);
|
||
assert.equal(p1.log().filter((e) => e.ev === "start")[1]!.oauthToken, `…${TOKEN("Claude A").slice(-4)}`);
|
||
for (const id of [s1, s2, s3]) await runner.stopSession(db, id);
|
||
});
|
||
|
||
test("выбор при запуске: раннер стартует на одной из отмеченных подписок", async () => {
|
||
const [x, y] = [await claudeSub("Pick X"), await claudeSub("Pick Y")];
|
||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||
const s = await p.start({ subscriptionIds: [y.id, x.id] });
|
||
assert.equal((await p.session(s)).subscriptionId, x.id, "first free by id among the ticked");
|
||
await runner.stopSession(db, s);
|
||
});
|
||
|
||
test("нет активных подписок → запуск отклонён; без пула — вход машины", async () => {
|
||
const bad = await claudeSub("Only bad", "bad");
|
||
await runner.checkSubscription(db, bad.id);
|
||
const pool = await core.createPool(db, { name: "Сломанный", subscriptionIds: [bad.id] });
|
||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||
await core.setProjectPool(db, (await core.getProject(db, p.key)).id, pool.id);
|
||
await assert.rejects(p.start(), /Нет активных подписок/);
|
||
await assert.rejects(p.start({ subscriptionIds: [bad.id] }), /Нет активных подписок/);
|
||
await assert.rejects(core.createPool(db, { name: "Сломанный", subscriptionIds: [] }), /уже есть/);
|
||
|
||
const free = await project({ turns: [[{ say: "ok" }]] });
|
||
const s = await free.start();
|
||
assert.equal((await free.session(s)).subscriptionId, null);
|
||
assert.equal((await free.waitLog("started", (e) => e.ev === "start")).oauthToken, null);
|
||
await runner.stopSession(db, s);
|
||
});
|
||
|
||
test("OpenCode: сессия в tmux с правилами из opencode.json и ключом подписки", async () => {
|
||
const oc = await runner.addSubscription(db, { provider: "opencode", name: "OC session", method: "api_key", secret: "mock-or-key-777", keyProvider: "openrouter", createdBy: asel.id });
|
||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||
const s = await p.start({ subscriptionIds: [oc.id] });
|
||
const start = await p.waitLog("started", (e) => e.ev === "start");
|
||
assert.equal(start.provider, "opencode");
|
||
assert.equal(start.apiKey, "…-777");
|
||
assert.ok((start.rulesChars as number) > 100, "rules from opencode.json instructions");
|
||
assert.equal((await p.session(s)).provider, "opencode");
|
||
await runner.stopSession(db, s);
|
||
});
|
||
|
||
test("удаление подписки и пула: сессии и проекты их забывают, каталог входа удалён", async () => {
|
||
const c = await runner.addSubscription(db, { provider: "codex", name: "To delete", method: "api_key", secret: "mock-openai-del", createdBy: asel.id });
|
||
const pool = await core.createPool(db, { name: "Временный", subscriptionIds: [c.id] });
|
||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||
const pid = (await core.getProject(db, p.key)).id;
|
||
await core.setProjectPool(db, pid, pool.id);
|
||
const s = await p.start();
|
||
assert.equal((await core.projectPool(db, pid))?.name, "Временный");
|
||
await runner.removeSubscription(db, c.id);
|
||
assert.equal((await p.session(s)).subscriptionId, null);
|
||
assert.ok(!existsSync(runner.subscriptionDir(c.id)));
|
||
assert.deepEqual((await core.listPools(db)).find((x) => x.id === pool.id)!.subscriptionIds, []);
|
||
await core.deletePool(db, pool.id);
|
||
assert.equal(await core.projectPool(db, pid), null);
|
||
await runner.stopSession(db, s);
|
||
});
|
||
});
|
||
|
||
describe("Перенос токена Claude из настроек", () => {
|
||
test("миграция: подписка «Claude — <login>» с тем же токеном, пул у проектов владельца", async () => {
|
||
const legacy = TOKEN("legacy");
|
||
const u = await core.upsertUserFromGitea(db, { id: 43, login: "mock-legacy" }, { access_token: "x" });
|
||
db.$client.prepare("UPDATE users SET claude_token_enc = ?, claude_token_set_at = ? WHERE id = ?").run(core.encrypt(legacy), Date.now(), u.id);
|
||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||
const pid = (await core.getProject(db, p.key)).id;
|
||
await core.setProjectOwner(db, pid, u.id);
|
||
|
||
// Re-run the data part of migration 0003 on this database.
|
||
const sql = readFileSync(join(ROOT, "packages/db/migrations/0003_subscriptions.sql"), "utf8");
|
||
const data = sql.split("--> statement-breakpoint").map((x) => x.trim()).filter((x) => /^(--.*\n)*\s*(INSERT|UPDATE)/.test(x));
|
||
assert.equal(data.length, 5);
|
||
for (const stmt of data) db.$client.exec(stmt);
|
||
|
||
const s = (await core.listSubscriptions(db)).find((x) => x.name === "Claude — mock-legacy")!;
|
||
assert.equal(s.status, "active");
|
||
assert.equal(s.provider, "claude");
|
||
assert.equal(core.subscriptionSecret(s), legacy);
|
||
assert.equal((await core.projectPool(db, pid))?.name, "Claude — mock-legacy");
|
||
assert.equal((await core.getUser(db, u.id))!.claudeTokenEnc, null);
|
||
assert.equal(await core.claudeTokenForProject(db, { id: pid }), legacy);
|
||
|
||
const sid = await p.start();
|
||
assert.equal((await p.waitLog("started", (e) => e.ev === "start")).oauthToken, `…${legacy.slice(-4)}`);
|
||
await runner.stopSession(db, sid);
|
||
});
|
||
});
|