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: enhance widget privacy handling and export functionality
nirholas516cc90868da
diff --git a/api/widgets/oembed.js b/api/widgets/oembed.jsindex 8ca8016bc..efb286a83 100644--- a/api/widgets/oembed.js+++ b/api/widgets/oembed.js@@ -9,31 +9,31 @@* Discord, Slack) can render the widget inline.*/-import { sql } from '../_lib/db.js';-import { env } from '../_lib/env.js';-import { cors, wrap, error } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+import { env } from '../_lib/env.js';+import { cors, wrap, error } from '../_lib/http.js';const DEFAULT_W = 600;const DEFAULT_H = 600;-const THUMB_W = 1200;-const THUMB_H = 630;+const THUMB_W = 1200;+const THUMB_H = 630;const TYPE_DIMENSIONS = {- 'turntable': { width: 600, height: 600 },- 'animation-gallery': { width: 720, height: 720 },- 'talking-agent': { width: 420, height: 600 },- 'passport': { width: 480, height: 560 },- 'hotspot-tour': { width: 800, height: 600 },+ turntable: { width: 600, height: 600 },+ 'animation-gallery': { width: 720, height: 720 },+ 'talking-agent': { width: 420, height: 600 },+ passport: { width: 480, height: 560 },+ 'hotspot-tour': { width: 800, height: 600 },};export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;- const url = new URL(req.url, 'http://x');+ const url = new URL(req.url, 'http://x');const target = url.searchParams.get('url');const format = (url.searchParams.get('format') || 'json').toLowerCase();- const maxW = parseInt(url.searchParams.get('maxwidth') || '0', 10) || null;- const maxH = parseInt(url.searchParams.get('maxheight') || '0', 10) || null;+ const maxW = parseInt(url.searchParams.get('maxwidth') || '0', 10) || null;+ const maxH = parseInt(url.searchParams.get('maxheight') || '0', 10) || null;if (!target) return error(res, 400, 'invalid_request', 'url parameter required');@@ -43,32 +43,33 @@ export default wrap(async (req, res) => {const widget = await loadWidget(widgetId);if (!widget) return error(res, 404, 'not_found', 'widget not found');- const origin = env.APP_ORIGIN;+ const origin = env.APP_ORIGIN;const embedUrl = `${origin}/#widget=${widget.id}&kiosk=true`;- const pageUrl = `${origin}/w/${widget.id}`;+ const pageUrl = `${origin}/w/${widget.id}`;const thumbUrl = `${origin}/api/widgets/${widget.id}/og`;- const title = widget.name || 'Widget';+ const title = widget.name || 'Widget';const dims = TYPE_DIMENSIONS[widget.type] || { width: DEFAULT_W, height: DEFAULT_H };- const width = clamp(maxW || dims.width, 240, 1600);+ const width = clamp(maxW || dims.width, 240, 1600);const height = clamp(maxH || dims.height, 240, 1600);const iframe = `<iframe src="${escapeAttr(embedUrl)}" width="${width}" height="${height}" style="border:0;border-radius:12px;max-width:100%" allow="autoplay; xr-spatial-tracking; clipboard-write" sandbox="allow-scripts allow-same-origin allow-popups allow-forms" loading="lazy"></iframe>`;const payload = {- type: 'rich',- version: '1.0',- provider_name: '3D Agent',- provider_url: origin,+ type: 'rich',+ version: '1.0',+ provider_name: '3D Agent',+ provider_url: origin,title,- author_name: title,- author_url: pageUrl,- html: iframe,+ author_name: title,+ author_url: pageUrl,+ html: iframe,width,height,- thumbnail_url: thumbUrl,- thumbnail_width: THUMB_W,- thumbnail_height: THUMB_H,+ thumbnail_url: thumbUrl,+ thumbnail_width: THUMB_W,+ thumbnail_height: THUMB_H,+ cache_age: 900,};res.setHeader('cache-control', 'public, max-age=900');@@ -102,12 +103,17 @@ async function loadWidget(id) {function extractWidgetId(target) {let parsed;- try { parsed = new URL(target); } catch { return null; }+ try {+ parsed = new URL(target);+ } catch {+ return null;+ }const originStr = `${parsed.protocol}//${parsed.host}`;- const okOrigin = originStr === env.APP_ORIGIN- || /^https?:\/\/localhost(:\d+)?$/.test(originStr)- || /^https?:\/\/3d\.irish$/.test(originStr);+ const okOrigin =+ originStr === env.APP_ORIGIN ||+ /^https?:\/\/localhost(:\d+)?$/.test(originStr) ||+ /^https?:\/\/3d\.irish$/.test(originStr);if (!okOrigin) return null;const pathMatch = parsed.pathname.match(/^\/w\/([A-Za-z0-9_-]+)\/?$/);@@ -125,25 +131,23 @@ function clamp(n, lo, hi) {}function toXml(payload) {- const lines = Object.entries(payload).map(([k, v]) =>- ` <${k}>${escapeXml(String(v))}</${k}>`- );+ const lines = Object.entries(payload).map(([k, v]) => ` <${k}>${escapeXml(String(v))}</${k}>`);return `<?xml version="1.0" encoding="utf-8" standalone="yes"?>\n<oembed>\n${lines.join('\n')}\n</oembed>`;}function escapeXml(s) {return String(s)- .replace(/&/g, '&')- .replace(/</g, '<')- .replace(/>/g, '>')- .replace(/"/g, '"')- .replace(/'/g, ''');+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');}function escapeAttr(s) {return String(s)- .replace(/&/g, '&')- .replace(/"/g, '"')- .replace(/</g, '<')- .replace(/>/g, '>');+ .replace(/&/g, '&')+ .replace(/"/g, '"')+ .replace(/</g, '<')+ .replace(/>/g, '>');}diff --git a/api/widgets/og.js b/api/widgets/og.jsindex e6b3d0063..8b7b55d44 100644--- a/api/widgets/og.js+++ b/api/widgets/og.js@@ -9,25 +9,25 @@* preview. Falls back to a server-rendered SVG card on miss.*/-import { sql } from '../_lib/db.js';-import { getAvatar } from '../_lib/avatars.js';+import { sql } from '../_lib/db.js';+import { getAvatar } from '../_lib/avatars.js';import { cors, wrap } from '../_lib/http.js';-const CACHE_CARD = 'public, max-age=3600, s-maxage=86400';+const CACHE_CARD = 'public, max-age=3600, s-maxage=86400';const CACHE_REDIR = 'public, max-age=3600';const TYPE_LABEL = {- 'turntable': 'Turntable Showcase',+ turntable: 'Turntable Showcase','animation-gallery': 'Animation Gallery',- 'talking-agent': 'Talking Agent',- 'passport': 'ERC-8004 Passport',- 'hotspot-tour': 'Hotspot Tour',+ 'talking-agent': 'Talking Agent',+ passport: 'ERC-8004 Passport',+ 'hotspot-tour': 'Hotspot Tour',};export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;- const url = new URL(req.url, 'http://x');+ const url = new URL(req.url, 'http://x');const widgetId = url.searchParams.get('id');if (!widgetId) return sendNotFound(res);@@ -35,6 +35,14 @@ export default wrap(async (req, res) => {const widget = await loadWidget(widgetId);if (!widget) return sendNotFound(res);+ if (widget.is_public === false) {+ sendCardSvg(res, 200, CACHE_CARD, {+ name: 'Private widget',+ type: '3D Agent',+ });+ return;+ }+if (widget.avatar_id) {const avatar = await getAvatar({ id: widget.avatar_id });if (avatar?.thumbnail_url) {@@ -55,9 +63,9 @@ export default wrap(async (req, res) => {async function loadWidget(id) {try {const [row] = await sql`- select id, name, type, avatar_id+ select id, name, type, avatar_id, is_publicfrom widgets- where id = ${id} and is_public = true and deleted_at is null+ where id = ${id} and deleted_at is nulllimit 1`;return row || null;@@ -104,9 +112,9 @@ function truncate(s, n) {function escapeXml(s) {return String(s)- .replace(/&/g, '&')- .replace(/</g, '<')- .replace(/>/g, '>')- .replace(/"/g, '"')- .replace(/'/g, ''');+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');}diff --git a/api/widgets/page.js b/api/widgets/page.jsindex 68a91c15e..614bb7298 100644--- a/api/widgets/page.js+++ b/api/widgets/page.js@@ -9,36 +9,45 @@* and replace into the SPA viewer at /#widget=<id>.*/-import { sql } from '../_lib/db.js';-import { env } from '../_lib/env.js';-import { cors, wrap } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+import { env } from '../_lib/env.js';+import { cors, wrap } from '../_lib/http.js';const TYPE_LABEL = {- 'turntable': 'Turntable Showcase',+ turntable: 'Turntable Showcase','animation-gallery': 'Animation Gallery',- 'talking-agent': 'Talking Agent',- 'passport': 'ERC-8004 Passport',- 'hotspot-tour': 'Hotspot Tour',+ 'talking-agent': 'Talking Agent',+ passport: 'ERC-8004 Passport',+ 'hotspot-tour': 'Hotspot Tour',};export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;- const url = new URL(req.url, 'http://x');+ const url = new URL(req.url, 'http://x');const widgetId = url.searchParams.get('id');if (!widgetId) return notFound(res);const widget = await loadWidget(widgetId);if (!widget) return notFound(res);- const origin = env.APP_ORIGIN;- const pageUrl = `${origin}/w/${widget.id}`;+ const origin = env.APP_ORIGIN;+ const pageUrl = `${origin}/w/${widget.id}`;+ const ogUrl = `${origin}/api/widgets/${widget.id}/og`;++ if (widget.is_public === false) {+ res.statusCode = 200;+ res.setHeader('content-type', 'text/html; charset=utf-8');+ res.setHeader('cache-control', 'private, max-age=60');+ res.end(renderPrivateHtml({ pageUrl, ogUrl }));+ return;+ }+const embedUrl = `${origin}/#widget=${widget.id}&kiosk=true`;- const ogUrl = `${origin}/api/widgets/${widget.id}/og`;const oembedJs = `${origin}/api/widgets/oembed?url=${encodeURIComponent(pageUrl)}&format=json`;- const title = widget.name || 'Widget';- const typeLbl = TYPE_LABEL[widget.type] || 'Widget';- const desc = `${typeLbl} · embeddable 3D, no code. Powered by 3D Agent.`;+ const title = widget.name || 'Widget';+ const typeLbl = TYPE_LABEL[widget.type] || 'Widget';+ const desc = `${typeLbl} · embeddable 3D, no code. Powered by 3D Agent.`;res.statusCode = 200;res.setHeader('content-type', 'text/html; charset=utf-8');@@ -49,9 +58,9 @@ export default wrap(async (req, res) => {async function loadWidget(id) {try {const [row] = await sql`- select id, name, type, avatar_id+ select id, name, type, avatar_id, is_publicfrom widgets- where id = ${id} and is_public = true and deleted_at is null+ where id = ${id} and deleted_at is nulllimit 1`;return row || null;@@ -151,10 +160,62 @@ ${escapeJsonLd({</html>`;}+function renderPrivateHtml({ pageUrl, ogUrl }) {+ const title = 'Private widget';+ const desc = 'This widget is private.';+ return `<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <title>${title} — 3D Agent</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <meta name="description" content="${desc}">+ <meta name="robots" content="noindex, nofollow">+ <meta name="theme-color" content="#0a0a0a">++ <meta property="og:type" content="website">+ <meta property="og:site_name" content="3D Agent">+ <meta property="og:title" content="${title}">+ <meta property="og:description" content="${desc}">+ <meta property="og:url" content="${escapeAttr(pageUrl)}">+ <meta property="og:image" content="${escapeAttr(ogUrl)}">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">++ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:title" content="${title}">+ <meta name="twitter:description" content="${desc}">+ <meta name="twitter:image" content="${escapeAttr(ogUrl)}">++ <link rel="canonical" href="${escapeAttr(pageUrl)}">+ <link rel="shortcut icon" href="/favicon.ico">++ <style>+ html,body{margin:0;padding:0;background:#0a0a0a;color:#e0e0e0;font-family:Inter,system-ui,sans-serif;height:100%}+ main{display:grid;place-items:center;height:100vh;text-align:center;padding:2rem;gap:1rem}+ a{color:#8b5cf6;text-decoration:none}+ a:hover{text-decoration:underline}+ </style>+</head>+<body>+ <main>+ <h1>${title}</h1>+ <p>${desc} The owner hasn't shared it publicly.</p>+ <p><a href="/">Open 3D Agent</a></p>+ </main>+</body>+</html>`;+}+function escapeHtml(s) {- return String(s).replace(/[&<>"']/g, (c) => ({ '&':'&','<':'<','>':'>','"':'"',"'":''' }[c]));+ return String(s).replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}+function escapeAttr(s) {+ return escapeHtml(s);}-function escapeAttr(s) { return escapeHtml(s); }function escapeJsonLd(obj) {return JSON.stringify(obj, null, 2).replace(/</g, '\\u003c');}diff --git a/src/app.js b/src/app.jsindex 0afd80853..da8a6b2c3 100644--- a/src/app.js+++ b/src/app.js@@ -428,9 +428,11 @@ class App {if (this.viewer) this.viewer.dispose();this.viewerEl = this.viewerContainerEl;this.viewer = new Viewer(this.viewerEl, this.options);- this.editor = new Editor(this.viewer);- this.editor.attach();- window.VIEWER.editor = this.editor;+ if (!this.options.kiosk) {+ this.editor = new Editor(this.viewer);+ this.editor.attach();+ window.VIEWER.editor = this.editor;+ }window.VIEWER.viewer = this.viewer;return this.viewer;}@@ -539,10 +541,11 @@ class App {// Notify the editor of the new model so it can rebuild panelsif (this.editor) {+ const isString = typeof rootFile === 'string';this.editor.onContentChanged({- url: typeof rootFile === 'string' ? rootFile : null,- file: typeof rootFile === 'object' ? rootFile : null,- name: typeof rootFile === 'string' ? rootFile : rootFile.name,+ url: isString ? rootFile : null,+ file: isString ? null : rootFile,+ name: isString ? rootFile.split('/').pop().split('?')[0] : rootFile.name,});}diff --git a/src/editor/index.js b/src/editor/index.jsindex b8f2db361..ffbb0dd32 100644--- a/src/editor/index.js+++ b/src/editor/index.js@@ -30,7 +30,11 @@ export class Editor {this._attached = true;this.sceneExplorer.attach();this._addExportFolder();- this.session.onChange(() => this._updateExportLabel());+ this.session.onChange(() => {+ this._updateExportLabel();+ this._updateExportEnabled();+ });+ this._updateExportEnabled();}onContentChanged({ url = null, file = null, name = null } = {}) {@@ -81,6 +85,16 @@ export class Editor {this._exportCtrl.name(count > 0 ? `${base} (${count})` : base);}+ _updateExportEnabled() {+ if (!this._exportCtrl) return;+ const ready = this.session.isExportReady();+ const row = this._exportCtrl.__li || this._exportCtrl.domElement;+ if (row) {+ row.style.pointerEvents = ready ? '' : 'none';+ row.style.opacity = ready ? '' : '0.4';+ }+ }+async _exportGLB() {try {const bytes = await exportEditedGLB(this.session);diff --git a/src/editor/publish.js b/src/editor/publish.jsnew file mode 100644index 000000000..0b7383e26--- /dev/null+++ b/src/editor/publish.js@@ -0,0 +1,222 @@+/**+ * publishEditedGLB(session, opts)+ * -------------------------------+ * Turn an in-progress EditorSession into a live shareable widget:+ * 1. exportEditedGLB(session) → Uint8Array+ * 2. POST /api/avatars/presign → { storage_key, upload_url, headers }+ * 3. PUT upload_url with the bytes → R2+ * 4. POST /api/avatars → { avatar }+ * 5. POST /api/widgets → { widget }+ *+ * Transport-only: no UI, no auth redirects. On 401 any step throws+ * AuthRequiredError so the caller (task 04) can redirect to sign-in.+ */++import { exportEditedGLB } from './glb-export.js';++export const MAX_BYTES = 25 * 1024 * 1024;++// Mirrors public/studio/studio.js TYPE_DEFAULTS.turntable + BRAND_DEFAULTS.+// Kept local because public/studio/* is served verbatim (not bundled).+const TURNTABLE_DEFAULTS = Object.freeze({+ rotationSpeed: 0.5,+ autoRotate: true,+ showControls: true,+ background: '#0a0a0a',+ accent: '#8b5cf6',+});++export class AuthRequiredError extends Error {+ constructor() {+ super('auth required');+ this.name = 'AuthRequiredError';+ }+}++export class SizeTooLargeError extends Error {+ constructor(bytes, limit) {+ super(`${bytes} > ${limit}`);+ this.name = 'SizeTooLargeError';+ this.bytes = bytes;+ this.limit = limit;+ }+}++export class ExportFailedError extends Error {+ constructor(cause) {+ super(`export failed: ${cause?.message || cause}`);+ this.name = 'ExportFailedError';+ this.cause = cause;+ }+}++export class PublishError extends Error {+ constructor(step, status, body) {+ super(`${step} failed: ${status} ${body?.error_description || ''}`.trim());+ this.name = 'PublishError';+ this.step = step;+ this.status = status;+ this.body = body;+ }+}++export async function publishEditedGLB(+ session,+ {+ origin = location.origin,+ widgetType = 'turntable',+ widgetName,+ isPublic = true,+ config = {},+ onStep = () => {},+ } = {},+) {+ const displayName = widgetName || toDisplayName(session?.sourceName);++ // 1. Export+ onStep({ step: 'export', pct: 0 });+ let bytes;+ try {+ bytes = await exportEditedGLB(session);+ } catch (e) {+ throw new ExportFailedError(e);+ }+ if (!bytes || !bytes.byteLength) throw new ExportFailedError(new Error('empty buffer'));+ if (bytes.byteLength > MAX_BYTES) throw new SizeTooLargeError(bytes.byteLength, MAX_BYTES);+ onStep({ step: 'export', pct: 1 });++ // 2. Presign+ const presign = await postJson(+ `${origin}/api/avatars/presign`,+ {+ size_bytes: bytes.byteLength,+ content_type: 'model/gltf-binary',+ },+ 'presign',+ );+ onStep({ step: 'presign', pct: 1 });++ // 3. PUT upload (no credentials — presigned URL carries its own auth).+ await putWithProgress(presign.upload_url, bytes, presign.headers || {}, (pct) =>+ onStep({ step: 'upload', pct }),+ );++ // 4. Register avatar+ const avatarRes = await postJson(+ `${origin}/api/avatars`,+ {+ name: displayName,+ slug: toSlug(session?.sourceName),+ storage_key: presign.storage_key,+ content_type: 'model/gltf-binary',+ size_bytes: bytes.byteLength,+ visibility: isPublic ? 'unlisted' : 'private',+ source: 'upload',+ source_meta: { origin: 'editor-publish' },+ },+ 'register',+ (status, body) => {+ if (status === 413) throw new SizeTooLargeError(bytes.byteLength, MAX_BYTES);+ },+ );+ const avatar = avatarRes.avatar;+ onStep({ step: 'register', pct: 1 });++ // 5. Create widget+ const widgetConfig = { ...TURNTABLE_DEFAULTS, ...config };+ const widgetRes = await postJson(+ `${origin}/api/widgets`,+ {+ type: widgetType,+ name: displayName,+ avatar_id: avatar.id,+ config: widgetConfig,+ is_public: isPublic,+ },+ 'widget',+ );+ const widget = widgetRes.widget;+ onStep({ step: 'widget', pct: 1 });++ const page = `${origin}/w/${widget.id}`;+ const iframe = `<iframe src="${page}" width="600" height="600" style="border:0"></iframe>`;+ const element =+ `<script type="module" src="${origin}/dist-lib/agent-3d.js"></script>\n` ++ `<agent-3d src="${origin}/api/avatars/${avatar.id}" style="width:600px;height:600px"></agent-3d>`;++ return { widget, avatar, urls: { page, iframe, element } };+}++async function postJson(url, body, step, onStatus) {+ let res;+ try {+ res = await fetch(url, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ } catch (e) {+ throw new PublishError(step, 0, { error_description: e?.message || String(e) });+ }+ if (res.status === 401) throw new AuthRequiredError();+ const parsed = await safeJson(res);+ if (onStatus) onStatus(res.status, parsed);+ if (!res.ok) throw new PublishError(step, res.status, parsed);+ return parsed;+}++function putWithProgress(url, bytes, headers, onProgress) {+ return new Promise((resolve, reject) => {+ onProgress(0);+ const xhr = new XMLHttpRequest();+ xhr.open('PUT', url, true);+ for (const [k, v] of Object.entries(headers)) xhr.setRequestHeader(k, v);+ xhr.upload.onprogress = (e) => {+ if (e.lengthComputable) onProgress(Math.max(0, Math.min(1, e.loaded / e.total)));+ };+ xhr.onerror = () =>+ reject(new PublishError('upload', 0, { error_description: 'network error' }));+ xhr.onabort = () => reject(new PublishError('upload', 0, { error_description: 'aborted' }));+ xhr.onload = () => {+ if (xhr.status === 401) return reject(new AuthRequiredError());+ if (xhr.status >= 200 && xhr.status < 300) {+ onProgress(1);+ return resolve();+ }+ reject(+ new PublishError('upload', xhr.status, {+ error_description: xhr.responseText || '',+ }),+ );+ };+ xhr.send(bytes);+ });+}++async function safeJson(res) {+ try {+ return await res.json();+ } catch {+ return null;+ }+}++function toDisplayName(raw) {+ const s = String(raw || 'Model')+ .replace(/\.(glb|gltf)$/i, '')+ .trim();+ return (s || 'Model').slice(0, 120);+}++function toSlug(raw) {+ let base = String(raw || 'model')+ .replace(/\.(glb|gltf)$/i, '')+ .toLowerCase()+ .replace(/[^a-z0-9_-]+/g, '-')+ .replace(/-+/g, '-')+ .replace(/^[-_]+|[-_]+$/g, '');+ if (!base || !/^[a-z0-9]/.test(base)) base = `model${base ? '-' + base : ''}`;+ const suffix = Math.random().toString(36).slice(2, 8);+ return `${base}-${suffix}`.slice(0, 64).replace(/[-_]+$/, '');+}diff --git a/src/editor/session.js b/src/editor/session.jsindex 6960c0359..f6fa421b4 100644--- a/src/editor/session.js+++ b/src/editor/session.js@@ -28,15 +28,20 @@ export class EditorSession {this.sourceFile = file;this.sourceBuffer = null;this.sourceName =- name ||- (file && file.name) ||- (url ? url.split('/').pop().split('?')[0] : 'model');+ name || (file && file.name) || (url ? url.split('/').pop().split('?')[0] : 'model');this.materialEdits = {};this.transformEdits = {};this.visibilityEdits = {};+ if (!url && !file) {+ console.warn('[editor] no source — export disabled');+ }this._emit();}+ isExportReady() {+ return !!(this.sourceURL || this.sourceFile || this.sourceBuffer);+ }+onChange(fn) {this._listeners.add(fn);return () => this._listeners.delete(fn);