mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-03 05:45:04 +03:00
* fix(cli-tools): guard modelId type before calling indexOf E2E shakedown v3.8.0: cli-tools quebrava com TypeError quando dynamicModels continha entradas sem .id (objeto retornado diretamente em vez de string). * fix(offline): avoid SSR/CSR hydration mismatch on navigator.onLine Replace useState+lazy-initializer with useSyncExternalStore so the server snapshot (() => false) and client snapshot (() => navigator.onLine) are declared separately. React hydrates with the server value and switches to the real online status client-side without a mismatch. * chore(i18n): add missing en.json keys for translator, cli-tools, memory, onboarding Adds 58 missing keys identified by the new dashboard audit script: - cliTools: 18 custom CLI builder keys (CustomCliCard) - translator: 24 keys covering stream transformer, live monitor, test bench - memory: 12 health/pagination/dialog keys - onboarding.tier: 8 keys for the tier tour walkthrough Also adds scripts/i18n/audit-dashboard-pages.mjs which scans all dashboard pages, reports t() calls referencing missing en.json keys, and flags candidate hardcoded JSX/attribute strings. * chore(i18n): replace hardcoded UI text with t() calls across dashboard (round 1) Subagents refactored 8 high-impact dashboard pages, replacing 81 of the 407 hardcoded English/PT strings flagged by the audit with proper useTranslations() lookups. Added 73 corresponding keys to en.json across the home, apiManager, providers, settings, and usage namespaces. Pages affected: - BudgetTab (27 → 0) - HomePageClient (2 → 0) - RoutingTab (25 → 7) - ResilienceTab (38 → 18) - SystemStorageTab (42 → 21) - providers/[id] (17 → 15) - ApiManagerPageClient (14 → 13) - OneproxyTab (13 → 10) Also adds two helper scripts: - scripts/i18n/extract-keys-from-diff.mjs — extracts new keys from git diff - scripts/i18n/merge-keys.mjs — merges a pending-keys JSON into en.json Remaining hardcoded strings will be addressed in follow-up rounds. * chore(i18n): replace hardcoded UI text with t() calls across dashboard (round 2) Continues round 1 (commit8d34f4c65). Round-2 subagents refactored additional dashboard pages, replacing 77 more hardcoded strings with useTranslations() lookups. Added 79 corresponding keys to en.json across the a2aDashboard, agents, analytics, apiManager, cliTools, common, and settings namespaces. Pages affected: - a2a/page (new useTranslations + 6 keys) - agent-skills/page (new useTranslations + 9 keys) - AutoRoutingAnalyticsTab (new useTranslations + 6 keys) - AppearanceTab (8 → 6 remaining) - OneproxyTab (10 → 0) - ResilienceTab (18 → 0 missing key) - RoutingTab (7 → 0 missing key) - VisionBridgeSettingsTab (new useTranslations + 6 keys) - CopilotToolCard (7 → 0 missing key) - ApiManagerPageClient (13 → 0 missing key) - gamification/admin (new useTranslations + 7 keys) Hardcoded total: 326 → 249. Real missing keys: 0 (the 6 still flagged are false positives in exampleTemplates.tsx where t is passed as a parameter — keys exist at translator.templatePayloads.*). * chore(i18n): replace hardcoded UI text with t() calls across dashboard (round 3) Round-3 subagents and manual edits refactored 9 more dashboard pages (plus 2 small extras), replacing ~80 hardcoded strings with useTranslations() lookups. Added 79 corresponding keys to en.json across analytics, cloudAgents, combos, common, health, settings, and usage namespaces. Pages affected: - analytics/ComboHealthTab (new useTranslations + 15 keys) - analytics/CompressionAnalyticsTab (new useTranslations + 11 keys) - settings/SystemStorageTab (21 → 0 missing key) - tokens/page (new useTranslations + 13 keys) - usage/BudgetTab (9 missing fixed) - health/page (manual: 6 keys) - cloud-agents/page (manual: 3 keys) - combos/page (manual: 1 key) Hardcoded total: 249 → 164. Real missing keys: 0 (6 remaining are exampleTemplates.tsx false positives). Also adds scripts/i18n/build-pending-from-missing.mjs which reads _audit.json and locates English values from HEAD to rebuild _pending-keys.json after race-condition resets between subagent edits. * chore(i18n): localize remaining dashboard settings labels Replace hardcoded labels in compression and resilience settings with translation lookups to continue the dashboard i18n cleanup. Add the v3.8.0 dashboard shakedown runbook to document the manual smoke-test process and known dev environment pitfalls. * chore(i18n): replace hardcoded UI text with t() calls across dashboard (round 4) Round-4 subagent + manual key-resolution refactored remaining strings in 3 high-traffic settings/API tabs, plus extracted English values for keys that were already added as t() calls but lost during the previous en.json race-condition resets. Pages affected: - api-manager/ApiManagerPageClient (7 → 0 missing key) - settings/CompressionSettingsTab (8 → 0 missing key) - settings/MemorySkillsTab (8 → 0 missing key) - settings/ResilienceTab (4 more keys recovered) Hardcoded total: 164 → 140. Real missing keys: 0 (6 remaining are the exampleTemplates.tsx false positives — t passed as parameter). * chore(i18n): replace hardcoded UI text with t() calls across dashboard (round 5) Round-5 agent began processing the remaining smaller dashboard files. Added 5 more keys to en.json for providers/[id]/page.tsx OAuth flow labels and the cross-OS auto-detection hint. Pages affected: - providers/[id]/page.tsx (5 keys) Hardcoded total: 140 → 136. Real missing keys: 0. * chore(i18n): resolve last 2 missing providers/[id] keys Adds providerDetailMyClaudeAccountPlaceholder and providerDetailPathAutoDetected — the final user-visible labels in the providers/[id] page that the round-5 subagent rewrote to t() calls without yet adding to en.json. Real missing keys: 0 (6 remaining are exampleTemplates.tsx false positives — t is passed as a parameter so the audit cannot resolve the namespace; keys do exist at translator.templatePayloads.*). * chore(i18n): replace hardcoded UI text with t() calls across dashboard (round 6 — 10 parallel agents) Round-6 dispatched 10 parallel subagents covering all 57 remaining dashboard files. Each agent worked on a disjoint file set to avoid en.json race conditions. Added ~60 new i18n keys across 9 namespaces covering small UI labels, table headers, search placeholders, and empty-state messages. Major changes: - analytics: SearchAnalyticsTab, ProviderUtilizationTab, DiversityScoreCard, CompressionAnalyticsTab (new useTranslations + keys) - batch: BatchDetailModal, BatchListTab, FileDetailModal, FilesListTab (new useTranslations + keys) - settings: CliproxyapiSettingsTab, PayloadRulesTab, ModelCooldownsCard, AppearanceTab, PricingTab (mostly new useTranslations) - endpoint: TokenSaverCard, ApiEndpointsTab, EndpointPageClient - cache: CachePerformance, IdempotencyLayer, ReasoningCacheTab, MediaPageClient, page - combos: IntelligentComboPanel, page - playground: ChatPlayground, SearchPlayground - providers: ProviderCard - onboarding: TierFlowDiagram - changelog: ChangelogViewer - home: ProviderTopology, TierCoverageWidget, BootstrapBanner, BadgeToast - usage: BudgetTab, BudgetTelemetryCards, QuotaTable - quotaShare: QuotaSharePageClient - profile: page - leaderboard: page - skills: page Hardcoded total: 131 → 60. Real missing keys: 0 plus 1 false-positive for combos.modePack (lookup via prop-passed t). * chore(i18n): finalize round-6 keys for batch/cache/endpoint/usage Adds the remaining keys produced by parallel agents A4, A6, A8, A9: - common: batch-related labels (BatchDetailModal, BatchListTab, FileDetailModal, FilesListTab, page) + profile/leaderboard - cache: hit rate, latency, retry, avg chars - endpoint: token saver, API endpoints, copy URL, cloud/local labels - usage: noSpend, activeSessions, quotaAlerts, budget timing - skills: install/marketplace/filter - proxyRegistry/quotaShare/mcpDashboard: misc labels Hardcoded total: 60 → 48. Real missing keys: 0 (modePack remaining is a false positive — combos.modePack exists but the audit can't resolve it since IntelligentComboPanel receives t as a prop). * fix(playground): dedupe filteredModels to avoid duplicate React key warning The /v1/models endpoint can return the same model id twice (e.g., when a model is listed by both an alias and its canonical provider), which made the <Select> emit two <option> elements with the same key — triggering "Encountered two children with the same key, codex/gpt-5.5". Replace the chained filter + map with a single pass that skips ids already added. * fix(playground): guard against non-string model ids before .split/.startsWith The /v1/models endpoint can include synthetic entries (combos, locals, in-progress imports) with a null/undefined id. The playground used to call m.id.split("/") in the provider-discovery loop, which threw on the first non-string entry; the surrounding .catch(() => {}) silently swallowed the error, so the provider/model/account dropdowns ended up empty even though /v1/models returned thousands of valid entries. - Skip entries without a string id before split/startsWith. - Log the rejection in the .catch handler so future regressions are visible in DevTools instead of silently emptying the UI. * fix(playground): guard ChatPlayground filteredModels for non-string ids Same root cause as commit49fe356b9: ChatPlayground filtered models with m.id.startsWith(...) which crashed on null/undefined ids returned by /v1/models (synthetic combo entries). Apply the same defensive guard and dedupe used in the parent page. * fix(claude): drop orphan tool_result after fixToolAdjacency strip (discussion #2410) Discussion #2410 reports Claude returning 400 for sequences like: assistant: tool_use(id=X) user: <plain text> ← breaks adjacency user: tool_result(id=X) The previous round added `fixToolAdjacency` (commit44d9abac9) which correctly strips the orphan tool_use from the assistant message. But that left the now-unmatched tool_result intact, so the upstream rejected the request with: messages.N.content.M: unexpected `tool_use_id` found in `tool_result` blocks: X. Each tool_result block must have a corresponding tool_use block in the previous message. Fix: after running `fixToolAdjacency`, re-run `fixToolPairs` to drop the orphaned tool_result blocks. All three call sites updated: - contextManager.purifyHistory (both inside the binary-search loop and the final pass) - BaseExecutor message-prep (Claude path) - claudeCodeCompatible request signer Also tightens an unrelated dynamic-key access in readNestedString (claudeCodeCompatible) to satisfy the prototype- pollution scanner triggered by the post-tool semgrep hook. * fix(mitm): point runtime manager re-export to js entrypoint Use the emitted `.js` path for the runtime manager re-export so dynamic runtime loading resolves correctly outside the Turbopack alias handling. * docs: add AgentRouter setup guide (#2422) Integrated into release/v3.8.0 — AgentRouter setup guide docs. * feat: add new feature on combos - falloverBeforeRetry (#2417) Integrated into release/v3.8.0 — falloverBeforeRetry for per-model quota skipping in combos. * feat(batch): implement 10 feature requests harvested (#2414) Integrated into release/v3.8.0 — batch of 10 feature requests: llama.cpp local provider, upstream error exposure, Termux detection, providers rotate CLI, t3.chat web skeleton, Zed Docker integration, Kiro multi-account OAuth isolation, auto-combo cost blending, auto-combo context filter, combo provider-level exhaustion tracking (#1731). Conflicts with #2417 (falloverBeforeRetry) resolved. * fix(gamification): resolve SQL bug, auth gap, pagination, and anomaly scoring (#2421) Integrated into release/v3.8.0 — 6 critical gamification bug fixes: SQL SELECT in checkActionCountBadges, federation auth enforcement, leaderboard pagination offset, real z-score computation, addXp level calculation, and barrel index.ts * docs(changelog): add post-release entries for #2414 #2417 #2421 #2422 - feat(batch): T3-Chat-Web executor, exhaustedProviders set (#1731), Zed Docker - feat(combos): falloverBeforeRetry + setTry loop (#2417 — @hartmark) - fix(gamification): SQL SELECT bug, federation auth, pagination, z-score (#2421 — @oyi77) - docs: AgentRouter setup guide (#2422 — @leninejunior) * fix(security): resolve CodeQL random/password-hash alerts and sync docs & tests --------- Co-authored-by: diegosouzapw <diego.souza.pw@gmail.com> Co-authored-by: Lenine Júnior <lenine@engrene.com.br> Co-authored-by: Markus Hartung <mail@hartmark.se> Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com>
1257 lines
38 KiB
TypeScript
1257 lines
38 KiB
TypeScript
import test from "node:test";
|
|
import assert from "node:assert/strict";
|
|
|
|
const tokenRefresh = await import("../../open-sse/services/tokenRefresh.ts");
|
|
const { PROVIDERS, OAUTH_ENDPOINTS } = await import("../../open-sse/config/constants.ts");
|
|
|
|
const {
|
|
TOKEN_EXPIRY_BUFFER_MS,
|
|
refreshAccessToken,
|
|
refreshClineToken,
|
|
refreshKimiCodingToken,
|
|
refreshClaudeOAuthToken,
|
|
refreshGoogleToken,
|
|
refreshQwenToken,
|
|
refreshCodexToken,
|
|
refreshKiroToken,
|
|
refreshQoderToken,
|
|
refreshGitHubToken,
|
|
refreshCopilotToken,
|
|
supportsTokenRefresh,
|
|
isUnrecoverableRefreshError,
|
|
getAccessToken,
|
|
formatProviderCredentials,
|
|
getAllAccessTokens,
|
|
isProviderBlocked,
|
|
getCircuitBreakerStatus,
|
|
getConnectionRefreshMutexStatus,
|
|
refreshWithRetry,
|
|
} = tokenRefresh;
|
|
|
|
type LogLevel = "debug" | "info" | "warn" | "error";
|
|
type LogEntry = {
|
|
level: LogLevel;
|
|
scope: unknown;
|
|
message: unknown;
|
|
meta: unknown;
|
|
};
|
|
type MockLogger = {
|
|
entries: LogEntry[];
|
|
debug: (...args: [unknown?, unknown?, unknown?]) => void;
|
|
info: (...args: [unknown?, unknown?, unknown?]) => void;
|
|
warn: (...args: [unknown?, unknown?, unknown?]) => void;
|
|
error: (...args: [unknown?, unknown?, unknown?]) => void;
|
|
};
|
|
|
|
type TestFetch = typeof fetch;
|
|
type FastSetTimeout = typeof globalThis.setTimeout & {
|
|
__promisify__?: typeof globalThis.setTimeout.__promisify__;
|
|
};
|
|
|
|
function createLog(): MockLogger {
|
|
const entries: LogEntry[] = [];
|
|
const push = (level: LogLevel, args: [unknown?, unknown?, unknown?]) => {
|
|
const [scope, message, meta] = args;
|
|
entries.push({ level, scope, message, meta });
|
|
};
|
|
|
|
return {
|
|
entries,
|
|
debug: (...args) => push("debug", args),
|
|
info: (...args) => push("info", args),
|
|
warn: (...args) => push("warn", args),
|
|
error: (...args) => push("error", args),
|
|
};
|
|
}
|
|
|
|
function jsonResponse(body: any, status = 200) {
|
|
return new Response(JSON.stringify(body), {
|
|
status,
|
|
headers: { "content-type": "application/json" },
|
|
});
|
|
}
|
|
|
|
function textResponse(text: any, status = 400) {
|
|
return new Response(text, {
|
|
status,
|
|
headers: { "content-type": "text/plain" },
|
|
});
|
|
}
|
|
|
|
function bodyToString(body: BodyInit | null | undefined) {
|
|
if (typeof body === "string") return body;
|
|
if (body instanceof URLSearchParams) return body.toString();
|
|
return String(body ?? "");
|
|
}
|
|
|
|
async function withMockedFetch<TResult>(fetchImpl: TestFetch, fn: () => Promise<TResult>) {
|
|
const originalFetch = globalThis.fetch;
|
|
globalThis.fetch = fetchImpl;
|
|
try {
|
|
return await fn();
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
}
|
|
|
|
async function withMockedNow<TResult>(now: number, fn: () => Promise<TResult>) {
|
|
const originalNow = Date.now;
|
|
Date.now = () => now;
|
|
try {
|
|
return await fn();
|
|
} finally {
|
|
Date.now = originalNow;
|
|
}
|
|
}
|
|
|
|
async function withPatchedProperties<TResult>(
|
|
target: object,
|
|
patch: Record<string, unknown>,
|
|
fn: () => Promise<TResult>
|
|
) {
|
|
const previous = new Map<string, unknown>();
|
|
const targetRecord = target as Record<string, unknown>;
|
|
for (const [key, value] of Object.entries(patch)) {
|
|
previous.set(
|
|
key,
|
|
Object.prototype.hasOwnProperty.call(targetRecord, key) ? targetRecord[key] : undefined
|
|
);
|
|
targetRecord[key] = value;
|
|
}
|
|
|
|
try {
|
|
return await fn();
|
|
} finally {
|
|
for (const [key] of Object.entries(patch)) {
|
|
const prior = previous.get(key);
|
|
if (prior === undefined) {
|
|
delete targetRecord[key];
|
|
} else {
|
|
targetRecord[key] = prior;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
async function withFastRetryTimers<TResult>(fn: () => Promise<TResult>) {
|
|
const originalSetTimeout = globalThis.setTimeout as FastSetTimeout;
|
|
const fastSetTimeout: FastSetTimeout = Object.assign(
|
|
((callback: TimerHandler, delay = 0, ...args: unknown[]) =>
|
|
originalSetTimeout(callback, delay === 30_000 ? delay : 0, ...args)) as typeof setTimeout,
|
|
{ __promisify__: originalSetTimeout.__promisify__ }
|
|
);
|
|
globalThis.setTimeout = fastSetTimeout;
|
|
try {
|
|
return await fn();
|
|
} finally {
|
|
globalThis.setTimeout = originalSetTimeout;
|
|
}
|
|
}
|
|
|
|
test("TOKEN_EXPIRY_BUFFER_MS stays at five minutes", () => {
|
|
assert.equal(TOKEN_EXPIRY_BUFFER_MS, 5 * 60 * 1000);
|
|
});
|
|
|
|
test("refreshAccessToken returns null when no provider refresh endpoint exists", async () => {
|
|
const log = createLog();
|
|
const result = await refreshAccessToken("qoder", "refresh-token", {}, log);
|
|
assert.equal(result, null);
|
|
assert.equal(
|
|
log.entries.some((entry) => entry.level === "warn"),
|
|
true
|
|
);
|
|
});
|
|
|
|
test("refreshAccessToken returns null when refresh token is missing", async () => {
|
|
const log = createLog();
|
|
|
|
await withPatchedProperties(
|
|
PROVIDERS,
|
|
{
|
|
"custom-oauth-task-207": { tokenUrl: "https://auth.example.com/token" },
|
|
},
|
|
async () => {
|
|
const result = await refreshAccessToken("custom-oauth-task-207", null, {}, log);
|
|
assert.equal(result, null);
|
|
}
|
|
);
|
|
});
|
|
|
|
test("refreshAccessToken posts form data and returns rotated tokens", async () => {
|
|
const log = createLog();
|
|
const calls: any[] = [];
|
|
|
|
await withPatchedProperties(
|
|
PROVIDERS,
|
|
{
|
|
"custom-oauth-task-207": {
|
|
refreshUrl: "https://auth.example.com/token",
|
|
clientId: "client-id",
|
|
clientSecret: "client-secret",
|
|
},
|
|
},
|
|
async () => {
|
|
await withMockedFetch(
|
|
async (url, options = {}) => {
|
|
calls.push({ url, options });
|
|
return jsonResponse({
|
|
access_token: "new-access",
|
|
refresh_token: "new-refresh",
|
|
expires_in: 3600,
|
|
});
|
|
},
|
|
async () => {
|
|
const result = await refreshAccessToken("custom-oauth-task-207", "refresh-123", {}, log);
|
|
|
|
assert.deepEqual(result, {
|
|
accessToken: "new-access",
|
|
refreshToken: "new-refresh",
|
|
expiresIn: 3600,
|
|
});
|
|
}
|
|
);
|
|
}
|
|
);
|
|
|
|
assert.equal(calls[0].url, "https://auth.example.com/token");
|
|
assert.equal(
|
|
bodyToString(calls[0].options.body),
|
|
"grant_type=refresh_token&refresh_token=refresh-123&client_id=client-id&client_secret=client-secret"
|
|
);
|
|
});
|
|
|
|
test("refreshAccessToken returns null on upstream refresh failure", async () => {
|
|
const log = createLog();
|
|
|
|
await withPatchedProperties(
|
|
PROVIDERS,
|
|
{
|
|
"custom-oauth-task-207": { tokenUrl: "https://auth.example.com/token" },
|
|
},
|
|
async () => {
|
|
await withMockedFetch(
|
|
async () => textResponse("rate limited", 429),
|
|
async () => {
|
|
const result = await refreshAccessToken("custom-oauth-task-207", "refresh-123", {}, log);
|
|
|
|
assert.equal(result, null);
|
|
assert.equal(
|
|
log.entries.some((entry) => entry.level === "error"),
|
|
true
|
|
);
|
|
}
|
|
);
|
|
}
|
|
);
|
|
});
|
|
|
|
test("refreshClineToken handles nested payloads and computes expiresIn", async () => {
|
|
const log = createLog();
|
|
const calls: any[] = [];
|
|
|
|
await withMockedNow(1_700_000_000_000, async () => {
|
|
await withMockedFetch(
|
|
async (url, options = {}) => {
|
|
calls.push({ url, options });
|
|
return jsonResponse({
|
|
data: {
|
|
accessToken: "cline-access",
|
|
refreshToken: "cline-refresh",
|
|
expiresAt: new Date(Date.now() + 95_000).toISOString(),
|
|
},
|
|
});
|
|
},
|
|
async () => {
|
|
const result = await refreshClineToken("refresh-cline", log);
|
|
assert.equal(result?.accessToken, "cline-access");
|
|
assert.equal(result?.refreshToken, "cline-refresh");
|
|
assert.equal(result?.expiresIn, 95);
|
|
}
|
|
);
|
|
});
|
|
|
|
assert.equal(calls[0].url, PROVIDERS.cline.refreshUrl);
|
|
assert.deepEqual(JSON.parse(calls[0].options.body), {
|
|
refreshToken: "refresh-cline",
|
|
grantType: "refresh_token",
|
|
clientType: "extension",
|
|
});
|
|
});
|
|
|
|
test("refreshKimiCodingToken adds provider-specific headers and fields", async () => {
|
|
const log = createLog();
|
|
const calls: any[] = [];
|
|
|
|
await withMockedFetch(
|
|
async (url, options = {}) => {
|
|
calls.push({ url, options });
|
|
return jsonResponse({
|
|
access_token: "kimi-access",
|
|
refresh_token: "kimi-refresh-next",
|
|
expires_in: 7200,
|
|
token_type: "Bearer",
|
|
scope: "coding offline_access",
|
|
});
|
|
},
|
|
async () => {
|
|
const result = await refreshKimiCodingToken("kimi-refresh", log);
|
|
assert.deepEqual(result, {
|
|
accessToken: "kimi-access",
|
|
refreshToken: "kimi-refresh-next",
|
|
expiresIn: 7200,
|
|
tokenType: "Bearer",
|
|
scope: "coding offline_access",
|
|
});
|
|
}
|
|
);
|
|
|
|
assert.equal(calls[0].url, PROVIDERS["kimi-coding"].refreshUrl);
|
|
assert.equal(calls[0].options.headers["X-Msh-Platform"], "omniroute");
|
|
assert.equal(calls[0].options.headers["X-Msh-Version"], "2.1.2");
|
|
assert.match(calls[0].options.headers["X-Msh-Device-Id"], /^kimi-refresh-/);
|
|
assert.match(bodyToString(calls[0].options.body), /grant_type=refresh_token/);
|
|
});
|
|
|
|
test("refreshClaudeOAuthToken posts the anthropic oauth refresh contract", async () => {
|
|
const log = createLog();
|
|
const calls: any[] = [];
|
|
|
|
await withMockedFetch(
|
|
async (url, options = {}) => {
|
|
calls.push({ url, options });
|
|
return jsonResponse({
|
|
access_token: "claude-access",
|
|
refresh_token: "claude-refresh-next",
|
|
expires_in: 1800,
|
|
});
|
|
},
|
|
async () => {
|
|
const result = await refreshClaudeOAuthToken("claude-refresh", log);
|
|
assert.deepEqual(result, {
|
|
accessToken: "claude-access",
|
|
refreshToken: "claude-refresh-next",
|
|
expiresIn: 1800,
|
|
});
|
|
}
|
|
);
|
|
|
|
assert.equal(calls[0].url, OAUTH_ENDPOINTS.anthropic.token);
|
|
assert.equal(calls[0].options.headers["anthropic-beta"], "oauth-2025-04-20");
|
|
assert.match(calls[0].options.body, /grant_type=refresh_token/);
|
|
assert.match(calls[0].options.body, /client_id=/);
|
|
});
|
|
|
|
test("refreshGoogleToken exchanges refresh tokens against the shared google endpoint", async () => {
|
|
const log = createLog();
|
|
const calls: any[] = [];
|
|
|
|
await withMockedFetch(
|
|
async (url, options = {}) => {
|
|
calls.push({ url, options });
|
|
return jsonResponse({
|
|
access_token: "google-access",
|
|
refresh_token: "google-refresh-next",
|
|
expires_in: 3600,
|
|
});
|
|
},
|
|
async () => {
|
|
const result = await refreshGoogleToken("google-refresh", "gid", "gsecret", log);
|
|
assert.deepEqual(result, {
|
|
accessToken: "google-access",
|
|
refreshToken: "google-refresh-next",
|
|
expiresIn: 3600,
|
|
});
|
|
}
|
|
);
|
|
|
|
assert.equal(calls[0].url, OAUTH_ENDPOINTS.google.token);
|
|
assert.equal(
|
|
bodyToString(calls[0].options.body),
|
|
"grant_type=refresh_token&refresh_token=google-refresh&client_id=gid&client_secret=gsecret"
|
|
);
|
|
});
|
|
|
|
test("refreshQwenToken maps resource_url into providerSpecificData", async () => {
|
|
const log = createLog();
|
|
|
|
await withMockedFetch(
|
|
async () =>
|
|
jsonResponse({
|
|
access_token: "qwen-access",
|
|
refresh_token: "qwen-refresh-next",
|
|
expires_in: 1500,
|
|
resource_url: "https://chat.qwen.ai/workspace/resource",
|
|
}),
|
|
async () => {
|
|
const result = await refreshQwenToken("qwen-refresh", log);
|
|
assert.deepEqual(result, {
|
|
accessToken: "qwen-access",
|
|
refreshToken: "qwen-refresh-next",
|
|
expiresIn: 1500,
|
|
providerSpecificData: {
|
|
resourceUrl: "https://chat.qwen.ai/workspace/resource",
|
|
},
|
|
});
|
|
}
|
|
);
|
|
});
|
|
|
|
test("refreshQwenToken surfaces invalid_request as unrecoverable", async () => {
|
|
const log = createLog();
|
|
|
|
await withMockedFetch(
|
|
async () => textResponse(JSON.stringify({ error: "invalid_request" }), 400),
|
|
async () => {
|
|
const result = await refreshQwenToken("qwen-refresh", log);
|
|
assert.deepEqual(result, { error: "invalid_request" });
|
|
}
|
|
);
|
|
});
|
|
|
|
test("refreshCodexToken recognizes refresh_token_reused responses", async () => {
|
|
const log = createLog();
|
|
|
|
await withMockedFetch(
|
|
async () => textResponse(JSON.stringify({ error: { code: "refresh_token_reused" } }), 400),
|
|
async () => {
|
|
const result = await refreshCodexToken("codex-refresh", log);
|
|
assert.deepEqual(result, {
|
|
error: "unrecoverable_refresh_error",
|
|
code: "refresh_token_reused",
|
|
});
|
|
}
|
|
);
|
|
});
|
|
|
|
test("refreshKiroToken uses the AWS OIDC flow when client credentials are present", async () => {
|
|
const log = createLog();
|
|
const calls: any[] = [];
|
|
|
|
await withMockedFetch(
|
|
async (url, options = {}) => {
|
|
calls.push({ url, options });
|
|
return jsonResponse({
|
|
accessToken: "kiro-aws-access",
|
|
refreshToken: "kiro-aws-refresh-next",
|
|
expiresIn: 900,
|
|
});
|
|
},
|
|
async () => {
|
|
const result = await refreshKiroToken(
|
|
"kiro-refresh",
|
|
{
|
|
authMethod: "idc",
|
|
clientId: "aws-client",
|
|
clientSecret: "aws-secret",
|
|
region: "eu-west-1",
|
|
},
|
|
log
|
|
);
|
|
|
|
assert.deepEqual(result, {
|
|
accessToken: "kiro-aws-access",
|
|
refreshToken: "kiro-aws-refresh-next",
|
|
expiresIn: 900,
|
|
});
|
|
}
|
|
);
|
|
|
|
assert.equal(calls[0].url, "https://oidc.eu-west-1.amazonaws.com/token");
|
|
assert.deepEqual(JSON.parse(calls[0].options.body), {
|
|
clientId: "aws-client",
|
|
clientSecret: "aws-secret",
|
|
refreshToken: "kiro-refresh",
|
|
grantType: "refresh_token",
|
|
});
|
|
});
|
|
|
|
test("refreshKiroToken uses stored region for AWS OIDC refresh without authMethod", async () => {
|
|
const log = createLog();
|
|
const calls: any[] = [];
|
|
|
|
await withMockedFetch(
|
|
async (url, options = {}) => {
|
|
calls.push({ url, options });
|
|
return jsonResponse({
|
|
accessToken: "kiro-aws-access",
|
|
refreshToken: "kiro-aws-refresh-next",
|
|
expiresIn: 900,
|
|
});
|
|
},
|
|
async () => {
|
|
const result = await refreshKiroToken(
|
|
"kiro-refresh",
|
|
{
|
|
clientId: "aws-client",
|
|
clientSecret: "aws-secret",
|
|
region: "ap-southeast-1",
|
|
},
|
|
log
|
|
);
|
|
|
|
assert.deepEqual(result, {
|
|
accessToken: "kiro-aws-access",
|
|
refreshToken: "kiro-aws-refresh-next",
|
|
expiresIn: 900,
|
|
});
|
|
}
|
|
);
|
|
|
|
assert.equal(calls[0].url, "https://oidc.ap-southeast-1.amazonaws.com/token");
|
|
assert.deepEqual(JSON.parse(calls[0].options.body), {
|
|
clientId: "aws-client",
|
|
clientSecret: "aws-secret",
|
|
refreshToken: "kiro-refresh",
|
|
grantType: "refresh_token",
|
|
});
|
|
});
|
|
|
|
test("refreshKiroToken falls back to the social-auth refresh endpoint", async () => {
|
|
const log = createLog();
|
|
const calls: any[] = [];
|
|
|
|
await withMockedFetch(
|
|
async (url, options = {}) => {
|
|
calls.push({ url, options });
|
|
return jsonResponse({
|
|
accessToken: "kiro-social-access",
|
|
refreshToken: "kiro-social-refresh-next",
|
|
expiresIn: 1200,
|
|
});
|
|
},
|
|
async () => {
|
|
const result = await refreshKiroToken("kiro-refresh", null, log);
|
|
assert.deepEqual(result, {
|
|
accessToken: "kiro-social-access",
|
|
refreshToken: "kiro-social-refresh-next",
|
|
expiresIn: 1200,
|
|
});
|
|
}
|
|
);
|
|
|
|
assert.equal(calls[0].url, PROVIDERS.kiro.tokenUrl);
|
|
assert.deepEqual(JSON.parse(calls[0].options.body), {
|
|
refreshToken: "kiro-refresh",
|
|
});
|
|
});
|
|
|
|
// Issue #2328 — once a social-auth token has clientId/clientSecret stored
|
|
// (because it was imported after v3.8.0), refreshKiroToken must use the AWS OIDC
|
|
// endpoint, not the shared social-auth endpoint, even though authMethod is "google".
|
|
test("refreshKiroToken uses AWS OIDC path for social-auth token when clientId is present (#2328)", async () => {
|
|
const log = createLog();
|
|
const calls: any[] = [];
|
|
|
|
await withMockedFetch(
|
|
async (url, options = {}) => {
|
|
calls.push({ url, options });
|
|
return jsonResponse({
|
|
accessToken: "kiro-isolated-access",
|
|
refreshToken: "kiro-isolated-refresh-next",
|
|
expiresIn: 900,
|
|
});
|
|
},
|
|
async () => {
|
|
const result = await refreshKiroToken(
|
|
"kiro-social-refresh",
|
|
{
|
|
authMethod: "google",
|
|
clientId: "isolated-client-id",
|
|
clientSecret: "isolated-client-secret",
|
|
region: "us-east-1",
|
|
},
|
|
log
|
|
);
|
|
|
|
assert.deepEqual(result, {
|
|
accessToken: "kiro-isolated-access",
|
|
refreshToken: "kiro-isolated-refresh-next",
|
|
expiresIn: 900,
|
|
});
|
|
}
|
|
);
|
|
|
|
// Must call the AWS OIDC endpoint — not the shared social-auth tokenUrl
|
|
assert.ok(
|
|
calls[0].url.includes("oidc.us-east-1.amazonaws.com/token"),
|
|
`expected AWS OIDC endpoint but got ${calls[0].url}`
|
|
);
|
|
assert.notEqual(
|
|
calls[0].url,
|
|
PROVIDERS.kiro.tokenUrl,
|
|
"should not call the shared social-auth endpoint when clientId is set"
|
|
);
|
|
assert.deepEqual(JSON.parse(calls[0].options.body), {
|
|
clientId: "isolated-client-id",
|
|
clientSecret: "isolated-client-secret",
|
|
refreshToken: "kiro-social-refresh",
|
|
grantType: "refresh_token",
|
|
});
|
|
});
|
|
|
|
test("refreshQoderToken uses basic auth once qoder oauth settings are configured", async () => {
|
|
const log = createLog();
|
|
const calls: any[] = [];
|
|
|
|
await withPatchedProperties(
|
|
PROVIDERS.qoder,
|
|
{
|
|
clientId: "qoder-client",
|
|
clientSecret: "qoder-secret",
|
|
},
|
|
async () => {
|
|
await withPatchedProperties(
|
|
OAUTH_ENDPOINTS.qoder,
|
|
{
|
|
token: "https://qoder.example.com/oauth/token",
|
|
},
|
|
async () => {
|
|
await withMockedFetch(
|
|
async (url, options = {}) => {
|
|
calls.push({ url, options });
|
|
return jsonResponse({
|
|
access_token: "qoder-access",
|
|
refresh_token: "qoder-refresh-next",
|
|
expires_in: 2400,
|
|
});
|
|
},
|
|
async () => {
|
|
const result = await refreshQoderToken("qoder-refresh", log);
|
|
assert.deepEqual(result, {
|
|
accessToken: "qoder-access",
|
|
refreshToken: "qoder-refresh-next",
|
|
expiresIn: 2400,
|
|
});
|
|
}
|
|
);
|
|
}
|
|
);
|
|
}
|
|
);
|
|
|
|
assert.equal(calls[0].url, "https://qoder.example.com/oauth/token");
|
|
assert.match(calls[0].options.headers.Authorization, /^Basic /);
|
|
});
|
|
|
|
test("refreshGitHubToken exchanges the refresh token with github oauth", async () => {
|
|
const log = createLog();
|
|
const calls: any[] = [];
|
|
|
|
await withPatchedProperties(
|
|
PROVIDERS.github,
|
|
{
|
|
clientId: "github-client",
|
|
clientSecret: "github-secret",
|
|
},
|
|
async () => {
|
|
await withMockedFetch(
|
|
async (url, options = {}) => {
|
|
calls.push({ url, options });
|
|
return jsonResponse({
|
|
access_token: "github-access",
|
|
refresh_token: "github-refresh-next",
|
|
expires_in: 3600,
|
|
});
|
|
},
|
|
async () => {
|
|
const result = await refreshGitHubToken("github-refresh", log);
|
|
assert.deepEqual(result, {
|
|
accessToken: "github-access",
|
|
refreshToken: "github-refresh-next",
|
|
expiresIn: 3600,
|
|
});
|
|
}
|
|
);
|
|
}
|
|
);
|
|
|
|
assert.equal(calls[0].url, OAUTH_ENDPOINTS.github.token);
|
|
assert.match(bodyToString(calls[0].options.body), /client_id=github-client/);
|
|
});
|
|
|
|
test("refreshCopilotToken returns the short-lived copilot token", async () => {
|
|
const log = createLog();
|
|
const calls: any[] = [];
|
|
|
|
await withMockedFetch(
|
|
async (url, options = {}) => {
|
|
calls.push({ url, options });
|
|
return jsonResponse({
|
|
token: "copilot-session-token",
|
|
expires_at: "2026-01-01T00:00:00.000Z",
|
|
});
|
|
},
|
|
async () => {
|
|
const result = await refreshCopilotToken("github-access-token", log);
|
|
assert.deepEqual(result, {
|
|
token: "copilot-session-token",
|
|
expiresAt: "2026-01-01T00:00:00.000Z",
|
|
});
|
|
}
|
|
);
|
|
|
|
assert.equal(calls[0].url, "https://api.github.com/copilot_internal/v2/token");
|
|
assert.equal(calls[0].options.headers.Authorization, "token github-access-token");
|
|
});
|
|
|
|
test("supportsTokenRefresh, isUnrecoverableRefreshError and formatProviderCredentials cover provider helpers", async () => {
|
|
const log = createLog();
|
|
|
|
await withPatchedProperties(
|
|
PROVIDERS,
|
|
{
|
|
"custom-oauth-task-207": { tokenUrl: "https://auth.example.com/token" },
|
|
},
|
|
async () => {
|
|
assert.equal(supportsTokenRefresh("claude"), true);
|
|
assert.equal(supportsTokenRefresh("amazon-q"), true);
|
|
assert.equal(supportsTokenRefresh("custom-oauth-task-207"), true);
|
|
assert.equal(supportsTokenRefresh("missing-provider"), false);
|
|
}
|
|
);
|
|
|
|
assert.equal(isUnrecoverableRefreshError({ error: "refresh_token_reused" }), true);
|
|
assert.equal(isUnrecoverableRefreshError({ error: "invalid_request" }), true);
|
|
assert.equal(isUnrecoverableRefreshError({ error: "temporary_failure" }), false);
|
|
|
|
assert.deepEqual(
|
|
formatProviderCredentials(
|
|
"gemini",
|
|
{
|
|
apiKey: "gemini-key",
|
|
accessToken: "gemini-access",
|
|
projectId: "project-1",
|
|
refreshToken: "ignored",
|
|
},
|
|
log
|
|
),
|
|
{
|
|
apiKey: "gemini-key",
|
|
accessToken: "gemini-access",
|
|
projectId: "project-1",
|
|
}
|
|
);
|
|
|
|
assert.deepEqual(
|
|
formatProviderCredentials(
|
|
"antigravity",
|
|
{
|
|
accessToken: "google-access",
|
|
refreshToken: "google-refresh",
|
|
},
|
|
log
|
|
),
|
|
{
|
|
accessToken: "google-access",
|
|
refreshToken: "google-refresh",
|
|
}
|
|
);
|
|
|
|
assert.equal(formatProviderCredentials("missing-provider", {}, log), null);
|
|
});
|
|
|
|
test("getAccessToken deduplicates concurrent refreshes for the same provider and token", async () => {
|
|
const log = createLog();
|
|
let fetchCount = 0;
|
|
|
|
await withPatchedProperties(
|
|
PROVIDERS,
|
|
{
|
|
"custom-oauth-task-207": { tokenUrl: "https://auth.example.com/token" },
|
|
},
|
|
async () => {
|
|
await withMockedFetch(
|
|
async () => {
|
|
fetchCount += 1;
|
|
return jsonResponse({
|
|
access_token: "shared-access",
|
|
refresh_token: "shared-refresh-next",
|
|
expires_in: 600,
|
|
});
|
|
},
|
|
async () => {
|
|
const [first, second] = await Promise.all([
|
|
getAccessToken("custom-oauth-task-207", { refreshToken: "same-refresh" }, log),
|
|
getAccessToken("custom-oauth-task-207", { refreshToken: "same-refresh" }, log),
|
|
]);
|
|
|
|
assert.equal(fetchCount, 1);
|
|
assert.strictEqual(first, second);
|
|
assert.equal(first.accessToken, "shared-access");
|
|
}
|
|
);
|
|
}
|
|
);
|
|
});
|
|
|
|
test("getAccessToken cleans the in-flight cache after resolve and separates different tokens", async () => {
|
|
const log = createLog();
|
|
let fetchCount = 0;
|
|
|
|
await withPatchedProperties(
|
|
PROVIDERS,
|
|
{
|
|
"custom-oauth-task-207": { tokenUrl: "https://auth.example.com/token" },
|
|
},
|
|
async () => {
|
|
await withMockedFetch(
|
|
async (_url, options: RequestInit = {}) => {
|
|
fetchCount += 1;
|
|
const refreshToken = new URLSearchParams(bodyToString(options.body)).get("refresh_token");
|
|
return jsonResponse({
|
|
access_token: `access-${refreshToken}`,
|
|
refresh_token: `next-${refreshToken}`,
|
|
expires_in: 600,
|
|
});
|
|
},
|
|
async () => {
|
|
const first = await getAccessToken(
|
|
"custom-oauth-task-207",
|
|
{ refreshToken: "refresh-a" },
|
|
log
|
|
);
|
|
const second = await getAccessToken(
|
|
"custom-oauth-task-207",
|
|
{ refreshToken: "refresh-a" },
|
|
log
|
|
);
|
|
const third = await getAccessToken(
|
|
"custom-oauth-task-207",
|
|
{ refreshToken: "refresh-b" },
|
|
log
|
|
);
|
|
|
|
assert.equal(fetchCount, 3);
|
|
assert.equal(first.accessToken, "access-refresh-a");
|
|
assert.equal(second.accessToken, "access-refresh-a");
|
|
assert.equal(third.accessToken, "access-refresh-b");
|
|
}
|
|
);
|
|
}
|
|
);
|
|
});
|
|
|
|
test("getAccessToken returns null for invalid refresh token input", async () => {
|
|
const log = createLog();
|
|
const result = await getAccessToken("codex", { refreshToken: null }, log);
|
|
assert.equal(result, null);
|
|
});
|
|
|
|
test("getAllAccessTokens refreshes only active connections with providers", async () => {
|
|
const log = createLog();
|
|
let fetchCount = 0;
|
|
|
|
await withPatchedProperties(
|
|
PROVIDERS,
|
|
{
|
|
"custom-oauth-task-207": { tokenUrl: "https://auth.example.com/token" },
|
|
},
|
|
async () => {
|
|
await withMockedFetch(
|
|
async (_url, options: RequestInit = {}) => {
|
|
fetchCount += 1;
|
|
const refreshToken = new URLSearchParams(bodyToString(options.body)).get("refresh_token");
|
|
return jsonResponse({
|
|
access_token: `access-${refreshToken}`,
|
|
refresh_token: `next-${refreshToken}`,
|
|
expires_in: 900,
|
|
});
|
|
},
|
|
async () => {
|
|
const tokens = await getAllAccessTokens(
|
|
{
|
|
connections: [
|
|
{
|
|
provider: "custom-oauth-task-207",
|
|
refreshToken: "active-one",
|
|
isActive: true,
|
|
},
|
|
{
|
|
provider: "custom-oauth-task-207",
|
|
refreshToken: "inactive-one",
|
|
isActive: false,
|
|
},
|
|
{
|
|
provider: null,
|
|
refreshToken: "missing-provider",
|
|
isActive: true,
|
|
},
|
|
],
|
|
},
|
|
log
|
|
);
|
|
|
|
assert.equal(fetchCount, 1);
|
|
assert.deepEqual(tokens, {
|
|
"custom-oauth-task-207": {
|
|
accessToken: "access-active-one",
|
|
refreshToken: "next-active-one",
|
|
expiresIn: 900,
|
|
},
|
|
});
|
|
}
|
|
);
|
|
}
|
|
);
|
|
});
|
|
|
|
test("refreshWithRetry retries to success and clears prior circuit-breaker state", async () => {
|
|
const provider = `retry-success-${Date.now()}`;
|
|
const log = createLog();
|
|
|
|
await refreshWithRetry(async () => null, 1, log, provider);
|
|
assert.equal(getCircuitBreakerStatus()[provider].failures, 1);
|
|
|
|
await withFastRetryTimers(async () => {
|
|
let attempts = 0;
|
|
const result = await refreshWithRetry(
|
|
async () => {
|
|
attempts += 1;
|
|
return attempts === 2 ? { accessToken: "recovered" } : null;
|
|
},
|
|
3,
|
|
log,
|
|
provider
|
|
);
|
|
|
|
assert.deepEqual(result, { accessToken: "recovered" });
|
|
assert.equal(attempts, 2);
|
|
assert.equal(getCircuitBreakerStatus()[provider], undefined);
|
|
});
|
|
});
|
|
|
|
test("refreshWithRetry trips the circuit breaker after repeated failures and blocks new calls", async () => {
|
|
const provider = `retry-blocked-${Date.now()}`;
|
|
const log = createLog();
|
|
|
|
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
const result = await refreshWithRetry(async () => null, 1, log, provider);
|
|
assert.equal(result, null);
|
|
}
|
|
|
|
assert.equal(isProviderBlocked(provider), true);
|
|
assert.equal(getCircuitBreakerStatus()[provider].blocked, true);
|
|
|
|
let called = false;
|
|
const blockedResult = await refreshWithRetry(
|
|
async () => {
|
|
called = true;
|
|
return { accessToken: "should-not-run" };
|
|
},
|
|
1,
|
|
log,
|
|
provider
|
|
);
|
|
|
|
assert.equal(blockedResult, null);
|
|
assert.equal(called, false);
|
|
});
|
|
|
|
test("isProviderBlocked clears expired circuit-breaker entries once cooldown passes", async () => {
|
|
const provider = `retry-expiry-${Date.now()}`;
|
|
const log = createLog();
|
|
|
|
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
await refreshWithRetry(async () => null, 1, log, provider);
|
|
}
|
|
|
|
const blockedUntil = Date.parse(getCircuitBreakerStatus()[provider].blockedUntil as string);
|
|
|
|
await withMockedNow(blockedUntil + 1, async () => {
|
|
assert.equal(isProviderBlocked(provider), false);
|
|
assert.equal(getCircuitBreakerStatus()[provider], undefined);
|
|
});
|
|
});
|
|
|
|
// ─── Per-connection mutex tests ────────────────────────────────────────────────
|
|
|
|
test("getAccessToken per-connection mutex: 5 concurrent callers fire exactly one upstream call", async () => {
|
|
const log = createLog();
|
|
let upstreamCallCount = 0;
|
|
|
|
await withPatchedProperties(
|
|
PROVIDERS,
|
|
{ "custom-oauth-conn-mutex": { tokenUrl: "https://auth.example.com/token" } },
|
|
async () => {
|
|
await withMockedFetch(
|
|
async () => {
|
|
upstreamCallCount++;
|
|
// Simulate 50ms upstream latency so all 5 callers are concurrent
|
|
await new Promise((r) => setTimeout(r, 50));
|
|
return jsonResponse({
|
|
access_token: "new-access-token",
|
|
refresh_token: "new-refresh-token",
|
|
expires_in: 3600,
|
|
});
|
|
},
|
|
async () => {
|
|
const credentials = {
|
|
connectionId: "conn-abc-123",
|
|
refreshToken: "old-refresh-token",
|
|
};
|
|
|
|
const results = await Promise.all([
|
|
getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),
|
|
getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),
|
|
getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),
|
|
getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),
|
|
getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),
|
|
]);
|
|
|
|
assert.equal(upstreamCallCount, 1, "upstream called exactly once");
|
|
for (const result of results) {
|
|
assert.equal(result?.accessToken, "new-access-token", "all callers got same token");
|
|
assert.equal(result?.refreshToken, "new-refresh-token");
|
|
}
|
|
// All results are the same object reference (shared promise)
|
|
assert.strictEqual(results[0], results[1]);
|
|
assert.strictEqual(results[1], results[4]);
|
|
}
|
|
);
|
|
}
|
|
);
|
|
});
|
|
|
|
test("getAccessToken per-connection mutex: logs concurrent refresh with waiter count", async () => {
|
|
const log = createLog();
|
|
|
|
await withPatchedProperties(
|
|
PROVIDERS,
|
|
{ "custom-oauth-conn-mutex": { tokenUrl: "https://auth.example.com/token" } },
|
|
async () => {
|
|
await withMockedFetch(
|
|
async () => {
|
|
await new Promise((r) => setTimeout(r, 20));
|
|
return jsonResponse({ access_token: "tok", refresh_token: "rtok", expires_in: 600 });
|
|
},
|
|
async () => {
|
|
const credentials = { connectionId: "conn-log-test", refreshToken: "rt" };
|
|
await Promise.all([
|
|
getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),
|
|
getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),
|
|
getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),
|
|
]);
|
|
|
|
const concurrentLogs = log.entries.filter(
|
|
(e) =>
|
|
e.level === "info" &&
|
|
e.message === "Concurrent refresh detected — sharing in-flight refresh"
|
|
);
|
|
assert.ok(concurrentLogs.length >= 1, "logged at least one concurrent refresh event");
|
|
assert.ok(
|
|
concurrentLogs.some((e) => e.meta?.connectionId === "conn-log-test"),
|
|
"log includes connectionId"
|
|
);
|
|
assert.ok(
|
|
concurrentLogs.some((e) => typeof e.meta?.waiters === "number" && e.meta.waiters >= 1),
|
|
"log includes waiter count"
|
|
);
|
|
}
|
|
);
|
|
}
|
|
);
|
|
});
|
|
|
|
test("getAccessToken per-connection mutex: failed refresh propagates null to all waiters (idempotent error)", async () => {
|
|
const log = createLog();
|
|
|
|
await withPatchedProperties(
|
|
PROVIDERS,
|
|
{ "custom-oauth-conn-mutex": { tokenUrl: "https://auth.example.com/token" } },
|
|
async () => {
|
|
await withMockedFetch(
|
|
async () => {
|
|
await new Promise((r) => setTimeout(r, 20));
|
|
// 400 response causes refreshAccessToken to return null
|
|
return new Response("bad_request", { status: 400 });
|
|
},
|
|
async () => {
|
|
const credentials = { connectionId: "conn-fail-test", refreshToken: "expired-rt" };
|
|
const results = await Promise.all([
|
|
getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),
|
|
getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),
|
|
getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),
|
|
]);
|
|
|
|
for (const result of results) {
|
|
assert.equal(result, null, "failed refresh returns null to all waiters");
|
|
}
|
|
// Mutex cleaned up after failure
|
|
assert.equal(
|
|
getConnectionRefreshMutexStatus()["conn-fail-test"],
|
|
undefined,
|
|
"mutex entry removed after failure"
|
|
);
|
|
}
|
|
);
|
|
}
|
|
);
|
|
});
|
|
|
|
test("getAccessToken per-connection mutex: different connections run independently", async () => {
|
|
const log = createLog();
|
|
let upstreamCallCount = 0;
|
|
|
|
await withPatchedProperties(
|
|
PROVIDERS,
|
|
{ "custom-oauth-conn-mutex": { tokenUrl: "https://auth.example.com/token" } },
|
|
async () => {
|
|
await withMockedFetch(
|
|
async () => {
|
|
upstreamCallCount++;
|
|
await new Promise((r) => setTimeout(r, 20));
|
|
return jsonResponse({
|
|
access_token: `access-${upstreamCallCount}`,
|
|
refresh_token: `refresh-${upstreamCallCount}`,
|
|
expires_in: 600,
|
|
});
|
|
},
|
|
async () => {
|
|
const [groupA, groupB] = await Promise.all([
|
|
Promise.all([
|
|
getAccessToken(
|
|
"custom-oauth-conn-mutex",
|
|
{ connectionId: "conn-A", refreshToken: "rt-a" },
|
|
log
|
|
),
|
|
getAccessToken(
|
|
"custom-oauth-conn-mutex",
|
|
{ connectionId: "conn-A", refreshToken: "rt-a" },
|
|
log
|
|
),
|
|
]),
|
|
Promise.all([
|
|
getAccessToken(
|
|
"custom-oauth-conn-mutex",
|
|
{ connectionId: "conn-B", refreshToken: "rt-b" },
|
|
log
|
|
),
|
|
getAccessToken(
|
|
"custom-oauth-conn-mutex",
|
|
{ connectionId: "conn-B", refreshToken: "rt-b" },
|
|
log
|
|
),
|
|
]),
|
|
]);
|
|
|
|
assert.equal(upstreamCallCount, 2, "one upstream call per distinct connection");
|
|
assert.strictEqual(groupA[0], groupA[1], "conn-A callers share same result");
|
|
assert.strictEqual(groupB[0], groupB[1], "conn-B callers share same result");
|
|
assert.notStrictEqual(groupA[0], groupB[0], "conn-A and conn-B got different results");
|
|
}
|
|
);
|
|
}
|
|
);
|
|
});
|
|
|
|
test("getAccessToken per-connection mutex: mutex cleared after success, next call re-fires upstream", async () => {
|
|
const log = createLog();
|
|
let upstreamCallCount = 0;
|
|
|
|
await withPatchedProperties(
|
|
PROVIDERS,
|
|
{ "custom-oauth-conn-mutex": { tokenUrl: "https://auth.example.com/token" } },
|
|
async () => {
|
|
await withMockedFetch(
|
|
async () => {
|
|
upstreamCallCount++;
|
|
return jsonResponse({
|
|
access_token: `access-${upstreamCallCount}`,
|
|
refresh_token: `refresh-${upstreamCallCount}`,
|
|
expires_in: 600,
|
|
});
|
|
},
|
|
async () => {
|
|
const credentials = { connectionId: "conn-refire", refreshToken: "rt" };
|
|
|
|
const first = await getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log);
|
|
const second = await getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log);
|
|
|
|
assert.equal(upstreamCallCount, 2, "each sequential call fires upstream once");
|
|
assert.equal(first?.accessToken, "access-1");
|
|
assert.equal(second?.accessToken, "access-2");
|
|
}
|
|
);
|
|
}
|
|
);
|
|
});
|
|
|
|
// ─── Unrecoverable error bail-out tests ──────────────────────────────────────
|
|
|
|
test("refreshWithRetry bails immediately on unrecoverable error without retrying", async () => {
|
|
const provider = `bail-unrecoverable-${Date.now()}`;
|
|
const log = createLog();
|
|
let callCount = 0;
|
|
|
|
const result = await refreshWithRetry(
|
|
async () => {
|
|
callCount++;
|
|
return { error: "unrecoverable_refresh_error", code: "http_400" };
|
|
},
|
|
3,
|
|
log,
|
|
provider
|
|
);
|
|
|
|
assert.equal(callCount, 1, "should only call refreshFn once (no retries)");
|
|
assert.deepEqual(result, { error: "unrecoverable_refresh_error", code: "http_400" });
|
|
const warnMessages = log.entries.filter((e) => e.level === "warn").map((e) => e.message);
|
|
assert.ok(
|
|
warnMessages.some((m) => String(m).includes("Unrecoverable")),
|
|
"should log an unrecoverable warning"
|
|
);
|
|
});
|
|
|
|
test("refreshWithRetry bails immediately on invalid_grant error without retrying", async () => {
|
|
const provider = `bail-invalid-grant-${Date.now()}`;
|
|
const log = createLog();
|
|
let callCount = 0;
|
|
|
|
const result = await refreshWithRetry(
|
|
async () => {
|
|
callCount++;
|
|
return { error: "invalid_grant", code: "http_400" };
|
|
},
|
|
3,
|
|
log,
|
|
provider
|
|
);
|
|
|
|
assert.equal(callCount, 1, "should only call refreshFn once (no retries)");
|
|
assert.deepEqual(result, { error: "invalid_grant", code: "http_400" });
|
|
});
|
|
|
|
test("refreshClaudeOAuthToken returns error object for invalid_grant (expired refresh token)", async () => {
|
|
const log = createLog();
|
|
|
|
await withMockedFetch(
|
|
async () =>
|
|
new Response(JSON.stringify({ error: "invalid_grant", error_description: "Token expired" }), {
|
|
status: 400,
|
|
headers: { "Content-Type": "application/json" },
|
|
}),
|
|
async () => {
|
|
const result = await refreshClaudeOAuthToken("expired-token", log);
|
|
assert.ok(result && typeof result === "object", "should return error object, not null");
|
|
assert.equal((result as any).error, "invalid_grant");
|
|
assert.ok(isUnrecoverableRefreshError(result), "should be detected as unrecoverable");
|
|
}
|
|
);
|
|
});
|
|
|
|
test("refreshClaudeOAuthToken returns null for transient server errors (not unrecoverable)", async () => {
|
|
const log = createLog();
|
|
|
|
await withMockedFetch(
|
|
async () =>
|
|
new Response(JSON.stringify({ error: "server_error" }), {
|
|
status: 503,
|
|
headers: { "Content-Type": "application/json" },
|
|
}),
|
|
async () => {
|
|
const result = await refreshClaudeOAuthToken("some-token", log);
|
|
assert.equal(result, null, "transient server errors should return null (retryable)");
|
|
}
|
|
);
|
|
});
|