Repository navigation
Merge test to main: Agent Signup & Verify endpoints - #427
Conversation
* feat: add agent signup and verify endpoints Add POST /api/agents/signup and POST /api/agents/verify for programmatic agent onboarding without auth. Agent+ prefix emails get instant API keys; all others require email verification via 6-digit code stored in Privy custom_metadata. New files: - lib/agents/ — validators, handlers, email sender, prefix check - lib/privy/ — createPrivyUser, getPrivyUserByEmail, setPrivyCustomMetadata - app/api/agents/signup/route.ts and verify/route.ts - 5 test files (23 tests passing) Co-Authored-By: Paperclip <noreply@paperclip.ing> * fix(agents): address PR #396 review feedback (TDD) Correctness fixes (critical — caught by both CodeRabbit and cubic): - agentVerifyHandler: check insertApiKey error and return 500 when the DB write fails. Previously the handler would hand back a raw API key that was never persisted, leaving the caller with an unusable key. - agentVerifyHandler: treat a missing verification_expires_at as expired (fail-safe). The previous conditional meant any row with an absent expiry would have an immortal verification code. - agentSignupHandler: randomInt upper bound is exclusive, so 999999 was never generated. Use randomInt(100000, 1000000) to cover all 6-digit codes. - validateAgentVerifyBody: enforce the 6-digit format with .regex(/^\d{6}$/) so malformed codes fail at validation instead of consuming rate-limited verification attempts. SRP refactor (per @sweetmantech review comments): - Both agentSignupHandler and agentVerifyHandler now accept NextRequest directly and call safeParseJson + the validate function internally, matching the convention used by createApiKeyHandler and the rest of the codebase. - The route handlers at app/api/agents/{signup,verify}/route.ts are now one-line passthroughs. Test coverage: - agentSignupHandler tests updated to build NextRequests via a helper, plus new cases for validation failures and a randomInt argument assertion that locks in the inclusive upper bound. - agentVerifyHandler tests similarly updated, plus new cases for the missing-expiry fail-safe, the insertApiKey-error → 500 path, and validation failures for missing/non-numeric codes. - validateAgentVerifyBody gains regex tests for non-numeric, 5-digit, 7-digit, and whitespace-containing codes. All changes followed TDD red/green. Full suite: 1847/1847 passing. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(agents): SRP — one function per file, prerequisites in validate Addresses two @sweetmantech review comments: ## 1. SRP filename rule (PR comment #3068768028) Every private helper inside agentSignupHandler.ts was lifted into its own file (name matches function): - lib/agents/createAccountWithEmail.ts - lib/agents/generateAndStoreApiKey.ts - lib/agents/storeVerificationCode.ts - lib/agents/handleAgentPrefixSignup.ts - lib/agents/handleExistingAccount.ts - lib/agents/handleNormalSignup.ts agentSignupHandler.ts now just dispatches to one of the three path handlers after body validation. Behavior note: generateAndStoreApiKey now throws on insertApiKey error instead of silently returning a raw key that was never persisted. The agentVerifyHandler's outer try/catch converts that into a 500 (already covered by the existing "returns 500 when insertApiKey fails" test). The signup handler's outer catch converts it to the existing silent "generic message" response, which is pre-existing behavior for catastrophic signup failures. ## 2. Prerequisite checks live in validateAgentVerifyBody (PR comment #3068770022) validateAgentVerifyBody is now async and absorbs every prerequisite check for the verify flow: - Body shape (email + 6-digit code, zod) - Privy user lookup + custom_metadata presence - verification_code_hash present - verification_expires_at present and not expired (fail-safe) - verification_attempts under MAX_ATTEMPTS - Supplied code hash matches stored hash (increments attempts on miss) - Email resolves to an account On success it returns `{ accountId, privyUserId }`, so agentVerifyHandler collapses to: "if validation passed, issue an API key and clear Privy metadata." Exported type `ValidatedAgentVerifyRequest` documents the contract. ## Tests (TDD red/green for every change) New per-helper tests: - createAccountWithEmail.test.ts - generateAndStoreApiKey.test.ts (covers the new throw-on-error path) - storeVerificationCode.test.ts - handleAgentPrefixSignup.test.ts - handleExistingAccount.test.ts - handleNormalSignup.test.ts Expanded validateAgentVerifyBody.test.ts to exercise every prerequisite check (missing privy user, missing code hash, missing/past expiry, attempts limit, hash mismatch + attempt increment, no account, success). Full suite: 1860/1860 passing. Lint clean on every touched file. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(agents): consolidate validation, share helpers, security fix Addresses 5 review comments + 1 cubic-flagged correctness bug. ## SRP — validate functions own request parsing (sweetmantech #3068780503, #3068791367) Both validateAgentSignupBody and validateAgentVerifyBody now accept a NextRequest, call safeParseJson internally, and return either a NextResponse or the resolved data. The two route handlers no longer need to know about JSON parsing — they just call the validate function and react to the result. ## DRY — shared signup message constant (sweetmantech #3068791367) AGENT_SIGNUP_GENERIC_MESSAGE moved to lib/const.ts (matching the project convention for shared constants per CLAUDE.md). Imported by agentSignupHandler, handleAgentPrefixSignup, handleExistingAccount, and handleNormalSignup. Single source of truth — no more drift if the copy ever needs to change. ## SRP — extract errorResponse helper (sweetmantech #3068791609) New lib/networking/errorResponse.ts (with tests). Replaces the inline helper that previously lived inside validateAgentVerifyBody. General purpose: any handler can now import errorResponse(message, status) instead of inlining NextResponse.json + cors headers + status. Audited the codebase first — only `lib/segments/createSegmentResponses.ts` had a similar helper but with a different signature, so this is a net new shared utility. ## Security fix — drop assignAccountToOrg from agent signup (sweetmantech #3068790703) This was a real privilege-escalation hole. Because: 1. Agent signup is unauthenticated 2. The agent+ prefix path bypasses email verification 3. assignAccountToOrg auto-joins new accounts to any org whose verified domain matches the email's domain …anyone on the internet could `curl -d '{"email":"agent+x@<orgdomain>"}'` and instantly receive an API key whose account was joined to that org. For human signups this is fine because Privy gates email ownership; the agent path has no such gate. createAccountWithEmail no longer calls assignAccountToOrg. Org membership for agents must now be a deliberate post-signup admin step. Documented the reason inline so a future contributor doesn't re-add it. ## Correctness fix — check insertAccountEmail / insertCreditsUsage errors (cubic P1) Both helpers return null on DB failure. The previous version silently ignored the result, leaving the door open for an account to exist without an email link (which would break every subsequent email-based lookup) or without a credits row. createAccountWithEmail now throws on either failure so the caller's outer try/catch can respond appropriately. ## Tests - New: lib/networking/__tests__/errorResponse.test.ts (2 tests) - Updated: validateAgentSignupBody.test.ts now exercises the request-based signature, including malformed-JSON handling - Updated: validateAgentVerifyBody.test.ts switched all call sites to NextRequest via a buildRequest helper - Updated: createAccountWithEmail.test.ts asserts the throw-on-null behavior for both insert failures, and dropped the assignAccountToOrg expectation - Updated: agentSignupHandler.test.ts mocks insertAccountEmail and insertCreditsUsage to return non-null defaults so the new throws don't trip the existing happy-path tests Full suite: 1865/1865 passing. Format clean. Zero lint errors on touched files (lint count 702 → 700; remaining errors are pre-existing in files merged from `test`). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(agents): three production bugs caught by preview deployment testing Comprehensive curl testing of the preview deployment surfaced 4×500 responses on every code path that touches Privy or hashes a key. The Vercel runtime logs nailed two distinct exceptions; together with the Privy API docs they pin down three independent bugs, all of them pre-existing in this PR's original commits and none catchable by the unit tests. ## Bug 1: getPrivyUserByEmail body field name Privy's POST /v1/users/email/address expects `{ "address": "..." }`, but we were sending `{ "email": "..." }`. Privy responded: Failed to get Privy user by email: 400 {"error":"[Input error] `address`: Email address must be provided", "code":"invalid_data", ...} This explains the verify-endpoint 500s — the catch block was triggering, returning my generic "Internal server error" JSON. ## Bug 2: PROJECT_SECRET env var doesn't exist Three callers in the agent code were doing: hashApiKey(rawKey, process.env.PROJECT_SECRET!) But `PROJECT_SECRET` is not defined anywhere in the codebase. The `!` non-null assertion lied to TypeScript; at runtime it's `undefined`, and `crypto.createHmac("sha256", undefined)` throws: TypeError: The "key" argument must be of type string ... Received undefined code: 'ERR_INVALID_ARG_TYPE' Every other API key in the system is hashed with `PRIVY_PROJECT_SECRET` imported from `@/lib/const` (see `lib/keys/createKey.ts:18`, `lib/auth/getApiKeyAccountId.ts:31`, `lib/keys/getApiKeyDetails.ts:24`). The agent code was using a different secret. This was silently catastrophic in two ways: (a) the function would crash before issuing a key, and (b) even if PROJECT_SECRET *had* been set, the resulting key hashes wouldn't match the rest of the system — agent-issued keys would never authenticate against any other endpoint. Switched all three callers to import `PRIVY_PROJECT_SECRET` from `@/lib/const`: - lib/agents/generateAndStoreApiKey.ts - lib/agents/storeVerificationCode.ts - lib/agents/validateAgentVerifyBody.ts This explains the signup-endpoint 500s — the createHmac crash escaped the handler's catch (see Bug 3) and surfaced as an empty-body Vercel function-level error. ## Bug 3: agentSignupHandler returned unawaited promises return handleAgentPrefixSignup(email); return handleExistingAccount(...); return handleNormalSignup(email); In an async function, `return promise` causes the outer `try/catch` to NOT catch a rejection from that promise (the function has already yielded). Switched to `return await` so child-handler errors land in the outer catch and produce a clean 200-with-generic-message instead of a Vercel function crash. Without this fix, the createHmac error in Bug 2 would have surfaced as the empty-body 500 the testing comment described. With this fix, it would have at least been logged and returned the catch's generic message — making future bugs of the same shape easier to debug. ## Tests - New: `lib/privy/__tests__/getPrivyUserByEmail.test.ts` — asserts the URL, method, and that the body is `{ address: email }`. Set to RED first by calling the existing implementation, confirmed it failed with `expected "address" / received "email"`, then GREEN after the fix. - Updated: `lib/agents/__tests__/generateAndStoreApiKey.test.ts` — mocks `@/lib/const` and asserts `hashApiKey` is called with the imported `PRIVY_PROJECT_SECRET`. Set to RED first, confirmed it failed with `received undefined`, then GREEN after switching to the imported constant. Full suite: 1869/1869 passing. Format clean. Zero lint errors on touched files. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(agents): NaN-guard malformed expiry; 5xx on internal failure Two CodeRabbit findings on commit 2a9da14, both legitimate. ## Bug 1: malformed verification_expires_at silently bypasses expiry check (Critical) `new Date("garbage").getTime()` returns `NaN`. `Date.now() > NaN` is `false`. So a non-empty but malformed `verification_expires_at` would silently slip past the expiry comparison and let an old/invalid code proceed. Today the only writer is `storeVerificationCode`, which always sets a real ISO string, so this is theoretical — but the defense is load-bearing precisely *because* the writer might one day produce something else (corrupted data, schema migration, etc.). Added an explicit `Number.isNaN(expiresAt)` check that treats malformed values as expired. The TDD for this was instructive: the first version of the test passed for the wrong reason — without the NaN guard, the function fell through to the (mocked-undefined) `selectAccountByEmail` branch and returned 400 anyway. Tightening the test to mock `selectAccountByEmail` with a valid account exposed the silent bypass, producing a real RED, then GREEN after the guard. ## Bug 2: signup catch returns 200 instead of 5xx (Major) The catch in `agentSignupHandler` returned `200` with the generic `AGENT_SIGNUP_GENERIC_MESSAGE` body. The intent was to avoid email enumeration (the existing-account branch returns the same shape with `api_key: null`). The flaw is that 200 makes internal failures *indistinguishable* from successful signups: - Client retry behavior doesn't kick in (clients only retry on 5xx) - Monitoring dashboards see "200 OK" and don't alert - Debugging is hard because every response looks successful Switched to `500` while keeping the body shape generic. There's no enumeration risk because the body is the same as the existing-account success path — only the status code carries the failure signal. ## TDD - New test in `validateAgentVerifyBody.test.ts`: malformed expiry string + valid account mock → must return 400. RED first (function returned success), GREEN after the NaN guard. - New "internal failures" suite in `agentSignupHandler.test.ts`: `selectAccountByEmail` rejects → must return 500 with generic body. RED first (returned 200), GREEN after the status change. Full suite: 1871/1871 passing. Format clean. Zero lint errors on touched files. The third CodeRabbit finding (race-prone attempt counter at the same file lines) is acknowledged but architecturally blocked — Privy `custom_metadata` has no CAS primitive. Replied on the thread; the fix lives in the follow-up Privy refactor PR that moves OTP state to Supabase. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: CTO Agent <cto@recoup.ai> Co-authored-by: Paperclip <noreply@paperclip.ing> Co-authored-by: Sweets Sweetman <sweetmantech@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 14 minutes and 30 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (13)
📒 Files selected for processing (19)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Summary
Promotes the agent signup/verify work from `test` to `main` after PR #396 was merged + tested end-to-end against the preview deployment.
See PR #396 for the full review thread.
Test plan
Summary by cubic
Adds unauthenticated agent onboarding endpoints.
agent+emails get instant API keys; other emails go through a 6‑digit email verification flow.New Features
POST /api/agents/signup: instant API key for first-timeagent+emails; otherwise sends a verification code and returnsapi_key: null.POST /api/agents/verify: validates{ email, code }, issues an API key, and clears Privy verification metadata. Codes expire in 24h with a 5-attempt limit.Bug Fixes
{ address }(not{ email }); all hashing usesPRIVY_PROJECT_SECRET.Written for commit 1b77d2f. Summary will update on new commits.