mirror of
https://github.com/Louis-CFM/coucou.git
synced 2026-12-07 07:32:35 +09:00
The Cloud is now sold: Free (everything on the Mac, unchanged) and « Cloud · your key » at 9 €/month (the AI on the user's own Anthropic key). Solo, Pro and Max are listed as coming, until the credit offers open. Worker (billing.ts): the offers in one place (GET /v1/plans, public, so a price changes without an app update); Stripe Checkout and the customer portal, opened in the browser (the card never touches Coucou); the signed Stripe webhook keeps the subscription's state; a user's Mochis run in the Cloud only with an active subscription (past_due included while Stripe retries) or a login in COMP_LOGINS (Louis-CFM). Without STRIPE_SECRET_KEY, billing is off. Under the VAT franchise: no VAT, the invoice footer says « TVA non applicable, article 293 B du CGI »; STRIPE_TAX turns Stripe Tax on. The new user columns are added by the Worker itself. scripts/stripe-setup.mjs makes the price, the portal and the webhook, and pipes the webhook's secret straight into wrangler. brain: `cloud subscribe`, `cloud billing` (--json gives the URL to the app); `cloud status` carries the offer and the offers. App: the offers view (CloudPlans.swift, for the onboarding too), a « Choose your offer » step in the Cloud setup, the offer on the account card (renews / ends / payment failed, Manage, See the offers); the switch to move a Mochi needs the offer. 28 strings in the 16 languages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LJm3SRL9k3gBPaVtfPhwcT
348 lines
23 KiB
TypeScript
348 lines
23 KiB
TypeScript
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
|
import { memoryD1 } from "./d1.js";
|
|
import worker from "../src/index.js";
|
|
import { collectRuns, type Env } from "../src/engine.js";
|
|
import { appJwt, open, seal, sha256, verifyGitHubSignature } from "../src/crypto.js";
|
|
|
|
const KEK = btoa(String.fromCharCode(...new Uint8Array(32).map((_, i) => i + 1)));
|
|
const SECRET = "webhook-secret";
|
|
let env: Env;
|
|
let pending: Promise<unknown>[];
|
|
const ctx = () => ({ waitUntil: (p: Promise<unknown>) => { pending.push(p); }, passThroughOnException() {} }) as unknown as ExecutionContext;
|
|
|
|
/** Every outside call goes through here: GitHub and Anthropic, answered by route. */
|
|
let calls: { method: string; url: string; body?: any; headers: Record<string, string> }[];
|
|
let routes: [RegExp, (body: any) => unknown][];
|
|
function fakeFetch(input: RequestInfo | URL, init?: RequestInit) {
|
|
const url = String(input);
|
|
const method = init?.method ?? "GET";
|
|
const body = init?.body ? (() => { try { return JSON.parse(String(init.body)); } catch { return init.body; } })() : undefined;
|
|
calls.push({ method, url, body, headers: (init?.headers ?? {}) as Record<string, string> });
|
|
const hit = routes.find(([re]) => re.test(`${method} ${url}`));
|
|
if (!hit) return Promise.resolve(new Response(`no route for ${method} ${url}`, { status: 404 }));
|
|
const out = hit[1](body);
|
|
return Promise.resolve(typeof out === "string" ? new Response(out) : new Response(JSON.stringify(out), { headers: { "content-type": "application/json" } }));
|
|
}
|
|
|
|
async function pemKey(): Promise<string> {
|
|
const pair = await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["sign", "verify"]);
|
|
const der = new Uint8Array(await crypto.subtle.exportKey("pkcs8", (pair as CryptoKeyPair).privateKey));
|
|
return `-----BEGIN PRIVATE KEY-----\n${btoa(String.fromCharCode(...der))}\n-----END PRIVATE KEY-----`;
|
|
}
|
|
|
|
async function hmac(body: string): Promise<string> {
|
|
const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(SECRET), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(body)));
|
|
return "sha256=" + [...sig].map(b => b.toString(16).padStart(2, "0")).join("");
|
|
}
|
|
|
|
const call = (path: string, init: RequestInit = {}) => worker.fetch(new Request(`https://cloud.test${path}`, init), env, ctx());
|
|
async function hook(event: string, payload: unknown, signed = true) {
|
|
const body = JSON.stringify(payload);
|
|
return worker.fetch(new Request("https://cloud.test/github/webhook", {
|
|
method: "POST", body, headers: { "x-github-event": event, "x-hub-signature-256": signed ? await hmac(body) : "sha256=00" },
|
|
}), env, ctx());
|
|
}
|
|
|
|
const PR = {
|
|
action: "opened",
|
|
installation: { id: 77 },
|
|
repository: { full_name: "Louis-CFM/coucou", private: false },
|
|
pull_request: { number: 1148, title: "Android notif", body: "Live Updates", html_url: "https://github.com/Louis-CFM/coucou/pull/1148", draft: false, head: { sha: "abc123def4567890" }, base: { ref: "main" } },
|
|
};
|
|
const PATCH = "diff --git a/app/Main.kt b/app/Main.kt\n@@ -1 +1 @@\n-val a = 1\n+val a = 2\ndiff --git a/package-lock.json b/package-lock.json\n@@ -1 +1 @@\n-{}\n+{\"big\":true}\n";
|
|
|
|
beforeEach(async () => {
|
|
calls = []; pending = [];
|
|
env = { DB: memoryD1(), GITHUB_APP_ID: "123", GITHUB_APP_PRIVATE_KEY: await pemKey(), GITHUB_WEBHOOK_SECRET: SECRET, KEY_ENCRYPTION_KEY: KEK };
|
|
routes = [
|
|
[/GET https:\/\/api\.github\.com\/user$/, () => ({ id: 42, login: "Louis-CFM" })],
|
|
[/GET https:\/\/api\.github\.com\/user\/installations/, () => ({ installations: [{ id: 77, account: { login: "Louis-CFM" } }] })],
|
|
[/GET https:\/\/api\.anthropic\.com\/v1\/models/, () => ({ data: [] })],
|
|
[/POST https:\/\/api\.github\.com\/app\/installations\/77\/access_tokens/, () => ({ token: "ghs_inst" })],
|
|
[/GET https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/pulls\/1148\/files/, () => [{ filename: "app/Main.kt" }, { filename: "package-lock.json" }]],
|
|
[/GET https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/pulls\/1148$/, () => PATCH],
|
|
[/POST https:\/\/api\.anthropic\.com\/v1\/agents$/, () => ({ id: "agent_1" })],
|
|
[/POST https:\/\/api\.anthropic\.com\/v1\/environments$/, () => ({ id: "env_1" })],
|
|
[/POST https:\/\/api\.anthropic\.com\/v1\/sessions$/, () => ({ id: "sesn_1", status: "running" })],
|
|
[/GET https:\/\/api\.anthropic\.com\/v1\/sessions\/sesn_1$/, () => ({ id: "sesn_1", status: "idle", usage: { list_cost: { amount: "17", currency: "USD" }, active_seconds: 78 } })],
|
|
[/GET https:\/\/api\.anthropic\.com\/v1\/sessions\/sesn_1\/events/, () => ({ data: [
|
|
{ type: "agent.tool_use", name: "bash" }, { type: "span.model_request_end" },
|
|
{ type: "agent.message", content: [{ type: "text", text: "## Summary\nGood.\n\n## Notes pour moi\nprivé" }] },
|
|
{ type: "session.status_idle", stop_reason: { type: "end_turn" } },
|
|
], next_page: null })],
|
|
[/POST https:\/\/api\.anthropic\.com\/v1\/sessions\/sesn_1\/archive/, () => ({})],
|
|
[/POST https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/pulls\/1148\/reviews/, () => ({ html_url: "https://github.com/Louis-CFM/coucou/pull/1148#pullrequestreview-1" })],
|
|
];
|
|
vi.stubGlobal("fetch", fakeFetch);
|
|
});
|
|
afterEach(() => vi.unstubAllGlobals());
|
|
|
|
async function signIn(): Promise<string> {
|
|
const r = await call("/v1/login", { method: "POST", body: JSON.stringify({ github_token: "ghu_user" }) });
|
|
const { token } = (await r.json()) as { token: string };
|
|
const auth = { authorization: `Bearer ${token}` };
|
|
expect((await call("/v1/anthropic-key", { method: "PUT", headers: auth, body: JSON.stringify({ key: "sk-ant-test", language: "fr" }) })).status).toBe(200);
|
|
expect((await call("/v1/mochis", { method: "PUT", headers: auth, body: JSON.stringify({ mochis: [
|
|
{ id: "pr-reviewer", name: "PR Reviewer", repo: "Louis-CFM/coucou", trigger: "pr-opened", instructions: "Relis la PR.", model: "sonnet", budget_cents: 100, enabled: true },
|
|
] }) })).status).toBe(200);
|
|
return token;
|
|
}
|
|
|
|
describe("crypto", () => {
|
|
it("seals the Anthropic key and opens it again; checks GitHub's signature; signs an app JWT", async () => {
|
|
const sealed = await seal(KEK, "sk-ant-secret");
|
|
expect(sealed).not.toContain("secret");
|
|
expect(await open(KEK, sealed)).toBe("sk-ant-secret");
|
|
expect(await verifyGitHubSignature(SECRET, "{}", await hmac("{}"))).toBe(true);
|
|
expect(await verifyGitHubSignature(SECRET, "{}", "sha256=" + "0".repeat(64))).toBe(false);
|
|
expect(await verifyGitHubSignature(SECRET, "{}", null)).toBe(false);
|
|
const jwt = await appJwt("123", env.GITHUB_APP_PRIVATE_KEY, 1_800_000_000);
|
|
expect(JSON.parse(atob(jwt.split(".")[1]!.replace(/-/g, "+").replace(/_/g, "/")))).toEqual({ iat: 1_799_999_940, exp: 1_800_000_540, iss: "123" });
|
|
});
|
|
});
|
|
|
|
describe("Coucou Cloud", () => {
|
|
it("refuses unsigned webhooks and unknown tokens", async () => {
|
|
expect((await hook("pull_request", PR, false)).status).toBe(401);
|
|
expect((await call("/v1/runs", { headers: { authorization: `Bearer ${"a".repeat(64)}` } })).status).toBe(401);
|
|
});
|
|
|
|
it("signs in from the Mac, keeps only the token's hash and a sealed key, finds the installation", async () => {
|
|
const token = await signIn();
|
|
const u = await env.DB.prepare("SELECT * FROM users").first<any>();
|
|
expect(u.token_hash).toBe(await sha256(token));
|
|
expect(u.anthropic_key).toMatch(/^v1\./);
|
|
expect(u.anthropic_key).not.toContain("sk-ant");
|
|
expect(await env.DB.prepare("SELECT * FROM installations").first()).toEqual({ id: 77, user_id: 1, account: "Louis-CFM" });
|
|
const me = await call("/v1/me", { headers: { authorization: `Bearer ${token}` } });
|
|
expect(await me.json()).toMatchObject({ login: "Louis-CFM", has_key: true, installations: ["Louis-CFM"], mochis: 1, plan: "free", entitled: true, billing: false });
|
|
});
|
|
|
|
it("a PR starts a session on the user's key, on the PR's commit, with the diff; collected, the review waits for a click", async () => {
|
|
const token = await signIn();
|
|
calls = [];
|
|
const r = await hook("pull_request", PR);
|
|
expect(await r.json()).toEqual({ ok: true, runs: 1 });
|
|
await Promise.all(pending);
|
|
|
|
const session = calls.find(c => c.method === "POST" && c.url.endsWith("/v1/sessions"))!;
|
|
expect(session.headers["x-api-key"]).toBe("sk-ant-test");
|
|
expect(session.body.resources[0]).toEqual({ type: "github_repository", url: "https://github.com/Louis-CFM/coucou", mount_path: "/workspace/repo", checkout: { type: "commit", sha: "abc123def4567890" } });
|
|
expect(session.body.budget.max_list_cost.amount).toBe("100");
|
|
const prompt: string = session.body.initial_events[0].content[0].text;
|
|
expect(prompt).toContain("Relis la PR.");
|
|
expect(prompt).toContain("+val a = 2");
|
|
expect(prompt).not.toContain('"big":true');
|
|
expect(prompt).toContain("git fetch origin pull/1148/head");
|
|
const agent = calls.find(c => c.url.endsWith("/v1/agents"))!;
|
|
expect(agent.body.model).toBe("claude-sonnet-5-5");
|
|
|
|
// the same delivery again: no second run
|
|
await hook("pull_request", PR); await Promise.all(pending);
|
|
expect(calls.filter(c => c.url.endsWith("/v1/sessions")).length).toBe(1);
|
|
|
|
expect(await collectRuns(env)).toBe(1);
|
|
const auth = { authorization: `Bearer ${token}` };
|
|
const { runs } = (await (await call("/v1/runs", { headers: auth })).json()) as { runs: any[] };
|
|
expect(runs).toHaveLength(1);
|
|
expect(runs[0]).toMatchObject({ status: "done", cost_usd: 0.17, turns: 1, proposal_state: "waiting", item_number: 1148 });
|
|
expect(JSON.parse(runs[0].proposal).body).toBe("## Summary\nGood.");
|
|
|
|
const applied = await call(`/v1/runs/${runs[0].id}/apply`, { method: "POST", headers: auth });
|
|
expect(await applied.json()).toEqual({ url: "https://github.com/Louis-CFM/coucou/pull/1148#pullrequestreview-1" });
|
|
const review = calls.find(c => c.url.endsWith("/pulls/1148/reviews"))!;
|
|
expect(review.body).toEqual({ body: "## Summary\nGood.", event: "COMMENT" });
|
|
expect(review.headers.authorization).toBe("Bearer ghs_inst");
|
|
// applied once only
|
|
expect((await call(`/v1/runs/${runs[0].id}/apply`, { method: "POST", headers: auth })).status).toBe(409);
|
|
});
|
|
|
|
it("an autonomous Mochi posts its review on its own when the run is collected", async () => {
|
|
const token = await signIn();
|
|
const auth = { authorization: `Bearer ${token}` };
|
|
await call("/v1/mochis", { method: "PUT", headers: auth, body: JSON.stringify({ mochis: [
|
|
{ id: "pr-reviewer", name: "PR Reviewer", repo: "Louis-CFM/coucou", trigger: "pr-opened", instructions: "Relis la PR.", model: "sonnet", budget_cents: 100, enabled: true, autonomous: true },
|
|
] }) });
|
|
await hook("pull_request", PR); await Promise.all(pending);
|
|
calls = [];
|
|
expect(await collectRuns(env)).toBe(1);
|
|
expect(calls.find(c => c.url.endsWith("/pulls/1148/reviews"))!.body).toEqual({ body: "## Summary\nGood.", event: "COMMENT" });
|
|
const { runs } = (await (await call("/v1/runs", { headers: auth })).json()) as { runs: any[] };
|
|
expect(runs[0]).toMatchObject({ proposal_state: "applied", auto: 1, proposal_url: "https://github.com/Louis-CFM/coucou/pull/1148#pullrequestreview-1" });
|
|
});
|
|
|
|
it("an autonomous post GitHub refuses waits for the click instead", async () => {
|
|
const token = await signIn();
|
|
const auth = { authorization: `Bearer ${token}` };
|
|
await call("/v1/mochis", { method: "PUT", headers: auth, body: JSON.stringify({ mochis: [
|
|
{ id: "pr-reviewer", name: "PR Reviewer", repo: "Louis-CFM/coucou", trigger: "pr-opened", instructions: "Relis la PR.", model: "sonnet", budget_cents: 100, enabled: true, autonomous: true },
|
|
] }) });
|
|
await hook("pull_request", PR); await Promise.all(pending);
|
|
const ok = routes.pop()!;
|
|
routes.push([/POST https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/pulls\/1148\/reviews/, () => { throw new Error("HTTP 403"); }]);
|
|
await collectRuns(env);
|
|
let { runs } = (await (await call("/v1/runs", { headers: auth })).json()) as { runs: any[] };
|
|
expect(runs[0]).toMatchObject({ proposal_state: "failed", auto: 1 });
|
|
routes.pop(); routes.push(ok);
|
|
expect((await call(`/v1/runs/${runs[0].id}/apply`, { method: "POST", headers: auth })).status).toBe(200);
|
|
({ runs } = (await (await call("/v1/runs", { headers: auth })).json()) as { runs: any[] });
|
|
expect(runs[0].proposal_state).toBe("applied");
|
|
});
|
|
|
|
it("adds the new columns to a database made before them", async () => {
|
|
const { ensureSchema } = await import("../src/engine.js");
|
|
const old = memoryD1("CREATE TABLE users (id INTEGER PRIMARY KEY, login TEXT); CREATE TABLE mochis (user_id INTEGER, id TEXT, enabled INTEGER); CREATE TABLE runs (id TEXT PRIMARY KEY, proposal_state TEXT);");
|
|
await ensureSchema({ ...env, DB: old });
|
|
const cols = async (t: string) => ((await old.prepare(`PRAGMA table_info(${t})`).all<{ name: string }>()).results ?? []).map(c => c.name);
|
|
expect(await cols("mochis")).toContain("autonomous");
|
|
expect(await cols("runs")).toContain("auto");
|
|
expect(await cols("users")).toEqual(expect.arrayContaining(["stripe_customer_id", "plan", "plan_status", "plan_renews_at", "plan_cancels"]));
|
|
});
|
|
|
|
it("does nothing for drafts, closed PRs, or a repo with no Cloud Mochi", async () => {
|
|
await signIn();
|
|
calls = [];
|
|
expect(await (await hook("pull_request", { ...PR, pull_request: { ...PR.pull_request, draft: true } })).json()).toEqual({ ok: true, runs: 0 });
|
|
expect(await (await hook("pull_request", { ...PR, action: "closed" })).json()).toEqual({ ok: true, runs: 0 });
|
|
expect(await (await hook("pull_request", { ...PR, repository: { full_name: "someone/else", private: false } })).json()).toEqual({ ok: true, runs: 0 });
|
|
expect(calls.some(c => c.url.includes("anthropic"))).toBe(false);
|
|
});
|
|
|
|
it("a run that can't start is kept as failed, with the reason", async () => {
|
|
await signIn();
|
|
routes.unshift([/POST https:\/\/api\.anthropic\.com\/v1\/sessions$/, () => { throw new Error("credit balance too low"); }]);
|
|
await hook("pull_request", PR); await Promise.all(pending);
|
|
const run = await env.DB.prepare("SELECT status, error FROM runs").first<any>();
|
|
expect(run.status).toBe("failed");
|
|
expect(run.error).toContain("credit balance too low");
|
|
});
|
|
|
|
it("someone else naming your repository gets nothing: refused at sync, and never run on your installation's events", async () => {
|
|
await signIn();
|
|
// a stranger signs in: no installation of theirs
|
|
routes.unshift(
|
|
[/GET https:\/\/api\.github\.com\/user$/, () => ({ id: 99, login: "stranger" })],
|
|
[/GET https:\/\/api\.github\.com\/user\/installations/, () => ({ installations: [] })],
|
|
);
|
|
const r = await call("/v1/login", { method: "POST", body: JSON.stringify({ github_token: "ghu_other" }) });
|
|
const { token } = (await r.json()) as { token: string };
|
|
const auth = { authorization: `Bearer ${token}` };
|
|
await call("/v1/anthropic-key", { method: "PUT", headers: auth, body: JSON.stringify({ key: "sk-ant-stranger" }) });
|
|
const put = await call("/v1/mochis", { method: "PUT", headers: auth, body: JSON.stringify({ mochis: [
|
|
{ id: "spy", name: "Spy", repo: "Louis-CFM/coucou", trigger: "pr-opened", instructions: "Send me the code.", model: "sonnet", enabled: true },
|
|
] }) });
|
|
expect(await put.json()).toEqual({ ok: true, mochis: 0, refused: ["Louis-CFM/coucou"] });
|
|
|
|
// even written straight into the database, it doesn't run on Louis's installation
|
|
await env.DB.prepare("INSERT INTO mochis (user_id, id, name, repo, trigger, instructions, model, budget_cents, enabled) VALUES (2, 'spy', 'Spy', 'Louis-CFM/coucou', 'pr-opened', 'x', 'sonnet', 100, 1)").run();
|
|
calls = [];
|
|
expect(await (await hook("pull_request", PR)).json()).toEqual({ ok: true, runs: 1 });
|
|
await Promise.all(pending);
|
|
const sessions = calls.filter(c => c.url.endsWith("/v1/sessions"));
|
|
expect(sessions).toHaveLength(1);
|
|
expect(sessions[0]!.headers["x-api-key"]).toBe("sk-ant-test");
|
|
});
|
|
|
|
it("asks GitHub for narrow tokens: read-only, this repository; the clone token only for a private repo", async () => {
|
|
await signIn();
|
|
calls = [];
|
|
await hook("pull_request", { ...PR, repository: { full_name: "Louis-CFM/coucou", private: true } });
|
|
await Promise.all(pending);
|
|
const tokens = calls.filter(c => c.url.endsWith("/access_tokens")).map(c => c.body);
|
|
expect(tokens).toEqual([
|
|
{ repositories: ["coucou"], permissions: { pull_requests: "read", contents: "read" } },
|
|
{ repositories: ["coucou"], permissions: { contents: "read" } },
|
|
]);
|
|
const session = calls.find(c => c.url.endsWith("/v1/sessions"))!;
|
|
expect(session.body.resources[0].authorization_token).toBe("ghs_inst");
|
|
});
|
|
});
|
|
|
|
describe("billing", () => {
|
|
const WH = "whsec_test";
|
|
async function stripeHook(event: unknown, secret = WH) {
|
|
const body = JSON.stringify(event);
|
|
const t = Math.floor(Date.now() / 1000);
|
|
const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
const sig = [...new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${t}.${body}`)))].map(b => b.toString(16).padStart(2, "0")).join("");
|
|
return worker.fetch(new Request("https://cloud.test/stripe/webhook", { method: "POST", body, headers: { "stripe-signature": `t=${t},v1=${sig}` } }), env, ctx());
|
|
}
|
|
const sub = (status: string, extra: object = {}) => ({ id: "sub_1", customer: "cus_1", status, cancel_at_period_end: false, metadata: { plan: "byok" },
|
|
items: { data: [{ current_period_end: 1_801_000_000, price: { lookup_key: "coucou_cloud_byok_monthly" } }] }, ...extra });
|
|
|
|
beforeEach(() => {
|
|
env = { ...env, STRIPE_SECRET_KEY: "sk_test_x", STRIPE_WEBHOOK_SECRET: WH, INVOICE_FOOTER: "TVA non applicable, article 293 B du CGI" };
|
|
routes.push(
|
|
[/POST https:\/\/api\.stripe\.com\/v1\/customers$/, () => ({ id: "cus_1" })],
|
|
[/GET https:\/\/api\.stripe\.com\/v1\/prices\?/, () => ({ data: [{ id: "price_byok" }] })],
|
|
[/POST https:\/\/api\.stripe\.com\/v1\/checkout\/sessions$/, () => ({ url: "https://checkout.stripe.com/c/pay/cs_1" })],
|
|
[/GET https:\/\/api\.stripe\.com\/v1\/billing_portal\/configurations/, () => ({ data: [{ id: "bpc_1", active: true, metadata: { coucou: "cloud" } }] })],
|
|
[/POST https:\/\/api\.stripe\.com\/v1\/billing_portal\/sessions$/, () => ({ url: "https://billing.stripe.com/p/session_1" })],
|
|
[/GET https:\/\/api\.stripe\.com\/v1\/subscriptions\/sub_1$/, () => sub("active")],
|
|
);
|
|
});
|
|
|
|
it("lists the offers to anyone, the credit ones not yet open", async () => {
|
|
const { plans } = (await (await call("/v1/plans")).json()) as { plans: any[] };
|
|
expect(plans.map(p => `${p.id}:${p.available}`)).toEqual(["free:true", "byok:true", "solo:false", "pro:false", "max:false"]);
|
|
expect(plans.find(p => p.id === "byok")).toMatchObject({ monthly: 900, currency: "eur", credits: null });
|
|
expect(plans[1].lookup).toBeUndefined();
|
|
});
|
|
|
|
it("no subscription, no Cloud; Checkout, Stripe's word, then the Cloud; cancelled, back to the Mac", async () => {
|
|
const r = await call("/v1/login", { method: "POST", body: JSON.stringify({ github_token: "ghu_user" }) });
|
|
const { token } = (await r.json()) as { token: string };
|
|
const auth = { authorization: `Bearer ${token}` };
|
|
await call("/v1/anthropic-key", { method: "PUT", headers: auth, body: JSON.stringify({ key: "sk-ant-test" }) });
|
|
const mochis = JSON.stringify({ mochis: [{ id: "pr-reviewer", name: "PR Reviewer", repo: "Louis-CFM/coucou", trigger: "pr-opened", instructions: "x", model: "sonnet", enabled: true }] });
|
|
expect((await call("/v1/mochis", { method: "PUT", headers: auth, body: mochis })).status).toBe(402);
|
|
expect(await (await call("/v1/me", { headers: auth })).json()).toMatchObject({ plan: "free", entitled: false, billing: true });
|
|
|
|
const co = await call("/v1/billing/checkout", { method: "POST", headers: auth, body: JSON.stringify({ plan: "byok" }) });
|
|
expect(await co.json()).toEqual({ url: "https://checkout.stripe.com/c/pay/cs_1" });
|
|
const customer = calls.find(c => c.url.endsWith("/v1/customers"))!;
|
|
expect(String(customer.body)).toContain(encodeURIComponent("invoice_settings[footer]"));
|
|
const session = new URLSearchParams(String(calls.find(c => c.url.endsWith("/checkout/sessions"))!.body));
|
|
expect(session.get("mode")).toBe("subscription");
|
|
expect(session.get("customer")).toBe("cus_1");
|
|
expect(session.get("line_items[0][price]")).toBe("price_byok");
|
|
expect(session.get("client_reference_id")).toBe("1");
|
|
expect(session.get("automatic_tax[enabled]")).toBe("false");
|
|
expect(session.get("success_url")).toBe("https://cloud.test/billing/done");
|
|
// the credit offers wait
|
|
expect((await call("/v1/billing/checkout", { method: "POST", headers: auth, body: JSON.stringify({ plan: "max" }) })).status).toBe(400);
|
|
|
|
// a forged event changes nothing
|
|
expect((await stripeHook({ type: "customer.subscription.created", data: { object: sub("active") } }, "whsec_other")).status).toBe(400);
|
|
expect(await (await call("/v1/me", { headers: auth })).json()).toMatchObject({ entitled: false });
|
|
|
|
expect(await (await stripeHook({ type: "checkout.session.completed", data: { object: { mode: "subscription", subscription: "sub_1", customer: "cus_1", client_reference_id: "1" } } })).json()).toEqual({ ok: true, did: "subscribed" });
|
|
expect(await (await call("/v1/me", { headers: auth })).json()).toMatchObject({ plan: "byok", status: "active", entitled: true, renews_at: new Date(1_801_000_000_000).toISOString(), cancels: false });
|
|
expect((await call("/v1/mochis", { method: "PUT", headers: auth, body: mochis })).status).toBe(200);
|
|
expect(await (await hook("pull_request", PR)).json()).toEqual({ ok: true, runs: 1 });
|
|
await Promise.all(pending);
|
|
|
|
expect(await (await call("/v1/billing/portal", { method: "POST", headers: auth })).json()).toEqual({ url: "https://billing.stripe.com/p/session_1" });
|
|
expect(new URLSearchParams(String(calls.find(c => c.url.endsWith("/billing_portal/sessions"))!.body)).get("configuration")).toBe("bpc_1");
|
|
|
|
await stripeHook({ type: "customer.subscription.deleted", data: { object: sub("canceled") } });
|
|
expect(await (await call("/v1/me", { headers: auth })).json()).toMatchObject({ plan: "free", entitled: false });
|
|
expect(await (await hook("pull_request", { ...PR, pull_request: { ...PR.pull_request, head: { sha: "fff" } } })).json()).toEqual({ ok: true, runs: 0 });
|
|
// bringing them back is always allowed
|
|
expect((await call("/v1/mochis", { method: "PUT", headers: auth, body: JSON.stringify({ mochis: [] }) })).status).toBe(200);
|
|
});
|
|
|
|
it("the logins the Cloud is offered to need no subscription", async () => {
|
|
env = { ...env, COMP_LOGINS: "someone, louis-cfm" };
|
|
const token = await signIn();
|
|
expect(await (await call("/v1/me", { headers: { authorization: `Bearer ${token}` } })).json()).toMatchObject({ plan: "comp", entitled: true });
|
|
});
|
|
|
|
it("the page Stripe sends the browser back to", async () => {
|
|
const r = await call("/billing/done");
|
|
expect(r.headers.get("content-type")).toContain("text/html");
|
|
expect(await r.text()).toContain("Coucou");
|
|
});
|
|
});
|