mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-08-14 23:07:29 +00:00
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:
parent
cf5d526176
commit
f0a9f3890e
24 changed files with 2102 additions and 1394 deletions
41
apps/logicsrc-web/src/app/[[...slug]]/page.tsx
Normal file
41
apps/logicsrc-web/src/app/[[...slug]]/page.tsx
Normal 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 />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
104
apps/logicsrc-web/src/app/api/oauth/coinpay/callback/route.ts
Normal file
104
apps/logicsrc-web/src/app/api/oauth/coinpay/callback/route.ts
Normal 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");
|
||||
}
|
||||
}
|
||||
25
apps/logicsrc-web/src/app/api/oauth/coinpay/session/route.ts
Normal file
25
apps/logicsrc-web/src/app/api/oauth/coinpay/session/route.ts
Normal 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
|
||||
});
|
||||
}
|
||||
34
apps/logicsrc-web/src/app/api/oauth/coinpay/start/route.ts
Normal file
34
apps/logicsrc-web/src/app/api/oauth/coinpay/start/route.ts
Normal 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"
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
32
apps/logicsrc-web/src/app/api/webhooks/coinpay/route.ts
Normal file
32
apps/logicsrc-web/src/app/api/webhooks/coinpay/route.ts
Normal 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 });
|
||||
}
|
||||
24
apps/logicsrc-web/src/app/layout.tsx
Normal file
24
apps/logicsrc-web/src/app/layout.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
120
apps/logicsrc-web/src/components/home-interactivity.tsx
Normal file
120
apps/logicsrc-web/src/components/home-interactivity.tsx
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
|
||||
// Client-side behavior for the LogicSRC page, ported from the legacy Vite
|
||||
// main.ts: register the service worker, wire the hire-us project form, reflect
|
||||
// CoinPay connection status on the Connect button, and scroll to the section
|
||||
// that matches the current path. The markup these hooks target is rendered on
|
||||
// the server by `renderPageMarkup`.
|
||||
export function HomeInteractivity(): null {
|
||||
useEffect(() => {
|
||||
if ("serviceWorker" in navigator) {
|
||||
navigator.serviceWorker.register("/service-worker.js").catch(() => undefined);
|
||||
}
|
||||
|
||||
const buildParagraph = (text: string): HTMLParagraphElement => {
|
||||
const paragraph = document.createElement("p");
|
||||
paragraph.textContent = text;
|
||||
return paragraph;
|
||||
};
|
||||
|
||||
const form = document.querySelector<HTMLFormElement>("#project-request-form");
|
||||
const onSubmit = async (event: Event): Promise<void> => {
|
||||
event.preventDefault();
|
||||
const button = document.querySelector<HTMLButtonElement>("#project-request-button");
|
||||
const result = document.querySelector<HTMLDivElement>("#project-request-result");
|
||||
const contact = document.querySelector<HTMLInputElement>("#project-contact");
|
||||
const project = document.querySelector<HTMLTextAreaElement>("#project-description");
|
||||
if (!button || !result || !contact || !project) return;
|
||||
|
||||
button.disabled = true;
|
||||
button.textContent = "Submitting...";
|
||||
result.replaceChildren(buildParagraph("Submitting project request."));
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/hire-us/project-request", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ contact: contact.value, project: project.value })
|
||||
});
|
||||
const payload = await response.json();
|
||||
|
||||
if (!response.ok || !payload.success) {
|
||||
throw new Error(payload.error || "Project request could not be submitted.");
|
||||
}
|
||||
|
||||
result.replaceChildren(
|
||||
buildParagraph("Request received. If it is a fit, we will send a $250/week recurring CoinPay invoice.")
|
||||
);
|
||||
} catch (error) {
|
||||
result.replaceChildren(
|
||||
buildParagraph(error instanceof Error ? error.message : "Project request could not be submitted.")
|
||||
);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
button.textContent = "Request review";
|
||||
}
|
||||
};
|
||||
form?.addEventListener("submit", onSubmit);
|
||||
|
||||
// Scroll to the section that matches the current path (mirrors the SPA).
|
||||
const { pathname } = window.location;
|
||||
if (pathname === "/agent-swarm") {
|
||||
document.querySelector("#agent-swarm")?.scrollIntoView();
|
||||
} else if (pathname === "/agentbyte") {
|
||||
document.querySelector("#agentbyte")?.scrollIntoView();
|
||||
} else {
|
||||
const pageRoute = pathname.slice(1);
|
||||
if (
|
||||
["docs", "blog", "openspec", "credential-sharing", "hire-us", "about", "terms", "privacy"].includes(pageRoute)
|
||||
) {
|
||||
document.querySelector(`#${pageRoute}`)?.scrollIntoView();
|
||||
}
|
||||
}
|
||||
|
||||
// CoinPay OAuth connection status: clean the query param and reflect state.
|
||||
const coinpayParam = new URLSearchParams(window.location.search).get("coinpay_oauth");
|
||||
if (coinpayParam) {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete("coinpay_oauth");
|
||||
url.searchParams.delete("error");
|
||||
history.replaceState(null, "", url.pathname + (url.search || ""));
|
||||
}
|
||||
|
||||
const updateCoinPayButton = async (): Promise<void> => {
|
||||
const connectBtn = document.querySelector<HTMLAnchorElement>(
|
||||
".hero-actions a[href='/api/oauth/coinpay/start']"
|
||||
);
|
||||
if (!connectBtn) return;
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/oauth/coinpay/session");
|
||||
const data = await res.json();
|
||||
|
||||
if (data.authenticated && data.user) {
|
||||
const label = data.user.email || data.user.name || data.user.sub || "CoinPay";
|
||||
connectBtn.textContent = `Connected: ${label}`;
|
||||
connectBtn.style.background = "#3a9e7e";
|
||||
connectBtn.removeAttribute("href");
|
||||
connectBtn.style.cursor = "default";
|
||||
connectBtn.title = `Connected via CoinPay since ${new Date(data.user.connected_at).toLocaleDateString()}`;
|
||||
} else if (coinpayParam === "connected") {
|
||||
connectBtn.textContent = "CoinPay Connected";
|
||||
connectBtn.style.background = "#3a9e7e";
|
||||
} else if (coinpayParam === "error") {
|
||||
connectBtn.textContent = "Connect CoinPay (retry)";
|
||||
}
|
||||
} catch {
|
||||
// session check failed — leave button as-is
|
||||
}
|
||||
};
|
||||
void updateCoinPayButton();
|
||||
|
||||
return () => {
|
||||
form?.removeEventListener("submit", onSubmit);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
197
apps/logicsrc-web/src/lib/coinpay.ts
Normal file
197
apps/logicsrc-web/src/lib/coinpay.ts
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
|
||||
// Server-side CoinPay + session helpers, ported from the legacy server.js so the
|
||||
// Next API routes keep identical behavior (eligibility-driven payment rails,
|
||||
// signed webhook verification, and HMAC-signed OAuth session cookies).
|
||||
|
||||
export const COINPAY_OAUTH_STATE_COOKIE = "logicsrc_coinpay_oauth_state";
|
||||
export const COINPAY_SESSION_COOKIE = "logicsrc_coinpay_session";
|
||||
|
||||
export interface MerchantEligibility {
|
||||
accepts_card: boolean;
|
||||
accepts_crypto: boolean;
|
||||
chains: string[];
|
||||
}
|
||||
|
||||
export interface PaymentRail {
|
||||
method: "both" | "card" | "crypto";
|
||||
currency: string;
|
||||
blockchain: string | null;
|
||||
}
|
||||
|
||||
export interface CoinPayOAuthConfig {
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
redirectUri: string;
|
||||
issuer: string;
|
||||
scopes: string;
|
||||
}
|
||||
|
||||
export function parseJson(text: string): Record<string, unknown> {
|
||||
try {
|
||||
return text ? (JSON.parse(text) as Record<string, unknown>) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchMerchantEligibility(
|
||||
apiUrl: string,
|
||||
apiKey: string | undefined,
|
||||
merchantId: string | undefined
|
||||
): Promise<MerchantEligibility | null> {
|
||||
if (!merchantId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL("/api/payments/merchant-eligibility", apiUrl);
|
||||
url.searchParams.set("merchant_id", merchantId);
|
||||
const response = await fetch(url, {
|
||||
headers: { authorization: `Bearer ${apiKey ?? ""}` }
|
||||
});
|
||||
const text = await response.text();
|
||||
const payload = parseJson(text);
|
||||
|
||||
if (!response.ok || payload.success !== true) {
|
||||
console.warn("[coinpay] merchant eligibility unavailable", {
|
||||
status: response.status,
|
||||
error: (payload.error as string) || text.slice(0, 120)
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
accepts_card: payload.accepts_card === true,
|
||||
accepts_crypto: payload.accepts_crypto === true,
|
||||
chains: Array.isArray(payload.chains)
|
||||
? (payload.chains as unknown[]).filter((chain): chain is string => typeof chain === "string")
|
||||
: []
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn("[coinpay] merchant eligibility request failed", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function choosePaymentRail(
|
||||
eligibility: MerchantEligibility | null,
|
||||
configuredBlockchain: string
|
||||
): PaymentRail | null {
|
||||
const cryptoCurrency = configuredBlockchain.toLowerCase();
|
||||
|
||||
if (!eligibility) {
|
||||
return { method: "both", currency: cryptoCurrency, blockchain: configuredBlockchain };
|
||||
}
|
||||
|
||||
const configuredChainAvailable = eligibility.chains
|
||||
.map((chain) => chain.toUpperCase())
|
||||
.includes(configuredBlockchain.toUpperCase());
|
||||
const acceptsConfiguredCrypto = eligibility.accepts_crypto && configuredChainAvailable;
|
||||
|
||||
if (eligibility.accepts_card && acceptsConfiguredCrypto) {
|
||||
return { method: "both", currency: cryptoCurrency, blockchain: configuredBlockchain };
|
||||
}
|
||||
|
||||
if (eligibility.accepts_card) {
|
||||
return { method: "card", currency: "card", blockchain: null };
|
||||
}
|
||||
|
||||
if (acceptsConfiguredCrypto) {
|
||||
return { method: "crypto", currency: cryptoCurrency, blockchain: configuredBlockchain };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function verifyCoinPayWebhook(
|
||||
rawBody: string,
|
||||
signatureHeader: string | null | undefined,
|
||||
secret: string
|
||||
): boolean {
|
||||
if (!signatureHeader) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const parts = signatureHeader.split(",");
|
||||
const timestamp = parts.find((part) => part.startsWith("t="))?.slice(2);
|
||||
const signature = parts.find((part) => part.startsWith("v1="))?.slice(3);
|
||||
if (!timestamp || !signature) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const timestampSeconds = Number.parseInt(timestamp, 10);
|
||||
if (!Number.isFinite(timestampSeconds) || Math.abs(Math.floor(Date.now() / 1000) - timestampSeconds) > 300) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const expected = createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest("hex");
|
||||
const actualBuffer = Buffer.from(signature, "hex");
|
||||
const expectedBuffer = Buffer.from(expected, "hex");
|
||||
return actualBuffer.length === expectedBuffer.length && timingSafeEqual(actualBuffer, expectedBuffer);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function getCoinPayOAuthConfig(): CoinPayOAuthConfig | null {
|
||||
const clientId = process.env.COINPAY_OAUTH_CLIENT_ID;
|
||||
const clientSecret = process.env.COINPAY_OAUTH_CLIENT_SECRET;
|
||||
const redirectUri = process.env.COINPAY_OAUTH_REDIRECT_URI;
|
||||
const issuer = process.env.COINPAY_OAUTH_ISSUER || process.env.COINPAY_API_URL || "https://coinpayportal.com";
|
||||
const scopes = process.env.COINPAY_OAUTH_SCOPES || "openid profile email";
|
||||
|
||||
if (!clientId || !clientSecret || !redirectUri) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { clientId, clientSecret, redirectUri, issuer, scopes };
|
||||
}
|
||||
|
||||
function getSessionSecret(): string {
|
||||
return process.env.LOGICSRC_SESSION_SECRET || process.env.COINPAY_OAUTH_CLIENT_SECRET || "logicsrc-dev-session-secret";
|
||||
}
|
||||
|
||||
export function signSession(payload: Record<string, unknown>): string {
|
||||
const encoded = Buffer.from(JSON.stringify(payload)).toString("base64url");
|
||||
const signature = createHmac("sha256", getSessionSecret()).update(encoded).digest("base64url");
|
||||
return `${encoded}.${signature}`;
|
||||
}
|
||||
|
||||
export function verifySession(value: string): Record<string, unknown> | null {
|
||||
const [encoded, signature] = value.split(".");
|
||||
if (!encoded || !signature) return null;
|
||||
|
||||
const expected = createHmac("sha256", getSessionSecret()).update(encoded).digest("base64url");
|
||||
const actualBuffer = Buffer.from(signature);
|
||||
const expectedBuffer = Buffer.from(expected);
|
||||
if (actualBuffer.length !== expectedBuffer.length || !timingSafeEqual(actualBuffer, expectedBuffer)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")) as Record<string, unknown>;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface CookieOptions {
|
||||
maxAge?: number;
|
||||
path?: string;
|
||||
}
|
||||
|
||||
export function serializeCookie(name: string, value: string, options: CookieOptions = {}): string {
|
||||
const parts = [`${name}=${encodeURIComponent(value)}`, "HttpOnly", "SameSite=Lax", `Path=${options.path || "/"}`];
|
||||
|
||||
if (typeof options.maxAge === "number") {
|
||||
parts.push(`Max-Age=${options.maxAge}`);
|
||||
}
|
||||
|
||||
if ((process.env.PUBLIC_URL || "").startsWith("https://")) {
|
||||
parts.push("Secure");
|
||||
}
|
||||
|
||||
return parts.join("; ");
|
||||
}
|
||||
9
apps/logicsrc-web/src/lib/http.ts
Normal file
9
apps/logicsrc-web/src/lib/http.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import { NextResponse } from "next/server";
|
||||
|
||||
// JSON responses are never cached, matching the legacy server.js `sendJson`.
|
||||
export function json(body: unknown, status = 200, headers: Record<string, string> = {}): NextResponse {
|
||||
return NextResponse.json(body, {
|
||||
status,
|
||||
headers: { "cache-control": "no-store", ...headers }
|
||||
});
|
||||
}
|
||||
|
|
@ -1,4 +1,8 @@
|
|||
import "./styles.css";
|
||||
// Server-rendered markup for the LogicSRC single-page site. This is a faithful
|
||||
// port of the legacy Vite `main.ts` innerHTML template: same data, same markup,
|
||||
// same class hooks — now rendered on the server for SEO instead of in the
|
||||
// browser. Interactivity (hire-us form, CoinPay button, section scroll) lives in
|
||||
// the `home-interactivity` client component.
|
||||
|
||||
const primitives = [
|
||||
{ name: "Identity", detail: "DIDs, OAuth accounts, profiles, and organization membership." },
|
||||
|
|
@ -103,7 +107,8 @@ const comparisonRows = [
|
|||
}
|
||||
];
|
||||
|
||||
document.querySelector<HTMLDivElement>("#app")!.innerHTML = `
|
||||
export function renderPageMarkup(): string {
|
||||
return `
|
||||
<main class="shell">
|
||||
<aside class="rail">
|
||||
<div class="brand">
|
||||
|
|
@ -391,147 +396,4 @@ COINPAY_STATUS=pending_acceptance</code></pre>
|
|||
</section>
|
||||
</main>
|
||||
`;
|
||||
|
||||
if ("serviceWorker" in navigator) {
|
||||
window.addEventListener("load", () => {
|
||||
navigator.serviceWorker.register("/service-worker.js").catch(() => undefined);
|
||||
});
|
||||
}
|
||||
|
||||
document.querySelector<HTMLFormElement>("#project-request-form")?.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const button = document.querySelector<HTMLButtonElement>("#project-request-button");
|
||||
const result = document.querySelector<HTMLDivElement>("#project-request-result");
|
||||
const contact = document.querySelector<HTMLInputElement>("#project-contact");
|
||||
const project = document.querySelector<HTMLTextAreaElement>("#project-description");
|
||||
if (!button || !result || !contact || !project) return;
|
||||
|
||||
button.disabled = true;
|
||||
button.textContent = "Submitting...";
|
||||
result.replaceChildren(buildParagraph("Submitting project request."));
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/hire-us/project-request", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ contact: contact.value, project: project.value })
|
||||
});
|
||||
const payload = await response.json();
|
||||
|
||||
if (!response.ok || !payload.success) {
|
||||
throw new Error(payload.error || "Project request could not be submitted.");
|
||||
}
|
||||
|
||||
result.replaceChildren(buildParagraph("Request received. If it is a fit, we will send a $250/week recurring CoinPay invoice."));
|
||||
} catch (error) {
|
||||
result.replaceChildren(
|
||||
buildParagraph(error instanceof Error ? error.message : "Project request could not be submitted.")
|
||||
);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
button.textContent = "Request review";
|
||||
}
|
||||
});
|
||||
|
||||
function buildCoinPayResult(payment: {
|
||||
amount_usd?: number;
|
||||
crypto_amount?: string | null;
|
||||
currency?: string;
|
||||
address?: string | null;
|
||||
id?: string;
|
||||
qr_code?: string | null;
|
||||
}) {
|
||||
const fragment = document.createDocumentFragment();
|
||||
const heading = document.createElement("strong");
|
||||
heading.textContent = "CoinPay payment ready";
|
||||
fragment.append(heading);
|
||||
|
||||
const details = document.createElement("dl");
|
||||
details.append(
|
||||
buildDetail("Amount", `$${payment.amount_usd ?? 250} / ${payment.crypto_amount ?? "quoted at checkout"} ${payment.currency ?? "USDC_POL"}`),
|
||||
buildDetail("Address", payment.address ?? "Open CoinPay to complete payment", true),
|
||||
buildDetail("Payment ID", payment.id ?? "pending", true)
|
||||
);
|
||||
fragment.append(details);
|
||||
|
||||
if (payment.qr_code) {
|
||||
const image = document.createElement("img");
|
||||
image.src = payment.qr_code;
|
||||
image.alt = "CoinPay payment QR code";
|
||||
fragment.append(image);
|
||||
}
|
||||
|
||||
return fragment;
|
||||
}
|
||||
|
||||
function buildDetail(label: string, value: string, code = false) {
|
||||
const row = document.createElement("div");
|
||||
const term = document.createElement("dt");
|
||||
const definition = document.createElement("dd");
|
||||
term.textContent = label;
|
||||
if (code) {
|
||||
const codeElement = document.createElement("code");
|
||||
codeElement.textContent = value;
|
||||
definition.append(codeElement);
|
||||
} else {
|
||||
definition.textContent = value;
|
||||
}
|
||||
row.append(term, definition);
|
||||
return row;
|
||||
}
|
||||
|
||||
function buildParagraph(text: string) {
|
||||
const paragraph = document.createElement("p");
|
||||
paragraph.textContent = text;
|
||||
return paragraph;
|
||||
}
|
||||
|
||||
if (window.location.pathname === "/agent-swarm") {
|
||||
document.querySelector("#agent-swarm")?.scrollIntoView();
|
||||
}
|
||||
|
||||
if (window.location.pathname === "/agentbyte") {
|
||||
document.querySelector("#agentbyte")?.scrollIntoView();
|
||||
}
|
||||
|
||||
const pageRoute = window.location.pathname.slice(1);
|
||||
if (["docs", "blog", "openspec", "credential-sharing", "hire-us", "about", "terms", "privacy"].includes(pageRoute)) {
|
||||
document.querySelector(`#${pageRoute}`)?.scrollIntoView();
|
||||
}
|
||||
|
||||
// CoinPay OAuth connection status
|
||||
const coinpayParam = new URLSearchParams(window.location.search).get("coinpay_oauth");
|
||||
if (coinpayParam) {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete("coinpay_oauth");
|
||||
url.searchParams.delete("error");
|
||||
history.replaceState(null, "", url.pathname + (url.search || ""));
|
||||
}
|
||||
|
||||
async function updateCoinPayButton() {
|
||||
const connectBtn = document.querySelector<HTMLAnchorElement>(".hero-actions a[href='/api/oauth/coinpay/start']");
|
||||
if (!connectBtn) return;
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/oauth/coinpay/session");
|
||||
const data = await res.json();
|
||||
|
||||
if (data.authenticated && data.user) {
|
||||
const label = data.user.email || data.user.name || data.user.sub || "CoinPay";
|
||||
connectBtn.textContent = `Connected: ${label}`;
|
||||
connectBtn.style.background = "#3a9e7e";
|
||||
connectBtn.removeAttribute("href");
|
||||
connectBtn.style.cursor = "default";
|
||||
connectBtn.title = `Connected via CoinPay since ${new Date(data.user.connected_at).toLocaleDateString()}`;
|
||||
} else if (coinpayParam === "connected") {
|
||||
connectBtn.textContent = "CoinPay Connected";
|
||||
connectBtn.style.background = "#3a9e7e";
|
||||
} else if (coinpayParam === "error") {
|
||||
connectBtn.textContent = "Connect CoinPay (retry)";
|
||||
}
|
||||
} catch {
|
||||
// session check failed — leave button as-is
|
||||
}
|
||||
}
|
||||
|
||||
updateCoinPayButton();
|
||||
20
apps/logicsrc-web/src/proxy.ts
Normal file
20
apps/logicsrc-web/src/proxy.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import { NextResponse } from "next/server";
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
// Canonical host: 301 www.* to the bare apex domain over https, preserving
|
||||
// path + query (e.g. https://www.logicsrc.com/foo -> https://logicsrc.com/foo).
|
||||
// This is the Next 16 "proxy" (formerly middleware) entrypoint.
|
||||
export function proxy(request: NextRequest): NextResponse {
|
||||
const host = request.headers.get("host") ?? "";
|
||||
if (host.startsWith("www.")) {
|
||||
const apexHost = host.slice("www.".length);
|
||||
const { pathname, search } = request.nextUrl;
|
||||
return NextResponse.redirect(`https://${apexHost}${pathname}${search}`, 301);
|
||||
}
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
export const config = {
|
||||
// Run on everything except Next's static assets and the favicon.
|
||||
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"]
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue