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(provenance): sign every GLB export by default, free, with a model-page verify badge
nirholas686eedf4ff9d
diff --git a/api/_lib/auto-provenance.js b/api/_lib/auto-provenance.jsnew file mode 100644index 000000000..5cec38afa--- /dev/null+++ b/api/_lib/auto-provenance.js@@ -0,0 +1,124 @@+// Automatic, free content credentials: the "by default" half of+// specs/PROVENANCE_3D.md. Before this module existed, a signed credential only+// came into being when an agent explicitly (and separately) paid for+// anchor_provenance (api/_mcp3d/tools/provenance.js). Every other GLB this+// platform delivered carried no credential at all: `verify_provenance` and+// GET /api/provenance answered `unknown` for it, forever, unless someone later+// anchored it by hand.+//+// This module signs and stores that SAME envelope shape automatically, for+// free, at the moment a GLB is finalized or served. No on-chain write, so no+// irreversible spend happens unattended (CLAUDE.md gate 1). Anchoring on+// Solana stays a separate, explicit, paid upgrade: decideVerdict+// (provenance-3d.js) already returns `verified` from the signature alone, so+// the free credential issued here is a complete, real, publicly verifiable+// authenticity record on its own; the paid anchor only adds an on-chain+// confirmation link on top of it.+//+// Best-effort and idempotent, the same contract as writeAssetProvenance+// (asset-provenance.js) and gradeDeliveredMesh (forge-store.js): a signing or+// storage failure here never blocks delivery of the asset it accompanies, and+// a GLB whose hash already has an envelope (auto-issued or anchored) is left+// alone: a credential is evidence, and evidence is not reissued.+//+// The owner is the only opt-out (work order 079): set PROVENANCE_AUTO_DISABLE+// to "true" on the deployment to turn this off everywhere it's called. No+// per-request or per-caller flag exists, by design: a credential records+// what three.ws produced, not a preference the caller gets to toggle.++import { headObject, putObject } from './r2.js';+import { decodeAttesterSecret } from './attest-event.js';+import { fetchSafePublicUrl } from './ssrf-guard.js';+import { sha256Hex, buildCredential, signCredential, credentialHash, provenanceKey } from './provenance-3d.js';++const MAX_GLB_BYTES = 64 * 1024 * 1024; // matches the MCP provenance tools' ceiling++export function autoProvenanceDisabled() {+ return process.env.PROVENANCE_AUTO_DISABLE === 'true';+}++/**+ * Sign and store a free (unanchored) content credential for a GLB already in+ * memory. Never throws.+ *+ * @returns {Promise<object|null>} the envelope written, or null when skipped+ * (owner opt-out, no issuer key configured, a credential already exists for+ * these exact bytes, or a signing/storage failure, logged, never thrown).+ */+export async function autoCredentialForBytes({+ buffer,+ assetId,+ creator,+ prompt,+ model,+ provider,+ lineage,+} = {}) {+ if (autoProvenanceDisabled()) return null;+ if (!buffer?.length) return null;++ const secret = decodeAttesterSecret(process.env.ATTEST_AGENT_SECRET_KEY || '');+ if (!secret) return null; // no issuer key on this deployment: an honest no-op, not a fake credential.++ const glbSha256 = sha256Hex(buffer);+ const key = provenanceKey(glbSha256);++ try {+ const existing = await headObject(key);+ if (existing) return null; // these exact bytes already carry a credential (auto or anchored).+ } catch (err) {+ console.warn('[auto-provenance] existence check failed, attempting to credential anyway:', err?.message);+ }++ let credential;+ try {+ credential = buildCredential({+ glbSha256,+ createdAt: new Date().toISOString(),+ assetId,+ creator,+ prompt,+ model,+ provider,+ lineage,+ });+ } catch (err) {+ console.warn('[auto-provenance] credential build failed:', err?.message);+ return null;+ }++ const { signature, issuer } = signCredential(credential, secret);+ const envelope = { credential, signature, issuer, credentialHash: credentialHash(credential) };++ try {+ await putObject({+ key,+ body: Buffer.from(JSON.stringify(envelope), 'utf8'),+ contentType: 'application/json',+ });+ return envelope;+ } catch (err) {+ console.warn('[auto-provenance] credential store failed:', err?.message);+ return null;+ }+}++/**+ * Same as autoCredentialForBytes, but for a known https GLB URL instead of+ * bytes already in hand (an export/download endpoint ensuring the asset it is+ * about to serve carries a credential). SSRF-guarded fetch, same ceiling as+ * the anchor/verify MCP tools. Never throws.+ */+export async function ensureAutoCredential({ glbUrl, assetId, creator, prompt, model, provider, lineage } = {}) {+ if (autoProvenanceDisabled()) return null;+ if (!/^https:\/\//i.test(String(glbUrl || ''))) return null;+ try {+ const res = await fetchSafePublicUrl(glbUrl, { redirect: 'follow' }, { maxBytes: MAX_GLB_BYTES });+ if (!res.ok) return null;+ const buffer = Buffer.from(await res.arrayBuffer());+ return await autoCredentialForBytes({ buffer, assetId, creator, prompt, model, provider, lineage });+ } catch (err) {+ console.warn('[auto-provenance] ensure-by-url failed:', err?.message);+ return null;+ }+}diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.jsindex 1a48f64a2..6cce01a31 100644--- a/api/_lib/forge-store.js+++ b/api/_lib/forge-store.js@@ -31,6 +31,7 @@ import { fetchUpstream, fetchUpstreamPublic } from './upstream-fetch.js';import { gradeSimReadiness } from './sim-readiness.js';import { putGrade } from './sim-readiness-store.js';import { dispatchWebhooks } from './webhook-dispatch.js';+import { autoCredentialForBytes } from './auto-provenance.js';import { validForgeDestination } from '../../src/shared/forge-destinations.js';// Stable, non-secret salt so a leaked DB row can't be trivially reversed to the@@ -715,6 +716,17 @@ export async function materializeCreation({ replicateJobId, clientKey, glbUrl, q});// Every delivered mesh gets a physics grade, cached by content hash.gradeDeliveredMesh({ buffer: glb.buffer, creationId: existing.id, sourceUrl: glb.publicUrl });+ // ...and a free, signed content credential by default (work order 079), no+ // explicit anchor_provenance call required. Fire-and-forget like the grade+ // above: a signing/storage hiccup here must never delay delivery.+ autoCredentialForBytes({+ buffer: glb.buffer,+ assetId: existing.id,+ creator: existing.user_id || existing.client_key || null,+ prompt: existing.prompt || null,+ model: existing.backend || null,+ provider: existing.path || null,+ }).catch(() => {});// …and a phone-sized delivery variant. See buildWebVariant for why this is// a second object and why it runs after the row is already 'done'.buildWebVariant({ buffer: glb.buffer, creationId: existing.id, keyPrefix });diff --git a/api/_lib/migrations/20261015030000_paid_assets_glb_sha256.sql b/api/_lib/migrations/20261015030000_paid_assets_glb_sha256.sqlnew file mode 100644index 000000000..4312449b6--- /dev/null+++ b/api/_lib/migrations/20261015030000_paid_assets_glb_sha256.sql@@ -0,0 +1,8 @@+-- Cache the GLB content hash on paid_assets so /api/x402/asset-download can+-- issue (or recall) its free, signed content credential (work order 079,+-- specs/PROVENANCE_3D.md) without re-fetching and re-hashing the full object+-- from R2 on every single paid download. Null until the first download after+-- this migration lands; backfilled lazily, not in bulk, the same way every+-- other best-effort provenance field in this codebase fills in.+alter table paid_assets+ add column if not exists glb_sha256 text;diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 5fcae5527..cdbaa3fed 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -1909,7 +1909,8 @@ CREATE TABLE IF NOT EXISTS paid_assets (creator_payto_base text,creator_payto_solana text,creator_payto_bsc text,- created_at timestamptz NOT NULL DEFAULT now()+ created_at timestamptz NOT NULL DEFAULT now(),+ glb_sha256 text);CREATE INDEX IF NOT EXISTS paid_assets_slug_idx ON paid_assets (slug);diff --git a/api/x402/asset-download.js b/api/x402/asset-download.jsindex a3bc1e1e0..62fd6f000 100644--- a/api/x402/asset-download.js+++ b/api/x402/asset-download.js@@ -14,10 +14,12 @@ import { buildBazaarSchema, paymentRequirements, send402 } from '../_lib/x402-spimport { priceFor } from '../_lib/x402-prices.js';import { withService } from '../_lib/x402/bazaar-helpers.js';import { sql } from '../_lib/db.js';-import { presignGet } from '../_lib/r2.js';+import { presignGet, getObjectBuffer } from '../_lib/r2.js';import { cors, error } from '../_lib/http.js';import { env } from '../_lib/env.js';import assetDownloadListing from '../_lib/service-catalog/services/asset-download.js';+import { autoCredentialForBytes } from '../_lib/auto-provenance.js';+import { sha256Hex } from '../_lib/provenance-3d.js';const ROUTE = '/api/x402/asset-download';@@ -53,6 +55,8 @@ const OUTPUT_EXAMPLE = {expiresAt: '2026-05-21T18:48:09.000Z',downloadUrl:'https://three-ws-public.r2.dev/assets/pole-dancer-rumba.glb?X-Amz-Algorithm=...',+ glbSha256: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b85',+ verifyUrl: 'https://three.ws/api/provenance?hash=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b85',};const OUTPUT_SCHEMA = {@@ -68,6 +72,12 @@ const OUTPUT_SCHEMA = {sizeBytes: { type: 'integer', minimum: 0 },expiresAt: { type: 'string', format: 'date-time' },downloadUrl: { type: 'string', format: 'uri' },+ // Present for GLB assets once their free, signed content credential+ // exists (work order 079): glbSha256 is the content hash the+ // credential is signed over; verifyUrl checks it for free, with no+ // account, wallet, or payment, against GET /api/provenance.+ glbSha256: { type: 'string', pattern: '^[0-9a-f]{64}$' },+ verifyUrl: { type: 'string', format: 'uri' },},};@@ -94,7 +104,7 @@ async function loadAsset(slug) {const rows = await sql`SELECT id, slug, title, description, mime_type, size_bytes, r2_key,price_atomics, creator_payto_base, creator_payto_solana,- creator_payto_bsc+ creator_payto_bsc, glb_sha256FROM paid_assetsWHERE slug = ${slug}LIMIT 1@@ -102,6 +112,36 @@ async function loadAsset(slug) {return rows[0] || null;}+// Every paid download carries a free, signed content credential by default+// (work order 079). The hash is cached on the row after the first download so+// a repeat buyer's re-download never re-fetches and re-hashes the full GLB+// just to answer "is this credentialed", only the first ever download pays+// that cost. Issuing the credential itself stays fire-and-forget (never+// delays the response the buyer is waiting on); the hash is awaited because+// it is needed for the verifyUrl in THIS response.+async function ensureAssetCredential(asset) {+ if (asset.glb_sha256) return asset.glb_sha256;+ if (asset.mime_type !== 'model/gltf-binary') return null; // credentials are GLB-specific+ try {+ const buffer = await getObjectBuffer(asset.r2_key);+ if (!buffer?.length) return null;+ const glbSha256 = sha256Hex(buffer);+ autoCredentialForBytes({+ buffer,+ assetId: asset.id,+ creator: null,+ prompt: null,+ model: asset.title,+ provider: 'paid_assets',+ }).catch(() => {});+ sql`UPDATE paid_assets SET glb_sha256 = ${glbSha256} WHERE id = ${asset.id}`.catch(() => {});+ return glbSha256;+ } catch (err) {+ console.warn('[asset-download] could not hash asset for a credential:', err?.message);+ return null;+ }+}+// Build the SIWX statement. EIP-4361 restricts the statement to a single line// of RFC 3986 reserved/unreserved characters + space — double quotes, braces,// backticks, etc. are illegal and make the official SIWX client (browser@@ -218,10 +258,10 @@ export default async function handler(req, res) {expirationSeconds: 300,},async handler() {- const url = await presignGet({- key: asset.r2_key,- expiresIn: PRESIGN_TTL_SECONDS,- });+ const [url, glbSha256] = await Promise.all([+ presignGet({ key: asset.r2_key, expiresIn: PRESIGN_TTL_SECONDS }),+ ensureAssetCredential(asset),+ ]);return {ok: true,slug: asset.slug,@@ -231,6 +271,9 @@ export default async function handler(req, res) {sizeBytes: Number(asset.size_bytes),expiresAt: new Date(Date.now() + PRESIGN_TTL_SECONDS * 1000).toISOString(),downloadUrl: url,+ ...(glbSha256+ ? { glbSha256, verifyUrl: `${env.APP_ORIGIN}/api/provenance?hash=${glbSha256}` }+ : {}),};},});diff --git a/src/model-page.js b/src/model-page.jsindex 31ed4e863..e1d86dc10 100644--- a/src/model-page.js+++ b/src/model-page.js@@ -115,6 +115,7 @@ async function boot() {renderSuggested();loadGeometry();loadSimReadiness();+ loadProvenanceBadge();loadComments();loadEdition();if (shell) shell.setAttribute('aria-busy', 'false');@@ -271,6 +272,7 @@ function renderInfo() {</div><div class="mp-geo" id="mp-geo"><span>Reading geometry…</span></div><div class="mp-sim" id="mp-sim"></div>+ <div class="mp-provenance" id="mp-provenance"></div><section class="mp-tools" aria-label="Model tools"><details class="mp-tool" id="mp-mesh-tools"><summary>Edit mesh <span>repair, smooth, decimate in your browser</span></summary>@@ -673,6 +675,39 @@ async function loadSimReadiness() {}}+// ── provenance badge (the free content-credential verify check) ────────────++// Every model this platform generates now carries a free, signed content+// credential by default (work order 079): api/_lib/forge-store.js issues one+// at the moment the mesh is materialized. This mirrors /viewer's badge+// (public/viewer.html checkProvenance) so the result reads identically+// whether a model is opened standalone or from its gallery page. Silent+// (badge stays empty) if the check can't run, a model page is not worth+// breaking over an authenticity badge.+async function loadProvenanceBadge() {+ const host = $('mp-provenance');+ const c = state.creation;+ if (!host || !c?.glb_url) return;+ try {+ const r = await fetch(`/api/provenance?src=${encodeURIComponent(c.glb_url)}`, {+ headers: { accept: 'application/json' },+ });+ if (!r.ok) return;+ const d = await r.json();+ if (!d?.status) return;+ const label =+ d.status === 'verified' ? `✓ ${d.badge || 'Verified · three.ws'}`+ : d.status === 'tampered' ? '⚠ Tampered'+ : 'Unverified';+ const tag = d.anchor?.explorerUrl ? 'a' : 'span';+ const href = d.anchor?.explorerUrl ? ` href="${esc(d.anchor.explorerUrl)}" target="_blank" rel="noopener"` : '';+ const title = d.reason ? ` title="${esc(d.reason)}"` : '';+ host.innerHTML = `<${tag} class="mp-provenance-badge ${esc(d.status)}"${href}${title}>${esc(label)}</${tag}>`;+ } catch (err) {+ log.warn('provenance check failed', err);+ }+}+// ── comments ─────────────────────────────────────────────────────────────────async function loadComments() {diff --git a/src/model.css b/src/model.cssindex c4744c276..5063d03da 100644--- a/src/model.css+++ b/src/model.css@@ -259,6 +259,50 @@ a.mp-creator-name:hover, a.mp-creator-name:focus-visible { text-decoration: undemargin: 0 0 var(--space-md);}+/* The provenance badge: whether this exact model carries a genuine, untampered+ three.ws content credential (specs/PROVENANCE_3D.md). Same verified / tampered+ / unknown states as the /viewer badge, re-themed to this page's design tokens+ instead of a hardcoded palette. Hidden until the free verify check answers, so+ a slow or failed check never shows a wrong state. */+.mp-provenance {+ display: flex;+ align-items: center;+ min-height: 25px;+ margin: 0 0 var(--space-md);+}+.mp-provenance-badge {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ text-decoration: none;+ font-size: var(--text-xs);+ font-weight: 700;+ letter-spacing: 0.01em;+ border-radius: 999px;+ padding: 4px 10px;+ border: 1px solid transparent;+ white-space: nowrap;+}+.mp-provenance-badge.verified {+ color: var(--success);+ background: color-mix(in srgb, var(--success) 14%, transparent);+ border-color: color-mix(in srgb, var(--success) 36%, transparent);+}+.mp-provenance-badge.tampered {+ color: var(--danger);+ background: color-mix(in srgb, var(--danger) 14%, transparent);+ border-color: color-mix(in srgb, var(--danger) 36%, transparent);+}+.mp-provenance-badge.unknown {+ color: var(--ink-faint);+ background: var(--surface-1);+ border-color: var(--border-subtle, transparent);+}+.mp-provenance-badge:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}+/* ── Model tools (mesh edits, slicer handoff) ───────────────────────────── */.mp-tools {diff --git a/tests/auto-provenance.test.js b/tests/auto-provenance.test.jsnew file mode 100644index 000000000..b7d851bfd--- /dev/null+++ b/tests/auto-provenance.test.js@@ -0,0 +1,147 @@+// Automatic, free content credentials (work order 079): every GLB+// materialized or paid-downloaded gets a signed credential without an+// explicit anchor_provenance call. r2 is mocked (no network, no bucket); the+// signing + verdict path is real, exercised against the same decideVerdict+// used by GET /api/provenance and verify_provenance.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const headObjectMock = vi.fn(async () => null);+const putObjectMock = vi.fn(async () => {});++vi.mock('../api/_lib/r2.js', () => ({+ headObject: (...args) => headObjectMock(...args),+ putObject: (...args) => putObjectMock(...args),+}));++const fetchSafePublicUrlMock = vi.fn();+vi.mock('../api/_lib/ssrf-guard.js', () => ({+ fetchSafePublicUrl: (...args) => fetchSafePublicUrlMock(...args),+}));++const { autoCredentialForBytes, ensureAutoCredential, autoProvenanceDisabled } = await import(+ '../api/_lib/auto-provenance.js'+);+const { sha256Hex, decideVerdict, verifyCredentialSignature } = await import('../api/_lib/provenance-3d.js');++// A 32-byte JSON-array seed, same decodeAttesterSecret form a Solana CLI+// keypair file carries; see api/_lib/attest-event.js.+const TEST_SEED = JSON.stringify(Array(32).fill(7));+const GLB = Buffer.from('a fake but stable GLB payload for auto-provenance tests');++beforeEach(() => {+ headObjectMock.mockReset().mockResolvedValue(null);+ putObjectMock.mockReset().mockResolvedValue(undefined);+ fetchSafePublicUrlMock.mockReset();+ process.env.ATTEST_AGENT_SECRET_KEY = TEST_SEED;+ delete process.env.PROVENANCE_AUTO_DISABLE;+});++afterEach(() => {+ delete process.env.ATTEST_AGENT_SECRET_KEY;+ delete process.env.PROVENANCE_AUTO_DISABLE;+});++describe('autoProvenanceDisabled', () => {+ it('is off unless the owner explicitly sets the flag to "true"', () => {+ expect(autoProvenanceDisabled()).toBe(false);+ process.env.PROVENANCE_AUTO_DISABLE = 'true';+ expect(autoProvenanceDisabled()).toBe(true);+ process.env.PROVENANCE_AUTO_DISABLE = 'yes'; // only the exact string "true" counts+ expect(autoProvenanceDisabled()).toBe(false);+ });+});++describe('autoCredentialForBytes', () => {+ it('signs and stores a credential that verifies as genuine', async () => {+ const envelope = await autoCredentialForBytes({+ buffer: GLB,+ assetId: 'creation-1',+ creator: 'client-abc',+ prompt: 'a brave knight',+ model: 'trellis_selfhost',+ provider: 'nvidia',+ });++ expect(envelope).toBeTruthy();+ expect(envelope.credential.glbSha256).toBe(sha256Hex(GLB));+ expect(envelope.credential.prompt).toBe('a brave knight');+ expect(verifyCredentialSignature(envelope.credential, envelope.signature, envelope.issuer)).toBe(true);++ const verdict = decideVerdict(sha256Hex(GLB), envelope);+ expect(verdict.status).toBe('verified');++ expect(putObjectMock).toHaveBeenCalledTimes(1);+ const [{ key, contentType }] = putObjectMock.mock.calls[0];+ expect(key).toBe(`provenance/${sha256Hex(GLB)}.json`);+ expect(contentType).toBe('application/json');+ });++ it('a single tampered byte fails verification against the stored credential', async () => {+ const envelope = await autoCredentialForBytes({ buffer: GLB, assetId: 'creation-1' });+ const tampered = Buffer.concat([GLB, Buffer.from('!')]);+ const verdict = decideVerdict(sha256Hex(tampered), envelope);+ expect(verdict.status).toBe('tampered');+ });++ it('skips (never throws) when the owner has disabled auto-credentialing', async () => {+ process.env.PROVENANCE_AUTO_DISABLE = 'true';+ const envelope = await autoCredentialForBytes({ buffer: GLB, assetId: 'creation-1' });+ expect(envelope).toBeNull();+ expect(putObjectMock).not.toHaveBeenCalled();+ });++ it('skips with an honest no-op when no issuer key is configured', async () => {+ delete process.env.ATTEST_AGENT_SECRET_KEY;+ const envelope = await autoCredentialForBytes({ buffer: GLB, assetId: 'creation-1' });+ expect(envelope).toBeNull();+ expect(putObjectMock).not.toHaveBeenCalled();+ });++ it('never re-issues a credential for bytes that already have one', async () => {+ headObjectMock.mockResolvedValue({ ContentLength: 1234 });+ const envelope = await autoCredentialForBytes({ buffer: GLB, assetId: 'creation-1' });+ expect(envelope).toBeNull();+ expect(putObjectMock).not.toHaveBeenCalled();+ });++ it('reports null, not a throw, when the store write fails', async () => {+ putObjectMock.mockRejectedValue(new Error('bucket unreachable'));+ await expect(autoCredentialForBytes({ buffer: GLB, assetId: 'creation-1' })).resolves.toBeNull();+ });++ it('no-ops on empty input', async () => {+ expect(await autoCredentialForBytes({})).toBeNull();+ expect(await autoCredentialForBytes({ buffer: Buffer.alloc(0) })).toBeNull();+ });+});++describe('ensureAutoCredential', () => {+ it('fetches the URL (SSRF-guarded) and credentials the bytes it gets back', async () => {+ fetchSafePublicUrlMock.mockResolvedValue({+ ok: true,+ arrayBuffer: async () => GLB.buffer.slice(GLB.byteOffset, GLB.byteOffset + GLB.byteLength),+ });++ const envelope = await ensureAutoCredential({ glbUrl: 'https://cdn.example.com/a.glb', assetId: 'x' });++ expect(fetchSafePublicUrlMock).toHaveBeenCalledWith(+ 'https://cdn.example.com/a.glb',+ expect.objectContaining({ redirect: 'follow' }),+ expect.anything(),+ );+ expect(envelope.credential.glbSha256).toBe(sha256Hex(GLB));+ });++ it('rejects a non-https URL without fetching anything', async () => {+ const envelope = await ensureAutoCredential({ glbUrl: 'http://insecure.example.com/a.glb' });+ expect(envelope).toBeNull();+ expect(fetchSafePublicUrlMock).not.toHaveBeenCalled();+ });++ it('is an honest no-op when the fetch fails', async () => {+ fetchSafePublicUrlMock.mockResolvedValue({ ok: false });+ const envelope = await ensureAutoCredential({ glbUrl: 'https://cdn.example.com/missing.glb' });+ expect(envelope).toBeNull();+ });+});