Skip to content

Commit ce9ce83

Browse files
committed
fix(oauth): use Codex CLI registered redirect URI and add callback listener
OpenAI's OAuth client (app_EMoamEEZ73f0CkXaXp7hrann) requires redirect_uri to be http://localhost:1455/auth/callback — this is what's registered for the Codex CLI client ID used by all third-party tools. Add temporary HttpListener in OAuthPkceService.ListenForCallbackAsync that binds to the redirect URI's port during the OAuth flow and shuts down after the callback arrives. Add OAuthExtraAuthParams to IProviderDescriptor for provider-specific authorization URL parameters. OpenAI requires id_token_add_organizations, codex_cli_simplified_flow, and originator. Sources documented in OpenAiDescriptor: - OpenCode: anomalyco/opencode#3281 - codex-oauth: https://github.com/7shi/codex-oauth - OpenClaw: https://docs.openclaw.ai/concepts/oauth Refs #173, #191
1 parent e9d0a69 commit ce9ce83

4 files changed

Lines changed: 107 additions & 4 deletions

File tree

‎src/Netclaw.Configuration/Providers/Descriptors/OpenAiDescriptor.cs‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,32 @@ public OpenAiDescriptor(HttpClient httpClient)
2323
public string? ApiKeyGuidanceUrl => "https://platform.openai.com/api-keys";
2424
public string? OAuthDeviceEndpoint => "https://auth.openai.com/api/accounts/deviceauth/usercode";
2525
public string? OAuthTokenEndpoint => "https://auth.openai.com/oauth/token";
26-
public string? OAuthDefaultClientId => "app_EMoamEEZ73f0CkXaXp7hrann";
2726
public string? OAuthPollingEndpoint => "https://auth.openai.com/api/accounts/deviceauth/token";
2827
public bool UseProprietaryDeviceFlow => true;
2928
public string? OAuthScope => "openid profile email offline_access";
3029
public string? OAuthAuthorizationEndpoint => "https://auth.openai.com/oauth/authorize";
31-
public string? OAuthRedirectUri => "http://127.0.0.1:5199/api/provider/oauth/callback";
30+
31+
// The Codex CLI public client ID. All third-party tools (OpenCode, OpenClaw, etc.) reuse
32+
// this because OpenAI does not provide a public API for registering custom OAuth clients.
33+
// The redirect_uri and extra auth params below must match what's registered for this client.
34+
// Sources:
35+
// - OpenCode: https://github.com/anomalyco/opencode/issues/3281
36+
// - codex-oauth: https://github.com/7shi/codex-oauth
37+
// - OpenClaw: https://docs.openclaw.ai/concepts/oauth
38+
public string? OAuthDefaultClientId => "app_EMoamEEZ73f0CkXaXp7hrann";
39+
40+
// Port 1455 and path /auth/callback are registered with OpenAI for the Codex CLI client ID.
41+
// Using any other redirect_uri produces "unknown_error" from auth.openai.com.
42+
public string? OAuthRedirectUri => "http://localhost:1455/auth/callback";
43+
44+
// OpenAI-specific authorization parameters required by the Codex OAuth flow.
45+
// Without these, the authorization endpoint returns errors.
46+
public IReadOnlyDictionary<string, string>? OAuthExtraAuthParams => new Dictionary<string, string>
47+
{
48+
["id_token_add_organizations"] = "true",
49+
["codex_cli_simplified_flow"] = "true",
50+
["originator"] = "netclaw",
51+
};
3252

3353
public Task<ProviderProbeResult> ProbeAsync(
3454
ProviderEntry entry, CancellationToken ct = default)

‎src/Netclaw.Configuration/Providers/IProviderDescriptor.cs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,13 @@ public interface IProviderDescriptor
7272
/// </summary>
7373
string? OAuthRedirectUri => null;
7474

75+
/// <summary>
76+
/// Extra query parameters to include in the authorization URL.
77+
/// Provider-specific parameters required by the OAuth endpoint.
78+
/// Null if no extra parameters are needed.
79+
/// </summary>
80+
IReadOnlyDictionary<string, string>? OAuthExtraAuthParams => null;
81+
7582
/// <summary>
7683
/// Polling endpoint for proprietary device flows (e.g. OpenAI's
7784
/// <c>/api/accounts/deviceauth/token</c>). Null for standard RFC 8628 flows

‎src/Netclaw.Configuration/Providers/OAuth/OAuthPkceService.cs‎

Lines changed: 73 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ public OAuthPkceService(HttpClient httpClient, TimeProvider? timeProvider = null
3333
string tokenEndpoint,
3434
string clientId,
3535
string redirectUri,
36-
string? scope = null)
36+
string? scope = null,
37+
IReadOnlyDictionary<string, string>? extraParams = null)
3738
{
3839
var codeVerifier = GenerateCodeVerifier();
3940
var codeChallenge = ComputeCodeChallenge(codeVerifier);
@@ -52,6 +53,12 @@ public OAuthPkceService(HttpClient httpClient, TimeProvider? timeProvider = null
5253
if (!string.IsNullOrWhiteSpace(scope))
5354
queryParams["scope"] = scope;
5455

56+
if (extraParams is not null)
57+
{
58+
foreach (var (key, value) in extraParams)
59+
queryParams[key] = value;
60+
}
61+
5562
var authUrl = authorizationEndpoint + "?" + string.Join("&",
5663
queryParams.Select(kv => $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value)}"));
5764

@@ -169,6 +176,71 @@ public async Task<OAuthDeviceFlowResult> ExchangeCodeForTokensAsync(
169176
return result;
170177
}
171178

179+
/// <summary>
180+
/// Start a temporary HTTP listener on the redirect URI's port to receive the OAuth callback.
181+
/// Listens until the callback arrives or the cancellation token fires.
182+
/// On callback, exchanges the authorization code for tokens and completes the pending flow.
183+
/// </summary>
184+
public async Task<OAuthDeviceFlowResult> ListenForCallbackAsync(
185+
string redirectUri, string state, CancellationToken ct = default)
186+
{
187+
// Extract the listener prefix from the redirect URI (e.g., "http://localhost:1455/")
188+
var uri = new Uri(redirectUri);
189+
var prefix = $"{uri.Scheme}://{uri.Host}:{uri.Port}/";
190+
191+
using var listener = new System.Net.HttpListener();
192+
listener.Prefixes.Add(prefix);
193+
listener.Start();
194+
195+
try
196+
{
197+
while (!ct.IsCancellationRequested)
198+
{
199+
var contextTask = listener.GetContextAsync();
200+
var completedTask = await Task.WhenAny(contextTask, Task.Delay(Timeout.Infinite, ct));
201+
202+
if (completedTask != contextTask)
203+
throw new OperationCanceledException(ct);
204+
205+
var context = await contextTask;
206+
var request = context.Request;
207+
var query = request.QueryString;
208+
209+
var code = query["code"];
210+
var callbackState = query["state"];
211+
212+
if (!string.IsNullOrEmpty(code) && callbackState == state)
213+
{
214+
// Send success HTML response to the browser
215+
var responseBytes = System.Text.Encoding.UTF8.GetBytes(
216+
"<html><body><h2>Authorization complete</h2><p>You may close this tab and return to the terminal.</p></body></html>");
217+
context.Response.ContentType = "text/html";
218+
context.Response.ContentLength64 = responseBytes.Length;
219+
await context.Response.OutputStream.WriteAsync(responseBytes, ct);
220+
context.Response.Close();
221+
222+
// Exchange code for tokens
223+
return await CompleteAuthorizationAsync(code, state, ct);
224+
}
225+
226+
// Wrong request — send error and keep listening
227+
var errorBytes = System.Text.Encoding.UTF8.GetBytes(
228+
"<html><body><h2>Authorization failed</h2><p>Missing or mismatched parameters.</p></body></html>");
229+
context.Response.StatusCode = 400;
230+
context.Response.ContentType = "text/html";
231+
context.Response.ContentLength64 = errorBytes.Length;
232+
await context.Response.OutputStream.WriteAsync(errorBytes, ct);
233+
context.Response.Close();
234+
}
235+
236+
throw new OperationCanceledException(ct);
237+
}
238+
finally
239+
{
240+
listener.Stop();
241+
}
242+
}
243+
172244
/// <summary>
173245
/// Get the status of a pending flow by state.
174246
/// </summary>

‎src/Netclaw.Daemon/Program.cs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,11 @@ await context.Response.WriteAsync(
162162
descriptor.OAuthTokenEndpoint,
163163
descriptor.OAuthDefaultClientId,
164164
descriptor.OAuthRedirectUri,
165-
descriptor.OAuthScope);
165+
descriptor.OAuthScope,
166+
descriptor.OAuthExtraAuthParams);
167+
168+
// Start temporary callback listener on the redirect URI's port
169+
_ = pkceService.ListenForCallbackAsync(descriptor.OAuthRedirectUri, state);
166170

167171
return Results.Ok(new { authorizationUrl = authUrl, state });
168172
});

0 commit comments

Comments
 (0)