xonecas.io
79113
Ma

mini-coding-agent / commit 0c6e4ce

feat: sign in with chatgpt to use the user's plan

`mini login` runs the Sign in with ChatGPT flow: PKCE against auth.openai.com, a loopback callback on 127.0.0.1:1455, then the token exchange and ID token verification against the published JWKS.

The credential lands in auth.json (0600, written through a temp file and a rename) and is refreshed per request under a single lock, so a rotating refresh token is never raced. A model marked "oauth": true takes its bearer from that record instead of the environment.

The callback page is dark, branded from the optional oauthRedirectBrand (24 chars, default Mini-coding-agent).

xonecas2026-10-19 0c6e4ce18ac0accb01af44d8a40c11e7cdab5307 parent 413b7bf

6 files changed

src/agent.zig+7−1
@@ -6,6 +6,7 @@ const platform = @import("platform.zig");
66 const tools = @import("tools.zig");
77 const session = @import("session.zig");
88 const config = @import("config.zig");
9+const auth = @import("auth.zig");
910 const time = @import("time.zig");
1011
1112 pub const Phase = enum { preparing, waiting_model, streaming, running_tool, snapshotting, pausing, idle };
@@ -185,6 +186,11 @@ pub fn runTurn(opts: Options, messages: *std.ArrayList(message_mod.Message), int
185186
186187 if (cancelled(opts, listener)) return;
187188 listener.emit(.{ .phase = .{ .phase = .waiting_model } });
189+ // An OAuth bearer expires, so it is renewed per step, not per session.
190+ var wire_model = model.*;
191+ if (wire_model.oauth) {
192+ if (auth.token(opts.cancel)) |bearer| wire_model.api_key = bearer;
193+ }
188194 var stream_ctx = StreamCtx{ .listener = listener };
189195 const assistant = opts.a.create(message_mod.AssistantMessage) catch {
190196 listener.emit(.{ .err = "out of memory" });
@@ -193,7 +199,7 @@ pub fn runTurn(opts: Options, messages: *std.ArrayList(message_mod.Message), int
193199 assistant.* = api.stream(.{
194200 .pers = opts.a,
195201 .scratch = scratch,
196- .model = model,
202+ .model = &wire_model,
197203 .system_prompt = opts.system_prompt,
198204 .tools_json = opts.tools_json,
199205 .messages = messages.items,
src/auth.zig+170−0
@@ -0,0 +1,170 @@
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 time = @import("time.zig");
7+
8+pub const token_url = "https://auth.openai.com/api/accounts/oauth/token";
9+pub const scope_url = "https://auth.openai.com/api/accounts/authorize";
10+pub const resource = "https://api.openai.com/v1";
11+pub const plan_scope = "chatgpt.tokens.use.direct";
12+
13+/// The credential `mini login` writes. Keys are camelCase to match the other
14+/// files in the config directory.
15+pub const Record = struct {
16+ email: ?[]const u8 = null,
17+ clientId: []const u8,
18+ accessToken: []const u8,
19+ refreshToken: ?[]const u8 = null,
20+ idToken: ?[]const u8 = null,
21+ expiresAt: i64 = 0,
22+ scope: []const u8 = "",
23+};
24+
25+pub fn path(a: std.mem.Allocator) []const u8 {
26+ return filesystem.join(a, &.{ config.configDir(a), "auth.json" }) catch "auth.json";
27+}
28+
29+pub fn load(a: std.mem.Allocator) ?Record {
30+ const text = filesystem.readFileAlloc(a, path(a), 1 << 20) catch return null;
31+ return std.json.parseFromSliceLeaky(Record, a, text, .{ .ignore_unknown_fields = true }) catch null;
32+}
33+
34+/// Written to a temporary file and renamed, so a crash mid-write cannot leave a
35+/// truncated credential with the refresh token already rotated.
36+pub fn save(a: std.mem.Allocator, record: Record) !void {
37+ const json = try std.json.Stringify.valueAlloc(a, record, .{ .whitespace = .indent_2 });
38+ const out = try std.fmt.allocPrint(a, "{s}\n", .{json});
39+ const target = path(a);
40+ const temp = try std.fmt.allocPrint(a, "{s}.tmp", .{target});
41+ try filesystem.writeFile(temp, out);
42+ try std.Io.Dir.cwd().rename(temp, std.Io.Dir.cwd(), target, platform.io);
43+}
44+
45+pub fn available(a: std.mem.Allocator) bool {
46+ return filesystem.fileExists(path(a));
47+}
48+
49+/// True when the granted `scope` string contains `name`.
50+pub fn granted(scope: []const u8, name: []const u8) bool {
51+ var it = std.mem.tokenizeAny(u8, scope, " +");
52+ while (it.next()) |s| {
53+ if (std.mem.eql(u8, s, name)) return true;
54+ }
55+ return false;
56+}
57+
58+pub const TokenResponse = struct {
59+ access_token: ?[]const u8 = null,
60+ refresh_token: ?[]const u8 = null,
61+ id_token: ?[]const u8 = null,
62+ expires_in: ?u64 = null,
63+ scope: ?[]const u8 = null,
64+};
65+
66+var no_cancel = std.atomic.Value(bool).init(false);
67+
68+/// POSTs an already encoded grant to the token endpoint. Null on any failure;
69+/// the reason is printed once and never retried.
70+pub fn tokenRequest(a: std.mem.Allocator, body: []const u8, cancel: ?*const std.atomic.Value(bool)) ?TokenResponse {
71+ const response = http.post(a, token_url, &.{
72+ .{ .name = "Content-Type", .value = "application/x-www-form-urlencoded" },
73+ .{ .name = "Accept", .value = "application/json" },
74+ }, body, cancel orelse &no_cancel) catch {
75+ platform.printErr("sign-in: token request failed\n", .{});
76+ return null;
77+ };
78+ if (response.status != 200) {
79+ platform.printErr("sign-in: token endpoint returned {d} {s}\n", .{ response.status, response.body });
80+ return null;
81+ }
82+ return std.json.parseFromSliceLeaky(TokenResponse, a, response.body, .{ .ignore_unknown_fields = true }) catch null;
83+}
84+
85+/// RFC 3986 percent encoding. A space becomes `%20`, which is also valid in an
86+/// `application/x-www-form-urlencoded` body, so one encoder serves both.
87+pub fn appendEncoded(a: std.mem.Allocator, out: *std.ArrayList(u8), value: []const u8) !void {
88+ const hex = "0123456789ABCDEF";
89+ for (value) |c| {
90+ switch (c) {
91+ 'A'...'Z', 'a'...'z', '0'...'9', '-', '.', '_', '~' => try out.append(a, c),
92+ else => {
93+ try out.append(a, '%');
94+ try out.append(a, hex[c >> 4]);
95+ try out.append(a, hex[c & 0xf]);
96+ },
97+ }
98+ }
99+}
100+
101+pub fn form(a: std.mem.Allocator, pairs: []const [2][]const u8) ![]u8 {
102+ var out: std.ArrayList(u8) = .empty;
103+ for (pairs, 0..) |pair, i| {
104+ if (i > 0) try out.append(a, '&');
105+ try appendEncoded(a, &out, pair[0]);
106+ try out.append(a, '=');
107+ try appendEncoded(a, &out, pair[1]);
108+ }
109+ return out.toOwnedSlice(a);
110+}
111+
112+/// One credential, one lock. Refreshes are serialized so two turns cannot race
113+/// the rotating refresh token.
114+pub const Session = struct {
115+ mutex: std.Io.Mutex = .init,
116+ record: Record,
117+
118+ /// The record owns its strings for the life of the process, so a caller's
119+ /// scratch allocator can be reset between requests without dangling it.
120+ pub fn access(self: *Session, cancel: *const std.atomic.Value(bool)) ?[]const u8 {
121+ const a = platform.gpa;
122+ self.mutex.lockUncancelable(platform.io);
123+ defer self.mutex.unlock(platform.io);
124+ if (self.record.expiresAt - time.nowMs() > 60_000) return self.record.accessToken;
125+ const next = self.renew(a, cancel) orelse return null;
126+ save(a, next) catch platform.printErr("sign-in: could not persist the refreshed credential\n", .{});
127+ self.record = next;
128+ return self.record.accessToken;
129+ }
130+
131+ fn renew(self: *Session, a: std.mem.Allocator, cancel: *const std.atomic.Value(bool)) ?Record {
132+ const refresh = self.record.refreshToken orelse return null;
133+ const body = form(a, &.{
134+ .{ "grant_type", "refresh_token" },
135+ .{ "client_id", self.record.clientId },
136+ .{ "refresh_token", refresh },
137+ .{ "resource", resource },
138+ }) catch return null;
139+ const response = tokenRequest(a, body, cancel) orelse return null;
140+ const bearer = response.access_token orelse return null;
141+ return .{
142+ .email = self.record.email,
143+ .clientId = self.record.clientId,
144+ .accessToken = bearer,
145+ .refreshToken = response.refresh_token orelse self.record.refreshToken,
146+ .idToken = response.id_token orelse self.record.idToken,
147+ .expiresAt = time.nowMs() + @as(i64, @intCast(response.expires_in orelse 3600)) * 1000,
148+ .scope = response.scope orelse self.record.scope,
149+ };
150+ }
151+};
152+
153+var session: ?Session = null;
154+var init_mutex: std.Io.Mutex = .init;
155+
156+/// The process-wide credential, loaded on first use and then kept in memory for
157+/// the life of the process. A `mini login` in another process is only visible to
158+/// a new one.
159+pub fn token(cancel: *const std.atomic.Value(bool)) ?[]const u8 {
160+ init_mutex.lockUncancelable(platform.io);
161+ if (session == null) {
162+ const record = load(platform.gpa) orelse {
163+ init_mutex.unlock(platform.io);
164+ return null;
165+ };
166+ session = .{ .record = record };
167+ }
168+ init_mutex.unlock(platform.io);
169+ return session.?.access(cancel);
170+}
src/config.zig+6−1
@@ -22,6 +22,7 @@ pub const CustomModel = struct {
2222 reasoning: bool,
2323 effort: []const []const u8 = &.{},
2424 cost: [3]f64,
25+ oauth: bool = false,
2526 };
2627
2728 pub const CustomProvider = struct {
@@ -56,6 +57,7 @@ pub const Config = struct {
5657 snapshot_uses_gitignore: bool,
5758 history_size: usize,
5859 max_diff_lines: usize,
60+ oauth_redirect_brand: ?[]const u8,
5961 };
6062
6163 const File = struct {
@@ -76,6 +78,7 @@ const File = struct {
7678 showImages: ?bool = null,
7779 snapshotIgnoreDirs: ?[]const []const u8 = null,
7880 snapshotUsesGitignore: ?bool = null,
81+ oauthRedirectBrand: ?[]const u8 = null,
7982 };
8083
8184 /// An empty environment variable is treated as unset, per the XDG spec.
@@ -84,7 +87,7 @@ fn xdg(key: []const u8) ?[]const u8 {
8487 return if (value.len == 0) null else value;
8588 }
8689
87-fn configDir(a: std.mem.Allocator) []const u8 {
90+pub fn configDir(a: std.mem.Allocator) []const u8 {
8891 const base = xdg("XDG_CONFIG_HOME") orelse
8992 filesystem.join(a, &.{ platform.home() orelse "", ".config" }) catch "";
9093 return filesystem.join(a, &.{ base, "mini-coding-agent" }) catch "mini-coding-agent";
@@ -157,6 +160,7 @@ fn readInto(a: std.mem.Allocator, path: []const u8, required: bool, cfg: *Config
157160 if (file.snapshotUsesGitignore) |v| cfg.snapshot_uses_gitignore = v;
158161 if (file.historySize) |v| cfg.history_size = v;
159162 if (file.maxDiffLines) |v| cfg.max_diff_lines = v;
163+ if (file.oauthRedirectBrand) |v| cfg.oauth_redirect_brand = v;
160164 }
161165
162166 pub const Update = struct {
@@ -211,5 +215,6 @@ fn defaults(a: std.mem.Allocator) !Config {
211215 .snapshot_uses_gitignore = true,
212216 .history_size = 100,
213217 .max_diff_lines = 2000,
218+ .oauth_redirect_brand = null,
214219 };
215220 }
src/main.zig+9−1
@@ -10,6 +10,7 @@ const mcp = @import("mcp.zig");
1010 const tui = @import("tui/tui.zig");
1111 const term = @import("tui/term.zig");
1212 const headless = @import("headless.zig");
13+const siwc = @import("siwc.zig");
1314
1415 pub const panic = std.debug.FullPanic(panicRestore);
1516
@@ -27,7 +28,7 @@ pub const debug = struct {
2728
2829 var cancel = std.atomic.Value(bool).init(false);
2930
30-const ParsedArgs = struct { print: ?[]const u8 = null, config: ?[]const u8 = null };
31+const ParsedArgs = struct { print: ?[]const u8 = null, config: ?[]const u8 = null, login: bool = false };
3132
3233 fn parseArgs(a: std.mem.Allocator) !ParsedArgs {
3334 var it = std.process.Args.Iterator.init(platform.args);
@@ -43,6 +44,8 @@ fn parseArgs(a: std.mem.Allocator) !ParsedArgs {
4344 result.print = try a.dupe(u8, value);
4445 } else if (std.mem.startsWith(u8, arg, "--config=")) {
4546 result.config = try a.dupe(u8, arg["--config=".len..]);
47+ } else if (std.mem.eql(u8, arg, "login")) {
48+ result.login = true;
4649 } else if (std.mem.eql(u8, arg, "-c") or std.mem.eql(u8, arg, "--config")) {
4750 const value = it.next() orelse return error.MissingConfig;
4851 result.config = try a.dupe(u8, value);
@@ -107,6 +110,11 @@ fn run() !u8 {
107110
108111 const cfg = config.load(a, args.config) catch return 1;
109112
113+ if (args.login) {
114+ siwc.login(a, &cfg) catch return 1;
115+ return 0;
116+ }
117+
110118 var resolve_err: ?[]const u8 = null;
111119 const model = models.resolve(a, &cfg, &resolve_err);
112120 if (resolve_err) |message| {
src/models.zig+9−0
@@ -3,6 +3,7 @@ const platform = @import("platform.zig");
33 const modelsdev = @import("models_dev.zig");
44 const http = @import("http.zig");
55 const config = @import("config.zig");
6+const auth = @import("auth.zig");
67
78 pub const Thinking = enum { off, budget, effort };
89
@@ -23,6 +24,8 @@ pub const Model = struct {
2324 session_header: ?[]const u8,
2425 headers: []const [2][]const u8 = &.{},
2526 thinking: Thinking = .budget,
27+ /// The bearer comes from the OAuth credential record, not from the environment.
28+ oauth: bool = false,
2629 };
2730
2831 const Builtin = struct {
@@ -150,6 +153,11 @@ pub fn resolveNamed(a: std.mem.Allocator, cfg: *const config.Config, provider_id
150153 if (custom(cfg, provider_id)) |p| {
151154 for (p.models) |m| {
152155 if (!std.mem.eql(u8, m.id, model_id)) continue;
156+ if (m.oauth and !auth.available(a)) {
157+ err.* = std.fmt.allocPrint(a, "provider \"{s}\" is not signed in; run `mini login`", .{provider_id}) catch
158+ "not signed in; run `mini login`";
159+ return null;
160+ }
153161 return Model{
154162 .id = m.id,
155163 .name = m.name orelse m.id,
@@ -166,6 +174,7 @@ pub fn resolveNamed(a: std.mem.Allocator, cfg: *const config.Config, provider_id
166174 .cost_cache_read = m.cost[2],
167175 .session_header = null,
168176 .headers = headerPairs(a, p.headers),
177+ .oauth = m.oauth,
169178 };
170179 }
171180 err.* = unknownModel(a, model_id, provider_id);
src/siwc.zig+444−0
@@ -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+}