mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-11-22 04:19:40 +00:00
refactor(oauth): type CopilotRefreshResult and extract GHE fallback helpers
This commit is contained in:
@@ -182,6 +182,34 @@ export class GheCopilotExecutor extends GithubExecutor {
|
||||
return transformed;
|
||||
}
|
||||
|
||||
private async fetchGheCopilotUserFallback(
|
||||
baseUrl: string,
|
||||
githubAccessToken: string,
|
||||
log?: { info?: (cat: string, msg: string) => void; error?: (cat: string, msg: string) => void },
|
||||
credentials?: ProviderCredentials | null
|
||||
): Promise<CopilotTokenResult | null> {
|
||||
const userUrl = `${baseUrl}/api/v3/copilot_internal/user`;
|
||||
this.assertOutboundUrlAllowed(userUrl);
|
||||
const userResponse = await dispatchGuarded(
|
||||
this.provider,
|
||||
userUrl,
|
||||
{ headers: { Authorization: `Bearer ${githubAccessToken}`, Accept: "application/json" } },
|
||||
credentials
|
||||
);
|
||||
if (!userResponse.ok) return null;
|
||||
|
||||
const userData = await userResponse.json().catch(() => ({}));
|
||||
log?.info?.("TOKEN", "GHE Copilot token resolved via copilot_internal/user");
|
||||
const endpoints = userData?.endpoints
|
||||
? { proxy: userData.endpoints.proxy, api: userData.endpoints.api }
|
||||
: undefined;
|
||||
return {
|
||||
token: githubAccessToken,
|
||||
expiresAt: Math.floor(Date.now() / 1000) + 3600,
|
||||
...(endpoints ? { endpoints } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
override async refreshCopilotToken(
|
||||
githubAccessToken: string,
|
||||
log?: { info?: (cat: string, msg: string) => void; error?: (cat: string, msg: string) => void },
|
||||
@@ -203,34 +231,9 @@ export class GheCopilotExecutor extends GithubExecutor {
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 404) {
|
||||
const userUrl = `${baseUrl}/api/v3/copilot_internal/user`;
|
||||
this.assertOutboundUrlAllowed(userUrl);
|
||||
const userResponse = await dispatchGuarded(
|
||||
this.provider,
|
||||
userUrl,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${githubAccessToken}`,
|
||||
Accept: "application/json",
|
||||
},
|
||||
},
|
||||
credentials
|
||||
);
|
||||
if (userResponse.ok) {
|
||||
const userData = await userResponse.json().catch(() => ({}));
|
||||
log?.info?.("TOKEN", "GHE Copilot token resolved via copilot_internal/user");
|
||||
const endpoints = userData?.endpoints
|
||||
? { proxy: userData.endpoints.proxy, api: userData.endpoints.api }
|
||||
: undefined;
|
||||
return {
|
||||
token: githubAccessToken,
|
||||
expiresAt: Math.floor(Date.now() / 1000) + 3600,
|
||||
...(endpoints ? { endpoints } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
return response.status === 404
|
||||
? await this.fetchGheCopilotUserFallback(baseUrl, githubAccessToken, log, credentials)
|
||||
: null;
|
||||
}
|
||||
const data = await response.json();
|
||||
log?.info?.("TOKEN", "GHE Copilot token refreshed");
|
||||
|
||||
@@ -4,6 +4,87 @@
|
||||
import { getGitHubCopilotRefreshHeaders } from "../../../config/providerHeaderProfiles.ts";
|
||||
import { runWithProxyContext } from "../../../utils/proxyFetch.ts";
|
||||
|
||||
export interface CopilotRefreshResult {
|
||||
token?: string;
|
||||
expiresAt?: number;
|
||||
status?: number | null;
|
||||
endpoints?: { proxy?: string; api?: string };
|
||||
}
|
||||
|
||||
function extractCopilotEndpoints(data: { endpoints?: { proxy?: string; api?: string } } | null) {
|
||||
return data?.endpoints ? { proxy: data.endpoints.proxy, api: data.endpoints.api } : undefined;
|
||||
}
|
||||
|
||||
function buildCopilotRefreshSuccess(
|
||||
token: string,
|
||||
expiresAt: number,
|
||||
data: { endpoints?: { proxy?: string; api?: string } } | null
|
||||
): CopilotRefreshResult {
|
||||
const endpoints = extractCopilotEndpoints(data);
|
||||
return endpoints ? { token, expiresAt, endpoints } : { token, expiresAt };
|
||||
}
|
||||
|
||||
export interface CopilotRefreshLogger {
|
||||
info?: (tag: string, msg: string, extra?: Record<string, unknown>) => void;
|
||||
error?: (tag: string, msg: string, extra?: Record<string, unknown>) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* GHE Cloud with data residency (*.ghe.com) returns 404 on
|
||||
* /copilot_internal/v2/token and instead serves endpoint metadata at
|
||||
* /copilot_internal/user while accepting the OAuth access token directly.
|
||||
*/
|
||||
async function refreshGheDataResidencyCopilotToken(
|
||||
githubAccessToken: string,
|
||||
normalizedBase: string,
|
||||
headers: Record<string, string>,
|
||||
proxyConfig: unknown,
|
||||
log?: CopilotRefreshLogger | null
|
||||
): Promise<CopilotRefreshResult | null> {
|
||||
if (normalizedBase === "https://api.github.com") return null;
|
||||
|
||||
const userUrl = `${normalizedBase}/copilot_internal/user`;
|
||||
const userResponse = await runWithProxyContext(proxyConfig, () => fetch(userUrl, { headers }));
|
||||
if (!userResponse.ok) {
|
||||
await userResponse.body?.cancel().catch(() => {});
|
||||
return null;
|
||||
}
|
||||
|
||||
const userData = await userResponse.json().catch(() => ({}));
|
||||
const expiresAt = Math.floor(Date.now() / 1000) + 3600;
|
||||
log?.info?.("TOKEN_REFRESH", "Refreshed GHE Copilot token via copilot_internal/user", {
|
||||
hasToken: true,
|
||||
expiresAt,
|
||||
});
|
||||
return buildCopilotRefreshSuccess(githubAccessToken, expiresAt, userData);
|
||||
}
|
||||
|
||||
async function handleFailedCopilotTokenResponse(
|
||||
response: Response,
|
||||
githubAccessToken: string,
|
||||
normalizedBase: string,
|
||||
headers: Record<string, string>,
|
||||
proxyConfig: unknown,
|
||||
log?: CopilotRefreshLogger | null
|
||||
): Promise<CopilotRefreshResult> {
|
||||
if (response.status === 404) {
|
||||
await response.body?.cancel().catch(() => {});
|
||||
const fallback = await refreshGheDataResidencyCopilotToken(
|
||||
githubAccessToken,
|
||||
normalizedBase,
|
||||
headers,
|
||||
proxyConfig,
|
||||
log
|
||||
);
|
||||
if (fallback) return fallback;
|
||||
}
|
||||
|
||||
log?.error?.("TOKEN_REFRESH", "Failed to refresh Copilot token", {
|
||||
status: response.status,
|
||||
});
|
||||
return { status: response.status };
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh GitHub Copilot token using a GitHub access token.
|
||||
*
|
||||
@@ -18,65 +99,30 @@ export async function refreshCopilotToken(
|
||||
log,
|
||||
proxyConfig: unknown = null,
|
||||
baseUrl: string = "https://api.github.com"
|
||||
) {
|
||||
): Promise<CopilotRefreshResult> {
|
||||
try {
|
||||
const normalizedBase = baseUrl.replace(/\/+$/, "");
|
||||
const tokenUrl = `${normalizedBase}/copilot_internal/v2/token`;
|
||||
const headers = getGitHubCopilotRefreshHeaders(`token ${githubAccessToken}`);
|
||||
const response = await runWithProxyContext(proxyConfig, () =>
|
||||
fetch(tokenUrl, { headers })
|
||||
);
|
||||
const response = await runWithProxyContext(proxyConfig, () => fetch(tokenUrl, { headers }));
|
||||
|
||||
if (!response.ok) {
|
||||
// GHE Cloud with data residency (*.ghe.com) returns 404 on
|
||||
// /copilot_internal/v2/token and instead serves endpoint metadata at
|
||||
// /copilot_internal/user while accepting the OAuth access token directly.
|
||||
if (response.status === 404 && normalizedBase !== "https://api.github.com") {
|
||||
await response.body?.cancel().catch(() => {});
|
||||
const userUrl = `${normalizedBase}/copilot_internal/user`;
|
||||
const userResponse = await runWithProxyContext(proxyConfig, () =>
|
||||
fetch(userUrl, { headers })
|
||||
);
|
||||
if (userResponse.ok) {
|
||||
const userData = await userResponse.json().catch(() => ({}));
|
||||
const expiresAt = Math.floor(Date.now() / 1000) + 3600;
|
||||
const endpoints = userData?.endpoints
|
||||
? { proxy: userData.endpoints.proxy, api: userData.endpoints.api }
|
||||
: undefined;
|
||||
log?.info?.("TOKEN_REFRESH", "Refreshed GHE Copilot token via copilot_internal/user", {
|
||||
hasToken: true,
|
||||
expiresAt,
|
||||
});
|
||||
return {
|
||||
token: githubAccessToken,
|
||||
expiresAt,
|
||||
...(endpoints ? { endpoints } : {}),
|
||||
};
|
||||
}
|
||||
await userResponse.body?.cancel().catch(() => {});
|
||||
}
|
||||
|
||||
log?.error?.("TOKEN_REFRESH", "Failed to refresh Copilot token", {
|
||||
status: response.status,
|
||||
});
|
||||
return { status: response.status };
|
||||
return await handleFailedCopilotTokenResponse(
|
||||
response,
|
||||
githubAccessToken,
|
||||
normalizedBase,
|
||||
headers,
|
||||
proxyConfig,
|
||||
log
|
||||
);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const endpoints = data?.endpoints
|
||||
? { proxy: data.endpoints.proxy, api: data.endpoints.api }
|
||||
: undefined;
|
||||
|
||||
log?.info?.("TOKEN_REFRESH", "Successfully refreshed Copilot token", {
|
||||
hasToken: !!data.token,
|
||||
expiresAt: data.expires_at,
|
||||
});
|
||||
|
||||
return {
|
||||
token: data.token,
|
||||
expiresAt: data.expires_at,
|
||||
...(endpoints ? { endpoints } : {}),
|
||||
};
|
||||
return buildCopilotRefreshSuccess(data.token, data.expires_at, data);
|
||||
} catch (error) {
|
||||
log?.error?.("TOKEN_REFRESH", "Error refreshing Copilot token", {
|
||||
errorType: error?.name || "Error",
|
||||
|
||||
@@ -75,6 +75,32 @@ async function optionalJson(url: string, init: RequestInit) {
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveGheCopilotToken(
|
||||
gheUrl: string,
|
||||
accessToken: string,
|
||||
lookupInit: RequestInit
|
||||
) {
|
||||
const copilotToken = await optionalJson(`${gheUrl}/api/v3/copilot_internal/v2/token`, lookupInit);
|
||||
if (copilotToken?.token || copilotToken?.endpoints?.api) {
|
||||
return copilotToken;
|
||||
}
|
||||
|
||||
// GHE Cloud with data residency (*.ghe.com) does not expose
|
||||
// /api/v3/copilot_internal/v2/token (returns 404). Instead, it exposes
|
||||
// endpoints via /api/v3/copilot_internal/user and accepts the GitHub OAuth
|
||||
// access_token directly as a Bearer token on endpoints.api.
|
||||
const copilotUser = await optionalJson(`${gheUrl}/api/v3/copilot_internal/user`, lookupInit);
|
||||
if (!copilotUser?.endpoints?.api && !copilotUser?.endpoints?.proxy) {
|
||||
return copilotToken;
|
||||
}
|
||||
return {
|
||||
...copilotToken,
|
||||
token: accessToken,
|
||||
expires_at: Math.floor(Date.now() / 1000) + 3600,
|
||||
endpoints: copilotUser.endpoints,
|
||||
};
|
||||
}
|
||||
|
||||
export const gheCopilot = {
|
||||
config: GHE_COPILOT_CONFIG,
|
||||
flowType: "device_code" as const,
|
||||
@@ -142,28 +168,7 @@ export const gheCopilot = {
|
||||
"User-Agent": getGitHubCopilotChatUserAgent(),
|
||||
},
|
||||
};
|
||||
let copilotToken = await optionalJson(
|
||||
`${gheUrl}/api/v3/copilot_internal/v2/token`,
|
||||
lookupInit
|
||||
);
|
||||
// GHE Cloud with data residency (*.ghe.com) does not expose
|
||||
// /api/v3/copilot_internal/v2/token (returns 404). Instead, it exposes
|
||||
// endpoints via /api/v3/copilot_internal/user and accepts the GitHub OAuth
|
||||
// access_token directly as a Bearer token on endpoints.api.
|
||||
if (!copilotToken?.token && !copilotToken?.endpoints?.api) {
|
||||
const copilotUser = await optionalJson(
|
||||
`${gheUrl}/api/v3/copilot_internal/user`,
|
||||
lookupInit
|
||||
);
|
||||
if (copilotUser?.endpoints?.api || copilotUser?.endpoints?.proxy) {
|
||||
copilotToken = {
|
||||
...copilotToken,
|
||||
token: tokens.access_token,
|
||||
expires_at: Math.floor(Date.now() / 1000) + 3600,
|
||||
endpoints: copilotUser.endpoints,
|
||||
};
|
||||
}
|
||||
}
|
||||
const copilotToken = await resolveGheCopilotToken(gheUrl, tokens.access_token, lookupInit);
|
||||
const userInfo = await optionalJson(`${gheUrl}/api/v3/user`, lookupInit);
|
||||
return {
|
||||
copilotToken,
|
||||
|
||||
@@ -810,15 +810,14 @@ export async function checkConnection(conn: any) {
|
||||
copilotResult.token &&
|
||||
copilotAboutToExpire
|
||||
) {
|
||||
const endpoints = (
|
||||
copilotResult as { endpoints?: { api?: string; proxy?: string } }
|
||||
).endpoints;
|
||||
refreshedProviderSpecificData = {
|
||||
...providerSpecificData,
|
||||
copilotToken: copilotResult.token,
|
||||
copilotTokenExpiresAt: copilotResult.expiresAt,
|
||||
...(endpoints?.api ? { copilotApiUrl: endpoints.api } : {}),
|
||||
...(endpoints?.proxy ? { copilotProxyUrl: endpoints.proxy } : {}),
|
||||
...(copilotResult.endpoints?.api ? { copilotApiUrl: copilotResult.endpoints.api } : {}),
|
||||
...(copilotResult.endpoints?.proxy
|
||||
? { copilotProxyUrl: copilotResult.endpoints.proxy }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -462,10 +462,10 @@ test("gheCopilot OAuth postExchange falls back to /api/v3/copilot_internal/user
|
||||
);
|
||||
}
|
||||
if (urlStr.endsWith("/api/v3/user")) {
|
||||
return new Response(
|
||||
JSON.stringify({ login: "corpuser", email: "corpuser@example.com" }),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
return new Response(JSON.stringify({ login: "corpuser", email: "corpuser@example.com" }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
return new Response("unexpected", { status: 500 });
|
||||
};
|
||||
@@ -481,23 +481,16 @@ test("gheCopilot OAuth postExchange falls back to /api/v3/copilot_internal/user
|
||||
"https://msft.ghe.com/api/v3/user",
|
||||
]);
|
||||
assert.equal(mapped.providerSpecificData.copilotToken, "gho_ghe_oauth_token");
|
||||
assert.equal(
|
||||
mapped.providerSpecificData.copilotApiUrl,
|
||||
"https://copilot-api.msft.ghe.com"
|
||||
);
|
||||
assert.equal(
|
||||
mapped.providerSpecificData.copilotProxyUrl,
|
||||
"https://copilot-proxy.msft.ghe.com"
|
||||
);
|
||||
assert.equal(mapped.providerSpecificData.copilotApiUrl, "https://copilot-api.msft.ghe.com");
|
||||
assert.equal(mapped.providerSpecificData.copilotProxyUrl, "https://copilot-proxy.msft.ghe.com");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test("refreshCopilotToken service falls back to /copilot_internal/user on 404 for GHE baseUrl", async () => {
|
||||
const { refreshCopilotToken } = await import(
|
||||
"../../open-sse/services/tokenRefresh/providers/copilot.ts"
|
||||
);
|
||||
const { refreshCopilotToken } =
|
||||
await import("../../open-sse/services/tokenRefresh/providers/copilot.ts");
|
||||
const originalFetch = globalThis.fetch;
|
||||
const calledUrls: string[] = [];
|
||||
|
||||
@@ -543,4 +536,3 @@ test("refreshCopilotToken service falls back to /copilot_internal/user on 404 fo
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user