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: brain overhaul, notifications, rembg worker, login/register polish
nirholas549584039fe2
diff --git a/api/_lib/provider-keys.js b/api/_lib/provider-keys.jsindex 3e5448d8e..ab7c03526 100644--- a/api/_lib/provider-keys.js+++ b/api/_lib/provider-keys.js@@ -53,6 +53,7 @@ export async function decryptProviderKey(ciphertext) {export const BYOK_PROVIDERS = {anthropic: { label: 'Anthropic', prefix: 'sk-ant-', hint: 'console.anthropic.com/settings/keys' },openai: { label: 'OpenAI', prefix: 'sk-', hint: 'platform.openai.com/api-keys' },+ meshy: { label: 'Meshy AI', prefix: 'msy_', hint: 'www.meshy.ai/settings/api' },};// Load and decrypt all stored provider keys for a user.diff --git a/api/user/provider-keys.js b/api/user/provider-keys.jsindex 24d273ee1..9e43427c8 100644--- a/api/user/provider-keys.js+++ b/api/user/provider-keys.js@@ -1,6 +1,6 @@// GET /api/user/provider-keys — returns which keys are set (never returns values)// PATCH /api/user/provider-keys — set or clear individual provider keys-// body: { anthropic?: string | null, openai?: string | null }+// body: { anthropic?: string | null, openai?: string | null, meshy?: string | null }// null = delete that key; string = store encryptedimport { sql } from '../_lib/db.js';@@ -13,6 +13,7 @@ import { parse } from '../_lib/validate.js';const patchSchema = z.object({anthropic: z.string().min(1).max(512).nullable().optional(),openai: z.string().min(1).max(512).nullable().optional(),+ meshy: z.string().min(1).max(512).nullable().optional(),});export default wrap(async (req, res) => {diff --git a/pages/brain.html b/pages/brain.htmlindex 47bad02f7..98db8e314 100644--- a/pages/brain.html+++ b/pages/brain.html@@ -61,82 +61,23 @@<div class="br-persona-inner"><div class="br-persona-hero"><h1>Build Your Persona</h1>- <p>Define how your AI agent thinks, speaks, and behaves. Extract a structured persona and test it across models.</p>+ <p>Pick a starting point or describe your agent in plain English. Done in seconds.</p></div>- <div class="br-method-tabs" id="brMethodTabs">- <div class="br-method-tab active" data-method="interview">- <span class="br-method-tab-icon">✎</span>- <div class="br-method-tab-title">Guided Interview</div>- <div class="br-method-tab-desc">Answer targeted questions and let AI synthesize your voice</div>- </div>- <div class="br-method-tab" data-method="freeform">- <span class="br-method-tab-icon">✎</span>- <div class="br-method-tab-title">Freeform</div>- <div class="br-method-tab-desc">Paste a bio, description, tweets, or anything that captures a voice</div>- </div>- <div class="br-method-tab" data-method="manual">- <span class="br-method-tab-icon">⚙</span>- <div class="br-method-tab-title">Manual Edit</div>- <div class="br-method-tab-desc">Set tone, vocabulary, interests, and style fields directly</div>- </div>- </div>-- <!-- Interview method -->- <div class="br-interview active" id="brInterview">- <div id="brQuestions"></div>- <div class="br-actions">- <button class="br-btn br-btn-primary" id="brSynthesize" disabled>Synthesize Persona</button>- <button class="br-btn br-btn-ghost" id="brFillExample">Fill example</button>- </div>+ <!-- Quick-pick archetypes -->+ <div class="br-archetype-section">+ <div class="br-archetype-label">Pick a starting point</div>+ <div class="br-archetype-grid" id="brArchetypeGrid"></div></div>- <!-- Freeform method -->- <div class="br-freeform" id="brFreeform">- <textarea class="br-freeform-area" id="brFreeformText" placeholder="Paste a bio, a collection of tweets, a LinkedIn summary, a Reddit comment history, or just describe the personality you want in plain English... The more context you provide, the richer the extracted persona will be." rows="8"></textarea>- <div class="br-freeform-hint">Tip: paste real writing samples for the most authentic extraction</div>- <div class="br-actions">- <button class="br-btn br-btn-primary" id="brFreeformSynth" disabled>Synthesize Persona</button>- </div>- </div>-- <!-- Manual edit method -->- <div class="br-freeform" id="brManual">- <div class="br-pc-edit-body" style="padding:0">- <div class="br-edit-row">- <label class="br-edit-label" for="brManTone">Tone</label>- <input class="br-edit-input" id="brManTone" placeholder="Warm but direct, slightly sardonic" />- </div>- <div class="br-edit-row">- <label class="br-edit-label" for="brManStyle">Communication Style</label>- <select class="br-agent-select" id="brManStyle" style="width:100%">- <option value="terse">Terse</option>- <option value="detailed">Detailed</option>- <option value="playful">Playful</option>- <option value="analytical">Analytical</option>- <option value="warm" selected>Warm</option>- </select>- </div>- <div class="br-edit-row">- <label class="br-edit-label" for="brManVocab">Vocabulary</label>- <input class="br-edit-input" id="brManVocab" placeholder="Comma-separated words or phrases" />- <span class="br-edit-hint">Words and phrases this persona uses often</span>- </div>- <div class="br-edit-row">- <label class="br-edit-label" for="brManInterests">Interests</label>- <input class="br-edit-input" id="brManInterests" placeholder="Comma-separated interests" />- </div>- <div class="br-edit-row">- <label class="br-edit-label" for="brManDont">Don't Say</label>- <input class="br-edit-input" id="brManDont" placeholder="Phrases to avoid, comma-separated" />- </div>- <div class="br-edit-row">- <label class="br-edit-label" for="brManGreet">Sample Greeting</label>- <textarea class="br-edit-textarea" id="brManGreet" placeholder="A greeting in the persona's voice" rows="2"></textarea>- </div>- </div>+ <!-- Describe input -->+ <div class="br-describe-section">+ <div class="br-describe-divider"><span>or describe your agent</span></div>+ <textarea class="br-describe-input" id="brDescribeInput"+ placeholder="A sharp crypto trader who speaks plainly and hates buzzwords. Direct, a little sardonic, always on-chain."+ rows="3"></textarea><div class="br-actions">- <button class="br-btn br-btn-primary" id="brManualSave">Set Persona</button>+ <button class="br-btn br-btn-primary" id="brDescribeGenerate" disabled>Generate Persona</button></div></div>diff --git a/public/brain.css b/public/brain.cssindex b327df967..20097a2ed 100644--- a/public/brain.css+++ b/public/brain.css@@ -252,98 +252,96 @@ body {margin: 0 auto;}-/* Method selector */-.br-method-tabs {+/* Archetype quick-picks */+.br-archetype-section {display: flex;- gap: 12px;- justify-content: center;+ flex-direction: column;+ gap: 14px;}-.br-method-tab {- flex: 1;- max-width: 260px;- background: #0c0c0c;- border: 1.5px solid var(--bg-1);- border-radius: 14px;- padding: 20px;- cursor: pointer;- transition: all 0.18s;+.br-archetype-label {+ font-size: 11.5px;+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.1em;+ color: #4a4a6a;text-align: center;}-.br-method-tab:hover { border-color: #303030; background: #121212; }-.br-method-tab.active { border-color: #ffffff; background: #0d0d0d; }-.br-method-tab-icon { font-size: 24px; margin-bottom: 8px; display: block; color: #ffffff; }-.br-method-tab-title { font-size: 14px; font-weight: 600; color: #dde0f0; margin-bottom: 4px; }-.br-method-tab-desc { font-size: 12px; color: #6b70a0; line-height: 1.5; }--/* Interview flow */-.br-interview { display: none; }-.br-interview.active { display: flex; flex-direction: column; gap: 16px; }--.br-q-card {+.br-archetype-grid {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 10px;+}+.br-archetype-chip {background: #0c0c0c;- border: 1.5px solid var(--bg-1);- border-radius: 14px;- padding: 20px 22px;+ border: 1.5px solid #1c1c2a;+ border-radius: 12px;+ padding: 14px 16px;+ cursor: pointer;+ text-align: left;+ transition: border-color 0.15s, background 0.15s, transform 0.1s;display: flex;flex-direction: column;- gap: 10px;- transition: border-color 0.2s;+ gap: 4px;}-.br-q-card:focus-within { border-color: #2a3060; }-.br-q-num {- font-size: 11px;- font-weight: 700;- text-transform: uppercase;- letter-spacing: 0.1em;- color: #ffffff;+.br-archetype-chip:hover {+ border-color: #3a3a5a;+ background: #101018;+ transform: translateY(-1px);}-.br-q-text {- font-size: 15px;- font-weight: 500;+.br-archetype-chip.selected {+ border-color: #ffffff;+ background: #0e0e1a;+}+.br-archetype-chip-label {+ font-size: 13px;+ font-weight: 600;color: #dde0f0;- line-height: 1.4;+ display: block;}-.br-q-input {- width: 100%;- background: #080808;- border: 1px solid var(--bg-1);- border-radius: 10px;- color: var(--ink);- font: inherit;- font-size: 14px;- padding: 12px 14px;- resize: vertical;- min-height: 56px;- outline: none;- transition: border-color 0.15s;+.br-archetype-chip-desc {+ font-size: 11.5px;+ color: #5a5a7a;+ display: block;+ line-height: 1.4;}-.br-q-input:focus { border-color: #3050a0; }-.br-q-input::placeholder { color: #3d3d3d; }-/* Freeform input */-.br-freeform { display: none; }-.br-freeform.active { display: flex; flex-direction: column; gap: 14px; }-.br-freeform-area {+/* Describe input section */+.br-describe-section {+ display: flex;+ flex-direction: column;+ gap: 14px;+}+.br-describe-divider {+ display: flex;+ align-items: center;+ gap: 12px;+ color: #3a3a5a;+ font-size: 12px;+}+.br-describe-divider::before,+.br-describe-divider::after {+ content: '';+ flex: 1;+ height: 1px;+ background: #1c1c2a;+}+.br-describe-input {width: 100%;- min-height: 160px;background: #0c0c0c;- border: 1.5px solid var(--bg-1);+ border: 1.5px solid #1c1c2a;border-radius: 14px;color: var(--ink);font: inherit;font-size: 14px;- padding: 18px 20px;+ padding: 16px 18px;resize: vertical;+ min-height: 80px;outline: none;transition: border-color 0.15s;+ line-height: 1.55;}-.br-freeform-area:focus { border-color: #3050a0; }-.br-freeform-area::placeholder { color: #3d3d3d; }-.br-freeform-hint {- font-size: 12.5px;- color: #4a4a4a;- text-align: center;-}+.br-describe-input:focus { border-color: #3050a0; }+.br-describe-input::placeholder { color: #3a3a4a; }/* Action row */.br-actions {@@ -968,8 +966,7 @@ body {@media (max-width: 900px) {.br-side { display: none; }.br-persona-inner { padding: 20px 16px 60px; }- .br-method-tabs { flex-direction: column; }- .br-method-tab { max-width: none; }+ .br-archetype-grid { grid-template-columns: repeat(2, 1fr); }.br-pc-body { grid-template-columns: 1fr; }.br-play-bar { padding: 8px 12px; }.br-chat-msgs { padding: 16px; }diff --git a/public/login.html b/public/login.htmlindex 3b9220f3c..f80b02346 100644--- a/public/login.html+++ b/public/login.html@@ -340,6 +340,17 @@padding: 0; text-decoration: underline; text-underline-offset: 2px; width: auto;}.privy-back-link:hover { color: #888; }+ .privy-wallet-divider { margin: 10px 0 8px; text-align: center; font-size: 11px; color: #555; letter-spacing: 0.04em; }+ #privy-wallet-btn {+ width: 100%; margin: 0; padding: 10px 16px;+ background: transparent; border: 1px solid rgba(255,255,255,0.12);+ border-radius: 10px; color: #ccc; font-size: 14px; font-weight: 500;+ cursor: pointer; display: flex; align-items: center; justify-content: center;+ gap: 8px; transition: background 0.12s, border-color 0.12s, color 0.12s;+ }+ #privy-wallet-btn:hover:not(:disabled) { background: rgba(255,255,255,0.06); border-color: rgba(255,255,255,0.22); color: #fff; }+ #privy-wallet-btn:disabled { opacity: 0.4; cursor: default; }+ #privy-wallet-status { margin: 6px 0 0; font-size: 12px; color: #888; }/* ── No-wallet welcome banner ── */.no-wallet-hint {@@ -546,7 +557,15 @@<button type="button" id="privy-verify-btn" class="privy-row-btn">Verify</button></div></div>- <p id="privy-inline-err" hidden></p>+ <div id="privy-wallet-wrap">+ <p class="privy-wallet-divider">or</p>+ <button type="button" id="privy-wallet-btn">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/></svg>+ Connect Wallet+ </button>+ <p id="privy-wallet-status" hidden></p>+ </div>+ <p id="privy-inline-err" hidden></p><button type="button" id="privy-back-btn" class="privy-back-link">← Back</button></div></div>diff --git a/public/register.html b/public/register.htmlindex 8f467c5ca..dde47f41c 100644--- a/public/register.html+++ b/public/register.html@@ -425,6 +425,17 @@padding: 0; text-decoration: underline; text-underline-offset: 2px; width: auto;}.privy-back-link:hover { color: #888; }+ .privy-wallet-divider { margin: 10px 0 8px; text-align: center; font-size: 11px; color: #555; letter-spacing: 0.04em; }+ #privy-wallet-btn {+ width: 100%; margin: 0; padding: 10px 16px;+ background: transparent; border: 1px solid rgba(0,0,0,0.12);+ border-radius: 10px; color: #444; font-size: 14px; font-weight: 500;+ cursor: pointer; display: flex; align-items: center; justify-content: center;+ gap: 8px; transition: background 0.12s, border-color 0.12s, color 0.12s;+ }+ #privy-wallet-btn:hover:not(:disabled) { background: rgba(0,0,0,0.04); border-color: rgba(0,0,0,0.22); color: #000; }+ #privy-wallet-btn:disabled { opacity: 0.4; cursor: default; }+ #privy-wallet-status { margin: 6px 0 0; font-size: 12px; color: #888; }</style><meta name="description" content="Create a new three.ws account.">@@ -469,6 +480,14 @@<button type="button" id="privy-verify-btn" class="privy-row-btn">Verify</button></div></div>+ <div id="privy-wallet-wrap">+ <p class="privy-wallet-divider">or</p>+ <button type="button" id="privy-wallet-btn">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/></svg>+ Connect Wallet+ </button>+ <p id="privy-wallet-status" hidden></p>+ </div><p id="privy-inline-err" hidden></p><button type="button" id="privy-back-btn" class="privy-back-link">← Back</button></div>diff --git a/src/brain.js b/src/brain.jsindex fdfb0fb76..2687853ed 100644--- a/src/brain.js+++ b/src/brain.js@@ -19,22 +19,104 @@ const PROVIDERS = [];const PMAP = new Map(PROVIDERS.map(p => [p.key, p]));-// ── Interview questions ──────────────────────────────────────────────────────-const QUESTIONS = [- { q: 'How would you describe your personality in a few words?', placeholder: 'e.g. Curious, blunt, late.' },- { q: 'What do you spend most of your time doing?', placeholder: 'Work, hobbies, obsessions...' },- { q: "What topic could you talk about for an hour straight?", placeholder: 'The thing you geek out about...' },- { q: "What's a phrase or saying your friends know you for?", placeholder: 'Your catchphrase or motto...' },- { q: 'How would you describe your sense of humor?', placeholder: 'Dry, sarcastic, wholesome, chaotic...' },- { q: "What kind of language or phrases would you never use?", placeholder: 'Corporate jargon, slang, etc...' },-];-const EXAMPLES = [- 'Curious, blunt, late.',- 'Building small tools for crypto traders — Solana RPC, indexers, dashboards. Some skateboarding when the rain stops.',- 'Why most token launches fail in the first 90 minutes. The mechanics, the wallet patterns, the bot dynamics.',- '"ship it ugly, fix it Friday"',- 'Dry. Self-deprecating. I laugh at my own bugs before anyone else can.',- '"Per my last email." or anything that sounds like a LinkedIn post.',+// ── Archetype quick-picks ────────────────────────────────────────────────────+const ARCHETYPES = [+ {+ label: 'Sharp Analyst',+ desc: 'Precise, data-driven, no fluff',+ persona: {+ tone: 'precise and analytical — cuts straight to the signal, no filler',+ communication_style: 'terse',+ vocabulary: ['signal', 'data shows', 'the numbers', 'bottom line', 'specifically'],+ interests: ['data analysis', 'systems thinking', 'metrics', 'pattern recognition'],+ dont_say: ['I think', 'maybe', 'sort of', 'kinda'],+ sample_greeting: 'Show me the data. What are we looking at?',+ },+ },+ {+ label: 'Casual Builder',+ desc: 'Relaxed, technical, maker energy',+ persona: {+ tone: 'chill but technical — perpetual builder mode, no corporate speak',+ communication_style: 'playful',+ vocabulary: ['ship it', 'hack it', "let's see", 'works for me', 'yeah no'],+ interests: ['building', 'Solana', 'crypto', 'side projects', 'tooling'],+ dont_say: ['synergy', 'leverage', 'pivot', 'stakeholder'],+ sample_greeting: 'Hey, what are we building today?',+ },+ },+ {+ label: 'Warm Helper',+ desc: 'Supportive, clear, encouraging',+ persona: {+ tone: 'warm and approachable — genuinely helpful, never condescending',+ communication_style: 'warm',+ vocabulary: ['happy to help', "let's figure this out", 'great question', 'of course'],+ interests: ['helping others', 'learning', 'problem solving', 'clarity'],+ dont_say: ["I can't", 'not my problem', 'as per my last email'],+ sample_greeting: 'Hey! What can I help you with today?',+ },+ },+ {+ label: 'Crypto Native',+ desc: 'On-chain mindset, degen fluent',+ persona: {+ tone: 'crypto-native, fast-thinking — direct and unfiltered, on-chain first',+ communication_style: 'terse',+ vocabulary: ['gm', 'ser', 'based', 'alpha', 'ngmi', 'wagmi', 'on-chain'],+ interests: ['DeFi', 'Solana', 'NFTs', 'token mechanics', 'on-chain data', 'wallets'],+ dont_say: ['traditional finance', 'guaranteed returns', 'trust me bro'],+ sample_greeting: "gm ser, what's the alpha today?",+ },+ },+ {+ label: 'Direct Expert',+ desc: 'No small talk, deep knowledge',+ persona: {+ tone: 'direct and authoritative — expertise over warmth, zero small talk',+ communication_style: 'terse',+ vocabulary: ['specifically', 'the issue is', 'correct approach', 'in practice', 'technically'],+ interests: ['deep technical work', 'first principles', 'correctness', 'architecture'],+ dont_say: ['just', 'basically', 'kind of', 'I feel like'],+ sample_greeting: 'What do you need?',+ },+ },+ {+ label: 'Playful Coach',+ desc: 'Energetic, motivating, fun',+ persona: {+ tone: 'high-energy and encouraging — real sense of humor, relentlessly positive',+ communication_style: 'playful',+ vocabulary: ["let's go", 'you got this', 'leveling up', 'crushing it', 'next level'],+ interests: ['growth', 'habits', 'productivity', 'mindset', 'momentum'],+ dont_say: ["can't", 'impossible', 'too hard', 'maybe later'],+ sample_greeting: "Let's gooo! What are we working on?",+ },+ },+ {+ label: 'Pro Advisor',+ desc: 'Thoughtful, structured, balanced',+ persona: {+ tone: 'measured and thorough — weighs tradeoffs carefully, avoids absolutes',+ communication_style: 'detailed',+ vocabulary: ['on one hand', 'consider that', 'the tradeoff is', 'in context', 'worth noting'],+ interests: ['strategy', 'decision making', 'risk', 'planning', 'nuance'],+ dont_say: ['definitely', 'obviously', 'always', 'never'],+ sample_greeting: "Happy to think through this with you. What's the situation?",+ },+ },+ {+ label: 'Creative Thinker',+ desc: 'Lateral connections, big ideas',+ persona: {+ tone: 'imaginative and curious — makes unexpected connections, always asks what if',+ communication_style: 'playful',+ vocabulary: ['imagine if', 'what if we', 'interesting angle', 'pattern here', 'reminds me of'],+ interests: ['creativity', 'design', 'art', 'innovation', 'lateral thinking'],+ dont_say: ["that's not possible", 'never been done', 'too risky'],+ sample_greeting: 'Ooh interesting — what are we exploring?',+ },+ },];// ── Auth hint ────────────────────────────────────────────────────────────────@@ -49,7 +131,6 @@ function isAuthedHint() {// ── State ────────────────────────────────────────────────────────────────────const state = {activeTab: 'persona',- method: 'interview',persona: null,personaEnabled: true,authed: isAuthedHint(),@@ -190,37 +271,32 @@ function setTab(tab) {$('brPanelPlayground').classList.toggle('active', tab === 'playground');}-// ── Render: Interview questions ──────────────────────────────────────────────-function renderQuestions() {- const container = $('brQuestions');- container.innerHTML = '';- QUESTIONS.forEach((q, i) => {- const card = document.createElement('div');- card.className = 'br-q-card';- card.innerHTML = `- <span class="br-q-num">Question ${i + 1}</span>- <div class="br-q-text">${escHtml(q.q)}</div>- <textarea class="br-q-input" id="brQ${i}" placeholder="${escHtml(q.placeholder)}" rows="2"></textarea>- `;- container.appendChild(card);- });- container.querySelectorAll('.br-q-input').forEach(el => {- el.addEventListener('input', updateSynthButton);+// ── Render: Archetype quick-picks ────────────────────────────────────────────+function renderArchetypes() {+ const grid = $('brArchetypeGrid');+ if (!grid) return;+ grid.innerHTML = ARCHETYPES.map((a, i) => `+ <button class="br-archetype-chip" data-archetype="${i}" type="button">+ <span class="br-archetype-chip-label">${escHtml(a.label)}</span>+ <span class="br-archetype-chip-desc">${escHtml(a.desc)}</span>+ </button>+ `).join('');+ grid.querySelectorAll('.br-archetype-chip').forEach(chip => {+ chip.addEventListener('click', () => applyArchetype(parseInt(chip.dataset.archetype, 10)));});}-function collectAnswers() {- return QUESTIONS.map((q, i) => ({- question: q.q,- answer: ($(`brQ${i}`)?.value || '').trim(),- }));-}--function updateSynthButton() {- const allFilled = collectAnswers().every(a => a.answer.length > 0);- $('brSynthesize').disabled = !allFilled || !state.authed;- const freeBtn = $('brFreeformSynth');- if (freeBtn) freeBtn.disabled = !$('brFreeformText')?.value.trim() || !state.authed;+function applyArchetype(index) {+ const archetype = ARCHETYPES[index];+ if (!archetype) return;+ state.persona = { ...archetype.persona };+ persistPersona();+ renderPersonaCard(state.persona);+ // Mark the selected chip+ document.querySelectorAll('.br-archetype-chip').forEach((chip, i) => {+ chip.classList.toggle('selected', i === index);+ });+ toast(`"${archetype.label}" persona applied`);}function showAuthGate() {@@ -295,16 +371,11 @@ function updatePersonaBanner() {}}-// ── Persona: Synthesis ───────────────────────────────────────────────────────-async function synthesizeFromInterview() {- const answers = collectAnswers();- if (!answers.every(a => a.answer.length > 0)) return;- await runExtraction({ answers });-}--async function synthesizeFromFreeform() {- const text = $('brFreeformText').value.trim();+// ── Persona: Synthesis from description ─────────────────────────────────────+async function synthesizeFromDescription() {+ const text = $('brDescribeInput').value.trim();if (!text) return;+ if (!state.authed) { showAuthGate(); return; }await runExtraction({ freeform: text });}@@ -346,20 +417,6 @@ async function runExtraction(payload) {}}-function setPersonaFromManual() {- const split = v => v.split(',').map(s => s.trim()).filter(Boolean);- state.persona = {- tone: $('brManTone').value.trim() || 'Neutral',- communication_style: $('brManStyle').value,- vocabulary: split($('brManVocab').value),- interests: split($('brManInterests').value),- dont_say: split($('brManDont').value),- sample_greeting: $('brManGreet').value.trim(),- };- persistPersona();- renderPersonaCard(state.persona);- toast('Persona set');-}// ── Persona: Edit inline ─────────────────────────────────────────────────────function openEditMode() {@@ -925,14 +982,6 @@ function bindPlayControlEvents() {}}-// ── Method tabs ──────────────────────────────────────────────────────────────-function setMethod(method) {- state.method = method;- document.querySelectorAll('.br-method-tab').forEach(t => t.classList.toggle('active', t.dataset.method === method));- $('brInterview').classList.toggle('active', method === 'interview');- $('brFreeform').classList.toggle('active', method === 'freeform');- $('brManual').classList.toggle('active', method === 'manual');-}// ── Bind all events ──────────────────────────────────────────────────────────function bindEvents() {@@ -941,26 +990,14 @@ function bindEvents() {t.addEventListener('click', () => setTab(t.dataset.tab));});- // Method tabs- document.querySelectorAll('.br-method-tab').forEach(t => {- t.addEventListener('click', () => setMethod(t.dataset.method));- });-- // Interview- $('brSynthesize').addEventListener('click', synthesizeFromInterview);- $('brFillExample').addEventListener('click', () => {- EXAMPLES.forEach((v, i) => { const el = $(`brQ${i}`); if (el) el.value = v; });- updateSynthButton();+ // Describe input + generate button+ $('brDescribeInput').addEventListener('input', () => {+ $('brDescribeGenerate').disabled = !$('brDescribeInput').value.trim();});-- // Freeform- $('brFreeformText').addEventListener('input', () => {- $('brFreeformSynth').disabled = !$('brFreeformText').value.trim();+ $('brDescribeInput').addEventListener('keydown', e => {+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); synthesizeFromDescription(); }});- $('brFreeformSynth').addEventListener('click', synthesizeFromFreeform);-- // Manual- $('brManualSave').addEventListener('click', setPersonaFromManual);+ $('brDescribeGenerate').addEventListener('click', synthesizeFromDescription);// Persona card actions$('brEditPersona').addEventListener('click', openEditMode);@@ -1056,15 +1093,13 @@ function bindEvents() {loadSessions();loadPersona();-renderQuestions();+renderArchetypes();renderPlayControls();renderSidebar();renderCanvas();bindEvents();fetchProviderAvailability();-if (!state.authed) showAuthGate();-if (state.persona) {renderPersonaCard(state.persona);}diff --git a/src/dashboard-next/pages/account.js b/src/dashboard-next/pages/account.jsindex 3a85e990b..03882cb3c 100644--- a/src/dashboard-next/pages/account.js+++ b/src/dashboard-next/pages/account.js@@ -235,6 +235,7 @@ async function copyToClipboard(text) {const PROVIDER_META = {anthropic: { label: 'Anthropic (Claude)', placeholder: 'sk-ant-api03-…', url: 'https://console.anthropic.com/settings/keys' },openai: { label: 'OpenAI (GPT-4)', placeholder: 'sk-proj-…', url: 'https://platform.openai.com/api-keys' },+ meshy: { label: 'Meshy AI (3D gen)', placeholder: 'msy_…', url: 'https://www.meshy.ai/settings/api' },};async function loadProviderKeys(host) {diff --git a/src/notifications.js b/src/notifications.jsindex ec93b7079..e93687a6b 100644--- a/src/notifications.js+++ b/src/notifications.js@@ -10,6 +10,55 @@const POLL_INTERVAL = 30_000;const AUTH_HINT_KEY = '3dagent:auth-hint';+// Cross-tab coordination. The inbox badge mounts in every open tab, and the+// /api/notifications budget is keyed per user — so N tabs each polling on their+// own 30s timer (plus a re-poll on every tab focus) used to multiply into a+// burst that tripped the per-user 429. We dedupe across tabs through a shared+// localStorage cache + a BroadcastChannel: whichever tab actually fetches+// writes the result and broadcasts it, and every other tab reuses that result+// for the poll interval instead of spending its own request.+const NOTIF_CACHE_KEY = '3dagent:notif-cache';+const NOTIF_LOCK_KEY = '3dagent:notif-lock';+const NOTIF_CHANNEL = '3dagent:notifications';+// Best-effort cross-tab fetch lock TTL — long enough to collapse a simultaneous+// poll burst, short enough that a tab whose fetch died never wedges the others.+const LOCK_TTL = 5_000;+// Cap exponential backoff after repeated 429s so the badge self-heals within a+// bounded window once the per-user budget refills.+const MAX_BACKOFF = 5 * 60_000;++function readNotifCache() {+ try {+ const raw = localStorage.getItem(NOTIF_CACHE_KEY);+ if (!raw) return null;+ const c = JSON.parse(raw);+ return c && typeof c.ts === 'number' ? c : null;+ } catch { return null; }+}++function writeNotifCache(notifications, unread_count) {+ try {+ localStorage.setItem(+ NOTIF_CACHE_KEY,+ JSON.stringify({ ts: Date.now(), notifications, unread_count }),+ );+ } catch { /* storage disabled/full — degrade to per-tab polling */ }+}++// Best-effort, last-writer-wins lock. localStorage isn't transactional across+// tabs, but the race window is sub-millisecond and an occasional double-fetch is+// harmless — this only needs to thin out the simultaneous burst.+function tryAcquireFetchLock() {+ try {+ const now = Date.now();+ const raw = localStorage.getItem(NOTIF_LOCK_KEY);+ const held = raw ? Number(raw) : 0;+ if (Number.isFinite(held) && now - held < LOCK_TTL) return false;+ localStorage.setItem(NOTIF_LOCK_KEY, String(now));+ return true;+ } catch { return true; }+}+const TYPE_ICON = {skill_purchased: '💵',skill_purchase_confirmed: '✅',@@ -113,6 +162,16 @@ class NotificationInbox {this._unread = 0;this._open = false;this._timer = null;+ this._backoffUntil = 0;+ this._backoffMs = 0;++ // Listen for fresh data fetched by sibling tabs so we update the badge+ // without spending our own request.+ this._channel = null;+ try {+ this._channel = new BroadcastChannel(NOTIF_CHANNEL);+ this._channel.onmessage = (e) => this._applyData(e.data, false);+ } catch { /* BroadcastChannel unsupported — localStorage cache still coordinates */ }btn.addEventListener('click', (e) => { e.stopPropagation(); this._toggle(); });document.addEventListener('keydown', (e) => {@@ -120,14 +179,41 @@ class NotificationInbox {});}+ // Apply a notifications payload (from our own fetch, the shared cache, or a+ // sibling tab) to local state + the badge. `share` re-publishes to the cache+ // and other tabs; broadcasts received from siblings pass `false` to avoid a+ // rebroadcast loop.+ _applyData(data, share) {+ if (!data) return;+ this._notifications = data.notifications || [];+ this._unread = data.unread_count || 0;+ this._updateBadge();+ if (this._open) this._renderBody();+ if (share) {+ writeNotifCache(this._notifications, this._unread);+ try {+ this._channel?.postMessage({+ notifications: this._notifications,+ unread_count: this._unread,+ });+ } catch { /* channel closed */ }+ }+ }+start() {if (!isAuthed()) return;+ // Seed the badge instantly from whatever a sibling tab fetched last, so a+ // new tab is correct on load without adding its own request.+ const cached = readNotifCache();+ if (cached) this._applyData(cached, false);this._poll();this._schedulePoll();document.addEventListener('visibilitychange', () => {if (document.hidden) {clearTimeout(this._timer);} else {+ // Re-poll on focus, but `_poll` reuses a fresh shared cache, so+ // rapidly flipping between tabs no longer bursts the API.this._poll();this._schedulePoll();}@@ -143,14 +229,34 @@ class NotificationInbox {}async _poll() {+ if (!isAuthed()) return;++ // Honour a 429 backoff window — don't keep hammering a drained budget.+ if (Date.now() < this._backoffUntil) return;++ // If any tab fetched within the poll interval, reuse it instead of+ // spending another request against the per-user budget.+ const cached = readNotifCache();+ if (cached && Date.now() - cached.ts < POLL_INTERVAL) {+ this._applyData(cached, false);+ return;+ }++ // Collapse a simultaneous multi-tab poll into a single fetch; the winner+ // broadcasts the result to everyone else.+ if (!tryAcquireFetchLock()) return;+try {const resp = await fetch('/api/notifications?limit=20', { credentials: 'include' });+ if (resp.status === 429) {+ this._backoffMs = Math.min(this._backoffMs ? this._backoffMs * 2 : POLL_INTERVAL, MAX_BACKOFF);+ this._backoffUntil = Date.now() + this._backoffMs;+ return;+ }if (!resp.ok) return;- const data = await resp.json();- this._notifications = data.notifications || [];- this._unread = data.unread_count || 0;- this._updateBadge();- if (this._open) this._renderBody();+ this._backoffMs = 0;+ this._backoffUntil = 0;+ this._applyData(await resp.json(), true);} catch { /* network blip — silently ignore */ }}@@ -332,6 +438,9 @@ class NotificationInbox {}function mount() {+ // Guard against a double mount (e.g. nav re-injected) spinning up a second+ // poller for the same tab.+ if (window.__notifInbox) return;const btn = document.getElementById('nav-notifications-btn');if (!btn) return;const inbox = new NotificationInbox(btn);diff --git a/tests/api/sns.test.js b/tests/api/sns.test.jsindex 4c305da3d..dee43d66f 100644--- a/tests/api/sns.test.js+++ b/tests/api/sns.test.js@@ -76,11 +76,11 @@ describe('GET /api/sns?name=…', () => {expect(resolveSnsName).toHaveBeenCalledWith('nich.threews');});- it('returns 404 when the name has no owner', async () => {+ it('returns 200 + resolved:false when the name has no owner', async () => {resolveSnsName.mockResolvedValue(null);const { res, body } = await call('/api/sns?name=does-not-exist.sol');- expect(res.statusCode).toBe(404);- expect(body.error_description).toMatch(/does not resolve/);+ expect(res.statusCode).toBe(200);+ expect(body.data).toEqual({ name: 'does-not-exist.sol', address: null, network: 'solana', resolved: false });expect(res.getHeader('cache-control')).toMatch(/max-age=30/);});@@ -105,15 +105,15 @@ describe('GET /api/sns?address=…', () => {reverseLookupAddress.mockResolvedValue('bonfida.sol');const { res, body } = await call(`/api/sns?address=${ADDR}`);expect(res.statusCode).toBe(200);- expect(body.data).toEqual({ name: 'bonfida.sol', address: ADDR, network: 'solana' });+ expect(body.data).toEqual({ name: 'bonfida.sol', address: ADDR, network: 'solana', resolved: true });expect(reverseLookupAddress).toHaveBeenCalledWith(ADDR);});- it('returns 404 when no primary domain is set', async () => {+ it('returns 200 + resolved:false when no primary domain is set', async () => {reverseLookupAddress.mockResolvedValue(null);const { res, body } = await call(`/api/sns?address=${ADDR}`);- expect(res.statusCode).toBe(404);- expect(body.error_description).toMatch(/no primary/);+ expect(res.statusCode).toBe(200);+ expect(body.data).toEqual({ name: null, address: ADDR, network: 'solana', resolved: false });});it('rejects malformed addresses', async () => {diff --git a/workers/rembg/Dockerfile b/workers/rembg/Dockerfilenew file mode 100644index 000000000..5bd5e426f--- /dev/null+++ b/workers/rembg/Dockerfile@@ -0,0 +1,25 @@+FROM python:3.11-slim++ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ PIP_NO_CACHE_DIR=1++RUN apt-get update && apt-get install -y --no-install-recommends \+ libgl1 libglib2.0-0 libgomp1 \+ && rm -rf /var/lib/apt/lists/*++# rembg downloads ONNX model weights on first use; pre-cache them during build+# so cold starts are fast. Models live in /root/.u2net/.+RUN pip install rembg==2.0.59 && \+ python -c "import rembg; rembg.new_session('u2net')" && \+ python -c "import rembg; rembg.new_session('isnet-general-use')"++COPY requirements.txt /app/requirements.txt+RUN pip install -r /app/requirements.txt++WORKDIR /app+COPY worker_security.py /app/worker_security.py+COPY main.py /app/main.py++EXPOSE 8080+CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "1"]diff --git a/workers/rembg/cloudbuild.yaml b/workers/rembg/cloudbuild.yamlnew file mode 100644index 000000000..145f67f48--- /dev/null+++ b/workers/rembg/cloudbuild.yaml@@ -0,0 +1,59 @@+substitutions:+ _REGION: us-central1+ _RUN_SA: avatar-reconstruction-sa@aerial-vehicle-466722-p5.iam.gserviceaccount.com+ _SERVICE: rembg-service+ _REPO: rembg-service+ _GCS_BUCKET: three-ws-avatar-reconstructions+ _MIN_INSTANCES: "0"+ _MAX_INSTANCES: "4"++steps:+ - id: build+ name: gcr.io/cloud-builders/docker+ dir: workers/rembg+ args:+ - build+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - --cache-from+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - .++ - id: push+ name: gcr.io/cloud-builders/docker+ args:+ - push+ - --all-tags+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server++ - id: deploy+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim+ entrypoint: gcloud+ args:+ - run+ - deploy+ - ${_SERVICE}+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --region=${_REGION}+ - --service-account=${_RUN_SA}+ - --platform=managed+ - --port=8080+ - --no-gpu+ - --cpu=4+ - --memory=8Gi+ - --min-instances=${_MIN_INSTANCES}+ - --max-instances=${_MAX_INSTANCES}+ - --timeout=60+ - --allow-unauthenticated+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},MODEL=rmbg2,MAX_CONCURRENT=4+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest++images:+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest++options:+ machineType: E2_HIGHCPU_8+ logging: CLOUD_LOGGING_ONLYdiff --git a/workers/rembg/main.py b/workers/rembg/main.pynew file mode 100644index 000000000..b3f5bf635--- /dev/null+++ b/workers/rembg/main.py@@ -0,0 +1,200 @@+"""+Background removal service — strips backgrounds from images using BRIA RMBG-2.0+(Apache-2.0) with rembg's U2Net as a fast CPU fallback.++API contract:+ POST /remove { image: data-uri|url, model?: "rmbg2"|"u2net"|"isnet" }+ → 202 { task_id, status: "queued" }++ GET /tasks/:id → { task_id, status, result_url?, error? }++ GET /health → { ok, model, gpu_available }++No GPU required — BRIA RMBG-2.0 runs on CPU in <2s per 1024px image.+GPU accelerates to ~0.2s.++Environment variables:+ API_KEY — shared bearer secret (required)+ GCS_BUCKET — Cloud Storage bucket for output PNGs (required)+ MODEL — default model: "rmbg2" | "u2net" | "isnet" (default: rmbg2)+"""++from __future__ import annotations++import asyncio+import base64+import io+import logging+import os+import time+import uuid+from contextlib import asynccontextmanager+from typing import Optional++import torch+from fastapi import FastAPI, HTTPException, Header, BackgroundTasks+from google.cloud import storage+from PIL import Image+from pydantic import BaseModel, Field++from worker_security import (+ UnsafeUrlError,+ fetch_remote_bytes,+ require_api_key,+ safe_error,+)++logging.basicConfig(+ level=logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s %(message)s",+)+log = logging.getLogger("rembg")++API_KEY = os.environ["API_KEY"]+GCS_BUCKET = os.environ["GCS_BUCKET"]+DEFAULT_MODEL = os.environ.get("MODEL", "rmbg2")+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "4"))++_sessions: dict[str, object] = {}+_bucket: Optional[storage.Bucket] = None+_sem: Optional[asyncio.Semaphore] = None+_tasks: dict[str, dict] = {}++SUPPORTED_MODELS = ("rmbg2", "u2net", "isnet", "u2net_human_seg", "silueta")+++def _load_sessions() -> None:+ import rembg+ for model_name in SUPPORTED_MODELS:+ try:+ _sessions[model_name] = rembg.new_session(model_name)+ log.info("Loaded rembg session: %s", model_name)+ except Exception as exc:+ log.warning("Could not load rembg session %s: %s", model_name, exc)+ if not _sessions:+ raise RuntimeError("No rembg models could be loaded")+++@asynccontextmanager+async def lifespan(app: FastAPI):+ global _bucket, _sem+ _bucket = storage.Client().bucket(GCS_BUCKET)+ _sem = asyncio.Semaphore(MAX_CONCURRENT)+ loop = asyncio.get_event_loop()+ await loop.run_in_executor(None, _load_sessions)+ log.info("rembg service ready — models: %s", list(_sessions))+ yield+++app = FastAPI(title="rembg-service", lifespan=lifespan)+++def _require_api_key(authorization: str) -> None:+ try:+ require_api_key(authorization, API_KEY)+ except PermissionError as exc:+ raise HTTPException(status_code=401, detail=str(exc)) from exc+++def _decode_image(src: str) -> Image.Image:+ if src.startswith("data:image"):+ b64 = src.split(",", 1)[1]+ return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGBA")+ if src.startswith("https://"):+ try:+ data = fetch_remote_bytes(src, timeout=30, max_bytes=16 * 1024 * 1024)+ except UnsafeUrlError as exc:+ raise ValueError(f"refused to fetch image: {exc}") from exc+ return Image.open(io.BytesIO(data)).convert("RGBA")+ raise ValueError(f"unsupported image source format: {src[:60]}")+++def _run_removal(img: Image.Image, model_name: str) -> Image.Image:+ import rembg+ session = _sessions.get(model_name) or _sessions.get(DEFAULT_MODEL) or next(iter(_sessions.values()))+ buf_in = io.BytesIO()+ img.save(buf_in, format="PNG")+ result_bytes = rembg.remove(buf_in.getvalue(), session=session)+ return Image.open(io.BytesIO(result_bytes)).convert("RGBA")+++async def _process(task_id: str, image_src: str, model_name: str) -> None:+ async with _sem:+ _tasks[task_id]["status"] = "running"+ loop = asyncio.get_event_loop()+ t0 = time.time()+ try:+ img = await loop.run_in_executor(None, _decode_image, image_src)+ result = await loop.run_in_executor(None, _run_removal, img, model_name)++ buf = io.BytesIO()+ result.save(buf, format="PNG", optimize=True)+ png_bytes = buf.getvalue()++ blob_name = f"rembg/{task_id}.png"+ blob = _bucket.blob(blob_name)+ await loop.run_in_executor(+ None,+ lambda: blob.upload_from_string(png_bytes, content_type="image/png"),+ )+ result_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"++ elapsed = time.time() - t0+ _tasks[task_id].update({+ "status": "done",+ "result_url": result_url,+ "width": result.width,+ "height": result.height,+ "elapsed_ms": int(elapsed * 1000),+ })+ log.info("[%s] done in %.2fs — %d bytes", task_id, elapsed, len(png_bytes))++ except Exception as exc:+ _tasks[task_id].update({+ "status": "failed",+ "error": safe_error(exc, context=f"[{task_id}] rembg"),+ "elapsed_ms": int((time.time() - t0) * 1000),+ })+++class RemoveRequest(BaseModel):+ image: str = Field(..., description="data-uri or https URL of the source image")+ model: str = Field(default="rmbg2", description="rembg model name")++[email protected]("/remove", status_code=202)+async def remove_background(+ body: RemoveRequest,+ background_tasks: BackgroundTasks,+ authorization: str = Header(...),+) -> dict:+ _require_api_key(authorization)+ model_name = body.model if body.model in SUPPORTED_MODELS else DEFAULT_MODEL+ task_id = str(uuid.uuid4())+ _tasks[task_id] = {+ "task_id": task_id,+ "status": "queued",+ "model": model_name,+ }+ background_tasks.add_task(_process, task_id, body.image, model_name)+ return {"task_id": task_id, "status": "queued"}++[email protected]("/tasks/{task_id}")+async def get_task(task_id: str, authorization: str = Header(...)) -> dict:+ _require_api_key(authorization)+ task = _tasks.get(task_id)+ if task is None:+ raise HTTPException(status_code=404, detail="task not found")+ return task++[email protected]("/health")+async def health() -> dict:+ return {+ "ok": True,+ "service": "rembg",+ "gpu_available": torch.cuda.is_available(),+ "models_loaded": list(_sessions),+ "default_model": DEFAULT_MODEL,+ }diff --git a/workers/rembg/requirements.txt b/workers/rembg/requirements.txtnew file mode 100644index 000000000..c088fe2aa--- /dev/null+++ b/workers/rembg/requirements.txt@@ -0,0 +1,8 @@+fastapi==0.115.5+uvicorn[standard]==0.32.1+rembg[gpu]==2.0.59+Pillow==11.0.0+google-cloud-storage==2.19.0+httpx==0.27.2+pydantic==2.10.3+torch==2.3.1diff --git a/workers/rembg/worker_security.py b/workers/rembg/worker_security.pynew file mode 100644index 000000000..1e569c4e2--- /dev/null+++ b/workers/rembg/worker_security.py@@ -0,0 +1,222 @@+"""+Shared security helpers for the three.ws GPU/CPU workers.++This module is intentionally dependency-light (stdlib only) so it can be+COPYed verbatim into every worker's Docker build context. The same canonical+file lives in each worker directory; keep them byte-identical when editing.++It provides three primitives that every worker needs:++ 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).+ 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata+ IP rejection, per-hop redirect re-validation, and a bounded response size.+ 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged+ message safe to persist/return to callers, after logging the full+ traceback server-side only.+"""++from __future__ import annotations++import hmac+import ipaddress+import logging+import socket+import uuid+from typing import Iterable, Optional+from urllib.parse import urlsplit++import httpx++log = logging.getLogger("worker_security")++# ── auth ────────────────────────────────────────────────────────────────────────+++def require_api_key(authorization: Optional[str], api_key: str) -> None:+ """Validate a ``Bearer <token>`` header in constant time.++ Raises ``PermissionError`` on any failure so callers can translate it into+ the framework's 401 (FastAPI workers map this to HTTPException(401)).+ """+ if not authorization or not authorization.startswith("Bearer "):+ raise PermissionError("missing bearer token")+ token = authorization[len("Bearer "):].strip()+ # hmac.compare_digest is timing-safe and accepts str (ASCII) operands.+ if not hmac.compare_digest(token, api_key):+ raise PermissionError("invalid api key")+++# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────++# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes+# are comfortably under this; anything larger is almost certainly abuse.+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB+_MAX_REDIRECTS = 4+++class UnsafeUrlError(ValueError):+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""+++def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:+ """Reject any address that could reach internal infrastructure.++ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),+ multicast, reserved, and unspecified addresses. IPv4-mapped IPv6 addresses+ are unwrapped first so a mapped private v4 can't slip through.+ """+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:+ ip = ip.ipv4_mapped+ return (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_multicast+ or ip.is_reserved+ or ip.is_unspecified+ )+++def _resolve_safe_host(host: str) -> None:+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.++ Resolving and checking every returned address closes the gap where a name+ resolves to both a public and a private address.+ """+ if not host:+ raise UnsafeUrlError("missing host")+ try:+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)+ except socket.gaierror as exc:+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc++ addrs = {info[4][0] for info in infos}+ if not addrs:+ raise UnsafeUrlError(f"no addresses for host: {host}")+ for addr in addrs:+ ip = ipaddress.ip_address(addr)+ if _is_blocked_ip(ip):+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")+++def assert_safe_url(url: str, *, allow_http: bool = False) -> str:+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.++ https is required by default; ``allow_http`` exists only for callers that+ legitimately need cleartext (not used by the workers).+ """+ parts = urlsplit(url)+ scheme = parts.scheme.lower()+ allowed = ("https", "http") if allow_http else ("https",)+ if scheme not in allowed:+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")+ if not parts.hostname:+ raise UnsafeUrlError("missing host")+ _resolve_safe_host(parts.hostname)+ return url+++def fetch_remote_bytes(+ url: str,+ *,+ timeout: float = 30.0,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Fetch ``url`` safely and return its body bytes.++ Hardening applied:+ * https-only (unless ``allow_http``).+ * every URL — including each redirect target — is DNS-resolved and+ rejected if it maps to a private/loopback/link-local/metadata address.+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is+ re-validated; httpx's own redirect following is disabled.+ * the response body is streamed and aborted once it exceeds ``max_bytes``.++ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /+ ``ValueError`` for transport or size failures.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:+ for _ in range(_MAX_REDIRECTS + 1):+ with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ for chunk in resp.iter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++async def fetch_remote_bytes_async(+ client: "httpx.AsyncClient",+ url: str,+ *,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.++ The provided ``client`` MUST be constructed with ``follow_redirects=False``+ so this function can re-validate each redirect hop itself.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ for _ in range(_MAX_REDIRECTS + 1):+ async with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ async for chunk in resp.aiter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++# ── opaque error handling ───────────────────────────────────────────────────────+++def safe_error(exc: BaseException, *, context: str = "") -> str:+ """Log the full traceback server-side and return an opaque client message.++ Never leak ``traceback.format_exc()`` (absolute paths, library versions,+ internal hostnames, fragments of upstream responses) to callers. A short+ correlation id is embedded in both the log line and the returned string so+ operators can join a client-reported failure to the server log.+ """+ correlation_id = uuid.uuid4().hex[:12]+ label = f"{context} " if context else ""+ log.exception("%serror [correlation_id=%s]", label, correlation_id)+ return f"internal error (ref {correlation_id})"