# Audit report

> Public review export 87b64e20b644d67a943f9d397a265986f038bb78. Producing World source e5f17432152670e5516f09fade16f2720b86dcb4.
>
> Review producing World source e5f17432152670e5516f09fade16f2720b86dcb4, following the five accepted findings in job a211537e-407d-4494-bfbb-159f2665bc33. Original report and exact baseline-to-fix patch are in context/. Reproduce the original failures against World1015b2c5/publiccc7b7b6, then test this fixed source; do not mistake historical evidence for current acceptance.
>
> M1: legacy GOLD challenge and pay now receive the installed provider's product list, mirroring the new quote API. Unsupported pending services fail before debit. Both challenge and debit SQL bind the immutable linked product against json_each of the trusted product list. Check empty/omitted lists, JS-guard bypass calibration, supported research, provider changes, challenge/order expiry equality, concurrency, repeated signatures, and already-paid replay while paused. Existing owed jobs remain intact; no new charge, deleted right or invented refund.
>
> L1/L3: economy-session.ts gives the affected financial/campaign/inventory routes one sticky nondecreasing safe-integer clock, verified initial sessions and post-I/O revalidation of exact token, wallet, original expiry, wallet type and method. Check every late read/write boundary, final session-read expiry comparison, regression above route start and transient invalid clock followed by recovery. Invalid time returns503; lost authority401 with no private body. ECDSA/ERC1271 reads remain valid; writes retain EOA/ECDSA and atomic live-session SQL. Full report authentication precedes provider access. Async revalidation must be awaited inside catch boundaries.
>
> L2: HTTP reconciliation chooses the report's post-write revalidation option. It returns401 after concurrent logout, never stale success. A legitimately owed credit may already be committed by the idempotent repair also used by cron; logout does not undo it. Check success and failure replies, original order/account ownership, cron/authenticated retry exactly once, capacity failures and paused admissions.
>
> I1: admin enabled service definitions now require product-scoped provider readiness. Disabled preparatory definitions and topups retain their own rules. Recheck immutable price versions and admin before/after evidence. New quote/admin and legacy challenge/pay responses also revalidate after commit; a failed HTTP response must not cause a second payment.
>
> Trace all GOLD credit/debit/hold/refund/admin repair and staking UTC boundaries, old/new entry points, schema guards, recovery and provider protocol, not just the changed lines. GOLD is a wallet-bound nontransferable/nonredeemable ledger credit, not an ERC20, AMM or trading pair. Retail topup/service/Mint admission stays closed; prices are unset and the approved game NFT catalogue is empty. Existing mainnet contracts and research VPS adapter are unchanged. Full-suite, native D1 and portable source tests are separate evidence; no load-capacity or real-wallet payment claim. Local fixes, actual production deployment, a public GitHub ref, paid submission and an accepted verdict are distinct facts. Return actionable reproductions, severity, fixes and regressions.

| | |
|---|---|
| Repository | https://github.com/tungweb3/imd-ember-world-review.git |
| Commit | `87b64e20b644d67a943f9d397a265986f038bb78` |
| Job | `f5a3b8f9-c3ee-4706-aa61-d1a7e4fb3159` |
| Judged | 2026-10-19 16:42 UTC |
| Findings | 2 low · 3 info |

Four agents audited the code as it is at `87b64e2`, each in one area (math, permissions, economics, control flow),
and a judge reproduced, merged and ranked what they found, then read the code once more itself. Nothing in the repository was changed or deployed.

## Findings

### 1. Low: Lost authority between the last session read and the GOLD write batch is reported as 503 GOLD_UNAVAILABLE / CAMPAIGN_UNAVAILABLE instead of 401 (quote, admin, campaign)

`world-source/server/world-gold-api.ts:73`

```
 }catch(e){const code=e instanceof Error?e.message:'GOLD_UNAVAILABLE';return bad(code==='INVALID_CLOCK'?503:code==='BAD_REQUEST'||code==='INVALID_PRODUCT'||code==='INVALID_REQUEST_ID'?400:code==='ADMIN_REQUIRED'?403:code.startsWith('INVALID_')||code.endsWith('_REQUIRED')||code==='ORDER_EXPIRED'||code==='IDEMPOTENCY_CONFLICT'||code==='FEATURE_PAUSED'||code==='PRODUCT_UNAVAILABLE'?409:503,/^[A-Z][A-Z0-9_]{1,80}$/.test(code)?code:'GOLD_UNAVAILABLE');}
```

L1/L3 and I1 state that on the affected financial/campaign routes lost authority is 401 with no private body and invalid time is 503. POST /api/gold/quote and POST /api/gold/admin revalidate the session (world-gold-api.ts:60) and then call goldQuote/goldAdminCommand, whose batch begins with authCheck (world-gold.ts:15), an INSERT INTO world_gold_write_checks with accepted=0 when the live-session EXISTS predicate is false. The CHECK(accepted=1) constraint aborts the batch with a raw SQLite message; goldQuote's retry lookup finds no order and rethrows, goldAdminCommand rethrows, and the catch here cannot match /^[A-Z][A-Z0-9_]{1,80}$/ so it answers 503 GOLD_UNAVAILABLE. POST /api/me/aimarket-campaign (aimarket-campaign.ts:39/44) has no pre-batch revalidation at all and maps the same raw error to 503 CAMPAIGN_UNAVAILABLE. The atomic SQL guard itself works (nothing is written, no private body), but the status tells a signed-out client that the service is down, so it retries instead of re-authenticating; the sibling legacy challenge route answers 401 AUTH_REQUIRED for the identical race (economy-ledger.ts:248). Fix: in goldQuote/goldAdminCommand, on a batch error re-evaluate the live-session predicate (or call revalidateEconomySession in the handlers' catch) and throw/return AUTH_REQUIRED mapped to 401 (today endsWith('_REQUIRED') maps AUTH_REQUIRED to 409 in this catch, so add an explicit 401 case); do the same in aimarket-campaign.ts. Regression: add a 'logout after the last session read, before batch' mutation to the audit9 committed-write matrix for quote, admin and campaign expecting 401 {error:'AUTH_REQUIRED'} and no rows written; INVALID_CLOCK must stay 503.

**Reproduction**

Reproduced with node --test (Node 24.21.0) against an isolated copy of world-source e5f1743 installed from its exact package-lock (npm ci), importing tests/world-gold-audit5-fixture.mjs. Session row: sessions(token_hash=sha256('z'*43),address=<wallet>,chain_id=1,created_at=NOW-1,expires_at=NOW+60000,wallet_type='EOA',verification_method='ECDSA'); requests to https://imdember.com with origin https://imdember.com, content-type application/json, cookie __Host-imd_session=z*43. 'Revoke after read N' = wrap db.prepare so that right after the Nth execution of 'SELECT address,expires_at,revoked_at,wallet_type,verification_method FROM sessions WHERE token_hash=?1' returns the still-live row, UPDATE sessions SET revoked_at=NOW+1 runs (a logout committing in another tab during the route's awaits). (1) quote: f=await fixture(); await f.topup(); session for W; revoke after read 2 (the pre-write revalidation); POST /api/gold/quote {expectedAddress:W,requestId:<uuid>,product:'pack'} with deps {db,config,now:()=>NOW+2,allow:async()=>true,serviceReady:true,serviceProducts:['research']}. Expected 401 {error:'AUTH_REQUIRED'}; observed 503 {"error":"GOLD_UNAVAILABLE"}, economy_orders count unchanged (1, the fixture topup). (2) admin: same with an OWNER session, POST /api/gold/admin {expectedAddress:OWNER,requestId:<uuid>,reason:'Late logout boundary',command:{action:'control',feature:'topup',version:0,enabled:false}} -> observed 503 GOLD_UNAVAILABLE, topup control row unchanged {enabled:1,version:0}. (3) campaign: OWNER session, revoke after read 1, POST /api/me/aimarket-campaign {expectedAddress:OWNER,requestId:<uuid>,reason:'Late logout campaign',version:1,startsMs:NOW,endsMs:NOW+1000,stopped:false}, deps {db,now:()=>NOW+2,allow:async()=>true} -> observed 503 {"error":"CAMPAIGN_UNAVAILABLE"}, world_gold_campaigns 0 rows. Control: identical wrapper on POST /api/economy/orders/<id>/gold/challenge -> 401 {"error":"AUTH_REQUIRED"}. Merged from audit_permissions findings 3109092e and fb08a022 (same authCheck-abort mechanism).

### 2. Low: Legacy GOLD pay and inventory write report a session revoked before their atomic batch as 409 (PAYMENT_UNAVAILABLE / REVISION_CONFLICT) instead of 401

`world-source/server/economy-ledger.ts:328`

```
  if(completed?.status!=='paid'){await sharedServiceAdmission(db,id,args.serviceReady,args.serviceProducts);throw new EconomyConflict('PAYMENT_UNAVAILABLE');}
```

Both writes embed the live-session predicate as a WHERE clause, so a revoked session makes the batch match zero rows and succeed silently. payEconomyOrderGold then re-reads the order, finds it still pending, and line 328 throws PAYMENT_UNAVAILABLE (409 via economy.ts:83), whereas createEconomyGoldChallenge handles the same zero-row state as AUTH_REQUIRED/401 (economy-ledger.ts:248). The inventory POST reads the session once (inventory.ts:80) with no pre-batch revalidation and inventory.ts:103 reports every zero-change UPDATE as 409 REVISION_CONFLICT, which the client treats as a CAS race (refetch and resubmit) rather than a logout. No debit, job, consumed challenge or arrangement is written and no private body leaks, and a retry after re-login still pays exactly once (challenge stays unconsumed), so impact is a wrong status contrary to the L1/L3 'lost authority 401' contract. Fix: when the batch changed nothing, evaluate the session predicate (SELECT 1 FROM sessions WHERE token_hash=? AND LOWER(address)=? AND revoked_at IS NULL AND expires_at>? AND wallet_type='EOA' AND verification_method='ECDSA', or revalidateEconomySession) and throw/return AUTH_REQUIRED -> 401 before falling back to PAYMENT_UNAVAILABLE / REVISION_CONFLICT. Regression: audit9 committed-write matrix 'logout before batch' for pay and inventory -> 401, book and arrangement unchanged; a genuine revision race still 409.

**Reproduction**

Reproduced with node --test (Node 24.21.0) against an isolated copy of world-source e5f1743 installed from its exact package-lock (npm ci), importing tests/world-gold-audit5-fixture.mjs. Session row: sessions(token_hash=sha256('z'*43),address=<wallet>,chain_id=1,created_at=NOW-1,expires_at=NOW+60000,wallet_type='EOA',verification_method='ECDSA'); requests to https://imdember.com with origin https://imdember.com, content-type application/json, cookie __Host-imd_session=z*43. 'Revoke after read N' = wrap db.prepare so that right after the Nth execution of 'SELECT address,expires_at,revoked_at,wallet_type,verification_method FROM sessions WHERE token_hash=?1' returns the still-live row, UPDATE sessions SET revoked_at=NOW+1 runs (a logout committing in another tab during the route's awaits). (1) pay: f=await fixture(); await f.topup(); id=await f.quote('research'); s=await f.challenge(id); session for W; revoke after read 2 (economy.ts:70 revalidation); POST /api/economy/orders/<id>/gold {expectedAddress:W,requestId:s.requestId,signature:s.signature}, deps {db,config,now:()=>NOW+2,allow:async()=>true,serviceReady:true,serviceProducts:['research']}. Expected 401 {error:'AUTH_REQUIRED'}; observed 409 {"error":"PAYMENT_UNAVAILABLE"}, book stays '10', world_gold_jobs 0 rows. Control: same wrapper on POST .../gold/challenge -> 401 AUTH_REQUIRED. (2) inventory: session for W, revoke after read 1; POST /api/me/inventory {expectedAddress:W,revision:0,command:{type:'publish',enabled:false}}, deps {db,now:()=>NOW+2,allow:async()=>true,home:async()=>({address:W,eligible:0,checkedAt:NOW+2,block:100})}. Expected 401; observed 409 {"error":"REVISION_CONFLICT"}, world_inventory_arrangements 0 rows; a following GET /api/me/inventory with the same cookie returns 401, proving the cause was lost authority. Merged from audit_permissions findings 57457ef8 and 016bd433 (same zero-row mechanism).

### 3. Info: Admin 'control service enable' ignores the product-scoped readiness: with an installed provider whose product list is empty the service feature can be enabled and /api/gold/state reports deliveryReady

`world-source/server/world-gold-api.ts:65`

```
   const cmd=command(b!.command),ready=deps.serviceReady&&(!deps.serviceProducts||cmd.action!=='product'||cmd.kind!=='service'||deps.serviceProducts.includes(cmd.product));
```

The I1 readiness expression is product-scoped only for cmd.action==='product'; for {action:'control',feature:'service',enabled:true} it reduces to deps.serviceReady, and hasGoldDeliveryProvider (world-gold-delivery.ts:11) does not require a non-empty products list. goldAdminCommand's control branch (world-gold.ts:208) therefore enables the service feature with serviceProducts:[], while M1 makes quote, legacy challenge and pay refuse every product for that list. The admin action and its before/after evidence record service enabled, and the state view publishes deliveryReady:true, for a provider that can serve nothing. No GOLD moves and no job is created (dead switch / consistency gap in the I1 family). The production aimarket adapter always declares ['research'], so this needs a provider object with an empty or fully unsupported list. Fix: for the control/service enable compute ready as deps.serviceReady&&(!deps.serviceProducts||deps.serviceProducts.some(hasGoldResultContract)) and derive deliveryReady from the same predicate. Regression: enable with [] -> 503 SERVICE_DELIVERY_UNAVAILABLE and controls row unchanged; with ['research'] -> 200.

**Reproduction**

Reproduced with node --test (Node 24.21.0) against an isolated copy of world-source e5f1743 installed from its exact package-lock (npm ci), importing tests/world-gold-audit5-fixture.mjs. Session row: sessions(token_hash=sha256('z'*43),address=<wallet>,chain_id=1,created_at=NOW-1,expires_at=NOW+60000,wallet_type='EOA',verification_method='ECDSA'); requests to https://imdember.com with origin https://imdember.com, content-type application/json, cookie __Host-imd_session=z*43. 'Revoke after read N' = wrap db.prepare so that right after the Nth execution of 'SELECT address,expires_at,revoked_at,wallet_type,verification_method FROM sessions WHERE token_hash=?1' returns the still-live row, UPDATE sessions SET revoked_at=NOW+1 runs (a logout committing in another tab during the route's awaits). f=await fixture(); session for OWNER; v=SELECT version FROM world_gold_controls WHERE feature='service'; f.admin({action:'control',feature:'service',enabled:false,version:v}). deps={db,config,now:()=>NOW+1,allow:async()=>true,serviceReady:true,serviceProducts:[]}. POST /api/gold/admin {expectedAddress:OWNER,requestId:'c'*20,reason:'enable with empty list',command:{action:'control',feature:'service',enabled:true,version:v+1}}. Expected 503 SERVICE_DELIVERY_UNAVAILABLE (as the product branch answers). Observed 200 {ok:true,...}, controls service row {enabled:1,version:2}. Same deps: product command research/service/enabled -> 503 (I1 works for definitions); POST /api/gold/quote research -> 503 SERVICE_DELIVERY_UNAVAILABLE; GET /api/gold/state -> 200 deliveryReady:true, controls service enabled:1. Merged from audit_economics 035d7995 and audit_flow b95f3b20 (duplicates).

### 4. Info: GET /api/gold/state publishes historical enabled service products the installed provider cannot serve, with a global deliveryReady:true, while their quote is always 503

`world-source/server/world-gold-api.ts:58`

```
   return await authReply({...snapshot,products,campaign,controls:controls.results,isAdmin,...actions?{actions:actions.results}:{},payment:deps.config?{chainId:deps.config.chainId,token:deps.config.token,contract:deps.config.paymentContract,treasury:deps.config.treasury}:null,paymentsReady:!!deps.config,formalPricesSet:false,deliveryReady:deps.serviceReady===true});
```

I1 blocks creating new enabled service definitions outside deps.serviceProducts, but product rows are immutable and goldProducts() still returns any earlier enabled version (e.g. created under a different provider or before this fix). The state reply lists it with a GOLD price and the single flag deliveryReady:deps.serviceReady===true, while POST /api/gold/quote computes serviceReady per product and answers 503. No GOLD moves (quote and the M1 legacy guards refuse); it is a UI/consistency gap. Fix: add a per-product serviceable flag computed from deps.serviceProducts (or filter kind==='service' rows not in the list) and keep historical rows immutable. Regression: with serviceProducts=['research'] and an enabled fortune:1 row, state must not present fortune as deliverable.

**Reproduction**

Reproduced with node --test (Node 24.21.0) against an isolated copy of world-source e5f1743 installed from its exact package-lock (npm ci), importing tests/world-gold-audit5-fixture.mjs. Session row: sessions(token_hash=sha256('z'*43),address=<wallet>,chain_id=1,created_at=NOW-1,expires_at=NOW+60000,wallet_type='EOA',verification_method='ECDSA'); requests to https://imdember.com with origin https://imdember.com, content-type application/json, cookie __Host-imd_session=z*43. 'Revoke after read N' = wrap db.prepare so that right after the Nth execution of 'SELECT address,expires_at,revoked_at,wallet_type,verification_method FROM sessions WHERE token_hash=?1' returns the still-live row, UPDATE sessions SET revoked_at=NOW+1 runs (a logout committing in another tab during the route's awaits). f=await fixture(); await f.topup(); await f.admin({action:'product',product:'fortune',kind:'service',title:'Fortune',gold:'1',enabled:true,version:1}) (historical row via the fixture's serviceReady:true wiring); session for W; deps {db,config,now:()=>NOW+1,allow:async()=>true,serviceReady:true,serviceProducts:['research']}. POST /api/gold/quote {expectedAddress:W,requestId:'f'*20,product:'fortune'} -> observed 503 SERVICE_DELIVERY_UNAVAILABLE. GET /api/gold/state?expected_address=W -> observed 200 deliveryReady:true and products containing {id:'fortune:1',kind:'service',gold:'1',enabled:1}. Expected: fortune not presented as deliverable. From audit_flow dad7ca17.

### 5. Info: HTTP /api/gold/orders/:id/reconcile ignores the reconcile_errors backoff that cron honours, re-running a failing credit and inflating attempts on every request

`world-source/server/world-gold.ts:76`

```
 const pending=await db.prepare(`SELECT o.id,l.kind FROM economy_orders o JOIN world_gold_links l ON l.order_id=o.id LEFT JOIN world_gold_reconcile_errors e ON e.order_id=o.id WHERE o.status='paid' AND ((l.kind='topup' AND l.gold>COALESCE((SELECT SUM(delta) FROM world_gold_entries WHERE order_id=o.id AND kind='topup'),0)) OR (l.kind='service' AND NOT EXISTS(SELECT 1 FROM world_gold_jobs WHERE order_id=o.id))) ${orderId?'AND o.id=?':'AND (e.order_id IS NULL OR e.retry_ms<=?)'} ORDER BY o.created_ms,o.id LIMIT 128`).bind(orderId??nowMs).all<{id:string;kind:string}>();
```

reconcileWorldGold selects candidates with orderId?'AND o.id=?':'AND (e.order_id IS NULL OR e.retry_ms<=?)' (also line 85 for failed jobs), so the authenticated HTTP retry never consults retry_ms. A persistently failing credit (GOLD_BALANCE_CAPACITY) is re-attempted on every call, each recordFailure increments attempts and pushes retry_ms. No GOLD moves (ON CONFLICT/triggers), the caller must own the order and is rate limited; an owner-initiated retry bypassing backoff may be intentional, so this is an operational note. Fix if unintended: when orderId is supplied, answer 409 with the stored code while e.retry_ms>now, or do not increment attempts on the HTTP path. Regression: cron unchanged; HTTP retry after retry_ms still credits exactly once.

**Reproduction**

Reproduced with node --test (Node 24.21.0) against an isolated copy of world-source e5f1743 installed from its exact package-lock (npm ci), importing tests/world-gold-audit5-fixture.mjs. Session row: sessions(token_hash=sha256('z'*43),address=<wallet>,chain_id=1,created_at=NOW-1,expires_at=NOW+60000,wallet_type='EOA',verification_method='ECDSA'); requests to https://imdember.com with origin https://imdember.com, content-type application/json, cookie __Host-imd_session=z*43. 'Revoke after read N' = wrap db.prepare so that right after the Nth execution of 'SELECT address,expires_at,revoked_at,wallet_type,verification_method FROM sessions WHERE token_hash=?1' returns the still-live row, UPDATE sessions SET revoked_at=NOW+1 runs (a logout committing in another tab during the route's awaits). f=await fixture(); set economy_gold_accounts balance for W to 9223372036854775800; id=await f.quote('pack'); await f.paid(id); reconcileWorldGold(db,NOW) -> failures GOLD_BALANCE_CAPACITY, reconcile_errors {attempts:1,retry_ms:NOW+300000}; reconcileWorldGold(db,NOW+1) -> processed 0 (backoff honoured). Session for W; POST /api/gold/orders/<id>/reconcile {expectedAddress:W} three times with now NOW+2..NOW+4 -> each 409 {ok:false,error:'GOLD_BALANCE_CAPACITY'}; afterwards attempts=4, retry_ms=NOW+300004. Expected (cron parity): attempts 1, retry_ms NOW+300000. From audit_math 5bd3c7e7.

---

Judge's submission `24272a291353f13ce65e622bfd2d16518bdf6f4c71bbd2f394bc365a00603666`, accepted on the IdentityMD network. Acceptance means the report met the job's checks;
it is not a guarantee that the code has no other defects.
