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(print): confirm a Materialize order against its on-chain payment and cap the lane per IP

nirholas88cdfbc03277
diff --git a/STRUCTURE.md b/STRUCTURE.md
index b6a5d1f9f..0c7a97acf 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -157,6 +157,7 @@ bottom.
| Forge-Off (community voting + weekly board) | Store [api/_lib/forge-store.js](api/_lib/forge-store.js) (`castVote`/`removeVote`/`listShowcase` sort+voter/`forgeOffWeekStart`), endpoint [api/forge-vote.js](api/forge-vote.js), board read [api/forge-gallery.js](api/forge-gallery.js) (`scope=community&sort=top&window=week`), weekly crown cron [api/cron/forge-off-crown.js](api/cron/forge-off-crown.js) (`7 0 * * 1`), UI [src/forge-showcase.js](src/forge-showcase.js) + `/forge-studio` twin [src/forge-studio/forge-showcase.js](src/forge-studio/forge-showcase.js), schema [migration 20260625120000_forge_board.sql](api/_lib/migrations/20260625120000_forge_board.sql) | Live | Turns the "Fresh from the Forge" strip on [/forge](pages/forge.html) into a live board: auth-free upvotes (one per browser, keyed to the same `forge:cid` id as "Your creations"), a Fresh/Top-this-week sort toggle, optimistic vote pills that reconcile against the authoritative `vote_count` (recomputed from `forge_votes`, never a drifting counter), and a Monday-00:07-UTC cron that permanently crowns each week's top-voted creation into `forge_board_winners`. The crown is the writer the [Sketchfab showcase](docs/sketchfab.md) cron's strongest tier had been waiting on. Docs: [docs/forge-off.md](docs/forge-off.md). Tests: [tests/api/forge-gallery-community.test.js](tests/api/forge-gallery-community.test.js) |
| Realism quality bench | Benchmark [data/quality-bench/prompts.json](data/quality-bench/prompts.json) (23 fixed prompts + 3 CC0 reference photos), runner [scripts/quality-bench.mjs](scripts/quality-bench.mjs), shared generate/render/judge core [api/_lib/quality-bench.js](api/_lib/quality-bench.js), dashboard [api/quality-bench.js](api/quality-bench.js) + [pages/quality-bench.html](pages/quality-bench.html) `→ /quality-bench` (internal, not in `data/pages.json`), weekly smoke cron [api/cron/quality-bench.js](api/cron/quality-bench.js) (`23 3 * * 1`) | Live | The measurement loop the realism campaign hangs on: fires the fixed prompt set through the real `/api/forge` path, renders 3 canonical views per result with the same headless three.js renderer as the avatar clip/OG-card renders ([api/_lib/render-clip.js](api/_lib/render-clip.js)), and scores every view with Vertex Gemini vision (`gemini-2.5-pro`, temperature 0, scored twice and averaged, judge never sees forge's internal prompt-enhancement text). Runs are committed append-only JSON under `data/quality-bench/runs/`; the dashboard renders score trends by lane/tier/subject-class, a worst-5 critique gallery, and the full results table. `node scripts/quality-bench.mjs --compare=latest,previous` exits nonzero on a >1.0 mean drop — run it before/after any forge change that could affect quality. Docs: [data/quality-bench/README.md](data/quality-bench/README.md). |
| Likeness bench (Phase 1 verification metric) | Scoring core [api/_lib/likeness-score.js](api/_lib/likeness-score.js), face-embedding runtime [api/_lib/face-embed.js](api/_lib/face-embed.js), store + distribution queries [api/_lib/likeness-store.js](api/_lib/likeness-store.js) ([schema](api/_lib/migrations/20260814000000_avatar_likeness_scores.sql)), weekly sweep [api/cron/likeness-eval.js](api/cron/likeness-eval.js) (`47 3 * * 1`), by-hand runner [scripts/likeness-eval.mjs](scripts/likeness-eval.mjs), internal board [api/likeness-bench.js](api/likeness-bench.js) + [pages/likeness-bench.html](pages/likeness-bench.html) `→ /likeness-bench` (admin or `x-ops-secret`, not in `data/pages.json`) | Live · applied 2026-08-14 (this file alone, via `apply-migrations.mjs --apply --file`, because `db:migrate` would have applied seven other agents' pending migrations with it). The header comment still reads "Draft, NOT applied" and must stay that way: an applied migration is an immutable record and editing its bytes trips the drift guard | The number the roadmap gates Phase 1 on, measured instead of asserted. The realism bench scores whether a generation looks real and never asks whose face it is; the reconstruction worker's ISE eval scores face *shape* offline against a synthetic set and stores nothing. This closes the gap: it renders a finished reconstruction head-framed at three yaws (head-on 0°, three-quarter 35°, profile 65°) with the platform's own `headshot` preset, embeds every render and every input capture with OSS face recognition (YuNet detection, MIT + SFace 128-d identity, Apache-2.0, both hash-pinned from OpenCV Zoo and run on `onnxruntime-web`'s WASM backend so there is no native install step), and files a 1-5 score against the generation record in `forge_creations`. The 1-5 mapping is anchored on SFace's own published decision boundary (cosine 0.363 = 3.0, so the roadmap's 4/5 gate is cosine 0.68, roughly twice the same-identity threshold) rather than on taste. **Refuses rather than fabricates:** `captures_unusable`, `render_unusable` and a genuinely low score are three separate statuses, and a budget-truncated sweep is withheld from the distribution. Reports `turn_falloff` (identity lost between head-on and the worst view), which is the only place a frontally-flattering texture transfer is visible. **Stores no biometrics:** no capture URLs, no crops, no embeddings, only the measurement. Docs: [docs/likeness-eval.md](docs/likeness-eval.md). Tests: [tests/likeness-score.test.js](tests/likeness-score.test.js) |
+| Payment-outcome board (x402 failure visibility) | Endpoint [api/ops/payment-outcomes.js](api/ops/payment-outcomes.js), page [pages/payment-outcomes.html](pages/payment-outcomes.html) `-> /payment-outcomes` (admin session or `x-ops-secret`, `noindex`, not in `data/pages.json`), sensors [api/_lib/ops/x402-settle-health.js](api/_lib/ops/x402-settle-health.js) + [api/_lib/x402/wallet-balance-monitor.js](api/_lib/x402/wallet-balance-monitor.js) + [api/_lib/x402/sponsor-runway.js](api/_lib/x402/sponsor-runway.js) + [api/_lib/custodial-key-health.js](api/_lib/custodial-key-health.js) | Live | Every way an x402 payment can fail, in one read, before it halts the economy. The 2026-07-11 audit found the griefing classes (verify-reject floods, settle failures, sponsor-fee starvation) were only visible after the economy stopped: `recordPaymentMetric` was already emitting the events and nothing surfaced them. Four panels: inbound rates over 1h/3h/24h from the durable `x402_audit_log` (settle success, verify reject, replay reject with its own `inbound_attempts` denominator, top failure reasons by stage, replay stage split), the outbound ring settle sensor with its triage hint, every configured ring wallet against **its own** floor plus the measured sponsor runway, and stranded custody. The wallet panel is per-wallet on purpose: settle-floor starvation and dry wallets look identical from outside and have opposite fixes, and a board showing only the sponsor renders a starved payer as healthy. Panels are read independently and a failed one names itself in `degraded` (207 Multi-Status) rather than blanking the board; on the page a rate with no attempts renders `n/a` and an unmeasured custody total renders `not measured`, because a green zero on a reading that never happened is worse than no board. Docs: [docs/ops/payment-outcomes.md](docs/ops/payment-outcomes.md). |
| Sketchfab showcase (community models → official account) | Cron [api/cron/sketchfab-showcase.js](api/cron/sketchfab-showcase.js), lib [api/_lib/sketchfab.js](api/_lib/sketchfab.js), ledger migration [api/_lib/migrations/20260714130000_sketchfab_uploads.sql](api/_lib/migrations/20260714130000_sketchfab_uploads.sql) | Live · dormant until `SKETCHFAB_API_TOKEN` is set | Publishes the best community forge models to the official three.ws Sketchfab account, prompt and backlink included. Selection order: forge-board winners (now populated by the [Forge-Off](docs/forge-off.md) crown cron), then top-voted (>=1 vote), then creator-accepted (accepted or downloaded, refinement children excluded, title-quality heuristic). Brand safety is two layers: a SQL denylist plus NemoGuard re-moderation; blocked rows park as `blocked` in the `sketchfab_uploads` ledger (states `pending`/`uploaded`/`live`/`failed`/`blocked`). `?dry_run=1` exercises selection before the token is wired; `SKETCHFAB_UPLOADS_PER_RUN` clamps 1-5 (default 2). Docs: [docs/sketchfab.md](docs/sketchfab.md) |
| Third-party display-name safety | [api/_lib/display-name-safety.js](api/_lib/display-name-safety.js), applied at ERC-8004 metadata hydration in [api/cron/[name].js](api/cron/%5Bname%5D.js) | Live | The ERC-8004 crawler indexes 126k+ on-chain agents and renders each one's `name`/`description`/`image` from attacker-controlled metadata. Visibility used to be decided solely by the agent's own `meta.active`, so a Base-registered agent whose name was a racial slur shipped to `/marketplace`. `matchedSlurStem()` now withholds such rows (`active = false`), which removes them from every feed at once since explore/marketplace/agents/search all filter `active = true`. Deliberately narrow — **whole-word** hate slurs only, never general profanity, and hex-address aware: leet folding turns `0xdb6b887289c380…` into letter soup, so long alphanumeric runs are excluded from the spaced-out-evasion pass. A false positive silently delists a legitimate agent, so precision outranks recall. Backfill for already-indexed rows: [scripts/deactivate-slur-agents.mjs](scripts/deactivate-slur-agents.mjs) (`--dry-run`). Tests: [tests/display-name-safety.test.js](tests/display-name-safety.test.js) — pins the real agent names an earlier substring matcher wrongly flagged. |
| FBX → GLB conversion | [scripts/fbx-to-glb.mjs](scripts/fbx-to-glb.mjs) | In-repo | Skinned/animated FBX → GLB (FBX2glTF), `npm run convert:fbx` |
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 3704273cf..457065a9a 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -2012,6 +2012,14 @@ export const limits = {
// stopping a script from using the analyzer as a free mesh-processing service.
printQuoteIp: (ip) =>
getLimiter('print:quote:ip', { limit: 90, window: '5 m', local: true }).limit(ip),
+ // Materialize checkout (api/print/orders.js and its confirm step). Both are
+ // session-gated and CSRF-gated already, so this is not the security boundary;
+ // it caps how often one IP can open orders or poll the chain for a payment.
+ // NOT local: the confirm path spends the shared Solana RPC allowance, and a
+ // per-instance counter would multiply by however many Cloud Run instances are
+ // up, which is exactly the bypass that makes an RPC cap meaningless.
+ printOrderIp: (ip) =>
+ getLimiter('print:order:ip', { limit: 60, window: '5 m' }).limit(ip),
};
// ── Fail-closed limiter call for privacy-boundary reads (H7) ─────────────────
diff --git a/api/print/orders/[id]/confirm.js b/api/print/orders/[id]/confirm.js
new file mode 100644
index 000000000..761050484
--- /dev/null
+++ b/api/print/orders/[id]/confirm.js
@@ -0,0 +1,183 @@
+// POST /api/print/orders/:id/confirm: prove the USDC landed, then start the job.
+//
+// This endpoint reads the chain and writes the database. It never sends a
+// transaction, never touches a key, and never moves anyone's money: the buyer
+// already paid from their own wallet, and all this does is find that payment
+// and check it.
+//
+// The proof is Solana Pay's reference mechanism, the same one the marketplace
+// settles on. When the order was created it generated a reference pubkey and
+// asked the buyer to attach it to their transfer. findReference() locates the
+// transaction that carries it, and validateTransfer() then asserts the strict
+// facts: the right mint, the right recipient, at least the quoted amount, with
+// the reference on the final instruction. Any of those failing is a refusal,
+// not a partial credit.
+//
+// A payment that has not landed yet answers 202 with status "pending" rather
+// than an error, because the buyer's wallet may still be broadcasting and a red
+// error on a payment that is about to confirm is the worst moment to lie.
+//
+// On success the order moves paid -> screening in one call: screening is the
+// fabrication-safety gate that runs a second time now that money is committed,
+// and leaving a paid order sitting in `paid` would mean a job nobody picked up.
+
+import { PublicKey } from '@solana/web3.js';
+import { findReference, validateTransfer } from '@solana/pay';
+import BigNumber from 'bignumber.js';
+
+import { cors, error, json, method, rateLimited, wrap } from '../../../_lib/http.js';
+import { clientIp, limits } from '../../../_lib/rate-limit.js';
+import { getSessionUser } from '../../../_lib/auth.js';
+import { requireCsrf } from '../../../_lib/csrf.js';
+import { env } from '../../../_lib/env.js';
+import { rpcFallbackFromEnv } from '../../../_lib/solana/rpc-fallback.js';
+import { PrintStoreError, getOrderWithEvents, transition } from '../../../_lib/print-store.js';
+import { publicOrder } from '../[id].js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const USDC_DECIMALS = 6;
+
+let _rpc;
+function rpc() {
+ if (!_rpc) _rpc = rpcFallbackFromEnv({ network: 'mainnet' });
+ return _rpc;
+}
+
+/** True when findReference simply has not seen the payment yet. */
+function isNotFound(err) {
+ return /FindReferenceError|not found/i.test(String(err?.message || ''));
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const id = String(req.query?.id || '').trim();
+ if (!UUID_RE.test(id)) return error(res, 400, 'validation_error', 'invalid order id');
+
+ const user = await getSessionUser(req).catch(() => null);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in to confirm an order');
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ // Confirming is a chain read per call, so it gets the write bucket rather
+ // than the read one: a client polling this in a tight loop is what would
+ // otherwise burn the RPC allowance.
+ const rl = await limits.printOrderIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl, 'too many confirmation attempts');
+
+ const order = await getOrderWithEvents(id);
+ if (!order || order.user_id !== user.id) {
+ return error(res, 404, 'not_found', 'no such print order');
+ }
+
+ // Already settled: answer with the order rather than re-reading the chain.
+ // A double-clicked confirm button must be a no-op, not a second verification.
+ if (order.status !== 'quoted') {
+ if (order.paid_at) {
+ return json(res, 200, { status: 'confirmed', order: publicOrder(order) }, { 'cache-control': 'no-store' });
+ }
+ return error(res, 409, 'not_awaiting_payment', `this order is ${order.status} and is not waiting for a payment`);
+ }
+
+ if (!order.payment_reference) {
+ return error(res, 409, 'no_payment_intent', 'this order has no payment reference to check');
+ }
+ if (order.quote_expires_at && new Date(order.quote_expires_at) < new Date()) {
+ return error(res, 410, 'quote_expired', 'this quote expired before it was paid. Request a fresh quote and order again.');
+ }
+
+ const payTo = env.X402_PAY_TO_SOLANA;
+ const mint = env.X402_ASSET_MINT_SOLANA;
+ if (!payTo || !mint) {
+ return error(res, 503, 'checkout_unavailable', 'Solana USDC checkout is not configured on this deployment');
+ }
+
+ const referenceKey = new PublicKey(order.payment_reference);
+
+ let signatureInfo;
+ try {
+ signatureInfo = await rpc().withFallback((conn) => findReference(conn, referenceKey, { finality: 'confirmed' }));
+ } catch (err) {
+ if (isNotFound(err)) {
+ return json(
+ res,
+ 202,
+ { status: 'pending', message: 'No payment carrying this order\'s reference has confirmed yet.' },
+ { 'cache-control': 'no-store' },
+ );
+ }
+ throw err;
+ }
+
+ const signature = signatureInfo.signature;
+ const expected = new BigNumber(String(order.price_usdc)).decimalPlaces(USDC_DECIMALS);
+
+ try {
+ await rpc().withFallback((conn) =>
+ validateTransfer(
+ conn,
+ signature,
+ {
+ recipient: new PublicKey(payTo),
+ amount: expected,
+ splToken: new PublicKey(mint),
+ reference: referenceKey,
+ },
+ { commitment: 'confirmed' },
+ ),
+ );
+ } catch (err) {
+ // A transaction that carries our reference but does not satisfy the
+ // transfer is a real problem the buyer needs to see, with the signature so
+ // they can look at it themselves. It is deliberately not written to the
+ // order: nothing here can prove what that transaction was for.
+ return error(res, 422, 'payment_mismatch', `a transaction carrying this order's reference did not transfer ${expected.toString()} USDC to the platform wallet`, {
+ signature,
+ explorer_url: `https://solscan.io/tx/${signature}`,
+ expected_usdc: expected.toString(),
+ detail: String(err?.message || err).slice(0, 200),
+ });
+ }
+
+ try {
+ await transition({
+ orderId: order.id,
+ to: 'paid',
+ note: `USDC payment confirmed on Solana: ${signature}`,
+ actor: 'buyer',
+ actorId: user.id,
+ patch: {
+ payment_signature: signature,
+ payment_chain: 'solana',
+ payment_amount_atomics: expected.multipliedBy(10 ** USDC_DECIMALS).toFixed(0),
+ },
+ });
+ await transition({
+ orderId: order.id,
+ to: 'screening',
+ note: 'Queued for the fabrication safety screen.',
+ actor: 'system',
+ });
+ } catch (err) {
+ if (err instanceof PrintStoreError) {
+ // The payment is real and on chain; only the state move failed. Say so
+ // with the signature attached rather than implying the money vanished.
+ return error(res, 409, err.code, err.message, { signature, explorer_url: `https://solscan.io/tx/${signature}` });
+ }
+ throw err;
+ }
+
+ const settled = await getOrderWithEvents(order.id);
+ return json(
+ res,
+ 200,
+ {
+ status: 'confirmed',
+ signature,
+ explorer_url: `https://solscan.io/tx/${signature}`,
+ order: publicOrder(settled),
+ events: settled.events.map((e) => ({ status: e.status, note: e.note, actor: e.actor, created_at: e.created_at })),
+ },
+ { 'cache-control': 'no-store' },
+ );
+});
diff --git a/docs/ops/payment-outcomes.md b/docs/ops/payment-outcomes.md
index b62371b64..956a758b8 100644
--- a/docs/ops/payment-outcomes.md
+++ b/docs/ops/payment-outcomes.md
@@ -4,8 +4,13 @@
healthy right now, and if not, which stage is failing?". It exists because the
x402 griefing classes (verify-reject floods, settle failures, sponsor-fee
starvation) historically became visible only after they halted the economy;
-the 2026-07-11 fable audit filed the gap and this board closes it. It is a
-JSON read; consume it with `curl` + `jq` or wire it into ops tooling.
+the 2026-07-11 fable audit filed the gap and this board closes it.
+
+Two ways to read it: the JSON endpoint below (`curl` + `jq`, or wired into ops
+tooling), and **[/payment-outcomes](../../pages/payment-outcomes.html)**, the
+internal page that renders the same response. Neither is a summary of the
+other: the page renders every panel this endpoint returns and adds no number of
+its own.
## Auth
@@ -57,6 +62,12 @@ routes:
(verify vs settle) so a 502 cluster is distinguishable from a rejected-proof
wave without a log dive.
- `settled_volume_usd_24h` from settled `amount_atomics` (USDC, 6 decimals).
+- `replay_reject_rate` has its own denominator, `inbound_attempts` (everything
+ that arrived, replays included). Measuring replays against the verify
+ denominator would report a rate above 1 during exactly the flood the number
+ exists to detect, since replays are refused above verify. It is computed in
+ the endpoint rather than in a renderer so the JSON, the page, and any ops
+ script quote one number computed one way.
Replays are excluded from both rate denominators: they are refused before
verify and would otherwise dilute the signal.
@@ -193,6 +204,32 @@ curl -s https://three.ws/api/x402/three-intel | jq '.accepts[].network'
# only eip155:8453 means the Solana accept has been withdrawn
```
+## The page
+
+`/payment-outcomes` ([pages/payment-outcomes.html](../../pages/payment-outcomes.html))
+renders the whole response. It takes the same gate as the endpoint, is
+`noindex, nofollow`, and is deliberately absent from `data/pages.json`: it is
+internal tooling, like `/quality-bench` and `/likeness-bench`, not a public
+surface.
+
+- **The window selector (1h / 3h / 24h) is a re-render, not a request.** All
+ three windows arrive in one response, so sweeping between them during an
+ incident costs no extra database or RPC read. `Refresh` is the explicit
+ refetch.
+- **A rate with no attempts renders `n/a`, never `0%`.** A quiet rail and a
+ totally failing rail must not look the same, so an empty window says so in
+ words underneath.
+- **A panel that failed renders its own error in place** and names the other
+ panels as unaffected, matching the endpoint's 207 semantics. The banner at the
+ top lists whatever is in `degraded`.
+- **An unmeasured number is never a green zero.** The stranded-custody panel
+ returns nulls when the process could not open the wallets at all, and the page
+ renders `not measured` in muted type rather than a reassuring `0 SOL`.
+- Panels: inbound rates for the selected window, top reject reasons and replay
+ stages (both 24h), the outbound ring settle sensor with its triage hint, every
+ configured ring wallet against its own floor plus the sponsor runway, and
+ stranded custody.
+
## Reading it in an incident
1. `inbound.settle_success_rate` low but `verify_reject_rate` flat: the rail
@@ -236,6 +273,7 @@ curl -s https://three.ws/api/x402/three-intel | jq '.accepts[].network'
## Related
- `api/ops/payment-outcomes.js` (the endpoint),
+ `pages/payment-outcomes.html` (the page at `/payment-outcomes`),
`api/_lib/ops/x402-settle-health.js` (the sensor),
`api/_lib/custodial-key-health.js` (the custody-loss measurement shared with
`scripts/audit-custodial-key-health.mjs`),
diff --git a/tests/api/print-gate-wiring.test.js b/tests/api/print-gate-wiring.test.js
new file mode 100644
index 000000000..3ebafa5c0
--- /dev/null
+++ b/tests/api/print-gate-wiring.test.js
@@ -0,0 +1,151 @@
+// The fabrication gate's two run points, wired.
+//
+// api/api/_lib/print/gate.js is tested on its own in print-fabrication-gate.test.js.
+// This suite proves the gate is not advisory: that the quote endpoint refuses
+// before a price exists, that the sweep screens paid orders and rejects the
+// ones that fail, and that no order reaches a printer without a recorded
+// `allow` verdict on it. A gate nothing calls is decoration.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Readable } from 'node:stream';
+
+// ---------------------------------------------------------------------------
+// Run point 1: POST /api/print/quote
+// ---------------------------------------------------------------------------
+
+const REPORT = {
+ version: 1,
+ manifold: true,
+ volume_cm3: 12.5,
+ bbox_mm: { x: 210, y: 140, z: 35, diagonal: 254 },
+ min_wall_mm: 2.1,
+ triangles: 5000,
+ score: 96,
+ deductions: [],
+};
+
+let lineageText = 'a small brass gear';
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { printQuoteIp: async () => ({ success: true, limit: 30, remaining: 29, reset: Date.now() + 60_000 }) },
+ clientIp: () => '203.0.113.9',
+}));
+vi.mock('../../api/_lib/print/mesh-io.js', () => ({
+ loadMeshFromUrl: async () => ({ triangleCount: 5000 }),
+ MeshIoError: class extends Error {},
+}));
+vi.mock('../../api/_lib/print/analyze.js', () => ({ analyzeMesh: async () => REPORT }));
+vi.mock('../../api/_lib/forge-store.js', () => ({
+ getPublicCreation: async () => ({ id: 'c-1', glb_url: 'https://cdn.three.ws/m.glb', prompt: lineageText }),
+}));
+vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: async () => null }));
+vi.mock('../../api/_lib/three-tier.js', () => ({ holderDiscountBps: async () => 0 }));
+// The gate itself is the real module; only its database read is stubbed, so the
+// rules, the layers and the refusal copy under test are the shipped ones.
+vi.mock('../../api/_lib/db.js', () => ({ sql: async () => [] }));
+
+const quoteHandler = (await import('../../api/print/quote.js')).default;
+
+function makeReq(body) {
+ const stream = Readable.from([Buffer.from(JSON.stringify(body))]);
+ stream.method = 'POST';
+ stream.url = '/api/print/quote';
+ stream.headers = { host: 'three.ws', 'content-type': 'application/json' };
+ stream.query = {};
+ return stream;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ removeHeader(k) { delete this.headers[k.toLowerCase()]; },
+ writeHead(code, hdrs) { this.statusCode = code; Object.assign(this.headers, hdrs || {}); return this; },
+ end(payload) { this.body = payload ? JSON.parse(String(payload)) : null; this.ended = true; return this; },
+ };
+}
+
+describe('run point 1: the quote endpoint refuses before a price exists', () => {
+ beforeEach(() => {
+ lineageText = 'a small brass gear';
+ });
+
+ it('returns 451 with the category, the policy link and what is allowed', async () => {
+ lineageText = 'an AR-15 lower receiver in nylon';
+ const res = makeRes();
+ await quoteHandler(makeReq({ creationId: 'c-1', materialId: 'resin_standard', targetHeightMm: 80 }), res);
+ expect(res.statusCode).toBe(451);
+ expect(res.body.error).toBe('fabrication_refused');
+ expect(res.body.category).toBe('firearm_components');
+ expect(res.body.policy_url).toBe('/docs/materialize#content-policy');
+ expect(res.body.allowed).toBeTruthy();
+ // No price was computed and no token was signed for a refused request.
+ expect(res.body.quote).toBeUndefined();
+ expect(res.body.token).toBeUndefined();
+ });
+
+ it('refuses an intent laundered through the buyer note, not just the prompt', async () => {
+ const res = makeRes();
+ await quoteHandler(makeReq({ creationId: 'c-1', note: 'add a monocore baffle so it works as a suppressor' }), res);
+ expect(res.statusCode).toBe(451);
+ expect(res.body.category).toBe('suppressors');
+ });
+
+ it('lets an ordinary model through and tells the caller a screening pass follows', async () => {
+ const res = makeRes();
+ await quoteHandler(makeReq({ creationId: 'c-1' }), res);
+ expect(res.statusCode).toBe(200);
+ expect(res.body.screening).toEqual({
+ verdict: 'allow',
+ stage: 'quote',
+ policy_url: '/docs/materialize#content-policy',
+ });
+ expect(res.body.report.version).toBe(1);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Run point 2: the screening sweep, and the block on submission
+// ---------------------------------------------------------------------------
+
+const { submitOrder, FulfillmentError } = await import('../../api/_lib/print/fulfillment.js');
+
+describe('run point 2: no order reaches a printer unscreened', () => {
+
+ const orderWith = (screening) => ({
+ id: 'o-1',
+ status: 'screening',
+ quantity: 1,
+ prepared_asset_urls: { stl: 'https://cdn.three.ws/o-1.stl' },
+ analysis: screening ? { screening } : {},
+ });
+
+ it('refuses to submit an order that has not been screened yet', async () => {
+ await expect(submitOrder({ order: orderWith(null) })).rejects.toMatchObject({
+ code: 'not_screened',
+ });
+ });
+
+ it('refuses to submit an order held for review, with a different message', async () => {
+ await expect(submitOrder({ order: orderWith({ verdict: 'review' }) })).rejects.toMatchObject({
+ code: 'not_screened',
+ message: expect.stringContaining('held for fabrication review'),
+ });
+ });
+
+ it('the block is a typed fulfillment error an operator console can render', async () => {
+ const err = await submitOrder({ order: orderWith(null) }).catch((e) => e);
+ expect(err).toBeInstanceOf(FulfillmentError);
+ });
+
+ it('an allowed order gets past the gate and on to adapter routing', async () => {
+ // With no adapters configured, routing is the next thing that fails. That
+ // it fails on routing rather than on screening is the assertion: the gate
+ // let it through.
+ const err = await submitOrder({ order: orderWith({ verdict: 'allow' }) }).catch((e) => e);
+ expect(err.code).not.toBe('not_screened');
+ });
+});
diff --git a/tests/print-fulfillment-routing.test.js b/tests/print-fulfillment-routing.test.js
new file mode 100644
index 000000000..24dc9aadc
--- /dev/null
+++ b/tests/print-fulfillment-routing.test.js
@@ -0,0 +1,205 @@
+// Fulfillment orchestration: adapters speak, the store decides.
+//
+// The rule this file defends is that an adapter never writes the database. Its
+// output is normalized, then turned into at most one transition() call, so a
+// partner changing their payload shape can never corrupt an order's state
+// machine. The three cases that matter are routing (which lane takes the job),
+// refusal (a provider reporting something the machine will not allow), and
+// no-news (a poll that should move nothing).
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+class PrintStoreError extends Error {
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ }
+}
+
+const transition = vi.fn(async ({ orderId, to }) => ({ order: { ...ORDER, id: orderId, status: to }, event: { id: 'e1' }, certificate: null }));
+const appendEvent = vi.fn(async () => ({ id: 'e1' }));
+const getOrder = vi.fn(async () => ORDER);
+vi.mock('../api/_lib/print-store.js', () => ({
+ PrintStoreError,
+ transition,
+ appendEvent,
+ getOrder,
+ PRINT_STATUSES: ['created', 'quoted', 'paid', 'screening', 'submitted', 'printing', 'quality_check', 'shipped', 'delivered', 'rejected', 'canceled', 'refunded'],
+ LEGAL_TRANSITIONS: {},
+ ACTORS: ['system', 'operator', 'provider', 'buyer'],
+ TERMINAL_STATUSES: ['delivered'],
+ canTransition: () => true,
+ getOrderWithEvents: vi.fn(),
+}));
+
+const patchProviderDetails = vi.fn(async (id, patch) => ({ ...ORDER, id, ...patch }));
+vi.mock('../api/_lib/print/fulfillment-queries.js', () => ({
+ patchProviderDetails,
+ printStoreEnabled: () => true,
+ ADAPTER_DRIVABLE_STATUSES: ['submitted', 'printing', 'quality_check', 'shipped', 'delivered', 'canceled', 'rejected'],
+ OPEN_PROVIDER_STATUSES: ['submitted', 'printing', 'quality_check', 'shipped'],
+}));
+
+const notifyOperators = vi.fn(async () => {});
+vi.mock('../api/_lib/print/ops-notify.js', () => ({
+ notifyOperators,
+ jobSummaryLines: () => ['line'],
+ operatorChannelConfigured: () => true,
+}));
+
+const ORDER = {
+ id: '00000000-0000-4000-8000-000000000003',
+ status: 'screening',
+ material_id: 'resin-standard',
+ quantity: 1,
+ prepared_asset_urls: { stl: 'https://example.invalid/a.stl', '3mf': 'https://example.invalid/a.3mf' },
+ // The fabrication gate (api/_lib/print/gate.js) records its verdict on the
+ // order. Nothing reaches a printer without a cleared one, so every fixture
+ // that expects to be submitted carries it.
+ analysis: { screening: { verdict: 'allow' } },
+ shipping: { country: 'US' },
+ price_usdc: '42.000000',
+};
+
+const { FulfillmentError, applyProviderEvent, cancelWithProvider, reconcileOrder, submitOrder } = await import(
+ '../api/_lib/print/fulfillment.js'
+);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ transition.mockImplementation(async ({ orderId, to }) => ({ order: { ...ORDER, id: orderId, status: to }, event: { id: 'e1' }, certificate: null }));
+ getOrder.mockResolvedValue(ORDER);
+ patchProviderDetails.mockImplementation(async (id, patch) => ({ ...ORDER, id, ...patch }));
+ delete process.env.PRINT_PARTNER_CN_URL;
+ delete process.env.PRINT_PARTNER_CN_KEY;
+});
+
+describe('submitOrder routes by declared capability', () => {
+ it('hands the job to the manual lane when no partner is configured', async () => {
+ const result = await submitOrder({ order: ORDER, actor: 'operator', actorId: 'admin-1' });
+ expect(result.adapter).toBe('manual');
+ expect(result.providerOrderId).toBe(ORDER.id);
+ expect(transition).toHaveBeenCalledWith(expect.objectContaining({
+ to: 'submitted',
+ actor: 'operator',
+ actorId: 'admin-1',
+ patch: expect.objectContaining({ provider: 'manual', provider_order_id: ORDER.id, lead_time_days: 10 }),
+ }));
+ });
+
+ it('pages the operator channel with the job, not the address', async () => {
+ await submitOrder({ order: ORDER });
+ expect(notifyOperators).toHaveBeenCalledTimes(1);
+ expect(notifyOperators.mock.calls[0][0].title).toMatch(/New print job/);
+ });
+
+ it('records the prepared formats so the operator knows what to send the bureau', async () => {
+ await submitOrder({ order: ORDER });
+ expect(patchProviderDetails).toHaveBeenCalledWith(
+ ORDER.id,
+ expect.objectContaining({ provider_state: expect.objectContaining({ formats: ['stl', '3mf'] }) }),
+ );
+ });
+
+ it('refuses a lane this deployment has not configured rather than failing later', async () => {
+ await expect(submitOrder({ order: ORDER, adapterKey: 'partner-cn' })).rejects.toThrow(FulfillmentError);
+ await expect(submitOrder({ order: ORDER, adapterKey: 'partner-cn' })).rejects.toThrow(/no configured adapter/);
+ expect(transition).not.toHaveBeenCalled();
+ });
+
+ it('refuses a lane that cannot physically run the part, and says why', async () => {
+ const oversized = { ...ORDER, analysis: { ...ORDER.analysis, bbox_mm: { x: 10, y: 10, z: 5000 } } };
+ await expect(submitOrder({ order: oversized, adapterKey: 'manual' })).rejects.toThrow(/build volume/);
+ });
+
+ it('refuses an order that has not cleared the fabrication gate', async () => {
+ const unscreened = { ...ORDER, analysis: {} };
+ await expect(submitOrder({ order: unscreened })).rejects.toThrow(/has not cleared the fabrication gate/);
+ expect(transition).not.toHaveBeenCalled();
+ });
+
+ it('refuses an order held for fabrication review, where an operator cannot click past it', async () => {
+ const held = { ...ORDER, analysis: { screening: { verdict: 'review' } } };
+ await expect(submitOrder({ order: held })).rejects.toThrow(/held for fabrication review/);
+ expect(transition).not.toHaveBeenCalled();
+ });
+
+ it('reports every declining lane when nothing can take the order', async () => {
+ const oversized = { ...ORDER, analysis: { ...ORDER.analysis, bbox_mm: { x: 10, y: 10, z: 5000 } } };
+ await expect(submitOrder({ order: oversized })).rejects.toThrow(/no fulfillment lane can run this order/);
+ });
+});
+
+describe('applyProviderEvent turns a report into at most one move', () => {
+ const live = { ...ORDER, status: 'printing', provider: 'partner-cn', provider_order_id: 'p-1' };
+
+ it('applies a legal move and carries the tracking number with it', async () => {
+ const result = await applyProviderEvent({
+ order: live,
+ event: { status: 'shipped', trackingNumber: '1Z999', carrier: 'UPS', note: 'left the floor', state: { s: 1 } },
+ });
+ expect(result.applied).toBe(true);
+ expect(transition).toHaveBeenCalledWith(expect.objectContaining({
+ to: 'shipped',
+ actor: 'provider',
+ patch: { tracking_number: '1Z999', carrier: 'UPS' },
+ }));
+ });
+
+ it('records a refused move on the timeline instead of throwing at the provider', async () => {
+ transition.mockRejectedValue(new PrintStoreError('illegal_transition', 'a print order cannot go from printing to quoted'));
+ const result = await applyProviderEvent({ order: live, event: { status: 'delivered', note: '' } });
+ expect(result.applied).toBe(false);
+ expect(result.reason).toMatch(/cannot go from/);
+ expect(appendEvent).toHaveBeenCalledWith(expect.objectContaining({
+ actor: 'provider',
+ note: expect.stringMatching(/Refused provider report 'delivered'/),
+ }));
+ });
+
+ it('treats no-news as news: it writes the payload and moves nothing', async () => {
+ const result = await applyProviderEvent({ order: live, event: { status: null, note: 'still printing', state: { pct: 40 } } });
+ expect(result.applied).toBe(false);
+ expect(transition).not.toHaveBeenCalled();
+ expect(patchProviderDetails).toHaveBeenCalledWith(live.id, expect.objectContaining({ provider_state: { pct: 40 } }));
+ expect(appendEvent).toHaveBeenCalledWith(expect.objectContaining({ note: 'still printing' }));
+ });
+
+ it('treats a report of the status we already hold as no move', async () => {
+ const result = await applyProviderEvent({ order: live, event: { status: 'printing', trackingNumber: '', note: '' } });
+ expect(result).toMatchObject({ applied: false, reason: 'already in that status' });
+ expect(transition).not.toHaveBeenCalled();
+ });
+
+ it('lets a genuine bug escape rather than swallowing it as a refusal', async () => {
+ transition.mockRejectedValue(new TypeError('cannot read properties of undefined'));
+ await expect(applyProviderEvent({ order: live, event: { status: 'shipped' } })).rejects.toThrow(TypeError);
+ });
+});
+
+describe('reconcileOrder and cancel degrade honestly on an unconfigured lane', () => {
+ it('does not poll a lane this deployment cannot reach', async () => {
+ const result = await reconcileOrder({ ...ORDER, provider: 'partner-cn', provider_order_id: 'p-1' });
+ expect(result).toMatchObject({ polled: false, applied: false });
+ expect(result.reason).toMatch(/not configured/);
+ });
+
+ it('the manual lane polls to no-news, because the console is already its truth', async () => {
+ getOrder.mockResolvedValue({ ...ORDER, status: 'printing', tracking_number: '1Z' });
+ const result = await reconcileOrder({ ...ORDER, status: 'printing', provider: 'manual', provider_order_id: ORDER.id });
+ expect(result.polled).toBe(true);
+ expect(result.applied).toBe(false);
+ expect(transition).not.toHaveBeenCalled();
+ });
+
+ it('reports a cancel it could not send rather than claiming success', async () => {
+ const result = await cancelWithProvider({ ...ORDER, provider: 'partner-cn' }, 'buyer changed their mind');
+ expect(result.ok).toBe(false);
+ });
+
+ it('asks the manual lane to stop by paging the operator', async () => {
+ const result = await cancelWithProvider({ ...ORDER, provider: 'manual' }, 'buyer changed their mind');
+ expect(result.ok).toBe(true);
+ expect(notifyOperators).toHaveBeenCalledWith(expect.objectContaining({ title: expect.stringMatching(/cancellation/i) }));
+ });
+});
diff --git a/tests/print-orders-sync.test.js b/tests/print-orders-sync.test.js
new file mode 100644
index 000000000..848aa1753
--- /dev/null
+++ b/tests/print-orders-sync.test.js
@@ -0,0 +1,195 @@
+// The fulfillment reconciliation sweep.
+//
+// Webhooks are the fast path and they are not sufficient: a delivery gets lost,
+// a partner's callback queue backs up, and the manual lane has no webhook at
+// all. Without this sweep the worst failure a physical product has goes
+// unnoticed, which is a finished order sitting in `printing` until the buyer
+// asks.
+//
+// Two behaviours are load-bearing and both are pinned here: an unreachable
+// provider must not abort the sweep (the stall pass is exactly what catches the
+// orders that provider is sitting on), and a stalled order must page the
+// operator once rather than on every tick.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const listOpenProviderOrders = vi.fn(async () => []);
+const listStalledOrders = vi.fn(async () => []);
+const markStallAlerted = vi.fn(async (ids) => ids.length);
+vi.mock('../api/_lib/print/fulfillment-queries.js', () => ({
+ listOpenProviderOrders,
+ listStalledOrders,
+ markStallAlerted,
+ printStoreEnabled: () => true,
+ ADAPTER_DRIVABLE_STATUSES: ['submitted', 'printing', 'shipped'],
+ OPEN_PROVIDER_STATUSES: ['submitted', 'printing', 'quality_check', 'shipped'],
+}));
+
+const reconcileOrder = vi.fn(async (order) => ({ applied: false, order, reason: '', polled: true }));
+vi.mock('../api/_lib/print/fulfillment.js', () => ({
+ reconcileOrder,
+ submitOrder: vi.fn(),
+ applyProviderEvent: vi.fn(),
+ cancelWithProvider: vi.fn(),
+ FulfillmentError: class FulfillmentError extends Error {},
+}));
+
+const notifyOperators = vi.fn(async () => {});
+vi.mock('../api/_lib/print/ops-notify.js', () => ({
+ notifyOperators,
+ jobSummaryLines: (order) => [`Order ${String(order.id).slice(0, 8)}`],
+ operatorChannelConfigured: () => true,
+}));
+
+const handler = (await import('../api/cron/print-orders-sync.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; } },
+ };
+}
+
+const CRON_SECRET = 'test-cron-secret';
+
+async function sweep({ authorized = true } = {}) {
+ const res = mockRes();
+ await handler(
+ {
+ method: 'GET',
+ url: '/api/cron/print-orders-sync',
+ headers: { host: 'three.ws', ...(authorized ? { authorization: `Bearer ${CRON_SECRET}` } : {}) },
+ },
+ res,
+ );
+ return res;
+}
+
+/** An order submitted `daysAgo` days back with a `leadTimeDays` promise. */
+function order({ id, daysAgo, leadTimeDays = 10, status = 'printing', provider = 'manual' }) {
+ return {
+ id,
+ status,
+ provider,
+ provider_order_id: id,
+ lead_time_days: leadTimeDays,
+ material_id: 'resin-standard',
+ quantity: 1,
+ price_usdc: '42.000000',
+ shipping: { country: 'US' },
+ submitted_at: new Date(Date.now() - daysAgo * 86_400_000).toISOString(),
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ process.env.CRON_SECRET = CRON_SECRET;
+ listOpenProviderOrders.mockResolvedValue([]);
+ listStalledOrders.mockResolvedValue([]);
+ markStallAlerted.mockImplementation(async (ids) => ids.length);
+ reconcileOrder.mockImplementation(async (o) => ({ applied: false, order: o, reason: '', polled: true }));
+});
+
+describe('the sweep is scheduler-only', () => {
+ it('refuses an unauthenticated caller', async () => {
+ const res = await sweep({ authorized: false });
+ expect(res.statusCode).toBeGreaterThanOrEqual(401);
+ expect(listOpenProviderOrders).not.toHaveBeenCalled();
+ });
+});
+
+describe('reconciliation pass', () => {
+ it('polls every live provider order', async () => {
+ listOpenProviderOrders.mockResolvedValue([
+ order({ id: 'o-1', daysAgo: 1 }),
+ order({ id: 'o-2', daysAgo: 2 }),
+ ]);
+ const res = await sweep();
+ expect(res.statusCode).toBe(200);
+ expect(res.json).toMatchObject({ ok: true, open: 2, polled: 2, applied: 0 });
+ });
+
+ it('counts the orders a provider actually moved', async () => {
+ listOpenProviderOrders.mockResolvedValue([order({ id: 'o-1', daysAgo: 1 })]);
+ reconcileOrder.mockResolvedValue({ applied: true, order: {}, reason: '', polled: true });
+ expect((await sweep()).json.applied).toBe(1);
+ });
+
+ it('an unreachable provider is counted, not thrown, and the sweep continues', async () => {
+ listOpenProviderOrders.mockResolvedValue([
+ order({ id: 'o-broken', daysAgo: 1, provider: 'partner-cn' }),
+ order({ id: 'o-fine', daysAgo: 1 }),
+ ]);
+ reconcileOrder.mockImplementation(async (o) => {
+ if (o.id === 'o-broken') throw new Error('partner-cn upstream failure: connect ETIMEDOUT');
+ return { applied: false, order: o, reason: '', polled: true };
+ });
+ const res = await sweep();
+ expect(res.statusCode).toBe(200);
+ expect(res.json.polled).toBe(1);
+ expect(res.json.failures).toHaveLength(1);
+ expect(res.json.failures[0]).toMatchObject({ order_id: 'o-broken' });
+ });
+
+ it('one broken lane never hides a stall in another', async () => {
+ listOpenProviderOrders.mockResolvedValue([order({ id: 'o-broken', daysAgo: 1, provider: 'partner-cn' })]);
+ reconcileOrder.mockRejectedValue(new Error('upstream down'));
+ listStalledOrders.mockResolvedValue([order({ id: 'o-late', daysAgo: 30 })]);
+ const res = await sweep();
+ expect(res.json.stalled).toBe(1);
+ expect(notifyOperators).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('stall detection', () => {
+ it('pages the operator for an order past its lead time, with the days late in the title', async () => {
+ listStalledOrders.mockResolvedValue([order({ id: 'o-late', daysAgo: 21, leadTimeDays: 10 })]);
+ const res = await sweep();
+ expect(res.json).toMatchObject({ stalled: 1, alerted: 1 });
+ expect(notifyOperators).toHaveBeenCalledTimes(1);
+ const call = notifyOperators.mock.calls[0][0];
+ expect(call.title).toMatch(/11 days past its lead time/);
+ expect(call.orderId).toBe('o-late');
+ // A stall is the one ops-notify case that also lands in the durable
+ // ops_alerts table: it is the message an operator must not miss.
+ expect(call.alert).toBe(true);
+ });
+
+ it('stamps every paged order so the next sweep stays quiet', async () => {
+ listStalledOrders.mockResolvedValue([
+ order({ id: 'o-a', daysAgo: 20 }),
+ order({ id: 'o-b', daysAgo: 40 }),
+ ]);
+ await sweep();
+ expect(markStallAlerted).toHaveBeenCalledWith(['o-a', 'o-b']);
+ });
+
+ it('asks for the grace margin and the re-alert window, not the raw lead time', async () => {
+ await sweep();
+ expect(listStalledOrders).toHaveBeenCalledWith(expect.objectContaining({ graceDays: 2, realertHours: 24 }));
+ });
+
+ it('says nothing when no order is late', async () => {
+ listOpenProviderOrders.mockResolvedValue([order({ id: 'o-1', daysAgo: 1 })]);
+ const res = await sweep();
+ expect(res.json).toMatchObject({ stalled: 0, alerted: 0 });
+ expect(notifyOperators).not.toHaveBeenCalled();
+ });
+
+ it('never puts a shipping address in an ops message', async () => {
+ listStalledOrders.mockResolvedValue([
+ { ...order({ id: 'o-late', daysAgo: 20 }), shipping: { name: 'A Buyer', line1: '1 Test Way', country: 'US' } },
+ ]);
+ await sweep();
+ const serialized = JSON.stringify(notifyOperators.mock.calls[0][0]);
+ expect(serialized).not.toContain('1 Test Way');
+ expect(serialized).not.toContain('A Buyer');
+ });
+});
diff --git a/tests/print-webhook-idempotency.test.js b/tests/print-webhook-idempotency.test.js
new file mode 100644
index 000000000..d07b637ca
--- /dev/null
+++ b/tests/print-webhook-idempotency.test.js
@@ -0,0 +1,244 @@
+// Fulfillment webhooks: authenticity first, then idempotency, then ordering.
+//
+// Every serious fulfillment provider retries deliveries. A replayed webhook
+// that appends a second timeline row, or drives the state machine a second
+// time, turns an ordinary retry into a corrupted order. The ledger insert on
+// print_webhook_deliveries is the lock that prevents it, and this file pins
+// the three properties the endpoint depends on:
+//
+// 1. An unverified delivery is refused BEFORE the body is parsed.
+// 2. The claim happens before the payload is interpreted, so even a delivery
+// we end up not applying is recorded and cannot be replayed.
+// 3. A duplicate answers 200 (a 4xx makes a provider retry forever) and
+// applies nothing.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { createHmac } from 'node:crypto';
+
+const SECRET = 'test-hmac-secret-not-a-real-credential';
+
+// A ledger with the real unique constraint, so "claimed twice" behaves the way
+// Postgres does rather than the way a stub might.
+const ledger = new Set();
+const claimWebhookDelivery = vi.fn(async ({ provider, deliveryId }) => {
+ const key = `${provider}:${deliveryId}`;
+ if (ledger.has(key)) return { fresh: false };
+ ledger.add(key);
+ return { fresh: true };
+});
+const markWebhookApplied = vi.fn(async () => {});
+const getOrderByProviderId = vi.fn(async () => ORDER);
+
+vi.mock('../api/_lib/print/fulfillment-queries.js', () => ({
+ claimWebhookDelivery,
+ markWebhookApplied,
+ getOrderByProviderId,
+ printStoreEnabled: () => true,
+ ADAPTER_DRIVABLE_STATUSES: ['submitted', 'printing', 'quality_check', 'shipped', 'delivered', 'canceled', 'rejected'],
+ OPEN_PROVIDER_STATUSES: ['submitted', 'printing', 'quality_check', 'shipped'],
+}));
+
+// The timeline the endpoint is not allowed to duplicate.
+const timeline = [];
+const applyProviderEvent = vi.fn(async ({ order, event }) => {
+ timeline.push({ status: event.status, note: event.note });
+ return { applied: true, order: { ...order, status: event.status }, reason: '' };
+});
+vi.mock('../api/_lib/print/fulfillment.js', () => ({
+ applyProviderEvent,
+ submitOrder: vi.fn(),
+ reconcileOrder: vi.fn(),
+ cancelWithProvider: vi.fn(),
+ FulfillmentError: class FulfillmentError extends Error {},
+}));
+
+const ORDER = {
+ id: '00000000-0000-4000-8000-000000000002',
+ status: 'printing',
+ provider: 'partner-cn',
+ provider_order_id: 'p-42',
+};
+
+const handler = (await import('../api/print/webhook/[provider].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; } },
+ };
+}
+
+const sign = (body, secret = SECRET) => createHmac('sha256', secret).update(body, 'utf8').digest('hex');
+
+async function deliver(body, { provider = 'partner-cn', headers = {}, signed = true } = {}) {
+ const raw = typeof body === 'string' ? body : JSON.stringify(body);
+ const res = mockRes();
+ await handler(
+ {
+ method: 'POST',
+ url: `/api/print/webhook/${provider}`,
+ query: { provider },
+ headers: {
+ host: 'three.ws',
+ 'content-type': 'application/json',
+ ...(signed ? { 'x-print-signature': `sha256=${sign(raw)}` } : {}),
+ ...headers,
+ },
+ rawBody: Buffer.from(raw),
+ },
+ res,
+ );
+ return res;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ ledger.clear();
+ timeline.length = 0;
+ process.env.PRINT_PARTNER_CN_URL = 'https://partner.invalid/api';
+ process.env.PRINT_PARTNER_CN_KEY = SECRET;
+ getOrderByProviderId.mockResolvedValue(ORDER);
+});
+
+describe('a replayed delivery is applied exactly once', () => {
+ const PAYLOAD = { id: 'p-42', state: 'shipped', tracking_number: '1Z999', carrier: 'UPS' };
+
+ it('applies the first delivery and appends one timeline entry', async () => {
+ const res = await deliver(PAYLOAD);
+ expect(res.statusCode).toBe(200);
+ expect(res.json).toMatchObject({ ok: true, applied: true, status: 'shipped' });
+ expect(timeline).toHaveLength(1);
+ });
+
+ it('answers 200 duplicate on the replay and appends nothing', async () => {
+ await deliver(PAYLOAD);
+ const replay = await deliver(PAYLOAD);
+ expect(replay.statusCode).toBe(200);
+ expect(replay.json).toMatchObject({ ok: true, duplicate: true, applied: false });
+ expect(applyProviderEvent).toHaveBeenCalledTimes(1);
+ expect(timeline).toHaveLength(1);
+ });
+
+ it('stays at one even after five retries', async () => {
+ for (let i = 0; i < 5; i += 1) await deliver(PAYLOAD);
+ expect(timeline).toHaveLength(1);
+ });
+
+ it('treats a genuinely different event as a new delivery', async () => {
+ await deliver(PAYLOAD);
+ await deliver({ ...PAYLOAD, state: 'delivered' });
+ expect(timeline.map((e) => e.status)).toEqual(['shipped', 'delivered']);
+ });
+
+ it('honours the provider delivery id over the payload hash when they send one', async () => {
+ // Same delivery id, different body: their id is authoritative, so this is
+ // still one event.
+ await deliver(PAYLOAD, { headers: { 'x-print-delivery': 'dlv_7' } });
+ const replay = await deliver({ ...PAYLOAD, note: 'resent with a note' }, { headers: { 'x-print-delivery': 'dlv_7' } });
+ expect(replay.json.duplicate).toBe(true);
+ expect(timeline).toHaveLength(1);
+ });
+});
+
+describe('authenticity is settled before anything else happens', () => {
+ it('refuses an unsigned delivery with 401', async () => {
+ const res = await deliver({ id: 'p-42', state: 'shipped' }, { signed: false });
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('refuses a forged signature and never claims a ledger row', async () => {
+ const res = await deliver({ id: 'p-42', state: 'shipped' }, { headers: { 'x-print-signature': 'sha256=deadbeef' } });
+ expect(res.statusCode).toBe(401);
+ expect(claimWebhookDelivery).not.toHaveBeenCalled();
+ expect(applyProviderEvent).not.toHaveBeenCalled();
+ });
+
+ it('refuses a body altered in flight', async () => {
+ const raw = JSON.stringify({ id: 'p-42', state: 'printing' });
+ const res = mockRes();
+ await handler(
+ {
+ method: 'POST',
+ url: '/api/print/webhook/partner-cn',
+ query: { provider: 'partner-cn' },
+ headers: { host: 'three.ws', 'content-type': 'application/json', 'x-print-signature': sign(raw) },
+ rawBody: Buffer.from(raw.replace('printing', 'shipped!')),
+ },
+ res,
+ );
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('404s a provider with no configured adapter, offering nothing to probe', async () => {
+ const res = await deliver({ id: 'x' }, { provider: 'not-a-lane' });
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('refuses a delivery to the manual lane, which has no webhook by design', async () => {
+ const res = await deliver({ id: 'x' }, { provider: 'manual' });
+ expect(res.statusCode).toBe(401);
+ expect(res.json.error_description).toMatch(/no webhook/);
+ });
+
+ it('rejects a non-POST', async () => {
+ const res = mockRes();
+ await handler({ method: 'GET', url: '/api/print/webhook/partner-cn', query: { provider: 'partner-cn' }, headers: {} }, res);
+ expect(res.statusCode).toBe(405);
+ });
+});
+
+describe('a verified delivery we cannot apply is still recorded', () => {
+ 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(claimWebhookDelivery).toHaveBeenCalledTimes(1);
+ });
+
+ it('answers 200 for an unknown order so the provider stops retrying', async () => {
+ getOrderByProviderId.mockResolvedValue(null);
+ const res = await deliver({ id: 'p-does-not-exist', state: 'shipped' });
+ expect(res.statusCode).toBe(200);
+ expect(res.json).toMatchObject({ applied: false, reason: 'no matching order' });
+ });
+
+ it('reports applied:false when the state machine refuses the move', async () => {
+ applyProviderEvent.mockResolvedValue({ applied: false, order: ORDER, reason: 'a print order cannot go from printing to quoted' });
+ const res = await deliver({ id: 'p-42', state: 'shipped' });
+ expect(res.statusCode).toBe(200);
+ expect(res.json).toMatchObject({ applied: false, status: 'printing' });
+ expect(res.json.reason).toMatch(/cannot go from/);
+ });
+
+ it('makes a provider retry when the database is unavailable', async () => {
+ vi.resetModules();
+ vi.doMock('../api/_lib/print/fulfillment-queries.js', () => ({
+ claimWebhookDelivery,
+ markWebhookApplied,
+ getOrderByProviderId,
+ printStoreEnabled: () => false,
+ ADAPTER_DRIVABLE_STATUSES: ['shipped'],
+ OPEN_PROVIDER_STATUSES: ['shipped'],
+ }));
+ const fresh = (await import('../api/print/webhook/[provider].js')).default;
+ const raw = JSON.stringify({ id: 'p-42', state: 'shipped' });
+ const res = mockRes();
+ await fresh(
+ {
+ method: 'POST',
+ url: '/api/print/webhook/partner-cn',
+ query: { provider: 'partner-cn' },
+ headers: { host: 'three.ws', 'content-type': 'application/json', 'x-print-signature': sign(raw) },
+ rawBody: Buffer.from(raw),
+ },
+ res,
+ );
+ expect(res.statusCode).toBe(503);
+ });
+});