From 54ec1a49259d9e7ca5a7acca5a4420b78b56e0b2 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Wed, 21 Oct 2026 05:02:09 -0700 Subject: [PATCH] fix(coinpay): settle paid Hire Us checkouts from the signed webhook (#252) The CoinPay webhook only logged. It now verifies X-CoinPay-Signature (t=,v1= over t.rawBody), reads the nested payload (data.payment_id, not the top-level event id), and records a confirmed/forwarded Hire Us payment once in hire_us_payments (payment_id primary key), mapped to the buyer via metadata.account_id/email. Unknown or pending payments are a 200 no-op. Hire Us checkout now sends property, account_id (CoinPay session) and email in metadata. Co-authored-by: Claude Opus 5.5 --- .../contract/coinpay-webhook.contract.test.ts | 92 ++++++++++++++ .../contract/logicsrc-web.contract.test.ts | 5 +- .../app/api/hire-us/coinpay-checkout/route.ts | 26 +++- .../src/app/api/webhooks/coinpay/route.ts | 26 ++-- apps/logicsrc-web/src/lib/coinpay-webhook.ts | 114 ++++++++++++++++++ apps/logicsrc-web/src/lib/hire-us-payments.ts | 17 +++ .../20261021010000_hire_us_payments.sql | 28 +++++ 7 files changed, 292 insertions(+), 16 deletions(-) create mode 100644 apps/logicsrc-web/contract/coinpay-webhook.contract.test.ts create mode 100644 apps/logicsrc-web/src/lib/coinpay-webhook.ts create mode 100644 apps/logicsrc-web/src/lib/hire-us-payments.ts create mode 100644 supabase/migrations/20261021010000_hire_us_payments.sql diff --git a/apps/logicsrc-web/contract/coinpay-webhook.contract.test.ts b/apps/logicsrc-web/contract/coinpay-webhook.contract.test.ts new file mode 100644 index 00000000..eae8f2cc --- /dev/null +++ b/apps/logicsrc-web/contract/coinpay-webhook.contract.test.ts @@ -0,0 +1,92 @@ +import { createHmac } from "node:crypto"; +import { describe, expect, it } from "vitest"; + +import { verifyCoinPayWebhook } from "@/lib/coinpay"; +import { readCoinPayWebhook, settleHireUsWebhook, type HireUsPaymentRow } from "@/lib/coinpay-webhook"; + +const SECRET = "whsecret_logicsrcContractTestSecret"; + +// Same signing as coinpayportal signWebhookPayload: t=,v1=hmac(`${t}.${body}`). +function sign(rawBody: string, ts = Math.floor(Date.now() / 1000)) { + return `t=${ts},v1=${createHmac("sha256", SECRET).update(`${ts}.${rawBody}`).digest("hex")}`; +} + +const PAYMENT_ID = "d084f959-c33c-4540-82b8-221181347639"; +function realShaped(status = "confirmed", type = "payment.confirmed") { + return { + id: `evt_${PAYMENT_ID}_1775551263`, + type, + data: { + payment_id: PAYMENT_ID, + status, + amount: 4000, + amount_crypto: "4000.000000", + amount_usd: 4000, + currency: "USDC_POL", + metadata: { + product: "logicsrc-hire-us", + billing: "metered_hours", + unit: "agent_hour", + hours: 10, + rate_usd_per_hour: 400, + source: "logicsrc.com/hire-us", + property: "logicsrc.com", + account_id: "coinpay-user-123", + email: "buyer@example.com" + } + }, + created_at: "2026-10-21T00:00:00.000Z", + business_id: "biz_1" + }; +} + +function memoryStore() { + const rows = new Map(); + return { + rows, + async insertIfAbsent(row: HireUsPaymentRow) { + if (rows.has(row.payment_id)) return false; + rows.set(row.payment_id, row); + return true; + } + }; +} + +describe("CoinPay webhook (logicsrc Hire Us)", () => { + it("verifies the X-CoinPay-Signature t=,v1= scheme over the raw body", () => { + const raw = JSON.stringify(realShaped()); + expect(verifyCoinPayWebhook(raw, sign(raw), SECRET)).toBe(true); + expect(verifyCoinPayWebhook(raw + " ", sign(raw), SECRET)).toBe(false); + expect(verifyCoinPayWebhook(raw, sign(raw, Math.floor(Date.now() / 1000) - 600), SECRET)).toBe(false); + expect(verifyCoinPayWebhook(raw, createHmac("sha256", SECRET).update(raw).digest("hex"), SECRET)).toBe(false); + }); + + it("reads the payment id from data, not the top-level event id", () => { + const e = readCoinPayWebhook(realShaped()); + expect(e.paymentId).toBe(PAYMENT_ID); + expect(e.eventId).toMatch(/^evt_/); + expect(e.metadata.account_id).toBe("coinpay-user-123"); + }); + + it("settles a paid Hire Us payment once, mapped to the account", async () => { + const store = memoryStore(); + const payload = JSON.parse(JSON.stringify(realShaped())); + const first = await settleHireUsWebhook(payload, store); + expect(first).toMatchObject({ settled: true, duplicate: false, payment_id: PAYMENT_ID, account_id: "coinpay-user-123" }); + const row = store.rows.get(PAYMENT_ID)!; + expect(row).toMatchObject({ amount_usd: 4000, hours: 10, buyer_email: "buyer@example.com", property: "logicsrc.com" }); + + const again = await settleHireUsWebhook(realShaped("forwarded", "payment.forwarded"), store); + expect(again).toMatchObject({ settled: true, duplicate: true }); + expect(store.rows.size).toBe(1); + }); + + it("acknowledges pending and unknown payments without recording", async () => { + const store = memoryStore(); + expect(await settleHireUsWebhook(realShaped("pending", "payment.pending"), store)).toMatchObject({ settled: false }); + const foreign = realShaped(); + foreign.data.metadata = {} as typeof foreign.data.metadata; + expect(await settleHireUsWebhook(foreign, store)).toMatchObject({ settled: false, reason: "unknown payment" }); + expect(store.rows.size).toBe(0); + }); +}); diff --git a/apps/logicsrc-web/contract/logicsrc-web.contract.test.ts b/apps/logicsrc-web/contract/logicsrc-web.contract.test.ts index a5fcfe25..c6ee24d3 100644 --- a/apps/logicsrc-web/contract/logicsrc-web.contract.test.ts +++ b/apps/logicsrc-web/contract/logicsrc-web.contract.test.ts @@ -199,6 +199,8 @@ describe("POST /api/hire-us/coinpay-checkout", () => { hours: 10, rate_usd_per_hour: 400, source: "logicsrc.com/hire-us", + property: "logicsrc.com", + email: "buyer@example.com", buyer_email: "buyer@example.com" } }); @@ -556,6 +558,7 @@ describe("POST /api/webhooks/coinpay", () => { const body = await response.json(); expect(response.status).toBe(200); - expect(body).toEqual({ received: true, complete: true, payment_id: "pay_123" }); + // No Hire Us metadata: acknowledged as a handled no-op, nothing recorded. + expect(body).toEqual({ received: true, handled: true, settled: false, reason: "unknown payment", payment_id: "pay_123" }); }); }); diff --git a/apps/logicsrc-web/src/app/api/hire-us/coinpay-checkout/route.ts b/apps/logicsrc-web/src/app/api/hire-us/coinpay-checkout/route.ts index de58a61d..07c4d5b6 100644 --- a/apps/logicsrc-web/src/app/api/hire-us/coinpay-checkout/route.ts +++ b/apps/logicsrc-web/src/app/api/hire-us/coinpay-checkout/route.ts @@ -1,6 +1,12 @@ import type { NextRequest } from "next/server"; import { json } from "@/lib/http"; -import { choosePaymentRail, fetchMerchantEligibility, parseJson } from "@/lib/coinpay"; +import { + COINPAY_SESSION_COOKIE, + choosePaymentRail, + fetchMerchantEligibility, + parseJson, + verifySession +} from "@/lib/coinpay"; export const dynamic = "force-dynamic"; @@ -37,7 +43,19 @@ export async function POST(request: NextRequest) { try { const body = (await request.json().catch(() => ({}))) as Record; - const buyerEmail = typeof body.email === "string" ? body.email.trim().slice(0, 160) : ""; + // A signed-in CoinPay session (OAuth cookie) identifies the account; the + // webhook maps the settled payment back to it via metadata.account_id. + const sessionCookie = request.cookies.get(COINPAY_SESSION_COOKIE)?.value; + let session: Record | null = null; + try { + session = sessionCookie ? verifySession(sessionCookie) : null; + } catch { + session = null; + } + const accountId = typeof session?.sub === "string" ? session.sub : ""; + const sessionEmail = typeof session?.email === "string" ? session.email : ""; + const bodyEmail = typeof body.email === "string" ? body.email.trim().slice(0, 160) : ""; + const buyerEmail = bodyEmail || sessionEmail; const hours = body.hours === undefined ? MINIMUM_HOURS : parseHours(body.hours); if (hours === null) { @@ -82,7 +100,9 @@ export async function POST(request: NextRequest) { hours, rate_usd_per_hour: RATE_USD_PER_HOUR, source: "logicsrc.com/hire-us", - ...(buyerEmail ? { buyer_email: buyerEmail } : {}) + property: "logicsrc.com", + ...(accountId ? { account_id: accountId } : {}), + ...(buyerEmail ? { email: buyerEmail, buyer_email: buyerEmail } : {}) } }) }); diff --git a/apps/logicsrc-web/src/app/api/webhooks/coinpay/route.ts b/apps/logicsrc-web/src/app/api/webhooks/coinpay/route.ts index 2d06bf10..1587e898 100644 --- a/apps/logicsrc-web/src/app/api/webhooks/coinpay/route.ts +++ b/apps/logicsrc-web/src/app/api/webhooks/coinpay/route.ts @@ -1,10 +1,14 @@ import type { NextRequest } from "next/server"; import { json } from "@/lib/http"; import { parseJson, verifyCoinPayWebhook } from "@/lib/coinpay"; +import { settleHireUsWebhook } from "@/lib/coinpay-webhook"; +import { supabaseHireUsPaymentStore } from "@/lib/hire-us-payments"; export const dynamic = "force-dynamic"; -// POST /api/webhooks/coinpay — verify the signed CoinPay webhook and acknowledge. +// POST /api/webhooks/coinpay — verify the signed CoinPay webhook +// (X-CoinPay-Signature: t=,v1=) and settle a +// paid Hire Us checkout exactly once, keyed on data.payment_id. export async function POST(request: NextRequest) { const webhookSecret = process.env.COINPAY_WEBHOOK_SECRET; if (!webhookSecret) { @@ -18,15 +22,13 @@ export async function POST(request: NextRequest) { } const payload = parseJson(rawBody); - const data = payload.data as Record | 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 }); + try { + const result = await settleHireUsWebhook(payload, supabaseHireUsPaymentStore()); + console.log("[coinpay] webhook", { type: payload.type ?? null, ...result }); + return json({ received: true, ...result }); + } catch (error) { + // 500 so CoinPay retries: the payment is real but we could not record it. + console.error("[coinpay] webhook settle failed", error); + return json({ received: false, error: "settlement failed" }, 500); + } } diff --git a/apps/logicsrc-web/src/lib/coinpay-webhook.ts b/apps/logicsrc-web/src/lib/coinpay-webhook.ts new file mode 100644 index 00000000..6a65aca8 --- /dev/null +++ b/apps/logicsrc-web/src/lib/coinpay-webhook.ts @@ -0,0 +1,114 @@ +// CoinPay webhook reading + Hire Us settlement. +// +// CoinPay signs and sends a NESTED body (coinpayportal src/lib/webhooks/service.ts): +// { id: "evt__", type: "payment.confirmed", +// data: { payment_id, status, amount, amount_usd, metadata: {...} }, +// created_at, business_id } +// The top-level `id` is the EVENT id, not the payment id. Read `data` first and +// fall back to the flat shape only for the legacy test sender. + +export interface CoinPayWebhookEvent { + eventId: string | null; + type: string | null; + paymentId: string | null; + status: string; + amountUsd: number | null; + metadata: Record; +} + +// `forwarded` counts: CoinPay retries a failed payment.forwarded delivery, while +// a failed payment.confirmed stops retrying after a few minutes. +const SETTLED_STATUSES = new Set(["confirmed", "forwarded", "completed", "paid"]); +const SETTLED_TYPES = new Set(["payment.confirmed", "payment.forwarded"]); + +export const HIRE_US_PRODUCT = "logicsrc-hire-us"; + +function asRecord(value: unknown): Record | null { + return value && typeof value === "object" && !Array.isArray(value) ? (value as Record) : null; +} + +function asString(value: unknown): string | null { + return typeof value === "string" && value.trim() ? value.trim() : null; +} + +function asNumber(value: unknown): number | null { + const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN; + return Number.isFinite(n) ? n : null; +} + +export function readCoinPayWebhook(payload: Record): CoinPayWebhookEvent { + const nested = asRecord(payload.data); + const d = nested ?? payload; + const paymentId = asString(d.payment_id) ?? (nested ? asString(nested.id) : asString(payload.payment_id)); + const type = asString(payload.type) ?? asString(payload.event); + let status = (asString(d.status) ?? "").toLowerCase(); + if (!status && type && SETTLED_TYPES.has(type)) status = type.slice("payment.".length); + return { + eventId: nested ? asString(payload.id) : null, + type, + paymentId, + status, + amountUsd: asNumber(d.amount_usd) ?? asNumber(d.amount), + metadata: asRecord(d.metadata) ?? asRecord(payload.metadata) ?? {} + }; +} + +export function isSettled(event: CoinPayWebhookEvent): boolean { + return SETTLED_STATUSES.has(event.status); +} + +export interface HireUsPaymentRow { + payment_id: string; + event_id: string | null; + event_type: string | null; + status: string; + amount_usd: number | null; + hours: number | null; + rate_usd_per_hour: number | null; + account_id: string | null; + buyer_email: string | null; + property: string | null; + metadata: Record; +} + +export interface HireUsPaymentStore { + /** Insert once; resolve true if this call created the row, false if it already existed. */ + insertIfAbsent(row: HireUsPaymentRow): Promise; +} + +export type SettleResult = + | { handled: true; settled: true; duplicate: boolean; payment_id: string; account_id: string | null; email: string | null } + | { handled: true; settled: false; reason: string; payment_id: string | null }; + +export async function settleHireUsWebhook( + payload: Record, + store: HireUsPaymentStore +): Promise { + const event = readCoinPayWebhook(payload); + if (!event.paymentId) return { handled: true, settled: false, reason: "no payment id", payment_id: null }; + if (!isSettled(event)) { + return { handled: true, settled: false, reason: `status ${event.status || "unknown"}`, payment_id: event.paymentId }; + } + const meta = event.metadata; + if (meta.product !== HIRE_US_PRODUCT) { + // Not a Hire Us checkout (or an unknown/test payment): acknowledge, do nothing. + return { handled: true, settled: false, reason: "unknown payment", payment_id: event.paymentId }; + } + + const accountId = asString(meta.account_id); + const email = asString(meta.email) ?? asString(meta.buyer_email); + const inserted = await store.insertIfAbsent({ + payment_id: event.paymentId, + event_id: event.eventId, + event_type: event.type, + status: event.status, + amount_usd: event.amountUsd, + hours: asNumber(meta.hours), + rate_usd_per_hour: asNumber(meta.rate_usd_per_hour), + account_id: accountId, + buyer_email: email, + property: asString(meta.property), + metadata: meta + }); + return { handled: true, settled: true, duplicate: !inserted, payment_id: event.paymentId, account_id: accountId, email }; +} diff --git a/apps/logicsrc-web/src/lib/hire-us-payments.ts b/apps/logicsrc-web/src/lib/hire-us-payments.ts new file mode 100644 index 00000000..205b795a --- /dev/null +++ b/apps/logicsrc-web/src/lib/hire-us-payments.ts @@ -0,0 +1,17 @@ +import { serviceClient } from "@/lib/supabase"; +import type { HireUsPaymentRow, HireUsPaymentStore } from "@/lib/coinpay-webhook"; + +// Supabase-backed store for settled Hire Us payments (table hire_us_payments, +// payment_id primary key). ignoreDuplicates makes a redelivery a no-op. +export function supabaseHireUsPaymentStore(): HireUsPaymentStore { + return { + async insertIfAbsent(row: HireUsPaymentRow) { + const { data, error } = await serviceClient() + .from("hire_us_payments") + .upsert(row, { onConflict: "payment_id", ignoreDuplicates: true }) + .select("payment_id"); + if (error) throw new Error(`hire_us_payments insert failed: ${error.message}`); + return Array.isArray(data) && data.length > 0; + } + }; +} diff --git a/supabase/migrations/20261021010000_hire_us_payments.sql b/supabase/migrations/20261021010000_hire_us_payments.sql new file mode 100644 index 00000000..e3201327 --- /dev/null +++ b/supabase/migrations/20261021010000_hire_us_payments.sql @@ -0,0 +1,28 @@ +-- Settled CoinPay payments for Hire Us (metered agent-hours). +-- Written only by the signed CoinPay webhook (/api/webhooks/coinpay) through the +-- service-role key. payment_id is CoinPay's payment id (data.payment_id in the +-- webhook, NOT the top-level event id), unique so a redelivered or duplicate +-- event can never book the same purchase twice. + +create table if not exists public.hire_us_payments ( + payment_id text primary key, + event_id text, + event_type text, + status text not null, + amount_usd numeric(12, 2), + hours numeric(10, 2), + rate_usd_per_hour numeric(10, 2), + account_id text, + buyer_email text, + property text, + metadata jsonb not null default '{}'::jsonb, + paid_at timestamptz not null default now(), + created_at timestamptz not null default now() +); + +create index if not exists hire_us_payments_account_idx on public.hire_us_payments (account_id); +create index if not exists hire_us_payments_email_idx on public.hire_us_payments (buyer_email); + +-- No policies: anon/authenticated cannot read or write; the service role bypasses RLS. +alter table public.hire_us_payments enable row level security; +grant all on public.hire_us_payments to service_role;