# Xmas Terminal — the community builds the terminal's look — Brain On BNB AI # One npx command, your own AI agent, a sandboxed theme on the live terminal. # # This is the complete xmas-terminal bundle as a single file, so it can be read in # one fetch. 13 files, 1412 lines. # Download as a zip: https://brainonbnb.com/code/xmas-terminal.zip # Everything else: https://brainonbnb.com/code/index.txt # # No secrets are present: they are supplied at runtime through the environment. # MIT licensed. ============================================================================== === FILE: scripts/xmas-admin.mjs ============================================================================== #!/usr/bin/env node // The operator's hand on the Xmas workshop (2026-11-17). Reads XMAS_ADMIN from .env. // node scripts/xmas-admin.mjs list // node scripts/xmas-admin.mjs order its place on the switch (smaller first; everyone uploaded is on it) // node scripts/xmas-admin.mjs block gone at once: files, list, uploads // node scripts/xmas-admin.mjs unblock import 'dotenv/config'; const API = process.env.BOBAI_XMAS_API || 'https://bobai-xmas.bobbuildonbnb.workers.dev'; const [action = 'list', slug, order] = process.argv.slice(2); if (!process.env.XMAS_ADMIN) { console.error('No XMAS_ADMIN in .env — run: node scripts/xmas-admin-secret.mjs'); process.exit(1); } const r = await fetch(API + '/admin', { method: 'POST', headers: { 'content-type': 'application/json', 'x-xmas-admin': process.env.XMAS_ADMIN }, body: JSON.stringify({ action, slug, ...(order != null ? { order: Number(order) } : {}) }) }); const j = await r.json().catch(() => ({})); if (!r.ok) { console.error(j.error || r.status); process.exit(1); } if (action === 'list') for (const t of j.themes) console.log(`${t.blocked ? 'BLOCKED ' : t.ver ? 'IN ' : 'empty '} ${t.slug.padEnd(24)} v${t.ver} ${String(t.files).padStart(3)} files ${(t.bytes / 1024).toFixed(0).padStart(6)} KB "${t.title}" by ${t.builder} ${t.preview}`); else console.log(JSON.stringify(j.theme, null, 2)); ============================================================================== === FILE: scripts/xmas-kit-regressions.mjs ============================================================================== #!/usr/bin/env node // The community Xmas terminal (2026-11-17): the kit (xmas-kit/) and the terminal's frame layer, offline. // node scripts/xmas-kit-regressions.mjs import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { spawnSync } from 'node:child_process'; const ROOT = path.resolve(import.meta.dirname, '..'); let fails = 0; const ok = (name, cond, extra = '') => { console.log((cond ? ' ok ' : ' FAIL ') + name + (cond || !extra ? '' : ' — ' + extra)); if (!cond) fails++; }; // --- the kit's check, on a folder made here const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'xmkit-')); fs.mkdirSync(path.join(tmp, 'theme')); fs.writeFileSync(path.join(tmp, 'xmas.json'), JSON.stringify({ title: 'T', builder: 'b', slug: 'b' })); fs.writeFileSync(path.join(tmp, '.xmas-key'), 'xk_' + 'Q'.repeat(32)); fs.copyFileSync(path.join(ROOT, 'xmas-kit', 'xmas.mjs'), path.join(tmp, 'xmas.mjs')); const run = (...a) => spawnSync(process.execPath, ['xmas.mjs', ...a], { cwd: tmp, encoding: 'utf8', env: { ...process.env, BOBAI_XMAS_API: 'http://127.0.0.1:9' } }); const write = (f, t) => { fs.mkdirSync(path.dirname(path.join(tmp, 'theme', f)), { recursive: true }); fs.writeFileSync(path.join(tmp, 'theme', f), t); }; let r = run('check'); ok('an empty theme/ is not ready (back.html or front.html needed)', r.status === 1 && /back\.html/.test(r.stdout)); write('back.html', '

snow

'); r = run('check'); ok('a page alone is ready', r.status === 0 && /ready to upload/.test(r.stdout), r.stdout); for (const [name, text] of [['an OpenAI key', 'const k = "' + ['sk', 'proj', 'AbCdEfGhIjKlMnOpQrStUvWxYz012345'].join('-') + '";'], ['a Google key', 'k="' + 'AI' + 'zaSyA1234567890abcdefghijklmnopqrstu' + '"'], ['the kit key', 'xk_' + 'Q'.repeat(32)], ['a .env line', 'OPENAI_API_KEY=sk-x']]) { write('leak.js', text); r = run('check'); ok(`${name} in a file stops the upload`, r.status === 1 && /API key or your \.xmas-key/.test(r.stdout), r.stdout); } fs.rmSync(path.join(tmp, 'theme', 'leak.js')); write('a.js', 'fetch("https://x.example"); eval("1"); localStorage.x=1; new Audio("a.mp3")'); r = run('check'); ok('calls out, eval, storage and sound are warned about', /calls out/.test(r.stdout) && /eval/.test(r.stdout) && /storage/.test(r.stdout) && /sound/.test(r.stdout)); write('x.exe', 'MZ'); r = run('check'); ok('an unknown kind of file is not ready', r.status === 1 && /x\.exe/.test(r.stdout)); fs.rmSync(path.join(tmp, 'theme', 'x.exe')); r = run('image', 'x', '--out', '../outside.webp'); ok('image/video write only into theme/', r.status === 1 && /(inside theme|OPENAI_API_KEY)/.test(r.stderr + r.stdout)); fs.rmSync(tmp, { recursive: true, force: true }); // --- the kit's files const kit = fs.readFileSync(path.join(ROOT, 'xmas-kit', 'xmas.mjs'), 'utf8'), guide = fs.readFileSync(path.join(ROOT, 'xmas-kit', 'guide.md'), 'utf8'); ok('the dev server serves theme files with the live CSP (sandbox, no calls out)', /const THEME_CSP = "sandbox allow-scripts;[^"]*connect-src 'none'/.test(kit)); ok('… and refuses a path out of theme/', /if \(!file\.startsWith\(path\.resolve\(theme\) \+ path\.sep\)\)/.test(kit)); ok('the start keeps the key out of git and makes .env for the AI keys', /'\.xmas-key\\n\.env\\n/.test(kit) && /OPENAI_API_KEY=\\nGEMINI_API_KEY=/.test(kit)); ok('every agent finds the guide: AGENTS, CLAUDE, GEMINI, Cursor, Copilot', ['AGENTS.md', 'CLAUDE.md', 'GEMINI.md', '.cursorrules', 'copilot-instructions.md'].every((f) => kit.includes(f))); ok('the guide names every message the terminal sends', ['hello', 'layout', 'event', 'moment', 'pose', 'mood', 'visible'].every((t) => guide.includes(`type: '${t}'`))); ok('the guide gives the figure as "figure" (the key "bobai" is the marker)', /figure: \{ x, y, w, h \}/.test(guide) && !/^\s+bobai: \{ x/m.test(guide)); const tgz = path.join(ROOT, 'dashboard', 'xmas', 'kit.tgz'); ok('the served kit is the built one (kit.tgz exists)', fs.existsSync(tgz) && fs.statSync(tgz).size > 5000); // The command stays the https link (18.11.; no npm package yet): X hides "https://" and npx then reads the link as a // file on disk, so the page and the guide say to keep it, and nothing names an npm package that is not published. const pageX = fs.readFileSync(path.join(ROOT, 'dashboard', 'xmas.html'), 'utf8'), workerX = fs.readFileSync(path.join(ROOT, 'worker-xmas', 'index.js'), 'utf8'); const CMD = 'npx https://brainonbnb.com/xmas/kit.tgz'; ok('the page, the worker and the kit give the https link as the command', pageX.includes(`${CMD}`) && workerX.includes(`how: '${CMD}'`) && kit.includes(`start a new one: ${CMD}'`)); ok('the page and the guide explain the ENOENT case (link without https://)', /Keep the https:\/\/<\/code>/.test(pageX) && /ENOENT/.test(pageX) && /ENOENT[^\n]*npx https:\/\/brainonbnb\.com\/xmas\/kit\.tgz/.test(guide)); ok('nothing tells people to run "npx bobai-xmas" (not on npm)', ![pageX, workerX, kit, guide].some((t) => /npx bobai-xmas\b/.test(t)) && !/npmjs\.com\/package\/bobai-xmas/.test(pageX)); ok('no command anywhere without the https:// (npx brainonbnb.com/…)', ![pageX, workerX, kit, guide].some((t) => /npx brainonbnb\.com/.test(t))); // --- the terminal's layer const T = fs.readFileSync(path.join(ROOT, 'temp', 'terminal-site', 'terminal', 'terminal.js'), 'utf8'), C = fs.readFileSync(path.join(ROOT, 'temp', 'terminal-site', 'terminal', 'terminal.css'), 'utf8'); ok('a theme frame is sandboxed with scripts only', /f\.setAttribute\('sandbox', 'allow-scripts'\)/.test(T) && !/allow-same-origin/.test(T.slice(T.indexOf('COMMUNITY XMAS TERMINAL')))); ok('the frames take no pointer events', /#bt \.xm\{[^}]*pointer-events:none/.test(C)); ok('back under BOBAI (z 1), front under every label and window (z 4)', /#bt \.xm-back\{z-index:1\}/.test(C) && /#bt \.xm-front\{z-index:4\}/.test(C)); ok('the dev folder loads only on 127.0.0.1 / localhost', /const devHost = \/\^\(127\\\.0\\\.0\\\.1\|localhost\)\$\/i\.test\(location\.hostname\)/.test(T)); ok('the marker is set last on every message (nothing overwrites it)', /\{ \.\.\.lay, bobai: 'xmas', v: 1 \}/.test(T) && /\.\.\.m, bobai: 'xmas', v: 1 \}/.test(T)); ok('the layout calls BOBAI "figure"', /figure: rel\(fig, r0\)/.test(T)); ok('only the stations on screen are named (from 1 Dec: burnA, liq, creator)', /stations: Object\.fromEntries\(DEST\.filter\(d => d\.pct > 0 && d\.pos\)/.test(T) && /stations: DEST\.filter\(d => d\.pct > 0\)\.map/.test(T) && /three stations plus the trades/.test(guide)); ok('a slow theme is put away (under 20 fps for 8 s)', /slowS = n < 20 \? slowS \+ 1 : 0/.test(T) && /if \(slowS >= 8\)/.test(T)); ok('the page listens to nothing a theme says', !/addEventListener\('message'/.test(T.slice(T.indexOf('COMMUNITY XMAS TERMINAL')))); const H = fs.readFileSync(path.join(ROOT, 'dashboard', '_headers'), 'utf8'); ok('the page CSP lets in the theme worker and nothing else new', /frame-src 'self' https:\/\/bobai-xmas\.bobbuildonbnb\.workers\.dev;/.test(H) && /connect-src 'self' https:\/\/bobai-xmas\.bobbuildonbnb\.workers\.dev /.test(H)); console.log(fails ? `\n${fails} FAIL` : '\nall pass'); process.exit(fails ? 1 : 0); ============================================================================== === FILE: scripts/xmas-worker-regressions.mjs ============================================================================== #!/usr/bin/env node // The community Xmas terminal's worker (worker-xmas/xmas.js, 2026-11-17), offline with a stand-in KV: joining, the key, // uploading, serving sandboxed, the operator's approval, counting users — and every way in that must stay shut. // node scripts/xmas-worker-regressions.mjs import { handleXmas, THEME_CSP, checkPath, slugOf, XMAS_LIMITS } from '../worker-xmas/xmas.js'; let fails = 0; const ok = (name, cond, extra = '') => { console.log((cond ? ' ok ' : ' FAIL ') + name + (cond || !extra ? '' : ' — ' + extra)); if (!cond) fails++; }; const store = new Map(); const KV = { async get(k, o) { const v = store.get(k); if (v == null) return null; const type = typeof o === 'string' ? o : o?.type; if (type === 'json') return JSON.parse(v); if (type === 'arrayBuffer') return v; return v; }, async put(k, v) { store.set(k, v instanceof ArrayBuffer ? v.slice(0) : v); }, async delete(k) { store.delete(k); }, }; const env = { XMAS: KV, XMAS_ADMIN: 'adm1n-secret' }; const call = async (method, path, { body, headers = {}, ip = '1.1.1.1' } = {}) => { const req = new Request('https://bobai-xmas.example' + path, { method, headers: { 'content-type': 'application/json', 'cf-connecting-ip': ip, ...headers }, body: body == null ? undefined : JSON.stringify(body) }); const res = await handleXmas(req, env, new URL(req.url), path); const text = await res.text(); let j = null; try { j = JSON.parse(text); } catch {} return { status: res.status, j, text, h: res.headers }; }; const b64 = (s) => Buffer.from(s).toString('base64'); // joining let r = await call('POST', '/join', { body: { title: 'Frosty Brain', builder: 'mmx_qq' } }); const key = r.j?.key; ok('join gives a key of 32 characters and the slug of the name', r.status === 200 && /^xk_[A-Za-z0-9]{32}$/.test(key || '') && r.j.slug === 'mmx_qq', JSON.stringify(r.j)); ok('the key is not kept in the clear', ![...store.keys()].some((k) => k.includes(key)) && ![...store.values()].some((v) => typeof v === 'string' && v.includes(key))); r = await call('POST', '/join', { body: { title: 'Copy', builder: 'MMX_QQ' } }); ok('a name is taken once (case does not make it new)', r.status === 409); r = await call('POST', '/join', { body: { title: '', builder: 'b' } }); ok('markup in a title or a name is stripped, never stored', r.status === 200 && !/[<>]/.test(r.j.title + r.j.builder), JSON.stringify(r.j)); for (let i = 0; i < XMAS_LIMITS.joinsPerIpPerDay; i++) await call('POST', '/join', { body: { title: 't', builder: 'spam' + i }, ip: '9.9.9.9' }); r = await call('POST', '/join', { body: { title: 't', builder: 'spammore' }, ip: '9.9.9.9' }); ok(`at most ${XMAS_LIMITS.joinsPerIpPerDay} new builders from one address a day`, r.status === 429); // the key r = await call('POST', '/upload', { body: { files: [{ path: 'back.html', b64: b64('

x

') }] } }); ok('an upload without a key is refused', r.status === 401); r = await call('POST', '/upload', { headers: { 'x-xmas-key': 'xk_' + 'A'.repeat(32) }, body: { files: [{ path: 'back.html', b64: b64('

x

') }] } }); ok('an upload with a made-up key is refused', r.status === 401); // paths ok('no way out of the folder', !!checkPath('../x.html').error && !!checkPath('a/../../x.js').error && !!checkPath('/etc/x.html').error && !!checkPath('a//b.png').error); ok('no unknown kinds of file (no .exe, .php, .wasm, sound)', ['a.exe', 'a.php', 'a.wasm', 'a.mp3', 'a.html.', 'noext'].every((p) => !!checkPath(p).error)); ok('the usual kinds are served with their type', checkPath('img/snow.webp').type === 'image/webp' && checkPath('back.html').type.startsWith('text/html') && checkPath('m/tree.glb').type === 'model/gltf-binary'); ok('a name becomes an address: lower case, safe characters', slugOf('Binance Square') === 'binance-square' && slugOf('x') === null && slugOf('ÄÖ!!') === null); // uploading const html = ''; r = await call('POST', '/upload', { headers: { 'x-xmas-key': key }, body: { files: [{ path: 'back.html', b64: b64(html) }, { path: 'snow.js', b64: b64('console.log(1)') }] } }); ok('the builder uploads: version 1, preview link', r.status === 200 && r.j.ver === 1 && /\?xmas=mmx_qq$/.test(r.j.preview), JSON.stringify(r.j)); r = await call('POST', '/upload', { headers: { 'x-xmas-key': key }, body: { files: [{ path: 'style.css', b64: b64('a{}') }] } }); ok('a theme without back.html or front.html is refused', r.status === 400); r = await call('POST', '/upload', { headers: { 'x-xmas-key': key }, body: { files: [{ path: 'back.html', b64: Buffer.alloc(XMAS_LIMITS.fileBytes + 1).toString('base64') }] } }); ok('a file over the limit is refused', r.status === 400); // serving r = await call('GET', '/t/mmx_qq/1/back.html'); ok('a file is served with its type', r.status === 200 && r.text === html && r.h.get('content-type').startsWith('text/html')); const csp = r.h.get('content-security-policy') || ''; ok('… sandboxed: its own CSP opens it in an opaque origin (no cookies, storage, page), scripts only', /^sandbox allow-scripts;/.test(csp) && !/allow-same-origin|allow-top-navigation|allow-popups|allow-forms|allow-modals/.test(csp)); ok('… no calls out, no eval or WebAssembly, no workers, no frames, no forms, no plugins', /connect-src 'none'/.test(csp) && !/unsafe-eval|wasm/.test(csp) && /worker-src 'none'/.test(csp) && /frame-src 'none'/.test(csp) && /form-action 'none'/.test(csp) && /object-src 'none'/.test(csp)); ok('… and only our pages may frame it', /frame-ancestors https:\/\/brainonbnb\.com /.test(csp) && !/frame-ancestors[^;]*\*(\s|;|$)/.test(csp)); ok('… nosniff', r.h.get('x-content-type-options') === 'nosniff'); ok('the CSP the worker sends is the one pinned here', csp === THEME_CSP); r = await call('GET', '/t/mmx_qq/1/..%2F..%2Fsecret.js'); ok('a path climbing out is not found', r.status === 404); r = await call('GET', '/t/mmx_qq/7/back.html'); ok('a version that does not exist is not found', r.status === 404); // the operator r = await call('GET', '/themes'); ok('everyone is in (17.11.): an uploaded theme is on the list, one with nothing uploaded is not', r.status === 200 && r.j.live.length === 1 && r.j.live[0].slug === 'mmx_qq' && /\/t\/mmx_qq\/1\/$/.test(r.j.live[0].base) && r.j.live[0].users_today === 0, JSON.stringify(r.j.live.map((t) => t.slug))); r = await call('GET', '/theme/mmx_qq'); ok('the preview link reads the theme', r.status === 200 && r.j.theme.ver === 1 && r.j.theme.layers.back === true && r.j.theme.layers.front === false); r = await call('POST', '/admin', { headers: { 'x-xmas-admin': 'wrong' }, body: { action: 'block', slug: 'mmx_qq' } }); ok('blocking needs the operator secret', r.status === 401); r = await call('POST', '/admin', { headers: { 'x-xmas-admin': 'adm1n-secret' }, body: { action: 'approve', slug: 'mmx_qq' } }); ok('there is no approving any more', r.status === 400); // counting users await call('POST', '/use', { body: { slug: 'mmx_qq' } }); await call('POST', '/use', { body: { slug: 'mmx_qq' } }); r = await call('POST', '/use', { body: { slug: 'spam0' } }); ok('a theme with nothing uploaded is not counted', r.j?.counted === false); r = await call('GET', '/themes'); ok('users today and in all', r.j.live[0].users_today === 2 && r.j.live[0].users_total === 2 && r.j.users_today_all === 2); ok('the count holds no address', ![...store.entries()].some(([k, v]) => k.startsWith('xmas:use') && /1\.1\.1\.1|9\.9\.9\.9/.test(String(v)))); // blocking await call('POST', '/admin', { headers: { 'x-xmas-admin': 'adm1n-secret' }, body: { action: 'block', slug: 'mmx_qq' } }); const g = await call('GET', '/t/mmx_qq/1/back.html'), l = await call('GET', '/themes'), u = await call('POST', '/upload', { headers: { 'x-xmas-key': key }, body: { files: [{ path: 'back.html', b64: b64('x') }] } }); ok('blocked: its files are gone, it leaves the list, its key uploads nothing', g.status === 404 && l.j.live.length === 0 && u.status === 403); console.log(fails ? `\n${fails} FAIL` : '\nall pass'); process.exit(fails ? 1 : 0); ============================================================================== === FILE: worker-xmas/index.js ============================================================================== // bobai-xmas: the community Xmas terminal's own worker (2026-11-17). Everything is in xmas.js; this worker holds no // key, no wallet and no binding to anything else of the project — on purpose (operator: "clean and hack-free"). import { handleXmas } from './xmas.js'; export default { async fetch(request, env) { const url = new URL(request.url); const path = url.pathname.replace(/\/+$/, '').replace(/^\/xmas(?=\/|$)/, '') || '/'; if (path === '/') return new Response(JSON.stringify({ name: 'BOBAI Xmas terminal workshop', how: 'npx https://brainonbnb.com/xmas/kit.tgz', themes: url.origin + '/themes' }, null, 2), { headers: { 'Content-Type': 'application/json; charset=utf-8', 'Access-Control-Allow-Origin': '*' } }); try { return await handleXmas(request, env, url, path); } catch (e) { return new Response(JSON.stringify({ error: 'something broke on our side; nothing was changed' }), { status: 500, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }); } }, }; ============================================================================== === FILE: worker-xmas/wrangler.toml ============================================================================== name = "bobai-xmas" main = "index.js" compatibility_date = "2025-01-01" workers_dev = true # Its own storage: nothing of the agent worker (payments, sessions, the board) is reachable from here. [[kv_namespaces]] binding = "XMAS" id = "" # Secret XMAS_ADMIN (wrangler secret put XMAS_ADMIN): the operator's approve / block. ============================================================================== === FILE: worker-xmas/xmas.js ============================================================================== // THE COMMUNITY XMAS TERMINAL (2026-11-17, operator: "the community builds the Xmas terminal theme — one command, // they build it themselves, it works for them as it does for me, they upload it; BOBAI and the standard terminal stay; // from 1 December it is live", then: "even better: an X post with the command, whoever wants builds one"). // // Operator, then: "everyone may build, Binance itself or other platforms too; once live you always see how many users // use which terminal; as many as want; but it must all be clean and hack-free — a sandbox page like xmas.preview". // // A WORKER OF ITS OWN, WITH STORAGE OF ITS OWN, ON A DOMAIN OF ITS OWN: nothing here can read or write what the agent // worker holds (payments, sessions, the board), and a theme's files come from *.workers.dev, never from brainonbnb.com. // // Anyone who runs the kit's one command joins (POST /join) and gets a key of their own, kept by the kit on their // machine; the key is the builder: every upload is theirs and nobody else's. A theme is a folder (back.html under // BOBAI, front.html over him, and whatever they load) stored as ONE bundle per version, served into a sandboxed frame // on the terminal: the response's own CSP says `sandbox allow-scripts` (an opaque origin even when a file is opened on // its own: no cookies, no storage, no page), `connect-src 'none'` (no calls out, no tracking), no eval and no // WebAssembly (no miner), no workers, no forms, no plugins, no frames. The terminal gives the frames no pointer events: // a theme can never put a button in front of a visitor. EVERYONE IS IN (operator, 17.11.: "no review, all are allowed — // just no racism, terror, hate"): every uploaded theme is on the switch from 1 December; the operator blocks one that // crosses that line (POST /admin block). A preview link works for anyone from the first upload: // https://xmas.bobai-dashboard.pages.dev/?xmas=. // // POST /join {title, builder} -> {key, slug} (the kit keeps the key; a builder name is taken once) // POST /hello x-xmas-key -> the builder's theme as it stands // POST /upload x-xmas-key, {files:[{path, b64}], title?} -> {ver, preview} // GET /themes -> every uploaded, unblocked theme with today's users, for the terminal's switch // GET /theme/ -> one theme (the preview link) // GET /t/// -> a file of a theme, sandboxed // POST /use {slug} -> a visitor's terminal shows this theme today (counted once a day per browser) // POST /admin x-xmas-admin, {action: list | block | unblock | order | rename} export const XMAS_SEASON = { from: '2026-12-01T00:00:00Z', to: '2027-01-01T00:00:00Z' }; export const XMAS_LIMITS = { files: 300, fileBytes: 5 * 1024 * 1024, totalBytes: 20 * 1024 * 1024, uploadsPerDay: 120, joinsPerIpPerDay: 10, themes: 5000 }; const EXT = { html: 'text/html; charset=utf-8', htm: 'text/html; charset=utf-8', css: 'text/css; charset=utf-8', js: 'text/javascript; charset=utf-8', mjs: 'text/javascript; charset=utf-8', json: 'application/json; charset=utf-8', txt: 'text/plain; charset=utf-8', svg: 'image/svg+xml', webp: 'image/webp', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', avif: 'image/avif', mp4: 'video/mp4', webm: 'video/webm', woff2: 'font/woff2', woff: 'font/woff', glb: 'model/gltf-binary', gltf: 'model/gltf+json', bin: 'application/octet-stream' }; // no sound: a terminal that starts playing music on a visitor is no terminal (videos play muted, the terminal says so) // The pages a theme may sit in: the site, its previews, the lab. const FRAME_ANCESTORS = "https://brainonbnb.com https://www.brainonbnb.com https://*.bobai-dashboard.pages.dev https://bobai-dashboard.pages.dev https://*.bobai-lab.pages.dev https://bobai-lab.pages.dev"; export const THEME_CSP = "sandbox allow-scripts; default-src 'self' data: blob:; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' data: blob:; font-src 'self' data:; connect-src 'none'; form-action 'none'; base-uri 'none'; frame-src 'none'; worker-src 'none'; manifest-src 'none'; object-src 'none'; frame-ancestors " + FRAME_ANCESTORS; const CORS = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, X-Xmas-Key' }; const out = (obj, status = 200, extra = {}) => new Response(JSON.stringify(obj, null, 2), { status, headers: { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', ...CORS, ...extra } }); const hex = (buf) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join(''); const sha = async (s) => hex(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(String(s)))); // previews open on the sandbox page (the live terminal's code with every theme reachable by link), never on brainonbnb.com export const SITE = 'https://xmas.bobai-dashboard.pages.dev'; export const SELF = 'https://bobai-xmas.bobbuildonbnb.workers.dev'; // A builder's name becomes the theme's address: lower case, letters, digits, _ and -, 2-24 long. export function slugOf(name) { const s = String(name || '').trim().toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 24); return s.length >= 2 ? s : null; } // What a person typed as a title or a name: plain text, one line, no markup, a sane length. export function cleanText(v, max) { const s = String(v ?? '').replace(/[\u0000-\u001f\u007f<>]/g, '').replace(/\s+/g, ' ').trim().slice(0, max); return s || null; } // A path inside a theme: relative, lower case or not, no way out of the folder, a known kind of file. export function checkPath(p) { const s = String(p || '').replace(/\\/g, '/').replace(/^\.\/+/, ''); if (!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(s) || s.includes('..') || s.includes('//') || s.endsWith('/')) return { error: `not a usable path: ${String(p).slice(0, 80)}` }; const ext = (s.match(/\.([A-Za-z0-9]+)$/) || [])[1]?.toLowerCase(); if (!ext || !EXT[ext]) return { error: `${s}: .${ext || '?'} files are not served (html, css, js, json, images, video, fonts, glb)` }; return { path: s, type: EXT[ext] }; } const b64bytes = (b64) => { const bin = atob(String(b64 || '')); const u = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i); return u; }; export function inSeason(t = Date.now()) { return t >= Date.parse(XMAS_SEASON.from) && t < Date.parse(XMAS_SEASON.to); } // Checks an upload and packs it: one buffer, an index of [path, type, offset, length]. export function packUpload(files) { if (!Array.isArray(files) || !files.length) return { error: 'no files: send {files:[{path, b64}]}' }; if (files.length > XMAS_LIMITS.files) return { error: `${files.length} files; at most ${XMAS_LIMITS.files}` }; const seen = new Set(), parts = [], index = []; let total = 0; for (const f of files) { const c = checkPath(f?.path); if (c.error) return { error: c.error }; if (seen.has(c.path)) return { error: `${c.path} twice` }; seen.add(c.path); let bytes; try { bytes = b64bytes(f.b64); } catch { return { error: `${c.path}: b64 is not base64` }; } if (bytes.length > XMAS_LIMITS.fileBytes) return { error: `${c.path}: ${(bytes.length / 1048576).toFixed(1)} MB; one file at most ${XMAS_LIMITS.fileBytes / 1048576} MB` }; index.push([c.path, c.type, total, bytes.length]); parts.push(bytes); total += bytes.length; if (total > XMAS_LIMITS.totalBytes) return { error: `more than ${XMAS_LIMITS.totalBytes / 1048576} MB in all` }; } if (!seen.has('back.html') && !seen.has('front.html')) return { error: 'a theme needs back.html (behind BOBAI) or front.html (in front of him), or both, at the top of the folder' }; const buf = new Uint8Array(total); let o = 0; for (const p of parts) { buf.set(p, o); o += p.length; } return { buf, index, total }; } const themeKey = (slug) => `xmas:theme:${slug}`, keyKey = (h) => `xmas:key:${h}`, bundleKey = (slug, ver) => `xmas:b:${slug}:${ver}`; async function readUse(env) { const day = new Date().toISOString().slice(0, 10); const [today, total] = await Promise.all([env.XMAS.get(`xmas:use:${day}`, 'json', { cacheTtl: 60 }), env.XMAS.get('xmas:use:total', 'json', { cacheTtl: 60 })]); return { day, today: today || {}, total: total || {} }; } async function listSlugs(env) { return (await env.XMAS.get('xmas:index', 'json').catch(() => null)) || []; } const publicView = (t) => ({ slug: t.slug, title: t.title, builder: t.builder, ver: t.ver || 0, updated: t.updated || null, live: !t.blocked && !!t.ver, base: t.ver ? `${SELF}/t/${t.slug}/${t.ver}/` : null, layers: { back: !!t.files?.some((f) => f[0] === 'back.html'), front: !!t.files?.some((f) => f[0] === 'front.html') }, preview: `${SITE}/?xmas=${t.slug}` }); async function builderOf(request, env) { const key = String(request.headers.get('x-xmas-key') || '').trim(); if (!/^xk_[A-Za-z0-9]{32}$/.test(key)) return { error: out({ error: 'no key: run the kit again (it keeps your key in .xmas-key)' }, 401) }; const rec = await env.XMAS.get(keyKey(await sha(key)), 'json'); if (!rec) return { error: out({ error: 'unknown key' }, 401) }; const t = await env.XMAS.get(themeKey(rec.slug), 'json'); if (!t) return { error: out({ error: 'unknown theme' }, 404) }; if (t.blocked) return { error: out({ error: 'this theme was stopped by the operator' }, 403) }; return { t }; } export async function handleXmas(request, env, url, path) { if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: CORS }); if (!env.XMAS) return out({ error: 'storage is not bound' }, 503); // a file of a theme, sandboxed const fm = path.match(/^\/t\/([a-z0-9_-]{2,24})\/(\d{1,6})\/(.+)$/); if (fm && request.method === 'GET') { const [, slug, ver, rawPath] = fm; const c = checkPath(decodeURIComponent(rawPath)); if (c.error) return new Response('not found', { status: 404 }); const t = await env.XMAS.get(themeKey(slug), 'json', { cacheTtl: 60 }); if (!t || t.blocked) return new Response('not found', { status: 404 }); const idx = Number(ver) === t.ver ? t.files : Number(ver) === t.prevVer ? t.prevFiles : null; const ent = idx?.find((f) => f[0] === c.path); if (!ent) return new Response('not found', { status: 404, headers: { 'Content-Security-Policy': THEME_CSP } }); const buf = await env.XMAS.get(bundleKey(slug, ver), { type: 'arrayBuffer', cacheTtl: 3600 }); if (!buf) return new Response('not found', { status: 404 }); return new Response(buf.slice(ent[2], ent[2] + ent[3]), { headers: { 'Content-Type': ent[1], 'Content-Security-Policy': THEME_CSP, 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'public, max-age=86400', 'Cross-Origin-Resource-Policy': 'cross-origin', 'Referrer-Policy': 'no-referrer', 'Access-Control-Allow-Origin': '*' } }); } if (path === '/themes' && request.method === 'GET') { const slugs = await listSlugs(env); const all = (await Promise.all(slugs.map((s) => env.XMAS.get(themeKey(s), 'json', { cacheTtl: 60 })))).filter(Boolean); const live = all.filter((t) => !t.blocked && t.ver).sort((a, b) => (a.order ?? 999) - (b.order ?? 999) || String(a.created).localeCompare(String(b.created))); const use = await readUse(env); return out({ season: XMAS_SEASON, in_season: inSeason(), day: use.day, live: live.map((t) => ({ ...publicView(t), users_today: use.today[t.slug] || 0, users_total: use.total[t.slug] || 0 })), users_today_all: Object.values(use.today).reduce((a, b) => a + b, 0), builders: all.filter((t) => !t.blocked).length }, 200, { 'Cache-Control': 'public, max-age=60' }); } // HOW MANY USE WHICH TERMINAL (operator, 2026-11-17): the terminal says once a day per browser which theme it shows. // A count of browsers, never who: no address, no IP kept. Counts go into one value per day (a few lost under a burst // of simultaneous writes is the price of not holding anything about a visitor). if (path === '/use' && request.method === 'POST') { const b = await request.json().catch(() => null), slug = String(b?.slug || ''); if (!/^[a-z0-9_-]{2,24}$/.test(slug)) return out({ ok: false }, 400); const t = await env.XMAS.get(themeKey(slug), 'json', { cacheTtl: 60 }); if (!t || t.blocked || !t.ver) return out({ ok: false, counted: false }); const day = new Date().toISOString().slice(0, 10), k = `xmas:use:${day}`; const m = (await env.XMAS.get(k, 'json')) || {}; m[slug] = (m[slug] || 0) + 1; await env.XMAS.put(k, JSON.stringify(m), { expirationTtl: 90 * 86400 }); const tot = (await env.XMAS.get('xmas:use:total', 'json')) || {}; tot[slug] = (tot[slug] || 0) + 1; await env.XMAS.put('xmas:use:total', JSON.stringify(tot)); return out({ ok: true, counted: true }); } const one = path.match(/^\/theme\/([a-z0-9_-]{2,24})$/); if (one && request.method === 'GET') { const t = await env.XMAS.get(themeKey(one[1]), 'json', { cacheTtl: 60 }); if (!t || t.blocked) return out({ error: 'no such theme' }, 404); return out({ season: XMAS_SEASON, theme: publicView(t) }, 200, { 'Cache-Control': 'public, max-age=30' }); } if (path === '/join' && request.method === 'POST') { const b = await request.json().catch(() => null); const title = cleanText(b?.title, 48), builder = cleanText(b?.builder, 32), slug = slugOf(builder); if (!title) return out({ error: 'title: what is your terminal called?' }, 400); if (!builder || !slug) return out({ error: 'builder: your name as it should show (2-24 letters or digits)' }, 400); const ip = request.headers.get('cf-connecting-ip') || 'x', day = new Date().toISOString().slice(0, 10), ipKey = `xmas:join:${day}:${await sha(ip)}`; const n = Number(await env.XMAS.get(ipKey)) || 0; if (n >= XMAS_LIMITS.joinsPerIpPerDay) return out({ error: 'too many new builders from here today; try tomorrow' }, 429); const slugs = await listSlugs(env); if (slugs.length >= XMAS_LIMITS.themes) return out({ error: 'the workshop is full' }, 503); if (slugs.includes(slug)) return out({ error: `the name "${builder}" is taken; choose another` }, 409); // 32 characters from 62 by rejection (no modulo bias): about 190 bits const A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let key = 'xk_'; while (key.length < 35) for (const x of crypto.getRandomValues(new Uint8Array(48))) if (x < 248 && key.length < 35) key += A[x % 62]; const now = new Date().toISOString(); await env.XMAS.put(themeKey(slug), JSON.stringify({ slug, title, builder, ver: 0, files: [], created: now, updated: null, uploads: {} })); await env.XMAS.put(keyKey(await sha(key)), JSON.stringify({ slug, created: now })); await env.XMAS.put('xmas:index', JSON.stringify([...slugs, slug])); await env.XMAS.put(ipKey, String(n + 1), { expirationTtl: 172800 }); return out({ key, slug, title, builder, preview: `${SITE}/?xmas=${slug}`, note: 'Keep the key: it is you. The kit stores it in .xmas-key; never post it.' }); } if (path === '/hello' && request.method === 'POST') { const r = await builderOf(request, env); if (r.error) return r.error; return out({ theme: publicView(r.t), season: XMAS_SEASON, limits: XMAS_LIMITS }); } if (path === '/upload' && request.method === 'POST') { const r = await builderOf(request, env); if (r.error) return r.error; const t = r.t, day = new Date().toISOString().slice(0, 10); const used = Number(t.uploads?.[day]) || 0; if (used >= XMAS_LIMITS.uploadsPerDay) return out({ error: `${XMAS_LIMITS.uploadsPerDay} uploads today already; the dev page shows your changes without uploading` }, 429); const b = await request.json().catch(() => null); const p = packUpload(b?.files); if (p.error) return out({ error: p.error }, 400); const ver = (t.ver || 0) + 1; await env.XMAS.put(bundleKey(t.slug, ver), p.buf.buffer); const old = t.prevVer; const title = cleanText(b?.title, 48) || t.title; const next = { ...t, title, prevVer: t.ver || null, prevFiles: t.files || [], ver, files: p.index, bytes: p.total, updated: new Date().toISOString(), uploads: { [day]: used + 1 } }; await env.XMAS.put(themeKey(t.slug), JSON.stringify(next)); if (old) await env.XMAS.delete(bundleKey(t.slug, old)).catch(() => {}); // the version before the previous one return out({ ok: true, ver, files: p.index.length, bytes: p.total, preview: `${SITE}/?xmas=${t.slug}`, live: true, note: 'Uploaded. The preview link shows it to anyone; from 1 December it is on the terminal\'s switch under your name (every upload replaces the last).' }); } if (path === '/admin' && request.method === 'POST') { if (!env.XMAS_ADMIN || request.headers.get('x-xmas-admin') !== env.XMAS_ADMIN) return out({ error: 'unauthorized' }, 401); const b = await request.json().catch(() => ({})); const slugs = await listSlugs(env); if (b.action === 'list') { const all = (await Promise.all(slugs.map((s) => env.XMAS.get(themeKey(s), 'json')))).filter(Boolean); return out({ themes: all.map((t) => ({ ...publicView(t), blocked: !!t.blocked, order: t.order ?? null, bytes: t.bytes || 0, files: (t.files || []).length, created: t.created })) }); } const t = await env.XMAS.get(themeKey(String(b.slug || '')), 'json'); if (!t) return out({ error: 'no such theme' }, 404); if (b.action === 'block') { t.blocked = true; t.blockedAt = new Date().toISOString(); } else if (b.action === 'unblock') t.blocked = false; else if (b.action === 'order') t.order = Number(b.order); else if (b.action === 'rename') { t.title = cleanText(b.title, 48) || t.title; } else return out({ error: 'action: list | block | unblock | order | rename' }, 400); await env.XMAS.put(themeKey(t.slug), JSON.stringify(t)); return out({ ok: true, theme: { ...publicView(t), blocked: !!t.blocked, order: t.order ?? null } }); } return out({ error: 'not found', see: 'POST /join, /hello, /upload, /use; GET /themes, /theme/' }, 404); } ============================================================================== === FILE: xmas-kit/guide.md ============================================================================== # BOBAI Xmas Terminal — "{{TITLE}}" by {{BUILDER}} You are helping **{{BUILDER}}** build **"{{TITLE}}"**: their own Xmas look for the **$BOBAI Brain Terminal** on https://brainonbnb.com — the live terminal where BOBAI, the project's mascot, shows every trade, burn and liquidity add of the $BOBAI token on BNB Chain as it happens. This folder is everything you need. Read this file once, fully; then work with your human the way a good teammate would: ask what they want, build it, show it, improve it. From **1 December 2026** visitors pick an Xmas terminal by its builder's name at the snowflake next to LIVE, and the terminal counts how many use each one, every day. Anyone may build one: people, teams, platforms. ## What you build — and what stays - **You build the surroundings and your own animations:** a scene, a sky, snow, lights, decorations around the stations, things that react when somebody buys or a burn happens. Your style, your idea. Nothing is given to you and nothing is expected: you start from two empty pages. - **What always stays as it is:** BOBAI himself (his figure, moves and words), the terminal's labels, numbers, log, timeline, buttons and windows. Your pages lie in layers *between* them; they cannot cover a button or take a click. - **The standard terminal is always one click away** for every visitor. ## The two pages | file | where it lies | use it for | |---|---|---| | `theme/back.html` | behind BOBAI, over the terminal's 3D scene | the world: sky, ground, scenery, things around the stations | | `theme/front.html` | in front of BOBAI, under every label, button and window | an overlay: snow, sparkles, things flying by | Either one or both. Both fill the terminal's window (`100% × 100%`) and are **transparent** unless you paint. In `front.html` never paint a full opaque background: it is an overlay, not a wall. In `back.html` you may paint a whole scene; the 3D stations of the terminal are then behind it — the `layout` message tells you where each one is, so you can decorate them in your own way instead. Put every file you load (images, scripts, fonts, video, 3D models) inside `theme/` and load it with a relative path: ``, ``, `import * as THREE from './lib/three.module.min.js'`. ## What the terminal tells your pages Every message arrives as `window.addEventListener('message', e => …)` with `e.data`: `{ bobai: 'xmas', v: 1, type: …, … }`. Ignore anything without `bobai: 'xmas'`. Positions are CSS pixels inside the terminal's window, `x`/`y` from its top-left; a box is `{ x, y, w, h }`. ```js { type: 'hello', layer: 'back' | 'front', reduced: false, portrait: false, dev: true, theme: { slug, title, builder }, stations: [ { k: 'burnA', name: 'BURN $BOBAI', color: '#ff8a1f', pct: 1 }, … ] } // once, when the page has loaded; only the ones on screen { type: 'layout', w: 1180, h: 760, portrait: false, dpr: 2, figure: { x, y, w, h }, // BOBAI's figure (he moves a little: it comes again when it changes) ring: { x, y }, // the next-buyback ring (the "brain" in the middle) trades: { x, y }, // where the trades come in brain: { x, y, r, bots: 5 }, // the hologram brain; its bots (the project's workers) fly on a ring of radius r around it stations: { burnA: {x,y}, liq: {x,y}, creator: {x,y} }, // only the stations on screen (from 1 December these three) ui: { top: {x,y,w,h}, log: {x,y,w,h}, timeline: {x,y,w,h} } } // the terminal's own boxes: keep busy things away from them // sent after hello, on every resize, and whenever something moved { type: 'event', kind: 'buy' | 'sell', usd: 23.5, alert: false, ours: false } // every trade of $BOBAI { type: 'event', kind: 'buy', usd: 412, alert: true } // a big buy: the terminal shows a moment { type: 'event', kind: 'burn', bobai_burned: 81234, … } // the buyback bot bought and burned $BOBAI { type: 'event', kind: 'liq', bnb: 0.04, … } // liquidity added to the pool (LP burned) { type: 'event', kind: 'tax', usd: 30 } // the token's own 3% tax swap { type: 'moment', kind: 'buy' | 'burn', usd, title } // the terminal is showing a big moment now { type: 'pose', pose: 'cheer' } // BOBAI's move: idle, cheer, coffee, bull, saber, moon, hodl, laugh, think, shrug, // dance, guitar, burn, liq, defi, giggle, buy-big, burn-mega, … (any name may come) { type: 'mood', mood: 'pump' | 'up' | 'flat' | 'down' | 'dump', change_1h_pct: 2.4 } // the market's last hour { type: 'visible', on: false } // the tab went out of sight: stop animating until { on: true } ``` **From 1 December 2026 the terminal has three stations plus the trades:** `burnA` (BURN $BOBAI), `liq` ($BOBAI liquidity, the LP burned) and `creator` (the creator wallet) — the token's 3% tax goes 1% to each, for good. `hello` and `layout` only ever name the stations that are on screen, so build for those three and the `trades` point; draw a station only when `layout.stations` has it (in November you may still see `burnB` $BOB burn, `defi` the DeFi agent and `giggle` the Giggle Academy pot — they end on 1 December). A theme that answers the chain — a burn that lights a candle at `burnA`, a big buy that rings a bell, snow that thickens when the mood pumps — is what makes it a *Brain Terminal* theme rather than a wallpaper. Testing events in dev: open the browser console on the dev page and run `__btXm.emit({ type: 'event', kind: 'burn', bobai_burned: 50000 })` (any message above works the same way). ## The sandbox (what does not work, on purpose) Your pages run in a sandbox, in dev exactly as live: - **no network**: `fetch`, XHR, WebSocket, beacons and files from other sites are blocked → everything in `theme/` - **no `eval`, `new Function`, WebAssembly, web workers** → plain scripts and modules - **no cookies, `localStorage`, `sessionStorage`, IndexedDB** (they throw) → keep state in variables - **no sound**, no forms, no popups, no frames, no clicks (the layers take no pointer events) - **no talking back**: the terminal tells your pages things and listens to nothing they say `node xmas.mjs check` warns about all of this before you upload. ## Fast, calm, on every screen - The terminal measures its own frame rate while a theme is on. **Under 20 fps for 8 seconds, the theme is put away for that visitor** and the standard terminal stays. Phones first: test the dev page at 390 px wide (browser dev tools, device mode) and on a real phone if you can. - Animate with `requestAnimationFrame`, CSS `transform`/`opacity`, or one ``; cap the canvas at `Math.min(devicePixelRatio, 2)`; prefer WebP images and short muted looping video; a few hundred particles, not tens of thousands. - **Stop when `visible` says `on: false`** (and on `document.hidden`). - **`reduced: true`** (the visitor asked their device for less motion): keep it still or nearly still — no flashing, no fast movement, no shaking. Never flash the whole screen for anyone (photosensitivity). - Leave BOBAI's face and the terminal's boxes (`layout.ui`, `layout.figure`) clear of busy motion in `front.html`. ## Pictures and clips — made the way the BOBAI terminal makes its own The terminal's own pictures and clips are made with OpenAI's image models and Google's Veo. You can do the same, with **your human's own keys and credits**: they go into `.env` in this folder (`OPENAI_API_KEY=…`, `GEMINI_API_KEY=…`), stay on this machine and are sent only to OpenAI or Google. Never put a key into `theme/` — `check` and `upload` refuse any file that contains one. ``` node xmas.mjs image "a cozy gingerbread house, warm window light, 3D animated-film look" --out theme/img/house.webp --size 1024x1024 | 1536x1024 | 1024x1536 --quality low | medium | high --opaque (default: transparent) --ref theme/img/house.webp (a new picture in the same style / a frame of a small animation: "the same house, now with snow on the roof") --model … (default: the newest image model the key can use that draws what you asked; transparent needs one that supports it) node xmas.mjs video "snow falls slowly over a quiet pine forest at night, the camera does not move" --out theme/vid/forest.mp4 --ratio 16:9 | 9:16 --secs 8 --image theme/img/start.png (first frame) --last theme/img/end.png (last frame; same as --image = a seamless loop) --model veo-3.1-fast-generate-preview (default) | veo-3.1-generate-preview ``` What works well (learned on the terminal): one style for everything, written into every prompt; transparent PNG/WebP for things that sit on the scene; a reference picture (`--ref`) to keep a set of pictures matching; for a seamless looping clip give the same picture as first and last frame. A clip that must be cut out (a figure over the scene) is drawn on a flat green or blue screen and keyed in a `` or a small WebGL shader — **set `video.crossOrigin = 'anonymous'`** (and `img.crossOrigin` for pictures you read pixels from): your pages are their own origin, and without it the canvas cannot read the frames; a whole backdrop in `back.html` needs no keying. Videos play **muted** (`