Skip to content
Merged
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
18 changes: 16 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ NVIDIA_API_KEY=
NVIDIA_KIMI_MODEL=moonshotai/kimi-k3
NVIDIA_RESEARCH_MODEL=z-ai/glm-5-3-flash

# Free trial — three days of access granted once, automatically, to a new
# account (see supabase/migrations/20261013_free_trial.sql).
# How many days the trial lasts. Bounded 1-30 to match the grant RPC.
AI_FREE_TRIAL_DAYS=3
# Daily token budget for a trialling account. Requests are UNLIMITED during the
# trial (that is the feature); this is the cost ceiling that stops a script
# turning a free account into an unbounded inference bill. A person prepping
# hard for a conference uses well under this, so it binds only on abuse.
AI_TRIAL_DAILY_TOKEN_CAP=1000000

# Admin session auth
# ADMIN_SESSION_SECRET must be at least 32 random bytes
ADMIN_SESSION_SECRET=
Expand All @@ -28,8 +38,12 @@ UROPAY_ALLOWED_HOSTS=api.uropai.in,uropai.in,www.uropai.in,checkout.uropai.in
NEXT_PUBLIC_SITE_URL=https://mun-ai-app.vercel.app

# x402 Machine-to-Machine Payments (AI agents & crawler microtransactions)
# Merchant EVM wallet address to receive bot micro-payments (USDC)
X402_PAY_TO=0x0000000000000000000000000000000000000000
# Merchant EVM wallet address to receive bot micro-payments (USDC).
# REQUIRED, with no usable default: a missing, malformed, zero, or placeholder
# address now closes the paid routes with a 503 instead of quietly advertising an
# address nobody controls. Replace this with YOUR wallet before enabling x402.
# Example shape: X402_PAY_TO=0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed
X402_PAY_TO=
# Target EVM network: eip155:84532 (Base Sepolia testnet) or eip155:8453 (Base mainnet)
X402_NETWORK=eip155:84532
# Facilitator service URL (defaults to https://x402.org/facilitator)
Expand Down
14 changes: 14 additions & 0 deletions .github/workflows/ai-safety.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,18 @@ jobs:
grep -rq "reserved_tokens" supabase/migrations || fail "reservation ledger column missing from migrations"
grep -q "upstream.abort" lib/ai/nvidia.ts || fail "client cancellation is not propagated to the provider request"
grep -q "getClientIp" app/api/ai/research/route.ts || fail "AI route does not use server-resolved client IP"
# Free trial: unlimited prompts, bounded cost, granted exactly once.
# The trial must stay out of the purchasable catalogue, because
# create-order resolves the amount it charges through getPlan().
grep -q "export function getPlanForDisplay" lib/plans.ts || fail "trial display resolver is missing"
grep -q "FREE_TRIAL_PLAN_ID" lib/plans.ts || fail "trial plan id is missing"
grep -q "start_free_trial" supabase/migrations/20261013_free_trial.sql || fail "trial grant RPC is missing"
grep -q "on conflict (uid) do nothing" supabase/migrations/20261013_free_trial.sql || fail "trial grant is not once-only"
grep -q "revoke all on function public.start_free_trial" supabase/migrations/20261013_free_trial.sql || fail "trial RPC is reachable from the browser"
grep -q "trialUsageLimits" app/api/ai/research/route.ts || fail "AI route does not apply trial limits"
grep -q "requestCap: 0" lib/server/trial.ts || fail "trial no longer lifts the request cap"
grep -q "trialDailyTokenCap" lib/server/trial.ts || fail "trial has no token ceiling"
grep -q "TRIAL_MAX_RESPONSE_MODE" lib/server/x402-machine-limits.ts || fail "trial no longer clamps the paid model"
grep -q "resolveEntitlementWithTrial" app/api/me/entitlement/route.ts || fail "trial never starts"
grep -q "assertPaidAccessOrStartTrial" app/api/ai/research/route.ts || fail "AI route bypasses the trial gate"
echo "AI safety OK"
14 changes: 14 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,20 @@ jobs:
- name: Install dependencies from lockfile
run: pnpm install --frozen-lockfile

- name: Payment guard tests (behavioural, offline)
# The rest of `pnpm test` asserts against the live x402 facilitator and
# needs network egress, so it is not run here. These suites are fully
# offline and pin the payment invariants: one grant per authorization
# under concurrency, no grant when settlement reports success but the
# claim is already taken, fail-closed when the claim store is down, an
# over-budget machine caller refused without being charged, a paid
# machine request whose inference cost stays inside the price paid, and
# a free trial that cannot be bought, bought twice, or reach Max.
run: >-
pnpm exec node --import ./scripts/test-loader.mjs
--experimental-strip-types --test tests/x402-payment-guard.test.ts
tests/x402-machine-limits.test.ts tests/free-trial.test.ts

- name: Lint
run: pnpm lint

Expand Down
53 changes: 53 additions & 0 deletions .github/workflows/payments.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,56 @@ jobs:
grep -q "processReferralCommission" lib/server/payment-reconciliation.ts || fail "reconciliation does not repair commissions"
grep -q "requireAdmin" app/api/admin/reconcile-payments/route.ts || fail "reconciliation endpoint lacks admin gate"
echo "Payment lifecycle OK"

- name: x402 one-payment-one-grant guard
run: |
fail() { echo "FAIL: $1"; exit 1; }
grep -q "export async function fulfilX402Payment" lib/server/x402-fulfil.ts || fail "shared fulfilment pipeline is missing"
grep -q "export async function claimX402Payment" lib/server/x402-payment-guard.ts || fail "atomic claim primitive is missing"
grep -q "x402_payment_claims" supabase/migrations/20261012_x402_payment_guard.sql || fail "claim table migration is missing"
grep -q "payment_already_consumed" lib/server/x402-fulfil.ts || fail "replay rejection response is missing"
grep -q "payment_guard_unavailable" lib/server/x402-fulfil.ts || fail "fail-closed guard response is missing"
grep -q "assertValidPayTo" lib/server/x402-server.ts || fail "payout address validation is missing"
grep -q "X402_PAID_CONTENT_CACHE_CONTROL" lib/server/x402-server.ts || fail "paid-content cache policy is missing"
grep -q "applyPaidContentCachePolicy" app/api/x402/content/route.ts || fail "paid content is not marked non-cacheable"
grep -q "X402_PAID_CONTENT_CACHE_CONTROL" app/api/ai/research/route.ts || fail "paid AI responses are not marked non-cacheable"
# Every x402 handler must route through the shared pipeline, so a new
# paid route cannot re-implement settlement and lose the claim step.
if grep -rn "processSettlement" app/api --include='*.ts'; then fail "a route settles payments directly instead of using fulfilX402Payment"; fi
grep -q "fulfilX402Payment" app/api/ai/research/route.ts || fail "AI route bypasses the fulfilment pipeline"
grep -q "fulfilX402Payment" app/api/x402/content/route.ts || fail "content route bypasses the fulfilment pipeline"
# The machine-caller flag must be set in exactly one place, after the
# pipeline succeeded. The deleted fail-open branch set it unconditionally,
# so a second occurrence means that free-access path has come back.
flag_count=$(grep -rho "isX402Bot = true" app/api --include='*.ts' | wc -l | tr -d ' ')
echo "isX402Bot assignments: $flag_count"
[ "$flag_count" -eq 1 ] || fail "expected exactly 1 machine-caller flag assignment, found $flag_count"
# The placeholder payout default must never come back.
if grep -rn "0x0000000000000000000000000000000000000001" lib app --include='*.ts'; then fail "placeholder payout address default returned"; fi
# A $0.05 payment must not buy Kimi K3 inference. The clamp lives in
# one module and the provider call must use what it returns, not the
# caller's own responseMode/maxTokens.
grep -q "export function grantedResponseLimits" lib/server/x402-machine-limits.ts || fail "machine response limits module is missing"
grep -q "grantedResponseLimits" app/api/ai/research/route.ts || fail "AI route does not clamp machine callers to what they paid"
grep -q "responseMode: granted.responseMode" app/api/ai/research/route.ts || fail "provider call ignores the granted response mode"
grep -q "maxTokens: granted.maxTokens" app/api/ai/research/route.ts || fail "provider call ignores the granted token budget"
echo "x402 guard OK"

# This repo has no install-based CI job today, so the behavioural suite
# (`pnpm test`) is not executed here. These assertions pin that the
# invariants keep existing; they are textual tripwires, not proof of
# behaviour. To run the real suite:
# pnpm exec node --import ./scripts/test-loader.mjs \
# --experimental-strip-types --test tests/x402-payment-guard.test.ts
- name: x402 guard test suite is present and covers the invariants
run: |
fail() { echo "FAIL: $1"; exit 1; }
test -f tests/x402-payment-guard.test.ts || fail "guard test suite is missing"
grep -q "grants exactly one claim under concurrency" tests/x402-payment-guard.test.ts || fail "concurrency single-use test is missing"
grep -q "withholds the resource when settlement succeeds but the claim is taken" tests/x402-payment-guard.test.ts || fail "non-authoritative facilitator test is missing"
grep -q "fails closed without granting when the claim store is unreachable" tests/x402-payment-guard.test.ts || fail "store-outage fail-closed test is missing"
grep -q "refuses an over-budget machine caller before charging it" tests/x402-payment-guard.test.ts || fail "machine budget pre-settlement test is missing"
test -f tests/x402-machine-limits.test.ts || fail "machine limits test suite is missing"
grep -q "refuses the Max model no matter what the caller asks for" tests/x402-machine-limits.test.ts || fail "max-mode clamp test is missing"
grep -q "keeps worst-case cost for a machine request well under the price" tests/x402-machine-limits.test.ts || fail "inference cost-bound test is missing"
echo "x402 guard tests present"
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -222,3 +222,9 @@ config/jwt/*.pem
*.tar
*.gz
*.7z

# The x402 research PoC under research/x402/poc is a standalone offline harness.
# This repo is pnpm-only (see .github/workflows/dependency-audit.yml), so its npm
# lockfile must never be committed. Reinstall there with `npm install` at will;
# the result is regenerable and deliberately not tracked.
/research/x402/poc/package-lock.json
18 changes: 15 additions & 3 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,21 +148,33 @@ node -e "console.log(process.env.ADMIN_SESSION_SECRET?.length >= 32 ? 'secret le
* **SEC-API-02:** EVERY list endpoint MUST clamp pagination (`limit 1..100`, `page*pageSize` numeric-clamped) — see `app/api/chats/route.ts:12-15`, `app/api/c8f2x9/users/route.ts:31-32`.
* **SEC-API-03:** NEVER trust client-supplied identity fields. Certificate route MUST ignore client `name` and use `user.name/email` (`app/api/courses/[slug]/certificate/route.ts:13-17,93`).
* **SEC-API-04:** Dynamic route params MUST be allowlisted: `legal/[slug]` → `legalPages[slug]`, `status/[state]` → `states.has(state)`, referral paths → `REFERRAL_PATH_PATTERN`, partner tokens → `^[a-f0-9]{48}$`.
* **SEC-API-05:** A non-purchasable plan MUST NOT be resolvable by the checkout path. `getPlan()` returns purchasable plans only and is what `create-order` uses to decide an amount; `getPlanForDisplay()` may additionally resolve the free trial, for labelling. Adding the trial to `plans[]`, or aliasing an id into `getPlan()`, would let a caller buy a ₹0 order and grant themselves access.

### Current route matrix (re-verify on every new route)

| Route | Gate | Ownership |
|---|---|---|
| `api/ai/research` | `requireUser` (+admin fallback), `assertPaidAccess` | `loadOwnedChat` `.eq(id).eq(uid)` |
| `api/ai/research` | `requireUser` (+admin fallback), `assertPaidAccessOrStartTrial` | `loadOwnedChat` `.eq(id).eq(uid)` |
| `api/chats`, `api/chats/[id]` | `requireUser` | `.eq(uid)` + `storedChat.uid===uid` |
| `api/me`, `api/me/entitlement`, `api/profile` | `requireUser` | `uid:user.uid` upserts, `.eq(uid)` reads |
| `api/me`, `api/me/entitlement`, `api/profile` | `requireUser` (`/entitlement` also starts the one-time trial) | `uid:user.uid` upserts, `.eq(uid)` reads |
| `api/progress`, `api/progress/checkpoint` | `requireUser` | `.eq(uid).eq(course_slug)` |
| `api/payments/create-order`, `api/payments/status` | `requireUser` + limits | insert `uid:user.uid`; updates `.eq(id).eq(uid)` |
| `api/courses/[slug]/certificate` | `requireUser` + limit | `.eq(uid).eq(course_slug)` |
| `api/referrals/apply` | `requireUser` + limit | `applyReferralCodeToUser(user.uid, …)` |
| `api/admin/*`, `api/c8f2x9/*` | `requireAdmin` / `requireAdminOwner` | owner-only for mutations |
| `api/auth/*`, `api/news`, `api/referrals/capture`, `api/partner/applications`, `api/webhooks/uropay` | public by design (limits / HMAC / honeypot) | N/A — see their sections |

### Free trial access model

Three days of access, granted once per account, automatically, on the first authenticated request. Four properties hold it together — break any one and it becomes either an unlimited free product or an unbounded bill:

1. **Granted once, ever.** `start_free_trial` (`supabase/migrations/20261013_free_trial.sql`) inserts only when no `entitlements` row exists for the uid — `on conflict (uid) do nothing`, with `uid` the primary key. Expired rows are never deleted, so the marker outlives the access it granted and cannot be re-collected. `trial_started_at` keeps that fact durable even after a paid grant overwrites `plan_id`.
2. **Not callable from a browser.** The RPC is `security definer` with `revoke all ... from public, anon, authenticated` and `grant execute ... to service_role` only.
3. **Gated behind a confirmed email.** It is called only after `requireUser()`, which rejects unverified sessions — so a trial costs at least one verified address.
4. **Cost-bounded.** Unlimited *requests* (`requestCap: 0`), but a finite `AI_TRIAL_DAILY_TOKEN_CAP` and **no Max model**: `grantedResponseLimits("trial", …)` downgrades to `thorough`, because a million tokens/day on Kimi K3 is ~₹1,320 while the same budget on GLM-5.3-Flash is ~₹44. See `lib/server/x402-machine-limits.ts`.

**Residual risk, accepted knowingly:** a user with a second email address can take a second trial. The gate is email verification (plus the 5/10min per-IP signup limit and the honeypot), not identity — that is inherent to any free trial and the cost ceiling above bounds the downside. If trial abuse is ever observed, the next step is a device or payment-instrument signal, not a tighter token cap, which would only inconvenience honest users.

---

## 8. Supabase Row Level Security
Expand Down Expand Up @@ -291,7 +303,7 @@ Implementation: DB-backed `rpc(rate_limit_check)` + `getClientIp` (prefers `x-ve
| `auth/signup` | `signup:{ip}` | 5/10min (+honeypot) |
| `auth/reset-request`, `reset-password` | per-IP | 5/10min |
| `c8f2x9/login` | `admin-login:{ip}` | 5/min |
| `ai/research` | per-user + per-IP + daily ledger | 12/min/user, 30/min/IP, caps `AI_DAILY_REQUEST_CAP=60` / `AI_DAILY_TOKEN_CAP=300000` |
| `ai/research` | per-user + per-IP + daily ledger | 12/min/user, 30/min/IP, caps `AI_DAILY_REQUEST_CAP=60` / `AI_DAILY_TOKEN_CAP=300000`. A **free-trial** account (see below) has **no request cap** and a `AI_TRIAL_DAILY_TOKEN_CAP=1000000` ceiling instead |
| `payments/create-order` | user + IP | 10/5min |
| `payments/status` | user | throttled |
| `news` | `news:{ip}` | 30/min |
Expand Down
Loading
Loading