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): serve the certificate page, the catalog, and the operator console over the fulfillment queries

nirholasd7ff1556f575
diff --git a/api/_lib/print/export-stl.js b/api/_lib/print/export-stl.js
new file mode 100644
index 000000000..ec5aea47a
--- /dev/null
+++ b/api/_lib/print/export-stl.js
@@ -0,0 +1,160 @@
+// Binary STL: the format every print bureau on earth accepts.
+//
+// STL is the lowest common denominator of manufacturing. It carries no units,
+// no color, no metadata and no vertex sharing; it is a bare list of triangles
+// with a normal each. That poverty is exactly why it is the format that always
+// works, so it is what the operator console hands a bureau and what a partner
+// adapter uploads.
+//
+// Binary only. ASCII STL is roughly five times the bytes for the same mesh and
+// loses precision in the float formatting, and every slicer written since 1990
+// reads binary. A writer that emits ASCII is offering the caller a worse file
+// for no benefit.
+//
+// Units: STL has none, and the entire industry's convention is that one STL
+// unit is one millimeter. glTF geometry arrives in meters, so it is scaled here
+// once and the exported numbers are millimeters, which is what a slicer will
+// assume when it opens the file.
+
+import { Buffer } from 'node:buffer';
+
+// Meters (glTF) to millimeters (the STL convention every slicer assumes).
+const MM_PER_METER = 1000;
+
+const HEADER_BYTES = 80;
+const COUNT_BYTES = 4;
+const TRIANGLE_BYTES = 50;
+
+export class StlExportError extends Error {
+ constructor(code, message) {
+ super(message);
+ this.name = 'StlExportError';
+ this.code = code;
+ }
+}
+
+/**
+ * Write a binary STL.
+ *
+ * @param {{positions: Float64Array|number[], indices: Uint32Array|number[]}} mesh
+ * Indexed triangles in glTF meters, as every module in this directory speaks.
+ * @param {{scale?: number, header?: string, requireWatertight?: boolean, openEdges?: number}} [opts]
+ * `scale` overrides the meter-to-millimeter conversion for a mesh already in
+ * another unit. `requireWatertight` refuses to write a mesh the caller knows
+ * still has boundary edges, so a hole cannot reach a printer as a silently
+ * accepted file.
+ * @returns {Buffer} the .stl bytes
+ */
+export function exportStl(mesh, opts = {}) {
+ const positions = mesh?.positions;
+ const indices = mesh?.indices;
+ if (!positions || !indices || indices.length < 3) {
+ throw new StlExportError('empty_mesh', 'no triangles to export');
+ }
+ if (indices.length % 3 !== 0) {
+ throw new StlExportError('bad_indices', 'index buffer is not a whole number of triangles');
+ }
+ if (opts.requireWatertight && (opts.openEdges ?? 0) > 0) {
+ throw new StlExportError(
+ 'not_watertight',
+ `mesh still has ${opts.openEdges} open edges; repair it before export`,
+ );
+ }
+
+ const scale = opts.scale ?? MM_PER_METER;
+ const triangles = indices.length / 3;
+ const out = Buffer.alloc(HEADER_BYTES + COUNT_BYTES + triangles * TRIANGLE_BYTES);
+
+ // The header must not begin with "solid": some readers sniff that prefix and
+ // then try to parse the file as ASCII. A banner naming the producer is the
+ // conventional payload and helps an operator identify a file on a bureau's
+ // intake queue.
+ const banner = (opts.header ?? 'three.ws Materialize binary STL, millimeters').slice(0, HEADER_BYTES - 1);
+ out.write(banner, 0, 'ascii');
+ out.writeUInt32LE(triangles, HEADER_BYTES);
+
+ let offset = HEADER_BYTES + COUNT_BYTES;
+ for (let t = 0; t < triangles; t += 1) {
+ const a = indices[t * 3] * 3;
+ const b = indices[t * 3 + 1] * 3;
+ const c = indices[t * 3 + 2] * 3;
+ const ax = positions[a] * scale;
+ const ay = positions[a + 1] * scale;
+ const az = positions[a + 2] * scale;
+ const bx = positions[b] * scale;
+ const by = positions[b + 1] * scale;
+ const bz = positions[b + 2] * scale;
+ const cx = positions[c] * scale;
+ const cy = positions[c + 1] * scale;
+ const cz = positions[c + 2] * scale;
+
+ // Face normal from the winding. Slicers re-derive orientation from the
+ // vertex order anyway, but a zero normal trips validators, so a
+ // degenerate triangle is written with a unit-Z placeholder rather than
+ // NaNs from a divide by zero.
+ const ux = bx - ax;
+ const uy = by - ay;
+ const uz = bz - az;
+ const vx = cx - ax;
+ const vy = cy - ay;
+ const vz = cz - az;
+ let nx = uy * vz - uz * vy;
+ let ny = uz * vx - ux * vz;
+ let nz = ux * vy - uy * vx;
+ const len = Math.hypot(nx, ny, nz);
+ if (len > 0) {
+ nx /= len;
+ ny /= len;
+ nz /= len;
+ } else {
+ nx = 0;
+ ny = 0;
+ nz = 1;
+ }
+
+ out.writeFloatLE(nx, offset);
+ out.writeFloatLE(ny, offset + 4);
+ out.writeFloatLE(nz, offset + 8);
+ out.writeFloatLE(ax, offset + 12);
+ out.writeFloatLE(ay, offset + 16);
+ out.writeFloatLE(az, offset + 20);
+ out.writeFloatLE(bx, offset + 24);
+ out.writeFloatLE(by, offset + 28);
+ out.writeFloatLE(bz, offset + 32);
+ out.writeFloatLE(cx, offset + 36);
+ out.writeFloatLE(cy, offset + 40);
+ out.writeFloatLE(cz, offset + 44);
+ // Attribute byte count. Zero is the only portable value; the color
+ // encodings some vendors hide here are mutually incompatible, and color
+ // travels in the 3MF instead.
+ out.writeUInt16LE(0, offset + 48);
+ offset += TRIANGLE_BYTES;
+ }
+
+ return out;
+}
+
+/**
+ * Read back the header and triangle count of a binary STL without parsing the
+ * whole body. The operator console and the export tests both need to confirm a
+ * stored file is the mesh they expect, and a 84-byte read answers that.
+ */
+export function readStlHeader(bytes) {
+ if (!bytes || bytes.byteLength < HEADER_BYTES + COUNT_BYTES) {
+ throw new StlExportError('truncated', 'buffer is too short to be a binary STL');
+ }
+ const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer ?? bytes, bytes.byteOffset ?? 0, bytes.byteLength);
+ const triangles = buf.readUInt32LE(HEADER_BYTES);
+ return {
+ header: buf.subarray(0, HEADER_BYTES).toString('ascii').replace(/\0+$/, ''),
+ triangles,
+ expectedBytes: HEADER_BYTES + COUNT_BYTES + triangles * TRIANGLE_BYTES,
+ actualBytes: buf.byteLength,
+ };
+}
+
+export const STL_BYTES = Object.freeze({
+ header: HEADER_BYTES,
+ count: COUNT_BYTES,
+ triangle: TRIANGLE_BYTES,
+});
diff --git a/api/_lib/print/gate.js b/api/_lib/print/gate.js
new file mode 100644
index 000000000..cf53ef4ae
--- /dev/null
+++ b/api/_lib/print/gate.js
@@ -0,0 +1,422 @@
+// The fabrication gate: the last thing between a prompt and a physical object.
+//
+// It runs twice on every order, on purpose:
+//
+// stage 'quote' cheap and synchronous, before a price is signed. No money
+// has moved, so a refusal here costs the buyer nothing and
+// costs the platform one mesh analysis. Deterministic
+// layers only (upstream verdict, denylist, geometry) so a
+// quote is never gated on a third-party model being up.
+// stage 'screening' thorough, on the paid → screening transition. Adds the
+// LLM pass over the same lineage. A refusal here moves the
+// order to `rejected`, which is the refund path, and pages
+// the operators so a human reviews the edge cases.
+//
+// Layer order is a precedence order, and the denylist always wins. An LLM that
+// says "allow" cannot un-refuse a lower receiver; that is the whole reason the
+// denylist exists as code with a test per rule (see rules.js). The LLM only
+// ever ADDS refusals, or resolves a soft rule the denylist deliberately left
+// undecided.
+//
+// What this gate does NOT claim to do is in specs/PRINT_PIPELINE.md under
+// "Gate limitations". Geometry cannot identify a weapon: blade profiles,
+// bores and receiver rails are not reliably detectable from a triangle soup,
+// and pretending otherwise would be worse than saying so. The one geometric
+// signal used here is scale, which is real: a tabletop miniature and a
+// life-size component are the same words and different objects.
+
+import { checkPromptSafety } from '../../_mcp-studio/safety.js';
+import { llmComplete } from '../llm.js';
+import { sql } from '../db.js';
+import { databaseConfigured } from '../env.js';
+import { notifyOperators } from './ops-notify.js';
+import { evaluateRules, ruleById, POLICY_URL } from './rules.js';
+
+export const GATE_VERSION = 1;
+export { POLICY_URL };
+
+// Longest bounding-box dimension, in millimetres, at or above which a
+// realistic weapon likeness stops reading as a display miniature. 120 mm is
+// generous: the tallest common tabletop scale (75 mm heroic) plus a base, and
+// well under the ~150 mm of the shortest real handgun.
+export const MINIATURE_MAX_MM = 120;
+
+const SCREENING_SYSTEM = `You review 3D models that a manufacturing service is about to physically print.
+Refuse only these categories:
+- firearm components or anything that becomes part of a working firearm
+- sound suppressors and the solvent-trap parts sold to convert into them
+- ammunition, ammunition components, magazines and feeding devices
+- working keys, lock picks, shims or other tools that defeat a real lock
+- counterfeit goods, other parties' brand marks, authentication tags, currency
+- working weapon mechanisms: concealed or spring-loaded blades, knuckles, caltrops
+- a realistic firearm likeness printed at or near life size
+
+Allow ordinary creative work: characters, creatures, props, jewellery, tools,
+enclosures, ornaments, stylised or fantasy weapons, and miniature figures that
+carry weapons at tabletop scale.
+
+Answer with one JSON object and nothing else:
+{"verdict":"allow"|"refuse","category":"<one of the ids above or null>","reason":"<one short sentence>"}`;
+
+/**
+ * Pull the prompt lineage for a creation: its own prompt plus every refine
+ * instruction and parent prompt above it. A buyer can launder an intent by
+ * refining ("make it functional") on top of an innocuous root, so the gate
+ * reads the whole chain, not the leaf.
+ *
+ * Bounded to 12 hops: lineage is a chain by construction, and a cycle
+ * introduced by a bad write must not spin a request.
+ *
+ * @returns {Promise<{ text: string, hops: number, creationIds: string[] }>}
+ */
+export async function loadLineage(creationId) {
+ if (!creationId || !databaseConfigured()) return { text: '', hops: 0, creationIds: [] };
+ const parts = [];
+ const creationIds = [];
+ let id = creationId;
+ for (let hop = 0; hop < 12 && id; hop += 1) {
+ let rows;
+ try {
+ rows = await sql`
+ select id, prompt, refine_instruction, parent_creation_id
+ from forge_creations
+ where id = ${id}
+ limit 1
+ `;
+ } catch {
+ break;
+ }
+ const row = rows?.[0];
+ if (!row || creationIds.includes(row.id)) break;
+ creationIds.push(row.id);
+ if (row.refine_instruction) parts.push(String(row.refine_instruction));
+ if (row.prompt) parts.push(String(row.prompt));
+ id = row.parent_creation_id || null;
+ }
+ return { text: parts.join('\n'), hops: creationIds.length, creationIds };
+}
+
+/**
+ * Everything the gate reads, concatenated. The order is oldest-intent-last so
+ * a truncated log still shows the buyer's own words first.
+ */
+export function gateSubject({ lineageText = '', modelTitle = '', buyerNote = '' } = {}) {
+ return [buyerNote, modelTitle, lineageText]
+ .map((s) => String(s || '').trim())
+ .filter(Boolean)
+ .join('\n');
+}
+
+/**
+ * Scale signal. Not a weapon detector: it only answers "is this object the
+ * size of a display piece or the size of a real part", which is what decides
+ * a soft rule.
+ */
+export function geometrySignal(analysis) {
+ const bbox = analysis?.bbox_mm || null;
+ const longest = bbox
+ ? Math.max(Number(bbox.x) || 0, Number(bbox.y) || 0, Number(bbox.z) || 0)
+ : null;
+ if (!longest) return { longest_mm: null, miniature: null, note: 'no bounding box available' };
+ return {
+ longest_mm: longest,
+ miniature: longest < MINIATURE_MAX_MM,
+ note: `longest dimension ${longest} mm; display-miniature threshold ${MINIATURE_MAX_MM} mm`,
+ };
+}
+
+function refusal({ category, label, message, allowed, layer, matched = null }) {
+ return {
+ verdict: 'refuse',
+ category,
+ label,
+ layer,
+ matched,
+ message,
+ allowed,
+ policy_url: POLICY_URL,
+ };
+}
+
+/**
+ * The deterministic layers: the upstream generation verdict, the fabrication
+ * denylist, and the scale signal. No network, no model, no database. This is
+ * what runs at quote time and what runs first at screening time.
+ *
+ * @param {{ subject: string, analysis?: object }} input
+ */
+export function screenDeterministic({ subject, analysis = null }) {
+ const geometry = geometrySignal(analysis);
+
+ // Layer 1: whatever the generation gate would have refused, fabrication
+ // refuses too. A mesh that should never have been generated must never be
+ // manufactured, including one generated before that gate covered its terms.
+ const upstream = checkPromptSafety(subject);
+ if (!upstream.allowed) {
+ return {
+ decision: refusal({
+ category: `generation_${upstream.category}`,
+ label: 'generation content policy',
+ layer: 'upstream',
+ matched: upstream.matched || null,
+ message: upstream.message,
+ allowed: 'Describe a character, creature, prop or object without that theme and generate it again.',
+ }),
+ layers: {
+ upstream: { verdict: 'refuse', category: upstream.category, matched: upstream.matched || null },
+ denylist: { verdict: 'skipped' },
+ geometry,
+ },
+ };
+ }
+
+ // Layer 2: the fabrication denylist. Hard rules refuse outright.
+ const rules = evaluateRules(subject);
+ if (rules.hard) {
+ return {
+ decision: refusal({
+ category: rules.hard.id,
+ label: rules.hard.label,
+ layer: 'denylist',
+ matched: rules.matched,
+ message: rules.hard.message,
+ allowed: rules.hard.allowed,
+ }),
+ layers: {
+ upstream: { verdict: 'allow' },
+ denylist: { verdict: 'refuse', rule: rules.hard.id, matched: rules.matched },
+ geometry,
+ },
+ };
+ }
+
+ // A soft rule plus life-size geometry is the one case the deterministic
+ // layers decide on their own: the words describe a firearm and the object is
+ // the size of one. Below the miniature threshold it stays undecided and the
+ // LLM layer resolves it at screening time.
+ const soft = rules.soft.map((s) => ({ rule: s.rule.id, matched: s.matched }));
+ if (rules.soft.length > 0 && geometry.miniature === false) {
+ const first = rules.soft[0].rule;
+ return {
+ decision: refusal({
+ category: first.id,
+ label: first.label,
+ layer: 'denylist',
+ matched: rules.soft[0].matched,
+ message: `${first.message} This model is ${geometry.longest_mm} mm at its longest, which is life size rather than display scale.`,
+ allowed: `${first.allowed} Printing this design at under ${MINIATURE_MAX_MM} mm is allowed.`,
+ }),
+ layers: {
+ upstream: { verdict: 'allow' },
+ denylist: { verdict: 'refuse', rule: first.id, matched: rules.soft[0].matched, soft: true },
+ geometry,
+ },
+ };
+ }
+
+ return {
+ decision: { verdict: 'allow', category: null, layer: null, message: null },
+ layers: {
+ upstream: { verdict: 'allow' },
+ denylist: { verdict: soft.length ? 'undecided' : 'allow', soft },
+ geometry,
+ },
+ };
+}
+
+/** Pull the first JSON object out of a model's answer, tolerating prose and fences. */
+function parseVerdict(text) {
+ const raw = String(text || '');
+ const start = raw.indexOf('{');
+ const end = raw.lastIndexOf('}');
+ if (start < 0 || end <= start) return null;
+ try {
+ const parsed = JSON.parse(raw.slice(start, end + 1));
+ if (!parsed || typeof parsed !== 'object') return null;
+ const verdict = parsed.verdict === 'refuse' ? 'refuse' : parsed.verdict === 'allow' ? 'allow' : null;
+ if (!verdict) return null;
+ return {
+ verdict,
+ category: typeof parsed.category === 'string' && parsed.category ? parsed.category : null,
+ reason: typeof parsed.reason === 'string' ? parsed.reason.slice(0, 400) : '',
+ };
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The LLM layer. Runs only at screening time, only when the deterministic
+ * layers did not already refuse, and only ever tightens the verdict.
+ *
+ * Its failure mode is designed rather than defaulted: when no provider answers,
+ * the order does not silently pass and does not auto-reject either. It returns
+ * `review`, which parks the order for an operator. Auto-rejecting a paid order
+ * because a third-party model was down would refund a legitimate buyer and lose
+ * the sale; auto-passing would make the layer decorative.
+ */
+export async function screenWithLlm({ subject, geometry, softRules = [], timeoutMs = 20_000 }) {
+ const context = [
+ `Request text:\n${subject.slice(0, 4000)}`,
+ geometry.longest_mm
+ ? `Printed size: ${geometry.longest_mm} mm at its longest dimension.`
+ : 'Printed size: unknown.',
+ softRules.length
+ ? `Automated pre-screen flagged, without deciding: ${softRules.map((s) => s.rule).join(', ')}.`
+ : '',
+ ]
+ .filter(Boolean)
+ .join('\n\n');
+
+ let completion;
+ try {
+ completion = await llmComplete({
+ system: SCREENING_SYSTEM,
+ user: context,
+ maxTokens: 200,
+ timeoutMs,
+ track: { tool: 'print-fabrication-screening' },
+ });
+ } catch (err) {
+ return { verdict: 'review', reason: `screening model unavailable: ${err?.message || err}`, provider: null, model: null };
+ }
+
+ const parsed = parseVerdict(completion?.text);
+ if (!parsed) {
+ return {
+ verdict: 'review',
+ reason: 'screening model returned an unreadable verdict',
+ provider: completion?.provider ?? null,
+ model: completion?.model ?? null,
+ };
+ }
+ return { ...parsed, provider: completion?.provider ?? null, model: completion?.model ?? null };
+}
+
+/**
+ * Run the gate.
+ *
+ * @param {object} input
+ * @param {'quote'|'screening'} input.stage
+ * @param {string} [input.lineageText] prompt lineage, from loadLineage()
+ * @param {string} [input.modelTitle]
+ * @param {string} [input.buyerNote]
+ * @param {object} [input.analysis] the printability report
+ * @param {boolean} [input.useLlm] override; defaults to true at screening stage
+ * @returns {Promise<object>} the verdict, stored verbatim on the order's
+ * `analysis.screening` and rendered by the refusal UI.
+ */
+export async function runFabricationGate({
+ stage = 'quote',
+ lineageText = '',
+ modelTitle = '',
+ buyerNote = '',
+ analysis = null,
+ useLlm,
+}) {
+ const subject = gateSubject({ lineageText, modelTitle, buyerNote });
+ const deterministic = screenDeterministic({ subject, analysis });
+ const base = {
+ version: GATE_VERSION,
+ stage,
+ policy_url: POLICY_URL,
+ checked_at: new Date().toISOString(),
+ };
+
+ if (deterministic.decision.verdict === 'refuse') {
+ return {
+ ...base,
+ verdict: 'refuse',
+ category: deterministic.decision.category,
+ label: deterministic.decision.label,
+ layer: deterministic.decision.layer,
+ matched: deterministic.decision.matched,
+ message: deterministic.decision.message,
+ allowed: deterministic.decision.allowed,
+ layers: { ...deterministic.layers, llm: { verdict: 'skipped', reason: 'refused before the model layer' } },
+ };
+ }
+
+ const runLlm = useLlm ?? stage === 'screening';
+ if (!runLlm) {
+ return {
+ ...base,
+ verdict: 'allow',
+ category: null,
+ message: null,
+ layers: { ...deterministic.layers, llm: { verdict: 'skipped', reason: 'deterministic layers only at quote time' } },
+ };
+ }
+
+ const llm = await screenWithLlm({
+ subject,
+ geometry: deterministic.layers.geometry,
+ softRules: deterministic.layers.denylist.soft || [],
+ });
+
+ if (llm.verdict === 'refuse') {
+ // The model may name a category the denylist knows; when it does, the
+ // buyer gets that rule's written message and its "what is allowed"
+ // sentence rather than raw model prose.
+ const known = ruleById(llm.category);
+ return {
+ ...base,
+ verdict: 'refuse',
+ category: llm.category || 'fabrication_policy',
+ label: known?.label || 'fabrication content policy',
+ layer: 'llm',
+ matched: null,
+ message: known?.message || 'This model cannot be manufactured under the three.ws fabrication policy.',
+ allowed: known?.allowed || 'Ordinary characters, creatures, props, ornaments and functional parts are all welcome.',
+ reason: llm.reason,
+ layers: { ...deterministic.layers, llm },
+ };
+ }
+
+ if (llm.verdict === 'review') {
+ return {
+ ...base,
+ verdict: 'review',
+ category: null,
+ label: 'awaiting operator review',
+ layer: 'llm',
+ message: 'This order is held for a quick human review before it goes to the printer. Nothing further is needed from you.',
+ allowed: null,
+ layers: { ...deterministic.layers, llm },
+ };
+ }
+
+ return {
+ ...base,
+ verdict: 'allow',
+ category: null,
+ message: null,
+ layers: { ...deterministic.layers, llm },
+ };
+}
+
+/**
+ * The ops-channel side effect. Every refusal and every held order is announced
+ * on the same channel a stalled job uses, because both need the same thing: a
+ * human looking at an edge case within the hour.
+ *
+ * Fire-and-forget by contract, exactly like the fulfillment notifications: a
+ * refusal must still be recorded on the order when the chat is unreachable.
+ */
+export async function notifyGateOutcome({ orderId = '', verdict, stage }) {
+ if (!verdict || (verdict.verdict !== 'refuse' && verdict.verdict !== 'review')) return;
+ const held = verdict.verdict === 'review';
+ await notifyOperators({
+ title: held
+ ? `Print order held for review (${stage})`
+ : `Print order refused by the fabrication gate (${stage})`,
+ lines: [
+ `Category: ${verdict.label || verdict.category || 'unclassified'}`,
+ verdict.layer ? `Decided by: ${verdict.layer} layer` : '',
+ verdict.matched ? `Matched: ${verdict.matched}` : '',
+ verdict.reason ? `Model reason: ${verdict.reason}` : '',
+ ].filter(Boolean),
+ orderId,
+ alert: held,
+ }).catch(() => {});
+}
diff --git a/api/cron/print-orders-sync.js b/api/cron/print-orders-sync.js
index 8f85065c4..c6fb1fe16 100644
--- a/api/cron/print-orders-sync.js
+++ b/api/cron/print-orders-sync.js
@@ -1,38 +1,114 @@
-// GET /api/cron/print-orders-sync — the Materialize reconciliation sweep.
+// @ts-check
+// GET /api/cron/print-orders-sync — reconcile live print jobs and surface
+// stalls.
//
-// One cron owns everything that has to be reconciled after a print order leaves
-// the request path, so the print lane never grows a second scheduler.
+// Webhooks are the fast path and they are not enough on their own. A delivery
+// gets lost, a partner's callback queue backs up, a lane has no webhook at all
+// (the manual one does not, by design). Without a sweep the failure mode is the
+// worst one a physical product has: an order that is genuinely finished sits in
+// `printing` forever and nobody finds out until the buyer asks.
//
-// Lane in place today: certificate attestation. Issuing a certificate is
-// deliberately fail-soft (a shipment is a physical fact and is never rolled
-// back because Solana had a bad minute), so a certificate can exist with its
-// memo unsent. This sweep finds those, backfills any missing QR, and retries
-// the send, oldest first, with a bounded attempt count so a permanently
-// unsendable certificate stops burning RPC calls and stays visible in ops
-// instead.
+// Two passes, deliberately separate:
//
-// Mainnet certificates whose owner approval is not yet recorded come back as
-// `refused` rather than `failed`: nothing is wrong with them, they are waiting
-// on a person. See api/_lib/print/certificate.js.
+// 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
+// state machine. An adapter with no news returns null and nothing moves,
+// so this is safe to run often. The manual lane answers null by
+// construction (the operator console is already its source of truth), so
+// hand-run jobs cost one database read and never a spurious transition.
+// 2. STALL. For every order past its own recorded lead time plus a grace
+// margin, page the operator channel once and stamp stall_alerted_at so the
+// 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.
+//
+// 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.
-import { cors, json, method, wrapCron } from '../_lib/http.js';
+import { error, json, method, wrapCron } from '../_lib/http.js';
import { requireCron } from '../_lib/cron-auth.js';
-import { retryPendingAttestations, certCluster } from '../_lib/print/certificate.js';
-
-export const maxDuration = 120;
+import {
+ listOpenProviderOrders,
+ listStalledOrders,
+ markStallAlerted,
+ printStoreEnabled,
+} from '../_lib/print/fulfillment-queries.js';
+import { reconcileOrder } from '../_lib/print/fulfillment.js';
+import { jobSummaryLines, notifyOperators } from '../_lib/print/ops-notify.js';
-const BATCH_LIMIT = Number(process.env.PRINT_CERT_RETRY_BATCH) || 10;
-const MAX_ATTEMPTS = Number(process.env.PRINT_CERT_MAX_ATTEMPTS) || 8;
+// 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.
+const STALL_GRACE_DAYS = 2;
+// One page per stalled order per day. Enough to stay on an operator's radar,
+// infrequent enough that a known-slow job does not train them to ignore it.
+const STALL_REALERT_HOURS = 24;
+const RECONCILE_BATCH = 100;
+const STALL_BATCH = 25;
export default wrapCron(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
if (!method(req, res, ['GET'])) return;
if (!requireCron(req, res)) return;
+ if (!printStoreEnabled()) {
+ return error(res, 503, 'not_configured', 'the fulfillment sweep needs a configured database');
+ }
+
+ const open = await listOpenProviderOrders({ limit: RECONCILE_BATCH });
+ let polled = 0;
+ let applied = 0;
+ /** @type {Array<{ order_id: string, error: string }>} */
+ const failures = [];
+
+ for (const order of open) {
+ try {
+ const result = await reconcileOrder(order);
+ if (result.polled) polled += 1;
+ if (result.applied) applied += 1;
+ } catch (err) {
+ // One unreachable partner must not stop the sweep: the stall pass below
+ // is exactly what catches the orders that partner is sitting on.
+ failures.push({ order_id: order.id, error: String(err?.message || err).slice(0, 300) });
+ }
+ }
- const certificates = await retryPendingAttestations({
- limit: BATCH_LIMIT,
- maxAttempts: MAX_ATTEMPTS,
+ const stalled = await listStalledOrders({
+ graceDays: STALL_GRACE_DAYS,
+ realertHours: STALL_REALERT_HOURS,
+ limit: STALL_BATCH,
});
- return json(res, 200, { ok: true, cluster: certCluster(), certificates });
+ for (const order of stalled) {
+ const lateBy = daysSince(order.submitted_at) - (Number(order.lead_time_days) || 0);
+ await notifyOperators({
+ title: `Print job stalled: ${Math.max(Math.round(lateBy), 0)} days past its lead time`,
+ lines: [
+ ...jobSummaryLines(order),
+ `Status ${order.status} with ${order.provider || 'no lane'} since ${formatDay(order.submitted_at)}`,
+ ],
+ orderId: order.id,
+ alert: true,
+ });
+ }
+ const alerted = await markStallAlerted(stalled.map((o) => o.id));
+
+ return json(res, 200, {
+ ok: true,
+ open: open.length,
+ polled,
+ applied,
+ stalled: stalled.length,
+ alerted,
+ failures,
+ });
});
+
+/** @param {string|Date|null} at */
+function daysSince(at) {
+ if (!at) return 0;
+ return (Date.now() - new Date(at).getTime()) / 86_400_000;
+}
+
+/** @param {string|Date|null} at */
+function formatDay(at) {
+ if (!at) return 'an unknown date';
+ return new Date(at).toISOString().slice(0, 10);
+}
diff --git a/api/print/catalog.js b/api/print/catalog.js
new file mode 100644
index 000000000..c22b44a6e
--- /dev/null
+++ b/api/print/catalog.js
@@ -0,0 +1,44 @@
+// GET /api/print/catalog — the Materialize price list, as data.
+//
+// Everything a buyer or an agent needs to build a valid quote request: the
+// materials with their real constraints (minimum wall, build volume, lead time),
+// the finishes and what they add, the size presets and the real-world scale
+// references the /materialize slider measures against, and the shipping zones.
+//
+// Free and keyless like the rest of the 3D API surface. An agent can read this,
+// pick a material its mesh actually fits, and call /api/print/quote without ever
+// guessing. Owner-only fields (the declared margin, the sourcing citations behind
+// each rate) are stripped here, so the file on disk stays the single source of
+// truth without leaking how it was tuned.
+//
+// Prices are quoted and settled in USDC on Solana. There is no card processor,
+// and the copy says so rather than apologising for it.
+
+import { cors, json, method, wrap } from '../_lib/http.js';
+import { publicCatalog } from '../_lib/print/quote.js';
+
+// The catalog is a checked-in file, not a query. A long public cache is correct
+// and the deploy that changes a price is what invalidates it.
+const CACHE_CONTROL = 'public, max-age=300, s-maxage=900, stale-while-revalidate=86400';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const catalog = publicCatalog();
+ return json(
+ res,
+ 200,
+ {
+ version: catalog.version,
+ currency: catalog.currency,
+ chain: catalog.chain,
+ pricing: catalog.pricing,
+ materials: catalog.materials,
+ sizePresets: catalog.sizePresets,
+ scaleReferences: catalog.scaleReferences,
+ shipping: catalog.shipping,
+ },
+ { 'cache-control': CACHE_CONTROL },
+ );
+});
diff --git a/api/print/ops/[action].js b/api/print/ops/[action].js
index 36b2a7753..87c45f806 100644
--- a/api/print/ops/[action].js
+++ b/api/print/ops/[action].js
@@ -20,19 +20,14 @@
import { error, json, method, readJson, wrap } from '../../_lib/http.js';
import { sql } from '../../_lib/db.js';
import { requireOperator } from '../../_lib/print/ops-auth.js';
+import { PrintStoreError, appendEvent, getOrder, getOrderWithEvents, transition } from '../../_lib/print-store.js';
import {
- PrintOrderNotFoundError,
- PrintTransitionError,
allowedTransitions,
- appendOrderEvent,
countOrdersByStatus,
- getOrder,
- listOrderEvents,
listOrders,
listWebhookDeliveries,
printStoreEnabled,
- transitionOrder,
-} from '../../_lib/print-store.js';
+} from '../../_lib/print/fulfillment-queries.js';
import { adapterSummaries } from '../../_lib/print/adapters/index.js';
import { FulfillmentError, cancelWithProvider, submitOrder } from '../../_lib/print/fulfillment.js';
import { AdapterContractError, AdapterUpstreamError } from '../../_lib/print/adapters/contract.js';
@@ -117,15 +112,13 @@ function queueRow(order) {
async function handleOrderDetail(req, res) {
const order = await loadOrder(req, res);
if (!order) return;
- const [events, deliveries] = await Promise.all([
- listOrderEvents(order.id),
+ const [withEvents, deliveries] = await Promise.all([
+ getOrderWithEvents(order.id),
listWebhookDeliveries(order.id),
]);
+ const { events, ...row } = withEvents || { ...order, events: [] };
return json(res, 200, {
- order: {
- ...order,
- next: allowedTransitions(order.status),
- },
+ order: { ...row, next: allowedTransitions(row.status) },
events,
webhook_deliveries: deliveries,
adapters: adapterSummaries(),
@@ -153,7 +146,7 @@ async function handleTransition(req, res, operator) {
return error(res, 400, 'validation_error', 'use /api/print/ops/submit to hand an order to a fulfillment lane');
}
- const { order: updated, event } = await transitionOrder({
+ const { order: updated, event } = await transition({
orderId: order.id,
to,
note: note || `Operator moved the order to ${to}.`,
@@ -205,7 +198,7 @@ async function handleTracking(req, res, operator) {
: `Tracking ${trackingNumber}${carrier ? ` via ${carrier}` : ''}.`;
if (ship) {
- const { order: updated, event } = await transitionOrder({
+ const { order: updated, event } = await transition({
orderId: order.id,
to: 'shipped',
note,
@@ -220,7 +213,7 @@ async function handleTracking(req, res, operator) {
const rows = await sql`
update print_orders set tracking_number = ${trackingNumber}, carrier = ${carrier || null}
where id = ${order.id} returning *`;
- const event = await appendOrderEvent({
+ const event = await appendEvent({
orderId: order.id,
status: order.status,
note,
@@ -247,7 +240,7 @@ async function handleCancel(req, res, operator) {
if (order.provider && order.provider_order_id) {
const result = await cancelWithProvider(order, reason);
if (!result.ok) {
- await appendOrderEvent({
+ await appendEvent({
orderId: order.id,
status: order.status,
note: `Cancellation refused by ${order.provider}: ${result.note}`,
@@ -259,7 +252,7 @@ async function handleCancel(req, res, operator) {
providerNote = result.note;
}
- const { order: updated, event } = await transitionOrder({
+ const { order: updated, event } = await transition({
orderId: order.id,
to: 'canceled',
note: reason ? `Canceled: ${reason}. ${providerNote}` : `Canceled by operator. ${providerNote}`,
@@ -283,7 +276,7 @@ async function handleRefund(req, res, operator) {
const note = typeof body.note === 'string' ? body.note.slice(0, 2000) : '';
const recipient = order.payer_wallet || null;
- const { order: updated, event } = await transitionOrder({
+ const { order: updated, event } = await transition({
orderId: order.id,
to: 'refunded',
note: note || 'Refund approved by operator.',
@@ -352,8 +345,10 @@ export default wrap(async (req, res) => {
try {
return await route.fn(req, res, operator);
} catch (err) {
- if (err instanceof PrintOrderNotFoundError) return error(res, 404, 'not_found', err.message);
- if (err instanceof PrintTransitionError) return error(res, 409, 'illegal_transition', err.message);
+ if (err instanceof PrintStoreError) {
+ const status = err.code === 'order_not_found' ? 404 : 409;
+ return error(res, status, err.code, err.message);
+ }
if (err instanceof FulfillmentError) return error(res, 409, err.code, err.message);
if (err instanceof AdapterUpstreamError) return error(res, 502, 'provider_unreachable', err.message);
if (err instanceof AdapterContractError) return error(res, 502, 'provider_contract', err.message);
diff --git a/api/print/webhook/[provider].js b/api/print/webhook/[provider].js
index 3fe7256fd..e7a8c9465 100644
--- a/api/print/webhook/[provider].js
+++ b/api/print/webhook/[provider].js
@@ -26,7 +26,7 @@ import {
getOrderByProviderId,
markWebhookApplied,
printStoreEnabled,
-} from '../../_lib/print-store.js';
+} from '../../_lib/print/fulfillment-queries.js';
import { getAdapter } from '../../_lib/print/adapters/index.js';
import { normalizeWebhookEvent } from '../../_lib/print/adapters/contract.js';
import { applyProviderEvent } from '../../_lib/print/fulfillment.js';
diff --git a/pages/certificate.html b/pages/certificate.html
new file mode 100644
index 000000000..65e372296
--- /dev/null
+++ b/pages/certificate.html
@@ -0,0 +1,66 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot, no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Certificate of Authenticity · three.ws</title>
+ <meta
+ name="description"
+ content="The provenance record for a three.ws physical print: the spinning original, its edition number, the SHA-256 of the exact bytes that were printed, and the Solana transaction attesting both."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="Certificate of Authenticity · three.ws" />
+ <meta
+ property="og:description"
+ content="The provenance record for a three.ws physical print: the spinning original, its edition number, the SHA-256 of the exact bytes that were printed, and the Solana transaction attesting both."
+ />
+ <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/certificate.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <script defer src="/footer-newsletter.js"></script>
+ <script src="/model-viewer-meshopt.js"></script>
+ <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js" integrity="sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw" crossorigin="anonymous"></script>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="ct-shell" id="ct-root" aria-busy="true">
+ <!-- Hydrated by /src/certificate-page.js from /api/print/certs/:id.
+ The skeleton is real markup rather than a spinner so the page holds
+ its final shape while a scanned QR loads on a phone network. -->
+ <div id="ct-skeleton">
+ <div class="ct-skeleton ct-skeleton--stage"></div>
+ <div class="ct-skeleton ct-skeleton--copy"></div>
+ </div>
+ <noscript>
+ <h1 class="ct-title">Certificate of Authenticity</h1>
+ <p class="ct-sub">
+ This page renders the provenance record for a three.ws physical print: the original
+ 3D model, its edition number, the SHA-256 of the printed bytes, and the Solana
+ transaction attesting them. Enable JavaScript to read it.
+ </p>
+ <a class="ct-btn ct-btn--primary" href="/materialize">About Materialize</a>
+ </noscript>
+ </main>
+
+ <div id="ct-live" class="ct-sr-only" role="status" aria-live="polite"></div>
+
+ <script type="module" src="/src/certificate-page.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module" src="/i18n.js"></script>
+ </body>
+</html>
diff --git a/src/certificate.css b/src/certificate.css
new file mode 100644
index 000000000..4e607140e
--- /dev/null
+++ b/src/certificate.css
@@ -0,0 +1,363 @@
+/* Materialize certificate of authenticity (/cert, /cert/:id).
+ Every value comes from public/tokens.css; the sheet holds no literal a token
+ already expresses. The proof block is deliberately monospace and selectable:
+ its whole job is to be copied out and hashed against by a stranger. */
+
+.ct-shell {
+ max-width: 1080px;
+ margin: 0 auto;
+ padding: var(--space-xl, 32px) var(--space-lg, 24px) var(--space-3xl, 96px);
+}
+
+.ct-sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+ white-space: nowrap;
+ border: 0;
+}
+
+.ct-back {
+ display: inline-block;
+ margin-bottom: var(--space-md, 16px);
+ font-size: var(--text-sm, 13px);
+ color: var(--ink-dim, rgba(255, 255, 255, 0.55));
+ text-decoration: none;
+ transition: color 0.15s ease;
+}
+.ct-back:hover,
+.ct-back:focus-visible {
+ color: var(--ink-bright, #fff);
+}
+
+/* ── header ───────────────────────────────────────────────────────────── */
+
+.ct-kicker {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2, 8px);
+ margin: 0 0 var(--space-sm, 12px);
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs, 11px);
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+ color: var(--ink-dim, rgba(255, 255, 255, 0.55));
+}
+
+.ct-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: var(--radius-pill, 999px);
+ background: var(--success, #4ade80);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--success, #4ade80) 22%, transparent);
+}
+.ct-dot--pending {
+ background: var(--warn, #fbbf24);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--warn, #fbbf24) 22%, transparent);
+}
+
+.ct-title {
+ margin: 0 0 var(--space-xs, 6px);
+ font-family: var(--font-display);
+ font-size: var(--text-2xl, 42px);
+ line-height: var(--leading-tight, 1.15);
+ letter-spacing: -0.02em;
+ font-weight: var(--weight-bold, 700);
+ color: var(--ink-bright, #fff);
+}
+
+.ct-sub {
+ margin: 0 0 var(--space-lg, 24px);
+ color: var(--ink-dim, rgba(255, 255, 255, 0.62));
+ font-size: var(--text-md, 15px);
+ max-width: 62ch;
+}
+
+/* ── layout ───────────────────────────────────────────────────────────── */
+
+.ct-grid {
+ display: grid;
+ grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr);
+ gap: var(--space-xl, 32px);
+ align-items: start;
+}
+
+@media (max-width: 900px) {
+ .ct-grid {
+ grid-template-columns: minmax(0, 1fr);
+ }
+}
+
+.ct-card {
+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
+ border-radius: var(--radius-lg, 16px);
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ padding: var(--space-lg, 24px);
+ margin-bottom: var(--space-lg, 24px);
+}
+
+.ct-card h2 {
+ margin: 0 0 var(--space-md, 16px);
+ font-size: var(--text-xs, 12px);
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+ font-family: var(--font-mono);
+ color: var(--ink-dim, rgba(255, 255, 255, 0.55));
+ font-weight: var(--weight-medium, 500);
+}
+
+/* ── viewer ───────────────────────────────────────────────────────────── */
+
+.ct-stage {
+ position: relative;
+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
+ border-radius: var(--radius-lg, 16px);
+ overflow: hidden;
+ background: var(--surface-2, rgba(255, 255, 255, 0.05));
+ aspect-ratio: 4 / 3;
+}
+
+.ct-stage model-viewer,
+.ct-stage img {
+ width: 100%;
+ height: 100%;
+ display: block;
+ object-fit: cover;
+ --poster-color: transparent;
+}
+
+.ct-stage-empty {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ height: 100%;
+ padding: var(--space-lg, 24px);
+ text-align: center;
+ color: var(--ink-dim, rgba(255, 255, 255, 0.55));
+ font-size: var(--text-sm, 13px);
+}
+
+.ct-edition {
+ position: absolute;
+ top: var(--space-sm, 12px);
+ left: var(--space-sm, 12px);
+ display: inline-flex;
+ align-items: baseline;
+ gap: 6px;
+ padding: 6px 12px;
+ border-radius: var(--radius-pill, 999px);
+ background: color-mix(in srgb, var(--bg, #0a0a0a) 78%, transparent);
+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.14));
+ backdrop-filter: blur(8px);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs, 12px);
+ color: var(--ink-bright, #fff);
+ letter-spacing: 0.02em;
+}
+.ct-edition strong {
+ font-size: var(--text-md, 15px);
+ font-weight: var(--weight-bold, 700);
+}
+
+/* ── facts ────────────────────────────────────────────────────────────── */
+
+.ct-facts {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
+ gap: var(--space-md, 16px);
+}
+
+.ct-fact dt {
+ margin: 0 0 4px;
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs, 11px);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--ink-dim, rgba(255, 255, 255, 0.5));
+}
+
+.ct-fact dd {
+ margin: 0;
+ color: var(--ink, rgba(255, 255, 255, 0.88));
+ font-size: var(--text-md, 15px);
+ overflow-wrap: anywhere;
+}
+
+/* ── proof ────────────────────────────────────────────────────────────── */
+
+.ct-proof-state {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2, 8px);
+ margin-bottom: var(--space-md, 16px);
+ font-size: var(--text-sm, 13px);
+ color: var(--ink, rgba(255, 255, 255, 0.88));
+}
+
+.ct-code {
+ display: block;
+ margin: 0 0 var(--space-sm, 12px);
+ padding: var(--space-sm, 12px);
+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
+ border-radius: var(--radius-md, 10px);
+ background: var(--surface-2, rgba(255, 255, 255, 0.05));
+ font-family: var(--font-mono);
+ font-size: var(--text-xs, 12px);
+ line-height: 1.6;
+ color: var(--ink, rgba(255, 255, 255, 0.88));
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ user-select: all;
+}
+
+.ct-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2, 8px);
+}
+
+.ct-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 9px 14px;
+ border-radius: var(--radius-pill, 999px);
+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.14));
+ background: transparent;
+ color: var(--ink, rgba(255, 255, 255, 0.88));
+ font: inherit;
+ font-size: var(--text-sm, 13px);
+ cursor: pointer;
+ text-decoration: none;
+ transition:
+ background 0.15s ease,
+ border-color 0.15s ease,
+ transform 0.1s ease;
+}
+.ct-btn:hover {
+ background: var(--surface-2, rgba(255, 255, 255, 0.06));
+ border-color: var(--stroke-strong, rgba(255, 255, 255, 0.24));
+}
+.ct-btn:active {
+ transform: translateY(1px);
+}
+.ct-btn:focus-visible {
+ outline: 2px solid var(--accent, #7c9cff);
+ outline-offset: 2px;
+}
+.ct-btn--primary {
+ background: var(--ink-bright, #fff);
+ color: var(--bg, #0a0a0a);
+ border-color: transparent;
+ font-weight: var(--weight-medium, 500);
+}
+.ct-btn--primary:hover {
+ background: var(--ink, rgba(255, 255, 255, 0.88));
+}
+
+.ct-steps {
+ margin: 0;
+ padding-left: 1.2em;
+ color: var(--ink-dim, rgba(255, 255, 255, 0.62));
+ font-size: var(--text-sm, 13px);
+ line-height: 1.7;
+}
+.ct-steps li + li {
+ margin-top: var(--space-2, 8px);
+}
+.ct-steps code {
+ font-family: var(--font-mono);
+ font-size: var(--text-xs, 12px);
+ padding: 1px 5px;
+ border-radius: var(--radius-sm, 6px);
+ background: var(--surface-2, rgba(255, 255, 255, 0.06));
+ overflow-wrap: anywhere;
+}
+
+.ct-qr {
+ display: block;
+ width: 132px;
+ height: 132px;
+ border-radius: var(--radius-md, 10px);
+ background: #fff;
+ padding: 8px;
+}
+
+.ct-note {
+ margin: var(--space-sm, 12px) 0 0;
+ font-size: var(--text-xs, 12px);
+ color: var(--ink-dim, rgba(255, 255, 255, 0.5));
+ line-height: 1.6;
+}
+
+/* ── lookup, empty, error ─────────────────────────────────────────────── */
+
+.ct-lookup {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2, 8px);
+ margin-top: var(--space-md, 16px);
+}
+
+.ct-input {
+ flex: 1 1 240px;
+ min-width: 0;
+ padding: 10px 14px;
+ border-radius: var(--radius-pill, 999px);
+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.14));
+ background: var(--surface-2, rgba(255, 255, 255, 0.05));
+ color: var(--ink-bright, #fff);
+ font-family: var(--font-mono);
+ font-size: var(--text-sm, 13px);
+}
+.ct-input:focus-visible {
+ outline: 2px solid var(--accent, #7c9cff);
+ outline-offset: 1px;
+}
+
+.ct-message {
+ margin: var(--space-sm, 12px) 0 0;
+ font-size: var(--text-sm, 13px);
+ color: var(--danger, #f87171);
+ min-height: 1.2em;
+}
+
+/* ── skeleton ─────────────────────────────────────────────────────────── */
+
+.ct-skeleton {
+ border-radius: var(--radius-lg, 16px);
+ background: linear-gradient(
+ 90deg,
+ var(--surface-1, rgba(255, 255, 255, 0.04)) 25%,
+ var(--surface-2, rgba(255, 255, 255, 0.08)) 37%,
+ var(--surface-1, rgba(255, 255, 255, 0.04)) 63%
+ );
+ background-size: 400% 100%;
+ animation: ct-shimmer 1.4s ease infinite;
+}
+.ct-skeleton--stage {
+ aspect-ratio: 4 / 3;
+}
+.ct-skeleton--copy {
+ height: 220px;
+ margin-top: var(--space-lg, 24px);
+}
+
+@keyframes ct-shimmer {
+ 0% {
+ background-position: 100% 50%;
+ }
+ 100% {
+ background-position: 0 50%;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .ct-skeleton {
+ animation: none;
+ }
+}
diff --git a/vercel.json b/vercel.json
index b555663df..bdcc80f76 100644
--- a/vercel.json
+++ b/vercel.json
@@ -2020,6 +2020,22 @@
"src": "/constellation/",
"dest": "/constellation.html"
},
+ {
+ "src": "/cert/?",
+ "dest": "/certificate.html"
+ },
+ {
+ "src": "/cert/([0-9a-f]{24})/?",
+ "dest": "/certificate.html"
+ },
+ {
+ "src": "/materialize/ops/?",
+ "dest": "/materialize-ops.html"
+ },
+ {
+ "src": "/materialize/insert/([0-9a-f]{24})/?",
+ "dest": "/print-insert.html"
+ },
{
"src": "/p/([a-z0-9-]+)/?",
"dest": "/p/index.html"
@@ -3340,6 +3356,14 @@
"src": "/api/social/sentiment-pulse",
"dest": "/api/social/sentiment-pulse.js"
},
+ {
+ "src": "/api/print/ops/(queue|order|adapters|transition|submit|tracking|cancel|refund)",
+ "dest": "/api/print/ops/[action]?action=$1"
+ },
+ {
+ "src": "/api/print/webhook/([a-z][a-z0-9-]{1,31})",
+ "dest": "/api/print/webhook/[provider]?provider=$1"
+ },
{
"src": "/api/irl/drops/([^/]+)/([^/]+)",
"dest": "/api/irl/drops.js"
@@ -6300,6 +6324,10 @@
{
"path": "/api/cron/feedback-triage",
"schedule": "*/5 * * * *"
+ },
+ {
+ "path": "/api/cron/print-orders-sync",
+ "schedule": "*/15 * * * *"
}
]
}