Rotate Secret for a Turnstile Widget

Generate a new secret key for this widget. If `invalidate_immediately` is set to `false`, the previous secret remains valid for 2 hours. Note that secrets cannot be rotated again during the grace period.

Script cloudflare Verified

by hugo697 ยท 11/16/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 383 days ago
1
type Cloudflare = {
2
  token: string;
3
  email: string;
4
  key: string;
5
};
6
/**
7
 * Rotate Secret for a Turnstile Widget
8
 * Generate a new secret key for this widget. If `invalidate_immediately`
9
is set to `false`, the previous secret remains valid for 2 hours.
10

11
Note that secrets cannot be rotated again during the grace period.
12

13
 */
14
export async function main(
15
  auth: Cloudflare,
16
  account_identifier: string,
17
  sitekey: string,
18
  body: { invalidate_immediately?: boolean; [k: string]: unknown }
19
) {
20
  const url = new URL(
21
    `https://api.cloudflare.com/client/v4/accounts/${account_identifier}/challenges/widgets/${sitekey}/rotate_secret`
22
  );
23

24
  const response = await fetch(url, {
25
    method: "POST",
26
    headers: {
27
      "X-AUTH-EMAIL": auth.email,
28
      "X-AUTH-KEY": auth.key,
29
      "Content-Type": "application/json",
30
      Authorization: "Bearer " + auth.token,
31
    },
32
    body: JSON.stringify(body),
33
  });
34
  if (!response.ok) {
35
    const text = await response.text();
36
    throw new Error(`${response.status} ${text}`);
37
  }
38
  return await response.json();
39
}
40