docs/pkg/oauth.md
pkg/oauth: Sign in with ChatGPT
This package owns the SIWC loopback authorization flow, OIDC verification, credential values, renewal, and remote revocation. It returns staged values; it does not read configuration or persist credentials. Account selection, user-global host identity, consent UI, and protected fresh-read/merge/write persistence belong to service configuration and the configurator. Inference and authenticated model discovery are separate consumers, not login steps.
Public interface and stored values
| 1 | LoginOpenAIChatGPT(ctx context.Context, options ChatGPTLoginOptions) (*OAuthCredentials, error) |
| 2 | RefreshOpenAIChatGPT(ctx context.Context, credentials *OAuthCredentials) (*OAuthCredentials, error) |
| 3 | RevokeOpenAIChatGPT(ctx context.Context, credentials *OAuthCredentials) error |
ChatGPTLoginOptions contains HostID string, Previous *OAuthCredentials,
BackgroundAuthorized bool, OpenBrowser func(string) error, and the additive
PresentHandoff func(ChatGPTHandoff) error option. The existing login and browser
hook signatures are unchanged. ChatGPTHandoff contains AuthorizationURL string
and SubmitCallback func(string) error.
Previous is the selected validated registration, including a signed-out
registration whose tokens were cleared. A partial or legacy record is not
silently upgraded. The browser hook must return promptly and never log its
URL or put it in errors. Login cancellation closes its listener even if the
hook has not returned. The caller owns the hook's process/goroutine lifetime.
When PresentHandoff is provided it replaces automatic browser opening, so
OpenBrowser may be nil. The presenter must return promptly, show the link only
in a private interaction, and never put it in logs or errors. Automatic display
stays temporary. The configurator's explicit Show link action can leave the
hint-free URL in private terminal scrollback, with a retention warning; it does
not export credentials or callback input. Its bounded,
concurrency-safe submit function accepts the full callback URL without fetching
or navigating it. Clear in-memory link and input state when the interaction ends.
At the five-minute deadline, login stops waiting and invalidates the listener
and submit callback. It does not interrupt a blocked hook; the caller owns hook
lifetime. The configurator separately bounds its terminal selection wait by the
attempt context.
The canonical token fields are Access, Refresh, and Expires, with YAML
keys access, refresh, and expires. Expiry remains Unix epoch milliseconds.
SIWC identity and permission fields have explicit YAML names:
| Go field | YAML key | Meaning |
|---|---|---|
ClientID | client_id | Issued registration, never dynamic_agent_client |
Issuer | issuer | Verified https://auth.openai.com |
Subject | subject | Verified ID-token subject |
Email | email | Optional display hint, not an account/workspace key |
IDToken | id_token | Verified retained identity token, not an inference bearer |
TokenType | token_type | Bearer token type |
Scopes []string | scopes | Actual token-response permissions |
BackgroundAuthorized | background_authorized | Caller-provided affirmative local authorization |
ConsentVersion | consent_version | 1 when locally accepted, otherwise 0 on login |
SessionID | session_id | Fresh random ID per validated login; unchanged by renewal |
Login and renewal use verified SIWC identity, not decoded Codex account claims. No legacy account-ID field or account-header request path remains.
RegistrationKey()hashes the issued client ID and verified issuer/subject with unambiguous encoding. It returns an empty string for incomplete/legacy records. It is safe as a lock/cache filename component and never keys by email.UsableSubscription()requires a complete renewable SIWC session, bearer type, positive expiry, direct-plan and resource-invoke scopes, and local acceptance at version 1. An expired access token can still belong to a renewable session. Always checkNeedsRefresh()before using the bearer.NeedsRefresh()uses a one-minute expiry margin and treats unknown expiry as needing refresh. Retained ID-token expiry does not end the renewable session.
All entrypoints leave caller records untouched, on both success and failure. Do not mutate records concurrently with these calls. Publish the returned record only after validation and successful protected persistence.
Authorization and identity validation
Login has a five-minute overall bound, shortened by its context. It binds only
127.0.0.1 before opening the browser or presenting a handoff, with a dynamically allocated port and
stable /auth/callback path. Every authorization generates independent random
state, nonce, and a 256-bit PKCE verifier with S256. The code exchange uses the
exact callback URI used in that attempt.
The authorization endpoint is
https://auth.openai.com/api/accounts/authorize. Initial registration uses
client_id=dynamic_agent_client, agent_name_hint=EzAgent, and the stable
ext_agent_host_id. Returning authorization uses the issued ID, omits the
name hint. Private browser-only callers may send retained ID-token/email hints.
Every handoff URL is constructed without both id_token_hint and login_hint,
including returning login; no hint-bearing URL is handed to a display sanitizer.
Returning issuer/subject/client-ID ownership checks are unchanged.
Explicit plan enablement with previously missing direct-plan scope
uses prompt=consent; ordinary returning sign-in does not force consent.
force_reconsent is not sent.
The requested scopes are
openid profile email offline_access resource.invoke chatgpt.tokens.use.direct,
with resource=https://api.openai.com/v1. Host identity must come from the
runtime's persisted user-global configuration, never a project override.
UUIDv4 URIs are validated; the published JWK-thumbprint and did:key identifier
prefixes are also accepted. No host keys are generated or interpreted here.
Host identity is an opaque identifier, not proof of key possession.
The callback checks the exact host, method, path, bounded query, unique parameters, and constant-time state match, including on denial. A matching state is consumed once. New registration requires an issued client ID; returning callbacks may omit it but cannot replace it. OAuth errors are handled before code exchange. Browser responses are fixed generic HTML, with no provider prose or hints reflected. Header/read/write/idle timeouts and an 8-KiB header setting bound the HTTP server. Completion, cancellation, and expiry close the listener and spare connections, including partial requests.
HTTP and manual callback intake share one validator, one mutex-protected atomic
consumption guard, and one terminal result channel. Manual input is bounded to
16 KiB before parsing. It must be the complete pending
http://127.0.0.1:PORT/auth/callback URL, with the exact scheme, host, port and
path, no userinfo, fragment, opaque URL or controls. Bare codes, tokens and
authorization URLs are rejected. Queries are bounded to 8 KiB; authorization
codes to 4096 bytes. Malformed encoding and duplicate parameters are rejected.
Invalid addresses or states do not consume the transaction. Matching-state
denial consumes without exchange; malformed terminal code/client data consumes
once too. HTTP/paste races and replays can produce at most one exchange/result.
Cancellation, expiry, consumption and a fresh generation invalidate old submit
callbacks. The listener and spare connections close before token exchange waits.
Code exchange is a form POST to
https://auth.openai.com/api/accounts/oauth/token with the issued client ID,
code, original verifier, exact redirect URI, and API resource. A code-exchange
invalid_grant triggers at most one fresh authorization, retaining the
issued ID within the staged attempt and regenerating state/nonce/PKCE. The
presenter receives a new link and submit function without resetting the total
five-minute deadline. The failed code itself is never retried. Other exchange
failures return to the caller.
github.com/coreos/go-oidc/v3 verifies RS256 signatures using trusted discovery
and JWKS. The implementation checks discovery's issuer and canonical authorize,
token, revocation, and JWKS endpoints before using them. It verifies audience
against the issued client ID, expiry, nonce, and a nonempty valid subject. ID
tokens must also contain a non-null numeric iat greater than zero and before
expiry; fractional NumericDate seconds are accepted. This explicit check follows
the website verification example
referenced by OSS sign-in, since go-oidc does not require that claim's presence.
Returning login must match the selected issuer/subject before replacing values.
Equal email addresses do not merge registrations or workspaces.
Successful token responses require nonempty valid access and replacement
refresh tokens, bearer type, a nonempty syntactically valid granted scope set,
and positive integer expires_in bounded to one day to prevent overflow and
unbounded sessions. Login also requires a verified ID token. A valid signed-in
identity without direct-plan permission is returned but cannot enable inference.
The caller's local acceptance cannot grant missing service-side scope.
Renewal, errors, and sign-out
Renewal is bounded to 30 seconds. It loads and validates discovery before sending
the rotating token, so a discovery outage cannot discard a successful rotation.
It sends the issued client ID, rotating
refresh token, and API resource, with no scope. Access, replacement refresh,
expiry, token type, and granted scopes are returned together. Missing replacement
refresh tokens fail closed; the legacy fallback is gone. Reduced granted
permission disables inference. If renewal returns an ID token, it is signature,
issuer, audience, expiry, issued-at, and account checked without inventing a new
authorization nonce. The successful response stays staged during at most three
verification attempts with backoff inside the same overall bound. These attempts
share one verifier and its JWKS cache, and never repeat the refresh POST. Otherwise
the prior validated identity hint is retained.
OAuthError exposes Operation, HTTP Status, independently allowlisted Code
and ErrorReason, and safe RequestID metadata from the X-Request-ID response
header. Request IDs must be a single value of at most 128 ASCII letters, digits,
underscores, or hyphens. Unsafe IDs, unknown codes/reasons, provider prose, raw
bodies, redirect targets, and browser-hook errors are excluded. Recognized reasons
are refresh_token_invalidated, refresh_token_reused, refresh_token_expired,
invalid_refresh_token, and token_expired. Reasons are diagnostic labels only;
they do not change retry or credential-clearing decisions. A refresh invalid_grant fails the current request without
clearing credentials, account selection, or local authorization. It does not
prove the saved token set is unusable. There is no immediate automatic retry;
a later request or explicit discovery refresh can try renewal again with the
saved token set. Persistent rejection may still require a new sign-in.
RequiresReauthorization() is true for explicit refresh-token errors
invalid_refresh_token, token_expired,
refresh_token_expired, refresh_token_invalidated, and refresh_token_reused.
The persistence owner must clear unusable access/refresh/ID tokens and session ID
while retaining the registration. invalid_client instead requires fixing
client configuration. Retryable() identifies transport failures and temporary
HTTP statuses outside rotating token-refresh POSTs. Token-refresh failures never
allow an immediate automatic replay, even after a transport drop or temporary
status, because submission may already have consumed the saved token. Safe
pre-submission discovery can be retried with a bound. A lost provider response
cannot be recovered without server support; preserve saved credentials and
report the failure without disabling a later deliberate retry.
A successful rotation whose response cannot be read or validated returns
the local code refresh_response_invalid, with Retryable() false and
RequiresReauthorization() true. This includes exhausted JWKS verification,
account mismatch, invalid required claims, and cancellation after rotation.
The old refresh token may already be consumed; clear the token set and sign in
with the saved registration rather than retrying it. This local code is not
accepted as an upstream OAuth code. Cancellation/deadline errors before rotation
support errors.Is. Diagnostics never expose the failed response or identity.
Remote sign-out uses the revocation endpoint confirmed by
https://auth.openai.com/.well-known/openid-configuration. It sends a form POST
with refresh token, token_type_hint=refresh_token, and the issued client_id.
An empty HTTP 200 confirms revocation. Network/temporary failures receive at most
three attempts with backoff, all inside a 30-second bound. This function does not
clear local records. The sign-out owner must stop requests, attempt revocation,
then clear local access/refresh/ID tokens and session ID regardless of the remote
result. Retain the registration and runtime host ID. If revocation is unconfirmed,
report that fact and direct the user to disconnect the app in ChatGPT Settings.
Transport and persistence safety
All OAuth, discovery, and JWKS operations use a dedicated direct client that
ignores environment proxies. It rejects all redirects, including credential-replaying
307/308 responses, and preserves normal certificate and hostname verification.
Each request has 30-second overall, 10-second dial/TLS, and 15-second response-header
bounds. Every response body, including discovery/JWKS and error bodies, is capped
at 64 KiB. Access/refresh tokens stay in POST bodies, never URLs. ID-token hints
are sent only to the authorization endpoint; those URLs are sensitive.
Rotating token-refresh POSTs have no GetBody, preventing internal HTTP/2 body
replay. Ordinary discovery and idempotent revocation retain their existing policy.
internal/privatefile.WithLock(ctx, path, fn) supplies cancellable cross-process
advisory locking on a durable protected lock file. It also serializes goroutines
using the same canonical path, without holding registry bookkeeping locks over
callbacks or network waits. Unix locks use owner-only regular nonsymlink,
singly-linked files in owner-controlled nonsymlink parent directories. Windows
uses protected owner-only DACLs, validates owner/reparse points, and denies delete
sharing while the lock is open. Kernel locks release on process exit. Never remove
or atomically replace lock files: doing so can split waiters across file identities.
All cooperating writers must agree on the paths; recursive use of the same lock
is unsupported. The callback itself must honor the context.
The persistence owner must implement this ordering:
- Take the registration/session refresh lock and reread the current record. Skip renewal if another process already renewed it. Never refresh a signed-out or replaced session snapshot.
- Check the initiating request's cancellation after the locked reread. Once renewal starts, own refresh and validation under a bounded independent context without holding the shared auth-file mutation lock. Request cancellation must not interrupt delivery of a consumed token's replacement.
- Take the separate short mutation lock, reread/merge current disk contents, and confirm the registration/session is still current before committing the entire new token set with the existing private atomic write. Persist a validated rotation under a bounded context independent of request cancellation. The old refresh token may already be consumed. Preserve current withdrawn authorization, then reject canceled request admission.
- All other writers, including configurator save, local acceptance, account selection, and sign-out, use that same short fresh-read/merge/write lock. Sign-out/replacement must prevent a late refresh from restoring tokens.
These entrypoints deliberately cannot perform persistence coordination themselves: they have no auth-file path or current-record loader. No global network lock or leaf-local token cache is introduced here. Persistence failures must reach the user. The daemon drains its owned subscription resolutions during graceful close. Renewal logs focus on failures at refresh, session validation, persistence, or cleanup. Refresh failures include sanitized OAuth operation, status, code/reason, and response-header request ID when available. No routine success or per-request trace is retained. Read failures and post-200 validation failures do not retain request IDs. This does not recover a truly lost network response or protect against a hard process kill, and does not establish the cause of past renewal failures.
Observed renewal rejection included HTTP 400 invalid_grant with
error_reason=refresh_token_invalidated. The cause remains unproved. Later user
reports of working automatic renewal after account-wide revocation are not
validation of a client-side fix or a guarantee that website logout resolves it.
Current implementation and evidence
Only the SIWC flow is implemented. The dead exported LoginOpenAICodex,
RefreshOpenAICodex, CodexAPIEndpoint, DeviceVerificationURL,
SupportsCodexModel, and OAuthUI were removed, along with
OAuthCredentials.AccountID and its unused IsExpired method. Use
LoginOpenAIChatGPT, RefreshOpenAIChatGPT, and NeedsRefresh instead.
Old auth YAML is detected for reconnection, never parsed into a usable legacy
token set. Model membership comes from authenticated discovery, not an allowlist.
No OpenAI SDK or SIWC DevKit is included. Go JSONL client signatures and Ruby
addon constructors, function arguments, and callbacks are unchanged.
Implementation references checked against published pages and discovery:
sign-in,
accounts/sessions,
token reference,
errors/recovery,
host identity, and
OpenID discovery.
OpenAI's devkit interprets numeric earliest_refresh_at as Unix seconds. This
implementation does not use it or change its existing one-minute expiry margin;
the observed failures do not establish a scheduling-policy fix.
Focused offline tests cover credential/YAML compatibility, listener-first PKCE, returning registration/account checks, callback/state/denial handling, cancellation and spare connections, OIDC signature/claim/key-rotation failures, scope/consent checks, strict token responses, renewal rotation and reduced permission, remote revocation/backoff, redaction, transport bounds/TLS/proxy/redirect rules, and private-file exclusion across goroutines and processes. Manual fixtures also cover new/returning hint-free login, HTTP/paste races, duplicate/replayed/denied callbacks, strict URI and input bounds, cancellation/expiry, spare connections, and the single fresh invalid-grant generation. These fixtures do not prove live OpenAI acceptance. Live sign-in and provider testing require separate user authorization and the normal integration review.
Software rights, privacy, and authorized use
EzAgent is licensed under BSD 2-Clause. That license grants rights to the software; it does not itself grant authorization to access OpenAI services or use any account, authentication credentials, or ChatGPT plan. Authorization comes separately from OpenAI and the relevant account holder. OpenAI's applicable terms govern that access independently of EzAgent's software license. This notice adds no conditions or restrictions to BSD 2-Clause. An independently operated non-OpenAI service has its own access requirements.
EzAgent is a free, open-source, single-user application, not an operator-hosted service. The real loop and credentials remain on the initial user-controlled runtime device. Personal containers and VMs remain user-controlled compute; accessing that instance from another device does not turn it into a shared hosted product. The current remote connector does not move inference or credentials.
Subscription requests must serve the authenticated user's activity or expressly authorized automation. User-owned tools, plugins, Ruby components, and helpers can participate in that workflow. Addons must not use the grant for another person, pool/share accounts or tokens, bypass usage limits, or expose a general-purpose subscription API to unrelated products. Passing a request through the central loop is not proof that an unrelated product is part of EzAgent. Future products need appropriate authorization under their own application identity. These are service-access obligations, not extra BSD restrictions.
The configurator presents its privacy notice before browser sign-in and obtains affirmative background authorization. Necessary account identity and credentials are processed locally. Selected conversation context, source content, attachments, and tool results are sent to OpenAI for inference; configured external services may process their own inputs. This flow does not fetch ChatGPT conversation history or unrelated account context. EzAgent archives conversations locally until the user deletes them or authorizes deletion. Deleting local history does not promise deletion of backups or external service records. Stop running work with Abort, or stop the daemon, before withdrawing authorization or signing out. The provider also observes withdrawal/sign-out during admitted inference through protected local reads and cancels affected requests. Other sessions remain independent. See configurator controls.
Security reporting
Keep credentials, ID-token hints, unnecessary personal data, and authorization URLs out of public issues, logs, and support transcripts. Maintainers should privately triage a reported EzAgent/SIWC vulnerability, contain affected use, coordinate a fix and disclosure, and retain only the details needed to investigate. SIWC Terms section 3 requires promptly contacting OpenAI with details of a vulnerability or breach that may affect users. Source availability is not a substitute for this obligation.
Use OpenAI's official coordinated vulnerability disclosure policy
and its linked Bugcrowd reporting channel for eligible
vulnerability reports. For a security incident, that policy directs reporters to
OpenAI's current encrypted-report contact instructions.
Check the current contact and encryption key in a browser before sending an
incident report. Automated fetching of security.txt was blocked during this
implementation, so no email address or key is copied here. Follow the published
scope and authorization rules; do not conduct unapproved testing or invent a
reporting deadline.
Provider release gates
The configurator implements manual completion of this authorization-code/PKCE native flow for SSH, Docker and phone use. Its compact dialog prioritizes Copy link through OSC 52, with an explicit Show link fallback on the normal terminal screen, plus a masked full-callback input and manual Finish action. QR is removed. A remote browser may end at an unreachable loopback page; the user privately copies that full returned address back to the pending configurator. This is an EzAgent interaction, not a new OpenAI device flow or a claim that OpenAI documents pasted callbacks. Phone browsers may not expose failed redirects. OpenAI's VM registration-transfer procedure is a different path and is not implemented; credentials remain on the runtime.
Login validation, its welcome, and connection status make no inference request.
subscription_sharing_usage_limit_exceeded belongs to inference admission, not
sign-in. It does not clear valid credentials, granted scopes or local consent.
A later new admission can recheck OpenAI with the same valid login. /usage is a
read-only usage/source view and Manage usage link, not a quota-data API.
Fresh user browser sign-in, cross-device full-address return, phone address-bar availability, terminal clipboard/Show link behavior, returning account recognition, declined plan scope, local consent, first-use confirmation, usage navigation, narrow-terminal display, and sign-out need manual acceptance. Credentials should be consumed only through the normal protected-file workflow, never pasted into review chat.
The provider reference describes
the bounded public Responses, multi-call, and WebSocket continuation checks.
API-key and subscription routes share one encoder and transport implementation.
Both prefer WebSocket with HTTP/SSE fallback or explicit opt-out. All requests
use store:false; continuation references stay within the same authenticated
connection, and reconnects send full history. Harness instructions use developer
messages on both routes. Subscription authorization and usage checks remain
separate; subscriptions never send max_output_tokens. No offline fixture proves
live acceptance.
Browser transaction ownership includes the selected provider registration and selection generation, not only the returning account's token session. The configurator stages both before authorization and compares them at commit for new and returning logins. Newer selection/login, withdrawal, sign-out, or session replacement rejects the stale transaction. A validated but uncommitted session receives a bounded revocation attempt without changing the newer local selection; a currently committed token set is never treated as abandoned.
Sign-out withdraws local authorization before waiting for the refresh/session lock. Renewal can still save its replacement token while preserving the withdrawal, but cannot admit it for inference. Sign-out then checks the still-current provider generation and session, rereads the latest token and clears locally before remote revocation. Changed selection is a conflict, not a claim that a newly selected account was signed out. See credential ownership and bounded inference recovery.