The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import * as Repos from "@distilled.cloud/github/repos"; |
| 2 | import { isResolved } from "alchemy/Diff"; |
| 3 | import * as Provider from "alchemy/Provider"; |
| 4 | import { Resource } from "alchemy/Resource"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Stream from "effect/Stream"; |
| 7 | import { withBaseUrl, gitHubBaseUrlChanged } from "./BaseUrl.ts"; |
| 8 | import type * as GitHub from "./Providers.ts"; |
| 9 | |
| 10 | export interface BranchProtectionProps { |
| 11 | /** |
| 12 | * Repository owner (user or organization). |
| 13 | */ |
| 14 | owner: string; |
| 15 | |
| 16 | /** |
| 17 | * Repository name. |
| 18 | */ |
| 19 | repository: string; |
| 20 | |
| 21 | /** |
| 22 | * Name of the branch to protect (e.g. `main`). The branch is the rule's |
| 23 | * identity — changing it replaces the protection. The branch must exist. |
| 24 | */ |
| 25 | branch: string; |
| 26 | |
| 27 | /** |
| 28 | * Require status checks to pass before merging. Omit to disable. |
| 29 | */ |
| 30 | requiredStatusChecks?: { |
| 31 | /** |
| 32 | * Require branches to be up to date with the base branch before merging. |
| 33 | * @default false |
| 34 | */ |
| 35 | strict?: boolean; |
| 36 | |
| 37 | /** |
| 38 | * Status check contexts that must pass. Prefer `checks` for control over |
| 39 | * which GitHub App must report the check. |
| 40 | */ |
| 41 | contexts?: string[]; |
| 42 | |
| 43 | /** |
| 44 | * Status checks that must pass, optionally pinned to the GitHub App that |
| 45 | * must report them. When this is set, the update sends `checks` and |
| 46 | * omits `contexts`. GitHub rejects a request that includes both. |
| 47 | */ |
| 48 | checks?: { |
| 49 | /** |
| 50 | * Name of the required check. |
| 51 | */ |
| 52 | context: string; |
| 53 | |
| 54 | /** |
| 55 | * ID of the GitHub App that must provide this check. Omit to accept the |
| 56 | * app that most recently reported it; pass `-1` to accept any app. |
| 57 | */ |
| 58 | appId?: number; |
| 59 | }[]; |
| 60 | }; |
| 61 | |
| 62 | /** |
| 63 | * Require pull request reviews before merging. Omit to disable. |
| 64 | */ |
| 65 | requiredPullRequestReviews?: { |
| 66 | /** |
| 67 | * Dismiss approving reviews when a new commit is pushed. |
| 68 | * @default false |
| 69 | */ |
| 70 | dismissStaleReviews?: boolean; |
| 71 | |
| 72 | /** |
| 73 | * Block merging until code owners have reviewed. |
| 74 | * @default false |
| 75 | */ |
| 76 | requireCodeOwnerReviews?: boolean; |
| 77 | |
| 78 | /** |
| 79 | * Number of approving reviews required (0–6). |
| 80 | * @default 0 |
| 81 | */ |
| 82 | requiredApprovingReviewCount?: number; |
| 83 | |
| 84 | /** |
| 85 | * Require the most recent push to be approved by someone other than the |
| 86 | * pusher. |
| 87 | * @default false |
| 88 | */ |
| 89 | requireLastPushApproval?: boolean; |
| 90 | |
| 91 | /** |
| 92 | * Who may dismiss pull request reviews. Only available on |
| 93 | * organization-owned repositories; omit for personal repositories. |
| 94 | */ |
| 95 | dismissalRestrictions?: { |
| 96 | /** |
| 97 | * User logins with dismissal access. |
| 98 | */ |
| 99 | users?: string[]; |
| 100 | |
| 101 | /** |
| 102 | * Team slugs with dismissal access. |
| 103 | */ |
| 104 | teams?: string[]; |
| 105 | |
| 106 | /** |
| 107 | * App slugs with dismissal access. |
| 108 | */ |
| 109 | apps?: string[]; |
| 110 | }; |
| 111 | |
| 112 | /** |
| 113 | * Who may bypass pull request requirements. |
| 114 | */ |
| 115 | bypassPullRequestAllowances?: { |
| 116 | /** |
| 117 | * User logins allowed to bypass. |
| 118 | */ |
| 119 | users?: string[]; |
| 120 | |
| 121 | /** |
| 122 | * Team slugs allowed to bypass. |
| 123 | */ |
| 124 | teams?: string[]; |
| 125 | |
| 126 | /** |
| 127 | * App slugs allowed to bypass. |
| 128 | */ |
| 129 | apps?: string[]; |
| 130 | }; |
| 131 | }; |
| 132 | |
| 133 | /** |
| 134 | * Restrict who can push to the branch. Only available on |
| 135 | * organization-owned repositories. Omit to disable. |
| 136 | */ |
| 137 | restrictions?: { |
| 138 | /** |
| 139 | * User logins with push access. |
| 140 | */ |
| 141 | users?: string[]; |
| 142 | |
| 143 | /** |
| 144 | * Team slugs with push access. |
| 145 | */ |
| 146 | teams?: string[]; |
| 147 | |
| 148 | /** |
| 149 | * App slugs with push access. |
| 150 | */ |
| 151 | apps?: string[]; |
| 152 | }; |
| 153 | |
| 154 | /** |
| 155 | * Enforce all configured restrictions for repository administrators. |
| 156 | * @default false |
| 157 | */ |
| 158 | enforceAdmins?: boolean; |
| 159 | |
| 160 | /** |
| 161 | * Require signed commits on the branch. |
| 162 | * @default false |
| 163 | */ |
| 164 | requiredSignatures?: boolean; |
| 165 | |
| 166 | /** |
| 167 | * Require a linear commit history (no merge commits). The repository must |
| 168 | * allow squash or rebase merging. |
| 169 | * @default false |
| 170 | */ |
| 171 | requiredLinearHistory?: boolean; |
| 172 | |
| 173 | /** |
| 174 | * Permit force pushes by anyone with write access. |
| 175 | * @default false |
| 176 | */ |
| 177 | allowForcePushes?: boolean; |
| 178 | |
| 179 | /** |
| 180 | * Permit deletion of the branch by anyone with write access. |
| 181 | * @default false |
| 182 | */ |
| 183 | allowDeletions?: boolean; |
| 184 | |
| 185 | /** |
| 186 | * When `restrictions` is set, also block pushes that create new branches |
| 187 | * unless the pusher is allowed by the restrictions. |
| 188 | * @default false |
| 189 | */ |
| 190 | blockCreations?: boolean; |
| 191 | |
| 192 | /** |
| 193 | * Require all pull request conversations to be resolved before merging. |
| 194 | * @default false |
| 195 | */ |
| 196 | requiredConversationResolution?: boolean; |
| 197 | |
| 198 | /** |
| 199 | * Make the branch read-only. |
| 200 | * @default false |
| 201 | */ |
| 202 | lockBranch?: boolean; |
| 203 | |
| 204 | /** |
| 205 | * Allow fork syncing (pulling upstream changes) while the branch is locked. |
| 206 | * @default false |
| 207 | */ |
| 208 | allowForkSyncing?: boolean; |
| 209 | |
| 210 | /** |
| 211 | * Override the GitHub host or API base URL for this resource only (e.g. |
| 212 | * `github.example.com` for GitHub Enterprise). Falls back to |
| 213 | * `GitHub.providers({ baseUrl })`, then to the host resolved by the auth |
| 214 | * provider. Changing it replaces the resource — the same branch on a |
| 215 | * different GitHub instance is a different physical resource. |
| 216 | */ |
| 217 | baseUrl?: string; |
| 218 | } |
| 219 | |
| 220 | export interface BranchProtection extends Resource< |
| 221 | "GitHub.BranchProtection", |
| 222 | BranchProtectionProps, |
| 223 | { |
| 224 | /** |
| 225 | * API URL of the branch protection rule. |
| 226 | */ |
| 227 | url: string; |
| 228 | |
| 229 | /** |
| 230 | * The protected branch name. |
| 231 | */ |
| 232 | branch: string; |
| 233 | |
| 234 | /** |
| 235 | * Whether restrictions are enforced for administrators. |
| 236 | */ |
| 237 | enforceAdmins: boolean; |
| 238 | |
| 239 | /** |
| 240 | * Whether signed commits are required. |
| 241 | */ |
| 242 | requiredSignatures: boolean; |
| 243 | |
| 244 | /** |
| 245 | * Whether a linear history is required. |
| 246 | */ |
| 247 | requiredLinearHistory: boolean; |
| 248 | |
| 249 | /** |
| 250 | * Whether force pushes are allowed. |
| 251 | */ |
| 252 | allowForcePushes: boolean; |
| 253 | |
| 254 | /** |
| 255 | * Whether branch deletion is allowed. |
| 256 | */ |
| 257 | allowDeletions: boolean; |
| 258 | |
| 259 | /** |
| 260 | * Whether conversation resolution is required before merging. |
| 261 | */ |
| 262 | requiredConversationResolution: boolean; |
| 263 | |
| 264 | /** |
| 265 | * Whether the branch is locked (read-only). |
| 266 | */ |
| 267 | lockBranch: boolean; |
| 268 | }, |
| 269 | never, |
| 270 | GitHub.Providers |
| 271 | > {} |
| 272 | |
| 273 | /** |
| 274 | * A GitHub branch protection rule. |
| 275 | * |
| 276 | * `BranchProtection` manages the classic branch protection settings on a |
| 277 | * single branch: required status checks, required pull request reviews, |
| 278 | * push restrictions, admin enforcement, signed commits, linear history, and |
| 279 | * the force-push / deletion / lock toggles. Pair it with `GitHub.Repository` |
| 280 | * to protect the default branch of a repository provisioned in the same |
| 281 | * stack. |
| 282 | * |
| 283 | * Branch protection is available on public repositories on every plan; |
| 284 | * private repositories require GitHub Pro, Team, or Enterprise. Push |
| 285 | * restrictions and dismissal restrictions are only available on |
| 286 | * organization-owned repositories. |
| 287 | * |
| 288 | * Authentication is resolved via the GitHub `Credentials` service supplied |
| 289 | * by `GitHub.providers()` (env, stored PAT, `gh` CLI, or OAuth). The token |
| 290 | * needs `repo` scope and admin access to the repository. |
| 291 | * |
| 292 | * ### Protecting a Branch |
| 293 | * **Example:** Require Pull Request Reviews |
| 294 | * ```typescript |
| 295 | * yield* GitHub.BranchProtection("main", { |
| 296 | * owner: "my-org", |
| 297 | * repository: "my-repo", |
| 298 | * branch: "main", |
| 299 | * requiredPullRequestReviews: { |
| 300 | * requiredApprovingReviewCount: 1, |
| 301 | * dismissStaleReviews: true, |
| 302 | * }, |
| 303 | * }); |
| 304 | * ``` |
| 305 | * |
| 306 | * **Example:** Require Status Checks and a Linear History |
| 307 | * ```typescript |
| 308 | * yield* GitHub.BranchProtection("main", { |
| 309 | * owner: "my-org", |
| 310 | * repository: "my-repo", |
| 311 | * branch: "main", |
| 312 | * requiredStatusChecks: { |
| 313 | * strict: true, |
| 314 | * checks: [{ context: "ci" }], |
| 315 | * }, |
| 316 | * requiredLinearHistory: true, |
| 317 | * requiredConversationResolution: true, |
| 318 | * enforceAdmins: true, |
| 319 | * }); |
| 320 | * ``` |
| 321 | * |
| 322 | * ### Protecting a Repository's Default Branch |
| 323 | * **Example:** Protect the Default Branch of a New Repository |
| 324 | * ```typescript |
| 325 | * import * as Output from "alchemy/Output"; |
| 326 | * |
| 327 | * const repo = yield* GitHub.Repository("repo", { |
| 328 | * owner: "my-org", |
| 329 | * name: "my-repo", |
| 330 | * autoInit: true, |
| 331 | * }); |
| 332 | * |
| 333 | * yield* GitHub.BranchProtection("main", { |
| 334 | * owner: "my-org", |
| 335 | * repository: Output.map(repo.fullName, (fullName) => fullName.split("/")[1]!), |
| 336 | * branch: repo.defaultBranch, |
| 337 | * requiredPullRequestReviews: { requiredApprovingReviewCount: 1 }, |
| 338 | * allowForcePushes: false, |
| 339 | * allowDeletions: false, |
| 340 | * }); |
| 341 | * ``` |
| 342 | * |
| 343 | * ### Restricting Pushes |
| 344 | * **Example:** Only a Team May Push |
| 345 | * ```typescript |
| 346 | * yield* GitHub.BranchProtection("release", { |
| 347 | * owner: "my-org", |
| 348 | * repository: "my-repo", |
| 349 | * branch: "release", |
| 350 | * restrictions: { teams: ["release-managers"] }, |
| 351 | * blockCreations: true, |
| 352 | * requiredSignatures: true, |
| 353 | * }); |
| 354 | * ``` |
| 355 | * |
| 356 | * @resource |
| 357 | * @product Repository |
| 358 | */ |
| 359 | export const BranchProtection = Resource<BranchProtection>("GitHub.BranchProtection"); |
| 360 | |
| 361 | /** |
| 362 | * The `GET .../protection` payload. Both the GET and PUT responses share this |
| 363 | * shape for the fields we surface; every nested block is optional because |
| 364 | * GitHub omits disabled aspects entirely. |
| 365 | */ |
| 366 | interface ProtectionPayload { |
| 367 | url?: string; |
| 368 | enforce_admins?: { enabled?: boolean }; |
| 369 | required_signatures?: { enabled?: boolean }; |
| 370 | required_linear_history?: { enabled?: boolean }; |
| 371 | allow_force_pushes?: { enabled?: boolean }; |
| 372 | allow_deletions?: { enabled?: boolean }; |
| 373 | required_conversation_resolution?: { enabled?: boolean }; |
| 374 | lock_branch?: { enabled?: boolean }; |
| 375 | } |
| 376 | |
| 377 | type RequiredStatusChecks = Repos.UpdateBranchProtectionRequest["required_status_checks"]; |
| 378 | |
| 379 | const requiredStatusChecksOf = ( |
| 380 | checks: BranchProtectionProps["requiredStatusChecks"], |
| 381 | ): RequiredStatusChecks => { |
| 382 | // `contexts` or `checks`, never both: GitHub rejects a body with both. |
| 383 | if (checks === undefined) return null; |
| 384 | const strict = checks.strict ?? false; |
| 385 | if (checks.checks === undefined) { |
| 386 | return { strict, contexts: checks.contexts ?? [] }; |
| 387 | } |
| 388 | return { |
| 389 | strict, |
| 390 | checks: checks.checks.map((check) => ({ |
| 391 | context: check.context, |
| 392 | ...(check.appId === undefined ? {} : { app_id: check.appId }), |
| 393 | })), |
| 394 | }; |
| 395 | }; |
| 396 | |
| 397 | const attrsOf = ( |
| 398 | branch: string, |
| 399 | protection: ProtectionPayload, |
| 400 | ): BranchProtection["Attributes"] => ({ |
| 401 | url: protection.url ?? "", |
| 402 | branch, |
| 403 | enforceAdmins: protection.enforce_admins?.enabled ?? false, |
| 404 | requiredSignatures: protection.required_signatures?.enabled ?? false, |
| 405 | requiredLinearHistory: protection.required_linear_history?.enabled ?? false, |
| 406 | allowForcePushes: protection.allow_force_pushes?.enabled ?? false, |
| 407 | allowDeletions: protection.allow_deletions?.enabled ?? false, |
| 408 | requiredConversationResolution: protection.required_conversation_resolution?.enabled ?? false, |
| 409 | lockBranch: protection.lock_branch?.enabled ?? false, |
| 410 | }); |
| 411 | |
| 412 | export const BranchProtectionProvider = () => |
| 413 | Provider.succeed(BranchProtection, { |
| 414 | stables: ["url", "branch"], |
| 415 | |
| 416 | // {owner, repository, branch, host} is the rule's path identity — GitHub |
| 417 | // has no rename, so changing any of them replaces the resource. |
| 418 | diff: Effect.fn(function* ({ news, olds }) { |
| 419 | if (olds === undefined) return; |
| 420 | // Unresolved props may change the path identity and orphan the old rule. |
| 421 | if (!isResolved(news)) return { action: "replace" }; |
| 422 | if ( |
| 423 | news.owner !== olds.owner || |
| 424 | news.repository !== olds.repository || |
| 425 | news.branch !== olds.branch || |
| 426 | (yield* gitHubBaseUrlChanged(olds, news)) |
| 427 | ) { |
| 428 | return { action: "replace" }; |
| 429 | } |
| 430 | }), |
| 431 | |
| 432 | reconcile: Effect.fn( |
| 433 | function* ({ news }) { |
| 434 | const branch = { owner: news.owner, repo: news.repository, branch: news.branch }; |
| 435 | |
| 436 | // Ensure & Sync — the PUT is a full upsert of the rule. Send explicit |
| 437 | // values (or `null`) for every aspect so removed props converge back |
| 438 | // to their defaults rather than being left as-is. |
| 439 | const requiredStatusChecks = requiredStatusChecksOf(news.requiredStatusChecks); |
| 440 | const reviews = news.requiredPullRequestReviews; |
| 441 | const restrictions = news.restrictions; |
| 442 | |
| 443 | yield* Repos.updateBranchProtection({ |
| 444 | ...branch, |
| 445 | required_status_checks: requiredStatusChecks, |
| 446 | enforce_admins: news.enforceAdmins ?? false, |
| 447 | required_pull_request_reviews: |
| 448 | reviews === undefined |
| 449 | ? null |
| 450 | : { |
| 451 | dismiss_stale_reviews: reviews.dismissStaleReviews ?? false, |
| 452 | require_code_owner_reviews: reviews.requireCodeOwnerReviews ?? false, |
| 453 | required_approving_review_count: reviews.requiredApprovingReviewCount ?? 0, |
| 454 | require_last_push_approval: reviews.requireLastPushApproval ?? false, |
| 455 | ...(reviews.dismissalRestrictions === undefined |
| 456 | ? {} |
| 457 | : { |
| 458 | dismissal_restrictions: { |
| 459 | users: reviews.dismissalRestrictions.users ?? [], |
| 460 | teams: reviews.dismissalRestrictions.teams ?? [], |
| 461 | apps: reviews.dismissalRestrictions.apps ?? [], |
| 462 | }, |
| 463 | }), |
| 464 | ...(reviews.bypassPullRequestAllowances === undefined |
| 465 | ? {} |
| 466 | : { |
| 467 | bypass_pull_request_allowances: { |
| 468 | users: reviews.bypassPullRequestAllowances.users ?? [], |
| 469 | teams: reviews.bypassPullRequestAllowances.teams ?? [], |
| 470 | apps: reviews.bypassPullRequestAllowances.apps ?? [], |
| 471 | }, |
| 472 | }), |
| 473 | }, |
| 474 | restrictions: |
| 475 | restrictions === undefined |
| 476 | ? null |
| 477 | : { |
| 478 | users: restrictions.users ?? [], |
| 479 | teams: restrictions.teams ?? [], |
| 480 | apps: restrictions.apps ?? [], |
| 481 | }, |
| 482 | required_linear_history: news.requiredLinearHistory ?? false, |
| 483 | allow_force_pushes: news.allowForcePushes ?? false, |
| 484 | allow_deletions: news.allowDeletions ?? false, |
| 485 | block_creations: news.blockCreations ?? false, |
| 486 | required_conversation_resolution: news.requiredConversationResolution ?? false, |
| 487 | lock_branch: news.lockBranch ?? false, |
| 488 | allow_fork_syncing: news.allowForkSyncing ?? false, |
| 489 | }); |
| 490 | |
| 491 | // Sync — required signatures live behind dedicated endpoints that the |
| 492 | // top-level PUT does not touch. Diff the observed flag against the |
| 493 | // desired one and only call the API on a real change. |
| 494 | const observed: ProtectionPayload = yield* Repos.getBranchProtection(branch); |
| 495 | |
| 496 | const desiredSignatures = news.requiredSignatures ?? false; |
| 497 | const observedSignatures = observed.required_signatures?.enabled ?? false; |
| 498 | if (desiredSignatures !== observedSignatures) { |
| 499 | yield* desiredSignatures |
| 500 | ? Repos.createCommitSignatureProtection(branch) |
| 501 | : Repos.deleteCommitSignatureProtection(branch); |
| 502 | } |
| 503 | |
| 504 | return attrsOf(news.branch, { |
| 505 | ...observed, |
| 506 | required_signatures: { enabled: desiredSignatures }, |
| 507 | }); |
| 508 | }, |
| 509 | (effect, { news }) => effect.pipe(withBaseUrl(news.baseUrl)), |
| 510 | ), |
| 511 | |
| 512 | // Refresh from the live rule. A 404 means either the branch is no longer |
| 513 | // protected or the branch/repository is gone — both are "missing". |
| 514 | read: Effect.fn( |
| 515 | function* ({ olds }) { |
| 516 | return yield* Repos.getBranchProtection({ |
| 517 | owner: olds.owner, |
| 518 | repo: olds.repository, |
| 519 | branch: olds.branch, |
| 520 | }).pipe( |
| 521 | Effect.map((protection) => attrsOf(olds.branch, protection)), |
| 522 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 523 | ); |
| 524 | }, |
| 525 | (effect, { olds }) => effect.pipe(withBaseUrl(olds.baseUrl)), |
| 526 | ), |
| 527 | |
| 528 | // Enumerate every protected branch across the repositories the token can |
| 529 | // see — protection rules are keyed by {owner, repository, branch} with no |
| 530 | // account-wide list endpoint, so walk the repos like the Environment |
| 531 | // provider does and fetch the rule for each protected branch. |
| 532 | list: Effect.fn(function* () { |
| 533 | const repos = yield* Stream.runCollect( |
| 534 | Repos.listForAuthenticatedUser.items({ per_page: 100 }), |
| 535 | ); |
| 536 | const perRepo = yield* Effect.forEach( |
| 537 | repos, |
| 538 | (repo) => { |
| 539 | const scope = { owner: repo.owner.login, repo: repo.name }; |
| 540 | return Stream.runCollect( |
| 541 | Repos.listBranches.items({ ...scope, protected: true, per_page: 100 }), |
| 542 | ).pipe( |
| 543 | Effect.flatMap((branches) => |
| 544 | Effect.forEach(branches, (branch) => |
| 545 | Repos.getBranchProtection({ ...scope, branch: branch.name }).pipe( |
| 546 | Effect.map((protection) => [attrsOf(branch.name, protection)]), |
| 547 | // Protection may be removed between the list and the get, or |
| 548 | // the branch may be governed by a ruleset only. |
| 549 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 550 | ), |
| 551 | ), |
| 552 | ), |
| 553 | Effect.map((rules) => rules.flat()), |
| 554 | // Repos without branch protection support (plan limits) or where |
| 555 | // the token lacks access reject with 403/404 — skip them rather |
| 556 | // than failing the whole enumeration. |
| 557 | Effect.catchTag(["Forbidden", "NotFound"], () => Effect.succeed([])), |
| 558 | ); |
| 559 | }, |
| 560 | { concurrency: 10 }, |
| 561 | ); |
| 562 | return perRepo.flat(); |
| 563 | }), |
| 564 | |
| 565 | delete: Effect.fn( |
| 566 | function* ({ olds }) { |
| 567 | yield* Repos.deleteBranchProtection({ |
| 568 | owner: olds.owner, |
| 569 | repo: olds.repository, |
| 570 | branch: olds.branch, |
| 571 | }).pipe( |
| 572 | // Already unprotected, or the branch/repository is gone. |
| 573 | Effect.catchTag("NotFound", () => Effect.void), |
| 574 | ); |
| 575 | }, |
| 576 | (effect, { olds }) => effect.pipe(withBaseUrl(olds.baseUrl)), |
| 577 | ), |
| 578 | }); |