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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(materialize): finish the print order lane end to end, from quote and gate to certificate and insert card
nirholas3a8182471899
diff --git a/api/_lib/print-store.js b/api/_lib/print-store.jsindex dddd71a5a..9243fb7fe 100644--- a/api/_lib/print-store.js+++ b/api/_lib/print-store.js@@ -18,8 +18,10 @@// retried by api/cron/print-orders-sync.js, and a shipment is never blocked by// an RPC having a bad minute.//-// Scope note for whoever extends this: order creation, quoting and the payment-// path are not here yet. Add them beside `transition()`, not around it.+// createOrder() opens an order from a verified quote token and nothing else:+// the price, the geometry and the material all come out of the token's signed+// payload, never out of the request, so neither checkout lane can be talked+// into a price this server did not sign.import { sql } from './db.js';import { publishUserEvent } from './feed.js';@@ -143,7 +145,8 @@ function notificationLine(status) {* @param {string} [input.actor] system | operator | provider | buyer* @param {string|null} [input.actorId] the operator's user id, when actor is 'operator'* @param {Record<string, unknown>} [input.patch] columns to write with the move- * (tracking_number, carrier, provider, provider_order_id, submitted_at)+ * (tracking_number, carrier, provider, provider_order_id, submitted_at,+ * payment_signature, payment_chain, payment_amount_atomics)* @returns {Promise<{ order: any, event: any, certificate: any|null }>}*/export async function transition({ orderId, to, note = null, actor = 'system', actorId = null, patch = {} }) {@@ -177,7 +180,13 @@ export async function transition({ orderId, to, note = null, actor = 'system', atracking_number = coalesce(${patch.tracking_number ?? null}, tracking_number),carrier = coalesce(${patch.carrier ?? null}, carrier),lead_time_days = coalesce(${patch.lead_time_days ?? null}, lead_time_days),+ payment_signature = coalesce(${patch.payment_signature ?? null}, payment_signature),+ payment_chain = coalesce(${patch.payment_chain ?? null}, payment_chain),+ payment_amount_atomics = coalesce(${patch.payment_amount_atomics ?? null}, payment_amount_atomics),submitted_at = case when ${to} = 'submitted' then coalesce(submitted_at, now()) else submitted_at end,+ -- Stamped by the move itself rather than by the caller, so the paid+ -- time is always the time the order actually became paid.+ paid_at = case when ${to} = 'paid' then coalesce(paid_at, now()) else paid_at end,stall_alerted_at = null,updated_at = now()where id = ${orderId} and status = ${order.status}@@ -231,3 +240,148 @@ export async function transition({ orderId, to, note = null, actor = 'system', areturn { order: updated, event, certificate };}++// ── Order creation ───────────────────────────────────────────────────────────+// Both checkout lanes land here. Everything money hangs off (material, height,+// quantity, volume, total) is read from the VERIFIED quote token, never from+// the request body, so a caller who edits a price in flight gets the price this+// server signed or nothing at all. The handlers verify the token; this function+// refuses to open an order without the decoded payload it produces.++/** Shipping fields we store, and the only ones. Anything else is dropped. */+const SHIPPING_FIELDS = Object.freeze([+ 'name', 'line1', 'line2', 'city', 'region', 'postal_code', 'country', 'phone',+]);+const SHIPPING_REQUIRED = Object.freeze(['name', 'line1', 'city', 'postal_code', 'country']);+const SHIPPING_MAX_LEN = 120;++/**+ * Normalize a shipping address down to the minimum this platform is willing to+ * hold. PII discipline is a schema decision, not a policy document: a field+ * that is never accepted is a field that can never leak.+ *+ * @param {Record<string, unknown>} input+ * @returns {{ name: string, line1: string, line2: string|null, city: string,+ * region: string|null, postal_code: string, country: string, phone: string|null }}+ */+export function normalizeShipping(input) {+ if (!input || typeof input !== 'object') {+ throw new PrintStoreError('shipping_required', 'a shipping address is required');+ }+ /** @type {Record<string, string|null>} */+ const out = {};+ for (const field of SHIPPING_FIELDS) {+ const raw = input[field];+ const value = raw == null ? '' : String(raw).trim().slice(0, SHIPPING_MAX_LEN);+ out[field] = value || null;+ }+ for (const field of SHIPPING_REQUIRED) {+ if (!out[field]) {+ throw new PrintStoreError('shipping_incomplete', `shipping.${field} is required`, { field });+ }+ }+ out.country = String(out.country).toUpperCase();+ if (!/^[A-Z]{2}$/.test(out.country)) {+ throw new PrintStoreError('shipping_incomplete', 'shipping.country must be an ISO 3166-1 alpha-2 code', {+ field: 'country',+ });+ }+ return /** @type {any} */ (out);+}++/**+ * Open a print order in `created`. The caller transitions it to `quoted` once+ * the row exists, so the edition check that guards scarcity runs against a real+ * order rather than against a request.+ *+ * Exactly one of userId (a signed-in human) or payerWallet (an agent that paid+ * over x402) must be present; the DB carries that as a check constraint and+ * this refuses it earlier, with a message a handler can return.+ *+ * @param {object} input+ * @param {string|null} [input.userId]+ * @param {string|null} [input.payerWallet]+ * @param {object} input.quote the decoded, verified quote-token payload+ * @param {object} input.itemization the full itemization the buyer was shown+ * @param {object} input.report the printability report at order time+ * @param {string} input.sourceGlbUrl+ * @param {string|null} [input.creationId]+ * @param {object} input.shipping already through normalizeShipping()+ * @param {string|null} [input.paymentReference] Solana Pay reference pubkey+ * @param {string|null} [input.paymentChain]+ */+export async function createOrder({+ userId = null,+ payerWallet = null,+ quote,+ itemization,+ report,+ sourceGlbUrl,+ creationId = null,+ shipping,+ paymentReference = null,+ paymentChain = null,+}) {+ if (!userId && !payerWallet) {+ throw new PrintStoreError('owner_required', 'an order needs either a session user or a payer wallet');+ }+ if (!quote || !quote.materialId || !(Number(quote.total) > 0)) {+ throw new PrintStoreError('quote_required', 'a verified quote token is required to open an order');+ }+ if (!sourceGlbUrl) {+ throw new PrintStoreError('source_required', 'an order needs the model it is printing');+ }++ const [row] = await sql`+ insert into print_orders (+ user_id, payer_wallet, creation_id, source_glb_url, analysis,+ material_id, target_height_mm, quantity, quote, price_usdc,+ shipping, status, payment_reference, payment_chain, quote_expires_at+ ) values (+ ${userId}, ${payerWallet}, ${creationId}, ${sourceGlbUrl},+ ${JSON.stringify(report ?? {})}::jsonb,+ ${quote.materialId}, ${quote.targetHeightMm}, ${quote.quantity},+ ${JSON.stringify(itemization ?? {})}::jsonb, ${quote.total},+ ${JSON.stringify(shipping)}::jsonb, 'created',+ ${paymentReference}, ${paymentChain},+ ${quote.expiresAt ? new Date(quote.expiresAt).toISOString() : null}+ )+ returning *+ `;+ await appendEvent({+ orderId: row.id,+ status: 'created',+ note: `${quote.quantity} x ${quote.materialId} at ${quote.targetHeightMm} mm, ${quote.total} USDC`,+ actor: userId ? 'buyer' : 'system',+ actorId: userId,+ });+ return row;+}++/**+ * A buyer's own orders, newest first. Never returns another account's rows: the+ * only selector is the caller's own user id.+ * @param {string} userId+ * @param {{ limit?: number }} [opts]+ */+export async function listOrdersForUser(userId, { limit = 50 } = {}) {+ const capped = Math.min(Math.max(Number(limit) || 50, 1), 100);+ return sql`+ select id, status, material_id, target_height_mm, quantity, price_usdc,+ tracking_number, carrier, lead_time_days, created_at, updated_at+ from print_orders+ where user_id = ${userId}+ order by created_at desc+ limit ${capped}+ `;+}++/**+ * The order behind a Solana Pay reference, for the confirm path. The reference+ * is unique, so this is a lookup rather than a search.+ * @param {string} reference+ */+export async function getOrderByPaymentReference(reference) {+ const [row] = await sql`select * from print_orders where payment_reference = ${reference} limit 1`;+ return row || null;+}diff --git a/api/_lib/print/fulfillment.js b/api/_lib/print/fulfillment.jsindex e56426f9b..16bc028f6 100644--- a/api/_lib/print/fulfillment.js+++ b/api/_lib/print/fulfillment.js@@ -35,6 +35,22 @@ import { patchProviderDetails } from './fulfillment-queries.js';* @returns {Promise<{ order: object, adapter: string, providerOrderId: string }>}*/export async function submitOrder({ order, adapterKey = '', actor = 'operator', actorId = null }) {+ // The fabrication gate is not advisory. An order reaches a printer only with+ // a recorded `allow` verdict on it: the quote-time pass cleared the+ // deterministic layers, and the screening sweep (api/cron/print-orders-sync)+ // cleared the model layer. An order still awaiting that pass, or one held for+ // operator review, is refused here rather than in a code path an operator+ // could click past. See api/_lib/print/gate.js.+ const screening = order?.analysis?.screening || null;+ if (screening?.verdict !== 'allow') {+ throw new FulfillmentError(+ 'not_screened',+ screening?.verdict === 'review'+ ? 'this order is held for fabrication review and cannot be submitted until that is resolved'+ : 'this order has not cleared the fabrication gate yet; the screening sweep runs every few minutes',+ );+ }+const assets = order?.prepared_asset_urls || {};let adapter;if (adapterKey) {diff --git a/api/cron/print-orders-sync.js b/api/cron/print-orders-sync.jsindex 7c1ed17db..271df57ca 100644--- a/api/cron/print-orders-sync.js+++ b/api/cron/print-orders-sync.js@@ -8,7 +8,7 @@// worst one a physical product has: an order that is genuinely finished sits in// `printing` forever and nobody finds out until the buyer asks.//-// Two passes, deliberately separate:+// Three passes, deliberately separate://// 1. RECONCILE. For every order a configured adapter still owns, ask the// adapter what it thinks the status is and apply the answer through the@@ -21,9 +21,16 @@// next sweep stays quiet. This is the pass that catches a job nobody is// working on, which no amount of polling a healthy provider will find.//+// 3. SCREEN. For every paid order sitting in `screening`, run the thorough+// fabrication gate (api/_lib/print/gate.js) and act on it: clear the order+// for submission, or move it to `rejected` (the refund path) and tell the+// operators. It runs here rather than inside the payment request because+// it makes a model call: a buyer's checkout must not wait on an LLM, and+// an LLM outage must not fail a payment that already settled.+//// A provider being down must not fail the sweep: each order is reconciled// independently and its failure is counted, not thrown, so one broken lane-// never hides a stall in another.+// never hides a stall in another. The same holds for screening.import { error, json, method, wrapCron } from '../_lib/http.js';import { requireCron } from '../_lib/cron-auth.js';@@ -35,6 +42,7 @@ import {} from '../_lib/print/fulfillment-queries.js';import { reconcileOrder } from '../_lib/print/fulfillment.js';import { jobSummaryLines, notifyOperators } from '../_lib/print/ops-notify.js';+import { listOrdersAwaitingScreening, screenPaidOrder } from '../_lib/print/gate.js';// A job is a stall once it is this many days past its recorded lead time. Two// days absorbs a weekend and a slow carrier scan without crying wolf.@@ -44,6 +52,10 @@ const STALL_GRACE_DAYS = 2;const STALL_REALERT_HOURS = 24;const RECONCILE_BATCH = 100;const STALL_BATCH = 25;+// Screening makes one model call per order, so the batch is small enough that a+// slow provider cannot push the sweep past its schedule. Anything left over is+// picked up by the next tick, which is minutes away.+const SCREEN_BATCH = 10;export default wrapCron(async (req, res) => {if (!method(req, res, ['GET'])) return;@@ -90,6 +102,19 @@ export default wrapCron(async (req, res) => {}const alerted = await markStallAlerted(stalled.map((o) => o.id));+ const awaiting = await listOrdersAwaitingScreening({ limit: SCREEN_BATCH });+ const screened = { allow: 0, refuse: 0, review: 0 };+ for (const order of awaiting) {+ try {+ const verdict = await screenPaidOrder(order);+ if (verdict.verdict in screened) screened[verdict.verdict] += 1;+ } catch (err) {+ // A screening failure leaves the order exactly where it was, which the+ // next sweep retries. It never advances an unscreened order.+ failures.push({ order_id: order.id, error: `screening: ${String(err?.message || err).slice(0, 280)}` });+ }+ }+return json(res, 200, {ok: true,open: open.length,@@ -97,6 +122,8 @@ export default wrapCron(async (req, res) => {applied,stalled: stalled.length,alerted,+ screening_pending: awaiting.length,+ screened,failures,});});diff --git a/api/print/orders.js b/api/print/orders.jsnew file mode 100644index 000000000..ba2138cbe--- /dev/null+++ b/api/print/orders.js@@ -0,0 +1,264 @@+// /api/print/orders: the human checkout lane for Materialize.+//+// POST → open an order from a signed quote token and hand back a Solana Pay+// intent the buyer settles in USDC. Session + CSRF.+// GET → the caller's own orders, newest first.+//+// The whole design is in one sentence: the price comes out of the token, never+// out of the request. verifyQuote() re-derives the material, the size, the+// quantity, the destination and the total from an HMAC this server signed, so a+// buyer who edits the JSON in flight gets either the price we quoted or a 422.+// A token older than the catalog's TTL fails the same way a forged one does.+//+// Payment rides the platform's existing Solana Pay rail, the same one the+// marketplace settles on: the order carries a freshly generated reference+// pubkey, the buyer attaches it to their transfer, and+// POST /api/print/orders/:id/confirm finds the transaction BY that reference and+// validates it moved the quoted USDC to the platform wallet. Verification is a+// read against the chain; this endpoint never sends anything.+//+// USDC on Solana is the only way to pay, and the copy says so plainly. There is+// no card processor, by decision, not by omission.++import { Keypair, PublicKey } from '@solana/web3.js';++import { cors, error, json, method, rateLimited, readJson, 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 { solanaConnection } from '../_lib/solana/connection.js';+import { buildGaslessPurchaseTx } from '../_lib/solana/gasless-tx.js';+import { verifyQuote } from '../_lib/print/quote.js';+import {+ PrintStoreError,+ createOrder,+ listOrdersForUser,+ normalizeShipping,+ transition,+} from '../_lib/print-store.js';++const USDC_DECIMALS = 6;+const PUBKEY_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++/** USDC atomics for a quoted dollar total, without floating-point drift. */+export function atomicsForUsdc(total) {+ return String(Math.round(Number(total) * 10 ** USDC_DECIMALS));+}++/**+ * The wallet a print order is paid to and the mint it is paid in. Missing+ * configuration is a 503, never a silent fallback to some other address: a+ * checkout that cannot name its receiver must not take money.+ */+function receiver() {+ const payTo = env.X402_PAY_TO_SOLANA;+ const mint = env.X402_ASSET_MINT_SOLANA;+ if (!payTo || !mint) {+ const err = new Error('Solana USDC checkout is not configured on this deployment');+ err.status = 503;+ err.code = 'checkout_unavailable';+ throw err;+ }+ return { payTo, mint };+}++/** The Solana Pay URL a wallet app or a QR code opens. */+function solanaPayUrl({ payTo, mint, amount, reference, label, message }) {+ const params = new URLSearchParams({+ 'spl-token': mint,+ amount: String(amount),+ reference,+ label,+ message,+ });+ return `solana:${payTo}?${params.toString()}`;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const user = await getSessionUser(req).catch(() => null);+ if (!user) return error(res, 401, 'unauthorized', 'sign in to order a print');++ if (req.method === 'GET') {+ const readRl = await limits.authedReadIp(clientIp(req));+ if (!readRl.success) return rateLimited(res, readRl);+ const orders = await listOrdersForUser(user.id);+ return json(res, 200, { orders }, { 'cache-control': 'no-store' });+ }++ if (!(await requireCsrf(req, res, user.id))) return;++ const rl = await limits.printOrderIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl, 'too many order attempts');++ const body = await readJson(req, 8_000).catch(() => null);+ if (!body || typeof body !== 'object') {+ return error(res, 400, 'validation_error', 'a JSON body is required');+ }++ // Every priced parameter is re-derived here, from the signature. A stale+ // token, an altered token and a forged token are all the same failure, and+ // none of them reaches the database.+ const quote = verifyQuote(typeof body.token === 'string' ? body.token : '');+ if (!quote) {+ return error(res, 422, 'quote_invalid', 'that quote is expired or was not issued by this server. Request a fresh one from /api/print/quote.');+ }++ let shipping;+ try {+ shipping = normalizeShipping(body.shipping);+ } catch (err) {+ if (err instanceof PrintStoreError) {+ return error(res, 422, err.code, err.message, err.field ? { field: err.field } : {});+ }+ throw err;+ }++ // Shipping cost is part of the signed total, so the address it ships to has+ // to be the country that total was priced for. Silently shipping elsewhere+ // would mean eating the difference on every order.+ if (quote.country && shipping.country !== quote.country) {+ return error(res, 422, 'destination_mismatch', `this quote was priced for shipping to ${quote.country}. Re-quote for ${shipping.country}.`, {+ quoted_country: quote.country,+ shipping_country: shipping.country,+ });+ }++ if (!quote.sourceUrl) {+ return error(res, 422, 'quote_invalid', 'that quote does not name a model to print');+ }++ let payment;+ try {+ payment = receiver();+ } catch (err) {+ return error(res, err.status || 503, err.code || 'checkout_unavailable', err.message);+ }++ const reference = Keypair.generate().publicKey.toBase58();++ let order;+ try {+ order = await createOrder({+ userId: user.id,+ quote,+ // The itemization the buyer was shown, kept verbatim beside the token+ // that signed it. The operator console and the receipt read this row;+ // neither ever recomputes a price.+ itemization: {+ token: body.token,+ total: quote.total,+ materialId: quote.materialId,+ finishId: quote.finishId,+ targetHeightMm: quote.targetHeightMm,+ quantity: quote.quantity,+ hollow: quote.hollow,+ country: quote.country,+ volumeCm3: quote.volumeCm3,+ leadTimeDays: quote.leadTimeDays,+ reportHash: quote.reportHash,+ expiresAt: quote.expiresAt,+ },+ report: { report_hash: quote.reportHash, volume_cm3: quote.volumeCm3 },+ sourceGlbUrl: quote.sourceUrl,+ creationId: quote.creationId || null,+ shipping,+ paymentReference: reference,+ paymentChain: 'solana',+ });+ // `quoted` is the state that says "this order has a price and is waiting+ // for money". The edition-scarcity check runs on this move, so a sold-out+ // edition is refused before the buyer is ever shown a payment request.+ const moved = await transition({+ orderId: order.id,+ to: 'quoted',+ note: 'Awaiting USDC payment on Solana.',+ actor: 'buyer',+ actorId: user.id,+ });+ order = moved.order;+ } catch (err) {+ if (err instanceof PrintStoreError) {+ const status = err.code === 'edition_sold_out' ? 409 : 422;+ return error(res, status, err.code, err.message);+ }+ throw err;+ }++ const amount = Number(quote.total).toFixed(2);+ const intent = {+ chain: 'solana',+ network: 'mainnet',+ recipient: payment.payTo,+ mint: payment.mint,+ mint_decimals: USDC_DECIMALS,+ amount,+ amount_atomics: atomicsForUsdc(quote.total),+ reference,+ url: solanaPayUrl({+ payTo: payment.payTo,+ mint: payment.mint,+ amount,+ reference,+ label: 'three.ws Materialize',+ message: `Print order ${order.id.slice(0, 8)}`,+ }),+ confirm_url: `/api/print/orders/${order.id}/confirm`,+ };++ // Gasless when the browser wallet is already connected: the platform pays the+ // network fee and pre-signs, so the buyer needs USDC and no SOL. Failing to+ // sponsor is never a checkout failure; the buyer can always pay for their own+ // transaction from the Solana Pay URL above.+ const buyerPublicKey =+ typeof body.buyer_public_key === 'string' && PUBKEY_RE.test(body.buyer_public_key)+ ? body.buyer_public_key+ : null;+ if (buyerPublicKey) {+ try {+ const prepared = await buildGaslessPurchaseTx({+ connection: solanaConnection({ commitment: 'confirmed' }),+ buyerPublicKey,+ recipient: payment.payTo,+ mint: payment.mint,+ creatorAtomics: BigInt(intent.amount_atomics),+ reference,+ decimals: USDC_DECIMALS,+ });+ if (prepared) {+ intent.transaction = prepared.transaction;+ intent.gasless = true;+ intent.fee_payer = prepared.feePayer;+ }+ } catch (err) {+ console.warn('[print] gasless sponsorship unavailable:', err?.message);+ }+ }++ return json(+ res,+ 201,+ {+ order: {+ id: order.id,+ status: order.status,+ material_id: order.material_id,+ target_height_mm: order.target_height_mm,+ quantity: order.quantity,+ price_usdc: order.price_usdc,+ lead_time_days: quote.leadTimeDays,+ quote_expires_at: order.quote_expires_at,+ },+ payment: intent,+ track_url: `/materialize/orders/${order.id}`,+ },+ { 'cache-control': 'no-store' },+ );+});++// Exported so the reference generator can be swapped in tests without mocking+// @solana/web3.js wholesale.+export { PUBKEY_RE };diff --git a/api/print/orders/[id].js b/api/print/orders/[id].jsnew file mode 100644index 000000000..7c3f377ce--- /dev/null+++ b/api/print/orders/[id].js@@ -0,0 +1,90 @@+// GET /api/print/orders/:id: one print order and its full timeline.+//+// The timeline is print_order_events, appended once per transition and never+// mutated, so this is the order's whole story: when it was quoted, when the+// money landed, when it went to the floor, when it shipped, and any note an+// operator left along the way.+//+// Visible to the order's owner and to nobody else. An agent order (paid over+// x402, no session) is read back with the payer wallet's own signed access,+// which is the x402 lane's business; this endpoint is the human one and it+// answers 404, not 403, for an order that is not yours. Telling a stranger that+// an id exists is itself a leak.++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 { getOrderWithEvents } from '../../_lib/print-store.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;++/**+ * The buyer-facing projection of an order row. Deliberately explicit rather+ * than a spread: print_orders holds the shipping address and the provider's own+ * state, and neither belongs in a response just because a column was added.+ */+export function publicOrder(row) {+ return {+ id: row.id,+ status: row.status,+ created_at: row.created_at,+ updated_at: row.updated_at,+ creation_id: row.creation_id,+ material_id: row.material_id,+ target_height_mm: row.target_height_mm,+ quantity: row.quantity,+ price_usdc: row.price_usdc,+ // The itemization the buyer agreed to, read back rather than recomputed.+ quote: row.quote ?? null,+ lead_time_days: row.lead_time_days,+ quote_expires_at: row.quote_expires_at,+ paid_at: row.paid_at,+ payment: {+ chain: row.payment_chain,+ reference: row.payment_reference,+ signature: row.payment_signature,+ explorer_url: row.payment_signature ? `https://solscan.io/tx/${row.payment_signature}` : null,+ },+ // Where the parcel is going, in the one form a buyer needs to confirm they+ // typed it correctly. The full address stays with the operator console.+ ship_to: row.shipping+ ? { name: row.shipping.name, city: row.shipping.city, country: row.shipping.country }+ : null,+ tracking_number: row.tracking_number,+ carrier: row.carrier,+ };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const id = String(req.query?.id || '').trim();+ if (!UUID_RE.test(id)) return error(res, 400, 'validation_error', 'invalid order id');++ const rl = await limits.authedReadIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const user = await getSessionUser(req).catch(() => null);+ if (!user) return error(res, 401, 'unauthorized', 'sign in to view an order');++ const order = await getOrderWithEvents(id);+ if (!order || order.user_id !== user.id) {+ return error(res, 404, 'not_found', 'no such print order');+ }++ return json(+ res,+ 200,+ {+ order: publicOrder(order),+ events: order.events.map((e) => ({+ status: e.status,+ note: e.note,+ actor: e.actor,+ created_at: e.created_at,+ })),+ },+ { 'cache-control': 'no-store' },+ );+});diff --git a/pages/payment-outcomes.html b/pages/payment-outcomes.htmlindex e107f7176..9f22ee0e5 100644--- a/pages/payment-outcomes.html+++ b/pages/payment-outcomes.html@@ -31,7 +31,7 @@.po-note h2 { font-size: 15px; margin: 0 0 0.6rem; color: #e2e8f0; font-weight: 700; }.po-note a { color: #a78bfa; }- .po-banner { display: flex; gap: 0.6rem; align-items: flex-start; padding: 0.85rem 1.1rem; border-radius: 11px; margin-bottom: 1.5rem; font-size: 12.5px; line-height: 1.6; background: rgba(240,169,59,0.07); border: 1px solid rgba(240,169,59,0.24); color: #f0a93b; }+ .po-banner { padding: 0.85rem 1.1rem; border-radius: 11px; margin-bottom: 1.5rem; font-size: 12.5px; line-height: 1.6; background: rgba(240,169,59,0.07); border: 1px solid rgba(240,169,59,0.24); color: #f0a93b; }.po-section-title { font-size: 11px; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 700; color: rgba(255,255,255,0.35); margin: 0 0 0.85rem; display: flex; gap: 0.6rem; align-items: baseline; }.po-section-title span { text-transform: none; letter-spacing: 0; font-weight: 500; color: rgba(255,255,255,0.25); }@@ -44,7 +44,7 @@.po-cell-note { font-size: 11.5px; color: rgba(255,255,255,0.35); margin-top: 0.4rem; line-height: 1.5; }.good { color: #2fbf71; }.warn { color: #f0a93b; }- .bad { color: var(--color-danger); }+ .bad { color: var(--color-danger, #f87171); }.muted { color: rgba(255,255,255,0.35); }.po-pill { display: inline-block; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; padding: 3px 9px; border-radius: 999px; border: 1px solid currentColor; }@@ -351,6 +351,11 @@function strandedSection(stranded) {if (!stranded) return '';if (stranded.error) return panelError('Stranded custody', stranded);+ // null is not zero. The panel returns nulls when the process could not+ // open the wallets at all (no decryption key, a partial balance read),+ // and rendering that as a green 0 would report "no customer money is+ // sealed" on the strength of a reading that never happened.+ const measured = typeof stranded.sol_stranded === 'number' && stranded.status !== 'unknown';const rows = (stranded.top_stranded || []).map((w) => `<tr><td class="po-addr">${esc(w.address)}</td>@@ -368,13 +373,17 @@</div><div class="po-cell"><div class="po-cell-label">SOL behind a retired key</div>- <div class="po-cell-value ${stranded.sol_stranded ? 'bad' : 'good'}">${sol(stranded.sol_stranded)}</div>- <div class="po-cell-note">platform ${sol(stranded.sol_stranded_platform)}, customer ${sol(stranded.sol_stranded_customer)}</div>+ <div class="po-cell-value ${measured ? (stranded.sol_stranded ? 'bad' : 'good') : 'muted'}">${measured ? sol(stranded.sol_stranded) : 'not measured'}</div>+ <div class="po-cell-note">${measured+ ? `platform ${sol(stranded.sol_stranded_platform)}, customer ${sol(stranded.sol_stranded_customer)}`+ : `${num(stranded.undecryptable)} of ${num(stranded.wallets)} wallets could not be opened by this process${stranded.reason ? ` (${esc(stranded.reason)})` : ''}`}</div></div><div class="po-cell"><div class="po-cell-label">Customer wallets affected</div>- <div class="po-cell-value ${stranded.customer_wallets_stranded ? 'bad' : ''}">${num(stranded.customer_wallets_stranded)}</div>- <div class="po-cell-note">${stranded.brief ? `support obligation: ${esc(stranded.brief)}` : 'no customer money is sealed'}</div>+ <div class="po-cell-value ${measured ? (stranded.customer_wallets_stranded ? 'bad' : 'good') : 'muted'}">${measured ? num(stranded.customer_wallets_stranded) : 'not measured'}</div>+ <div class="po-cell-note">${measured+ ? (stranded.brief ? `support obligation: ${esc(stranded.brief)}` : 'no customer money is sealed')+ : 'an unmeasured panel is not an all-clear'}</div></div></div>${rows ? `<div class="po-table-wrap" style="margin-top:1.25rem">diff --git a/tests/print-adapter-contract.test.js b/tests/print-adapter-contract.test.jsnew file mode 100644index 000000000..dfb2ebffc--- /dev/null+++ b/tests/print-adapter-contract.test.js@@ -0,0 +1,314 @@+// The fulfillment adapter conformance suite.+//+// Every adapter that can move a print order runs through the same checks here,+// because the entire value of the adapter layer is that a contracted partner's+// API becomes a config change rather than a rebuild. That only holds if every+// lane is held to one shape.+//+// `partner-cn` is deliberately uncontracted (materialize-00-CONTEXT): the paths+// exercised below are the ones that run WITHOUT partner credentials plus the+// two that need only the HMAC secret, which the test supplies itself.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { createHmac } from 'node:crypto';++import manual from '../api/_lib/print/adapters/manual.js';+import partnerCn, { PARTNER_STATE_MAP, mapState } from '../api/_lib/print/adapters/partner-cn.js';+import {+ ADAPTER_DRIVABLE_STATUSES,+ AdapterContractError,+ adapterSupportsOrder,+ assertAdapterShape,+ assertCapabilities,+ derivedDeliveryId,+ mapProviderStatus,+ normalizeStatusResult,+ normalizeSubmitResult,+ normalizeWebhookEvent,+} from '../api/_lib/print/adapters/contract.js';+import { PRINT_STATUSES } from '../api/_lib/print-store.js';++const ADAPTERS = [manual, partnerCn];++describe('conformance: every adapter satisfies the contract', () => {+ for (const adapter of ADAPTERS) {+ describe(adapter.key, () => {+ it('declares a valid shape', () => {+ expect(() => assertAdapterShape(adapter)).not.toThrow();+ });++ it('declares capabilities the router can compare against', () => {+ expect(() => assertCapabilities(adapter.key, adapter.capabilities)).not.toThrow();+ expect(adapter.capabilities.leadTimeDays).toBeGreaterThan(0);+ });++ it('answers configured() without throwing', () => {+ expect(typeof adapter.configured()).toBe('boolean');+ });++ it('refuses a webhook it cannot authenticate', () => {+ const verdict = adapter.verifyWebhook('{}', {});+ expect(verdict.ok).toBe(false);+ expect(verdict.reason).toBeTruthy();+ });+ });+ }+});++describe('assertAdapterShape rejects a half-built adapter', () => {+ const base = { key: 'test-lane', label: 'Test', capabilities: manual.capabilities, ...methodStubs() };++ function methodStubs() {+ return {+ configured: () => true,+ submit: async () => ({}),+ status: async () => ({}),+ cancel: async () => ({}),+ verifyWebhook: () => ({ ok: false }),+ parseWebhook: () => ({}),+ };+ }++ it('rejects a missing method', () => {+ const broken = { ...base };+ delete broken.status;+ expect(() => assertAdapterShape(broken)).toThrow(AdapterContractError);+ });++ it('rejects a key that is not lower-kebab', () => {+ expect(() => assertAdapterShape({ ...base, key: 'Partner CN' })).toThrow(/lower-kebab/);+ });++ it('rejects capabilities without a build volume', () => {+ expect(() => assertAdapterShape({ ...base, capabilities: { materials: '*', shipsFrom: 'US', leadTimeDays: 5 } })).toThrow(/maxBboxMm/);+ });++ it('rejects a lead time nobody could honour', () => {+ expect(() => assertCapabilities('x', { ...manual.capabilities, leadTimeDays: 0 })).toThrow(/leadTimeDays/);+ expect(() => assertCapabilities('x', { ...manual.capabilities, leadTimeDays: 900 })).toThrow(/leadTimeDays/);+ });++ it('rejects a shipsFrom that is not a country code', () => {+ expect(() => assertCapabilities('x', { ...manual.capabilities, shipsFrom: 'China' })).toThrow(/alpha-2/);+ });+});++describe('capability routing is a comparison against published facts', () => {+ it('the manual lane runs any material', () => {+ expect(adapterSupportsOrder(manual, { material_id: 'anything-at-all' }).ok).toBe(true);+ });++ it('a partner declines a material it does not run', () => {+ const verdict = adapterSupportsOrder(partnerCn, { material_id: 'pla-draft' });+ expect(verdict.ok).toBe(false);+ expect(verdict.reason).toMatch(/not offered/);+ });++ it('a part larger than the build volume is declined, not attempted', () => {+ const verdict = adapterSupportsOrder(manual, {+ material_id: 'resin-standard',+ analysis: { bbox_mm: { x: 50, y: 50, z: 900 } },+ });+ expect(verdict.ok).toBe(false);+ expect(verdict.reason).toMatch(/build volume/);+ });++ it('an order with no analysis is not blocked on a bbox nobody measured', () => {+ expect(adapterSupportsOrder(manual, { material_id: 'resin-standard' }).ok).toBe(true);+ });+});++describe('the drivable status set cannot reach behind the payment gate', () => {+ it('is a subset of the store vocabulary', () => {+ for (const s of ADAPTER_DRIVABLE_STATUSES) expect(PRINT_STATUSES).toContain(s);+ });++ it('excludes everything before submission and the refund decision', () => {+ for (const s of ['created', 'quoted', 'paid', 'screening', 'refunded']) {+ expect(ADAPTER_DRIVABLE_STATUSES).not.toContain(s);+ }+ });+});++describe('result normalization refuses junk at the adapter boundary', () => {+ it('requires a provider order id from submit()', () => {+ expect(() => normalizeSubmitResult('x', { status: 'submitted' })).toThrow(/providerOrderId/);+ });++ it('refuses a submit status the provider may not drive', () => {+ expect(() => normalizeSubmitResult('x', { providerOrderId: 'a', status: 'refunded' })).toThrow(/must be one of/);+ });++ it('treats a null status from status() as no news, not an error', () => {+ const out = normalizeStatusResult('x', { status: null, trackingNumber: ' 1Z999 ' });+ expect(out.status).toBeNull();+ expect(out.trackingNumber).toBe('1Z999');+ });++ it('requires a webhook event to identify the order', () => {+ expect(() => normalizeWebhookEvent('x', { status: 'shipped' })).toThrow(/identify the order/);+ });++ it('drops a provider state blob too large for the column', () => {+ const huge = { blob: 'x'.repeat(20_000) };+ const out = normalizeStatusResult('x', { status: 'printing', state: huge });+ expect(out.state.truncated).toBe(true);+ });++ it('survives a circular provider payload instead of throwing', () => {+ const circular = { a: 1 };+ circular.self = circular;+ expect(normalizeStatusResult('x', { status: 'printing', state: circular }).state).toEqual({});+ });+});++describe('provider status mapping never guesses', () => {+ it('maps a documented state', () => {+ expect(mapState('in_production')).toBe('printing');+ expect(mapState('SHIPPED')).toBe('shipped');+ });++ it('maps an unknown state to null rather than inventing a transition', () => {+ expect(mapState('doing_something_new')).toBeNull();+ expect(mapState(undefined)).toBeNull();+ expect(mapState(42)).toBeNull();+ });++ it('every declared mapping targets a real store status', () => {+ for (const target of Object.values(PARTNER_STATE_MAP)) expect(PRINT_STATUSES).toContain(target);+ });++ it('refuses a mapping table entry that is not a status', () => {+ expect(mapProviderStatus({ weird: 'not_a_status' }, 'weird')).toBeNull();+ });+});++describe('derived delivery ids make an unlabelled retry idempotent', () => {+ it('is stable for the same payload and distinct across providers', () => {+ const body = '{"id":"abc","state":"shipped"}';+ expect(derivedDeliveryId('partner-cn', body)).toBe(derivedDeliveryId('partner-cn', body));+ expect(derivedDeliveryId('partner-cn', body)).not.toBe(derivedDeliveryId('other', body));+ });++ it('changes when a single byte of the payload changes', () => {+ expect(derivedDeliveryId('p', '{"a":1}')).not.toBe(derivedDeliveryId('p', '{"a":2}'));+ });+});++describe('manual lane: the launch path, with no webhook door', () => {+ it('is always configured, because it needs a person and not a credential', () => {+ expect(manual.configured()).toBe(true);+ });++ it('refuses every webhook delivery, signed or not', () => {+ expect(manual.verifyWebhook('{"id":"x"}', { 'x-print-signature': 'anything' }).ok).toBe(false);+ });++ it('parseWebhook is unreachable and says so rather than returning a fake event', () => {+ expect(() => manual.parseWebhook({})).toThrow(/receives no webhooks/);+ });+});++describe('partner-cn without credentials', () => {+ const saved = { url: process.env.PRINT_PARTNER_CN_URL, key: process.env.PRINT_PARTNER_CN_KEY };++ beforeEach(() => {+ delete process.env.PRINT_PARTNER_CN_URL;+ delete process.env.PRINT_PARTNER_CN_KEY;+ });++ afterEach(() => {+ if (saved.url) process.env.PRINT_PARTNER_CN_URL = saved.url;+ else delete process.env.PRINT_PARTNER_CN_URL;+ if (saved.key) process.env.PRINT_PARTNER_CN_KEY = saved.key;+ else delete process.env.PRINT_PARTNER_CN_KEY;+ });++ it('is not configured', () => {+ expect(partnerCn.configured()).toBe(false);+ });++ it('refuses a webhook rather than accepting an unverifiable one', () => {+ const verdict = partnerCn.verifyWebhook('{}', { 'x-print-signature': 'sha256=deadbeef' });+ expect(verdict.ok).toBe(false);+ expect(verdict.reason).toMatch(/not configured/);+ });++ it('refuses to submit rather than calling an unconfigured base URL', async () => {+ await expect(partnerCn.submit({ id: 'o1' }, {})).rejects.toThrow(/not configured/);+ });++ it('still parses a payload into store vocabulary, which is credential-free', () => {+ const event = partnerCn.parseWebhook({ id: 'p-1', state: 'shipped', tracking_number: '1Z', carrier: 'UPS' });+ expect(event).toMatchObject({ providerOrderId: 'p-1', status: 'shipped', trackingNumber: '1Z', carrier: 'UPS' });+ });+});++describe('partner-cn webhook verification, with only the HMAC secret', () => {+ const SECRET = 'test-hmac-secret-not-a-real-credential';+ const BODY = '{"id":"p-42","state":"in_production"}';++ beforeEach(() => {+ process.env.PRINT_PARTNER_CN_URL = 'https://partner.invalid/api';+ process.env.PRINT_PARTNER_CN_KEY = SECRET;+ });++ afterEach(() => {+ delete process.env.PRINT_PARTNER_CN_URL;+ delete process.env.PRINT_PARTNER_CN_KEY;+ });++ const sign = (body, secret = SECRET) => createHmac('sha256', secret).update(body, 'utf8').digest('hex');++ it('accepts a correctly signed delivery and derives an id when none is supplied', () => {+ const verdict = partnerCn.verifyWebhook(BODY, { 'x-print-signature': `sha256=${sign(BODY)}` });+ expect(verdict.ok).toBe(true);+ expect(verdict.deliveryId).toBe(derivedDeliveryId('partner-cn', BODY));+ });++ it('prefers the provider delivery id when they send one', () => {+ const verdict = partnerCn.verifyWebhook(BODY, {+ 'x-print-signature': sign(BODY),+ 'x-print-delivery': 'dlv_991',+ });+ expect(verdict).toMatchObject({ ok: true, deliveryId: 'dlv_991' });+ });++ it('rejects a signature computed with the wrong secret', () => {+ const verdict = partnerCn.verifyWebhook(BODY, { 'x-print-signature': sign(BODY, 'wrong-secret') });+ expect(verdict).toMatchObject({ ok: false, reason: 'signature mismatch' });+ });++ it('rejects a body that was altered after signing', () => {+ const signature = sign(BODY);+ const tampered = BODY.replace('in_production', 'shipped');+ expect(partnerCn.verifyWebhook(tampered, { 'x-print-signature': signature }).ok).toBe(false);+ });++ it('rejects a truncated signature without throwing on the length mismatch', () => {+ expect(() => partnerCn.verifyWebhook(BODY, { 'x-print-signature': 'sha256=ab' })).not.toThrow();+ expect(partnerCn.verifyWebhook(BODY, { 'x-print-signature': 'sha256=ab' }).ok).toBe(false);+ });++ it('rejects a delivery with no signature at all', () => {+ expect(partnerCn.verifyWebhook(BODY, {}).reason).toMatch(/missing x-print-signature/);+ });++ it('registers in the adapter registry only once configured', async () => {+ vi.resetModules();+ const { listAdapters } = await import('../api/_lib/print/adapters/index.js');+ expect(listAdapters().map((a) => a.key)).toContain('partner-cn');+ });+});++describe('the registry hides a lane whose credentials are absent', () => {+ it('offers only the manual lane on a deployment with no partner', async () => {+ delete process.env.PRINT_PARTNER_CN_URL;+ delete process.env.PRINT_PARTNER_CN_KEY;+ vi.resetModules();+ const { listAdapters, getAdapter, routeOrder } = await import('../api/_lib/print/adapters/index.js');+ expect(listAdapters().map((a) => a.key)).toEqual(['manual']);+ expect(getAdapter('partner-cn')).toBeNull();+ expect(routeOrder({ material_id: 'resin-standard' }).adapter.key).toBe('manual');+ });+});diff --git a/tests/print-certificate.test.js b/tests/print-certificate.test.jsnew file mode 100644index 000000000..9f82a4198--- /dev/null+++ b/tests/print-certificate.test.js@@ -0,0 +1,564 @@+/**+ * Materialize certificates: hashing, atomic edition claiming, memo shape,+ * cluster gating, and the visibility rule on the public read.+ *+ * The database boundary is a faithful in-memory double rather than a stub that+ * returns whatever the assertion wants: it enforces the two unique indexes the+ * migration declares and, in the concurrency test, deliberately interleaves two+ * writers between reading `max(edition_no)` and inserting, which is precisely+ * the race the HAVING clause plus the unique index exist to survive. A stub+ * that could not lose that race would prove nothing.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';++const db = { sql: null };+vi.mock('../api/_lib/db.js', () => ({+ get sql() {+ return db.sql;+ },+}));++const {+ sha256Hex,+ buildCertificateMemo,+ claimEdition,+ certCluster,+ mainnetAttestationAllowed,+ explorerTxUrl,+ newCertificateId,+ pickPrintAsset,+ getPublicCertificate,+ certificateUrl,+ CERT_ID_RE,+ CERT_MEMO_KIND,+} = await import('../api/_lib/print/certificate.js');++const {+ normalizeEditionLimit,+ seriesKeyFor,+ assertEditionAvailable,+ PrintEditionError,+} = await import('../api/_lib/print/editions.js');++// ── an in-memory print_certificates that behaves like the real table ─────────++class UniqueViolation extends Error {+ constructor(constraint) {+ super(`duplicate key value violates unique constraint "${constraint}"`);+ this.code = '23505';+ this.constraint = constraint;+ }+}++/**+ * @param {object[]} rows shared table contents+ * @param {() => Promise<void>} [yieldPoint] awaited between reading max() and+ * inserting, so a test can interleave two writers at exactly the racy moment.+ */+function makeCertificateSql(rows, yieldPoint = null) {+ return async (strings, ...values) => {+ const text = strings.join(' ? ').replace(/\s+/g, ' ').trim();++ if (text.startsWith('insert into print_certificates')) {+ const [+ id, orderId, creationId, seriesKey, editionOf,+ glbSha256, glbBytes, printAssetKind, printAssetKey, printAssetSha256,+ materialId, materialLabel, network, whereSeries, havingA, havingB,+ ] = values;+ const max = rows+ .filter((r) => r.series_key === whereSeries)+ .reduce((m, r) => Math.max(m, r.edition_no), 0);+ const next = max + 1;+ if (yieldPoint) await yieldPoint();+ if (havingA !== null && havingB !== null && next > Number(havingB)) return [];+ if (rows.some((r) => r.order_id === orderId)) {+ throw new UniqueViolation('print_certificates_order_uniq');+ }+ if (rows.some((r) => r.series_key === seriesKey && r.edition_no === next)) {+ throw new UniqueViolation('print_certificates_series_edition_uniq');+ }+ const row = {+ id, order_id: orderId, creation_id: creationId, series_key: seriesKey,+ edition_no: next, edition_of: editionOf, glb_sha256: glbSha256,+ glb_bytes: glbBytes, print_asset_kind: printAssetKind,+ print_asset_key: printAssetKey, print_asset_sha256: printAssetSha256,+ material_id: materialId, material_label: materialLabel,+ network, memo: '', solana_signature: null,+ };+ rows.push(row);+ return [row];+ }++ if (text.startsWith('select * from print_certificates where order_id')) {+ const found = rows.filter((r) => r.order_id === values[0]);+ return found.length ? [found[0]] : [];+ }++ if (text.includes('count(*)::int as n from print_certificates')) {+ return [{ n: rows.filter((r) => r.series_key === values[0]).length }];+ }++ throw new Error(`unhandled query in test double: ${text}`);+ };+}++function certRow(overrides = {}) {+ return {+ id: newCertificateId(),+ order_id: `order-${Math.random().toString(36).slice(2, 10)}`,+ creation_id: '11111111-1111-4111-8111-111111111111',+ series_key: '11111111-1111-4111-8111-111111111111',+ edition_of: null,+ glb_sha256: 'a'.repeat(64),+ glb_bytes: 1024,+ print_asset_kind: null,+ print_asset_key: null,+ print_asset_sha256: null,+ material_id: 'resin-standard',+ material_label: 'Standard resin',+ network: 'devnet',+ ...overrides,+ };+}++beforeEach(() => {+ db.sql = null;+ delete process.env.PRINT_CERT_CLUSTER;+ delete process.env.PRINT_CERT_MAINNET_APPROVAL;+});++// ── hashing ─────────────────────────────────────────────────────────────────++describe('sha256Hex', () => {+ it('matches the published SHA-256 vectors byte for byte', () => {+ expect(sha256Hex(Buffer.from('abc'))).toBe(+ 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',+ );+ expect(sha256Hex(Buffer.alloc(0))).toBe(+ 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',+ );+ expect(sha256Hex(Buffer.from('three.ws'))).toBe(+ 'cb73ad9077afe7f5456a1473320974ef441820fce9c05c95101290480156a67e',+ );+ });++ it('hashes bytes, not their encoding: a Uint8Array and a Buffer agree', () => {+ const bytes = new Uint8Array([0, 1, 2, 250, 251, 255]);+ expect(sha256Hex(bytes)).toBe(sha256Hex(Buffer.from(bytes)));+ });++ it('separates one byte of difference', () => {+ expect(sha256Hex(Buffer.from([1, 2, 3]))).not.toBe(sha256Hex(Buffer.from([1, 2, 4])));+ });+});++describe('newCertificateId', () => {+ it('produces 24 lowercase hex characters that the route regex accepts', () => {+ for (let i = 0; i < 50; i++) {+ const id = newCertificateId();+ expect(id).toMatch(CERT_ID_RE);+ expect(id).toMatch(/^[0-9a-f]{24}$/);+ }+ });++ it('does not repeat across a batch', () => {+ const ids = new Set(Array.from({ length: 500 }, () => newCertificateId()));+ expect(ids.size).toBe(500);+ });+});++// ── memo payload ────────────────────────────────────────────────────────────++describe('buildCertificateMemo', () => {+ it('carries the certificate, the hash, and the edition in a versioned envelope', () => {+ const memo = buildCertificateMemo({+ id: 'abcdef0123456789abcdef01',+ glb_sha256: 'b'.repeat(64),+ edition_no: 3,+ edition_of: 25,+ creation_id: '11111111-1111-4111-8111-111111111111',+ printed_at: '2026-09-02T12:00:00.000Z',+ });+ const parsed = JSON.parse(memo);+ expect(parsed).toEqual({+ v: 1,+ kind: CERT_MEMO_KIND,+ cert: 'abcdef0123456789abcdef01',+ sha256: 'b'.repeat(64),+ ed: 3,+ of: 25,+ ts: 1788350400,+ creation: '11111111-1111-4111-8111-111111111111',+ });+ });++ it('records an open edition as an explicit null rather than omitting it', () => {+ const parsed = JSON.parse(buildCertificateMemo({ id: 'a'.repeat(24), glb_sha256: 'c'.repeat(64), edition_no: 1, edition_of: null }));+ expect(parsed.of).toBeNull();+ expect(Object.prototype.hasOwnProperty.call(parsed, 'of')).toBe(true);+ });++ it('omits the creation key for a direct upload that has no forge row', () => {+ const parsed = JSON.parse(buildCertificateMemo({ id: 'a'.repeat(24), glb_sha256: 'c'.repeat(64), edition_no: 1, creation_id: null }));+ expect(Object.prototype.hasOwnProperty.call(parsed, 'creation')).toBe(false);+ });++ it('adds the manufacturing file hash only when both its kind and hash are known', () => {+ const withPrint = JSON.parse(+ buildCertificateMemo({+ id: 'a'.repeat(24), glb_sha256: 'c'.repeat(64), edition_no: 1,+ print_asset_kind: '3mf', print_asset_sha256: 'd'.repeat(64),+ }),+ );+ expect(withPrint.print).toBe(`3mf:${'d'.repeat(64)}`);+ const withoutKind = JSON.parse(+ buildCertificateMemo({ id: 'a'.repeat(24), glb_sha256: 'c'.repeat(64), edition_no: 1, print_asset_sha256: 'd'.repeat(64) }),+ );+ expect(withoutKind.print).toBeUndefined();+ });++ it('stays well inside the SPL Memo per-transaction ceiling', () => {+ const memo = buildCertificateMemo({+ id: 'f'.repeat(24), glb_sha256: 'e'.repeat(64), edition_no: 9999, edition_of: 10000,+ creation_id: '11111111-1111-4111-8111-111111111111',+ print_asset_kind: '3mf', print_asset_sha256: 'd'.repeat(64),+ });+ expect(Buffer.byteLength(memo, 'utf8')).toBeLessThan(566);+ });+});++// ── cluster and the mainnet gate ────────────────────────────────────────────++describe('certCluster', () => {+ it('defaults to devnet when nothing is configured', () => {+ expect(certCluster()).toBe('devnet');+ });++ it('stays on devnet for anything that is not exactly mainnet', () => {+ for (const value of ['', 'testnet', 'main', 'MAINNET-BETA', 'true', 'yes']) {+ process.env.PRINT_CERT_CLUSTER = value;+ expect(certCluster()).toBe('devnet');+ }+ });++ it('selects mainnet only on the explicit flag, case and padding tolerant', () => {+ process.env.PRINT_CERT_CLUSTER = ' MainNet ';+ expect(certCluster()).toBe('mainnet');+ });+});++describe('mainnetAttestationAllowed', () => {+ it('refuses without a recorded owner approval', () => {+ const gate = mainnetAttestationAllowed();+ expect(gate.allowed).toBe(false);+ expect(gate.reason).toContain('PRINT_CERT_MAINNET_APPROVAL');+ });++ it('allows once the approval is recorded', () => {+ process.env.PRINT_CERT_MAINNET_APPROVAL = 'owner-approved-2026-09-02';+ expect(mainnetAttestationAllowed().allowed).toBe(true);+ });++ it('treats whitespace as no approval at all', () => {+ process.env.PRINT_CERT_MAINNET_APPROVAL = ' ';+ expect(mainnetAttestationAllowed().allowed).toBe(false);+ });+});++describe('explorerTxUrl', () => {+ it('marks devnet signatures with the cluster query and leaves mainnet bare', () => {+ expect(explorerTxUrl('sig123', 'devnet')).toBe('https://explorer.solana.com/tx/sig123?cluster=devnet');+ expect(explorerTxUrl('sig123', 'mainnet')).toBe('https://explorer.solana.com/tx/sig123');+ });+});++describe('certificateUrl', () => {+ it('builds the address the QR encodes', () => {+ expect(certificateUrl('abcdef0123456789abcdef01')).toMatch(/\/cert\/abcdef0123456789abcdef01$/);+ });+});++describe('pickPrintAsset', () => {+ it('prefers the richest manufacturing format the prepare step produced', () => {+ expect(pickPrintAsset({ glb: 'g', stl: 's', '3mf': 'm' })).toEqual({ kind: '3mf', url: 'm' });+ expect(pickPrintAsset({ glb: 'g', stl: 's' })).toEqual({ kind: 'stl', url: 's' });+ expect(pickPrintAsset({ glb: 'g' })).toEqual({ kind: 'glb', url: 'g' });+ expect(pickPrintAsset({})).toBeNull();+ expect(pickPrintAsset(null)).toBeNull();+ });+});++// ── edition claiming ────────────────────────────────────────────────────────++describe('claimEdition', () => {+ it('numbers a series from one and keeps counting', async () => {+ const rows = [];+ db.sql = makeCertificateSql(rows);+ const first = await claimEdition(certRow());+ const second = await claimEdition(certRow());+ expect([first.edition_no, second.edition_no]).toEqual([1, 2]);+ });++ it('numbers separate series independently', async () => {+ const rows = [];+ db.sql = makeCertificateSql(rows);+ await claimEdition(certRow({ series_key: 'model-a' }));+ const other = await claimEdition(certRow({ series_key: 'model-b' }));+ expect(other.edition_no).toBe(1);+ });++ it('returns the existing certificate when an order is claimed twice', async () => {+ const rows = [];+ db.sql = makeCertificateSql(rows);+ const row = certRow();+ const first = await claimEdition(row);+ const again = await claimEdition({ ...certRow(), order_id: row.order_id });+ expect(again.id).toBe(first.id);+ expect(rows).toHaveLength(1);+ });++ it('issues no duplicate edition number when two shipments race', async () => {+ const rows = [];+ // Both writers read max(edition_no) before either inserts: the exact+ // interleaving the unique index has to survive.+ let waiting = null;+ const yieldPoint = () =>+ new Promise((resolve) => {+ if (waiting) {+ const other = waiting;+ waiting = null;+ other();+ resolve();+ } else {+ waiting = resolve;+ setTimeout(() => {+ if (waiting === resolve) {+ waiting = null;+ resolve();+ }+ }, 5);+ }+ });+ db.sql = makeCertificateSql(rows, yieldPoint);++ const [a, b] = await Promise.all([claimEdition(certRow()), claimEdition(certRow())]);+ expect(new Set([a.edition_no, b.edition_no]).size).toBe(2);+ expect([a.edition_no, b.edition_no].sort()).toEqual([1, 2]);+ expect(rows).toHaveLength(2);+ });++ it('survives a wider stampede without repeating a number', async () => {+ const rows = [];+ db.sql = makeCertificateSql(rows, () => new Promise((r) => setTimeout(r, 1)));+ const claims = await Promise.all(Array.from({ length: 8 }, () => claimEdition(certRow())));+ const numbers = claims.map((c) => c.edition_no).sort((x, y) => x - y);+ expect(numbers).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);+ });++ it('refuses to over-number a capped edition', async () => {+ const rows = [];+ db.sql = makeCertificateSql(rows);+ await claimEdition(certRow({ edition_of: 2 }));+ await claimEdition(certRow({ edition_of: 2 }));+ await expect(claimEdition(certRow({ edition_of: 2 }))).rejects.toMatchObject({+ code: 'edition_sold_out',+ });+ expect(rows).toHaveLength(2);+ });++ it('lets a capped edition fill exactly to its last copy under a race', async () => {+ const rows = [];+ db.sql = makeCertificateSql(rows, () => new Promise((r) => setTimeout(r, 1)));+ const settled = await Promise.allSettled([+ claimEdition(certRow({ edition_of: 1 })),+ claimEdition(certRow({ edition_of: 1 })),+ ]);+ expect(settled.filter((s) => s.status === 'fulfilled')).toHaveLength(1);+ expect(settled.filter((s) => s.status === 'rejected')).toHaveLength(1);+ expect(rows).toHaveLength(1);+ });+});++// ── editions module ─────────────────────────────────────────────────────────++describe('normalizeEditionLimit', () => {+ it('reads an absent cap as an open edition', () => {+ for (const value of [null, undefined, '']) expect(normalizeEditionLimit(value)).toBeNull();+ });++ it('accepts a whole number inside the band', () => {+ expect(normalizeEditionLimit(25)).toBe(25);+ expect(normalizeEditionLimit(' 7 ')).toBe(7);+ expect(normalizeEditionLimit(10000)).toBe(10000);+ });++ it('refuses fractions, zero, negatives, and anything past the ceiling', () => {+ for (const bad of [2.5, 0, -1, 10001, 'many']) {+ expect(() => normalizeEditionLimit(bad)).toThrow(PrintEditionError);+ }+ });+});++describe('seriesKeyFor', () => {+ it('keys a forge print by its creation', () => {+ expect(seriesKeyFor({ creationId: 'abc' })).toBe('abc');+ });++ it('keys a direct upload by its content hash so identical bytes share one series', () => {+ expect(seriesKeyFor({ glbSha256: 'a'.repeat(64) })).toBe(`sha256:${'a'.repeat(64)}`);+ });++ it('refuses to invent a series from nothing', () => {+ expect(() => seriesKeyFor({})).toThrow(PrintEditionError);+ expect(() => seriesKeyFor({ glbSha256: 'not-a-hash' })).toThrow(PrintEditionError);+ });+});++describe('assertEditionAvailable', () => {+ function editionSql({ limit, issued }) {+ return async (strings, ...values) => {+ const text = strings.join(' ? ').replace(/\s+/g, ' ').trim();+ if (text.includes('print_edition_limit from forge_creations')) return [{ print_edition_limit: limit }];+ if (text.includes('count(*)::int as n from print_certificates')) return [{ n: issued }];+ throw new Error(`unhandled query: ${text}`);+ };+ }++ it('lets an open edition through at any quantity', async () => {+ db.sql = editionSql({ limit: null, issued: 900 });+ const state = await assertEditionAvailable({ creationId: 'c1', quantity: 50 });+ expect(state.limit).toBeNull();+ expect(state.soldOut).toBe(false);+ });++ it('lets a partly-filled edition through', async () => {+ db.sql = editionSql({ limit: 25, issued: 3 });+ const state = await assertEditionAvailable({ creationId: 'c1', quantity: 2 });+ expect(state.remaining).toBe(22);+ });++ it('refuses a quote once the last copy has shipped', async () => {+ db.sql = editionSql({ limit: 5, issued: 5 });+ await expect(assertEditionAvailable({ creationId: 'c1' })).rejects.toMatchObject({+ code: 'edition_sold_out',+ });+ });++ it('refuses a quantity larger than what is left, and says how many remain', async () => {+ db.sql = editionSql({ limit: 5, issued: 4 });+ await expect(assertEditionAvailable({ creationId: 'c1', quantity: 3 })).rejects.toThrow(/Only 1 of this 5-piece edition is left/);+ });++ it('reports a sold-out series in language a buyer can act on', async () => {+ db.sql = editionSql({ limit: 5, issued: 5 });+ await expect(assertEditionAvailable({ creationId: 'c1' })).rejects.toThrow(/sold out. All 5 copies have shipped/);+ });+});++// ── the public read and its visibility rule ─────────────────────────────────++describe('getPublicCertificate', () => {+ function readSql(row) {+ return async (strings, ...values) => {+ const text = strings.join(' ? ').replace(/\s+/g, ' ').trim();+ if (text.includes('from print_certificates c join print_orders o')) return row ? [row] : [];+ if (text.includes('count(*)::int as n from print_certificates')) return [{ n: 4 }];+ throw new Error(`unhandled query: ${text}`);+ };+ }++ const base = {+ id: 'abcdef0123456789abcdef01',+ order_id: 'order-1',+ creation_id: '11111111-1111-4111-8111-111111111111',+ series_key: '11111111-1111-4111-8111-111111111111',+ edition_no: 3,+ edition_of: 25,+ glb_sha256: 'a'.repeat(64),+ glb_bytes: 4096,+ print_asset_kind: '3mf',+ print_asset_sha256: 'b'.repeat(64),+ material_id: 'resin-standard',+ material_label: 'Standard resin',+ printed_at: '2026-09-02T00:00:00.000Z',+ network: 'devnet',+ memo: '{"v":1}',+ solana_signature: 'sig-1',+ attested_at: '2026-09-02T00:01:00.000Z',+ qr_url: 'https://cdn.example.com/print/certs/x/qr.png',+ creation_prompt: 'a brass orrery',+ creation_visibility: null,+ creation_glb_url: 'https://cdn.example.com/model.glb',+ creation_preview_url: 'https://cdn.example.com/model.png',+ creation_parent_id: '22222222-2222-4222-8222-222222222222',+ creation_refine_instruction: 'more brass',+ creator_username: 'ada',+ creator_display_name: 'Ada',+ };++ it('rejects a malformed id without touching the database', async () => {+ db.sql = () => {+ throw new Error('should not query');+ };+ expect(await getPublicCertificate('nope')).toBeNull();+ expect(await getPublicCertificate('')).toBeNull();+ expect(await getPublicCertificate('ABCDEF0123456789ABCDEF01')).toBeNull();+ });++ it('returns null for an unknown certificate', async () => {+ db.sql = readSql(null);+ expect(await getPublicCertificate('abcdef0123456789abcdef01')).toBeNull();+ });++ it('renders a public model in full, prompt included', async () => {+ db.sql = readSql(base);+ const cert = await getPublicCertificate(base.id);+ expect(cert.creation.prompt).toBe('a brass orrery');+ expect(cert.creation.prompt_withheld).toBe(false);+ expect(cert.creation.model_url).toBe('/m/11111111-1111-4111-8111-111111111111');+ expect(cert.creation.creator_username).toBe('ada');+ expect(cert.edition_no).toBe(3);+ expect(cert.edition_of).toBe(25);+ expect(cert.explorer_url).toContain('cluster=devnet');+ });++ it('withholds a private model prompt while still issuing the certificate', async () => {+ db.sql = readSql({ ...base, creation_visibility: 'private' });+ const cert = await getPublicCertificate(base.id);+ expect(cert.creation.prompt).toBeNull();+ expect(cert.creation.prompt_withheld).toBe(true);+ expect(cert.creation.refine_instruction).toBeNull();+ expect(cert.creation.parent_creation_id).toBeNull();+ expect(cert.creation.creator_username).toBeNull();+ expect(cert.creation.model_url).toBeNull();+ // The proof itself is never withheld: the holder of the object owns it.+ expect(cert.glb_sha256).toBe('a'.repeat(64));+ expect(cert.memo).toBe('{"v":1}');+ expect(cert.solana_signature).toBe('sig-1');+ expect(cert.edition_no).toBe(3);+ });++ it('treats an unlisted model as public for its own certificate', async () => {+ db.sql = readSql({ ...base, creation_visibility: 'unlisted' });+ const cert = await getPublicCertificate(base.id);+ expect(cert.creation.prompt).toBe('a brass orrery');+ expect(cert.creation.prompt_withheld).toBe(false);+ });++ it('carries no order id, buyer, or shipping detail', async () => {+ db.sql = readSql(base);+ const cert = await getPublicCertificate(base.id);+ const serialized = JSON.stringify(cert);+ expect(serialized).not.toContain('order-1');+ expect(cert.order_id).toBeUndefined();+ expect(cert.shipping).toBeUndefined();+ });++ it('reports an unattested certificate honestly instead of inventing a link', async () => {+ db.sql = readSql({ ...base, solana_signature: null, attested_at: null });+ const cert = await getPublicCertificate(base.id);+ expect(cert.solana_signature).toBeNull();+ expect(cert.explorer_url).toBeNull();+ expect(cert.memo).toBe('{"v":1}');+ });+});diff --git a/tests/print-ops-authorization.test.js b/tests/print-ops-authorization.test.jsnew file mode 100644index 000000000..8b378849a--- /dev/null+++ b/tests/print-ops-authorization.test.js@@ -0,0 +1,304 @@+// Authorization on the Materialize operator console.+//+// These endpoints read shipping addresses (the first real PII this platform+// stores) and move orders through a state machine that ends in a refund. So the+// gate is stricter than the read-only ops boards: it fails closed in+// development too, and every action authorizes BEFORE it reads an order.+//+// The test that matters most is the sweep at the bottom: it enumerates the+// dispatch table itself, so an action added later without a gate fails here+// rather than shipping open.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const getSessionUser = vi.fn(async () => null);+const isAdminUser = vi.fn(async () => false);+const sqlMock = vi.fn(async () => []);++vi.mock('../api/_lib/auth.js', () => ({ getSessionUser }));+vi.mock('../api/_lib/admin.js', () => ({ isAdminUser, requireAdmin: vi.fn() }));+vi.mock('../api/_lib/db.js', () => ({+ sql: sqlMock,+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: () => false,+}));++const queries = {+ printStoreEnabled: vi.fn(() => true),+ countOrdersByStatus: vi.fn(async () => ({ paid: 1 })),+ listOrders: vi.fn(async () => []),+ listWebhookDeliveries: vi.fn(async () => []),+ allowedTransitions: vi.fn(() => ['screening']),+ ADAPTER_DRIVABLE_STATUSES: ['submitted'],+ OPEN_PROVIDER_STATUSES: ['submitted'],+ getOrderByProviderId: vi.fn(async () => null),+ listOpenProviderOrders: vi.fn(async () => []),+ listStalledOrders: vi.fn(async () => []),+ markStallAlerted: vi.fn(async () => 0),+ patchProviderDetails: vi.fn(async () => null),+ claimWebhookDelivery: vi.fn(async () => ({ fresh: true })),+ markWebhookApplied: vi.fn(async () => {}),+};+vi.mock('../api/_lib/print/fulfillment-queries.js', () => queries);++const store = {+ PRINT_STATUSES: ['created', 'quoted', 'paid', 'screening', 'submitted', 'shipped', 'refunded', 'canceled'],+ LEGAL_TRANSITIONS: { paid: ['screening'] },+ ACTORS: ['system', 'operator', 'provider', 'buyer'],+ TERMINAL_STATUSES: ['delivered'],+ PrintStoreError: class PrintStoreError extends Error {+ constructor(code, message) {+ super(message);+ this.code = code;+ }+ },+ canTransition: () => true,+ getOrder: vi.fn(async () => ORDER),+ getOrderWithEvents: vi.fn(async () => ({ ...ORDER, events: [] })),+ appendEvent: vi.fn(async () => ({ id: 'e1' })),+ transition: vi.fn(async () => ({ order: { ...ORDER, status: 'screening' }, event: { id: 'e1' }, certificate: null })),+};+vi.mock('../api/_lib/print-store.js', () => store);++const submitOrder = vi.fn(async () => ({ order: ORDER, adapter: 'manual', providerOrderId: ORDER.id }));+const cancelWithProvider = vi.fn(async () => ({ ok: true, note: 'stopped', state: {} }));+vi.mock('../api/_lib/print/fulfillment.js', () => ({+ submitOrder,+ cancelWithProvider,+ applyProviderEvent: vi.fn(),+ reconcileOrder: vi.fn(),+ FulfillmentError: class FulfillmentError extends Error {},+}));++const notifyOperators = vi.fn(async () => {});+vi.mock('../api/_lib/print/ops-notify.js', () => ({+ notifyOperators,+ jobSummaryLines: () => [],+ operatorChannelConfigured: () => false,+}));++const ORDER = {+ id: '00000000-0000-4000-8000-000000000001',+ status: 'paid',+ material_id: 'resin-standard',+ quantity: 1,+ price_usdc: '42.000000',+ payer_wallet: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ // The whole reason this gate fails closed: a leaked queue read is a leaked+ // home address.+ shipping: { name: 'A Buyer', line1: '1 Test Way', city: 'Denver', country: 'US' },+ prepared_asset_urls: { stl: 'https://example.invalid/a.stl' },+};++const handler = (await import('../api/print/ops/[action].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; } },+ };+}++// Every action the console exposes, with a request that would succeed if the+// caller were authorized. Kept as data so the sweeps below cannot miss one.+const ACTIONS = [+ { action: 'queue', method: 'GET' },+ { action: 'order', method: 'GET' },+ { action: 'adapters', method: 'GET' },+ { action: 'transition', method: 'POST', body: { order_id: ORDER.id, to: 'screening' } },+ { action: 'submit', method: 'POST', body: { order_id: ORDER.id } },+ { action: 'tracking', method: 'POST', body: { order_id: ORDER.id, tracking_number: '1Z999' } },+ { action: 'cancel', method: 'POST', body: { order_id: ORDER.id } },+ { action: 'refund', method: 'POST', body: { order_id: ORDER.id } },+];++function mockReq({ action, method: httpMethod = 'GET', body = null, headers = {} }) {+ const req = {+ method: httpMethod,+ url: `/api/print/ops/${action}?id=${ORDER.id}`,+ query: { action, id: ORDER.id },+ headers: { host: 'three.ws', ...headers },+ };+ if (body) {+ req.headers['content-type'] = 'application/json';+ req.rawBody = Buffer.from(JSON.stringify(body));+ }+ return req;+}++async function call(spec, headers = {}) {+ const res = mockRes();+ await handler(mockReq({ ...spec, headers }), res);+ return res;+}++beforeEach(() => {+ vi.clearAllMocks();+ getSessionUser.mockResolvedValue(null);+ isAdminUser.mockResolvedValue(false);+ queries.printStoreEnabled.mockReturnValue(true);+ queries.countOrdersByStatus.mockResolvedValue({ paid: 1 });+ queries.listOrders.mockResolvedValue([]);+ queries.listWebhookDeliveries.mockResolvedValue([]);+ queries.allowedTransitions.mockReturnValue(['screening']);+ store.getOrder.mockResolvedValue(ORDER);+ store.getOrderWithEvents.mockResolvedValue({ ...ORDER, events: [] });+ store.transition.mockResolvedValue({ order: { ...ORDER, status: 'screening' }, event: { id: 'e1' }, certificate: null });+ submitOrder.mockResolvedValue({ order: ORDER, adapter: 'manual', providerOrderId: ORDER.id });+ delete process.env.OPS_SECRET;+ delete process.env.PRINT_OPERATORS;+ delete process.env.NODE_ENV;+ delete process.env.VERCEL_ENV;+});++describe('anonymous callers are refused on every action', () => {+ for (const spec of ACTIONS) {+ it(`refuses anonymous ${spec.method} /api/print/ops/${spec.action}`, async () => {+ const res = await call(spec);+ expect(res.statusCode).toBe(403);+ expect(res.json.error).toBe('forbidden');+ });+ }++ it('leaks no order data in the refusal', async () => {+ const res = await call({ action: 'order', method: 'GET' });+ expect(res._body).not.toContain('1 Test Way');+ expect(res._body).not.toContain(ORDER.id);+ });++ it('never reads an order before deciding', async () => {+ await call({ action: 'order', method: 'GET' });+ expect(store.getOrder).not.toHaveBeenCalled();+ expect(store.getOrderWithEvents).not.toHaveBeenCalled();+ });+});++describe('a signed-in NON-operator is refused on every action', () => {+ beforeEach(() => {+ getSessionUser.mockResolvedValue({ id: 'user-9', wallet_address: 'NotAnOperator1111111111111111111111111111111' });+ isAdminUser.mockResolvedValue(false);+ });++ for (const spec of ACTIONS) {+ it(`refuses a plain user on ${spec.action}`, async () => {+ const res = await call(spec);+ expect(res.statusCode).toBe(403);+ });+ }++ it('does not move an order it refused', async () => {+ await call({ action: 'transition', method: 'POST', body: { order_id: ORDER.id, to: 'screening' } });+ expect(store.transition).not.toHaveBeenCalled();+ });++ it('a user on an allowlist that names someone else is still refused', async () => {+ process.env.PRINT_OPERATORS = 'someone-else,0x0000000000000000000000000000000000000001';+ expect((await call({ action: 'queue', method: 'GET' })).statusCode).toBe(403);+ });+});++describe('the gate fails closed in development', () => {+ it('an unconfigured deployment does not open the console to anyone', async () => {+ // api/_lib/ops-auth.js deliberately opens off-production when no secret is+ // set. This console must not inherit that: no NODE_ENV, no OPS_SECRET, and+ // the answer is still no.+ expect((await call({ action: 'queue', method: 'GET' })).statusCode).toBe(403);+ });+});++describe('authorized operators get through', () => {+ it('admits a platform admin and attributes the move to them', async () => {+ getSessionUser.mockResolvedValue({ id: 'admin-1', wallet_address: 'AdminWa11et' });+ isAdminUser.mockResolvedValue(true);+ const res = await call({ action: 'transition', method: 'POST', body: { order_id: ORDER.id, to: 'screening' } });+ expect(res.statusCode).toBe(200);+ expect(store.transition).toHaveBeenCalledWith(expect.objectContaining({ actor: 'operator', actorId: 'admin-1' }));+ });++ it('admits an allowlisted operator who is not an admin', async () => {+ process.env.PRINT_OPERATORS = 'op-user-7';+ getSessionUser.mockResolvedValue({ id: 'op-user-7', wallet_address: 'OperatorWa11et' });+ expect((await call({ action: 'queue', method: 'GET' })).statusCode).toBe(200);+ });++ it('admits the ops secret, with no user identity attached', async () => {+ process.env.OPS_SECRET = 'a-high-entropy-ops-secret';+ const res = await call(+ { action: 'transition', method: 'POST', body: { order_id: ORDER.id, to: 'screening' } },+ { 'x-ops-secret': 'a-high-entropy-ops-secret' },+ );+ expect(res.statusCode).toBe(200);+ expect(store.transition).toHaveBeenCalledWith(expect.objectContaining({ actorId: null }));+ });++ it('refuses a wrong ops secret', async () => {+ process.env.OPS_SECRET = 'a-high-entropy-ops-secret';+ expect((await call({ action: 'queue', method: 'GET' }, { 'x-ops-secret': 'guess' })).statusCode).toBe(403);+ });+});++describe('authorized behaviour that protects the operator from themselves', () => {+ beforeEach(() => {+ getSessionUser.mockResolvedValue({ id: 'admin-1', wallet_address: 'AdminWa11et' });+ isAdminUser.mockResolvedValue(true);+ });++ it('refuses to reach submitted through the generic mover', async () => {+ const res = await call({ action: 'transition', method: 'POST', body: { order_id: ORDER.id, to: 'submitted' } });+ expect(res.statusCode).toBe(400);+ expect(res.json.error_description).toMatch(/ops\/submit/);+ expect(store.transition).not.toHaveBeenCalled();+ });++ it('maps an illegal transition to 409 rather than a 500', async () => {+ store.transition.mockRejectedValue(new store.PrintStoreError('illegal_transition', 'a print order cannot go from paid to shipped'));+ const res = await call({ action: 'transition', method: 'POST', body: { order_id: ORDER.id, to: 'shipped' } });+ expect(res.statusCode).toBe(409);+ expect(res.json.error).toBe('illegal_transition');+ });++ it('maps a missing order to 404', async () => {+ store.getOrder.mockResolvedValue(null);+ expect((await call({ action: 'order', method: 'GET' })).statusCode).toBe(404);+ });++ it('renders the refund payout as an owner instruction and moves no money', async () => {+ store.transition.mockResolvedValue({ order: { ...ORDER, status: 'refunded' }, event: { id: 'e1' }, certificate: null });+ const res = await call({ action: 'refund', method: 'POST', body: { order_id: ORDER.id, note: 'failed QC twice' } });+ expect(res.statusCode).toBe(200);+ expect(res.json.payout).toMatchObject({+ required: true,+ executed: false,+ recipient: ORDER.payer_wallet,+ chain: 'solana',+ asset: 'USDC',+ });+ });++ it('does not mark an order canceled when the provider refuses', async () => {+ store.getOrder.mockResolvedValue({ ...ORDER, status: 'submitted', provider: 'partner-cn', provider_order_id: 'p-1' });+ cancelWithProvider.mockResolvedValue({ ok: false, note: 'already on the machine', state: {} });+ const res = await call({ action: 'cancel', method: 'POST', body: { order_id: ORDER.id } });+ expect(res.statusCode).toBe(409);+ expect(store.transition).not.toHaveBeenCalled();+ });++ it('rejects an unknown action instead of dispatching it', async () => {+ const res = mockRes();+ await handler(mockReq({ action: 'delete-everything', method: 'GET' }), res);+ expect(res.statusCode).toBe(404);+ });++ it('returns 503, not a crash, when the deployment has no database', async () => {+ queries.printStoreEnabled.mockReturnValue(false);+ expect((await call({ action: 'queue', method: 'GET' })).statusCode).toBe(503);+ });+});diff --git a/tests/print-store.test.js b/tests/print-store.test.jsnew file mode 100644index 000000000..8bcfc321c--- /dev/null+++ b/tests/print-store.test.js@@ -0,0 +1,255 @@+/**+ * The Materialize order state machine: what it lets through, what it refuses,+ * and the two things a transition is besides a column write (a timeline row,+ * and, at `shipped`, the certificate).+ *+ * The rules that matter here are the ones that cost money or trust when they+ * are wrong: a sold-out edition must be refused where the price is set rather+ * than after payment, an illegal move must throw instead of silently no-opping,+ * two writers must not both move the same order, and a certificate that cannot+ * be minted must never roll back a shipment that physically happened.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';++const db = { sql: null };+const certificate = { issue: null };+const editions = { assert: null };+const feed = { published: [] };++vi.mock('../api/_lib/db.js', () => ({+ get sql() {+ return db.sql;+ },+}));+vi.mock('../api/_lib/print/certificate.js', () => ({+ issueCertificateForOrder: (...args) => certificate.issue(...args),+}));+vi.mock('../api/_lib/print/editions.js', () => ({+ assertEditionAvailable: (...args) => editions.assert(...args),+}));+vi.mock('../api/_lib/feed.js', () => ({+ publishUserEvent: (userId, event) => feed.published.push({ userId, event }),+}));++const {+ transition,+ canTransition,+ appendEvent,+ getOrderWithEvents,+ PRINT_STATUSES,+ TERMINAL_STATUSES,+ LEGAL_TRANSITIONS,+ PrintStoreError,+} = await import('../api/_lib/print-store.js');++/**+ * A double for the two tables a transition touches. `moved` lets a test make+ * the guarded UPDATE match nothing, which is how a lost race looks.+ */+function makeSql(order, { moved = false } = {}) {+ const events = [];+ const state = { order: { ...order }, events };+ state.sql = async (strings, ...values) => {+ const text = strings.join(' ? ').replace(/\s+/g, ' ').trim();+ if (text.startsWith('select * from print_orders')) return [{ ...state.order }];+ if (text.startsWith('update print_orders set')) {+ if (moved) return [];+ state.order = { ...state.order, status: values[0] };+ return [{ ...state.order }];+ }+ if (text.startsWith('insert into print_order_events')) {+ const row = { order_id: values[0], status: values[1], note: values[2], actor: values[3], actor_id: values[4] };+ events.push(row);+ return [row];+ }+ if (text.includes('from print_order_events')) return events.map((e) => ({ ...e }));+ throw new Error(`unhandled query: ${text}`);+ };+ return state;+}++const ORDER = {+ id: '33333333-3333-4333-8333-333333333333',+ status: 'quality_check',+ user_id: '44444444-4444-4444-8444-444444444444',+ creation_id: '11111111-1111-4111-8111-111111111111',+ quantity: 1,+};++beforeEach(() => {+ feed.published = [];+ editions.assert = async () => ({ limit: null, issued: 0, remaining: null, soldOut: false });+ certificate.issue = async () => ({ certificate: { id: 'abcdef0123456789abcdef01' }, created: true, attestation: null });+});++describe('the transition table', () => {+ it('covers every status the database accepts', () => {+ expect(Object.keys(LEGAL_TRANSITIONS).sort()).toEqual([...PRINT_STATUSES].sort());+ });++ it('leaves every terminal status with nowhere to go', () => {+ for (const status of TERMINAL_STATUSES) {+ if (status === 'rejected' || status === 'canceled') continue;+ expect(LEGAL_TRANSITIONS[status]).toEqual([]);+ }+ });++ it('never lets a status transition to itself', () => {+ for (const [from, targets] of Object.entries(LEGAL_TRANSITIONS)) {+ expect(targets).not.toContain(from);+ }+ });++ it('only ever names statuses the database accepts', () => {+ for (const targets of Object.values(LEGAL_TRANSITIONS)) {+ for (const target of targets) expect(PRINT_STATUSES).toContain(target);+ }+ });++ it('walks the happy path end to end', () => {+ const path = ['created', 'quoted', 'paid', 'screening', 'submitted', 'printing', 'quality_check', 'shipped', 'delivered'];+ for (let i = 0; i < path.length - 1; i++) {+ expect(canTransition(path[i], path[i + 1])).toBe(true);+ }+ });++ it('refuses the moves that would skip money or screening', () => {+ expect(canTransition('created', 'paid')).toBe(false);+ expect(canTransition('paid', 'submitted')).toBe(false);+ expect(canTransition('quoted', 'shipped')).toBe(false);+ expect(canTransition('delivered', 'printing')).toBe(false);+ });+});++describe('transition()', () => {+ it('writes the status, appends a timeline row, and notifies the buyer', async () => {+ const state = makeSql(ORDER);+ db.sql = state.sql;+ const out = await transition({ orderId: ORDER.id, to: 'shipped', note: 'boxed', actor: 'operator', actorId: 'op-1' });+ expect(out.order.status).toBe('shipped');+ expect(state.events).toHaveLength(1);+ expect(state.events[0]).toMatchObject({ status: 'shipped', note: 'boxed', actor: 'operator', actor_id: 'op-1' });+ expect(feed.published).toHaveLength(1);+ expect(feed.published[0].event.type).toBe('print_update');+ expect(feed.published[0].event.link).toBe('/cert/abcdef0123456789abcdef01');+ });++ it('issues the certificate exactly when the order ships', async () => {+ const issued = vi.fn(async () => ({ certificate: { id: 'a'.repeat(24) }, created: true, attestation: null }));+ certificate.issue = issued;+ db.sql = makeSql({ ...ORDER, status: 'printing' }).sql;+ await transition({ orderId: ORDER.id, to: 'quality_check' });+ expect(issued).not.toHaveBeenCalled();++ db.sql = makeSql(ORDER).sql;+ await transition({ orderId: ORDER.id, to: 'shipped' });+ expect(issued).toHaveBeenCalledWith({ orderId: ORDER.id });+ });++ it('ships the order even when the certificate cannot be minted, and says so on the timeline', async () => {+ certificate.issue = async () => {+ throw new Error('solana rpc timeout after 20000ms');+ };+ const state = makeSql(ORDER);+ db.sql = state.sql;+ const out = await transition({ orderId: ORDER.id, to: 'shipped' });+ expect(out.order.status).toBe('shipped');+ expect(out.certificate).toBeNull();+ expect(state.events).toHaveLength(2);+ expect(state.events[1].note).toContain('certificate issuance deferred');+ });++ it('refuses an illegal move instead of silently doing nothing', async () => {+ db.sql = makeSql({ ...ORDER, status: 'created' }).sql;+ await expect(transition({ orderId: ORDER.id, to: 'shipped' })).rejects.toMatchObject({+ code: 'illegal_transition',+ from: 'created',+ to: 'shipped',+ });+ });++ it('refuses a status the database has never heard of', async () => {+ db.sql = makeSql(ORDER).sql;+ await expect(transition({ orderId: ORDER.id, to: 'posted' })).rejects.toMatchObject({ code: 'unknown_status' });+ });++ it('reports a lost race with what actually happened', async () => {+ db.sql = makeSql(ORDER, { moved: true }).sql;+ await expect(transition({ orderId: ORDER.id, to: 'shipped' })).rejects.toMatchObject({ code: 'transition_raced' });+ });++ it('does not notify an agent order that has no signed-in buyer', async () => {+ db.sql = makeSql({ ...ORDER, user_id: null }).sql;+ await transition({ orderId: ORDER.id, to: 'shipped' });+ expect(feed.published).toHaveLength(0);+ });+});++describe('quote-time edition enforcement', () => {+ it('checks the edition before an order is priced', async () => {+ const assertion = vi.fn(async () => ({ limit: 25, issued: 3, remaining: 22, soldOut: false }));+ editions.assert = assertion;+ db.sql = makeSql({ ...ORDER, status: 'created', quantity: 2 }).sql;+ await transition({ orderId: ORDER.id, to: 'quoted' });+ expect(assertion).toHaveBeenCalledWith({ creationId: ORDER.creation_id, quantity: 2 });+ });++ it('refuses to quote a sold-out edition, and never writes the status', async () => {+ editions.assert = async () => {+ throw Object.assign(new Error('This edition is sold out. All 5 copies have shipped.'), {+ name: 'PrintEditionError',+ code: 'edition_sold_out',+ });+ };+ const state = makeSql({ ...ORDER, status: 'created' });+ db.sql = state.sql;+ await expect(transition({ orderId: ORDER.id, to: 'quoted' })).rejects.toMatchObject({ code: 'edition_sold_out' });+ expect(state.order.status).toBe('created');+ expect(state.events).toHaveLength(0);+ });++ it('does not re-check the edition on any later transition', async () => {+ const assertion = vi.fn(async () => ({ limit: null, issued: 0, remaining: null, soldOut: false }));+ editions.assert = assertion;+ db.sql = makeSql({ ...ORDER, status: 'quoted' }).sql;+ await transition({ orderId: ORDER.id, to: 'paid' });+ expect(assertion).not.toHaveBeenCalled();+ });+});++describe('appendEvent()', () => {+ it('records an operator note without moving the order', async () => {+ const state = makeSql(ORDER);+ db.sql = state.sql;+ await appendEvent({ orderId: ORDER.id, status: 'quality_check', note: 'reprinting the base', actor: 'operator' });+ expect(state.order.status).toBe('quality_check');+ expect(state.events).toHaveLength(1);+ });++ it('falls back to the system actor rather than writing one the constraint rejects', async () => {+ const state = makeSql(ORDER);+ db.sql = state.sql;+ await appendEvent({ orderId: ORDER.id, status: 'shipped', actor: 'robot' });+ expect(state.events[0].actor).toBe('system');+ });+});++describe('getOrderWithEvents()', () => {+ it('returns the order with its timeline', async () => {+ const state = makeSql(ORDER);+ db.sql = state.sql;+ await appendEvent({ orderId: ORDER.id, status: 'shipped', note: 'first' });+ const out = await getOrderWithEvents(ORDER.id);+ expect(out.id).toBe(ORDER.id);+ expect(out.events).toHaveLength(1);+ });+});++describe('PrintStoreError', () => {+ it('carries a machine-readable code beside its message', () => {+ const err = new PrintStoreError('illegal_transition', 'nope', { from: 'a', to: 'b' });+ expect(err).toBeInstanceOf(Error);+ expect(err.code).toBe('illegal_transition');+ expect(err.from).toBe('a');+ });+});