File size: 12,465 Bytes
35205e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
from __future__ import annotations

import datetime
import ssl
import http.server
import json
import secrets
import threading
import time
import urllib.parse
import urllib.request
from typing import Any, Dict, Tuple

import certifi

from .config import OAUTH_ISSUER_DEFAULT
from .models import AuthBundle, PkceCodes, TokenData
from .utils import eprint, generate_pkce, parse_jwt_claims, write_auth_file


REQUIRED_PORT = 1455
URL_BASE = f"http://localhost:{REQUIRED_PORT}"
DEFAULT_ISSUER = OAUTH_ISSUER_DEFAULT


LOGIN_SUCCESS_HTML = """<!DOCTYPE html>
<html lang=\"en\">
  <head>
    <meta charset=\"utf-8\" />
    <title>Login successful</title>
  </head>
  <body>
    <div style=\"max-width: 640px; margin: 80px auto; font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif;\"> 
      <h1>Login successful</h1>
      <p>You can now close this window and return to the terminal and run <code>python3 chatmock.py serve</code> to start the server.</p>
    </div>
  </body>
  </html>
"""

_SSL_CONTEXT = ssl.create_default_context(cafile=certifi.where())

class OAuthHTTPServer(http.server.HTTPServer):
    def __init__(
        self,
        server_address: tuple[str, int],
        request_handler_class: type[http.server.BaseHTTPRequestHandler],
        *,
        home_dir: str,
        client_id: str,
        verbose: bool = False,
    ) -> None:
        super().__init__(server_address, request_handler_class, bind_and_activate=True)
        self.exit_code = 1
        self.home_dir = home_dir
        self.verbose = verbose
        self.issuer = DEFAULT_ISSUER
        self.token_endpoint = f"{self.issuer}/oauth/token"
        self.client_id = client_id
        port = server_address[1]
        self.redirect_uri = f"http://localhost:{port}/auth/callback"
        self.pkce = generate_pkce()
        self.state = secrets.token_hex(32)

    def auth_url(self) -> str:
        params = {
            "response_type": "code",
            "client_id": self.client_id,
            "redirect_uri": self.redirect_uri,
            "scope": "openid profile email offline_access",
            "code_challenge": self.pkce.code_challenge,
            "code_challenge_method": "S256",
            "id_token_add_organizations": "true",
            "codex_cli_simplified_flow": "true",
            "state": self.state,
        }
        return f"{self.issuer}/oauth/authorize?" + urllib.parse.urlencode(params)

    def exchange_code(self, code: str) -> tuple[AuthBundle, str]:
        data = urllib.parse.urlencode(
            {
                "grant_type": "authorization_code",
                "code": code,
                "redirect_uri": self.redirect_uri,
                "client_id": self.client_id,
                "code_verifier": self.pkce.code_verifier,
            }
        ).encode()

        with urllib.request.urlopen(
            urllib.request.Request(
                self.token_endpoint,
                data=data,
                method="POST",
                headers={"Content-Type": "application/x-www-form-urlencoded"},
            ),
            context=_SSL_CONTEXT,
        ) as resp:
            payload = json.loads(resp.read().decode())

        id_token = payload.get("id_token", "")
        access_token = payload.get("access_token", "")
        refresh_token = payload.get("refresh_token", "")

        id_token_claims = parse_jwt_claims(id_token)
        access_token_claims = parse_jwt_claims(access_token)

        auth_claims = (id_token_claims or {}).get("https://api.openai.com/auth", {})
        chatgpt_account_id = auth_claims.get("chatgpt_account_id", "")

        token_data = TokenData(
            id_token=id_token,
            access_token=access_token,
            refresh_token=refresh_token,
            account_id=chatgpt_account_id,
        )

        api_key, success_url = self.maybe_obtain_api_key(
            id_token_claims or {}, access_token_claims or {}, token_data
        )

        last_refresh_str = (
            datetime.datetime.now(datetime.timezone.utc).isoformat().replace("+00:00", "Z")
        )
        bundle = AuthBundle(api_key=api_key, token_data=token_data, last_refresh=last_refresh_str)
        return bundle, success_url or f"{URL_BASE}/success"

    def maybe_obtain_api_key(
        self,
        token_claims: Dict[str, Any],
        access_claims: Dict[str, Any],
        token_data: TokenData,
    ) -> tuple[str | None, str | None]:
        org_id = token_claims.get("organization_id")
        project_id = token_claims.get("project_id")
        if not org_id or not project_id:
            query = {
                "id_token": token_data.id_token,
                "needs_setup": "false",
                "org_id": org_id or "",
                "project_id": project_id or "",
                "plan_type": access_claims.get("chatgpt_plan_type"),
                "platform_url": "https://platform.openai.com",
            }
            return None, f"{URL_BASE}/success?{urllib.parse.urlencode(query)}"

        today = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d")
        exchange_data = urllib.parse.urlencode(
            {
                "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
                "client_id": self.client_id,
                "requested_token": "openai-api-key",
                "subject_token": token_data.id_token,
                "subject_token_type": "urn:ietf:params:oauth:token-type:id_token",
                "name": f"ChatMock [auto-generated] ({today})",
            }
        ).encode()

        with urllib.request.urlopen(
            urllib.request.Request(
                self.token_endpoint,
                data=exchange_data,
                method="POST",
                headers={"Content-Type": "application/x-www-form-urlencoded"},
            ),
            context=_SSL_CONTEXT,
        ) as resp:
            exchange_payload = json.loads(resp.read().decode())
            exchanged_access_token = exchange_payload.get("access_token")

        chatgpt_plan_type = access_claims.get("chatgpt_plan_type")
        success_url_query = {
            "id_token": token_data.id_token,
            "access_token": token_data.access_token,
            "refresh_token": token_data.refresh_token,
            "exchanged_access_token": exchanged_access_token,
            "org_id": org_id,
            "project_id": project_id,
            "plan_type": chatgpt_plan_type,
            "platform_url": "https://platform.openai.com",
        }
        success_url = f"{URL_BASE}/success?{urllib.parse.urlencode(success_url_query)}"
        return exchanged_access_token, success_url

    def persist_auth(self, bundle: AuthBundle) -> bool:
        auth_json_contents = {
            "OPENAI_API_KEY": bundle.api_key,
            "tokens": {
                "id_token": bundle.token_data.id_token,
                "access_token": bundle.token_data.access_token,
                "refresh_token": bundle.token_data.refresh_token,
                "account_id": bundle.token_data.account_id,
            },
            "last_refresh": bundle.last_refresh,
        }
        return write_auth_file(auth_json_contents)


class OAuthHandler(http.server.BaseHTTPRequestHandler):
    server: "OAuthHTTPServer"

    def do_GET(self) -> None:
        path = urllib.parse.urlparse(self.path).path
        if path == "/success":
            self._send_html(LOGIN_SUCCESS_HTML)
            try:
                self.wfile.flush()
            except Exception as e:
                eprint(f"Failed to flush response: {e}")
            self._shutdown_after_delay(2.0)
            return

        if path != "/auth/callback":
            self.send_error(404, "Not Found")
            self._shutdown()
            return

        query = urllib.parse.urlparse(self.path).query
        params = urllib.parse.parse_qs(query)

        code = params.get("code", [None])[0]
        if not code:
            self.send_error(400, "Missing auth code")
            self._shutdown()
            return

        try:
            auth_bundle, success_url = self._exchange_code(code)
        except Exception as exc:
            self.send_error(500, f"Token exchange failed: {exc}")
            self._shutdown()
            return

        auth_json_contents = {
            "OPENAI_API_KEY": auth_bundle.api_key,
            "tokens": {
                "id_token": auth_bundle.token_data.id_token,
                "access_token": auth_bundle.token_data.access_token,
                "refresh_token": auth_bundle.token_data.refresh_token,
                "account_id": auth_bundle.token_data.account_id,
            },
            "last_refresh": auth_bundle.last_refresh,
        }
        if write_auth_file(auth_json_contents):
            self.server.exit_code = 0
            self._send_html(LOGIN_SUCCESS_HTML)
        else:
            self.send_error(500, "Unable to persist auth file")
        self._shutdown_after_delay(2.0)

    def do_POST(self) -> None:
        self.send_error(404, "Not Found")
        self._shutdown()

    def log_message(self, fmt: str, *args):
        if getattr(self.server, "verbose", False):
            super().log_message(fmt, *args)

    def _send_redirect(self, url: str) -> None:
        self.send_response(302)
        self.send_header("Location", url)
        self.end_headers()

    def _send_html(self, body: str) -> None:
        encoded = body.encode()
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(encoded)))
        self.end_headers()
        self.wfile.write(encoded)

    def _shutdown(self) -> None:
        threading.Thread(target=self.server.shutdown, daemon=True).start()

    def _shutdown_after_delay(self, seconds: float = 2.0) -> None:
        def _later():
            try:
                time.sleep(seconds)
            finally:
                self._shutdown()

        threading.Thread(target=_later, daemon=True).start()

    def _exchange_code(self, code: str) -> Tuple[AuthBundle, str]:
        return self.server.exchange_code(code)

    def _maybe_obtain_api_key(
        self,
        token_claims: Dict[str, Any],
        access_claims: Dict[str, Any],
        token_data: TokenData,
    ) -> Tuple[str | None, str | None]:
        org_id = token_claims.get("organization_id")
        project_id = token_claims.get("project_id")
        if not org_id or not project_id:
            query = {
                "id_token": token_data.id_token,
                "needs_setup": "false",
                "org_id": org_id or "",
                "project_id": project_id or "",
                "plan_type": access_claims.get("chatgpt_plan_type"),
                "platform_url": "https://platform.openai.com",
            }
            return None, f"{URL_BASE}/success?{urllib.parse.urlencode(query)}"

        today = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d")
        exchange_data = urllib.parse.urlencode(
            {
                "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
                "client_id": self.server.client_id,
                "requested_token": "openai-api-key",
                "subject_token": token_data.id_token,
                "subject_token_type": "urn:ietf:params:oauth:token-type:id_token",
                "name": f"ChatMock [auto-generated] ({today})",
            }
        ).encode()

        with urllib.request.urlopen(
            urllib.request.Request(
                self.server.token_endpoint,
                data=exchange_data,
                method="POST",
                headers={"Content-Type": "application/x-www-form-urlencoded"},
            ),
            context=_SSL_CONTEXT,
        ) as resp:
            exchange_payload = json.loads(resp.read().decode())
            exchanged_access_token = exchange_payload.get("access_token")

        chatgpt_plan_type = access_claims.get("chatgpt_plan_type")
        success_url_query = {
            "id_token": token_data.id_token,
            "needs_setup": "false",
            "org_id": org_id,
            "project_id": project_id,
            "plan_type": chatgpt_plan_type,
            "platform_url": "https://platform.openai.com",
        }
        success_url = f"{URL_BASE}/success?{urllib.parse.urlencode(success_url_query)}"
        return exchanged_access_token, success_url