Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
feat(api): DELETE /v2/browser/profiles/:name (#4734)
Gergő Móricze65197defe8f
diff --git a/apps/api/src/__tests__/snips/v2/browser-profiles.test.ts b/apps/api/src/__tests__/snips/v2/browser-profiles.test.tsindex 9787ce65a..adc7ed9ca 100644--- a/apps/api/src/__tests__/snips/v2/browser-profiles.test.ts+++ b/apps/api/src/__tests__/snips/v2/browser-profiles.test.ts@@ -233,3 +233,132 @@ describeIf(TEST_PRODUCTION && !!WEBHOOK_SECRET)(});},);++// Deleting goes through the browser service, which deletes the saved state.+describeIf(TEST_PRODUCTION && !!config.BROWSER_SERVICE_URL)(+ "DELETE /v2/browser/profiles/:name",+ () => {+ let identity: Identity;+ const profileNames: string[] = [];++ beforeAll(async () => {+ identity = await idmux({ name: "browser-profiles-delete", credits: 100 });+ });++ afterAll(async () => {+ if (profileNames.length > 0) {+ await db+ .delete(schema.browser_profiles)+ .where(+ and(+ eq(schema.browser_profiles.team_id, identity.teamId),+ inArray(schema.browser_profiles.name, profileNames),+ ),+ );+ }+ });++ const del = (name: string, apiKey: string | null = identity.apiKey) => {+ const req = request(TEST_API_URL).delete(+ `/v2/browser/profiles/${encodeURIComponent(name)}`,+ );+ if (apiKey !== null) req.set("Authorization", `Bearer ${apiKey}`);+ return req.send();+ };++ const profileExists = async (name: string) =>+ (+ await db+ .select()+ .from(schema.browser_profiles)+ .where(+ and(+ eq(schema.browser_profiles.team_id, identity.teamId),+ eq(schema.browser_profiles.name, name),+ ),+ )+ ).length > 0;++ it("deletes a listed profile", async () => {+ // Includes a slash and a space, which must survive URL encoding.+ const name = `snips-${uuidv7()}/a b`;+ profileNames.push(name);+ await db.insert(schema.browser_profiles).values({+ team_id: identity.teamId,+ name,+ saved_at: "2026-09-22T10:00:00.000Z",+ size_bytes: 100,+ });++ const res = await del(name);+ expect(res.statusCode).toBe(200);+ expect(res.body).toEqual({ success: true });+ expect(await profileExists(name)).toBe(false);+ });++ it("succeeds for a profile with no saved state", async () => {+ const res = await del(`snips-missing-${uuidv7()}`);+ expect(res.statusCode).toBe(200);+ expect(res.body).toEqual({ success: true });+ });++ it("rejects names over 128 characters and unauthenticated requests", async () => {+ expect((await del("x".repeat(129))).statusCode).toBe(400);+ expect((await del(`snips-${uuidv7()}`, null)).statusCode).toBe(401);+ });++ // A profile.saved for a save made before the delete can arrive after it+ // (the browser service retries); it must not bring the listing back.+ (WEBHOOK_SECRET ? it : it.skip)(+ "ignores a late save from before the delete but records a later one",+ async () => {+ const name = `snips-${uuidv7()}`;+ profileNames.push(name);+ const sessionId = uuidv7();+ const browserId = `snips-${sessionId}`;+ await db.insert(schema.browser_sessions).values({+ id: sessionId,+ team_id: identity.teamId,+ browser_id: browserId,+ workspace_id: "",+ context_id: "",+ cdp_url: "wss://example.invalid/cdp",+ cdp_path: "https://example.invalid/view",+ stream_web_view: false,+ status: "destroyed",+ ttl_total: 60,+ should_bill: false,+ profile_name: name,+ });+ const saved = (savedAt: string) =>+ request(TEST_API_URL)+ .post("/v2/browser/webhook/destroyed")+ .set("x-browser-service-secret", WEBHOOK_SECRET!)+ .send({+ eventId: uuidv7(),+ eventType: "profile.saved",+ sessionId: browserId,+ profileId: browserProfileStorageId(identity.teamId, name),+ savedAt,+ attempt: 1,+ });++ try {+ const before = new Date(Date.now() - 60_000).toISOString();+ expect((await del(name)).statusCode).toBe(200);++ expect((await saved(before)).statusCode).toBe(200);+ expect(await profileExists(name)).toBe(false);++ const after = new Date(Date.now() + 60_000).toISOString();+ expect((await saved(after)).statusCode).toBe(200);+ expect(await profileExists(name)).toBe(true);+ } finally {+ await db+ .delete(schema.browser_sessions)+ .where(eq(schema.browser_sessions.id, sessionId));+ }+ },+ );+ },+);diff --git a/apps/api/src/controllers/v2/browser.ts b/apps/api/src/controllers/v2/browser.tsindex c4f0b896e..0271d8578 100644--- a/apps/api/src/controllers/v2/browser.ts+++ b/apps/api/src/controllers/v2/browser.ts@@ -16,6 +16,9 @@ import {didBrowserSessionUsePrompt,clearBrowserSessionPromptFlag,upsertBrowserProfile,+ deleteBrowserProfile,+ recordBrowserProfileDeleted,+ getBrowserProfileDeletedAt,} from "../../lib/browser-sessions";import {getCombinedTeamActiveCount,@@ -577,6 +580,94 @@ export async function browserExecuteController(});}+const profileNameSchema = z.string().min(1).max(128);+const deletedAtSchema = z.iso.datetime({ offset: true });++// DELETE /v2/browser/profiles/:name+// Deletes a persistent profile's saved state and its listing. Deleting a+// profile that has no saved state succeeds.+export async function browserProfileDeleteController(+ req: RequestWithAuth<{ name: string }, { success: boolean; error?: string }>,+ res: Response<{ success: boolean; error?: string }>,+) {+ if (getSafeMode(req.acuc?.flags)) {+ return res.status(403).json({+ success: false,+ error: SAFE_MODE_BROWSER_UNSUPPORTED_MESSAGE,+ });+ }++ const parsed = profileNameSchema.safeParse(req.params.name);+ if (!parsed.success) {+ return res.status(400).json({+ success: false,+ error: "Profile name must be between 1 and 128 characters.",+ });+ }+ const name = parsed.data;++ if (!config.BROWSER_SERVICE_URL) {+ return res.status(503).json({+ success: false,+ error:+ "Browser feature is not configured (BROWSER_SERVICE_URL is missing).",+ });+ }++ const logger = _logger.child({+ teamId: req.auth.team_id,+ module: "api/v2",+ method: "browserProfileDeleteController",+ });++ const storageId = browserProfileStorageId(req.auth.team_id, name);+ let result: { deletedAt?: unknown } | undefined;+ try {+ result = await browserServiceRequest<{ deletedAt?: unknown }>(+ "DELETE",+ `/profiles/${encodeURIComponent(storageId)}`,+ );+ } catch (err) {+ if (err instanceof BrowserServiceError && err.status === 409) {+ return res.status(409).json({+ success: false,+ error:+ "A session is currently saving to this profile. Stop that session, then delete the profile.",+ });+ }+ logger.error("Failed to delete profile via browser service", {+ error: err,+ });+ return res.status(502).json({+ success: false,+ error: "Failed to delete profile.",+ });+ }++ // profile.saved events carry the browser service's clock, so the tombstone+ // must too; without its deletion time the tombstone could not be compared,+ // so fail and let the (idempotent) delete be retried.+ const parsedDeletedAt = deletedAtSchema.safeParse(result?.deletedAt);+ if (!parsedDeletedAt.success) {+ logger.error("Browser service profile delete returned no valid deletedAt", {+ deletedAt: result?.deletedAt,+ });+ return res.status(502).json({+ success: false,+ error: "Failed to delete profile.",+ });+ }+ const deletedAt = parsedDeletedAt.data;++ // Tombstone before removing the row: a late profile.saved for an earlier+ // save that lands before this upserts a row the delete below removes, and+ // any that lands after it is ignored.+ await recordBrowserProfileDeleted(storageId, deletedAt);+ await deleteBrowserProfile(req.auth.team_id, name);+ logger.info("Deleted browser profile");+ return res.status(200).json({ success: true });+}+export async function browserDeleteController(req: RequestWithAuth<{ sessionId: string }, BrowserDeleteResponse>,res: Response<BrowserDeleteResponse>,@@ -818,7 +909,11 @@ async function handleProfileSavedWebhook(return res.status(200).json({ ok: true });}- const resolution = resolveProfileSave(session, event);+ const resolution = resolveProfileSave(+ session,+ event,+ await getBrowserProfileDeletedAt(event.profileId),+ );if (resolution.action === "ignore") {logger.info("Not recording saved profile", {browserId,diff --git a/apps/api/src/lib/browser-profiles.test.ts b/apps/api/src/lib/browser-profiles.test.tsindex 5bea8b479..f53ce10eb 100644--- a/apps/api/src/lib/browser-profiles.test.ts+++ b/apps/api/src/lib/browser-profiles.test.ts@@ -65,20 +65,24 @@ describe("profileSavedEventSchema", () => {describe("resolveProfileSave", () => {const profileId = browserProfileStorageId(TEAM, "my-profile");+ const savedAt = "2026-09-22T12:00:00.000Z";+ const session = { team_id: TEAM, profile_name: "my-profile" };it("upserts under the session's own team and profile name", () => {- expect(- resolveProfileSave(- { team_id: TEAM, profile_name: "my-profile" },- { profileId },- ),- ).toEqual({ action: "upsert", teamId: TEAM, name: "my-profile" });+ expect(resolveProfileSave(session, { profileId, savedAt })).toEqual({+ action: "upsert",+ teamId: TEAM,+ name: "my-profile",+ });});it("ignores sessions that recorded no profile name", () => {for (const profile_name of [null, undefined]) {expect(- resolveProfileSave({ team_id: TEAM, profile_name }, { profileId }),+ resolveProfileSave(+ { team_id: TEAM, profile_name },+ { profileId, savedAt },+ ),).toEqual({ action: "ignore", reason: "no_profile_name" });}});@@ -88,26 +92,53 @@ describe("resolveProfileSave", () => {expect(resolveProfileSave({ team_id: keylessTeam, profile_name: "my-profile" },- { profileId: browserProfileStorageId(keylessTeam, "my-profile") },+ {+ profileId: browserProfileStorageId(keylessTeam, "my-profile"),+ savedAt,+ },),).toEqual({ action: "ignore", reason: "not_a_team" });});it("rejects a storage id that belongs to another team", () => {expect(- resolveProfileSave(- { team_id: TEAM, profile_name: "my-profile" },- { profileId: browserProfileStorageId(OTHER_TEAM, "my-profile") },- ),+ resolveProfileSave(session, {+ profileId: browserProfileStorageId(OTHER_TEAM, "my-profile"),+ savedAt,+ }),).toEqual({ action: "reject", reason: "profile_mismatch" });});it("rejects a storage id for a different profile name", () => {+ expect(+ resolveProfileSave(session, {+ profileId: browserProfileStorageId(TEAM, "other-profile"),+ savedAt,+ }),+ ).toEqual({ action: "reject", reason: "profile_mismatch" });+ });++ it("ignores a save from before the profile was deleted", () => {+ for (const deletedAt of [savedAt, "2026-09-22T12:00:01.000Z"]) {+ expect(+ resolveProfileSave(session, { profileId, savedAt }, deletedAt),+ ).toEqual({ action: "ignore", reason: "deleted" });+ }+ });++ it("fails closed on an unreadable deletion time", () => {+ expect(+ resolveProfileSave(session, { profileId, savedAt }, "not-a-time"),+ ).toEqual({ action: "ignore", reason: "deleted" });+ });++ it("records a save made after the profile was deleted", () => {expect(resolveProfileSave(- { team_id: TEAM, profile_name: "my-profile" },- { profileId: browserProfileStorageId(TEAM, "other-profile") },+ session,+ { profileId, savedAt },+ "2026-09-22T11:59:59.000Z",),- ).toEqual({ action: "reject", reason: "profile_mismatch" });+ ).toEqual({ action: "upsert", teamId: TEAM, name: "my-profile" });});});diff --git a/apps/api/src/lib/browser-profiles.ts b/apps/api/src/lib/browser-profiles.tsindex f6fa0991b..39005405c 100644--- a/apps/api/src/lib/browser-profiles.ts+++ b/apps/api/src/lib/browser-profiles.ts@@ -33,17 +33,25 @@ type ProfileSavedEvent = z.infer<typeof profileSavedEventSchema>;type ProfileSaveResolution =| { action: "upsert"; teamId: string; name: string }- | { action: "ignore"; reason: "no_profile_name" | "not_a_team" }+ | { action: "ignore"; reason: "no_profile_name" | "not_a_team" | "deleted" }| { action: "reject"; reason: "profile_mismatch" };+// Redis key holding when a profile was last deleted (browser-service clock),+// kept for longer than the browser service retries a profile.saved event.+export function browserProfileDeletedKey(storageId: string): string {+ return `browser-profile-deleted:${storageId}`;+}+/*** Decides what a reported save means for the session it came from. The team* and profile name come from our own session row, never from the event, and- * the event's storage id must be the one that row derives.+ * the event's storage id must be the one that row derives. `deletedAt` is when+ * the profile was last deleted, if recently.*/export function resolveProfileSave(session: { team_id: string; profile_name?: string | null },- event: Pick<ProfileSavedEvent, "profileId">,+ event: Pick<ProfileSavedEvent, "profileId" | "savedAt">,+ deletedAt?: string | null,): ProfileSaveResolution {// Sessions created before profile_name was recorded.if (!session.profile_name) {@@ -59,6 +67,15 @@ export function resolveProfileSave() {return { action: "reject", reason: "profile_mismatch" };}+ // A save that finished before the profile was deleted (its event delivered+ // late) must not bring the listing back; a save after the delete does. An+ // unreadable deletion time fails closed.+ if (deletedAt) {+ const deletedMs = Date.parse(deletedAt);+ if (Number.isNaN(deletedMs) || Date.parse(event.savedAt) <= deletedMs) {+ return { action: "ignore", reason: "deleted" };+ }+ }return {action: "upsert",teamId: session.team_id,diff --git a/apps/api/src/lib/browser-sessions.ts b/apps/api/src/lib/browser-sessions.tsindex 8ffebe725..7bf3cc822 100644--- a/apps/api/src/lib/browser-sessions.ts+++ b/apps/api/src/lib/browser-sessions.ts@@ -1,7 +1,10 @@import { and, desc, eq, sql } from "drizzle-orm";+import { z } from "zod";import { deleteKey, getValue, setValue } from "../services/redis";+import { redisRateLimitClient } from "../services/rate-limiter";import { db } from "../db/connection";import * as schema from "../db/schema";+import { browserProfileDeletedKey } from "./browser-profiles";import { logger as _logger } from "./logger";const logger = _logger.child({ module: "browser-sessions" });@@ -312,6 +315,54 @@ export async function upsertBrowserProfile(input: {});}+// Remembers when a profile was deleted, so a profile.saved event for an+// earlier save that is delivered late cannot relist it. Outlives the browser+// service's retries (at most ~10 minutes).+const PROFILE_DELETED_TTL_SECONDS = 3600;++// Keeps the newest deletion time: responses to concurrent deletes can land+// out of order, and an older time must not shrink the window. Timestamps are+// normalized with toISOString, which compares in time order.+const SET_IF_NEWER_LUA = `+ local current = redis.call('GET', KEYS[1])+ if (not current) or current < ARGV[1] then+ redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[2])+ end+ return 1+`;++export async function recordBrowserProfileDeleted(+ storageId: string,+ deletedAt: string,+): Promise<void> {+ await redisRateLimitClient.eval(+ SET_IF_NEWER_LUA,+ 1,+ browserProfileDeletedKey(storageId),+ new Date(deletedAt).toISOString(),+ String(PROFILE_DELETED_TTL_SECONDS),+ );+}++export async function getBrowserProfileDeletedAt(+ storageId: string,+): Promise<string | null> {+ return getValue(browserProfileDeletedKey(storageId));+}++// Removes a profile's listing once its saved state is deleted. Keyless callers+// (non-UUID team ids) are never listed, so there is nothing to remove.+export async function deleteBrowserProfile(+ teamId: string,+ name: string,+): Promise<void> {+ if (!z.uuid().safeParse(teamId).success) return;+ const profiles = schema.browser_profiles;+ await db+ .delete(profiles)+ .where(and(eq(profiles.team_id, teamId), eq(profiles.name, name)));+}+// ---------------------------------------------------------------------------// Prompt usage tracking (Redis)// ---------------------------------------------------------------------------diff --git a/apps/api/src/routes/v2.ts b/apps/api/src/routes/v2.tsindex 157c798ca..309d15ba0 100644--- a/apps/api/src/routes/v2.ts+++ b/apps/api/src/routes/v2.ts@@ -67,6 +67,7 @@ import {browserExecuteController,browserDeleteController,browserListController,+ browserProfileDeleteController,browserWebhookDestroyedController,} from "../controllers/v2/browser";import {@@ -654,6 +655,12 @@ v2Router.get(wrap(browserReplayPageController),);+v2Router.delete(+ ["/browser/profiles/:name", "/interact/profiles/:name"],+ authMiddleware(RateLimiterMode.BrowserExecute),+ wrap(browserProfileDeleteController),+);+v2Router.delete(["/browser/:sessionId", "/interact/:sessionId"],authMiddleware(RateLimiterMode.BrowserExecute),