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(orb): serve avatar, forge and deployment thumbnails through the same-origin /cdn/ proxy, not the raw r2.dev domain
nirholasa5a651f67dd2
diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.jsindex 77c743923..ca40872e9 100644--- a/api/_lib/forge-store.js+++ b/api/_lib/forge-store.js@@ -18,7 +18,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';import { randomUUID } from 'node:crypto';import { sql, isDbUnavailableError } from './db.js';import { databaseConfigured } from './env.js';-import { putObject, publicUrl, deleteObject, keyFromPublicUrl, objectStorageConfigured } from './r2.js';+import { putObject, cdnUrl, deleteObject, keyFromPublicUrl, normalizeStoredUrl, objectStorageConfigured } from './r2.js';import { recordDailyActivity, maybeAwardFirstCreation } from './streaks.js';import { recordGenerationEvent } from './forge-events.js';import { scoreGlbQuality } from './glb-quality.js';@@ -531,7 +531,11 @@ async function copyToBucket({ sourceUrl, key, fallbackContentType, maxBytes, com// `buffer` is the bytes actually stored, post-cleanup and post-compression, so// a caller that hashes or grades them is describing the asset users receive// rather than the provider's original, and does it without a second fetch.- return { bytes: buf.length, publicUrl: publicUrl(key), quality, compression, cleaned, pbr, fit, buffer: buf };+ // The URL handed back is the same-origin /cdn/ proxy, not the raw bucket+ // domain: a browser <img>/<model-viewer> consumer of this field is exactly+ // what Chrome's ORB blocked above, so every durable forge URL must be+ // ORB-safe the same way avatar thumbnails already are (thumbnailUrl()).+ return { bytes: buf.length, publicUrl: cdnUrl(key), quality, compression, cleaned, pbr, fit, buffer: buf };}function imageExtFor(url) {@@ -614,12 +618,12 @@ export function buildWebVariant({ buffer, creationId, keyPrefix }) {await sql`update forge_creationsset web_glb_key = ${key},- web_glb_url = ${publicUrl(key)},+ web_glb_url = ${cdnUrl(key)},web_size_bytes = ${result.outputBytes},updated_at = now()where id = ${creationId}`;- return { key, url: publicUrl(key), bytes: result.outputBytes };+ return { key, url: cdnUrl(key), bytes: result.outputBytes };}).catch((err) => {console.warn('[forge-store] web delivery variant failed:', err?.message);@@ -658,12 +662,12 @@ export function buildLodVariant({ buffer, creationId, keyPrefix }) {await sql`update forge_creationsset lod_glb_key = ${key},- lod_glb_url = ${publicUrl(key)},+ lod_glb_url = ${cdnUrl(key)},lod_levels = ${JSON.stringify(levels)},updated_at = now()where id = ${creationId}`;- return { key, url: publicUrl(key), levels };+ return { key, url: cdnUrl(key), levels };}).catch((err) => {console.warn('[forge-store] LOD chain variant failed:', err?.message);@@ -874,7 +878,7 @@ export async function attachPoster({ id, clientKey, body, contentType, ext }) {const key = `forge/${clientKey.slice(0, 12)}/${id}-poster.${ext}`;await putObject({ key, body, contentType, metadata: { source: 'forge-poster' } });- const url = publicUrl(key);+ const url = cdnUrl(key);const updated = await sql`update forge_creationsset preview_key = ${key}, preview_image_url = ${url}, updated_at = now()@@ -1287,9 +1291,9 @@ export async function listCreations({ clientKey, limit = 24 }) {id: r.id,prompt: r.prompt,aspect: r.aspect,- glb_url: r.glb_url,- web_glb_url: r.web_glb_url ?? null,- preview_image_url: r.preview_image_url,+ glb_url: normalizeStoredUrl(r.glb_url),+ web_glb_url: normalizeStoredUrl(r.web_glb_url) ?? null,+ preview_image_url: normalizeStoredUrl(r.preview_image_url),outcome: r.outcome,downloaded: r.downloaded,views_used: r.views_used ?? null,@@ -1345,9 +1349,9 @@ export async function listCreationsByUser({ userId, limit = 24, before } = {}) {id: r.id,type: 'model',prompt: r.prompt,- glbUrl: r.glb_url,- webGlbUrl: r.web_glb_url ?? null,- previewImageUrl: r.preview_image_url,+ glbUrl: normalizeStoredUrl(r.glb_url),+ webGlbUrl: normalizeStoredUrl(r.web_glb_url) ?? null,+ previewImageUrl: normalizeStoredUrl(r.preview_image_url),category: r.model_category ?? 'other',isRemix: Boolean(r.parent_creation_id),remixable: Boolean(r.remixable),@@ -1439,9 +1443,9 @@ export async function listShowcase({ limit = 12, voterKey = null, sort = 'fresh'return rows.map((r) => ({id: r.id,prompt: r.prompt,- glb_url: r.glb_url,- web_glb_url: r.web_glb_url ?? null,- preview_image_url: r.preview_image_url,+ glb_url: normalizeStoredUrl(r.glb_url),+ web_glb_url: normalizeStoredUrl(r.web_glb_url) ?? null,+ preview_image_url: normalizeStoredUrl(r.preview_image_url),views_used: r.views_used ?? null,multiview: r.multiview ?? null,backend: r.backend ?? null,@@ -1599,8 +1603,8 @@ export async function listRecentCreations({ limit = 24, before } = {}) {id: r.id,type: 'model',prompt: r.prompt,- glbUrl: r.glb_url,- previewImageUrl: r.preview_image_url,+ glbUrl: normalizeStoredUrl(r.glb_url),+ previewImageUrl: normalizeStoredUrl(r.preview_image_url),category: r.model_category ?? 'other',isRemix: Boolean(r.parent_creation_id),createdAt: r.created_at,@@ -1736,8 +1740,8 @@ export async function listRemixable({ limit = 24, before, category, q, sort } =return rows.map((r) => ({id: r.id,prompt: r.prompt,- glb_url: r.glb_url,- preview_image_url: r.preview_image_url,+ glb_url: normalizeStoredUrl(r.glb_url),+ preview_image_url: normalizeStoredUrl(r.preview_image_url),royaltyBps: r.remix_royalty_bps ?? 0,// Provenance + terms VISIBLE before remixing — but never leak the raw// payout wallet in the public feed; only whether royalties can route.@@ -1790,8 +1794,8 @@ export async function listMostRemixed({ limit = 10 } = {}) {return rows.map((r) => ({id: r.id,prompt: r.prompt,- glb_url: r.glb_url,- preview_image_url: r.preview_image_url,+ glb_url: normalizeStoredUrl(r.glb_url),+ preview_image_url: normalizeStoredUrl(r.preview_image_url),royaltyBps: r.remix_royalty_bps ?? 0,royaltyPayable: Boolean(r.creator_wallet_solana),remixable: Boolean(r.remixable),diff --git a/api/_lib/forge-thumbs.js b/api/_lib/forge-thumbs.jsindex e636c0397..46c95018f 100644--- a/api/_lib/forge-thumbs.js+++ b/api/_lib/forge-thumbs.js@@ -24,7 +24,7 @@// and a batch runner that aborts (refunding untouched claims) if chromium dies.import { sql } from './db.js';-import { putObject, publicUrl } from './r2.js';+import { putObject, cdnUrl } from './r2.js';import { thumbBackdropFor } from './avatar-thumbs.js';// 768² matches the avatar thumbnail size — crisp on retina cards, one PNG the@@ -173,7 +173,9 @@ export async function renderThumbnail({ id, glb_url: glbUrl }) {// Fill-only: only claim the preview slot if it is still empty, so a poster the// maker captured in the meantime always wins over a headless render.- const url = publicUrl(key);+ // Same-origin /cdn/ URL, not the raw bucket domain: a card's <img> loading+ // this preview must not hit Chrome's Opaque Response Blocking (ORB).+ const url = cdnUrl(key);const updated = await sql`UPDATE forge_creationsSET preview_image_url = ${url}, preview_key = ${key}, updated_at = now()diff --git a/api/_lib/r2.js b/api/_lib/r2.jsindex 141027101..4b5d118d8 100644--- a/api/_lib/r2.js+++ b/api/_lib/r2.js@@ -398,7 +398,29 @@ export function isLegacyOgThumbnailKey(thumbnailKey) {// not bare publicUrl(). See docs/avatar-thumbnails.md.export function thumbnailUrl(thumbnailKey) {if (!thumbnailKey || isLegacyOgThumbnailKey(thumbnailKey)) return null;- return cdnUrlOrNull(thumbnailKey);+ // keyFromPublicUrl() reads S3_PUBLIC_DOMAIN, which throws when object+ // storage isn't configured. cdnUrlOrNull() below needs no bucket domain+ // at all, so a thrown lookup here must not stop this read path from+ // still resolving the key through /cdn/.+ let key = thumbnailKey;+ try {+ key = keyFromPublicUrl(thumbnailKey) || thumbnailKey;+ } catch {+ // object storage unconfigured: fall through with the raw key.+ }+ return cdnUrlOrNull(key);+}++// A stored *_url column (forge_creations.preview_image_url, glb_url,+// web_glb_url) written before the fix that routed those writes through+// cdnUrl() still carries the raw public *.r2.dev domain. That domain trips+// Chrome's Opaque Response Blocking on an <img>/model-viewer load, so a read+// path serving one of these columns to a browser must normalize it here+// rather than return it verbatim. Anything already on cdnUrl()'s form, or an+// external URL (a caller's own reference image), passes through untouched.+export function normalizeStoredUrl(url) {+ const key = keyFromPublicUrl(url);+ return key ? cdnUrl(key) : url;}export function encodeR2Key(key) {diff --git a/api/deployments.js b/api/deployments.jsindex db788b7f8..46747f2c5 100644--- a/api/deployments.js+++ b/api/deployments.js@@ -25,7 +25,7 @@ import { sql, isDbUnavailableError } from './_lib/db.js';import { cors, json, method, error, serverError, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { cacheGet, cacheSet } from './_lib/cache.js';-import { publicUrl } from './_lib/r2.js';+import { cdnUrl } from './_lib/r2.js';import { CHAINS, CHAIN_BY_ID, tokenExplorerUrl, addressExplorerUrl } from './_lib/erc8004-chains.js';const FEED_TTL_S = 20; // feed page cache — registrations land in minutes, not seconds@@ -104,7 +104,8 @@ function decodeCursor(raw) {// Shape one feed row (EVM or Solana) into the public deployment event the client// renders. Pure. The `family` discriminator decides explorer-URL construction.-function shapeRow(r) {+// Exported for direct unit testing of the image-URL ORB fix below.+export function shapeRow(r) {if (r.family === 'solana') {const asset = r.asset || r.agent_id;return {@@ -115,7 +116,9 @@ function shapeRow(r) {agent_id: r.agent_id,name: r.name || null,description: r.description || null,- image: r.image || (r.image_key ? publicUrl(r.image_key) : null),+ // Same-origin /cdn/ URL, not the raw bucket domain: this feeds an <img>+ // in the deployments feed, so the raw r2.dev domain would ORB-block it.+ image: r.image || (r.image_key ? cdnUrl(r.image_key) : null),owner: r.owner || null,has_3d: !!r.has_3d,x402_support: !!r.x402_support,diff --git a/api/pulse.js b/api/pulse.jsindex b796452d1..d041275f7 100644--- a/api/pulse.js+++ b/api/pulse.js@@ -36,7 +36,7 @@ import { sql, isDbUnavailableError } from './_lib/db.js';import { cors, json, method, error, serverError, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { isUuid } from './_lib/validate.js';-import { publicUrlOrNull as r2PublicUrl } from './_lib/r2.js';+import { thumbnailUrl } from './_lib/r2.js';import { explorerTxUrl, explorerAccountUrl } from './_lib/avatar-wallet.js';import { cacheGet, cacheSet } from './_lib/cache.js';import { marketplaceFeeBps } from './_lib/marketplace-platform-fee.js';@@ -97,7 +97,7 @@ function decodeCursor(raw) {}const r2Url = (key, visible) =>- key && visible ? r2PublicUrl(key) : null;+ key && visible ? thumbnailUrl(key) : null;// Shape one DB row into the public pulse event the client renders. Pure.function shapeEvent(r) {diff --git a/tests/api/deployments-image-url.test.js b/tests/api/deployments-image-url.test.jsnew file mode 100644index 000000000..a9a1165fc--- /dev/null+++ b/tests/api/deployments-image-url.test.js@@ -0,0 +1,75 @@+/**+ * api/deployments.js: shapeRow() image URL (prompt-402 "console errors" work+ * order). A Solana row's `image_key` (aliased from `avatars.thumbnail_key`)+ * was turned into a browser-facing `image` URL with the raw bucket domain+ * (publicUrl), the exact guard-evading pattern tests/thumbnail-url-guard.js+ * misses because the variable is named `image_key`, not "...thumb...". That+ * raw domain trips Chrome's Opaque Response Blocking on an <img> load; the+ * same-origin /cdn/ proxy (cdnUrl) is the ORB-safe form every other avatar+ * thumbnail already uses.+ */+import { describe, it, expect } from 'vitest';+import { shapeRow } from '../../api/deployments.js';++describe('shapeRow: ORB-safe image URL', () => {+ it('routes a Solana row image_key through cdnUrl(), not the raw bucket domain', () => {+ const row = {+ family: 'solana',+ chain_id: 101,+ agent_id: 'mint-abc',+ asset: 'mint-abc',+ name: 'Agent',+ description: null,+ image: null,+ image_key: 'thumb/abc-123.png',+ owner: 'owner-wallet',+ has_3d: true,+ x402_support: false,+ registered_at: new Date().toISOString(),+ registered_tx: 'tx-abc',+ };+ const shaped = shapeRow(row);+ expect(shaped.image).toBe('https://three.ws/cdn/thumb/abc-123.png');+ expect(shaped.image).not.toMatch(/r2\.dev/);+ });++ it('passes through an already-absolute r.image untouched', () => {+ const row = {+ family: 'solana',+ chain_id: 101,+ agent_id: 'mint-def',+ asset: 'mint-def',+ name: 'Agent',+ description: null,+ image: 'https://example.com/already-absolute.png',+ image_key: 'thumb/should-be-ignored.png',+ owner: 'owner-wallet',+ has_3d: true,+ x402_support: false,+ registered_at: new Date().toISOString(),+ registered_tx: 'tx-def',+ };+ const shaped = shapeRow(row);+ expect(shaped.image).toBe('https://example.com/already-absolute.png');+ });++ it('is null when neither image nor image_key is set', () => {+ const row = {+ family: 'solana',+ chain_id: 101,+ agent_id: 'mint-ghi',+ asset: 'mint-ghi',+ name: 'Agent',+ description: null,+ image: null,+ image_key: null,+ owner: 'owner-wallet',+ has_3d: false,+ x402_support: false,+ registered_at: new Date().toISOString(),+ registered_tx: null,+ };+ const shaped = shapeRow(row);+ expect(shaped.image).toBeNull();+ });+});diff --git a/tests/forge-store-list-engine-version.test.js b/tests/forge-store-list-engine-version.test.jsindex be9a44325..5f8776e55 100644--- a/tests/forge-store-list-engine-version.test.js+++ b/tests/forge-store-list-engine-version.test.js@@ -32,6 +32,10 @@ vi.mock('../api/_lib/r2.js', () => ({publicUrl: (key) => `https://cdn.example.com/${key}`,deleteObject: vi.fn(async () => {}),keyFromPublicUrl: () => null,+ // listCreations now routes glb_url/web_glb_url/preview_image_url through+ // normalizeStoredUrl() (prompt-402 "console errors" work order); this+ // mock's rows already carry CDN-shaped URLs, so a passthrough is correct.+ normalizeStoredUrl: (url) => url,}));const { listCreations } = await import('../api/_lib/forge-store.js');diff --git a/tests/forge-store-listing-orb-safe.test.js b/tests/forge-store-listing-orb-safe.test.jsnew file mode 100644index 000000000..df68be69a--- /dev/null+++ b/tests/forge-store-listing-orb-safe.test.js@@ -0,0 +1,135 @@+/**+ * forge-store.js listing reads (prompt-402 "console errors" work order).+ *+ * glb_url / web_glb_url / preview_image_url are baked URL strings, written+ * once at creation time and returned verbatim by every listing read. A row+ * created before the write-path fix that routes those writes through+ * cdnUrl() still carries the raw public *.r2.dev bucket domain in the DB.+ * Chrome's Opaque Response Blocking rejects that domain on an <img> /+ * model-viewer load (net::ERR_BLOCKED_BY_ORB), confirmed live on /grok's+ * "Fresh from the Forge" strip (listShowcase, via GET /api/forge-gallery).+ *+ * Every browser-facing listing export must run each stored URL column+ * through normalizeStoredUrl() so an already-existing row self-heals at read+ * time, matching the thumbnailUrl() convention for thumbnail_key.+ */+import { describe, it, expect, vi, afterEach } from 'vitest';++Object.assign(process.env, {+ DATABASE_URL: 'postgres://test:test@localhost:5432/test',+ S3_ENDPOINT: 'https://s3.example.com',+ S3_BUCKET: 'test-bucket',+ S3_PUBLIC_DOMAIN: 'https://pub-legacy.r2.dev',+ S3_ACCESS_KEY_ID: 'test-key',+ S3_SECRET_ACCESS_KEY: 'test-secret',+ APP_ORIGIN: 'https://three.ws',+});++let rows = [];+const sqlMock = vi.fn(async () => rows);+vi.mock('../api/_lib/db.js', () => ({+ sql: (...args) => sqlMock(...args),+ isDbUnavailableError: () => false,+}));++vi.mock('../api/_lib/r2.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ putObject: vi.fn(async () => {}),+ deleteObject: vi.fn(async () => {}),+ objectStorageConfigured: () => true,+ publicUrl: actual.publicUrl,+ keyFromPublicUrl: actual.keyFromPublicUrl,+ normalizeStoredUrl: actual.normalizeStoredUrl,+ cdnUrl: actual.cdnUrl,+ };+});++const { listCreations, listCreationsByUser, listShowcase, listRecentCreations, listRemixable, listMostRemixed } =+ await import('../api/_lib/forge-store.js');+const { publicUrl, cdnUrl } = await import('../api/_lib/r2.js');++const LEGACY_GLB = publicUrl('forge/client-1/legacy.glb');+const LEGACY_PREVIEW = publicUrl('forge/thumb/legacy.png');++afterEach(() => {+ sqlMock.mockClear();+});++describe('forge-store listing reads normalize legacy raw-domain URLs', () => {+ it('listCreations: glb_url, web_glb_url, preview_image_url', async () => {+ rows = [{+ id: 'c1', prompt: 'x', aspect: null, glb_url: LEGACY_GLB, web_glb_url: LEGACY_GLB,+ preview_image_url: LEGACY_PREVIEW, outcome: 'generated', downloaded: false,+ views_used: null, multiview: false, backend: 'trellis', tier: 'standard', path: 'image',+ model_category: 'other', created_at: new Date().toISOString(),+ }];+ const [row] = await listCreations({ clientKey: 'client-1' });+ expect(row.glb_url).toBe(cdnUrl('forge/client-1/legacy.glb'));+ expect(row.web_glb_url).toBe(cdnUrl('forge/client-1/legacy.glb'));+ expect(row.preview_image_url).toBe(cdnUrl('forge/thumb/legacy.png'));+ expect(row.glb_url).not.toMatch(/r2\.dev/);+ });++ it('listCreationsByUser: glbUrl, previewImageUrl', async () => {+ rows = [{+ id: 'c2', prompt: 'x', glb_url: LEGACY_GLB, preview_image_url: LEGACY_PREVIEW,+ model_category: 'other', parent_creation_id: null, remixable: true,+ created_at: new Date().toISOString(),+ }];+ const [row] = await listCreationsByUser({ userId: 'user-1' });+ expect(row.glbUrl).toBe(cdnUrl('forge/client-1/legacy.glb'));+ expect(row.previewImageUrl).toBe(cdnUrl('forge/thumb/legacy.png'));+ });++ it('listShowcase: glb_url, web_glb_url, preview_image_url', async () => {+ rows = [{+ id: 'c3', prompt: 'x', glb_url: LEGACY_GLB, web_glb_url: LEGACY_GLB,+ preview_image_url: LEGACY_PREVIEW, views_used: null, multiview: false,+ backend: 'trellis', tier: 'standard', path: 'image', model_category: 'other',+ created_at: new Date().toISOString(), vote_count: 0, voted: false,+ x402_payer: null, x402_tx_sig: null, x402_price_atomic: null,+ }];+ const [row] = await listShowcase({});+ expect(row.glb_url).toBe(cdnUrl('forge/client-1/legacy.glb'));+ expect(row.web_glb_url).toBe(cdnUrl('forge/client-1/legacy.glb'));+ expect(row.preview_image_url).toBe(cdnUrl('forge/thumb/legacy.png'));+ });++ it('listRecentCreations: glbUrl, previewImageUrl', async () => {+ rows = [{+ id: 'c4', prompt: 'x', glb_url: LEGACY_GLB, web_glb_url: null,+ preview_image_url: LEGACY_PREVIEW, model_category: 'other',+ parent_creation_id: null, created_at: new Date().toISOString(),+ x402_payer: null, x402_tx_sig: null, x402_price_atomic: null,+ username: null, display_name: null, avatar_url: null,+ }];+ const [row] = await listRecentCreations({});+ expect(row.glbUrl).toBe(cdnUrl('forge/client-1/legacy.glb'));+ expect(row.previewImageUrl).toBe(cdnUrl('forge/thumb/legacy.png'));+ });++ it('listRemixable: glb_url, preview_image_url', async () => {+ rows = [{+ id: 'c5', prompt: 'x', glb_url: LEGACY_GLB, preview_image_url: LEGACY_PREVIEW,+ remix_royalty_bps: 500, creator_wallet_solana: null, parent_creation_id: null,+ lineage_index: 0, backend: 'trellis', model_category: 'other',+ created_at: new Date().toISOString(), remix_count: 0,+ owner_username: null, owner_display_name: null, owner_avatar_url: null,+ }];+ const [row] = await listRemixable({});+ expect(row.glb_url).toBe(cdnUrl('forge/client-1/legacy.glb'));+ expect(row.preview_image_url).toBe(cdnUrl('forge/thumb/legacy.png'));+ });++ it('listMostRemixed: glb_url, preview_image_url', async () => {+ rows = [{+ id: 'c6', prompt: 'x', glb_url: LEGACY_GLB, preview_image_url: LEGACY_PREVIEW,+ remix_royalty_bps: 0, creator_wallet_solana: null, remixable: true,+ model_category: 'other', created_at: new Date().toISOString(), remix_count: 3,+ }];+ const [row] = await listMostRemixed({});+ expect(row.glb_url).toBe(cdnUrl('forge/client-1/legacy.glb'));+ expect(row.preview_image_url).toBe(cdnUrl('forge/thumb/legacy.png'));+ });+});diff --git a/tests/forge-store-materialize.test.js b/tests/forge-store-materialize.test.jsindex 8e1090ebd..2a671eeea 100644--- a/tests/forge-store-materialize.test.js+++ b/tests/forge-store-materialize.test.js@@ -63,13 +63,29 @@ vi.mock('../api/_lib/r2.js', () => ({// mock has to carry it or every store call throws before it runs.objectStorageConfigured: () => true,publicUrl: (key) => `https://cdn.example.com/${key}`,+ // Every durable forge URL (glb, variants, previews) is a same-origin+ // /cdn/ URL, not the raw bucket domain (prompt-402 "console errors" work+ // order: a browser <img>/<model-viewer> loading the raw domain hits+ // Chrome's ORB or a bare CORS rejection). Kept at a different domain than+ // the publicUrl mock above so a test can tell the two apart.+ cdnUrl: (key) => `https://app.example.com/cdn/${key}`,}));vi.mock('../api/_lib/forge-events.js', () => ({recordGenerationEvent: vi.fn(async () => {}),}));-const { materializeCreation, buildLodVariant } = await import('../api/_lib/forge-store.js');+// The preview-image copy uses untrustedSource:true, which runs the real+// per-hop SSRF check (dns.lookup) before fetching. The stubbed `global.fetch`+// below never touches the network either way, but the SSRF pre-check would+// still do a real DNS lookup on the fake "provider.example" host, so it is+// stubbed out exactly like the network/db/object-storage boundaries above.+vi.mock('../api/_lib/ssrf-guard.js', () => ({+ assertSafePublicUrl: async () => {},+ SsrfBlockedError: class SsrfBlockedError extends Error {},+}));++const { materializeCreation, buildLodVariant, attachPoster } = await import('../api/_lib/forge-store.js');function stubFetch(buf) {global.fetch = vi.fn(async () => ({@@ -97,7 +113,7 @@ describe('materializeCreation — quality + compression (additive, opt-in)', ()clientKey: 'client-1',glbUrl: 'https://provider.example/fox.glb',});- expect(out.glbUrl).toBe(`https://cdn.example.com/forge/client-1/${existingRow.id}.glb`);+ expect(out.glbUrl).toBe(`https://app.example.com/cdn/forge/client-1/${existingRow.id}.glb`);expect(out.quality).toBeNull();expect(out.compression).toBeNull();// The geometry pass shrank the raw input.@@ -177,6 +193,42 @@ describe('materializeCreation — quality + compression (additive, opt-in)', ()expect(out.quality.valid).toBe(false);expect(out.quality.flag).toBe('invalid');});++ // prompt-402 "console errors" work order: the homepage and /grok rendered+ // their forge preview images straight from the raw r2.dev bucket domain,+ // which Chrome's Opaque Response Blocking refuses to load as an <img>.+ // Root cause: this write site handed back copyToBucket's publicUrl(key)+ // verbatim instead of routing it through cdnUrl() like every avatar+ // thumbnail already must (tests/thumbnail-url-guard.test.js). The variable+ // here is named `copied`/`preview`, not "...thumb...", so that guard's+ // regex never caught it.+ it('writes preview_image_url through cdnUrl(), not the raw bucket domain (ORB fix)', async () => {+ stubFetch(FOX_GLB);+ sqlMock.mockImplementationOnce(async () => [+ { ...existingRow, id: 'creation-preview', preview_image_url: 'https://provider.example/ref.jpg' },+ ]);+ const out = await materializeCreation({+ replicateJobId: 'job-preview',+ clientKey: 'client-1',+ glbUrl: 'https://provider.example/fox.glb',+ });+ expect(out.previewImageUrl).toBe('https://app.example.com/cdn/forge/client-1/creation-preview.jpg');+ });+});++describe('attachPoster: ORB-safe preview URL (prompt-402 "console errors" work order)', () => {+ it('writes preview_image_url through cdnUrl(), not the raw bucket domain', async () => {+ sqlMock.mockImplementationOnce(async () => [{ id: 'poster-1', preview_image_url: null }]);+ sqlMock.mockImplementationOnce(async () => [{ id: 'poster-1' }]);+ const url = await attachPoster({+ id: 'poster-1',+ clientKey: 'client-1',+ body: Buffer.from('fake-webp-bytes'),+ contentType: 'image/webp',+ ext: 'webp',+ });+ expect(url).toBe('https://app.example.com/cdn/forge/client-1/poster-1-poster.webp');+ });});describe('buildLodVariant: real MSFT_lod chain (prompt-071 "LOD and Engine QA" work order)', () => {@@ -189,7 +241,7 @@ describe('buildLodVariant: real MSFT_lod chain (prompt-071 "LOD and Engine QA" wconst out = await buildLodVariant({ buffer: FOX_GLB, creationId: existingRow.id, keyPrefix: `forge/client-1/${existingRow.id}` });expect(out).not.toBeNull();expect(out.key).toBe(`forge/client-1/${existingRow.id}.lod.glb`);- expect(out.url).toBe(`https://cdn.example.com/forge/client-1/${existingRow.id}.lod.glb`);+ expect(out.url).toBe(`https://app.example.com/cdn/forge/client-1/${existingRow.id}.lod.glb`);expect(out.levels.length).toBeGreaterThanOrEqual(2);for (let i = 1; i < out.levels.length; i++) {expect(out.levels[i].triangleCount).toBeLessThanOrEqual(out.levels[i - 1].triangleCount);diff --git a/tests/forge-thumbs.test.js b/tests/forge-thumbs.test.jsindex ec7a68aba..628b9d274 100644--- a/tests/forge-thumbs.test.js+++ b/tests/forge-thumbs.test.js@@ -27,6 +27,11 @@ const putObjectMock = vi.fn(async () => order.push('r2'));vi.mock('../api/_lib/r2.js', () => ({putObject: (...a) => putObjectMock(...a),publicUrl: (key) => `https://cdn.example/${key}`,+ // renderThumbnail persists this as a same-origin /cdn/ URL, not the raw+ // bucket domain (prompt-402 "console errors" work order: the raw domain+ // trips Chrome's ORB on an <img> load). Different domain than the+ // publicUrl mock above so a test can tell the two apart.+ cdnUrl: (key) => `https://app.example/cdn/${key}`,}));const renderGlbToPngMock = vi.fn(async () => Buffer.from('x'.repeat(5000)));@@ -65,7 +70,7 @@ describe('renderThumbnail', () => {const r = await renderThumbnail({ id: 'c-2', glb_url: 'https://cdn/y.glb' });expect(putObjectMock.mock.calls[0][0].key).toBe(forgeThumbKeyFor('c-2'));expect(r.key).toBe('forge/thumb/c-2.png');- expect(r.url).toBe('https://cdn.example/forge/thumb/c-2.png');+ expect(r.url).toBe('https://app.example/cdn/forge/thumb/c-2.png');expect(r.filled).toBe(true);// The UPDATE is fill-only — guarded by preview_image_url IS NULL.const upd = sqlCalls.find((c) => /UPDATE forge_creations/i.test(c.text));diff --git a/tests/forge-webhooks.test.js b/tests/forge-webhooks.test.jsindex 5593e7fe5..ef92a35b7 100644--- a/tests/forge-webhooks.test.js+++ b/tests/forge-webhooks.test.js@@ -74,6 +74,10 @@ vi.mock('../api/_lib/r2.js', () => ({putObject: vi.fn(async ({ key }) => ({ key })),objectStorageConfigured: () => true,publicUrl: (key) => `https://cdn.example.com/${key}`,+ // materializeCreation writes the delivered glb_url through cdnUrl(), not the+ // raw bucket domain (prompt-402 "console errors" work order), so this mock+ // has to carry it or the write throws before dispatchWebhooks ever runs.+ cdnUrl: (key) => `https://cdn.example.com/${key}`,}));vi.mock('../api/_lib/forge-events.js', () => ({diff --git a/tests/pulse-thumbnail-url.test.js b/tests/pulse-thumbnail-url.test.jsnew file mode 100644index 000000000..9954da4d6--- /dev/null+++ b/tests/pulse-thumbnail-url.test.js@@ -0,0 +1,34 @@+// /api/pulse avatar thumbnail URLs (prompt-402 "console errors" work order).+//+// `r2Url()` built every `avatar_thumbnail_url` in the Money Pulse feed, the+// agent wallet story, and the money-flow graph from `publicUrlOrNull()`: the+// raw `*.r2.dev` bucket domain. An <img> pointed at that domain trips Chrome's+// Opaque Response Blocking the moment the response's actual content doesn't+// match what an <img> tag expects (and ORBs outright on a 404's text/plain+// body for a since-deleted key). thumbnailUrl() is the ORB-safe, same-origin+// /cdn/ form every other avatar thumbnail already uses, and it additionally+// nulls out the legacy-poisoned *_og.png keys a stale cache bug once wrote+// (see isLegacyOgThumbnailKey() in api/_lib/r2.js).+//+// api/pulse.js has heavy top-level DB/cache dependencies, so (matching+// tests/pulse-marketplace-paid-filter.test.js) this pins the fix against the+// source text rather than importing the module.++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';++const SRC = readFileSync(fileURLToPath(new URL('../api/pulse.js', import.meta.url)), 'utf8');++describe('pulse avatar thumbnail URLs are ORB-safe', () => {+ it('imports thumbnailUrl from r2.js', () => {+ expect(SRC).toMatch(/import\s*\{[^}]*\bthumbnailUrl\b[^}]*\}\s*from\s*'\.\/_lib\/r2\.js'/);+ });++ it('builds r2Url() on thumbnailUrl(), not the raw bucket domain', () => {+ const def = SRC.match(/const r2Url = \([^)]*\) =>\s*\n?\s*[^\n;]+;/);+ expect(def, 'r2Url() helper should exist').toBeTruthy();+ expect(def[0]).toMatch(/thumbnailUrl\(/);+ expect(def[0]).not.toMatch(/r2PublicUrl\(|publicUrlOrNull\(/);+ });+});diff --git a/tests/r2-normalize-stored-url.test.js b/tests/r2-normalize-stored-url.test.jsnew file mode 100644index 000000000..aea0073d9--- /dev/null+++ b/tests/r2-normalize-stored-url.test.js@@ -0,0 +1,82 @@+/**+ * normalizeStoredUrl() (prompt-402 "console errors" work order).+ *+ * forge_creations.preview_image_url / glb_url / web_glb_url are baked URL+ * strings, written once at creation time and returned verbatim by every+ * listing read (listShowcase, listCreations, ...). Rows created before the+ * fix that routed those writes through cdnUrl() still carry the raw public+ * *.r2.dev domain, which trips Chrome's Opaque Response Blocking on an <img>+ * or model-viewer load. normalizeStoredUrl() is the read-time rewrite for+ * already-existing rows: it resolves a raw-domain URL back to its bucket key+ * (keyFromPublicUrl) and re-renders it through cdnUrl(), same convention as+ * thumbnailUrl() for thumbnail_key.+ */+import { describe, it, expect, beforeAll } from 'vitest';++beforeAll(() => {+ Object.assign(process.env, {+ S3_ENDPOINT: 'https://s3.example.com',+ S3_BUCKET: 'test-bucket',+ S3_PUBLIC_DOMAIN: 'https://pub-abc123.r2.dev',+ S3_ACCESS_KEY_ID: 'test-key',+ S3_SECRET_ACCESS_KEY: 'test-secret',+ APP_ORIGIN: 'https://three.ws',+ });+});++const { normalizeStoredUrl, thumbnailUrl, publicUrl, cdnUrl } = await import('../api/_lib/r2.js');++describe('normalizeStoredUrl', () => {+ it('rewrites a legacy raw-bucket-domain URL to the same-origin /cdn/ form', () => {+ const legacy = publicUrl('forge/thumb/abc-123.png');+ expect(legacy).toMatch(/^https:\/\/pub-abc123\.r2\.dev\//);+ expect(normalizeStoredUrl(legacy)).toBe(cdnUrl('forge/thumb/abc-123.png'));+ expect(normalizeStoredUrl(legacy)).not.toMatch(/r2\.dev/);+ });++ it('passes an already-cdnUrl() value through untouched', () => {+ const good = cdnUrl('forge/thumb/already-good.png');+ expect(normalizeStoredUrl(good)).toBe(good);+ });++ it('passes a caller-supplied external reference image through untouched', () => {+ expect(normalizeStoredUrl('https://replicate.delivery/pbxt/thing.png')).toBe(+ 'https://replicate.delivery/pbxt/thing.png',+ );+ });++ it('passes through null/undefined for a slot that was never filled', () => {+ expect(normalizeStoredUrl(null)).toBeNull();+ expect(normalizeStoredUrl(undefined)).toBeUndefined();+ });+});++// avatars.thumbnail_key is meant to hold a bare R2 key (see the+// `~ '^https?://'` guard in api/_lib/avatar-thumbs.js's own backfill query,+// which treats any absolute-URL value as legacy data to self-heal). A row+// backfill never reached still carries that raw-domain URL, and before this+// fix thumbnailUrl() only screened out the dead `*_og.png` subset of those,+// passing every other absolute URL straight through cdnUrl()'s+// already-resolved passthrough: a live, 200-rendering object still tripped+// Chrome's Opaque Response Blocking because it loaded on the bare r2.dev+// domain instead of the same-origin /cdn/ proxy.+describe('thumbnailUrl', () => {+ it('rewrites a legacy raw-bucket-domain thumbnail_key to the /cdn/ form', () => {+ const legacy = publicUrl('thumb/legacy-avatar.png');+ expect(thumbnailUrl(legacy)).toBe(cdnUrl('thumb/legacy-avatar.png'));+ expect(thumbnailUrl(legacy)).not.toMatch(/r2\.dev/);+ });++ it('still nulls out a legacy OG key', () => {+ expect(thumbnailUrl('https://three.ws/avatars/abc_og.png')).toBeNull();+ });++ it('still resolves a bare key the normal way', () => {+ expect(thumbnailUrl('thumb/bare-key.png')).toBe(cdnUrl('thumb/bare-key.png'));+ });++ it('still returns null for a falsy key', () => {+ expect(thumbnailUrl(null)).toBeNull();+ expect(thumbnailUrl('')).toBeNull();+ });+});