github-copilot-oauth.test.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import { loginGitHubCopilot } from "../src/utils/oauth/github-copilot.ts";
  3. function jsonResponse(body: unknown, status: number = 200): Response {
  4. return new Response(JSON.stringify(body), {
  5. status,
  6. headers: {
  7. "Content-Type": "application/json",
  8. },
  9. });
  10. }
  11. function getUrl(input: unknown): string {
  12. if (typeof input === "string") {
  13. return input;
  14. }
  15. if (input instanceof URL) {
  16. return input.toString();
  17. }
  18. if (input instanceof Request) {
  19. return input.url;
  20. }
  21. throw new Error(`Unsupported fetch input: ${String(input)}`);
  22. }
  23. describe("GitHub Copilot OAuth device flow", () => {
  24. afterEach(() => {
  25. vi.unstubAllGlobals();
  26. vi.useRealTimers();
  27. });
  28. it("reports device-code details through onDeviceCode", async () => {
  29. vi.useFakeTimers();
  30. vi.setSystemTime(new Date("2026-03-09T00:00:00Z"));
  31. const fetchMock = vi.fn(async (input: unknown): Promise<Response> => {
  32. const url = getUrl(input);
  33. if (url.endsWith("/login/device/code")) {
  34. return jsonResponse({
  35. device_code: "device-code",
  36. user_code: "ABCD-EFGH",
  37. verification_uri: "https://github.com/login/device",
  38. interval: 1,
  39. expires_in: 900,
  40. });
  41. }
  42. if (url.endsWith("/login/oauth/access_token")) {
  43. return jsonResponse({ access_token: "ghu_refresh_token" });
  44. }
  45. if (url.includes("/copilot_internal/v2/token")) {
  46. return jsonResponse({
  47. token: "tid=test;exp=9999999999;proxy-ep=proxy.individual.githubcopilot.com;",
  48. expires_at: 9999999999,
  49. });
  50. }
  51. if (url.includes("/models/") && url.endsWith("/policy")) {
  52. return new Response("", { status: 200 });
  53. }
  54. throw new Error(`Unexpected fetch URL: ${url}`);
  55. });
  56. vi.stubGlobal("fetch", fetchMock);
  57. const onDeviceCode = vi.fn();
  58. const loginPromise = loginGitHubCopilot({
  59. onDeviceCode,
  60. onPrompt: async () => "",
  61. });
  62. await vi.advanceTimersByTimeAsync(0);
  63. expect(onDeviceCode).toHaveBeenCalledWith({
  64. userCode: "ABCD-EFGH",
  65. verificationUri: "https://github.com/login/device",
  66. intervalSeconds: 1,
  67. expiresInSeconds: 900,
  68. });
  69. await vi.advanceTimersByTimeAsync(1000);
  70. await loginPromise;
  71. });
  72. it("rejects a non-http(s) verification_uri before it reaches onDeviceCode", async () => {
  73. // A malicious enterprise OAuth server could return a verification_uri that
  74. // the browser launcher would otherwise hand to the OS. Ensure such values
  75. // are rejected at the deserialization boundary.
  76. const fetchMock = vi.fn(async (input: unknown): Promise<Response> => {
  77. const url = getUrl(input);
  78. if (url.endsWith("/login/device/code")) {
  79. return jsonResponse({
  80. device_code: "device-code",
  81. user_code: "ABCD-EFGH",
  82. verification_uri: "$(id>/tmp/pwned)",
  83. interval: 1,
  84. expires_in: 900,
  85. });
  86. }
  87. throw new Error(`Unexpected fetch URL: ${url}`);
  88. });
  89. vi.stubGlobal("fetch", fetchMock);
  90. const onDeviceCode = vi.fn();
  91. await expect(
  92. loginGitHubCopilot({
  93. onDeviceCode,
  94. onPrompt: async () => "",
  95. }),
  96. ).rejects.toThrow(/Untrusted verification_uri/);
  97. expect(onDeviceCode).not.toHaveBeenCalled();
  98. });
  99. it("normalizes verification_uri before it reaches onDeviceCode", async () => {
  100. vi.useFakeTimers();
  101. vi.setSystemTime(new Date("2026-03-09T00:00:00Z"));
  102. const rawVerificationUri = "https://github.com/login/\x1b]8;;evil";
  103. const normalizedVerificationUri = new URL(rawVerificationUri).href;
  104. expect(normalizedVerificationUri).not.toBe(rawVerificationUri);
  105. const fetchMock = vi.fn(async (input: unknown): Promise<Response> => {
  106. const url = getUrl(input);
  107. if (url.endsWith("/login/device/code")) {
  108. return jsonResponse({
  109. device_code: "device-code",
  110. user_code: "ABCD-EFGH",
  111. verification_uri: rawVerificationUri,
  112. interval: 1,
  113. expires_in: 900,
  114. });
  115. }
  116. if (url.endsWith("/login/oauth/access_token")) {
  117. return jsonResponse({ access_token: "ghu_refresh_token" });
  118. }
  119. if (url.includes("/copilot_internal/v2/token")) {
  120. return jsonResponse({
  121. token: "tid=test;exp=9999999999;proxy-ep=proxy.individual.githubcopilot.com;",
  122. expires_at: 9999999999,
  123. });
  124. }
  125. if (url.includes("/models/") && url.endsWith("/policy")) {
  126. return new Response("", { status: 200 });
  127. }
  128. throw new Error(`Unexpected fetch URL: ${url}`);
  129. });
  130. vi.stubGlobal("fetch", fetchMock);
  131. const onDeviceCode = vi.fn();
  132. const loginPromise = loginGitHubCopilot({
  133. onDeviceCode,
  134. onPrompt: async () => "",
  135. });
  136. await vi.advanceTimersByTimeAsync(0);
  137. expect(onDeviceCode).toHaveBeenCalledWith({
  138. userCode: "ABCD-EFGH",
  139. verificationUri: normalizedVerificationUri,
  140. intervalSeconds: 1,
  141. expiresInSeconds: 900,
  142. });
  143. expect(onDeviceCode).not.toHaveBeenCalledWith(expect.objectContaining({ verificationUri: rawVerificationUri }));
  144. await vi.advanceTimersByTimeAsync(1000);
  145. await loginPromise;
  146. });
  147. it("polls immediately and increases the interval after slow_down", async () => {
  148. vi.useFakeTimers();
  149. const startTime = new Date("2026-03-09T00:00:00Z");
  150. vi.setSystemTime(startTime);
  151. const accessTokenPollTimes: number[] = [];
  152. const accessTokenResponses = [
  153. jsonResponse({ error: "authorization_pending", error_description: "pending" }),
  154. jsonResponse({ error: "slow_down", error_description: "slow down" }),
  155. jsonResponse({ access_token: "ghu_refresh_token" }),
  156. ];
  157. const fetchMock = vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
  158. const url = getUrl(input);
  159. if (url.endsWith("/login/device/code")) {
  160. expect(init?.method).toBe("POST");
  161. expect(init?.headers).toMatchObject({
  162. Accept: "application/json",
  163. "Content-Type": "application/x-www-form-urlencoded",
  164. });
  165. expect(String(init?.body)).toContain("client_id=");
  166. expect(String(init?.body)).toContain("scope=read%3Auser");
  167. return jsonResponse({
  168. device_code: "device-code",
  169. user_code: "ABCD-EFGH",
  170. verification_uri: "https://github.com/login/device",
  171. interval: 5,
  172. expires_in: 900,
  173. });
  174. }
  175. if (url.endsWith("/login/oauth/access_token")) {
  176. accessTokenPollTimes.push(Date.now());
  177. expect(init?.method).toBe("POST");
  178. expect(init?.headers).toMatchObject({
  179. Accept: "application/json",
  180. "Content-Type": "application/x-www-form-urlencoded",
  181. });
  182. expect(String(init?.body)).toContain("client_id=");
  183. expect(String(init?.body)).toContain("device_code=device-code");
  184. expect(String(init?.body)).toContain("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code");
  185. const response = accessTokenResponses.shift();
  186. if (!response) {
  187. throw new Error("Unexpected extra access token poll");
  188. }
  189. return response;
  190. }
  191. if (url.includes("/copilot_internal/v2/token")) {
  192. return jsonResponse({
  193. token: "tid=test;exp=9999999999;proxy-ep=proxy.individual.githubcopilot.com;",
  194. expires_at: 9999999999,
  195. });
  196. }
  197. if (url.includes("/models/") && url.endsWith("/policy")) {
  198. return new Response("", { status: 200 });
  199. }
  200. throw new Error(`Unexpected fetch URL: ${url}`);
  201. });
  202. vi.stubGlobal("fetch", fetchMock);
  203. const loginPromise = loginGitHubCopilot({
  204. onDeviceCode: () => {},
  205. onPrompt: async () => "",
  206. onProgress: () => {},
  207. });
  208. await vi.advanceTimersByTimeAsync(0);
  209. expect(accessTokenPollTimes).toHaveLength(1);
  210. await vi.advanceTimersByTimeAsync(4999);
  211. expect(accessTokenPollTimes).toHaveLength(1);
  212. await vi.advanceTimersByTimeAsync(1);
  213. expect(accessTokenPollTimes).toHaveLength(2);
  214. await vi.advanceTimersByTimeAsync(9999);
  215. expect(accessTokenPollTimes).toHaveLength(2);
  216. await vi.advanceTimersByTimeAsync(1);
  217. await loginPromise;
  218. expect(accessTokenPollTimes).toEqual([
  219. startTime.getTime(),
  220. startTime.getTime() + 5000,
  221. startTime.getTime() + 15000,
  222. ]);
  223. });
  224. it("times out after repeated slow_down responses", async () => {
  225. vi.useFakeTimers();
  226. const startTime = new Date("2026-03-09T00:00:00Z");
  227. vi.setSystemTime(startTime);
  228. const accessTokenPollTimes: number[] = [];
  229. const accessTokenResponses = [
  230. jsonResponse({ error: "slow_down", error_description: "slow down" }),
  231. jsonResponse({ error: "slow_down", error_description: "still too fast" }),
  232. jsonResponse({ error: "authorization_pending", error_description: "pending" }),
  233. ];
  234. const fetchMock = vi.fn(async (input: unknown): Promise<Response> => {
  235. const url = getUrl(input);
  236. if (url.endsWith("/login/device/code")) {
  237. return jsonResponse({
  238. device_code: "device-code",
  239. user_code: "ABCD-EFGH",
  240. verification_uri: "https://github.com/login/device",
  241. interval: 5,
  242. expires_in: 25,
  243. });
  244. }
  245. if (url.endsWith("/login/oauth/access_token")) {
  246. accessTokenPollTimes.push(Date.now());
  247. const response = accessTokenResponses.shift();
  248. if (!response) {
  249. throw new Error("Unexpected extra access token poll");
  250. }
  251. return response;
  252. }
  253. throw new Error(`Unexpected fetch URL: ${url}`);
  254. });
  255. vi.stubGlobal("fetch", fetchMock);
  256. const loginPromise = loginGitHubCopilot({
  257. onDeviceCode: () => {},
  258. onPrompt: async () => "",
  259. });
  260. const rejection = expect(loginPromise).rejects.toThrow(
  261. /Device flow timed out after one or more slow_down responses/,
  262. );
  263. await vi.advanceTimersByTimeAsync(5000);
  264. expect(accessTokenPollTimes).toEqual([startTime.getTime()]);
  265. await vi.advanceTimersByTimeAsync(5000);
  266. expect(accessTokenPollTimes).toEqual([startTime.getTime(), startTime.getTime() + 10000]);
  267. await vi.advanceTimersByTimeAsync(14999);
  268. expect(accessTokenPollTimes).toEqual([startTime.getTime(), startTime.getTime() + 10000]);
  269. await vi.advanceTimersByTimeAsync(1);
  270. await rejection;
  271. expect(accessTokenPollTimes).toEqual([startTime.getTime(), startTime.getTime() + 10000]);
  272. });
  273. });