Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(forge): add a signed Tripo webhook receiver, polling stays the fallback

nirholas6dc8c3275ad7
diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.js
index ceef9032f..23ca8f694 100644
--- a/api/_lib/forge-store.js
+++ b/api/_lib/forge-store.js
@@ -300,6 +300,53 @@ export async function findByJob({ replicateJobId, clientKey }) {
}
}
+// clientKey-agnostic sibling of findByJob, for the one caller that cannot
+// supply a clientKey: a provider webhook, which calls the server directly
+// with no cookie/session context. Returns client_key on the row so the
+// webhook handler can feed it straight into materializeCreation/markFailed,
+// which stay scoped exactly as before: this never widens their privacy
+// boundary, it only lets the webhook learn the scope it needs to use.
+export async function findByJobAnyClient({ replicateJobId }) {
+ if (!forgeStoreEnabled() || !replicateJobId) return null;
+ try {
+ const rows = await sql`
+ select id, status, glb_url, glb_key, prompt, preview_image_url,
+ views_requested, views_used, multiview, backend, tier, path, model_category,
+ user_id, created_at, destination, internal, client_key
+ from forge_creations
+ where replicate_job_id = ${replicateJobId}
+ limit 1
+ `;
+ return rows[0] ?? null;
+ } catch (err) {
+ if (isDbUnavailableError(err)) console.warn('[forge-store] findByJobAnyClient skipped (db unavailable):', err?.message);
+ else console.error('[forge-store] findByJobAnyClient failed:', err?.message);
+ return null;
+ }
+}
+
+// Idempotency claim for an inbound generation-provider webhook (Tripo), mirror
+// of claimWebhookDelivery in print/fulfillment-queries.js: the insert IS the
+// concurrency lock, so a retried delivery is a 200 no-op rather than a second
+// materialize/markFailed call.
+export async function claimForgeWebhookDelivery({ provider, deliveryId, jobId }) {
+ const rows = await sql`
+ insert into forge_webhook_deliveries (provider, delivery_id, job_id)
+ values (${provider}, ${deliveryId}, ${jobId ?? null})
+ on conflict (provider, delivery_id) do nothing
+ returning delivery_id
+ `;
+ return { fresh: rows.length > 0 };
+}
+
+export async function markForgeWebhookApplied({ provider, deliveryId }) {
+ await sql`
+ update forge_webhook_deliveries
+ set applied = true
+ where provider = ${provider} and delivery_id = ${deliveryId}
+ `;
+}
+
// Provider asset URLs are frequently short-lived (HuggingFace Spaces serve the
// mesh from an ephemeral gradio /tmp path; CDNs hiccup). Pull the bytes with a
// few quick retries so a transient network error or 5xx/429 — the dominant cause
diff --git a/api/_lib/migrations/20261015040000_forge_webhook_deliveries.sql b/api/_lib/migrations/20261015040000_forge_webhook_deliveries.sql
new file mode 100644
index 000000000..f1e29339a
--- /dev/null
+++ b/api/_lib/migrations/20261015040000_forge_webhook_deliveries.sql
@@ -0,0 +1,18 @@
+-- Idempotency ledger for signed Tripo generation webhooks (work order
+-- 084-partners-01, task 2): a delivery is claimed by inserting its id here
+-- before the body is ever parsed, so a provider retry of the same delivery is
+-- a 200 no-op rather than a second materialize/markFailed call. Mirrors
+-- print_webhook_deliveries (20260902130000_print_orders_fulfillment.sql);
+-- job_id is text, not a forge_creations uuid FK, since the webhook arrives
+-- keyed on the provider's own task id before the row is looked up.
+create table if not exists forge_webhook_deliveries (
+ provider text not null,
+ delivery_id text not null,
+ job_id text,
+ applied boolean not null default false,
+ received_at timestamptz not null default now(),
+ primary key (provider, delivery_id)
+);
+
+create index if not exists forge_webhook_deliveries_job_idx
+ on forge_webhook_deliveries (job_id, received_at desc);
diff --git a/api/forge/webhook/tripo.js b/api/forge/webhook/tripo.js
new file mode 100644
index 000000000..be7baf42a
--- /dev/null
+++ b/api/forge/webhook/tripo.js
@@ -0,0 +1,159 @@
+// @ts-check
+// POST /api/forge/webhook/tripo: Tripo reporting a text-to-model /
+// image-to-model task done or failed. Polling (pollJob in api/forge.js)
+// stays the fallback when no webhook arrives in time or TRIPO_WEBHOOK_SECRET
+// is unset; this endpoint only completes a job faster when it does.
+//
+// Same three properties as api/print/webhook/[provider].js, in the same
+// order:
+//
+// 1. AUTHENTICITY. Tripo-Webhook-Signature is `t=<unix>,v1=<hex>`, an
+// HMAC-SHA256 of `{timestamp}.{raw body}` keyed on TRIPO_WEBHOOK_SECRET,
+// constant-time compared, with a 5 minute replay window. Unverified or
+// unconfigured (no secret set) never reaches JSON.parse.
+// 2. IDEMPOTENCY. Tripo-Webhook-Delivery is claimed on forge_webhook_deliveries
+// before the payload's meaning is used, so a retried delivery is a 200
+// no-op.
+// 3. ORDERING. materializeCreation is already idempotent on job status (a
+// second completion for a 'done' row returns its durable copy without
+// re-writing it), so an out-of-order or duplicate task.completed can
+// never regress a row that a prior poll already finished.
+//
+// Deliberately minimal completion, not pollJob's full richness (quality-gate
+// scoring, result-cache population, failover redispatch): the webhook's job
+// is to materialize or fail the row fast. A client still polling after the
+// webhook lands sees the same 'done'/'failed' row and gets the full
+// pollJob response on its next poll.
+
+import { createHmac, timingSafeEqual } from 'node:crypto';
+import { error, json, method, readBody, wrap } from '../../_lib/http.js';
+import {
+ claimForgeWebhookDelivery,
+ findByJobAnyClient,
+ forgeStoreEnabled,
+ markFailed,
+ markForgeWebhookApplied,
+ materializeCreation,
+} from '../../_lib/forge-store.js';
+
+const PROVIDER = 'tripo';
+const MAX_BODY_BYTES = 256 * 1024;
+const REPLAY_WINDOW_SECONDS = 300;
+
+/**
+ * @param {string} rawBody
+ * @param {Record<string, string | string[] | undefined>} headers
+ * @returns {{ ok: boolean, reason?: string }}
+ */
+export function verifySignature(rawBody, headers) {
+ const secret = process.env.TRIPO_WEBHOOK_SECRET || '';
+ if (!secret) return { ok: false, reason: 'webhook not configured (TRIPO_WEBHOOK_SECRET unset)' };
+
+ const header = headers?.['tripo-webhook-signature'];
+ const value = Array.isArray(header) ? header[0] : header;
+ const m = /^t=(\d+),v1=([0-9a-f]+)$/i.exec(String(value || '').trim());
+ if (!m) return { ok: false, reason: 'missing or malformed Tripo-Webhook-Signature' };
+
+ const timestamp = Number(m[1]);
+ const sig = m[2].toLowerCase();
+ if (!Number.isFinite(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > REPLAY_WINDOW_SECONDS) {
+ return { ok: false, reason: 'signature timestamp outside the replay window' };
+ }
+
+ const expected = createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex');
+ const a = Buffer.from(sig, 'utf8');
+ const b = Buffer.from(expected, 'utf8');
+ if (a.length !== b.length || !timingSafeEqual(a, b)) {
+ return { ok: false, reason: 'signature mismatch' };
+ }
+ return { ok: true };
+}
+
+/** Tripo's error.message (task.failed) or a generic note. */
+function failureMessage(data) {
+ const msg = data?.error?.message || data?.error?.code;
+ return msg ? String(msg).slice(0, 500) : 'tripo task failed';
+}
+
+export default wrap(async (req, res) => {
+ if (!method(req, res, ['POST'])) return;
+
+ const raw = (await readBody(req, MAX_BODY_BYTES)).toString('utf8');
+ const verdict = verifySignature(raw, req.headers || {});
+ if (!verdict.ok) {
+ return error(res, 401, 'unauthorized', verdict.reason || 'delivery could not be verified');
+ }
+
+ if (!forgeStoreEnabled()) {
+ // 503 so Tripo retries: the delivery is genuine, we just cannot record it.
+ return error(res, 503, 'not_configured', 'forge webhooks need a configured database');
+ }
+
+ const deliveryHeader = req.headers?.['tripo-webhook-delivery'];
+ const deliveryId = String(Array.isArray(deliveryHeader) ? deliveryHeader[0] : deliveryHeader || '').trim();
+ if (!deliveryId) {
+ return error(res, 400, 'validation_error', 'missing Tripo-Webhook-Delivery header');
+ }
+
+ // Claim before parsing the body's meaning: the claim is what makes a retry
+ // harmless, and it must happen even for a payload that turns out malformed,
+ // an event type we end up ignoring (balance.low), or a task we cannot find a
+ // row for. job_id is filled in below once it's known; a claim racing ahead
+ // of that fill is still a correct, singular claim on (provider, delivery_id).
+ const { fresh } = await claimForgeWebhookDelivery({ provider: PROVIDER, deliveryId, jobId: null });
+ if (!fresh) {
+ return json(res, 200, { ok: true, duplicate: true, applied: false });
+ }
+
+ let payload;
+ try {
+ payload = JSON.parse(raw);
+ } catch {
+ return error(res, 400, 'validation_error', 'body must be JSON');
+ }
+
+ const eventType = String(payload?.type || '').trim();
+ const data = payload?.data || {};
+ const taskId = String(data?.task_id || '').trim();
+ if (!taskId) {
+ return error(res, 400, 'validation_error', 'body carries no data.task_id');
+ }
+
+ if (eventType !== 'task.completed' && eventType !== 'task.failed') {
+ // balance.low and anything future: acknowledged, not applied to a job.
+ return json(res, 200, { ok: true, applied: false, reason: `event '${eventType}' is informational` });
+ }
+
+ const existing = await findByJobAnyClient({ replicateJobId: taskId });
+ if (!existing) {
+ // Verified sender, unknown job (e.g. a task submitted before this row's
+ // retention window, or outside forge entirely). Answer 200 so Tripo stops
+ // retrying.
+ return json(res, 200, { ok: true, applied: false, reason: 'no matching job' });
+ }
+
+ let applied = true;
+ let status = existing.status;
+ if (eventType === 'task.completed') {
+ const modelUrl = data?.output?.model_url;
+ if (!modelUrl) {
+ applied = false;
+ status = existing.status;
+ } else {
+ const result = await materializeCreation({
+ replicateJobId: taskId,
+ clientKey: existing.client_key,
+ glbUrl: modelUrl,
+ });
+ status = result ? 'done' : existing.status;
+ applied = Boolean(result);
+ }
+ } else {
+ await markFailed({ replicateJobId: taskId, clientKey: existing.client_key, error: failureMessage(data) });
+ status = 'failed';
+ }
+
+ await markForgeWebhookApplied({ provider: PROVIDER, deliveryId });
+
+ return json(res, 200, { ok: true, applied, status });
+});
diff --git a/tests/api/forge-webhook-tripo.test.js b/tests/api/forge-webhook-tripo.test.js
new file mode 100644
index 000000000..4793a23fa
--- /dev/null
+++ b/tests/api/forge-webhook-tripo.test.js
@@ -0,0 +1,255 @@
+// Tripo generation webhook: authenticity first, then idempotency, then
+// ordering. Mirrors tests/print-webhook-idempotency.test.js's three
+// properties for the print fulfillment webhook, applied to forge_creations.
+//
+// 1. An unsigned or forged delivery is refused with 401 before JSON.parse.
+// 2. The claim on forge_webhook_deliveries happens before the payload's
+// meaning is used, so a retried delivery is a no-op.
+// 3. materializeCreation's own idempotency (a 'done' row short-circuits)
+// means a duplicate or out-of-order task.completed can't regress a row
+// a prior poll already finished.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { createHmac } from 'node:crypto';
+
+const SECRET = 'whsec_test_not_a_real_credential';
+
+const ledger = new Set();
+const claimForgeWebhookDelivery = vi.fn(async ({ provider, deliveryId }) => {
+ const key = `${provider}:${deliveryId}`;
+ if (ledger.has(key)) return { fresh: false };
+ ledger.add(key);
+ return { fresh: true };
+});
+const markForgeWebhookApplied = vi.fn(async () => {});
+const materializeCreation = vi.fn(async ({ replicateJobId }) => ({
+ id: 'creation-1',
+ glbUrl: `https://cdn.example.com/forge/creation-1.glb`,
+}));
+const markFailed = vi.fn(async () => {});
+const findByJobAnyClient = vi.fn(async () => ROW);
+
+vi.mock('../../api/_lib/forge-store.js', () => ({
+ claimForgeWebhookDelivery: (...a) => claimForgeWebhookDelivery(...a),
+ markForgeWebhookApplied: (...a) => markForgeWebhookApplied(...a),
+ materializeCreation: (...a) => materializeCreation(...a),
+ markFailed: (...a) => markFailed(...a),
+ findByJobAnyClient: (...a) => findByJobAnyClient(...a),
+ forgeStoreEnabled: () => true,
+}));
+
+const ROW = { id: 'creation-1', status: 'pending', client_key: 'client-1' };
+
+const handler = (await import('../../api/forge/webhook/tripo.js')).default;
+
+function mockRes() {
+ return {
+ statusCode: 200,
+ _headers: {},
+ _body: '',
+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this._headers[k.toLowerCase()]; },
+ end(b) { this._body = b || ''; },
+ get headersSent() { return false; },
+ get writableEnded() { return false; },
+ get json() { try { return JSON.parse(this._body); } catch { return null; } },
+ };
+}
+
+function sign(raw, timestamp = Math.floor(Date.now() / 1000), secret = SECRET) {
+ const sig = createHmac('sha256', secret).update(`${timestamp}.${raw}`).digest('hex');
+ return `t=${timestamp},v1=${sig}`;
+}
+
+async function deliver(body, { headers = {}, signed = true, deliveryId = 'dlv-1' } = {}) {
+ const raw = typeof body === 'string' ? body : JSON.stringify(body);
+ const res = mockRes();
+ await handler(
+ {
+ method: 'POST',
+ url: '/api/forge/webhook/tripo',
+ headers: {
+ host: 'three.ws',
+ 'content-type': 'application/json',
+ ...(signed ? { 'tripo-webhook-signature': sign(raw) } : {}),
+ 'tripo-webhook-delivery': deliveryId,
+ ...headers,
+ },
+ rawBody: Buffer.from(raw),
+ },
+ res,
+ );
+ return res;
+}
+
+const COMPLETED = {
+ id: 'evt_1',
+ type: 'task.completed',
+ created_at: new Date().toISOString(),
+ data: { task_id: 'task-42', status: 'success', output: { model_url: 'https://tripo.example/task-42.glb' } },
+};
+
+const FAILED = {
+ id: 'evt_2',
+ type: 'task.failed',
+ created_at: new Date().toISOString(),
+ data: { task_id: 'task-42', status: 'failed', error: { code: 'GENERATION_ERROR', message: 'mesh collapsed' } },
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ ledger.clear();
+ findByJobAnyClient.mockResolvedValue(ROW);
+ process.env.TRIPO_WEBHOOK_SECRET = SECRET;
+});
+
+describe('authenticity is settled before anything else happens', () => {
+ it('refuses a delivery with no TRIPO_WEBHOOK_SECRET configured', async () => {
+ delete process.env.TRIPO_WEBHOOK_SECRET;
+ const res = await deliver(COMPLETED);
+ expect(res.statusCode).toBe(401);
+ expect(claimForgeWebhookDelivery).not.toHaveBeenCalled();
+ });
+
+ it('refuses an unsigned delivery with 401', async () => {
+ const res = await deliver(COMPLETED, { signed: false });
+ expect(res.statusCode).toBe(401);
+ expect(claimForgeWebhookDelivery).not.toHaveBeenCalled();
+ });
+
+ it('refuses a forged signature and never claims a ledger row', async () => {
+ const res = await deliver(COMPLETED, { headers: { 'tripo-webhook-signature': 't=9999999999,v1=deadbeef' } });
+ expect(res.statusCode).toBe(401);
+ expect(claimForgeWebhookDelivery).not.toHaveBeenCalled();
+ });
+
+ it('refuses a signature outside the 5 minute replay window', async () => {
+ const raw = JSON.stringify(COMPLETED);
+ const stale = Math.floor(Date.now() / 1000) - 600;
+ const res = await deliver(COMPLETED, { headers: { 'tripo-webhook-signature': sign(raw, stale) } });
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('refuses a body altered in flight', async () => {
+ const raw = JSON.stringify(COMPLETED);
+ const res = mockRes();
+ await handler(
+ {
+ method: 'POST',
+ url: '/api/forge/webhook/tripo',
+ headers: {
+ host: 'three.ws',
+ 'content-type': 'application/json',
+ 'tripo-webhook-signature': sign(raw),
+ 'tripo-webhook-delivery': 'dlv-tamper',
+ },
+ rawBody: Buffer.from(raw.replace('success', 'failed')),
+ },
+ res,
+ );
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('rejects a non-POST', async () => {
+ const res = mockRes();
+ await handler({ method: 'GET', url: '/api/forge/webhook/tripo', headers: {} }, res);
+ expect(res.statusCode).toBe(405);
+ });
+});
+
+describe('a verified delivery completes the job the way polling does', () => {
+ it('materializes the creation on task.completed', async () => {
+ const res = await deliver(COMPLETED);
+ expect(res.statusCode).toBe(200);
+ expect(res.json).toMatchObject({ ok: true, applied: true, status: 'done' });
+ expect(materializeCreation).toHaveBeenCalledWith({
+ replicateJobId: 'task-42',
+ clientKey: 'client-1',
+ glbUrl: 'https://tripo.example/task-42.glb',
+ });
+ expect(markForgeWebhookApplied).toHaveBeenCalledWith({ provider: 'tripo', deliveryId: 'dlv-1' });
+ });
+
+ it('marks the job failed on task.failed, carrying the error message', async () => {
+ const res = await deliver(FAILED);
+ expect(res.statusCode).toBe(200);
+ expect(res.json).toMatchObject({ ok: true, applied: true, status: 'failed' });
+ expect(markFailed).toHaveBeenCalledWith({
+ replicateJobId: 'task-42',
+ clientKey: 'client-1',
+ error: 'mesh collapsed',
+ });
+ });
+
+ it('answers 200 for an unknown job so Tripo stops retrying', async () => {
+ findByJobAnyClient.mockResolvedValue(null);
+ const res = await deliver(COMPLETED);
+ expect(res.statusCode).toBe(200);
+ expect(res.json).toMatchObject({ ok: true, applied: false, reason: 'no matching job' });
+ expect(materializeCreation).not.toHaveBeenCalled();
+ });
+
+ it('acknowledges an informational event without touching a job', async () => {
+ const res = await deliver({ type: 'balance.low', data: { task_id: 'task-42' } });
+ expect(res.statusCode).toBe(200);
+ expect(res.json).toMatchObject({ ok: true, applied: false });
+ expect(materializeCreation).not.toHaveBeenCalled();
+ expect(markFailed).not.toHaveBeenCalled();
+ });
+});
+
+describe('a replayed delivery is applied exactly once', () => {
+ it('answers 200 duplicate on the replay and never calls materializeCreation twice', async () => {
+ await deliver(COMPLETED);
+ const replay = await deliver(COMPLETED);
+ expect(replay.statusCode).toBe(200);
+ expect(replay.json).toMatchObject({ ok: true, duplicate: true, applied: false });
+ expect(materializeCreation).toHaveBeenCalledTimes(1);
+ });
+
+ it('stays at one even after five retries of the same delivery id', async () => {
+ for (let i = 0; i < 5; i += 1) await deliver(COMPLETED);
+ expect(materializeCreation).toHaveBeenCalledTimes(1);
+ });
+
+ it('claims the delivery before parsing, so malformed JSON cannot be replayed', async () => {
+ const res = await deliver('{not json');
+ expect(res.statusCode).toBe(400);
+ expect(claimForgeWebhookDelivery).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('the database being unavailable makes Tripo retry', () => {
+ it('returns 503 when forgeStoreEnabled() is false', async () => {
+ vi.resetModules();
+ vi.doMock('../../api/_lib/forge-store.js', () => ({
+ claimForgeWebhookDelivery,
+ markForgeWebhookApplied,
+ materializeCreation,
+ markFailed,
+ findByJobAnyClient,
+ forgeStoreEnabled: () => false,
+ }));
+ const fresh = (await import('../../api/forge/webhook/tripo.js')).default;
+ const res = await (async () => {
+ const raw = JSON.stringify(COMPLETED);
+ const r = mockRes();
+ await fresh(
+ {
+ method: 'POST',
+ url: '/api/forge/webhook/tripo',
+ headers: {
+ host: 'three.ws',
+ 'content-type': 'application/json',
+ 'tripo-webhook-signature': sign(raw),
+ 'tripo-webhook-delivery': 'dlv-db-down',
+ },
+ rawBody: Buffer.from(raw),
+ },
+ r,
+ );
+ return r;
+ })();
+ expect(res.statusCode).toBe(503);
+ });
+});