diff --git a/app/api/agents/signup/route.ts b/app/api/agents/signup/route.ts new file mode 100644 index 000000000..f5d6ee0ed --- /dev/null +++ b/app/api/agents/signup/route.ts @@ -0,0 +1,33 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +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 the body + * @returns Signup response with `account_id`, `api_key` (or null), and `message` + */ +export async function POST(req: NextRequest) { + return agentSignupHandler(req); +} + +/** + * 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..b8ea80946 --- /dev/null +++ b/app/api/agents/verify/route.ts @@ -0,0 +1,32 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +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, code }` in the body + * @returns Verify response with `account_id`, `api_key`, and `message` + */ +export async function POST(req: NextRequest) { + return agentVerifyHandler(req); +} + +/** + * 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..a972e1f84 --- /dev/null +++ b/lib/agents/__tests__/agentSignupHandler.test.ts @@ -0,0 +1,178 @@ +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": "*" })), +})); + +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(() => ({ id: "ae_1" })), +})); + +vi.mock("@/lib/supabase/credits_usage/insertCreditsUsage", () => ({ + insertCreditsUsage: vi.fn(() => ({ id: "cu_1" })), +})); + +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(), +})); + +vi.mock("crypto", async () => { + const actual = await vi.importActual("crypto"); + return { + ...actual, + randomInt: vi.fn(() => 123456), + }; +}); + +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(buildRequest({ 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(buildRequest({ 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(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); + }); + }); + + 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__/agentVerifyHandler.test.ts b/lib/agents/__tests__/agentVerifyHandler.test.ts new file mode 100644 index 000000000..a8f8b6f0f --- /dev/null +++ b/lib/agents/__tests__/agentVerifyHandler.test.ts @@ -0,0 +1,221 @@ +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": "*" })), +})); + +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( + buildRequest({ 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( + buildRequest({ email: "user@example.com", code: "999999" }), + ); + + 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( + buildRequest({ 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( + buildRequest({ 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( + buildRequest({ 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( + 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__/createAccountWithEmail.test.ts b/lib/agents/__tests__/createAccountWithEmail.test.ts new file mode 100644 index 000000000..5dba14dc4 --- /dev/null +++ b/lib/agents/__tests__/createAccountWithEmail.test.ts @@ -0,0 +1,57 @@ +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"; + +vi.mock("@/lib/supabase/accounts/insertAccount", () => ({ + insertAccount: vi.fn(), +})); + +vi.mock("@/lib/supabase/account_emails/insertAccountEmail", () => ({ + insertAccountEmail: vi.fn(() => ({ id: "ae_1" })), +})); + +vi.mock("@/lib/supabase/credits_usage/insertCreditsUsage", () => ({ + insertCreditsUsage: vi.fn(() => ({ id: "cu_1" })), +})); + +describe("createAccountWithEmail", () => { + beforeEach(() => { + vi.clearAllMocks(); + 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"); + }); + + 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__/generateAndStoreApiKey.test.ts b/lib/agents/__tests__/generateAndStoreApiKey.test.ts new file mode 100644 index 000000000..970c1d687 --- /dev/null +++ b/lib/agents/__tests__/generateAndStoreApiKey.test.ts @@ -0,0 +1,48 @@ +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", () => ({ + 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 })), +})); + +vi.mock("@/lib/const", () => ({ + PRIVY_PROJECT_SECRET: "test-privy-secret", +})); + +describe("generateAndStoreApiKey", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + 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", + 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__/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__/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__/validateAgentSignupBody.test.ts b/lib/agents/__tests__/validateAgentSignupBody.test.ts new file mode 100644 index 000000000..fa7aaca83 --- /dev/null +++ b/lib/agents/__tests__/validateAgentSignupBody.test.ts @@ -0,0 +1,56 @@ +import { describe, it, expect } from "vitest"; +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 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", async () => { + const result = await validateAgentSignupBody(buildRequest({ email: "user@example.com" })); + expect(result).toEqual({ email: "user@example.com" }); + }); + + 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 empty body", async () => { + const result = await validateAgentSignupBody(buildRequest(undefined)); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + }); + + 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 new file mode 100644 index 000000000..b1bba0bb4 --- /dev/null +++ b/lib/agents/__tests__/validateAgentVerifyBody.test.ts @@ -0,0 +1,237 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest, 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": "*" })), +})); + +/** + * 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(), +})); + +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_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(), + verification_attempts: 0, + ...overrides, + } as { + verification_code_hash: string; + verification_expires_at: string; + verification_attempts: number; + }; +} + +describe("validateAgentVerifyBody", () => { + beforeEach(() => { + vi.clearAllMocks(); + process.env.PROJECT_SECRET = "test-secret"; + }); + + describe("body shape", () => { + it("returns 400 for missing email", async () => { + 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(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(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( + 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( + 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( + buildRequest({ email: "user@example.com", code: "1234567" }), + ); + 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_REQUEST()); + 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_REQUEST()); + 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_REQUEST()); + 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_REQUEST()); + expect(result).toBeInstanceOf(NextResponse); + 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", + custom_metadata: metadataWith({ verification_attempts: 5 }), + }); + const result = await validateAgentVerifyBody(VALID_REQUEST()); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(429); + }); + }); + + 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_REQUEST()); + expect(result).toBeInstanceOf(NextResponse); + expect((result as NextResponse).status).toBe(400); + expect(setPrivyCustomMetadata).toHaveBeenCalledWith( + "privy_1", + expect.objectContaining({ verification_attempts: 1 }), + ); + }); + }); + + 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_REQUEST()); + 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_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 new file mode 100644 index 000000000..dd900df3f --- /dev/null +++ b/lib/agents/agentSignupHandler.ts @@ -0,0 +1,50 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +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"; +import { handleAgentPrefixSignup } from "@/lib/agents/handleAgentPrefixSignup"; +import { handleExistingAccount } from "@/lib/agents/handleExistingAccount"; +import { handleNormalSignup } from "@/lib/agents/handleNormalSignup"; + +/** + * 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 + * @returns NextResponse with `account_id`, `api_key` (or null), and `message` + */ +export async function agentSignupHandler(request: NextRequest): Promise { + try { + const validated = await validateAgentSignupBody(request); + if (validated instanceof NextResponse) { + return validated; + } + + const { email } = validated; + + const existingAccount = await selectAccountByEmail(email); + if (existingAccount) { + // `return await` (not bare `return`) — without the await, a rejection + // from the child handler would settle outside this frame and bypass + // the catch block below, surfacing as a Vercel function crash. + return await handleExistingAccount(existingAccount.account_id, email); + } + + if (isAgentPrefixEmail(email)) { + return await handleAgentPrefixSignup(email); + } + + return await handleNormalSignup(email); + } catch (error) { + console.error("[ERROR] agentSignupHandler:", error); + // 5xx so monitoring + client retry behavior can distinguish a real + // failure from a successful signup. Body stays the generic shape to + // avoid email enumeration via response-body diffing. + return NextResponse.json( + { account_id: null, api_key: null, message: AGENT_SIGNUP_GENERIC_MESSAGE }, + { status: 500, headers: getCorsHeaders() }, + ); + } +} diff --git a/lib/agents/agentVerifyHandler.ts b/lib/agents/agentVerifyHandler.ts new file mode 100644 index 000000000..05e669444 --- /dev/null +++ b/lib/agents/agentVerifyHandler.ts @@ -0,0 +1,38 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { validateAgentVerifyBody } from "@/lib/agents/validateAgentVerifyBody"; +import { generateAndStoreApiKey } from "@/lib/agents/generateAndStoreApiKey"; +import { setPrivyCustomMetadata } from "@/lib/privy/setPrivyCustomMetadata"; + +/** + * 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 + */ +export async function agentVerifyHandler(request: NextRequest): Promise { + try { + const validated = await validateAgentVerifyBody(request); + if (validated instanceof NextResponse) { + return validated; + } + + const { accountId, privyUserId } = validated; + const rawKey = await generateAndStoreApiKey(accountId); + await setPrivyCustomMetadata(privyUserId, {}); + + 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/createAccountWithEmail.ts b/lib/agents/createAccountWithEmail.ts new file mode 100644 index 000000000..2ae486d78 --- /dev/null +++ b/lib/agents/createAccountWithEmail.ts @@ -0,0 +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"; + +/** + * 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({}); + + 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/generateAndStoreApiKey.ts b/lib/agents/generateAndStoreApiKey.ts new file mode 100644 index 000000000..1c2d56d5e --- /dev/null +++ b/lib/agents/generateAndStoreApiKey.ts @@ -0,0 +1,28 @@ +import { PRIVY_PROJECT_SECRET } from "@/lib/const"; +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, PRIVY_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..9fcf91674 --- /dev/null +++ b/lib/agents/handleAgentPrefixSignup.ts @@ -0,0 +1,28 @@ +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"; + +/** + * 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: AGENT_SIGNUP_GENERIC_MESSAGE }, + { status: 200, headers: getCorsHeaders() }, + ); +} diff --git a/lib/agents/handleExistingAccount.ts b/lib/agents/handleExistingAccount.ts new file mode 100644 index 000000000..1c6d30e22 --- /dev/null +++ b/lib/agents/handleExistingAccount.ts @@ -0,0 +1,24 @@ +import { NextResponse } from "next/server"; +import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; +import { AGENT_SIGNUP_GENERIC_MESSAGE } from "@/lib/const"; +import { storeVerificationCode } from "@/lib/agents/storeVerificationCode"; + +/** + * 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: AGENT_SIGNUP_GENERIC_MESSAGE }, + { status: 200, headers: getCorsHeaders() }, + ); +} diff --git a/lib/agents/handleNormalSignup.ts b/lib/agents/handleNormalSignup.ts new file mode 100644 index 000000000..6b0b8d25f --- /dev/null +++ b/lib/agents/handleNormalSignup.ts @@ -0,0 +1,23 @@ +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 { storeVerificationCode } from "@/lib/agents/storeVerificationCode"; + +/** + * 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: AGENT_SIGNUP_GENERIC_MESSAGE }, + { status: 200, 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/storeVerificationCode.ts b/lib/agents/storeVerificationCode.ts new file mode 100644 index 000000000..35f8dbec5 --- /dev/null +++ b/lib/agents/storeVerificationCode.ts @@ -0,0 +1,35 @@ +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"; +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, PRIVY_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/validateAgentSignupBody.ts b/lib/agents/validateAgentSignupBody.ts new file mode 100644 index 000000000..077aa96e8 --- /dev/null +++ b/lib/agents/validateAgentSignupBody.ts @@ -0,0 +1,43 @@ +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"), +}); + +export type AgentSignupBody = z.infer; + +/** + * 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 request - The incoming Next.js request + * @returns NextResponse with an error if validation fails, or the validated body + */ +export async function validateAgentSignupBody( + request: NextRequest, +): Promise { + const body = await safeParseJson(request); + 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..9d5a71bfc --- /dev/null +++ b/lib/agents/validateAgentVerifyBody.ts @@ -0,0 +1,106 @@ +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"; +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"), + code: z.string({ message: "code is required" }).regex(/^\d{6}$/, "code must be a 6-digit number"), +}); + +export type AgentVerifyBody = z.infer; + +/** + * 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; +}; + +/** + * 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 request - The incoming Next.js request + * @returns NextResponse on any failure, or the resolved `accountId` + `privyUserId` on success + */ +export async function validateAgentVerifyBody( + request: NextRequest, +): Promise { + const body = await safeParseJson(request); + 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() }, + ); + } + + 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: a missing or malformed expiry is treated as expired. + // `new Date("garbage").getTime()` returns NaN, and `Date.now() > NaN` is + // false, which would silently bypass the comparison without the isNaN guard. + if (!metadata.verification_expires_at) { + return errorResponse(GENERIC_ERROR, 400); + } + const expiresAt = new Date(metadata.verification_expires_at).getTime(); + if (Number.isNaN(expiresAt) || Date.now() > expiresAt) { + 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, PRIVY_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 }; +} 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() }); +} 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/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..09e2354e9 --- /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({ address: 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}`); + } +}