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

@ -0,0 +1,41 @@
import { notFound } from "next/navigation";
import type { ReactNode } from "react";
import { renderPageMarkup } from "@/lib/page-markup";
import { HomeInteractivity } from "@/components/home-interactivity";
// The legacy SPA served the same single page for every top-level path and just
// scrolled to the matching section. We preserve those URLs (they are canonical
// in sitemap.xml) by rendering the same page for each known route and 404ing
// anything else.
const KNOWN_ROUTES = new Set([
"docs",
"blog",
"openspec",
"credential-sharing",
"hire-us",
"about",
"terms",
"privacy",
"agent-swarm",
"agentbyte"
]);
export default async function Page({
params
}: {
params: Promise<{ slug?: string[] }>;
}): Promise<ReactNode> {
const { slug } = await params;
if (slug && slug.length > 0) {
if (slug.length > 1 || !KNOWN_ROUTES.has(slug[0])) {
notFound();
}
}
return (
<>
<div id="app" dangerouslySetInnerHTML={{ __html: renderPageMarkup() }} />
<HomeInteractivity />
</>
);
}

View file

@ -0,0 +1,95 @@
import type { NextRequest } from "next/server";
import { json } from "@/lib/http";
import { choosePaymentRail, fetchMerchantEligibility, parseJson } from "@/lib/coinpay";
export const dynamic = "force-dynamic";
// POST /api/hire-us/coinpay-checkout — create a $250/week CoinPay checkout for
// the Hire Us plan, choosing card/crypto/both based on merchant eligibility.
export async function POST(request: NextRequest) {
const apiKey = process.env.COINPAY_API_KEY;
const eligibilityApiKey = process.env.COINPAY_ELIGIBILITY_API_KEY || process.env.COINPAY_AGENT_API_KEY || apiKey;
const businessId = process.env.COINPAY_BUSINESS_ID || process.env.COINPAY_MERCHANT_ID;
const eligibilityMerchantId = process.env.COINPAY_ELIGIBILITY_MERCHANT_ID || process.env.COINPAY_MERCHANT_ID;
const apiUrl = process.env.COINPAY_API_URL || "https://coinpayportal.com";
const blockchain = process.env.COINPAY_HIRE_US_BLOCKCHAIN || "USDC_POL";
const publicUrl = process.env.PUBLIC_URL || "https://logicsrc.com";
if (!apiKey || !businessId) {
return json({ success: false, error: "CoinPay checkout is not configured" }, 503);
}
try {
const body = (await request.json().catch(() => ({}))) as Record<string, unknown>;
const buyerEmail = typeof body.email === "string" ? body.email.trim().slice(0, 160) : "";
const eligibility = await fetchMerchantEligibility(apiUrl, eligibilityApiKey, eligibilityMerchantId);
const paymentRail = choosePaymentRail(eligibility, blockchain);
if (!paymentRail) {
return json({ success: false, error: "CoinPay checkout is not available for this merchant" }, 503);
}
const checkoutResponse = await fetch(new URL("/api/payments/create", apiUrl), {
method: "POST",
headers: {
authorization: `Bearer ${apiKey}`,
"content-type": "application/json"
},
body: JSON.stringify({
business_id: businessId,
amount_usd: 250,
payment_method: paymentRail.method,
currency: paymentRail.currency,
...(paymentRail.blockchain ? { blockchain: paymentRail.blockchain } : {}),
description: "LogicSRC Hire Us - $250/week",
success_url: `${publicUrl}/hire-us?payment=success`,
cancel_url: `${publicUrl}/hire-us?payment=cancelled`,
redirect_url: `${publicUrl}/hire-us?payment=coinpay`,
webhook_url: `${publicUrl}/api/webhooks/coinpay`,
metadata: {
product: "logicsrc-hire-us",
interval: "week",
source: "logicsrc.com/hire-us",
...(buyerEmail ? { buyer_email: buyerEmail } : {})
}
})
});
const responseText = await checkoutResponse.text();
const payload = parseJson(responseText);
if (!checkoutResponse.ok || payload.success !== true) {
console.error("[coinpay] checkout create failed", {
status: checkoutResponse.status,
error: (payload.error as string) || responseText.slice(0, 300)
});
return json(
{ success: false, error: (payload.error as string) || "CoinPay checkout failed" },
checkoutResponse.ok ? 502 : checkoutResponse.status
);
}
const payment = (payload.payment as Record<string, unknown>) || {};
return json(
{
success: true,
payment: {
id: payment.id,
amount_usd: Number(payment.amount_usd ?? payment.amount ?? 250),
payment_method: payment.stripe_checkout_url ? "card" : paymentRail.method,
currency: payment.currency ?? payment.blockchain ?? paymentRail.blockchain ?? paymentRail.currency,
crypto_amount: payment.amount_crypto ?? payment.crypto_amount ?? null,
address: payment.payment_address ?? null,
qr_code: payment.qr_code ?? null,
expires_at: payment.expires_at ?? null,
status: payment.status ?? "pending",
checkout_url: payment.stripe_checkout_url ?? payload.checkout_url ?? payment.checkout_url ?? null
}
},
201
);
} catch (error) {
console.error("[coinpay] checkout request failed", error);
return json({ success: false, error: "Unable to reach CoinPay checkout" }, 500);
}
}

View file

@ -0,0 +1,44 @@
import type { NextRequest } from "next/server";
import { json } from "@/lib/http";
export const dynamic = "force-dynamic";
// POST /api/hire-us/project-request — accept a Hire Us project request before a
// recurring CoinPay invoice is created (invoice is created after acceptance).
export async function POST(request: NextRequest) {
try {
const body = (await request.json().catch(() => ({}))) as Record<string, unknown>;
const contact = typeof body.contact === "string" ? body.contact.trim().slice(0, 160) : "";
const project = typeof body.project === "string" ? body.project.trim().slice(0, 4000) : "";
if (!contact || project.length < 20) {
return json({ success: false, error: "Contact and a project description are required" }, 422);
}
const requestId = `hire_${Date.now()}`;
console.log("[hire-us] project request received", {
id: requestId,
contact,
project_length: project.length,
plan: "250/week",
invoice: "pending_acceptance"
});
return json(
{
success: true,
request: {
id: requestId,
status: "pending_acceptance",
amount_usd: 250,
interval: "week",
invoice: "created_after_acceptance"
}
},
202
);
} catch (error) {
console.error("[hire-us] project request failed", error);
return json({ success: false, error: "Unable to submit project request" }, 500);
}
}

View file

@ -0,0 +1,104 @@
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { json } from "@/lib/http";
import {
COINPAY_OAUTH_STATE_COOKIE,
COINPAY_SESSION_COOKIE,
getCoinPayOAuthConfig,
parseJson,
serializeCookie,
signSession
} from "@/lib/coinpay";
export const dynamic = "force-dynamic";
function redirectWithOAuthStatus(status: string, error?: string): NextResponse {
const params = new URLSearchParams({ coinpay_oauth: status });
if (error) {
params.set("error", error);
}
return new NextResponse(null, { status: 302, headers: { location: `/?${params.toString()}` } });
}
// GET /api/oauth/coinpay/callback — validate state, exchange the code for tokens,
// fetch userinfo, and store a signed session cookie.
export async function GET(request: NextRequest) {
const config = getCoinPayOAuthConfig();
if (!config) {
return json({ success: false, error: "CoinPay OAuth is not configured" }, 503);
}
const url = request.nextUrl;
const callbackError = url.searchParams.get("error");
if (callbackError) {
return redirectWithOAuthStatus("error", callbackError);
}
const code = url.searchParams.get("code");
const state = url.searchParams.get("state");
const expectedState = request.cookies.get(COINPAY_OAUTH_STATE_COOKIE)?.value;
if (!code) {
return redirectWithOAuthStatus("error", "missing_code");
}
if (!state || !expectedState || state !== expectedState) {
return redirectWithOAuthStatus("error", "invalid_state");
}
try {
const tokenResponse = await fetch(new URL("/api/oauth/token", config.issuer), {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: config.redirectUri,
client_id: config.clientId,
client_secret: config.clientSecret
})
});
const tokenText = await tokenResponse.text();
const tokenPayload = parseJson(tokenText);
if (!tokenResponse.ok || typeof tokenPayload.access_token !== "string") {
console.error("[coinpay-oauth] token exchange failed", {
status: tokenResponse.status,
error: (tokenPayload.error as string) || tokenText.slice(0, 160)
});
return redirectWithOAuthStatus("error", "token_exchange_failed");
}
const userResponse = await fetch(new URL("/api/oauth/userinfo", config.issuer), {
headers: { authorization: `Bearer ${tokenPayload.access_token}` }
});
const userText = await userResponse.text();
const userInfo = userResponse.ok ? parseJson(userText) : {};
const session = signSession({
provider: "coinpay",
sub: typeof userInfo.sub === "string" ? userInfo.sub : null,
email: typeof userInfo.email === "string" ? userInfo.email : null,
name: typeof userInfo.name === "string" ? userInfo.name : null,
scope: typeof tokenPayload.scope === "string" ? tokenPayload.scope : config.scopes,
connected_at: new Date().toISOString()
});
const response = new NextResponse(null, {
status: 302,
headers: { location: "/?coinpay_oauth=connected" }
});
response.headers.append(
"set-cookie",
serializeCookie(COINPAY_SESSION_COOKIE, session, { maxAge: 60 * 60 * 24 * 30, path: "/" })
);
response.headers.append(
"set-cookie",
serializeCookie(COINPAY_OAUTH_STATE_COOKIE, "", { maxAge: 0, path: "/api/oauth/coinpay" })
);
return response;
} catch (error) {
console.error("[coinpay-oauth] callback failed", error);
return redirectWithOAuthStatus("error", "callback_failed");
}
}

View file

@ -0,0 +1,25 @@
import type { NextRequest } from "next/server";
import { json } from "@/lib/http";
import { COINPAY_SESSION_COOKIE, verifySession } from "@/lib/coinpay";
export const dynamic = "force-dynamic";
// GET /api/oauth/coinpay/session — report whether a valid CoinPay session cookie
// is present and, if so, the connected user.
export async function GET(request: NextRequest) {
const sessionCookie = request.cookies.get(COINPAY_SESSION_COOKIE)?.value;
const session = sessionCookie ? verifySession(sessionCookie) : null;
return json({
authenticated: !!session,
user: session
? {
provider: session.provider,
sub: session.sub,
email: session.email,
name: session.name,
scope: session.scope,
connected_at: session.connected_at
}
: null
});
}

View file

@ -0,0 +1,34 @@
import { NextResponse } from "next/server";
import { randomBytes } from "node:crypto";
import { json } from "@/lib/http";
import { COINPAY_OAUTH_STATE_COOKIE, getCoinPayOAuthConfig, serializeCookie } from "@/lib/coinpay";
export const dynamic = "force-dynamic";
// GET /api/oauth/coinpay/start — begin CoinPay OAuth: set a signed state cookie
// and redirect to the provider's authorize endpoint.
export async function GET() {
const config = getCoinPayOAuthConfig();
if (!config) {
return json({ success: false, error: "CoinPay OAuth is not configured" }, 503);
}
const state = randomBytes(16).toString("hex");
const authorizeUrl = new URL("/api/oauth/authorize", config.issuer);
authorizeUrl.searchParams.set("response_type", "code");
authorizeUrl.searchParams.set("client_id", config.clientId);
authorizeUrl.searchParams.set("redirect_uri", config.redirectUri);
authorizeUrl.searchParams.set("scope", config.scopes);
authorizeUrl.searchParams.set("state", state);
return new NextResponse(null, {
status: 302,
headers: {
location: authorizeUrl.toString(),
"set-cookie": serializeCookie(COINPAY_OAUTH_STATE_COOKIE, state, {
maxAge: 600,
path: "/api/oauth/coinpay"
})
}
});
}

View file

@ -0,0 +1,32 @@
import type { NextRequest } from "next/server";
import { json } from "@/lib/http";
import { parseJson, verifyCoinPayWebhook } from "@/lib/coinpay";
export const dynamic = "force-dynamic";
// POST /api/webhooks/coinpay — verify the signed CoinPay webhook and acknowledge.
export async function POST(request: NextRequest) {
const webhookSecret = process.env.COINPAY_WEBHOOK_SECRET;
if (!webhookSecret) {
return json({ success: false, error: "CoinPay webhook is not configured" }, 503);
}
const rawBody = await request.text();
const signatureHeader = request.headers.get("x-coinpay-signature");
if (!verifyCoinPayWebhook(rawBody, signatureHeader, webhookSecret)) {
return json({ success: false, error: "Invalid signature" }, 401);
}
const payload = parseJson(rawBody);
const data = payload.data as Record<string, unknown> | undefined;
const paymentId = (data?.payment_id ?? payload.payment_id ?? null) as string | null;
const complete = payload.type === "payment.confirmed" || payload.type === "payment.forwarded";
console.log("[coinpay] webhook received", {
type: payload.type ?? null,
payment_id: paymentId,
complete
});
return json({ received: true, complete, payment_id: paymentId });
}

View file

@ -0,0 +1,24 @@
import type { Metadata, Viewport } from "next";
import type { ReactNode } from "react";
import "../styles.css";
export const metadata: Metadata = {
title: "LogicSRC",
description:
"Open schemas, primitives, and conventions for coordination between humans, AI agents, plugins, payment systems, and hosted products.",
manifest: "/manifest.webmanifest"
};
export const viewport: Viewport = {
themeColor: "#101418",
width: "device-width",
initialScale: 1
};
export default function RootLayout({ children }: { children: ReactNode }): ReactNode {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}