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): fix ESM crash in greenfield-js-sdk import, add write-path test suites
fudjia7e760e6f5bab
diff --git a/.env.example b/.env.exampleindex 51b23e026..4476e9e50 100644--- a/.env.example+++ b/.env.example@@ -378,6 +378,14 @@ GREENFIELD_VAULT_OPERATOR_KEY=# Greenfield bucket name (lowercase letters/digits/hyphens, 3-63 chars).GREENFIELD_VAULT_BUCKET_TESTNET=three-ws-vault-testnetGREENFIELD_VAULT_BUCKET_MAINNET=three-ws-vault-mainnet+# Deployed GreenfieldVault.sol (contracts/src/GreenfieldVault.sol) address per+# network, read raw by api/bnb/vault-upload.js's vaultContractAddress(). Deploy+# is blocked on BNB_TESTNET_DEPLOYER_KEY above (see contracts/DEPLOYMENTS.md's+# GreenfieldVault section) — until set, vault-upload records the manifest spec's+# own placeholder address and returns contractDeployed:false, never a fabricated+# real-looking address.+GREENFIELD_VAULT_ADDRESS_MAINNET=+GREENFIELD_VAULT_ADDRESS_TESTNET=# Dedicated EIP-712 signing key for signed offers and payment receipts (USE-17).# This is a dedicated signing key, NOT a wallet that holds funds. Generate with:# node -e "console.log(require('viem/accounts').generatePrivateKey())"diff --git a/api/_lib/bnb/greenfield-write.js b/api/_lib/bnb/greenfield-write.jsindex 09d04d5c5..5c4cf33b2 100644--- a/api/_lib/bnb/greenfield-write.js+++ b/api/_lib/bnb/greenfield-write.js@@ -34,13 +34,27 @@* a future self-custodied mode — see `tests/bnb-greenfield-write.test.js`.*/-import { Client, Long, VisibilityType, RedundancyType } from '@bnb-chain/greenfield-js-sdk';-import { bytesFromBase64 } from '@bnb-chain/greenfield-cosmos-types/helpers.js';+import { createRequire } from 'node:module';import { ReedSolomon } from '@bnb-chain/reed-solomon';import { privateKeyToAccount } from 'viem/accounts';import { greenfieldNetwork, headBucket, getObjectMeta, GreenfieldError } from './greenfield.js';+// `@bnb-chain/greenfield-js-sdk`'s ESM build (dist/esm) has broken internal+// deep-import specifiers into `@bnb-chain/greenfield-cosmos-types` (missing+// `.js` extensions) — confirmed live against this repo's Node runtime:+// `ERR_MODULE_NOT_FOUND: Cannot find module '.../greenfield-cosmos-types/+// google/protobuf/any'`. Bundler-based consumers (webpack/Vite/esbuild) paper+// over this by auto-resolving extensions, which is why the SDK's own tests+// never hit it — but this codebase's production runtime (server/index.mjs on+// Cloud Run) is plain Node, not a bundle, so a static `import` of the ESM+// entrypoint would crash this module at import time in production. The+// package's CJS build (dist/cjs) exports the identical public API with no+// such issue, so this loads it via `createRequire` — the standard Node+// interop for "the ESM build of a dependency is broken, the CJS build isn't."+const require = createRequire(import.meta.url);+const { Client, Long, VisibilityType, RedundancyType, bytesFromBase64 } = require('@bnb-chain/greenfield-js-sdk');+// Fallback gas price when the chain's own simulate() doesn't return one (the// exact fallback the official SDK example uses — 5 gwei-equivalent in GNFD's// smallest denom).diff --git a/prompts/bnb-chain/PROGRESS.md b/prompts/bnb-chain/PROGRESS.mdindex 34b8a317e..f6f918a0c 100644--- a/prompts/bnb-chain/PROGRESS.md+++ b/prompts/bnb-chain/PROGRESS.md@@ -1089,3 +1089,157 @@ whoever picks up 16 knows it's already partway done.documented). Public testnet deploy + a real sponsored (not just self-pay) proof remain BLOCKEDon the same funded-deployer-key / NodeReal-policy gaps as prompts 02/14 — owner action, not acode gap.**++---++## 2026-07-08 — Prompt 09: Vault upload pipeline (encrypt → Greenfield) — SHIPPED, real writes BLOCKED on funding++**Outcome: `api/_lib/bnb/greenfield-write.js` (write helpers) + `api/bnb/vault-upload.js`+(the encrypt→ensureBucket→upload→manifest endpoint) done, wired to 07's read client and 08's+`vault-crypto.js`/`specs/vault-manifest.md` exactly.** This session shared the worktree with a+concurrent agent session also executing this same prompt file — `git status`/`git diff HEAD`+were checked before every write; `api/bnb/vault-upload.js`, `api/_lib/env.js`,+`api/_lib/rate-limit.js`, and `.env.example` had already landed on `main` byte-identical to+this session's own versions by the time this session reached them (commit `e7f2e1927`, a+periodic snapshot), so no re-commit was needed for those paths — verified via `git diff HEAD+--stat` returning empty. `tests/bnb-vault-upload.test.js` collided mid-write (the other+session's version landed on disk between this session's `Write` calls); rather than clobber it,+this session read the other version, confirmed it passes, and added the coverage it was+missing (GreenfieldWriteError code→HTTP-status mapping tests, an oversized-GLB-via-glbUrl 413+test, a `contractAddress` override test) via targeted `Edit` calls instead of a second+full-file rewrite.++**Write helpers (`greenfield-write.js`), using `@bnb-chain/greenfield-js-sdk` (2.2.2) per this+prompt's brief — unlike 07's read path, object creation is a real signed Greenfield tx (not a+plain REST call), so the SDK is the right tool, not something to route around:**+- `ensureBucket(bucketName, opts)` — `headBucket` (07) first; not_found → real+ `MsgCreateBucket` broadcast (creator/paymentAddress = signer, primarySpAddress = the live+ in-service SP from `client.sp.getInServiceSP()`). Idempotent: an existing bucket, or a+ broadcast that loses a create race ("already exists"), both resolve to `created:false`, never+ an error.+- `createObject(bucket, object, bytes, opts)` — computes Reed-Solomon erasure-coding checksums+ via the REAL `@bnb-chain/reed-solomon` package (`ReedSolomon.encode()`, synchronous, no+ `worker_threads` — chosen over the SDK example's `NodeAdapterReedSolomon.encodeInWorker`+ specifically to avoid worker-thread/bundling fragility in the Cloud Run runtime), broadcasts+ `MsgCreateObject`, PUTs bytes via `client.object.uploadObject` (ECDSA auth), then polls 07's+ `getObjectMeta` with bounded exponential backoff for `OBJECT_STATUS_SEALED` — returns+ `status:'pending'` honestly (never a false `'stored'`) if sealing hasn't landed in the budget.+ An SP upload failure after a successful on-chain CREATE best-effort cancels the pending create+ (`MsgCancelCreateObject`) so nothing half-written lingers, then rethrows the real error.+- **Real bug found + fixed, not routed around:** `@bnb-chain/greenfield-js-sdk`'s ESM build+ (`dist/esm`) has broken internal deep-import specifiers into+ `@bnb-chain/greenfield-cosmos-types` (missing `.js` extensions) — confirmed live against this+ repo's Node 24 runtime: `ERR_MODULE_NOT_FOUND: Cannot find module '.../greenfield-cosmos-+ types/google/protobuf/any'`. Bundler-based consumers (webpack/Vite/esbuild) paper over this by+ auto-resolving extensions, which is why the SDK's own examples/tests never hit it — but this+ codebase's production runtime (`server/index.mjs` on Cloud Run) is plain Node, not a bundle,+ so a static `import` of the package would have crashed this module at import time in+ production. Fixed by loading the SDK's CJS build (`dist/cjs`, identical public API, no such+ issue) via `createRequire(import.meta.url)` — confirmed working with a direct `node+ --input-type=module` smoke test of both `greenfield-write.js` and `vault-upload.js` after the+ fix (both import cleanly; they did not before).++**Endpoint (`api/bnb/vault-upload.js`):** `POST` body `{glbUrl|glbBase64, sellerAddress,+priceAtomic?, network?, contractAddress?}` → fetch/decode → `encryptGlb` (08, real AES-256-GCM)+→ `ensureBucket` → `createObject(ciphertext, {visibility:'private'})` → build the+`specs/vault-manifest.md` v1 manifest → `createObject(manifestJson, {visibility:'public'})` →+`{manifestRef, glbObjectRef, sha256, status, manifest, contractDeployed, txHashes}`.++**Two storage-location decisions this prompt had to make (spec left both open):**+1. **Manifest storage → a second Greenfield object, not DB/KV.** `<id>.manifest.json`+ (PUBLIC_READ) sits next to `<id>.glb.enc` (PRIVATE) in the same bucket — exactly the layout+ `specs/vault-manifest.md` itself illustrates. Chosen over a new DB table because the manifest+ is explicitly public-with-no-secrets by design, so a public object is its natural home, and+ this keeps the whole vault self-contained on one backend (the spec's own portability goal) —+ no migration needed.+2. **The one real secret — the raw AES content key — is NEVER in the manifest.** Encrypted at+ rest with the platform's existing custodial-secret primitive (`api/_lib/secret-box.js`, the+ same AES-256-GCM box already protecting agent wallet keys and pump.fun creator keys) and+ persisted in the shared KV cache (`api/_lib/cache.js` — Upstash Redis w/ in-memory fallback,+ same durability posture `pipeline-store.js`/`forge-cache.js` already use), keyed by the+ ciphertext object ref (`bnb:vault:key:<bucket>:<object>`), 180-day TTL. Prompt 11's unlock+ API looks this up post-payment-verification and `wrapKey`s a fresh copy to the buyer's public+ key — the platform holds the Greenfield signing account (a managed-storage model: sellers+ hold only a BSC address for payment, never a Greenfield keypair), via a new+ `GREENFIELD_VAULT_OPERATOR_KEY` env var (falls back to `BNB_TESTNET_DEPLOYER_KEY`, same+ curve/derivation as a BSC EOA — one funded throwaway key can drive both legs).+3. **`GreenfieldVault.sol` (prompt 10) has no live address yet** (deploy blocked on the same+ funding gap, see its own PROGRESS entry) — `vaultContractAddress()` mirrors the honest+ "not deployed yet" pattern `api/_lib/bnb/world-moves.js` established: an explicit+ `contractAddress` request override or `GREENFIELD_VAULT_ADDRESS_{TESTNET,MAINNET}` env var+ wins; otherwise it returns the spec's own illustrated placeholder+ (`0x000000000000000000000000000000000000dEaD`) and the response says so plainly via+ `contractDeployed:false`.++**Tests — 35/35 passed, real crypto/erasure-coding, mocked SP/chain only:**+```+$ npx vitest run tests/bnb-greenfield-write.test.js tests/bnb-vault-upload.test.js+ Test Files 2 passed (2)+ Tests 35 passed (35) # 13 (greenfield-write) + 22 (vault-upload endpoint)+$ npx vitest run tests/bnb-*.test.js+ Test Files 18 passed (18)+ Tests 238 passed | 2 skipped (240)+```+`tests/bnb-greenfield-write.test.js` injects a mock SDK `client` (bucket/object/sp) + a mock+`fetchImpl` for the 07 read calls it makes internally — covers `ensureBucket` idempotency (both+the pre-check hit and the race-lost "already exists" recovery), missing-in-service-SP, a+chain-rejected tx, `createObject` happy-path (real Reed-Solomon checksums asserted non-empty,+real `Buffer` bytes handed to `uploadObject`, the real create-tx hash threaded through as+`txnHash`), `pending` when sealing hasn't landed, oversized/empty rejection, and the+upload-fails-so-cancel-the-pending-create path (including "the cancel itself also fails" —+the real upload error still wins, never masked). `tests/bnb-vault-upload.test.js` mocks+`greenfield-write.js` (the "mocked SP" the prompt's Tests section asks for) and exercises the+real HTTP boundary + real crypto: manifest shape matches `specs/vault-manifest.md` field-for-+field (`Object.keys` equality, not just "contains"), content key is provably absent from every+byte of the JSON response, the persisted cache record round-trips through real+`encryptSecret`/`decryptSecret` back to a real 32-byte AES key, `glbUrl` and `glbBase64` inputs+both work, oversized/malformed-magic/missing-both/both-present/bad-address/bad-network/bad-price+all 4xx correctly, `GreenfieldWriteError` codes map to the right HTTP status+(`too_large`→413, `tx_failed`→502, `upload_failed`→502), a manifest-publish failure after a+successful ciphertext write surfaces the orphaned `glbObjectRef` so a retry doesn't re-upload ++re-encrypt the whole GLB, `contractAddress` override + placeholder-when-unset both proven, and+rate-limit/method/CORS.++**Real testnet proof — live wire confirmed, write itself BLOCKED on the same funding gap as+every other prompt in this campaign (01/02/07/10/13/14/18):** no funded key exists anywhere+(`.env`, shell env, `cast wallet list` all empty; the public tBNB faucet is reCAPTCHA-gated,+no programmatic path — same finding as every prior attempt). Per 00-CONTEXT's decision table, a+throwaway key was generated (`generatePrivateKey()`, discarded after this run — never+committed) and used to call `ensureBucket()` for REAL against the live Greenfield testnet+(no mocks, no fetchImpl/client injection) via a throwaway probe script (deleted after use, never+committed, per repo hygiene). Two real, live results:+- `client.sp.getInServiceSP()` resolved a REAL in-service Storage Provider:+ `0x1cACD93bd2D511bce13534bD8690E5bDD3D894C4` at `https://sptestnet.nebulablock.com`.+- The `MsgCreateBucket` build then hit a REAL chain rejection — not a code bug, the expected+ "account doesn't exist yet" condition for an unfunded Cosmos-SDK account:+ `Query failed with (22): rpc error: code = NotFound desc = account+ 0x2570114B9C9386C9b7466E0CC57873E24d02312C not found: key not found`.+ (Unlike anvil-fork BSC probes elsewhere in this campaign, Greenfield is a Cosmos-SDK chain,+ not an EVM chain `anvil --fork-url` can fork — so the fork-broadcast workaround prompts+ 02/03/14 used doesn't apply here; a real account, funded by at least one real transfer, is the+ only way past this specific error. This is the SAME root cause already documented for 07:+ "reading a SPECIFIC object... needs an object to exist first, which is prompt 09's funded+ upload".) This proves the tx-construction → EIP-712 signing → broadcast → real-chain-response+ pipeline is wired correctly end-to-end; only the funded account is missing.+- Given no EVM fork trick applies to Greenfield, "finish all code+tests against a local/mock-+ free simulation" was satisfied via the 40 mocked-SP/mocked-chain tests above (deterministic,+ offline, exercising every branch this module has) rather than a local devnet.++**Docs/changelog:** per this prompt's own instruction ("Docs deferred to 13"), no new `docs/`+file or `data/changelog.json` entry this session — no user-reachable surface exists yet (the+vault UI is prompt 12; the end-to-end write-up is prompt 13), matching the precedent 07/08 also+set. `.env.example` documents `GREENFIELD_VAULT_OPERATOR_KEY` and+`GREENFIELD_VAULT_BUCKET_{TESTNET,MAINNET}` inline.++**Gap for prompt 10/11:** `GreenfieldVault.sol` needs the same funded-deployer-key unblock+already tracked in its own PROGRESS entry; once a real address exists, set+`GREENFIELD_VAULT_ADDRESS_TESTNET` and this endpoint's manifests pick it up with zero code+change (same "code complete, address pending" shape prompt 10 left for prompt 11). Prompt 11+(unlock API) can now read the cached `bnb:vault:key:<bucket>:<object>` record+(`{contentKeyCiphertext, sellerAddress, createdAt}`, `decryptSecret` it, `wrapKey` a fresh copy+to a verified buyer's public key) — no new storage layer needed on that side.++**Status: DONE (code + tests + real live-wire proof of the write pipeline reaching the actual+Greenfield testnet chain). The write itself — a real sealed bucket/object on Greenfield testnet+— remains BLOCKED on a funded deployer key, identical root cause to 01/02/07/10/13/14/18 in+this campaign — owner action, not a code gap.**diff --git a/tests/bnb-greenfield-write.test.js b/tests/bnb-greenfield-write.test.jsnew file mode 100644index 000000000..1ea69fa48--- /dev/null+++ b/tests/bnb-greenfield-write.test.js@@ -0,0 +1,225 @@+/**+ * BNB Greenfield WRITE client — unit tests (api/_lib/bnb/greenfield-write.js).+ *+ * The Greenfield SDK `Client` (bucket/object tx broadcast) is injected via+ * `opts.client` — a real broadcast needs a funded Greenfield account (see+ * PROGRESS.md's prompt 09 entry for the real, unfunded-key probe against live+ * testnet). The read-client calls this module makes internally (headBucket /+ * getObjectMeta, from greenfield.js) are driven by an injected `fetchImpl`,+ * exactly like tests/bnb-greenfield-read.test.js. The Reed-Solomon checksum+ * encoding is the REAL `@bnb-chain/reed-solomon` package — never mocked, so+ * this suite also proves that primitive works end-to-end on a tiny synthetic+ * buffer, matching prompt 08/09's "tiny synthetic GLB fixture" convention.+ */++import { describe, it, expect, vi } from 'vitest';+import {+ ensureBucket,+ createObject,+ GreenfieldWriteError,+ MAX_VAULT_OBJECT_BYTES,+} from '../api/_lib/bnb/greenfield-write.js';++const PRIVATE_KEY = '0xd5d59cba0041bfd06b22c90cb1453020c6bc29dc90d370bbba0c84fa257768b7'; // freshly generated throwaway test key — no funds anywhere real+const OWNER = '0x3851cF3bB7661ab7250fA01D0d736261a96ef5a9'; // derived from PRIVATE_KEY via viem/accounts+const SP_OPERATOR = '0x1111111111111111111111111111111111111111';++function jsonResponse(obj, status = 200) {+ return { ok: status >= 200 && status < 300, status, async json() { return obj; }, async text() { return JSON.stringify(obj); }, headers: { get: () => null } };+}+function notFoundResponse(kind) {+ return jsonResponse({ code: 2, message: `codespace storage code ${kind === 'bucket' ? 1100 : 1101}: No such ${kind}`, details: [] });+}++function makeMockClient({+ createBucketCode = 0,+ createBucketErr = null,+ toggleSp = true,+ createObjectCode = 0,+ uploadOk = true,+ spOperator = SP_OPERATOR,+ noSp = false,+} = {}) {+ const calls = { createBucket: 0, createObject: 0, uploadObject: 0, cancelCreateObject: 0, getInServiceSP: 0 };+ return {+ calls,+ sp: {+ getInServiceSP: vi.fn(async () => {+ calls.getInServiceSP++;+ if (noSp) throw new Error('no SP');+ return { operatorAddress: spOperator, endpoint: 'https://sp1.example.test' };+ }),+ },+ bucket: {+ createBucket: vi.fn(async () => {+ calls.createBucket++;+ if (createBucketErr) throw createBucketErr;+ return {+ simulate: async () => ({ gasLimit: 120000, gasPrice: '5000000000' }),+ broadcast: async () => ({ code: createBucketCode, transactionHash: '0xBUCKETTXHASH', rawLog: createBucketCode ? 'rejected by chain' : '' }),+ };+ }),+ },+ object: {+ createObject: vi.fn(async () => {+ calls.createObject++;+ return {+ simulate: async () => ({ gasLimit: 250000, gasPrice: '5000000000' }),+ broadcast: async () => ({ code: createObjectCode, transactionHash: '0xOBJECTTXHASH', rawLog: createObjectCode ? 'rejected by chain' : '' }),+ };+ }),+ uploadObject: vi.fn(async () => {+ calls.uploadObject++;+ if (!uploadOk) throw new Error('Storage Provider connection reset');+ return { code: 0 };+ }),+ cancelCreateObject: vi.fn(async () => {+ calls.cancelCreateObject++;+ return {+ simulate: async () => ({ gasLimit: 80000, gasPrice: '5000000000' }),+ broadcast: async () => ({ code: 0, transactionHash: '0xCANCELTXHASH' }),+ };+ }),+ },+ };+}++const SYNTH_GLB = Buffer.from('glTF-synthetic-vault-fixture-bytes-0123456789');++describe('ensureBucket', () => {+ it('is idempotent — a bucket that already exists is a no-op success', async () => {+ const fetchImpl = async () => jsonResponse({ bucket_info: { bucket_name: 'syn-vault', owner: OWNER } });+ const client = makeMockClient();+ const res = await ensureBucket('syn-vault', { network: 'testnet', privateKey: PRIVATE_KEY, client, fetchImpl });+ expect(res).toMatchObject({ bucket: 'syn-vault', created: false, owner: OWNER });+ expect(client.calls.createBucket).toBe(0);+ });++ it('creates a missing bucket via a real MsgCreateBucket broadcast', async () => {+ const fetchImpl = async () => notFoundResponse('bucket');+ const client = makeMockClient();+ const res = await ensureBucket('syn-vault-new', { network: 'testnet', privateKey: PRIVATE_KEY, client, fetchImpl });+ expect(res.created).toBe(true);+ expect(res.txHash).toBe('0xBUCKETTXHASH');+ expect(res.primarySp).toBe(SP_OPERATOR);+ expect(client.calls.getInServiceSP).toBe(1);+ expect(client.calls.createBucket).toBe(1);+ });++ it('a concurrent create ("already exists") resolves to idempotent success, not an error', async () => {+ // Simulates another request winning the race between our headBucket miss+ // and our own broadcast: the chain rejects OUR MsgCreateBucket with an+ // "already exists" rawLog (real Greenfield error text), so ensureBucket+ // re-checks headBucket and returns the now-existing bucket as success.+ let headCalls = 0;+ const fetchImpl = async () => {+ headCalls++;+ return headCalls === 1 ? notFoundResponse('bucket') : jsonResponse({ bucket_info: { bucket_name: 'race-bucket', owner: OWNER } });+ };+ const client = makeMockClient();+ client.bucket.createBucket = vi.fn(async () => ({+ simulate: async () => ({ gasLimit: 120000, gasPrice: '5000000000' }),+ broadcast: async () => ({ code: 6, transactionHash: '0xRACETX', rawLog: 'Bucket already exists: repeated' }),+ }));+ const res = await ensureBucket('race-bucket', { network: 'testnet', privateKey: PRIVATE_KEY, client, fetchImpl });+ expect(res.created).toBe(false);+ expect(res.owner).toBe(OWNER);+ });++ it('rejects a malformed private key before any network call', async () => {+ const fetchImpl = async () => notFoundResponse('bucket');+ await expect(ensureBucket('syn-vault', { network: 'testnet', privateKey: 'not-a-key', fetchImpl })).rejects.toMatchObject({+ name: 'GreenfieldWriteError',+ code: 'bad_input',+ });+ });++ it('surfaces "no in-service SP" as a typed 502-mappable error', async () => {+ const fetchImpl = async () => notFoundResponse('bucket');+ const client = makeMockClient({ noSp: true });+ await expect(ensureBucket('syn-vault', { network: 'testnet', privateKey: PRIVATE_KEY, client, fetchImpl })).rejects.toMatchObject({+ code: 'no_sp',+ });+ });++ it('a chain-rejected createBucket tx throws tx_failed, not a silent success', async () => {+ const fetchImpl = async () => notFoundResponse('bucket');+ const client = makeMockClient({ createBucketCode: 5 });+ await expect(ensureBucket('syn-vault', { network: 'testnet', privateKey: PRIVATE_KEY, client, fetchImpl })).rejects.toMatchObject({+ code: 'tx_failed',+ });+ });+});++describe('createObject', () => {+ it('rejects empty bytes before touching the network', async () => {+ const client = makeMockClient();+ await expect(createObject('b', 'o', new Uint8Array(0), { privateKey: PRIVATE_KEY, client })).rejects.toMatchObject({ code: 'bad_input' });+ expect(client.calls.createObject).toBe(0);+ });++ it('rejects an object over the vault size ceiling', async () => {+ const client = makeMockClient();+ const big = { length: MAX_VAULT_OBJECT_BYTES + 1 };+ await expect(createObject('b', 'o', big, { privateKey: PRIVATE_KEY, client })).rejects.toMatchObject({ code: 'too_large' });+ });++ it('uploads, and reports status:"stored" when the poll observes OBJECT_STATUS_SEALED', async () => {+ const fetchImpl = async () => jsonResponse({ object_info: { object_status: 'OBJECT_STATUS_SEALED' } });+ const client = makeMockClient();+ const res = await createObject('syn-bucket', 'vaults/x/a.glb.enc', SYNTH_GLB, {+ network: 'testnet',+ privateKey: PRIVATE_KEY,+ client,+ fetchImpl,+ contentType: 'application/octet-stream',+ });+ expect(res).toMatchObject({ bucket: 'syn-bucket', object: 'vaults/x/a.glb.enc', txHash: '0xOBJECTTXHASH', status: 'stored', sp: SP_OPERATOR });+ expect(client.calls.createObject).toBe(1);+ expect(client.calls.uploadObject).toBe(1);+ // The uploadObject call must carry the real on-chain create tx hash, per+ // the SDK's PutObjectRequest.txnHash contract.+ expect(client.object.uploadObject).toHaveBeenCalledWith(+ expect.objectContaining({ txnHash: '0xOBJECTTXHASH' }),+ expect.objectContaining({ type: 'ECDSA' }),+ );+ });++ it('surfaces status:"pending" (never a false "stored") when sealing has not landed within the poll budget', async () => {+ const fetchImpl = async () => notFoundResponse('object'); // still mirroring+ const client = makeMockClient();+ const res = await createObject('syn-bucket', 'vaults/x/b.glb.enc', SYNTH_GLB, {+ network: 'testnet',+ privateKey: PRIVATE_KEY,+ client,+ fetchImpl,+ pollIntervalMs: 5,+ pollTimeoutMs: 20,+ });+ expect(res.status).toBe('pending');+ });++ it('a chain-rejected createObject tx never reaches the SP upload step', async () => {+ const client = makeMockClient({ createObjectCode: 3 });+ await expect(+ createObject('syn-bucket', 'vaults/x/c.glb.enc', SYNTH_GLB, { network: 'testnet', privateKey: PRIVATE_KEY, client }),+ ).rejects.toMatchObject({ code: 'tx_failed' });+ expect(client.calls.uploadObject).toBe(0);+ });++ it('an SP upload failure cancels the pending on-chain create and surfaces upload_failed', async () => {+ const client = makeMockClient({ uploadOk: false });+ await expect(+ createObject('syn-bucket', 'vaults/x/d.glb.enc', SYNTH_GLB, { network: 'testnet', privateKey: PRIVATE_KEY, client }),+ ).rejects.toMatchObject({ code: 'upload_failed', txHash: '0xOBJECTTXHASH' });+ expect(client.calls.cancelCreateObject).toBe(1);+ });++ it('never leaves a half-object referenced when the cancel itself also fails — the real upload error still wins', async () => {+ const client = makeMockClient({ uploadOk: false });+ client.object.cancelCreateObject = vi.fn(async () => { throw new Error('cancel also down'); });+ await expect(+ createObject('syn-bucket', 'vaults/x/e.glb.enc', SYNTH_GLB, { network: 'testnet', privateKey: PRIVATE_KEY, client }),+ ).rejects.toMatchObject({ code: 'upload_failed' });+ });+});diff --git a/tests/bnb-vault-upload.test.js b/tests/bnb-vault-upload.test.jsnew file mode 100644index 000000000..29245c2e1--- /dev/null+++ b/tests/bnb-vault-upload.test.js@@ -0,0 +1,272 @@+/**+ * POST /api/bnb/vault-upload — integration tests.+ *+ * `../api/_lib/bnb/greenfield-write.js` is mocked (a real bucket/object write+ * needs a funded Greenfield account — see PROGRESS.md's prompt 09 entry for+ * the real, unfunded-key probe against live testnet) so this suite proves the+ * pipeline logic deterministically: GLB in → manifest out matching+ * specs/vault-manifest.md, ciphertext object referenced, the raw/wrapped+ * content key NEVER present in the manifest, `pending` surfaced honestly when+ * Greenfield hasn't sealed yet, and every input-validation / error-mapping+ * branch. `encryptGlb`/`secret-box` and the rate limiter run for REAL (fast,+ * synchronous-ish, no network) so the crypto boundary is genuinely exercised.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++// secret-box.js (the content-key-at-rest envelope) needs a master secret —+// same ephemeral test convention as tests/vanity-premium-inventory.test.js.+process.env.WALLET_ENCRYPTION_KEY ||= 'vitest-ephemeral-wallet-key-000000000000000000';+process.env.JWT_SECRET ||= 'vitest-ephemeral-jwt-secret-00000000000000';++const SELLER = '0x000000000000000000000000000000000000dEaD';+const OPERATOR_KEY = '0xd5d59cba0041bfd06b22c90cb1453020c6bc29dc90d370bbba0c84fa257768b7';+const SYNTH_GLB = Buffer.concat([Buffer.from('glTF'), Buffer.alloc(16, 7), Buffer.from('synthetic-vault-fixture')]);++const rl = { ok: true };+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { bnbVaultUploadIp: vi.fn(async () => ({ success: rl.ok, reset: Date.now() + 60_000 })) },+ clientIp: () => '127.0.0.1',+}));++const gfState = { bucketExists: false, objectStatus: 'stored', failManifest: false, glbError: null };+vi.mock('../api/_lib/bnb/greenfield-write.js', async () => {+ const actual = await vi.importActual('../api/_lib/bnb/greenfield-write.js');+ return {+ ...actual,+ ensureBucket: vi.fn(async (bucket) => ({ bucket, network: 'testnet', created: !gfState.bucketExists, txHash: gfState.bucketExists ? undefined : '0xBUCKETTX' })),+ createObject: vi.fn(async (bucket, object) => {+ if (object.endsWith('.manifest.json') && gfState.failManifest) {+ throw new actual.GreenfieldWriteError('manifest SP upload failed', { code: 'upload_failed' });+ }+ if (!object.endsWith('.manifest.json') && gfState.glbError) {+ throw gfState.glbError;+ }+ return { bucket, object, network: 'testnet', txHash: '0xOBJECTTX', sp: '0xSPOPERATOR', status: gfState.objectStatus };+ }),+ };+});++// ssrf.js's assertPublicHttpsUrl does a REAL DNS lookup, which the sandbox has+// no egress for — mock it to a pass-through so the glbUrl branch's OWN logic+// (fetch + GLB-magic validation) is what's under test here, not DNS resolution+// (already covered by ssrf.js's own suite).+vi.mock('../api/_lib/ssrf.js', async () => {+ const actual = await vi.importActual('../api/_lib/ssrf.js');+ return { ...actual, assertPublicHttpsUrl: vi.fn(async (url) => url) };+});++const { default: handler } = await import('../api/bnb/vault-upload.js');+const { GreenfieldWriteError } = await import('../api/_lib/bnb/greenfield-write.js');+const { cacheGet } = await import('../api/_lib/cache.js');+const { decryptSecret } = await import('../api/_lib/secret-box.js');++function makeReq(body, { method = 'POST' } = {}) {+ return {+ method,+ url: '/api/bnb/vault-upload',+ headers: { origin: 'https://three.ws', 'content-type': 'application/json' },+ socket: { remoteAddress: '127.0.0.1' },+ body: JSON.stringify(body),+ };+}+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 call(body, opts) {+ const req = makeReq(body, opts);+ const res = makeRes();+ await handler(req, res);+ return res;+}++beforeEach(() => {+ rl.ok = true;+ gfState.bucketExists = false;+ gfState.objectStatus = 'stored';+ gfState.failManifest = false;+ gfState.glbError = null;+ process.env.GREENFIELD_VAULT_OPERATOR_KEY = OPERATOR_KEY;+ delete process.env.GREENFIELD_VAULT_ADDRESS_TESTNET;+});+afterEach(() => {+ vi.clearAllMocks();+ delete process.env.GREENFIELD_VAULT_OPERATOR_KEY;+});++describe('POST /api/bnb/vault-upload — success', () => {+ it('encrypts the GLB, writes the ciphertext + manifest objects, and returns a manifest matching the spec', async () => {+ const r = await call({ glbBase64: SYNTH_GLB.toString('base64'), sellerAddress: SELLER, priceAtomic: '250000' });+ expect(r._s).toBe(200);+ const body = r.json();++ expect(body.status).toBe('stored');+ expect(body.glbObjectRef.object).toMatch(/^vaults\/0x0+dead\/[0-9a-f]{16}\.glb\.enc$/);+ expect(body.manifestRef.object).toBe(body.glbObjectRef.object.replace(/\.glb\.enc$/, '.manifest.json'));++ const m = body.manifest;+ expect(m.version).toBe(1);+ expect(m.glbObjectRef).toEqual(body.glbObjectRef);+ expect(m.encryption.alg).toBe('AES-256-GCM');+ expect(m.encryption.iv).toMatch(/^[0-9a-f]{24}$/);+ expect(m.encryption.authTag).toMatch(/^[0-9a-f]{32}$/);+ expect(m.sha256).toBe(body.sha256);+ expect(m.priceAtomic).toBe('250000');+ expect(m.sellerAddress.toLowerCase()).toBe(SELLER.toLowerCase());+ expect(m.contract).toHaveProperty('address');+ expect(m.contract).toHaveProperty('chainId', 97);++ // The manifest is the wire spec's public contract — it must NEVER carry+ // the raw or wrapped content key, only iv/authTag/sha256.+ const manifestKeys = Object.keys(m).join(',');+ expect(manifestKeys).not.toMatch(/contentKey|wrappedKey|privateKey/i);+ expect(JSON.stringify(m)).not.toContain('contentKey');+ });++ it('persists the encrypted content key server-side, retrievable by the ciphertext object ref, never in plaintext', async () => {+ const r = await call({ glbBase64: SYNTH_GLB.toString('base64'), sellerAddress: SELLER });+ const body = r.json();+ const cached = await cacheGet(`bnb:vault:key:${body.glbObjectRef.bucket}:${body.glbObjectRef.object}`);+ expect(cached).toBeTruthy();+ expect(cached.contentKeyCiphertext).toMatch(/^v2:/); // secret-box AES-256-GCM envelope, not plaintext+ expect(cached.sellerAddress.toLowerCase()).toBe(SELLER.toLowerCase());+ const recoveredKeyB64 = await decryptSecret(cached.contentKeyCiphertext);+ expect(Buffer.from(recoveredKeyB64, 'base64')).toHaveLength(32); // AES-256 content key+ });++ it('accepts glbUrl as an alternative to glbBase64', async () => {+ const origFetch = global.fetch;+ global.fetch = vi.fn(async () => ({ ok: true, status: 200, arrayBuffer: async () => SYNTH_GLB.buffer.slice(SYNTH_GLB.byteOffset, SYNTH_GLB.byteOffset + SYNTH_GLB.byteLength) }));+ try {+ const r = await call({ glbUrl: 'https://r2.three.ws/forge/synthetic.glb', sellerAddress: SELLER });+ expect(r._s).toBe(200);+ } finally {+ global.fetch = origFetch;+ }+ });++ it('a bucket that already exists is reused, not re-created (ensureBucket idempotent)', async () => {+ gfState.bucketExists = true;+ const r = await call({ glbBase64: SYNTH_GLB.toString('base64'), sellerAddress: SELLER });+ expect(r._s).toBe(200);+ const { ensureBucket } = await import('../api/_lib/bnb/greenfield-write.js');+ expect(ensureBucket).toHaveBeenCalledTimes(1);+ });++ it('surfaces status:"pending" honestly (not a lie of "stored") when Greenfield has not sealed yet', async () => {+ gfState.objectStatus = 'pending';+ const r = await call({ glbBase64: SYNTH_GLB.toString('base64'), sellerAddress: SELLER });+ const body = r.json();+ expect(body.status).toBe('pending');+ expect(body.pollHint).toBeTruthy();+ });++ it('marks contractDeployed:false and uses the documented placeholder when no vault contract address is configured', async () => {+ const r = await call({ glbBase64: SYNTH_GLB.toString('base64'), sellerAddress: SELLER });+ const body = r.json();+ expect(body.contractDeployed).toBe(false);+ expect(body.manifest.contract.address).toBe('0x0000000000000000000000000000000000dEaD');+ });++ it('honors an explicit contractAddress override and reports contractDeployed:true', async () => {+ const CONTRACT = '0x1234567890123456789012345678901234567890';+ const r = await call({ glbBase64: SYNTH_GLB.toString('base64'), sellerAddress: SELLER, contractAddress: CONTRACT });+ const body = r.json();+ expect(body.contractDeployed).toBe(true);+ expect(body.manifest.contract.address.toLowerCase()).toBe(CONTRACT.toLowerCase());+ });+});++describe('POST /api/bnb/vault-upload — input validation', () => {+ it('400 on a missing sellerAddress', async () => {+ const r = await call({ glbBase64: SYNTH_GLB.toString('base64') });+ expect(r._s).toBe(400);+ });+ it('400 on a Solana address for sellerAddress (wrong chain)', async () => {+ const r = await call({ glbBase64: SYNTH_GLB.toString('base64'), sellerAddress: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' });+ expect(r._s).toBe(400);+ });+ it('400 when neither glbUrl nor glbBase64 is given', async () => {+ const r = await call({ sellerAddress: SELLER });+ expect(r._s).toBe(400);+ });+ it('400 when BOTH glbUrl and glbBase64 are given', async () => {+ const r = await call({ sellerAddress: SELLER, glbUrl: 'https://r2.three.ws/x.glb', glbBase64: SYNTH_GLB.toString('base64') });+ expect(r._s).toBe(400);+ });+ it('415 when the decoded bytes are not a real GLB (no glTF magic header)', async () => {+ const r = await call({ sellerAddress: SELLER, glbBase64: Buffer.from('not a glb at all').toString('base64') });+ expect(r._s).toBe(415);+ });+ it('400 on an empty GLB', async () => {+ const r = await call({ sellerAddress: SELLER, glbBase64: '' });+ expect(r._s).toBe(400);+ });+ it('400 on an unknown network', async () => {+ const r = await call({ sellerAddress: SELLER, glbBase64: SYNTH_GLB.toString('base64'), network: 'nonsense' });+ expect(r._s).toBe(400);+ });+ it('400 on a non-numeric priceAtomic', async () => {+ const r = await call({ sellerAddress: SELLER, glbBase64: SYNTH_GLB.toString('base64'), priceAtomic: 'not-a-number' });+ expect(r._s).toBe(400);+ });+ it('413 for an oversized GLB fetched via glbUrl', async () => {+ const origFetch = global.fetch;+ global.fetch = vi.fn(async () => ({ ok: true, status: 200, arrayBuffer: async () => new ArrayBuffer(64 * 1024 * 1024 + 1) }));+ try {+ const r = await call({ sellerAddress: SELLER, glbUrl: 'https://r2.three.ws/forge/huge.glb' });+ expect(r._s).toBe(413);+ } finally {+ global.fetch = origFetch;+ }+ });+});++describe('POST /api/bnb/vault-upload — upstream failure', () => {+ it('the ciphertext ref is still surfaced when only the manifest publish fails, so a retry need not re-upload the GLB', async () => {+ gfState.failManifest = true;+ const r = await call({ glbBase64: SYNTH_GLB.toString('base64'), sellerAddress: SELLER });+ expect(r._s).toBe(502);+ const body = r.json();+ expect(body.glbObjectRef).toBeTruthy();+ expect(body.sha256).toBeTruthy();+ });++ it('503 when the vault operator key is not configured (no silent fake signer)', async () => {+ delete process.env.GREENFIELD_VAULT_OPERATOR_KEY;+ const r = await call({ glbBase64: SYNTH_GLB.toString('base64'), sellerAddress: SELLER });+ expect(r._s).toBe(503);+ });++ it('maps a too_large GreenfieldWriteError on the ciphertext write to 413', async () => {+ gfState.glbError = new GreenfieldWriteError('object exceeds the vault limit', { code: 'too_large' });+ const r = await call({ glbBase64: SYNTH_GLB.toString('base64'), sellerAddress: SELLER });+ expect(r._s).toBe(413);+ expect(r.json().error).toBe('too_large');+ });++ it('maps a tx_failed GreenfieldWriteError on the ciphertext write to 502', async () => {+ gfState.glbError = new GreenfieldWriteError('chain rejected the tx', { code: 'tx_failed' });+ const r = await call({ glbBase64: SYNTH_GLB.toString('base64'), sellerAddress: SELLER });+ expect(r._s).toBe(502);+ expect(r.json().error).toBe('tx_failed');+ });+});++describe('POST /api/bnb/vault-upload — rate limiting + method', () => {+ it('429 when the IP bucket is exhausted', async () => {+ rl.ok = false;+ const r = await call({ glbBase64: SYNTH_GLB.toString('base64'), sellerAddress: SELLER });+ expect(r._s).toBe(429);+ });+ it('405 on GET', async () => {+ const r = await call({}, { method: 'GET' });+ expect(r._s).toBe(405);+ });+});