graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Browser sign-ins wait for their own redirect
justrachaac5b7686298
diff --git a/src/mcp_oauth.zig b/src/mcp_oauth.zigindex 75f85e4e..75d6e68d 100644--- a/src/mcp_oauth.zig+++ b/src/mcp_oauth.zig@@ -6,6 +6,7 @@ const builtin = @import("builtin");const util = @import("util.zig");const discovery = @import("mcp_oauth_discovery.zig");const credential_store = @import("credential_store.zig");+const callback = @import("oauth_callback.zig");const Io = std.Io;const Allocator = std.mem.Allocator;@@ -415,36 +416,25 @@ fn loginInner(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, serverquery,});- var address = std.Io.net.IpAddress.parseLiteral("127.0.0.1:1456") catch return error.BadOAuthResponse;- var listener = try std.Io.net.IpAddress.listen(&address, io, .{});+ var listener = try callback.listen(io, 1456);defer listener.deinit(io);try out.print("\nOpen this URL to authorize (the browser should open automatically):\n\n{s}\n\nWaiting for the callback on {s} …\n", .{ authorization_url, redirect_uri });try out.flush();openBrowser(io, authorization_url);- const stream = try listener.accept(io);- defer stream.close(io);+ // Only this attempt's redirect (its state) ends the wait.var read_buffer: [16 * 1024]u8 = undefined;- var reader = std.Io.net.Stream.Reader.init(stream, io, &read_buffer);- const request_line = (reader.interface.takeDelimiter('\n') catch null) orelse return error.BadOAuthResponse;- const code = try queryParam(arena, request_line, "code") orelse {- const description = try queryParam(arena, request_line, "error_description") orelse- try queryParam(arena, request_line, "error") orelse "authorization server returned no code";+ const cb = try callback.wait(io, &listener, "/callback", state, &read_buffer);+ defer cb.stream.close(io);+ const code = try queryParam(arena, cb.line, "code") orelse {+ callback.answer(io, cb.stream, "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nOAuth authorization failed. Return to the CLI.\n");+ const description = try queryParam(arena, cb.line, "error_description") orelse+ try queryParam(arena, cb.line, "error") orelse "authorization server returned no code";try out.print("OAuth authorization failed: {s}\n", .{description});try out.flush();return error.AuthorizationDenied;};- const returned_state = try queryParam(arena, request_line, "state") orelse return error.StateMismatch;-- var write_buffer: [2048]u8 = undefined;- var stream_writer = std.Io.net.Stream.Writer.init(stream, io, &write_buffer);- if (!std.mem.eql(u8, state, returned_state)) {- try stream_writer.interface.writeAll("HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nOAuth state mismatch. Return to the CLI and try again.\n");- try stream_writer.interface.flush();- return error.StateMismatch;- }- try stream_writer.interface.writeAll("HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\nMCP authorization complete. You can close this tab.\n");- try stream_writer.interface.flush();+ callback.answer(io, cb.stream, "HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\nMCP authorization complete. You can close this tab.\n");var fields = [_]struct { []const u8, []const u8 }{.{ "grant_type", "authorization_code" },diff --git a/src/oauth.zig b/src/oauth.zigindex e3eb75e0..8559d33d 100644--- a/src/oauth.zig+++ b/src/oauth.zig@@ -20,6 +20,7 @@ const writeCodexAuth = helpers.writeCodexAuth;const codex_login_page_html = helpers.codex_login_page_html;const queryParam = helpers.queryParam;const openBrowser = helpers.openBrowser;+const callback = @import("oauth_callback.zig");const ansi = @import("ansi.zig");const style = &ansi.style;@@ -136,41 +137,31 @@ pub fn codexLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, re// Bind the callback port BEFORE opening the browser, so the redirect// can't arrive before we're listening.- var addr = std.Io.net.IpAddress.parseLiteral("127.0.0.1:1455") catch return error.BadOAuthResponse;- var server = try std.Io.net.IpAddress.listen(&addr, io, .{});+ var server = try callback.listen(io, 1455);defer server.deinit(io);try out.print("\nOpen this URL to authorize (browser should open automatically):\n\n{s}\n\nwaiting for the callback on {s} …\n", .{ url, codex_redirect });try out.flush();openBrowser(io, url);- const stream = try server.accept(io);- defer stream.close(io);-+ // Only this attempt's redirect ends the wait (oauth_callback.zig).var rbuf: [16 * 1024]u8 = undefined;- var sr = std.Io.net.Stream.Reader.init(stream, io, &rbuf);- const req_line = (sr.interface.takeDelimiter('\n') catch null) orelse return error.BadOAuthResponse;-- // Branded, dark-mode-aware confirmation card (charset utf-8 so the ✓/◆- // render) so the callback tab shows a real "you're all set" page, not a- // bare line — then we read the code out of the same request below.- const page = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nConnection: close\r\n\r\n" ++ codex_login_page_html;- var wbuf: [4096]u8 = undefined;- var sw = std.Io.net.Stream.Writer.init(stream, io, &wbuf);- sw.interface.writeAll(page) catch {};- sw.interface.flush() catch {};-- const code = queryParam(req_line, "code") orelse {- try out.writeAll("✗ no authorization code in callback\n");+ const cb = callback.wait(io, &server, "/auth/callback", state, &rbuf) catch |err| {+ if (err != error.Cancelled) return err;+ try out.writeAll("✗ sign-in cancelled: a newer login took over the callback port\n");try out.flush();return;};- const got_state = queryParam(req_line, "state") orelse "";- if (!std.mem.eql(u8, got_state, state)) {- try out.writeAll("✗ state mismatch — possible CSRF, aborting\n");+ defer cb.stream.close(io);+ const code = queryParam(cb.line, "code") orelse {+ callback.answer(io, cb.stream, "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\nSign-in failed. Return to the terminal.\n");+ try out.print("✗ sign-in failed: {s}\n", .{queryParam(cb.line, "error") orelse "no authorization code in the callback"});try out.flush();return;- }+ };+ // Branded, dark-mode-aware confirmation card (charset utf-8 so the ✓/◆+ // render) so the callback tab shows a real "you're all set" page.+ callback.answer(io, cb.stream, "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nConnection: close\r\n\r\n" ++ codex_login_page_html);body = try std.fmt.allocPrint(arena, "grant_type=authorization_code&client_id={s}&code={s}&redirect_uri={s}&code_verifier={s}", .{ codex_client_id, code, codex_redirect_enc, verifier });}diff --git a/src/oauth_callback.zig b/src/oauth_callback.zignew file mode 100644index 00000000..b63de709--- /dev/null+++ b/src/oauth_callback.zig@@ -0,0 +1,162 @@+//! The loopback half of a browser sign-in: wait on the callback port for the+//! redirect that belongs to this attempt. A browser reaches the port for other+//! reasons too: a connection opened ahead of time and dropped unused, a+//! /favicon.ico, a tab left from an earlier attempt. None of those may end the+//! wait. The codex login used to answer only the first connection, so a spare+//! connection the browser closed unused ended it, and the real redirect then+//! found the port closed ("connection refused").++const std = @import("std");+const Io = std.Io;+const queryParam = @import("oauth_helpers.zig").queryParam;++pub const not_found = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";+const stale_page = "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\nThis sign-in page is from an earlier attempt. Finish the newest one, or start the login again.\n";+const cancelled_page = "HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\nSign-in cancelled.\n";++pub const Kind = enum { other, stale, cancel, mine };++/// One request line on the callback port: this attempt's redirect (its+/// `state`), a redirect from an earlier attempt, a /cancel from a newer+/// sign-in that needs the port, or anything else.+pub fn classify(req_line: []const u8, path: []const u8, state: []const u8) Kind {+ var parts = std.mem.tokenizeScalar(u8, req_line, ' ');+ _ = parts.next() orelse return .other;+ const target = parts.next() orelse return .other;+ const route = target[0 .. std.mem.indexOfScalar(u8, target, '?') orelse target.len];+ if (std.mem.eql(u8, route, "/cancel")) return .cancel;+ if (!std.mem.eql(u8, route, path)) return .other;+ const got = queryParam(req_line, "state") orelse return .stale;+ return if (std.mem.eql(u8, got, state)) .mine else .stale;+}++/// This attempt's redirect. `line` points into the caller's buffer; answer on+/// `stream`, then close it.+pub const Callback = struct { stream: Io.net.Stream, line: []const u8 };++/// Accept until this attempt's redirect arrives, answering and skipping+/// everything else. error.Cancelled: a newer sign-in asked for the port.+pub fn wait(io: Io, server: *Io.net.Server, path: []const u8, state: []const u8, buf: []u8) !Callback {+ while (true) {+ const stream = try server.accept(io);+ var reader = Io.net.Stream.Reader.init(stream, io, buf);+ const line = (reader.interface.takeDelimiter('\n') catch null) orelse {+ stream.close(io); // closed before sending a request+ continue;+ };+ const kind = classify(line, path, state);+ if (kind == .mine) return .{ .stream = stream, .line = line };+ answer(io, stream, switch (kind) {+ .stale => stale_page,+ .cancel => cancelled_page,+ else => not_found,+ });+ stream.close(io);+ if (kind == .cancel) return error.Cancelled;+ }+}++pub fn answer(io: Io, stream: Io.net.Stream, response: []const u8) void {+ var wbuf: [1024]u8 = undefined;+ var w = Io.net.Stream.Writer.init(stream, io, &wbuf);+ w.interface.writeAll(response) catch {};+ w.interface.flush() catch {};+}++/// Bind 127.0.0.1:`port` for the redirect. When an earlier sign-in still+/// holds it (graff's or the Codex CLI's; both answer /cancel), ask it to let+/// go and retry for about two seconds, as the Codex CLI's own login does.+pub fn listen(io: Io, port: u16) !Io.net.Server {+ var buf: [32]u8 = undefined;+ var addr = try Io.net.IpAddress.parseLiteral(try std.fmt.bufPrint(&buf, "127.0.0.1:{d}", .{port}));+ var tries: usize = 0;+ while (true) : (tries += 1) {+ return Io.net.IpAddress.listen(&addr, io, .{}) catch |err| {+ if (err != error.AddressInUse or tries == 10) return err;+ if (tries == 0) cancelHolder(io, &addr);+ io.sleep(.fromMilliseconds(200), .awake) catch {};+ continue;+ };+ }+}++fn cancelHolder(io: Io, addr: *const Io.net.IpAddress) void {+ const stream = addr.connect(io, .{ .mode = .stream }) catch return;+ defer stream.close(io);+ answer(io, stream, "GET /cancel HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n");+}++test "classify: only this attempt's redirect is the callback" {+ const s = "Nh-So_9HxnY6gdCtrPC_ig";+ try std.testing.expectEqual(Kind.mine, classify("GET /auth/callback?code=ac_1&scope=openid&state=" ++ s ++ " HTTP/1.1\r", "/auth/callback", s));+ try std.testing.expectEqual(Kind.mine, classify("GET /auth/callback?error=access_denied&state=" ++ s ++ " HTTP/1.1\r", "/auth/callback", s));+ try std.testing.expectEqual(Kind.stale, classify("GET /auth/callback?code=ac_0&state=older HTTP/1.1\r", "/auth/callback", s));+ try std.testing.expectEqual(Kind.stale, classify("GET /auth/callback?code=ac_0 HTTP/1.1\r", "/auth/callback", s));+ try std.testing.expectEqual(Kind.other, classify("GET /favicon.ico HTTP/1.1\r", "/auth/callback", s));+ try std.testing.expectEqual(Kind.other, classify("GET /auth/callbackx?state=" ++ s ++ " HTTP/1.1\r", "/auth/callback", s));+ try std.testing.expectEqual(Kind.other, classify("", "/auth/callback", s));+ try std.testing.expectEqual(Kind.cancel, classify("GET /cancel HTTP/1.1\r", "/auth/callback", s));+}++const Visitor = struct {+ fn send(io: Io, port: u16, request: []const u8) []const u8 {+ var buf: [32]u8 = undefined;+ const addr = Io.net.IpAddress.parseLiteral(std.fmt.bufPrint(&buf, "127.0.0.1:{d}", .{port}) catch return "") catch return "";+ const stream = addr.connect(io, .{ .mode = .stream }) catch return "";+ defer stream.close(io);+ if (request.len == 0) return ""; // connect and hang up, like a spare browser connection+ answer(io, stream, request);+ var rbuf: [256]u8 = undefined;+ var r = Io.net.Stream.Reader.init(stream, io, &rbuf);+ const status = (r.interface.takeDelimiter('\n') catch null) orelse return "";+ if (std.mem.startsWith(u8, status, "HTTP/1.1 404")) return "404";+ if (std.mem.startsWith(u8, status, "HTTP/1.1 400")) return "400";+ return "other";+ }++ fn run(io: Io, port: u16, statuses: *[3][]const u8) void {+ _ = send(io, port, "");+ statuses[0] = send(io, port, "GET /favicon.ico HTTP/1.1\r\nHost: localhost\r\n\r\n");+ statuses[1] = send(io, port, "GET /auth/callback?code=ac_old&state=older HTTP/1.1\r\nHost: localhost\r\n\r\n");+ statuses[2] = send(io, port, "GET /auth/callback?code=ac_new&state=s1 HTTP/1.1\r\nHost: localhost\r\n\r\n");+ }+};++test "wait: a dropped connection, a favicon and an older tab do not end the sign-in" {+ const io = std.testing.io;+ var server = try listen(io, 0);+ defer server.deinit(io);+ var statuses: [3][]const u8 = .{ "", "", "" };+ var group: Io.Group = .init;+ defer group.cancel(io);+ try group.concurrent(io, Visitor.run, .{ io, server.socket.address.getPort(), &statuses });+ var buf: [4096]u8 = undefined;+ const cb = try wait(io, &server, "/auth/callback", "s1", &buf);+ try std.testing.expectEqualStrings("ac_new", queryParam(cb.line, "code").?);+ answer(io, cb.stream, "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");+ cb.stream.close(io);+ try group.await(io);+ try std.testing.expectEqualStrings("404", statuses[0]);+ try std.testing.expectEqualStrings("400", statuses[1]);+ try std.testing.expectEqualStrings("other", statuses[2]);+}++fn waitForCancel(io: Io, server: *Io.net.Server, got: *?anyerror) void {+ var buf: [1024]u8 = undefined;+ if (wait(io, server, "/auth/callback", "s1", &buf)) |cb| cb.stream.close(io) else |err| got.* = err;+ server.deinit(io);+}++test "listen: a newer sign-in takes the port from one still waiting" {+ const io = std.testing.io;+ var first = try listen(io, 0);+ const port = first.socket.address.getPort();+ var got: ?anyerror = null;+ var group: Io.Group = .init;+ defer group.cancel(io);+ try group.concurrent(io, waitForCancel, .{ io, &first, &got });+ var second = try listen(io, port);+ defer second.deinit(io);+ try group.await(io);+ try std.testing.expectEqual(@as(?anyerror, error.Cancelled), got);+}diff --git a/src/oauth_chatgpt.zig b/src/oauth_chatgpt.zigindex 40255217..d3719b6f 100644--- a/src/oauth_chatgpt.zig+++ b/src/oauth_chatgpt.zig@@ -21,6 +21,7 @@ const helpers = @import("oauth_helpers.zig");const credential_store = @import("credential_store.zig");const jwt = @import("oauth_chatgpt_jwt.zig");const page = @import("oauth_chatgpt_page.zig");+const callback = @import("oauth_callback.zig");const authorize_url = jwt.issuer ++ "/api/accounts/authorize";const token_url = jwt.issuer ++ "/api/accounts/oauth/token";@@ -405,25 +406,19 @@ pub fn login(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !void {try out.print("waiting for the sign-in on {s} …\n", .{attempt.redirect});try out.flush();helpers.openBrowser(io, url);- while (true) {- const stream = try listener.server.accept(io);- defer stream.close(io);- var rbuf: [16 * 1024]u8 = undefined;- var sr = std.Io.net.Stream.Reader.init(stream, io, &rbuf);- const req_line = (sr.interface.takeDelimiter('\n') catch null) orelse continue;- var wbuf: [8192]u8 = undefined;- var sw = std.Io.net.Stream.Writer.init(stream, io, &wbuf);- const cb = parseCallback(arena, req_line) orelse {- sw.interface.writeAll(page.not_found) catch {};- sw.interface.flush() catch {};- continue;- };- // The browser waits on this response, so the page shows the outcome.- const outcome = finish(io, gpa, arena, home, saved, attempt, verifier, cb);- sw.interface.writeAll(page.response(arena, outcome.state, outcome.account) catch page.not_found) catch {};- sw.interface.flush() catch {};- return report(out, outcome);- }+ // Only this attempt's redirect ends the wait; a tab left from an earlier+ // attempt gets a page saying so (oauth_callback.zig).+ var rbuf: [16 * 1024]u8 = undefined;+ const conn = callback.wait(io, &listener.server, "/auth/callback", attempt.state, &rbuf) catch |err| {+ if (err != error.Cancelled) return err;+ return report(out, failed("a newer sign-in took over the callback port"));+ };+ defer conn.stream.close(io);+ const cb = parseCallback(arena, conn.line) orelse return report(out, failed("the callback could not be read"));+ // The browser waits on this response, so the page shows the outcome.+ const outcome = finish(io, gpa, arena, home, saved, attempt, verifier, cb);+ callback.answer(io, conn.stream, page.response(arena, outcome.state, outcome.account) catch page.not_found);+ return report(out, outcome);}var dead_refresh: u64 = 0;diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex c852dae1..6ca167a9 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -331,6 +331,7 @@ test {_ = agent_compact_summary_test;_ = side_question_tests;_ = @import("worker_mcp.zig"); // ADR 0227+ _ = @import("oauth_callback.zig");_ = @import("cache_key_tests.zig"); // ADR 0223: moved off http_headers.zig (600-line cap)_ = @import("mcp_shapes_tests.zig"); // ADR 0225: moved off mcp_shapes.zig (600-line cap)_ = json_controls;