Migrate logicsrc-web from Vite SPA to Next.js 16 App Router

Replaces the Vite single-page app + custom Node server.js with a Next.js
16.2.6 App Router app.

- proxy.ts (src/proxy.ts): www.logicsrc.com -> logicsrc.com 301 over https,
  preserving path + query (the original request, now via Next 16 Proxy).
- One SSR page via an optional catch-all ([[...slug]]) that renders the same
  marketing/spec page for each known top-level route (/docs, /blog, /openspec,
  ...) and 404s unknown paths, preserving existing canonical URLs. Markup is a
  faithful server-rendered port of the old main.ts (SEO upgrade over the prior
  client render); interactivity (hire-us form, CoinPay button, section scroll)
  moves to a client component.
- API routes ported to app/api/**: hire-us coinpay-checkout + project-request,
  oauth/coinpay start/callback/session, webhooks/coinpay. Shared logic in
  src/lib/coinpay.ts (eligibility, payment-rail selection, webhook verify,
  HMAC session sign/verify, cookies).
- commandboard-api (/health + /api/boards|tasks|plugins/*) is no longer mounted
  in-process; next.config.ts proxies those paths to COMMANDBOARD_API_URL via
  afterFiles rewrites (our own /api routes match first).
- Build/start switch to next build / next start. Contract tests rewritten to
  exercise proxy.ts, the route handlers, and pure helpers directly (21 passing);
  Playwright webServer updated.

Deployment (Railway): set COMMANDBOARD_API_URL to the commandboard-api service
URL and run it as its own service; root start now runs next start.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-06-07 03:41:48 +00:00
parent cf5d526176
commit f0a9f3890e
24 changed files with 2102 additions and 1394 deletions

View file

@ -1,78 +1,130 @@
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { createHmac } from "node:crypto";
import { accessSync } from "node:fs";
import { createServer, type Server as HttpServer } from "node:http";
import type { AddressInfo } from "node:net";
import { setTimeout as delay } from "node:timers/promises";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { NextRequest } from "next/server";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
let server: ChildProcessWithoutNullStreams;
const port = 4291;
const baseUrl = `http://127.0.0.1:${port}`;
let nextCheckoutPort = 4292;
import { proxy } from "../src/proxy";
import { renderPageMarkup } from "@/lib/page-markup";
import { choosePaymentRail, signSession, verifyCoinPayWebhook, verifySession } from "@/lib/coinpay";
import { POST as coinpayCheckout } from "@/app/api/hire-us/coinpay-checkout/route";
import { POST as projectRequest } from "@/app/api/hire-us/project-request/route";
import { GET as oauthStart } from "@/app/api/oauth/coinpay/start/route";
import { GET as oauthCallback } from "@/app/api/oauth/coinpay/callback/route";
import { GET as oauthSession } from "@/app/api/oauth/coinpay/session/route";
import { POST as coinpayWebhook } from "@/app/api/webhooks/coinpay/route";
beforeAll(async () => {
accessSync(new URL("../dist/index.html", import.meta.url));
server = spawn(process.execPath, ["server.js"], {
cwd: new URL("..", import.meta.url),
env: {
...process.env,
PORT: String(port),
COINPAY_API_KEY: "",
COINPAY_API_URL: "https://coinpayportal.example"
}
});
// CoinPay/OAuth/webhook env keys we clear between tests so each case controls
// exactly what is configured.
const COINPAY_ENV_KEYS = [
"COINPAY_API_KEY",
"COINPAY_API_URL",
"COINPAY_ELIGIBILITY_API_KEY",
"COINPAY_AGENT_API_KEY",
"COINPAY_BUSINESS_ID",
"COINPAY_MERCHANT_ID",
"COINPAY_ELIGIBILITY_MERCHANT_ID",
"COINPAY_HIRE_US_BLOCKCHAIN",
"PUBLIC_URL",
"COINPAY_WEBHOOK_SECRET",
"COINPAY_OAUTH_ISSUER",
"COINPAY_OAUTH_CLIENT_ID",
"COINPAY_OAUTH_CLIENT_SECRET",
"COINPAY_OAUTH_REDIRECT_URI",
"LOGICSRC_SESSION_SECRET"
];
await waitForServer(baseUrl);
const savedEnv: Record<string, string | undefined> = {};
beforeEach(() => {
for (const key of COINPAY_ENV_KEYS) {
savedEnv[key] = process.env[key];
delete process.env[key];
}
});
afterAll(() => {
server?.kill();
afterEach(() => {
for (const key of COINPAY_ENV_KEYS) {
if (savedEnv[key] === undefined) {
delete process.env[key];
} else {
process.env[key] = savedEnv[key];
}
}
vi.restoreAllMocks();
});
describe("LogicSRC web contracts", () => {
it("serves SPA routes from the built app shell", async () => {
for (const route of ["/", "/openspec", "/credential-sharing", "/docs", "/blog", "/hire-us", "/about", "/terms", "/privacy"]) {
const response = await fetch(`${baseUrl}${route}`);
const text = await response.text();
expect(response.status, route).toBe(200);
expect(response.headers.get("content-type")).toContain("text/html");
expect(text).toContain('<div id="app"></div>');
}
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { "content-type": "application/json" }
});
}
it("serves sitemap.xml as XML with canonical routes", async () => {
const response = await fetch(`${baseUrl}/sitemap.xml`);
const text = await response.text();
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toContain("application/xml");
expect(response.headers.get("cache-control")).toBe("no-store");
expect(text).toContain("<loc>https://logicsrc.com/openspec</loc>");
expect(text).toContain("<loc>https://logicsrc.com/credential-sharing</loc>");
expect(text).toContain("<loc>https://logicsrc.com/hire-us</loc>");
expect(text).toContain("<loc>https://logicsrc.com/blog</loc>");
});
it("serves blog/rss.xml as RSS XML", async () => {
const response = await fetch(`${baseUrl}/blog/rss.xml`);
const text = await response.text();
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toContain("application/xml");
expect(response.headers.get("cache-control")).toBe("no-store");
expect(text).toContain("<rss version=\"2.0\"");
expect(text).toContain("<title>LogicSRC OpenSpec Compatibility</title>");
expect(text).toContain("<title>LogicSRC Credential Sharing OpenSpec</title>");
});
it("does not create CoinPay checkout without server credentials", async () => {
const response = await fetch(`${baseUrl}/api/hire-us/coinpay-checkout`, {
method: "POST",
headers: { "content-type": "application/json" },
body: "{}"
describe("www canonical redirect (proxy.ts)", () => {
it("301s www to the apex host over https, preserving path + query", () => {
const request = new NextRequest("https://www.logicsrc.com/openspec?ref=email", {
headers: { host: "www.logicsrc.com" }
});
const response = proxy(request);
expect(response.status).toBe(301);
expect(response.headers.get("location")).toBe("https://logicsrc.com/openspec?ref=email");
});
it("passes through apex requests untouched", () => {
const request = new NextRequest("https://logicsrc.com/hire-us", {
headers: { host: "logicsrc.com" }
});
const response = proxy(request);
// NextResponse.next() yields a non-redirect response.
expect(response.status).toBe(200);
expect(response.headers.get("location")).toBeNull();
});
});
describe("server-rendered page markup", () => {
it("includes canonical section content and the CoinPay connect action", () => {
const markup = renderPageMarkup();
expect(markup).toContain("LogicSRC vs OpenSpec.dev");
expect(markup).toContain("Open replacement architecture for secrets");
expect(markup).toContain("/api/oauth/coinpay/start");
expect(markup).toContain('id="project-request-form"');
});
});
describe("payment rail selection", () => {
it("prefers both when card and configured crypto are available", () => {
expect(
choosePaymentRail({ accepts_card: true, accepts_crypto: true, chains: ["USDC_POL"] }, "USDC_POL")
).toEqual({ method: "both", currency: "usdc_pol", blockchain: "USDC_POL" });
});
it("falls back to card when configured crypto is unavailable", () => {
expect(
choosePaymentRail({ accepts_card: true, accepts_crypto: false, chains: [] }, "USDC_POL")
).toEqual({ method: "card", currency: "card", blockchain: null });
});
it("uses crypto only when card is not enabled", () => {
expect(
choosePaymentRail({ accepts_card: false, accepts_crypto: true, chains: ["USDC_POL"] }, "USDC_POL")
).toEqual({ method: "crypto", currency: "usdc_pol", blockchain: "USDC_POL" });
});
it("returns null when no rail is available", () => {
expect(choosePaymentRail({ accepts_card: false, accepts_crypto: false, chains: [] }, "USDC_POL")).toBeNull();
});
});
describe("POST /api/hire-us/coinpay-checkout", () => {
it("does not create checkout without server credentials", async () => {
const response = await coinpayCheckout(
new NextRequest("http://localhost/api/hire-us/coinpay-checkout", {
method: "POST",
headers: { "content-type": "application/json" },
body: "{}"
})
);
const body = await response.json();
expect(response.status).toBe(503);
@ -80,18 +132,46 @@ describe("LogicSRC web contracts", () => {
expect(body).toEqual({ success: false, error: "CoinPay checkout is not configured" });
});
it("creates CoinPay checkout with card and crypto when both rails are available", async () => {
const { response, body, upstreamRequests } = await createCheckout({
eligibility: { accepts_card: true, accepts_crypto: true, chains: ["USDC_POL"] },
payment: { stripe_checkout_url: "https://checkout.stripe.test/session" }
it("creates a checkout with card and crypto when both rails are available", async () => {
process.env.COINPAY_API_KEY = "cp_test_key";
process.env.COINPAY_API_URL = "https://coinpayportal.example";
process.env.COINPAY_BUSINESS_ID = "business-123";
process.env.COINPAY_ELIGIBILITY_MERCHANT_ID = "merchant-123";
process.env.COINPAY_HIRE_US_BLOCKCHAIN = "USDC_POL";
process.env.PUBLIC_URL = "https://logicsrc.test";
const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
const url = typeof input === "string" ? input : input.toString();
if (url.includes("/api/payments/merchant-eligibility")) {
return jsonResponse({ success: true, accepts_card: true, accepts_crypto: true, chains: ["USDC_POL"] });
}
if (url.includes("/api/payments/create")) {
return jsonResponse(
{ success: true, payment: { id: "pay_123", stripe_checkout_url: "https://checkout.stripe.test/session" } },
201
);
}
throw new Error(`unexpected fetch ${url}`);
});
const paymentRequest = upstreamRequests.find((request) => request.url === "/api/payments/create");
const response = await coinpayCheckout(
new NextRequest("http://localhost/api/hire-us/coinpay-checkout", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email: "buyer@example.com" })
})
);
const body = await response.json();
const createCall = fetchMock.mock.calls.find(([input]) =>
(typeof input === "string" ? input : input.toString()).includes("/api/payments/create")
);
const createBody = JSON.parse((createCall?.[1]?.body as string) ?? "{}");
expect(response.status).toBe(201);
expect(body.payment.checkout_url).toBe("https://checkout.stripe.test/session");
expect(paymentRequest?.method).toBe("POST");
expect(paymentRequest?.authorization).toBe("Bearer cp_test_key");
expect(paymentRequest?.body).toMatchObject({
expect(createCall?.[1]?.headers).toMatchObject({ authorization: "Bearer cp_test_key" });
expect(createBody).toMatchObject({
business_id: "business-123",
amount_usd: 250,
payment_method: "both",
@ -111,406 +191,234 @@ describe("LogicSRC web contracts", () => {
});
});
it("uses card-only checkout when Stripe is available and configured crypto is not", async () => {
const { response, body, upstreamRequests } = await createCheckout({
eligibility: { accepts_card: true, accepts_crypto: false, chains: [] },
payment: { stripe_checkout_url: "https://checkout.stripe.test/card-only" }
it("uses card-only checkout when configured crypto is not available", async () => {
process.env.COINPAY_API_KEY = "cp_test_key";
process.env.COINPAY_API_URL = "https://coinpayportal.example";
process.env.COINPAY_BUSINESS_ID = "business-123";
process.env.COINPAY_ELIGIBILITY_MERCHANT_ID = "merchant-123";
vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
const url = typeof input === "string" ? input : input.toString();
if (url.includes("/api/payments/merchant-eligibility")) {
return jsonResponse({ success: true, accepts_card: true, accepts_crypto: false, chains: [] });
}
return jsonResponse(
{ success: true, payment: { id: "pay_123", stripe_checkout_url: "https://checkout.stripe.test/card-only" } },
201
);
});
const paymentRequest = upstreamRequests.find((request) => request.url === "/api/payments/create");
const response = await coinpayCheckout(
new NextRequest("http://localhost/api/hire-us/coinpay-checkout", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email: "buyer@example.com" })
})
);
const body = await response.json();
expect(response.status).toBe(201);
expect(body.payment.checkout_url).toBe("https://checkout.stripe.test/card-only");
expect(paymentRequest?.body).toMatchObject({
payment_method: "card",
currency: "card"
});
expect(paymentRequest?.body).not.toHaveProperty("blockchain");
});
it("uses crypto-only checkout when Stripe is not enabled", async () => {
const { response, body, upstreamRequests } = await createCheckout({
eligibility: { accepts_card: false, accepts_crypto: true, chains: ["USDC_POL"] },
payment: {}
});
const paymentRequest = upstreamRequests.find((request) => request.url === "/api/payments/create");
it("does not create checkout when no payment rail is available", async () => {
process.env.COINPAY_API_KEY = "cp_test_key";
process.env.COINPAY_API_URL = "https://coinpayportal.example";
process.env.COINPAY_BUSINESS_ID = "business-123";
process.env.COINPAY_ELIGIBILITY_MERCHANT_ID = "merchant-123";
expect(response.status).toBe(201);
expect(body.payment.checkout_url).toBeNull();
expect(body.payment.address).toBe("0xabc");
expect(paymentRequest?.body).toMatchObject({
payment_method: "crypto",
currency: "usdc_pol",
blockchain: "USDC_POL"
});
});
const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async () =>
jsonResponse({ success: true, accepts_card: false, accepts_crypto: false, chains: [] })
);
it("does not create CoinPay checkout when no payment rail is available", async () => {
const { response, body, upstreamRequests } = await createCheckout({
eligibility: { accepts_card: false, accepts_crypto: false, chains: [] },
payment: {}
});
const response = await coinpayCheckout(
new NextRequest("http://localhost/api/hire-us/coinpay-checkout", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email: "buyer@example.com" })
})
);
const body = await response.json();
expect(response.status).toBe(503);
expect(body).toEqual({
success: false,
error: "CoinPay checkout is not available for this merchant"
});
expect(upstreamRequests.some((request) => request.url === "/api/payments/create")).toBe(false);
expect(body).toEqual({ success: false, error: "CoinPay checkout is not available for this merchant" });
expect(
fetchMock.mock.calls.some(([input]) =>
(typeof input === "string" ? input : input.toString()).includes("/api/payments/create")
)
).toBe(false);
});
});
it("accepts Hire Us project requests before creating a recurring invoice", async () => {
const { appServer, appBaseUrl } = await startApp({});
try {
const response = await fetch(`${appBaseUrl}/api/hire-us/project-request`, {
describe("POST /api/hire-us/project-request", () => {
it("accepts a valid project request before invoicing", async () => {
const response = await projectRequest(
new NextRequest("http://localhost/api/hire-us/project-request", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
contact: "buyer@example.com",
project: "Build a LogicSRC plugin and API contract for a recurring agent workflow."
})
});
const body = await response.json();
})
);
const body = await response.json();
expect(response.status).toBe(202);
expect(body).toMatchObject({
success: true,
request: {
status: "pending_acceptance",
amount_usd: 250,
interval: "week",
invoice: "created_after_acceptance"
}
});
expect(body.request.id).toMatch(/^hire_/);
} finally {
appServer.kill();
}
expect(response.status).toBe(202);
expect(body).toMatchObject({
success: true,
request: { status: "pending_acceptance", amount_usd: 250, interval: "week", invoice: "created_after_acceptance" }
});
expect(body.request.id).toMatch(/^hire_/);
});
it("accepts signed CoinPay payment webhooks", async () => {
const secret = "whsec_test";
const { appServer, appBaseUrl } = await startApp({
COINPAY_API_KEY: "cp_test_key",
COINPAY_MERCHANT_ID: "business-123",
COINPAY_WEBHOOK_SECRET: secret
});
const payload = JSON.stringify({
id: "evt_1",
type: "payment.forwarded",
data: { payment_id: "pay_123", status: "forwarded" }
});
const timestamp = Math.floor(Date.now() / 1000).toString();
const signature = createHmac("sha256", secret).update(`${timestamp}.${payload}`).digest("hex");
try {
const response = await fetch(`${appBaseUrl}/api/webhooks/coinpay`, {
method: "POST",
headers: {
"content-type": "application/json",
"x-coinpay-signature": `t=${timestamp},v1=${signature}`
},
body: payload
});
const body = await response.json();
expect(response.status).toBe(200);
expect(body).toEqual({ received: true, complete: true, payment_id: "pay_123" });
} finally {
appServer.kill();
}
});
it("rejects unsigned CoinPay payment webhooks", async () => {
const { appServer, appBaseUrl } = await startApp({
COINPAY_API_KEY: "cp_test_key",
COINPAY_MERCHANT_ID: "business-123",
COINPAY_WEBHOOK_SECRET: "whsec_test"
});
try {
const response = await fetch(`${appBaseUrl}/api/webhooks/coinpay`, {
it("rejects an incomplete project request", async () => {
const response = await projectRequest(
new NextRequest("http://localhost/api/hire-us/project-request", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ type: "payment.confirmed", data: { payment_id: "pay_123" } })
});
const body = await response.json();
body: JSON.stringify({ contact: "", project: "too short" })
})
);
expect(response.status).toBe(401);
expect(body).toEqual({ success: false, error: "Invalid signature" });
} finally {
appServer.kill();
}
});
it("starts CoinPay OAuth with a registered callback and state cookie", async () => {
const { appServer, appBaseUrl } = await startApp({
COINPAY_OAUTH_ISSUER: "https://coinpayportal.example",
COINPAY_OAUTH_CLIENT_ID: "cp_test_client",
COINPAY_OAUTH_CLIENT_SECRET: "cps_test_secret",
COINPAY_OAUTH_REDIRECT_URI: "https://logicsrc.com/api/oauth/coinpay/callback"
});
try {
const response = await fetch(`${appBaseUrl}/api/oauth/coinpay/start`, { redirect: "manual" });
const location = new URL(response.headers.get("location") ?? "");
expect(response.status).toBe(302);
expect(location.origin).toBe("https://coinpayportal.example");
expect(location.pathname).toBe("/api/oauth/authorize");
expect(location.searchParams.get("response_type")).toBe("code");
expect(location.searchParams.get("client_id")).toBe("cp_test_client");
expect(location.searchParams.get("redirect_uri")).toBe("https://logicsrc.com/api/oauth/coinpay/callback");
expect(location.searchParams.get("scope")).toBe("openid profile email");
expect(location.searchParams.get("state")).toMatch(/^[a-f0-9]{32}$/);
expect(response.headers.get("set-cookie")).toContain("logicsrc_coinpay_oauth_state=");
} finally {
appServer.kill();
}
});
it("exchanges CoinPay OAuth callback codes and stores a signed session", async () => {
const { fakeCoinPay, fakeCoinPayBaseUrl, tokenRequests } = await startFakeCoinPayOAuth();
const { appServer, appBaseUrl } = await startApp({
COINPAY_OAUTH_ISSUER: fakeCoinPayBaseUrl,
COINPAY_OAUTH_CLIENT_ID: "cp_test_client",
COINPAY_OAUTH_CLIENT_SECRET: "cps_test_secret",
COINPAY_OAUTH_REDIRECT_URI: "https://logicsrc.com/api/oauth/coinpay/callback",
LOGICSRC_SESSION_SECRET: "session_secret_for_tests"
});
try {
const response = await fetch(`${appBaseUrl}/api/oauth/coinpay/callback?code=auth_code_123&state=state_123`, {
redirect: "manual",
headers: { cookie: "logicsrc_coinpay_oauth_state=state_123" }
});
const cookieHeader = response.headers.get("set-cookie") ?? "";
const sessionCookie = cookieHeader.match(/logicsrc_coinpay_session=([^;]+)/)?.[0];
expect(response.status).toBe(302);
expect(response.headers.get("location")).toBe("/?coinpay_oauth=connected");
expect(sessionCookie).toBeTruthy();
expect(tokenRequests[0]).toMatchObject({
grant_type: "authorization_code",
code: "auth_code_123",
redirect_uri: "https://logicsrc.com/api/oauth/coinpay/callback",
client_id: "cp_test_client",
client_secret: "cps_test_secret"
});
const sessionResponse = await fetch(`${appBaseUrl}/api/oauth/coinpay/session`, {
headers: { cookie: sessionCookie ?? "" }
});
const sessionBody = await sessionResponse.json();
expect(sessionBody).toMatchObject({
authenticated: true,
user: {
provider: "coinpay",
sub: "merchant-123",
email: "merchant@example.com",
name: "Merchant User",
scope: "openid profile email"
}
});
} finally {
appServer.kill();
await close(fakeCoinPay);
}
expect(response.status).toBe(422);
});
});
async function createCheckout({
eligibility,
payment
}: {
eligibility: { accepts_card: boolean; accepts_crypto: boolean; chains: string[] };
payment: Record<string, unknown>;
}) {
const upstreamRequests: Array<{
method?: string;
url?: string;
authorization?: string;
body?: Record<string, unknown>;
}> = [];
const fakeCoinPay = createServer((request, response) => {
let rawBody = "";
request.setEncoding("utf8");
request.on("data", (chunk) => {
rawBody += chunk;
});
request.on("end", () => {
upstreamRequests.push({
method: request.method,
url: request.url,
authorization: request.headers.authorization,
body: rawBody ? JSON.parse(rawBody) : undefined
});
if (request.method === "GET" && request.url?.startsWith("/api/payments/merchant-eligibility")) {
response.writeHead(200, { "content-type": "application/json; charset=utf-8" });
response.end(JSON.stringify({
success: true,
merchant_id: "merchant-123",
...eligibility
}));
return;
}
if (request.method === "POST" && request.url === "/api/payments/create") {
response.writeHead(201, { "content-type": "application/json; charset=utf-8" });
response.end(JSON.stringify({
success: true,
payment: {
id: "pay_123",
amount_usd: 250,
blockchain: "USDC_POL",
amount_crypto: "499.5",
payment_address: "0xabc",
expires_at: "2030-01-01T00:00:00.000Z",
status: "pending",
...payment
}
}));
return;
}
response.writeHead(404, { "content-type": "application/json; charset=utf-8" });
response.end(JSON.stringify({ success: false, error: "not found" }));
});
describe("CoinPay OAuth", () => {
it("returns 503 from start when OAuth is not configured", async () => {
const response = await oauthStart();
expect(response.status).toBe(503);
});
await listen(fakeCoinPay);
const fakeCoinPayPort = (fakeCoinPay.address() as AddressInfo).port;
const appPort = nextCheckoutPort;
nextCheckoutPort += 1;
const { appServer, appBaseUrl } = await startApp({
PORT: String(appPort),
COINPAY_API_KEY: "cp_test_key",
COINPAY_API_URL: `http://127.0.0.1:${fakeCoinPayPort}`,
COINPAY_BUSINESS_ID: "business-123",
COINPAY_ELIGIBILITY_MERCHANT_ID: "merchant-123",
COINPAY_HIRE_US_BLOCKCHAIN: "USDC_POL",
PUBLIC_URL: "https://logicsrc.test"
it("starts OAuth with a registered callback and state cookie", async () => {
process.env.COINPAY_OAUTH_ISSUER = "https://coinpayportal.example";
process.env.COINPAY_OAUTH_CLIENT_ID = "cp_test_client";
process.env.COINPAY_OAUTH_CLIENT_SECRET = "cps_test_secret";
process.env.COINPAY_OAUTH_REDIRECT_URI = "https://logicsrc.com/api/oauth/coinpay/callback";
const response = await oauthStart();
const location = new URL(response.headers.get("location") ?? "");
expect(response.status).toBe(302);
expect(location.origin).toBe("https://coinpayportal.example");
expect(location.pathname).toBe("/api/oauth/authorize");
expect(location.searchParams.get("client_id")).toBe("cp_test_client");
expect(location.searchParams.get("redirect_uri")).toBe("https://logicsrc.com/api/oauth/coinpay/callback");
expect(location.searchParams.get("state")).toMatch(/^[a-f0-9]{32}$/);
expect(response.headers.get("set-cookie")).toContain("logicsrc_coinpay_oauth_state=");
});
try {
await waitForServer(appBaseUrl);
it("rejects a callback with mismatched state", async () => {
process.env.COINPAY_OAUTH_ISSUER = "https://coinpayportal.example";
process.env.COINPAY_OAUTH_CLIENT_ID = "cp_test_client";
process.env.COINPAY_OAUTH_CLIENT_SECRET = "cps_test_secret";
process.env.COINPAY_OAUTH_REDIRECT_URI = "https://logicsrc.com/api/oauth/coinpay/callback";
const response = await fetch(`${appBaseUrl}/api/hire-us/coinpay-checkout`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email: "buyer@example.com" })
const response = await oauthCallback(
new NextRequest("http://localhost/api/oauth/coinpay/callback?code=abc&state=wrong", {
headers: { cookie: "logicsrc_coinpay_oauth_state=expected" }
})
);
expect(response.status).toBe(302);
expect(response.headers.get("location")).toBe("/?coinpay_oauth=error&error=invalid_state");
});
it("exchanges a callback code and stores a verifiable session", async () => {
process.env.COINPAY_OAUTH_ISSUER = "https://coinpayportal.example";
process.env.COINPAY_OAUTH_CLIENT_ID = "cp_test_client";
process.env.COINPAY_OAUTH_CLIENT_SECRET = "cps_test_secret";
process.env.COINPAY_OAUTH_REDIRECT_URI = "https://logicsrc.com/api/oauth/coinpay/callback";
process.env.LOGICSRC_SESSION_SECRET = "session_secret_for_tests";
vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {
const url = typeof input === "string" ? input : input.toString();
if (url.includes("/api/oauth/token")) {
return jsonResponse({ access_token: "access_token_123", token_type: "Bearer", scope: "openid profile email" });
}
if (url.includes("/api/oauth/userinfo")) {
return jsonResponse({ sub: "merchant-123", email: "merchant@example.com", name: "Merchant User" });
}
throw new Error(`unexpected fetch ${url}`);
});
const callback = await oauthCallback(
new NextRequest("http://localhost/api/oauth/coinpay/callback?code=auth_code_123&state=state_123", {
headers: { cookie: "logicsrc_coinpay_oauth_state=state_123" }
})
);
expect(callback.status).toBe(302);
expect(callback.headers.get("location")).toBe("/?coinpay_oauth=connected");
const setCookies = callback.headers.getSetCookie();
const sessionCookie = setCookies.find((cookie) => cookie.startsWith("logicsrc_coinpay_session="));
expect(sessionCookie).toBeTruthy();
const sessionValue = decodeURIComponent(sessionCookie!.split(";")[0].split("=")[1]);
const session = await oauthSession(
new NextRequest("http://localhost/api/oauth/coinpay/session", {
headers: { cookie: `logicsrc_coinpay_session=${encodeURIComponent(sessionValue)}` }
})
);
const sessionBody = await session.json();
expect(sessionBody).toMatchObject({
authenticated: true,
user: { provider: "coinpay", sub: "merchant-123", email: "merchant@example.com", name: "Merchant User" }
});
});
});
describe("session signing", () => {
it("verifies a session it signed and rejects tampering", () => {
process.env.LOGICSRC_SESSION_SECRET = "session_secret_for_tests";
const token = signSession({ provider: "coinpay", sub: "merchant-123" });
expect(verifySession(token)).toMatchObject({ provider: "coinpay", sub: "merchant-123" });
expect(verifySession(`${token}tampered`)).toBeNull();
});
});
describe("POST /api/webhooks/coinpay", () => {
it("returns 503 when no webhook secret is configured", async () => {
const response = await coinpayWebhook(
new NextRequest("http://localhost/api/webhooks/coinpay", { method: "POST", body: "{}" })
);
expect(response.status).toBe(503);
});
it("rejects unsigned webhooks", async () => {
process.env.COINPAY_WEBHOOK_SECRET = "whsec_test";
const response = await coinpayWebhook(
new NextRequest("http://localhost/api/webhooks/coinpay", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ type: "payment.confirmed", data: { payment_id: "pay_123" } })
})
);
expect(response.status).toBe(401);
});
it("accepts signed webhooks", async () => {
const secret = "whsec_test";
process.env.COINPAY_WEBHOOK_SECRET = secret;
const payload = JSON.stringify({ id: "evt_1", type: "payment.forwarded", data: { payment_id: "pay_123" } });
const timestamp = Math.floor(Date.now() / 1000).toString();
const signature = createHmac("sha256", secret).update(`${timestamp}.${payload}`).digest("hex");
expect(verifyCoinPayWebhook(payload, `t=${timestamp},v1=${signature}`, secret)).toBe(true);
const response = await coinpayWebhook(
new NextRequest("http://localhost/api/webhooks/coinpay", {
method: "POST",
headers: { "content-type": "application/json", "x-coinpay-signature": `t=${timestamp},v1=${signature}` },
body: payload
})
);
const body = await response.json();
return { response, body, upstreamRequests };
} finally {
appServer.kill();
await close(fakeCoinPay);
}
}
async function startApp(env: Record<string, string>) {
const appPort = env.PORT ? Number(env.PORT) : nextCheckoutPort;
if (!env.PORT) {
nextCheckoutPort += 1;
}
const appBaseUrl = `http://127.0.0.1:${appPort}`;
const appServer = spawn(process.execPath, ["server.js"], {
cwd: new URL("..", import.meta.url),
env: {
...process.env,
PORT: String(appPort),
COINPAY_API_URL: "https://coinpayportal.example",
PUBLIC_URL: "https://logicsrc.test",
...env
}
expect(response.status).toBe(200);
expect(body).toEqual({ received: true, complete: true, payment_id: "pay_123" });
});
await waitForServer(appBaseUrl);
return { appServer, appBaseUrl };
}
async function startFakeCoinPayOAuth() {
const tokenRequests: Array<Record<string, string>> = [];
const fakeCoinPay = createServer((request, response) => {
let rawBody = "";
request.setEncoding("utf8");
request.on("data", (chunk) => {
rawBody += chunk;
});
request.on("end", () => {
if (request.method === "POST" && request.url === "/api/oauth/token") {
tokenRequests.push(Object.fromEntries(new URLSearchParams(rawBody)));
response.writeHead(200, { "content-type": "application/json; charset=utf-8" });
response.end(JSON.stringify({
access_token: "access_token_123",
token_type: "Bearer",
expires_in: 3600,
refresh_token: "refresh_token_123",
scope: "openid profile email"
}));
return;
}
if (request.method === "GET" && request.url === "/api/oauth/userinfo") {
response.writeHead(200, { "content-type": "application/json; charset=utf-8" });
response.end(JSON.stringify({
sub: "merchant-123",
email: "merchant@example.com",
name: "Merchant User"
}));
return;
}
response.writeHead(404, { "content-type": "application/json; charset=utf-8" });
response.end(JSON.stringify({ error: "not found" }));
});
});
await listen(fakeCoinPay);
const fakeCoinPayPort = (fakeCoinPay.address() as AddressInfo).port;
return {
fakeCoinPay,
fakeCoinPayBaseUrl: `http://127.0.0.1:${fakeCoinPayPort}`,
tokenRequests
};
}
function listen(server: HttpServer) {
return new Promise<void>((resolve) => {
server.listen(0, "127.0.0.1", resolve);
});
}
function close(server: HttpServer) {
return new Promise<void>((resolve, reject) => {
server.close((error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
async function waitForServer(serverBaseUrl: string) {
let lastError: unknown;
for (let attempt = 0; attempt < 40; attempt += 1) {
try {
const response = await fetch(`${serverBaseUrl}/health`);
if (response.ok) {
return;
}
} catch (error) {
lastError = error;
}
await delay(250);
}
throw new Error(`LogicSRC web server did not start: ${String(lastError)}`);
}
});