Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CLAIM_LEDGER.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,13 @@ failure.

| Claim | What exists | Missing to reach VERIFIED | Owner |
|-------|-------------|---------------------------|-------|
| x402 payment-proof linking gates positive deltas | `src/services/x402-outcome-link.ts` (+tests); STEP 2 `627e571` caught a real FAIL-OPEN | A live positive-reward run where the anchor is required and present | CC |
| x402 payment-proof linking gates positive deltas | `src/services/x402-outcome-link.ts` (+tests); STEP 2 `627e571` caught a real FAIL-OPEN. **The link checks SHAPE only unless a caller passes `requireVerified`** [E2E eval 2026-11-16 §3a: a made-up hash turned an UNCERTAIN outcome into +25 through `scripts/demo/trust-harness-e2e.mjs`]. On-chain checks: `x402-settlement-verifier.ts` (receipt, canonical-USDC `Transfer` to the payee ≥ value) and `payment-anchor-verify.ts` (payee, payer and price from the contract's own record, tx bound to that contract, replay refused), the second in SHADOW behind `PAYMENT_ANCHOR_VERIFY_MODE` (default off; enforce refused in code) | (1) the `payment_anchor_claims` replay table applied (draft migration `20261116130000`, Sean); (2) enforce, Sean's call; (3) a production caller: `scoreSettledInteraction` has none today [MEASURED 2026-11-16], so no live score consumes a caller-supplied anchor yet; (4) then a live positive-reward run where the anchor is required, present and verified | CC |
| HAL confidence calibration fit on a frozen holdout | `src/services/hal-calibration.ts` + `scripts/hal-eval/fit-calibration.ts` (ECE) | A published ECE number on the current frozen corpus with its ruler | CC |
| Outcome classification schema with enforced asymmetric deltas | `src/services/outcome-classification.ts` (+158-line test) | (folded into VERIFIED harness run above; keep here until independent test-count asserted) | CC |
| TrustShell `presentProof` / badge path | `presentProof` + `verifyProofLocally` on the SDK client, `src/lib/badge.ts` (`renderProofBadge` / `renderProofBadgeMarkdown` / `proofBadgeStatus`), a `badge` CLI command, all exported from `src/lib/index.ts`. **14/14 `tests/badge.test.ts` pass [RUN 2026-09-04]**, and they pin the honest states, not just the happy one: verifier UNAVAILABLE → red and explicitly NOT a pass (fail-closed); no verification run → grey, "we refuse to imply unchecked trust"; the badge NEVER reveals the score in any state; the SVG is self-contained with no external references | A live run against the backend producing a real proof, verified client-side, with the badge rendered from it | CC |
| TrustMarket rating ingestion consuming fold root + dual-auth decision | `src/services/rating-ingestion.ts` consumes BOTH halves — it imports `Decision` from `./dual-auth-gate` and rejects `outcome_not_authorized` unless the gate said ALLOW, and rejects `fold_root_mismatch` when the claimed root disagrees with the server's. Fails closed by design: "an unrecorded ALLOW is not an ALLOW" (`:151`). **39/39 pass across `tests/rating-ingestion.test.ts` + `tests/participant-rating.test.ts` [RUN 2026-09-04]** | A live rating ingested end-to-end against a real settled interaction; both tables held 0 rows at last check, so the path is tested but unexercised | CC |
| X8 local adversarial harness (anvil fork pin + LOCAL_MODE scratch + 7 probes as code) | `scripts/adversarial-harness/` + `tests/adversarial-harness.test.ts`. One command `npm run harness`. Synthetic ids only. | Anvil binary on the operator box (optional; A1–A6 run without it). No prod writes. | XC |
| C8 grounding multiplier in shadow | `src/scoring/grounding.ts` is the single `resolveGrounding`. Floor $0.10, parties join, idempotent on (evidence, agent, event_type). | Prod unique index + RPC (Sean DDL / GROUNDING_RPC_URL). Enforce is a later ticket. | XC |
| C8 grounding multiplier in shadow | `src/scoring/grounding.ts` is the single `resolveGrounding`. Floor $0.10, parties join, idempotent on (evidence, agent, event_type). | Prod unique index + RPC (Sean DDL / GROUNDING_RPC_URL). **The table `repid_grounding_claims` itself does not exist in prod** [MEASURED 2026-11-16, `to_regclass` = null], and no production caller passes a chain reader, so a payment grounds `chain_not_checked`. Enforce is a later ticket. | XC |
| C9 L5 bound-entity decay | `src/identity/decay-bound.ts` — bound kinds hold score, `last_verified_action` is the public gap, unclaimed DBT still decays with a typed event. | Kind column on prod `repid_agents` (C7 DDL, Sean). | XC |
| C10 caps as config | `src/config/entity-caps.json` ladder 3→7→12→21, Bronze ceiling, claim 100%, slash drops a rung. | Custodian rows in prod (C7). | XC |

Expand Down
38 changes: 38 additions & 0 deletions scripts/demo/trust-harness-e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,32 @@ try {
// Left null → verifyProofLocally fails closed on step 3.
}

/**
* The shipped payment-anchor check (src/services/payment-anchor-verify.ts), when
* PAYMENT_ANCHOR_VERIFY_MODE is set. DEMO_CONTRACT_ID names the contract the payment settles; its
* terms and the replay table are then read from Supabase (needs real credentials). Without it the
* verifier refuses the anchor as unbound, before any read. Never throws: a verifier that cannot load
* is NOT_CHECKED, never a pass.
*/
async function shadowAnchorCheck(txHash) {
const raw = (process.env.PAYMENT_ANCHOR_VERIFY_MODE ?? '').trim().toLowerCase();
if (raw === '' || raw === 'off') return null;
try {
const { shadowCheckPaymentAnchor, paymentAnchorVerifyMode } = await import('../../dist/services/payment-anchor-verify.js');
const contractId = process.env.DEMO_CONTRACT_ID || null;
const deps = contractId
? await import('../../dist/services/payment-anchor-db.js').then((m) => ({ loadTerms: m.dbAnchorTerms, replay: m.dbAnchorReplayStore() }))
: {
loadTerms: async () => null,
replay: { find: async () => null, bind: async () => { throw new Error('no replay store'); } },
};
return await shadowCheckPaymentAnchor({ txHash, chainId: 84532, contractId }, deps, paymentAnchorVerifyMode());
} catch {
// dist not built, or config refused to load (it needs SUPABASE_URL set, even to a dummy).
return { verdict: 'NOT_CHECKED', reason: 'verifier_unavailable (run npm run build; set SUPABASE_URL)' };
}
}

const ENGINE = process.env.TRUSTSHELL_API_URL || 'https://repid-engine-production.up.railway.app';

// The leaf binary is RESOLVED, not assumed. This used to default to an absolute path under
Expand Down Expand Up @@ -375,6 +401,18 @@ if (!deltaFor || !linkPaymentProof) {
(linked.anchored ? ok : unk)(
linked.anchored ? `payment anchor attached: ${linked.record.x402PaymentProof}` : 'no payment anchor',
);
// GAP 4 (E2E eval 2026-11-16): the attach above checks the anchor's SHAPE only, so a made-up hash
// earned +25 here. With PAYMENT_ANCHOR_VERIFY_MODE=shadow, ask the shipped verifier what it would
// do with this anchor. Shadow: it reports, and the delta below is unchanged.
if (linked.anchored) {
const a = await shadowAnchorCheck(linked.record.x402PaymentProof);
if (a) {
const tail = 'shadow only: the delta below is unchanged';
if (a.verdict === 'VERIFIED') ok(`payment anchor VERIFIED on chain (${a.settlement_kind}), bound to its contract (${tail})`);
else if (a.verdict === 'REFUSED') bad(`payment anchor would be REFUSED: ${a.reason}. Under enforce it is stripped and the success demoted (${tail})`);
else unk(`payment anchor NOT_CHECKED: ${a.reason}. Under enforce it would not earn (${tail})`);
}
}

const d = deltaFor(linked.record);
const newScore = applyDelta(prevScore, d.delta);
Expand Down
1 change: 1 addition & 0 deletions src/config/known-env-vars.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,7 @@ OWNER_CEILING_SHADOW_ENABLED
OWNER_DISTINCT_SHADOW
PANEL_CLOSE_NO_MAJORITY
PARTICIPANT_RATING_MODE
PAYMENT_ANCHOR_VERIFY_MODE
PCP_THRESHOLD_FAIL
PCP_THRESHOLD_PASS
PCP_VALIDATOR_MODEL
Expand Down
1 change: 1 addition & 0 deletions src/ops/flag-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ OWNER_BUDGET_MODE
OWNER_CEILING_SHADOW_ENABLED
OWNER_DISTINCT_SHADOW
PARTICIPANT_RATING_MODE
PAYMENT_ANCHOR_VERIFY_MODE
PEER_VERIFY_PANEL_ENABLED
PEER_VERIFY_PREFILTER_MODE
PEER_VERIFY_REPID_ENABLED
Expand Down
98 changes: 98 additions & 0 deletions src/services/payment-anchor-db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/**
* payment-anchor-db.ts — the Supabase side of `payment-anchor-verify.ts`.
*
* TERMS come from three tables, all written by the engine, none by the caller:
* service_contracts provider, buyer, agreed_price_usdc_raw (the price, in USDC's smallest unit)
* repid_agents the provider's `wallet_address` = the payee
* x402_settlements the settlement recorded for the contract (`idempotency_key` = contract id):
* its `tx_hash` and the facilitator-verified `payer_address`
*
* Why `wallet_address` and not `erc8004_address`: MEASURED 2026-11-16 on the five most recent real
* settlements, every payee was the provider's `wallet_address`, while `erc8004_address` held values
* such as `pending-mint:…`, a registry contract's address, and free text. A payee read from that
* column would refuse real payments or accept payments to the wrong address.
*
* Why the payer is NOT the buyer's wallet: the same five settlements were all paid by the custodian
* wallet, not by the buyer agent's own `wallet_address`. The payer is what the facilitator verified
* from the signed authorization, which `x402_settlements.payer_address` records.
*
* REPLAY TABLE: `payment_anchor_claims`, created by the DRAFT migration
* `supabase/migrations/20261116130000_payment_anchor_claims.sql`. Until Sean applies it, an anchor
* the chain refuses is still REFUSED, and one the chain accepts reports NOT_CHECKED
* `replay_store_unreachable` with `chain_verified: true`: it says exactly what is missing instead of
* passing.
*/
import { db } from '../db';
import type { AnchorBindingRow, AnchorReplayStore, AnchorTerms } from './payment-anchor-verify';

const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const HEX32 = /^0x[0-9a-fA-F]{64}$/;

/** Load a contract's payment terms. null = no such contract. Throws when the read fails. */
export async function dbAnchorTerms(contractId: string): Promise<AnchorTerms | null> {
if (!UUID.test(contractId)) return null; // service_contracts.id is a uuid; anything else is not a contract

const { data: c, error: cErr } = await db
.from('service_contracts')
.select('id, provider_agent_id, agreed_price_usdc_raw')
.eq('id', contractId)
.maybeSingle();
if (cErr) throw new Error('service_contracts read failed');
if (!c) return null;

const { data: p, error: pErr } = await db
.from('repid_agents')
.select('wallet_address')
.eq('id', (c as any).provider_agent_id)
.maybeSingle();
if (pErr) throw new Error('repid_agents read failed');

// More than one settlement row for a contract is itself an anomaly: maybeSingle errors, which
// surfaces as NOT_CHECKED rather than picking one.
const { data: s, error: sErr } = await db
.from('x402_settlements')
.select('tx_hash, payer_address, is_simulated')
.eq('idempotency_key', contractId)
.maybeSingle();
if (sErr) throw new Error('x402_settlements read failed');

const recordedTx =
s && (s as any).is_simulated === false && HEX32.test(String((s as any).tx_hash ?? '')) ? String((s as any).tx_hash) : null;

let units: bigint;
try {
units = BigInt((c as any).agreed_price_usdc_raw ?? 0);
} catch {
units = 0n;
}

return {
contractId,
payeeAddress: (p as any)?.wallet_address ?? null,
claimedUnits: units,
payerAddress: recordedTx ? ((s as any).payer_address ?? null) : null,
recordedTxHash: recordedTx,
};
Comment on lines +69 to +75

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Payment-anchor verification drops the payer and contract-tx binding for a contract whose recorded settlement is simulated

Severity: LOW

TL;DR: For a contract whose settlement row is is_simulated, dbAnchorTerms returns no recorded tx and no payer, so verifyPaymentAnchor skips the tx binding and credits any sender, answering VERIFIED for a transfer that never paid for this contract.

Impact: Once the draft replay table is applied and enforce ships, an agent can anchor a contract it never paid for using another buyer's real transfer to the same provider, consuming that tx so its rightful contract can no longer verify. In shadow mode no score moves.

Root cause:

  • The binding strength is derived from the settlement row's is_simulated flag rather than from whether the contract has a real payment, so the one row that records "no money moved" is treated as carrying no binding information instead of as a reason to refuse.
  • payment-anchor-db.ts:59-60,73 nulls recordedTxHash and gates payerAddress on it, so payment-anchor-verify.ts:271 never compares the anchor against the contract's own tx and :315-317 falls back to summing every sender's inflow in the receipt.
  • Nothing in the verifier treats a simulated settlement as a refusal, so our own record that this contract was never paid is outweighed by any canonical-USDC transfer to the payee and the answer is VERIFIED rather than REFUSED or NOT_CHECKED.
Suggested change
return {
contractId,
payeeAddress: (p as any)?.wallet_address ?? null,
claimedUnits: units,
payerAddress: recordedTx ? ((s as any).payer_address ?? null) : null,
recordedTxHash: recordedTx,
};
return {
contractId,
payeeAddress: (p as any)?.wallet_address ?? null,
claimedUnits: units,
payerAddress: recordedTx ? ((s as any).payer_address ?? null) : null,
recordedTxHash: recordedTx,
settlementSimulated: s ? (s as any).is_simulated !== false : false,
};
Prompt to fix with AI
This is a security vulnerability found during a code review.

Vulnerability: Payment-anchor verification drops the payer and contract-tx binding for a contract whose recorded settlement is simulated
Severity: LOW
CWE: CWE-345

**TL;DR:** For a contract whose settlement row is `is_simulated`, `dbAnchorTerms` returns no recorded tx and no payer, so `verifyPaymentAnchor` skips the tx binding and credits any sender, answering VERIFIED for a transfer that never paid for this contract.

**Impact:** Once the draft replay table is applied and `enforce` ships, an agent can anchor a contract it never paid for using another buyer's real transfer to the same provider, consuming that tx so its rightful contract can no longer verify. In shadow mode no score moves.

**Root cause:**
- The binding strength is derived from the settlement row's `is_simulated` flag rather than from whether the contract has a real payment, so the one row that records "no money moved" is treated as carrying no binding information instead of as a reason to refuse.
- `payment-anchor-db.ts:59-60,73` nulls `recordedTxHash` and gates `payerAddress` on it, so `payment-anchor-verify.ts:271` never compares the anchor against the contract's own tx and `:315-317` falls back to summing every sender's inflow in the receipt.
- Nothing in the verifier treats a simulated settlement as a refusal, so our own record that this contract was never paid is outweighed by any canonical-USDC transfer to the payee and the answer is VERIFIED rather than REFUSED or NOT_CHECKED.

Location: src/services/payment-anchor-db.ts:69-75
Context: primary: carry the simulated flag instead of silently dropping both bindings
```
// Before:
  return {
    contractId,
    payeeAddress: (p as any)?.wallet_address ?? null,
    claimedUnits: units,
    payerAddress: recordedTx ? ((s as any).payer_address ?? null) : null,
    recordedTxHash: recordedTx,
  };
// After:
  return {
    contractId,
    payeeAddress: (p as any)?.wallet_address ?? null,
    claimedUnits: units,
    payerAddress: recordedTx ? ((s as any).payer_address ?? null) : null,
    recordedTxHash: recordedTx,
    settlementSimulated: s ? (s as any).is_simulated !== false : false,
  };
```

Location: src/services/payment-anchor-verify.ts:104-104
Context: terms type carries the simulated state
```
// Before:
  recordedTxHash: string | null;
// After:
  recordedTxHash: string | null;
  /** True when our own record says this contract was settled in simulation: no money moved. */
  settlementSimulated?: boolean;
```

Location: src/services/payment-anchor-verify.ts:163-163
Context: refusal reason
```
// Before:
  | 'refunded_in_tx'
// After:
  | 'refunded_in_tx'
  | 'settlement_simulated'
```

Location: src/services/payment-anchor-verify.ts:263-263
Context: refuse a contract our own record says was never paid
```
// Before:
  if (!terms) return refuse('contract_unknown');
// After:
  if (!terms) return refuse('contract_unknown');
  // Our own record says this contract was settled in simulation, so no money moved for it. An
  // anchor claiming otherwise contradicts that record and is refused, not graded against the chain.
  if (terms.settlementSimulated === true) return refuse('settlement_simulated');
```

How to fix:
Refuse an anchor for a contract whose own settlement record says the payment was simulated, instead of grading it against the payee's inbound transfers. Keep the payer binding independent of the tx binding so a recorded `payer_address` is still enforced when no chain tx is usable, and add a test that a simulated settlement row can never produce VERIFIED.

Please fix this vulnerability. If you propose a fix, make it concise and minimal.

React 👍 / 👎 to tune Strix for this repo. A repo collaborator (or the PR author) can resolve this thread to dismiss the finding.

}

/** The replay table. Any read or write error throws, which the verifier reports as NOT_CHECKED. */
export function dbAnchorReplayStore(): AnchorReplayStore {
return {
async find(chainId, txHash) {
const { data, error } = await db
.from('payment_anchor_claims')
.select('contract_id')
.eq('chain_id', chainId)
.eq('tx_hash', txHash.toLowerCase())
.maybeSingle();
if (error) throw new Error('payment_anchor_claims read failed');
return data ? { contract_id: String((data as any).contract_id) } : null;
},
async bind(row: AnchorBindingRow) {
const { error } = await db.from('payment_anchor_claims').insert(row);
if (!error) return 'ok';
if (String(error.code) === '23505') return 'duplicate';
throw new Error('payment_anchor_claims write failed');
},
};
}
Loading
Loading