Skip to content

Auth and session ​

TodoAI uses Web3 wallet signatures for identity verification, then issues a JWT in an httpOnly cookie after login.

Auth Flow

Login flow ​

1. MetaMask signs ​

Frontend calls signer.signMessage('Login to TodoAI: <timestamp>') — this is EIP-191 personal_sign, not an on-chain transaction

2. POST /api/user/login ​

Send { address, signature, message } to the backend

3. Verify signature ​

Server uses ethers.verifyMessage(message, signature) to recover the address and compares it with address (case-insensitive)

4. Upsert user ​

prisma.user.upsert({ where: { address } }) — first login auto-creates the account

5. Issue JWT ​

createSession(address, userId, tier) → HS256 JWT containing address / userId / subscriptionLevel

qt_session httpOnly + sameSite=lax + secure(production) + maxAge=24h

Two session paths ​

Resolving userId for subsequent requests splits into two:

getServerSession(req) — fast path ​

ts
const { payload } = await jwtVerify(cookie, getJwtSecret());
// Only verify signature, no DB call
return { userId, address, subscriptionLevel };

For:

  • Most IDOR-protected routes — /api/strategy/*, /api/backtest, /api/trade/panic
  • Any endpoint that just needs "which user is this"
  • High-QPS scenarios (saves a Prisma roundtrip per request)

requireFreshSession(req) — slow path ​

ts
const fast = await getServerSession(req);
const cachedTier = await tierCache.get(fast.address);
if (cachedTier) return { ...fast, subscriptionLevel: cachedTier };
// Cache miss → DB
const user = await prisma.user.findUnique({ where: { address } });

For — endpoints whose behavior may change with tier:

  • /api/strategy/reasoning/generate — FREE must be blocked
  • /api/payment/verify — must work immediately after a payment upgrade
  • /api/admin/* — admin downgrade must take effect immediately

Invariant: no user can stay on PRO because their JWT is stale. This is fail-closed.

Tier cache ​

The subscriptionLevel in the JWT is a snapshot at login time. Downgrades / upgrades do not reflect immediately. Endpoints that need 5-minute freshness must go through requireFreshSession.

Cache layer:

  • Production: Upstash Redis, key = qt:tier:<lowercase address>, TTL 5 minutes
  • Development / single-instance: Map + in-memory TTL
  • Without Redis config, automatically falls back to in-process mode

When an admin downgrades a user's tier, call clearTierCache(address) to invalidate the cache immediately (already added, see src/lib/session.ts).

Security invariants ​

userId is always read from session ​

Never read userId from query string or POST body. This is the foundation of the PR1–PR3 IDOR defense.

ts
// ✅ Correct
const session = await getServerSession(request);
const userId = session.userId;

// ❌ Wrong — DO NOT DO
const { userId } = await request.json();
const userId = new URL(req.url).searchParams.get('userId');

New routes must use session.userId, never trust a client-supplied userId.

JWT_SECRET and ENCRYPTION_KEY must be independent ​

src/lib/session.ts::getJwtSecret() in production mode forces JWT_SECRET to exist, and to be different from ENCRYPTION_KEY (reusing would be a critical auth vulnerability).

Generate both with openssl rand -hex 32:

bash
openssl rand -hex 32  # → ENCRYPTION_KEY
openssl rand -hex 32  # → JWT_SECRET (separate!)

Rate limiting ​

/api/user/login is rate-limited to 5/minute/IP to prevent signature brute-force. src/lib/rate-limit.ts provides:

ts
const ip = request.headers.get('x-forwarded-for')?.split(',')[0];
if (isRouteRateLimited('auth:login', ip, ...)) {
  return 429 with Retry-After header;
}

Chain check (soft) ​

UserContext.login() reads provider.getNetwork() before signing and console.warns on unknown chainIds. It does not block login — because TodoAI's actual trading happens on CEX (OKX), chain ID is irrelevant to the signature itself.

Hard chain check lives in pricing/page.tsx for the BSC payment flow — there we need eth_sendTransaction, so we must wallet_switchEthereumChain + waitForChainSettle first.

TodoAI · Turn trading ideas into automated strategies