Create an IP Access rule

Creates a new IP Access rule for an account. The rule will apply to all zones in the account. Note: To create an IP Access rule that applies to a single zone, refer to the [IP Access rules for a zone](#ip-access-rules-for-a-zone) endpoints.

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
 * Create an IP Access rule
8
 * Creates a new IP Access rule for an account. The rule will apply to all zones in the account.
9

10
Note: To create an IP Access rule that applies to a single zone, refer to the [IP Access rules for a zone](#ip-access-rules-for-a-zone) endpoints.
11
 */
12
export async function main(
13
  auth: Cloudflare,
14
  account_identifier: string,
15
  body: {
16
    configuration:
17
      | { target?: "ip"; value?: string; [k: string]: unknown }
18
      | { target?: "ip6"; value?: string; [k: string]: unknown }
19
      | { target?: "ip_range"; value?: string; [k: string]: unknown }
20
      | { target?: "asn"; value?: string; [k: string]: unknown }
21
      | { target?: "country"; value?: string; [k: string]: unknown };
22
    mode:
23
      | "block"
24
      | "challenge"
25
      | "whitelist"
26
      | "js_challenge"
27
      | "managed_challenge";
28
    notes?: string;
29
    [k: string]: unknown;
30
  }
31
) {
32
  const url = new URL(
33
    `https://api.cloudflare.com/client/v4/accounts/${account_identifier}/firewall/access_rules/rules`
34
  );
35

36
  const response = await fetch(url, {
37
    method: "POST",
38
    headers: {
39
      "X-AUTH-EMAIL": auth.email,
40
      "X-AUTH-KEY": auth.key,
41
      "Content-Type": "application/json",
42
      Authorization: "Bearer " + auth.token,
43
    },
44
    body: JSON.stringify(body),
45
  });
46
  if (!response.ok) {
47
    const text = await response.text();
48
    throw new Error(`${response.status} ${text}`);
49
  }
50
  return await response.json();
51
}
52