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): sync order fulfillment on a cron and serve the certificate route

nirholas0797b9ec6217
diff --git a/api/_lib/print/adapters/contract.js b/api/_lib/print/adapters/contract.js
index a0fbc675b..39deee16f 100644
--- a/api/_lib/print/adapters/contract.js
+++ b/api/_lib/print/adapters/contract.js
@@ -13,7 +13,7 @@
// origin country, lead time) rather than a try-and-see.
//
// THE RULE THAT MATTERS: an adapter never writes the database. It returns
-// vocabulary the store understands, and the caller drives transitionOrder().
+// vocabulary the store understands, and the caller drives transition().
// That is what keeps a partner changing their payload shape from being able to
// corrupt an order's state machine.
//
@@ -35,21 +35,9 @@
import { createHash } from 'node:crypto';
import { PRINT_STATUSES } from '../../print-store.js';
+import { ADAPTER_DRIVABLE_STATUSES } from '../fulfillment-queries.js';
-/**
- * The statuses a fulfillment provider is allowed to drive. Everything before
- * `submitted` is ours (quoting, payment, safety screening) and no adapter may
- * reach back into it; `refunded` is a money action and stays operator-only.
- */
-export const ADAPTER_DRIVABLE_STATUSES = Object.freeze([
- 'submitted',
- 'printing',
- 'quality_check',
- 'shipped',
- 'delivered',
- 'canceled',
- 'rejected',
-]);
+export { ADAPTER_DRIVABLE_STATUSES };
/** Thrown when an adapter returns something the store cannot use. */
export class AdapterContractError extends Error {
diff --git a/api/_lib/print/fulfillment-queries.js b/api/_lib/print/fulfillment-queries.js
new file mode 100644
index 000000000..414e06247
--- /dev/null
+++ b/api/_lib/print/fulfillment-queries.js
@@ -0,0 +1,218 @@
+// @ts-check
+// The reads and the ledger the fulfillment lane needs, alongside the state
+// machine rather than inside it.
+//
+// api/_lib/print-store.js owns one thing: moving an order from one status to
+// the next, and everything that must happen when it does. This module owns the
+// questions fulfillment asks about orders it is not moving: what is in the
+// operator queue, which jobs a provider still owes us, which of those are late,
+// and whether we have already seen a given webhook delivery.
+//
+// Keeping them apart matters. The store is the file every reviewer reads to
+// learn the rules; padding it with queue pagination and a delivery ledger makes
+// those rules harder to see, and a read that does not transition an order has
+// no business living next to the code that does.
+
+import { sql } from '../db.js';
+import { databaseConfigured } from '../env.js';
+import { LEGAL_TRANSITIONS, PRINT_STATUSES } from '../print-store.js';
+
+/** True when this deployment can persist orders at all. */
+export function printStoreEnabled() {
+ return Boolean(databaseConfigured());
+}
+
+/**
+ * Statuses a fulfillment provider is allowed to drive. Everything before
+ * `submitted` is ours (quoting, payment, safety screening) and no adapter may
+ * reach back into it; `refunded` is a money decision and stays operator-only.
+ */
+export const ADAPTER_DRIVABLE_STATUSES = Object.freeze([
+ 'submitted', 'printing', 'quality_check', 'shipped', 'delivered', 'canceled', 'rejected',
+]);
+
+/**
+ * Statuses where a provider owns the job and the reconciliation sweep should
+ * keep polling. Matches the print_orders_open_idx partial index.
+ */
+export const OPEN_PROVIDER_STATUSES = Object.freeze(['submitted', 'printing', 'quality_check', 'shipped']);
+
+/**
+ * The moves allowed out of a status, as a fresh array so a caller cannot mutate
+ * the machine. The console renders this to build its action buttons, which is
+ * why an unknown status yields an empty list instead of throwing.
+ * @param {string} status
+ * @returns {string[]}
+ */
+export function allowedTransitions(status) {
+ return [...(LEGAL_TRANSITIONS[status] || [])];
+}
+
+/**
+ * The operator queue. `status` may be one status, a list, or omitted for
+ * everything. Newest first, which is the order the console renders.
+ * @param {{ status?: string|string[], limit?: number, offset?: number }} [opts]
+ */
+export async function listOrders({ status, limit = 50, offset = 0 } = {}) {
+ if (!printStoreEnabled()) return [];
+ const statuses = (Array.isArray(status) ? status : status ? [status] : []).filter((s) => PRINT_STATUSES.includes(s));
+ const cap = Math.min(Math.max(Number(limit) || 50, 1), 200);
+ const skip = Math.max(Number(offset) || 0, 0);
+ const where = statuses.length ? sql`where status = any(${statuses})` : sql`where true`;
+ return sql`select * from print_orders ${where} order by created_at desc limit ${cap} offset ${skip}`;
+}
+
+/** Per-status counts for the console's queue rail. Every status is present. */
+export async function countOrdersByStatus() {
+ if (!printStoreEnabled()) return {};
+ const rows = await sql`select status, count(*)::int as n from print_orders group by status`;
+ /** @type {Record<string, number>} */
+ const out = {};
+ for (const s of PRINT_STATUSES) out[s] = 0;
+ for (const r of rows) out[r.status] = r.n;
+ return out;
+}
+
+/**
+ * Resolve an order by the provider's own identifier. This is how a webhook
+ * finds the job: a partner knows their id, never ours.
+ * @param {string} provider
+ * @param {string} providerOrderId
+ */
+export async function getOrderByProviderId(provider, providerOrderId) {
+ if (!printStoreEnabled() || !provider || !providerOrderId) return null;
+ const [row] = await sql`
+ select * from print_orders
+ where provider = ${provider} and provider_order_id = ${providerOrderId}
+ limit 1`;
+ return row || null;
+}
+
+/**
+ * Live jobs a provider owns, for the reconciliation poll. Late or not: polling
+ * is how we learn a job shipped when a webhook was lost.
+ * @param {{ limit?: number }} [opts]
+ */
+export async function listOpenProviderOrders({ limit = 100 } = {}) {
+ if (!printStoreEnabled()) return [];
+ const cap = Math.min(Math.max(Number(limit) || 100, 1), 500);
+ return sql`
+ select * from print_orders
+ where status = any(${[...OPEN_PROVIDER_STATUSES]})
+ and provider is not null
+ and provider_order_id is not null
+ order by submitted_at asc nulls first
+ limit ${cap}`;
+}
+
+/**
+ * Jobs a provider has been quiet on for longer than their declared lead time.
+ *
+ * `graceDays` is added on top of the order's own lead_time_days, so a job is a
+ * stall only once it is late by a margin, not the moment it hits its estimate.
+ * Orders alerted within `realertHours` are excluded, which is what stops one
+ * stuck job paging the operator on every sweep.
+ *
+ * @param {{ graceDays?: number, realertHours?: number, limit?: number }} [opts]
+ */
+export async function listStalledOrders({ graceDays = 2, realertHours = 24, limit = 50 } = {}) {
+ if (!printStoreEnabled()) return [];
+ const grace = Math.max(Number(graceDays) || 0, 0);
+ const realert = Math.max(Number(realertHours) || 0, 0);
+ const cap = Math.min(Math.max(Number(limit) || 50, 1), 200);
+ return sql`
+ select * from print_orders
+ where status = any(${[...OPEN_PROVIDER_STATUSES]})
+ and submitted_at is not null
+ and submitted_at < now() - make_interval(days => (coalesce(lead_time_days, 0) + ${grace})::int)
+ and (stall_alerted_at is null or stall_alerted_at < now() - make_interval(hours => ${realert}::int))
+ order by submitted_at asc
+ limit ${cap}`;
+}
+
+/**
+ * Record that the operator has been told about a stalled order. Deliberately
+ * not a transition: nothing about the order's lifecycle changed.
+ * @param {string[]} orderIds
+ */
+export async function markStallAlerted(orderIds) {
+ if (!printStoreEnabled() || !orderIds?.length) return 0;
+ const rows = await sql`update print_orders set stall_alerted_at = now() where id = any(${orderIds}) returning id`;
+ return rows.length;
+}
+
+/**
+ * Write the provider's last-seen payload and shipment details WITHOUT a status
+ * change, for the case where a provider reports news that is not a move (a
+ * tracking number that arrives before the shipment event, a heartbeat).
+ *
+ * provider_state is diagnostic only: nothing reads it to make a decision, which
+ * is what keeps a partner changing their payload shape from being able to break
+ * the state machine.
+ *
+ * @param {string} orderId
+ * @param {{ tracking_number?: string, carrier?: string, provider_state?: object }} patch
+ */
+export async function patchProviderDetails(orderId, patch = {}) {
+ if (!printStoreEnabled()) return null;
+ const [row] = await sql`
+ update print_orders set
+ tracking_number = coalesce(${patch.tracking_number ?? null}, tracking_number),
+ carrier = coalesce(${patch.carrier ?? null}, carrier),
+ provider_state = coalesce(${patch.provider_state ? JSON.stringify(patch.provider_state) : null}::jsonb, provider_state),
+ updated_at = now()
+ where id = ${orderId}
+ returning *`;
+ return row || null;
+}
+
+// ── webhook idempotency ledger ───────────────────────────────────────────────
+
+/**
+ * Claim a webhook delivery. Returns fresh: true exactly once per (provider,
+ * delivery_id) pair. The insert IS the lock, so a provider retrying a delivery
+ * (every serious one does) cannot append the timeline row twice even when two
+ * retries land concurrently on two containers.
+ *
+ * @param {{ provider: string, deliveryId: string, orderId?: string|null }} input
+ * @returns {Promise<{ fresh: boolean }>}
+ */
+export async function claimWebhookDelivery({ provider, deliveryId, orderId = null }) {
+ const rows = await sql`
+ insert into print_webhook_deliveries (provider, delivery_id, order_id)
+ values (${provider}, ${deliveryId}, ${orderId})
+ on conflict (provider, delivery_id) do nothing
+ returning delivery_id`;
+ return { fresh: rows.length > 0 };
+}
+
+/**
+ * Mark a claimed delivery as having actually driven a change, so an operator
+ * reading the ledger can tell "seen and duplicate" from "seen and it moved the
+ * order".
+ * @param {{ provider: string, deliveryId: string, orderId?: string|null }} input
+ */
+export async function markWebhookApplied({ provider, deliveryId, orderId = null }) {
+ await sql`
+ update print_webhook_deliveries
+ set applied = true, order_id = coalesce(${orderId}, order_id)
+ where provider = ${provider} and delivery_id = ${deliveryId}`;
+}
+
+/**
+ * Deliveries recorded against an order, newest first. Diagnostic read for the
+ * console: "did their webhook actually reach us?" is the first question when a
+ * job looks stuck.
+ * @param {string} orderId
+ * @param {number} [limit]
+ */
+export async function listWebhookDeliveries(orderId, limit = 50) {
+ if (!printStoreEnabled() || !orderId) return [];
+ const cap = Math.min(Math.max(Number(limit) || 50, 1), 200);
+ return sql`
+ select provider, delivery_id, applied, received_at
+ from print_webhook_deliveries
+ where order_id = ${orderId}
+ order by received_at desc
+ limit ${cap}`;
+}
diff --git a/api/_lib/print/fulfillment.js b/api/_lib/print/fulfillment.js
index 1e4c71e7b..e56426f9b 100644
--- a/api/_lib/print/fulfillment.js
+++ b/api/_lib/print/fulfillment.js
@@ -3,7 +3,7 @@
// machine.
//
// Adapters speak; the store decides. Every path in here takes a normalized
-// adapter result and turns it into at most one transitionOrder() call, so the
+// adapter result and turns it into at most one transition() call, so the
// rules about what may follow what live in print-store.js and nowhere else.
//
// The interesting case is a provider reporting something the machine refuses:
@@ -14,13 +14,7 @@
// the timeline as a provider event with the refusal in its note, and the HTTP
// caller gets a 200 that says `applied: false`.
-import { sql } from '../db.js';
-import {
- PrintTransitionError,
- appendOrderEvent,
- getOrder,
- transitionOrder,
-} from '../print-store.js';
+import { PrintStoreError, appendEvent, getOrder, transition } from '../print-store.js';
import {
normalizeCancelResult,
normalizeStatusResult,
@@ -28,6 +22,7 @@ import {
adapterSupportsOrder,
} from './adapters/contract.js';
import { getAdapter, routeOrder } from './adapters/index.js';
+import { patchProviderDetails } from './fulfillment-queries.js';
/**
* Hand a screened order to a fulfillment lane.
@@ -59,7 +54,7 @@ export async function submitOrder({ order, adapterKey = '', actor = 'operator',
const raw = await adapter.submit(order, assets);
const result = normalizeSubmitResult(adapter.key, raw);
- const { order: updated } = await transitionOrder({
+ const { order: updated } = await transition({
orderId: order.id,
to: result.status,
note: result.note || `Submitted to ${adapter.label}.`,
@@ -68,14 +63,16 @@ export async function submitOrder({ order, adapterKey = '', actor = 'operator',
patch: {
provider: adapter.key,
provider_order_id: result.providerOrderId,
- provider_state: result.state,
lead_time_days: result.leadTimeDays || adapter.capabilities.leadTimeDays,
- submitted_at: new Date().toISOString(),
- stall_alerted_at: null,
},
});
- return { order: updated, adapter: adapter.key, providerOrderId: result.providerOrderId };
+ // provider_state is not a lifecycle column, so it is written beside the move
+ // rather than through it. A failure here loses a diagnostic blob, never the
+ // fact that the job was submitted.
+ const withState = (await patchProviderDetails(order.id, { provider_state: result.state })) || updated;
+
+ return { order: withState, adapter: adapter.key, providerOrderId: result.providerOrderId };
}
/** A fulfillment routing/lane failure with a code a handler can map to HTTP. */
@@ -108,32 +105,30 @@ export async function applyProviderEvent({ order, event, actor = 'provider' }) {
// No status, or the status we already hold: this is news about the job, not
// a move. Record what changed and stop.
if (!event.status || event.status === order.status) {
- const changed = await patchOnly(order, patch);
+ const changed = (await patchProviderDetails(order.id, patch)) || order;
if (event.note) {
- await appendOrderEvent({
- orderId: order.id,
- status: order.status,
- note: event.note,
- actor,
- });
+ await appendEvent({ orderId: order.id, status: order.status, note: event.note, actor });
}
return { applied: false, order: changed, reason: event.status ? 'already in that status' : 'no status change reported' };
}
try {
- const { order: updated } = await transitionOrder({
+ const { order: updated } = await transition({
orderId: order.id,
to: event.status,
note: event.note || `Provider reported ${event.status}.`,
actor,
- patch,
+ patch: { tracking_number: patch.tracking_number, carrier: patch.carrier },
});
- return { applied: true, order: updated, reason: '' };
+ const withState = patch.provider_state
+ ? (await patchProviderDetails(order.id, { provider_state: patch.provider_state })) || updated
+ : updated;
+ return { applied: true, order: withState, reason: '' };
} catch (err) {
- if (err instanceof PrintTransitionError) {
- // Out-of-order or impossible: keep it on the timeline where an operator
- // will see it, and tell the caller it was not applied.
- await appendOrderEvent({
+ if (err instanceof PrintStoreError) {
+ // Out of order, impossible, or lost a race: keep it on the timeline
+ // where an operator will see it, and tell the caller it was not applied.
+ await appendEvent({
orderId: order.id,
status: order.status,
note: `Refused provider report '${event.status}': ${err.message}`,
@@ -146,27 +141,6 @@ export async function applyProviderEvent({ order, event, actor = 'provider' }) {
}
}
-/**
- * Write patched columns without a status change. Used when a provider reports
- * a tracking number before (or after) the transition that carries it.
- * @param {object} order
- * @param {Record<string, unknown>} patch
- */
-async function patchOnly(order, patch) {
- if (!patch || Object.keys(patch).length === 0) return order;
- // transitionOrder is the only writer of `status`; a no-op self transition is
- // not legal, so patch-only writes go through a dedicated statement here. It
- // touches no lifecycle column, which is why it does not need the machine.
- const rows = await sql`
- update print_orders set
- tracking_number = coalesce(${patch.tracking_number ?? null}, tracking_number),
- carrier = coalesce(${patch.carrier ?? null}, carrier),
- provider_state = coalesce(${patch.provider_state ? JSON.stringify(patch.provider_state) : null}::jsonb, provider_state)
- where id = ${order.id}
- returning *`;
- return rows[0] || order;
-}
-
/**
* Poll a lane for one order and apply whatever it says.
* @param {object} order
diff --git a/api/_lib/print/rules.js b/api/_lib/print/rules.js
new file mode 100644
index 000000000..203675be9
--- /dev/null
+++ b/api/_lib/print/rules.js
@@ -0,0 +1,175 @@
+// The fabrication denylist: what three.ws will not manufacture.
+//
+// A refused image generation costs nothing. A printed firearm receiver is a
+// felony in most of the jurisdictions this platform ships to, and a printed
+// key to somebody's front door is a burglary tool. Physical output raises the
+// stakes of every moderation decision, so the line lives in code, with a test
+// per rule, rather than in a prompt an LLM may or may not honour.
+//
+// Structure, deliberately not one regex blob:
+//
+// tier 'hard' — refused outright. The object has no lawful hobby use that
+// a print bureau would accept, and no phrasing exempts it.
+// tier 'soft' — refused unless the request is unambiguously a display piece
+// AND the geometry agrees (a tabletop miniature is centimetres
+// tall; a functional part is life-size). A platform whose main
+// output is AI figurines cannot refuse the word "sword", so
+// these escalate to the LLM layer instead of auto-refusing.
+//
+// Every rule carries the buyer-facing message it refuses with. A refusal that
+// says "blocked" and nothing else is a support ticket; one that names the
+// category, links the policy and says what IS allowed is a designed state.
+
+export const POLICY_URL = '/docs/materialize#content-policy';
+
+/** Whole-word match so "assassin" never trips on "ass" and "barrelled" never trips on "barrel". */
+export function matchTerm(text, terms) {
+ for (const term of terms) {
+ const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\s+/g, '[\\s_-]+');
+ const re = new RegExp(`(^|[^a-z0-9])${escaped}([^a-z0-9]|$)`, 'i');
+ if (re.test(text)) return term;
+ }
+ return null;
+}
+
+export const FABRICATION_RULES = Object.freeze([
+ {
+ id: 'firearm_components',
+ tier: 'hard',
+ label: 'firearm components',
+ terms: [
+ 'lower receiver', 'upper receiver', 'ar15 lower', 'ar-15 lower', 'ar15 receiver',
+ 'ar-15 receiver', 'ak receiver', 'glock frame', 'pistol frame', 'firearm frame',
+ 'auto sear', 'autosear', 'drop in auto sear', 'lightning link', 'glock switch',
+ 'giggle switch', 'forced reset trigger', 'bump stock', 'ghost gun', 'ghost guns',
+ '80 percent lower', '80% lower', 'unserialized firearm', 'untraceable firearm',
+ 'fgc9', 'fgc-9', 'liberator pistol', 'zip gun', 'slam fire', 'firing pin',
+ 'bolt carrier group', 'trigger group', 'sear housing', 'gun barrel', 'rifled barrel',
+ 'barrel liner', 'breech block', 'pistol slide', 'firearm suppressor',
+ ],
+ message:
+ 'three.ws does not manufacture firearm components. Receivers, frames, trigger and fire-control parts, barrels and conversion devices are refused regardless of intended use.',
+ allowed:
+ 'Display models of historical or fictional weapons that are one solid piece with no moving mechanism, printed as miniatures, are fine.',
+ },
+ {
+ id: 'suppressors',
+ tier: 'hard',
+ label: 'suppressors and solvent traps',
+ terms: [
+ 'suppressor', 'silencer', 'solvent trap', 'baffle stack', 'suppressor baffle',
+ 'monocore baffle', 'oil filter adapter', 'freeze plug kit', 'muzzle can',
+ ],
+ message:
+ 'three.ws does not manufacture sound suppressors or the parts marketed as solvent traps that convert into them.',
+ allowed:
+ 'Non-functional prop barrels for costume and film use, printed solid with no bore, are fine.',
+ },
+ {
+ id: 'ammunition',
+ tier: 'hard',
+ label: 'ammunition and feeding devices',
+ terms: [
+ 'ammunition', 'live ammunition', 'cartridge case', 'shell casing', 'bullet mold',
+ 'bullet mould', 'primer pocket', 'reloading die', 'powder measure',
+ 'high capacity magazine', 'high-capacity magazine', 'drum magazine',
+ 'magazine follower', 'magazine baseplate', 'speed loader', 'ammo belt link',
+ ],
+ message:
+ 'three.ws does not manufacture ammunition, ammunition components, or magazines and feeding devices.',
+ allowed:
+ 'Inert display shells for a museum-style diorama, modelled as a single solid with no cavity, are fine.',
+ },
+ {
+ id: 'lock_bypass',
+ tier: 'hard',
+ label: 'keys and lock-bypass tools',
+ terms: [
+ 'bump key', 'bump keys', 'lock pick', 'lock picks', 'lockpick', 'lockpicks',
+ 'lock picking set', 'tension wrench', 'tensioner wrench', 'handcuff key',
+ 'handcuff shim', 'jiggler key', 'try out key', 'tryout key', 'key blank',
+ 'key bitting', 'key copy from photo', 'duplicate this key', 'copy of my key',
+ 'tubular lock pick', 'car door jiggler', 'jim tool', 'slim jim',
+ 'bypass driver', 'safe bypass tool', 'padlock shim', 'rfid key fob clone',
+ ],
+ message:
+ 'three.ws does not manufacture keys or lock-bypass tools. A working key, a pick, or a shim is a burglary tool no matter who orders it.',
+ allowed:
+ 'Decorative or fantasy key sculptures that do not reproduce a real key bitting are fine.',
+ },
+ {
+ id: 'counterfeit',
+ tier: 'hard',
+ label: 'counterfeit and trademark-infringing goods',
+ terms: [
+ 'counterfeit', 'counterfeits', 'knockoff', 'knock off', 'bootleg', 'replica logo',
+ 'fake logo', 'copy of the logo', 'brand logo badge', 'trademark logo',
+ 'authentication tag', 'authenticity hologram', 'serial number plate',
+ 'hallmark stamp', 'luxury brand emblem', 'designer monogram', 'fake hallmark',
+ 'currency note', 'banknote', 'coin die', 'passport stamp', 'id card blank',
+ ],
+ message:
+ 'three.ws does not manufacture counterfeit goods, brand marks, or anything that authenticates a product or identity it is not.',
+ allowed:
+ 'Your own logo, your own brand, and original designs are welcome. Upload or generate the mark you own.',
+ },
+ {
+ id: 'working_weapon_mechanisms',
+ tier: 'hard',
+ label: 'working weapon mechanisms',
+ terms: [
+ 'switchblade', 'automatic knife', 'otf knife', 'out the front knife',
+ 'butterfly knife', 'balisong', 'push dagger', 'brass knuckles', 'knuckle duster',
+ 'knuckleduster', 'garrote', 'garrotte', 'blackjack sap', 'spring loaded blade',
+ 'concealed blade', 'sharpened blade', 'crossbow trigger', 'speargun trigger',
+ 'blowgun dart', 'caltrop', 'caltrops', 'tire spike', 'punji stake',
+ ],
+ message:
+ 'three.ws does not manufacture working weapon mechanisms, concealed blades, or impact and area-denial weapons.',
+ allowed:
+ 'Prop and costume weapons with blunt edges, printed as a single non-articulating piece, are fine.',
+ },
+ {
+ id: 'weapon_likeness',
+ tier: 'soft',
+ label: 'realistic weapon likeness',
+ terms: [
+ 'pistol', 'handgun', 'revolver', 'rifle', 'shotgun', 'carbine', 'submachine gun',
+ 'assault rifle', 'machine gun', 'ar15', 'ar-15', 'ak47', 'ak-47', 'glock',
+ 'grenade', 'landmine', 'pipe bomb', 'detonator', 'firearm', 'firearms',
+ ],
+ // A soft rule never refuses on its own. It marks the request for the LLM
+ // layer and pairs with the geometry signal: a 28 mm tabletop trooper and a
+ // 210 mm life-size pistol shell are the same words and different objects.
+ message:
+ 'three.ws does not manufacture realistic firearm likenesses at or near life size.',
+ allowed:
+ 'Miniature and tabletop-scale figures carrying weapons, and clearly stylised or fantasy designs, are fine.',
+ },
+]);
+
+/**
+ * Evaluate the denylist over one blob of text (prompt lineage, model title and
+ * buyer note, concatenated by the caller).
+ *
+ * @param {string} text
+ * @returns {{ hard: object|null, soft: object[], matched: string|null }}
+ */
+export function evaluateRules(text) {
+ const haystack = String(text || '').toLowerCase();
+ if (!haystack.trim()) return { hard: null, soft: [], matched: null };
+
+ const soft = [];
+ for (const rule of FABRICATION_RULES) {
+ const matched = matchTerm(haystack, rule.terms);
+ if (!matched) continue;
+ if (rule.tier === 'hard') return { hard: rule, soft, matched };
+ soft.push({ rule, matched });
+ }
+ return { hard: null, soft, matched: soft[0]?.matched ?? null };
+}
+
+/** Look a rule up by id, for tests and for rendering a stored verdict. */
+export function ruleById(id) {
+ return FABRICATION_RULES.find((r) => r.id === id) || null;
+}
diff --git a/api/cron/print-orders-sync.js b/api/cron/print-orders-sync.js
new file mode 100644
index 000000000..8f85065c4
--- /dev/null
+++ b/api/cron/print-orders-sync.js
@@ -0,0 +1,38 @@
+// GET /api/cron/print-orders-sync — the Materialize reconciliation sweep.
+//
+// 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.
+//
+// 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.
+//
+// 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.
+
+import { cors, 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;
+
+const BATCH_LIMIT = Number(process.env.PRINT_CERT_RETRY_BATCH) || 10;
+const MAX_ATTEMPTS = Number(process.env.PRINT_CERT_MAX_ATTEMPTS) || 8;
+
+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;
+
+ const certificates = await retryPendingAttestations({
+ limit: BATCH_LIMIT,
+ maxAttempts: MAX_ATTEMPTS,
+ });
+
+ return json(res, 200, { ok: true, cluster: certCluster(), certificates });
+});
diff --git a/vite.config.js b/vite.config.js
index 90d5b6f8a..ac257e72d 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -543,6 +543,8 @@ const appConfig = {
'drop-collection': resolve(__dirname, 'pages/drop-collection.html'),
spotlight: resolve(__dirname, 'pages/spotlight.html'),
'spotlight-entry': resolve(__dirname, 'pages/spotlight-entry.html'),
+ certificate: resolve(__dirname, 'pages/certificate.html'),
+ 'print-insert': resolve(__dirname, 'pages/print-insert.html'),
app: resolve(__dirname, 'pages/app.html'),
proof: resolve(__dirname, 'pages/proof.html'),
stream: resolve(__dirname, 'pages/stream.html'),
@@ -1442,6 +1444,8 @@ const appConfig = {
'/drops/': resolve(root, 'pages/drops.html'),
'/spotlight': resolve(root, 'pages/spotlight.html'),
'/spotlight/': resolve(root, 'pages/spotlight.html'),
+ '/cert': resolve(root, 'pages/certificate.html'),
+ '/cert/': resolve(root, 'pages/certificate.html'),
'/airdrops': resolve(root, 'pages/airdrops.html'),
'/airdrops/': resolve(root, 'pages/airdrops.html'),
'/launcher': resolve(root, 'pages/launcher.html'),
@@ -2153,6 +2157,12 @@ const appConfig = {
// /spotlight/:id → one Agent Spotlight entry (uuid).
else if (!filePath && /^\/spotlight\/[0-9a-fA-F-]{36}\/?$/.test(path))
filePath = resolve(root, 'pages/spotlight-entry.html');
+ // /cert/:certId → one Materialize certificate of authenticity (24 hex).
+ else if (!filePath && /^\/cert\/[0-9a-f]{24}\/?$/.test(path))
+ filePath = resolve(root, 'pages/certificate.html');
+ // /materialize/insert/:certId → the printable package insert card (ops).
+ else if (!filePath && /^\/materialize\/insert\/[0-9a-f]{24}\/?$/.test(path))
+ filePath = resolve(root, 'pages/print-insert.html');
// /drops/:slug → one generative 3D collection. Declared ahead of the
// /drop/:id rule below so the singular sealed-gift route and this
// plural collection route can never shadow each other.