Open History to see the last commit
1/**
2 * Mark a PR `secure` and approve waiting first-time-contributor workflow runs.
3 */
4
5import type { GitHubClient } from '../../scripts/maintainer/github.ts'
6
7export const SECURE_LABEL = {
8 name: 'secure',
9 color: '0e8a16',
10 description: 'AI review: no malware found. Waiting workflows were approved.',
11} as const
12
13function errorMentionsStatus(error: unknown, status: string) {
14 return error instanceof Error && error.message.includes(status)
15}
16
17function isRecord(value: unknown): value is Record<string, unknown> {
18 return typeof value === 'object' && value !== null && !Array.isArray(value)
19}
20
21function parseRunIds(raw: unknown, path: string) {
22 if (!isRecord(raw) || !Array.isArray(raw.workflow_runs)) {
23 throw new Error(`GitHub GET ${path} is missing workflow_runs`)
24 }
25 const ids = []
26 for (const run of raw.workflow_runs) {
27 if (!isRecord(run) || typeof run.id !== 'number') {
28 throw new Error(`GitHub GET ${path} has a run without id`)
29 }
30 ids.push(run.id)
31 }
32 return ids
33}
34
35/**
36 * Add or remove the `secure` label. Creates the repo label if it is missing.
37 */
38export async function setSecureLabel(
39 client: GitHubClient,
40 repo: string,
41 issueNumber: number,
42 on: boolean,
43) {
44 try {
45 await client.rest('POST', `/repos/${repo}/labels`, SECURE_LABEL)
46 } catch (error) {
47 if (!errorMentionsStatus(error, '422')) throw error
48 }
49
50 const issuePath = `/repos/${repo}/issues/${issueNumber}/labels/${encodeURIComponent(SECURE_LABEL.name)}`
51 if (!on) {
52 try {
53 await client.rest('DELETE', issuePath)
54 } catch (error) {
55 if (!errorMentionsStatus(error, '404')) throw error
56 }
57 return
58 }
59
60 await client.rest('POST', `/repos/${repo}/issues/${issueNumber}/labels`, {
61 labels: [SECURE_LABEL.name],
62 })
63}
64
65/**
66 * Approve workflow runs on this head SHA that wait for first-time-contributor
67 * approval. Returns how many approve calls succeeded.
68 */
69export async function approveWaitingWorkflows(
70 client: GitHubClient,
71 repo: string,
72 headSha: string,
73) {
74 const statuses = ['waiting', 'action_required']
75 const ids = new Set<number>()
76 for (const status of statuses) {
77 const path = `/repos/${repo}/actions/runs?head_sha=${encodeURIComponent(headSha)}&status=${status}&per_page=100`
78 const batch = parseRunIds(await client.rest('GET', path), path)
79 for (const id of batch) ids.add(id)
80 }
81
82 let approved = 0
83 for (const id of ids) {
84 await client.rest('POST', `/repos/${repo}/actions/runs/${id}/approve`)
85 approved += 1
86 }
87 return approved
88}