agentcomply / tree / cre/screen-before-pay/main.test.ts ยท raw (this view has old GitHub links rewritten for the mirror; raw is byte-exact)
import { describe, expect, test } from "bun:test";
import { initWorkflow, screenPayment, type Config } from "./main";

const config: Config = { schedule: "0 */10 * * * *", agentcomplyUrl: "https://agentcomply.example", demoPayment: { payTo: "vitalik.eth" } };
const body = (o: unknown) => new TextEncoder().encode(typeof o === "string" ? o : JSON.stringify(o));
// Fake HTTPSendRequester: returns canned responses for /v1/screen and /v1/verify.
const fake = (screen: { statusCode: number; body: Uint8Array }, verifyValid: boolean) => ({
  sendRequest: (req: any) => ({ result: () => (req.url.endsWith("/v1/verify") ? { statusCode: 200, body: body({ valid: verifyValid }) } : screen) }),
}) as any;
const receipt = { receipt_id: "r1", integrity: { hash: "ab".repeat(32) }, chain: { seq: 3 } };

describe("screenPayment (fail-closed)", () => {
  test("ok + verified receipt passes through", () => {
    const s = screenPayment(fake({ statusCode: 200, body: body({ verdict: "ok", action: "proceed", receipt }) }, true), config, { payTo: "vitalik.eth" });
    expect(s).toEqual({ status: 200, verdict: "ok", action: "proceed", receiptId: "r1", receiptHash: "ab".repeat(32), seq: 3, signatureValid: true });
  });
  test("non-JSON / upstream error => caution/hold, never ok", () => {
    const s = screenPayment(fake({ statusCode: 502, body: body("<html>bad gateway</html>") }, true), config, { payTo: "x" });
    expect([s.verdict, s.action, s.signatureValid]).toEqual(["caution", "hold", false]);
  });
  test("503 ledger_busy without receipt => caution/hold", () => {
    const s = screenPayment(fake({ statusCode: 503, body: body({ error: "ledger_busy", verdict: "caution" }) }, true), config, { payTo: "x" });
    expect([s.verdict, s.action]).toEqual(["caution", "hold"]);
  });
  test("receipt that fails /v1/verify is flagged", () => {
    const s = screenPayment(fake({ statusCode: 200, body: body({ verdict: "ok", action: "proceed", receipt }) }, false), config, { payTo: "x" });
    expect(s.signatureValid).toBe(false);
  });
  test("screen call uses the shared cache so a DON run issues one receipt", () => {
    let seen: any; const r = { sendRequest: (req: any) => { if (!seen) seen = req; return { result: () => ({ statusCode: 200, body: body({ verdict: "ok", action: "proceed", receipt }) }) }; } } as any;
    screenPayment(r, config, { payTo: "x" });
    expect(seen.url).toBe("https://agentcomply.example/v1/screen");
    expect(seen.cacheSettings.store).toBe(true);
  });
});

describe("initWorkflow", () => {
  test("cron + HTTP handlers", () => {
    const h = initWorkflow(config);
    expect(h).toHaveLength(2);
    expect((h[0].trigger as any).config.schedule).toBe(config.schedule);
  });
});

agentgate-source: code mirror on Cloudflare Pages. All repos