-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathlint-github-settings.mts
More file actions
1062 lines (1011 loc) · 35 KB
/
lint-github-settings.mts
File metadata and controls
1062 lines (1011 loc) · 35 KB
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file Fleet lint: validate (and optionally fix) the GitHub repository
* settings against the canonical fleet config. Why this exists: a half-dozen
* repo settings determine whether the fleet enforces signed commits,
* restricts PRs to collaborators, disables wikis/discussions/projects/forks,
* and forces squash-only merges. GitHub doesn't make these flags discoverable
* to the maintainer, and the only signal a repo is misconfigured is when
* something breaks in production. This script audits them and prints the
* exact URL to fix each, or PATCHes them itself with `--fix`. Run cadence:
* weekly, locally. The first successful run writes
* `.cache/socket-wheelhouse-github-settings.json` with a timestamp;
* subsequent runs within 7 days are no-ops (use `--force` to override). CI
* behavior: if `CI=true` is in the env (GitHub Actions, etc.), the script
* skips entirely. Settings audits aren't a CI gate — the local cache write is
* the gate. CI failing on a missing/stale cache would burn API quota on every
* job and serialize maintainers behind it. Auth: requires `gh` CLI
* authenticated, OR `GITHUB_TOKEN` / `GH_TOKEN` in env. Read-only audit needs
* `repo:read`; `--fix` needs `repo:admin` (PATCH /repos/{owner}/{repo}).
* Usage: node scripts/lint-github-settings.mts # audit (uses cache) node
* scripts/lint-github-settings.mts --force # audit (skip cache) node
* scripts/lint-github-settings.mts --fix # audit + apply fixes node
* scripts/lint-github-settings.mts --json # machine-readable.
*/
import { spawnSync } from '@socketsecurity/lib-stable/process/spawn/child'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import process from 'node:process'
import { REPO_ROOT } from './paths.mts'
// Inline path + config-loader equivalents of the wheelhouse template's
// paths.mts helpers. `lint-github-settings.mts` cascades into fleet
// repos whose per-package `paths.mts` is intentionally minimal
// (`socket-cli`, `ultrathink`, etc. only export REPO_ROOT +
// package-specific build paths). Importing `NODE_MODULES_CACHE_DIR` /
// `loadSocketWheelhouseConfig` from `./paths.mts` would force every
// consumer to widen their paths.mts surface — wrong direction. Keep
// the per-package paths.mts narrow; carry the standalone helpers here.
const NODE_MODULES_CACHE_DIR = path.join(REPO_ROOT, 'node_modules', '.cache')
const SOCKET_WHEELHOUSE_CONFIG_PRIMARY_REL = '.config/socket-wheelhouse.json'
const SOCKET_WHEELHOUSE_CONFIG_LEGACY_REL = '.socket-wheelhouse.json'
interface LoadedSocketWheelhouseConfig {
readonly value: Record<string, unknown>
}
function loadSocketWheelhouseConfig(
repoRoot: string,
): LoadedSocketWheelhouseConfig | undefined {
const primary = path.join(repoRoot, SOCKET_WHEELHOUSE_CONFIG_PRIMARY_REL)
const legacy = path.join(repoRoot, SOCKET_WHEELHOUSE_CONFIG_LEGACY_REL)
const target = existsSync(primary)
? primary
: existsSync(legacy)
? legacy
: undefined
if (!target) {
return undefined
}
let raw: string
try {
raw = readFileSync(target, 'utf8')
} catch {
return undefined
}
let parsed: unknown
try {
parsed = JSON.parse(raw)
} catch {
return undefined
}
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
return undefined
}
return { value: parsed as Record<string, unknown> }
}
interface RepoApiPayload {
default_branch?: string | undefined
has_wiki?: boolean | undefined
has_discussions?: boolean | undefined
has_projects?: boolean | undefined
allow_forking?: boolean | undefined
allow_squash_merge?: boolean | undefined
allow_merge_commit?: boolean | undefined
allow_rebase_merge?: boolean | undefined
allow_auto_merge?: boolean | undefined
allow_update_branch?: boolean | undefined
delete_branch_on_merge?: boolean | undefined
pull_request_creation_policy?: string | undefined
full_name?: string | undefined
fork?: boolean | undefined
}
interface BranchProtectionPayload {
required_signatures?: { enabled?: boolean | undefined } | undefined
required_pull_request_reviews?:
| {
required_approving_review_count?: number | undefined
require_code_owner_reviews?: boolean | undefined
dismiss_stale_reviews?: boolean | undefined
}
| undefined
allow_force_pushes?: { enabled?: boolean | undefined } | undefined
allow_deletions?: { enabled?: boolean | undefined } | undefined
enforce_admins?: { enabled?: boolean | undefined } | undefined
}
/**
* GitHub custom-property values for the repo, shaped as the API returns: an
* array of `{ property_name, value }` pairs. We normalize to `Record<string,
* string | null>` at read time.
*
* Recognized fleet properties:
*
* - `disable-github-actions-security` ('true' | 'false') When 'true', the fleet's
* branch-protection-must-require-signed- commits rule downgrades from error →
* warn. Rationale: the shared socket-registry setup/install action IS the
* security gate; per-repo branch protection is belt-and-suspenders.
* - `doesnt-touch-customers` ('true' | 'false') Public repos default 'false'
* (they DO touch customers; full fleet rules apply). Private repos not
* published to npm can set 'true' to opt out of customer-facing rules.
* - `temporarily-doesnt-touch-customers` ('true' | 'false') Escape hatch for
* repos mid-remediation. Always downgrades customer-facing rules to warn.
* Should be removed once the remediation lands.
*/
interface CustomPropertyValue {
property_name?: string | undefined
value?: string | null | undefined
}
type Severity = 'error' | 'warn'
interface Finding {
rule: string
severity: Severity
current: unknown
expected: unknown
fixUrl: string
fixable: boolean
/**
* PATCH-shaped patch payload to apply when --fix is given.
*/
fixPatch?: Record<string, unknown> | undefined
/**
* Required permission for the PATCH; informational.
*/
fixRequires?: string | undefined
}
interface CacheEntry {
verifiedAt: string
repo: string
pass: boolean
ttl: number
findings: Finding[]
}
// Cache lives at `node_modules/.cache/` — fleet convention for
// build-tool state (vitest, etc.) and the only `.cache/` flavor
// that's auto-ignored everywhere (via pnpm/npm's gitignore + the
// fleet's `**/.cache/` rule). Path constructed once.
// Cache file name mirrors the script name (`lint-github-settings`)
// + the `socket-wheelhouse-` fleet prefix so it doesn't collide with
// any other tool's cache file under node_modules/.cache/.
const CACHE_FILE = path.join(
NODE_MODULES_CACHE_DIR,
'socket-wheelhouse-lint-github-settings.json',
)
// 7 days in ms. Mirrors the fleet's npm catalog soak time
// (minimumReleaseAge: 10080 minutes), which is the same governing
// timeframe for "things we don't need to re-verify constantly."
const TTL_MS = 7 * 24 * 60 * 60 * 1000
interface CliFlags {
fix: boolean
force: boolean
json: boolean
}
function parseFlags(): CliFlags {
const argv = process.argv.slice(2)
return {
fix: argv.includes('--fix'),
force: argv.includes('--force'),
json: argv.includes('--json'),
}
}
/**
* Read a fresh cache entry, or undefined if absent/stale/malformed. Stale is
* decided by `verifiedAt + ttl < now`. Malformed entries (parse error, missing
* fields, wrong repo) are treated as absent — the next run will rewrite them.
*/
function readCache(repo: string): CacheEntry | undefined {
if (!existsSync(CACHE_FILE)) {
return undefined
}
let raw: string
try {
raw = readFileSync(CACHE_FILE, 'utf8')
} catch {
return undefined
}
let entry: CacheEntry
try {
entry = JSON.parse(raw) as CacheEntry
} catch {
return undefined
}
if (entry.repo !== repo) {
return undefined
}
const verifiedAt = Date.parse(entry.verifiedAt)
if (!Number.isFinite(verifiedAt)) {
return undefined
}
if (Date.now() - verifiedAt > (entry.ttl ?? TTL_MS)) {
return undefined
}
return entry
}
function writeCache(entry: CacheEntry): void {
if (!existsSync(NODE_MODULES_CACHE_DIR)) {
mkdirSync(NODE_MODULES_CACHE_DIR, { recursive: true })
}
writeFileSync(CACHE_FILE, JSON.stringify(entry, null, 2) + '\n')
}
/**
* Resolve `<owner>/<repo>` by parsing the `origin` git remote. We deliberately
* use `origin` instead of `gh repo view` because in a fork checkout (e.g.
* socket-packageurl-js, a fork of package-url/packageurl-js), `gh repo view`
* returns the UPSTREAM parent, not the SocketDev fork. The audit needs to
* inspect the SocketDev fork's settings, not upstream's. The git remote is the
* source of truth for "which repo does this checkout push to."
*/
function resolveRepo(): string | undefined {
const remote = spawnSync('git', ['config', '--get', 'remote.origin.url'], {
cwd: REPO_ROOT,
})
if (remote.status !== 0) {
return undefined
}
const url = String(remote.stdout).trim()
// Match `git@github.com:owner/repo[.git]` or
// `https://github.com/owner/repo[.git]`.
const m = /github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/.exec(url)
if (!m) {
return undefined
}
return `${m[1]}/${m[2]}`
}
/**
* Thin wrapper around `gh api`. Returns JSON-parsed body on success or
* undefined on any error. The caller decides whether undefined is an
* audit-failing condition or a soft skip.
*/
function ghApi<T>(
endpoint: string,
method: 'GET' | 'PATCH' = 'GET',
body?: Record<string, unknown>,
): T | undefined {
const args = ['api', endpoint]
if (method !== 'GET') {
args.push('-X', method)
}
if (body) {
for (const [k, v] of Object.entries(body)) {
// gh api uses -F for raw JSON values (bool/null), -f for strings.
const isRaw =
typeof v === 'boolean' ||
typeof v === 'number' ||
v === null ||
Array.isArray(v) ||
typeof v === 'object'
const flag = isRaw ? '-F' : '-f'
args.push(flag, `${k}=${typeof v === 'string' ? v : JSON.stringify(v)}`)
}
}
const r = spawnSync('gh', args, {})
if (r.status !== 0) {
if (process.env['DEBUG']) {
process.stderr.write(`gh ${args.join(' ')} failed: ${r.stderr}\n`)
}
return undefined
}
if (!String(r.stdout).trim()) {
return undefined as unknown as T
}
try {
return JSON.parse(String(r.stdout)) as T
} catch {
return undefined
}
}
/**
* Required GitHub Apps. We can't list installations directly without
* `admin:org` scope, so we infer presence from recent check-run activity on
* main HEAD. An app that's installed but inactive on main may false-negative;
* for the fleet's hot repos this is rare.
*
* Alphabetical order.
*/
const REQUIRED_APP_SLUGS = [
'cursor',
'socket-security',
'socket-trufflehog',
] as const
interface CheckSuitesPayload {
check_suites?:
| Array<{
app?: { slug?: string | undefined } | undefined
}>
| undefined
}
/**
* Probe app presence by listing check-SUITES (not check-runs) on recent
* commits. Why suites and not runs: - Check-runs are only created when an app
* posts a finding. Apps like socket-trufflehog that only report on
* secrets-found don't post check-runs on clean commits — listing check-runs
* would false-negative. - Check-suites are created whenever an app receives the
* commit webhook, regardless of whether it ultimately posted a run. This is the
* broader signal — "did this app see the event."
*
* Walks the most recent 10 commits on the repo's default branch (resolved at
* call time so forks with `main` work the same as `master`-only legacy repos).
* Returns the union of app slugs observed.
*/
/**
* Load the repo's custom-property values. Returns `{ <name>: <value or null>
* }`. Empty object when the API isn't available or the call fails — equivalent
* to "no opt-outs."
*/
function loadCustomProperties(repo: string): Record<string, string | null> {
const props = ghApi<CustomPropertyValue[]>(`repos/${repo}/properties/values`)
if (!Array.isArray(props)) {
return {}
}
const out: Record<string, string | null> = {}
for (let i = 0, { length } = props; i < length; i += 1) {
const p = props[i]!
if (typeof p.property_name === 'string') {
if (p.value === null || typeof p.value === 'string') {
out[p.property_name] = p.value
}
}
}
return out
}
/**
* Read the declared GitHub apps from this checkout's
* `.config/socket-wheelhouse.json` (the fleet-config canon — sibling of
* `claude`, `workspace`, `hooks` blocks). Schema:
*
* { "github": { "apps": ["cursor", "socket-security", "socket-trufflehog"] } }
*
* Used for apps whose installation can't be reliably inferred from check-suites
* — socket-trufflehog being the canonical example (it only posts a check-suite
* when a secret is found, so a clean repo with the app installed would
* false-negative under check-suites detection alone).
*
* Audit treats apps listed here as installed (trust the manifest). The
* maintainer's signed statement IS the install record — trust +
* verify-once-via-eyeballs > unreliable automation.
*/
function readDeclaredApps(): Set<string> {
const declared = new Set<string>()
const loaded = loadSocketWheelhouseConfig(REPO_ROOT)
if (!loaded) {
return declared
}
const github = loaded.value['github']
if (typeof github !== 'object' || github === null) {
return declared
}
const apps = (github as Record<string, unknown>)['apps']
if (Array.isArray(apps)) {
for (let i = 0, { length } = apps; i < length; i += 1) {
const a = apps[i]!
if (typeof a === 'string') {
declared.add(a)
}
}
}
return declared
}
function detectInstalledApps(repo: string, defaultBranch: string): Set<string> {
const seen = new Set<string>()
// List of commits, not a single commit — `/commits` (plural) with
// `sha` query for the branch ref. The singular `/commits/{ref}`
// endpoint returns ONE commit, which is the bug shape this fixes.
const commits = ghApi<Array<{ sha?: string | undefined }>>(
`repos/${repo}/commits?sha=${encodeURIComponent(defaultBranch)}&per_page=10`,
)
for (const c of commits ?? []) {
if (!c.sha) {
continue
}
const suites = ghApi<CheckSuitesPayload>(
`repos/${repo}/commits/${c.sha}/check-suites?per_page=100`,
)
for (const s of suites?.check_suites ?? []) {
if (s.app?.slug) {
seen.add(s.app.slug)
}
}
if (seen.size >= REQUIRED_APP_SLUGS.length) {
break
}
}
return seen
}
interface WorkflowsPayload {
workflows?:
| Array<{
name?: string | undefined
path?: string | undefined
state?: string | undefined
}>
| undefined
}
/**
* Names of canonical shared workflows hosted in socket-registry. When a fleet
* repo has a local workflow file whose path basename matches one of these AND
* the workflow body doesn't `uses:` the shared variant AND doesn't carry the
* explicit opt-out marker, that's drift.
*
* Two exemption shapes:
*
* 1. `_local-not-for-reuse-*` filename prefix — the socket-registry convention for
* local triggers that consume a shared workflow. The file IS the right
* shape.
* 2. `# socket-wheelhouse-shadow-allow: <reason>` header line — maintainer's
* explicit, audit-able commitment that the local workflow inlines logic by
* design (e.g. socket-cli's provenance.yml does CLI-specific multi-package
* release orchestration that doesn't fit the generic shared shape). The
* comment text serves as the documented reason.
*/
const SHARED_WORKFLOW_BASENAMES = [
'build.yml',
'install.yml',
'lint.yml',
'provenance.yml',
'release.yml',
'setup.yml',
'test.yml',
] as const
function detectLocalShadows(
repo: string,
): Array<{ basename: string; localPath: string }> {
const out: Array<{ basename: string; localPath: string }> = []
const wf = ghApi<WorkflowsPayload>(
`repos/${repo}/actions/workflows?per_page=100`,
)
if (!wf?.workflows) {
return out
}
for (const w of wf.workflows) {
if (!w.path || !w.path.startsWith('.github/workflows/')) {
continue
}
const basename = w.path.slice('.github/workflows/'.length)
if (basename.startsWith('_local-not-for-reuse-')) {
continue
}
if (
!SHARED_WORKFLOW_BASENAMES.includes(
basename as (typeof SHARED_WORKFLOW_BASENAMES)[number],
)
) {
continue
}
const r = spawnSync('gh', ['api', `repos/${repo}/contents/${w.path}`], {
cwd: REPO_ROOT,
})
if (r.status !== 0) {
continue
}
let bodyRaw: string
try {
const obj = JSON.parse(String(r.stdout)) as {
content?: string | undefined
encoding?: string | undefined
}
if (obj.encoding !== 'base64' || !obj.content) {
continue
}
bodyRaw = Buffer.from(obj.content, 'base64').toString('utf8')
} catch {
continue
}
// Exemption 1: delegates to the shared workflow via `uses:`.
if (
/uses:\s*SocketDev\/socket-registry\/\.github\/workflows\//.test(bodyRaw)
) {
continue
}
// Exemption 2: explicit opt-out comment. Single unified fleet
// marker `socket-bypass: <name>` (one prefix for hooks, custom
// lints, audits — fewer prefixes to remember).
// # socket-bypass: workflow-shadow -- <reason>
// Free-text reason after `--` is encouraged but not parsed;
// maintainer accountability via git blame.
if (/^#\s*socket-bypass:\s*workflow-shadow\b/m.test(bodyRaw)) {
continue
}
out.push({ basename, localPath: w.path })
}
return out
}
/**
* Canonical fleet config. Each rule names the API field, expected value, and
* the fix URL. `fixPatch` is the body to send to PATCH /repos/{owner}/{repo}
* when --fix is given (undefined = manual fix required, no API endpoint yet).
*/
/**
* Custom-property opt-out knobs that downgrade specific rules from 'error' to
* 'warn'. Reading the property values is one API call per audit (see
* `loadCustomProperties`).
*
* Why warn-not-skip: a maintainer marking a repo
* `temporarily-doesnt-touch-customers: true` should still see a reminder of
* what's deferred — silencing the finding entirely would mean the eventual lift
* forgets the reminder existed. Warn = visible-but-not-CI-blocking.
*/
function severityOverride(
ruleKey: string,
props: Record<string, string | null>,
): Severity {
const disableGhAS = props['disable-github-actions-security'] === 'true'
const doesntTouchCustomers = props['doesnt-touch-customers'] === 'true'
const tempDoesntTouchCustomers =
props['temporarily-doesnt-touch-customers'] === 'true'
// The shared socket-registry setup/install IS the security gate;
// per-repo branch protection is belt-and-suspenders. When the
// maintainer has explicitly opted out of redundant GH Actions
// security, downgrade branch-protection findings to warn.
if (
disableGhAS &&
(ruleKey === 'branch-protection-allow-deletions' ||
ruleKey === 'branch-protection-allow-force-pushes' ||
ruleKey === 'branch-protection-dismiss-stale-reviews' ||
ruleKey === 'branch-protection-enforce-admins' ||
ruleKey === 'branch-protection-exists' ||
ruleKey === 'branch-protection-required-pr-reviews' ||
ruleKey === 'branch-protection-required-signatures')
) {
return 'warn'
}
// Customer-facing rules: only enforce on repos that DO touch
// customers. Private/unpublished or in-remediation repos get
// warnings instead of errors so the maintainer sees the reminder
// without CI red.
const customerFacingRules = new Set([
'has_discussions must be false',
'has_projects must be false',
'has_wiki must be false',
'pull_request_creation_policy must be collaborators_only',
])
if (
(doesntTouchCustomers || tempDoesntTouchCustomers) &&
customerFacingRules.has(ruleKey)
) {
return 'warn'
}
return 'error'
}
function evaluate(
repo: string,
apiRepo: RepoApiPayload,
apiProtection: BranchProtectionPayload | undefined,
installedApps: Set<string>,
localShadows: ReadonlyArray<{ basename: string; localPath: string }>,
customProps: Record<string, string | null>,
): Finding[] {
const findings: Finding[] = []
const settingsUrl = `https://github.com/${repo}/settings`
const branchesUrl = `https://github.com/${repo}/settings/branches`
const check = (
rule: string,
current: unknown,
expected: unknown,
fixUrl: string,
fixPatch: Record<string, unknown> | undefined,
): void => {
if (current === expected) {
return
}
findings.push({
rule,
severity: severityOverride(rule, customProps),
current,
expected,
fixUrl,
fixable: fixPatch !== undefined,
...(fixPatch !== undefined
? { fixPatch, fixRequires: 'repo:admin' }
: {}),
})
}
check(
'default_branch must be main',
apiRepo.default_branch,
'main',
branchesUrl,
// No PATCH for default_branch via /repos/{owner}/{repo} — need to
// rename the branch first via /repos/{owner}/{repo}/rename-branch
// and then set it. Manual.
undefined,
)
check(
'has_wiki must be false',
apiRepo.has_wiki,
false,
`${settingsUrl}#features`,
{ has_wiki: false },
)
check(
'has_discussions must be false',
apiRepo.has_discussions,
false,
`${settingsUrl}#features`,
{ has_discussions: false },
)
check(
'has_projects must be false',
apiRepo.has_projects,
false,
`${settingsUrl}#features`,
{ has_projects: false },
)
// Note: `allow_forking` is intentionally NOT checked. The actual
// "no outside-contributor PRs" gate is `pull_request_creation_
// policy: collaborators_only` (checked below). Letting people fork
// for read access / personal-use is the open-source default and
// doesn't bypass PR review.
check(
'allow_squash_merge must be true',
apiRepo.allow_squash_merge,
true,
`${settingsUrl}#pull-requests`,
{ allow_squash_merge: true },
)
check(
'allow_merge_commit must be false',
apiRepo.allow_merge_commit,
false,
`${settingsUrl}#pull-requests`,
{ allow_merge_commit: false },
)
check(
'allow_rebase_merge must be false',
apiRepo.allow_rebase_merge,
false,
`${settingsUrl}#pull-requests`,
{ allow_rebase_merge: false },
)
check(
'allow_auto_merge must be true',
apiRepo.allow_auto_merge,
true,
`${settingsUrl}#pull-requests`,
{ allow_auto_merge: true },
)
check(
'allow_update_branch must be true',
apiRepo.allow_update_branch,
true,
`${settingsUrl}#pull-requests`,
{ allow_update_branch: true },
)
check(
'delete_branch_on_merge must be true',
apiRepo.delete_branch_on_merge,
true,
`${settingsUrl}#pull-requests`,
{ delete_branch_on_merge: true },
)
check(
'pull_request_creation_policy must be collaborators_only',
apiRepo.pull_request_creation_policy,
'collaborators_only',
`${settingsUrl}#pull-requests`,
{ pull_request_creation_policy: 'collaborators_only' },
)
// Branch protection on main — signed commits.
if (!apiProtection) {
findings.push({
rule: 'main branch protection must exist',
severity: severityOverride('branch-protection-exists', customProps),
current: undefined,
expected: '{ required_signatures: { enabled: true } }',
fixUrl: branchesUrl,
fixable: false,
})
} else {
// Required signatures.
if (apiProtection.required_signatures?.enabled !== true) {
findings.push({
rule: 'main branch protection: required_signatures must be enabled',
severity: severityOverride(
'branch-protection-required-signatures',
customProps,
),
current: apiProtection.required_signatures?.enabled ?? false,
expected: true,
fixUrl: branchesUrl,
// PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures
// is the endpoint; this script's --fix doesn't auto-apply it
// because rewriting branch protection rules can clobber custom
// status-check requirements set by the maintainer. Manual.
fixable: false,
})
}
// Required PR reviews. Direct pushes to main are forbidden under
// the fleet's standard policy. At least 1 approving review,
// dismiss stale reviews on new pushes. Code-owner enforcement
// is opt-in per repo (some repos don't have a CODEOWNERS file).
const prReviews = apiProtection.required_pull_request_reviews
if (!prReviews) {
findings.push({
rule: 'main branch protection: required_pull_request_reviews must be enabled',
severity: severityOverride(
'branch-protection-required-pr-reviews',
customProps,
),
current: undefined,
expected:
'{ required_approving_review_count: 1, dismiss_stale_reviews: true }',
fixUrl: branchesUrl,
fixable: false,
})
} else {
if ((prReviews.required_approving_review_count ?? 0) < 1) {
findings.push({
rule: 'main branch protection: required_approving_review_count must be ≥ 1',
severity: severityOverride(
'branch-protection-required-pr-reviews',
customProps,
),
current: prReviews.required_approving_review_count ?? 0,
expected: '≥ 1',
fixUrl: branchesUrl,
fixable: false,
})
}
if (prReviews.dismiss_stale_reviews !== true) {
findings.push({
rule: 'main branch protection: dismiss_stale_reviews must be enabled',
severity: severityOverride(
'branch-protection-dismiss-stale-reviews',
customProps,
),
current: prReviews.dismiss_stale_reviews ?? false,
expected: true,
fixUrl: branchesUrl,
fixable: false,
})
}
}
// Force pushes — must be disabled. A force push to main is the
// recovery-from-bad-state pattern that also enables stolen-token
// attacks (rewrite history, push back).
if (apiProtection.allow_force_pushes?.enabled === true) {
findings.push({
rule: 'main branch protection: allow_force_pushes must be disabled',
severity: severityOverride(
'branch-protection-allow-force-pushes',
customProps,
),
current: true,
expected: false,
fixUrl: branchesUrl,
fixable: false,
})
}
// Branch deletion — must be disabled. The default branch shouldn't
// be deletable via the API (separate concern from regular
// branch cleanup).
if (apiProtection.allow_deletions?.enabled === true) {
findings.push({
rule: 'main branch protection: allow_deletions must be disabled',
severity: severityOverride(
'branch-protection-allow-deletions',
customProps,
),
current: true,
expected: false,
fixUrl: branchesUrl,
fixable: false,
})
}
// Enforce admins — must be enabled. Without this, repo admins
// can bypass every other branch-protection rule. The whole
// point of branch protection is to apply uniformly; admin
// bypass undermines it.
if (apiProtection.enforce_admins?.enabled !== true) {
findings.push({
rule: 'main branch protection: enforce_admins must be enabled',
severity: severityOverride(
'branch-protection-enforce-admins',
customProps,
),
current: apiProtection.enforce_admins?.enabled ?? false,
expected: true,
fixUrl: branchesUrl,
fixable: false,
})
}
}
// Required apps. Each missing app gets one finding with the install URL.
for (let i = 0, { length } = REQUIRED_APP_SLUGS; i < length; i += 1) {
const slug = REQUIRED_APP_SLUGS[i]!
if (!installedApps.has(slug)) {
findings.push({
rule: `GitHub App must be installed: ${slug}`,
// App findings stay 'error' regardless of custom properties —
// app installation is universal. (Could be made overridable
// per-property if a use case emerges.)
severity: 'error',
current:
'not detected on recent check-suites or declared in .github/required-apps.yml',
expected: 'installed + declared',
fixUrl: `https://github.com/apps/${slug}`,
fixable: false,
})
}
}
// Local shadows of shared workflows. Either delete the local file
// (and `uses:` the shared one), or add the explicit opt-out header
// `# socket-wheelhouse-shadow-allow: <reason>` documenting why the
// local version is intentional.
for (let i = 0, { length } = localShadows; i < length; i += 1) {
const shadow = localShadows[i]!
findings.push({
rule: `Local workflow shadows a shared one: ${shadow.basename}`,
severity: 'error',
current: shadow.localPath,
expected:
`uses: SocketDev/socket-registry/.github/workflows/${shadow.basename}@<sha> ` +
`OR add a header comment '# socket-bypass: workflow-shadow -- <reason>' ` +
`to document why this local workflow is intentional`,
fixUrl: `https://github.com/${repo}/blob/${apiRepo.default_branch ?? 'main'}/${shadow.localPath}`,
fixable: false,
})
}
return findings
}
function applyFixes(repo: string, findings: readonly Finding[]): number {
const patchable = findings.filter(f => f.fixable && f.fixPatch)
if (patchable.length === 0) {
return 0
}
// Merge all PATCH bodies into one call — /repos/{owner}/{repo}
// accepts arbitrary subsets of settings.
const patch: Record<string, unknown> = {}
for (let i = 0, { length } = patchable; i < length; i += 1) {
const f = patchable[i]!
Object.assign(patch, f.fixPatch)
}
process.stdout.write(
`\n🔧 Applying ${patchable.length} fixes via PATCH /repos/${repo}:\n`,
)
for (const [k, v] of Object.entries(patch)) {
process.stdout.write(` ${k} = ${JSON.stringify(v)}\n`)
}
const result = ghApi(`repos/${repo}`, 'PATCH', patch)
if (!result) {
process.stderr.write(
'::error::PATCH failed. Token may lack `repo:admin` permission.\n',
)
return 0
}
return patchable.length
}
function printReport(
findings: readonly Finding[],
repo: string,
json: boolean,
): void {
if (json) {
process.stdout.write(JSON.stringify({ repo, findings }, null, 2) + '\n')
return
}
if (findings.length === 0) {
process.stdout.write(`✓ GitHub settings audit passed for ${repo}.\n`)
return
}
const errors = findings.filter(f => f.severity === 'error')
const warns = findings.filter(f => f.severity === 'warn')
process.stdout.write(
`\n${repo}: ${errors.length} error(s), ${warns.length} warning(s)\n\n`,
)
// Errors first, then warnings — operator should fix errors before
// worrying about warnings.
for (const f of [...errors, ...warns]) {
const marker = f.severity === 'error' ? '✗' : '⚠'
process.stdout.write(` ${marker} [${f.severity}] ${f.rule}\n`)
process.stdout.write(` current: ${JSON.stringify(f.current)}\n`)
process.stdout.write(` expected: ${JSON.stringify(f.expected)}\n`)
process.stdout.write(` fix: ${f.fixUrl}\n`)
if (f.fixable) {
process.stdout.write(` auto-fix: --fix (requires repo:admin)\n`)
}
process.stdout.write('\n')
}
// Manual-verify items — always print.
const settingsUrl = `https://github.com/${repo}/settings`
process.stdout.write('Manual-verify (no REST API; check via UI):\n')
process.stdout.write(
` • Commit comments must be disabled: ${settingsUrl} → General → Commits\n`,
)
process.stdout.write(
` • Release immutability enabled: ${settingsUrl} → General → Releases\n`,
)
process.stdout.write(
` • Sponsorships button off: ${settingsUrl} → General → Features\n`,
)
process.stdout.write(
` • Auto-close issues with merged linked PRs ON: ${settingsUrl} → General → Pull Requests\n`,
)
process.stdout.write(
` • Single-push branch+tag update limit = 5: ${settingsUrl} → General → Pushes\n`,
)
process.stdout.write(
` • Required Actions secrets present (ANTHROPIC_API_KEY, SOCKET_API_TOKEN): ${settingsUrl}/secrets/actions\n`,
)
}
function main(): number {
// CI bypass — settings audits are local-run only. See header comment.
if (process.env['CI'] === 'true') {
process.stdout.write(
'CI=true detected; skipping GitHub settings audit (local-run only).\n',
)
return 0
}
const flags = parseFlags()
const repo = resolveRepo()
if (!repo) {
process.stderr.write(
'::error::Could not resolve <owner>/<repo>. Run from inside a git checkout with a github.com remote.\n',
)
return 1
}
// Cache hit shortcut (unless --force or --fix).
if (!flags.force && !flags.fix) {
const cached = readCache(repo)
if (cached?.pass) {
const ageHours = Math.round(
(Date.now() - Date.parse(cached.verifiedAt)) / 3600_000,
)
process.stdout.write(
`✓ Cache fresh (${ageHours}h old, < 7d TTL). Use --force to re-check.\n`,
)
return 0
}
}
const apiRepo = ghApi<RepoApiPayload>(`repos/${repo}`)
if (!apiRepo) {
process.stderr.write(
`::error::Could not fetch repos/${repo}. Check gh auth status / token permissions.\n`,
)
return 1
}
// Branch protection lookup must use the repo's actual default
// branch — a fork on a legacy `master` default would never have
// protection on `main`. Default to 'main' when the API doesn't
// expose it (rare).
const defaultBranch = apiRepo.default_branch ?? 'main'