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(forge): make Tripo a house lane when TRIPO_API_KEY is set
nirholasbaee3fb2d75b
diff --git a/api/_lib/forge-provider-key.js b/api/_lib/forge-provider-key.jsindex 178f08b61..26db0b86f 100644--- a/api/_lib/forge-provider-key.js+++ b/api/_lib/forge-provider-key.js@@ -1,36 +1,65 @@-// BYOK key resolution for the geometry generation providers (Meshy / Tripo) —+// BYOK key resolution for the geometry generation providers (Meshy / Tripo),// shared by the /api/forge endpoint and the 3D Studio MCP server (/api/mcp-3d).//-// No platform key exists for these backends, so the key must come from the-// caller. Two real sources, in priority order:-// 1. An inline key on the request — header `x-forge-provider-key` (preferred,+// Most of these backends have no platform key: the key must come from the+// caller. Three possible sources, in priority order:+// 1. An inline key on the request, header `x-forge-provider-key` (preferred,// kept out of URLs/logs) or `provider_key` in the POST body. Used// transiently and never persisted.// 2. The signed-in user's stored, encrypted key (the dashboard BYOK store),// when the request carries a session cookie.-// Returns the plaintext key or null when none is available.+// 3. A house key: for the one provider configured in HOUSE_KEY_ENV (Tripo),+// the platform's own env-var key, billed through our credits like any+// other house lane. Checked last so a user's own key always wins.+// resolveProviderKey returns the plaintext key or null when none is available.import { getSessionUser } from './auth.js';import { sql } from './db.js';import { loadUserProviderKeys } from './provider-keys.js';-export async function resolveProviderKey(req, body, providerName) {+// Providers with a platform (house) key lane, mapped to the env var that+// carries it. Absent here, or unset in the environment, a provider behaves+// exactly as it always has: user-supplied keys only.+const HOUSE_KEY_ENV = {+ tripo: 'TRIPO_API_KEY',+};++async function resolveInlineOrUserKey(req, body, providerName) {const header = req.headers['x-forge-provider-key'];const inline =(typeof header === 'string' && header) ||(Array.isArray(header) && header[0]) ||(typeof body?.provider_key === 'string' ? body.provider_key : '');- if (inline && inline.trim()) return inline.trim();+ if (inline && inline.trim()) return { key: inline.trim(), source: 'inline' };try {const session = await getSessionUser(req);if (session?.id) {const [row] = await sql`SELECT provider_keys FROM users WHERE id = ${session.id}`;const keys = await loadUserProviderKeys(row?.provider_keys);- if (keys[providerName]) return keys[providerName];+ if (keys[providerName]) return { key: keys[providerName], source: 'user' };}} catch {- // No DB / no session — fall through to "no key".+ // No DB / no session, fall through to "no key".}- return null;+ return { key: null, source: null };+}++// Same priority order as resolveProviderKey, plus a `source` tag so callers+// that bill differently per source (forge.js's house-key credits gate) can+// tell a user's own key apart from the platform's.+export async function resolveProviderKeyWithSource(req, body, providerName) {+ const found = await resolveInlineOrUserKey(req, body, providerName);+ if (found.key) return found;++ const envVar = HOUSE_KEY_ENV[providerName];+ const houseKey = envVar ? process.env[envVar] : null;+ if (houseKey) return { key: houseKey, source: 'house' };++ return { key: null, source: null };+}++export async function resolveProviderKey(req, body, providerName) {+ const { key } = await resolveInlineOrUserKey(req, body, providerName);+ return key;}diff --git a/api/_lib/forge-tiers.js b/api/_lib/forge-tiers.jsindex 04f7bab63..4fb015115 100644--- a/api/_lib/forge-tiers.js+++ b/api/_lib/forge-tiers.js@@ -198,6 +198,10 @@ export const BACKENDS = Object.freeze({byok: 'tripo',provider: 'tripo',requiresEnv: Object.freeze([]),+ // When set, TRIPO_API_KEY turns Tripo into a house lane: the default+ // geometry engine on the High tier, billed through our own credits+ // like the other house lanes, with a user's own key still preferred.+ houseKeyEnv: 'TRIPO_API_KEY',polyControl: true,baseEta: 70,// Tripo bills credits per task type; texture/quad add-ons cost extra.@@ -704,12 +708,28 @@ export function freeLaneCandidates(p, tierId, userImages, subjectClass = null, creturn out;}+// A house-key lane (a BACKENDS entry with `houseKeyEnv` set) becomes the+// default for its path on the High tier only, when its env var is actually+// set and no free lane claimed the slot above it. Draft/standard are+// untouched, so the free-for-us policy there never changes. Today this+// applies only to Tripo on the geometry path (the only path with no free+// lane at all, per FREE_DEFAULT_FOR_TIERS/FREE_FALLBACK_FOR_PATH above), and+// is a no-op everywhere TRIPO_API_KEY is unset.+function houseDefaultForPath(p, tierId) {+ if (tierId !== 'high') return null;+ for (const b of Object.values(BACKENDS)) {+ if (b.houseKeyEnv && b.paths.includes(p) && process.env[b.houseKeyEnv]) return b.id;+ }+ return null;+}+// Resolve the default backend for a (path, tier) when the caller didn't name one.// Free-for-us policy: the first configured free lane in the candidate ordering,-// and only the paid standing default when NO free lane is live on this deployment.+// then a configured house-key lane for this path/tier, and only the paid+// standing default when neither is live on this deployment.function defaultBackendFor(p, tierId, userImages, subjectClass = null, country = null) {const candidates = freeLaneCandidates(p, tierId, userImages, subjectClass, country);- return candidates[0] || DEFAULT_BACKEND_FOR_PATH[p];+ return candidates[0] || houseDefaultForPath(p, tierId) || DEFAULT_BACKEND_FOR_PATH[p];}// Health-aware default resolver. Given a `health` map of laneId → 'ok' | 'down' |@@ -728,7 +748,7 @@ function defaultBackendFor(p, tierId, userImages, subjectClass = null, country =// would, so callers with no telemetry are unaffected.export function defaultBackendForHealthAware(p, tierId, userImages, health, subjectClass = null, country = null) {const candidates = freeLaneCandidates(p, tierId, userImages, subjectClass, country);- if (!candidates.length) return DEFAULT_BACKEND_FOR_PATH[p];+ if (!candidates.length) return houseDefaultForPath(p, tierId) || DEFAULT_BACKEND_FOR_PATH[p];const statusOf = (id) => health?.[id];const preferred = candidates.find((id) => {const s = statusOf(id);@@ -737,9 +757,9 @@ export function defaultBackendForHealthAware(p, tierId, userImages, health, subjif (preferred) return preferred;const usable = candidates.find((id) => statusOf(id) !== 'down');if (usable) return usable;- // Every free lane is confirmed down — fall to the paid default rather than- // dead-ending on a lane we know will fail.- return DEFAULT_BACKEND_FOR_PATH[p];+ // Every free lane is confirmed down. Fall to a configured house-key lane,+ // then the paid default, rather than dead-ending on a lane we know will fail.+ return houseDefaultForPath(p, tierId) || DEFAULT_BACKEND_FOR_PATH[p];}// `userImages: true` = the request carries caller-supplied reference images, so@@ -1025,6 +1045,11 @@ export function buildCatalog() {// hosted TRELLIS preview) — the UI must not offer it for photo input.user_images: b.userImages !== false,configured: backendIsConfigured(b.id),+ // True when this BYOK backend also has a platform house key configured+ // (currently only Tripo, via TRIPO_API_KEY): the picker can offer it as+ // an explicit choice billed through platform credits, with no key+ // prompt, while a caller who supplies their own key still uses it.+ house_key_available: Boolean(b.houseKeyEnv && process.env[b.houseKeyEnv]),blurb: b.blurb,// Voxel resolutions the lane accepts as the `resolution` request option.resolutions: b.id === 'trellis2' ? TRELLIS2_RESOLUTIONS : b.id === 'pixal3d' ? PIXAL3D_RESOLUTIONS : undefined,diff --git a/api/forge.js b/api/forge.jsindex 15ada74a6..0a03595f6 100644--- a/api/forge.js+++ b/api/forge.js@@ -94,7 +94,7 @@ import {HF_LANE_COOLDOWN_SECONDS,} from './_lib/forge-lane-health.js';import { isInlineImageRef } from './_lib/image-persist.js';-import { resolveProviderKey } from './_lib/forge-provider-key.js';+import { resolveProviderKey, resolveProviderKeyWithSource } from './_lib/forge-provider-key.js';import { validateForgeImage } from './_lib/forge-image-validate.js';import { encodeJobToken, decodeJobToken } from './_lib/forge-job-token.js';import {@@ -1252,9 +1252,12 @@ async function startJobWithBody(req, res, body) {}if (path === 'geometry' && !backendExplicit) {const defaultByok = BACKENDS[backendId]?.byok;- if (defaultByok && !(await resolveProviderKey(req, body, defaultByok))) {- path = 'image';- backendId = resolveBackendId({ path, tier, userImages: isImageMode, subjectClass, country });+ if (defaultByok) {+ const { key } = await resolveProviderKeyWithSource(req, body, defaultByok);+ if (!key) {+ path = 'image';+ backendId = resolveBackendId({ path, tier, userImages: isImageMode, subjectClass, country });+ }}}@@ -1288,6 +1291,20 @@ async function startJobWithBody(req, res, body) {const coldStartFor = laneColdStart;+ // House-key billing/gate awareness, resolved once, for Tripo only (the one+ // backend with a house-key lane right now): the SAME priority order (inline,+ // then user session, then house env var) the BYOK dispatch below uses, so the+ // $THREE gate and the actual dispatch always agree on who is paying. An+ // inline or user key here always wins; this only flips true when the request+ // falls through to the platform's own key, in which case the resolved key is+ // cached here so the dispatch below doesn't re-run the session/DB lookup.+ let usingTripoHouseKey = false;+ let resolvedTripoKey = null;+ if (BACKENDS[backendId]?.byok === 'tripo' && BACKENDS[backendId]?.houseKeyEnv) {+ resolvedTripoKey = await resolveProviderKeyWithSource(req, body, 'tripo');+ usingTripoHouseKey = resolvedTripoKey.source === 'house';+ }+// Content-addressed result cache (see _lib/forge-cache.js): a text→3D request// on a platform-keyed lane (never BYOK: that spends the caller's own account,// so it must never be replayed to a stranger) can be served instantly from a@@ -1341,7 +1358,7 @@ async function startJobWithBody(req, res, body) {// never gated, and internal cron seed jobs bypass it entirely.// requireFeatureAccess writes the 402 (three_hold_required) itself and returns// { ok:false }; on a holder it writes nothing and lets the job proceed.- if (tier.id === 'high' && BACKENDS[backendId]?.byok === false && !isInternalSeedRequest(req)) {+ if (tier.id === 'high' && (BACKENDS[backendId]?.byok === false || usingTripoHouseKey) && !isInternalSeedRequest(req)) {// Consumption lever: a non-holder may present a settled $THREE payment// (payment_id + the client nonce it was bound to) to satisfy the gate per// generation instead of holding. Validate it read-only here; the single-use@@ -1745,13 +1762,18 @@ async function startJobWithBody(req, res, body) {// A native 3D model emits mesh geometry directly: from the prompt// (text→geometry) or a single photo (image→3D): with no synthesized// intermediate view, so detail isn't capped by one image. These backends- // have no platform key; the caller supplies their own. Dispatch is a- // registry lookup on the backend's `byok` name (Replicate BYOK is handled- // on the image-intermediate path below: it speaks a different interface).+ // have no platform key, except Tripo when TRIPO_API_KEY is set (the house+ // lane, resolved above into resolvedTripoKey/usingTripoHouseKey so this+ // reuses it instead of re-querying). Dispatch is a registry lookup on the+ // backend's `byok` name (Replicate BYOK is handled on the image-intermediate+ // path below: it speaks a different interface).const byokProvider = BACKENDS[backendId].byok;const byokFactory = BYOK_PROVIDER_FACTORIES[byokProvider];if (byokFactory) {- const key = await resolveProviderKey(req, body, byokProvider);+ const key =+ byokProvider === 'tripo' && resolvedTripoKey+ ? resolvedTripoKey.key+ : await resolveProviderKey(req, body, byokProvider);if (!key) return needsKey(res, backendId);let gp;@@ -2748,10 +2770,12 @@ async function startJobWithBody(req, res, body) {message: err.message || 'The provider rejected this API key.',});}- if (err?.code === 'insufficient_credits' && BACKENDS[backendId]?.byok) {+ if (err?.code === 'insufficient_credits' && BACKENDS[backendId]?.byok && !usingTripoHouseKey) {// BYOK lane: the message names the CALLER'S own provider account, which- // they can act on: surface it. The platform's own paid lane falls through- // to the sanitized "temporarily unavailable" state below.+ // they can act on: surface it. The house-key Tripo lane and the platform's+ // own paid lane both fall through to the sanitized "temporarily+ // unavailable" state below, since it's the PLATFORM's account that's out+ // of credits, not the caller's: naming it here would be misleading.return json(res, 402, {error: 'insufficient_credits',message: err.message || 'The provider account is out of credits.',diff --git a/src/forge.js b/src/forge.jsindex 30b1bd54d..c1f0c9af5 100644--- a/src/forge.js+++ b/src/forge.js@@ -849,6 +849,7 @@ function buildEngineButtons() {btn.dataset.path = path;btn.dataset.backend = b.id;btn.dataset.byok = b.byok || '';+ btn.dataset.housekey = String(Boolean(b.house_key_available));btn.dataset.poly = String(Boolean(b.poly_control));// Text-only engines (the free NVIDIA TRELLIS preview) can't take photos;// updateEngineAvailability() disables them while reference views are set.@@ -856,10 +857,14 @@ function buildEngineButtons() {// BYOK engines carry a small key glyph so the picker shows at a glance// which lanes run on the user's own API key vs the free/included ones.const short = ENGINE_LABELS[b.id] || b.label;- btn.innerHTML = `<span class="eng-label">${short}</span> ${b.free ? ENGINE_FREE_PILL : ''}${b.byok ? ENGINE_KEY_SVG : ''}`;- const keyNote = b.byok ? ` · uses your own ${KEY_HINTS[b.byok]?.label || b.byok} key` : '';+ btn.innerHTML = `<span class="eng-label">${short}</span> ${b.free ? ENGINE_FREE_PILL : ''}${b.byok && !b.house_key_available ? ENGINE_KEY_SVG : ''}`;+ const keyNote = b.house_key_available+ ? ' · included, or bring your own key'+ : b.byok+ ? ` · uses your own ${KEY_HINTS[b.byok]?.label || b.byok} key`+ : '';const freeNote = b.free ? ' · free, no API key' : '';- btn.title = `${b.label} — ${b.blurb}${freeNote}${keyNote}`;+ btn.title = `${b.label}: ${b.blurb}${freeNote}${keyNote}`;// aria-label survives the dynamic title rewrites in updateEngineAvailability.btn.setAttribute('aria-label', `${short}${freeNote}${keyNote}`);btn.setAttribute('aria-pressed', String(b.id === selectedEngine.backend));@@ -963,6 +968,7 @@ function selectEngine(btn, silent) {path: btn.dataset.path,backend: btn.dataset.backend,byok: btn.dataset.byok || null,+ houseKeyAvailable: btn.dataset.housekey === 'true',polyControl: btn.dataset.poly === 'true',modly: btn.dataset.modly === '1',modelId: btn.dataset.modelId || null,@@ -987,7 +993,10 @@ function selectEngine(btn, silent) {for (let i = 0; i < slots.length; i++) renderSlot(i);}-// Show the key field only for BYOK engines, with provider-specific hint + link.+// Show the key field for BYOK engines, with provider-specific hint + link. A+// house-key lane (Tripo, when the platform key is configured) shows the same+// field but as an optional override, since the job runs on platform credits+// when it's left blank.function updateByokRow() {if (!els.byokRow) return;const byok = selectedEngine.byok;@@ -995,6 +1004,12 @@ function updateByokRow() {if (!byok) return;const hint = KEY_HINTS[byok];const name = hint?.label || byok;+ if (selectedEngine.houseKeyAvailable) {+ els.byokLabel.textContent = `${name} key (optional)`;+ els.providerKey.placeholder = `Your own ${name} API key, to use it instead of the included lane`;+ els.byokHint.innerHTML = `This engine is included, billed to your platform credits. Paste your own ${name} key here to use it instead${hint ? ` (<a href="${hint.url}" target="_blank" rel="noopener">get a key</a>)` : ''}.`;+ return;+ }els.byokLabel.textContent = `${name} key`;els.providerKey.placeholder = `Your ${name} API key (kept in this browser)`;els.byokHint.innerHTML = hint@@ -1027,11 +1042,17 @@ let _highAccess = null; // last resolved forge.high access payload (for the gate// The only combination the server actually $THREE-gates: High tier on a PLATFORM-keyed// backend. BYOK engines run on the caller's own vendor key, so the server exempts BYOK-// High (key-gated, not hold-gated) — and so must the client, or a non-holder with their-// own Meshy/Tripo/Rodin key would be wrongly blocked from High. Draft/Standard are never-// gated. Every client gate check keys on this, so the lock can never engage outside it.+// High (key-gated, not hold-gated), and so must the client, or a non-holder with their+// own Meshy/Tripo/Rodin key would be wrongly blocked from High. The one exception is a+// house-key lane (Tripo, when TRIPO_API_KEY is set): the server bills that the same as+// any other platform lane even though the backend is flagged `byok`, because the key+// running the job is ours, not the caller's, so the client gate must match (a caller+// who typed their own key still stays exempt; see updateByokRow's providerKey check+// below). Draft/Standard are never gated. Every client gate check keys on this.function highTierNeedsPass() {- return selectedTier === 'high' && !selectedEngine.byok && !selectedEngine.modly;+ if (selectedTier !== 'high' || selectedEngine.modly) return false;+ if (!selectedEngine.byok) return true;+ return Boolean(selectedEngine.houseKeyAvailable) && !providerKey;}function accessHost() {@@ -1213,7 +1234,8 @@ async function updatePerkLine() {// caller's own provider key. `_highAccess.eligible` reflects a resolved $THREE// hold, so a holder sees High as already unlocked.function costSegment(backend, tierMeta) {- if (backend.byok) return 'billed to your own key';+ const houseLane = backend.house_key_available && !providerKey;+ if (backend.byok && !houseLane) return 'billed to your own key';if (tierMeta.id === 'high') {return _highAccess?.eligible? '<span class="est-free">Free</span> · you hold $THREE'@@ -3930,6 +3952,12 @@ els.engine?.addEventListener('click', (e) => {els.providerKey?.addEventListener('input', () => {providerKey = els.providerKey.value.trim();els.providerKey.removeAttribute('aria-invalid');+ // Typing/clearing a key on a house-key lane (Tripo) flips whether High is+ // $THREE-gated for this request, so re-run the same check a tier/engine+ // switch triggers.+ if (selectedEngine.houseKeyAvailable && selectedTier === 'high') {+ reflectHighAccess('high', { silent: true });+ }});els.cancel.addEventListener('click', () => {diff --git a/tests/api/forge-provider-key.test.js b/tests/api/forge-provider-key.test.jsnew file mode 100644index 000000000..0b8034fb8--- /dev/null+++ b/tests/api/forge-provider-key.test.js@@ -0,0 +1,91 @@+// resolveProviderKeyWithSource: the priority order behind the Tripo house-key+// lane (inline header/body key, then the signed-in user's stored key, then a+// provider's house env var, last). resolveProviderKey (every other caller:+// regen-provider.js, the MCP studio tools) must keep returning just the key,+// unaffected by whether a house lane exists for that provider.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => null) }));+vi.mock('../../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));+vi.mock('../../api/_lib/provider-keys.js', () => ({+ loadUserProviderKeys: vi.fn(async () => ({})),+}));++import { getSessionUser } from '../../api/_lib/auth.js';+import { sql } from '../../api/_lib/db.js';+import { loadUserProviderKeys } from '../../api/_lib/provider-keys.js';+import { resolveProviderKey, resolveProviderKeyWithSource } from '../../api/_lib/forge-provider-key.js';++const priorKey = process.env.TRIPO_API_KEY;++function req(headers = {}) {+ return { headers };+}++beforeEach(() => {+ vi.mocked(getSessionUser).mockResolvedValue(null);+ vi.mocked(sql).mockResolvedValue([]);+ vi.mocked(loadUserProviderKeys).mockResolvedValue({});+ delete process.env.TRIPO_API_KEY;+});++afterEach(() => {+ if (priorKey === undefined) delete process.env.TRIPO_API_KEY;+ else process.env.TRIPO_API_KEY = priorKey;+});++describe('resolveProviderKeyWithSource', () => {+ it('an inline header key wins over everything, source:inline', async () => {+ process.env.TRIPO_API_KEY = 'house-key';+ const got = await resolveProviderKeyWithSource(req({ 'x-forge-provider-key': ' inline-key ' }), null, 'tripo');+ expect(got).toEqual({ key: 'inline-key', source: 'inline' });+ });++ it('an inline body key wins over the house key, source:inline', async () => {+ process.env.TRIPO_API_KEY = 'house-key';+ const got = await resolveProviderKeyWithSource(req(), { provider_key: 'body-key' }, 'tripo');+ expect(got).toEqual({ key: 'body-key', source: 'inline' });+ });++ it('the signed-in user key wins over the house key, source:user', async () => {+ process.env.TRIPO_API_KEY = 'house-key';+ vi.mocked(getSessionUser).mockResolvedValue({ id: 'u1' });+ vi.mocked(sql).mockResolvedValue([{ provider_keys: 'encrypted-blob' }]);+ vi.mocked(loadUserProviderKeys).mockResolvedValue({ tripo: 'user-key' });+ const got = await resolveProviderKeyWithSource(req(), null, 'tripo');+ expect(got).toEqual({ key: 'user-key', source: 'user' });+ });++ it('falls back to the house env var only when no inline/user key exists, source:house', async () => {+ process.env.TRIPO_API_KEY = 'house-key';+ const got = await resolveProviderKeyWithSource(req(), null, 'tripo');+ expect(got).toEqual({ key: 'house-key', source: 'house' });+ });++ it('returns null/null when nothing is available anywhere', async () => {+ delete process.env.TRIPO_API_KEY;+ const got = await resolveProviderKeyWithSource(req(), null, 'tripo');+ expect(got).toEqual({ key: null, source: null });+ });++ it('a provider with no house-key lane (meshy) never falls back to an env var', async () => {+ process.env.MESHY_API_KEY = 'should-never-be-read';+ const got = await resolveProviderKeyWithSource(req(), null, 'meshy');+ expect(got).toEqual({ key: null, source: null });+ delete process.env.MESHY_API_KEY;+ });+});++describe('resolveProviderKey (unchanged callers)', () => {+ it('never falls back to the house key: plain resolveProviderKey keeps returning null when unresolved', async () => {+ process.env.TRIPO_API_KEY = 'house-key';+ const key = await resolveProviderKey(req(), null, 'tripo');+ expect(key).toBeNull();+ });++ it('still returns an inline/user key exactly as before', async () => {+ const key = await resolveProviderKey(req({ 'x-forge-provider-key': 'abc' }), null, 'tripo');+ expect(key).toBe('abc');+ });+});diff --git a/tests/forge-high-gate-tripo-house.test.js b/tests/forge-high-gate-tripo-house.test.jsnew file mode 100644index 000000000..6595eb07a--- /dev/null+++ b/tests/forge-high-gate-tripo-house.test.js@@ -0,0 +1,119 @@+// Tripo house-key lane: the $THREE High-tier gate must track who actually+// pays for the job, not the backend's static `byok` flag.+//+// • TRIPO_API_KEY unset -> byte-for-byte today's BYOK behavior+// (needs_key, never the hold gate), same as every other BYOK backend.+// • TRIPO_API_KEY set, no caller key -> the house key pays: gated exactly+// like a platform backend (402 three_hold_required with no pass).+// • TRIPO_API_KEY set, caller supplies their own key -> the caller's key+// still wins and stays exempt from the gate (needs_key/dispatch path,+// never 402).+//+// Mirrors the harness in tests/forge-high-gate.test.js.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { Readable } from 'node:stream';++let forge;+const ORIGINAL_FETCH = globalThis.fetch;+const priorKey = process.env.TRIPO_API_KEY;++function mockRes() {+ return {+ statusCode: 200, _headers: {}, _body: '', _ended: false,+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },+ getHeader(k) { return this._headers[k.toLowerCase()]; },+ end(b) { this._body = b || ''; this._ended = true; },+ get json() { try { return JSON.parse(this._body); } catch { return null; } },+ };+}++function mockReq({ body = null, headers = {} } = {}) {+ const chunks = body != null ? [Buffer.from(JSON.stringify(body))] : [];+ const r = Readable.from(chunks);+ r.method = 'POST';+ r.url = '/api/forge';+ r.headers = { origin: 'http://localhost:3000', 'content-type': 'application/json', ...headers };+ return r;+}++beforeEach(async () => {+ vi.resetModules();+ process.env.NODE_ENV = 'development';+ delete process.env.HOLDER_PASS_SECRET;+ // Any dispatch past the gate hits this stub instead of the real network:+ // a fast, deterministic 401 so a non-gated request still resolves quickly.+ globalThis.fetch = vi.fn(async () => ({+ ok: false,+ status: 401,+ json: async () => ({ code: 1000, message: 'invalid key' }),+ }));+ forge = (await import('../api/forge.js')).default;+});++afterEach(() => {+ globalThis.fetch = ORIGINAL_FETCH;+ if (priorKey === undefined) delete process.env.TRIPO_API_KEY;+ else process.env.TRIPO_API_KEY = priorKey;+ vi.restoreAllMocks();+});++describe('POST /api/forge: Tripo house-key lane vs the $THREE gate', () => {+ it('TRIPO_API_KEY unset: High + tripo behaves exactly like any other BYOK backend', async () => {+ delete process.env.TRIPO_API_KEY;+ const res = mockRes();+ await forge(mockReq({ body: { prompt: 'a brass telescope', tier: 'high', backend: 'tripo' } }), res);+ expect(res.statusCode).not.toBe(402);+ expect(res.json?.error).not.toBe('three_hold_required');+ expect(res.json?.error).toBe('needs_key');+ });++ it('TRIPO_API_KEY set, no caller key: High + tripo is hold-gated like a platform lane', async () => {+ process.env.TRIPO_API_KEY = 'house-key-for-test';+ const res = mockRes();+ await forge(mockReq({ body: { prompt: 'a brass telescope', tier: 'high', backend: 'tripo' } }), res);+ expect(res.statusCode).toBe(402);+ expect(res.json.error).toBe('three_hold_required');+ });++ it('TRIPO_API_KEY set, caller supplies their own key: the caller key still wins, no gate', async () => {+ process.env.TRIPO_API_KEY = 'house-key-for-test';+ const res = mockRes();+ await forge(+ mockReq({+ body: { prompt: 'a brass telescope', tier: 'high', backend: 'tripo' },+ headers: { 'x-forge-provider-key': 'caller-own-key' },+ }),+ res,+ );+ expect(res.statusCode).not.toBe(402);+ expect(res.json?.error).not.toBe('three_hold_required');+ });++ it('TRIPO_API_KEY set: the High tier default backend for the geometry path becomes tripo', async () => {+ process.env.TRIPO_API_KEY = 'house-key-for-test';+ const { resolveBackendId } = await import('../api/_lib/forge-tiers.js');+ expect(resolveBackendId({ path: 'geometry', tier: 'high' })).toBe('tripo');+ expect(resolveBackendId({ path: 'geometry', tier: 'draft' })).not.toBe('tripo');+ expect(resolveBackendId({ path: 'geometry', tier: 'standard' })).not.toBe('tripo');+ });++ it('TRIPO_API_KEY unset: the High tier default backend for the geometry path stays meshy', async () => {+ delete process.env.TRIPO_API_KEY;+ const { resolveBackendId } = await import('../api/_lib/forge-tiers.js');+ expect(resolveBackendId({ path: 'geometry', tier: 'high' })).toBe('meshy');+ });++ it('catalog surfaces house_key_available only when TRIPO_API_KEY is set', async () => {+ delete process.env.TRIPO_API_KEY;+ const mod1 = await import('../api/_lib/forge-tiers.js');+ const catOff = mod1.buildCatalog();+ expect(catOff.backends.find((b) => b.id === 'tripo').house_key_available).toBe(false);++ vi.resetModules();+ process.env.TRIPO_API_KEY = 'house-key-for-test';+ const mod2 = await import('../api/_lib/forge-tiers.js');+ const catOn = mod2.buildCatalog();+ expect(catOn.backends.find((b) => b.id === 'tripo').house_key_available).toBe(true);+ });+});