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
fix(forge): resolve the holder's real entitlement before the Game-Ready gate
nirholas95995c2481aa
diff --git a/docs/hold-to-access.md b/docs/hold-to-access.mdindex f9271262a..cc37175a1 100644--- a/docs/hold-to-access.md+++ b/docs/hold-to-access.md@@ -169,6 +169,50 @@ feature **Live** vs **Planned**, so the platform never promises an unwired perk.---+## Proving a holding from the browser++The server only ever sees what the page sends it, so a gated surface that mints its proof+from the wrong identity charges holders. **[`src/three-access.js`](../src/three-access.js)+is the one client module a gated surface may use.** It resolves both identities a holder+can arrive with:++| Identity | How the pass is minted | Prompt? |+|----------|------------------------|---------|+| Signed in, wallet linked to the account | `POST /api/three/tier-pass` with the session cookie | silent |+| Wallet connected, no account (Phantom, Seeker) | signs a domain-bound message, `POST { wallet, message, signature }` | one free signature |++Wire a gated request in three steps:++```js+import { getAccess, getTierPass, attachTierPass } from './three-access.js';++const { access } = (await getAccess('forge.gameready', { fresh: true })) || {};+// Interactive only when the read says this identity is eligible, so a non-holder is+// never asked to sign for something that could not unlock anything.+await getTierPass({ interactive: Boolean(access?.eligible) });+const res = await fetch('/api/forge-gameready', {+ method: 'POST',+ headers: attachTierPass({ 'content-type': 'application/json' }),+ body: JSON.stringify(payload),+});+```++Rules that keep the two identities from drifting apart:++- **Mint before the request, not on page load.** A pass lives 10 minutes; minting at the+ moment of the gated call is what guarantees the header is fresh.+- **Read access with `{ fresh: true }`, and re-read on `wallet:changed`.** Connecting or+ switching a wallet changes who is asking; the cached matrix is then the wrong identity's.+- **Never gate the UI on the client's answer.** The server is the only authority; the+ client read exists so the surface can state the viewer's real price up front instead of+ a generic pitch.++`src/three-tier-pass.js` is the earlier, session-only helper. It backs `<three-gate>`'s+access read and mints nothing for a connected wallet, so a surface that uses it to build+headers silently bills every account-less holder. Do not use it for a new gated request.++---+## Activation roadmapGoal: **drive $THREE demand** by activating registered-but-dormant perks. A perk is onlydiff --git a/src/forge-gameready.js b/src/forge-gameready.jsindex 0fbcfb538..e22ea7169 100644--- a/src/forge-gameready.js+++ b/src/forge-gameready.js@@ -20,7 +20,7 @@// price is whatever the server gate quotes — never hardcoded here.import { payForConsumption } from './forge-pay.js';-import { threeHeaders } from './three-tier-pass.js';+import { attachTierPass, getAccess, getTierPass } from './three-access.js';const resultPanel = document.getElementById('state-result');const viewer = document.getElementById('viewer');@@ -207,6 +207,7 @@ if (resultPanel && viewer && triggerBtn) {const statusEl = panel.querySelector('.gr-status');const deltaEl = panel.querySelector('.gr-delta');const downloadsEl = panel.querySelector('.gr-downloads');+ const payNote = panel.querySelector('.gr-pay-note');const state = {glbUrl: null,@@ -216,6 +217,7 @@ if (resultPanel && viewer && triggerBtn) {running: false,pollAbort: false,previewUrl: null, // retopologized GLB used by the wireframe preview+ access: null, // last resolved forge.gameready access payload};// ── Helpers ────────────────────────────────────────────────────────────────@@ -381,6 +383,41 @@ if (resultPanel && viewer && triggerBtn) {deltaEl.classList.add('is-shown');}+ // ── Entitlement ──────────────────────────────────────────────────────────+ // Two identities can hold $THREE here, and both must clear the gate: a signed-in+ // account with a linked wallet (mints its pass silently from the session), and a+ // visitor who has only connected a wallet (proves ownership by signing a free,+ // domain-bound message). The signature dialog is raised ONLY for a wallet the+ // access read already calls eligible, so a non-holder is never asked to sign for+ // something that could not unlock anyway.+ async function resolveAccess() {+ const data = await getAccess('forge.gameready', { fresh: true });+ state.access = data?.access || null;+ renderPayNote();+ return state.access;+ }++ // Mint (or reuse) the tier proof this very request will carry. Never throws:+ // both reads degrade to null, which just means the request goes out unproven and+ // the server answers with the normal hold-or-pay 402.+ async function primeTierProof() {+ const access = await resolveAccess();+ await getTierPass({ interactive: Boolean(access?.eligible) });+ }++ // The panel's footnote, told from what the viewer actually holds instead of the+ // generic pitch. Unresolved access keeps the neutral default already in the DOM.+ function renderPayNote() {+ if (!payNote || !state.access) return;+ if (state.access.eligible) {+ payNote.innerHTML = 'Your $THREE holding covers this. Game-Ready exports are free for you.';+ return;+ }+ const usd = Number(state.access.pay_per_use?.usd) || 0;+ const price = usd > 0 ? `$${usd.toFixed(2)} per export` : 'a one-time fee';+ payNote.innerHTML = `$THREE holders export free. Without a holding it is ${price}. <a href="/three-token">Hold $THREE →</a>`;+ }+// ── Network ──────────────────────────────────────────────────────────────function sleep(ms) {return new Promise((r) => setTimeout(r, ms));@@ -390,10 +427,9 @@ if (resultPanel && viewer && triggerBtn) {// Carry the holder's $THREE tier pass so an eligible holder clears the gate// (no payment); harmless / empty for everyone else. A non-holder attaches the// settled pay-per-export proof instead.- const threeHdrs = await threeHeaders();const res = await fetch('/api/forge-gameready', {method: 'POST',- headers: { 'content-type': 'application/json', ...CLIENT_HEADERS, ...threeHdrs },+ headers: attachTierPass({ 'content-type': 'application/json', ...CLIENT_HEADERS }),body: JSON.stringify({mesh_url: state.glbUrl,topology: state.topology,@@ -446,6 +482,9 @@ if (resultPanel && viewer && triggerBtn) {// user dismissed the payment. The price comes from the server gate — never// hardcoded — so it stays correct if the catalog price changes.async function startWithGate(formats) {+ // Prove the holding BEFORE the first attempt, so an eligible holder is never+ // shown a pay modal for an export their $THREE already covers.+ await primeTierProof();try {return await startExport(formats);} catch (err) {@@ -680,10 +719,20 @@ if (resultPanel && viewer && triggerBtn) {function openPanel(open) {panel.dataset.open = String(open);triggerBtn.setAttribute('aria-expanded', String(open));- if (open) panel.scrollIntoView({ behavior: 'smooth', block: 'nearest' });- else hideWireframe();+ if (open) {+ panel.scrollIntoView({ behavior: 'smooth', block: 'nearest' });+ // Read the viewer's entitlement while they pick settings, so the footnote+ // states their real price before they commit to the export.+ resolveAccess();+ } else hideWireframe();}+ // Connecting, switching, or disconnecting a wallet changes who is asking, so the+ // resolved entitlement is stale. Re-read it while the panel is on screen.+ window.addEventListener('wallet:changed', () => {+ if (panel.dataset.open === 'true') resolveAccess();+ });+triggerBtn.addEventListener('click', () => {openPanel(panel.dataset.open !== 'true');});diff --git a/src/forge-studio/forge-gameready.js b/src/forge-studio/forge-gameready.jsindex ef3c28248..9b8e20054 100644--- a/src/forge-studio/forge-gameready.js+++ b/src/forge-studio/forge-gameready.js@@ -20,7 +20,7 @@// price is whatever the server gate quotes — never hardcoded here.import { payForConsumption } from './forge-pay.js';-import { threeHeaders } from '../three-tier-pass.js';+import { attachTierPass, getAccess, getTierPass } from '../three-access.js';const resultPanel = document.getElementById('state-result');const viewer = document.getElementById('viewer');@@ -207,6 +207,7 @@ if (resultPanel && viewer && triggerBtn) {const statusEl = panel.querySelector('.gr-status');const deltaEl = panel.querySelector('.gr-delta');const downloadsEl = panel.querySelector('.gr-downloads');+ const payNote = panel.querySelector('.gr-pay-note');const state = {glbUrl: null,@@ -216,6 +217,7 @@ if (resultPanel && viewer && triggerBtn) {running: false,pollAbort: false,previewUrl: null, // retopologized GLB used by the wireframe preview+ access: null, // last resolved forge.gameready access payload};// ── Helpers ────────────────────────────────────────────────────────────────@@ -381,6 +383,41 @@ if (resultPanel && viewer && triggerBtn) {deltaEl.classList.add('is-shown');}+ // ── Entitlement ──────────────────────────────────────────────────────────+ // Two identities can hold $THREE here, and both must clear the gate: a signed-in+ // account with a linked wallet (mints its pass silently from the session), and a+ // visitor who has only connected a wallet (proves ownership by signing a free,+ // domain-bound message). The signature dialog is raised ONLY for a wallet the+ // access read already calls eligible, so a non-holder is never asked to sign for+ // something that could not unlock anyway.+ async function resolveAccess() {+ const data = await getAccess('forge.gameready', { fresh: true });+ state.access = data?.access || null;+ renderPayNote();+ return state.access;+ }++ // Mint (or reuse) the tier proof this very request will carry. Never throws:+ // both reads degrade to null, which just means the request goes out unproven and+ // the server answers with the normal hold-or-pay 402.+ async function primeTierProof() {+ const access = await resolveAccess();+ await getTierPass({ interactive: Boolean(access?.eligible) });+ }++ // The panel's footnote, told from what the viewer actually holds instead of the+ // generic pitch. Unresolved access keeps the neutral default already in the DOM.+ function renderPayNote() {+ if (!payNote || !state.access) return;+ if (state.access.eligible) {+ payNote.innerHTML = 'Your $THREE holding covers this. Game-Ready exports are free for you.';+ return;+ }+ const usd = Number(state.access.pay_per_use?.usd) || 0;+ const price = usd > 0 ? `$${usd.toFixed(2)} per export` : 'a one-time fee';+ payNote.innerHTML = `$THREE holders export free. Without a holding it is ${price}. <a href="/three-token">Hold $THREE →</a>`;+ }+// ── Network ──────────────────────────────────────────────────────────────function sleep(ms) {return new Promise((r) => setTimeout(r, ms));@@ -390,10 +427,9 @@ if (resultPanel && viewer && triggerBtn) {// Carry the holder's $THREE tier pass so an eligible holder clears the gate// (no payment); harmless / empty for everyone else. A non-holder attaches the// settled pay-per-export proof instead.- const threeHdrs = await threeHeaders();const res = await fetch('/api/forge-gameready', {method: 'POST',- headers: { 'content-type': 'application/json', ...CLIENT_HEADERS, ...threeHdrs },+ headers: attachTierPass({ 'content-type': 'application/json', ...CLIENT_HEADERS }),body: JSON.stringify({mesh_url: state.glbUrl,topology: state.topology,@@ -446,6 +482,9 @@ if (resultPanel && viewer && triggerBtn) {// user dismissed the payment. The price comes from the server gate — never// hardcoded — so it stays correct if the catalog price changes.async function startWithGate(formats) {+ // Prove the holding BEFORE the first attempt, so an eligible holder is never+ // shown a pay modal for an export their $THREE already covers.+ await primeTierProof();try {return await startExport(formats);} catch (err) {@@ -670,10 +709,20 @@ if (resultPanel && viewer && triggerBtn) {function openPanel(open) {panel.dataset.open = String(open);triggerBtn.setAttribute('aria-expanded', String(open));- if (open) panel.scrollIntoView({ behavior: 'smooth', block: 'nearest' });- else hideWireframe();+ if (open) {+ panel.scrollIntoView({ behavior: 'smooth', block: 'nearest' });+ // Read the viewer's entitlement while they pick settings, so the footnote+ // states their real price before they commit to the export.+ resolveAccess();+ } else hideWireframe();}+ // Connecting, switching, or disconnecting a wallet changes who is asking, so the+ // resolved entitlement is stale. Re-read it while the panel is on screen.+ window.addEventListener('wallet:changed', () => {+ if (panel.dataset.open === 'true') resolveAccess();+ });+triggerBtn.addEventListener('click', () => {openPanel(panel.dataset.open !== 'true');});diff --git a/tests/forge-gameready-gate.test.js b/tests/forge-gameready-gate.test.jsnew file mode 100644index 000000000..56fb9e590--- /dev/null+++ b/tests/forge-gameready-gate.test.js@@ -0,0 +1,177 @@+// @vitest-environment jsdom+//+// The Game-Ready export panel (src/forge-gameready.js) is $THREE hold-or-pay+// gated, and the proof it carries decides whether a real holder is charged. The+// panel used to mint that proof through the session-only helper, so a visitor+// who had connected a holding wallet without linking it to an account was billed+// the per-export fee their holding already covered. These tests pin the wiring+// that fixes it:+//+// 1. An eligible holder's export carries the x-three-tier-pass header, and the+// pass is minted interactively (a connected wallet signs) before the request.+// 2. An eligible holder is never shown the pay modal.+// 3. A non-holder is not asked to sign, hits the 402, pays once, and the retry+// carries the settled payment proof.+// 4. Opening the panel states the viewer's real price: free for a holder, the+// server-quoted per-export price for everyone else.+//+// three-access / forge-pay are mocked: this suite is about the panel's own gate+// wiring, not the access network or the payment modal.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++// Shared, hoisted so the vi.mock factories below can read it: `eligible` drives+// what the access read reports, and `pass` is the minted proof attachTierPass+// puts on a request (exactly the real module's contract).+const stub = vi.hoisted(() => ({ eligible: false, pass: null }));++vi.mock('../src/three-access.js', () => ({+ getAccess: vi.fn(async () => ({+ signed_in: false,+ wallet_linked: false,+ access: {+ feature: 'forge.gameready',+ label: 'Game-Ready export (Unity/Unreal retopo + PBR)',+ eligible: stub.eligible,+ pay_per_use: { action: 'forge.gameready', usd: 0.1 },+ },+ })),+ getTierPass: vi.fn(async () => {+ stub.pass = stub.eligible ? 'signed.tier.pass' : null;+ return stub.pass;+ }),+ attachTierPass: vi.fn((headers = {}) => {+ if (stub.pass) headers['x-three-tier-pass'] = stub.pass;+ return headers;+ }),+}));++vi.mock('../src/forge-pay.js', () => ({+ payForConsumption: vi.fn(async () => ({ ok: true, paymentId: 'pay_1', refId: 'ref_1' })),+}));++const GLB_URL = 'https://cdn.three.ws/models/knight.glb';++// The three elements src/forge-gameready.js mounts against on /forge.+function mountPage() {+ document.body.innerHTML = `+ <section id="state-result">+ <div id="viewer-shell"><model-viewer id="viewer"></model-viewer></div>+ <button id="forge-gameready-btn" aria-expanded="false"></button>+ </section>`;+}++// The forge POST bodies seen so far, newest last.+function exportPosts() {+ return global.fetch.mock.calls+ .filter(([url, init]) => String(url) === '/api/forge-gameready' && init?.method === 'POST')+ .map(([, init]) => ({ headers: init.headers, body: JSON.parse(init.body) }));+}++// Mount the panel with a live model selected. `serverStatus` decides how the+// first export attempt is answered, so a test can drive the 402 gate.+async function mountWithModel({ gate402 = false } = {}) {+ let attempts = 0;+ global.fetch = vi.fn(async (url, init) => {+ const u = String(url);+ // The panel reads the source GLB to size its poly budget; a non-ok read+ // leaves the default budget, which is all these tests need.+ if (u === GLB_URL) return { ok: false, status: 404, json: async () => ({}) };+ if (u === '/api/forge-gameready' && init?.method === 'POST') {+ attempts += 1;+ const paid = Boolean(JSON.parse(init.body).payment_id);+ if (gate402 && attempts === 1 && !paid) {+ return {+ ok: false,+ status: 402,+ json: async () => ({+ error: 'three_hold_required',+ message: 'Game-Ready export requires holding $THREE.',+ pay_per_use: { action: 'forge.gameready', usd: 0.1 },+ }),+ };+ }+ return { ok: true, status: 200, json: async () => ({ job_id: 'job_1' }) };+ }+ return { ok: true, status: 200, json: async () => ({ status: 'running' }) };+ });++ mountPage();+ await import('../src/forge-gameready.js');+ document.dispatchEvent(new CustomEvent('forge:model-ready', { detail: { glbUrl: GLB_URL, label: 'knight' } }));+ await vi.advanceTimersByTimeAsync(1);+}++beforeEach(() => {+ vi.useFakeTimers();+ vi.resetModules();+ vi.clearAllMocks();+ stub.eligible = false;+ stub.pass = null;+ // jsdom has no scrollIntoView, and the panel calls it on open.+ Element.prototype.scrollIntoView = vi.fn();+});++afterEach(() => {+ vi.useRealTimers();+ document.body.innerHTML = '';+});++describe('Game-Ready export gate', () => {+ it('carries the tier pass for an eligible holder and never opens the pay modal', async () => {+ stub.eligible = true;+ await mountWithModel();+ const { getTierPass } = await import('../src/three-access.js');+ const { payForConsumption } = await import('../src/forge-pay.js');++ document.querySelector('.gr-run').click();+ await vi.advanceTimersByTimeAsync(1);++ const posts = exportPosts();+ expect(posts).toHaveLength(1);+ expect(posts[0].headers['x-three-tier-pass']).toBe('signed.tier.pass');+ // Interactive: a connected wallet with no account signs to prove the holding.+ expect(getTierPass).toHaveBeenCalledWith({ interactive: true });+ expect(payForConsumption).not.toHaveBeenCalled();+ });++ it('never raises a signature prompt for a viewer who could not unlock anything', async () => {+ await mountWithModel();+ const { getTierPass } = await import('../src/three-access.js');++ document.querySelector('.gr-run').click();+ await vi.advanceTimersByTimeAsync(1);++ expect(getTierPass).toHaveBeenCalledWith({ interactive: false });+ expect(exportPosts()[0].headers['x-three-tier-pass']).toBeUndefined();+ });++ it('pays once on the 402 and retries with the settled proof', async () => {+ await mountWithModel({ gate402: true });+ const { payForConsumption } = await import('../src/forge-pay.js');++ document.querySelector('.gr-run').click();+ await vi.advanceTimersByTimeAsync(1);++ expect(payForConsumption).toHaveBeenCalledTimes(1);+ // The price is the server's quote, never a hardcoded client constant.+ expect(payForConsumption.mock.calls[0][0].usd).toBe(0.1);+ const posts = exportPosts();+ expect(posts).toHaveLength(2);+ expect(posts[1].body.payment_id).toBe('pay_1');+ expect(posts[1].body.ref_id).toBe('ref_1');+ });++ it('states the real price in the footnote when the panel opens', async () => {+ await mountWithModel();+ document.getElementById('forge-gameready-btn').click();+ await vi.advanceTimersByTimeAsync(1);+ expect(document.querySelector('.gr-pay-note').textContent).toContain('$0.10 per export');++ // Connecting a holding wallet re-reads the entitlement while the panel is open.+ stub.eligible = true;+ window.dispatchEvent(new CustomEvent('wallet:changed', { detail: { address: 'Wa11et' } }));+ await vi.advanceTimersByTimeAsync(1);+ expect(document.querySelector('.gr-pay-note').textContent).toContain('free for you');+ });+});