Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

fix(connectors): keep provider error details on token failures

Jet Zhoufe8aaffb42a2
diff --git a/src/connectors/oauth.ts b/src/connectors/oauth.ts
index d7a6bdd85..3f96b2ca3 100644
--- a/src/connectors/oauth.ts
+++ b/src/connectors/oauth.ts
@@ -4,6 +4,7 @@ import { randomUUID, randomBytes, createHash } from "node:crypto";
import { decodeJwt } from "jose";
import { mintSignedPayload, verifySignedPayload } from "../auth/signed-token.ts";
import { swallow } from "../util/errors.ts";
+import { isObj } from "../util/objects.ts";
export const ACCOUNT_TYPES = ["default", "personal", "company"] as const;
export type AccountType = (typeof ACCOUNT_TYPES)[number];
@@ -95,6 +96,19 @@ function toToken(
};
}
+function oauthErrorDetail(body: unknown): string {
+ if (!isObj(body)) return "";
+ const nested = isObj(body.error) ? body.error : undefined;
+ const code = nested ? (nested.code ?? nested.type) : body.error;
+ const description = nested ? nested.message : (body.error_description ?? body.reason);
+ return [code, description].filter((part): part is string => typeof part === "string" && part.length > 0).join(": ");
+}
+
+export async function oauthFailure(action: string, res: { status: number; json(): Promise<unknown> }): Promise<Error> {
+ const detail = oauthErrorDetail(await res.json().catch(() => undefined));
+ return new Error(`${action} failed (${res.status})${detail ? `: ${detail}` : ""}`);
+}
+
const resourceBody = (p: OAuthProviderConfig): Record<string, string> =>
p.authParams?.resource ? { resource: p.authParams.resource } : {};
@@ -120,7 +134,7 @@ function makeTokenAdapters(opts: {
basic || !client.secret ? { client_id: client.id } : { client_id: client.id, client_secret: client.secret };
const checkErrorBody = (raw: Record<string, unknown>): void => {
if (opts.rejectErrorBody && raw.error)
- throw new Error(`${prefix}oauth error: ${String(raw.error_description ?? raw.error)}`);
+ throw new Error(`${prefix}oauth error: ${oauthErrorDetail(raw) || String(raw.error)}`);
};
return {
async exchange({ provider, client, code, redirectUri, fetchImpl, now, codeVerifier }) {
@@ -136,7 +150,7 @@ function makeTokenAdapters(opts: {
...resourceBody(provider),
}).toString(),
});
- if (!res.ok) throw new Error(`${prefix}token exchange failed (${res.status})`);
+ if (!res.ok) throw await oauthFailure(`${prefix}token exchange`, res);
const raw = (await res.json()) as Record<string, unknown>;
checkErrorBody(raw);
return { hosts: provider.hosts, token: toToken(raw, undefined, now), raw };
@@ -152,7 +166,7 @@ function makeTokenAdapters(opts: {
...resourceBody(provider),
}).toString(),
});
- if (!res.ok) throw new Error(`${prefix}token refresh failed (${res.status})`);
+ if (!res.ok) throw await oauthFailure(`${prefix}token refresh`, res);
const raw = (await res.json()) as Record<string, unknown>;
checkErrorBody(raw);
return toToken(raw, token.refreshToken, now, token.grantedScopes);
@@ -200,7 +214,7 @@ const slackExchange: OAuthExchangeAdapter = async ({ provider, client, code, red
client_secret: client.secret,
}).toString(),
});
- if (!res.ok) throw new Error(`slack token exchange failed (${res.status})`);
+ if (!res.ok) throw await oauthFailure("slack token exchange", res);
const raw = (await res.json()) as Record<string, unknown>;
if (raw.ok !== true) throw new Error(`slack oauth error: ${String(raw.error ?? "unknown")}`);
const authedUser = (raw.authed_user ?? {}) as Record<string, unknown>;
@@ -217,7 +231,7 @@ const notionExchange: OAuthExchangeAdapter = async ({ provider, client, code, re
headers: { "content-type": "application/json", authorization: `Basic ${basic}` },
body: JSON.stringify({ grant_type: "authorization_code", code, redirect_uri: redirectUri }),
});
- if (!res.ok) throw new Error(`notion token exchange failed (${res.status})`);
+ if (!res.ok) throw await oauthFailure("notion token exchange", res);
const raw = (await res.json()) as Record<string, unknown>;
const access = String(raw.access_token ?? "");
if (!access) throw new Error("notion token exchange returned no access_token");
diff --git a/src/model/subscription-oauth.ts b/src/model/subscription-oauth.ts
index d31ab4671..537674165 100644
--- a/src/model/subscription-oauth.ts
+++ b/src/model/subscription-oauth.ts
@@ -1,4 +1,4 @@
-import { codeChallengeS256, generateCodeVerifier } from "../connectors/oauth.ts";
+import { codeChallengeS256, generateCodeVerifier, oauthFailure } from "../connectors/oauth.ts";
import { chatgptAccountIdFromToken, tokenExpiry } from "./chatgpt-auth-file.ts";
import type { UserOAuthTokens } from "./user-model-credential-store.ts";
@@ -36,7 +36,7 @@ export async function refreshChatGPTTokens(refreshToken: string): Promise<UserOA
}),
signal: AbortSignal.timeout(15_000),
});
- if (!res.ok) throw new Error(`chatgpt refresh failed (${res.status})`);
+ if (!res.ok) throw await oauthFailure("chatgpt refresh", res);
const raw = (await res.json()) as {
access_token?: string;
refresh_token?: string;
@@ -88,7 +88,7 @@ export async function completeClaudeLogin(pastedCode: string, verifier: string):
}),
signal: AbortSignal.timeout(15_000),
});
- if (!res.ok) throw new Error(`claude token exchange failed (${res.status})`);
+ if (!res.ok) throw await oauthFailure("claude token exchange", res);
const raw = (await res.json()) as { access_token?: string; refresh_token?: string; expires_in?: number };
if (!raw.access_token) throw new Error("claude token response missing access_token");
return {
@@ -105,7 +105,7 @@ export async function refreshClaudeTokens(refreshToken: string): Promise<UserOAu
body: JSON.stringify({ grant_type: "refresh_token", refresh_token: refreshToken, client_id: CLAUDE_CLIENT_ID }),
signal: AbortSignal.timeout(15_000),
});
- if (!res.ok) throw new Error(`claude refresh failed (${res.status})`);
+ if (!res.ok) throw await oauthFailure("claude refresh", res);
const raw = (await res.json()) as { access_token?: string; refresh_token?: string; expires_in?: number };
if (!raw.access_token) throw new Error("claude refresh missing access_token");
return {
diff --git a/test/oauth.test.ts b/test/oauth.test.ts
index 093b3db72..edeeb7ff6 100644
--- a/test/oauth.test.ts
+++ b/test/oauth.test.ts
@@ -507,6 +507,48 @@ test("X refresh captures the ROTATED refresh token (single-use) — the connecti
assert.equal(fresh.expiresAt, 5_000 + 7200_000);
});
+test("token failures keep the provider's error detail", async () => {
+ const failing =
+ (status: number, json: () => Promise<unknown>): FetchLike =>
+ async () => ({ ok: false, status, json });
+ await assert.rejects(
+ exchangeCode("google", "code", "https://app/cb", {
+ client: await googleClient(),
+ fetchImpl: failing(400, async () => ({ error: "invalid_grant", error_description: "Code expired" })),
+ now: 1_000,
+ }),
+ /token exchange failed \(400\): invalid_grant: Code expired$/,
+ );
+ await assert.rejects(
+ makeRefresh({
+ resolveClient: resolve,
+ fetchImpl: failing(401, async () => ({ reason: "Invalid client_id or client_secret", error: "invalid_client" })),
+ now: () => 1_000,
+ })("api.x.com", { accessToken: "old", refreshToken: "rt", expiresAt: 0 }),
+ /x token refresh failed \(401\): invalid_client: Invalid client_id or client_secret$/,
+ );
+ await assert.rejects(
+ exchangeCode("google", "code", "https://app/cb", {
+ client: await googleClient(),
+ fetchImpl: failing(401, async () => ({
+ error: { code: "refresh_token_reused", message: "Refresh token already used" },
+ })),
+ now: 1_000,
+ }),
+ /token exchange failed \(401\): refresh_token_reused: Refresh token already used$/,
+ );
+ await assert.rejects(
+ exchangeCode("google", "code", "https://app/cb", {
+ client: await googleClient(),
+ fetchImpl: failing(502, async () => {
+ throw new SyntaxError("Unexpected token <");
+ }),
+ now: 1_000,
+ }),
+ /token exchange failed \(502\)$/,
+ );
+});
+
test("oauth flow store — a short opaque state resolves once, then expires", async () => {
const store = createOAuthFlowStore(createMemoryMap<OAuthState>(), { now: () => 1_000 });
const flowId = await store.start({