DEV Community

loginwith.ai
loginwith.ai

Posted on Originally published at loginwith.ai

Sign in with ChatGPT in a Python CLI: use the user's ChatGPT plan, no API key

Originally published at loginwith.ai.

Open-source and local apps can use Sign in with ChatGPT today, without approval, a client secret or a partner API key. Users sign in with their ChatGPT account, and your app's AI requests count toward their ChatGPT plan instead of your API bill. This is how OpenCode, Pi and OpenClaw work.

This post is one Python script that does the whole flow: first sign-in, saving credentials, refreshing them, and streaming a response. It follows OpenAI's open-source sign-in docs and models and inference docs. For the full error table, see our developer guide.

The open-source path is meant for apps that run on the user's own machine or self-hosted VM. Paid or remotely hosted apps use the partner path (Express, FastAPI).

How the flow differs from a website

  • No client ID up front. The first sign-in sends client_id=dynamic_agent_client plus your app's name in agent_name_hint. The user names and approves the app, and the callback returns an issued client_id (oaiapp_…). Save it and use it from then on.
  • A host ID. Each machine sends its own stable ext_agent_host_id, generated once and reused.
  • A loopback callback. The redirect goes to http://127.0.0.1:<port>/auth/callback. Only the port may change between sign-ins, and never use localhost.
  • Plan-usage scopes. offline_access resource.invoke chatgpt.tokens.use.direct, with resource=https://api.openai.com/v1.

The script

pip install "pyjwt[crypto]" openai, then save this as chatgpt_cli.py:

#!/usr/bin/env python3
"""Sign in with ChatGPT for a local app, then answer a prompt on the user's ChatGPT plan."""
import base64
import hashlib
import json
import os
import secrets
import sys
import time
import uuid
import webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import parse_qs, urlencode, urlparse
from urllib.request import Request, urlopen

import jwt
from openai import OpenAI

APP_NAME = "My Agent"  # your app's real name, the same on every install
DIR = Path.home() / ".config" / "my-agent"
CREDS = DIR / "chatgpt.json"

ISSUER = "https://auth.openai.com"
AUTHORIZE = f"{ISSUER}/api/accounts/authorize"
TOKEN = f"{ISSUER}/api/accounts/oauth/token"
JWKS = jwt.PyJWKClient(f"{ISSUER}/.well-known/jwks.json")
RESOURCE = "https://api.openai.com/v1"
SCOPE = "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct"
REFRESH_DEAD = {"invalid_grant", "invalid_refresh_token", "token_expired",
                "refresh_token_expired", "refresh_token_invalidated", "refresh_token_reused"}


def b64url(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()


def save(path: Path, text: str) -> None:
    """Atomic write, owner-only (0600)."""
    DIR.mkdir(parents=True, exist_ok=True, mode=0o700)
    tmp = path.with_suffix(".tmp")
    with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
        f.write(text)
    os.replace(tmp, path)


def host_id() -> str:
    path = DIR / "host-id"
    if not path.exists():
        save(path, f"urn:uuid:{uuid.uuid4()}")
    return path.read_text().strip()


def post_form(url: str, data: dict) -> dict:
    req = Request(url, data=urlencode(data).encode(),
                  headers={"content-type": "application/x-www-form-urlencoded"})
    with urlopen(req) as res:
        return json.load(res)


def wait_for_callback(server: HTTPServer) -> dict:
    result: dict = {}

    class Handler(BaseHTTPRequestHandler):
        def do_GET(self):
            url = urlparse(self.path)
            if url.path != "/auth/callback":
                self.send_error(404)
                return
            result.update({k: v[0] for k, v in parse_qs(url.query).items()})
            self.send_response(200)
            self.send_header("content-type", "text/plain")
            self.end_headers()
            self.wfile.write(b"Signed in. You can close this tab.")

        def log_message(self, *args):
            pass

    server.RequestHandlerClass = Handler
    while not result:
        server.handle_request()
    return result


def sign_in(saved: dict | None = None) -> dict:
    """First sign-in (saved=None) registers the app; later ones reuse the issued client_id."""
    state, nonce, verifier = (secrets.token_urlsafe(32) for _ in range(3))
    server = HTTPServer(("127.0.0.1", 0), BaseHTTPRequestHandler)  # listen before opening the browser
    redirect_uri = f"http://127.0.0.1:{server.server_port}/auth/callback"
    params = {
        "client_id": saved["client_id"] if saved else "dynamic_agent_client",
        "ext_agent_host_id": host_id(),
        "response_type": "code",
        "redirect_uri": redirect_uri,
        "scope": SCOPE,
        "resource": RESOURCE,
        "state": state,
        "nonce": nonce,
        "code_challenge": b64url(hashlib.sha256(verifier.encode()).digest()),
        "code_challenge_method": "S256",
    }
    if saved:
        params["id_token_hint"] = saved["id_token"]  # same ChatGPT account as before
    else:
        params["agent_name_hint"] = APP_NAME
    url = f"{AUTHORIZE}?{urlencode(params)}"
    print(f"Sign in with ChatGPT in your browser. If it didn't open, visit:\n{url}")
    webbrowser.open(url)
    cb = wait_for_callback(server)
    server.server_close()

    if not secrets.compare_digest(cb.get("state", ""), state):
        sys.exit("Invalid state")
    if "error" in cb:
        sys.exit(f"Sign-in failed: {cb['error']}")
    client_id = saved["client_id"] if saved else cb.get("client_id")
    if not client_id or cb.get("client_id", client_id) != client_id:
        sys.exit("Missing or unexpected client_id")

    tokens = post_form(TOKEN, {
        "grant_type": "authorization_code",
        "client_id": client_id,  # the issued ID, never dynamic_agent_client
        "code": cb["code"],
        "code_verifier": verifier,
        "redirect_uri": redirect_uri,
        "resource": RESOURCE,
    })
    id_token = tokens["id_token"]
    claims = jwt.decode(id_token, JWKS.get_signing_key_from_jwt(id_token).key,
                        algorithms=["RS256"], audience=client_id, issuer=ISSUER)
    if not secrets.compare_digest(claims.get("nonce", ""), nonce):
        sys.exit("Invalid nonce")
    if saved and claims["sub"] != saved["subject"]:
        sys.exit("That's a different ChatGPT account")
    if "chatgpt.tokens.use.direct" not in (tokens.get("scope") or cb.get("scope", "")).split():
        sys.exit("ChatGPT plan usage wasn't granted")

    creds = {
        "issuer": ISSUER, "subject": claims["sub"], "email": claims.get("email"),
        "client_id": client_id, "ext_agent_host_id": host_id(),
        "id_token": id_token, "access_token": tokens["access_token"],
        "refresh_token": tokens["refresh_token"], "expires_at": time.time() + tokens["expires_in"],
    }
    save(CREDS, json.dumps(creds))
    return creds


def refresh(creds: dict) -> dict:
    try:
        tokens = post_form(TOKEN, {
            "grant_type": "refresh_token",
            "client_id": creds["client_id"],
            "refresh_token": creds["refresh_token"],
            "resource": RESOURCE,
        })
    except HTTPError as e:
        body = json.loads(e.read() or b"{}")
        code = body.get("error")
        code = code.get("code") if isinstance(code, dict) else code
        if code in REFRESH_DEAD:
            return sign_in(creds)  # refresh token is unusable: sign in again, same client_id
        raise  # temporary failure: keep the saved credentials
    creds.update(
        access_token=tokens["access_token"],
        refresh_token=tokens.get("refresh_token", creds["refresh_token"]),  # rotated on each refresh
        expires_at=time.time() + tokens["expires_in"],
    )
    if "id_token" in tokens:
        creds["id_token"] = tokens["id_token"]
    save(CREDS, json.dumps(creds))
    return creds


def credentials() -> dict:
    if not CREDS.exists():
        return sign_in()
    creds = json.loads(CREDS.read_text())
    return refresh(creds) if time.time() > creds["expires_at"] - 300 else creds


def models(access_token: str) -> list[dict]:
    req = Request(f"{RESOURCE}/models", headers={"authorization": f"Bearer {access_token}"})
    with urlopen(req) as res:
        return [m for m in json.load(res)["models"] if m.get("visibility") == "list"]


def main() -> None:
    prompt = " ".join(sys.argv[1:]) or "Say exactly: Hello, world!"
    creds = credentials()
    available = models(creds["access_token"])
    print("Models on your plan:", ", ".join(m["display_name"] for m in available))
    client = OpenAI(api_key=creds["access_token"], base_url=RESOURCE, max_retries=0)
    completed = False
    with client.responses.create(
        model=available[0]["slug"],
        input=[{"role": "user", "content": prompt}],  # send all context every time: nothing is stored
        store=False,
        stream=True,
    ) as stream:
        for event in stream:
            if event.type == "response.output_text.delta":
                print(event.delta, end="", flush=True)
            elif event.type == "response.failed":
                error = event.response.error
                sys.exit(f"\nResponse failed: {error.code if error else 'unknown_error'}")
            elif event.type == "response.completed":
                completed = True
    print()
    if not completed:
        sys.exit("Stream ended before response.completed")


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

Run python chatgpt_cli.py "Explain PKCE in one sentence". The first run opens the browser. Later runs reuse the saved credentials and refresh them when they're about to expire.

What the script gets right

  • The issued client_id comes from the callback, not the token response. On first sign-in the callback URL carries code, state and client_id. If a later callback sends a different client ID, reject it.
  • Credentials are per account, owner-only. The file is written atomically with 0600 permissions. Keep it out of logs, source control and analytics.
  • Refresh tokens rotate. Access tokens last an hour and refresh tokens 30 days, and each refresh returns a new refresh token. Save it every time.
  • Temporary failures don't erase credentials. Only a terminal refresh error (like invalid_grant or refresh_token_reused) sends the user back through sign-in.
  • Success means response.completed. A stream can end early, and a usage-limit error can arrive mid-stream.

Errors you'll see

  • subscription_sharing_usage_limit_exceeded (429): the user hit a usage limit. Stop and point them to chatgpt.com/settings/usage.
  • subscription_sharing_user_not_eligible (403): plan usage isn't available for this user or workspace. Explain it; don't retry or loop the sign-in.
  • subscription_sharing_unsupported_capability (400): a parameter, tool or model isn't supported in this flow. Check error.param. Parameters like temperature and max_output_tokens aren't supported.

The developer guide has the full table and the preview limitations.

Next steps

Top comments (0)