This repository was archived by the owner on Jul 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
426 lines (358 loc) Β· 11.8 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import {appAuth} from '@stoe/octoherd-script-common'
import {setTimeout} from 'timers/promises'
/**
* @param {import('@octoherd/cli').Octokit} octokit
* @param {import('@octoherd/cli').Repository} repository
* @param {object} [options]
* @param {int} [options.appId=0]
* @param {string} [options.privateKey='']
* @param {boolean} [options.dryRun=false]
*/
export async function script(octokit, repository, {appId = 0, privateKey = '', dryRun = false}) {
const {
archived,
disabled,
fork,
size,
owner: {login: owner},
name: repo,
node_id: repoID,
clone_url: url,
} = repository
// skip archived, disabled, forked and empty repos
if (archived || disabled || fork || size === 0) return
const language = repository.language ? repository.language.toLowerCase() : null
let ok = octokit
if (appId && privateKey) {
try {
ok = await appAuth(repository, appId, privateKey)
octokit.log.info(` π€ authenticated as app`)
} catch (error) {
octokit.log.info({error}, ` β failed to authenticate as app`)
return
}
}
// branch protection
const {
repository: {
owner: {id: ownerID, type: ownerType},
branchProtectionRules: {nodes: rules},
},
} = await ok.graphql(getBranchProtectionQuery, {owner, repo})
let actors = []
if (ownerType === 'User') {
actors = [ownerID]
}
try {
// determine if branch protection needs to be created or updated
const create = rules.length === 0
const update = rules.length > 0
if (!create && !update) {
octokit.log.info({skipped: true}, ` π branch protection`)
} else {
const statusCheckContext = []
if (language === 'javascript') {
statusCheckContext.push('test / test-matrix (16, false)')
statusCheckContext.push('test / test')
}
const branchProtection = {
repo: repoID,
statusCheckContext,
actors,
}
// create
if (create) {
if (dryRun) {
octokit.log.info(
{checks: true, language, statusCheckContext: branchProtection.statusCheckContext},
` π’ dry-run create branch protection`,
)
} else {
await ok.graphql(createBranchProtectionQuery, branchProtection)
octokit.log.info(
{checks: true, language, statusCheckContext: branchProtection.statusCheckContext},
` π create branch protection`,
)
}
}
// update
if (update) {
for (const rule of rules) {
const {pattern, id} = rule
branchProtection.pattern = pattern
branchProtection.branchProtectionRuleId = id
if (['main', 'master'].includes(pattern)) {
if (dryRun) {
octokit.log.info(
{checks: true, pattern, language, statusCheckContext: branchProtection.statusCheckContext},
` π’ dry-run update branch protection`,
)
} else {
await ok.graphql(updateBranchProtectionQuery, branchProtection)
octokit.log.info(
{checks: true, pattern, language, statusCheckContext: branchProtection.statusCheckContext},
` π update branch protection`,
)
}
} else {
octokit.log.info(
{skipped: true, pattern, language, statusCheckContext: branchProtection.statusCheckContext},
` π branch protection`,
)
continue
}
}
}
}
} catch (error) {
octokit.log.error({error: error.message}, ` β branch protection`)
}
// sleep 1 second
await setTimeout(1000)
// tags
try {
// enable tag protection if not already enabled
// https://docs.github.com/en/rest/repos/tags#list-tag-protection-states-for-a-repository
const {data} = await ok.request('GET /repos/{owner}/{repo}/tags/protection', {
owner,
repo,
})
if (data.length < 1 || data.every(d => d.pattern !== 'v*.*.*')) {
const tagPattern = 'v*.*.*'
if (dryRun) {
octokit.log.info({checks: true}, ` π’ dry-run tag protection ${tagPattern}`)
} else {
// https://docs.github.com/en/rest/repos/tags#create-a-tag-protection-state-for-a-repository
await ok.request('POST /repos/{owner}/{repo}/tags/protection', {
owner,
repo,
pattern: tagPattern,
})
octokit.log.info({checks: true}, ` π tag protection ${tagPattern}`)
}
} else {
octokit.log.info({skipped: true, patterns: data.map(d => d.pattern)}, ` π tag protection`)
}
} catch (error) {
octokit.log.error({error: error.message}, ` β tag protection`)
}
// sleep 1 second
await setTimeout(1000)
// settings
// https://docs.github.com/en/rest/reference/repos#update-a-repository
const config = {
owner,
repo,
name: repo,
has_issues: true,
has_projects: false,
has_wiki: false,
allow_squash_merge: true,
allow_merge_commit: false,
allow_rebase_merge: false,
allow_auto_merge: true,
delete_branch_on_merge: true,
security_and_analysis: {
secret_scanning: {
status: 'enabled',
},
secret_scanning_push_protection: {
status: 'enabled',
},
},
squash_merge_commit_title: 'PR_TITLE',
squash_merge_commit_message: 'BLANK',
}
try {
if (dryRun) {
octokit.log.info({updated: true}, ` π’ dry-run vulnerability alerts`)
} else {
// https://docs.github.com/en/rest/reference/repos#enable-vulnerability-alerts
await ok.request('PUT /repos/{owner}/{repo}/vulnerability-alerts', {
owner,
repo,
})
octokit.log.info({updated: true}, ` π automated security fixes`)
// sleep 1 second
await setTimeout(1000)
}
if (dryRun) {
octokit.log.info({updated: true}, ` π’ dry-run automated security fixes`)
} else {
// https://docs.github.com/en/rest/reference/repos#enable-automated-security-fixes
await ok.request('PUT /repos/{owner}/{repo}/automated-security-fixes', {
owner,
repo,
})
octokit.log.info({updated: true}, ` π vulnerability alerts`)
// sleep 1 second
await setTimeout(1000)
}
if (config.security_and_analysis.secret_scanning && repository.visibility === 'public') {
// Secret Scanning is enabled on public repositories
delete config.security_and_analysis.secret_scanning
octokit.log.info({skipped: true, visibility: repository.visibility, type: ownerType}, ` π secret scanning`)
}
if (
(config.security_and_analysis.secret_scanning || config.security_and_analysis.secret_scanning_push_protection) &&
ownerType === 'User'
) {
// Secret Scanning can only be set on organization owned repositories
delete config.security_and_analysis.secret_scanning
delete config.security_and_analysis.secret_scanning_push_protection
octokit.log.info(
{skipped: true, visibility: repository.visibility, type: ownerType},
` π secret scanning push protection`,
)
}
if (Object.keys(config.security_and_analysis).length === 0) {
delete config.security_and_analysis
} else {
if (config.security_and_analysis.secret_scanning) {
octokit.log.info({updated: true, visibility: repository.visibility, type: ownerType}, ` π secret scanning`)
}
if (config.security_and_analysis.secret_scanning_push_protection) {
octokit.log.info(
{updated: true, visibility: repository.visibility, type: ownerType},
` π secret scanning push protection`,
)
}
}
if (dryRun) {
const c = {}
for (const [key, value] of Object.entries(config)) {
if (!['owner', 'repo', 'name'].includes(key)) {
c[key] = value
}
}
octokit.log.info(
{
updated: true,
config: c,
},
` π’ dry-run repository settings`,
)
} else {
await ok.request('PATCH /repos/{owner}/{repo}', config)
octokit.log.info({updated: true}, ` π§ repository settings`)
// sleep 1 second
await setTimeout(1000)
}
} catch (error) {
octokit.log.warn({error: error.message}, ` β repository settings, retrying without secret scanning`)
if (error.message === 'Secret scanning can only be enabled on repos where Advanced Security is enabled') {
delete config.security_and_analysis.secret_scanning
await ok.request('PATCH /repos/{owner}/{repo}', config)
octokit.log.info({updated: true}, ` π§ repository settings`)
}
}
// sleep 1 second
await setTimeout(1000)
// actions settings
const actionsConfig = {
owner,
repo,
default_workflow_permissions: 'read',
// can_approve_pull_request_reviews: true,
}
if (dryRun) {
octokit.log.info({updated: true, config: actionsConfig}, ` π’ dry-run actions settings`)
} else {
try {
// https://docs.github.com/en/rest/actions/permissions#set-default-workflow-permissions-for-a-repository
await ok.request('PUT /repos/{owner}/{repo}/actions/permissions/workflow', actionsConfig)
octokit.log.info({updated: true}, ` π§ actions settings`)
} catch (error) {
octokit.log.warn({error: error.message}, ` β actions settings`)
}
}
// done
octokit.log.info(` β
${url}`)
return true
}
const getBranchProtectionQuery = `query(
$owner: String!,
$repo: String!
) {
repository(
owner: $owner,
name: $repo
) {
owner {
id
type: __typename
}
branchProtectionRules(first: 5) {
nodes {
id
pattern
requiredStatusChecks {
context
}
}
}
}
}`
// https://docs.github.com/en/graphql/reference/input-objects#createbranchprotectionruleinput
const createBranchProtectionQuery = `mutation(
$repo: ID!,
$statusCheckContext: [String!] = [],
$actors: [ID!] = []
) {
createBranchProtectionRule(input: {
clientMutationId: "@stoe/octoherd-script-repo-settings"
repositoryId: $repo
pattern: "main"
requiresApprovingReviews: true
requiredApprovingReviewCount: 0
requiresCodeOwnerReviews: true
restrictsReviewDismissals: false
requireLastPushApproval: true
requiresStatusChecks: true
requiresStrictStatusChecks: true
requiredStatusCheckContexts: $statusCheckContext
requiresConversationResolution: true
requiresCommitSignatures: true
requiresLinearHistory: true
restrictsPushes: false
isAdminEnforced: false
allowsForcePushes: false
bypassForcePushActorIds: $actors
bypassPullRequestActorIds: $actors
allowsDeletions: false
}) {
clientMutationId
}
}`
// https://docs.github.com/en/graphql/reference/mutations#updatebranchprotectionrule
const updateBranchProtectionQuery = `mutation(
$branchProtectionRuleId: ID!
$pattern: String = "main",
$statusCheckContext: [String!] = [],
$actors: [ID!] = []
) {
updateBranchProtectionRule(input: {
clientMutationId: "@stoe/octoherd-script-repo-settings"
branchProtectionRuleId: $branchProtectionRuleId
pattern: $pattern
requiresApprovingReviews: true
requiredApprovingReviewCount: 0
requiresCodeOwnerReviews: true
restrictsReviewDismissals: false
requireLastPushApproval: true
requiresStatusChecks: true
requiresStrictStatusChecks: true
requiredStatusCheckContexts: $statusCheckContext
requiresConversationResolution: true
requiresCommitSignatures: true
requiresLinearHistory: true
restrictsPushes: false
isAdminEnforced: false
allowsForcePushes: false
bypassForcePushActorIds: $actors
bypassPullRequestActorIds: $actors
allowsDeletions: false
}) {
clientMutationId
}
}`