/* OpenAI's Sign in with ChatGPT for open-source agents, as Pi's openai * provider does it (pi-ai auth/oauth/openai-chatgpt.ts): a public client * registered per sign-in (OpenAI hands the issued client id back on the * redirect), PKCE, the redirect to 127.0.0.1:1455, and a token whose * chatgpt.tokens.use.direct scope lets the subscription pay for Responses * API requests to api.openai.com. The token is sent as the API key would be. */ #include #include #include #include "oauth.h" #include "platform.h" #include "userdb.h" #define OPENAI_AUTH "https://auth.openai.com" #define OPENAI_AUTHORIZE "/api/accounts/authorize" #define OPENAI_TOKEN "/api/accounts/oauth/token" #define OPENAI_RESOURCE "https://api.openai.com/v1" #define OPENAI_CLIENT "dynamic_agent_client" /* every sign-in registers a client under this id */ #define OPENAI_AGENT "pic" #define OPENAI_PORT 1455 /* the redirect OpenAI accepts */ #define OPENAI_PATH "/auth/callback" #define OPENAI_DIRECT_SCOPE "chatgpt.tokens.use.direct" #define OPENAI_SCOPE "openid profile email offline_access resource.invoke " OPENAI_DIRECT_SCOPE /* Refresh this long before the real expiry, so no request starts with a token about to lapse. */ #define OPENAI_EXPIRY_MARGIN_MS (3 * 60 * 1000) #define OPENAI_WAIT_SECONDS 300 static const char *openai_auth(void) { return pic_oauth_seam("PIC_TEST_OPENAI_AUTH", OPENAI_AUTH); } /* The token response as pic's credential JSON (malloc'd): access, refresh * (REFRESH when the response keeps the old one), expires, clientId, scope. * NULL with err when it lacks a field or the direct-use scope. */ static char *openai_credential(const char *token, const char *client_id, const char *refresh, char *err, size_t errcap) { sqlite3 *db = pic_userdb(err, errcap); sqlite3_stmt *q = NULL; char *out = NULL; long long now = (long long)(pic_platform_get()->wall_ns() / 1000000); if (!db) { return NULL; } if (sqlite3_prepare_v2( db, "SELECT json_object('access', json_extract(?1, '$.access_token')," " 'refresh', coalesce(json_extract(?1, '$.refresh_token'), ?3)," " 'expires', ?4 + CAST(json_extract(?1, '$.expires_in') * 1000 AS INTEGER) - ?5," " 'clientId', ?2, 'scope', json_extract(?1, '$.scope'))" " WHERE json_valid(?1) AND json_type(?1, '$.access_token') = 'text' AND length(json_extract(?1, '$.access_token')) > 0" " AND (json_type(?1, '$.refresh_token') = 'text' OR ?3 IS NOT NULL)" " AND json_type(?1, '$.expires_in') IN ('integer', 'real') AND json_extract(?1, '$.expires_in') > 0" " AND json_type(?1, '$.scope') = 'text'" " AND instr(' ' || json_extract(?1, '$.scope') || ' ', ' ' || ?6 || ' ') > 0", -1, &q, NULL) != SQLITE_OK) { (void)snprintf(err, errcap, "sql: %s", sqlite3_errmsg(db)); return NULL; } sqlite3_bind_text(q, 1, token, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, client_id, -1, SQLITE_STATIC); if (refresh) { sqlite3_bind_text(q, 3, refresh, -1, SQLITE_STATIC); } sqlite3_bind_int64(q, 4, now); sqlite3_bind_int64(q, 5, OPENAI_EXPIRY_MARGIN_MS); sqlite3_bind_text(q, 6, OPENAI_DIRECT_SCOPE, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW && (out = malloc((size_t)sqlite3_column_bytes(q, 0) + 1))) { memcpy(out, sqlite3_column_text(q, 0), (size_t)sqlite3_column_bytes(q, 0) + 1); } else { (void)snprintf(err, errcap, "OpenAI's token response lacks a token, its lifetime or the %s scope", OPENAI_DIRECT_SCOPE); } sqlite3_finalize(q); return out; } /* POSTs a token request built from PAIRS; 0 with the response JSON, -1 with err. */ static int openai_token(const char *const *pairs, char **body, char *err, size_t errcap) { char url[512], *form = pic_oauth_form(pairs); int status = 0, rc; *body = NULL; if (!form) { (void)snprintf(err, errcap, "out of memory"); return -1; } (void)snprintf(url, sizeof url, "%s%s", openai_auth(), OPENAI_TOKEN); rc = pic_oauth_post(url, form, 0, &status, body, err, errcap); pic_cred_wipe(form, strlen(form)); free(form); if (rc == 0 && status != 200) { pic_oauth_error(status, *body, err, errcap); pic_cred_wipe(*body, strlen(*body)); free(*body); *body = NULL; rc = -1; } return rc; } static void openai_free(char *s) { if (s) { pic_cred_wipe(s, strlen(s)); free(s); } } static int openai_login(const pic_oauth_io *io, const char **kind, char **secret, char *err, size_t errcap) { char id[37], host[64], verifier[64], challenge[64], state[64], nonce[64], redirect[128]; char *url = NULL, *query = NULL, *pasted = NULL, *code = NULL, *client = NULL, *body = NULL, *id_token = NULL; pic_oauth_callback cb; int port = atoi(pic_oauth_seam("PIC_TEST_OAUTH_PORT", "1455")), rc = -1; *secret = NULL; *kind = "oauth"; cb.fd = -1; if (pic_install_id(id) != 0) { (void)snprintf(err, errcap, "cannot read or make this installation's id in ~/.pic/pic.sqlite"); return -1; } (void)snprintf(host, sizeof host, "urn:uuid:%s", id); if (pic_oauth_pkce(verifier, challenge) != 0 || pic_oauth_random(state, sizeof state, 32) != 0 || pic_oauth_random(nonce, sizeof nonce, 32) != 0) { (void)snprintf(err, errcap, "no entropy for the sign-in"); return -1; } /* Without this listener the browser's redirect would reach whatever else holds the port. */ if (pic_oauth_listen(&cb, port, OPENAI_PATH, state, err, errcap) != 0) { (void)snprintf(err, errcap, "port %d is in use, probably by an unfinished sign-in in another pic or by the Codex CLI: finish or" " cancel that one and try again", port); return -1; } (void)snprintf(redirect, sizeof redirect, "http://127.0.0.1:%d%s", cb.port, OPENAI_PATH); { const char *pairs[] = {"client_id", OPENAI_CLIENT, "agent_name_hint", OPENAI_AGENT, "ext_agent_host_id", host, "response_type", "code", "redirect_uri", redirect, "resource", OPENAI_RESOURCE, "scope", OPENAI_SCOPE, "state", state, "code_challenge", challenge, "code_challenge_method", "S256", "nonce", nonce, NULL}; char *q = pic_oauth_form(pairs); size_t n = q ? strlen(openai_auth()) + sizeof OPENAI_AUTHORIZE + strlen(q) + 2 : 0; if (!q || !(url = malloc(n))) { free(q); (void)snprintf(err, errcap, "out of memory"); goto out; } (void)snprintf(url, n, "%s%s?%s", openai_auth(), OPENAI_AUTHORIZE, q); free(q); } pic_oauth_show_url(io, url, "Sign in to ChatGPT in the browser. If the browser cannot reach this machine, paste the address it" " ends on here and press Enter."); if (pic_oauth_wait(&cb, io, OPENAI_WAIT_SECONDS, &query, &pasted, err, errcap) != 0) { goto out; } pic_oauth_close(&cb); if (pasted && pic_oauth_pasted_query(pasted, redirect, state, &query, err, errcap) != 0) { goto out; } code = pic_oauth_param(query, "code"); client = pic_oauth_param(query, "client_id"); if (!code || !*code) { (void)snprintf(err, errcap, "the redirect carried no authorization code"); goto out; } if (!client || !*client) { (void)snprintf(err, errcap, "OpenAI's redirect did not carry the issued client id"); goto out; } fprintf(io->out, "Exchanging the authorization code for tokens...\n"); (void)fflush(io->out); { const char *pairs[] = {"grant_type", "authorization_code", "client_id", client, "code", code, "code_verifier", verifier, "redirect_uri", redirect, "resource", OPENAI_RESOURCE, NULL}; if (openai_token(pairs, &body, err, errcap) != 0) { goto out; } } /* pic does not read the ID token; its presence is part of the response's contract. */ if (!(id_token = pic_oauth_json_text(body, "$.id_token")) || !*id_token) { (void)snprintf(err, errcap, "OpenAI's token response has no ID token"); goto out; } if ((*secret = openai_credential(body, client, NULL, err, errcap)) != NULL) { rc = 0; } out: pic_oauth_close(&cb); pic_cred_wipe(verifier, sizeof verifier); free(url); openai_free(query); openai_free(pasted); openai_free(code); free(client); openai_free(body); openai_free(id_token); return rc; } static int openai_refresh(const char *cred, char **out, char *err, size_t errcap) { char *client = pic_oauth_json_text(cred, "$.clientId"), *refresh = pic_oauth_json_text(cred, "$.refresh"), *body = NULL; int rc = -1; *out = NULL; if (!client || !*client) { (void)snprintf(err, errcap, "the stored sign-in has no issued client id"); } else if (!refresh || !*refresh) { (void)snprintf(err, errcap, "the stored sign-in has no refresh token"); } else { const char *pairs[] = {"grant_type", "refresh_token", "client_id", client, "refresh_token", refresh, "resource", OPENAI_RESOURCE, NULL}; if (openai_token(pairs, &body, err, errcap) == 0 && (*out = openai_credential(body, client, refresh, err, errcap))) { rc = 0; } } free(client); openai_free(refresh); openai_free(body); return rc; } const pic_oauth_flow pic_oauth_flow_openai = {"openai", "Sign in with ChatGPT", openai_login, openai_refresh};