@@ -0,0 +1,444 @@
1+const std = @import("std");
2+const platform = @import("platform.zig");
3+const config = @import("config.zig");
4+const filesystem = @import("filesystem.zig");
5+const http = @import("http.zig");
6+const auth = @import("auth.zig");
7+const time = @import("time.zig");
8+
9+const redirect_uri = "http://127.0.0.1:1455/auth/callback";
10+const discovery_url = "https://auth.openai.com/.well-known/openid-configuration";
11+const issuer = "https://auth.openai.com";
12+const identity_scope = "openid profile email offline_access resource.invoke";
13+const default_brand = "Mini-coding-agent";
14+const max_brand = 24;
15+
16+pub const Error = error{ LoginFailed, OutOfMemory };
17+
18+/// Runs the Sign in with ChatGPT (SIWC) flow and writes the credential record.
19+/// Called by `mini login`; never from the TUI, where the loopback listener and
20+/// a browser hand-off would block the render loop.
21+pub fn login(a: std.mem.Allocator, cfg: *const config.Config) Error!void {
22+ const previous = auth.load(a);
23+ const host = hostId(a) catch return error.OutOfMemory;
24+ const verifier = random(a, 32) catch return error.OutOfMemory;
25+ var digest: [32]u8 = undefined;
26+ std.crypto.hash.sha2.Sha256.hash(verifier, &digest, .{});
27+ const challenge = encode64(a, &digest) catch return error.OutOfMemory;
28+ const state = random(a, 16) catch return error.OutOfMemory;
29+ const nonce = random(a, 16) catch return error.OutOfMemory;
30+
31+ // A returning account reauthorizes its issued client; a new one registers.
32+ const saved_id: ?[]const u8 = if (previous) |r| r.clientId else null;
33+ const saved_token: ?[]const u8 = if (previous) |r| r.idToken else null;
34+ const url = authorizeUrl(a, .{
35+ .client_id = saved_id orelse "dynamic_agent_client",
36+ .host_id = host,
37+ .state = state,
38+ .nonce = nonce,
39+ .challenge = challenge,
40+ .agent_name = if (saved_id == null) "mini" else null,
41+ .id_token_hint = saved_token,
42+ }) catch return error.OutOfMemory;
43+
44+ // Bind before the browser opens: a fast redirect must not find a closed port.
45+ var listener = listen() catch return error.LoginFailed;
46+ defer listener.deinit(platform.io);
47+
48+ platform.printErr("sign-in: opening the browser\n{s}\n\n", .{redact(a, url)});
49+ openBrowser(url);
50+
51+ const callback = serve(a, &listener, state, brand(cfg)) catch return error.LoginFailed;
52+
53+ const body = auth.form(a, &.{
54+ .{ "grant_type", "authorization_code" },
55+ .{ "client_id", callback.client_id orelse saved_id orelse return error.LoginFailed },
56+ .{ "code", callback.code },
57+ .{ "code_verifier", verifier },
58+ .{ "redirect_uri", redirect_uri },
59+ .{ "resource", auth.resource },
60+ }) catch return error.OutOfMemory;
61+ const response = auth.tokenRequest(a, body, null) orelse return error.LoginFailed;
62+ const access = response.access_token orelse return error.LoginFailed;
63+ const scope = response.scope orelse callback.scope orelse "";
64+ if (!auth.granted(scope, auth.plan_scope)) {
65+ platform.printErr("sign-in: the ChatGPT plan permission was not granted\n", .{});
66+ return error.LoginFailed;
67+ }
68+ const identity = verifyIdToken(a, response.id_token orelse return error.LoginFailed, .{
69+ .client_id = callback.client_id orelse saved_id orelse return error.LoginFailed,
70+ .nonce = nonce,
71+ }) orelse return error.LoginFailed;
72+
73+ auth.save(a, .{
74+ .email = identity,
75+ .clientId = callback.client_id orelse saved_id orelse return error.LoginFailed,
76+ .accessToken = access,
77+ .refreshToken = response.refresh_token,
78+ .idToken = response.id_token,
79+ .expiresAt = time.nowMs() + @as(i64, @intCast(response.expires_in orelse 3600)) * 1000,
80+ .scope = scope,
81+ }) catch {
82+ platform.printErr("sign-in: could not write {s}\n", .{auth.path(a)});
83+ return error.LoginFailed;
84+ };
85+
86+ platform.printErr("sign-in: done, {s}; credentials in {s}\n", .{ identity, auth.path(a) });
87+}
88+
89+const Authorize = struct {
90+ client_id: []const u8,
91+ host_id: []const u8,
92+ state: []const u8,
93+ nonce: []const u8,
94+ challenge: []const u8,
95+ agent_name: ?[]const u8 = null,
96+ id_token_hint: ?[]const u8 = null,
97+};
98+
99+fn authorizeUrl(a: std.mem.Allocator, p: Authorize) ![]u8 {
100+ var out: std.ArrayList(u8) = .empty;
101+ try out.appendSlice(a, auth.scope_url);
102+ try out.append(a, '?');
103+ const pairs = [_][2]?[]const u8{
104+ .{ "client_id", p.client_id },
105+ .{ "agent_name_hint", p.agent_name },
106+ .{ "ext_agent_host_id", p.host_id },
107+ .{ "id_token_hint", p.id_token_hint },
108+ .{ "response_type", "code" },
109+ .{ "redirect_uri", redirect_uri },
110+ .{ "scope", identity_scope ++ " " ++ auth.plan_scope },
111+ .{ "resource", auth.resource },
112+ .{ "state", p.state },
113+ .{ "nonce", p.nonce },
114+ .{ "code_challenge", p.challenge },
115+ .{ "code_challenge_method", "S256" },
116+ };
117+ var first = true;
118+ for (pairs) |pair| {
119+ const value = pair[1] orelse continue;
120+ if (!first) try out.append(a, '&');
121+ first = false;
122+ try auth.appendEncoded(a, &out, pair[0].?);
123+ try out.append(a, '=');
124+ try auth.appendEncoded(a, &out, value);
125+ }
126+ return out.toOwnedSlice(a);
127+}
128+
129+const Callback = struct {
130+ code: []const u8,
131+ client_id: ?[]const u8 = null,
132+ scope: ?[]const u8 = null,
133+};
134+
135+fn listen() Error!std.Io.net.Server {
136+ const uri = std.Uri.parse(redirect_uri) catch return error.LoginFailed;
137+ const port = uri.port orelse 1455;
138+ const address = std.Io.net.IpAddress.parseIp4("127.0.0.1", port) catch return error.LoginFailed;
139+ return address.listen(platform.io, .{ .reuse_address = true }) catch {
140+ platform.printErr("sign-in: cannot listen on 127.0.0.1:{d}\n", .{port});
141+ return error.LoginFailed;
142+ };
143+}
144+
145+/// Serves the loopback callback until the redirect arrives. Unrelated requests
146+/// (favicon, browser preconnect) are answered and ignored; only a callback
147+/// carrying our state, or an explicit failure, ends the wait.
148+fn serve(a: std.mem.Allocator, listener: *std.Io.net.Server, state: []const u8, name: []const u8) Error!Callback {
149+ var in_buf: [16 * 1024]u8 = undefined;
150+ var out_buf: [8 * 1024]u8 = undefined;
151+ var conn_arena = std.heap.ArenaAllocator.init(a);
152+ defer conn_arena.deinit();
153+ while (true) {
154+ var connection = listener.accept(platform.io) catch return error.LoginFailed;
155+ defer connection.close(platform.io);
156+
157+ // A browser preconnect completes the handshake and then sends nothing;
158+ // never block the accept loop on it.
159+ var ready = [_]std.posix.pollfd{.{
160+ .fd = connection.socket.handle,
161+ .events = std.posix.POLL.IN,
162+ .revents = 0,
163+ }};
164+ if ((std.posix.poll(&ready, 2000) catch 0) == 0) continue;
165+
166+ _ = conn_arena.reset(.retain_capacity);
167+ const ca = conn_arena.allocator();
168+
169+ var reader = connection.reader(platform.io, &in_buf);
170+ var writer = connection.writer(platform.io, &out_buf);
171+ var server = std.http.Server.init(&reader.interface, &writer.interface);
172+ var request = server.receiveHead() catch continue;
173+
174+ const target = request.head.target;
175+ const query = if (std.mem.indexOfScalar(u8, target, '?')) |i| target[i + 1 ..] else "";
176+ const got_state = param(ca, query, "state");
177+ const code = param(ca, query, "code");
178+ const failure = param(ca, query, "error");
179+ const ok = got_state != null and std.mem.eql(u8, got_state.?, state) and
180+ failure == null and code != null;
181+
182+ request.respond(page(ca, name, ok), .{
183+ .status = if (ok) .ok else .bad_request,
184+ .extra_headers = &.{.{ .name = "content-type", .value = "text/html; charset=utf-8" }},
185+ }) catch {};
186+ if (ok) return .{
187+ .code = a.dupe(u8, code.?) catch return error.OutOfMemory,
188+ .client_id = duped(a, param(ca, query, "client_id")),
189+ .scope = duped(a, param(ca, query, "scope")),
190+ };
191+ if (failure != null or code != null or got_state != null) return error.LoginFailed;
192+ }
193+}
194+
195+fn duped(a: std.mem.Allocator, value: ?[]const u8) ?[]const u8 {
196+ return a.dupe(u8, value orelse return null) catch null;
197+}
198+
199+/// Drops the id_token_hint value: the docs require authorization URLs carrying
200+/// it to be redacted from logs and diagnostics.
201+fn redact(a: std.mem.Allocator, url: []const u8) []const u8 {
202+ const key = "id_token_hint=";
203+ const start = std.mem.indexOf(u8, url, key) orelse return url;
204+ const value_start = start + key.len;
205+ const value_end = std.mem.indexOfScalarPos(u8, url, value_start, '&') orelse url.len;
206+ var out: std.ArrayList(u8) = .empty;
207+ out.appendSlice(a, url[0..value_start]) catch return url;
208+ out.appendSlice(a, "redacted") catch return url;
209+ out.appendSlice(a, url[value_end..]) catch return url;
210+ return out.toOwnedSlice(a) catch url;
211+}
212+
213+fn param(a: std.mem.Allocator, query: []const u8, key: []const u8) ?[]const u8 {
214+ var it = std.mem.splitScalar(u8, query, '&');
215+ while (it.next()) |pair| {
216+ const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue;
217+ if (!std.mem.eql(u8, pair[0..eq], key)) continue;
218+ const buf = a.dupe(u8, pair[eq + 1 ..]) catch return null;
219+ for (buf) |*ch| {
220+ if (ch.* == '+') ch.* = ' ';
221+ }
222+ return std.Uri.percentDecodeInPlace(buf);
223+ }
224+ return null;
225+}
226+
227+fn hostId(a: std.mem.Allocator) ![]const u8 {
228+ const file = try filesystem.join(a, &.{ config.configDir(a), "host-id" });
229+ if (filesystem.readFileAlloc(a, file, 256)) |text| {
230+ const trimmed = std.mem.trim(u8, text, " \r\n\t");
231+ if (trimmed.len > 0) return trimmed;
232+ } else |_| {}
233+ var b: [16]u8 = undefined;
234+ std.Io.random(platform.io, &b);
235+ b[6] = (b[6] & 0x0f) | 0x40;
236+ b[8] = (b[8] & 0x3f) | 0x80;
237+ const id = try std.fmt.allocPrint(a, "urn:uuid:{x:0>2}{x:0>2}{x:0>2}{x:0>2}-{x:0>2}{x:0>2}-{x:0>2}{x:0>2}-{x:0>2}{x:0>2}-{x:0>2}{x:0>2}{x:0>2}{x:0>2}{x:0>2}{x:0>2}", .{
238+ b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
239+ b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15],
240+ });
241+ try filesystem.writeFile(file, id);
242+ return id;
243+}
244+
245+fn random(a: std.mem.Allocator, n: usize) ![]const u8 {
246+ const bytes = try a.alloc(u8, n);
247+ std.Io.random(platform.io, bytes);
248+ return encode64(a, bytes);
249+}
250+
251+fn encode64(a: std.mem.Allocator, bytes: []const u8) ![]const u8 {
252+ const out = try a.alloc(u8, std.base64.url_safe_no_pad.Encoder.calcSize(bytes.len));
253+ return std.base64.url_safe_no_pad.Encoder.encode(out, bytes);
254+}
255+
256+fn decode64(a: std.mem.Allocator, text: []const u8) ?[]u8 {
257+ const trimmed = std.mem.trimEnd(u8, text, "=");
258+ const size = std.base64.url_safe_no_pad.Decoder.calcSizeForSlice(trimmed) catch return null;
259+ const out = a.alloc(u8, size) catch return null;
260+ std.base64.url_safe_no_pad.Decoder.decode(out, trimmed) catch return null;
261+ return out;
262+}
263+
264+fn openBrowser(url: []const u8) void {
265+ var child = std.process.spawn(platform.io, .{
266+ .argv = &.{ "xdg-open", url },
267+ .stdin = .ignore,
268+ .stdout = .ignore,
269+ .stderr = .ignore,
270+ }) catch return;
271+ _ = child.wait(platform.io) catch {};
272+}
273+
274+const Expect = struct { client_id: []const u8, nonce: []const u8 };
275+
276+var never = std.atomic.Value(bool).init(false);
277+
278+/// Validates the ID token: RS256 signature against the published JWKS, then
279+/// the claims this flow depends on. Returns the email when one is present.
280+fn verifyIdToken(a: std.mem.Allocator, token: []const u8, expect: Expect) ?[]const u8 {
281+ const split = std.mem.lastIndexOfScalar(u8, token, '.') orelse return null;
282+ const header_end = std.mem.indexOfScalar(u8, token, '.') orelse return null;
283+ const signing_input = token[0..split];
284+ const header = std.json.parseFromSliceLeaky(Header, a, decode64(a, token[0..header_end]) orelse return null, .{
285+ .ignore_unknown_fields = true,
286+ }) catch return null;
287+
288+ if (header.alg == null or !std.mem.eql(u8, header.alg.?, "RS256")) {
289+ platform.printErr("sign-in: unexpected id token algorithm\n", .{});
290+ return null;
291+ }
292+ if (!verifySignature(a, signing_input, decode64(a, token[split + 1 ..]) orelse return null, header.kid)) {
293+ platform.printErr("sign-in: id token signature did not verify\n", .{});
294+ return null;
295+ }
296+
297+ const claims = std.json.parseFromSliceLeaky(Claims, a, decode64(a, token[header_end + 1 .. split]) orelse return null, .{
298+ .ignore_unknown_fields = true,
299+ }) catch return null;
300+
301+ if (claims.iss == null or !std.mem.eql(u8, claims.iss.?, issuer)) return null;
302+ if (!audMatches(claims.aud, expect.client_id)) return null;
303+ if (claims.nonce == null or !std.mem.eql(u8, claims.nonce.?, expect.nonce)) return null;
304+ const exp = seconds(claims.exp) orelse return null;
305+ if (exp <= @divTrunc(time.nowMs(), 1000)) return null;
306+ return claims.email;
307+}
308+
309+const Header = struct { alg: ?[]const u8 = null, kid: ?[]const u8 = null };
310+
311+const Claims = struct {
312+ iss: ?[]const u8 = null,
313+ aud: ?std.json.Value = null,
314+ exp: ?std.json.Value = null,
315+ nonce: ?[]const u8 = null,
316+ email: ?[]const u8 = null,
317+};
318+
319+const Key = struct {
320+ kty: ?[]const u8 = null,
321+ kid: ?[]const u8 = null,
322+ n: ?[]const u8 = null,
323+ e: ?[]const u8 = null,
324+};
325+
326+fn verifySignature(a: std.mem.Allocator, msg: []const u8, sig: []const u8, kid: ?[]const u8) bool {
327+ const rsa = std.crypto.Certificate.rsa;
328+ const meta = http.get(a, discovery_url, &.{}, &never) catch return false;
329+ const discovery = std.json.parseFromSliceLeaky(struct {
330+ jwks_uri: ?[]const u8 = null,
331+ }, a, meta, .{ .ignore_unknown_fields = true }) catch return false;
332+ const jwks_uri = discovery.jwks_uri orelse return false;
333+
334+ const body = http.get(a, jwks_uri, &.{}, &never) catch return false;
335+ const keys = std.json.parseFromSliceLeaky(struct { keys: []const Key }, a, body, .{
336+ .ignore_unknown_fields = true,
337+ }) catch return false;
338+
339+ for (keys.keys) |key| {
340+ if (key.kty == null or !std.mem.eql(u8, key.kty.?, "RSA")) continue;
341+ if (kid) |want| {
342+ if (key.kid == null or !std.mem.eql(u8, key.kid.?, want)) continue;
343+ }
344+ const modulus_bytes = decode64(a, key.n orelse continue) orelse continue;
345+ const exponent_bytes = decode64(a, key.e orelse continue) orelse continue;
346+ if (sig.len != modulus_bytes.len) continue;
347+ const public_key = rsa.PublicKey.fromBytes(exponent_bytes, modulus_bytes) catch continue;
348+ return switch (sig.len) {
349+ 256 => checkRs256(256, sig, msg, public_key),
350+ 384 => checkRs256(384, sig, msg, public_key),
351+ 512 => checkRs256(512, sig, msg, public_key),
352+ else => false,
353+ };
354+ }
355+ return false;
356+}
357+
358+fn checkRs256(comptime len: usize, sig: []const u8, msg: []const u8, key: std.crypto.Certificate.rsa.PublicKey) bool {
359+ std.crypto.Certificate.rsa.PKCS1v1_5Signature.verify(
360+ len,
361+ sig[0..len].*,
362+ msg,
363+ key,
364+ std.crypto.hash.sha2.Sha256,
365+ ) catch return false;
366+ return true;
367+}
368+
369+fn audMatches(aud: ?std.json.Value, client_id: []const u8) bool {
370+ const value = aud orelse return false;
371+ return switch (value) {
372+ .string => |s| std.mem.eql(u8, s, client_id),
373+ .array => |items| blk: {
374+ for (items.items) |item| {
375+ if (item == .string and std.mem.eql(u8, item.string, client_id)) break :blk true;
376+ }
377+ break :blk false;
378+ },
379+ else => false,
380+ };
381+}
382+
383+fn seconds(value: ?std.json.Value) ?i64 {
384+ const v = value orelse return null;
385+ return switch (v) {
386+ .integer => |i| i,
387+ .float => |f| @intFromFloat(f),
388+ .number_string => |s| std.fmt.parseInt(i64, s, 10) catch null,
389+ else => null,
390+ };
391+}
392+
393+/// The configured brand, or the default when it is missing or carries anything
394+/// outside a conservative printable set. This is the boundary that keeps the
395+/// value safe to interpolate into the page.
396+fn brand(cfg: *const config.Config) []const u8 {
397+ const raw = cfg.oauth_redirect_brand orelse return default_brand;
398+ if (raw.len == 0 or raw.len > max_brand) return default_brand;
399+ for (raw) |c| switch (c) {
400+ 'A'...'Z', 'a'...'z', '0'...'9', ' ', '.', '-', '_' => {},
401+ else => return default_brand,
402+ };
403+ return raw;
404+}
405+
406+const style =
407+ ":root{color-scheme:dark}" ++
408+ "*{box-sizing:border-box}" ++
409+ "body{margin:0;min-height:100vh;display:grid;place-items:center;" ++
410+ "background:#0b0d10;color:#e6e8eb;" ++
411+ "font:400 15px/1.6 ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif}" ++
412+ "main{text-align:center;padding:2.5rem 2rem}" ++
413+ ".mark{width:52px;height:52px;margin:0 auto 22px;border-radius:14px;" ++
414+ "display:grid;place-items:center;font-size:20px;font-weight:600;" ++
415+ "text-transform:uppercase;background:#12161b;border:1px solid #232a33}" ++
416+ ".ok{color:#8fd6a4}" ++
417+ ".err{color:#e08f8f}" ++
418+ "h1{margin:0 0 6px;font-size:16px;font-weight:600;letter-spacing:-.01em}" ++
419+ "p{margin:0;color:#7d868f;font-size:13px}";
420+
421+const template =
422+ "<!doctype html><html lang=en style=\"background:#0b0d10\">" ++
423+ "<meta charset=utf-8>" ++
424+ "<meta name=viewport content=\"width=device-width,initial-scale=1\">" ++
425+ "<title>{s}</title><style>{s}</style>" ++
426+ "<main><div class=\"mark {s}\">{s}</div><h1>{s}</h1><p>{s}</p></main>";
427+
428+/// Dark by default, in `color-scheme` and in the inline html background, so the
429+/// browser never paints a white frame before the stylesheet applies.
430+fn page(a: std.mem.Allocator, name: []const u8, ok: bool) []const u8 {
431+ const initial = if (name.len > 0) name[0..1] else "m";
432+ const message = if (ok)
433+ "You're signed in. You can close this tab."
434+ else
435+ "Sign-in didn't complete. Check the terminal and try again.";
436+ return std.fmt.allocPrint(a, template, .{
437+ name,
438+ style,
439+ if (ok) "ok" else "err",
440+ initial,
441+ name,
442+ message,
443+ }) catch "<!doctype html><html style=\"background:#0b0d10\"><title>mini</title>";
444+}