File size: 9,700 Bytes
5d0a52f
 
5dd5107
 
 
5d0a52f
50ae780
5dd5107
 
 
 
 
1b6fb15
 
5dd5107
5d0a52f
5dd5107
 
 
 
5d0a52f
 
 
 
 
 
1f63c38
 
5d0a52f
 
 
 
 
 
 
 
 
5dd5107
 
 
 
50ae780
5dd5107
 
 
 
 
 
 
50ae780
5dd5107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b6fb15
 
 
 
5dd5107
 
 
 
 
 
 
1b6fb15
5dd5107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d0a52f
 
5dd5107
 
1b6fb15
 
 
 
 
 
5dd5107
 
 
 
 
 
 
1b6fb15
5dd5107
 
 
 
 
 
 
 
 
 
5d0a52f
5dd5107
5d0a52f
5dd5107
 
 
 
5d0a52f
5dd5107
 
 
 
 
 
 
 
 
5d0a52f
5dd5107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fc11c2
 
5dd5107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d0a52f
5dd5107
 
5d0a52f
 
5dd5107
5d0a52f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dd5107
 
5d0a52f
 
 
 
 
 
 
 
 
 
 
5dd5107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Hono } from "hono";
import type { AccountPool } from "../auth/account-pool.js";
import type { RefreshScheduler } from "../auth/refresh-scheduler.js";
import { validateManualToken } from "../auth/chatgpt-oauth.js";
import { getConfig } from "../config.js";
import {
  startOAuthFlow,
  consumeSession,
  exchangeCode,
  requestDeviceCode,
  pollDeviceToken,
  importCliAuth,
  markSessionCompleted,
  isSessionCompleted,
} from "../auth/oauth-pkce.js";

export function createAuthRoutes(
  pool: AccountPool,
  scheduler: RefreshScheduler,
): Hono {
  const app = new Hono();

  // Auth status (JSON) β€” pool-level summary
  app.get("/auth/status", (c) => {
    const authenticated = pool.isAuthenticated();
    const userInfo = pool.getUserInfo();
    const config = getConfig();
    const proxyApiKey = config.server.proxy_api_key ?? pool.getProxyApiKey();
    const summary = pool.getPoolSummary();
    return c.json({
      authenticated,
      user: authenticated ? userInfo : null,
      proxy_api_key: authenticated ? proxyApiKey : null,
      pool: summary,
    });
  });

  // Start OAuth login β€” 302 redirect to Auth0 (same-machine shortcut)
  app.get("/auth/login", (c) => {
    const config = getConfig();
    const originalHost = c.req.header("host") || `localhost:${config.server.port}`;
    const { authUrl } = startOAuthFlow(originalHost, "login", pool, scheduler);
    return c.redirect(authUrl);
  });

  // POST /auth/login-start β€” returns { authUrl, state } for popup flow
  app.post("/auth/login-start", (c) => {
    const config = getConfig();
    const originalHost = c.req.header("host") || `localhost:${config.server.port}`;
    const { authUrl, state } = startOAuthFlow(originalHost, "login", pool, scheduler);
    return c.json({ authUrl, state });
  });

  // POST /auth/code-relay β€” accepts { callbackUrl }, parses code+state, exchanges tokens
  app.post("/auth/code-relay", async (c) => {
    const body = await c.req.json<{ callbackUrl: string }>();
    const callbackUrl = body.callbackUrl?.trim();

    if (!callbackUrl) {
      return c.json({ error: "callbackUrl is required" }, 400);
    }

    let url: URL;
    try {
      url = new URL(callbackUrl);
    } catch {
      return c.json({ error: "Invalid URL" }, 400);
    }

    const code = url.searchParams.get("code");
    const state = url.searchParams.get("state");
    const error = url.searchParams.get("error");

    if (error) {
      const desc = url.searchParams.get("error_description") || error;
      return c.json({ error: `OAuth error: ${desc}` }, 400);
    }

    if (!code || !state) {
      return c.json({ error: "URL must contain code and state parameters" }, 400);
    }

    const session = consumeSession(state);
    if (!session) {
      // Session already consumed by callback server β€” treat as success
      if (isSessionCompleted(state)) {
        return c.json({ success: true });
      }
      return c.json({ error: "Invalid or expired session. Please try again." }, 400);
    }

    try {
      const tokens = await exchangeCode(code, session.codeVerifier, session.redirectUri);
      const entryId = pool.addAccount(tokens.access_token, tokens.refresh_token);
      scheduler.scheduleOne(entryId, tokens.access_token);
      markSessionCompleted(state);

      console.log(`[Auth] OAuth via code-relay β€” account ${entryId} added`);
      return c.json({ success: true });
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      console.error("[Auth] Code relay token exchange failed:", msg);
      return c.json({ error: `Token exchange failed: ${msg}` }, 500);
    }
  });

  // OAuth callback β€” Auth0 redirects here after user login (legacy/fallback)
  app.get("/auth/callback", async (c) => {
    const code = c.req.query("code");
    const state = c.req.query("state");
    const error = c.req.query("error");
    const errorDescription = c.req.query("error_description");

    if (error) {
      console.error(`[Auth] OAuth error: ${error} β€” ${errorDescription}`);
      return c.html(errorPage(`OAuth error: ${errorDescription || error}`));
    }

    if (!code || !state) {
      return c.html(errorPage("Missing code or state parameter"), 400);
    }

    const session = consumeSession(state);
    if (!session) {
      // Session already consumed by callback server β€” redirect home
      if (isSessionCompleted(state)) {
        const config = getConfig();
        const host = c.req.header("host") || `localhost:${config.server.port}`;
        return c.redirect(`http://${host}/`);
      }
      return c.html(errorPage("Invalid or expired OAuth session. Please try again."), 400);
    }

    try {
      const tokens = await exchangeCode(code, session.codeVerifier, session.redirectUri);
      const entryId = pool.addAccount(tokens.access_token, tokens.refresh_token);
      scheduler.scheduleOne(entryId, tokens.access_token);
      markSessionCompleted(state);

      console.log(`[Auth] OAuth login completed β€” account ${entryId} added`);

      // Redirect back to the original host the user was browsing from
      const returnUrl = `http://${session.returnHost}/`;
      return c.redirect(returnUrl);
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      console.error("[Auth] Token exchange failed:", msg);
      return c.html(errorPage(`Token exchange failed: ${msg}`), 500);
    }
  });

  // ── Device Code Flow ────────────────────────────────────────────

  // POST /auth/device-login β€” start device code flow
  app.post("/auth/device-login", async (c) => {
    try {
      const deviceResp = await requestDeviceCode();
      console.log(`[Auth] Device code flow started β€” user_code: ${deviceResp.user_code}`);
      return c.json({
        userCode: deviceResp.user_code,
        verificationUri: deviceResp.verification_uri,
        verificationUriComplete: deviceResp.verification_uri_complete,
        deviceCode: deviceResp.device_code,
        expiresIn: deviceResp.expires_in,
        interval: deviceResp.interval,
      });
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      console.error("[Auth] Device code request failed:", msg);
      return c.json({ error: msg }, 500);
    }
  });

  // GET /auth/device-poll/:deviceCode β€” poll for device code authorization
  app.get("/auth/device-poll/:deviceCode", async (c) => {
    const deviceCode = c.req.param("deviceCode");

    try {
      const tokens = await pollDeviceToken(deviceCode);
      const entryId = pool.addAccount(tokens.access_token, tokens.refresh_token);
      scheduler.scheduleOne(entryId, tokens.access_token);

      console.log(`[Auth] Device code flow completed β€” account ${entryId} added`);
      return c.json({ success: true });
    } catch (err: unknown) {
      const code = (err as { code?: string }).code || "unknown";
      if (code === "authorization_pending" || code === "slow_down") {
        return c.json({ pending: true, code });
      }
      const msg = err instanceof Error ? err.message : String(err);
      console.error("[Auth] Device code poll failed:", msg);
      return c.json({ error: msg }, 400);
    }
  });

  // ── CLI Token Import ───────────────────────────────────────────

  // POST /auth/import-cli β€” import token from Codex CLI auth.json
  app.post("/auth/import-cli", async (c) => {
    try {
      const cliAuth = importCliAuth();
      const entryId = pool.addAccount(cliAuth.access_token!, cliAuth.refresh_token);
      scheduler.scheduleOne(entryId, cliAuth.access_token!);

      console.log(`[Auth] CLI token imported β€” account ${entryId} added`);
      return c.json({ success: true });
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      console.error("[Auth] CLI import failed:", msg);
      return c.json({ error: msg }, 500);
    }
  });

  // Manual token submission β€” adds to pool
  app.post("/auth/token", async (c) => {
    const body = await c.req.json<{ token: string }>();
    const token = body.token?.trim();

    if (!token) {
      c.status(400);
      return c.json({ error: "Token is required" });
    }

    const validation = validateManualToken(token);
    if (!validation.valid) {
      c.status(400);
      return c.json({ error: validation.error });
    }

    const entryId = pool.addAccount(token);
    scheduler.scheduleOne(entryId, token);
    return c.json({ success: true });
  });

  // Logout β€” clears all accounts
  app.post("/auth/logout", (c) => {
    pool.clearToken();
    return c.json({ success: true });
  });

  return app;
}

function errorPage(message: string): string {
  return `<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>Login Error</title>
<style>
  body { font-family: -apple-system, sans-serif; background: #0d1117; color: #c9d1d9;
    display: flex; align-items: center; justify-content: center; min-height: 100vh; }
  .card { background: #161b22; border: 1px solid #30363d; border-radius: 12px;
    padding: 2rem; max-width: 420px; text-align: center; }
  h2 { color: #f85149; margin-bottom: 1rem; }
  a { color: #58a6ff; }
</style></head>
<body><div class="card">
  <h2>Login Failed</h2>
  <p>${escapeHtml(message)}</p>
  <p style="margin-top:1rem"><a href="/">Back to Home</a></p>
</div></body></html>`;
}

function escapeHtml(str: string): string {
  return str
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}