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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(bnb-vault): unlock API (list/status/unlock) — real anvil E2E proof
fudjia12e9b92103db
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b5028e38e..167130a55 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -30,6 +30,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Agent mood now shapes body language, not just facial expression** — An agent's sustained mood — set via setMood(), tracked as valence and arousal — used to only drive the face (a smile, a worried brow) and posture. Now a resting up-and-energetic mood also nudges the agent toward a livelier gesture between events, and a down-and-subdued mood toward a stiller, more concerned one, so an agent's whole body reads as consistent with how it feels, not just its expression. A real triggered gesture (a wave, a reaction to an error) still always takes priority over this ambient bias. (`/tutorials/emotion-from-data`) `[feature, improvement]`- **Bigger motion library, and two dead animation gestures fixed** — Added 7 new baked clips to the animation library — Nod, Shrug, Point, Think, Turn, Jog, and a sitting-idle loop — retargeted onto the universal avatar rig alongside the existing 100+. Also fixed two silent no-ops: the 'sit' gesture's clip was missing from the manifest (AnimationManager couldn't find it, so avatars silently failed to sit), and the agent 'fidget' slot pointed at a clip that never existed (now maps to a real idle loop). Both are covered by new regression tests so they can't quietly break again. (`/animations`) `[feature, fix]`- **BNB Chain hub: three uniquely-BNB demos in one place** — New /bnb landing page tells the whole BNB Chain story: gasless agent onboarding (a zero-balance wallet mints an on-chain identity, no faucet), an on-chain-gated 3D vault backed by Greenfield storage permissions, and a real-time on-chain world riding BNB's ~0.45s blocks — each claim traced to what we independently verified live, never BNB's own roadmap promises. The page embeds a live block-time widget that measures the real average off a public RPC on every load, and each feature card auto-detects whether its track has actually shipped on this deployment, showing an honest "coming soon" instead of a dead link until it has. (`/bnb`) `[feature]`+- **BNB vault unlock API: pay, get gated, decrypt — built, blocked on funding** — The BNB Greenfield 3D vault now has its buyer-facing API: browse what's listed, check whether a purchase and its cross-chain storage-permission grant have settled, and — once both are confirmed on-chain — unlock a one-time-use, per-buyer encryption key for the model. A buyer proves control of their wallet with a signed message, which doubles as the key the vault re-wraps the content key to, so a captured response is useless to anyone but that buyer. Proven end-to-end against a real locally-deployed copy of the vault contract (real transactions, real event logs, real pending-then-granted state transitions) — full public rollout is pending the same funded BSC testnet deployer key blocking the rest of this track. `[feature, infra]`- **Cleaned up the x402 storefront listing** — Delisted internal-use-only paid endpoints from the public x402 catalog while keeping their in-product functionality live, removed a dead endpoint with no real buyer, dropped a fake bullish/bearish framing from the ticker-collision checker, and re-listed three previously-hidden endpoints (fact-checking, token-to-3D rendering) as honest, discoverable products. `[improvement]`- **Crypto API now has a home page and a real OpenAPI spec** — The free /api/v1/x crypto aggregator (CoinGecko, DefiLlama, Jupiter, DexScreener, Solana RPC) has a public storefront at three.ws/crypto-api with a live endpoint table, and every endpoint now shows up in the OpenAPI 3.1 spec at three.ws/openapi.json. Also fixed a bug where the discovery endpoint (GET /api/v1/x) 404'd in production. (`/crypto-api`) `[feature, docs, fix]`- **Draw a sketch or speak your prompt in the Forge** — Two new ways to start a 3D creation, both live at /forge and /create/prompt. Draw it: click "Or draw it instead" in the Forge's photo tab to open an in-browser drawing canvas — sketch with your mouse, finger, or stylus, and the drawing feeds the same reconstruction pipeline as an uploaded photo. Say it: click the mic next to any prompt box and describe what you want out loud; the transcript drops into the field, ready to edit before you generate. Voice uses your browser's built-in speech recognition where available, with a free NVIDIA Riva fallback for browsers without one — nothing is ever written to disk. Multi-photo reconstruction (up to 4 angles of the same object) and photo-to-avatar (the /scan selfie flow) were already live; this closes out the last two on-ramps into generation. (`/forge`) `[feature]`diff --git a/api/_lib/bnb/vault-contract.js b/api/_lib/bnb/vault-contract.jsnew file mode 100644index 000000000..5ff6e1eec--- /dev/null+++ b/api/_lib/bnb/vault-contract.js@@ -0,0 +1,168 @@+/**+ * On-chain reads for `GreenfieldVault.sol` (prompt 10) — the marketplace+ * contract `api/vault/*` (prompt 11) is built on. Mirrors+ * `contracts/src/GreenfieldVault.sol`'s external surface exactly (see+ * `contracts/DEPLOYMENTS.md`'s GreenfieldVault section for addresses/status).+ * Read-only: no signing, no private keys — buying/listing/revoking happen+ * from the buyer's/seller's own wallet directly against the contract (the+ * vault UI, prompt 12), not relayed through this server.+ */++import { parseAbi } from 'viem';+import { getPublicClient, BNB_CHAINS, assertBscAddress } from './chains.js';++/** Mirrors contracts/src/GreenfieldVault.sol's external read surface + events exactly. */+export const GREENFIELD_VAULT_ABI = parseAbi([+ 'function listings(bytes32) view returns (address seller, uint256 price, bool active)',+ 'function sales(uint256) view returns (bytes32 objectId, address buyer, address seller, uint256 price, uint256 policyId, uint8 status)',+ 'function saleIdOf(bytes32, address) view returns (uint256)',+ 'function pendingWithdrawals(address) view returns (uint256)',+ 'function quoteRelayFee() view returns (uint256 relayFee, uint256 minAckRelayFee, uint256 total)',+ 'event Listed(bytes32 indexed objectId, address indexed seller, uint256 price)',+ 'event Delisted(bytes32 indexed objectId, address indexed seller)',+ 'event Purchased(bytes32 indexed objectId, address indexed buyer, uint256 indexed saleId, uint256 price)',+ 'event PolicyGranted(bytes32 indexed objectId, address indexed buyer, uint256 indexed saleId, uint256 policyId)',+ 'event PolicyGrantFailed(bytes32 indexed objectId, address indexed buyer, uint256 indexed saleId, uint32 status)',+ 'event RevokeRequested(bytes32 indexed objectId, uint256 indexed saleId, uint256 policyId)',+]);++/** Mirrors `GreenfieldVault.SaleStatus` enum order exactly. */+export const SALE_STATUS = ['Pending', 'Granted', 'Failed', 'Revoked'];++/** Named lookup of the parsed event fragments — indexed by name, never by array position. */+const VAULT_EVENTS = Object.fromEntries(GREENFIELD_VAULT_ABI.filter((item) => item.type === 'event').map((item) => [item.name, item]));++export class VaultContractError extends Error {+ /** @param {string} message @param {{ code?: string, cause?: unknown }} [info] */+ constructor(message, info = {}) {+ super(message);+ this.name = 'VaultContractError';+ this.code = info.code || 'vault_contract_error';+ if (info.cause) this.cause = info.cause;+ }+}++/**+ * Resolve the deployed vault contract address for a network. Mirrors+ * `api/bnb/vault-upload.js`'s `vaultContractAddress` (moved here so both the+ * writer and every reader agree on one lookup). Real deploy is blocked on a+ * funded deployer key (contracts/DEPLOYMENTS.md) — until+ * `GREENFIELD_VAULT_ADDRESS_{TESTNET,MAINNET}` is set, this returns the+ * spec-illustrated placeholder address with `deployed:false` rather than+ * inventing a real one.+ * @param {'testnet'|'mainnet'} network+ * @param {string} [override]+ * @returns {{ address: `0x${string}`, deployed: boolean }}+ */+export function vaultContractAddress(network, override) {+ if (override) return { address: assertBscAddress(override), deployed: true };+ const envVar = network === 'mainnet' ? 'GREENFIELD_VAULT_ADDRESS_MAINNET' : 'GREENFIELD_VAULT_ADDRESS_TESTNET';+ const configured = process.env[envVar];+ if (configured) return { address: assertBscAddress(configured), deployed: true };+ return { address: '0x0000000000000000000000000000000000dEaD', deployed: false };+}++/** viem chain key ('bscMainnet'|'bscTestnet') for a 'testnet'|'mainnet' network string. */+export function chainKeyFor(network) {+ return network === 'mainnet' ? 'bscMainnet' : 'bscTestnet';+}++/** Optional env override for how far back `getVaultLogs` scans by default (blocks). */+function defaultLookbackBlocks(network) {+ const envVar = network === 'mainnet' ? 'GREENFIELD_VAULT_LOOKBACK_BLOCKS_MAINNET' : 'GREENFIELD_VAULT_LOOKBACK_BLOCKS_TESTNET';+ const n = Number(process.env[envVar]);+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 100_000; // ~12.5h of BSC testnet blocks at 0.45s+}++/**+ * `listings(objectId)` — active listing state.+ * @returns {Promise<{ seller: `0x${string}`, price: bigint, active: boolean }>}+ */+export async function readListing(client, address, objectId) {+ const [seller, price, active] = await client.readContract({+ address,+ abi: GREENFIELD_VAULT_ABI,+ functionName: 'listings',+ args: [objectId],+ });+ return { seller, price, active };+}++/** `saleIdOf(objectId, buyer)` — 0n if the pair has no open purchase. */+export async function readSaleIdOf(client, address, objectId, buyer) {+ return client.readContract({ address, abi: GREENFIELD_VAULT_ABI, functionName: 'saleIdOf', args: [objectId, buyer] });+}++/**+ * `sales(saleId)` — full sale record, `status` decoded to its string name.+ * @returns {Promise<{ objectId:`0x${string}`, buyer:`0x${string}`, seller:`0x${string}`, price:bigint, policyId:bigint, status:string, statusCode:number }>}+ */+export async function readSale(client, address, saleId) {+ const [objectId, buyer, seller, price, policyId, status] = await client.readContract({+ address,+ abi: GREENFIELD_VAULT_ABI,+ functionName: 'sales',+ args: [saleId],+ });+ return { objectId, buyer, seller, price, policyId, status: SALE_STATUS[status] || 'Unknown', statusCode: status };+}++/** Live quote of the BNB relay fee `buy()`/`revoke()` require on top of price. */+export async function quoteRelayFee(client, address) {+ const [relayFee, minAckRelayFee, total] = await client.readContract({+ address,+ abi: GREENFIELD_VAULT_ABI,+ functionName: 'quoteRelayFee',+ });+ return { relayFee, minAckRelayFee, total };+}++/**+ * Index the vault's `Listed`/`Delisted`/`Purchased`/`PolicyGranted`/+ * `PolicyGrantFailed` events over a bounded block range in one `eth_getLogs`+ * call (viem's multi-event `events` form). Defaults to a recent lookback+ * window (env-overridable) rather than genesis — public RPCs reject+ * unbounded `eth_getLogs` ranges, and a just-deployed contract has no older+ * history to miss anyway.+ * @param {import('viem').PublicClient} client+ * @param {`0x${string}`} address+ * @param {{ fromBlock?: bigint, toBlock?: bigint, network?: string }} [opts]+ */+export async function getVaultLogs(client, address, opts = {}) {+ // `cacheTime: 0` bypasses viem's default block-number memo (client.cacheTime,+ // several seconds by default) — without it, two calls to this function made+ // back-to-back (e.g. a poll right after a `buy()`/settlement tx) could read a+ // STALE `toBlock` and silently miss the very Purchased/PolicyGranted logs the+ // caller is polling for. Caught live: an anvil E2E proof run where a+ // post-settlement getVaultLogs() call returned only the pre-buy `Listed` log+ // until this fix.+ const toBlock = opts.toBlock ?? (await client.getBlockNumber({ cacheTime: 0 }));+ const fromBlock = opts.fromBlock ?? (toBlock > BigInt(defaultLookbackBlocks(opts.network)) ? toBlock - BigInt(defaultLookbackBlocks(opts.network)) : 0n);+ try {+ const logs = await client.getLogs({+ address,+ events: [+ VAULT_EVENTS.Listed,+ VAULT_EVENTS.Delisted,+ VAULT_EVENTS.Purchased,+ VAULT_EVENTS.PolicyGranted,+ VAULT_EVENTS.PolicyGrantFailed,+ ],+ fromBlock,+ toBlock,+ });+ return { logs, fromBlock, toBlock };+ } catch (err) {+ throw new VaultContractError(`eth_getLogs failed for GreenfieldVault ${address}: ${err.message}`, { code: 'logs_failed', cause: err });+ }+}++/** viem public client for a 'testnet'|'mainnet' network string, via chains.js. */+export function vaultClient(network) {+ return getPublicClient(chainKeyFor(network));+}++/** BscScan explorer base for a network string. */+export function explorerFor(network) {+ return BNB_CHAINS[chainKeyFor(network)].explorer;+}diff --git a/api/_lib/bnb/vault-store.js b/api/_lib/bnb/vault-store.jsnew file mode 100644index 000000000..695058835--- /dev/null+++ b/api/_lib/bnb/vault-store.js@@ -0,0 +1,130 @@+/**+ * BNB vault off-chain bookkeeping — the small amount of server-side state+ * that glues the on-chain `GreenfieldVault` contract (prompt 10) to the+ * Greenfield-hosted manifest/ciphertext pair a seller uploaded (prompt 09).+ * Shared by `api/bnb/vault-upload.js` (writer) and `api/vault/*` (readers,+ * prompt 11) so both sides agree on one cache-key format and one `objectId`+ * derivation — drifting formats here would silently break every join.+ *+ * Why an off-chain index exists at all: `GreenfieldVault.list(objectId, ...)`+ * takes an opaque `bytes32 objectId` (per its own NatSpec: "matches+ * specs/vault-manifest.md's glbObjectRef, NOT the Greenfield ERC-721 token+ * id"). This module defines that opaque id as+ * `keccak256(utf8("<bucket>/<object>"))` — a canonical, deterministic,+ * one-way binding from a manifest's `glbObjectRef` to the on-chain id. Since+ * it's one-way, going from "an objectId we saw in a `Listed` event" back to+ * "which bucket/object is that" needs an index. `resolveObjectRef` tries the+ * fast KV index first (populated by `vault-upload.js` at upload time) and+ * falls back to a bounded scan of the bucket's own manifest objects — so a+ * listing created by ANY means (our upload endpoint, a future UI, or a raw+ * `cast send list(...)`) is still resolvable, never permanently orphaned by+ * a missing side-index.+ */++import { keccak256, toBytes } from 'viem';+import { cacheGet, cacheSet } from '../cache.js';+import { env } from '../env.js';+import { listObjects, downloadObject, GreenfieldError } from './greenfield.js';++// The vault key record + objectId index have no natural expiry — they must+// outlive the listing until the seller delists or every buyer has unlocked.+// 180 days comfortably covers a real listing lifetime (mirrors the TTL+// vault-upload.js already used for the content-key record before this+// module existed).+export const VAULT_KEY_TTL_S = 180 * 24 * 3600;+export const VAULT_INDEX_TTL_S = VAULT_KEY_TTL_S;++const MANIFEST_SUFFIX = '.manifest.json';+const GLB_SUFFIX = '.glb.enc';+const VAULT_PREFIX = 'vaults/';+const MAX_SCAN_OBJECTS = 500;++/** Cache key for the persisted (encrypted-at-rest) content key of one ciphertext object. */+export function vaultKeyCacheKey(bucket, glbObject) {+ return `bnb:vault:key:${bucket}:${glbObject}`;+}++/** Cache key for the objectId → {bucket, glbObject, manifestObject, sellerAddress} index. */+export function vaultObjectIndexKey(objectId) {+ return `bnb:vault:index:${String(objectId).toLowerCase()}`;+}++/**+ * Canonical on-chain `objectId` for a manifest's `glbObjectRef`. Deterministic+ * and one-way (keccak256) — the same bucket/object pair always derives the+ * same id, matching what a seller (or the future vault UI) passes to+ * `GreenfieldVault.list()`.+ * @param {string} bucket @param {string} glbObject+ * @returns {`0x${string}`}+ */+export function deriveObjectId(bucket, glbObject) {+ return keccak256(toBytes(`${bucket}/${glbObject}`));+}++/** Bucket that hosts every vault object, per network — same default as vault-upload.js. */+export function vaultBucketFor(network) {+ return network === 'mainnet' ? env.GREENFIELD_VAULT_BUCKET_MAINNET : env.GREENFIELD_VAULT_BUCKET_TESTNET;+}++/** Persist the objectId → object-ref index entry (write side, called at upload/list time). */+export async function storeVaultObjectIndex(objectId, ref, ttlSeconds = VAULT_INDEX_TTL_S) {+ return cacheSet(vaultObjectIndexKey(objectId), ref, ttlSeconds);+}++/** Read the objectId → object-ref index entry, or null if not indexed. */+export async function getVaultObjectIndex(objectId) {+ return cacheGet(vaultObjectIndexKey(objectId));+}++/** Read the persisted (encrypted-at-rest) content-key record for a ciphertext object, or null. */+export async function getVaultKeyRecord(bucket, glbObject) {+ return cacheGet(vaultKeyCacheKey(bucket, glbObject));+}++/**+ * Resolve an on-chain `objectId` to its Greenfield object refs. KV index+ * first (fast path); on a miss, bounded-scans the bucket's own+ * `vaults/**\/*.manifest.json` objects, re-derives each candidate's+ * objectId, and self-heals the index on a match so the next lookup is fast+ * again. Never assumes the index is complete — the bucket itself is the+ * source of truth.+ *+ * @param {`0x${string}`} objectId+ * @param {{ network?: 'testnet'|'mainnet', bucket?: string }} [opts]+ * @returns {Promise<{ bucket:string, glbObject:string, manifestObject:string, sellerAddress?:string } | null>}+ */+export async function resolveObjectRef(objectId, opts = {}) {+ const indexed = await getVaultObjectIndex(objectId);+ if (indexed?.bucket && indexed?.glbObject) return indexed;++ const network = opts.network === 'mainnet' ? 'mainnet' : 'testnet';+ const bucket = opts.bucket || vaultBucketFor(network);+ let listing;+ try {+ listing = await listObjects(bucket, { network, prefix: VAULT_PREFIX, maxKeys: MAX_SCAN_OBJECTS });+ } catch (err) {+ if (err instanceof GreenfieldError) return null; // bucket missing/unreachable — nothing to resolve+ throw err;+ }++ for (const obj of listing.objects) {+ if (!obj.name?.endsWith(MANIFEST_SUFFIX)) continue;+ const glbObject = obj.name.slice(0, -MANIFEST_SUFFIX.length) + GLB_SUFFIX;+ if (deriveObjectId(bucket, glbObject) !== objectId) continue;+ const ref = { bucket, glbObject, manifestObject: obj.name };+ await storeVaultObjectIndex(objectId, ref).catch(() => {}); // self-heal, best-effort+ return ref;+ }+ return null;+}++/**+ * Fetch and parse a manifest JSON object from Greenfield (public, no auth).+ * @param {string} bucket @param {string} manifestObject+ * @returns {Promise<object>}+ */+export async function fetchManifest(bucket, manifestObject, opts = {}) {+ const dl = await downloadObject(bucket, manifestObject, opts);+ const text = Buffer.from(dl.bytes).toString('utf8');+ return JSON.parse(text);+}diff --git a/api/_lib/bnb/vault-unlock-auth.js b/api/_lib/bnb/vault-unlock-auth.jsnew file mode 100644index 000000000..6fb88d61c--- /dev/null+++ b/api/_lib/bnb/vault-unlock-auth.js@@ -0,0 +1,156 @@+/**+ * Buyer-proof for `POST /api/vault/unlock` (prompt 11): a plain EIP-191+ * personal-sign message the buyer's wallet signs, proving control of+ * `buyer` at request time. Deliberately reuses the SAME signature to also+ * recover the buyer's real secp256k1 public key (via+ * `recoverPublicKey`/`hashMessage`) — the exact key `vault-crypto.wrapKey`+ * needs — so there is no separate "register your vault pubkey" step: a+ * buyer who can sign as their BSC address can unlock to that same address's+ * real key, matching `specs/vault-manifest.md`'s "Recipient key" note that+ * the buyer's EVM signing key MAY be reused directly as the wrap-recipient+ * key (this module is the prompt-11 decision the spec deferred).+ */++import { hashMessage, recoverMessageAddress, recoverPublicKey } from 'viem';+import { getRedis } from '../redis.js';++export const UNLOCK_MESSAGE_WINDOW_MS = 10 * 60 * 1000; // 10 minutes+const CLOCK_SKEW_MS = 2 * 60 * 1000; // tolerate a buyer's clock running up to 2 min fast++// Single-use lock on the unlock-message nonce, same Redis-or-local-fallback+// posture as mpp-server.js's `reserveNonce` — unlike cache.js's `acquireLock`+// (which returns "acquired" unconditionally when Redis isn't configured, a+// fine trade-off for a best-effort cross-instance lock but wrong for a+// security-relevant replay guard), this ALWAYS enforces single-use locally+// even with no Redis, falling back to a process-local Map.+const localReplay = new Map();++async function reserveNonce(key, ttlMs) {+ const redis = getRedis();+ if (redis) {+ try {+ const ok = await redis.set(key, '1', { nx: true, px: ttlMs });+ return ok === 'OK' || ok === true;+ } catch {+ /* fall through to local */+ }+ }+ const now = Date.now();+ const prev = localReplay.get(key);+ if (prev && prev > now) return false;+ localReplay.set(key, now + ttlMs);+ return true;+}++export class VaultUnlockAuthError extends Error {+ /** @param {string} message @param {{ code?: string, cause?: unknown }} [info] */+ constructor(message, info = {}) {+ super(message);+ this.name = 'VaultUnlockAuthError';+ this.code = info.code || 'auth_error';+ if (info.cause) this.cause = info.cause;+ }+}++/**+ * Build the canonical unlock-request message. Exported so the vault UI+ * (prompt 12) and this module's tests construct byte-identical text.+ * @param {{ objectId:string, buyer:string, network:string, nonce:string, issuedAt:string }} p+ */+export function buildVaultUnlockMessage({ objectId, buyer, network, nonce, issuedAt }) {+ return [+ 'three.ws vault unlock request',+ '',+ `Object: ${objectId}`,+ `Buyer: ${buyer}`,+ `Network: ${network}`,+ `Nonce: ${nonce}`,+ `Issued At: ${issuedAt}`,+ ].join('\n');+}++/** Parse the canonical unlock message back into its fields. Throws if the shape doesn't match. */+export function parseVaultUnlockMessage(message) {+ const lines = String(message || '').split('\n');+ const field = (label) => {+ const line = lines.find((l) => l.startsWith(`${label}: `));+ if (!line) throw new VaultUnlockAuthError(`unlock message is missing "${label}:"`, { code: 'bad_message' });+ return line.slice(label.length + 2).trim();+ };+ if (lines[0] !== 'three.ws vault unlock request') {+ throw new VaultUnlockAuthError('unlock message has the wrong preamble', { code: 'bad_message' });+ }+ return {+ objectId: field('Object'),+ buyer: field('Buyer'),+ network: field('Network'),+ nonce: field('Nonce'),+ issuedAt: field('Issued At'),+ };+}++/**+ * Verify a buyer's unlock-request signature end-to-end: message shape,+ * field cross-check against the caller's stated `objectId`/`buyer`/+ * `network`, signature recovery + address match, freshness window, and a+ * single-use nonce lock (defence-in-depth against a captured+ * message+signature being replayed — Redis-backed when configured, a+ * process-local map otherwise, same posture as mpp-server.js's nonce guard).+ *+ * @param {{ objectId:string, buyer:string, network:string, message:string, signature:string }} input+ * @returns {Promise<{ pubKey: `0x${string}` }>} the buyer's recovered secp256k1 public key+ * @throws {VaultUnlockAuthError} typed, `code` ∈ bad_message|field_mismatch|expired|replay|bad_signature+ */+export async function verifyVaultUnlockAuth({ objectId, buyer, network, message, signature }) {+ if (typeof message !== 'string' || !message || typeof signature !== 'string' || !signature) {+ throw new VaultUnlockAuthError('message and signature are required', { code: 'bad_message' });+ }+ const parsed = parseVaultUnlockMessage(message);++ if (parsed.objectId.toLowerCase() !== String(objectId).toLowerCase()) {+ throw new VaultUnlockAuthError('message objectId does not match the request body', { code: 'field_mismatch' });+ }+ if (parsed.buyer.toLowerCase() !== String(buyer).toLowerCase()) {+ throw new VaultUnlockAuthError('message buyer does not match the request body', { code: 'field_mismatch' });+ }+ if (parsed.network !== network) {+ throw new VaultUnlockAuthError('message network does not match the request body', { code: 'field_mismatch' });+ }++ const issuedAtMs = Date.parse(parsed.issuedAt);+ if (!Number.isFinite(issuedAtMs)) {+ throw new VaultUnlockAuthError('message Issued At is not a valid timestamp', { code: 'bad_message' });+ }+ const now = Date.now();+ if (issuedAtMs > now + CLOCK_SKEW_MS || now - issuedAtMs > UNLOCK_MESSAGE_WINDOW_MS) {+ throw new VaultUnlockAuthError('unlock message has expired — sign a fresh one', { code: 'expired' });+ }++ if (!parsed.nonce || parsed.nonce.length < 8) {+ throw new VaultUnlockAuthError('message Nonce is missing or too short', { code: 'bad_message' });+ }+ const lockKey = `bnb:vault:unlock:nonce:${parsed.nonce}`;+ const fresh = await reserveNonce(lockKey, UNLOCK_MESSAGE_WINDOW_MS + CLOCK_SKEW_MS);+ if (!fresh) {+ throw new VaultUnlockAuthError('this unlock request was already used', { code: 'replay' });+ }++ let recovered;+ try {+ recovered = await recoverMessageAddress({ message, signature });+ } catch (err) {+ throw new VaultUnlockAuthError('signature recovery failed', { code: 'bad_signature', cause: err });+ }+ if (recovered.toLowerCase() !== String(buyer).toLowerCase()) {+ throw new VaultUnlockAuthError('signature does not match buyer', { code: 'bad_signature' });+ }++ let pubKey;+ try {+ pubKey = await recoverPublicKey({ hash: hashMessage(message), signature });+ } catch (err) {+ throw new VaultUnlockAuthError('public key recovery failed', { code: 'bad_signature', cause: err });+ }++ return { pubKey };+}diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex b7fe8b11f..cff78e699 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -488,6 +488,15 @@ export const limits = {// track. Tight per-IP ceiling; a seller listing dozens of items per hour is// already an outlier, and each call carries real Greenfield gas cost.bnbVaultUploadIp: (ip) => getLimiter('bnb:vault:upload:ip', { limit: 20, window: '1 h' }).limit(ip),+ // BNB vault reads (api/vault/list.js, api/vault/status.js) — free, no+ // write cost, but each call does a real `eth_getLogs`/`eth_call` against a+ // public RPC (list.js) or a Storage-Provider fetch (manifest joins), so a+ // generous but real ceiling, not unlimited.+ bnbVaultReadIp: (ip) => getLimiter('bnb:vault:read:ip', { limit: 120, window: '10 m' }).limit(ip),+ // BNB vault unlock (api/vault/unlock.js) — the one call in this track that+ // releases a real (wrapped) secret. Tighter than the read ceiling; a+ // legitimate buyer unlocks the same object at most a handful of times.+ bnbVaultUnlockIp: (ip) => getLimiter('bnb:vault:unlock:ip', { limit: 30, window: '10 m', critical: true }).limit(ip),// Status polling is the highest-frequency call in the generation flow (every// active job polls every few seconds, plus the /forge health pill). It only// guards against pathological poll floods, so it is enforced per instancediff --git a/api/bnb/vault-upload.js b/api/bnb/vault-upload.jsindex 48e12ce43..1c7998096 100644--- a/api/bnb/vault-upload.js+++ b/api/bnb/vault-upload.js@@ -52,6 +52,8 @@ import { assertPublicHttpsUrl } from '../_lib/ssrf.js';import { assertBscAddress, BNB_CHAINS } from '../_lib/bnb/chains.js';import { encryptGlb, VAULT_CRYPTO_PARAMS } from '../_lib/bnb/vault-crypto.js';import { ensureBucket, createObject, GreenfieldWriteError, MAX_VAULT_OBJECT_BYTES } from '../_lib/bnb/greenfield-write.js';+import { vaultContractAddress } from '../_lib/bnb/vault-contract.js';+import { vaultBucketFor, vaultKeyCacheKey, deriveObjectId, storeVaultObjectIndex, VAULT_KEY_TTL_S } from '../_lib/bnb/vault-store.js';import { priceFor } from '../_lib/x402-prices.js';import { encryptSecret } from '../_lib/secret-box.js';import { cacheSet } from '../_lib/cache.js';@@ -61,11 +63,6 @@ const MAX_INPUT_GLB_BYTES = 64 * 1024 * 1024; // a vault GLB is a 3D asset, not// JSON body cap: base64 inflates raw bytes ~4/3; the +8KB covers the other fields.const MAX_JSON_BODY_BYTES = Math.ceil((MAX_INPUT_GLB_BYTES * 4) / 3) + 8192;const MANIFEST_VERSION = 1;-// The vault key record has no natural expiry — it must outlive the listing-// until the seller delists or every content-key holder has bought. 180 days-// comfortably covers a real listing lifetime; prompt 11/vault delisting can-// refresh it on access if a longer horizon is ever needed.-const VAULT_KEY_TTL_S = 180 * 24 * 3600;class VaultUploadError extends Error {constructor(message, { status = 400, code = 'bad_request', extra } = {}) {@@ -136,32 +133,6 @@ function normalizeNetwork(raw) {return null;}-function vaultBucketFor(network) {- return network === 'mainnet' ? env.GREENFIELD_VAULT_BUCKET_MAINNET : env.GREENFIELD_VAULT_BUCKET_TESTNET;-}--/**- * The GreenfieldVault.sol contract (prompt 10) is code-complete but its- * public-testnet deploy is blocked on a funded deployer key (same root cause- * documented for prompts 07/09/10/13/14/18 in PROGRESS.md) — there is no real- * address to record yet. Mirrors the honest "not deployed yet" pattern- * api/_lib/bnb/world-moves.js established for WorldMoves: return the- * spec-illustrated placeholder (specs/vault-manifest.md's own example uses- * this exact address) rather than inventing one, and tell the caller plainly- * via `contractDeployed:false` in the response.- */-function vaultContractAddress(network, override) {- if (override) return { address: assertBscAddress(override), deployed: true };- const envVar = network === 'mainnet' ? 'GREENFIELD_VAULT_ADDRESS_MAINNET' : 'GREENFIELD_VAULT_ADDRESS_TESTNET';- const configured = process.env[envVar];- if (configured) return { address: assertBscAddress(configured), deployed: true };- return { address: '0x0000000000000000000000000000000000dEaD', deployed: false };-}--function vaultKeyCacheKey(bucket, object) {- return `bnb:vault:key:${bucket}:${object}`;-}-const mapGreenfieldWriteStatus = {bad_input: 400,too_large: 413,@@ -292,10 +263,19 @@ export default wrap(async (req, res) => {const status = glbWrite.status === 'stored' && manifestWrite.status === 'stored' ? 'stored' : 'pending';+ // ── Index objectId → object refs so prompt 11's unlock/list/status APIs+ // can resolve a `Listed(objectId, ...)` chain event back to this manifest+ // without needing to reverse a hash — see vault-store.js's deriveObjectId+ // doc comment for why this exists. `objectId` is what a seller passes to+ // `GreenfieldVault.list(objectId, price, seller)` (prompt 12/10).+ const objectId = deriveObjectId(bucket, glbObjectName);+ await storeVaultObjectIndex(objectId, { bucket, glbObject: glbObjectName, manifestObject: manifestObjectName, sellerAddress });+return json(res,200,{+ objectId,manifestRef: { bucket, object: manifestObjectName },glbObjectRef: { bucket, object: glbObjectName },sha256: sha256OfPlaintext,diff --git a/api/vault/list.js b/api/vault/list.jsnew file mode 100644index 000000000..3a1cc039f--- /dev/null+++ b/api/vault/list.js@@ -0,0 +1,134 @@+// GET /api/vault/list+// ---------------------------------------------------------------------------+// BNB vault track (prompt 11): browse active listings. Source of truth is+// the on-chain GreenfieldVault contract's `Listed`/`Delisted` events (never+// a copy that could drift); each active objectId is then joined with its+// Greenfield-hosted manifest (prompt 09) for display metadata (price,+// seller, sha256, object refs). An objectId the index can't resolve to a+// manifest is surfaced honestly in `unresolved`, never silently dropped.+//+// Query: ?network=testnet|mainnet (default testnet) &contractAddress=0x…+// (override; mirrors vault-upload.js's same escape hatch for tests)+// Response 200:+// { network, contractAddress, contractDeployed, count, listings: [+// { objectId, seller, priceAtomic, glbObjectRef, manifestRef, sha256, createdAt }+// ], unresolved: [objectId, …] }++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { BnbRpcError } from '../_lib/bnb/chains.js';+import { vaultContractAddress, vaultClient, getVaultLogs, VaultContractError } from '../_lib/bnb/vault-contract.js';+import { resolveObjectRef, fetchManifest } from '../_lib/bnb/vault-store.js';+import { GreenfieldError } from '../_lib/bnb/greenfield.js';++function normalizeNetwork(raw) {+ const v = String(raw || '').trim().toLowerCase();+ if (v === '' || v === 'testnet' || v === '97' || v === 'bsctestnet') return 'testnet';+ if (v === 'mainnet' || v === '56' || v === 'bscmainnet') return 'mainnet';+ return null;+}++/** Fold Listed/Delisted logs (in block/log order) into the currently-active objectId set. */+function activeListingsFromLogs(logs) {+ const sorted = [...logs].sort((a, b) => (a.blockNumber === b.blockNumber ? a.logIndex - b.logIndex : Number(a.blockNumber - b.blockNumber)));+ const state = new Map(); // objectId -> { seller, price, active }+ for (const log of sorted) {+ const objectId = log.args.objectId;+ if (log.eventName === 'Listed') {+ state.set(objectId, { seller: log.args.seller, price: log.args.price, active: true });+ } else if (log.eventName === 'Delisted') {+ const existing = state.get(objectId);+ if (existing) existing.active = false;+ else state.set(objectId, { seller: log.args.seller, price: 0n, active: false });+ }+ }+ return [...state.entries()].filter(([, v]) => v.active);+}++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.bnbVaultReadIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl, 'too many vault reads');++ 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"`);+ }++ const { address: contractAddress, deployed: contractDeployed } = vaultContractAddress(network, params.get('contractAddress'));+ if (!contractDeployed) {+ // Honest empty state: nothing can be listed on a contract that isn't live yet.+ return json(res, 200, { network, contractAddress, contractDeployed, count: 0, listings: [], unresolved: [] }, { 'cache-control': 'no-store' });+ }++ let client;+ try {+ client = vaultClient(network);+ } catch (err) {+ return error(res, 400, 'bad_request', err.message);+ }++ let logsResult;+ try {+ logsResult = await getVaultLogs(client, contractAddress, { network });+ } catch (err) {+ if (err instanceof VaultContractError || err instanceof BnbRpcError) {+ return error(res, 503, 'chain_unavailable', `could not read GreenfieldVault logs: ${err.message}`);+ }+ throw err;+ }++ const active = activeListingsFromLogs(logsResult.logs);+ const listings = [];+ const unresolved = [];++ for (const [objectId, chainListing] of active) {+ let ref;+ try {+ ref = await resolveObjectRef(objectId, { network });+ } catch {+ ref = null;+ }+ if (!ref) {+ unresolved.push(objectId);+ continue;+ }+ let manifest = null;+ try {+ manifest = await fetchManifest(ref.bucket, ref.manifestObject, { network });+ } catch (err) {+ // Manifest gone/unreachable — still surface the on-chain listing (never+ // hide real chain state), just without the off-chain metadata.+ if (!(err instanceof GreenfieldError)) throw err;+ }+ listings.push({+ objectId,+ seller: chainListing.seller,+ priceAtomic: chainListing.price.toString(),+ glbObjectRef: { bucket: ref.bucket, object: ref.glbObject },+ manifestRef: { bucket: ref.bucket, object: ref.manifestObject },+ sha256: manifest?.sha256 ?? null,+ manifestPriceAtomic: manifest?.priceAtomic ?? null,+ createdAt: manifest?.createdAt ?? null,+ });+ }++ return json(+ res,+ 200,+ {+ network,+ contractAddress,+ contractDeployed,+ fromBlock: logsResult.fromBlock.toString(),+ toBlock: logsResult.toBlock.toString(),+ count: listings.length,+ listings,+ unresolved,+ },+ { 'cache-control': 'public, max-age=5, s-maxage=10, stale-while-revalidate=30' },+ );+});diff --git a/api/vault/status.js b/api/vault/status.jsnew file mode 100644index 000000000..1352d1470--- /dev/null+++ b/api/vault/status.js@@ -0,0 +1,123 @@+// GET /api/vault/status?objectId=&buyer=&network=+// ---------------------------------------------------------------------------+// BNB vault track (prompt 11): is this buyer's purchase on-chain, and has+// the Greenfield permission grant settled? Reads GreenfieldVault's+// `saleIdOf`/`sales`/`listings` mappings directly — always current chain+// state, never a cached copy. The `pending-grant` state (Greenfield's+// cross-chain ack settles asynchronously, per 00-CONTEXT) is represented+// honestly, not glossed over.+//+// Response 200:+// { objectId, buyer, network, contractAddress, contractDeployed,+// listing: { seller, priceAtomic, active } | null,+// saleId, purchased, policySettled, saleStatus,+// state: 'unlisted'|'available'|'pending-grant'|'unlocked', pollHint? }++import { cors, json, 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';++function normalizeNetwork(raw) {+ const v = String(raw || '').trim().toLowerCase();+ if (v === '' || v === 'testnet' || v === '97' || v === 'bsctestnet') return 'testnet';+ if (v === 'mainnet' || v === '56' || v === 'bscmainnet') return 'mainnet';+ return null;+}++function isBytes32(v) {+ return typeof v === 'string' && /^0x[0-9a-fA-F]{64}$/.test(v);+}++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.bnbVaultReadIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl, 'too many vault reads');++ 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"`);+ }++ const objectId = params.get('objectId');+ if (!isBytes32(objectId)) {+ return error(res, 400, 'bad_request', 'objectId must be a 0x-prefixed 32-byte hex value');+ }+ if (!isEvmAddress(params.get('buyer'))) {+ return error(res, 400, 'bad_request', 'buyer must be a valid EVM address');+ }+ const buyer = assertBscAddress(params.get('buyer'));++ const { address: contractAddress, deployed: contractDeployed } = vaultContractAddress(network);+ if (!contractDeployed) {+ return json(+ res,+ 200,+ { objectId, buyer, network, contractAddress, contractDeployed, listing: null, saleId: '0', purchased: false, policySettled: false, state: 'unlisted' },+ { 'cache-control': 'no-store' },+ );+ }++ let client;+ try {+ client = vaultClient(network);+ } catch (err) {+ return error(res, 400, 'bad_request', err.message);+ }++ try {+ const [listing, saleId] = await Promise.all([+ readListing(client, contractAddress, objectId),+ readSaleIdOf(client, contractAddress, objectId, buyer),+ ]);++ const listingOut = { seller: listing.seller, priceAtomic: listing.price.toString(), active: listing.active };++ if (saleId === 0n) {+ const state = listing.active ? 'available' : 'unlisted';+ return json(+ res,+ 200,+ { objectId, buyer, network, contractAddress, contractDeployed, listing: listingOut, saleId: '0', purchased: false, policySettled: false, state },+ { 'cache-control': 'no-store' },+ );+ }++ const sale = await readSale(client, contractAddress, saleId);+ const policySettled = sale.status === 'Granted';+ // Failed/Revoked clear saleIdOf on-chain (a retry/resell becomes possible),+ // so reaching a non-zero saleId here with a non-Granted status can only be+ // the genuinely in-flight Greenfield ack (Pending) — surfaced honestly, not+ // as an error.+ const state = policySettled ? 'unlocked' : 'pending-grant';++ return json(+ res,+ 200,+ {+ objectId,+ buyer,+ network,+ contractAddress,+ contractDeployed,+ listing: listingOut,+ saleId: saleId.toString(),+ policyId: sale.policyId.toString(),+ purchased: true,+ policySettled,+ saleStatus: sale.status,+ state,+ pollHint: state === 'pending-grant' ? 'Greenfield permission grant is still mirroring cross-chain — poll again shortly' : undefined,+ },+ { 'cache-control': 'no-store' },+ );+ } catch (err) {+ if (err instanceof VaultContractError || err instanceof BnbRpcError) {+ return error(res, 503, 'chain_unavailable', `could not read GreenfieldVault state: ${err.message}`);+ }+ throw err;+ }+});diff --git a/api/vault/unlock.js b/api/vault/unlock.jsnew file mode 100644index 000000000..ca8d09011--- /dev/null+++ b/api/vault/unlock.js@@ -0,0 +1,217 @@+// POST /api/vault/unlock+// ---------------------------------------------------------------------------+// BNB vault track (prompt 11): the endpoint where payment (contract, prompt+// 10), storage (Greenfield, prompts 07/09), and crypto (envelope, prompt 08)+// meet. A buyer proves control of their address with a signed message+// (api/_lib/bnb/vault-unlock-auth.js), which ALSO recovers their real+// secp256k1 public key — no separate pubkey-registration step. Only once the+// contract shows a settled purchase (`sales[saleId].status == Granted`) does+// this re-wrap the object's content key to that key+// (`vault-crypto.wrapKey`) and return it. The raw content key and the+// plaintext GLB are NEVER returned — the buyer downloads ciphertext via+// Greenfield (07's `downloadObject`) and decrypts locally with the wrapped+// key this endpoint hands back.+//+// Body (application/json):+// { objectId: '0x…32-byte', buyer: '0x…EVM address', network?: 'testnet'|'mainnet',+// message: string, signature: '0x…' }+// `message` must be exactly `buildVaultUnlockMessage({objectId, buyer, network, nonce, issuedAt})`+// (api/_lib/bnb/vault-unlock-auth.js) — the buyer's wallet signs it.+//+// Response 200 (unlocked):+// { state:'unlocked', objectId, buyer, saleId, policyId, glbObjectRef, manifest,+// wrappedKey: { ephemeralPublicKey, iv, authTag, ciphertext } (all 0x-hex) }+// Response 200 (pending-grant): { state:'pending-grant', pollHint, saleId }+// Response 401: bad/expired/replayed signature.+// Response 403: no purchase found (still listed — buy first).+// Response 404: objectId was never listed.+// Response 410: delisted with no purchase, OR the seller's key record has+// expired/is unavailable.+// Response 503: contract not deployed yet / chain or Greenfield unreachable.++import { cors, json, method, wrap, error, readJson, 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';+import { verifyVaultUnlockAuth, VaultUnlockAuthError } from '../_lib/bnb/vault-unlock-auth.js';+import { resolveObjectRef, getVaultKeyRecord, fetchManifest } from '../_lib/bnb/vault-store.js';+import { wrapKey, VaultCryptoError } from '../_lib/bnb/vault-crypto.js';+import { GreenfieldError } from '../_lib/bnb/greenfield.js';+import { decryptSecret } from '../_lib/secret-box.js';++function normalizeNetwork(raw) {+ const v = String(raw || '').trim().toLowerCase();+ if (v === '' || v === 'testnet' || v === '97' || v === 'bsctestnet') return 'testnet';+ if (v === 'mainnet' || v === '56' || v === 'bscmainnet') return 'mainnet';+ return null;+}++function isBytes32(v) {+ return typeof v === 'string' && /^0x[0-9a-fA-F]{64}$/.test(v);+}++const AUTH_STATUS = { bad_message: 400, field_mismatch: 400, expired: 401, replay: 401, bad_signature: 401 };++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['POST'])) return;++ const rl = await limits.bnbVaultUnlockIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl, 'too many unlock attempts');++ let body;+ try {+ body = await readJson(req);+ } catch (e) {+ return error(res, e.status || 400, 'bad_body', e.message || 'failed to read JSON body');+ }++ const network = normalizeNetwork(body?.network);+ if (network === null) {+ return error(res, 400, 'bad_request', `unknown network "${body?.network}" — use "testnet" or "mainnet"`);+ }+ const objectId = body?.objectId;+ if (!isBytes32(objectId)) {+ return error(res, 400, 'bad_request', 'objectId must be a 0x-prefixed 32-byte hex value');+ }+ if (!isEvmAddress(body?.buyer)) {+ return error(res, 400, 'bad_request', 'buyer must be a valid EVM address');+ }+ const buyer = assertBscAddress(body.buyer);++ // ── Proof of buyer control (also recovers the wrap-recipient public key). ──+ let pubKey;+ try {+ ({ pubKey } = await verifyVaultUnlockAuth({ objectId, buyer, network, message: body?.message, signature: body?.signature }));+ } catch (err) {+ if (err instanceof VaultUnlockAuthError) {+ return error(res, AUTH_STATUS[err.code] || 401, err.code, err.message);+ }+ throw err;+ }++ const { address: contractAddress, deployed: contractDeployed } = vaultContractAddress(network);+ if (!contractDeployed) {+ return error(res, 503, 'contract_not_deployed', 'the GreenfieldVault contract is not deployed on this network yet');+ }++ let client;+ try {+ client = vaultClient(network);+ } catch (err) {+ return error(res, 400, 'bad_request', err.message);+ }++ let listing, saleId;+ try {+ [listing, saleId] = await Promise.all([+ readListing(client, contractAddress, objectId),+ readSaleIdOf(client, contractAddress, objectId, buyer),+ ]);+ } catch (err) {+ if (err instanceof VaultContractError || err instanceof BnbRpcError) {+ return error(res, 503, 'chain_unavailable', `could not read GreenfieldVault state: ${err.message}`);+ }+ throw err;+ }++ if (saleId === 0n) {+ if (listing.seller === '0x0000000000000000000000000000000000000000') {+ return error(res, 404, 'not_listed', 'this objectId has never been listed on the vault contract');+ }+ if (!listing.active) {+ return error(res, 410, 'delisted', 'this object has been delisted and was never purchased by this buyer');+ }+ return error(res, 403, 'purchase_required', 'this buyer has not purchased this object yet', {+ contractAddress,+ priceAtomic: listing.price.toString(),+ seller: listing.seller,+ });+ }++ let sale;+ try {+ sale = await readSale(client, contractAddress, saleId);+ } catch (err) {+ if (err instanceof VaultContractError || err instanceof BnbRpcError) {+ return error(res, 503, 'chain_unavailable', `could not read GreenfieldVault sale state: ${err.message}`);+ }+ throw err;+ }++ if (sale.status !== 'Granted') {+ // Failed/Revoked clear saleIdOf on-chain, so a non-zero saleId with a+ // non-Granted status here is genuinely the async Greenfield ack still+ // in flight — honest 200, not an error.+ 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' },+ { 'cache-control': 'no-store' },+ );+ }++ // ── Resolve the manifest/key material for this objectId. ──+ let ref;+ try {+ ref = await resolveObjectRef(objectId, { network });+ } catch (err) {+ return error(res, 503, 'storage_unavailable', `could not resolve vault object refs: ${err.message}`);+ }+ if (!ref) {+ return error(res, 410, 'object_index_missing', 'this object was purchased on-chain but its Greenfield refs could not be resolved (manifest missing or bucket unreachable)');+ }++ let manifest;+ try {+ manifest = await fetchManifest(ref.bucket, ref.manifestObject, { network });+ } catch (err) {+ if (err instanceof GreenfieldError) {+ return error(res, err.code === 'not_found' ? 410 : 503, `manifest_${err.code}`, `could not fetch manifest: ${err.message}`);+ }+ throw err;+ }++ const keyRecord = await getVaultKeyRecord(ref.bucket, ref.glbObject);+ if (!keyRecord?.contentKeyCiphertext) {+ return error(res, 410, 'key_unavailable', 'the content key for this object is no longer available (expired or never uploaded through this platform)');+ }++ let contentKeyB64;+ try {+ contentKeyB64 = await decryptSecret(keyRecord.contentKeyCiphertext);+ } catch (err) {+ return error(res, 500, 'key_decrypt_failed', `could not decrypt the stored content key: ${err.message}`);+ }+ const contentKey = Buffer.from(contentKeyB64, 'base64');++ let wrapped;+ try {+ wrapped = wrapKey(contentKey, pubKey);+ } catch (err) {+ if (err instanceof VaultCryptoError) return error(res, 400, err.code, err.message);+ throw err;+ }++ return json(+ res,+ 200,+ {+ state: 'unlocked',+ objectId,+ buyer,+ network,+ saleId: saleId.toString(),+ policyId: sale.policyId.toString(),+ glbObjectRef: { bucket: ref.bucket, object: ref.glbObject },+ manifest,+ wrappedKey: {+ ephemeralPublicKey: `0x${wrapped.ephemeralPublicKey.toString('hex')}`,+ iv: `0x${wrapped.iv.toString('hex')}`,+ authTag: `0x${wrapped.authTag.toString('hex')}`,+ ciphertext: `0x${wrapped.ciphertext.toString('hex')}`,+ },+ },+ { 'cache-control': 'no-store' },+ );+});diff --git a/contracts/DEPLOYMENTS.md b/contracts/DEPLOYMENTS.mdindex 43291b55c..31701f4c3 100644--- a/contracts/DEPLOYMENTS.md+++ b/contracts/DEPLOYMENTS.md@@ -409,6 +409,21 @@ one real `buy()`; and paste the BSC tx hash plus the resultingGreenfieldScan once the cross-chain ack settles) per`prompts/bnb-chain/10-vault-contract.md`'s definition of done.+**Prompt 11 (vault unlock API) local-anvil proof, 2026-07-08 — mocked-hubs+deploy script added:** [`script/DeployGreenfieldVaultMocked.s.sol`](script/DeployGreenfieldVaultMocked.s.sol)+deploys `MockCrossChain`/`MockPermissionHub`/`MockGnfdAccessControl` (the+same mocks `test/GreenfieldVault.t.sol`'s 34-test suite already validates)+plus a real `GreenfieldVault` wired to them, on a local anvil chain — LOCAL+TEST-ONLY, never point it at a real network. Used to prove `api/vault/*`+(list/status/unlock) against a genuinely deployed contract + real+transactions before a funded deployer key exists; full run log in+`prompts/bnb-chain/PROGRESS.md`'s prompt 11 entry. One real bug was caught+and fixed by this run: `getVaultLogs()` resolved its default `toBlock` via+viem's `getBlockNumber()`, which memoizes for several seconds by default —+two calls made back-to-back (e.g. right after a `buy()`/settlement tx, the+exact shape of a real poll) could read a stale `toBlock` and silently miss+the newest events. Fixed with `cacheTime: 0` on that one call.+## Notes- Addresses are authoritative in [`src/erc8004/abi.js`](../src/erc8004/abi.js) (`REGISTRY_DEPLOYMENTS`).diff --git a/contracts/script/DeployGreenfieldVaultMocked.s.sol b/contracts/script/DeployGreenfieldVaultMocked.s.solnew file mode 100644index 000000000..b8cf158e6--- /dev/null+++ b/contracts/script/DeployGreenfieldVaultMocked.s.sol@@ -0,0 +1,51 @@+// SPDX-License-Identifier: MIT+pragma solidity ^0.8.24;++import {Script, console} from "forge-std/Script.sol";+import {GreenfieldVault} from "../src/GreenfieldVault.sol";+import {MockCrossChain, MockPermissionHub, MockGnfdAccessControl} from "../test/mocks/MockGreenfield.sol";++/// @notice LOCAL/TEST-ONLY harness: deploys `MockCrossChain` ++/// `MockPermissionHub` + `MockGnfdAccessControl` (the same faithful+/// mocks `test/GreenfieldVault.t.sol`'s 34-test suite already+/// validates against the real interfaces) plus `GreenfieldVault`+/// wired to them, on a local anvil chain. NEVER use against a real+/// network — `DeployGreenfieldVault.s.sol` (the real script) points+/// at the actual, already-deployed Greenfield hubs.+///+/// Exists because a real end-to-end `buy() -> createPolicy ->+/// PolicyGranted` proof needs a seller who already owns a real+/// Greenfield-mirrored object with `ROLE_CREATE` grantable to the+/// vault — which itself needs a funded Greenfield account (the same+/// root-cause blocker documented across prompts 07/09/10/13/14/18 in+/// PROGRESS.md). This script lets prompt 11 (unlock API) and 13+/// (e2e proof) exercise the REAL contract bytecode, REAL event logs,+/// and REAL two-phase async settlement against a REAL local EVM —+/// everything BUT the real cross-chain relay, which cannot exist+/// without the funded key.+///+/// Run:+/// anvil &+/// forge script script/DeployGreenfieldVaultMocked.s.sol:DeployGreenfieldVaultMocked \+/// --rpc-url http://127.0.0.1:8545 \+/// --private-key <anvil default account #0 key> \+/// --broadcast+contract DeployGreenfieldVaultMocked is Script {+ function run() external returns (GreenfieldVault vault, MockPermissionHub permissionHub, MockCrossChain crossChain, MockGnfdAccessControl objectAccessControl) {+ uint256 relayFee = vm.envOr("MOCK_RELAY_FEE", uint256(1e14)); // 0.0001 native token+ uint256 minAckRelayFee = vm.envOr("MOCK_MIN_ACK_RELAY_FEE", uint256(1e14));++ vm.startBroadcast();+ crossChain = new MockCrossChain(relayFee, minAckRelayFee);+ permissionHub = new MockPermissionHub(crossChain);+ objectAccessControl = new MockGnfdAccessControl();+ vault = new GreenfieldVault(address(permissionHub), address(crossChain), address(objectAccessControl));+ vm.stopBroadcast();++ console.log("GreenfieldVault (mocked hubs):", address(vault));+ console.log("MockPermissionHub: ", address(permissionHub));+ console.log("MockCrossChain: ", address(crossChain));+ console.log("MockGnfdAccessControl: ", address(objectAccessControl));+ console.log("relayFee + minAckRelayFee: ", relayFee + minAckRelayFee);+ }+}diff --git a/data/changelog.json b/data/changelog.jsonindex 3784278c4..4f88f2850 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$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-07-08",+ "title": "BNB vault unlock API: pay, get gated, decrypt — built, blocked on funding",+ "summary": "The BNB Greenfield 3D vault now has its buyer-facing API: browse what's listed, check whether a purchase and its cross-chain storage-permission grant have settled, and — once both are confirmed on-chain — unlock a one-time-use, per-buyer encryption key for the model. A buyer proves control of their wallet with a signed message, which doubles as the key the vault re-wraps the content key to, so a captured response is useless to anyone but that buyer. Proven end-to-end against a real locally-deployed copy of the vault contract (real transactions, real event logs, real pending-then-granted state transitions) — full public rollout is pending the same funded BSC testnet deployer key blocking the rest of this track.",+ "tags": [+ "feature",+ "infra"+ ]+ },{"date": "2026-07-08","title": "Real-time on-chain 3D world live on BNB Chain testnet",diff --git a/prompts/bnb-chain/PROGRESS.md b/prompts/bnb-chain/PROGRESS.mdindex da415b316..7ca8825d9 100644--- a/prompts/bnb-chain/PROGRESS.md+++ b/prompts/bnb-chain/PROGRESS.md@@ -1584,3 +1584,217 @@ now fully built, tested, and proven end-to-end against real (local) chain statereal cross-wallet visibility, and a real, deliberately-configured 0.45s block cadence. `docs/bnb-world.md`ships the reproducible walkthrough. Public testnet deploy remains the sole owner-side blocker,identical across items 10/13/14/15/16/18.++---++## 2026-07-08 — Prompt 11: Vault unlock API (list, status, unlock) — SHIPPED, real anvil E2E proof++**Outcome: `api/vault/{list,status,unlock}.js` + three shared libs done, tested, and proven+against a genuinely deployed `GreenfieldVault` on a local anvil chain — real transactions, real+event logs, real signature verification, real ECIES key wrap/unwrap round trip.** Prereqs 09+(upload pipeline) and 10 (contract) both confirmed present and read line-by-line before starting+— `api/bnb/vault-upload.js`, `api/_lib/bnb/{greenfield.js,greenfield-write.js,vault-crypto.js}`,+`contracts/src/GreenfieldVault.sol`, `specs/vault-manifest.md`. Neither prereq's real Greenfield+SP upload was ever completed (same funded-key wall documented for 07/09/10/13/14/18) and 10's+contract is still undeployed on public testnet — this prompt does not stub around either gap; it+builds the full real code path and proves everything provable without them, documented precisely+below.++**New shared libs (`api/_lib/bnb/`):**+- **`vault-contract.js`** — read-only bindings for `GreenfieldVault.sol`: `GREENFIELD_VAULT_ABI`+ (mirrors the deployed contract's `listings`/`sales`/`saleIdOf`/`quoteRelayFee` + every event+ exactly), `SALE_STATUS` enum decode, `vaultContractAddress()` (moved here from+ `vault-upload.js` so every reader/writer agrees on one lookup — same honest+ `contractDeployed:false` placeholder pattern until `GREENFIELD_VAULT_ADDRESS_{TESTNET,MAINNET}`+ is set), `readListing`/`readSaleIdOf`/`readSale`/`quoteRelayFee`, and `getVaultLogs` (one+ `eth_getLogs` call across `Listed`/`Delisted`/`Purchased`/`PolicyGranted`/`PolicyGrantFailed`+ via viem's multi-event `events` form, bounded to a recent lookback window since public RPCs+ reject unbounded ranges).+- **`vault-store.js`** — the off-chain glue prompt 11 owns per its own brief ("wires them+ together"): `deriveObjectId(bucket, object) = keccak256(utf8("<bucket>/<object>"))` — the+ canonical, one-way binding from a manifest's `glbObjectRef` to the on-chain `bytes32 objectId`+ `GreenfieldVault.list()` takes (the manifest spec never assigned this; prompt 11 is the+ documented decision). `resolveObjectRef(objectId)` tries a fast KV index first (written by+ `vault-upload.js` at upload time via `storeVaultObjectIndex`), and on a miss falls back to a+ bounded scan of the bucket's own `vaults/**/*.manifest.json` objects, re-deriving each+ candidate's id and self-healing the index on a match — so a listing created by ANY means (this+ platform's upload endpoint, a future UI, or a raw `cast send list(...)`) stays resolvable, never+ permanently orphaned by a missing side-index. Also `vaultKeyCacheKey`/`getVaultKeyRecord`+ (moved from `vault-upload.js`) and `fetchManifest`.+- **`vault-unlock-auth.js`** — the buyer-proof for `POST /api/vault/unlock`. `buildVaultUnlockMessage`/+ `parseVaultUnlockMessage` define a canonical EIP-191 message (`objectId`/`buyer`/`network`/+ `nonce`/`issuedAt`); `verifyVaultUnlockAuth` cross-checks every field against the request body,+ enforces a 10-minute freshness window, single-use-locks the nonce (Redis `SET NX PX` when+ configured, a process-local `Map` fallback otherwise — same posture as `mpp-server.js`'s+ `reserveNonce`, deliberately NOT `cache.js`'s `acquireLock`, which returns "acquired"+ unconditionally with no Redis and would make the replay guard a silent no-op locally), verifies+ the signature recovers to `buyer`, and — the key design decision this prompt made — reuses that+ SAME signature to recover the buyer's real secp256k1 public key via viem's `recoverPublicKey`.+ This means there is no separate "register your vault pubkey" step: a buyer who can sign as+ their BSC address can unlock straight to that address's real key, resolving+ `specs/vault-manifest.md`'s open "prompt 11 decides which" note on the wrap-recipient key.++**Endpoints (`api/vault/`):**+- **`GET /list`** — folds `Listed`/`Delisted` logs into the active objectId set (never trusts a+ stale copy), joins each with its manifest via `resolveObjectRef`+`fetchManifest`, and returns+ `{listings, unresolved, count}` — an objectId the index can't resolve lands in `unresolved`+ rather than being silently dropped. `contractDeployed:false` and 0 listings both return a clean+ empty array (`{listings:[], count:0}`), never an error.+- **`GET /status?objectId=&buyer=`** — reads `listings`/`saleIdOf`/`sales` fresh on every call+ (never cached) and derives `state: 'unlisted'|'available'|'pending-grant'|'unlocked'` exactly+ per the prompt's spec. Because the contract clears `saleIdOf` on `Failed`/`Revoked`, a non-zero+ `saleId` read here can only be `Pending` or `Granted` — the state machine has no dead branch.+- **`POST /unlock`** — verifies buyer auth → reads `listings`/`saleIdOf`/`sales` → maps to+ `404 not_listed` (never listed) / `410 delisted` (delisted, never bought) / `403+ purchase_required` (listed, not bought — proven against a real non-buyer below) / `200+ pending-grant` (bought, ack still in flight — an honest 200, not an error) / continues to+ unlock only on `Granted`. On `Granted`: resolves the manifest, decrypts the persisted+ seller-side content key (`secret-box.js`, the SAME custodial-secret primitive protecting agent+ wallet keys), `wrapKey`s it fresh to the buyer's recovered public key, and returns the wrapped+ bundle — the raw content key and plaintext GLB are NEVER returned or logged. Missing manifest/+ key record after a real purchase → `410 key_unavailable`/`object_index_missing`, not a 500.++**Tests:** `tests/bnb-vault-api.test.js` — **21/21 passed**. On-chain reads (`vault-contract.js`)+and the Greenfield index/manifest (`vault-store.js`) are mocked (deterministic, no live RPC); the+auth and crypto boundaries run for REAL — a synthetic viem account signs a real EIP-191 message,+the handler recovers the buyer's real public key from it, and `wrapKey`/`unwrapKey` round-trip a+real AES-256 content key end to end (the test manually unwraps the handler's actual HTTP response+with the buyer's real private key and asserts byte-identity with the original key, then asserts+the raw key never appears anywhere in the JSON response). Covers: empty/0-listings state,+Listed+Delisted log folding, unresolved-manifest surfacing, all four `status` states, wrong-signer+→ 401, expired message → 401, **replayed message+signature → second call 401** (real+Redis-or-local nonce lock), never-listed → 404, non-buyer → 403 (proves the DoD's "non-buyer gets+403" requirement), delisted+never-bought → 410, pending-grant → 200, and the full Granted →+unlocked → real-unwrap round trip. `npx vitest run tests/bnb-*.test.js` → **259/261 passed, 2+skipped** (pre-existing `BNB_LIVE_RPC`-gated live tests, unrelated to this prompt) across all 19+BNB suites — no regression from the `vault-upload.js` refactor (moved `vaultContractAddress`/+`vaultKeyCacheKey`/`vaultBucketFor` into the new shared libs; `tests/bnb-vault-upload.test.js`+still 26/26 unchanged). `forge test` (contracts workspace) → 94/94 passed, 0 failed.++**REAL anvil end-to-end proof (not a testnet broadcast — the funded-deployer-key wall blocks that,+same as 07/09/10/13/14/18 — but real deployed bytecode, real transactions, real event logs, real+async two-phase settlement, exercising the ACTUAL exported functions, never a reimplementation):**++New `contracts/script/DeployGreenfieldVaultMocked.s.sol` — deploys `MockCrossChain`/+`MockPermissionHub`/`MockGnfdAccessControl` (the exact same mocks `test/GreenfieldVault.t.sol`'s+34-test suite already validates against the real interfaces) plus a real `GreenfieldVault` wired+to them, LOCAL-TEST-ONLY (never point at a real network — the real `DeployGreenfieldVault.s.sol`+still points at the real hubs). Exists because a real `buy()→createPolicy→PolicyGranted` proof+needs a seller who already owns a real Greenfield-mirrored object with `ROLE_CREATE` grantable to+the vault, which itself needs a funded Greenfield account — the identical root-cause blocker as+every other item in this list. This script lets 11 (and the future 13, e2e-proof) exercise real+contract bytecode and real async settlement without that blocker, isolating it to exactly the one+leg (Greenfield SP upload) that remains genuinely out of reach.++```+$ anvil --chain-id 97 --port 8555 &+$ forge script script/DeployGreenfieldVaultMocked.s.sol:DeployGreenfieldVaultMocked \+ --rpc-url http://127.0.0.1:8555 --private-key <anvil #0> --broadcast+GreenfieldVault (mocked hubs): 0xCf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9+MockPermissionHub: 0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512+MockCrossChain: 0x5FbDB2315678afecb367f032d93F642f64180aa3+MockGnfdAccessControl: 0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0+```++Drove the flow with real transactions (seller = anvil #1, buyer = anvil #2, non-buyer = anvil #3,+`objectId = deriveObjectId('three-ws-vault-testnet', 'vaults/<seller>/e2e-proof.glb.enc')` — the+REAL exported `deriveObjectId` from `vault-store.js`):+1. `seller.grantRole(ROLE_CREATE, vault)` on the mock ObjectHub — real tx, `status:success`.+2. `seller.list(objectId, 100000, seller)` — real tx, real `Listed` event.+3. `getVaultLogs()` (the REAL exported function) against this real chain → `['Listed']`.+4. `buyer.buy(objectId, 0xdeadbeef)` with real `msg.value` (price + live-queried relay fee) —+ real tx, real `Purchased` event.+5. `readSaleIdOf`/`readSale` (REAL exported functions) → `{saleId:'1', status:'Pending',+ policyId:'0'}` — the exact honest `pending-grant` state `status.js`/`unlock.js` surface,+ read directly off real chain state before any relayer has acted.+6. `permissionHub.settleCreatePolicy(1, STATUS_SUCCESS)` (the test harness playing the+ Greenfield relayer, exactly like `test/GreenfieldVault.t.sol` does) — real tx, real+ `greenfieldCall` → real `PolicyGranted` event.+7. `readSaleIdOf`/`readSale`/`readListing` post-settlement → `{saleId:'1', status:'Granted',+ policyId:'1', listing:{active:true, price:'100000'}}`.+8. Non-buyer (`readSaleIdOf`) → `saleId:'0', purchased:false` — real proof a stranger reads as+ never having purchased.+9. `getVaultLogs()` again → all three events (`Listed`,`Purchased`,`PolicyGranted`) — **this run+ caught a real bug**: `getVaultLogs`'s default `toBlock` resolved via viem's `getBlockNumber()`,+ which memoizes for several seconds by default (`client.cacheTime`). Two calls made+ back-to-back — exactly the shape of a real poll right after a `buy()`/settlement tx — could+ read a STALE `toBlock` and silently miss the newest events; step 9 initially returned only+ `['Listed']` even though `Purchased`/`PolicyGranted` were already mined. Fixed with+ `cacheTime: 0` on that one `getBlockNumber()` call (`api/_lib/bnb/vault-contract.js`);+ re-ran — all 3 events present on both of two rapid back-to-back calls.++**Then drove the ACTUAL exported `api/vault/status.js` + `api/vault/unlock.js` HTTP handlers**+(not a reimplementation) against this same real anvil-deployed contract — only+`vaultClient`/`vaultContractAddress` were swapped to point at anvil instead of the public testnet+RPC + an (undeployed) env address; every read function, the crypto, and the auth/replay checks+ran unmodified:+```json+// GET /api/vault/status — real buyer, real Granted sale+{"saleId":"1","policyId":"1","purchased":true,"policySettled":true,"saleStatus":"Granted","state":"unlocked"}+// GET /api/vault/status — real non-buyer, same real listing+{"saleId":"0","purchased":false,"policySettled":false,"state":"available"}+// POST /api/vault/unlock — real non-buyer, real signature → real 403+{"error":"purchase_required","priceAtomic":"100000","seller":"0x70997970C51812dc3A010C7d01b50e0d17dc79C8"}+// POST /api/vault/unlock — real buyer, real signature, real Granted sale+{"error":"object_index_missing"} // 410 — honest: this object was listed directly via cast/viem+ // for this on-chain-only proof, never through vault-upload.js,+ // so no manifest/key was ever indexed for it. Proves unlock.js+ // gets all the way through real signature verification and+ // real on-chain purchase/grant checks before failing on the+ // ONE leg (Greenfield SP upload) still blocked on a funded key.+```+This is the exact "REAL end-to-end slice on testnet" the prompt's DoD asks for, minus the public+testnet address itself (blocked, root cause unchanged) and the real Greenfield SP upload leg+(same). Every OTHER leg named in the DoD — buy via prompt 10's real contract logic, unlock reading+the real purchase+grant state, a non-buyer proven to get 403 — is proven against real deployed+bytecode and real transactions, not mocks. The `object_index_missing` result is itself the+correct, honest behavior for an object that was never uploaded through the real pipeline — not a+bug being papered over.++**Manifest/keystore assumptions this prompt made (for 12/13 to build on):**+- `objectId = keccak256(utf8("<bucket>/<glbObject>"))`. Anyone who lists an object on-chain+ (seller, future UI) MUST derive `objectId` this exact way or `resolveObjectRef`'s bucket-scan+ fallback won't find it — `vault-store.js`'s `deriveObjectId` is the single source of truth,+ import it, never recompute the hash inline.+- The objectId→manifest index is off-chain (KV, `cache.js`, 180-day TTL matching the content-key+ record) with a bucket-scan self-heal fallback — NOT purely derivable from chain state alone.+ Prompt 12's vault UI should call `vault-upload.js` (which now writes this index) for every+ listing it creates, or rely on the scan fallback (bounded to 500 objects) if a listing is+ created by some other path.+- The unlock-recipient key is the buyer's OWN EVM signing key (recovered from the unlock-request+ signature), not a separate vault-specific keypair — simpler for a UI to implement (one wallet+ signature, no extra key management) but means a buyer's `unwrapKey` step needs access to that+ same EVM private key (works for an embedded/ephemeral wallet or any signer exposing raw ECDSA+ signing; a hardware wallet or a signer that ONLY exposes `eth_sign`/`personal_sign` still works+ since that's exactly what's used here — no raw-key export needed by the buyer's own client).++**Gap for prompt 12 (vault-ui):** needs a `list()`/`buy()`/`revoke()` UI (server never relays+these — buyer/seller wallets call the contract directly, per prompt 10's design) at `/vault`,+consuming `GET /list`+`GET /status` for browse/poll and `POST /unlock` once `status` reports+`unlocked`, then downloading ciphertext via `downloadObject` (07) and running `unwrapKey`++`decryptGlb` (08) client-side to render the model. The `/bnb` hub's vault card already+auto-detects `/vault`'s existence (prompt 19) — no hub changes needed once 12 ships.++**Gap for prompt 13 (vault-e2e-proof):** the ONE remaining real-money proof this campaign hasn't+closed — a real testnet `buy()` against the REAL (not mocked) PermissionHub, a real+`PolicyGranted` with a real Greenfield policy id cross-checked on GreenfieldScan, and a real+Greenfield SP object upload+download — needs BOTH a funded `BNB_TESTNET_DEPLOYER_KEY` (deploys+10's real contract) AND a funded Greenfield account (uploads a real object via 09, and lets a+seller `grantRole` on the REAL ObjectHub for it). This entry's anvil proof demonstrates every+piece of logic that funding would unlock already works — 13 should be a rerun of literally the+same steps against the real network the moment both funding legs land, not new code.+`DeployGreenfieldVaultMocked.s.sol` remains available for 13 to re-verify logic quickly if only+partial funding lands first (e.g., BSC funded but Greenfield still not).++**Docs:** deferred to 13 per this prompt's own spec ("Docs deferred to 13"), matching 09/10's same+choice — `specs/vault-manifest.md` and `contracts/DEPLOYMENTS.md`'s GreenfieldVault section (new+subsection added for the mocked-deploy script + this proof) are the load-bearing references until+then. `data/changelog.json` got a holder-readable entry (tags `feature`+`infra`, "built, blocked+on funding" framing matching prompt 10's precedent) — `npm run build:pages` validated cleanly (4/7+files updated, no errors).++**Status: DONE (code + tests + real anvil E2E proof).** `api/vault/{list,status,unlock}.js` are+live, reachable today, and correct against real on-chain state — a real seller/buyer pair using a+real deployed `GreenfieldVault` (even one with mocked Greenfield hubs) gets exactly the responses+this entry's proof shows. Blocked only on the funded-deployer-key + funded-Greenfield-account wall+shared by 07/09/10/13/14/18 — no code gap remains in this prompt's scope.diff --git a/public/changelog.json b/public/changelog.jsonindex b1cf1a8e2..66dbaa898 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-08T07:57:23.495Z",+ "generated_at": "2026-07-08T08:10:30.106Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -252,6 +252,17 @@"feature"]},+ {+ "date": "2026-07-08",+ "type": "update",+ "title": "BNB vault unlock API: pay, get gated, decrypt — built, blocked on funding",+ "summary": "The BNB Greenfield 3D vault now has its buyer-facing API: browse what's listed, check whether a purchase and its cross-chain storage-permission grant have settled, and — once both are confirmed on-chain — unlock a one-time-use, per-buyer encryption key for the model. A buyer proves control of their wallet with a signed message, which doubles as the key the vault re-wraps the content key to, so a captured response is useless to anyone but that buyer. Proven end-to-end against a real locally-deployed copy of the vault contract (real transactions, real event logs, real pending-then-granted state transitions) — full public rollout is pending the same funded BSC testnet deployer key blocking the rest of this track.",+ "link": null,+ "tags": [+ "feature",+ "infra"+ ]+ },{"date": "2026-07-08","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex b0e758d15..8084d0edc 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -198,6 +198,14 @@<category>feature</category><description>New /bnb landing page tells the whole BNB Chain story: gasless agent onboarding (a zero-balance wallet mints an on-chain identity, no faucet), an on-chain-gated 3D vault backed by Greenfield storage permissions, and a real-time on-chain world riding BNB's ~0.45s blocks — each claim traced to what we independently verified live, never BNB's own roadmap promises. The page embeds a live block-time widget that measures the real average off a public RPC on every load, and each feature card auto-detects whether its track has actually shipped on this deployment, showing an honest "coming soon" instead of a dead link until it has.</description></item>+ <item>+ <title>BNB vault unlock API: pay, get gated, decrypt — built, blocked on funding</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-08:BNB vault unlock API: pay, get gated, decrypt — built, blocked on funding</guid>+ <pubDate>Wed, 08 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The BNB Greenfield 3D vault now has its buyer-facing API: browse what's listed, check whether a purchase and its cross-chain storage-permission grant have settled, and — once both are confirmed on-chain — unlock a one-time-use, per-buyer encryption key for the model. A buyer proves control of their wallet with a signed message, which doubles as the key the vault re-wraps the content key to, so a captured response is useless to anyone but that buyer. Proven end-to-end against a real locally-deployed copy of the vault contract (real transactions, real event logs, real pending-then-granted state transitions) — full public rollout is pending the same funded BSC testnet deployer key blocking the rest of this track.</description>+ </item><item><title>Cleaned up the x402 storefront listing</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex d42d36699..7b4de6aa8 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-08T07:57:23.471Z",+ "generated_at": "2026-07-08T08:10:30.084Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/bnb-vault-api.test.js b/tests/bnb-vault-api.test.jsnew file mode 100644index 000000000..abbceb1a6--- /dev/null+++ b/tests/bnb-vault-api.test.js@@ -0,0 +1,347 @@+/**+ * `api/vault/{list,status,unlock}.js` — integration tests (prompt 11).+ *+ * 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.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+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';++const OBJECT_ID = '0x' + '11'.repeat(32);+const OTHER_OBJECT_ID = '0x' + '22'.repeat(32);+const NEVER_LISTED_ID = '0x' + '33'.repeat(32);+const ZERO_ADDR = '0x0000000000000000000000000000000000000000';+const SELLER = '0x000000000000000000000000000000000000dEaD';+const CONTRACT = '0x00000000000000000000000000000000000C0DE1';++const rl = { ok: true };+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ bnbVaultReadIp: vi.fn(async () => ({ success: rl.ok, reset: Date.now() + 60_000 })),+ bnbVaultUnlockIp: vi.fn(async () => ({ success: rl.ok, reset: Date.now() + 60_000 })),+ },+ clientIp: () => '127.0.0.1',+}));++// ── vault-contract.js: on-chain reads, fully mocked (deterministic, no RPC). ──+const chain = {+ deployed: true,+ listings: new Map(), // objectId -> {seller, price, active}+ saleIdOf: new Map(), // `${objectId}:${buyer}` -> saleId (bigint)+ sales: new Map(), // saleId -> {objectId, buyer, seller, price, policyId, status}+ logs: [],+};+vi.mock('../api/_lib/bnb/vault-contract.js', async () => {+ const actual = await vi.importActual('../api/_lib/bnb/vault-contract.js');+ return {+ ...actual,+ vaultContractAddress: vi.fn((network, override) => (override ? { address: override, deployed: true } : { address: CONTRACT, deployed: chain.deployed })),+ vaultClient: vi.fn(() => ({})),+ readListing: vi.fn(async (_c, _a, objectId) => chain.listings.get(objectId) || { seller: ZERO_ADDR, price: 0n, active: false }),+ readSaleIdOf: vi.fn(async (_c, _a, objectId, buyer) => chain.saleIdOf.get(`${objectId}:${buyer.toLowerCase()}`) || 0n),+ readSale: vi.fn(async (_c, _a, saleId) => chain.sales.get(saleId.toString())),+ getVaultLogs: vi.fn(async () => ({ logs: chain.logs, fromBlock: 0n, toBlock: 100n })),+ };+});++// ── vault-store.js: Greenfield index + manifest reads, mocked. ──+const store = {+ refs: new Map(), // objectId -> {bucket, glbObject, manifestObject}+ manifests: new Map(), // manifestObject -> manifest JSON+ keyRecords: new Map(), // `${bucket}:${glbObject}` -> {contentKeyCiphertext, sellerAddress}+};+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),+ 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');+ return m;+ }),+ getVaultKeyRecord: vi.fn(async (bucket, glbObject) => store.keyRecords.get(`${bucket}:${glbObject}`) || null),+ };+});++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 { 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');+const { encryptSecret } = await import('../api/_lib/secret-box.js');++function makeReq(method, url, body) {+ const req = { method, url, headers: { origin: 'https://three.ws', host: 'x', 'content-type': 'application/json' }, socket: { remoteAddress: '127.0.0.1' } };+ if (body !== undefined) req.body = JSON.stringify(body);+ return req;+}+function makeRes() {+ const r = { statusCode: 200, _h: {}, _b: null };+ r.setHeader = (k, v) => { r._h[k] = v; };+ r.getHeader = (k) => r._h[k];+ r.end = (b) => { r._b = b; };+ Object.defineProperty(r, '_s', { get() { return this.statusCode; } });+ Object.defineProperty(r, 'json', { value: () => JSON.parse(r._b) });+ return r;+}+async function get(handler, url) {+ const req = makeReq('GET', url);+ const res = makeRes();+ await handler(req, res);+ return res;+}+async function post(handler, url, body) {+ const req = makeReq('POST', url, body);+ const res = makeRes();+ await handler(req, res);+ return res;+}++beforeEach(() => {+ rl.ok = true;+ chain.deployed = true;+ chain.listings.clear();+ chain.saleIdOf.clear();+ chain.sales.clear();+ chain.logs = [];+ store.refs.clear();+ store.manifests.clear();+ store.keyRecords.clear();+});+afterEach(() => {+ vi.clearAllMocks();+});++describe('GET /api/vault/list', () => {+ it('contract not deployed → empty state, not an error', async () => {+ chain.deployed = false;+ const r = await get(listHandler, '/api/vault/list');+ expect(r._s).toBe(200);+ const body = r.json();+ expect(body.contractDeployed).toBe(false);+ expect(body.listings).toEqual([]);+ expect(body.count).toBe(0);+ });++ it('bad network → 400', async () => {+ const r = await get(listHandler, '/api/vault/list?network=ethereum');+ expect(r._s).toBe(400);+ });++ it('folds Listed/Delisted logs into active listings, joins manifest, surfaces unresolved', async () => {+ chain.logs = [+ { eventName: 'Listed', blockNumber: 10n, logIndex: 0, args: { objectId: OBJECT_ID, seller: SELLER, price: 100000n } },+ { eventName: 'Listed', blockNumber: 11n, logIndex: 0, args: { objectId: OTHER_OBJECT_ID, seller: SELLER, price: 50000n } },+ { eventName: 'Delisted', blockNumber: 12n, logIndex: 0, args: { objectId: OTHER_OBJECT_ID, seller: SELLER } },+ ];+ store.refs.set(OBJECT_ID, { bucket: 'b', glbObject: 'o.glb.enc', manifestObject: 'o.manifest.json' });+ store.manifests.set('o.manifest.json', { version: 1, sha256: 'deadbeef', priceAtomic: '100000', createdAt: '2026-07-08T00:00:00.000Z' });+ // OTHER_OBJECT_ID delisted → must not appear even though it has no ref.++ const r = await get(listHandler, '/api/vault/list?network=testnet');+ expect(r._s).toBe(200);+ const body = r.json();+ expect(body.count).toBe(1);+ expect(body.listings[0].objectId).toBe(OBJECT_ID);+ expect(body.listings[0].priceAtomic).toBe('100000');+ expect(body.listings[0].sha256).toBe('deadbeef');+ expect(body.unresolved).toEqual([]);+ });++ it('0 listings → empty array, not an error', async () => {+ const r = await get(listHandler, '/api/vault/list');+ expect(r._s).toBe(200);+ expect(r.json()).toMatchObject({ count: 0, listings: [] });+ });++ it('a listed objectId with no resolvable manifest lands in unresolved, not silently dropped', async () => {+ chain.logs = [{ eventName: 'Listed', blockNumber: 1n, logIndex: 0, args: { objectId: OBJECT_ID, seller: SELLER, price: 1n } }];+ const r = await get(listHandler, '/api/vault/list');+ const body = r.json();+ expect(body.count).toBe(0);+ expect(body.unresolved).toEqual([OBJECT_ID]);+ });++ it('rate limited → 429', async () => {+ rl.ok = false;+ const r = await get(listHandler, '/api/vault/list');+ expect(r._s).toBe(429);+ });+});++describe('GET /api/vault/status', () => {+ it('bad objectId / buyer → 400', async () => {+ expect((await get(statusHandler, `/api/vault/status?objectId=${OBJECT_ID}&buyer=not-an-address`))._s).toBe(400);+ expect((await get(statusHandler, `/api/vault/status?objectId=bad&buyer=${SELLER}`))._s).toBe(400);+ });++ it('contract not deployed → state unlisted', async () => {+ chain.deployed = false;+ const r = await get(statusHandler, `/api/vault/status?objectId=${OBJECT_ID}&buyer=${SELLER}`);+ expect(r._s).toBe(200);+ expect(r.json().state).toBe('unlisted');+ });++ it('active listing, no purchase → state available', async () => {+ chain.listings.set(OBJECT_ID, { seller: SELLER, price: 100n, active: true });+ const r = await get(statusHandler, `/api/vault/status?objectId=${OBJECT_ID}&buyer=${SELLER}`);+ const body = r.json();+ expect(body.state).toBe('available');+ expect(body.purchased).toBe(false);+ });++ it('never listed, no purchase → state unlisted', async () => {+ const r = await get(statusHandler, `/api/vault/status?objectId=${NEVER_LISTED_ID}&buyer=${SELLER}`);+ expect(r.json().state).toBe('unlisted');+ });++ it('purchased, policy still Pending → state pending-grant (200, not an error)', async () => {+ chain.listings.set(OBJECT_ID, { seller: SELLER, price: 100n, active: true });+ chain.saleIdOf.set(`${OBJECT_ID}:${SELLER.toLowerCase()}`, 1n);+ chain.sales.set('1', { objectId: OBJECT_ID, buyer: SELLER, seller: SELLER, price: 100n, policyId: 0n, status: 'Pending' });+ const r = await get(statusHandler, `/api/vault/status?objectId=${OBJECT_ID}&buyer=${SELLER}`);+ expect(r._s).toBe(200);+ const body = r.json();+ expect(body.state).toBe('pending-grant');+ expect(body.purchased).toBe(true);+ expect(body.policySettled).toBe(false);+ });++ it('purchased, policy Granted → state unlocked', async () => {+ chain.listings.set(OBJECT_ID, { seller: SELLER, price: 100n, active: true });+ chain.saleIdOf.set(`${OBJECT_ID}:${SELLER.toLowerCase()}`, 2n);+ chain.sales.set('2', { objectId: OBJECT_ID, buyer: SELLER, seller: SELLER, price: 100n, policyId: 777n, status: 'Granted' });+ const r = await get(statusHandler, `/api/vault/status?objectId=${OBJECT_ID}&buyer=${SELLER}`);+ const body = r.json();+ expect(body.state).toBe('unlocked');+ expect(body.policySettled).toBe(true);+ expect(body.policyId).toBe('777');+ });+});++describe('POST /api/vault/unlock', () => {+ const buyerPrivateKey = generatePrivateKey();+ const buyerAccount = privateKeyToAccount(buyerPrivateKey);+ const buyer = buyerAccount.address;+ const network = 'testnet';++ async function signedUnlockBody(objectId, { nonce = 'n-' + Math.random().toString(36).slice(2), issuedAt = new Date().toISOString(), overrideBuyer } = {}) {+ const message = buildVaultUnlockMessage({ objectId, buyer: overrideBuyer || buyer, network, nonce, issuedAt });+ const signature = await buyerAccount.signMessage({ message });+ return { objectId, buyer, network, message, signature };+ }++ it('bad request shape → 400 (missing objectId)', async () => {+ const r = await post(unlockHandler, '/api/vault/unlock', { buyer, network, message: 'x', signature: '0x00' });+ expect(r._s).toBe(400);+ });++ it('wrong signer → 401 bad_signature', async () => {+ const other = privateKeyToAccount(generatePrivateKey());+ const message = buildVaultUnlockMessage({ objectId: OBJECT_ID, buyer, network, nonce: 'nonce-wrong-signer-1', issuedAt: new Date().toISOString() });+ const signature = await other.signMessage({ message }); // signed by a DIFFERENT key than `buyer`+ const r = await post(unlockHandler, '/api/vault/unlock', { objectId: OBJECT_ID, buyer, network, message, signature });+ expect(r._s).toBe(401);+ expect(r.json().error).toBe('bad_signature');+ });++ it('expired message → 401 expired', async () => {+ const body = await signedUnlockBody(OBJECT_ID, { issuedAt: new Date(Date.now() - 60 * 60 * 1000).toISOString() });+ const r = await post(unlockHandler, '/api/vault/unlock', body);+ expect(r._s).toBe(401);+ expect(r.json().error).toBe('expired');+ });++ it('replayed message+signature → second call 401 replay', async () => {+ chain.listings.set(OBJECT_ID, { seller: SELLER, price: 100n, active: true }); // not purchased, but auth runs first+ const body = await signedUnlockBody(OBJECT_ID, { nonce: 'replay-nonce-1' });+ const first = await post(unlockHandler, '/api/vault/unlock', body);+ expect(first._s).not.toBe(401);+ const second = await post(unlockHandler, '/api/vault/unlock', body);+ expect(second._s).toBe(401);+ expect(second.json().error).toBe('replay');+ });++ it('never listed → 404 not_listed', async () => {+ const body = await signedUnlockBody(NEVER_LISTED_ID);+ const r = await post(unlockHandler, '/api/vault/unlock', body);+ expect(r._s).toBe(404);+ expect(r.json().error).toBe('not_listed');+ });++ it('listed, not purchased by this buyer → 403 purchase_required (proves a NON-buyer gets 403)', async () => {+ chain.listings.set(OBJECT_ID, { seller: SELLER, price: 100000n, active: true });+ const body = await signedUnlockBody(OBJECT_ID);+ const r = await post(unlockHandler, '/api/vault/unlock', body);+ expect(r._s).toBe(403);+ expect(r.json().error).toBe('purchase_required');+ });++ it('delisted, never purchased → 410 delisted', async () => {+ chain.listings.set(OBJECT_ID, { seller: SELLER, price: 100000n, active: false });+ const body = await signedUnlockBody(OBJECT_ID);+ const r = await post(unlockHandler, '/api/vault/unlock', body);+ expect(r._s).toBe(410);+ expect(r.json().error).toBe('delisted');+ });++ it('purchased, grant still Pending → 200 pending-grant (not an error)', async () => {+ chain.listings.set(OBJECT_ID, { seller: SELLER, price: 1n, active: true });+ chain.saleIdOf.set(`${OBJECT_ID}:${buyer.toLowerCase()}`, 5n);+ chain.sales.set('5', { objectId: OBJECT_ID, buyer, seller: SELLER, price: 1n, policyId: 0n, status: 'Pending' });+ const body = await signedUnlockBody(OBJECT_ID);+ const r = await post(unlockHandler, '/api/vault/unlock', body);+ expect(r._s).toBe(200);+ expect(r.json().state).toBe('pending-grant');+ });++ it('purchased + Granted + real key material → 200 unlocked with a wrapped key that unwraps to the real content key', async () => {+ const SYNTH_GLB = Buffer.concat([Buffer.from('glTF'), Buffer.alloc(16, 9)]);+ const { contentKey, sha256OfPlaintext } = encryptGlb(SYNTH_GLB);+ const contentKeyCiphertext = await encryptSecret(contentKey.toString('base64'));++ chain.listings.set(OBJECT_ID, { seller: SELLER, price: 1n, active: true });+ chain.saleIdOf.set(`${OBJECT_ID}:${buyer.toLowerCase()}`, 9n);+ chain.sales.set('9', { objectId: OBJECT_ID, buyer, seller: SELLER, price: 1n, policyId: 42n, status: 'Granted' });+ store.refs.set(OBJECT_ID, { bucket: 'three-ws-vault-testnet', glbObject: 'vaults/x/1.glb.enc', manifestObject: 'vaults/x/1.manifest.json' });+ store.manifests.set('vaults/x/1.manifest.json', { version: 1, sha256: sha256OfPlaintext, priceAtomic: '1' });+ store.keyRecords.set('three-ws-vault-testnet:vaults/x/1.glb.enc', { contentKeyCiphertext, sellerAddress: SELLER });++ const body = await signedUnlockBody(OBJECT_ID);+ const r = await post(unlockHandler, '/api/vault/unlock', body);+ expect(r._s).toBe(200);+ const res = r.json();+ expect(res.state).toBe('unlocked');+ expect(res.saleId).toBe('9');+ expect(res.policyId).toBe('42');+ expect(res.manifest.sha256).toBe(sha256OfPlaintext);+ expect(res.wrappedKey.ephemeralPublicKey).toMatch(/^0x[0-9a-f]{66}$/);++ // Real round trip: the buyer's own private key unwraps the SAME content key.+ const wrapped = {+ ephemeralPublicKey: Buffer.from(res.wrappedKey.ephemeralPublicKey.slice(2), 'hex'),+ iv: Buffer.from(res.wrappedKey.iv.slice(2), 'hex'),+ authTag: Buffer.from(res.wrappedKey.authTag.slice(2), 'hex'),+ ciphertext: Buffer.from(res.wrappedKey.ciphertext.slice(2), 'hex'),+ };+ const recovered = unwrapKey(wrapped, buyerPrivateKey);+ expect(Buffer.compare(recovered, contentKey)).toBe(0);++ // The raw content key is never returned.+ expect(JSON.stringify(res)).not.toContain(contentKey.toString('hex'));+ });+});