Dough Git

commit

add /burst

commit
ee2fe51c28cf55b8dafe736f2447f2da775c8b71
author
Clove Twilight <[email protected]>
date
2026-08-10 22:07

diff --git a/.dev.vars.example b/.dev.vars.example
index 6b21d0f..56075ea 100644
--- a/.dev.vars.example
+++ b/.dev.vars.example
@@ -74,3 +74,14 @@ GITHUB_TOKEN=
 # (its sections return null with source "unavailable"); /minecraft/general
 # (Mojang profile + skin) needs no key and always works.
 HYPIXEL_API_KEY=
+
+# ---- /v2/burst — purge ALL Cloudflare cache --------------------------------
+# Cloudflare API token. /v2/burst lists every zone this token can see (across
+# every account it has access to, including the account that owns this Worker)
+# and purges everything on each. Create at My Profile > API Tokens with:
+#   Zone > Zone       : Read
+#   Zone > Cache Purge: Purge
+# Production: `wrangler secret put CF_API_TOKEN`.
+# WARNING: the endpoint is unauthenticated — anyone who loads /v2/burst nukes
+# all cache. Leave blank to disable (route returns code: CF_API_TOKEN ...).
+CF_API_TOKEN=
diff --git a/src/cloudflare.ts b/src/cloudflare.ts
new file mode 100644
index 0000000..b6e5dcd
--- /dev/null
+++ b/src/cloudflare.ts
@@ -0,0 +1,120 @@
+/* =====================================================================
+ * cloudflare.ts — nuke ALL Cloudflare cache.
+ *
+ * purgeAllCache() lists every zone the CF_API_TOKEN can see (which spans
+ * every account the token has access to, including the one that owns this
+ * Worker) and issues `purge_everything` against each. Powers /v2/burst.
+ *
+ * Token permissions required (single token):
+ *   - Zone → Zone      : Read          (to enumerate every zone)
+ *   - Zone → Cache Purge: Purge         (to purge each zone)
+ * Create it at: My Profile → API Tokens → Create Token. Then set it as a
+ * secret:  wrangler secret put CF_API_TOKEN
+ * ===================================================================== */
+
+import type { Env } from "./types";
+
+const CF_API = "https://api.cloudflare.com/client/v4";
+
+/** Outcome of a burst: ok + how many zones were purged, or the first error. */
+export interface BurstResult {
+  ok: boolean;
+  error?: string;
+  purged: number;
+  total: number;
+}
+
+interface CfZone {
+  id: string;
+  name: string;
+}
+
+interface CfError {
+  code?: number;
+  message?: string;
+}
+
+interface CfResultInfo {
+  page?: number;
+  total_pages?: number;
+}
+
+interface CfListResponse {
+  success: boolean;
+  errors?: CfError[];
+  result?: CfZone[];
+  result_info?: CfResultInfo;
+}
+
+interface CfMutResponse {
+  success: boolean;
+  errors?: CfError[];
+}
+
+/** First human-readable message out of a CF error envelope, if any. */
+function cfErr(body: { errors?: CfError[] }): string | null {
+  const first = body.errors?.[0];
+  if (!first) return null;
+  return first.message ?? (first.code != null ? `code ${first.code}` : null);
+}
+
+/**
+ * Purge everything, everywhere. Stops at the first failure and reports it so
+ * the caller can surface `code: {error}`. Any thrown network error is caught
+ * by the route and turned into the same envelope.
+ */
+export async function purgeAllCache(env: Env): Promise<BurstResult> {
+  const token = env.CF_API_TOKEN;
+  if (!token) {
+    return { ok: false, error: "CF_API_TOKEN is not configured", purged: 0, total: 0 };
+  }
+
+  const auth = { Authorization: `Bearer ${token}` };
+
+  // 1. Enumerate every zone across every account this token can reach.
+  const zones: CfZone[] = [];
+  let page = 1;
+  for (;;) {
+    const res = await fetch(`${CF_API}/zones?per_page=50&page=${page}`, { headers: auth });
+    const body = (await res.json()) as CfListResponse;
+    if (!res.ok || !body.success) {
+      return {
+        ok: false,
+        error: cfErr(body) ?? `zone list failed (HTTP ${res.status})`,
+        purged: 0,
+        total: zones.length,
+      };
+    }
+    for (const z of body.result ?? []) zones.push({ id: z.id, name: z.name });
+
+    const totalPages = body.result_info?.total_pages ?? page;
+    if (page >= totalPages || (body.result?.length ?? 0) === 0) break;
+    page++;
+  }
+
+  if (zones.length === 0) {
+    return { ok: false, error: "no zones visible to CF_API_TOKEN", purged: 0, total: 0 };
+  }
+
+  // 2. Purge everything on each zone. First failure aborts and is reported.
+  let purged = 0;
+  for (const z of zones) {
+    const res = await fetch(`${CF_API}/zones/${z.id}/purge_cache`, {
+      method: "POST",
+      headers: { ...auth, "Content-Type": "application/json" },
+      body: JSON.stringify({ purge_everything: true }),
+    });
+    const body = (await res.json()) as CfMutResponse;
+    if (!res.ok || !body.success) {
+      return {
+        ok: false,
+        error: `${z.name}: ${cfErr(body) ?? `HTTP ${res.status}`}`,
+        purged,
+        total: zones.length,
+      };
+    }
+    purged++;
+  }
+
+  return { ok: true, purged, total: zones.length };
+}
diff --git a/src/index.ts b/src/index.ts
index be6cc2d..4fbf5f0 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -43,6 +43,7 @@ import { getGuildInvite } from "./guild";
 import { getGirlsResource, isGirlsIdType } from "./girls";
 import { getMinecraftGeneral, getMinecraftHypixel, getVanillaCapeList, normalizeMcUuid, isAllowedHypixelUuid, MojangUpstreamError } from "./minecraft";
 import { getContributions } from "./contribapi";
+import { purgeAllCache } from "./cloudflare";
 import {
   getGenshinRoster,
   getGenshinCharacterDetail,
@@ -242,6 +243,27 @@ export default {
       );
     }
 
+    // ---- /v2/burst  (nuke ALL Cloudflare cache, everywhere) --------------
+    // Lists every zone the CF_API_TOKEN can see (all accounts, including the
+    // one that owns this Worker) and purges everything on each. Returns
+    // {code:"success"} when every zone purged, else {code:"<error>"}.
+    // WARNING: unauthenticated — anyone who loads this URL purges all cache.
+    if (path === "/v2/burst") {
+      let code: string;
+      let ok = false;
+      try {
+        const result = await purgeAllCache(env);
+        ok = result.ok;
+        code = result.ok ? "success" : (result.error ?? "unknown error");
+      } catch (err) {
+        code = (err as Error).message || "unknown error";
+      }
+      return new Response(JSON.stringify({ code }), {
+        status: ok ? 200 : 500,
+        headers: { "Content-Type": "application/json", "Cache-Control": "no-store", ...CORS, ...SECURITY_HEADERS },
+      });
+    }
+
     // ---- Gateway status (debug) ------------------------------------------
     if (path === "/v2/discord/status") {
       const res = await gatewayStub(env).fetch("https://do/status");
diff --git a/src/types.ts b/src/types.ts
index b97a7ab..63c45c2 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -82,6 +82,12 @@ export interface Env {
    *  our own accounts — arbitrary UUIDs are rejected so it can't be used to
    *  proxy the Public API to third parties. Empty = endpoint disabled. */
   MINECRAFT_ALLOWED_UUIDS?: string;
+
+  // ---- /v2/burst  (purge ALL Cloudflare cache) ---------------------------
+  /** Cloudflare API token used by /v2/burst to purge every zone's cache
+   *  across every account the token can access. Needs Zone:Read + Cache
+   *  Purge. Set as a secret: `wrangler secret put CF_API_TOKEN`. */
+  CF_API_TOKEN?: string;
 }
 
 export type DiscordStatus = "online" | "idle" | "dnd" | "offline";