Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Delete cached Google data and unused Google tokens as the policy promises (#943)
Ben Senescu5aa931ea8ac7
diff --git a/docs/maintainers/runbooks/gdpr-erasure.md b/docs/maintainers/runbooks/gdpr-erasure.mdindex 871982e1..e94a2cc4 100644--- a/docs/maintainers/runbooks/gdpr-erasure.md+++ b/docs/maintainers/runbooks/gdpr-erasure.md@@ -73,8 +73,8 @@ The execution order is designed for safe retries:Autumn plus its linked Stripe customer.2. Call the Worker endpoint, which terminates active site-audit and rank-checkWorkflow instances, revokes Google grants, and erases chat/scratchpad- Durable Objects, R2 audit payloads, KV progress entries, and MCP OAuth- grants/tokens.+ Durable Objects, R2 audit payloads, the projects' cached Search Console+ rows, KV progress entries, and MCP OAuth grants/tokens.3. Delete the organizations and user in one Postgres transaction, relying onforeign-key cascades for project data, then verify the root rows are gone.diff --git a/src/server.ts b/src/server.tsindex 2fa91f4e..b7cac9ed 100644--- a/src/server.ts+++ b/src/server.ts@@ -223,6 +223,17 @@ export default {} catch (err) {console.error("[cron] Dub referral sale sweep failed:", err);}++ // Daily cleanup of Google grants no project uses any more, as the+ // hosted privacy policy promises.+ try {+ const { purgeUnusedGoogleData } =+ await import("@/server/features/google/googleDataRetention");+ const purged = await withPgClient(() => purgeUnusedGoogleData());+ console.log("[retention] purged unused Google data", purged);+ } catch (err) {+ console.error("[cron] Google data cleanup failed:", err);+ }}return;}diff --git a/src/server/features/ai-visibility/services/aiVisibilityStorage.ts b/src/server/features/ai-visibility/services/aiVisibilityStorage.tsindex 492f0fec..b9ec4a70 100644--- a/src/server/features/ai-visibility/services/aiVisibilityStorage.ts+++ b/src/server/features/ai-visibility/services/aiVisibilityStorage.ts@@ -1,21 +1,11 @@+import { deleteR2Prefix } from "@/server/lib/r2";+/** Generated exports are private project data. */export async function deleteProjectAiObjects(bucket: R2Bucket,projectId: string,) {- let cursor: string | undefined;- let deleted = 0;- do {- const page = await bucket.list({- prefix: `ai-visibility/${projectId}/`,- cursor,- });- const keys = page.objects.map((object) => object.key);- if (keys.length) await bucket.delete(keys);- deleted += keys.length;- cursor = page.truncated ? page.cursor : undefined;- } while (cursor);- return deleted;+ return deleteR2Prefix(bucket, `ai-visibility/${projectId}/`);}/** Exports carry their expiry; anything without one is stale. */diff --git a/src/server/features/audit/services/AuditService.ts b/src/server/features/audit/services/AuditService.tsindex 68ec6697..0a7c8382 100644--- a/src/server/features/audit/services/AuditService.ts+++ b/src/server/features/audit/services/AuditService.ts@@ -19,6 +19,7 @@ import {type AuditLimitTier,} from "@/server/features/audit/services/audit-capacity";import { AppError } from "@/server/lib/errors";+import { deleteR2Prefix } from "@/server/lib/r2";import { RENDERED_MAX_AUDIT_PAGES } from "@/shared/audit-limits";import { AuditProgressKV } from "@/server/lib/audit/progress-kv";import {@@ -325,6 +326,13 @@ async function remove(auditId: string, projectId: string) {} catch (error) {console.warn(`Failed to destroy audit scratchpad ${auditId}:`, error);}+ // Best-effort: the stored Lighthouse reports. A miss is swept when the+ // account is erased (storage-erasure.ts).+ try {+ await deleteR2Prefix(env.R2, `site-audit/${projectId}/${auditId}/`);+ } catch (error) {+ console.warn(`Failed to delete audit files ${auditId}:`, error);+ }}export const AuditService = {diff --git a/src/server/features/dashboard/services/DashboardCacheService.ts b/src/server/features/dashboard/services/DashboardCacheService.tsindex f14cfc68..9e4f8dda 100644--- a/src/server/features/dashboard/services/DashboardCacheService.ts+++ b/src/server/features/dashboard/services/DashboardCacheService.ts@@ -1,5 +1,12 @@+import { env } from "cloudflare:workers";import { z } from "zod";-import { buildCacheKey, getCached, setCached } from "@/server/lib/r2-cache";+import {+ buildCacheKey,+ cacheObjectPrefix,+ getCached,+ setCached,+} from "@/server/lib/r2-cache";+import { deleteR2Prefix } from "@/server/lib/r2";import { DataRefreshClaimRepository } from "@/server/features/dashboard/repositories/DataRefreshClaimRepository";import { AppError, asAppError } from "@/server/lib/errors";@@ -66,4 +73,22 @@ async function readThrough<T>(input: {}}-export const DashboardCacheService = { readThrough };+// Search Console rows are Google data the privacy policy lets users remove, so+// every cached copy for a project sits under one prefix that disconnect,+// project deletion, and account erasure can drop.+function gscNamespace(projectId: string, name: string) {+ return `dashboard:gsc:${projectId}:${name}`;+}++async function deleteGscCache(projectId: string) {+ return deleteR2Prefix(+ env.R2,+ cacheObjectPrefix(`dashboard:gsc:${projectId}`),+ );+}++export const DashboardCacheService = {+ readThrough,+ gscNamespace,+ deleteGscCache,+};diff --git a/src/server/features/dashboard/services/DashboardSiteService.test.ts b/src/server/features/dashboard/services/DashboardSiteService.test.tsindex 076744ec..11d68971 100644--- a/src/server/features/dashboard/services/DashboardSiteService.test.ts+++ b/src/server/features/dashboard/services/DashboardSiteService.test.ts@@ -20,6 +20,7 @@ vi.mock("@/server/features/gsc/services/GscService", async () => ({}));vi.mock("./DashboardCacheService", () => ({DashboardCacheService: {+ gscNamespace: () => "dashboard:gsc",readThrough: async (input: { load: () => Promise<unknown> }) => ({value: await input.load(),}),diff --git a/src/server/features/dashboard/services/DashboardSiteService.ts b/src/server/features/dashboard/services/DashboardSiteService.tsindex 66a80b18..c29504f7 100644--- a/src/server/features/dashboard/services/DashboardSiteService.ts+++ b/src/server/features/dashboard/services/DashboardSiteService.ts@@ -91,7 +91,7 @@ async function getKeywords(projectId: string, organizationId: string) {refreshError: null,};return DashboardCacheService.readThrough({- namespace: "dashboard:gsc-keywords-v2",+ namespace: DashboardCacheService.gscNamespace(projectId, "keywords"),organizationId,params: {projectId,@@ -169,7 +169,10 @@ async function getEmergingQueries(projectId: string, organizationId: string) {};}return DashboardCacheService.readThrough({- namespace: "dashboard:emerging-queries",+ namespace: DashboardCacheService.gscNamespace(+ projectId,+ "emerging-queries",+ ),organizationId,params: {projectId,diff --git a/src/server/features/google/GoogleAccountRepository.ts b/src/server/features/google/GoogleAccountRepository.tsindex 694b0d44..5a3f57cd 100644--- a/src/server/features/google/GoogleAccountRepository.ts+++ b/src/server/features/google/GoogleAccountRepository.ts@@ -1,4 +1,16 @@-import { and, count, eq, isNull, or } from "drizzle-orm";+import {+ and,+ count,+ eq,+ exists,+ inArray,+ isNull,+ lt,+ not,+ or,+ sql,+ type SQL,+} from "drizzle-orm";import { db } from "@/db";import { runBatch } from "@/db/runBatch";import { account, ga4Connections, gscConnections } from "@/db/schema";@@ -57,4 +69,104 @@ async function remove(input: AccountInput) {]);}-export const GoogleAccountRepository = { getRemovalImpact, remove };+async function listGscProjectIds(input: AccountInput) {+ const rows = await db+ .select({ projectId: gscConnections.projectId })+ .from(gscConnections)+ .where(scope({ ...input, provider: "gsc" }).usage);+ return rows.map((row) => row.projectId);+}++const DATA_PROVIDER_IDS = [GSC_OAUTH_PROVIDER_ID, GA4_OAUTH_PROVIDER_ID];++// Correlated on the outer `account` row: true while a project mapping still+// relies on that grant, with the same rules `scope().usage` applies.+function grantInUse(): SQL {+ const inUse = or(+ and(+ eq(account.providerId, GSC_OAUTH_PROVIDER_ID),+ exists(+ db+ .select({ id: gscConnections.id })+ .from(gscConnections)+ .where(+ and(+ eq(gscConnections.connectedByUserId, account.userId),+ or(+ eq(gscConnections.gscAccountId, account.accountId),+ isNull(gscConnections.gscAccountId),+ ),+ ),+ ),+ ),+ ),+ and(+ eq(account.providerId, GA4_OAUTH_PROVIDER_ID),+ exists(+ db+ .select({ id: ga4Connections.id })+ .from(ga4Connections)+ .where(+ and(+ eq(ga4Connections.connectedByUserId, account.userId),+ eq(ga4Connections.ga4AccountId, account.accountId),+ ),+ ),+ ),+ ),+ );+ // `or` is only undefined when given no conditions.+ return inUse ?? sql`false`;+}++/** Search Console / Analytics grants no project uses, last touched before the cutoff. */+async function listUnusedGrants(updatedBefore: Date, limit: number) {+ return db+ .select({+ id: account.id,+ userId: account.userId,+ providerId: account.providerId,+ accountId: account.accountId,+ })+ .from(account)+ .where(+ and(+ inArray(account.providerId, DATA_PROVIDER_IDS),+ lt(account.updatedAt, updatedBefore),+ not(grantInUse()),+ ),+ )+ .limit(limit);+}++/** Deletes the grant unless a project started using it since it was listed. */+async function deleteUnusedGrant(id: string) {+ const deleted = await db+ .delete(account)+ .where(and(eq(account.id, id), not(grantInUse())))+ .returning({ id: account.id });+ return deleted.length > 0;+}++/** Whether any OpenSEO user still stores a data grant for this Google account. */+async function hasDataGrantsForGoogleAccount(accountId: string) {+ const [result] = await db+ .select({ grants: count() })+ .from(account)+ .where(+ and(+ inArray(account.providerId, DATA_PROVIDER_IDS),+ eq(account.accountId, accountId),+ ),+ );+ return (result?.grants ?? 0) > 0;+}++export const GoogleAccountRepository = {+ getRemovalImpact,+ remove,+ listGscProjectIds,+ listUnusedGrants,+ deleteUnusedGrant,+ hasDataGrantsForGoogleAccount,+};diff --git a/src/server/features/google/GoogleAccountService.test.ts b/src/server/features/google/GoogleAccountService.test.tsindex 8f119a16..156c510c 100644--- a/src/server/features/google/GoogleAccountService.test.ts+++ b/src/server/features/google/GoogleAccountService.test.ts@@ -15,7 +15,16 @@ import {import type { runBatch } from "@/db/runBatch";import type * as ServiceModule from "./GoogleAccountService";+const oauth = vi.hoisted(() => ({+ getGoogleAccessToken: vi.fn(),+ revokeGoogleToken: vi.fn(),+ deleteGscCache: vi.fn(),+}));vi.mock("cloudflare:workers", () => ({ env: {} }));+vi.mock("./googleOAuth", () => oauth);+vi.mock("@/server/features/dashboard/services/DashboardCacheService", () => ({+ DashboardCacheService: { deleteGscCache: oauth.deleteGscCache },+}));let client: Client;const directory = mkdtempSync(join(tmpdir(), "google-account-removal-"));let service: typeof ServiceModule.GoogleAccountService;@@ -75,15 +84,29 @@ afterAll(() => {rmSync(directory, { recursive: true });});beforeEach(async () => {+ oauth.getGoogleAccessToken.mockImplementation(+ async ({ accountId }: { accountId: string }) => `token-${accountId}`,+ );await client.executeMultiple("DROP TRIGGER IF EXISTS fail_remove; DELETE FROM gsc_connections; DELETE FROM ga4_connections; DELETE FROM account;",);});-async function grant(provider: string, accountId = "google-a", userId = "u1") {+async function grant(+ provider: string,+ accountId = "google-a",+ userId = "u1",+ updatedAt = 1,+) {await client.execute({- sql: "INSERT INTO account (id, account_id, provider_id, user_id, updated_at, access_token, refresh_token) VALUES (?, ?, ?, ?, 1, 'access', 'refresh')",- args: [`${provider}-${userId}-${accountId}`, accountId, provider, userId],+ sql: "INSERT INTO account (id, account_id, provider_id, user_id, updated_at, access_token, refresh_token) VALUES (?, ?, ?, ?, ?, 'access', 'refresh')",+ args: [+ `${provider}-${userId}-${accountId}`,+ accountId,+ provider,+ userId,+ updatedAt,+ ],});}async function mapping(@@ -252,3 +275,30 @@ it.each(["same-account", "other-account", "other-user"] as const)();},);++it("revokes a removed grant only once no stored grant uses that Google account", async () => {+ await grant("google-search-console");+ await grant("google-analytics");+ const input = {+ provider: "gsc" as const,+ accountId: "google-a",+ userId: "u1",+ };+ await service.remove(input);+ expect(oauth.revokeGoogleToken).not.toHaveBeenCalled();+ await service.remove({ ...input, provider: "ga4" });+ expect(oauth.revokeGoogleToken.mock.calls).toEqual([["token-google-a"]]);+});++it("purges and revokes grants no project uses that were last updated before the cutoff", async () => {+ await grant("google-search-console", "unused");+ await grant("google-search-console", "mapped");+ await grant("google-analytics", "recent", "u1", 2_000);+ await mapping("gsc", "p1", "mapped");+ expect(await service.purgeUnusedGrants(new Date(1_000))).toBe(1);+ expect((await rows("account")).map((row) => row.account_id)).toEqual([+ "recent",+ "mapped",+ ]);+ expect(oauth.revokeGoogleToken.mock.calls).toEqual([["token-unused"]]);+});diff --git a/src/server/features/google/GoogleAccountService.ts b/src/server/features/google/GoogleAccountService.tsindex 1e3a5520..79328677 100644--- a/src/server/features/google/GoogleAccountService.ts+++ b/src/server/features/google/GoogleAccountService.ts@@ -1,4 +1,8 @@+import { DashboardCacheService } from "@/server/features/dashboard/services/DashboardCacheService";+import { GA4_OAUTH_PROVIDER_ID } from "@/shared/ga4";+import { GSC_OAUTH_PROVIDER_ID } from "@/shared/gsc";import { GoogleAccountRepository } from "./GoogleAccountRepository";+import { getGoogleAccessToken, revokeGoogleToken } from "./googleOAuth";type AccountInput = {userId: string;@@ -10,12 +14,75 @@ async function getRemovalImpact(input: AccountInput) {return GoogleAccountRepository.getRemovalImpact(input);}+// A token minted before the grant row is deleted, so it can be revoked after.+async function tokenForRevocation(grant: {+ userId: string;+ providerId: string;+ accountId: string;+}) {+ return getGoogleAccessToken(grant).catch(() => null);+}++// Google revokes every scope our OAuth client holds for a Google account, so+// revoking while another OpenSEO user (or the other integration) still stores+// a grant for it would break that grant too. Best-effort: the local token is+// already gone, which is what stops OpenSEO from using it.+async function revokeIfLastGrant(accountId: string, token: string | null) {+ if (!token) return;+ if (await GoogleAccountRepository.hasDataGrantsForGoogleAccount(accountId))+ return;+ try {+ await revokeGoogleToken(token);+ } catch (error) {+ console.error("[google] token revocation failed", error);+ }+}+async function remove(input: AccountInput) {// A user owns their personal Google authorization even when its projects// belong to other organizations. Removing it releases the provider identity// for another OpenSEO user; it does not delete Google sign-in or other scopes.+ const token = await tokenForRevocation({+ userId: input.userId,+ providerId:+ input.provider === "gsc" ? GSC_OAUTH_PROVIDER_ID : GA4_OAUTH_PROVIDER_ID,+ accountId: input.accountId,+ });+ const gscProjectIds =+ input.provider === "gsc"+ ? await GoogleAccountRepository.listGscProjectIds(input)+ : [];await GoogleAccountRepository.remove(input);+ for (const projectId of gscProjectIds)+ await DashboardCacheService.deleteGscCache(projectId);+ await revokeIfLastGrant(input.accountId, token);return { removed: true as const };}-export const GoogleAccountService = { getRemovalImpact, remove };+/**+ * Deletes (and revokes) Search Console / Analytics grants that no project+ * uses. The grace period covers the gap between linking a Google account and+ * picking a site or property for it.+ */+async function purgeUnusedGrants(updatedBefore: Date, deadline = Infinity) {+ let purged = 0;+ // Grants left at the deadline wait for the next run.+ const grants = await GoogleAccountRepository.listUnusedGrants(+ updatedBefore,+ 1000,+ );+ for (const grant of grants) {+ if (Date.now() >= deadline) break;+ const token = await tokenForRevocation(grant);+ if (!(await GoogleAccountRepository.deleteUnusedGrant(grant.id))) continue;+ purged += 1;+ await revokeIfLastGrant(grant.accountId, token);+ }+ return purged;+}++export const GoogleAccountService = {+ getRemovalImpact,+ remove,+ purgeUnusedGrants,+};diff --git a/src/server/features/google/googleDataRetention.ts b/src/server/features/google/googleDataRetention.tsnew file mode 100644index 00000000..39e31d9c--- /dev/null+++ b/src/server/features/google/googleDataRetention.ts@@ -0,0 +1,21 @@+import { GoogleAccountService } from "@/server/features/google/GoogleAccountService";++// A grant gets a day to be bound to a project after the connect flow.+const UNUSED_GRANT_GRACE_MS = 24 * 60 * 60 * 1000;+// Each grant costs a token refresh and a revocation at Google plus a few+// queries. The daily cron has 15 minutes for all its jobs, so the purge stops+// starting new grants after this and the backlog continues the next day.+const PURGE_TIME_BUDGET_MS = 8 * 60 * 1000;++/**+ * Daily cron body: drops Google grants no project uses any more, as the+ * privacy policy promises. Cached Google reports expire on their own: the+ * bucket's `dataforseo-cache/` lifecycle rule deletes them after 7 days.+ */+export async function purgeUnusedGoogleData(now = new Date()) {+ const googleGrants = await GoogleAccountService.purgeUnusedGrants(+ new Date(now.getTime() - UNUSED_GRANT_GRACE_MS),+ now.getTime() + PURGE_TIME_BUDGET_MS,+ );+ return { googleGrants };+}diff --git a/src/server/features/google/googleOAuth.ts b/src/server/features/google/googleOAuth.tsindex 20de215e..9f4c5ca9 100644--- a/src/server/features/google/googleOAuth.ts+++ b/src/server/features/google/googleOAuth.ts@@ -50,6 +50,7 @@ import {const GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";+const GOOGLE_REVOKE_URL = "https://oauth2.googleapis.com/revoke";// Refresh when the stored access token is within this many ms of expiry.const ACCESS_TOKEN_SKEW_MS = 5_000;@@ -402,6 +403,25 @@ export async function getGoogleAccessToken(input: {return tokens.access_token;}+/**+ * Revokes a Google access or refresh token. Google revokes the whole grant+ * the token belongs to (every scope this OAuth client holds for that Google+ * account), so callers must make sure no other stored grant still needs it.+ */+export async function revokeGoogleToken(token: string): Promise<void> {+ const response = await fetch(GOOGLE_REVOKE_URL, {+ method: "POST",+ headers: { "Content-Type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({ token }),+ signal: AbortSignal.timeout(10_000),+ });+ // Google answers 400 invalid_token for an already-revoked or expired token,+ // which leaves no live grant either way.+ if (!response.ok && response.status !== 400) {+ throw new Error(`Google token revocation failed: ${response.status}`);+ }+}+export async function handleGoogleOAuthCallbackRequest(request: Request,integration: GoogleOAuthIntegration,diff --git a/src/server/features/gsc/services/GscService.ts b/src/server/features/gsc/services/GscService.tsindex 9196f4a8..c70c382d 100644--- a/src/server/features/gsc/services/GscService.ts+++ b/src/server/features/gsc/services/GscService.ts@@ -22,6 +22,7 @@ import {GscConnectionRepository,type GscConnection,} from "@/server/features/gsc/repositories/GscConnectionRepository";+import { DashboardCacheService } from "@/server/features/dashboard/services/DashboardCacheService";import type {GscSearchAnalyticsRequest,GscSearchAnalyticsRow,@@ -197,6 +198,7 @@ async function setSite(input: {async function disconnect(input: { projectId: string }): Promise<void> {await GscConnectionRepository.deleteByProjectId(input.projectId);+ await DashboardCacheService.deleteGscCache(input.projectId);}/** Pass-through of GSC `searchAnalytics.query` for a project's connected property. */diff --git a/src/server/gdpr/storage-erasure.ts b/src/server/gdpr/storage-erasure.tsindex 9b2f48d3..be653adb 100644--- a/src/server/gdpr/storage-erasure.ts+++ b/src/server/gdpr/storage-erasure.ts@@ -1,6 +1,11 @@-import { getGoogleAccessToken } from "@/server/features/google/googleOAuth";+import {+ getGoogleAccessToken,+ revokeGoogleToken,+} from "@/server/features/google/googleOAuth";import type { SamChatAgent } from "@/server/features/sam/SamChatAgent";import { captureServerError } from "@/server/lib/posthog";+import { deleteR2Prefix } from "@/server/lib/r2";+import { DashboardCacheService } from "@/server/features/dashboard/services/DashboardCacheService";import { deleteProjectAiObjects } from "@/server/features/ai-visibility/services/aiVisibilityStorage";import {DUB_REFERRED_ORG_KV_PREFIX,@@ -18,7 +23,6 @@ import {const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;const MAX_BODY_BYTES = 5 * 1024 * 1024;-const GOOGLE_REVOKE_URL = "https://oauth2.googleapis.com/revoke";const PROMPT_CACHE_PREFIX = cacheObjectPrefix(AI_SEARCH_PROMPT_CACHE_NAMESPACE);type GoogleRevocationResult = {@@ -153,16 +157,12 @@ async function revokeGoogleAccount(return { ...account, status: "token_unavailable" };}- const response = await fetch(GOOGLE_REVOKE_URL, {- method: "POST",- headers: { "Content-Type": "application/x-www-form-urlencoded" },- body: new URLSearchParams({ token: accessToken }),- });- // Google uses invalid_token for an already-revoked token. Either response- // leaves OpenSEO without a live upstream grant once the local row is erased.- if (!response.ok && response.status !== 400) {+ try {+ await revokeGoogleToken(accessToken);+ } catch (error) {throw new Error(- `Google token revocation failed for ${account.providerId}/${account.accountId}: ${response.status}`,+ `Google token revocation failed for ${account.providerId}/${account.accountId}`,+ { cause: error },);}return { ...account, status: "revoked" };@@ -228,9 +228,20 @@ async function eraseStorage(env: Env, payload: GdprStorageErasurePayload) {env.R2,payload.organizationIds,);+ // aiVisibilityProjectIds lists every project of the erased organizations.let aiVisibilityObjects = 0;+ let searchConsoleCacheObjects = 0;+ let siteAuditObjects = 0;for (const projectId of payload.aiVisibilityProjectIds) {aiVisibilityObjects += await deleteProjectAiObjects(env.R2, projectId);+ searchConsoleCacheObjects +=+ await DashboardCacheService.deleteGscCache(projectId);+ // Lighthouse files a best-effort audit deletion missed: their database+ // rows, and so their keys in r2Keys, are already gone.+ siteAuditObjects += await deleteR2Prefix(+ env.R2,+ `site-audit/${projectId}/`,+ );}const oauth = await deleteOauthGrants(env.OAUTH_KV, payload.userId);@@ -252,6 +263,8 @@ async function eraseStorage(env: Env, payload: GdprStorageErasurePayload) {r2Objects: payload.r2Keys.length,promptCacheObjects,aiVisibilityObjects,+ searchConsoleCacheObjects,+ siteAuditObjects,googleRevocations,};}diff --git a/src/server/lib/r2.ts b/src/server/lib/r2.tsindex 4eef8970..97324525 100644--- a/src/server/lib/r2.ts+++ b/src/server/lib/r2.ts@@ -24,3 +24,17 @@ export async function putTextToR2(sizeBytes: Buffer.byteLength(body),};}++/** Deletes every object under `prefix`; returns how many were removed. */+export async function deleteR2Prefix(bucket: R2Bucket, prefix: string) {+ let cursor: string | undefined;+ let deleted = 0;+ do {+ const page = await bucket.list({ prefix, cursor });+ const keys = page.objects.map((object) => object.key);+ if (keys.length) await bucket.delete(keys);+ deleted += keys.length;+ cursor = page.truncated ? page.cursor : undefined;+ } while (cursor);+ return deleted;+}