Skip to content

Token Worker

The codehawk-token Cloudflare Worker exchanges a GitHub Actions OIDC token for a short-lived installation token from CodeHawk App (codehawk-app, owned by bts-io). A job can request a token for its own repository, with only the permissions it needs. The App private key stays in the Worker.

The hosted Worker serves only Code Hawk's own reusable workflows at a release. Install the CodeHawk App, then call a released reusable workflow and grant its calling job id-token: write. The called workflow cannot raise its caller's permissions. A direct actions/token step in your own job requires your own App key with app-id and private-key.

jobs:
review:
permissions:
contents: read
pull-requests: read
id-token: write
uses: bts-io/codehawk/.github/workflows/pr-review.yml@<release sha>
with:
inference: ${{ vars.CODEHAWK_INFERENCE }}
secrets:
CODEHAWK_CREDENTIAL_1: ${{ secrets.CODEHAWK_CREDENTIAL_1 }}

The key stays in the Worker. The action requests and masks OIDC and installation tokens before emitting outputs.

Input Default Purpose
permissions Required A nonempty JSON object with the Worker's permission names and allowed levels.
worker-url https://token.codehawk.app HTTPS base URL with no credentials, query or fragment. An empty value uses this default. Path prefixes are preserved.
app-id Empty Your own App's ID, used only with private-key.
private-key Empty Your own App's key, selecting the self-hosted path. The key never reaches the token bundle.
audience Empty Required for a custom Worker. The two hosted origins default to codehawk.
app-slug Empty Fallback when a custom Worker omits its App slug. A valid response slug wins.
Output Value
token Masked repository-scoped installation token.
expires-at Worker token expiry, empty on the App key path.
app-slug App slug for the bot login, such as codehawk-app[bot] after appending [bot].
source worker or app-key.

Reusable workflows expose the base URL as token_worker_url, empty for the hosted Worker. For your own App, forward CODEHAWK_PRIVATE_KEY and pass app_id. See self-hosted App. A key without an ID fails. An ID without a key produces one notice and uses the hosted path. Permissions are validated on both paths.

The action retries at most once. rate_limited and ip_rate_limited retry only with an integer Retry-After from 1 to 60 seconds. github_error retries after five seconds. Each retry requests a fresh OIDC token because a previous admission consumed its jti. Other failures stop at once. Each request has a 15-second timeout.

Local failures use these codes. Worker exchange codes are listed under Errors. The action logs its own fixed messages and never logs the Worker's response message.

Code Meaning
invalid_permissions Permissions are not a nonempty JSON object of string levels.
permission_not_allowed A key or level is outside the Worker allowlist.
app_id_required A private key was supplied without app-id.
invalid_worker_url The base URL is not HTTPS or contains credentials, a query or a fragment.
missing_repository GITHUB_REPOSITORY is absent.
oidc_unavailable The runner has no OIDC request URL or token. Check the job and caller grants. Fork PRs and Dependabot have no OIDC access.
oidc_failed The OIDC request failed or did not return a usable token.
worker_unreachable The exchange request threw or timed out.
invalid_response A successful Worker response lacks a usable token, expiry or matching repository.
unexpected_response The Worker returned an unknown code or a non-JSON error.
audience_required A custom worker-url needs its own audience input, so its OIDC tokens are never valid for another Worker.
app_slug_required A custom worker-url did not name its App. Pass app-slug.

The signed job_workflow_ref must name a file in the table below under bts-io/codehawk/.github/workflows/. Its ref must be a version tag such as refs/tags/v1.0.0 or a full lowercase release SHA. job_workflow_sha must match that tag's entry or a value in the reviewed CODEHAWK_RELEASES table. Branches, moving major tags and imposter commits from the fork network are refused with workflow_not_allowed. A trusted workflow on a different event gets workflow_event_not_allowed.

The job is not signed in OIDC claims. The allowed slice is the union of matching rows for the workflow and event, taking the higher level of each permission. Requests must be nonempty subsets at that level or below. Related context is available only to pr-review.yml on pull_request and returns contents read only.

Workflow Job Events Permission slice
pr-review.yml review pull_request contents read, pull_requests write, issues read
pr-review.yml reply pull_request_review_comment, issue_comment contents read, pull_requests write, issues read
pr-scan.yml line-scan-report pull_request contents read, pull_requests write
pr-scan.yml osv-report pull_request pull_requests write
weekly-review.yml review schedule, workflow_dispatch contents read, issues write
fix-request.yml publish issue_comment, pull_request_review_comment contents write, pull_requests write, issues write
fix-issues.yml publish issues, workflow_dispatch contents write, pull_requests write, issues write
browser-flows.yml report pull_request contents read, pull_requests write
preview-flows.yml prepare, report pull_request contents read, pull_requests write, deployments read
settings-command.yml apply issue_comment contents write, pull_requests write, issues write

CODEHAWK_RELEASES is an object mapping exact vMAJOR.MINOR.PATCH tags to full lowercase commit SHAs. The checked-in table is currently empty, so hosted exchanges remain locked until a release is recorded. The workflow lock checks both the signed workflow ref and SHA, then the event and requested permission slice. Caller inputs are not part of that lock.

Self-hosted Workers may set CODEHAWK_WORKFLOW_REPOSITORY to another owner/repo. Its default is bts-io/codehawk. A malformed repository, release table or denylist fails closed with not_configured. An empty valid release table refuses every hosted request until the first release is recorded. Preview preparation and reporting share the preview workflow slice. The browser job has no App token or OIDC access. Deployments read is issued only for this workflow.

Give the GitHub Actions job id-token: write. Request an OIDC token with audience codehawk, then send it as the Bearer token to POST /v1/token:

POST /v1/token
Authorization: Bearer <GitHub Actions OIDC token>
Content-Type: application/json
{"repository":"octo-org/widgets","permissions":{"contents":"read","pull_requests":"write"}}

repository must match the signed repository claim, ignoring case. The Worker scopes the installation token to the signed repository ID. It refuses pull_request_target workflows. For pull_request, pull_request_review and pull_request_review_comment, the request must include pull_requests with read or write. Requests without it return 400 pull_requests_permission_required before any token is minted or any GitHub API call. The Worker checks the pull request's head repository with the issued token before returning it. A fork or deleted head repository is refused and the token is revoked. If that check fails, revocation is attempted and the request returns github_error.

A nonempty permissions object is required. The Worker sends the requested object unchanged when every pair is allowed:

Workflow Job Events Permission slice
pr-review.yml review pull_request contents read, pull_requests write, issues read
pr-review.yml reply pull_request_review_comment, issue_comment contents read, pull_requests write, issues read
pr-scan.yml line-scan-report pull_request contents read, pull_requests write
pr-scan.yml osv-report pull_request pull_requests write
weekly-review.yml review schedule, workflow_dispatch contents read, issues write
fix-request.yml publish issue_comment, pull_request_review_comment contents write, pull_requests write, issues write
fix-issues.yml publish issues, workflow_dispatch contents write, pull_requests write, issues write
browser-flows.yml report pull_request contents read, pull_requests write
preview-flows.yml prepare, report pull_request contents read, pull_requests write, deployments read
settings-command.yml apply issue_comment contents write, pull_requests write, issues write

Other keys and levels are refused before any GitHub call. workflows: write is never issued through this endpoint. Only the automatic installation setup uses it inside the Worker. The setup page does not request it.

A successful response is HTTP 200 with Cache-Control: no-store:

{"token":"<installation token>","expires_at":"2026-11-23T10:00:00Z","repository":"octo-org/widgets","app_slug":"codehawk-app"}

Use the token until expires_at, then exchange a fresh OIDC token. Every OIDC jti can be admitted once. Request bodies are limited to 16 KiB.

actions/related-token is the workflow side of POST /v1/token/related. The PR review workflow calls it with the same OIDC requirements as actions/token. Request at most three distinct repositories under the calling repository's owner. Larger requests fail with too_many_repositories.

POST /v1/token/related
Authorization: Bearer <GitHub Actions OIDC token>
Content-Type: application/json
{"repository":"octo-org/widgets","repositories":["octo-org/lib"]}

Each related repository must belong to the caller's App installation and consent in its own .github/codehawk.json on its default branch:

{
"related_context": {
"allow": ["octo-org/widgets", "octo-org/*"]
}
}

Entries match full names or owner/*, ignoring case. Only the related repository's maintainers can grant this access. The Worker also reads both repositories' visibility through the installation-scoped repository API. A private related repository cannot share context with a public caller, whatever its consent file says. The refusal is private_to_public with message A private repository cannot share context with a public one. Caller-supplied visibility is never used.

A successful response is HTTP 200 with Cache-Control: no-store. The token grants contents: read on the allowed repositories only:

{"token":"<installation token>","expires_at":"2026-11-23T10:00:00Z","repository":"octo-org/widgets","allowed":["octo-org/lib"],"refused":[]}

When none is allowed, there is no returned token:

{"token":null,"expires_at":null,"repository":"octo-org/widgets","allowed":[],"refused":[{"repository":"octo-org/lib","reason":"not_allowed"}]}

The lists retain request order. Refusals are notices in the workflow log and unavailable repositories in the review summary.

Reason Meaning
other_owner The related repository has a different owner.
same_repository The caller named itself.
not_installed The related repository is outside the caller's App installation.
no_consent_file No .github/codehawk.json is available on its default branch.
invalid_consent_file The file cannot be decoded or has an invalid consent list.
not_allowed The consent list does not match the caller, or the setting is absent.
private_to_public A private repository cannot share context with a public one.

The Worker reads visibility and consent with an internal probe token that it revokes before answering, including on failure. That token also covers the caller for visibility and, on pull request events, the pull request head check. The returned token never covers the caller or refused repositories. Fork pull request events are refused like /v1/token, before reading consent. pull_request_target is refused too. An OIDC token is admitted once across both routes, and a related request counts in the same installation rate window. The action requests fresh OIDC for each attempt and uses the same single-retry rules as actions/token.

Both routes check the kill switch first, configuration next, then the bearer and body. /v1/token checks the static permission union before the IP limiter. The limiter runs before OIDC verification, followed by the event refusal, trusted release workflow and its event slice. Pull ref and repository checks precede key import. The Durable Object then claims the single-use OIDC id and reads its installation cache. Only a cache miss looks up the caller's installation. A negative hit refuses at once. The denylist comes before the installation rate count and token minting. Thus a replay makes no installation lookup, and a cached admission makes no GitHub API call before replay, denylist and rate checks.

The related route uses this same claim, cache, denylist and count order for repository A. It then checks the installations for the requested B names directly, mints its probe, checks the pull head, reads visibility and consent, and mints contents read on consenting names only. Every GitHub and JWKS fetch has a ten-second timeout.

TOKEN_IP_LIMITER allows 60 requests per 60 seconds per Cloudflare location, keyed by the runner address. Cloudflare's counts are approximate and eventually consistent. A refusal is ip_rate_limited with Retry-After: 60, before OIDC or crypto work. The Durable Object enforces a global per-installation limit of 60 admissions per 60 seconds. At most five token requests accompany each PR push, each retried at most once, so the window fits six fully retried pushes or twelve clean ones. Replies and fixes also consume admissions.

RATE_LIMIT_MAX accepts whole numbers from 1 to 1000, otherwise it falls back to 60. INSTALLATION_CACHE_SECONDS defaults to 300. Invalid values use 300 and zero disables both caches. Positive installation ids live for the configured period. Missing or suspended installations are cached for 60 seconds. Upstream failures are never cached. Lifecycle webhooks forget the cached installation at once.

Set CODEHAWK_DISABLED to exactly 1 to return service_paused before other token checks. Webhooks keep working while paused. Add installation ids to CODEHAWK_DENIED_INSTALLATIONS to return installation_denied before counting or minting. Both settings are vars changed by a reviewed commit. Both operations require no secret to be read or changed.

Reviews, model calls and browser flows run in your GitHub Actions jobs. Your model key stays with those jobs. The Worker verifies job identity, authenticates App webhooks and opens setup or settings pull requests. It uses temporary rate-limit and replay state, installation and setup bookkeeping, and short-lived login session records. See what token requests and webhooks retain and what setup sign-in retains for the specific fields and expiry rules.

One structured line is logged per request with msg, outcome, repository_id, installation_id, run_id and event_name when known. Related requests add the counts allowed and refused. Webhooks add event, action and delivery, plus queued and skipped counts for additions. Invocation logs are disabled. Workers Logs are kept for 7 days on Workers Paid.

The token guard stores single-use token ids with expiry, rate counters per installation, and the repository to installation cache with expiry. The setup queue also stores pending repository names and ids, as described below. The Worker never stores installation tokens, code or consent files. The setup page stores encrypted user tokens only for its short sessions, described below. Uninstalling the App drops the installation cache and pending setup work at once through its webhook. Logs exclude repository names, keys, tokens, payloads and upstream response details.

Every error is JSON with Cache-Control: no-store, for example {"error":"permissions_required","message":"Request a permissions object."}.

Code HTTP status Message
workflow_not_allowed 403 Tokens are issued only to Code Hawk's own reusable workflows at a release.
workflow_event_not_allowed 403 This Code Hawk workflow does not receive tokens for this event.
installation_denied 403 This installation may not use the hosted token service.
ip_rate_limited 429 Too many token requests from this address. Try again shortly.
permission_not_granted 403 The App installation has not granted the requested permissions. An owner must accept the App's permissions.
service_paused 503 The token service is paused. Try again later.
missing_token 401 Send the GitHub Actions OIDC token as a Bearer token.
invalid_token 401 The OIDC token is not valid.
token_expired 401 The OIDC token has expired.
token_not_yet_valid 401 The OIDC token is not valid yet.
invalid_claims 401 The OIDC token is missing claims Code Hawk needs.
invalid_request 400 The request body is not valid.
pull_requests_permission_required 400 Pull request events need pull_requests read or write.
permissions_required 400 Request a permissions object.
too_many_repositories 400 Request related context for at most 3 repositories.
permission_not_allowed 403 Requested permission is not allowed.
payload_too_large 413 The request body is too large.
repository_mismatch 403 A token is only issued for the repository the workflow runs in.
event_not_allowed 403 Tokens are not issued to pull_request_target workflows.
fork_pull_request 403 Tokens are not issued to pull requests from forks.
not_installed 403 The Code Hawk App is not installed on this repository.
replayed_token 409 This OIDC token has already been used.
rate_limited 429 Too many token requests for this installation. Try again shortly.
github_error 502 GitHub did not issue a token. Try again shortly.
not_configured 503 The token service is not configured.
invalid_signature 401 Webhook signature does not match.
hook_failed 500 The webhook could not be processed.
not_found 404 Not found.

rate_limited includes Retry-After in seconds. The default limit is 60 admissions per installation per fixed 60-second window. A rate-limited request consumes its OIDC jti, so retry with a fresh OIDC token after the wait.

POST /v1/webhook verifies the full raw request's HMAC signature with CODEHAWK_WEBHOOK_SECRET. Installation creation and repository addition bodies can be up to 25 MB (25,000,000 bytes). All other events keep the 1 MiB limit. The hosted account uses Workers Paid. Additions require a delivery id of 1 to 64 hex digits or hyphens. They read only the action and installation id, queue one repository listing job, and return HTTP 202 without a GitHub call. Repository lists from webhook bodies are ignored. A hook failure returns HTTP 500. A duplicate delivery returns handled: false and queues nothing.

Lifecycle deliveries for installation actions deleted, suspend, unsuspend and new_permissions_accepted, or installation_repositories action removed, forget the installation cache. Deletion and suspension also cancel pending installation setup. Removal cancels the named repository ids, including discoveries already in flight. These events retain outcome forgotten and return handled: true. Other valid deliveries, including ping, remain ignored.

One SQLite SetupQueue Durable Object, named global, lists repositories through GET /installation/repositories in pages of 100 inside alarms. Each page uses a metadata read token, revoked after the page. The webhook request never lists repositories. An hourly cron starts the global object if it has not received a webhook yet. Hourly alarms page through GET /app/installations and each installation's repositories to recover missed deliveries. The sweep skips repositories with any recorded outcome. An explicit repository addition can retry after the cooldown.

Each alarm performs one discovery page or one repository setup. At most three discovery pages run before a ready repository write, so a large sweep cannot starve setup. At most one repository is attempted per minute, with installation fairness. Large installs take about an hour per 60 repositories, plus time for discovery, retries and other queued installations. The first alarm is requested five seconds after enqueueing. Pausing keeps accepting signed deliveries but defers alarms by five minutes without GitHub calls. The installation denylist applies to discovery and repository setup.

Setup checks the repository id, state, default branch, existing settings, setup pull request and setup branch. It never overwrites existing settings or a branch without an open setup pull request, and never adds commits to an existing setup pull request automatically. It mints a token for one repository id with contents write, pull requests write and workflows write, then revokes it in a finally block. If workflows permission is unavailable or GitHub refuses the workflow path, it opens a settings-only pull request with the full workflow text to copy by hand. Git Data API writes omit author, committer and signature fields so GitHub can sign the commit as the App.

Our budget estimate is at most 23 GitHub subrequests and 8 content-creating requests per repository attempt. These are our own counts and assumptions for the two writer attempts, including the workflow refusal fallback, token mint and revocation. They are not a documented alarm allowance. One attempt per minute keeps our estimated content writes at 480 per hour, below GitHub's 500 per hour secondary limit. Discovery uses at most three subrequests per alarm and persists pagination between alarms. Rate limits block the whole queue for the supplied wait, clamped to one second through one hour. Other failures retry with exponential waits starting at 60 seconds and give up after five attempts.

Stored data Lifetime and use
Delivery id and received time 30 days for replay protection
Pending repository id, installation id, full name, times and attempts Until completion, cancellation or seven day expiry
Installation listing cursor, id, times, attempts and generation Until listing finishes, cancellation or seven day expiry
Completed repository id and finish time 24 hour cooldown
Repository ids with an outcome Retained so hourly sweeps do not repeat handled work, with no names
Removed repository ids by installation Until the next signed addition or installation cancellation, to stop in-flight discovery restoring removed jobs
Installation ids and last served times Retained for scheduling fairness
Sweep cursor, due time, retries, discovery count and pacing state Retained to resume alarms after eviction

Each finished or retried repository logs exactly { msg: "setup", outcome, installation_id, repository_id }. Outcomes include opened, opened_settings_only, repository skips, retry, rate_limited, gave_up and expired. Unexpected alarm or discovery errors log only { msg: "setup", outcome: "error" }. No repository name, owner, branch, token or upstream response body enters these lines.

GET / returns service, ok, configured, setup_configured and paused with Cache-Control: no-store, without importing the key or revealing settings. The hosted Worker answers on https://token.codehawk.app, the action default since v1.0.5. https://codehawk-token.borderlesstechnologysolutions.workers.dev stays a permanent alias for callers pinned to earlier releases.

CI uses these repository values:

Kind Name Value or purpose
Variable CLOUDFLARE_ACCOUNT_ID Target account, kept outside the repository
Secret CLOUDFLARE_API_TOKEN Worker deployment credentials
Variable CODEHAWK_WORKER_NAME codehawk-token
Variable CODEHAWK_APP_ID Numeric ID of codehawk-app
Secret CODEHAWK_APP_PRIVATE_KEY App RSA private key, PKCS#1 or PKCS#8 PEM
Secret CODEHAWK_WEBHOOK_SECRET App webhook signing secret

The deploy workflow runs on main only, verifies without secrets in a separate job, installs production dependencies in the deploy job, sets Worker secrets through standard input, and deploys to the CI-selected name. The custom domain comes from wrangler.jsonc. Production deploys are serialized without cancellation. The check workflow verifies Worker pull requests. The account ID and secret values are never committed. The first deployment and App webhook URL are set by the maintainer.

The site's Worker forwards /setup/api/* through a Service Binding to the token Worker's named SetupApi entrypoint. Named entrypoints are reachable only through Service Bindings, not through a public URL. The public token Worker returns 404 for setup paths. All setup requests use the site origin, with no CORS access.

Method Route Purpose
GET /setup/api/login Start GitHub sign-in with state and S256 PKCE
GET /setup/api/callback Exchange the code and start a fresh session
GET /setup/api/session Return the login and CSRF token
GET /setup/api/catalog Return the priced model lists, job names and secret names
GET /setup/api/repositories List installed repositories the user can write to
GET /setup/api/settings Read settings from the open setup pull request or default branch
POST /setup/api/settings Open or update a settings pull request
POST /setup/api/logout Delete the session and revoke its user token

The __Host-codehawk-login cookie is Secure, HttpOnly, SameSite=Lax, with a ten minute lifetime. The __Host-codehawk-session cookie is Secure, HttpOnly, SameSite=Strict, with a 60 minute lifetime. Both use Path=/ and have no Domain. Their values are random identifiers. A session expires after 20 minutes idle, or 60 minutes from sign-in, whichever comes first. Browser storage holds no settings or tokens.

SetupSession Durable Objects store pending state and PKCE verifiers for ten minutes. Session records hold an AES-256-GCM encrypted user token, IV, hashed object name, login, numeric user ID, CSRF token, expiry and last-seen time, plus a save count. The encryption authenticates the object name. Records are deleted on logout or expiry. GitHub refresh tokens are discarded. The user token is used only to read identity, installations, repository lists and current write access. Logout and expiry revoke it through GitHub's application token endpoint. Revocation failure leaves the token unknown to the Worker and it expires at GitHub after eight hours.

Reads use a short-lived installation token with contents read and pull requests read for one repository. Saves recheck user access, then use contents write and pull requests write for that repository. Both tokens are revoked after use, including failed saves. The setup page never requests workflows permission. Legacy .github/codereview-hawk.json settings are read when the current file is absent. Saving adds the current filename and deletes the legacy filename in one commit.

State changes require a matching Origin, same-origin fetch metadata when present, JSON and a session CSRF token. Bodies are limited to 16 KiB. Each session allows ten saves per hour, with an additional setup IP limit of 60 requests per minute. Rate-limit responses include Retry-After: 60. Every setup response is no-store. The setup page has a separate content security policy that permits only its own scripts and styles.

Each setup request logs only msg: "setup", route, outcome and, when known, installation_id. Alarms log route alarm and outcome expired. Logs contain no login, user ID, repository name, token, code, state, cookie or upstream response body.

The token Worker adds vars CODEHAWK_APP_CLIENT_ID and SETUP_ORIGINS, secrets CODEHAWK_APP_CLIENT_SECRET and CODEHAWK_SESSION_KEY, a SETUP_SESSION Durable Object binding and the SETUP_IP_LIMITER rate limit binding. The session key is 32 random bytes in standard base64. CI reads the two secrets from repository secrets and sends them to Wrangler through standard input. The site holds no secrets. setup_configured is true only with a valid client ID, nonempty client secret, valid 32-byte session key and an allowed HTTPS origin list.