Repository navigation
Three-day free trial, x402 payment hardening, and the founder-pack run - #12
Merged
Merged
Conversation
The x402 bot-payment path granted resources on a payment that could be replayed, was not bound to the resource it bought, and recorded nothing in the ledger. Ten defects (F1-F10) fixed: - F1 ledger: payments.uid is NOT NULL REFERENCES auth.users, but the writer passed the all-zero UUID, so EVERY x402 ledger insert raised a foreign-key violation that was logged and swallowed. uid is now nullable for machine rows only, guarded by a CHECK so human rows still require an owner. - F2 fail-open: the AI route's fallback branch set isX402Bot = true and served paid AI for free on any outcome that was neither a challenge nor a verified payment. Deleted; every non-verified outcome is a 402. - F3 replay: no HTTP-layer idempotency existed, so one signed authorization produced N grants against any facilitator not authoritative for single-use. New x402_payment_claims table + claimX402Payment, keyed on sha256(network|asset|payer|nonce) from SIGNED fields only. Replay -> 409. - F4 payment is now bound to the resource via resourceKey. - F5 both paid routes now mark granted content private, no-store. - F6 X402_PAY_TO no longer defaults to the placeholder 0x...0001. - F7 ledger amounts converted to atomic USDC (5000, not 1). - F8 the no-op 20261011 migration is marked superseded. - F9 machine callers are metered against the claims table BEFORE settlement, so an over-budget caller is refused with 429 without being charged. - F10 the machine UID now satisfies the v4 pattern, so bot transcripts are actually persisted instead of silently discarded. Adds tests/x402-payment-guard.test.ts (24 cases) pinning the invariants: single grant under 12-way concurrency, no grant when settlement reports success but the claim is taken, fail-closed on an unreachable claim store, and no charge for an over-budget caller. Wired into CI as an offline step. The UroPay path is unchanged. research/x402/x402-security-review.md section 8 corrected: the provider is UroPay on Next.js + Supabase, not Razorpay. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
…ot yet) Applies all eleven skills of the founder pack to this business and compiles them into founder/business-plan.md. Verdict comes from compile.py, not from hand: Not yet — three of four checks pass, the buyer panel falls short at 22% against a 25% bar. Sourced findings that changed the picture: - UroPay charges zero per-transaction commission, so payment cost belongs in fixed_monthly, not variable; the only per-sale variable cost is the 16.72% referral commission. Contribution is 85% and break-even is ~8 sales/month. - The Max mode (Kimi K3) costs ~191x the default model per request and is user-selectable with identical daily caps on both plans. One Max request a day loses money per user; as an average-user cost the business never breaks even. This is the highest-value fix in the pack. - The system prompt promises "no invented citations" with no retrieval layer behind it, while the category leader sells cited primary sources. - No age gate or parental-consent flow, in a product built for 14-22 year olds. Flagged for a lawyer (DPDP Act), not resolved here. Verdict caveats are stated in the pack: the panel is SIMULATED buyers and was emulated in one pass rather than by the one-sub-agent-per-buyer design the skill specifies, so the buy rate is a direction and not a measurement. Not financial, legal or tax advice. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
…ence
F9 fixed the 503 by metering machine callers on the claims table instead of
ai_usage_daily — but only on REQUEST COUNT. `responseMode` and `maxTokens`
arrive in the caller's own body and were passed straight to the router, so a
paying bot could ask for `max` and receive up to 12,000 Kimi K3 completion
tokens for the $0.05 x402 price.
At the published rates (Sep-Oct 2026):
Max (Kimi K3, $3/M in, $15/M out): 3,000 in + 12,000 out = $0.189
-> 3.8x the price. At the 60-request daily cap that is ~$8.30 of
net loss per bot per day, and the number of bots is unbounded.
Thorough (GLM-5.3-Flash, $0.15/M in, $0.50/M out): 10,000 in + 8,000 out
= $0.0055 -> 89% margin.
No completion length makes $0.05 cover the Max path, so a machine caller is
never routed to it. `grantedResponseLimits()` fixes the mode to what the price
covers and caps the completion ceiling inside it, honouring a smaller request
and never widening a larger one. Human callers are passed through untouched —
the 300k-token ledger is what bounds them.
The provider call now uses the GRANTED limits, not the client's body, which is
the part that actually closes the hole.
Tests: 9 new cases in tests/x402-machine-limits.test.ts, including one that
asserts the COST BOUND at the published rates so raising the ceiling without
raising the price fails the suite. Wired into main.yml's offline guard step
beside the payment suite.
Verified: 102 tests / 100 pass, 2 fail (both the known sandbox facilitator
egress failures); tsc clean; eslint 0 errors (5 pre-existing warnings);
manifests OK; both workflows valid YAML and their tripwires pass.
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
A new account gets 3 days of full access as soon as it joins, granted
automatically on its first authenticated request.
Granted once, ever. `start_free_trial` inserts only when no entitlements row
exists for the uid (`on conflict (uid) do nothing`, uid being the primary key),
so a user cannot let the trial expire and collect another one. Expired rows are
never deleted and `trial_started_at` survives a later paid grant, so the marker
outlives the access it granted. The RPC is security definer and service_role
only. It runs behind requireUser(), so it costs a verified email address.
Unlimited prompts, bounded cost — the one place the feature is narrower than
"unlimited", deliberately:
* requests are uncapped (reserve_ai_usage treats requestCap 0 as no limit),
which is what makes the trial genuinely unlimited to a person;
* a finite AI_TRIAL_DAILY_TOKEN_CAP keeps an abusive account bounded;
* Max is downgraded to Thorough. On the cheap model a million tokens/day is
~Rs 44; the same budget on Kimi K3 is ~Rs 1,320. The workspace defaults to
Quick, so the trial loses nothing in experience, and Max becomes a genuine
reason to pay.
Unlimited-with-no-ceiling was not implemented on purpose: it is a free,
scriptable, resellable LLM endpoint at ~Rs 13.86 per Max request.
Also closes a hole this feature would otherwise have opened: create-order
resolves the amount it charges through getPlan(), so the trial plan is kept out
of the purchasable catalogue and reachable only via getPlanForDisplay(). Adding
it to plans[], or aliasing "trial" into getPlan(), would let a caller buy a Rs 0
order and grant themselves access. Pinned by test and by SEC-API-05.
UX: the landing hero advertises the trial, the entitlement banner shows days
left with a "Choose a plan" CTA, and the pricing page says the trial is active
and that remaining trial days stack onto a purchased pass (which is what
grant_entitlement_atomic actually does).
Verified: 119 tests / 117 pass, 2 fail (both the known sandbox facilitator
egress failures); 17 new trial cases. tsc clean; eslint 0 errors (5 pre-existing
warnings); next build compiled successfully; manifests OK. CI: the new suite is
wired into main.yml's offline guard step, with tripwires in ai-safety.yml.
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
…-app Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Skipping CodeAnt AI review — this PR changes more than 100 files, which usually means a migration, codemod, or vendored drop. Line-level review on diffs this large produces duplicate findings on the same rewrite pattern and drowns out anything that actually matters. If you still want a review, comment |
CodeQL flagged three alerts in research/x402/poc/ on PR #12. They are in analysis fixtures rather than shipped code, and they are fixed here rather than dismissed, because a dismissed alert hides the reasoning and this keeps the evidence files honest and reviewable. priv.mjs (2 findings) - The logging proxy forwarded whatever path it was given to the local facilitator. It now forwards exactly /supported, /verify and /settle, each as a string literal in a map, so no caller-controlled value reaches the upstream URL. This is a narrower and more correct fixture either way: a general forwarding proxy is not something you want sitting on a port, even on localhost. - An upstream failure echoed the exception to the caller; it is now logged locally and reported as "upstream_unreachable" with no internal detail. facilitator.js (1 finding) - CodeQL's missing-rate-limiting query reads the SDK call facilitator.verify(...) as an authorization check, so the /verify route was reported as authorizing without throttling. That is a name-based false positive, but the remedy is legitimate rather than cosmetic: a real facilitator exposes /verify and /settle to the internet and should throttle them, so the mock now carries a small in-memory limiter on both. The PoCs' behaviour is otherwise unchanged, and the README note is updated to match. Syntax-checked with `node --check`; the scripts cannot be executed here because their dependencies are not installed in this sandbox, and their companion lockfile is intentionally untracked.
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 381 |
| Duplication | 4 |
NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.
The previous commit added a hand-rolled in-memory limiter to the mock facilitator's /verify and /settle routes. CodeQL still reported js/missing-rate-limiting against /verify: the query recognises rate limiting by library middleware, and a bespoke helper does not count, however correct it is. This replaces it with express-rate-limit as app-level middleware registered before the routes, which is both the idiomatic Express shape and the one the query understands. The ceiling is 600/min because every PoC request arrives from 127.0.0.1 and shares one bucket; header validations are left at their defaults, which is safe here because no PoC script sends X-Forwarded-For to the facilitator (headers.mjs targets the merchant on :4198). express-rate-limit is pinned to 8.7.1 exactly, per AGENTS.md. Its peer range is express >= 4.11, satisfied by the fixture's express ^4.21.2. The underlying finding is still a name-based false positive — CodeQL reads the SDK call facilitator.verify(...) as an authorization check, and it is a payment-payload validation — but throttling a facilitator's credential-facing routes is right for a real deployment too, so the fixture now shows that.
Codacy reported one new high-severity security issue on this PR. Its dashboard
is not reachable from this environment, so the finding cannot be read directly,
but the shape is unambiguous: eight added files each carried a literal private
key, which a secret scanner cannot distinguish from a leaked credential.
The key was the publicly documented Anvil/Hardhat test-account key — worthless,
and not a real credential. It is removed regardless. A repository should not
carry the pattern at all, even as a false positive, and a fixture that mints its
own account cannot silently come to depend on one that has been funded, drained
or reused elsewhere.
key.mjs now exports a single POC_PRIVATE_KEY, generated at startup unless
POC_PRIVATE_KEY is set — which keeps a specific run reproducible for anyone
re-running the §3 experiments. No script depended on the payer's address:
nothing in the testbed inspects it, and the facilitator verifies each signature
against whatever `from` the payload carries.
Every script is syntax-checked. They cannot be executed here because their
dependencies are not installed in this sandbox, so the call sites were verified
by inspection instead — which caught a mistake in the first pass of this edit,
where the replacement left the surrounding quotes in place and produced
privateKeyToAccount("POC_PRIVATE_KEY") as a string literal.
…ect key Codacy's one new high-severity finding on PR #12 is research/x402/poc/server.js:54, security/detect-object-injection on stats.handlerRuns[key] = (stats.handlerRuns[key] || 0) + 1; Reading the finding was the hard part. Codacy's dashboard rejects this environment (403 via the API, curl exit 35 against the domain), but its check-run does publish annotations, which is where the file and line came from. The earlier guess — that the eight hardcoded Anvil keys were the issue — was wrong, and the guard against it is still worth keeping; this one was simply a different alert. The counter map is a Map now instead of an object, so no value ever reaches a computed property key. The key is always a literal at the call sites ("cheap", "twin", "expensive", "sideeffect"), so this cannot be exploited today, but a fixture modelling a payment server should not carry the pattern at all: that shape is how prototype pollution is introduced when a route name later becomes caller-controlled. /stats keeps the exact JSON contract the attack scripts read (after.handlerRuns.cheap ?? 0 at attack-v1.mjs:86, twin at :101, sideeffect at :132), via an explicit snapshot() that flattens the Map — a bare res.json(stats) would serialize a Map to {} and silently break every measurement. Verified by executing the fixture rather than by inspection: the file was run against stubbed express/@x402 modules, the four routes exercised, and /stats asserted byte-identical to the previous object-backed output. This is the one place in the PoC directory where a shape change would corrupt the numbers the x402 write-up rests on.
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Five commits: a security remediation, a fix to that remediation, a new free trial, and the business-plan run that prompted them. The x402 and trial work is code; the founder pack is documentation.
1. Free trial — three days for every new account
An account gets 3 days of full access, granted automatically on its first authenticated request (not at signup, so trial days are not spent waiting for email verification).
Granted once, ever. Recorded by the existence of an
entitlementsrow, andstart_free_trialinserts only when no row exists for that uid (on conflict (uid) do nothing, uid being the primary key). Expired rows are never deleted, andtrial_started_atsurvives a later paid grant, so the marker outlives the access it granted.security definer,service_roleonly.Unlimited prompts, bounded cost. This is the one place the feature is deliberately narrower than "unlimited", and it is a decision worth reviewing:
reserve_ai_usagetreats a request cap of 0 as no limit);AI_TRIAL_DAILY_TOKEN_CAP(default 1,000,000) bounds an abusive account;Unlimited with no ceiling was not implemented: it is a free, scriptable, resellable LLM endpoint at ~₹13.86 per Max request. Worst case for one abusive trial account is ~₹132 across the full three days.
Residual risk accepted: a second email address buys a second trial. The gate is email verification plus existing signup limits, not identity.
2. x402 payment hardening (F1–F11)
ai_usage_dailyand onto the claims table, but only for request count —responseModeandmaxTokensarrive in the caller's own body, so a $0.05 payment could buy ~$0.19 of Kimi K3 inference (3.8× the price, ~$8.30 of net loss per bot per day at the 60-request cap).grantedResponseLimits()now fixes the mode to what the price covers; the provider call uses the granted limits, not the client's.3. Founder-pack run (
founder/)Eleven skills run against this business, compiled by the pack's own
compile.pyintofounder/business-plan.md. Verdict: Not yet — three of four computed checks pass; the buyer panel falls short at 22% against a 25% bar.founder/one-pager.mdis the two-minute version. It also found the two things now fixed above (the Max-mode cost hole, and that the product had no way for a visitor to see anything before paying).This adds 67 files of planning documentation. Drop the commit if you would rather keep the repo code-only.
Deployment note — apply the migration
supabase/migrations/20261013_free_trial.sqlmust be run before this code reaches users, otherwise new accounts are paywalled instead of trialled. That is a safe failure, not a broken one:ensureTrialEntitlementnever throws, existing paying users short-circuit before the RPC is reached, and a missing RPC just means no trial. Please test the grant-once rule on a staging project by calling the RPC twice and confirming the second returnsgranted = false.Verification
node scripts/check-commit-identity.mjs— passes. Note: the first two commits were authoredagent@arena.ai, which this repo denies; history was rewritten to the owner's no-reply address per AGENTS.md, and the tree content is byte-identical.tscclean;eslint0 errors (5 pre-existing warnings);next buildcompiles; manifests OK; all workflows valid YAML.Caveats