Skip to content

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.

fix(shared): reject truncated GLBs before upload, roll Money Pulse numbers into the right unit, and lock URL guards with tests

nirholasab0b03be2b1e
diff --git a/src/shared/glb-magic.js b/src/shared/glb-magic.js
index aa1f2de52..a14ef59bc 100644
--- a/src/shared/glb-magic.js
+++ b/src/shared/glb-magic.js
@@ -6,8 +6,9 @@
/**
* Returns true iff the file has a valid binary glTF 2.0 header.
- * Checks: magic bytes ('glTF'), version (must be 2), and that the
- * declared file length field is at least the minimum GLB size.
+ * Checks: magic bytes ('glTF'), version (must be 2), and that the declared
+ * file length (uint32 at offset 8) is at least the 20-byte minimum GLB size
+ * and no larger than the file itself, so a truncated upload is rejected here.
*
* @param {File} file
* @returns {Promise<boolean>}
@@ -21,5 +22,8 @@ export async function isValidGlbMagic(file) {
// Version: must be 2 (little-endian uint32 at offset 4)
const version = new DataView(buf).getUint32(4, true);
if (version !== 2) return false;
+ // Declared length: same bounds as the server (api/_lib/glb-inspect.js).
+ const declaredLen = new DataView(buf).getUint32(8, true);
+ if (declaredLen < 20 || declaredLen > file.size) return false;
return true;
}
diff --git a/src/shared/pulse-format.js b/src/shared/pulse-format.js
index d83c7f0e5..36e911b49 100644
--- a/src/shared/pulse-format.js
+++ b/src/shared/pulse-format.js
@@ -15,11 +15,15 @@ import { walletChipHTML } from './agent-wallet-chip.js';
export const esc = (s) =>
String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+// The unit is chosen after rounding, so a value that rounds up to the next
+// band (999.6 -> 1000) is labelled in that band ($1.0k), never "$1000".
export function fmtUsd(n) {
if (!(Number(n) > 0)) return '$0';
const v = Number(n);
- if (v >= 1000) return `$${(v / 1000).toFixed(1)}k`;
- return `$${v.toFixed(v < 10 ? 2 : 0)}`;
+ if (v >= 1_000_000 || Math.round(v / 1000 * 10) / 10 >= 1000) return `$${(v / 1_000_000).toFixed(1)}M`;
+ if (v >= 1000 || Math.round(v) >= 1000) return `$${(v / 1000).toFixed(1)}k`;
+ if (v < 10 && Number(v.toFixed(2)) < 10) return `$${v.toFixed(2)}`;
+ return `$${v.toFixed(0)}`;
}
export function fmtSol(n) {
@@ -33,11 +37,11 @@ export function fmtNum(n) {
return String(v);
}
-// Whole-token $THREE amount → compact label (e.g. 12.4k, 1.2M, 340).
+
export function fmtThree(n) {
const v = Number(n) || 0;
- if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(2)}M`;
- if (v >= 1000) return `${(v / 1000).toFixed(1)}k`;
+ if (v >= 1_000_000 || Math.round(v / 1000 * 10) / 10 >= 1000) return `${(v / 1_000_000).toFixed(2)}M`;
+ if (v >= 1000 || Math.round(v) >= 1000) return `${(v / 1000).toFixed(1)}k`;
if (v >= 100) return String(Math.round(v));
return v.toFixed(v < 1 ? 3 : 1).replace(/\.0$/, '');
}
diff --git a/tests/glb-magic.test.js b/tests/glb-magic.test.js
new file mode 100644
index 000000000..e00d5db00
--- /dev/null
+++ b/tests/glb-magic.test.js
@@ -0,0 +1,54 @@
+import { describe, it, expect, vi } from 'vitest';
+import { isValidGlbMagic } from '../src/shared/glb-magic.js';
+
+function header({ magic = 0x46546c67, version = 2, declared = 12 } = {}) {
+ const b = new ArrayBuffer(12);
+ const v = new DataView(b);
+ v.setUint32(0, magic, true);
+ v.setUint32(4, version, true);
+ v.setUint32(8, declared, true);
+ return new Uint8Array(b);
+}
+
+// A file of `size` bytes whose first 12 bytes are `head`.
+function glb(head, size = head.length) {
+ const body = new Uint8Array(Math.max(size, head.length));
+ body.set(head);
+ return new File([body], 'a.glb');
+}
+
+describe('isValidGlbMagic', () => {
+ it('accepts a valid header whose declared length equals the file size', async () => {
+ expect(await isValidGlbMagic(glb(header({ declared: 64 }), 64))).toBe(true);
+ });
+
+ it('accepts a declared length smaller than the file (trailing bytes)', async () => {
+ expect(await isValidGlbMagic(glb(header({ declared: 40 }), 64))).toBe(true);
+ });
+
+ it('rejects a declared length larger than the file (truncated)', async () => {
+ expect(await isValidGlbMagic(glb(header({ declared: 5000 })))).toBe(false);
+ });
+
+ it('rejects a declared length below the 20-byte minimum', async () => {
+ expect(await isValidGlbMagic(glb(header({ declared: 8 }), 64))).toBe(false);
+ expect(await isValidGlbMagic(glb(header({ declared: 19 }), 64))).toBe(false);
+ expect(await isValidGlbMagic(glb(header({ declared: 20 }), 64))).toBe(true);
+ });
+
+ it('rejects wrong magic, version 1, short files and a missing file', async () => {
+ expect(await isValidGlbMagic(glb(header({ magic: 0x12345678, declared: 64 }), 64))).toBe(false);
+ expect(await isValidGlbMagic(glb(header({ version: 1, declared: 64 }), 64))).toBe(false);
+ expect(await isValidGlbMagic(new File([new Uint8Array(11)], 'a.glb'))).toBe(false);
+ expect(await isValidGlbMagic(null)).toBe(false);
+ expect(await isValidGlbMagic(undefined)).toBe(false);
+ });
+
+ it('reads only the first 12 bytes', async () => {
+ const file = glb(header({ declared: 64 }), 64);
+ const slice = vi.spyOn(file, 'slice');
+ await isValidGlbMagic(file);
+ expect(slice).toHaveBeenCalledTimes(1);
+ expect(slice).toHaveBeenCalledWith(0, 12);
+ });
+});
diff --git a/tests/pulse-format.test.js b/tests/pulse-format.test.js
new file mode 100644
index 000000000..3fcc55732
--- /dev/null
+++ b/tests/pulse-format.test.js
@@ -0,0 +1,38 @@
+import { describe, it, expect } from 'vitest';
+import { fmtUsd, fmtThree } from '../src/shared/pulse-format.js';
+
+describe('fmtUsd', () => {
+ it.each([
+ [0, '$0'], [5, '$5.00'], [9.99, '$9.99'], [10, '$10'], [42, '$42'], [999, '$999'],
+ [1000, '$1.0k'], [12345, '$12.3k'], [1_000_000, '$1.0M'], [2_500_000, '$2.5M'],
+ ])('keeps %s in its band: %s', (input, out) => expect(fmtUsd(input)).toBe(out));
+
+ it.each([
+ [9.999, '$10'], [999.6, '$1.0k'], [999_999, '$1.0M'],
+ ])('rolls %s over to the next unit after rounding: %s', (input, out) => expect(fmtUsd(input)).toBe(out));
+
+ it.each([
+ [9.99, '$9.99'], [10, '$10'], [10.01, '$10'],
+ [999.4, '$999'], [1000, '$1.0k'], [1000.4, '$1.0k'],
+ [999_949, '$999.9k'], [999_950, '$1.0M'], [1_000_001, '$1.0M'],
+ ])('boundary %s: %s', (input, out) => expect(fmtUsd(input)).toBe(out));
+
+ it.each([[-5], [NaN], ['x'], [null], [undefined]])('renders %s as $0', (input) => expect(fmtUsd(input)).toBe('$0'));
+});
+
+describe('fmtThree', () => {
+ it.each([
+ [0.5, '0.500'], [42, '42'], [340, '340'], [12400, '12.4k'], [1_200_000, '1.20M'],
+ ])('keeps %s in its band: %s', (input, out) => expect(fmtThree(input)).toBe(out));
+
+ it.each([
+ [999.6, '1.0k'], [999_950, '1.00M'],
+ ])('rolls %s over to the next unit after rounding: %s', (input, out) => expect(fmtThree(input)).toBe(out));
+
+ it.each([
+ [999.4, '999'], [1000, '1.0k'], [1000.4, '1.0k'],
+ [999_949, '999.9k'], [999_950, '1.00M'], [1_000_000, '1.00M'], [1_000_001, '1.00M'],
+ ])('boundary %s: %s', (input, out) => expect(fmtThree(input)).toBe(out));
+
+ it.each([[NaN, '0.000'], ['x', '0.000'], [null, '0.000'], [-5, '-5.000']])('renders %s as before: %s', (input, out) => expect(fmtThree(input)).toBe(out));
+});
diff --git a/tests/safe-model-url.test.js b/tests/safe-model-url.test.js
new file mode 100644
index 000000000..ba7531eb6
--- /dev/null
+++ b/tests/safe-model-url.test.js
@@ -0,0 +1,35 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { isSafeQueryModelUrl } from '../src/shared/safe-model-url.js';
+
+describe('isSafeQueryModelUrl', () => {
+ beforeEach(() => vi.stubGlobal('location', { origin: 'https://three.ws' }));
+ afterEach(() => vi.unstubAllGlobals());
+
+ it.each([
+ ['/avatars/a.glb', true],
+ ['//evil.com/a.glb', false],
+ ['ipfs://bafy', true],
+ ['ar://abc123', true],
+ ['https://pub-x.r2.dev/a.glb', true],
+ ['https://three.ws.evil.com/a.glb', false],
+ ['https://evilr2.dev/a.glb', false],
+ ['http://three.ws/a.glb', false],
+ ['https://three.ws/x.glb', true],
+ ['https://cdn.three.ws/x.glb', true],
+ ['https://storage.googleapis.com/b/a.glb', true],
+ ])('%s -> %s', (url, expected) => expect(isSafeQueryModelUrl(url)).toBe(expected));
+
+ it.each([
+ 'https://three.ws.evil.com/a.glb', 'https://evilthree.ws/a.glb',
+ 'https://r2.dev.evil.com/a.glb', 'https://evilr2.dev/a.glb',
+ 'https://ipfs.io.evil.com/a.glb', 'https://evilipfs.io/a.glb',
+ 'https://mypinata.cloud.evil.com/a.glb', 'https://evilarweave.net/a.glb',
+ ])('rejects look-alike host %s', (url) => expect(isSafeQueryModelUrl(url)).toBe(false));
+
+ it.each([[null], [undefined], [42], [{}], [''], ['https://']])('rejects %j', (v) => expect(isSafeQueryModelUrl(v)).toBe(false));
+
+ it('does not leave a location stub behind', () => {
+ vi.unstubAllGlobals();
+ expect(typeof globalThis.location === 'undefined' || globalThis.location.origin !== 'https://three.ws').toBe(true);
+ });
+});
diff --git a/tests/url-scheme-guards.test.js b/tests/url-scheme-guards.test.js
new file mode 100644
index 000000000..e6661264a
--- /dev/null
+++ b/tests/url-scheme-guards.test.js
@@ -0,0 +1,44 @@
+import { describe, it, expect } from 'vitest';
+import { safeUrl } from '../src/safe-url.js';
+import { sanitizeUrl } from '../src/shared/sanitize-url.js';
+
+const SCRIPT = ['javascript:alert(1)', ' javascript:alert(1)', 'JaVaScRiPt:x', 'JAVASCRIPT:x', 'data:text/html,x', 'DaTa:x', ' vbscript:x', 'VBScript:x'];
+const NON_STRINGS = [null, undefined, 42, {}, [], true];
+
+describe('safeUrl', () => {
+ it.each(SCRIPT)('rejects script scheme %j', (u) => expect(safeUrl(u)).toBe('#'));
+ it('rejects protocol-relative //host', () => expect(safeUrl('//evil.com')).toBe('#'));
+ it.each([
+ ['https://x.y', 'https://x.y'], ['http://x.y', 'http://x.y'], ['/path', '/path'],
+ ['#top', '#top'], ['./a', './a'], ['../a', '../a'],
+ ])('allows %s', (u, out) => expect(safeUrl(u)).toBe(out));
+ it.each(NON_STRINGS)('returns the fallback for non-string %j', (u) => {
+ expect(safeUrl(u)).toBe('#');
+ expect(safeUrl(u, '/home')).toBe('/home');
+ });
+ it.each(['', ' ', '\n'])('returns the fallback for blank %j', (u) => {
+ expect(safeUrl(u)).toBe('#');
+ expect(safeUrl(u, '/home')).toBe('/home');
+ });
+ it('honours a custom fallback on rejection', () => expect(safeUrl('javascript:x', '/safe')).toBe('/safe'));
+
+ // Intentional differences from sanitizeUrl, locked so changing them is deliberate.
+ it('differs: rejects mailto:', () => expect(safeUrl('mailto:[email protected]')).toBe('#'));
+ it('differs: allows ./ relative paths', () => expect(safeUrl('./a')).toBe('./a'));
+ it('differs: returns an allowed URL untrimmed', () => expect(safeUrl(' https://x.y ')).toBe(' https://x.y '));
+});
+
+describe('sanitizeUrl', () => {
+ it.each(SCRIPT)('rejects script scheme %j', (u) => expect(sanitizeUrl(u)).toBe('#'));
+ it('rejects protocol-relative //host', () => expect(sanitizeUrl('//evil.com')).toBe('#'));
+ it.each([
+ ['https://x.y', 'https://x.y'], ['http://x.y', 'http://x.y'], ['/path', '/path'],
+ ['#top', '#top'], ['mailto:[email protected]', 'mailto:[email protected]'],
+ ])('allows %s', (u, out) => expect(sanitizeUrl(u)).toBe(out));
+ it.each(NON_STRINGS)('returns # for non-string %j', (u) => expect(sanitizeUrl(u)).toBe('#'));
+ it.each(['', ' ', '\n'])('returns # for blank %j', (u) => expect(sanitizeUrl(u)).toBe('#'));
+
+ it('differs: allows mailto:', () => expect(sanitizeUrl('mailto:[email protected]')).toBe('mailto:[email protected]'));
+ it('differs: rejects ./ relative paths', () => expect(sanitizeUrl('./a')).toBe('#'));
+ it('differs: returns an allowed URL trimmed', () => expect(sanitizeUrl(' https://x.y ')).toBe('https://x.y'));
+});