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(vaults): parse caller amounts and ids at the edge instead of 500ing inside the coercion

nirholas64bbf93791d6
diff --git a/api/_lib/vault-accounting.js b/api/_lib/vault-accounting.js
index 61b0be911..b483a8750 100644
--- a/api/_lib/vault-accounting.js
+++ b/api/_lib/vault-accounting.js
@@ -29,6 +29,25 @@ export const USDC_DECIMALS = 6;
export const USDC_ATOMICS = 1_000_000n;
export const BPS = 10_000n;
+// The negotiable vault terms and their hard bounds. One definition, shared by the
+// open route and the owner's terms PATCH, so the two can never drift apart on
+// what a legal performance fee or drawdown limit is.
+export const TERM_BOUNDS = {
+ performanceFeeBps: { min: 0, max: 5000, def: 1000 },
+ maxDrawdownBps: { min: 100, max: 9000, def: 2500 },
+};
+
+/**
+ * Clamp a caller-supplied basis-points term into its bound. Returns null when the
+ * value is not a real number, so a PATCH can reject "abc" at the boundary instead
+ * of writing a NaN into an integer column.
+ */
+export function clampTermBps(value, bound) {
+ const n = Math.round(Number(value));
+ if (!Number.isFinite(n)) return null;
+ return Math.max(bound.min, Math.min(bound.max, n));
+}
+
/** Coerce a value (BigInt | number | numeric-string | null) to BigInt atomics. */
export function toBig(v) {
if (typeof v === 'bigint') return v;
@@ -45,6 +64,26 @@ export function toBig(v) {
return BigInt(dot >= 0 ? s.slice(0, dot) : s);
}
+/**
+ * Boundary parse for a caller-supplied share/token amount. `toBig` is the
+ * INTERNAL coercion and trusts its input (a numeric column, a computed value);
+ * handing it a caller's "abc" throws a SyntaxError that surfaces as a 500. This
+ * is the guard that belongs at the HTTP edge: it returns a non-negative BigInt
+ * for anything genuinely numeric, and null for anything else so the handler can
+ * answer 400 instead.
+ */
+export function parseAmountInput(value) {
+ if (typeof value === 'bigint') return value >= 0n ? value : null;
+ if (typeof value === 'number') {
+ if (!Number.isFinite(value) || value < 0) return null;
+ return BigInt(Math.trunc(value));
+ }
+ if (typeof value !== 'string') return null;
+ const s = value.trim();
+ if (!/^\d+(\.\d+)?$/.test(s)) return null;
+ return toBig(s);
+}
+
/** Float USDC → 6-decimal atomics (BigInt, floored, never negative). */
export function usdcToAtomics(usdc) {
const n = Number(usdc);
diff --git a/api/vault/buy-policy-data.js b/api/vault/buy-policy-data.js
index c93370314..789f7d975 100644
--- a/api/vault/buy-policy-data.js
+++ b/api/vault/buy-policy-data.js
@@ -47,7 +47,7 @@ export default wrap(async (req, res) => {
res,
400,
'bad_request',
- `unknown network "${params.get('network')}" — use "testnet" or "mainnet"`,
+ `unknown network "${params.get('network')}": use "testnet" or "mainnet"`,
);
}
const objectId = params.get('objectId');
diff --git a/api/vault/download.js b/api/vault/download.js
index 18175ba5d..c05a3cef5 100644
--- a/api/vault/download.js
+++ b/api/vault/download.js
@@ -17,7 +17,7 @@
// Errors mirror unlock.js's status codes (401 bad/expired token, 403 not
// purchased, 404 not listed, 410 delisted/unavailable, 503 upstream).
-import { cors, method, wrap, error } from '../_lib/http.js';
+import { cors, method, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { assertBscAddress, isEvmAddress, BnbRpcError } from '../_lib/bnb/chains.js';
import { vaultContractAddress, vaultClient, readListing, readSaleIdOf, readSale, VaultContractError } from '../_lib/bnb/vault-contract.js';
@@ -43,13 +43,18 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
- const rl = await limits.bnbVaultUnlockIp(clientIp(req)); // same tight budget as unlock — this also spends real bandwidth/SP calls
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many vault downloads');
+ // Same tight budget as unlock: this also spends real bandwidth and SP calls.
+ // `rateLimited` (not a hand-rolled 429) so the retry-after / RateLimit headers
+ // and the limiter's own `reason` survive. This bucket is `critical: true`, so a
+ // Redis outage fails it closed with `rate_limiter_unavailable`, and a client that
+ // never sees that reason misreads a limiter outage as its own quota being spent.
+ const rl = await limits.bnbVaultUnlockIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl, 'too many vault downloads');
const params = new URL(req.url, `http://${req.headers?.host || 'x'}`).searchParams;
const network = normalizeNetwork(params.get('network'));
if (network === null) {
- return error(res, 400, 'bad_request', `unknown network "${params.get('network')}" — use "testnet" or "mainnet"`);
+ return error(res, 400, 'bad_request', `unknown network "${params.get('network')}": use "testnet" or "mainnet"`);
}
const objectId = params.get('objectId');
if (!isBytes32(objectId)) {
@@ -62,11 +67,11 @@ export default wrap(async (req, res) => {
const claim = decodeVaultDownloadToken(params.get('token'));
if (!claim || claim.objectId !== objectId || claim.buyer !== buyer.toLowerCase() || claim.network !== network) {
- return error(res, 401, 'bad_token', 'missing, expired, or mismatched download token — unlock again to get a fresh one');
+ return error(res, 401, 'bad_token', 'missing, expired, or mismatched download token; unlock again to get a fresh one');
}
if (!env.GREENFIELD_VAULT_OPERATOR_KEY) {
- return error(res, 503, 'vault_not_configured', 'GREENFIELD_VAULT_OPERATOR_KEY is not set — the vault storage account is not provisioned yet');
+ return error(res, 503, 'vault_not_configured', 'GREENFIELD_VAULT_OPERATOR_KEY is not set; the vault storage account is not provisioned yet');
}
const { address: contractAddress, deployed: contractDeployed } = vaultContractAddress(network);
@@ -109,7 +114,7 @@ export default wrap(async (req, res) => {
throw err;
}
if (sale.status !== 'Granted') {
- return error(res, 403, 'grant_pending', 'the Greenfield permission grant has not settled yet — poll GET /api/vault/status');
+ return error(res, 403, 'grant_pending', 'the Greenfield permission grant has not settled yet; poll GET /api/vault/status');
}
let ref;
diff --git a/api/vault/list.js b/api/vault/list.js
index 3a1cc039f..28732e8ee 100644
--- a/api/vault/list.js
+++ b/api/vault/list.js
@@ -55,7 +55,7 @@ export default wrap(async (req, res) => {
const params = new URL(req.url, `http://${req.headers?.host || 'x'}`).searchParams;
const network = normalizeNetwork(params.get('network'));
if (network === null) {
- return error(res, 400, 'bad_request', `unknown network "${params.get('network')}" — use "testnet" or "mainnet"`);
+ return error(res, 400, 'bad_request', `unknown network "${params.get('network')}": use "testnet" or "mainnet"`);
}
const { address: contractAddress, deployed: contractDeployed } = vaultContractAddress(network, params.get('contractAddress'));
@@ -89,7 +89,15 @@ export default wrap(async (req, res) => {
let ref;
try {
ref = await resolveObjectRef(objectId, { network });
- } catch {
+ } catch (err) {
+ // A Greenfield miss is a genuine "no manifest for this listing" and belongs
+ // in `unresolved`. Anything else (the object index being down, a programmer
+ // error) is an outage, and reporting it as "this listing has no manifest"
+ // would be a lie about real chain state. Same split the manifest fetch below
+ // makes, and the same 503 the other vault endpoints return for it.
+ if (!(err instanceof GreenfieldError)) {
+ return error(res, 503, 'storage_unavailable', `could not resolve vault object refs: ${err.message}`);
+ }
ref = null;
}
if (!ref) {
diff --git a/api/vault/status.js b/api/vault/status.js
index 1352d1470..b7e5b1f20 100644
--- a/api/vault/status.js
+++ b/api/vault/status.js
@@ -39,7 +39,7 @@ export default wrap(async (req, res) => {
const params = new URL(req.url, `http://${req.headers?.host || 'x'}`).searchParams;
const network = normalizeNetwork(params.get('network'));
if (network === null) {
- return error(res, 400, 'bad_request', `unknown network "${params.get('network')}" — use "testnet" or "mainnet"`);
+ return error(res, 400, 'bad_request', `unknown network "${params.get('network')}": use "testnet" or "mainnet"`);
}
const objectId = params.get('objectId');
@@ -110,7 +110,7 @@ export default wrap(async (req, res) => {
policySettled,
saleStatus: sale.status,
state,
- pollHint: state === 'pending-grant' ? 'Greenfield permission grant is still mirroring cross-chain — poll again shortly' : undefined,
+ pollHint: state === 'pending-grant' ? 'Greenfield permission grant is still mirroring cross-chain, poll again shortly' : undefined,
},
{ 'cache-control': 'no-store' },
);
diff --git a/api/vault/unlock.js b/api/vault/unlock.js
index 5eae12b63..c51876a23 100644
--- a/api/vault/unlock.js
+++ b/api/vault/unlock.js
@@ -69,7 +69,7 @@ export default wrap(async (req, res) => {
const network = normalizeNetwork(body?.network);
if (network === null) {
- return error(res, 400, 'bad_request', `unknown network "${body?.network}" — use "testnet" or "mainnet"`);
+ return error(res, 400, 'bad_request', `unknown network "${body?.network}": use "testnet" or "mainnet"`);
}
const objectId = body?.objectId;
if (!isBytes32(objectId)) {
@@ -147,7 +147,7 @@ export default wrap(async (req, res) => {
return json(
res,
200,
- { state: 'pending-grant', objectId, buyer, network, saleId: saleId.toString(), saleStatus: sale.status, pollHint: 'Greenfield permission grant is still mirroring cross-chain — poll again shortly' },
+ { state: 'pending-grant', objectId, buyer, network, saleId: saleId.toString(), saleStatus: sale.status, pollHint: 'Greenfield permission grant is still mirroring cross-chain, poll again shortly' },
{ 'cache-control': 'no-store' },
);
}
diff --git a/api/vaults/[id].js b/api/vaults/[id].js
index 2514e489b..499d75ec4 100644
--- a/api/vaults/[id].js
+++ b/api/vaults/[id].js
@@ -16,6 +16,7 @@ import {
import { computeVaultNav } from '../_lib/vault-wallet.js';
import {
sharePriceE6, roiBps, toBig, usdcToAtomics, settleRedemption,
+ TERM_BOUNDS, clampTermBps,
} from '../_lib/vault-accounting.js';
import { isUuid } from '../_lib/validate.js';
@@ -133,14 +134,34 @@ async function handlePatch(req, res, id) {
}
if (action === 'terms') {
const patch = {};
- if (body.performanceFeeBps != null) patch.performanceFeeBps = Math.max(0, Math.min(5000, Math.round(Number(body.performanceFeeBps))));
- if (body.maxDrawdownBps != null) patch.maxDrawdownBps = Math.max(100, Math.min(9000, Math.round(Number(body.maxDrawdownBps))));
- if (body.maxPerTradeUsdc != null) { const v = Number(body.maxPerTradeUsdc); if (v > 0) patch.maxPerTradeAtomics = usdcToAtomics(v); }
- if (body.dailyBudgetUsdc != null) { const v = Number(body.dailyBudgetUsdc); if (v > 0) patch.dailyBudgetAtomics = usdcToAtomics(v); }
+ if (body.performanceFeeBps != null) {
+ const bps = clampTermBps(body.performanceFeeBps, TERM_BOUNDS.performanceFeeBps);
+ if (bps == null) return error(res, 400, 'validation_error', 'performanceFeeBps must be a number');
+ patch.performanceFeeBps = bps;
+ }
+ if (body.maxDrawdownBps != null) {
+ const bps = clampTermBps(body.maxDrawdownBps, TERM_BOUNDS.maxDrawdownBps);
+ if (bps == null) return error(res, 400, 'validation_error', 'maxDrawdownBps must be a number');
+ patch.maxDrawdownBps = bps;
+ }
+ if (body.maxPerTradeUsdc != null) {
+ const v = Number(body.maxPerTradeUsdc);
+ if (!(v > 0)) return error(res, 400, 'validation_error', 'maxPerTradeUsdc must be a positive number');
+ patch.maxPerTradeAtomics = usdcToAtomics(v);
+ }
+ if (body.dailyBudgetUsdc != null) {
+ const v = Number(body.dailyBudgetUsdc);
+ if (!(v > 0)) return error(res, 400, 'validation_error', 'dailyBudgetUsdc must be a positive number');
+ patch.dailyBudgetAtomics = usdcToAtomics(v);
+ }
if ('perBackerCapUsdc' in body) {
const v = body.perBackerCapUsdc;
+ if (v != null && !Number.isFinite(Number(v))) return error(res, 400, 'validation_error', 'perBackerCapUsdc must be a number or null');
patch.perBackerCapAtomics = v == null || Number(v) <= 0 ? null : usdcToAtomics(Number(v));
}
+ const effectivePerTrade = patch.maxPerTradeAtomics ?? toBig(vault.max_per_trade_atomics);
+ const effectiveDaily = patch.dailyBudgetAtomics ?? toBig(vault.daily_budget_atomics);
+ if (effectivePerTrade > effectiveDaily) return error(res, 400, 'validation_error', 'per-trade ceiling cannot exceed the daily budget');
const next = await updateVaultTerms(vault.id, patch);
await recordVaultEvent({ vaultId: vault.id, type: 'terms', userId: who.userId, reason: 'terms updated', meta: { patch: Object.fromEntries(Object.entries(patch).map(([k, v]) => [k, v == null ? null : String(v)])) } });
return json(res, 200, { data: { vault: next } }, { 'cache-control': 'no-store' });
diff --git a/api/vaults/claim-fees.js b/api/vaults/claim-fees.js
index 595cacd9a..1dc817e4f 100644
--- a/api/vaults/claim-fees.js
+++ b/api/vaults/claim-fees.js
@@ -10,6 +10,7 @@ import { limits } from '../_lib/rate-limit.js';
import { authWrite, loadOwnedAgent } from '../_lib/vault-auth.js';
import { getVault } from '../_lib/vault-store.js';
import { claimVaultFees } from '../_lib/vault-transfer.js';
+import { isUuid } from '../_lib/validate.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
@@ -28,7 +29,9 @@ export default wrap(async (req, res) => {
const vaultId = String(body.vaultId || body.vault_id || '').trim();
const toAgentId = String(body.toAgentId || body.to_agent_id || '').trim();
if (!vaultId) return error(res, 400, 'validation_error', 'vaultId required');
+ if (!isUuid(vaultId)) return error(res, 400, 'validation_error', 'vaultId must be a vault id');
if (!toAgentId) return error(res, 400, 'validation_error', 'toAgentId required (the wallet to receive fees)');
+ if (!isUuid(toAgentId)) return error(res, 400, 'validation_error', 'toAgentId must be an agent id');
const vault = await getVault(vaultId);
if (!vault) return error(res, 404, 'not_found', 'vault not found');
diff --git a/api/vaults/deposit.js b/api/vaults/deposit.js
index 623d5e7c6..294d8ce29 100644
--- a/api/vaults/deposit.js
+++ b/api/vaults/deposit.js
@@ -11,6 +11,8 @@ import { limits } from '../_lib/rate-limit.js';
import { authWrite, loadOwnedAgent } from '../_lib/vault-auth.js';
import { getVault } from '../_lib/vault-store.js';
import { depositToVault } from '../_lib/vault-transfer.js';
+import { usdcToAtomics } from '../_lib/vault-accounting.js';
+import { isUuid } from '../_lib/validate.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
@@ -30,7 +32,9 @@ export default wrap(async (req, res) => {
const backerAgentId = String(body.backerAgentId || body.backer_agent_id || '').trim();
const usdc = Number(body.usdc);
if (!vaultId) return error(res, 400, 'validation_error', 'vaultId required');
+ if (!isUuid(vaultId)) return error(res, 400, 'validation_error', 'vaultId must be a vault id');
if (!backerAgentId) return error(res, 400, 'validation_error', 'backerAgentId required (the agent wallet to fund from)');
+ if (!isUuid(backerAgentId)) return error(res, 400, 'validation_error', 'backerAgentId must be an agent id');
if (!(usdc > 0)) return error(res, 400, 'validation_error', 'usdc must be a positive number');
const vault = await getVault(vaultId);
@@ -39,10 +43,9 @@ export default wrap(async (req, res) => {
let backerAgent;
try { backerAgent = await loadOwnedAgent(backerAgentId, userId); } catch (e) { return error(res, e.status || 400, e.code || 'bad_request', e.message); }
if (!backerAgent.meta?.solana_address || !backerAgent.meta?.encrypted_solana_secret) {
- return error(res, 400, 'wallet_unready', 'that agent has no funded Solana wallet yet — provision and fund it first');
+ return error(res, 400, 'wallet_unready', 'that agent has no funded Solana wallet yet. Provision and fund it first.');
}
- const { usdcToAtomics } = await import('../_lib/vault-accounting.js');
const result = await depositToVault({
vault, backerAgent, userId,
usdcAtomics: usdcToAtomics(usdc),
diff --git a/api/vaults/index.js b/api/vaults/index.js
index e65e28a7e..295b4e462 100644
--- a/api/vaults/index.js
+++ b/api/vaults/index.js
@@ -14,17 +14,11 @@ import { authWrite, loadOwnedAgent, assertReputationVerified, traderBadge } from
import { resolveUserId } from '../_lib/vault-auth.js';
import { createVault, listVaults, listBackedVaults, recordVaultEvent } from '../_lib/vault-store.js';
import { generateVaultWallet } from '../_lib/vault-wallet.js';
-import { usdcToAtomics, sharePriceE6, roiBps, toBig } from '../_lib/vault-accounting.js';
+import { usdcToAtomics, sharePriceE6, roiBps, toBig, TERM_BOUNDS, clampTermBps } from '../_lib/vault-accounting.js';
+import { isUuid } from '../_lib/validate.js';
-const TERM_BOUNDS = {
- performanceFeeBps: { min: 0, max: 5000, def: 1000 },
- maxDrawdownBps: { min: 100, max: 9000, def: 2500 },
-};
-
-function clampInt(v, { min, max, def }) {
- const n = Math.round(Number(v));
- if (!Number.isFinite(n)) return def;
- return Math.max(min, Math.min(max, n));
+function clampInt(v, bound) {
+ return clampTermBps(v, bound) ?? bound.def;
}
async function handleList(req, res) {
@@ -94,12 +88,13 @@ async function handleOpen(req, res) {
const agentId = String(body.agentId || body.agent_id || '').trim();
if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agentId must be an agent id');
const network = body.network === 'devnet' ? 'devnet' : 'mainnet';
let agent;
try { agent = await loadOwnedAgent(agentId, userId); } catch (e) { return error(res, e.status || 400, e.code || 'bad_request', e.message); }
- // Reputation gate — only a verifiably-skilled agent can open a vault.
+ // Reputation gate: only a verifiably-skilled agent can open a vault.
try { await assertReputationVerified(agentId, network); } catch (e) { return error(res, e.status || 403, e.code || 'forbidden', e.message, e.detail || {}); }
// Required risk terms.
diff --git a/api/vaults/redeem.js b/api/vaults/redeem.js
index b2fd15bb3..935a5b3b6 100644
--- a/api/vaults/redeem.js
+++ b/api/vaults/redeem.js
@@ -3,13 +3,15 @@
// Redeem your shares at real NAV. The owner's performance fee is charged only on
// your realized gain. If the vault can't pay the full claim instantly (capital is
// live in open positions), we redeem what the liquid USDC covers and queue the
-// rest honestly — never a fake instant number.
+// rest honestly, never a fake instant number.
import { randomUUID } from 'node:crypto';
import { cors, json, method, error, readJson, wrap, rateLimited } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
import { authWrite } from '../_lib/vault-auth.js';
import { redeemFromVault } from '../_lib/vault-transfer.js';
+import { parseAmountInput } from '../_lib/vault-accounting.js';
+import { isUuid } from '../_lib/validate.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
@@ -27,7 +29,14 @@ export default wrap(async (req, res) => {
const vaultId = String(body.vaultId || body.vault_id || '').trim();
if (!vaultId) return error(res, 400, 'validation_error', 'vaultId required');
- const sharesIn = body.shares === 'max' || body.shares == null ? 'max' : String(body.shares);
+ if (!isUuid(vaultId)) return error(res, 400, 'validation_error', 'vaultId must be a vault id');
+
+ let sharesIn = 'max';
+ if (body.shares !== 'max' && body.shares != null) {
+ const parsed = parseAmountInput(body.shares);
+ if (parsed == null) return error(res, 400, 'validation_error', 'shares must be a positive number or "max"');
+ sharesIn = String(parsed);
+ }
const result = await redeemFromVault({
vaultId, userId, shares: sharesIn,
diff --git a/api/vaults/trade.js b/api/vaults/trade.js
index dd6bc972a..9c7556e0d 100644
--- a/api/vaults/trade.js
+++ b/api/vaults/trade.js
@@ -13,7 +13,8 @@ import { limits } from '../_lib/rate-limit.js';
import { authWrite } from '../_lib/vault-auth.js';
import { getVault } from '../_lib/vault-store.js';
import { vaultTrade } from '../_lib/vault-trade.js';
-import { usdcToAtomics, toBig } from '../_lib/vault-accounting.js';
+import { usdcToAtomics, parseAmountInput } from '../_lib/vault-accounting.js';
+import { isUuid, isValidSolanaAddress } from '../_lib/validate.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
@@ -33,8 +34,10 @@ export default wrap(async (req, res) => {
const side = body.side === 'sell' ? 'sell' : body.side === 'buy' ? 'buy' : null;
const mint = String(body.mint || '').trim();
if (!vaultId) return error(res, 400, 'validation_error', 'vaultId required');
+ if (!isUuid(vaultId)) return error(res, 400, 'validation_error', 'vaultId must be a vault id');
if (!side) return error(res, 400, 'validation_error', 'side must be "buy" or "sell"');
if (!mint) return error(res, 400, 'validation_error', 'mint required');
+ if (!isValidSolanaAddress(mint)) return error(res, 400, 'validation_error', 'mint must be a Solana mint address');
const vault = await getVault(vaultId);
if (!vault) return error(res, 404, 'not_found', 'vault not found');
@@ -47,8 +50,11 @@ export default wrap(async (req, res) => {
const usdc = Number(body.usdc);
if (!(usdc > 0)) return error(res, 400, 'validation_error', 'usdc must be a positive number for a buy');
usdcInAtomics = usdcToAtomics(usdc);
+ } else if (body.amount === 'max' || body.amount == null) {
+ amountRaw = 'max';
} else {
- amountRaw = body.amount === 'max' || body.amount == null ? 'max' : toBig(body.amount);
+ amountRaw = parseAmountInput(body.amount);
+ if (amountRaw == null) return error(res, 400, 'validation_error', 'amount must be a positive number or "max"');
}
const result = await vaultTrade({
diff --git a/tests/bnb-vault-api.test.js b/tests/bnb-vault-api.test.js
index abbceb1a6..454c36188 100644
--- a/tests/bnb-vault-api.test.js
+++ b/tests/bnb-vault-api.test.js
@@ -1,16 +1,20 @@
/**
- * `api/vault/{list,status,unlock}.js` — integration tests (prompt 11).
+ * `api/vault/{list,status,unlock,download,buy-policy-data}.js` integration tests.
*
- * The signature/auth boundary (`api/_lib/bnb/vault-unlock-auth.js`) and the
- * crypto boundary (`api/_lib/bnb/vault-crypto.js` wrapKey/unwrapKey,
- * `secret-box.js` encryptSecret/decryptSecret) run for REAL — a synthetic
- * viem account signs a real EIP-191 message, the handler recovers the real
- * public key from it, and `wrapKey`/`unwrapKey` round-trip a real content
- * key — mirroring this campaign's "real crypto, mocked chain/storage" test
- * convention (tests/bnb-mpp-server.test.js, tests/bnb-vault-crypto.test.js).
- * Only the on-chain reads (`vault-contract.js`) and Greenfield/off-chain
- * index (`vault-store.js`) are mocked, since those need live infra this
- * sandbox doesn't have egress for.
+ * The signature/auth boundary (`api/_lib/bnb/vault-unlock-auth.js`), the crypto
+ * boundary (`api/_lib/bnb/vault-crypto.js` wrapKey/unwrapKey, `secret-box.js`
+ * encryptSecret/decryptSecret), the download-token HMAC codec
+ * (`vault-download-token.js`) and the protobuf policy encoder
+ * (`vault-policy-data.js`) all run for REAL: a synthetic viem account signs a
+ * real EIP-191 message, the handler recovers the real public key from it,
+ * `wrapKey`/`unwrapKey` round-trip a real content key, and the emitted
+ * `policyData` bytes are decoded back through the real generated codec. That
+ * mirrors this campaign's "real crypto, mocked chain/storage" test convention
+ * (tests/bnb-mpp-server.test.js, tests/bnb-vault-crypto.test.js). Only what
+ * needs live infra this sandbox has no egress for is mocked: the on-chain reads
+ * (`vault-contract.js`), the off-chain index and manifest reads
+ * (`vault-store.js`), the object-metadata read (`greenfield.js` getObjectMeta),
+ * and the authenticated SP fetch (`greenfield-write.js` downloadPrivateObject).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
@@ -18,6 +22,10 @@ import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
process.env.WALLET_ENCRYPTION_KEY ||= 'vitest-ephemeral-wallet-key-000000000000000000';
process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';
+// download.js refuses with 503 vault_not_configured when no operator key exists, so
+// the authorization path below can only be exercised with one present. Ephemeral and
+// never used to sign: the Greenfield fetch it would authenticate is mocked out.
+process.env.GREENFIELD_VAULT_OPERATOR_KEY ||= '0x' + '7'.repeat(64);
const OBJECT_ID = '0x' + '11'.repeat(32);
const OTHER_OBJECT_ID = '0x' + '22'.repeat(32);
@@ -61,12 +69,16 @@ const store = {
refs: new Map(), // objectId -> {bucket, glbObject, manifestObject}
manifests: new Map(), // manifestObject -> manifest JSON
keyRecords: new Map(), // `${bucket}:${glbObject}` -> {contentKeyCiphertext, sellerAddress}
+ refError: null, // when set, resolveObjectRef rejects with it
};
vi.mock('../api/_lib/bnb/vault-store.js', async () => {
const actual = await vi.importActual('../api/_lib/bnb/vault-store.js');
return {
...actual,
- resolveObjectRef: vi.fn(async (objectId) => store.refs.get(objectId) || null),
+ resolveObjectRef: vi.fn(async (objectId) => {
+ if (store.refError) throw store.refError;
+ return store.refs.get(objectId) || null;
+ }),
fetchManifest: vi.fn(async (_bucket, manifestObject) => {
const m = store.manifests.get(manifestObject);
if (!m) throw new (await import('../api/_lib/bnb/greenfield.js')).GreenfieldError('not found', 'not_found');
@@ -76,9 +88,42 @@ vi.mock('../api/_lib/bnb/vault-store.js', async () => {
};
});
+// ── greenfield.js: only the object-metadata read buy-policy-data.js needs. The
+// protobuf policy encoder itself runs for REAL against it (same "real crypto /
+// real wire format, mocked network" split the rest of this file uses).
+const greenfield = { meta: null, error: null };
+vi.mock('../api/_lib/bnb/greenfield.js', async () => {
+ const actual = await vi.importActual('../api/_lib/bnb/greenfield.js');
+ return {
+ ...actual,
+ getObjectMeta: vi.fn(async () => {
+ if (greenfield.error) throw greenfield.error;
+ return greenfield.meta;
+ }),
+ };
+});
+
+// ── greenfield-write.js: the authenticated SP fetch download.js relays. ──
+const sp = { bytes: null, error: null };
+vi.mock('../api/_lib/bnb/greenfield-write.js', async () => {
+ const actual = await vi.importActual('../api/_lib/bnb/greenfield-write.js');
+ return {
+ ...actual,
+ downloadPrivateObject: vi.fn(async () => {
+ if (sp.error) throw sp.error;
+ return { bytes: sp.bytes };
+ }),
+ };
+});
+
const { default: listHandler } = await import('../api/vault/list.js');
const { default: statusHandler } = await import('../api/vault/status.js');
const { default: unlockHandler } = await import('../api/vault/unlock.js');
+const { default: downloadHandler } = await import('../api/vault/download.js');
+const { default: policyDataHandler } = await import('../api/vault/buy-policy-data.js');
+const { encodeVaultDownloadToken } = await import('../api/_lib/bnb/vault-download-token.js');
+const { GreenfieldError } = await import('../api/_lib/bnb/greenfield.js');
+const { GreenfieldWriteError } = await import('../api/_lib/bnb/greenfield-write.js');
const { buildVaultUnlockMessage } = await import('../api/_lib/bnb/vault-unlock-auth.js');
const { encryptGlb } = await import('../api/_lib/bnb/vault-crypto.js');
const { unwrapKey } = await import('../api/_lib/bnb/vault-crypto.js');
@@ -93,6 +138,9 @@ function makeRes() {
const r = { statusCode: 200, _h: {}, _b: null };
r.setHeader = (k, v) => { r._h[k] = v; };
r.getHeader = (k) => r._h[k];
+ // download.js streams its success path through writeHead + end(Buffer) rather
+ // than json(), so the fake has to honor both shapes.
+ r.writeHead = (code, headers) => { r.statusCode = code; Object.assign(r._h, headers || {}); return r; };
r.end = (b) => { r._b = b; };
Object.defineProperty(r, '_s', { get() { return this.statusCode; } });
Object.defineProperty(r, 'json', { value: () => JSON.parse(r._b) });
@@ -121,6 +169,11 @@ beforeEach(() => {
store.refs.clear();
store.manifests.clear();
store.keyRecords.clear();
+ store.refError = null;
+ greenfield.meta = null;
+ greenfield.error = null;
+ sp.bytes = null;
+ sp.error = null;
});
afterEach(() => {
vi.clearAllMocks();
@@ -181,6 +234,22 @@ describe('GET /api/vault/list', () => {
const r = await get(listHandler, '/api/vault/list');
expect(r._s).toBe(429);
});
+
+ it('a Greenfield miss while resolving refs lands in unresolved, not a 5xx', async () => {
+ chain.logs = [{ eventName: 'Listed', blockNumber: 1n, logIndex: 0, args: { objectId: OBJECT_ID, seller: SELLER, price: 1n } }];
+ store.refError = new GreenfieldError('bucket unreachable', 'unavailable');
+ const r = await get(listHandler, '/api/vault/list');
+ expect(r._s).toBe(200);
+ expect(r.json().unresolved).toEqual([OBJECT_ID]);
+ });
+
+ it('an object-index outage → 503, never a listing silently reported as manifest-less', async () => {
+ chain.logs = [{ eventName: 'Listed', blockNumber: 1n, logIndex: 0, args: { objectId: OBJECT_ID, seller: SELLER, price: 1n } }];
+ store.refError = new Error('index db connection refused'); // not a GreenfieldError
+ const r = await get(listHandler, '/api/vault/list');
+ expect(r._s).toBe(503);
+ expect(r.json().error).toBe('storage_unavailable');
+ });
});
describe('GET /api/vault/status', () => {
@@ -345,3 +414,207 @@ describe('POST /api/vault/unlock', () => {
expect(JSON.stringify(res)).not.toContain(contentKey.toString('hex'));
});
});
+
+describe('GET /api/vault/download', () => {
+ const buyer = '0x2222222222222222222222222222222222222222';
+ const CIPHERTEXT = Buffer.from('vault-ciphertext-bytes-not-plaintext-glb');
+ const REF = { bucket: 'three-ws-vault-testnet', glbObject: 'vaults/d/1.glb.enc', manifestObject: 'vaults/d/1.manifest.json' };
+
+ function token(over = {}) {
+ return encodeVaultDownloadToken({ objectId: OBJECT_ID, buyer, network: 'testnet', ...over });
+ }
+ function url(over = {}) {
+ const p = { objectId: OBJECT_ID, buyer, token: token(), ...over };
+ return `/api/vault/download?${new URLSearchParams(p)}`;
+ }
+ /** Chain + storage state of a settled, granted purchase for `buyer`. */
+ function grantPurchase(status = 'Granted') {
+ chain.listings.set(OBJECT_ID, { seller: SELLER, price: 100n, active: true });
+ chain.saleIdOf.set(`${OBJECT_ID}:${buyer.toLowerCase()}`, 3n);
+ chain.sales.set('3', { objectId: OBJECT_ID, buyer, seller: SELLER, price: 100n, policyId: 7n, status });
+ store.refs.set(OBJECT_ID, REF);
+ sp.bytes = CIPHERTEXT;
+ }
+
+ it('purchased + Granted → 200 streams the raw ciphertext bytes', async () => {
+ grantPurchase();
+ const r = await get(downloadHandler, url());
+ expect(r._s).toBe(200);
+ expect(r._h['content-type']).toBe('application/octet-stream');
+ expect(r._h['content-length']).toBe(String(CIPHERTEXT.length));
+ expect(r._h['cache-control']).toBe('no-store');
+ expect(Buffer.compare(r._b, CIPHERTEXT)).toBe(0);
+ });
+
+ it('no token → 401 bad_token (the bytes gate is never open by default)', async () => {
+ grantPurchase();
+ const r = await get(downloadHandler, '/api/vault/download?objectId=' + OBJECT_ID + '&buyer=' + buyer);
+ expect(r._s).toBe(401);
+ expect(r.json().error).toBe('bad_token');
+ });
+
+ it('a valid token for one buyer cannot fetch the bytes of a different buyer', async () => {
+ grantPurchase();
+ const other = '0x4444444444444444444444444444444444444444';
+ chain.saleIdOf.set(`${OBJECT_ID}:${other.toLowerCase()}`, 3n); // other bought it too
+ const r = await get(downloadHandler, url({ buyer: other })); // token still says `buyer`
+ expect(r._s).toBe(401);
+ expect(r.json().error).toBe('bad_token');
+ });
+
+ it('a token minted for another objectId is rejected', async () => {
+ grantPurchase();
+ const r = await get(downloadHandler, url({ token: token({ objectId: OTHER_OBJECT_ID }) }));
+ expect(r._s).toBe(401);
+ });
+
+ it('a tampered signature is rejected', async () => {
+ grantPurchase();
+ const r = await get(downloadHandler, url({ token: token() + 'x' }));
+ expect(r._s).toBe(401);
+ });
+
+ it('an expired token is rejected even with a settled purchase', async () => {
+ grantPurchase();
+ const stale = token();
+ vi.useFakeTimers();
+ vi.setSystemTime(Date.now() + 16 * 60 * 1000); // TTL is 15 minutes
+ const r = await get(downloadHandler, url({ token: stale }));
+ vi.useRealTimers();
+ expect(r._s).toBe(401);
+ expect(r.json().error).toBe('bad_token');
+ });
+
+ it('valid token but no purchase → 403 purchase_required (the token is not the authorization)', async () => {
+ chain.listings.set(OBJECT_ID, { seller: SELLER, price: 100n, active: true });
+ store.refs.set(OBJECT_ID, REF);
+ sp.bytes = CIPHERTEXT;
+ const r = await get(downloadHandler, url());
+ expect(r._s).toBe(403);
+ expect(r.json().error).toBe('purchase_required');
+ });
+
+ it('valid token but the grant is still Pending → 403 grant_pending', async () => {
+ grantPurchase('Pending');
+ const r = await get(downloadHandler, url());
+ expect(r._s).toBe(403);
+ expect(r.json().error).toBe('grant_pending');
+ });
+
+ it('never listed → 404 not_listed', async () => {
+ const r = await get(downloadHandler, url({ objectId: NEVER_LISTED_ID, token: token({ objectId: NEVER_LISTED_ID }) }));
+ expect(r._s).toBe(404);
+ expect(r.json().error).toBe('not_listed');
+ });
+
+ it('delisted with no purchase → 410 delisted', async () => {
+ chain.listings.set(OBJECT_ID, { seller: SELLER, price: 100n, active: false });
+ const r = await get(downloadHandler, url());
+ expect(r._s).toBe(410);
+ expect(r.json().error).toBe('delisted');
+ });
+
+ it('purchased but refs unresolvable → 410 object_index_missing', async () => {
+ grantPurchase();
+ store.refs.clear();
+ const r = await get(downloadHandler, url());
+ expect(r._s).toBe(410);
+ expect(r.json().error).toBe('object_index_missing');
+ });
+
+ it('the SP losing the object → 410, and a transport failure → 503', async () => {
+ grantPurchase();
+ sp.error = new GreenfieldWriteError('object gone', { code: 'not_found' });
+ expect((await get(downloadHandler, url()))._s).toBe(410);
+ sp.error = new GreenfieldWriteError('sp unreachable', { code: 'unavailable' });
+ expect((await get(downloadHandler, url()))._s).toBe(503);
+ });
+
+ it('contract not deployed → 503, never bytes', async () => {
+ grantPurchase();
+ chain.deployed = false;
+ const r = await get(downloadHandler, url());
+ expect(r._s).toBe(503);
+ expect(r.json().error).toBe('contract_not_deployed');
+ });
+
+ it('bad objectId / buyer / network → 400', async () => {
+ expect((await get(downloadHandler, url({ objectId: 'nope' })))._s).toBe(400);
+ expect((await get(downloadHandler, url({ buyer: 'nope' })))._s).toBe(400);
+ expect((await get(downloadHandler, url({ network: 'ethereum' })))._s).toBe(400);
+ });
+
+ it('rate limited → 429 carrying retry-after, not a bare refusal', async () => {
+ rl.ok = false;
+ const r = await get(downloadHandler, url());
+ expect(r._s).toBe(429);
+ expect(r._h['retry-after']).toBeTruthy();
+ expect(r.json().retry_after).toBeGreaterThan(0);
+ });
+});
+
+describe('GET /api/vault/buy-policy-data', () => {
+ const buyer = '0x5555555555555555555555555555555555555555';
+ const url = (over = {}) => `/api/vault/buy-policy-data?${new URLSearchParams({ objectId: OBJECT_ID, buyer, ...over })}`;
+
+ it('a real Greenfield resource id → real protobuf policy bytes', async () => {
+ store.refs.set(OBJECT_ID, { bucket: 'three-ws-vault-testnet', glbObject: 'vaults/p/1.glb.enc', manifestObject: 'vaults/p/1.manifest.json' });
+ greenfield.meta = { id: '18446744073709551', owner: SELLER };
+ const r = await get(policyDataHandler, url());
+ expect(r._s).toBe(200);
+ const body = r.json();
+ expect(body.resourceId).toBe('18446744073709551');
+ expect(body.policyData).toMatch(/^0x[0-9a-f]+$/);
+ expect(body.buyer.toLowerCase()).toBe(buyer.toLowerCase());
+ // The bytes are a real `greenfield.permission.Policy`: decoding them back
+ // must yield this buyer as principal and this object as the resource.
+ const { createRequire } = await import('node:module');
+ const require = createRequire(import.meta.url);
+ const { Policy } = require('@bnb-chain/greenfield-cosmos-types/greenfield/permission/types.js');
+ const decoded = Policy.decode(Buffer.from(body.policyData.slice(2), 'hex'));
+ expect(decoded.principal.value.toLowerCase()).toBe(buyer.toLowerCase());
+ expect(decoded.resourceId).toBe('18446744073709551');
+ expect(decoded.statements).toHaveLength(1);
+ });
+
+ it('an objectId with no resolvable Greenfield ref → 404 not_listed, never invented bytes', async () => {
+ const r = await get(policyDataHandler, url());
+ expect(r._s).toBe(404);
+ expect(r.json().error).toBe('not_listed');
+ });
+
+ it('an object never mirrored to Greenfield → 404 object_not_found, never a fabricated resourceId', async () => {
+ store.refs.set(OBJECT_ID, { bucket: 'b', glbObject: 'o.glb.enc', manifestObject: 'o.manifest.json' });
+ greenfield.error = new GreenfieldError('head_object 404', 'not_found');
+ const r = await get(policyDataHandler, url());
+ expect(r._s).toBe(404);
+ expect(r.json().error).toBe('object_not_found');
+ });
+
+ it('metadata with a zero resource id → 404, never a policy bound to id 0', async () => {
+ store.refs.set(OBJECT_ID, { bucket: 'b', glbObject: 'o.glb.enc', manifestObject: 'o.manifest.json' });
+ greenfield.meta = { id: '0' };
+ const r = await get(policyDataHandler, url());
+ expect(r._s).toBe(404);
+ expect(r.json().error).toBe('object_not_found');
+ });
+
+ it('Greenfield unreachable → 503, not a 404 that reads as "never uploaded"', async () => {
+ store.refs.set(OBJECT_ID, { bucket: 'b', glbObject: 'o.glb.enc', manifestObject: 'o.manifest.json' });
+ greenfield.error = new GreenfieldError('lcd timeout', 'unavailable');
+ const r = await get(policyDataHandler, url());
+ expect(r._s).toBe(503);
+ expect(r.json().error).toBe('greenfield_unavailable');
+ });
+
+ it('bad objectId / buyer / network → 400', async () => {
+ expect((await get(policyDataHandler, url({ objectId: 'nope' })))._s).toBe(400);
+ expect((await get(policyDataHandler, url({ buyer: 'nope' })))._s).toBe(400);
+ expect((await get(policyDataHandler, url({ network: 'ethereum' })))._s).toBe(400);
+ });
+
+ it('rate limited → 429', async () => {
+ rl.ok = false;
+ expect((await get(policyDataHandler, url()))._s).toBe(429);
+ });
+});