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: audit — parallelize detectHolder, normalize isGrantableTier, drop unused SELECT columns, fix code-input caret, add tier changelog entry

qhqf9ce47d6695c1
diff --git a/api/_lib/account-tier.js b/api/_lib/account-tier.js
index f67b9e57b..34443d060 100644
--- a/api/_lib/account-tier.js
+++ b/api/_lib/account-tier.js
@@ -123,7 +123,7 @@ export function tierById(id) {
/** True if `id` is a mode an admin is allowed to grant. */
export function isGrantableTier(id) {
- return GRANTABLE_TIER_IDS.includes(String(id || ''));
+ return GRANTABLE_TIER_IDS.includes(String(id || '').toLowerCase());
}
/**
@@ -147,13 +147,12 @@ export function normalizeTierGrant(input) {
* @returns {Promise<{ isHolder: boolean, amount: number, usd: number }>}
*/
export async function detectHolder(walletAddresses = []) {
- const seen = new Set();
+ const unique = [...new Set(walletAddresses.filter(Boolean))];
+ if (unique.length === 0) return { isHolder: false, amount: 0, usd: 0 };
+ const results = await Promise.all(unique.map((w) => holderUsd(w)));
let amount = 0;
let usd = 0;
- for (const w of walletAddresses) {
- if (!w || seen.has(w)) continue;
- seen.add(w);
- const held = await holderUsd(w); // validates Solana addr + fails closed to 0
+ for (const held of results) {
if (held.amount > amount) amount = held.amount;
if (held.usd > usd) usd = held.usd;
}
diff --git a/api/users/me/tier.js b/api/users/me/tier.js
index 659b01f01..7e60a493f 100644
--- a/api/users/me/tier.js
+++ b/api/users/me/tier.js
@@ -29,7 +29,7 @@ export default wrap(async (req, res) => {
if (!rl.success) return rateLimited(res, rl);
const [user] = await sql`
- select id, plan, account_tier, wallet_address, display_name, username
+ select id, plan, account_tier, wallet_address
from users
where id = ${userId} and deleted_at is null
limit 1
diff --git a/data/changelog.json b/data/changelog.json
index 97dff6a50..d5c599c09 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,20 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-21",
+ "title": "Membership tiers and referral codes",
+ "summary": "Every member now wears a mode on their card: User, Beta, Pro, Holder, or Three Dimensional. The tier panel on your referrals page shows every badge you hold, what each one unlocks, and the next mode to aim for — with a live $THREE holder check across all your linked wallets. Referral codes now default to your name and you can customize them at any time from your membership card.",
+ "tags": ["feature"],
+ "link": "/dashboard/referrals"
+ },
+ {
+ "date": "2026-06-21",
+ "title": "User profiles: wallets, NFTs, accessories, shop listings, fork agents and avatars",
+ "summary": "The /u/ profile pages now surface the full picture of what a user owns and builds. A wallets row shows every linked Solana and EVM address with one-click copy and a link to the chain explorer. On-chain collectibles load in a lazy background pass — 3D NFTs display as interactive model-viewer tiles; image NFTs sit in a grid. Any premium accessories purchased through the x402 cosmetics rail appear in their own tab with rarity badges. Published avatars and agents carry a Fork button so visitors can clone the item directly into their own account. Items actively listed for sale land in a For sale tab with direct buy links. All counts surface in the stat strip.",
+ "tags": ["feature", "improvement"],
+ "link": "/u"
+ },
{
"date": "2026-06-21",
"title": "Guided Tour: smoother, more reliable, more accessible",
diff --git a/src/dashboard-next/pages/referrals.js b/src/dashboard-next/pages/referrals.js
index 82802c35a..5b2087de3 100644
--- a/src/dashboard-next/pages/referrals.js
+++ b/src/dashboard-next/pages/referrals.js
@@ -737,11 +737,13 @@ function wireCodeEditor(host, card) {
input.addEventListener('input', () => {
// Live-sanitize to the canonical alphabet so the field only ever holds
// what can actually be saved.
- const caret = input.selectionStart;
const cleaned = input.value.replace(/[^A-Za-z0-9]/g, '').toUpperCase().slice(0, CODE_MAX);
if (cleaned !== input.value) {
input.value = cleaned;
- if (caret != null) input.setSelectionRange(caret - 1, caret - 1);
+ // Place cursor at end of cleaned value — multi-char strips (e.g.
+ // paste of "my-code!") may remove more than one character, making
+ // caret - 1 wrong. End-of-field is always safe and expected.
+ input.setSelectionRange(cleaned.length, cleaned.length);
}
clearTimeout(debounce);
debounce = setTimeout(evaluate, 280);
diff --git a/tests/api-users-me-tier.test.js b/tests/api-users-me-tier.test.js
new file mode 100644
index 000000000..24c519aaf
--- /dev/null
+++ b/tests/api-users-me-tier.test.js
@@ -0,0 +1,131 @@
+// Endpoint test for GET /api/users/me/tier — drives the real handler with a
+// fake req/res and mocked DB / auth / rate-limit / on-chain read. Proves the
+// response contract the dashboard tier panel renders against: primary tier,
+// stacked badges, next mode, and the full ladder. http.js (json/cors/method/
+// wrap) runs for real so the status + envelope are genuinely exercised.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Tagged-template `sql` that returns whatever the test queued, in order.
+const queue = [];
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => (queue.length ? queue.shift() : [])),
+}));
+
+// Auth: the test sets `session` / `bearer` per case.
+let session = null;
+let bearer = null;
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => session),
+ authenticateBearer: vi.fn(async () => bearer),
+ extractBearer: vi.fn(() => null),
+}));
+
+// Rate limiter: always allow.
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { widgetRead: vi.fn(async () => ({ success: true, limit: 60, remaining: 59, reset: Date.now() + 1000 })) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+// On-chain holder read (account-tier.detectHolder → three-tier.holderUsd).
+const holderUsd = vi.fn(async () => ({ amount: 0, usd: 0, priceUsd: 0 }));
+vi.mock('../api/_lib/three-tier.js', () => ({ holderUsd: (...a) => holderUsd(...a) }));
+
+import handler from '../api/users/me/tier.js';
+
+function mockRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ end(payload) { this.headersSent = true; this.writableEnded = true; this.body = payload; },
+ get json() { return this.body ? JSON.parse(this.body) : null; },
+ };
+}
+
+const req = (over = {}) => ({ method: 'GET', url: '/api/users/me/tier', headers: {}, socket: {}, ...over });
+
+beforeEach(() => {
+ queue.length = 0;
+ session = null;
+ bearer = null;
+ vi.clearAllMocks();
+ holderUsd.mockResolvedValue({ amount: 0, usd: 0, priceUsd: 0 });
+});
+
+describe('GET /api/users/me/tier', () => {
+ it('401s with no session or bearer', async () => {
+ const res = mockRes();
+ await handler(req(), res);
+ expect(res.statusCode).toBe(401);
+ expect(res.json.error).toBe('unauthorized');
+ });
+
+ it('resolves a default account to the user tier with the full ladder', async () => {
+ session = { id: 'u1' };
+ queue.push([{ id: 'u1', plan: 'free', account_tier: null, wallet_address: null }]); // user row
+ queue.push([]); // linked solana wallets
+
+ const res = mockRes();
+ await handler(req(), res);
+
+ expect(res.statusCode).toBe(200);
+ const b = res.json;
+ expect(b.tier.id).toBe('user');
+ expect(b.badges.map((x) => x.id)).toEqual(['user']);
+ expect(b.next.id).toBe('beta');
+ expect(b.holder.isHolder).toBe(false);
+ expect(b.tiers).toHaveLength(5);
+ expect(holderUsd).not.toHaveBeenCalled(); // no wallets → no RPC
+ expect(res.getHeader('cache-control')).toBe('no-store');
+ });
+
+ it('stacks granted + plan + on-chain holder badges, picking the highest as primary', async () => {
+ session = { id: 'u2' };
+ queue.push([{ id: 'u2', plan: 'team', account_tier: 'beta', wallet_address: 'LoginWallet111' }]);
+ queue.push([{ address: 'LinkedWallet222' }]); // linked solana wallet
+ // First wallet holds nothing; the linked one holds $THREE.
+ holderUsd
+ .mockResolvedValueOnce({ amount: 0, usd: 0, priceUsd: 0 })
+ .mockResolvedValueOnce({ amount: 5000, usd: 230, priceUsd: 0.046 });
+
+ const res = mockRes();
+ await handler(req(), res);
+
+ expect(res.statusCode).toBe(200);
+ const b = res.json;
+ const ids = b.badges.map((x) => x.id);
+ expect(ids).toEqual(['user', 'beta', 'pro', 'holder']); // rank order
+ expect(b.tier.id).toBe('holder'); // highest-ranked active
+ expect(b.granted).toBe('beta');
+ expect(b.holder).toEqual({ isHolder: true, amount: 5000, usd: 230 });
+ expect(b.next.id).toBe('three-dimensional');
+ expect(holderUsd).toHaveBeenCalledTimes(2); // login + linked wallet
+ });
+
+ it('authenticates via Bearer when there is no session', async () => {
+ bearer = { userId: 'u3' };
+ queue.push([{ id: 'u3', plan: 'pro', account_tier: null, wallet_address: null }]);
+ queue.push([]);
+
+ const res = mockRes();
+ await handler(req(), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.json.tier.id).toBe('pro');
+ });
+
+ it('404s when the user record is gone', async () => {
+ session = { id: 'ghost' };
+ queue.push([]); // no user row
+
+ const res = mockRes();
+ await handler(req(), res);
+ expect(res.statusCode).toBe(404);
+ expect(res.json.error).toBe('not_found');
+ });
+});