Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions app/api/agents/signup/route.ts
Original file line number Diff line number Diff line change
@@ -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;
44 changes: 44 additions & 0 deletions app/api/agents/verify/route.ts
Original file line number Diff line number Diff line change
@@ -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;
116 changes: 116 additions & 0 deletions lib/agents/__tests__/agentSignupHandler.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof insertAccount>
>);

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<ReturnType<typeof selectAccountByEmail>>);
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<typeof insertAccount>
>);
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();
});
});
});
136 changes: 136 additions & 0 deletions lib/agents/__tests__/agentVerifyHandler.test.ts
Original file line number Diff line number Diff line change
@@ -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<ReturnType<typeof selectAccountByEmail>>);

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);
});
});
20 changes: 20 additions & 0 deletions lib/agents/__tests__/isAgentPrefixEmail.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
33 changes: 33 additions & 0 deletions lib/agents/__tests__/validateAgentSignupBody.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
Loading
Loading