From 0ac00a50f9e7278a5cf281290ae39840e0f85ae0 Mon Sep 17 00:00:00 2001 From: CTO Agent Date: Mon, 6 Apr 2026 03:01:12 +0000 Subject: [PATCH 1/6] feat: add agent signup and verify endpoints MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- app/api/agents/signup/route.ts | 45 +++++ app/api/agents/verify/route.ts | 44 +++++ .../__tests__/agentSignupHandler.test.ts | 116 +++++++++++++ .../__tests__/agentVerifyHandler.test.ts | 136 +++++++++++++++ .../__tests__/isAgentPrefixEmail.test.ts | 20 +++ .../__tests__/validateAgentSignupBody.test.ts | 33 ++++ .../__tests__/validateAgentVerifyBody.test.ts | 34 ++++ lib/agents/agentSignupHandler.ts | 158 ++++++++++++++++++ lib/agents/agentVerifyHandler.ts | 111 ++++++++++++ lib/agents/isAgentPrefixEmail.ts | 9 + lib/agents/sendVerificationEmail.ts | 21 +++ lib/agents/validateAgentSignupBody.ts | 36 ++++ lib/agents/validateAgentVerifyBody.ts | 37 ++++ lib/privy/createPrivyUser.ts | 26 +++ lib/privy/getPrivyUserByEmail.ts | 30 ++++ lib/privy/setPrivyCustomMetadata.ts | 25 +++ 16 files changed, 881 insertions(+) create mode 100644 app/api/agents/signup/route.ts create mode 100644 app/api/agents/verify/route.ts create mode 100644 lib/agents/__tests__/agentSignupHandler.test.ts create mode 100644 lib/agents/__tests__/agentVerifyHandler.test.ts create mode 100644 lib/agents/__tests__/isAgentPrefixEmail.test.ts create mode 100644 lib/agents/__tests__/validateAgentSignupBody.test.ts create mode 100644 lib/agents/__tests__/validateAgentVerifyBody.test.ts create mode 100644 lib/agents/agentSignupHandler.ts create mode 100644 lib/agents/agentVerifyHandler.ts create mode 100644 lib/agents/isAgentPrefixEmail.ts create mode 100644 lib/agents/sendVerificationEmail.ts create mode 100644 lib/agents/validateAgentSignupBody.ts create mode 100644 lib/agents/validateAgentVerifyBody.ts create mode 100644 lib/privy/createPrivyUser.ts create mode 100644 lib/privy/getPrivyUserByEmail.ts create mode 100644 lib/privy/setPrivyCustomMetadata.ts diff --git a/app/api/agents/signup/route.ts b/app/api/agents/signup/route.ts new file mode 100644 index 000000000..dfd2846c7 --- /dev/null +++ b/app/api/agents/signup/route.ts @@ -0,0 +1,45 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { safeParseJson } from "@/lib/networking/safeParseJson"; +import { + validateAgentSignupBody, + type AgentSignupBody, +} from "@/lib/agents/validateAgentSignupBody"; +import { agentSignupHandler } from "@/lib/agents/agentSignupHandler"; + +/** + * POST /api/agents/signup + * + * Register an agent. For new agent+ emails, returns an API key immediately. + * For all other cases, sends a verification code to the email. + * This endpoint is unauthenticated. + * + * @param req - The incoming request with email in body + * @returns Signup response with account_id, api_key (or null), and message + */ +export async function POST(req: NextRequest) { + const body = await safeParseJson(req); + + const validated = validateAgentSignupBody(body); + if (validated instanceof NextResponse) { + return validated; + } + + return agentSignupHandler(validated as AgentSignupBody); +} + +/** + * OPTIONS handler for CORS preflight requests. + * + * @returns NextResponse with CORS headers + */ +export async function OPTIONS() { + return new NextResponse(null, { + status: 204, + headers: getCorsHeaders(), + }); +} + +export const dynamic = "force-dynamic"; +export const fetchCache = "force-no-store"; +export const revalidate = 0; diff --git a/app/api/agents/verify/route.ts b/app/api/agents/verify/route.ts new file mode 100644 index 000000000..f634bb7c3 --- /dev/null +++ b/app/api/agents/verify/route.ts @@ -0,0 +1,44 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { safeParseJson } from "@/lib/networking/safeParseJson"; +import { + validateAgentVerifyBody, + type AgentVerifyBody, +} from "@/lib/agents/validateAgentVerifyBody"; +import { agentVerifyHandler } from "@/lib/agents/agentVerifyHandler"; + +/** + * POST /api/agents/verify + * + * Verify an agent's email with the code sent during signup. + * Returns an API key on success. This endpoint is unauthenticated. + * + * @param req - The incoming request with email and code in body + * @returns Verify response with account_id, api_key, and message + */ +export async function POST(req: NextRequest) { + const body = await safeParseJson(req); + + const validated = validateAgentVerifyBody(body); + if (validated instanceof NextResponse) { + return validated; + } + + return agentVerifyHandler(validated as AgentVerifyBody); +} + +/** + * OPTIONS handler for CORS preflight requests. + * + * @returns NextResponse with CORS headers + */ +export async function OPTIONS() { + return new NextResponse(null, { + status: 204, + headers: getCorsHeaders(), + }); +} + +export const dynamic = "force-dynamic"; +export const fetchCache = "force-no-store"; +export const revalidate = 0; diff --git a/lib/agents/__tests__/agentSignupHandler.test.ts b/lib/agents/__tests__/agentSignupHandler.test.ts new file mode 100644 index 000000000..9a290415a --- /dev/null +++ b/lib/agents/__tests__/agentSignupHandler.test.ts @@ -0,0 +1,116 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { agentSignupHandler } from "@/lib/agents/agentSignupHandler"; + +import { selectAccountByEmail } from "@/lib/supabase/account_emails/selectAccountByEmail"; +import { insertAccount } from "@/lib/supabase/accounts/insertAccount"; +import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; + +vi.mock("@/lib/networking/getCorsHeaders", () => ({ + getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })), +})); + +vi.mock("@/lib/supabase/account_emails/selectAccountByEmail", () => ({ + selectAccountByEmail: vi.fn(), +})); + +vi.mock("@/lib/supabase/accounts/insertAccount", () => ({ + insertAccount: vi.fn(), +})); + +vi.mock("@/lib/supabase/account_emails/insertAccountEmail", () => ({ + insertAccountEmail: vi.fn(), +})); + +vi.mock("@/lib/supabase/credits_usage/insertCreditsUsage", () => ({ + insertCreditsUsage: vi.fn(), +})); + +vi.mock("@/lib/organizations/assignAccountToOrg", () => ({ + assignAccountToOrg: vi.fn(), +})); + +vi.mock("@/lib/keys/generateApiKey", () => ({ + generateApiKey: vi.fn(() => "recoup_sk_test123"), +})); + +vi.mock("@/lib/keys/hashApiKey", () => ({ + hashApiKey: vi.fn(() => "hashed_key"), +})); + +vi.mock("@/lib/supabase/account_api_keys/insertApiKey", () => ({ + insertApiKey: vi.fn(() => ({ data: {}, error: null })), +})); + +vi.mock("@/lib/privy/createPrivyUser", () => ({ + createPrivyUser: vi.fn(() => ({ id: "privy_user_123" })), +})); + +vi.mock("@/lib/privy/getPrivyUserByEmail", () => ({ + getPrivyUserByEmail: vi.fn(), +})); + +vi.mock("@/lib/privy/setPrivyCustomMetadata", () => ({ + setPrivyCustomMetadata: vi.fn(), +})); + +vi.mock("@/lib/agents/sendVerificationEmail", () => ({ + sendVerificationEmail: vi.fn(), +})); + +describe("agentSignupHandler", () => { + beforeEach(() => { + vi.clearAllMocks(); + process.env.PROJECT_SECRET = "test-secret"; + }); + + describe("agent+ prefix email (new account)", () => { + it("returns api_key immediately for new agent+ email", async () => { + vi.mocked(selectAccountByEmail).mockResolvedValue(null); + vi.mocked(insertAccount).mockResolvedValue({ id: "acc_123" } as unknown as Awaited< + ReturnType + >); + + const result = await agentSignupHandler({ email: "agent+bot@example.com" }); + const body = await result.json(); + + expect(result.status).toBe(200); + expect(body.account_id).toBe("acc_123"); + expect(body.api_key).toBe("recoup_sk_test123"); + expect(body.message).toBeTruthy(); + }); + }); + + describe("existing account", () => { + it("sends verification code and returns null api_key", async () => { + vi.mocked(selectAccountByEmail).mockResolvedValue({ + account_id: "acc_existing", + email: "user@example.com", + } as unknown as Awaited>); + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ id: "privy_456" }); + + const result = await agentSignupHandler({ email: "user@example.com" }); + const body = await result.json(); + + expect(result.status).toBe(200); + expect(body.account_id).toBe("acc_existing"); + expect(body.api_key).toBeNull(); + }); + }); + + describe("normal email (new account)", () => { + it("creates account and sends verification code", async () => { + vi.mocked(selectAccountByEmail).mockResolvedValue(null); + vi.mocked(insertAccount).mockResolvedValue({ id: "acc_new" } as unknown as Awaited< + ReturnType + >); + vi.mocked(getPrivyUserByEmail).mockResolvedValue(null); + + const result = await agentSignupHandler({ email: "user@example.com" }); + const body = await result.json(); + + expect(result.status).toBe(200); + expect(body.account_id).toBe("acc_new"); + expect(body.api_key).toBeNull(); + }); + }); +}); diff --git a/lib/agents/__tests__/agentVerifyHandler.test.ts b/lib/agents/__tests__/agentVerifyHandler.test.ts new file mode 100644 index 000000000..d004f3660 --- /dev/null +++ b/lib/agents/__tests__/agentVerifyHandler.test.ts @@ -0,0 +1,136 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { agentVerifyHandler } from "@/lib/agents/agentVerifyHandler"; + +import { selectAccountByEmail } from "@/lib/supabase/account_emails/selectAccountByEmail"; +import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; +import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; + +vi.mock("@/lib/networking/getCorsHeaders", () => ({ + getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })), +})); + +vi.mock("@/lib/supabase/account_emails/selectAccountByEmail", () => ({ + selectAccountByEmail: vi.fn(), +})); + +vi.mock("@/lib/keys/generateApiKey", () => ({ + generateApiKey: vi.fn(() => "recoup_sk_verified123"), +})); + +vi.mock("@/lib/keys/hashApiKey", () => ({ + hashApiKey: vi.fn((input: string) => `hashed_${input}`), +})); + +vi.mock("@/lib/supabase/account_api_keys/insertApiKey", () => ({ + insertApiKey: vi.fn(() => ({ data: {}, error: null })), +})); + +vi.mock("@/lib/privy/getPrivyUserByEmail", () => ({ + getPrivyUserByEmail: vi.fn(), +})); + +vi.mock("@/lib/privy/setPrivyCustomMetadata", () => ({ + setPrivyCustomMetadata: vi.fn(), +})); + +describe("agentVerifyHandler", () => { + beforeEach(() => { + vi.clearAllMocks(); + process.env.PROJECT_SECRET = "test-secret"; + }); + + it("returns api_key on correct code", async () => { + const codeHash = "hashed_123456"; + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ + id: "privy_123", + custom_metadata: { + verification_code_hash: codeHash, + verification_expires_at: new Date(Date.now() + 60000).toISOString(), + verification_attempts: 0, + }, + }); + vi.mocked(selectAccountByEmail).mockResolvedValue({ + account_id: "acc_123", + email: "user@example.com", + } as unknown as Awaited>); + + const result = await agentVerifyHandler({ email: "user@example.com", code: "123456" }); + const body = await result.json(); + + expect(result.status).toBe(200); + expect(body.account_id).toBe("acc_123"); + expect(body.api_key).toBe("recoup_sk_verified123"); + expect(body.message).toBe("Verified"); + expect(setPrivyCustomMetadata).toHaveBeenCalledWith("privy_123", {}); + }); + + it("returns 400 for wrong code", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ + id: "privy_123", + custom_metadata: { + verification_code_hash: "hashed_correct_code", + verification_expires_at: new Date(Date.now() + 60000).toISOString(), + verification_attempts: 0, + }, + }); + + const result = await agentVerifyHandler({ email: "user@example.com", code: "wrong" }); + + expect(result.status).toBe(400); + expect(setPrivyCustomMetadata).toHaveBeenCalledWith( + "privy_123", + expect.objectContaining({ + verification_attempts: 1, + }), + ); + }); + + it("returns 429 after 5 failed attempts", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ + id: "privy_123", + custom_metadata: { + verification_code_hash: "hashed_code", + verification_expires_at: new Date(Date.now() + 60000).toISOString(), + verification_attempts: 5, + }, + }); + + const result = await agentVerifyHandler({ email: "user@example.com", code: "123456" }); + + expect(result.status).toBe(429); + }); + + it("returns 400 for expired code", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ + id: "privy_123", + custom_metadata: { + verification_code_hash: "hashed_123456", + verification_expires_at: new Date(Date.now() - 1000).toISOString(), + verification_attempts: 0, + }, + }); + + const result = await agentVerifyHandler({ email: "user@example.com", code: "123456" }); + + expect(result.status).toBe(400); + }); + + it("returns 400 when no privy user found", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue(null); + + const result = await agentVerifyHandler({ email: "user@example.com", code: "123456" }); + + expect(result.status).toBe(400); + }); + + it("returns 400 when no verification code stored", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ + id: "privy_123", + custom_metadata: {}, + }); + + const result = await agentVerifyHandler({ email: "user@example.com", code: "123456" }); + + expect(result.status).toBe(400); + }); +}); diff --git a/lib/agents/__tests__/isAgentPrefixEmail.test.ts b/lib/agents/__tests__/isAgentPrefixEmail.test.ts new file mode 100644 index 000000000..a995f6239 --- /dev/null +++ b/lib/agents/__tests__/isAgentPrefixEmail.test.ts @@ -0,0 +1,20 @@ +import { describe, it, expect } from "vitest"; +import { isAgentPrefixEmail } from "@/lib/agents/isAgentPrefixEmail"; + +describe("isAgentPrefixEmail", () => { + it("returns true for agent+ prefix email", () => { + expect(isAgentPrefixEmail("agent+mybot@example.com")).toBe(true); + }); + + it("returns true for uppercase agent+ prefix", () => { + expect(isAgentPrefixEmail("Agent+MyBot@example.com")).toBe(true); + }); + + it("returns false for normal email", () => { + expect(isAgentPrefixEmail("user@example.com")).toBe(false); + }); + + it("returns false for email containing agent but not as prefix", () => { + expect(isAgentPrefixEmail("my-agent@example.com")).toBe(false); + }); +}); diff --git a/lib/agents/__tests__/validateAgentSignupBody.test.ts b/lib/agents/__tests__/validateAgentSignupBody.test.ts new file mode 100644 index 000000000..562a5842b --- /dev/null +++ b/lib/agents/__tests__/validateAgentSignupBody.test.ts @@ -0,0 +1,33 @@ +import { describe, it, expect } from "vitest"; +import { NextResponse } from "next/server"; +import { validateAgentSignupBody } from "@/lib/agents/validateAgentSignupBody"; + +describe("validateAgentSignupBody", () => { + it("returns validated body for valid email", () => { + const result = validateAgentSignupBody({ email: "agent+test@example.com" }); + expect(result).toEqual({ email: "agent+test@example.com" }); + }); + + it("returns validated body for normal email", () => { + const result = validateAgentSignupBody({ email: "user@example.com" }); + expect(result).toEqual({ email: "user@example.com" }); + }); + + it("returns 400 for missing email", () => { + const result = validateAgentSignupBody({}); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + + it("returns 400 for invalid email", () => { + const result = validateAgentSignupBody({ email: "not-an-email" }); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + + it("returns 400 for empty body", () => { + const result = validateAgentSignupBody(null); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); +}); diff --git a/lib/agents/__tests__/validateAgentVerifyBody.test.ts b/lib/agents/__tests__/validateAgentVerifyBody.test.ts new file mode 100644 index 000000000..3c08e2096 --- /dev/null +++ b/lib/agents/__tests__/validateAgentVerifyBody.test.ts @@ -0,0 +1,34 @@ +import { describe, it, expect } from "vitest"; +import { NextResponse } from "next/server"; +import { validateAgentVerifyBody } from "@/lib/agents/validateAgentVerifyBody"; + +describe("validateAgentVerifyBody", () => { + it("returns validated body for valid input", () => { + const result = validateAgentVerifyBody({ email: "user@example.com", code: "123456" }); + expect(result).toEqual({ email: "user@example.com", code: "123456" }); + }); + + it("returns 400 for missing email", () => { + const result = validateAgentVerifyBody({ code: "123456" }); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + + it("returns 400 for missing code", () => { + const result = validateAgentVerifyBody({ email: "user@example.com" }); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + + it("returns 400 for empty code", () => { + const result = validateAgentVerifyBody({ email: "user@example.com", code: "" }); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + + it("returns 400 for invalid email", () => { + const result = validateAgentVerifyBody({ email: "bad", code: "123456" }); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); +}); diff --git a/lib/agents/agentSignupHandler.ts b/lib/agents/agentSignupHandler.ts new file mode 100644 index 000000000..13311428d --- /dev/null +++ b/lib/agents/agentSignupHandler.ts @@ -0,0 +1,158 @@ +import { NextResponse } from "next/server"; +import { randomInt } from "crypto"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { selectAccountByEmail } from "@/lib/supabase/account_emails/selectAccountByEmail"; +import { insertAccount } from "@/lib/supabase/accounts/insertAccount"; +import { insertAccountEmail } from "@/lib/supabase/account_emails/insertAccountEmail"; +import { insertCreditsUsage } from "@/lib/supabase/credits_usage/insertCreditsUsage"; +import { assignAccountToOrg } from "@/lib/organizations/assignAccountToOrg"; +import { generateApiKey } from "@/lib/keys/generateApiKey"; +import { hashApiKey } from "@/lib/keys/hashApiKey"; +import { insertApiKey } from "@/lib/supabase/account_api_keys/insertApiKey"; +import { isAgentPrefixEmail } from "@/lib/agents/isAgentPrefixEmail"; +import { createPrivyUser } from "@/lib/privy/createPrivyUser"; +import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; +import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; +import { sendVerificationEmail } from "@/lib/agents/sendVerificationEmail"; +import type { AgentSignupBody } from "@/lib/agents/validateAgentSignupBody"; + +const GENERIC_MESSAGE = + "If this is a new agent+ email, your API key is included. Otherwise, check your email for a verification code."; + +/** + * Handles agent signup flow. + * + * @param body - Validated signup request body + * @returns NextResponse with account_id, api_key (or null), and message + */ +export async function agentSignupHandler(body: AgentSignupBody): Promise { + const { email } = body; + + try { + const existingAccount = await selectAccountByEmail(email); + + if (existingAccount) { + // Case 3c: Account exists — send verification code + return handleExistingAccount(existingAccount.account_id, email); + } + + if (isAgentPrefixEmail(email)) { + // Case 3a: New account + agent+ prefix — instant key + return handleAgentPrefixSignup(email); + } + + // Case 3b: New account + normal email — verification required + return handleNormalSignup(email); + } catch (error) { + console.error("[ERROR] agentSignupHandler:", error); + return NextResponse.json( + { account_id: null, api_key: null, message: GENERIC_MESSAGE }, + { status: 200, headers: getCorsHeaders() }, + ); + } +} + +/** + * Creates a new account with email, credits, and org assignment. + * + * @param email - The email address for the new account + * @returns The new account ID + */ +async function createAccountWithEmail(email: string): Promise { + const account = await insertAccount({}); + await insertAccountEmail(account.id, email); + await insertCreditsUsage(account.id); + await assignAccountToOrg(account.id, email); + return account.id; +} + +/** + * Generates a new API key, hashes it, and stores it in the database. + * + * @param accountId - The account ID to associate the key with + * @returns The raw API key string + */ +async function generateAndStoreApiKey(accountId: string): Promise { + const today = new Date().toISOString().slice(0, 10); + const rawKey = generateApiKey("recoup_sk"); + const keyHash = hashApiKey(rawKey, process.env.PROJECT_SECRET!); + await insertApiKey({ name: `Agent ${today}`, account: accountId, key_hash: keyHash }); + return rawKey; +} + +/** + * Handles instant signup for agent+ prefix emails. + * + * @param email - The agent+ email address + * @returns NextResponse with api_key + */ +async function handleAgentPrefixSignup(email: string): Promise { + const accountId = await createAccountWithEmail(email); + + // Create Privy user and clear metadata + const privyUser = await createPrivyUser(email); + await setPrivyCustomMetadata(privyUser.id, {}); + + const rawKey = await generateAndStoreApiKey(accountId); + + return NextResponse.json( + { account_id: accountId, api_key: rawKey, message: GENERIC_MESSAGE }, + { status: 200, headers: getCorsHeaders() }, + ); +} + +/** + * Generates a verification code, stores its hash in Privy, and sends it via email. + * + * @param email - The email address to send the code to + */ +async function storeVerificationCode(email: string): Promise { + const code = randomInt(100000, 999999).toString(); + const codeHash = hashApiKey(code, process.env.PROJECT_SECRET!); + const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(); + + let privyUser = await getPrivyUserByEmail(email); + if (!privyUser) { + privyUser = await createPrivyUser(email); + } + + await setPrivyCustomMetadata(privyUser.id, { + verification_code_hash: codeHash, + verification_expires_at: expiresAt, + verification_attempts: 0, + }); + + await sendVerificationEmail(email, code); +} + +/** + * Handles signup for an email that already has an account. + * + * @param accountId - The existing account ID + * @param email - The email address + * @returns NextResponse with null api_key + */ +async function handleExistingAccount(accountId: string, email: string): Promise { + await storeVerificationCode(email); + + return NextResponse.json( + { account_id: accountId, api_key: null, message: GENERIC_MESSAGE }, + { status: 200, headers: getCorsHeaders() }, + ); +} + +/** + * Handles signup for a normal email (creates account, sends verification code). + * + * @param email - The email address + * @returns NextResponse with null api_key + */ +async function handleNormalSignup(email: string): Promise { + const accountId = await createAccountWithEmail(email); + await storeVerificationCode(email); + + return NextResponse.json( + { account_id: accountId, api_key: null, message: GENERIC_MESSAGE }, + { status: 200, headers: getCorsHeaders() }, + ); +} diff --git a/lib/agents/agentVerifyHandler.ts b/lib/agents/agentVerifyHandler.ts new file mode 100644 index 000000000..ada1e73d4 --- /dev/null +++ b/lib/agents/agentVerifyHandler.ts @@ -0,0 +1,111 @@ +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { selectAccountByEmail } from "@/lib/supabase/account_emails/selectAccountByEmail"; +import { generateApiKey } from "@/lib/keys/generateApiKey"; +import { hashApiKey } from "@/lib/keys/hashApiKey"; +import { insertApiKey } from "@/lib/supabase/account_api_keys/insertApiKey"; +import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; +import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; +import type { AgentVerifyBody } from "@/lib/agents/validateAgentVerifyBody"; + +const GENERIC_ERROR = "Invalid or expired verification code."; +const MAX_ATTEMPTS = 5; + +/** + * Handles agent email verification flow. + * + * @param body - Validated verify request body + * @returns NextResponse with account_id, api_key, and message + */ +export async function agentVerifyHandler(body: AgentVerifyBody): Promise { + const { email, code } = body; + + try { + // Look up Privy user and custom_metadata + const privyUser = await getPrivyUserByEmail(email); + if (!privyUser?.custom_metadata) { + return NextResponse.json( + { error: GENERIC_ERROR }, + { status: 400, headers: getCorsHeaders() }, + ); + } + + const metadata = privyUser.custom_metadata as { + verification_code_hash?: string; + verification_expires_at?: string; + verification_attempts?: number; + }; + + // No code stored + if (!metadata.verification_code_hash) { + return NextResponse.json( + { error: GENERIC_ERROR }, + { status: 400, headers: getCorsHeaders() }, + ); + } + + // Expired + if (metadata.verification_expires_at) { + const expiresAt = new Date(metadata.verification_expires_at).getTime(); + if (Date.now() > expiresAt) { + return NextResponse.json( + { error: GENERIC_ERROR }, + { status: 400, headers: getCorsHeaders() }, + ); + } + } + + // Too many attempts + const attempts = metadata.verification_attempts ?? 0; + if (attempts >= MAX_ATTEMPTS) { + return NextResponse.json( + { error: "Too many failed verification attempts. Please request a new code." }, + { status: 429, headers: getCorsHeaders() }, + ); + } + + // Compare hashes + const providedHash = hashApiKey(code, process.env.PROJECT_SECRET!); + if (providedHash !== metadata.verification_code_hash) { + // Increment attempts + await setPrivyCustomMetadata(privyUser.id, { + ...metadata, + verification_attempts: attempts + 1, + }); + + return NextResponse.json( + { error: GENERIC_ERROR }, + { status: 400, headers: getCorsHeaders() }, + ); + } + + // Code matches — generate API key + const existingAccount = await selectAccountByEmail(email); + if (!existingAccount) { + return NextResponse.json( + { error: GENERIC_ERROR }, + { status: 400, headers: getCorsHeaders() }, + ); + } + + const accountId = existingAccount.account_id; + const today = new Date().toISOString().slice(0, 10); + const rawKey = generateApiKey("recoup_sk"); + const keyHash = hashApiKey(rawKey, process.env.PROJECT_SECRET!); + await insertApiKey({ name: `Agent ${today}`, account: accountId, key_hash: keyHash }); + + // Clear custom_metadata + await setPrivyCustomMetadata(privyUser.id, {}); + + return NextResponse.json( + { account_id: accountId, api_key: rawKey, message: "Verified" }, + { status: 200, headers: getCorsHeaders() }, + ); + } catch (error) { + console.error("[ERROR] agentVerifyHandler:", error); + return NextResponse.json( + { error: "Internal server error" }, + { status: 500, headers: getCorsHeaders() }, + ); + } +} diff --git a/lib/agents/isAgentPrefixEmail.ts b/lib/agents/isAgentPrefixEmail.ts new file mode 100644 index 000000000..9a6ae70b5 --- /dev/null +++ b/lib/agents/isAgentPrefixEmail.ts @@ -0,0 +1,9 @@ +/** + * Checks if an email address uses the agent+ prefix. + * + * @param email - The email address to check + * @returns True if the email starts with "agent+" + */ +export function isAgentPrefixEmail(email: string): boolean { + return email.toLowerCase().startsWith("agent+"); +} diff --git a/lib/agents/sendVerificationEmail.ts b/lib/agents/sendVerificationEmail.ts new file mode 100644 index 000000000..fa160f185 --- /dev/null +++ b/lib/agents/sendVerificationEmail.ts @@ -0,0 +1,21 @@ +import { sendEmailWithResend } from "@/lib/emails/sendEmail"; +import { RECOUP_FROM_EMAIL } from "@/lib/const"; + +/** + * Sends a 6-digit verification code to the given email address. + * + * @param email - The recipient email address + * @param code - The 6-digit verification code + */ +export async function sendVerificationEmail(email: string, code: string): Promise { + const result = await sendEmailWithResend({ + from: RECOUP_FROM_EMAIL, + to: email, + subject: "Your Recoup verification code", + html: `

Your verification code is: ${code}

This code expires in 24 hours.

`, + }); + + if (result instanceof Response) { + throw new Error("Failed to send verification email"); + } +} diff --git a/lib/agents/validateAgentSignupBody.ts b/lib/agents/validateAgentSignupBody.ts new file mode 100644 index 000000000..1571006c7 --- /dev/null +++ b/lib/agents/validateAgentSignupBody.ts @@ -0,0 +1,36 @@ +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { z } from "zod"; + +export const agentSignupBodySchema = z.object({ + email: z.string({ message: "email is required" }).email("email must be a valid email address"), +}); + +export type AgentSignupBody = z.infer; + +/** + * Validates request body for POST /api/agents/signup. + * + * @param body - The request body + * @returns A NextResponse with an error if validation fails, or the validated body + */ +export function validateAgentSignupBody(body: unknown): NextResponse | AgentSignupBody { + const result = agentSignupBodySchema.safeParse(body); + + if (!result.success) { + const firstError = result.error.issues[0]; + return NextResponse.json( + { + status: "error", + missing_fields: firstError.path, + error: firstError.message, + }, + { + status: 400, + headers: getCorsHeaders(), + }, + ); + } + + return result.data; +} diff --git a/lib/agents/validateAgentVerifyBody.ts b/lib/agents/validateAgentVerifyBody.ts new file mode 100644 index 000000000..cc9779d9b --- /dev/null +++ b/lib/agents/validateAgentVerifyBody.ts @@ -0,0 +1,37 @@ +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { z } from "zod"; + +export const agentVerifyBodySchema = z.object({ + email: z.string({ message: "email is required" }).email("email must be a valid email address"), + code: z.string({ message: "code is required" }).min(1, "code cannot be empty"), +}); + +export type AgentVerifyBody = z.infer; + +/** + * Validates request body for POST /api/agents/verify. + * + * @param body - The request body + * @returns A NextResponse with an error if validation fails, or the validated body + */ +export function validateAgentVerifyBody(body: unknown): NextResponse | AgentVerifyBody { + const result = agentVerifyBodySchema.safeParse(body); + + if (!result.success) { + const firstError = result.error.issues[0]; + return NextResponse.json( + { + status: "error", + missing_fields: firstError.path, + error: firstError.message, + }, + { + status: 400, + headers: getCorsHeaders(), + }, + ); + } + + return result.data; +} diff --git a/lib/privy/createPrivyUser.ts b/lib/privy/createPrivyUser.ts new file mode 100644 index 000000000..86c7d0dfb --- /dev/null +++ b/lib/privy/createPrivyUser.ts @@ -0,0 +1,26 @@ +/** + * Creates a new Privy user with a linked email account. + * + * @param email - The email address to link to the new Privy user + * @returns The created Privy user object + */ +export async function createPrivyUser(email: string): Promise<{ id: string }> { + const response = await fetch("https://api.privy.io/v1/users", { + method: "POST", + headers: { + "Content-Type": "application/json", + "privy-app-id": process.env.PRIVY_APP_ID!, + Authorization: `Basic ${btoa(process.env.PRIVY_APP_ID! + ":" + process.env.PRIVY_PROJECT_SECRET!)}`, + }, + body: JSON.stringify({ + linked_accounts: [{ type: "email", address: email }], + }), + }); + + if (!response.ok) { + const errorBody = await response.text(); + throw new Error(`Failed to create Privy user: ${response.status} ${errorBody}`); + } + + return response.json(); +} diff --git a/lib/privy/getPrivyUserByEmail.ts b/lib/privy/getPrivyUserByEmail.ts new file mode 100644 index 000000000..988d8e570 --- /dev/null +++ b/lib/privy/getPrivyUserByEmail.ts @@ -0,0 +1,30 @@ +/** + * Looks up a Privy user by email address. + * + * @param email - The email address to look up + * @returns The Privy user object if found, null if not found + */ +export async function getPrivyUserByEmail( + email: string, +): Promise<{ id: string; custom_metadata?: Record } | null> { + const response = await fetch("https://api.privy.io/v1/users/email/address", { + method: "POST", + headers: { + "Content-Type": "application/json", + "privy-app-id": process.env.PRIVY_APP_ID!, + Authorization: `Basic ${btoa(process.env.PRIVY_APP_ID! + ":" + process.env.PRIVY_PROJECT_SECRET!)}`, + }, + body: JSON.stringify({ email }), + }); + + if (response.status === 404) { + return null; + } + + if (!response.ok) { + const errorBody = await response.text(); + throw new Error(`Failed to get Privy user by email: ${response.status} ${errorBody}`); + } + + return response.json(); +} diff --git a/lib/privy/setPrivyCustomMetadata.ts b/lib/privy/setPrivyCustomMetadata.ts new file mode 100644 index 000000000..db942d91a --- /dev/null +++ b/lib/privy/setPrivyCustomMetadata.ts @@ -0,0 +1,25 @@ +/** + * Sets custom metadata on a Privy user. + * + * @param userId - The Privy user ID + * @param metadata - The custom metadata to set + */ +export async function setPrivyCustomMetadata( + userId: string, + metadata: Record, +): Promise { + const response = await fetch(`https://api.privy.io/v1/users/${userId}/custom_metadata`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "privy-app-id": process.env.PRIVY_APP_ID!, + Authorization: `Basic ${btoa(process.env.PRIVY_APP_ID! + ":" + process.env.PRIVY_PROJECT_SECRET!)}`, + }, + body: JSON.stringify({ custom_metadata: metadata }), + }); + + if (!response.ok) { + const errorBody = await response.text(); + throw new Error(`Failed to set Privy custom metadata: ${response.status} ${errorBody}`); + } +} From 77d08b47ef81ba0aecf985a8075bb4b2a1591572 Mon Sep 17 00:00:00 2001 From: Sweets Sweetman Date: Sat, 11 Apr 2026 19:32:31 -0500 Subject: [PATCH 2/6] fix(agents): address PR #396 review feedback (TDD) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- app/api/agents/signup/route.ts | 18 +--- app/api/agents/verify/route.ts | 18 +--- .../__tests__/agentSignupHandler.test.ts | 55 ++++++++++- .../__tests__/agentVerifyHandler.test.ts | 97 +++++++++++++++++-- .../__tests__/validateAgentVerifyBody.test.ts | 24 +++++ lib/agents/agentSignupHandler.ts | 61 +++++++----- lib/agents/agentVerifyHandler.ts | 59 +++++++---- lib/agents/validateAgentVerifyBody.ts | 2 +- 8 files changed, 250 insertions(+), 84 deletions(-) diff --git a/app/api/agents/signup/route.ts b/app/api/agents/signup/route.ts index dfd2846c7..f5d6ee0ed 100644 --- a/app/api/agents/signup/route.ts +++ b/app/api/agents/signup/route.ts @@ -1,10 +1,5 @@ import { NextRequest, NextResponse } from "next/server"; import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; -import { safeParseJson } from "@/lib/networking/safeParseJson"; -import { - validateAgentSignupBody, - type AgentSignupBody, -} from "@/lib/agents/validateAgentSignupBody"; import { agentSignupHandler } from "@/lib/agents/agentSignupHandler"; /** @@ -14,18 +9,11 @@ import { agentSignupHandler } from "@/lib/agents/agentSignupHandler"; * For all other cases, sends a verification code to the email. * This endpoint is unauthenticated. * - * @param req - The incoming request with email in body - * @returns Signup response with account_id, api_key (or null), and message + * @param req - The incoming request with `{ email }` in the body + * @returns Signup response with `account_id`, `api_key` (or null), and `message` */ export async function POST(req: NextRequest) { - const body = await safeParseJson(req); - - const validated = validateAgentSignupBody(body); - if (validated instanceof NextResponse) { - return validated; - } - - return agentSignupHandler(validated as AgentSignupBody); + return agentSignupHandler(req); } /** diff --git a/app/api/agents/verify/route.ts b/app/api/agents/verify/route.ts index f634bb7c3..b8ea80946 100644 --- a/app/api/agents/verify/route.ts +++ b/app/api/agents/verify/route.ts @@ -1,10 +1,5 @@ import { NextRequest, NextResponse } from "next/server"; import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; -import { safeParseJson } from "@/lib/networking/safeParseJson"; -import { - validateAgentVerifyBody, - type AgentVerifyBody, -} from "@/lib/agents/validateAgentVerifyBody"; import { agentVerifyHandler } from "@/lib/agents/agentVerifyHandler"; /** @@ -13,18 +8,11 @@ import { agentVerifyHandler } from "@/lib/agents/agentVerifyHandler"; * Verify an agent's email with the code sent during signup. * Returns an API key on success. This endpoint is unauthenticated. * - * @param req - The incoming request with email and code in body - * @returns Verify response with account_id, api_key, and message + * @param req - The incoming request with `{ email, code }` in the body + * @returns Verify response with `account_id`, `api_key`, and `message` */ export async function POST(req: NextRequest) { - const body = await safeParseJson(req); - - const validated = validateAgentVerifyBody(body); - if (validated instanceof NextResponse) { - return validated; - } - - return agentVerifyHandler(validated as AgentVerifyBody); + return agentVerifyHandler(req); } /** diff --git a/lib/agents/__tests__/agentSignupHandler.test.ts b/lib/agents/__tests__/agentSignupHandler.test.ts index 9a290415a..566aae86e 100644 --- a/lib/agents/__tests__/agentSignupHandler.test.ts +++ b/lib/agents/__tests__/agentSignupHandler.test.ts @@ -1,10 +1,25 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; +import { randomInt } from "crypto"; import { agentSignupHandler } from "@/lib/agents/agentSignupHandler"; import { selectAccountByEmail } from "@/lib/supabase/account_emails/selectAccountByEmail"; import { insertAccount } from "@/lib/supabase/accounts/insertAccount"; import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; +/** + * Builds a NextRequest for the agent signup endpoint with the given body. + * + * @param body - The request body to serialize + * @returns A NextRequest targeting `/api/agents/signup` + */ +function buildRequest(body: unknown): NextRequest { + return new NextRequest("http://localhost/api/agents/signup", { + method: "POST", + body: JSON.stringify(body), + }); +} + vi.mock("@/lib/networking/getCorsHeaders", () => ({ getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })), })); @@ -57,6 +72,14 @@ vi.mock("@/lib/agents/sendVerificationEmail", () => ({ sendVerificationEmail: vi.fn(), })); +vi.mock("crypto", async () => { + const actual = await vi.importActual("crypto"); + return { + ...actual, + randomInt: vi.fn(() => 123456), + }; +}); + describe("agentSignupHandler", () => { beforeEach(() => { vi.clearAllMocks(); @@ -70,7 +93,7 @@ describe("agentSignupHandler", () => { ReturnType >); - const result = await agentSignupHandler({ email: "agent+bot@example.com" }); + const result = await agentSignupHandler(buildRequest({ email: "agent+bot@example.com" })); const body = await result.json(); expect(result.status).toBe(200); @@ -88,7 +111,7 @@ describe("agentSignupHandler", () => { } as unknown as Awaited>); vi.mocked(getPrivyUserByEmail).mockResolvedValue({ id: "privy_456" }); - const result = await agentSignupHandler({ email: "user@example.com" }); + const result = await agentSignupHandler(buildRequest({ email: "user@example.com" })); const body = await result.json(); expect(result.status).toBe(200); @@ -105,12 +128,38 @@ describe("agentSignupHandler", () => { >); vi.mocked(getPrivyUserByEmail).mockResolvedValue(null); - const result = await agentSignupHandler({ email: "user@example.com" }); + const result = await agentSignupHandler(buildRequest({ email: "user@example.com" })); const body = await result.json(); expect(result.status).toBe(200); expect(body.account_id).toBe("acc_new"); expect(body.api_key).toBeNull(); }); + + it("generates verification code with inclusive upper bound (100000 <= code <= 999999)", async () => { + vi.mocked(selectAccountByEmail).mockResolvedValue(null); + vi.mocked(insertAccount).mockResolvedValue({ id: "acc_new" } as unknown as Awaited< + ReturnType + >); + vi.mocked(getPrivyUserByEmail).mockResolvedValue(null); + + await agentSignupHandler(buildRequest({ email: "user@example.com" })); + + // Node's randomInt upper bound is exclusive. Using 1000000 covers 999999 + // as a possible value; using 999999 would never generate it. + expect(randomInt).toHaveBeenCalledWith(100000, 1000000); + }); + }); + + describe("validation", () => { + it("returns 400 for missing email", async () => { + const result = await agentSignupHandler(buildRequest({})); + expect(result.status).toBe(400); + }); + + it("returns 400 for invalid email", async () => { + const result = await agentSignupHandler(buildRequest({ email: "not-an-email" })); + expect(result.status).toBe(400); + }); }); }); diff --git a/lib/agents/__tests__/agentVerifyHandler.test.ts b/lib/agents/__tests__/agentVerifyHandler.test.ts index d004f3660..a8f8b6f0f 100644 --- a/lib/agents/__tests__/agentVerifyHandler.test.ts +++ b/lib/agents/__tests__/agentVerifyHandler.test.ts @@ -1,9 +1,24 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; import { agentVerifyHandler } from "@/lib/agents/agentVerifyHandler"; import { selectAccountByEmail } from "@/lib/supabase/account_emails/selectAccountByEmail"; import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; +import { insertApiKey } from "@/lib/supabase/account_api_keys/insertApiKey"; + +/** + * Builds a NextRequest for the agent verify endpoint with the given body. + * + * @param body - The request body to serialize + * @returns A NextRequest targeting `/api/agents/verify` + */ +function buildRequest(body: unknown): NextRequest { + return new NextRequest("http://localhost/api/agents/verify", { + method: "POST", + body: JSON.stringify(body), + }); +} vi.mock("@/lib/networking/getCorsHeaders", () => ({ getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })), @@ -54,7 +69,9 @@ describe("agentVerifyHandler", () => { email: "user@example.com", } as unknown as Awaited>); - const result = await agentVerifyHandler({ email: "user@example.com", code: "123456" }); + const result = await agentVerifyHandler( + buildRequest({ email: "user@example.com", code: "123456" }), + ); const body = await result.json(); expect(result.status).toBe(200); @@ -74,7 +91,9 @@ describe("agentVerifyHandler", () => { }, }); - const result = await agentVerifyHandler({ email: "user@example.com", code: "wrong" }); + const result = await agentVerifyHandler( + buildRequest({ email: "user@example.com", code: "999999" }), + ); expect(result.status).toBe(400); expect(setPrivyCustomMetadata).toHaveBeenCalledWith( @@ -95,7 +114,9 @@ describe("agentVerifyHandler", () => { }, }); - const result = await agentVerifyHandler({ email: "user@example.com", code: "123456" }); + const result = await agentVerifyHandler( + buildRequest({ email: "user@example.com", code: "123456" }), + ); expect(result.status).toBe(429); }); @@ -110,7 +131,9 @@ describe("agentVerifyHandler", () => { }, }); - const result = await agentVerifyHandler({ email: "user@example.com", code: "123456" }); + const result = await agentVerifyHandler( + buildRequest({ email: "user@example.com", code: "123456" }), + ); expect(result.status).toBe(400); }); @@ -118,7 +141,9 @@ describe("agentVerifyHandler", () => { it("returns 400 when no privy user found", async () => { vi.mocked(getPrivyUserByEmail).mockResolvedValue(null); - const result = await agentVerifyHandler({ email: "user@example.com", code: "123456" }); + const result = await agentVerifyHandler( + buildRequest({ email: "user@example.com", code: "123456" }), + ); expect(result.status).toBe(400); }); @@ -129,8 +154,68 @@ describe("agentVerifyHandler", () => { custom_metadata: {}, }); - const result = await agentVerifyHandler({ email: "user@example.com", code: "123456" }); + const result = await agentVerifyHandler( + buildRequest({ email: "user@example.com", code: "123456" }), + ); + + expect(result.status).toBe(400); + }); + + it("returns 400 when verification_expires_at is missing (fail-safe)", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ + id: "privy_123", + custom_metadata: { + verification_code_hash: "hashed_123456", + // verification_expires_at intentionally omitted + verification_attempts: 0, + }, + }); + + const result = await agentVerifyHandler( + buildRequest({ email: "user@example.com", code: "123456" }), + ); expect(result.status).toBe(400); }); + + it("returns 500 and does NOT expose api_key when insertApiKey fails", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ + id: "privy_123", + custom_metadata: { + verification_code_hash: "hashed_123456", + verification_expires_at: new Date(Date.now() + 60000).toISOString(), + verification_attempts: 0, + }, + }); + vi.mocked(selectAccountByEmail).mockResolvedValue({ + account_id: "acc_123", + email: "user@example.com", + } as unknown as Awaited>); + vi.mocked(insertApiKey).mockResolvedValueOnce({ + data: null, + error: { message: "DB write failed" }, + } as unknown as Awaited>); + + const result = await agentVerifyHandler( + buildRequest({ email: "user@example.com", code: "123456" }), + ); + const body = await result.json(); + + expect(result.status).toBe(500); + expect(body.api_key).toBeUndefined(); + }); + + describe("validation", () => { + it("returns 400 for missing code", async () => { + const result = await agentVerifyHandler(buildRequest({ email: "user@example.com" })); + expect(result.status).toBe(400); + }); + + it("returns 400 for non-numeric code", async () => { + const result = await agentVerifyHandler( + buildRequest({ email: "user@example.com", code: "abcdef" }), + ); + expect(result.status).toBe(400); + }); + }); }); diff --git a/lib/agents/__tests__/validateAgentVerifyBody.test.ts b/lib/agents/__tests__/validateAgentVerifyBody.test.ts index 3c08e2096..8757dfece 100644 --- a/lib/agents/__tests__/validateAgentVerifyBody.test.ts +++ b/lib/agents/__tests__/validateAgentVerifyBody.test.ts @@ -31,4 +31,28 @@ describe("validateAgentVerifyBody", () => { expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); }); + + it("returns 400 for non-numeric code", () => { + const result = validateAgentVerifyBody({ email: "user@example.com", code: "abcdef" }); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + + it("returns 400 for 5-digit code", () => { + const result = validateAgentVerifyBody({ email: "user@example.com", code: "12345" }); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + + it("returns 400 for 7-digit code", () => { + const result = validateAgentVerifyBody({ email: "user@example.com", code: "1234567" }); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + + it("returns 400 for code with spaces", () => { + const result = validateAgentVerifyBody({ email: "user@example.com", code: "123 456" }); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); }); diff --git a/lib/agents/agentSignupHandler.ts b/lib/agents/agentSignupHandler.ts index 13311428d..ffa33c0c5 100644 --- a/lib/agents/agentSignupHandler.ts +++ b/lib/agents/agentSignupHandler.ts @@ -1,6 +1,8 @@ -import { NextResponse } from "next/server"; +import { NextRequest, NextResponse } from "next/server"; import { randomInt } from "crypto"; import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { safeParseJson } from "@/lib/networking/safeParseJson"; +import { validateAgentSignupBody } from "@/lib/agents/validateAgentSignupBody"; import { selectAccountByEmail } from "@/lib/supabase/account_emails/selectAccountByEmail"; import { insertAccount } from "@/lib/supabase/accounts/insertAccount"; import { insertAccountEmail } from "@/lib/supabase/account_emails/insertAccountEmail"; @@ -14,21 +16,28 @@ import { createPrivyUser } from "@/lib/privy/createPrivyUser"; import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; import { sendVerificationEmail } from "@/lib/agents/sendVerificationEmail"; -import type { AgentSignupBody } from "@/lib/agents/validateAgentSignupBody"; const GENERIC_MESSAGE = "If this is a new agent+ email, your API key is included. Otherwise, check your email for a verification code."; /** - * Handles agent signup flow. + * Handles agent signup flow — validates the request body and dispatches to + * the instant-signup, existing-account, or normal-signup path. * - * @param body - Validated signup request body - * @returns NextResponse with account_id, api_key (or null), and message + * @param request - The incoming Next.js request with `{ email }` in the body + * @returns NextResponse with `account_id`, `api_key` (or null), and `message` */ -export async function agentSignupHandler(body: AgentSignupBody): Promise { - const { email } = body; - +export async function agentSignupHandler(request: NextRequest): Promise { try { + const body = await safeParseJson(request); + + const validated = validateAgentSignupBody(body); + if (validated instanceof NextResponse) { + return validated; + } + + const { email } = validated; + const existingAccount = await selectAccountByEmail(email); if (existingAccount) { @@ -53,9 +62,9 @@ export async function agentSignupHandler(body: AgentSignupBody): Promise { @@ -67,10 +76,10 @@ async function createAccountWithEmail(email: string): Promise { } /** - * Generates a new API key, hashes it, and stores it in the database. + * Generates a new API key, stores its hash, and returns the raw key. * - * @param accountId - The account ID to associate the key with - * @returns The raw API key string + * @param accountId - Account to associate the key with + * @returns The raw (un-hashed) API key string */ async function generateAndStoreApiKey(accountId: string): Promise { const today = new Date().toISOString().slice(0, 10); @@ -81,15 +90,14 @@ async function generateAndStoreApiKey(accountId: string): Promise { } /** - * Handles instant signup for agent+ prefix emails. + * Instant-signup path for fresh `agent+` emails — returns an API key immediately. * - * @param email - The agent+ email address - * @returns NextResponse with api_key + * @param email - The `agent+` email address + * @returns NextResponse with the freshly generated API key */ async function handleAgentPrefixSignup(email: string): Promise { const accountId = await createAccountWithEmail(email); - // Create Privy user and clear metadata const privyUser = await createPrivyUser(email); await setPrivyCustomMetadata(privyUser.id, {}); @@ -102,12 +110,13 @@ async function handleAgentPrefixSignup(email: string): Promise { } /** - * Generates a verification code, stores its hash in Privy, and sends it via email. + * Generates a 6-digit code, stores its hash in Privy metadata, and emails it. * - * @param email - The email address to send the code to + * @param email - Email to deliver the verification code to */ async function storeVerificationCode(email: string): Promise { - const code = randomInt(100000, 999999).toString(); + // randomInt upper bound is exclusive — use 1000000 to include 999999. + const code = randomInt(100000, 1000000).toString(); const codeHash = hashApiKey(code, process.env.PROJECT_SECRET!); const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(); @@ -126,11 +135,11 @@ async function storeVerificationCode(email: string): Promise { } /** - * Handles signup for an email that already has an account. + * Existing-account path — always sends a verification code, never returns a key. * * @param accountId - The existing account ID - * @param email - The email address - * @returns NextResponse with null api_key + * @param email - The email that matched an existing account + * @returns NextResponse with `api_key: null` */ async function handleExistingAccount(accountId: string, email: string): Promise { await storeVerificationCode(email); @@ -142,10 +151,10 @@ async function handleExistingAccount(accountId: string, email: string): Promise< } /** - * Handles signup for a normal email (creates account, sends verification code). + * Non-`agent+` new-account path — creates the account, then sends a verification code. * - * @param email - The email address - * @returns NextResponse with null api_key + * @param email - Email for the new account + * @returns NextResponse with `api_key: null` */ async function handleNormalSignup(email: string): Promise { const accountId = await createAccountWithEmail(email); diff --git a/lib/agents/agentVerifyHandler.ts b/lib/agents/agentVerifyHandler.ts index ada1e73d4..e33b3f7ee 100644 --- a/lib/agents/agentVerifyHandler.ts +++ b/lib/agents/agentVerifyHandler.ts @@ -1,26 +1,34 @@ -import { NextResponse } from "next/server"; +import { NextRequest, NextResponse } from "next/server"; import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { safeParseJson } from "@/lib/networking/safeParseJson"; +import { validateAgentVerifyBody } from "@/lib/agents/validateAgentVerifyBody"; import { selectAccountByEmail } from "@/lib/supabase/account_emails/selectAccountByEmail"; import { generateApiKey } from "@/lib/keys/generateApiKey"; import { hashApiKey } from "@/lib/keys/hashApiKey"; import { insertApiKey } from "@/lib/supabase/account_api_keys/insertApiKey"; import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; -import type { AgentVerifyBody } from "@/lib/agents/validateAgentVerifyBody"; const GENERIC_ERROR = "Invalid or expired verification code."; const MAX_ATTEMPTS = 5; /** - * Handles agent email verification flow. + * Handles agent email verification — validates the request body, checks the + * submitted code against the stored hash, and returns an API key on success. * - * @param body - Validated verify request body - * @returns NextResponse with account_id, api_key, and message + * @param request - The incoming Next.js request with `{ email, code }` in the body + * @returns NextResponse with `account_id`, `api_key`, and `message` on success */ -export async function agentVerifyHandler(body: AgentVerifyBody): Promise { - const { email, code } = body; - +export async function agentVerifyHandler(request: NextRequest): Promise { try { + const body = await safeParseJson(request); + + const validated = validateAgentVerifyBody(body); + if (validated instanceof NextResponse) { + return validated; + } + + const { email, code } = validated; // Look up Privy user and custom_metadata const privyUser = await getPrivyUserByEmail(email); if (!privyUser?.custom_metadata) { @@ -44,15 +52,19 @@ export async function agentVerifyHandler(body: AgentVerifyBody): Promise expiresAt) { - return NextResponse.json( - { error: GENERIC_ERROR }, - { status: 400, headers: getCorsHeaders() }, - ); - } + // Expired — fail-safe: missing expiry is treated as expired + if (!metadata.verification_expires_at) { + return NextResponse.json( + { error: GENERIC_ERROR }, + { status: 400, headers: getCorsHeaders() }, + ); + } + const expiresAt = new Date(metadata.verification_expires_at).getTime(); + if (Date.now() > expiresAt) { + return NextResponse.json( + { error: GENERIC_ERROR }, + { status: 400, headers: getCorsHeaders() }, + ); } // Too many attempts @@ -92,7 +104,18 @@ export async function agentVerifyHandler(body: AgentVerifyBody): Promise; From e9f6738a657a36460b0e9d57d31ba1d517c06760 Mon Sep 17 00:00:00 2001 From: Sweets Sweetman Date: Sat, 11 Apr 2026 19:45:20 -0500 Subject: [PATCH 3/6] =?UTF-8?q?refactor(agents):=20SRP=20=E2=80=94=20one?= =?UTF-8?q?=20function=20per=20file,=20prerequisites=20in=20validate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- .../__tests__/createAccountWithEmail.test.ts | 42 ++++ .../__tests__/generateAndStoreApiKey.test.ts | 43 ++++ .../__tests__/handleAgentPrefixSignup.test.ts | 48 ++++ .../__tests__/handleExistingAccount.test.ts | 27 +++ .../__tests__/handleNormalSignup.test.ts | 35 +++ .../__tests__/storeVerificationCode.test.ts | 67 ++++++ .../__tests__/validateAgentVerifyBody.test.ts | 206 ++++++++++++++---- lib/agents/agentSignupHandler.ts | 128 +---------- lib/agents/agentVerifyHandler.ts | 111 +--------- lib/agents/createAccountWithEmail.ts | 19 ++ lib/agents/generateAndStoreApiKey.ts | 27 +++ lib/agents/handleAgentPrefixSignup.ts | 30 +++ lib/agents/handleExistingAccount.ts | 26 +++ lib/agents/handleNormalSignup.ts | 25 +++ lib/agents/storeVerificationCode.ts | 34 +++ lib/agents/validateAgentVerifyBody.ts | 108 +++++++-- 16 files changed, 694 insertions(+), 282 deletions(-) create mode 100644 lib/agents/__tests__/createAccountWithEmail.test.ts create mode 100644 lib/agents/__tests__/generateAndStoreApiKey.test.ts create mode 100644 lib/agents/__tests__/handleAgentPrefixSignup.test.ts create mode 100644 lib/agents/__tests__/handleExistingAccount.test.ts create mode 100644 lib/agents/__tests__/handleNormalSignup.test.ts create mode 100644 lib/agents/__tests__/storeVerificationCode.test.ts create mode 100644 lib/agents/createAccountWithEmail.ts create mode 100644 lib/agents/generateAndStoreApiKey.ts create mode 100644 lib/agents/handleAgentPrefixSignup.ts create mode 100644 lib/agents/handleExistingAccount.ts create mode 100644 lib/agents/handleNormalSignup.ts create mode 100644 lib/agents/storeVerificationCode.ts diff --git a/lib/agents/__tests__/createAccountWithEmail.test.ts b/lib/agents/__tests__/createAccountWithEmail.test.ts new file mode 100644 index 000000000..f88e2f5ed --- /dev/null +++ b/lib/agents/__tests__/createAccountWithEmail.test.ts @@ -0,0 +1,42 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { createAccountWithEmail } from "@/lib/agents/createAccountWithEmail"; +import { insertAccount } from "@/lib/supabase/accounts/insertAccount"; +import { insertAccountEmail } from "@/lib/supabase/account_emails/insertAccountEmail"; +import { insertCreditsUsage } from "@/lib/supabase/credits_usage/insertCreditsUsage"; +import { assignAccountToOrg } from "@/lib/organizations/assignAccountToOrg"; + +vi.mock("@/lib/supabase/accounts/insertAccount", () => ({ + insertAccount: vi.fn(), +})); + +vi.mock("@/lib/supabase/account_emails/insertAccountEmail", () => ({ + insertAccountEmail: vi.fn(), +})); + +vi.mock("@/lib/supabase/credits_usage/insertCreditsUsage", () => ({ + insertCreditsUsage: vi.fn(), +})); + +vi.mock("@/lib/organizations/assignAccountToOrg", () => ({ + assignAccountToOrg: vi.fn(), +})); + +describe("createAccountWithEmail", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("creates account, inserts email, credits, and assigns to org", async () => { + vi.mocked(insertAccount).mockResolvedValue({ id: "acc_new" } as unknown as Awaited< + ReturnType + >); + + const result = await createAccountWithEmail("user@example.com"); + + expect(result).toBe("acc_new"); + expect(insertAccount).toHaveBeenCalledOnce(); + expect(insertAccountEmail).toHaveBeenCalledWith("acc_new", "user@example.com"); + expect(insertCreditsUsage).toHaveBeenCalledWith("acc_new"); + expect(assignAccountToOrg).toHaveBeenCalledWith("acc_new", "user@example.com"); + }); +}); diff --git a/lib/agents/__tests__/generateAndStoreApiKey.test.ts b/lib/agents/__tests__/generateAndStoreApiKey.test.ts new file mode 100644 index 000000000..c0975c8c6 --- /dev/null +++ b/lib/agents/__tests__/generateAndStoreApiKey.test.ts @@ -0,0 +1,43 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { generateAndStoreApiKey } from "@/lib/agents/generateAndStoreApiKey"; +import { insertApiKey } from "@/lib/supabase/account_api_keys/insertApiKey"; + +vi.mock("@/lib/keys/generateApiKey", () => ({ + generateApiKey: vi.fn(() => "recoup_sk_test123"), +})); + +vi.mock("@/lib/keys/hashApiKey", () => ({ + hashApiKey: vi.fn((input: string) => `hashed_${input}`), +})); + +vi.mock("@/lib/supabase/account_api_keys/insertApiKey", () => ({ + insertApiKey: vi.fn(() => ({ data: {}, error: null })), +})); + +describe("generateAndStoreApiKey", () => { + beforeEach(() => { + vi.clearAllMocks(); + process.env.PROJECT_SECRET = "test-secret"; + }); + + it("generates a raw key, hashes it, inserts it, and returns the raw key", async () => { + const rawKey = await generateAndStoreApiKey("acc_123"); + + expect(rawKey).toBe("recoup_sk_test123"); + expect(insertApiKey).toHaveBeenCalledWith( + expect.objectContaining({ + account: "acc_123", + key_hash: "hashed_recoup_sk_test123", + }), + ); + }); + + it("throws when insertApiKey returns an error so the caller cannot leak an unpersisted key", async () => { + vi.mocked(insertApiKey).mockResolvedValueOnce({ + data: null, + error: { message: "DB write failed" }, + } as unknown as Awaited>); + + await expect(generateAndStoreApiKey("acc_123")).rejects.toThrow(/DB write failed/); + }); +}); diff --git a/lib/agents/__tests__/handleAgentPrefixSignup.test.ts b/lib/agents/__tests__/handleAgentPrefixSignup.test.ts new file mode 100644 index 000000000..ff9ecb4e7 --- /dev/null +++ b/lib/agents/__tests__/handleAgentPrefixSignup.test.ts @@ -0,0 +1,48 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { handleAgentPrefixSignup } from "@/lib/agents/handleAgentPrefixSignup"; +import { createAccountWithEmail } from "@/lib/agents/createAccountWithEmail"; +import { generateAndStoreApiKey } from "@/lib/agents/generateAndStoreApiKey"; +import { createPrivyUser } from "@/lib/privy/createPrivyUser"; +import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; + +vi.mock("@/lib/networking/getCorsHeaders", () => ({ + getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })), +})); + +vi.mock("@/lib/agents/createAccountWithEmail", () => ({ + createAccountWithEmail: vi.fn(), +})); + +vi.mock("@/lib/agents/generateAndStoreApiKey", () => ({ + generateAndStoreApiKey: vi.fn(), +})); + +vi.mock("@/lib/privy/createPrivyUser", () => ({ + createPrivyUser: vi.fn(() => ({ id: "privy_abc" })), +})); + +vi.mock("@/lib/privy/setPrivyCustomMetadata", () => ({ + setPrivyCustomMetadata: vi.fn(), +})); + +describe("handleAgentPrefixSignup", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("creates account, creates Privy user with empty metadata, and returns api_key", async () => { + vi.mocked(createAccountWithEmail).mockResolvedValue("acc_new"); + vi.mocked(generateAndStoreApiKey).mockResolvedValue("recoup_sk_new"); + + const result = await handleAgentPrefixSignup("agent+bot@example.com"); + const body = await result.json(); + + expect(result.status).toBe(200); + expect(body.account_id).toBe("acc_new"); + expect(body.api_key).toBe("recoup_sk_new"); + expect(createAccountWithEmail).toHaveBeenCalledWith("agent+bot@example.com"); + expect(createPrivyUser).toHaveBeenCalledWith("agent+bot@example.com"); + expect(setPrivyCustomMetadata).toHaveBeenCalledWith("privy_abc", {}); + expect(generateAndStoreApiKey).toHaveBeenCalledWith("acc_new"); + }); +}); diff --git a/lib/agents/__tests__/handleExistingAccount.test.ts b/lib/agents/__tests__/handleExistingAccount.test.ts new file mode 100644 index 000000000..48c5e2cbd --- /dev/null +++ b/lib/agents/__tests__/handleExistingAccount.test.ts @@ -0,0 +1,27 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { handleExistingAccount } from "@/lib/agents/handleExistingAccount"; +import { storeVerificationCode } from "@/lib/agents/storeVerificationCode"; + +vi.mock("@/lib/networking/getCorsHeaders", () => ({ + getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })), +})); + +vi.mock("@/lib/agents/storeVerificationCode", () => ({ + storeVerificationCode: vi.fn(), +})); + +describe("handleExistingAccount", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("sends a verification code and returns null api_key with the existing account_id", async () => { + const result = await handleExistingAccount("acc_existing", "user@example.com"); + const body = await result.json(); + + expect(result.status).toBe(200); + expect(body.account_id).toBe("acc_existing"); + expect(body.api_key).toBeNull(); + expect(storeVerificationCode).toHaveBeenCalledWith("user@example.com"); + }); +}); diff --git a/lib/agents/__tests__/handleNormalSignup.test.ts b/lib/agents/__tests__/handleNormalSignup.test.ts new file mode 100644 index 000000000..d36fa6ee7 --- /dev/null +++ b/lib/agents/__tests__/handleNormalSignup.test.ts @@ -0,0 +1,35 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { handleNormalSignup } from "@/lib/agents/handleNormalSignup"; +import { createAccountWithEmail } from "@/lib/agents/createAccountWithEmail"; +import { storeVerificationCode } from "@/lib/agents/storeVerificationCode"; + +vi.mock("@/lib/networking/getCorsHeaders", () => ({ + getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })), +})); + +vi.mock("@/lib/agents/createAccountWithEmail", () => ({ + createAccountWithEmail: vi.fn(), +})); + +vi.mock("@/lib/agents/storeVerificationCode", () => ({ + storeVerificationCode: vi.fn(), +})); + +describe("handleNormalSignup", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("creates a new account, sends a verification code, and returns null api_key", async () => { + vi.mocked(createAccountWithEmail).mockResolvedValue("acc_new"); + + const result = await handleNormalSignup("user@example.com"); + const body = await result.json(); + + expect(result.status).toBe(200); + expect(body.account_id).toBe("acc_new"); + expect(body.api_key).toBeNull(); + expect(createAccountWithEmail).toHaveBeenCalledWith("user@example.com"); + expect(storeVerificationCode).toHaveBeenCalledWith("user@example.com"); + }); +}); diff --git a/lib/agents/__tests__/storeVerificationCode.test.ts b/lib/agents/__tests__/storeVerificationCode.test.ts new file mode 100644 index 000000000..c20b366cb --- /dev/null +++ b/lib/agents/__tests__/storeVerificationCode.test.ts @@ -0,0 +1,67 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { randomInt } from "crypto"; +import { storeVerificationCode } from "@/lib/agents/storeVerificationCode"; +import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; +import { createPrivyUser } from "@/lib/privy/createPrivyUser"; +import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; +import { sendVerificationEmail } from "@/lib/agents/sendVerificationEmail"; + +vi.mock("@/lib/privy/getPrivyUserByEmail", () => ({ + getPrivyUserByEmail: vi.fn(), +})); + +vi.mock("@/lib/privy/createPrivyUser", () => ({ + createPrivyUser: vi.fn(() => ({ id: "privy_new" })), +})); + +vi.mock("@/lib/privy/setPrivyCustomMetadata", () => ({ + setPrivyCustomMetadata: vi.fn(), +})); + +vi.mock("@/lib/agents/sendVerificationEmail", () => ({ + sendVerificationEmail: vi.fn(), +})); + +vi.mock("@/lib/keys/hashApiKey", () => ({ + hashApiKey: vi.fn((input: string) => `hashed_${input}`), +})); + +vi.mock("crypto", async () => { + const actual = await vi.importActual("crypto"); + return { + ...actual, + randomInt: vi.fn(() => 123456), + }; +}); + +describe("storeVerificationCode", () => { + beforeEach(() => { + vi.clearAllMocks(); + process.env.PROJECT_SECRET = "test-secret"; + }); + + it("generates a 6-digit code, stores its hash in Privy metadata, and emails it", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ id: "privy_existing" }); + + await storeVerificationCode("user@example.com"); + + expect(randomInt).toHaveBeenCalledWith(100000, 1000000); + expect(setPrivyCustomMetadata).toHaveBeenCalledWith( + "privy_existing", + expect.objectContaining({ + verification_code_hash: "hashed_123456", + verification_attempts: 0, + }), + ); + expect(sendVerificationEmail).toHaveBeenCalledWith("user@example.com", "123456"); + }); + + it("creates a Privy user if none exists, then stores the code", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue(null); + + await storeVerificationCode("new@example.com"); + + expect(createPrivyUser).toHaveBeenCalledWith("new@example.com"); + expect(setPrivyCustomMetadata).toHaveBeenCalledWith("privy_new", expect.any(Object)); + }); +}); diff --git a/lib/agents/__tests__/validateAgentVerifyBody.test.ts b/lib/agents/__tests__/validateAgentVerifyBody.test.ts index 8757dfece..9ea0710df 100644 --- a/lib/agents/__tests__/validateAgentVerifyBody.test.ts +++ b/lib/agents/__tests__/validateAgentVerifyBody.test.ts @@ -1,58 +1,186 @@ -import { describe, it, expect } from "vitest"; +import { describe, it, expect, vi, beforeEach } from "vitest"; import { NextResponse } from "next/server"; import { validateAgentVerifyBody } from "@/lib/agents/validateAgentVerifyBody"; +import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; +import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; +import { selectAccountByEmail } from "@/lib/supabase/account_emails/selectAccountByEmail"; + +vi.mock("@/lib/networking/getCorsHeaders", () => ({ + getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })), +})); + +vi.mock("@/lib/privy/getPrivyUserByEmail", () => ({ + getPrivyUserByEmail: vi.fn(), +})); + +vi.mock("@/lib/privy/setPrivyCustomMetadata", () => ({ + setPrivyCustomMetadata: vi.fn(), +})); + +vi.mock("@/lib/supabase/account_emails/selectAccountByEmail", () => ({ + selectAccountByEmail: vi.fn(), +})); + +vi.mock("@/lib/keys/hashApiKey", () => ({ + hashApiKey: vi.fn((input: string) => `hashed_${input}`), +})); + +const VALID_BODY = { email: "user@example.com", code: "123456" }; + +function metadataWith( + overrides: Record = {}, +): { verification_code_hash: string; verification_expires_at: string; verification_attempts: number } { + return { + verification_code_hash: "hashed_123456", + verification_expires_at: new Date(Date.now() + 60_000).toISOString(), + verification_attempts: 0, + ...overrides, + } as { + verification_code_hash: string; + verification_expires_at: string; + verification_attempts: number; + }; +} describe("validateAgentVerifyBody", () => { - it("returns validated body for valid input", () => { - const result = validateAgentVerifyBody({ email: "user@example.com", code: "123456" }); - expect(result).toEqual({ email: "user@example.com", code: "123456" }); + beforeEach(() => { + vi.clearAllMocks(); + process.env.PROJECT_SECRET = "test-secret"; }); - it("returns 400 for missing email", () => { - const result = validateAgentVerifyBody({ code: "123456" }); - expect(result).toBeInstanceOf(NextResponse); - expect((result as NextResponse).status).toBe(400); - }); + describe("body shape", () => { + it("returns 400 for missing email", async () => { + const result = await validateAgentVerifyBody({ code: "123456" }); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); - it("returns 400 for missing code", () => { - const result = validateAgentVerifyBody({ email: "user@example.com" }); - expect(result).toBeInstanceOf(NextResponse); - expect((result as NextResponse).status).toBe(400); - }); + it("returns 400 for missing code", async () => { + const result = await validateAgentVerifyBody({ email: "user@example.com" }); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); - it("returns 400 for empty code", () => { - const result = validateAgentVerifyBody({ email: "user@example.com", code: "" }); - expect(result).toBeInstanceOf(NextResponse); - expect((result as NextResponse).status).toBe(400); - }); + it("returns 400 for invalid email", async () => { + const result = await validateAgentVerifyBody({ email: "bad", code: "123456" }); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + + it("returns 400 for non-numeric code", async () => { + const result = await validateAgentVerifyBody({ email: "user@example.com", code: "abcdef" }); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + + it("returns 400 for 5-digit code", async () => { + const result = await validateAgentVerifyBody({ email: "user@example.com", code: "12345" }); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); - it("returns 400 for invalid email", () => { - const result = validateAgentVerifyBody({ email: "bad", code: "123456" }); - expect(result).toBeInstanceOf(NextResponse); - expect((result as NextResponse).status).toBe(400); + it("returns 400 for 7-digit code", async () => { + const result = await validateAgentVerifyBody({ email: "user@example.com", code: "1234567" }); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); }); - it("returns 400 for non-numeric code", () => { - const result = validateAgentVerifyBody({ email: "user@example.com", code: "abcdef" }); - expect(result).toBeInstanceOf(NextResponse); - expect((result as NextResponse).status).toBe(400); + describe("stored verification state", () => { + it("returns 400 when Privy user is missing", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue(null); + const result = await validateAgentVerifyBody(VALID_BODY); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + + it("returns 400 when no verification_code_hash is stored", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ + id: "privy_1", + custom_metadata: {}, + }); + const result = await validateAgentVerifyBody(VALID_BODY); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + + it("returns 400 when verification_expires_at is missing (fail-safe)", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ + id: "privy_1", + custom_metadata: { verification_code_hash: "hashed_123456", verification_attempts: 0 }, + }); + const result = await validateAgentVerifyBody(VALID_BODY); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + + it("returns 400 when the code has expired", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ + id: "privy_1", + custom_metadata: metadataWith({ + verification_expires_at: new Date(Date.now() - 1_000).toISOString(), + }), + }); + const result = await validateAgentVerifyBody(VALID_BODY); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + + it("returns 429 when verification_attempts is at or above the limit", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ + id: "privy_1", + custom_metadata: metadataWith({ verification_attempts: 5 }), + }); + const result = await validateAgentVerifyBody(VALID_BODY); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(429); + }); }); - it("returns 400 for 5-digit code", () => { - const result = validateAgentVerifyBody({ email: "user@example.com", code: "12345" }); - expect(result).toBeInstanceOf(NextResponse); - expect((result as NextResponse).status).toBe(400); + describe("code comparison", () => { + it("returns 400 and increments attempts when the submitted code does not match", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ + id: "privy_1", + custom_metadata: metadataWith({ verification_code_hash: "hashed_999999" }), + }); + const result = await validateAgentVerifyBody(VALID_BODY); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + expect(setPrivyCustomMetadata).toHaveBeenCalledWith( + "privy_1", + expect.objectContaining({ verification_attempts: 1 }), + ); + }); }); - it("returns 400 for 7-digit code", () => { - const result = validateAgentVerifyBody({ email: "user@example.com", code: "1234567" }); - expect(result).toBeInstanceOf(NextResponse); - expect((result as NextResponse).status).toBe(400); + describe("account resolution", () => { + it("returns 400 when the email has no matching account", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ + id: "privy_1", + custom_metadata: metadataWith(), + }); + vi.mocked(selectAccountByEmail).mockResolvedValue(null); + const result = await validateAgentVerifyBody(VALID_BODY); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); }); - it("returns 400 for code with spaces", () => { - const result = validateAgentVerifyBody({ email: "user@example.com", code: "123 456" }); - expect(result).toBeInstanceOf(NextResponse); - expect((result as NextResponse).status).toBe(400); + describe("success", () => { + it("returns the resolved accountId and privyUserId", async () => { + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ + id: "privy_1", + custom_metadata: metadataWith(), + }); + vi.mocked(selectAccountByEmail).mockResolvedValue({ + account_id: "acc_123", + email: "user@example.com", + } as unknown as Awaited>); + + const result = await validateAgentVerifyBody(VALID_BODY); + + expect(result).not.toBeInstanceOf(NextResponse); + expect(result).toEqual({ accountId: "acc_123", privyUserId: "privy_1" }); + }); }); }); diff --git a/lib/agents/agentSignupHandler.ts b/lib/agents/agentSignupHandler.ts index ffa33c0c5..cc6b59e00 100644 --- a/lib/agents/agentSignupHandler.ts +++ b/lib/agents/agentSignupHandler.ts @@ -1,28 +1,19 @@ import { NextRequest, NextResponse } from "next/server"; -import { randomInt } from "crypto"; import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { safeParseJson } from "@/lib/networking/safeParseJson"; import { validateAgentSignupBody } from "@/lib/agents/validateAgentSignupBody"; import { selectAccountByEmail } from "@/lib/supabase/account_emails/selectAccountByEmail"; -import { insertAccount } from "@/lib/supabase/accounts/insertAccount"; -import { insertAccountEmail } from "@/lib/supabase/account_emails/insertAccountEmail"; -import { insertCreditsUsage } from "@/lib/supabase/credits_usage/insertCreditsUsage"; -import { assignAccountToOrg } from "@/lib/organizations/assignAccountToOrg"; -import { generateApiKey } from "@/lib/keys/generateApiKey"; -import { hashApiKey } from "@/lib/keys/hashApiKey"; -import { insertApiKey } from "@/lib/supabase/account_api_keys/insertApiKey"; import { isAgentPrefixEmail } from "@/lib/agents/isAgentPrefixEmail"; -import { createPrivyUser } from "@/lib/privy/createPrivyUser"; -import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; -import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; -import { sendVerificationEmail } from "@/lib/agents/sendVerificationEmail"; +import { handleAgentPrefixSignup } from "@/lib/agents/handleAgentPrefixSignup"; +import { handleExistingAccount } from "@/lib/agents/handleExistingAccount"; +import { handleNormalSignup } from "@/lib/agents/handleNormalSignup"; const GENERIC_MESSAGE = "If this is a new agent+ email, your API key is included. Otherwise, check your email for a verification code."; /** - * Handles agent signup flow — validates the request body and dispatches to - * the instant-signup, existing-account, or normal-signup path. + * Handles agent signup — validates the request body and dispatches to the + * instant-signup, existing-account, or normal-signup path. * * @param request - The incoming Next.js request with `{ email }` in the body * @returns NextResponse with `account_id`, `api_key` (or null), and `message` @@ -39,18 +30,14 @@ export async function agentSignupHandler(request: NextRequest): Promise { - const account = await insertAccount({}); - await insertAccountEmail(account.id, email); - await insertCreditsUsage(account.id); - await assignAccountToOrg(account.id, email); - return account.id; -} - -/** - * Generates a new API key, stores its hash, and returns the raw key. - * - * @param accountId - Account to associate the key with - * @returns The raw (un-hashed) API key string - */ -async function generateAndStoreApiKey(accountId: string): Promise { - const today = new Date().toISOString().slice(0, 10); - const rawKey = generateApiKey("recoup_sk"); - const keyHash = hashApiKey(rawKey, process.env.PROJECT_SECRET!); - await insertApiKey({ name: `Agent ${today}`, account: accountId, key_hash: keyHash }); - return rawKey; -} - -/** - * Instant-signup path for fresh `agent+` emails — returns an API key immediately. - * - * @param email - The `agent+` email address - * @returns NextResponse with the freshly generated API key - */ -async function handleAgentPrefixSignup(email: string): Promise { - const accountId = await createAccountWithEmail(email); - - const privyUser = await createPrivyUser(email); - await setPrivyCustomMetadata(privyUser.id, {}); - - const rawKey = await generateAndStoreApiKey(accountId); - - return NextResponse.json( - { account_id: accountId, api_key: rawKey, message: GENERIC_MESSAGE }, - { status: 200, headers: getCorsHeaders() }, - ); -} - -/** - * Generates a 6-digit code, stores its hash in Privy metadata, and emails it. - * - * @param email - Email to deliver the verification code to - */ -async function storeVerificationCode(email: string): Promise { - // randomInt upper bound is exclusive — use 1000000 to include 999999. - const code = randomInt(100000, 1000000).toString(); - const codeHash = hashApiKey(code, process.env.PROJECT_SECRET!); - const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(); - - let privyUser = await getPrivyUserByEmail(email); - if (!privyUser) { - privyUser = await createPrivyUser(email); - } - - await setPrivyCustomMetadata(privyUser.id, { - verification_code_hash: codeHash, - verification_expires_at: expiresAt, - verification_attempts: 0, - }); - - await sendVerificationEmail(email, code); -} - -/** - * Existing-account path — always sends a verification code, never returns a key. - * - * @param accountId - The existing account ID - * @param email - The email that matched an existing account - * @returns NextResponse with `api_key: null` - */ -async function handleExistingAccount(accountId: string, email: string): Promise { - await storeVerificationCode(email); - - return NextResponse.json( - { account_id: accountId, api_key: null, message: GENERIC_MESSAGE }, - { status: 200, headers: getCorsHeaders() }, - ); -} - -/** - * Non-`agent+` new-account path — creates the account, then sends a verification code. - * - * @param email - Email for the new account - * @returns NextResponse with `api_key: null` - */ -async function handleNormalSignup(email: string): Promise { - const accountId = await createAccountWithEmail(email); - await storeVerificationCode(email); - - return NextResponse.json( - { account_id: accountId, api_key: null, message: GENERIC_MESSAGE }, - { status: 200, headers: getCorsHeaders() }, - ); -} diff --git a/lib/agents/agentVerifyHandler.ts b/lib/agents/agentVerifyHandler.ts index e33b3f7ee..a0b272590 100644 --- a/lib/agents/agentVerifyHandler.ts +++ b/lib/agents/agentVerifyHandler.ts @@ -2,19 +2,14 @@ import { NextRequest, NextResponse } from "next/server"; import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { safeParseJson } from "@/lib/networking/safeParseJson"; import { validateAgentVerifyBody } from "@/lib/agents/validateAgentVerifyBody"; -import { selectAccountByEmail } from "@/lib/supabase/account_emails/selectAccountByEmail"; -import { generateApiKey } from "@/lib/keys/generateApiKey"; -import { hashApiKey } from "@/lib/keys/hashApiKey"; -import { insertApiKey } from "@/lib/supabase/account_api_keys/insertApiKey"; -import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; +import { generateAndStoreApiKey } from "@/lib/agents/generateAndStoreApiKey"; import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; -const GENERIC_ERROR = "Invalid or expired verification code."; -const MAX_ATTEMPTS = 5; - /** - * Handles agent email verification — validates the request body, checks the - * submitted code against the stored hash, and returns an API key on success. + * Handles agent email verification. All prerequisite checks (body shape, + * stored verification state, code comparison, account resolution) live in + * `validateAgentVerifyBody`. Once validation passes, this handler issues an + * API key and clears the Privy verification metadata. * * @param request - The incoming Next.js request with `{ email, code }` in the body * @returns NextResponse with `account_id`, `api_key`, and `message` on success @@ -23,102 +18,14 @@ export async function agentVerifyHandler(request: NextRequest): Promise expiresAt) { - return NextResponse.json( - { error: GENERIC_ERROR }, - { status: 400, headers: getCorsHeaders() }, - ); - } - - // Too many attempts - const attempts = metadata.verification_attempts ?? 0; - if (attempts >= MAX_ATTEMPTS) { - return NextResponse.json( - { error: "Too many failed verification attempts. Please request a new code." }, - { status: 429, headers: getCorsHeaders() }, - ); - } - - // Compare hashes - const providedHash = hashApiKey(code, process.env.PROJECT_SECRET!); - if (providedHash !== metadata.verification_code_hash) { - // Increment attempts - await setPrivyCustomMetadata(privyUser.id, { - ...metadata, - verification_attempts: attempts + 1, - }); - - return NextResponse.json( - { error: GENERIC_ERROR }, - { status: 400, headers: getCorsHeaders() }, - ); - } - - // Code matches — generate API key - const existingAccount = await selectAccountByEmail(email); - if (!existingAccount) { - return NextResponse.json( - { error: GENERIC_ERROR }, - { status: 400, headers: getCorsHeaders() }, - ); - } - - const accountId = existingAccount.account_id; - const today = new Date().toISOString().slice(0, 10); - const rawKey = generateApiKey("recoup_sk"); - const keyHash = hashApiKey(rawKey, process.env.PROJECT_SECRET!); - const { error: insertError } = await insertApiKey({ - name: `Agent ${today}`, - account: accountId, - key_hash: keyHash, - }); - if (insertError) { - console.error("[ERROR] agentVerifyHandler: insertApiKey failed", insertError); - return NextResponse.json( - { error: "Internal server error" }, - { status: 500, headers: getCorsHeaders() }, - ); - } - - // Clear custom_metadata - await setPrivyCustomMetadata(privyUser.id, {}); + const { accountId, privyUserId } = validated; + const rawKey = await generateAndStoreApiKey(accountId); + await setPrivyCustomMetadata(privyUserId, {}); return NextResponse.json( { account_id: accountId, api_key: rawKey, message: "Verified" }, diff --git a/lib/agents/createAccountWithEmail.ts b/lib/agents/createAccountWithEmail.ts new file mode 100644 index 000000000..5ef08ee78 --- /dev/null +++ b/lib/agents/createAccountWithEmail.ts @@ -0,0 +1,19 @@ +import { insertAccount } from "@/lib/supabase/accounts/insertAccount"; +import { insertAccountEmail } from "@/lib/supabase/account_emails/insertAccountEmail"; +import { insertCreditsUsage } from "@/lib/supabase/credits_usage/insertCreditsUsage"; +import { assignAccountToOrg } from "@/lib/organizations/assignAccountToOrg"; + +/** + * Creates a new account row and wires up its email, credits usage, and org + * membership. Used by the agent signup flow. + * + * @param email - Email to associate with the new account + * @returns The new account ID + */ +export async function createAccountWithEmail(email: string): Promise { + const account = await insertAccount({}); + await insertAccountEmail(account.id, email); + await insertCreditsUsage(account.id); + await assignAccountToOrg(account.id, email); + return account.id; +} diff --git a/lib/agents/generateAndStoreApiKey.ts b/lib/agents/generateAndStoreApiKey.ts new file mode 100644 index 000000000..2077ec6fa --- /dev/null +++ b/lib/agents/generateAndStoreApiKey.ts @@ -0,0 +1,27 @@ +import { generateApiKey } from "@/lib/keys/generateApiKey"; +import { hashApiKey } from "@/lib/keys/hashApiKey"; +import { insertApiKey } from "@/lib/supabase/account_api_keys/insertApiKey"; + +/** + * Generates a new API key for an account, stores its hash in the database, + * and returns the raw key. Throws if the database insert fails — this is the + * load-bearing guarantee that prevents the caller from leaking an + * un-persisted API key back to the user. + * + * @param accountId - Account to associate the key with + * @returns The raw (un-hashed) API key string + */ +export async function generateAndStoreApiKey(accountId: string): Promise { + const today = new Date().toISOString().slice(0, 10); + const rawKey = generateApiKey("recoup_sk"); + const keyHash = hashApiKey(rawKey, process.env.PROJECT_SECRET!); + const { error } = await insertApiKey({ + name: `Agent ${today}`, + account: accountId, + key_hash: keyHash, + }); + if (error) { + throw new Error(`insertApiKey failed: ${error.message ?? "unknown error"}`); + } + return rawKey; +} diff --git a/lib/agents/handleAgentPrefixSignup.ts b/lib/agents/handleAgentPrefixSignup.ts new file mode 100644 index 000000000..2aa5a811c --- /dev/null +++ b/lib/agents/handleAgentPrefixSignup.ts @@ -0,0 +1,30 @@ +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { createAccountWithEmail } from "@/lib/agents/createAccountWithEmail"; +import { generateAndStoreApiKey } from "@/lib/agents/generateAndStoreApiKey"; +import { createPrivyUser } from "@/lib/privy/createPrivyUser"; +import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; + +const GENERIC_MESSAGE = + "If this is a new agent+ email, your API key is included. Otherwise, check your email for a verification code."; + +/** + * Instant-signup path for fresh `agent+` emails — creates the account, a + * matching Privy user, and an API key, then returns the key immediately. + * + * @param email - The `agent+` email address + * @returns NextResponse with the freshly generated API key + */ +export async function handleAgentPrefixSignup(email: string): Promise { + const accountId = await createAccountWithEmail(email); + + const privyUser = await createPrivyUser(email); + await setPrivyCustomMetadata(privyUser.id, {}); + + const rawKey = await generateAndStoreApiKey(accountId); + + return NextResponse.json( + { account_id: accountId, api_key: rawKey, message: GENERIC_MESSAGE }, + { status: 200, headers: getCorsHeaders() }, + ); +} diff --git a/lib/agents/handleExistingAccount.ts b/lib/agents/handleExistingAccount.ts new file mode 100644 index 000000000..5bfd4c85b --- /dev/null +++ b/lib/agents/handleExistingAccount.ts @@ -0,0 +1,26 @@ +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { storeVerificationCode } from "@/lib/agents/storeVerificationCode"; + +const GENERIC_MESSAGE = + "If this is a new agent+ email, your API key is included. Otherwise, check your email for a verification code."; + +/** + * Existing-account path — email already has an account, so we never issue a + * key directly. Always sends a verification code and returns `api_key: null`. + * + * @param accountId - The existing account ID + * @param email - The email that matched an existing account + * @returns NextResponse with `api_key: null` + */ +export async function handleExistingAccount( + accountId: string, + email: string, +): Promise { + await storeVerificationCode(email); + + return NextResponse.json( + { account_id: accountId, api_key: null, message: GENERIC_MESSAGE }, + { status: 200, headers: getCorsHeaders() }, + ); +} diff --git a/lib/agents/handleNormalSignup.ts b/lib/agents/handleNormalSignup.ts new file mode 100644 index 000000000..09ef7d29c --- /dev/null +++ b/lib/agents/handleNormalSignup.ts @@ -0,0 +1,25 @@ +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { createAccountWithEmail } from "@/lib/agents/createAccountWithEmail"; +import { storeVerificationCode } from "@/lib/agents/storeVerificationCode"; + +const GENERIC_MESSAGE = + "If this is a new agent+ email, your API key is included. Otherwise, check your email for a verification code."; + +/** + * Non-`agent+` new-account path — creates a fresh account and sends a + * verification code. The account is created immediately but the API key is + * only issued after the caller verifies the code via `/api/agents/verify`. + * + * @param email - Email for the new account + * @returns NextResponse with `api_key: null` + */ +export async function handleNormalSignup(email: string): Promise { + const accountId = await createAccountWithEmail(email); + await storeVerificationCode(email); + + return NextResponse.json( + { account_id: accountId, api_key: null, message: GENERIC_MESSAGE }, + { status: 200, headers: getCorsHeaders() }, + ); +} diff --git a/lib/agents/storeVerificationCode.ts b/lib/agents/storeVerificationCode.ts new file mode 100644 index 000000000..138cdbb2b --- /dev/null +++ b/lib/agents/storeVerificationCode.ts @@ -0,0 +1,34 @@ +import { randomInt } from "crypto"; +import { hashApiKey } from "@/lib/keys/hashApiKey"; +import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; +import { createPrivyUser } from "@/lib/privy/createPrivyUser"; +import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; +import { sendVerificationEmail } from "@/lib/agents/sendVerificationEmail"; + +const EXPIRY_MS = 24 * 60 * 60 * 1000; + +/** + * Generates a 6-digit verification code, stores its hash in the Privy user's + * `custom_metadata` (creating the Privy user if needed), and emails the code. + * + * @param email - Email to deliver the verification code to + */ +export async function storeVerificationCode(email: string): Promise { + // randomInt upper bound is exclusive — use 1000000 so 999999 is reachable. + const code = randomInt(100000, 1000000).toString(); + const codeHash = hashApiKey(code, process.env.PROJECT_SECRET!); + const expiresAt = new Date(Date.now() + EXPIRY_MS).toISOString(); + + let privyUser = await getPrivyUserByEmail(email); + if (!privyUser) { + privyUser = await createPrivyUser(email); + } + + await setPrivyCustomMetadata(privyUser.id, { + verification_code_hash: codeHash, + verification_expires_at: expiresAt, + verification_attempts: 0, + }); + + await sendVerificationEmail(email, code); +} diff --git a/lib/agents/validateAgentVerifyBody.ts b/lib/agents/validateAgentVerifyBody.ts index e62f6460a..a61fbf883 100644 --- a/lib/agents/validateAgentVerifyBody.ts +++ b/lib/agents/validateAgentVerifyBody.ts @@ -1,6 +1,13 @@ import { NextResponse } from "next/server"; -import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { z } from "zod"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { hashApiKey } from "@/lib/keys/hashApiKey"; +import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; +import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; +import { selectAccountByEmail } from "@/lib/supabase/account_emails/selectAccountByEmail"; + +const GENERIC_ERROR = "Invalid or expired verification code."; +const MAX_ATTEMPTS = 5; export const agentVerifyBodySchema = z.object({ email: z.string({ message: "email is required" }).email("email must be a valid email address"), @@ -10,28 +17,93 @@ export const agentVerifyBodySchema = z.object({ export type AgentVerifyBody = z.infer; /** - * Validates request body for POST /api/agents/verify. + * Resolved verify request — the caller is cleared to issue an API key for + * `accountId` and clear metadata on `privyUserId`. + */ +export type ValidatedAgentVerifyRequest = { + accountId: string; + privyUserId: string; +}; + +type StoredVerification = { + verification_code_hash?: string; + verification_expires_at?: string; + verification_attempts?: number; +}; + +/** + * Builds a JSON error response with CORS headers. * - * @param body - The request body - * @returns A NextResponse with an error if validation fails, or the validated body + * @param error - Human-readable error message + * @param status - HTTP status code + * @returns NextResponse with the given error payload */ -export function validateAgentVerifyBody(body: unknown): NextResponse | AgentVerifyBody { - const result = agentVerifyBodySchema.safeParse(body); +function errorResponse(error: string, status: number): NextResponse { + return NextResponse.json({ error }, { status, headers: getCorsHeaders() }); +} - if (!result.success) { - const firstError = result.error.issues[0]; +/** + * Validates a POST /api/agents/verify request end-to-end. Checks include: + * the body shape (email + 6-digit code), the Privy-stored verification + * metadata (code hash, expiry, attempts), the supplied code against the + * stored hash (and increments attempts on mismatch), and resolves the + * email to an account. All prerequisite checks live here so the handler + * can reduce to "if validation passes, issue an API key". + * + * @param body - The raw request body + * @returns NextResponse on any failure, or the resolved `accountId` + `privyUserId` on success + */ +export async function validateAgentVerifyBody( + body: unknown, +): Promise { + const parsed = agentVerifyBodySchema.safeParse(body); + if (!parsed.success) { + const firstError = parsed.error.issues[0]; return NextResponse.json( - { - status: "error", - missing_fields: firstError.path, - error: firstError.message, - }, - { - status: 400, - headers: getCorsHeaders(), - }, + { status: "error", missing_fields: firstError.path, error: firstError.message }, + { status: 400, headers: getCorsHeaders() }, ); } - return result.data; + const { email, code } = parsed.data; + + const privyUser = await getPrivyUserByEmail(email); + if (!privyUser?.custom_metadata) { + return errorResponse(GENERIC_ERROR, 400); + } + + const metadata = privyUser.custom_metadata as StoredVerification; + + if (!metadata.verification_code_hash) { + return errorResponse(GENERIC_ERROR, 400); + } + + // Fail-safe: missing expiry is treated as expired. + if (!metadata.verification_expires_at) { + return errorResponse(GENERIC_ERROR, 400); + } + if (Date.now() > new Date(metadata.verification_expires_at).getTime()) { + return errorResponse(GENERIC_ERROR, 400); + } + + const attempts = metadata.verification_attempts ?? 0; + if (attempts >= MAX_ATTEMPTS) { + return errorResponse("Too many failed verification attempts. Please request a new code.", 429); + } + + const providedHash = hashApiKey(code, process.env.PROJECT_SECRET!); + if (providedHash !== metadata.verification_code_hash) { + await setPrivyCustomMetadata(privyUser.id, { + ...metadata, + verification_attempts: attempts + 1, + }); + return errorResponse(GENERIC_ERROR, 400); + } + + const existingAccount = await selectAccountByEmail(email); + if (!existingAccount) { + return errorResponse(GENERIC_ERROR, 400); + } + + return { accountId: existingAccount.account_id, privyUserId: privyUser.id }; } From 03c24c6570a5afd419018cfe70e54f17640f6581 Mon Sep 17 00:00:00 2001 From: Sweets Sweetman Date: Sat, 11 Apr 2026 20:12:38 -0500 Subject: [PATCH 4/6] refactor(agents): consolidate validation, share helpers, security fix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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@"}'` 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) --- .../__tests__/agentSignupHandler.test.ts | 8 +-- .../__tests__/createAccountWithEmail.test.ts | 37 +++++++--- .../__tests__/validateAgentSignupBody.test.ts | 45 +++++++++--- .../__tests__/validateAgentVerifyBody.test.ts | 69 +++++++++++++------ lib/agents/agentSignupHandler.ts | 13 ++-- lib/agents/agentVerifyHandler.ts | 5 +- lib/agents/createAccountWithEmail.ts | 29 ++++++-- lib/agents/handleAgentPrefixSignup.ts | 6 +- lib/agents/handleExistingAccount.ts | 6 +- lib/agents/handleNormalSignup.ts | 6 +- lib/agents/validateAgentSignupBody.ts | 19 +++-- lib/agents/validateAgentVerifyBody.ts | 33 ++++----- lib/const.ts | 9 +++ .../__tests__/errorResponse.test.ts | 21 ++++++ lib/networking/errorResponse.ts | 15 ++++ 15 files changed, 216 insertions(+), 105 deletions(-) create mode 100644 lib/networking/__tests__/errorResponse.test.ts create mode 100644 lib/networking/errorResponse.ts diff --git a/lib/agents/__tests__/agentSignupHandler.test.ts b/lib/agents/__tests__/agentSignupHandler.test.ts index 566aae86e..0736e21d5 100644 --- a/lib/agents/__tests__/agentSignupHandler.test.ts +++ b/lib/agents/__tests__/agentSignupHandler.test.ts @@ -33,15 +33,11 @@ vi.mock("@/lib/supabase/accounts/insertAccount", () => ({ })); vi.mock("@/lib/supabase/account_emails/insertAccountEmail", () => ({ - insertAccountEmail: vi.fn(), + insertAccountEmail: vi.fn(() => ({ id: "ae_1" })), })); vi.mock("@/lib/supabase/credits_usage/insertCreditsUsage", () => ({ - insertCreditsUsage: vi.fn(), -})); - -vi.mock("@/lib/organizations/assignAccountToOrg", () => ({ - assignAccountToOrg: vi.fn(), + insertCreditsUsage: vi.fn(() => ({ id: "cu_1" })), })); vi.mock("@/lib/keys/generateApiKey", () => ({ diff --git a/lib/agents/__tests__/createAccountWithEmail.test.ts b/lib/agents/__tests__/createAccountWithEmail.test.ts index f88e2f5ed..5dba14dc4 100644 --- a/lib/agents/__tests__/createAccountWithEmail.test.ts +++ b/lib/agents/__tests__/createAccountWithEmail.test.ts @@ -3,40 +3,55 @@ import { createAccountWithEmail } from "@/lib/agents/createAccountWithEmail"; import { insertAccount } from "@/lib/supabase/accounts/insertAccount"; import { insertAccountEmail } from "@/lib/supabase/account_emails/insertAccountEmail"; import { insertCreditsUsage } from "@/lib/supabase/credits_usage/insertCreditsUsage"; -import { assignAccountToOrg } from "@/lib/organizations/assignAccountToOrg"; vi.mock("@/lib/supabase/accounts/insertAccount", () => ({ insertAccount: vi.fn(), })); vi.mock("@/lib/supabase/account_emails/insertAccountEmail", () => ({ - insertAccountEmail: vi.fn(), + insertAccountEmail: vi.fn(() => ({ id: "ae_1" })), })); vi.mock("@/lib/supabase/credits_usage/insertCreditsUsage", () => ({ - insertCreditsUsage: vi.fn(), -})); - -vi.mock("@/lib/organizations/assignAccountToOrg", () => ({ - assignAccountToOrg: vi.fn(), + insertCreditsUsage: vi.fn(() => ({ id: "cu_1" })), })); describe("createAccountWithEmail", () => { beforeEach(() => { vi.clearAllMocks(); - }); - - it("creates account, inserts email, credits, and assigns to org", async () => { vi.mocked(insertAccount).mockResolvedValue({ id: "acc_new" } as unknown as Awaited< ReturnType >); + vi.mocked(insertAccountEmail).mockResolvedValue({ + id: "ae_1", + } as unknown as Awaited>); + vi.mocked(insertCreditsUsage).mockResolvedValue({ + id: "cu_1", + } as unknown as Awaited>); + }); + it("creates the account, inserts the email link and credits row, and returns the new account id", async () => { const result = await createAccountWithEmail("user@example.com"); expect(result).toBe("acc_new"); expect(insertAccount).toHaveBeenCalledOnce(); expect(insertAccountEmail).toHaveBeenCalledWith("acc_new", "user@example.com"); expect(insertCreditsUsage).toHaveBeenCalledWith("acc_new"); - expect(assignAccountToOrg).toHaveBeenCalledWith("acc_new", "user@example.com"); + }); + + it("throws when insertAccountEmail returns null so the caller cannot end up with an emailless account", async () => { + vi.mocked(insertAccountEmail).mockResolvedValueOnce( + null as unknown as Awaited>, + ); + + await expect(createAccountWithEmail("user@example.com")).rejects.toThrow(/insertAccountEmail/); + }); + + it("throws when insertCreditsUsage returns null", async () => { + vi.mocked(insertCreditsUsage).mockResolvedValueOnce( + null as unknown as Awaited>, + ); + + await expect(createAccountWithEmail("user@example.com")).rejects.toThrow(/insertCreditsUsage/); }); }); diff --git a/lib/agents/__tests__/validateAgentSignupBody.test.ts b/lib/agents/__tests__/validateAgentSignupBody.test.ts index 562a5842b..fa7aaca83 100644 --- a/lib/agents/__tests__/validateAgentSignupBody.test.ts +++ b/lib/agents/__tests__/validateAgentSignupBody.test.ts @@ -1,32 +1,55 @@ import { describe, it, expect } from "vitest"; -import { NextResponse } from "next/server"; +import { NextRequest, NextResponse } from "next/server"; import { validateAgentSignupBody } from "@/lib/agents/validateAgentSignupBody"; +/** + * Builds a NextRequest with the given body for the agent signup endpoint. + * + * @param body - JSON body to serialize, or undefined for an empty request + * @returns A NextRequest pointed at /api/agents/signup + */ +function buildRequest(body: unknown): NextRequest { + return new NextRequest("http://localhost/api/agents/signup", { + method: "POST", + body: body === undefined ? undefined : JSON.stringify(body), + }); +} + describe("validateAgentSignupBody", () => { - it("returns validated body for valid email", () => { - const result = validateAgentSignupBody({ email: "agent+test@example.com" }); + it("returns validated body for valid agent+ email", async () => { + const result = await validateAgentSignupBody(buildRequest({ email: "agent+test@example.com" })); expect(result).toEqual({ email: "agent+test@example.com" }); }); - it("returns validated body for normal email", () => { - const result = validateAgentSignupBody({ email: "user@example.com" }); + it("returns validated body for normal email", async () => { + const result = await validateAgentSignupBody(buildRequest({ email: "user@example.com" })); expect(result).toEqual({ email: "user@example.com" }); }); - it("returns 400 for missing email", () => { - const result = validateAgentSignupBody({}); + it("returns 400 for missing email", async () => { + const result = await validateAgentSignupBody(buildRequest({})); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + + it("returns 400 for invalid email", async () => { + const result = await validateAgentSignupBody(buildRequest({ email: "not-an-email" })); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); }); - it("returns 400 for invalid email", () => { - const result = validateAgentSignupBody({ email: "not-an-email" }); + it("returns 400 for empty body", async () => { + const result = await validateAgentSignupBody(buildRequest(undefined)); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); }); - it("returns 400 for empty body", () => { - const result = validateAgentSignupBody(null); + it("returns 400 for malformed JSON body", async () => { + const req = new NextRequest("http://localhost/api/agents/signup", { + method: "POST", + body: "{not valid json", + }); + const result = await validateAgentSignupBody(req); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); }); diff --git a/lib/agents/__tests__/validateAgentVerifyBody.test.ts b/lib/agents/__tests__/validateAgentVerifyBody.test.ts index 9ea0710df..85ef86a5e 100644 --- a/lib/agents/__tests__/validateAgentVerifyBody.test.ts +++ b/lib/agents/__tests__/validateAgentVerifyBody.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; -import { NextResponse } from "next/server"; +import { NextRequest, NextResponse } from "next/server"; import { validateAgentVerifyBody } from "@/lib/agents/validateAgentVerifyBody"; import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; @@ -9,6 +9,19 @@ vi.mock("@/lib/networking/getCorsHeaders", () => ({ getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })), })); +/** + * Builds a NextRequest with the given JSON body for the verify endpoint. + * + * @param body - JSON-serializable body, or undefined for an empty request + * @returns A NextRequest pointed at /api/agents/verify + */ +function buildRequest(body: unknown): NextRequest { + return new NextRequest("http://localhost/api/agents/verify", { + method: "POST", + body: body === undefined ? undefined : JSON.stringify(body), + }); +} + vi.mock("@/lib/privy/getPrivyUserByEmail", () => ({ getPrivyUserByEmail: vi.fn(), })); @@ -25,11 +38,21 @@ vi.mock("@/lib/keys/hashApiKey", () => ({ hashApiKey: vi.fn((input: string) => `hashed_${input}`), })); -const VALID_BODY = { email: "user@example.com", code: "123456" }; - -function metadataWith( - overrides: Record = {}, -): { verification_code_hash: string; verification_expires_at: string; verification_attempts: number } { +const VALID_REQUEST = () => buildRequest({ email: "user@example.com", code: "123456" }); + +/** + * Builds a Privy `custom_metadata` payload with sensible defaults that + * pass every prerequisite check, letting individual tests override only + * the field they want to exercise. + * + * @param overrides - Fields to overlay on top of the valid defaults + * @returns A fully populated metadata object + */ +function metadataWith(overrides: Record = {}): { + verification_code_hash: string; + verification_expires_at: string; + verification_attempts: number; +} { return { verification_code_hash: "hashed_123456", verification_expires_at: new Date(Date.now() + 60_000).toISOString(), @@ -50,37 +73,43 @@ describe("validateAgentVerifyBody", () => { describe("body shape", () => { it("returns 400 for missing email", async () => { - const result = await validateAgentVerifyBody({ code: "123456" }); + const result = await validateAgentVerifyBody(buildRequest({ code: "123456" })); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); }); it("returns 400 for missing code", async () => { - const result = await validateAgentVerifyBody({ email: "user@example.com" }); + const result = await validateAgentVerifyBody(buildRequest({ email: "user@example.com" })); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); }); it("returns 400 for invalid email", async () => { - const result = await validateAgentVerifyBody({ email: "bad", code: "123456" }); + const result = await validateAgentVerifyBody(buildRequest({ email: "bad", code: "123456" })); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); }); it("returns 400 for non-numeric code", async () => { - const result = await validateAgentVerifyBody({ email: "user@example.com", code: "abcdef" }); + const result = await validateAgentVerifyBody( + buildRequest({ email: "user@example.com", code: "abcdef" }), + ); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); }); it("returns 400 for 5-digit code", async () => { - const result = await validateAgentVerifyBody({ email: "user@example.com", code: "12345" }); + const result = await validateAgentVerifyBody( + buildRequest({ email: "user@example.com", code: "12345" }), + ); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); }); it("returns 400 for 7-digit code", async () => { - const result = await validateAgentVerifyBody({ email: "user@example.com", code: "1234567" }); + const result = await validateAgentVerifyBody( + buildRequest({ email: "user@example.com", code: "1234567" }), + ); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); }); @@ -89,7 +118,7 @@ describe("validateAgentVerifyBody", () => { describe("stored verification state", () => { it("returns 400 when Privy user is missing", async () => { vi.mocked(getPrivyUserByEmail).mockResolvedValue(null); - const result = await validateAgentVerifyBody(VALID_BODY); + const result = await validateAgentVerifyBody(VALID_REQUEST()); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); }); @@ -99,7 +128,7 @@ describe("validateAgentVerifyBody", () => { id: "privy_1", custom_metadata: {}, }); - const result = await validateAgentVerifyBody(VALID_BODY); + const result = await validateAgentVerifyBody(VALID_REQUEST()); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); }); @@ -109,7 +138,7 @@ describe("validateAgentVerifyBody", () => { id: "privy_1", custom_metadata: { verification_code_hash: "hashed_123456", verification_attempts: 0 }, }); - const result = await validateAgentVerifyBody(VALID_BODY); + const result = await validateAgentVerifyBody(VALID_REQUEST()); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); }); @@ -121,7 +150,7 @@ describe("validateAgentVerifyBody", () => { verification_expires_at: new Date(Date.now() - 1_000).toISOString(), }), }); - const result = await validateAgentVerifyBody(VALID_BODY); + const result = await validateAgentVerifyBody(VALID_REQUEST()); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); }); @@ -131,7 +160,7 @@ describe("validateAgentVerifyBody", () => { id: "privy_1", custom_metadata: metadataWith({ verification_attempts: 5 }), }); - const result = await validateAgentVerifyBody(VALID_BODY); + const result = await validateAgentVerifyBody(VALID_REQUEST()); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(429); }); @@ -143,7 +172,7 @@ describe("validateAgentVerifyBody", () => { id: "privy_1", custom_metadata: metadataWith({ verification_code_hash: "hashed_999999" }), }); - const result = await validateAgentVerifyBody(VALID_BODY); + const result = await validateAgentVerifyBody(VALID_REQUEST()); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); expect(setPrivyCustomMetadata).toHaveBeenCalledWith( @@ -160,7 +189,7 @@ describe("validateAgentVerifyBody", () => { custom_metadata: metadataWith(), }); vi.mocked(selectAccountByEmail).mockResolvedValue(null); - const result = await validateAgentVerifyBody(VALID_BODY); + const result = await validateAgentVerifyBody(VALID_REQUEST()); expect(result).toBeInstanceOf(NextResponse); expect((result as NextResponse).status).toBe(400); }); @@ -177,7 +206,7 @@ describe("validateAgentVerifyBody", () => { email: "user@example.com", } as unknown as Awaited>); - const result = await validateAgentVerifyBody(VALID_BODY); + const result = await validateAgentVerifyBody(VALID_REQUEST()); expect(result).not.toBeInstanceOf(NextResponse); expect(result).toEqual({ accountId: "acc_123", privyUserId: "privy_1" }); diff --git a/lib/agents/agentSignupHandler.ts b/lib/agents/agentSignupHandler.ts index cc6b59e00..1d470b1e4 100644 --- a/lib/agents/agentSignupHandler.ts +++ b/lib/agents/agentSignupHandler.ts @@ -1,6 +1,6 @@ import { NextRequest, NextResponse } from "next/server"; import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; -import { safeParseJson } from "@/lib/networking/safeParseJson"; +import { AGENT_SIGNUP_GENERIC_MESSAGE } from "@/lib/const"; import { validateAgentSignupBody } from "@/lib/agents/validateAgentSignupBody"; import { selectAccountByEmail } from "@/lib/supabase/account_emails/selectAccountByEmail"; import { isAgentPrefixEmail } from "@/lib/agents/isAgentPrefixEmail"; @@ -8,11 +8,8 @@ import { handleAgentPrefixSignup } from "@/lib/agents/handleAgentPrefixSignup"; import { handleExistingAccount } from "@/lib/agents/handleExistingAccount"; import { handleNormalSignup } from "@/lib/agents/handleNormalSignup"; -const GENERIC_MESSAGE = - "If this is a new agent+ email, your API key is included. Otherwise, check your email for a verification code."; - /** - * Handles agent signup — validates the request body and dispatches to the + * Handles agent signup — validates the request and dispatches to the * instant-signup, existing-account, or normal-signup path. * * @param request - The incoming Next.js request with `{ email }` in the body @@ -20,9 +17,7 @@ const GENERIC_MESSAGE = */ export async function agentSignupHandler(request: NextRequest): Promise { try { - const body = await safeParseJson(request); - - const validated = validateAgentSignupBody(body); + const validated = await validateAgentSignupBody(request); if (validated instanceof NextResponse) { return validated; } @@ -42,7 +37,7 @@ export async function agentSignupHandler(request: NextRequest): Promise { try { - const body = await safeParseJson(request); - - const validated = await validateAgentVerifyBody(body); + const validated = await validateAgentVerifyBody(request); if (validated instanceof NextResponse) { return validated; } diff --git a/lib/agents/createAccountWithEmail.ts b/lib/agents/createAccountWithEmail.ts index 5ef08ee78..2ae486d78 100644 --- a/lib/agents/createAccountWithEmail.ts +++ b/lib/agents/createAccountWithEmail.ts @@ -1,19 +1,36 @@ import { insertAccount } from "@/lib/supabase/accounts/insertAccount"; import { insertAccountEmail } from "@/lib/supabase/account_emails/insertAccountEmail"; import { insertCreditsUsage } from "@/lib/supabase/credits_usage/insertCreditsUsage"; -import { assignAccountToOrg } from "@/lib/organizations/assignAccountToOrg"; /** - * Creates a new account row and wires up its email, credits usage, and org - * membership. Used by the agent signup flow. + * Creates a new account row and wires up its email link and credits usage + * row. Used by the unauthenticated agent signup flow. + * + * Deliberately does NOT call `assignAccountToOrg`. The org-by-domain + * assignment is appropriate for human signups (which are gated by Privy + * email-ownership proof) but is unsafe for the agent path because the + * agent+ shortcut is unauthenticated and bypasses email verification — + * an attacker could mint a key auto-joined to any domain-verified org. + * Org membership for agents must be a deliberate post-signup admin step. + * + * Throws on any DB write failure so the caller cannot leak an account + * that lacks an email link or credits row. * * @param email - Email to associate with the new account * @returns The new account ID */ export async function createAccountWithEmail(email: string): Promise { const account = await insertAccount({}); - await insertAccountEmail(account.id, email); - await insertCreditsUsage(account.id); - await assignAccountToOrg(account.id, email); + + const emailLink = await insertAccountEmail(account.id, email); + if (!emailLink) { + throw new Error("createAccountWithEmail: insertAccountEmail returned null"); + } + + const credits = await insertCreditsUsage(account.id); + if (!credits) { + throw new Error("createAccountWithEmail: insertCreditsUsage returned null"); + } + return account.id; } diff --git a/lib/agents/handleAgentPrefixSignup.ts b/lib/agents/handleAgentPrefixSignup.ts index 2aa5a811c..9fcf91674 100644 --- a/lib/agents/handleAgentPrefixSignup.ts +++ b/lib/agents/handleAgentPrefixSignup.ts @@ -1,13 +1,11 @@ import { NextResponse } from "next/server"; import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { AGENT_SIGNUP_GENERIC_MESSAGE } from "@/lib/const"; import { createAccountWithEmail } from "@/lib/agents/createAccountWithEmail"; import { generateAndStoreApiKey } from "@/lib/agents/generateAndStoreApiKey"; import { createPrivyUser } from "@/lib/privy/createPrivyUser"; import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; -const GENERIC_MESSAGE = - "If this is a new agent+ email, your API key is included. Otherwise, check your email for a verification code."; - /** * Instant-signup path for fresh `agent+` emails — creates the account, a * matching Privy user, and an API key, then returns the key immediately. @@ -24,7 +22,7 @@ export async function handleAgentPrefixSignup(email: string): Promise { await storeVerificationCode(email); return NextResponse.json( - { account_id: accountId, api_key: null, message: GENERIC_MESSAGE }, + { account_id: accountId, api_key: null, message: AGENT_SIGNUP_GENERIC_MESSAGE }, { status: 200, headers: getCorsHeaders() }, ); } diff --git a/lib/agents/validateAgentSignupBody.ts b/lib/agents/validateAgentSignupBody.ts index 1571006c7..077aa96e8 100644 --- a/lib/agents/validateAgentSignupBody.ts +++ b/lib/agents/validateAgentSignupBody.ts @@ -1,6 +1,7 @@ -import { NextResponse } from "next/server"; -import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { safeParseJson } from "@/lib/networking/safeParseJson"; export const agentSignupBodySchema = z.object({ email: z.string({ message: "email is required" }).email("email must be a valid email address"), @@ -9,12 +10,18 @@ export const agentSignupBodySchema = z.object({ export type AgentSignupBody = z.infer; /** - * Validates request body for POST /api/agents/signup. + * Validates POST /api/agents/signup. Parses the request body, runs the + * zod schema check, and returns either the validated body or a 400 + * NextResponse describing the first failure. The handler does not need + * to know about JSON parsing or zod — it just receives the typed body. * - * @param body - The request body - * @returns A NextResponse with an error if validation fails, or the validated body + * @param request - The incoming Next.js request + * @returns NextResponse with an error if validation fails, or the validated body */ -export function validateAgentSignupBody(body: unknown): NextResponse | AgentSignupBody { +export async function validateAgentSignupBody( + request: NextRequest, +): Promise { + const body = await safeParseJson(request); const result = agentSignupBodySchema.safeParse(body); if (!result.success) { diff --git a/lib/agents/validateAgentVerifyBody.ts b/lib/agents/validateAgentVerifyBody.ts index a61fbf883..1554e2668 100644 --- a/lib/agents/validateAgentVerifyBody.ts +++ b/lib/agents/validateAgentVerifyBody.ts @@ -1,6 +1,8 @@ -import { NextResponse } from "next/server"; +import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { safeParseJson } from "@/lib/networking/safeParseJson"; +import { errorResponse } from "@/lib/networking/errorResponse"; import { hashApiKey } from "@/lib/keys/hashApiKey"; import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; @@ -32,30 +34,21 @@ type StoredVerification = { }; /** - * Builds a JSON error response with CORS headers. + * Validates a POST /api/agents/verify request end-to-end. Parses the body, + * runs the zod schema check, looks up the Privy user, verifies the stored + * verification metadata (code hash, expiry, attempts), compares the + * supplied code against the stored hash (and increments attempts on + * mismatch), and resolves the email to an account. All prerequisite + * checks live here so the handler can reduce to "if validation passes, + * issue an API key". * - * @param error - Human-readable error message - * @param status - HTTP status code - * @returns NextResponse with the given error payload - */ -function errorResponse(error: string, status: number): NextResponse { - return NextResponse.json({ error }, { status, headers: getCorsHeaders() }); -} - -/** - * Validates a POST /api/agents/verify request end-to-end. Checks include: - * the body shape (email + 6-digit code), the Privy-stored verification - * metadata (code hash, expiry, attempts), the supplied code against the - * stored hash (and increments attempts on mismatch), and resolves the - * email to an account. All prerequisite checks live here so the handler - * can reduce to "if validation passes, issue an API key". - * - * @param body - The raw request body + * @param request - The incoming Next.js request * @returns NextResponse on any failure, or the resolved `accountId` + `privyUserId` on success */ export async function validateAgentVerifyBody( - body: unknown, + request: NextRequest, ): Promise { + const body = await safeParseJson(request); const parsed = agentVerifyBodySchema.safeParse(body); if (!parsed.success) { const firstError = parsed.error.issues[0]; diff --git a/lib/const.ts b/lib/const.ts index a5cccfac8..2362805ef 100644 --- a/lib/const.ts +++ b/lib/const.ts @@ -21,6 +21,15 @@ export const OUTBOUND_EMAIL_DOMAIN = "@recoupable.com"; /** Default from address for outbound emails */ export const RECOUP_FROM_EMAIL = `Agent by Recoup `; +/** + * Generic message returned for every POST /api/agents/signup response, + * regardless of which branch (new agent+, existing account, new normal + * account) executed. Keeping the response body identical prevents callers + * from probing the system to discover which emails already have accounts. + */ +export const AGENT_SIGNUP_GENERIC_MESSAGE = + "If this is a new agent+ email, your API key is included. Otherwise, check your email for a verification code."; + export const SUPABASE_STORAGE_BUCKET = "user-files"; export const CREATE_CONTENT_TASK_ID = "create-content"; diff --git a/lib/networking/__tests__/errorResponse.test.ts b/lib/networking/__tests__/errorResponse.test.ts new file mode 100644 index 000000000..bce015381 --- /dev/null +++ b/lib/networking/__tests__/errorResponse.test.ts @@ -0,0 +1,21 @@ +import { describe, it, expect, vi } from "vitest"; +import { errorResponse } from "@/lib/networking/errorResponse"; + +vi.mock("@/lib/networking/getCorsHeaders", () => ({ + getCorsHeaders: vi.fn(() => ({ "Access-Control-Allow-Origin": "*" })), +})); + +describe("errorResponse", () => { + it("returns a NextResponse with the given message and status", async () => { + const result = errorResponse("Something went wrong", 400); + const body = await result.json(); + + expect(result.status).toBe(400); + expect(body.error).toBe("Something went wrong"); + }); + + it("includes CORS headers on the response", () => { + const result = errorResponse("nope", 429); + expect(result.headers.get("Access-Control-Allow-Origin")).toBe("*"); + }); +}); diff --git a/lib/networking/errorResponse.ts b/lib/networking/errorResponse.ts new file mode 100644 index 000000000..41beb3b7a --- /dev/null +++ b/lib/networking/errorResponse.ts @@ -0,0 +1,15 @@ +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; + +/** + * Builds a JSON error response with CORS headers. Use this instead of + * inlining `NextResponse.json({ error }, { status, headers: getCorsHeaders() })` + * at every API error return site. + * + * @param error - Human-readable error message + * @param status - HTTP status code (e.g. 400, 403, 429, 500) + * @returns NextResponse carrying `{ error }` at the given status + */ +export function errorResponse(error: string, status: number): NextResponse { + return NextResponse.json({ error }, { status, headers: getCorsHeaders() }); +} From 2a9da147b21d6f5040342098d148d98ade741478 Mon Sep 17 00:00:00 2001 From: Sweets Sweetman Date: Sat, 11 Apr 2026 20:38:56 -0500 Subject: [PATCH 5/6] fix(agents): three production bugs caught by preview deployment testing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- .../__tests__/generateAndStoreApiKey.test.ts | 9 ++- lib/agents/agentSignupHandler.ts | 9 ++- lib/agents/generateAndStoreApiKey.ts | 3 +- lib/agents/storeVerificationCode.ts | 3 +- lib/agents/validateAgentVerifyBody.ts | 3 +- .../__tests__/getPrivyUserByEmail.test.ts | 70 +++++++++++++++++++ lib/privy/getPrivyUserByEmail.ts | 2 +- 7 files changed, 90 insertions(+), 9 deletions(-) create mode 100644 lib/privy/__tests__/getPrivyUserByEmail.test.ts diff --git a/lib/agents/__tests__/generateAndStoreApiKey.test.ts b/lib/agents/__tests__/generateAndStoreApiKey.test.ts index c0975c8c6..970c1d687 100644 --- a/lib/agents/__tests__/generateAndStoreApiKey.test.ts +++ b/lib/agents/__tests__/generateAndStoreApiKey.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { generateAndStoreApiKey } from "@/lib/agents/generateAndStoreApiKey"; +import { hashApiKey } from "@/lib/keys/hashApiKey"; import { insertApiKey } from "@/lib/supabase/account_api_keys/insertApiKey"; vi.mock("@/lib/keys/generateApiKey", () => ({ @@ -14,16 +15,20 @@ vi.mock("@/lib/supabase/account_api_keys/insertApiKey", () => ({ insertApiKey: vi.fn(() => ({ data: {}, error: null })), })); +vi.mock("@/lib/const", () => ({ + PRIVY_PROJECT_SECRET: "test-privy-secret", +})); + describe("generateAndStoreApiKey", () => { beforeEach(() => { vi.clearAllMocks(); - process.env.PROJECT_SECRET = "test-secret"; }); - it("generates a raw key, hashes it, inserts it, and returns the raw key", async () => { + it("generates a raw key, hashes it with PRIVY_PROJECT_SECRET, inserts it, and returns the raw key", async () => { const rawKey = await generateAndStoreApiKey("acc_123"); expect(rawKey).toBe("recoup_sk_test123"); + expect(hashApiKey).toHaveBeenCalledWith("recoup_sk_test123", "test-privy-secret"); expect(insertApiKey).toHaveBeenCalledWith( expect.objectContaining({ account: "acc_123", diff --git a/lib/agents/agentSignupHandler.ts b/lib/agents/agentSignupHandler.ts index 1d470b1e4..950b061af 100644 --- a/lib/agents/agentSignupHandler.ts +++ b/lib/agents/agentSignupHandler.ts @@ -26,14 +26,17 @@ export async function agentSignupHandler(request: NextRequest): Promise { const today = new Date().toISOString().slice(0, 10); const rawKey = generateApiKey("recoup_sk"); - const keyHash = hashApiKey(rawKey, process.env.PROJECT_SECRET!); + const keyHash = hashApiKey(rawKey, PRIVY_PROJECT_SECRET); const { error } = await insertApiKey({ name: `Agent ${today}`, account: accountId, diff --git a/lib/agents/storeVerificationCode.ts b/lib/agents/storeVerificationCode.ts index 138cdbb2b..35f8dbec5 100644 --- a/lib/agents/storeVerificationCode.ts +++ b/lib/agents/storeVerificationCode.ts @@ -1,4 +1,5 @@ import { randomInt } from "crypto"; +import { PRIVY_PROJECT_SECRET } from "@/lib/const"; import { hashApiKey } from "@/lib/keys/hashApiKey"; import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; import { createPrivyUser } from "@/lib/privy/createPrivyUser"; @@ -16,7 +17,7 @@ const EXPIRY_MS = 24 * 60 * 60 * 1000; export async function storeVerificationCode(email: string): Promise { // randomInt upper bound is exclusive — use 1000000 so 999999 is reachable. const code = randomInt(100000, 1000000).toString(); - const codeHash = hashApiKey(code, process.env.PROJECT_SECRET!); + const codeHash = hashApiKey(code, PRIVY_PROJECT_SECRET); const expiresAt = new Date(Date.now() + EXPIRY_MS).toISOString(); let privyUser = await getPrivyUserByEmail(email); diff --git a/lib/agents/validateAgentVerifyBody.ts b/lib/agents/validateAgentVerifyBody.ts index 1554e2668..583896ed8 100644 --- a/lib/agents/validateAgentVerifyBody.ts +++ b/lib/agents/validateAgentVerifyBody.ts @@ -1,5 +1,6 @@ import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; +import { PRIVY_PROJECT_SECRET } from "@/lib/const"; import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; import { safeParseJson } from "@/lib/networking/safeParseJson"; import { errorResponse } from "@/lib/networking/errorResponse"; @@ -84,7 +85,7 @@ export async function validateAgentVerifyBody( return errorResponse("Too many failed verification attempts. Please request a new code.", 429); } - const providedHash = hashApiKey(code, process.env.PROJECT_SECRET!); + const providedHash = hashApiKey(code, PRIVY_PROJECT_SECRET); if (providedHash !== metadata.verification_code_hash) { await setPrivyCustomMetadata(privyUser.id, { ...metadata, diff --git a/lib/privy/__tests__/getPrivyUserByEmail.test.ts b/lib/privy/__tests__/getPrivyUserByEmail.test.ts new file mode 100644 index 000000000..6b041dc1d --- /dev/null +++ b/lib/privy/__tests__/getPrivyUserByEmail.test.ts @@ -0,0 +1,70 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { getPrivyUserByEmail } from "@/lib/privy/getPrivyUserByEmail"; + +/** + * Builds a fetch mock that always resolves to the given Response. + * + * @param response - The Response to return on every fetch call + * @returns The vi mock function (so callers can assert call args) + */ +function mockFetch(response: Response): ReturnType { + const fetchMock = vi.fn().mockResolvedValue(response); + globalThis.fetch = fetchMock as unknown as typeof fetch; + return fetchMock; +} + +describe("getPrivyUserByEmail", () => { + const originalFetch = globalThis.fetch; + + beforeEach(() => { + process.env.PRIVY_APP_ID = "test-app-id"; + process.env.PRIVY_PROJECT_SECRET = "test-secret"; + }); + + afterEach(() => { + globalThis.fetch = originalFetch; + vi.restoreAllMocks(); + }); + + it("posts to /v1/users/email/address with `address` (not `email`) in the body", async () => { + const fetchMock = mockFetch( + new Response(JSON.stringify({ id: "did:privy:abc", custom_metadata: {} }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }), + ); + + await getPrivyUserByEmail("user@example.com"); + + expect(fetchMock).toHaveBeenCalledOnce(); + const [url, init] = fetchMock.mock.calls[0]; + expect(url).toBe("https://api.privy.io/v1/users/email/address"); + expect(init).toMatchObject({ method: "POST" }); + expect(JSON.parse(init.body)).toEqual({ address: "user@example.com" }); + }); + + it("returns the parsed user object on 200", async () => { + mockFetch( + new Response(JSON.stringify({ id: "did:privy:abc", custom_metadata: { foo: "bar" } }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }), + ); + + const result = await getPrivyUserByEmail("user@example.com"); + expect(result).toEqual({ id: "did:privy:abc", custom_metadata: { foo: "bar" } }); + }); + + it("returns null on 404", async () => { + mockFetch(new Response("", { status: 404 })); + + const result = await getPrivyUserByEmail("nobody@example.com"); + expect(result).toBeNull(); + }); + + it("throws on non-2xx, non-404 responses", async () => { + mockFetch(new Response("rate limited", { status: 429 })); + + await expect(getPrivyUserByEmail("user@example.com")).rejects.toThrow(/429.*rate limited/); + }); +}); diff --git a/lib/privy/getPrivyUserByEmail.ts b/lib/privy/getPrivyUserByEmail.ts index 988d8e570..09e2354e9 100644 --- a/lib/privy/getPrivyUserByEmail.ts +++ b/lib/privy/getPrivyUserByEmail.ts @@ -14,7 +14,7 @@ export async function getPrivyUserByEmail( "privy-app-id": process.env.PRIVY_APP_ID!, Authorization: `Basic ${btoa(process.env.PRIVY_APP_ID! + ":" + process.env.PRIVY_PROJECT_SECRET!)}`, }, - body: JSON.stringify({ email }), + body: JSON.stringify({ address: email }), }); if (response.status === 404) { From 7665a92e3f5aee96d2455a764de599d265a38eee Mon Sep 17 00:00:00 2001 From: Sweets Sweetman Date: Sat, 11 Apr 2026 20:52:46 -0500 Subject: [PATCH 6/6] fix(agents): NaN-guard malformed expiry; 5xx on internal failure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two CodeRabbit findings on commit 2a9da147, 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) --- .../__tests__/agentSignupHandler.test.ts | 17 ++++++++++++++ .../__tests__/validateAgentVerifyBody.test.ts | 22 +++++++++++++++++++ lib/agents/agentSignupHandler.ts | 5 ++++- lib/agents/validateAgentVerifyBody.ts | 7 ++++-- 4 files changed, 48 insertions(+), 3 deletions(-) diff --git a/lib/agents/__tests__/agentSignupHandler.test.ts b/lib/agents/__tests__/agentSignupHandler.test.ts index 0736e21d5..a972e1f84 100644 --- a/lib/agents/__tests__/agentSignupHandler.test.ts +++ b/lib/agents/__tests__/agentSignupHandler.test.ts @@ -158,4 +158,21 @@ describe("agentSignupHandler", () => { expect(result.status).toBe(400); }); }); + + describe("internal failures", () => { + it("returns 500 with the generic body when an internal error is thrown", async () => { + vi.mocked(selectAccountByEmail).mockRejectedValueOnce(new Error("supabase down")); + + const result = await agentSignupHandler(buildRequest({ email: "user@example.com" })); + const body = await result.json(); + + // 5xx is required so monitoring can distinguish failures from successes + // and clients know to retry; the body stays generic to avoid email + // enumeration (matches the existing-account branch's body shape). + expect(result.status).toBe(500); + expect(body.account_id).toBeNull(); + expect(body.api_key).toBeNull(); + expect(body.message).toBeTruthy(); + }); + }); }); diff --git a/lib/agents/__tests__/validateAgentVerifyBody.test.ts b/lib/agents/__tests__/validateAgentVerifyBody.test.ts index 85ef86a5e..b1bba0bb4 100644 --- a/lib/agents/__tests__/validateAgentVerifyBody.test.ts +++ b/lib/agents/__tests__/validateAgentVerifyBody.test.ts @@ -155,6 +155,28 @@ describe("validateAgentVerifyBody", () => { expect((result as NextResponse).status).toBe(400); }); + it("returns 400 when verification_expires_at is a malformed string (NaN guard)", async () => { + // Set the success path up so the ONLY way to fail is the expiry check. + // Without the NaN guard, the malformed string parses to NaN, the + // `Date.now() > NaN` comparison is `false`, the expiry check is silently + // skipped, the (mocked-matching) hash comparison passes, and the function + // would succeed instead of rejecting — that's the silent bypass we're + // guarding against. + vi.mocked(getPrivyUserByEmail).mockResolvedValue({ + id: "privy_1", + custom_metadata: metadataWith({ verification_expires_at: "not-a-real-date" }), + }); + vi.mocked(selectAccountByEmail).mockResolvedValue({ + account_id: "acc_should_not_be_returned", + email: "user@example.com", + } as unknown as Awaited>); + + const result = await validateAgentVerifyBody(VALID_REQUEST()); + + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + it("returns 429 when verification_attempts is at or above the limit", async () => { vi.mocked(getPrivyUserByEmail).mockResolvedValue({ id: "privy_1", diff --git a/lib/agents/agentSignupHandler.ts b/lib/agents/agentSignupHandler.ts index 950b061af..dd900df3f 100644 --- a/lib/agents/agentSignupHandler.ts +++ b/lib/agents/agentSignupHandler.ts @@ -39,9 +39,12 @@ export async function agentSignupHandler(request: NextRequest): Promise NaN` is + // false, which would silently bypass the comparison without the isNaN guard. if (!metadata.verification_expires_at) { return errorResponse(GENERIC_ERROR, 400); } - if (Date.now() > new Date(metadata.verification_expires_at).getTime()) { + const expiresAt = new Date(metadata.verification_expires_at).getTime(); + if (Number.isNaN(expiresAt) || Date.now() > expiresAt) { return errorResponse(GENERIC_ERROR, 400); }