Files
agents-marketplace/tests/unit/buyer-server-config.test.ts
david facf07c35f buyer: single-operator password gate (BUYER_PASSWORD + signed session cookie)
Adds an Express requireAuth middleware on /v1/* + the SPA shell and a
Vite/React login screen so anyone who reaches mp-buyers.* must authenticate
before driving the operator's wallet via /v1/submit-prompt or /v1/accept.

Why: the buyer-app sits on a public HTTP port and signs txs with a
server-held private key. Until now the only gate was network reachability.

Mechanics:
- BUYER_PASSWORD + SESSION_SECRET (>=32 chars) loaded by config.ts and
  surfaced as createApp() deps. Production refuses to start without both.
- buyer/src/auth.ts: HMAC-SHA256 signed buyer_session cookie (HttpOnly,
  SameSite=Lax, Path=/, optional Secure), 7-day rolling expiry,
  timing-safe password compare, in-memory 5/15-min per-IP rate limiter.
- /v1/auth/{login,logout,whoami}. Login is rate-limited; 6th wrong
  attempt returns 429 + Retry-After. Success resets the bucket.
- SPA boot block (__BUYER_BOOT__ injected by server.ts) is gated by the
  same cookie so the buyer's address never reaches an unauthenticated
  browser.
- New <AuthProvider>/<RequireAuth> in buyer/src/ui/state/AuthContext.tsx
  probes /v1/auth/whoami on mount and a scoped window.fetch patch drops
  to the login screen on any mid-session 401 from /v1/* (excluding
  /v1/auth/* so wrong-password 401s stay local to <Login>).
- Tailwind login card at buyer/src/ui/pages/Login.tsx. App.tsx wraps in
  <RequireAuth> and adds a "Sign out" button in the nav.

Tests: tests/unit/buyer-server-auth.test.ts covers sign/verify, rate
limiter, cookie helpers, login flow (400/401/204/429), whoami
(no-cookie/valid/tampered/expired), rolling renewal, logout, gated
/v1/*, /healthz still open, and the no-auth-deps construction shape.
Updated buyer-server-config + buyer-ui-smoke for the new required env
vars and the AuthProvider wrap.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 10:52:01 +02:00

121 lines
4.6 KiB
TypeScript

/**
* buyer-server-config.test.ts — RED phase (M1-E)
*
* Category H: Server / config (~5 tests)
*
* All tests FAIL until M1-E-green.
*/
import { describe, it, expect } from "vitest";
import { join } from "path";
import { loadConfig } from "../../buyer/src/config.js";
import { createApp } from "../../buyer/src/server.js";
// ─── loadConfig tests ─────────────────────────────────────────────────────────
describe("loadConfig(env)", () => {
const VALID_ENV = {
BUYER_PRIV_KEY_HEX: "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae3942",
INDEXER_URL: "http://localhost:3001",
BUYER_PORT: "3002",
NETWORK_ID: "0",
BUYER_PASSWORD: "hunter2",
SESSION_SECRET: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
};
it("returns a BuyerConfig when all required env vars are present", () => {
const config = loadConfig(VALID_ENV);
expect(config.privKeyHex).toBe(VALID_ENV.BUYER_PRIV_KEY_HEX);
expect(config.indexerUrl).toBe(VALID_ENV.INDEXER_URL);
expect(config.port).toBe(3002);
expect(config.networkId).toBe(0);
expect(config.password).toBe(VALID_ENV.BUYER_PASSWORD);
expect(config.sessionSecret).toBe(VALID_ENV.SESSION_SECRET);
expect(config.cookieSecure).toBe(true);
});
it("throws when BUYER_PRIV_KEY_HEX is missing", () => {
const env = { ...VALID_ENV };
delete (env as Record<string, string | undefined>).BUYER_PRIV_KEY_HEX;
expect(() => loadConfig(env)).toThrow();
});
it("throws when INDEXER_URL is missing", () => {
const env = { ...VALID_ENV };
delete (env as Record<string, string | undefined>).INDEXER_URL;
expect(() => loadConfig(env)).toThrow();
});
it("defaults BUYER_PORT to 3002 when not provided", () => {
const env = { ...VALID_ENV };
delete (env as Record<string, string | undefined>).BUYER_PORT;
const config = loadConfig(env);
expect(config.port).toBe(3002);
});
it("defaults NETWORK_ID to 0 (testnet) when not provided", () => {
const env = { ...VALID_ENV };
delete (env as Record<string, string | undefined>).NETWORK_ID;
const config = loadConfig(env);
expect(config.networkId).toBe(0);
});
it("throws when BUYER_PASSWORD is missing", () => {
const env = { ...VALID_ENV };
delete (env as Record<string, string | undefined>).BUYER_PASSWORD;
expect(() => loadConfig(env)).toThrow(/BUYER_PASSWORD/);
});
it("throws when SESSION_SECRET is missing", () => {
const env = { ...VALID_ENV };
delete (env as Record<string, string | undefined>).SESSION_SECRET;
expect(() => loadConfig(env)).toThrow(/SESSION_SECRET/);
});
it("throws when SESSION_SECRET is shorter than 32 chars", () => {
const env = { ...VALID_ENV, SESSION_SECRET: "too-short" };
expect(() => loadConfig(env)).toThrow(/SESSION_SECRET/);
});
it('honours COOKIE_SECURE="0" for plain-HTTP loopback dev', () => {
const env = { ...VALID_ENV, COOKIE_SECURE: "0" };
const config = loadConfig(env);
expect(config.cookieSecure).toBe(false);
});
it("throws when COOKIE_SECURE is not 0 or 1", () => {
const env = { ...VALID_ENV, COOKIE_SECURE: "true" };
expect(() => loadConfig(env)).toThrow(/COOKIE_SECURE/);
});
});
// ─── createApp tests ──────────────────────────────────────────────────────────
describe("createApp(deps)", () => {
it("GET /healthz returns { ok: true } with status 200", async () => {
const app = createApp({});
// Use supertest-style in-process request
const { default: request } = await import("supertest");
const res = await request(app).get("/healthz");
expect(res.status).toBe(200);
expect(res.body).toMatchObject({ ok: true });
});
it("serves static dist/ directory when distPath exists", async () => {
// The dist path doesn't exist yet; createApp should mount it without crashing.
// We test that the app at least starts up with the distPath option.
const app = createApp({ distPath: "/tmp/nonexistent-dist" });
const { default: request } = await import("supertest");
// /healthz still works regardless of distPath
const res = await request(app).get("/healthz");
expect(res.status).toBe(200);
});
it("returns 404 for unknown routes when dist/ is not set", async () => {
const app = createApp({});
const { default: request } = await import("supertest");
const res = await request(app).get("/this-page-does-not-exist");
expect(res.status).toBe(404);
});
});