Skip to content

feat: sign in with a ChatGPT account - #38

Merged
fylorn merged 1 commit into
mainfrom
feat/chatgpt-login
Sep 17, 2026
Merged

fylorn merged 1 commit into
mainfrom
feat/chatgpt-login

Conversation

@fylorn

@fylorn fylorn commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Summary

A ChatGPT subscription becomes an upstream like any other. The user signs in once in the browser, and the credentials go into config.yaml alongside every other provider.

This is phase 3 of the ChatGPT account work. Phase 1 (header credentials) shipped in v0.3.0 and phase 2 (any-to-any conversion) in v0.4.0. The desktop UI comes in phase 4.

Login (control plane)

Endpoint Purpose
POST /chatgpt/login Start OAuth authorization code + PKCE and return the authorize URL
GET /chatgpt/login/{id} Login status: pending / done / failed / expired / cancelled
DELETE /chatgpt/login/{id} Cancel

Callback

  • core waits for the browser on 127.0.0.1:1455, falling back to :1457. These are the redirect URIs registered for the Codex OAuth client. OpenAI does not offer third-party client registration.
  • The code is exchanged through the proxy the user picked.
  • The provider is written with:
    • protocol: chatgpt
    • refresh token, access token and expiry
    • the ChatGPT-Account-Id header
    • billing: subscription

Re-login and hand-back

  • Signing in again replaces only the credentials. Proxy, model scope and the other settings stay.
  • return_to lets the callback page hand back to the app (thinkwatch://…). Web URLs are refused, so this cannot become an open redirect.

Robustness

  • A callback with the wrong state is ignored, and the login keeps waiting.
  • A duplicate callback exchanges the code only once.
  • The port is released as soon as the login settles, or after 15 minutes.
  • LoginFinished is emitted, so the UI does not need to poll.

Revoke on delete

  • Deleting a signed-in provider revokes its refresh token.
  • Revocation is skipped if another provider still uses the same token, e.g. a duplicated provider.

Usage and rate-limit reset credits

  • GET /providers/{name}/chatgpt/usage returns the plan, quota windows and the number of available reset credits. The same backend response also carries the email and user ID; those are not passed on.
  • GET /providers/{name}/chatgpt/resets lists the reset credits.
  • POST /providers/{name}/chatgpt/resets consumes one.
    • It requires an idempotency key and only runs on an explicit request. The gateway never spends a credit on its own.
    • Credits are scarce and cannot be refunded, so every test runs against a local fake backend.
  • These calls identify honestly too, and get one token renewal on a 401.

Gateway

Identity

  • Requests identify as ThinkWatch: originator, user agent, session ID.
  • Identity headers cannot be set in config, and the client's own are not forwarded.
  • This was verified live on 2026-09-18: the backend accepts honest identification.

Request and response shape

  • The backend only streams and rejects max_output_tokens, so requests are shaped to match.
  • A client that asked for a whole response gets one collected from the stream.
  • The stream has no Content-Type, so successful responses are marked as SSE.
  • This also fixes a general bug: converted streams were sent to non-streaming clients labelled application/json.

OAuth

  • A 401 from any OAuth upstream gets one fresh token and one retry.
    • Exception: a token obtained within the last minute is not renewed again. Otherwise an account-level 401 would rotate the refresh token on every request.
  • Refreshes are single-flight per provider, because rotated refresh tokens are single-use.
  • Access tokens and their expiry are written back to config.yaml on every renewal. A restart reuses them instead of rotating the refresh token.

Events and quota

  • CredentialExpired and QuotaExhausted are emitted once per transition. They are the inputs for desktop notifications.
  • Codex quota windows are named from window-minutes, and zero-length windows are skipped.
  • Models come from /models?client_version=….

Test plan

  • cargo fmt --all -- --check
  • cargo clippy --workspace --all-targets -- -D warnings
  • cargo test --workspace --no-fail-fast
    • tw-gateway/tests/chatgpt.rs (8): identity, whole-response collection, 401 retry, no refresh storm, single-flight, revoked login, quota exhaustion, models
    • tw-control/tests/chatgpt.rs (14):
      • login end to end against a fake OpenAI: PKCE, config write, hand-back, model fetch
      • state mismatch, denial and rejected code
      • duplicate callback and port release
      • re-login, superseding and cancel
      • usage without personal details, token renewal on 401
      • reset credits: list, validation, consume
      • revoke on delete and shared-token skip
  • ./scripts/smoke.sh: 48 passed, 0 failed. Memory is 34 MB against a 30 MB target, which the script reports as over target but not a regression.

🤖 Generated with Claude Code

A ChatGPT subscription becomes an upstream like any other: sign in once in
the browser, and the credentials land in config.yaml next to every other
provider.

Login (control plane)
- POST /chatgpt/login starts an OAuth authorization-code + PKCE flow and
  waits for the browser on 127.0.0.1:1455 (or 1457), the redirect URIs
  registered for the Codex client. GET/DELETE /chatgpt/login/{id} report or
  cancel it; LoginFinished is emitted when it settles.
- The callback exchanges the code through the chosen proxy and writes the
  provider: protocol chatgpt, refresh + access token + expiry, the account
  ID header, subscription billing. Signing in again replaces only the
  credentials. The page can hand back to the app through an app-scheme
  return_to; web URLs are refused so it cannot be an open redirect.
- A callback with the wrong state is ignored, duplicates exchange the code
  once, and the callback port is released as soon as the login settles.
- Deleting a signed-in provider revokes its refresh token, unless another
  provider still uses the same one.

Usage and rate-limit reset credits
- GET /providers/{name}/chatgpt/usage returns plan, windows and the number
  of reset credits, without the email or user ID in the same response.
- GET/POST /providers/{name}/chatgpt/resets lists and consumes reset
  credits. Consuming requires an idempotency key and only happens on an
  explicit request; the gateway never spends one on its own.

Gateway
- Requests identify as ThinkWatch (originator, user agent, session ID);
  identity headers are not configurable and the client's are not forwarded.
- The backend only streams and rejects max_output_tokens: requests are
  shaped accordingly, and a client that asked for a whole response gets one
  collected from the stream. The stream has no Content-Type, so success
  responses are marked as SSE. This also fixes converted streams being sent
  as application/json to non-streaming clients.
- A 401 from an OAuth upstream gets one fresh token and one retry, unless
  the token was obtained within the last minute. Refreshes are single-flight
  per provider, since rotated refresh tokens are single-use.
- Access tokens and their expiry are persisted to config.yaml on every
  renewal, so a restart reuses them instead of rotating the refresh token.
- CredentialExpired and QuotaExhausted are emitted once per transition.
  Codex quota windows are named from window-minutes; zero-length windows
  are skipped. Models come from /models?client_version.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown

Thanks for the PR. One thing before review: this targets main, and it should target dev.

main is a release-only line — branch-protected, linear history, and every commit on it is a tagged release snapshot. Routine work lands on dev and reaches main with the next release. GitHub pre-filled main here because it is the default branch, so this is our defaults being unhelpful rather than anything you did wrong.

No need to close and reopen: click Edit next to the PR title and change the base branch to dev. The commits and the discussion carry over.

See CONTRIBUTING.md and CONTRIBUTING.md for the branch contract.

@fylorn
fylorn merged commit 53692ff into main Sep 17, 2026
2 checks passed
@fylorn
fylorn deleted the feat/chatgpt-login branch September 17, 2026 18:01
@fylorn fylorn mentioned this pull request Sep 17, 2026
fylorn added a commit that referenced this pull request Sep 17, 2026
Sign in with a ChatGPT account (#38) is the release's headline: the
subscription becomes an upstream like any other.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant