Create signed URL tokens for videos

Creates a signed URL token for a video. If a body is not provided in the request, a token is created with default values.

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 signed URL tokens for videos
8
 * Creates a signed URL token for a video. If a body is not provided in the request, a token is created with default values.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  identifier: string,
13
  account_identifier: string,
14
  body: {
15
    accessRules?: {
16
      action?: "allow" | "block";
17
      country?: string[];
18
      ip?: string[];
19
      type?: "any" | "ip.src" | "ip.geoip.country";
20
      [k: string]: unknown;
21
    }[];
22
    downloadable?: boolean;
23
    exp?: number;
24
    id?: string;
25
    nbf?: number;
26
    pem?: string;
27
    [k: string]: unknown;
28
  }
29
) {
30
  const url = new URL(
31
    `https://api.cloudflare.com/client/v4/accounts/${account_identifier}/stream/${identifier}/token`
32
  );
33

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