0
Create a scoped access token
One script reply has been approved by the moderators Verified

Use a non-scoped user-to-server access token to create a repository scoped and/or permission scoped user-to-server access token.

Created by hugo697 176 days ago Viewed 3954 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 176 days ago
1
type Github = {
2
  token: string;
3
};
4
/**
5
 * Create a scoped access token
6
 * Use a non-scoped user-to-server access token to create a repository scoped and/or permission scoped user-to-server access token.
7
 */
8
export async function main(
9
  auth: Github,
10
  client_id: string,
11
  body: {
12
    access_token: string;
13
    permissions?: {
14
      actions?: "read" | "write";
15
      administration?: "read" | "write";
16
      checks?: "read" | "write";
17
      contents?: "read" | "write";
18
      deployments?: "read" | "write";
19
      environments?: "read" | "write";
20
      issues?: "read" | "write";
21
      members?: "read" | "write";
22
      metadata?: "read" | "write";
23
      organization_administration?: "read" | "write";
24
      organization_announcement_banners?: "read" | "write";
25
      organization_custom_roles?: "read" | "write";
26
      organization_hooks?: "read" | "write";
27
      organization_packages?: "read" | "write";
28
      organization_plan?: "read";
29
      organization_projects?: "read" | "write" | "admin";
30
      organization_secrets?: "read" | "write";
31
      organization_self_hosted_runners?: "read" | "write";
32
      organization_user_blocking?: "read" | "write";
33
      packages?: "read" | "write";
34
      pages?: "read" | "write";
35
      pull_requests?: "read" | "write";
36
      repository_announcement_banners?: "read" | "write";
37
      repository_hooks?: "read" | "write";
38
      repository_projects?: "read" | "write" | "admin";
39
      secret_scanning_alerts?: "read" | "write";
40
      secrets?: "read" | "write";
41
      security_events?: "read" | "write";
42
      single_file?: "read" | "write";
43
      statuses?: "read" | "write";
44
      team_discussions?: "read" | "write";
45
      vulnerability_alerts?: "read" | "write";
46
      workflows?: "write";
47
      [k: string]: unknown;
48
    };
49
    repositories?: string[];
50
    repository_ids?: number[];
51
    target?: string;
52
    target_id?: number;
53
    [k: string]: unknown;
54
  }
55
) {
56
  const url = new URL(
57
    `https://api.github.com/applications/${client_id}/token/scoped`
58
  );
59

60
  const response = await fetch(url, {
61
    method: "POST",
62
    headers: {
63
      "Content-Type": "application/json",
64
      Authorization: "Bearer " + auth.token,
65
    },
66
    body: JSON.stringify(body),
67
  });
68
  if (!response.ok) {
69
    const text = await response.text();
70
    throw new Error(`${response.status} ${text}`);
71
  }
72
  return await response.json();
73
}
74