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.

feat(access): comp an allowlisted account through every $THREE gate, no wallet required

nirholas725cb082dd8e
diff --git a/api/_lib/comp-access.js b/api/_lib/comp-access.js
new file mode 100644
index 000000000..163ad8695
--- /dev/null
+++ b/api/_lib/comp-access.js
@@ -0,0 +1,136 @@
+// Comped platform access: the explicit allowlist of accounts that get every
+// $THREE-gated feature without holding, without linking a wallet, and without
+// paying per use.
+//
+// Why this exists: hold-to-access (three-access.js + require-three.js) is the
+// platform's monetization lever, but a small set of accounts are deliberately
+// exempt: the owner's own accounts, and creators/partners the owner has granted
+// lifetime access. Encoding that as data in ONE module keeps the exemption
+// auditable in git and revocable in one edit, instead of scattering
+// `if (user.id === …)` branches through every gated endpoint.
+//
+// Where it applies: every enforced gate resolves through requireFeatureAccess
+// (api/_lib/require-three.js), so the check lives there and automatically covers
+// forge.high (High-quality generation), forge.gameready (Game-Ready GLB/FBX
+// export), and any gate added later. The read endpoint GET /api/three/access
+// applies it too, so the UI renders unlocked instead of showing a lock the
+// server would not actually enforce.
+//
+// What it grants: the TOP tier level, so a comped account clears every gate
+// regardless of that gate's minLevel, plus the top free-lane rate multiplier.
+// It never bypasses BYOK (a caller's own vendor key is still their own key) and
+// never touches the abuse ceilings that protect real platform spend.
+//
+// What it costs: nothing on the anonymous path. The lookup is guarded by
+// hasSessionCookie(), so a request with no session never issues a query. The
+// zero-latency anonymous free lane stays exactly as fast as it was.
+//
+// Extending it: add the handle to COMPED_ACCOUNTS below, or set the env var
+// THREE_COMP_ACCOUNTS to a comma-separated list of handles / emails / user ids.
+// Env entries are MERGED with the built-ins, never replace them, so an env typo
+// can't silently revoke a comp that was granted in code.
+//
+// Which identifiers are trusted, and why: `username`, `email`, and `id` are all
+// uniquely indexed on the users table, and a username-registered account's handle
+// is also the local part of the platform-issued `<handle>@users.three.ws.local`
+// address that api/auth/[action].js mints for it. `display_name` is deliberately
+// NOT matched: it is user-settable and carries no uniqueness constraint, so
+// honoring it would let anyone comp themselves by renaming.
+
+import { TIERS } from './three-tier.js';
+import { getSessionUser, hasSessionCookie } from './auth.js';
+
+// Accounts granted full platform access, by handle. Matching is case-insensitive
+// and also accepts an email or user id, so an env-supplied entry can be any
+// stable identifier the account is known by.
+export const COMPED_ACCOUNTS = Object.freeze([
+ 'nichisarealnigga',
+]);
+
+// The email domain the platform issues to username-registered accounts (see
+// handleRegister in api/auth/[action].js). Addresses in it are server-minted and
+// unique, so their local part is a trustworthy stand-in for the handle on an
+// account whose `username` column was never populated.
+const PLATFORM_EMAIL_DOMAIN = 'users.three.ws.local';
+
+// The tier a comped account resolves to: the top of the ladder, so it clears
+// every gate no matter how high that gate's minLevel is set later.
+export const COMP_TIER = TIERS[TIERS.length - 1];
+
+/** The granted tier level (top of the ladder). */
+export const COMP_TIER_LEVEL = COMP_TIER.level;
+
+function normalize(value) {
+ return typeof value === 'string' ? value.trim().toLowerCase() : '';
+}
+
+/**
+ * The full set of comped identifiers: the built-in list merged with anything in
+ * THREE_COMP_ACCOUNTS. Read per call so an env change takes effect on the next
+ * request without a redeploy (the list is tiny; this is a few string ops).
+ * @returns {Set<string>} lowercased usernames / emails / user ids
+ */
+export function compedIdentifiers() {
+ const set = new Set(COMPED_ACCOUNTS.map(normalize).filter(Boolean));
+ const extra = typeof process !== 'undefined' ? process.env?.THREE_COMP_ACCOUNTS : null;
+ if (extra) {
+ for (const entry of String(extra).split(',')) {
+ const id = normalize(entry);
+ if (id) set.add(id);
+ }
+ }
+ return set;
+}
+
+/**
+ * The identifiers a user account can be matched by: its username, its email, its
+ * id, and (when the email is a platform-issued `@users.three.ws.local` address)
+ * the handle in that address's local part. Every one of these is unique per
+ * account, so none of them can be claimed by a second user.
+ * @param {{ id?: string, username?: string, email?: string } | null} user
+ * @returns {string[]} lowercased identifiers (empty for a missing user)
+ */
+export function identifiersForUser(user) {
+ if (!user) return [];
+ const out = [normalize(user.username), normalize(user.email), normalize(user.id)];
+ const email = normalize(user.email);
+ const at = email.lastIndexOf('@');
+ if (at > 0 && email.slice(at + 1) === PLATFORM_EMAIL_DOMAIN) {
+ out.push(email.slice(0, at));
+ }
+ return out.filter(Boolean);
+}
+
+/**
+ * Is this resolved session user comped? The grant survives an email or username
+ * change as long as the listed identifier still resolves to the account.
+ * @param {{ id?: string, username?: string, email?: string } | null} user
+ * @returns {boolean}
+ */
+export function isCompedUser(user) {
+ const ids = compedIdentifiers();
+ if (ids.size === 0) return false;
+ return identifiersForUser(user).some((id) => ids.has(id));
+}
+
+/**
+ * Resolve the caller's comped status from the request. Never throws: an auth or
+ * DB hiccup resolves to "not comped", which just means the normal hold-or-pay
+ * gate applies (fail closed on the perk, never fail the request).
+ *
+ * Anonymous requests short-circuit on the cookie check with zero queries.
+ *
+ * @param {import('http').IncomingMessage} req
+ * @param {import('http').ServerResponse} [res]
+ * @returns {Promise<{ comped: boolean, user: object|null }>}
+ */
+export async function resolveCompAccess(req, res) {
+ if (!hasSessionCookie(req)) return { comped: false, user: null };
+ let user = null;
+ try {
+ user = await getSessionUser(req, res);
+ } catch {
+ return { comped: false, user: null };
+ }
+ return { comped: isCompedUser(user), user };
+}
diff --git a/api/_lib/require-three.js b/api/_lib/require-three.js
index d0aaa5237..16a66f4dd 100644
--- a/api/_lib/require-three.js
+++ b/api/_lib/require-three.js
@@ -21,6 +21,7 @@ import { verifyTierPass, resolveUserTier } from './three-tier.js';
import { accessFromTierLevel, gatedFeature, requiredTierFor } from './three-access.js';
import { catalogEntry } from './pricing/catalog.js';
import { getSessionUser } from './auth.js';
+import { resolveCompAccess, COMP_TIER_LEVEL } from './comp-access.js';
import { TOKEN_MINT, publicConfig } from './token/config.js';
// The "how to acquire $THREE" block the 402 surfaces so a non-holder can act
@@ -41,10 +42,27 @@ function acquireBlock() {
};
}
-// Resolve the caller's verified holder level for gating. Pass-first (pure HMAC,
-// never depends on a live RPC), then the session user's on-chain tier, then
+// Resolve the caller's verified holder level for gating. Comp-first (an allowlisted
+// account is entitled regardless of what it holds), then a signed tier pass (pure
+// HMAC, never depends on a live RPC), then the session user's on-chain tier, then
// anonymous Member (level 0). Never throws.
async function resolveCaller(req, res, body) {
+ // 0. Comped account (api/_lib/comp-access.js): full access with no wallet, no
+ // hold, no payment. Checked FIRST so a stale low-tier pass in the client's
+ // storage can't under-resolve a comped caller, and it costs an anonymous
+ // request nothing (the lookup short-circuits without a session cookie).
+ const comp = await resolveCompAccess(req, res);
+ if (comp.comped) {
+ return {
+ level: COMP_TIER_LEVEL,
+ wallet: comp.user?.wallet_address || null,
+ usd: null,
+ source: 'comp',
+ hasUser: true,
+ hasWallet: Boolean(comp.user?.wallet_address),
+ };
+ }
+
// 1. Signed tier pass — header or parsed body. Pure HMAC, no RPC.
const token = req.headers?.['x-three-tier-pass'] || body?.tier_pass || null;
if (token) {
diff --git a/api/forge.js b/api/forge.js
index 3f4e49c6b..9d69c0f67 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -104,6 +104,7 @@ import {
import { env as _env } from './_lib/env.js';
import { verifyTierPass, TIERS } from './_lib/three-tier.js';
import { requireFeatureAccess } from './_lib/require-three.js';
+import { resolveCompAccess, COMP_TIER } from './_lib/comp-access.js';
import { priceForAction } from './_lib/pricing/catalog.js';
import {
assertForgePayment,
@@ -188,13 +189,22 @@ export function nimCooldownSeconds(err) {
// generation ceiling by that tier's multiplier. The pass is pure-HMAC verifiable
// (no RPC/price feed), so this adds zero latency to the anonymous free lane. An
// absent or invalid pass simply leaves the multiplier at 1 (the base 60/h).
-function freeLaneMultiplier(req, body) {
+// A comped account (api/_lib/comp-access.js) gets the top multiplier without a
+// pass. Its lookup is cookie-guarded, so the anonymous path stays query-free.
+async function freeLaneMultiplier(req, body) {
const token = req.headers?.['x-three-tier-pass'] || body?.tier_pass || null;
- if (!token) return 1;
- const payload = verifyTierPass(token);
- if (!payload) return 1;
- const tier = TIERS.find((t) => t.level === payload.level);
- return tier?.rateMultiplier || 1;
+ let fromPass = 1;
+ if (token) {
+ const payload = verifyTierPass(token);
+ const tier = payload ? TIERS.find((t) => t.level === payload.level) : null;
+ fromPass = tier?.rateMultiplier || 1;
+ }
+ // A pass that actually lifts the ceiling short-circuits: the holder perk is
+ // already proven and no lookup is worth doing. A Member-level (or absent) pass
+ // lifts nothing, so fall through and let a comp answer instead.
+ if (fromPass > 1) return fromPass;
+ const { comped } = await resolveCompAccess(req);
+ return comped ? COMP_TIER.rateMultiplier || 1 : fromPass;
}
// Returns true when the request carries the internal cron seed token, meaning
@@ -1263,7 +1273,7 @@ async function startJob(req, res) {
const isFreeLane = backendMeta?.free === true;
if (!isInternalSeedRequest(req)) {
const rl = isFreeLane
- ? await limits.mcp3dGenerateFreeTiered(ip, freeLaneMultiplier(req, body))
+ ? await limits.mcp3dGenerateFreeTiered(ip, await freeLaneMultiplier(req, body))
: await limits.mcp3dGenerate(ip);
if (!rl.success) {
return rateLimited(res, rl, 'Generation limit reached. Try again shortly.');
diff --git a/api/gpt-forge.js b/api/gpt-forge.js
index 49932ef9e..914381842 100644
--- a/api/gpt-forge.js
+++ b/api/gpt-forge.js
@@ -112,6 +112,7 @@ import {
import { env as _env } from './_lib/env.js';
import { verifyTierPass, TIERS } from './_lib/three-tier.js';
import { requireFeatureAccess } from './_lib/require-three.js';
+import { resolveCompAccess, COMP_TIER } from './_lib/comp-access.js';
import { priceForAction } from './_lib/pricing/catalog.js';
import {
assertForgePayment,
@@ -196,13 +197,22 @@ export function nimCooldownSeconds(err) {
// generation ceiling by that tier's multiplier. The pass is pure-HMAC verifiable
// (no RPC/price feed), so this adds zero latency to the anonymous free lane. An
// absent or invalid pass simply leaves the multiplier at 1 (the base 60/h).
-function freeLaneMultiplier(req, body) {
+// A comped account (api/_lib/comp-access.js) gets the top multiplier without a
+// pass. Its lookup is cookie-guarded, so the anonymous path stays query-free.
+async function freeLaneMultiplier(req, body) {
const token = req.headers?.['x-three-tier-pass'] || body?.tier_pass || null;
- if (!token) return 1;
- const payload = verifyTierPass(token);
- if (!payload) return 1;
- const tier = TIERS.find((t) => t.level === payload.level);
- return tier?.rateMultiplier || 1;
+ let fromPass = 1;
+ if (token) {
+ const payload = verifyTierPass(token);
+ const tier = payload ? TIERS.find((t) => t.level === payload.level) : null;
+ fromPass = tier?.rateMultiplier || 1;
+ }
+ // A pass that actually lifts the ceiling short-circuits: the holder perk is
+ // already proven and no lookup is worth doing. A Member-level (or absent) pass
+ // lifts nothing, so fall through and let a comp answer instead.
+ if (fromPass > 1) return fromPass;
+ const { comped } = await resolveCompAccess(req);
+ return comped ? COMP_TIER.rateMultiplier || 1 : fromPass;
}
// Returns true when the request carries the internal cron seed token, meaning
@@ -1266,7 +1276,7 @@ async function startJob(req, res) {
const isFreeLane = backendMeta?.free === true;
if (!isInternalSeedRequest(req)) {
const rl = isFreeLane
- ? await limits.mcp3dGenerateFreeTiered(ip, freeLaneMultiplier(req, body))
+ ? await limits.mcp3dGenerateFreeTiered(ip, await freeLaneMultiplier(req, body))
: await limits.mcp3dGenerate(ip);
if (!rl.success) {
return rateLimited(res, rl, 'Generation limit reached. Try again shortly.');
diff --git a/api/three/[action].js b/api/three/[action].js
index 5131d17bc..fea29eded 100644
--- a/api/three/[action].js
+++ b/api/three/[action].js
@@ -34,6 +34,7 @@ import {
TIERS,
} from '../_lib/three-tier.js';
import { accessFromTierLevel, listGatedFeatures } from '../_lib/three-access.js';
+import { isCompedUser, COMP_TIER } from '../_lib/comp-access.js';
import { verifySiwsSignature } from '../_lib/siws.js';
import { creatorEarnings, economyStats, listRewardsDistributions } from '../_lib/token/index.js';
import { priceName, isValidLabel, RARITY_TIERS } from '../_lib/pricing/name-rarity.js';
@@ -420,6 +421,14 @@ async function handleAccess(req, res) {
const walletMode = Boolean(walletParam);
const hasWallet = walletMode || Boolean(user?.wallet_address);
+ // A comped account (api/_lib/comp-access.js) is entitled to every gated feature
+ // with no wallet, no holding, and no payment. Read here as well as in the
+ // enforcement path (require-three.js) so the UI renders those features unlocked
+ // instead of showing a lock the server would not actually enforce. It is keyed on
+ // the SESSION, so it holds in wallet mode too: a comped user who happens to have
+ // a wallet connected must not see a lock the API would let straight through.
+ const comped = isCompedUser(user);
+
// One tier resolution for the whole request; every feature check below is then a
// pure level comparison (no extra on-chain reads). Degrades to Member on failure.
let tier = TIERS[0];
@@ -435,6 +444,10 @@ async function handleAccess(req, res) {
}
}
const heldUsd = Math.round((Number(usd) || 0) * 100) / 100;
+ // The level entitlement is checked against. A comp lifts it to the top of the
+ // ladder without touching the tier/held figures above, so the badge keeps
+ // reporting what the wallet really holds while the features read as unlocked.
+ const accessLevel = comped ? Math.max(tier.level, COMP_TIER.level) : tier.level;
// Attach the catalog price to a pay-per-use action (null for variable-price ones).
const payInfo = (actionId) => {
@@ -466,13 +479,15 @@ async function handleAccess(req, res) {
pay_per_use: payInfo(a.pay_per_use),
});
- const tierSummary = { level: tier.level, id: tier.id, label: tier.label, held_usd: heldUsd };
+ // `comped` tells the UI the entitlement came from the allowlist, not a holding,
+ // so it can show "Included" instead of a held-USD figure that would read as wrong.
+ const tierSummary = { level: tier.level, id: tier.id, label: tier.label, held_usd: heldUsd, comped };
const feature = url.searchParams.get('feature');
if (feature) {
let access;
try {
- access = accessFromTierLevel(tier.level, feature);
+ access = accessFromTierLevel(accessLevel, feature);
} catch (e) {
if (e.code === 'unknown_feature') {
return error(res, 404, 'unknown_feature', `unknown gated feature: ${feature}`);
@@ -487,7 +502,7 @@ async function handleAccess(req, res) {
});
}
- const features = listGatedFeatures().map((id) => decorate(accessFromTierLevel(tier.level, id)));
+ const features = listGatedFeatures().map((id) => decorate(accessFromTierLevel(accessLevel, id)));
return json(res, 200, {
signed_in: Boolean(user),
wallet_linked: hasWallet,
diff --git a/docs/hold-to-access.md b/docs/hold-to-access.md
index e8aad7dd3..f9271262a 100644
--- a/docs/hold-to-access.md
+++ b/docs/hold-to-access.md
@@ -67,9 +67,53 @@ if (!gate.ok) return; // 402 three_hold_required already sent
// ...gate.access, gate.level, gate.wallet are available here
```
-Resolution is **pass-first**: a signed tier pass (header `x-three-tier-pass` or
-`body.tier_pass`), then the session user's on-chain tier, then anonymous Member. Every
-failure degrades to Member — a clean 402, never a 500.
+Resolution is **comp-first, then pass-first**: a comped account (below), then a signed
+tier pass (header `x-three-tier-pass` or `body.tier_pass`), then the session user's
+on-chain tier, then anonymous Member. Every failure degrades to Member: a clean 402,
+never a 500.
+
+### Comped accounts
+
+Some accounts are exempt from the ladder entirely: the owner's own accounts, and
+creators/partners granted lifetime access. They clear **every** gated feature with no
+wallet, no holding, and no payment.
+
+The allowlist is [`api/_lib/comp-access.js`](../api/_lib/comp-access.js), and it is the
+only place the exemption lives, because `requireFeatureAccess` is the single keystone
+every enforced gate resolves through, one entry covers `forge.high`, `forge.gameready`,
+and any gate added later. `GET /api/three/access` applies it too, so the UI renders those
+features unlocked rather than showing a lock the API would let straight through; that
+response carries `tier.comped: true` to explain why a $0 holder reads as entitled.
+
+```js
+import { isCompedUser, resolveCompAccess } from './_lib/comp-access.js';
+
+const { comped } = await resolveCompAccess(req); // from a request (session-aware)
+if (isCompedUser(user)) { /* from an already-resolved user */ }
+```
+
+Grant access by adding a handle to `COMPED_ACCOUNTS` in that module, or by setting
+`THREE_COMP_ACCOUNTS` to a comma-separated list of handles / emails / user ids. Env
+entries are **merged** with the built-ins, never replace them, so an env typo cannot
+silently revoke a comp granted in code.
+
+Three properties keep it safe and cheap:
+
+- **Only unique identifiers count.** `username`, `email`, and `id` are uniquely indexed
+ on `users`, as is the handle in a platform-issued `<handle>@users.three.ws.local`
+ address (minted by `handleRegister` for username registrations, which leave the
+ `username` column null). `display_name` is deliberately **not** matched, because it is
+ user-settable and not unique, so honoring it would let anyone comp themselves by
+ renaming.
+- **Anonymous requests pay nothing.** The lookup is guarded by `hasSessionCookie()`, so a
+ request with no session never issues a query and the zero-latency anonymous free lane
+ is untouched.
+- **It fails closed on the perk.** An auth or DB hiccup resolves to "not comped", which
+ simply means the normal hold-or-pay gate applies. It never fails the request.
+
+A comp also lifts the free-lane rate multiplier to the top tier (`api/forge.js`,
+`api/gpt-forge.js`). It does **not** bypass BYOK (a caller's own vendor key is still
+their own key), nor the platform-wide spend ceilings that protect real vendor budget.
### The hold-or-pay 402
@@ -198,6 +242,7 @@ worlds unaffected.
| Env var | Required | Purpose |
|---------|----------|---------|
| `HOLDER_PASS_SECRET` | prod | HMAC key for signing/verifying tier passes |
+| `THREE_COMP_ACCOUNTS` | no | extra comped handles / emails / user ids, comma-separated (merged with the built-in allowlist) |
| `THREE_TOKEN_MINT` | — | $THREE mint (defaults to the canonical CA) |
| `THREE_TOKEN_DECIMALS` | — | token decimals (default 6) |
| `SOLANA_RPC_URL` (+ provider keys) | — | RPC for on-chain balance reads (see `solana/connection.js`) |
diff --git a/tests/api/three-access.test.js b/tests/api/three-access.test.js
index 72e136fe9..1684f9590 100644
--- a/tests/api/three-access.test.js
+++ b/tests/api/three-access.test.js
@@ -14,6 +14,7 @@
import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';
import { Readable } from 'node:stream';
+import { COMPED_ACCOUNTS } from '../../api/_lib/comp-access.js';
const getBalances = vi.fn();
const getTokenPriceUsd = vi.fn();
@@ -28,6 +29,9 @@ vi.mock('../../api/_lib/auth.js', async (orig) => ({
let handler, TOKEN_MINT, FEATURE_IDS;
const WALLET = 'So11111111111111111111111111111111111111112';
+// The first built-in comped handle (api/_lib/comp-access.js): full platform
+// access with no wallet and no holding.
+const COMPED = COMPED_ACCOUNTS[0];
function mockRes() {
return {
@@ -207,3 +211,50 @@ describe('GET /api/three/access — signed-in reasons', () => {
expect(res.json.access.reason).toBe('eligible');
});
});
+
+describe('GET /api/three/access, comped accounts', () => {
+ it('reports every gated feature as eligible with no wallet and no chain read', async () => {
+ // The production shape of a username-registered account: username null,
+ // handle carried in the platform-issued address.
+ getSessionUser.mockResolvedValue({
+ id: 'u-comp',
+ username: null,
+ email: `${COMPED}@users.three.ws.local`,
+ wallet_address: null,
+ });
+ const res = await get('/api/three/access');
+ expect(res.statusCode).toBe(200);
+ expect(res.json.signed_in).toBe(true);
+ expect(res.json.wallet_linked).toBe(false);
+ expect(res.json.tier.comped).toBe(true);
+ for (const f of res.json.features) {
+ expect(f.eligible, `${f.feature} should read as unlocked`).toBe(true);
+ expect(f.reason).toBe('eligible');
+ }
+ expect(getBalances).not.toHaveBeenCalled();
+ });
+
+ it('stays unlocked in wallet mode, so a connected wallet never shows a false lock', async () => {
+ getSessionUser.mockResolvedValue({
+ id: 'u-comp',
+ username: COMPED,
+ email: `${COMPED}@users.three.ws.local`,
+ wallet_address: WALLET,
+ });
+ mockHeldUsd(0); // holds nothing; the comp is the entitlement
+ const res = await get(`/api/three/access?feature=forge.high&wallet=${WALLET}`);
+ expect(res.json.access.eligible).toBe(true);
+ expect(res.json.access.reason).toBe('eligible');
+ // The badge still reports what the wallet actually holds.
+ expect(res.json.tier.held_usd).toBe(0);
+ expect(res.json.tier.comped).toBe(true);
+ });
+
+ it('leaves a non-comped signed-in user gated exactly as before', async () => {
+ getSessionUser.mockResolvedValue({ id: 'u-plain', username: 'someone-else' });
+ const res = await get('/api/three/access?feature=forge.high');
+ expect(res.json.tier.comped).toBe(false);
+ expect(res.json.access.eligible).toBe(false);
+ expect(res.json.access.reason).toBe('link_wallet');
+ });
+});
diff --git a/tests/comp-access.test.js b/tests/comp-access.test.js
new file mode 100644
index 000000000..02efa96c7
--- /dev/null
+++ b/tests/comp-access.test.js
@@ -0,0 +1,211 @@
+// Tests for comped platform access (api/_lib/comp-access.js) and its two wirings:
+// the enforcement keystone (requireFeatureAccess) and the read the UI consumes.
+//
+// A comped account must clear every gated feature with NO wallet, NO $THREE
+// holding, and NO payment, and it must do so without ever touching an RPC or a
+// price feed. These prove exactly that, plus the two properties that keep the
+// allowlist safe: an anonymous request never pays for the lookup, and a
+// non-comped signed-in user is still gated normally.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const getBalances = vi.fn();
+const getTokenPriceUsd = vi.fn();
+const getSessionUser = vi.fn();
+vi.mock('../api/_lib/balances.js', () => ({ getBalances: (...a) => getBalances(...a) }));
+vi.mock('../api/_lib/token/price.js', () => ({ getTokenPriceUsd: (...a) => getTokenPriceUsd(...a) }));
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUser(...a),
+ hasSessionCookie: (req) => Boolean(req?.headers?.cookie),
+}));
+
+import {
+ COMPED_ACCOUNTS,
+ COMP_TIER,
+ COMP_TIER_LEVEL,
+ compedIdentifiers,
+ isCompedUser,
+ resolveCompAccess,
+} from '../api/_lib/comp-access.js';
+import { requireFeatureAccess } from '../api/_lib/require-three.js';
+import { listGatedFeatures } from '../api/_lib/three-access.js';
+import { TIERS } from '../api/_lib/three-tier.js';
+
+const COMPED = COMPED_ACCOUNTS[0];
+const SESSION_COOKIE = '__Host-sid=abc';
+
+function mockRes() {
+ return {
+ statusCode: 200, _headers: {}, _body: '', _ended: false,
+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this._headers[k.toLowerCase()]; },
+ end(b) { this._body = b || ''; this._ended = true; },
+ get json() { try { return JSON.parse(this._body); } catch { return null; } },
+ };
+}
+
+function mockReq({ headers = {} } = {}) {
+ return { method: 'POST', url: '/api/forge', headers: { ...headers } };
+}
+
+// A request that carries a session cookie, so the comp lookup actually runs.
+function signedInReq(headers = {}) {
+ return mockReq({ headers: { cookie: SESSION_COOKIE, ...headers } });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ delete process.env.THREE_COMP_ACCOUNTS;
+ process.env.HOLDER_PASS_SECRET = 'comp-access-test-secret';
+ process.env.NODE_ENV = 'test';
+ getSessionUser.mockResolvedValue(null);
+});
+
+describe('comp-access: the allowlist', () => {
+ it('grants the top tier of the ladder', () => {
+ expect(COMP_TIER).toBe(TIERS[TIERS.length - 1]);
+ expect(COMP_TIER_LEVEL).toBe(TIERS[TIERS.length - 1].level);
+ });
+
+ it('matches a built-in account by username, case-insensitively', () => {
+ expect(isCompedUser({ id: 'u1', username: COMPED })).toBe(true);
+ expect(isCompedUser({ id: 'u1', username: COMPED.toUpperCase() })).toBe(true);
+ expect(isCompedUser({ id: 'u1', username: ` ${COMPED} ` })).toBe(true);
+ });
+
+ it('matches the handle in a platform-issued @users.three.ws.local address', () => {
+ // A username-registered account leaves users.username null and carries its
+ // handle in the server-minted address (api/auth/[action].js handleRegister).
+ expect(isCompedUser({ id: 'u1', username: null, email: `${COMPED}@users.three.ws.local` })).toBe(true);
+ expect(isCompedUser({ id: 'u1', username: null, email: `${COMPED.toUpperCase()}@users.three.ws.local` })).toBe(true);
+ });
+
+ it('does not match anyone else', () => {
+ expect(isCompedUser({ id: 'u2', username: 'someone-else', email: '[email protected]' })).toBe(false);
+ expect(isCompedUser(null)).toBe(false);
+ expect(isCompedUser({})).toBe(false);
+ });
+
+ it('cannot be claimed by a lookalike on a domain we do not issue', () => {
+ // Only the platform-issued domain grants the local-part match; email is
+ // uniquely indexed, so the real address can never be registered twice.
+ expect(isCompedUser({ id: 'u4', email: `${COMPED}@gmail.com` })).toBe(false);
+ expect(isCompedUser({ id: 'u5', email: `${COMPED}@users.three.ws.local.evil.com` })).toBe(false);
+ });
+
+ it('ignores display_name, which is user-settable and not unique', () => {
+ expect(isCompedUser({ id: 'u6', display_name: COMPED, email: '[email protected]' })).toBe(false);
+ expect(isCompedUser({ id: 'u7', display_name: COMPED.toUpperCase(), username: 'impostor' })).toBe(false);
+ });
+
+ it('matches an env-listed account by email or id, merged with the built-ins', () => {
+ process.env.THREE_COMP_ACCOUNTS = '[email protected], 11111111-2222-3333-4444-555555555555';
+ expect(isCompedUser({ id: 'u3', email: '[email protected]' })).toBe(true);
+ expect(isCompedUser({ id: '11111111-2222-3333-4444-555555555555' })).toBe(true);
+ // The env list never revokes a committed comp.
+ expect(isCompedUser({ id: 'u1', username: COMPED })).toBe(true);
+ expect(compedIdentifiers().has(COMPED)).toBe(true);
+ });
+
+ it('ignores blank env entries', () => {
+ process.env.THREE_COMP_ACCOUNTS = ' , ,, ';
+ expect(compedIdentifiers().size).toBe(COMPED_ACCOUNTS.length);
+ expect(isCompedUser({ id: '', username: '' })).toBe(false);
+ });
+});
+
+describe('comp-access: resolveCompAccess', () => {
+ it('costs an anonymous request nothing (no session cookie → no lookup)', async () => {
+ const out = await resolveCompAccess(mockReq());
+ expect(out).toEqual({ comped: false, user: null });
+ expect(getSessionUser).not.toHaveBeenCalled();
+ });
+
+ it('resolves a comped session user', async () => {
+ getSessionUser.mockResolvedValue({ id: 'u1', username: COMPED, wallet_address: null });
+ const out = await resolveCompAccess(signedInReq());
+ expect(out.comped).toBe(true);
+ expect(out.user.username).toBe(COMPED);
+ });
+
+ it('resolves the real account shape: null username, platform-issued email', async () => {
+ getSessionUser.mockResolvedValue({
+ id: 'b2db97f8-a212-4719-9f48-0df8996e3836',
+ username: null,
+ display_name: COMPED.toUpperCase(),
+ email: `${COMPED}@users.three.ws.local`,
+ wallet_address: null,
+ });
+ const out = await resolveCompAccess(signedInReq());
+ expect(out.comped).toBe(true);
+ });
+
+ it('fails closed on the perk when the session lookup throws', async () => {
+ getSessionUser.mockRejectedValue(new Error('db down'));
+ const out = await resolveCompAccess(signedInReq());
+ expect(out).toEqual({ comped: false, user: null });
+ });
+});
+
+describe('requireFeatureAccess: a comped account', () => {
+ it('clears EVERY gated feature with no wallet and no holding', async () => {
+ // The production account shape: username null, handle in the platform email.
+ getSessionUser.mockResolvedValue({
+ id: 'u1',
+ username: null,
+ email: `${COMPED}@users.three.ws.local`,
+ wallet_address: null,
+ });
+ for (const feature of listGatedFeatures()) {
+ const res = mockRes();
+ const gate = await requireFeatureAccess(signedInReq(), res, feature);
+ expect(gate.ok, `${feature} should be comped`).toBe(true);
+ expect(gate.level).toBe(COMP_TIER_LEVEL);
+ expect(res._ended, `${feature} must write nothing on the allow path`).toBe(false);
+ }
+ // Never reads a balance or a price; the comp is pure account state.
+ expect(getBalances).not.toHaveBeenCalled();
+ expect(getTokenPriceUsd).not.toHaveBeenCalled();
+ });
+
+ it('clears forge.high without a wallet, where a normal signed-in user is 402d', async () => {
+ getSessionUser.mockResolvedValue({ id: 'u9', username: 'regular-user', wallet_address: null });
+ const blocked = mockRes();
+ const blockedGate = await requireFeatureAccess(signedInReq(), blocked, 'forge.high');
+ expect(blockedGate.ok).toBe(false);
+ expect(blocked.statusCode).toBe(402);
+ expect(blocked.json.reason).toBe('link_wallet');
+
+ getSessionUser.mockResolvedValue({ id: 'u1', username: COMPED, wallet_address: null });
+ const allowed = mockRes();
+ const allowedGate = await requireFeatureAccess(signedInReq(), allowed, 'forge.high');
+ expect(allowedGate.ok).toBe(true);
+ expect(allowed._ended).toBe(false);
+ });
+
+ it('is not under-resolved by a stale low-tier pass in the client', async () => {
+ // A Member-level pass would short-circuit the old resolution at level 0; the
+ // comp check runs first, so a comped caller is never blocked by stale storage.
+ const { signTierPass } = await import('../api/_lib/three-tier.js');
+ const stale = signTierPass({
+ wallet: 'So11111111111111111111111111111111111111112',
+ level: 0,
+ tierId: 'member',
+ usd: 0,
+ });
+ getSessionUser.mockResolvedValue({ id: 'u1', username: COMPED, wallet_address: null });
+ const res = mockRes();
+ const gate = await requireFeatureAccess(signedInReq({ 'x-three-tier-pass': stale }), res, 'forge.high');
+ expect(gate.ok).toBe(true);
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('leaves the anonymous 402 exactly as it was', async () => {
+ const res = mockRes();
+ const gate = await requireFeatureAccess(mockReq(), res, 'forge.high');
+ expect(gate.ok).toBe(false);
+ expect(res.statusCode).toBe(402);
+ expect(res.json.error).toBe('three_hold_required');
+ expect(res.json.reason).toBe('sign_in');
+ });
+});
diff --git a/tests/three-require.test.js b/tests/three-require.test.js
index 1a750162d..e4e10cbeb 100644
--- a/tests/three-require.test.js
+++ b/tests/three-require.test.js
@@ -13,7 +13,13 @@ const getTokenPriceUsd = vi.fn();
const getSessionUser = vi.fn();
vi.mock('../api/_lib/balances.js', () => ({ getBalances: (...a) => getBalances(...a) }));
vi.mock('../api/_lib/token/price.js', () => ({ getTokenPriceUsd: (...a) => getTokenPriceUsd(...a) }));
-vi.mock('../api/_lib/auth.js', () => ({ getSessionUser: (...a) => getSessionUser(...a) }));
+// hasSessionCookie gates the comped-access lookup (api/_lib/comp-access.js): it
+// reads the real cookie header, so an anonymous mockReq() skips the lookup and a
+// case that sets a cookie exercises it against the mocked getSessionUser.
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUser(...a),
+ hasSessionCookie: (req) => Boolean(req?.headers?.cookie),
+}));
import { requireFeatureAccess } from '../api/_lib/require-three.js';
import { signTierPass } from '../api/_lib/three-tier.js';