@davidvornholt/standards 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +7 -5
  2. package/package.json +19 -1
  3. package/src/cli.ts +2 -2
  4. package/src/creds-add-cloudflare-commit.ts +2 -5
  5. package/src/creds-add-github.ts +82 -30
  6. package/src/creds-add-policy.ts +106 -26
  7. package/src/creds-add-preflight.ts +68 -0
  8. package/src/creds-add.ts +29 -20
  9. package/src/creds-args.ts +14 -0
  10. package/src/creds-cloudflare-account.ts +2 -2
  11. package/src/creds-cloudflare-id.ts +10 -0
  12. package/src/creds-cloudflare-zone.ts +40 -0
  13. package/src/creds-commands.ts +34 -11
  14. package/src/creds-github-app-api.ts +132 -0
  15. package/src/creds-github-apps.ts +107 -0
  16. package/src/creds-login-github-manifest.ts +38 -15
  17. package/src/creds-login-github.ts +78 -24
  18. package/src/creds-naming.ts +13 -0
  19. package/src/creds-plan-renew.ts +2 -5
  20. package/src/creds-plan-report.ts +87 -0
  21. package/src/creds-plan-run.ts +2 -11
  22. package/src/creds-plan-types.ts +19 -0
  23. package/src/creds-plan-unmanaged.ts +102 -0
  24. package/src/creds-plan.ts +25 -21
  25. package/src/creds-revoke.ts +162 -0
  26. package/src/creds-sops-value.ts +89 -0
  27. package/src/creds-sops.ts +0 -53
  28. package/src/creds-store-github.ts +121 -0
  29. package/src/creds-store-lock-holder.ts +105 -0
  30. package/src/creds-store-lock-inspection.ts +125 -0
  31. package/src/creds-store-lock-lease.ts +32 -0
  32. package/src/creds-store-lock.ts +28 -51
  33. package/src/creds-store.ts +14 -43
  34. package/src/dev-env-compose.ts +120 -0
  35. package/src/dev-env-destination-duplicates.ts +10 -10
  36. package/src/dev-env-destination-gitignore.ts +22 -0
  37. package/src/dev-env-destination.ts +52 -30
  38. package/src/dev-env-document.ts +19 -6
  39. package/src/dev-env-dotenv.ts +12 -3
  40. package/src/dev-env-reconciliation.ts +170 -0
  41. package/src/dev-env-secrets.ts +41 -0
  42. package/src/dev-env-transaction-recovery.ts +74 -11
  43. package/src/dev-env-transaction.ts +61 -15
  44. package/src/dev-env.ts +115 -63
  45. package/src/github-command-shared.ts +8 -1
  46. package/src/github-live-drift.ts +3 -3
  47. package/src/poller-closing-reference.ts +179 -0
  48. package/src/poller-fix-outcome.ts +9 -0
  49. package/src/poller-fix-publication.ts +5 -12
  50. package/src/poller-fix-run.ts +2 -3
  51. package/src/poller-fix-validation.ts +7 -8
  52. package/src/poller-outcome.ts +4 -1
  53. package/src/poller-protected-paths.ts +1 -25
  54. package/src/poller-protocol.ts +0 -42
  55. package/src/poller-review-publication.ts +2 -8
  56. package/src/poller-review-validation.ts +5 -12
package/README.md CHANGED
@@ -16,28 +16,30 @@ standards github --apply
16
16
  standards creds login github
17
17
  standards creds login cloudflare
18
18
  standards creds add cloudflare --dest ci:ci.cloudflare_workers_token --permissions "Workers Scripts Write"
19
+ standards creds add cloudflare --dest ci:ci.cloudflare_dns_token --zone 1bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb --permissions "DNS Write"
19
20
  standards creds add cloudflare --dest ci:ci.r2_read --bucket assets --s3 --permissions "Workers R2 Storage Bucket Item Read"
20
21
  standards creds add cloudflare --dest ci:ci.eu_r2_read --bucket eu-assets --jurisdiction eu --s3 --permissions "Workers R2 Storage Bucket Item Read"
21
22
  standards creds add github --dest ci:ci.broker_app
22
23
  standards creds plan
23
24
  standards creds apply
25
+ standards creds revoke --token-id <token-id>
24
26
  standards poller --config <path>
25
27
  standards poller --print-units --config <path>
26
28
  ```
27
29
 
28
30
  `dependabot --write` regenerates the composed `.github/dependabot.yml` from the canonical `.github/dependabot.base.yml` and the optional repo-owned `.github/dependabot.local.yml`; `init` and `sync` do the same automatically. `dependabot --check` verifies the generated file still matches its sources, and `doctor`/`check` include the same verification. The overlay is deliberately lean and additive only: new update blocks for repo-specific ecosystems, top-level private registry definitions, and `ignore` or `registries` entries appended by repeating a canonical block's normalized target. Matching blocks cannot add labels, groups, cooldowns, pull-request limits, or other policy. Update blocks for the same ecosystem and target branch must not select intersecting directories after Dependabot's path normalization. A plural `directories` target is expanded as a glob when it contains `*`, `?`, or both `[` and `]`: `*` and bare `**` stay within one path segment, `**/` matches zero or more directory segments, `?` matches one non-separator character, and bracket expressions match character sets or ranges. Singular `directory` values are always literal.
29
31
 
30
- `dev-env` decrypts the SOPS-encrypted `secrets/dev.yaml` — keyed by workspace group and a one-segment kebab-case workspace name (`apps.<name>`, `packages.<name>`), each mapping portable environment variable names to string values — and transactionally writes every declared workspace's `.env.local` with owner-only permissions and a do-not-edit header. Its Bun-specific dotenv codec exactly round-trips every value it accepts without adding helper environment variables; a value the codec cannot encode exactly is gathered as a validation problem instead of being changed silently. Validation gathers all document, containment, destination-type, workspace, and gitignore problems before writing anything. Generation then stages every output in its destination directory and rolls the whole set back if staging or commit fails, preserving prior contents, modes, and absent files; symlink destinations, duplicate resolved destinations, changed parent-directory identities, and symlinked workspace paths are rejected without following the link. Cleanup trouble after a completed commit is reported loudly as a warning rather than falsely reporting generation failure. Parent identities are checked immediately before each path operation; an unavoidable swap in the syscall-sized interval after a check remains outside the non-hostile maintainer threat model. The canonical `justfile` exposes the command as `just dev-env-generate`, and `just dev-refresh` chains a `just secrets edit dev` session into regeneration.
32
+ `dev-env` composes each workspace's dev environment from three layers sharing one shape — keyed by workspace group and a one-segment kebab-case workspace name (`apps.<name>`, `packages.<name>`), each mapping portable environment variable names to string values: the tracked plain `config/dev.yaml`, the SOPS-encrypted `secrets/dev.yaml` (required, decrypted via sops), and the gitignored plain `config/dev.local.yaml`, applied in that order with later layers overriding per key. A key declared in both tracked shared layers is a validation problem — a value is either configuration or a secret — while a local override of either is the file's purpose. Plain layers are optional and may be comment-only; `config/dev.local.yaml` must itself be gitignored because it may override secret values. The command transactionally writes every declared workspace's `.env.local` with owner-only permissions and a do-not-edit header naming the contributing sources. It also discovers direct `apps/*` and `packages/*` directories containing `package.json` and removes a stale `.env.local` only when its first line is that exact header; hand-owned files, edited headers, nested directories, and symlinked paths are left untouched. Writes and removals commit or roll back as one transaction, preserving prior contents, modes, and absent files. The final files and the transaction's actual random `.env.local.standards-*.tmp` and `.env.local.standards-*.bak` paths must all be gitignored before staging starts. Existing consumers must add those two artifact patterns themselves because `.gitignore` is seeded only during `init`; `sync` does not change it. Its Bun-specific dotenv codec exactly round-trips every value it accepts without adding helper environment variables; a value the codec cannot encode exactly is gathered as a validation problem instead of being changed silently. Validation gathers all document, containment, destination-type, workspace, and gitignore problems before writing anything; symlink destinations, duplicate resolved destinations, changed parent-directory identities, and symlinked workspace paths are rejected without following the link. Cleanup trouble after a completed commit is reported loudly as a warning rather than falsely reporting generation failure. Parent identities are checked immediately before each path operation; an unavoidable swap in the syscall-sized interval after a check remains outside the non-hostile maintainer threat model. The canonical `justfile` exposes the command as `just dev-env-generate`, and `just dev-refresh` chains a `just secrets edit dev` session into regeneration.
31
33
 
32
34
  `check` also rejects the raw token formed by `biome-` + `ignore` anywhere in lock-listed canonical files. The intentionally blunt policy keeps synced sources compatible with consumer Biome configurations without invoking Biome or maintaining language-aware comment parsing.
33
35
 
34
- `github --check` compares the live GitHub repository (including the canonical squash-only repository settings, rulesets, and declared labels) against the merged declaration in `.github/settings.json` + `.github/settings.local.json`; `github --apply` converges that declared state. The canonical declaration enables squash while disabling merge commits and rebases, and its default-branch ruleset independently allows only squash. Undeclared live labels remain untouched, while undeclared repository-owned rulesets are removed. `check` runs the same comparison whenever `.github/settings.json` is present, and fails closed: declared state the token cannot see fails the gate with a message naming the token fix instead of passing unverified. The canonical workflow sets `STANDARDS_SKIP_GITHUB_CHECK=true` only in its unprivileged quality step because its isolated `github-settings` job runs the live comparison with the settings-read token; this is a workflow-internal integration seam, not a general way to disable the local gate. The CLI prints an explicit diagnostic whenever that exact value skips either `check`'s live phase or `github --check`; `github --apply` is never skipped. `--apply` re-diffs the PATCH response, so a setting GitHub accepts with HTTP 200 but silently ignores (plan-unavailable features) is a reported failure, not a false success. A repository whose GitHub plan cannot enforce rulesets can declare that in the seam (see `rulesetEnforcement` below); both commands then skip rulesets and plan-gated repository settings, converge the rest, and print an unprotected-branch notice on every run.
36
+ `github --check` compares the live GitHub repository (including the canonical squash-only repository settings, rulesets, and declared labels) against the merged declaration in `.github/settings.json` + `.github/settings.local.json`; `github --apply` converges that declared state. The canonical declaration enables squash while disabling merge commits and rebases, and its default-branch ruleset independently allows only squash. Undeclared live labels remain untouched, while undeclared repository-owned rulesets are removed. `check` runs the same comparison whenever `.github/settings.json` is present, and fails closed: declared state the token cannot see fails the gate with a message naming the token fix instead of passing unverified. The canonical workflow sets `STANDARDS_SKIP_GITHUB_CHECK=true` only in its unprivileged quality step because its isolated `github-settings` job runs the live comparison with its own workflow token; this is a workflow-internal integration seam, not a general way to disable the local gate. The CLI prints an explicit diagnostic whenever that exact value skips either `check`'s live phase or `github --check`; `github --apply` is never skipped. `--apply` re-diffs the PATCH response, so a setting GitHub accepts with HTTP 200 but silently ignores (plan-unavailable features) is a reported failure, not a false success. A repository whose GitHub plan cannot enforce rulesets can declare that in the seam (see `rulesetEnforcement` below); both commands then skip rulesets and plan-gated repository settings, converge the rest, and print an unprotected-branch notice on every run.
35
37
 
36
38
  `structure` enforces the canonical monorepo structure contract: workspace scripts (`check-types`, `lint`, `lint:fix`, `test`), root gate scripts, filtered Turbo convenience aliases, internal `0.0.0`/`workspace:*` versioning, package `exports`, shared tsconfig inheritance, and browser a11y wiring. Only a workspace containing an explicit `*.a11y.ts` suite must provide a `test:a11y` script and direct `@axe-core/playwright` and `@playwright/test` dependencies. `check` includes `structure`, so these rules gate every consumer PR.
37
39
 
38
40
  `poller` runs one tick of the fix poller: host-level automation that turns maintainer-approved GitHub issues into verified draft PRs and maintainer-approved draft PRs into completed review-fix cycles, using headless Codex runs. All workflow state lives in GitHub labels, comments, and draft PRs (the labels are canonical declared settings — see `github --apply`), so ticks are stateless, re-runnable, and safe to schedule from any host. A tick claims work by label (`fix-in-progress` / `review-in-progress`), releases claims stale for longer than `staleClaimHours`, and fails loudly — a red tick means jobs stalled, never silence. A separate acknowledgement tick validates pending approvals and posts one deduplicated queued message per approval generation; it never claims or starts work, so it can keep giving maintainers prompt feedback while the worker is occupied. When a worker claims a request, it posts a concise start message. The exact approval and distributed claim records remain in hidden comment metadata, and losing claim contenders remove their duplicate comments. Trust is verified per event, not per configuration: the approval labels (`approved-for-fix`, `approved-for-review`) only count when the applying user holds the `admin` or `maintain` role, bind to the exact approved issue revision or PR head, and are revalidated before publication; only admin/maintain comments are treated as answers to agent questions. Approved Codex runs inherit the poller's GitHub token and use authenticated `gh` for relevant reads and comments; review runs also maintain the PR review ledger, apply authorized title or body edits, post fix threads, and file deferred findings directly. The run works in a throwaway git worktree, grants Codex write access to that worktree and its exact Git common directory so commits can update the linked repository metadata, and hands results back through a structured outcome file. The poller then verifies the approved head, commits, and protected paths before pushing or publishing; it replies to and resolves agent-posted fix threads only after the reviewed head is pushed, and it alone changes protocol labels, posts the final report, and flips a reviewed draft ready, while required CI remains the quality gate. If publishing a sealed fix or review result fails, the poller releases only its owned in-progress claim and keeps the approval and sealed output, so the next worker tick retries publication without another Codex run. Sealed review plans from the earlier protocol are rejected and their output branches are ignored, so the review reruns on a fresh protocol-versioned branch rather than silently dropping legacy deferred work. Host mutation is declarative-only: `--print-units` emits four correctly escaped systemd units for the polling host's infrastructure repository to adapt and deploy: the worker service and timer plus an independent lightweight acknowledgement service and timer. That repository owns the service identity, writable HOME, PATH, authenticated `gh`, lingering, and deployment. The worker service's tick budget (`TimeoutStartSec`) is derived from `maxJobsPerTick` × `runTimeoutMinutes` plus overhead, so re-render and redeploy the units after changing either value.
39
41
 
40
- `creds` is the credential broker: it mints scoped Cloudflare tokens, rotates and revokes those tokens, and places GitHub App credentials into SOPS-encrypted targets — secret values never touch stdout, argv, or an agent's context; commands print only metadata (token name, scopes, expiry, destination). Cloudflare reconciliation has exactly two sources of truth: the plaintext key structure of the SOPS files and the provider token list under the deterministic naming scheme `standards/<owner>/<repo>/<sops-target>/<dotted.key>`; there is no separate credential manifest. `plan` and `apply` reconcile Cloudflare only: each run uses the stored bootstrap credential to verify its current provider token ID, excludes that ID from reconciliation regardless of its current name, and aborts if the identity cannot be correlated with the complete account token list; a brokered token whose SOPS key was deleted is revoked, while one nearing expiry (30 days) is renewed by creating a fresh-expiry replacement with the live token's policy, durably writing and verifying the new value, and only then revoking the old token; secrets the broker did not mint are never touched. Without a manifest there is no desired-policy record, so live policy drift is not detected, and a repository rename or transfer changes the deterministic namespace and requires the visible old token to be re-minted under the new name and revoked. `add cloudflare` mints an account-owned API token (default TTL 90 days) scoped to the named permission groups (`permissions` lists the valid names) and writes it to `--dest <target>:<dotted.key>`, where `<target>` resolves like the canonical `just secrets` targets (`ci` → `secrets/ci.yaml`, `prod-1` → `infra/hosts/prod-1/secrets.yaml`); zone-scoped groups such as DNS Write are rejected because the current command supplies an account resource, not a zone resource. `--bucket <name>` switches the policy resource to a single R2 bucket; `--jurisdiction default|eu` selects the provider jurisdiction and defaults to `default`, producing `com.cloudflare.edge.r2.bucket.<account_id>_default_<bucket>` or `com.cloudflare.edge.r2.bucket.<account_id>_eu_<bucket>`. FedRAMP jurisdictions are not supported. Bucket destinations accept only bucket-scoped groups such as Workers R2 Storage Bucket Item Read/Write, and account-scoped groups are rejected. `--s3` requires `--bucket` and stores the S3-compatible credential pair Cloudflare derives from an API token — access key ID is the token ID, secret access key is the SHA-256 hex digest of the token value — as `<dotted.key>.access_key_id` and `<dotted.key>.secret_access_key` under the destination instead of the raw token value; the default endpoint is `https://<account_id>.r2.cloudflarestorage.com`, while EU uses `https://<account_id>.eu.r2.cloudflarestorage.com`. Reconciliation infers each destination's concrete write footprint from the plaintext SOPS key structure — a bearer owns the leaf at its key, while an S3 token owns both pair leaves — and aborts before mutation when managed footprints intersect. `plan` and `apply` renew and revoke S3 destinations like any other brokered token, but renewal first proves the stored access key ID matches the current provider token; an incomplete pair, unreadable value, or identity mismatch is surfaced as a finding and never mutated automatically. `add github` writes the broker GitHub App's `app_id` and `private_key` under the destination key; durable GitHub tokens cannot be created via API (PAT and OAuth-app creation are UI-only), so workflows mint short-lived installation tokens from the App at runtime (`actions/create-github-app-token`), scoped per repository and permission. The canonical weekly sync expects `bun standards creds add github --dest ci:ci.broker_app`, then mints a current-repository token with Contents read and Pull requests write; missing credentials or minting failures stop it without a fallback. Bootstrap is once per machine: `login github` runs the App manifest flow (a localhost page posts the pre-filled manifest; one "Create GitHub App" click; credentials return through the conversion endpoint — nothing is copied by hand) and opens the installation page, where the App must be bound to selected repositories rather than all repositories; `login cloudflare` guides the one dashboard paste Cloudflare requires for the first account token (named `standards-broker` to match the App, created from the "Create additional tokens" token template because its "Account API Tokens: Edit" permission is unavailable in the custom token builder, and holding that permission only), verifies that it is active, correlates its verified ID with the complete account token list and an active list record, and stores it; a bootstrap token named inside the minted `standards/` namespace is rejected before storage to keep its role unambiguous, while any other divergence from the recommended name only warns. `plan` and `apply` do not rotate GitHub App keys; create a replacement key on the App's settings page, atomically replace `github.private_key` in the protected machine-global broker store while preserving its `0600` mode, then update every intended SOPS destination, verify workflows can mint installation tokens, and revoke the old key manually. Root credentials live in the machine-global broker store (see Configuration); SOPS writes go through `sops edit` with a non-interactive editor, preserving comments and reusing the file's data key.
42
+ `creds` is the credential broker: it mints scoped Cloudflare tokens, rotates and revokes those tokens, and places GitHub App credentials into SOPS-encrypted targets — secret values never touch stdout, argv, or an agent's context; commands print only metadata (token name, scopes, expiry, destination). Cloudflare reconciliation has exactly two sources of truth: the plaintext key structure of the SOPS files and the provider token list under the deterministic naming scheme `standards/<owner>/<repo>/<sops-target>/<dotted.key>`; there is no separate credential manifest. `plan` and `apply` reconcile Cloudflare only: each run uses the stored bootstrap credential to verify its current provider token ID, excludes that ID from reconciliation regardless of its current name, and aborts if the identity cannot be correlated with the complete account token list; a brokered token whose SOPS key was deleted is revoked, while one nearing expiry (30 days) is renewed by creating a fresh-expiry replacement with the live token's policies, durably writing and verifying the new value, and only then revoking the old token; secrets the broker did not mint are never touched. Both also report what reconciliation will never touch, in two separately labelled and separately counted blocks that never block: unmanaged tokens, meaning every unexpired token in the account whose name falls outside the reserved `standards/` namespace — with one exception, this machine's own bootstrap credential, which every run removes by verified ID before anything is classified — and tokens brokered to another repository, each printed with the repository whose `apply` owns it. An expired token is omitted from the unmanaged listing because it grants nothing. Neither block is idle information: nothing here renews or revokes those tokens, and a forgotten one — the original half of a hand-made credential that was replaced rather than retired, or a brokered token whose repository was renamed away — stays valid indefinitely, so a listed token is normally printed with the exact command that retires it, carrying `--account` and, for a token brokered elsewhere, `--force` and the one condition that justifies it. Two rows are exceptions. A token named `standards-broker` holds the reserved name for a machine's bootstrap credential, so it is either another machine's or a superseded one on this machine; `revoke` refuses it by name, so the row names the Cloudflare dashboard rather than a command that would always fail. The other exception looks like an ordinary brokered-elsewhere row, and its command fails. `plan` classifies by exact token name, so a token whose brokered repository differs from this checkout's origin only in capitalisation lands in the brokered-elsewhere block with a `--force` command; `revoke` compares repository names case-insensitively, reads the same token as this checkout's own, and refuses. Row and block header both read that token as foreign — the header labels the block tokens brokered to another repository, and the row explains the `--force` by the owning repository having been renamed, transferred, or deleted. Neither holds there: GitHub names are case-insensitive, so the owning repository is this one and it is still alive. Re-point the origin remote at the capitalisation the token carries, or retire the token in the Cloudflare dashboard. A name that claims this repository's brokered namespace without being one the broker mints is a finding instead, and findings abort reconciliation before any mutation, because reconciliation cannot own that token; plain `revoke --token-id` takes it once you decide it should go. `revoke --token-id <id>` deletes exactly one Cloudflare token, named by its 32-character hexadecimal ID, with `--account <id>` required whenever more than one account is configured; it records no ownership, so the power is momentary rather than standing and a human names the target every time. It refuses an ID the account does not hold, the bootstrap credential this machine has stored (matched by verified ID, so a rename cannot disguise it), and any other token named `standards-broker`, the reserved name for a machine's bootstrap (matched by name, because that one is another machine's bootstrap or a superseded one, retired in the Cloudflare dashboard where you can confirm whose it is — the broker cannot re-mint its own root credential). A token brokered to this repository is refused with the remedy that works here: delete its SOPS key in this repository and run `apply`, which revokes the token and keeps the secret in step. A token whose brokered name differs from this checkout's origin only in capitalisation is refused too, and without the `apply` remedy: reconciliation matches the name exactly, so from here it would neither renew nor revoke the token. Its remedies are re-pointing the origin remote at the capitalisation the token carries, which brings it back under reconciliation, or retiring it in the Cloudflare dashboard. A token brokered to a repository that is genuinely a different one is refused with that repository named, because the same `apply` remedy runs there. `--force` widens exactly that last refusal, and nothing else: it lets `revoke` delete a token whose brokered repository is not this checkout's. It verifies nothing about the state of that repository, so it is justified only when nothing reconciles the token any more — the owning repository was renamed, transferred, or deleted, and no checkout resolves to its name. `revoke` decides ownership from the origin remote and compares it case-insensitively, as GitHub names are; `plan` classifies by exact name instead, which is why the two disagree about a case-only difference. When the origin remote resolves to no GitHub repository, every brokered token is refused, `--force` included, because the check it widens is the one that could not be run. `--force` never bypasses either bootstrap guard, the case-only refusal, or that unresolvable-origin refusal. Without a manifest there is no desired-policy record, so live policy drift is not detected, and a repository rename or transfer changes the deterministic namespace and requires the visible old token to be re-minted under the new name and revoked. `add cloudflare` mints an account-owned API token (default TTL 90 days) scoped to the named permission groups (`permissions` lists the valid names) and writes it to `--dest <target>:<dotted.key>`, where `<target>` resolves like the canonical `just secrets` targets (`ci` → `secrets/ci.yaml`, `prod-1` → `infra/hosts/prod-1/secrets.yaml`). `--zone <zone-id>[,<zone-id>...]` adds a zone resource so zone-scoped groups such as DNS Write can be minted. Zones are named by their 32-character hexadecimal ID, shown on the zone's dashboard overview and not a secret; resolving a domain name instead would need Zone Read on the bootstrap token, which holds Account API Tokens / Edit and nothing else. With zones named, the selection is split by what each group can target: every group Cloudflare reports as zone-scoped forms one policy holding all named zones, and groups that can only target an account keep their own account policy on the same token, so one credential can hold DNS access next to account-wide access. A group Cloudflare reports as both takes the zone policy, which is the narrower reading of `--zone`. A group matching neither resource is named and rejected, `--zone` requires at least one zone-scoped group, and `--zone` cannot be combined with `--bucket`, which is a separate credential. The mint summary prints the resources the token reaches, so an account policy alongside the zones is visible rather than implied. `--bucket <name>` switches the policy resource to a single R2 bucket; `--jurisdiction default|eu` selects the provider jurisdiction and defaults to `default`, producing `com.cloudflare.edge.r2.bucket.<account_id>_default_<bucket>` or `com.cloudflare.edge.r2.bucket.<account_id>_eu_<bucket>`. FedRAMP jurisdictions are not supported. Bucket destinations accept only bucket-scoped groups such as Workers R2 Storage Bucket Item Read/Write, and account-scoped groups are rejected. `--s3` requires `--bucket` and stores the S3-compatible credential pair Cloudflare derives from an API token — access key ID is the token ID, secret access key is the SHA-256 hex digest of the token value — as `<dotted.key>.access_key_id` and `<dotted.key>.secret_access_key` under the destination instead of the raw token value; the default endpoint is `https://<account_id>.r2.cloudflarestorage.com`, while EU uses `https://<account_id>.eu.r2.cloudflarestorage.com`. Reconciliation infers each destination's concrete write footprint from the plaintext SOPS key structure — a bearer owns the leaf at its key, while an S3 token owns both pair leaves — and aborts before mutation when managed footprints intersect. `plan` and `apply` renew and revoke S3 destinations like any other brokered token, but renewal first proves the stored access key ID matches the current provider token; an incomplete pair, unreadable value, or identity mismatch is surfaced as a finding and never mutated automatically. `add github` selects the private broker App whose owner matches the destination repository's origin owner, checks both local SOPS leaves before authenticating, proves that the exact selected App is installed on that repository, and writes only while that full App identity still holds the synchronized broker-store entry; missing, duplicate, replaced, or mismatched owners fail before SOPS changes. Durable GitHub tokens cannot be created via API (PAT and OAuth-app creation are UI-only), so workflows mint short-lived installation tokens from the App at runtime (`actions/create-github-app-token`), scoped per repository and permission. The canonical weekly sync expects `bun standards creds add github --dest ci:ci.broker_app`, then mints a current-repository token with Contents read and Pull requests write; missing credentials or minting failures stop it without a fallback. Bootstrap is once per machine and per GitHub owner: `login github` creates a private personal App, while `login github --org <org>` creates or replaces only that organization's entry; each manifest conversion records GitHub's authoritative owner, and the command opens the installation page, where the App must be bound to selected repositories rather than all repositories. GitHub App names are globally unique and limited to 34 characters, so organization defaults include owners up to 17 characters; a longer owner or a colliding replacement name requires an explicit shorter unused `--name`. The first GitHub-specific command against an existing singleton broker store authenticates as that App, resolves its registration owner, and atomically migrates the old mapping to that one owner; a failed lookup leaves the persisted bytes untouched. If the singleton was a public App installed on repositories owned by other users or organizations, those repositories stop matching after migration because owner selection no longer treats that App as shared. For each affected owner, run `login github` while signed in as that personal owner or `login github --org <owner>`, install the new private App only on the selected repositories, run `bun standards creds add github --dest <target>:<key>` in every consumer, and verify its workflows can mint tokens. Retire the old public App only after every repository owner has its own entry, every intended SOPS destination has been reprovisioned, and token minting has been verified; until then, keep its key and installation available for any destinations not yet migrated. `login cloudflare` guides the one dashboard paste Cloudflare requires for the first account token (named `standards-broker` to match the App, created from the "Create additional tokens" token template because its "Account API Tokens: Edit" permission is unavailable in the custom token builder, and holding that permission only), verifies that it is active, correlates its verified ID with the complete account token list and an active list record, and stores it; a bootstrap token named inside the minted `standards/` namespace is rejected before storage to keep its role unambiguous, while any other divergence from the recommended name only warns. `plan` and `apply` do not rotate GitHub App keys; create a replacement key on the App's settings page, atomically replace that owner's `private_key` in the protected machine-global broker store while preserving its `0600` mode, then update every intended SOPS destination, verify workflows can mint installation tokens, and revoke the old key manually. Root credentials live in the machine-global broker store (see Configuration); SOPS writes go through `sops edit` with a non-interactive editor, preserving comments and reusing the file's data key.
41
43
 
42
44
  `structure --profile source` validates the standards source repository itself, which is deliberately not a consumer. The profile pins its intentional exceptions so they cannot drift silently: exact, ordered root gate scripts that run this CLI from the local checkout (`structure --profile source`, `dependabot --check` or `dependabot --write`, `github --check`, and the Turbo gate) instead of a recursive `standards check`, and a non-private published bin-only CLI workspace that carries a stable release SemVer and exactly maps the `standards` bin to `src/cli.ts` without `exports`. Every other consumer rule still applies.
43
45
 
@@ -47,7 +49,7 @@ standards poller --print-units --config <path>
47
49
  - **`sync-standards.local.json`** (optional) — consumer-owned sync policy at the repo root, validated by `doctor`/`check` and every `init`/`sync` even when an explicit ref or local source makes its `"ref"` irrelevant. All fields optional; a missing file means the defaults. `"ref"` is a non-empty single-line string that pins a tag, branch, or full commit sha to sync from instead of `main` (an explicit `--ref` overrides it; a local-path `--from` source is used as-is and ignores only the validated pin). `"autoSync": false` is read by the standards-sync workflow, not the CLI, and skips the weekly scheduled run; deliberate syncs then run locally because the secret-bearing workflow is schedule-only. Version 0.7.0 removes the legacy `STANDARDS_AUTO_SYNC` and `STANDARDS_SYNC_REF` variable behavior; consumers must upgrade the package and lockfile before adopting a policy file.
48
50
  - **`.github/settings.local.json` `"rulesetEnforcement": "unavailable-on-plan"`** (optional) — declares that the repository's GitHub plan cannot enforce rulesets (private repositories on GitHub Free, both personal accounts and organizations). `github --check` and `--apply` then skip rulesets instead of comparing them, because a comparison cannot be trusted there: personal accounts answer ruleset reads with HTTP 403, and free-plan organizations report declared rulesets as active while silently not enforcing them. Plan-gated repository settings that only function alongside branch protection (`allow_auto_merge`) are skipped for the same reason — GitHub accepts a PATCH for them with HTTP 200 and silently keeps the old value. The remaining repository merge settings are still checked and converged, and both commands print an unprotected-branch notice on every run. The only accepted value is `"unavailable-on-plan"` (enforcement is the default; omit the key on paid plans), and combining the opt-out with additional local rulesets is rejected. After upgrading the plan, remove the declaration and run `bun standards github --apply` to restore enforcement.
49
51
  - **Poller config file** (required for `poller`, passed via `--config`) — host-level JSON, deliberately not repository state. Required: `"repos"` (1–12 unique `owner/repo` strings), `"model"` and `"reasoningEffort"` (passed to `codex exec`; the model choice is deliberate and has no default). The 12-repository maximum and five-minute acknowledgement cooldown keep supported mixed fix/review queues and persisted review-plan recovery below the 5,000-request/hour GitHub API budget with at least 1,400 requests/hour reserved for pagination, active jobs, writes, and other token users; the compound regression bound covers four acknowledged fixes plus four acknowledged reviews with persisted plans in every repository at no more than 3,312 requests/hour. Existing configs above the repository limit must be reduced or split across pollers with independent GitHub API budgets before upgrading. Optional: `"maxJobsPerTick"` (default 1 — the maximum number of new Codex runs the sequential worker may start in one tick), `"staleClaimHours"` (default 6; must exceed `runTimeoutMinutes` so a sweep can never release the claim of a job that is still running), `"runTimeoutMinutes"` (default 240 — the timeout catches wedged agents, not honest multi-hour review runs), `"cacheDir"` (default `~/.cache/standards-poller`; holds bare mirrors and job worktrees; relative paths resolve against the config file), `"extraCodexArgs"` (extra `codex exec` arguments, e.g. enabling the collaboration feature for subagent fan-out). Unknown keys are rejected. The poller needs `git`, `gh`, `codex` (authenticated — its rotating auth state must live in a writable location), and a GitHub token per the bullet below; the token needs issues, pull-requests, and contents write on the watched repos, and nothing else.
50
- - **Broker store** (created by `creds login`) — machine-global root credentials at `$XDG_CONFIG_HOME/standards/broker.yaml` (default `~/.config/standards/broker.yaml`; override with `STANDARDS_BROKER_FILE`), holding the GitHub App identity (id, slug, client id, private key) and one bootstrap token per Cloudflare account. The file is plaintext with `0600` permissions — deliberately the same local-account trust boundary as the plaintext personal age identity at `~/.config/sops/age/keys.txt`, which unlocks the same secrets; SOPS-encrypting the store to that adjacent identity would not improve custody. Writes use an owner-only temporary file and atomic replacement, and simultaneous provider logins merge rather than overwrite each other; `creds status` warns when the final mode is broader. The store lives outside every repository, is never synced or backed up, and losing it is cheap: re-run the two login commands and revoke the old App key and bootstrap token. On an additional machine, do not create a second App: generate an additional private key from the existing App's settings page (GitHub Apps support several active keys; key generation has no API) and add it to that machine's store, so retiring a machine revokes one key, not the setup.
51
- - **`GH_TOKEN` / `GITHUB_TOKEN`** (optional generally; poller automation requires this or a logged-in `gh`) — GitHub API token for the `github` command and the GitHub portion of `check`; poller runs pass environment tokens through to Codex, while a local poller can share the service identity's authenticated `gh` state. When neither is available, other commands can still read public repositories anonymously, but poller writes and `github --apply` fail. GitHub's REST API reveals repo merge settings only to write-capable viewers, and `check` retries REST-hidden keys over GraphQL, which serves them to read-only tokens. REST serves ruleset `bypass_actors` only to a user-scoped token holding repository Administration read (a fine-grained PAT with that permission, such as CI's settings token, or the local `gh` CLI), and never to a GitHub App installation token at any permission level, so `check` retries the hidden lists over GraphQL, which withholds the actor identities but answers an exact bypass-actor count (established for a GitHub App installation token and for a non-admin classic-scope viewer, not for every identity class): a declared-empty list verifies exactly, a count that disagrees with the declared length is drift, and a matching non-zero count leaves *which* actors bypass unconfirmed, so the gate fails closed on that ruleset. An installation-token run therefore leaves a declared non-empty list failing until the check is re-run locally with admin `gh` auth; broadening the settings PAT beyond read-only Administration is not the fix. Private-repository labels require Issues read (or Pull requests read); a token that still cannot see declared state fails the check rather than passing unverified. In CI, the canonical workflow decrypts `ci.github_settings_read_token` from the SOPS-encrypted `secrets/ci.yaml`: a repository-scoped fine-grained PAT with read-only "Administration" and "Issues" access.
52
+ - **Broker store** (created by `creds login`) — machine-global root credentials at `$XDG_CONFIG_HOME/standards/broker.yaml` (default `~/.config/standards/broker.yaml`; override with `STANDARDS_BROKER_FILE`), holding one private GitHub App identity (owner, id, slug, client id, private key) per GitHub account and one bootstrap token per Cloudflare account. The file is plaintext with `0600` permissions — deliberately the same local-account trust boundary as the plaintext personal age identity at `~/.config/sops/age/keys.txt`, which unlocks the same secrets; SOPS-encrypting the store to that adjacent identity would not improve custody. Writes use an owner-only temporary file and atomic replacement, and simultaneous provider logins merge rather than overwrite other accounts; `creds status` lists every App and owner and warns when the final mode is broader. The store lives outside every repository, is never synced or backed up, and losing it is cheap: re-run the provider login commands, revoke the old App keys on each App's settings page, and retire the old bootstrap tokens in the Cloudflare dashboard. The dashboard is the only route for those tokens: `login cloudflare` walks you through creating a second one under the reserved `standards-broker` name, the old one stays live under that same name, and `revoke` refuses every token holding it. On an additional machine, do not create second Apps: generate an additional private key from each existing App's settings page (GitHub Apps support several active keys; key generation has no API) and add it to that machine's store, so retiring a machine revokes one key per owner, not the setups.
53
+ - **`GH_TOKEN` / `GITHUB_TOKEN`** (optional generally; poller automation requires this or a logged-in `gh`) — GitHub API token for the `github` command and the GitHub portion of `check`; poller runs pass environment tokens through to Codex, while a local poller can share the service identity's authenticated `gh` state. When neither is available, other commands can still read public repositories anonymously, but poller writes and `github --apply` fail. GitHub's REST API reveals repo merge settings only to write-capable viewers, and `check` retries REST-hidden keys over GraphQL, which serves them to read-only tokens. REST serves ruleset `bypass_actors` only to a user-scoped token holding repository Administration read (a fine-grained PAT with that permission, or the local `gh` CLI under an admin account), and never to a GitHub App installation token at any permission level, so `check` retries the hidden lists over GraphQL, which withholds the actor identities but answers an exact bypass-actor count (established for a GitHub App installation token and for a non-admin classic-scope viewer, not for every identity class): a declared-empty list verifies exactly, a count that disagrees with the declared length is drift, and a matching non-zero count leaves *which* actors bypass unconfirmed, so the gate fails closed on that ruleset. An installation-token run therefore leaves a declared non-empty list failing until the check is re-run locally with admin `gh` auth; widening the App's permissions is not the fix. Private-repository labels require Issues read (or Pull requests read); a token that still cannot see declared state fails the check rather than passing unverified. In CI, the canonical workflow verifies with the workflow token, granted read-only "Contents" and "Issues"; Issues is what declared-label reads need, listing rulesets rides on the implicit "Metadata" read, and merge settings come over GraphQL. A private-repository probe compared that grant set against a broker App installation token across every read the check performs and found no difference, so CI provisions no settings credential of its own.
52
54
 
53
55
  See the standards repository README for the ownership model and adoption workflow.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@davidvornholt/standards",
3
- "version": "0.19.0",
3
+ "version": "0.21.0",
4
4
  "description": "Bootstrap, synchronize, and validate davidvornholt/standards consumers",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -25,16 +25,21 @@
25
25
  "src/creds-add-cloudflare-commit.ts",
26
26
  "src/creds-add-github.ts",
27
27
  "src/creds-add-policy.ts",
28
+ "src/creds-add-preflight.ts",
28
29
  "src/creds-browser.ts",
29
30
  "src/creds-cloudflare-account.ts",
30
31
  "src/creds-cloudflare.ts",
31
32
  "src/creds-cloudflare-api.ts",
32
33
  "src/creds-cloudflare-condition.ts",
33
34
  "src/creds-cloudflare-expiry.ts",
35
+ "src/creds-cloudflare-id.ts",
34
36
  "src/creds-cloudflare-pagination.ts",
37
+ "src/creds-cloudflare-zone.ts",
35
38
  "src/creds-commands.ts",
36
39
  "src/creds-args.ts",
37
40
  "src/creds-dest.ts",
41
+ "src/creds-github-app-api.ts",
42
+ "src/creds-github-apps.ts",
38
43
  "src/creds-login-cloudflare.ts",
39
44
  "src/creds-login-github.ts",
40
45
  "src/creds-login-github-manifest.ts",
@@ -42,16 +47,24 @@
42
47
  "src/creds-plan.ts",
43
48
  "src/creds-plan-groups.ts",
44
49
  "src/creds-plan-renew.ts",
50
+ "src/creds-plan-report.ts",
45
51
  "src/creds-plan-run.ts",
46
52
  "src/creds-plan-revoke.ts",
47
53
  "src/creds-plan-types.ts",
54
+ "src/creds-plan-unmanaged.ts",
48
55
  "src/creds-prompt.ts",
49
56
  "src/creds-r2.ts",
57
+ "src/creds-revoke.ts",
50
58
  "src/creds-sops.ts",
51
59
  "src/creds-sops-editor.ts",
52
60
  "src/creds-sops-structure.ts",
61
+ "src/creds-sops-value.ts",
53
62
  "src/creds-store.ts",
63
+ "src/creds-store-github.ts",
54
64
  "src/creds-store-lock.ts",
65
+ "src/creds-store-lock-holder.ts",
66
+ "src/creds-store-lock-inspection.ts",
67
+ "src/creds-store-lock-lease.ts",
55
68
  "src/dependabot-compose-input.ts",
56
69
  "src/dependabot-compose.ts",
57
70
  "src/dependabot-directory-character-class.ts",
@@ -59,11 +72,15 @@
59
72
  "src/dependabot-directory-overlap.ts",
60
73
  "src/dependabot-inspect.ts",
61
74
  "src/dependabot-update.ts",
75
+ "src/dev-env-compose.ts",
62
76
  "src/dev-env-document.ts",
63
77
  "src/dev-env-destination-duplicates.ts",
78
+ "src/dev-env-destination-gitignore.ts",
64
79
  "src/dev-env-destination.ts",
65
80
  "src/dev-env-dotenv-value.ts",
66
81
  "src/dev-env-dotenv.ts",
82
+ "src/dev-env-reconciliation.ts",
83
+ "src/dev-env-secrets.ts",
67
84
  "src/dev-env-transaction-recovery.ts",
68
85
  "src/dev-env-transaction.ts",
69
86
  "src/dev-env.ts",
@@ -95,6 +112,7 @@
95
112
  "src/poller-comment-metadata.ts",
96
113
  "src/poller-comment-reconciliation.ts",
97
114
  "src/poller-claim-reconciliation.ts",
115
+ "src/poller-closing-reference.ts",
98
116
  "src/poller-config.ts",
99
117
  "src/poller-fix-outcome.ts",
100
118
  "src/poller-fix-output.ts",
package/src/cli.ts CHANGED
@@ -965,7 +965,7 @@ Commands:
965
965
  doctor Validate extension seams only
966
966
  structure Validate monorepo structure rules only
967
967
  dependabot Verify (--check) or regenerate (--write) the composed .github/dependabot.yml
968
- dev-env Write each workspace's generated .env.local from the SOPS-encrypted secrets/dev.yaml
968
+ dev-env Compose each workspace's generated .env.local from config/dev.yaml, the SOPS-encrypted secrets/dev.yaml, and gitignored config/dev.local.yaml overrides
969
969
  github Compare (--check) or converge (--apply) live GitHub settings
970
970
  creds Mint, rotate, and revoke brokered credentials (see \`standards creds help\`)
971
971
  poller Run one fix-poller tick over the configured repositories (host automation)
@@ -1216,7 +1216,7 @@ const runCheckCommand = async (consumer: string): Promise<boolean> => {
1216
1216
  };
1217
1217
 
1218
1218
  // The canonical workflow sets this only for its unprivileged quality job,
1219
- // where a separate isolated job runs the same live check with the settings-read
1219
+ // where a separate isolated job runs the same live check with its own workflow
1220
1220
  // token. Absent that exact workflow seam, local and explicit checks remain
1221
1221
  // fail-closed.
1222
1222
  const runGithubCheckGate = (consumer: string): Promise<boolean> => {
@@ -1,9 +1,6 @@
1
1
  import { deleteAccountToken } from './creds-cloudflare';
2
- import {
3
- type SopsValueChange,
4
- type SopsWriteResult,
5
- verifySopsStoredValue,
6
- } from './creds-sops';
2
+ import type { SopsValueChange, SopsWriteResult } from './creds-sops';
3
+ import { verifySopsStoredValue } from './creds-sops-value';
7
4
 
8
5
  export const commitCreatedCloudflareToken = async (input: {
9
6
  readonly consumer: string;
@@ -4,12 +4,18 @@
4
4
  // identity itself; workflows mint short-lived installation tokens from it at
5
5
  // runtime, scoped per repository and permission.
6
6
 
7
+ import { inspectDestinations } from './creds-add-preflight';
7
8
  import { resolveContext } from './creds-dest';
9
+ import { verifyGithubAppInstallation } from './creds-github-app-api';
8
10
  import {
9
- inspectSopsScalarDestination,
10
- setSopsValues,
11
- verifySopsScalarLeaf,
12
- } from './creds-sops';
11
+ loadOwnedGithubStore,
12
+ sameGithubApp,
13
+ selectGithubAppForRepo,
14
+ } from './creds-github-apps';
15
+ import { setSopsValues } from './creds-sops';
16
+ import { verifySopsStoredValue } from './creds-sops-value';
17
+ import { readBrokerStore, resolveBrokerPath } from './creds-store';
18
+ import { withBrokerLock } from './creds-store-lock';
13
19
 
14
20
  export const runCredsAddGithub = async (
15
21
  consumer: string,
@@ -19,41 +25,87 @@ export const runCredsAddGithub = async (
19
25
  if (context === null) {
20
26
  return false;
21
27
  }
22
- if (context.store.github === null) {
23
- console.error(
24
- 'standards creds: no broker GitHub App configured; run `standards creds login github`',
25
- );
26
- return false;
27
- }
28
- const { appId, privateKey, slug } = context.store.github;
29
28
  const appIdPath = `${context.dest.key}.app_id`;
30
29
  const privateKeyPath = `${context.dest.key}.private_key`;
31
- const preflight = await Promise.all(
32
- [appIdPath, privateKeyPath].map((path) =>
33
- inspectSopsScalarDestination(consumer, context.rel, path),
34
- ),
30
+ const blocked = await inspectDestinations(consumer, context.rel, [
31
+ appIdPath,
32
+ privateKeyPath,
33
+ ]);
34
+ if (blocked !== null) {
35
+ console.error(`standards creds: ${blocked}`);
36
+ return false;
37
+ }
38
+ const storePath = resolveBrokerPath();
39
+ const loaded = await loadOwnedGithubStore(storePath);
40
+ if (!loaded.ok) {
41
+ console.error(`standards creds: ${loaded.problem}`);
42
+ return false;
43
+ }
44
+ const selected = selectGithubAppForRepo(loaded.value.github, context.repo);
45
+ if (!selected.ok) {
46
+ console.error(`standards creds: ${selected.problem}`);
47
+ return false;
48
+ }
49
+ const installation = await verifyGithubAppInstallation(
50
+ selected.value,
51
+ context.repo,
35
52
  );
36
- const blocked = preflight.find((result) => !result.ok);
37
- if (blocked !== undefined && !blocked.ok) {
38
- console.error(`standards creds: ${blocked.problem}`);
53
+ if (!installation.ok) {
54
+ console.error(`standards creds: ${installation.problem}`);
55
+ return false;
56
+ }
57
+ const { appId, privateKey, slug } = selected.value;
58
+ let writeResult:
59
+ | { readonly ok: true }
60
+ | { readonly ok: false; readonly problem: string };
61
+ try {
62
+ writeResult = await withBrokerLock(storePath, async () => {
63
+ const current = selectGithubAppForRepo(
64
+ (await readBrokerStore(storePath)).github,
65
+ context.repo,
66
+ );
67
+ if (!current.ok) {
68
+ return current;
69
+ }
70
+ if (!sameGithubApp(current.value, selected.value)) {
71
+ return {
72
+ ok: false,
73
+ problem: `the broker GitHub App for ${selected.value.owner} changed while its installation was being verified; retry so the replacement can be verified`,
74
+ };
75
+ }
76
+ return setSopsValues(consumer, context.rel, [
77
+ { path: appIdPath, value: String(appId) },
78
+ { path: privateKeyPath, value: privateKey },
79
+ ]);
80
+ });
81
+ } catch (error) {
82
+ const message = error instanceof Error ? error.message : String(error);
83
+ console.error(`standards creds: ${message}`);
84
+ return false;
85
+ }
86
+ if (!writeResult.ok) {
87
+ console.error(`standards creds: ${writeResult.problem}`);
39
88
  return false;
40
89
  }
41
- const written = setSopsValues(consumer, context.rel, [
90
+ const verified = [
42
91
  { path: appIdPath, value: String(appId) },
43
92
  { path: privateKeyPath, value: privateKey },
44
- ]);
45
- if (!written.ok) {
46
- console.error(`standards creds: ${written.problem}`);
93
+ ].map(({ path, value }) => ({
94
+ path,
95
+ result: verifySopsStoredValue(consumer, context.rel, path, value),
96
+ }));
97
+ const unverifiable = verified.find(({ result }) => !result.ok);
98
+ if (unverifiable !== undefined && !unverifiable.result.ok) {
99
+ console.error(`standards creds: ${unverifiable.result.problem}`);
47
100
  return false;
48
101
  }
49
- const verified = await Promise.all(
50
- [appIdPath, privateKeyPath].map((path) =>
51
- verifySopsScalarLeaf(consumer, context.rel, path),
52
- ),
53
- );
54
- const failedVerification = verified.find((result) => !result.ok);
55
- if (failedVerification !== undefined && !failedVerification.ok) {
56
- console.error(`standards creds: ${failedVerification.problem}`);
102
+ const mismatched = verified
103
+ .filter(({ result }) => result.ok && !result.matches)
104
+ .map(({ path }) => path);
105
+ if (mismatched.length > 0) {
106
+ console.error(
107
+ `standards creds: the stored SOPS value at ${mismatched.join(', ')} does not match the selected GitHub App`,
108
+ );
57
109
  return false;
58
110
  }
59
111
  console.log(
@@ -6,9 +6,8 @@
6
6
 
7
7
  import { listPermissionGroups } from './creds-cloudflare';
8
8
  import type { PermissionGroup, TokenPolicy } from './creds-cloudflare-api';
9
+ import { ZONE_SCOPE, zoneResource } from './creds-cloudflare-zone';
9
10
  import {
10
- DEFAULT_R2_JURISDICTION,
11
- isR2BucketName,
12
11
  R2_BUCKET_SCOPE,
13
12
  type R2Jurisdiction,
14
13
  r2BucketResource,
@@ -17,6 +16,16 @@ import type { CloudflareBrokerAccount } from './creds-store';
17
16
 
18
17
  const ACCOUNT_SCOPE = 'com.cloudflare.api.account';
19
18
 
19
+ const tokenPolicy = (
20
+ resources: TokenPolicy['resources'],
21
+ groups: ReadonlyArray<PermissionGroup>,
22
+ ): TokenPolicy => ({
23
+ effect: 'allow',
24
+ resources,
25
+ // biome-ignore lint/style/useNamingConvention: Cloudflare's policy wire field is snake_case.
26
+ permission_groups: groups.map(({ id }) => ({ id })),
27
+ });
28
+
20
29
  export const unsupportedResourceScopes = (
21
30
  groups: ReadonlyArray<PermissionGroup>,
22
31
  scope: string,
@@ -26,23 +35,99 @@ export const unsupportedResourceScopes = (
26
35
  .map((group) => group.name);
27
36
 
28
37
  const scopeProblem = (
29
- bucket: string | undefined,
38
+ resource: { readonly kind: 'account' | 'bucket' },
30
39
  selected: ReadonlyArray<PermissionGroup>,
31
40
  ): string | null => {
32
- const scope = bucket === undefined ? ACCOUNT_SCOPE : R2_BUCKET_SCOPE;
41
+ const scope = resource.kind === 'account' ? ACCOUNT_SCOPE : R2_BUCKET_SCOPE;
33
42
  const unsupported = unsupportedResourceScopes(selected, scope);
34
43
  if (unsupported.length === 0) {
35
44
  return null;
36
45
  }
37
- return bucket === undefined
38
- ? `permission group(s) ${unsupported.join(', ')} cannot target an account resource; choose account-scoped groups (zone-scoped groups require an explicit zone resource, which this command does not yet support, and R2 bucket-item groups require --bucket)`
46
+ return resource.kind === 'account'
47
+ ? `permission group(s) ${unsupported.join(', ')} cannot target an account resource; choose account-scoped groups, name the zones with --zone for zone-scoped groups, or pass --bucket for R2 bucket-item groups`
39
48
  : `permission group(s) ${unsupported.join(', ')} cannot target an R2 bucket resource; --bucket accepts only bucket-scoped groups such as Workers R2 Storage Bucket Item Read/Write`;
40
49
  };
41
50
 
51
+ // With zones named, a token spans two resources, so the selection is split by
52
+ // what each group can actually target rather than checked against one scope.
53
+ // A group matching neither resource is the operator's mistake and is named.
54
+ // A group Cloudflare reports as both zone- and account-scoped goes to the zone
55
+ // policy: `--zone` asks for zone reach, and the narrower reading is the safe
56
+ // one to guess wrong.
57
+ const zonePolicies = (
58
+ accountId: string,
59
+ zoneIds: ReadonlyArray<string>,
60
+ selected: ReadonlyArray<PermissionGroup>,
61
+ ):
62
+ | { readonly policies: ReadonlyArray<TokenPolicy> }
63
+ | { readonly problem: string } => {
64
+ const zoneGroups = selected.filter((group) =>
65
+ group.scopes.includes(ZONE_SCOPE),
66
+ );
67
+ const accountGroups = selected.filter(
68
+ (group) =>
69
+ !group.scopes.includes(ZONE_SCOPE) &&
70
+ group.scopes.includes(ACCOUNT_SCOPE),
71
+ );
72
+ const unsupported = selected
73
+ .filter(
74
+ (group) =>
75
+ !(
76
+ group.scopes.includes(ZONE_SCOPE) ||
77
+ group.scopes.includes(ACCOUNT_SCOPE)
78
+ ),
79
+ )
80
+ .map((group) => group.name);
81
+ if (unsupported.length > 0) {
82
+ return {
83
+ problem: `permission group(s) ${unsupported.join(', ')} target neither a zone nor an account resource; R2 bucket-item groups require --bucket, which cannot be combined with --zone`,
84
+ };
85
+ }
86
+ if (zoneGroups.length === 0) {
87
+ return {
88
+ problem:
89
+ '--zone was given but no selected permission group is zone-scoped; drop --zone, or add a zone-scoped group such as DNS Write',
90
+ };
91
+ }
92
+ const zoneResources = Object.fromEntries(
93
+ zoneIds.map((zoneId) => [zoneResource(zoneId), '*']),
94
+ );
95
+ return {
96
+ policies: [
97
+ ...(accountGroups.length === 0
98
+ ? []
99
+ : [
100
+ tokenPolicy(
101
+ { [`${ACCOUNT_SCOPE}.${accountId}`]: '*' },
102
+ accountGroups,
103
+ ),
104
+ ]),
105
+ tokenPolicy(zoneResources, zoneGroups),
106
+ ],
107
+ };
108
+ };
109
+
110
+ // One token reaches exactly one kind of resource, so the caller states which
111
+ // rather than passing flags whose illegal combinations would have to be
112
+ // re-rejected here.
113
+ export type PolicyResource =
114
+ | { readonly kind: 'account' }
115
+ | {
116
+ readonly kind: 'bucket';
117
+ readonly bucket: string;
118
+ readonly jurisdiction: R2Jurisdiction;
119
+ }
120
+ | {
121
+ readonly kind: 'zones';
122
+ // Non-empty by type: a zone policy with no resource would be accepted by
123
+ // the wire shape and reach nothing.
124
+ readonly zoneIds: readonly [string, ...ReadonlyArray<string>];
125
+ };
126
+
42
127
  export type ResolvedTokenPolicy =
43
128
  | {
44
129
  readonly ok: true;
45
- readonly policy: TokenPolicy;
130
+ readonly policies: ReadonlyArray<TokenPolicy>;
46
131
  readonly wanted: ReadonlyArray<string>;
47
132
  }
48
133
  | { readonly ok: false; readonly problem: string };
@@ -51,10 +136,10 @@ export const resolveTokenPolicy = async (
51
136
  account: CloudflareBrokerAccount,
52
137
  options: {
53
138
  readonly permissions: string | undefined;
54
- readonly bucket: string | undefined;
55
- readonly jurisdiction?: R2Jurisdiction;
139
+ readonly resource: PolicyResource;
56
140
  },
57
141
  ): Promise<ResolvedTokenPolicy> => {
142
+ const { resource } = options;
58
143
  if (options.permissions === undefined || options.permissions.length === 0) {
59
144
  return {
60
145
  ok: false,
@@ -62,12 +147,6 @@ export const resolveTokenPolicy = async (
62
147
  '--permissions "<Group Name>[,<Group Name>...]" is required; list names with `standards creds permissions`',
63
148
  };
64
149
  }
65
- if (options.bucket !== undefined && !isR2BucketName(options.bucket)) {
66
- return {
67
- ok: false,
68
- problem: `invalid R2 bucket name: ${options.bucket} (3-63 lowercase letters, digits, and hyphens)`,
69
- };
70
- }
71
150
  const groups = await listPermissionGroups(account.accountId, account.token);
72
151
  if (!groups.ok) {
73
152
  return { ok: false, problem: groups.problem };
@@ -93,26 +172,27 @@ export const resolveTokenPolicy = async (
93
172
  const selected = resolved.flatMap(({ group }) =>
94
173
  group === undefined ? [] : [group],
95
174
  );
96
- const problem = scopeProblem(options.bucket, selected);
175
+ if (resource.kind === 'zones') {
176
+ const zoned = zonePolicies(account.accountId, resource.zoneIds, selected);
177
+ return 'problem' in zoned
178
+ ? { ok: false, problem: zoned.problem }
179
+ : { ok: true, wanted, policies: zoned.policies };
180
+ }
181
+ const problem = scopeProblem(resource, selected);
97
182
  if (problem !== null) {
98
183
  return { ok: false, problem };
99
184
  }
100
- const resource =
101
- options.bucket === undefined
185
+ const target =
186
+ resource.kind === 'account'
102
187
  ? `${ACCOUNT_SCOPE}.${account.accountId}`
103
188
  : r2BucketResource(
104
189
  account.accountId,
105
- options.bucket,
106
- options.jurisdiction ?? DEFAULT_R2_JURISDICTION,
190
+ resource.bucket,
191
+ resource.jurisdiction,
107
192
  );
108
193
  return {
109
194
  ok: true,
110
195
  wanted,
111
- policy: {
112
- effect: 'allow',
113
- resources: { [resource]: '*' },
114
- // biome-ignore lint/style/useNamingConvention: Cloudflare's policy wire field is snake_case.
115
- permission_groups: selected.map(({ id }) => ({ id })),
116
- },
196
+ policies: [tokenPolicy({ [target]: '*' }, selected)],
117
197
  };
118
198
  };
@@ -0,0 +1,68 @@
1
+ // Everything `creds add cloudflare` can settle before it mints anything: which
2
+ // resource the token will reach, and whether each destination is a writable
3
+ // scalar leaf. Minting first and discovering these afterwards would leave a
4
+ // live credential nobody asked for.
5
+
6
+ import type { PolicyResource } from './creds-add-policy';
7
+ import { parseZoneArgument } from './creds-cloudflare-zone';
8
+ import {
9
+ DEFAULT_R2_JURISDICTION,
10
+ isR2BucketName,
11
+ type R2Jurisdiction,
12
+ } from './creds-r2';
13
+ import { inspectSopsScalarDestination } from './creds-sops';
14
+
15
+ export const inspectDestinations = async (
16
+ consumer: string,
17
+ rel: string,
18
+ paths: ReadonlyArray<string>,
19
+ ): Promise<string | null> => {
20
+ const inspected = await Promise.all(
21
+ paths.map((path) => inspectSopsScalarDestination(consumer, rel, path)),
22
+ );
23
+ const blocked = inspected.find((result) => !result.ok);
24
+ return blocked !== undefined && !blocked.ok ? blocked.problem : null;
25
+ };
26
+
27
+ export type ResolvedResourceFlags =
28
+ | { readonly ok: true; readonly resource: PolicyResource }
29
+ | { readonly ok: false; readonly problem: string };
30
+
31
+ // A token reaches one kind of resource, so the flags naming it collapse to that
32
+ // one choice here — before any provider or SOPS work, because no rejection
33
+ // below can be salvaged afterwards.
34
+ export const resolveResourceFlags = (options: {
35
+ readonly bucket: string | undefined;
36
+ readonly zone: string | undefined;
37
+ readonly jurisdiction?: R2Jurisdiction;
38
+ }): ResolvedResourceFlags => {
39
+ if (options.bucket !== undefined && options.zone !== undefined) {
40
+ return {
41
+ ok: false,
42
+ problem:
43
+ '--bucket and --zone cannot be combined; an R2 bucket credential and a zone credential are separate tokens',
44
+ };
45
+ }
46
+ if (options.bucket !== undefined) {
47
+ return isR2BucketName(options.bucket)
48
+ ? {
49
+ ok: true,
50
+ resource: {
51
+ kind: 'bucket',
52
+ bucket: options.bucket,
53
+ jurisdiction: options.jurisdiction ?? DEFAULT_R2_JURISDICTION,
54
+ },
55
+ }
56
+ : {
57
+ ok: false,
58
+ problem: `invalid R2 bucket name: ${options.bucket} (3-63 lowercase letters, digits, and hyphens)`,
59
+ };
60
+ }
61
+ if (options.zone === undefined) {
62
+ return { ok: true, resource: { kind: 'account' } };
63
+ }
64
+ const zones = parseZoneArgument(options.zone);
65
+ return zones.ok
66
+ ? { ok: true, resource: { kind: 'zones', zoneIds: zones.zoneIds } }
67
+ : { ok: false, problem: zones.problem };
68
+ };