Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

feat(api): implement agent signup v0 endpoints and enforcement

firecrawl-spring[bot]33991f23454e
diff --git a/apps/api/src/controllers/auth.ts b/apps/api/src/controllers/auth.ts
index 07072ede8..5906300c7 100644
--- a/apps/api/src/controllers/auth.ts
+++ b/apps/api/src/controllers/auth.ts
@@ -18,6 +18,7 @@ import { getRedisConnection } from "../services/queue-service";
import { validate } from "uuid";
import * as Sentry from "@sentry/node";
import { AuthCreditUsageChunk, AuthCreditUsageChunkFromTeam } from "./v1/types";
+import { getAgentSponsorStatus } from "../services/agent-sponsor";
function normalizedApiIsUuid(potentialUuid: string): boolean {
// Check if the string is a valid UUID
@@ -543,6 +544,25 @@ async function supaAuthenticateUser(
// return { success: false, error: "Unauthorized: Invalid token", status: 401 };
}
+ // Check if this is an agent-provisioned key and attach sponsor status
+ if (chunk && chunk.api_key_id) {
+ try {
+ const sponsorStatus = await getAgentSponsorStatus(chunk.api_key_id);
+ if (sponsorStatus) {
+ chunk._agentSponsor = {
+ status: sponsorStatus.status,
+ verification_deadline: sponsorStatus.verification_deadline,
+ email: sponsorStatus.email,
+ };
+ }
+ } catch (err) {
+ logger.warn("Failed to check agent sponsor status", {
+ error: err,
+ api_key_id: chunk.api_key_id,
+ });
+ }
+ }
+
return {
success: true,
team_id: teamId ?? undefined,
diff --git a/apps/api/src/controllers/v1/types.ts b/apps/api/src/controllers/v1/types.ts
index 53f742884..9eb9b77a2 100644
--- a/apps/api/src/controllers/v1/types.ts
+++ b/apps/api/src/controllers/v1/types.ts
@@ -1255,6 +1255,13 @@ export type AuthCreditUsageChunk = {
// appended on JS-side
is_extract?: boolean;
+
+ // Agent signup: populated when the key is agent-provisioned
+ _agentSponsor?: {
+ status: "pending" | "verified" | "blocked";
+ verification_deadline: string;
+ email: string;
+ } | null;
};
export type TeamFlags = {
diff --git a/apps/api/src/controllers/v2/agent-signup-confirm.ts b/apps/api/src/controllers/v2/agent-signup-confirm.ts
new file mode 100644
index 000000000..41a98adbf
--- /dev/null
+++ b/apps/api/src/controllers/v2/agent-signup-confirm.ts
@@ -0,0 +1,286 @@
+import { Request, Response } from "express";
+import { z } from "zod";
+import { supabase_service, supabase_rr_service } from "../../services/supabase";
+import { logger as _logger } from "../../lib/logger";
+import {
+ getAgentSponsorByToken,
+ markSponsorVerified,
+ markSponsorBlocked,
+ clearAgentSponsorCache,
+} from "../../services/agent-sponsor";
+import { clearACUC } from "../auth";
+
+const tokenSchema = z.object({
+ token: z.string().min(1),
+});
+
+/**
+ * POST /v2/agent-signup/confirm
+ * Confirms a pending agent sponsor, merging the sandboxed key into the sponsor's real account.
+ */
+export async function agentSignupConfirmController(
+ req: Request,
+ res: Response,
+) {
+ const logger = _logger.child({
+ module: "v2/agent-signup-confirm",
+ method: "agentSignupConfirmController",
+ });
+
+ try {
+ const { token } = tokenSchema.parse(req.body);
+
+ const sponsor = await getAgentSponsorByToken(token);
+ if (!sponsor) {
+ return res.status(404).json({
+ success: false,
+ error: "Invalid or expired verification token.",
+ });
+ }
+
+ if (sponsor.status === "verified") {
+ return res.status(200).json({
+ success: true,
+ message: "This agent key has already been confirmed.",
+ });
+ }
+
+ if (sponsor.status === "blocked") {
+ return res.status(403).json({
+ success: false,
+ error: "This agent signup has been blocked.",
+ });
+ }
+
+ // Check deadline
+ const deadline = new Date(sponsor.verification_deadline);
+ if (deadline < new Date()) {
+ return res.status(403).json({
+ success: false,
+ error:
+ "Verification deadline has passed. Please log in to manage your account.",
+ login_url: "https://firecrawl.dev/signin",
+ });
+ }
+
+ // Look up existing user by sponsor email
+ const { data: existingUser } = await supabase_rr_service
+ .from("users")
+ .select("id, team_id")
+ .eq("email", sponsor.email)
+ .limit(1);
+
+ if (existingUser && existingUser.length > 0) {
+ // Merge: move the agent API key from the sandboxed team to the existing user's team
+ const realTeamId = existingUser[0].team_id;
+ const realUserId = existingUser[0].id;
+
+ // Move the API key to the real team
+ const { error: moveKeyError } = await supabase_service
+ .from("api_keys")
+ .update({ team_id: realTeamId, owner_id: realUserId } as any)
+ .eq("id", sponsor.api_key_id);
+
+ if (moveKeyError) {
+ logger.error("Failed to move API key to real team", {
+ error: moveKeyError,
+ });
+ return res
+ .status(500)
+ .json({ success: false, error: "Failed to confirm agent key." });
+ }
+
+ // Carry over credit_usage from sandboxed team to real team
+ const { error: creditMoveError } = await supabase_service
+ .from("credit_usage")
+ .update({ team_id: realTeamId } as any)
+ .eq("team_id", sponsor.sandboxed_team_id);
+
+ if (creditMoveError) {
+ logger.warn("Failed to carry over credit usage from sandboxed team", {
+ error: creditMoveError,
+ sandboxedTeamId: sponsor.sandboxed_team_id,
+ realTeamId,
+ });
+ // Non-fatal: continue with merge
+ }
+
+ // Ban the sandboxed team to deactivate it
+ const { error: banError } = await supabase_service
+ .from("teams")
+ .update({ banned: true })
+ .eq("id", sponsor.sandboxed_team_id);
+
+ if (banError) {
+ logger.warn("Failed to ban sandboxed team", { error: banError });
+ }
+
+ // Clear ACUC caches so the key picks up the real account's plan
+ const { data: apiKeyData } = await supabase_service
+ .from("api_keys")
+ .select("key")
+ .eq("id", sponsor.api_key_id)
+ .single();
+
+ if (apiKeyData) {
+ await clearACUC(apiKeyData.key);
+ }
+
+ logger.info("Agent key merged into existing account", {
+ email: sponsor.email,
+ realTeamId,
+ sandboxedTeamId: sponsor.sandboxed_team_id,
+ apiKeyId: sponsor.api_key_id,
+ });
+ } else {
+ // No existing user: the sandboxed account becomes the real account
+ // Update the auth.users email from synthetic to the real sponsor email
+ const { data: sandboxedTeamUsers } = await supabase_service
+ .from("users")
+ .select("id")
+ .eq("team_id", sponsor.sandboxed_team_id)
+ .limit(1);
+
+ if (sandboxedTeamUsers && sandboxedTeamUsers.length > 0) {
+ const userId = sandboxedTeamUsers[0].id;
+
+ // Update auth.users email via admin API
+ const { error: updateAuthError } =
+ await supabase_service.auth.admin.updateUserById(userId, {
+ email: sponsor.email,
+ });
+
+ if (updateAuthError) {
+ logger.error("Failed to update auth user email", {
+ error: updateAuthError,
+ });
+ return res
+ .status(500)
+ .json({ success: false, error: "Failed to confirm agent key." });
+ }
+
+ // Update public.users email
+ const { error: updateUserError } = await supabase_service
+ .from("users")
+ .update({ email: sponsor.email })
+ .eq("id", userId);
+
+ if (updateUserError) {
+ logger.warn("Failed to update public.users email", {
+ error: updateUserError,
+ });
+ }
+ }
+
+ logger.info("Sandboxed account promoted to real account", {
+ email: sponsor.email,
+ sandboxedTeamId: sponsor.sandboxed_team_id,
+ apiKeyId: sponsor.api_key_id,
+ });
+ }
+
+ // Mark sponsor as verified
+ await markSponsorVerified(sponsor.id);
+ await clearAgentSponsorCache(sponsor.api_key_id);
+
+ return res.status(200).json({
+ success: true,
+ message: "Agent key confirmed and linked to your account.",
+ });
+ } catch (error) {
+ if (error instanceof z.ZodError) {
+ return res.status(400).json({
+ success: false,
+ error: "Invalid request: token is required.",
+ });
+ }
+ logger.error("Unexpected error in agent signup confirm", { error });
+ return res
+ .status(500)
+ .json({ success: false, error: "Internal server error" });
+ }
+}
+
+/**
+ * POST /v2/agent-signup/block
+ * Blocks an agent sponsor, disabling the sandboxed key.
+ */
+export async function agentSignupBlockController(req: Request, res: Response) {
+ const logger = _logger.child({
+ module: "v2/agent-signup-block",
+ method: "agentSignupBlockController",
+ });
+
+ try {
+ const { token } = tokenSchema.parse(req.body);
+
+ const sponsor = await getAgentSponsorByToken(token);
+ if (!sponsor) {
+ return res.status(404).json({
+ success: false,
+ error: "Invalid verification token.",
+ });
+ }
+
+ if (sponsor.status === "blocked") {
+ return res.status(200).json({
+ success: true,
+ message: "This agent signup has already been blocked.",
+ });
+ }
+
+ if (sponsor.status === "verified") {
+ return res.status(409).json({
+ success: false,
+ error:
+ "This agent key has already been confirmed and cannot be blocked.",
+ });
+ }
+
+ // Disable the API key
+ const { error: deleteKeyError } = await supabase_service
+ .from("api_keys")
+ .delete()
+ .eq("id", sponsor.api_key_id);
+
+ if (deleteKeyError) {
+ logger.warn("Failed to delete agent API key", { error: deleteKeyError });
+ }
+
+ // Ban the sandboxed team
+ const { error: banError } = await supabase_service
+ .from("teams")
+ .update({ banned: true })
+ .eq("id", sponsor.sandboxed_team_id);
+
+ if (banError) {
+ logger.warn("Failed to ban sandboxed team", { error: banError });
+ }
+
+ // Mark sponsor as blocked
+ await markSponsorBlocked(sponsor.id);
+ await clearAgentSponsorCache(sponsor.api_key_id);
+
+ logger.info("Agent signup blocked", {
+ email: sponsor.email,
+ sandboxedTeamId: sponsor.sandboxed_team_id,
+ apiKeyId: sponsor.api_key_id,
+ });
+
+ return res.status(200).json({
+ success: true,
+ message: "Agent key has been blocked and disabled.",
+ });
+ } catch (error) {
+ if (error instanceof z.ZodError) {
+ return res.status(400).json({
+ success: false,
+ error: "Invalid request: token is required.",
+ });
+ }
+ logger.error("Unexpected error in agent signup block", { error });
+ return res
+ .status(500)
+ .json({ success: false, error: "Internal server error" });
+ }
+}
diff --git a/apps/api/src/controllers/v2/agent-signup.ts b/apps/api/src/controllers/v2/agent-signup.ts
new file mode 100644
index 000000000..b5ecfcb06
--- /dev/null
+++ b/apps/api/src/controllers/v2/agent-signup.ts
@@ -0,0 +1,348 @@
+import { Request, Response } from "express";
+import { z } from "zod";
+import crypto from "crypto";
+import { supabase_service, supabase_rr_service } from "../../services/supabase";
+import { apiKeyToFcApiKey } from "../../lib/parseApi";
+import { logger as _logger } from "../../lib/logger";
+import { Resend } from "resend";
+import { config } from "../../config";
+import { RateLimiterRedis } from "rate-limiter-flexible";
+import { redisRateLimitClient } from "../../services/rate-limiter";
+
+const PUBLIC_EMAIL_DOMAINS = new Set([
+ "gmail.com",
+ "googlemail.com",
+ "outlook.com",
+ "hotmail.com",
+ "live.com",
+ "yahoo.com",
+ "yahoo.co.uk",
+ "icloud.com",
+ "me.com",
+ "mac.com",
+ "aol.com",
+ "protonmail.com",
+ "proton.me",
+ "mail.com",
+ "zoho.com",
+ "yandex.com",
+ "gmx.com",
+ "gmx.net",
+ "tutanota.com",
+ "fastmail.com",
+]);
+
+// Rate limiters
+const ipRateLimiter = new RateLimiterRedis({
+ storeClient: redisRateLimitClient,
+ keyPrefix: "agent_signup_ip",
+ points: 5,
+ duration: 3600, // 1 hour
+});
+
+const domainRateLimiter = new RateLimiterRedis({
+ storeClient: redisRateLimitClient,
+ keyPrefix: "agent_signup_domain",
+ points: 20,
+ duration: 86400, // 24 hours
+});
+
+const agentSignupSchema = z.object({
+ email: z.string().email(),
+ agent_name: z.string().min(1).max(100),
+ accept_terms: z.literal(true),
+});
+
+export async function agentSignupController(req: Request, res: Response) {
+ const logger = _logger.child({
+ module: "v2/agent-signup",
+ method: "agentSignupController",
+ });
+
+ try {
+ // Parse and validate input
+ const body = agentSignupSchema.parse(req.body);
+ const { email, agent_name } = body;
+
+ // Rate limit by IP
+ const incomingIP = (req.headers["x-forwarded-for"] ||
+ req.socket.remoteAddress ||
+ "unknown") as string;
+ try {
+ await ipRateLimiter.consume(incomingIP);
+ } catch {
+ return res.status(429).json({
+ success: false,
+ error:
+ "Rate limit exceeded. Maximum 5 agent signup requests per hour per IP.",
+ });
+ }
+
+ // Rate limit by domain (per-email for public providers)
+ const emailDomain = email.split("@")[1]?.toLowerCase();
+ const domainKey = PUBLIC_EMAIL_DOMAINS.has(emailDomain)
+ ? email.toLowerCase()
+ : emailDomain;
+ try {
+ await domainRateLimiter.consume(domainKey);
+ } catch {
+ return res.status(429).json({
+ success: false,
+ error:
+ "Too many agent signups for this email domain. Please try again later.",
+ });
+ }
+
+ // Check for existing blocked sponsor record
+ const { data: blockedSponsor } = await supabase_rr_service
+ .from("agent_sponsors")
+ .select("id")
+ .eq("email", email.toLowerCase())
+ .eq("status", "blocked")
+ .limit(1);
+
+ if (blockedSponsor && blockedSponsor.length > 0) {
+ return res.status(403).json({
+ success: false,
+ error: "This email has blocked agent signups.",
+ });
+ }
+
+ // Check for existing pending sponsor record
+ const { data: pendingSponsor } = await supabase_rr_service
+ .from("agent_sponsors")
+ .select("id, verification_deadline")
+ .eq("email", email.toLowerCase())
+ .eq("status", "pending")
+ .limit(1);
+
+ if (pendingSponsor && pendingSponsor.length > 0) {
+ const deadline = new Date(pendingSponsor[0].verification_deadline);
+ if (deadline > new Date()) {
+ return res.status(409).json({
+ success: false,
+ error:
+ "A pending agent signup confirmation has already been sent to this email.",
+ login_url: "https://firecrawl.dev/signin",
+ });
+ } else {
+ return res.status(403).json({
+ success: false,
+ error:
+ "Previous agent signup verification has expired. Please log in to manage your account.",
+ login_url: "https://firecrawl.dev/signin",
+ });
+ }
+ }
+
+ // Create sandboxed account via Supabase auth
+ const sandboxId = crypto.randomUUID();
+ const syntheticEmail = `agent-${sandboxId}@agent.sandbox.firecrawl.dev`;
+
+ const { data: newUser, error: newUserError } =
+ await supabase_service.auth.admin.createUser({
+ email: syntheticEmail,
+ email_confirm: true,
+ user_metadata: {
+ referrer_integration: "agent_signup",
+ agent_name: agent_name,
+ },
+ });
+
+ if (newUserError) {
+ logger.error("Failed to create sandboxed user", { error: newUserError });
+ return res
+ .status(500)
+ .json({ success: false, error: "Failed to create agent account." });
+ }
+
+ // Wait briefly for the trigger to complete, then fetch the created records
+ // The handle_new_user_6 trigger creates user, team, org, api_key
+ let teamId: string | null = null;
+ let apiKeyRecord: { id: number; key: string } | null = null;
+
+ // Poll for trigger completion (the trigger runs synchronously in the same transaction)
+ const { data: fcUser, error: fcUserError } = await supabase_service
+ .from("users")
+ .select("team_id")
+ .eq("id", newUser.user.id)
+ .single();
+
+ if (fcUserError || !fcUser) {
+ logger.error("Failed to look up sandboxed user after creation", {
+ error: fcUserError,
+ });
+ return res
+ .status(500)
+ .json({ success: false, error: "Failed to create agent account." });
+ }
+
+ teamId = fcUser.team_id;
+
+ const { data: apiKeyData, error: apiKeyError } = await supabase_service
+ .from("api_keys")
+ .select("id, key")
+ .eq("team_id", teamId)
+ .limit(1)
+ .single();
+
+ if (apiKeyError || !apiKeyData) {
+ logger.error("Failed to look up API key for sandboxed team", {
+ error: apiKeyError,
+ });
+ return res
+ .status(500)
+ .json({ success: false, error: "Failed to create agent account." });
+ }
+
+ apiKeyRecord = apiKeyData;
+
+ // Mark the API key as agent_provisioned
+ const { error: updateKeyError } = await supabase_service
+ .from("api_keys")
+ .update({ agent_provisioned: true } as any)
+ .eq("id", apiKeyRecord.id);
+
+ if (updateKeyError) {
+ logger.error("Failed to mark API key as agent_provisioned", {
+ error: updateKeyError,
+ });
+ }
+
+ // Generate verification token
+ const verificationToken = crypto.randomBytes(32).toString("hex");
+
+ // Compute deadline (3 days from now)
+ const deadline = new Date();
+ deadline.setDate(deadline.getDate() + 3);
+
+ // Create sponsor record
+ const { error: sponsorError } = await supabase_service
+ .from("agent_sponsors")
+ .insert({
+ email: email.toLowerCase(),
+ status: "pending",
+ verification_deadline: deadline.toISOString(),
+ agent_name,
+ sandboxed_team_id: teamId,
+ api_key_id: apiKeyRecord.id,
+ requesting_ip: incomingIP,
+ tos_version: "2025-01-01",
+ tos_hash: crypto
+ .createHash("sha256")
+ .update("accept_terms:true")
+ .digest("hex"),
+ verification_token: verificationToken,
+ } as any);
+
+ if (sponsorError) {
+ logger.error("Failed to create sponsor record", { error: sponsorError });
+ return res
+ .status(500)
+ .json({ success: false, error: "Failed to create agent signup." });
+ }
+
+ // Send confirmation email
+ const confirmUrl = `https://firecrawl.dev/agent-confirm?token=${verificationToken}&action=confirm`;
+ const blockUrl = `https://firecrawl.dev/agent-confirm?token=${verificationToken}&action=block`;
+
+ if (config.RESEND_API_KEY) {
+ const resend = new Resend(config.RESEND_API_KEY);
+ await resend.emails
+ .send({
+ from: "Firecrawl <[email protected]>",
+ to: [email],
+ reply_to: "[email protected]",
+ subject: `An AI agent "${agent_name}" created an API key under your email — Firecrawl`,
+ html: `
+ <p>Hey there,</p>
+ <p>An AI agent called <strong>${escapeHtml(agent_name)}</strong> just created a Firecrawl API key and listed your email as the account holder.</p>
+ <p>The key is currently sandboxed with a <strong>50-credit limit</strong>. To link it to your account and unlock your full plan, please confirm:</p>
+ <p><a href="${confirmUrl}" style="display:inline-block;padding:12px 24px;background:#f97316;color:#fff;text-decoration:none;border-radius:6px;font-weight:bold;">Confirm &amp; Link Key</a></p>
+ <p>If you did not authorize this, you can block the key:</p>
+ <p><a href="${blockUrl}">Block this key</a></p>
+ <p>This confirmation link expires on <strong>${deadline.toLocaleDateString("en-US", { weekday: "long", year: "numeric", month: "long", day: "numeric" })}</strong>.</p>
+ <p>If you have questions, reach out to us at <a href="mailto:[email protected]">[email protected]</a>.</p>
+ <br/>
+ <p>Thanks,<br/>Firecrawl Team</p>
+ `,
+ })
+ .catch(err => {
+ logger.error("Failed to send agent sponsor confirmation email", {
+ error: err,
+ });
+ });
+ }
+
+ // If sponsor email matches an existing user, queue in-app notification
+ const { data: existingUser } = await supabase_rr_service
+ .from("users")
+ .select("team_id")
+ .eq("email", email.toLowerCase())
+ .limit(1);
+
+ if (existingUser && existingUser.length > 0) {
+ await supabase_service
+ .from("user_notifications")
+ .insert({
+ team_id: existingUser[0].team_id,
+ notification_type: "agentSponsorConfirm",
+ sent_date: new Date().toISOString(),
+ timestamp: new Date().toISOString(),
+ metadata: {
+ agent_name,
+ confirm_url: confirmUrl,
+ block_url: blockUrl,
+ verification_token: verificationToken,
+ deadline: deadline.toISOString(),
+ },
+ } as any)
+ .then(({ error }) => {
+ if (error) {
+ logger.error("Failed to insert in-app notification", { error });
+ }
+ });
+ }
+
+ logger.info("Agent signup completed", {
+ email: email.toLowerCase(),
+ agent_name,
+ teamId,
+ apiKeyId: apiKeyRecord.id,
+ });
+
+ return res.status(201).json({
+ success: true,
+ api_key: apiKeyToFcApiKey(apiKeyRecord.key),
+ sponsor_status: "pending",
+ credit_limit: 50,
+ credits_remaining: 50,
+ verification_deadline_at: deadline.toISOString(),
+ tos_url: "https://firecrawl.dev/terms",
+ });
+ } catch (error) {
+ if (error instanceof z.ZodError) {
+ return res.status(400).json({
+ success: false,
+ error:
+ "Invalid request body: " +
+ (error as z.ZodError).issues
+ .map((e: z.ZodIssue) => e.message)
+ .join(", "),
+ });
+ }
+ logger.error("Unexpected error in agent signup", { error });
+ return res
+ .status(500)
+ .json({ success: false, error: "Internal server error" });
+ }
+}
+
+function escapeHtml(str: string): string {
+ return str
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
+ .replace(/"/g, "&quot;")
+ .replace(/'/g, "&#039;");
+}
diff --git a/apps/api/src/routes/shared.ts b/apps/api/src/routes/shared.ts
index c556e3d2a..7d982a811 100644
--- a/apps/api/src/routes/shared.ts
+++ b/apps/api/src/routes/shared.ts
@@ -41,6 +41,48 @@ export function checkCreditsMiddleware(
return next();
}
+ // Agent-provisioned key enforcement: check sponsor status and 50-credit cap
+ if (req.acuc?._agentSponsor) {
+ const sponsor = req.acuc._agentSponsor;
+
+ if (sponsor.status === "blocked") {
+ return res.status(403).json({
+ success: false,
+ error: "This API key has been blocked by the account holder.",
+ });
+ }
+
+ if (sponsor.status === "pending") {
+ const deadline = new Date(sponsor.verification_deadline);
+ if (deadline < new Date()) {
+ return res.status(403).json({
+ success: false,
+ error: "sponsor_verification_expired",
+ message:
+ "Sponsor verification has expired. The account holder needs to log in to confirm.",
+ login_url: "https://firecrawl.dev/signin",
+ });
+ }
+
+ // Enforce 50-credit cap for unverified agent keys
+ const UNVERIFIED_CREDIT_LIMIT = 50;
+ if (req.acuc.adjusted_credits_used >= UNVERIFIED_CREDIT_LIMIT) {
+ return res.status(402).json({
+ success: false,
+ error: "unverified_credit_limit_reached",
+ message:
+ "This agent key has used its 50 unverified credits. Ask the account holder to confirm the key to unlock full access.",
+ credit_limit: UNVERIFIED_CREDIT_LIMIT,
+ credits_used: req.acuc.adjusted_credits_used,
+ sponsor_status: "pending",
+ login_url: "https://firecrawl.dev/signin",
+ upgrade_url: "https://firecrawl.dev/pricing",
+ });
+ }
+ }
+ // If verified, fall through to normal credit check (key is now on real account)
+ }
+
if (!minimum && req.body) {
minimum = Number(
(req.body as any)?.limit ?? (req.body as any)?.urls?.length ?? 1,
diff --git a/apps/api/src/routes/v2.ts b/apps/api/src/routes/v2.ts
index 47f57a240..5456453c0 100644
--- a/apps/api/src/routes/v2.ts
+++ b/apps/api/src/routes/v2.ts
@@ -50,6 +50,11 @@ import {
browserListController,
browserWebhookDestroyedController,
} from "../controllers/v2/browser";
+import { agentSignupController } from "../controllers/v2/agent-signup";
+import {
+ agentSignupConfirmController,
+ agentSignupBlockController,
+} from "../controllers/v2/agent-signup-confirm";
expressWs(express());
@@ -403,6 +408,11 @@ v2Router.post(
wrap(browserWebhookDestroyedController),
);
+// Agent signup routes (public, no auth required — rate limiting is handled inside the controller)
+v2Router.post("/agent-signup", wrap(agentSignupController));
+v2Router.post("/agent-signup/confirm", wrap(agentSignupConfirmController));
+v2Router.post("/agent-signup/block", wrap(agentSignupBlockController));
+
// Only register x402 routes if X402_PAY_TO_ADDRESS is configured
if (isX402Enabled()) {
v2Router.post(
diff --git a/apps/api/src/services/agent-sponsor.ts b/apps/api/src/services/agent-sponsor.ts
new file mode 100644
index 000000000..f2f9bbbab
--- /dev/null
+++ b/apps/api/src/services/agent-sponsor.ts
@@ -0,0 +1,135 @@
+import { supabase_service, supabase_rr_service } from "./supabase";
+import { getValue, setValue, deleteKey } from "./redis";
+import { logger } from "../lib/logger";
+
+type AgentSponsorStatus = {
+ status: "pending" | "verified" | "blocked";
+ verification_deadline: string;
+ email: string;
+ agent_name: string;
+ sandboxed_team_id: string;
+ verification_token: string;
+};
+
+const AGENT_SPONSOR_CACHE_TTL = 300; // 5 minutes
+
+/**
+ * Look up agent sponsor status by api_key_id with Redis caching.
+ */
+export async function getAgentSponsorStatus(
+ api_key_id: number,
+): Promise<AgentSponsorStatus | null> {
+ const cacheKey = `agent_sponsor_${api_key_id}`;
+
+ const cached = await getValue(cacheKey);
+ if (cached !== null) {
+ const parsed = JSON.parse(cached);
+ // Cache "no sponsor" as empty object
+ if (parsed && parsed._none) return null;
+ return parsed;
+ }
+
+ try {
+ const { data, error } = await supabase_rr_service
+ .from("agent_sponsors")
+ .select(
+ "status, verification_deadline, email, agent_name, sandboxed_team_id, verification_token",
+ )
+ .eq("api_key_id", api_key_id)
+ .single();
+
+ if (error || !data) {
+ // Cache the miss to avoid repeated queries
+ await setValue(
+ cacheKey,
+ JSON.stringify({ _none: true }),
+ AGENT_SPONSOR_CACHE_TTL,
+ );
+ return null;
+ }
+
+ const result: AgentSponsorStatus = {
+ status: data.status,
+ verification_deadline: data.verification_deadline,
+ email: data.email,
+ agent_name: data.agent_name,
+ sandboxed_team_id: data.sandboxed_team_id,
+ verification_token: data.verification_token,
+ };
+
+ await setValue(cacheKey, JSON.stringify(result), AGENT_SPONSOR_CACHE_TTL);
+ return result;
+ } catch (err) {
+ logger.error("Failed to look up agent sponsor status", {
+ api_key_id,
+ error: err,
+ });
+ return null;
+ }
+}
+
+/**
+ * Clear cached agent sponsor status for a given api_key_id.
+ */
+export async function clearAgentSponsorCache(
+ api_key_id: number,
+): Promise<void> {
+ await deleteKey(`agent_sponsor_${api_key_id}`);
+}
+
+/**
+ * Look up agent sponsor record by verification token.
+ */
+export async function getAgentSponsorByToken(token: string): Promise<{
+ id: number;
+ email: string;
+ status: string;
+ verification_deadline: string;
+ agent_name: string;
+ sandboxed_team_id: string;
+ api_key_id: number;
+} | null> {
+ const { data, error } = await supabase_service
+ .from("agent_sponsors")
+ .select(
+ "id, email, status, verification_deadline, agent_name, sandboxed_team_id, api_key_id",
+ )
+ .eq("verification_token", token)
+ .single();
+
+ if (error || !data) {
+ return null;
+ }
+
+ return data;
+}
+
+/**
+ * Mark sponsor as verified and set verified_at timestamp.
+ */
+export async function markSponsorVerified(sponsorId: number): Promise<void> {
+ const { error } = await supabase_service
+ .from("agent_sponsors")
+ .update({ status: "verified", verified_at: new Date().toISOString() })
+ .eq("id", sponsorId);
+
+ if (error) {
+ logger.error("Failed to mark sponsor as verified", { sponsorId, error });
+ throw error;
+ }
+}
+
+/**
+ * Mark sponsor as blocked.
+ */
+export async function markSponsorBlocked(sponsorId: number): Promise<void> {
+ const { error } = await supabase_service
+ .from("agent_sponsors")
+ .update({ status: "blocked" })
+ .eq("id", sponsorId);
+
+ if (error) {
+ logger.error("Failed to mark sponsor as blocked", { sponsorId, error });
+ throw error;
+ }
+}
diff --git a/apps/api/src/types.ts b/apps/api/src/types.ts
index b054dc0ae..9146eb803 100644
--- a/apps/api/src/types.ts
+++ b/apps/api/src/types.ts
@@ -166,4 +166,5 @@ export enum NotificationType {
AUTO_RECHARGE_FAILED = "autoRechargeFailed",
CONCURRENCY_LIMIT_REACHED = "concurrencyLimitReached",
AUTO_RECHARGE_FREQUENT = "autoRechargeFrequent",
+ AGENT_SPONSOR_CONFIRM = "agentSponsorConfirm",
}