The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 2 | import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest"; |
| 3 | import * as Deferred from "effect/Deferred"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as Fiber from "effect/Fiber"; |
| 6 | import * as FileSystem from "effect/FileSystem"; |
| 7 | import * as Layer from "effect/Layer"; |
| 8 | import * as Option from "effect/Option"; |
| 9 | import * as Redacted from "effect/Redacted"; |
| 10 | import { HttpClient, HttpClientResponse } from "effect/http"; |
| 11 | import { ChildProcessSpawner } from "effect/process"; |
| 12 | import * as TestClock from "effect/testing/TestClock"; |
| 13 | |
| 14 | import { DEFAULT_SERVER_SETTINGS, ServerSettingsError } from "@t3tools/contracts"; |
| 15 | import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; |
| 16 | import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; |
| 17 | import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition"; |
| 18 | import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; |
| 19 | import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; |
| 20 | |
| 21 | import * as GitHubClient from "../shared/definition.ts"; |
| 22 | import * as GitHubAppAccess from "./GitHubAppAccess.ts"; |
| 23 | import * as GitHubAppSignIn from "./GitHubAppSignIn.ts"; |
| 24 | import * as GitHubRest from "./GitHubRest.ts"; |
| 25 | |
| 26 | type Reply = { readonly status?: number; readonly body: unknown }; |
| 27 | interface Sent { |
| 28 | readonly host: string; |
| 29 | readonly path: string; |
| 30 | readonly form: URLSearchParams; |
| 31 | /** The bearer token, if any. */ |
| 32 | readonly token: string | undefined; |
| 33 | } |
| 34 | |
| 35 | const HOUR = 3_600_000; |
| 36 | |
| 37 | const session = (overrides: Record<string, unknown> = {}) => |
| 38 | JSON.stringify({ |
| 39 | accessToken: "ghu_current", |
| 40 | accessTokenExpiresAt: 8 * HOUR, |
| 41 | refreshToken: "ghr_current", |
| 42 | refreshTokenExpiresAt: 4_000 * HOUR, |
| 43 | ...overrides, |
| 44 | }); |
| 45 | |
| 46 | /** The whole GitHub request stack over a fake GitHub that `handle` answers. */ |
| 47 | function harness(options: { |
| 48 | readonly handle: (sent: Sent) => Reply; |
| 49 | readonly signIns?: Record<string, string>; |
| 50 | readonly tokens?: Record<string, string>; |
| 51 | /** Without one, the server has no `gh` login to fall back to. */ |
| 52 | readonly ghSignedIn?: boolean; |
| 53 | /** Makes every settings write fail, as a full disk would. */ |
| 54 | readonly settingsWritesFail?: boolean; |
| 55 | /** Holds a request open until it completes, to interleave other work with it. */ |
| 56 | readonly gate?: (sent: Sent) => Effect.Effect<void>; |
| 57 | }) { |
| 58 | const requests: Array<Sent> = []; |
| 59 | const http = HttpClient.make((request) => { |
| 60 | const url = new URL(request.url); |
| 61 | const sent: Sent = { |
| 62 | host: url.host, |
| 63 | path: url.pathname, |
| 64 | form: new URLSearchParams( |
| 65 | request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "", |
| 66 | ), |
| 67 | token: request.headers["authorization"]?.replace(/^Bearer /, ""), |
| 68 | }; |
| 69 | return Effect.suspend(() => options.gate?.(sent) ?? Effect.void).pipe( |
| 70 | Effect.map(() => { |
| 71 | requests.push(sent); |
| 72 | const reply = options.handle(sent); |
| 73 | return HttpClientResponse.fromWeb( |
| 74 | request, |
| 75 | new Response(JSON.stringify(reply.body), { |
| 76 | status: reply.status ?? 200, |
| 77 | headers: { "content-type": "application/json" }, |
| 78 | }), |
| 79 | ); |
| 80 | }), |
| 81 | ); |
| 82 | }); |
| 83 | const run: SourceControlHost.SourceControlHost["Service"]["process"]["run"] = () => |
| 84 | Effect.succeed({ |
| 85 | exitCode: ChildProcessSpawner.ExitCode(0), |
| 86 | stdout: options.ghSignedIn === false ? "" : "gh-token\n", |
| 87 | stderr: "", |
| 88 | stdoutTruncated: false, |
| 89 | stderrTruncated: false, |
| 90 | }); |
| 91 | const host = TestSourceControlHost.layer({ |
| 92 | settings: applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { |
| 93 | sourceControlHosts: { |
| 94 | github: { signIns: options.signIns ?? {}, tokens: options.tokens ?? {} }, |
| 95 | }, |
| 96 | }), |
| 97 | process: { run }, |
| 98 | }); |
| 99 | const failingWrites = Layer.effect( |
| 100 | SourceControlHost.SourceControlHost, |
| 101 | Effect.map(Effect.service(SourceControlHost.SourceControlHost), (service) => ({ |
| 102 | ...service, |
| 103 | settings: { |
| 104 | ...service.settings, |
| 105 | update: () => |
| 106 | Effect.fail( |
| 107 | new ServerSettingsError({ settingsPath: "settings.json", operation: "write-file" }), |
| 108 | ), |
| 109 | }, |
| 110 | })), |
| 111 | ).pipe(Layer.provideMerge(host)); |
| 112 | const layer = GitHubAppAccess.layer.pipe( |
| 113 | Layer.provideMerge(GitHubRest.layerWithDependencies), |
| 114 | Layer.provideMerge(SourceControlRateLimit.layer), |
| 115 | Layer.provideMerge(options.settingsWritesFail === true ? failingWrites : host), |
| 116 | Layer.provide(NodeCrypto.layer), |
| 117 | Layer.provide(FileSystem.layerNoop({})), |
| 118 | Layer.provide(Layer.succeed(HttpClient.HttpClient, http)), |
| 119 | ); |
| 120 | return { layer, requests }; |
| 121 | } |
| 122 | |
| 123 | const savedSignIns = Effect.gen(function* () { |
| 124 | const host = yield* SourceControlHost.SourceControlHost; |
| 125 | const settings = yield* host.settings.get; |
| 126 | return readSourceControlHostSettings(GitHubClient.settings, settings.sourceControlHosts.github) |
| 127 | .signIns; |
| 128 | }); |
| 129 | |
| 130 | /** A REST read through the request policy, answering with the token it went out with. */ |
| 131 | const readUser = Effect.gen(function* () { |
| 132 | const api = yield* GitHubRest.GitHubRest; |
| 133 | return yield* api.rest({ host: "github.com", operation: "test", path: "user" }); |
| 134 | }); |
| 135 | |
| 136 | const deviceCode = { |
| 137 | device_code: "device-1", |
| 138 | user_code: "ABCD-1234", |
| 139 | verification_uri: "https://github.com/login/device", |
| 140 | expires_in: 900, |
| 141 | interval: 5, |
| 142 | }; |
| 143 | |
| 144 | const installedOn = (sent: Sent): Reply => |
| 145 | sent.path === "/user/installations" |
| 146 | ? { |
| 147 | body: { |
| 148 | installations: [ |
| 149 | { id: 1, repository_selection: "all", account: { login: "pingdotgg" } }, |
| 150 | { id: 2, repository_selection: "selected", account: { login: "acme" } }, |
| 151 | ], |
| 152 | }, |
| 153 | } |
| 154 | : sent.path === "/user/installations/2/repositories" |
| 155 | ? { body: { repositories: [{ full_name: "acme/one" }] } } |
| 156 | : { status: 404, body: {} }; |
| 157 | |
| 158 | beforeEach(() => { |
| 159 | for (const name of ["GH_TOKEN", "GITHUB_TOKEN"]) vi.stubEnv(name, ""); |
| 160 | vi.stubEnv(GitHubAppSignIn.CLIENT_ID_VARIABLE, "Iv-test-client"); |
| 161 | }); |
| 162 | afterEach(() => { |
| 163 | vi.unstubAllEnvs(); |
| 164 | }); |
| 165 | |
| 166 | describe("GitHubAppSignIn", () => { |
| 167 | it.effect("finishes a device-flow sign-in and saves the session", () => { |
| 168 | const answers = [ |
| 169 | { error: "authorization_pending" }, |
| 170 | { error: "slow_down", interval: 10 }, |
| 171 | { |
| 172 | access_token: "ghu_new", |
| 173 | expires_in: 28_800, |
| 174 | refresh_token: "ghr_new", |
| 175 | refresh_token_expires_in: 15_897_600, |
| 176 | }, |
| 177 | ]; |
| 178 | const { layer, requests } = harness({ |
| 179 | handle: (sent) => |
| 180 | sent.path === "/login/device/code" ? { body: deviceCode } : { body: answers.shift() }, |
| 181 | }); |
| 182 | return Effect.gen(function* () { |
| 183 | const signIn = yield* GitHubAppSignIn.GitHubAppSignIn; |
| 184 | expect(yield* signIn.start("github.com")).toEqual({ |
| 185 | userCode: "ABCD-1234", |
| 186 | verificationUri: "https://github.com/login/device", |
| 187 | expiresAt: 900_000, |
| 188 | }); |
| 189 | const waiting = yield* Effect.forkChild(signIn.wait("github.com")); |
| 190 | yield* TestClock.adjust("20 seconds"); |
| 191 | yield* Fiber.join(waiting); |
| 192 | |
| 193 | // `slow_down` stretches the interval: polls at 5s, 10s, then 20s. |
| 194 | const polls = requests.filter((sent) => sent.path === "/login/oauth/access_token"); |
| 195 | expect(polls).toHaveLength(3); |
| 196 | expect(polls[0]?.form.get("client_id")).toBe("Iv-test-client"); |
| 197 | expect(polls[0]?.form.get("device_code")).toBe("device-1"); |
| 198 | expect(JSON.parse((yield* savedSignIns)["github.com"] ?? "")).toEqual({ |
| 199 | accessToken: "ghu_new", |
| 200 | accessTokenExpiresAt: 20_000 + 28_800_000, |
| 201 | refreshToken: "ghr_new", |
| 202 | refreshTokenExpiresAt: 20_000 + 15_897_600_000, |
| 203 | }); |
| 204 | }).pipe(Effect.provide(layer)); |
| 205 | }); |
| 206 | |
| 207 | it.effect("reports a sign-in cancelled on GitHub and saves nothing", () => { |
| 208 | const { layer } = harness({ |
| 209 | handle: (sent) => |
| 210 | sent.path === "/login/device/code" |
| 211 | ? { body: deviceCode } |
| 212 | : { body: { error: "access_denied" } }, |
| 213 | }); |
| 214 | return Effect.gen(function* () { |
| 215 | const signIn = yield* GitHubAppSignIn.GitHubAppSignIn; |
| 216 | yield* signIn.start("github.com"); |
| 217 | const waiting = yield* Effect.forkChild(Effect.flip(signIn.wait("github.com"))); |
| 218 | yield* TestClock.adjust("5 seconds"); |
| 219 | expect((yield* Fiber.join(waiting)).reason).toBe("denied"); |
| 220 | expect(yield* savedSignIns).toEqual({}); |
| 221 | }).pipe(Effect.provide(layer)); |
| 222 | }); |
| 223 | |
| 224 | it.effect("expires a code nobody entered", () => { |
| 225 | const { layer } = harness({ |
| 226 | handle: (sent) => |
| 227 | sent.path === "/login/device/code" |
| 228 | ? { body: { ...deviceCode, expires_in: 12 } } |
| 229 | : { body: { error: "authorization_pending" } }, |
| 230 | }); |
| 231 | return Effect.gen(function* () { |
| 232 | const signIn = yield* GitHubAppSignIn.GitHubAppSignIn; |
| 233 | yield* signIn.start("github.com"); |
| 234 | const waiting = yield* Effect.forkChild(Effect.flip(signIn.wait("github.com"))); |
| 235 | yield* TestClock.adjust("15 seconds"); |
| 236 | expect((yield* Fiber.join(waiting)).reason).toBe("expired"); |
| 237 | }).pipe(Effect.provide(layer)); |
| 238 | }); |
| 239 | |
| 240 | it.effect("cancels a sign-in so approving the code afterwards saves nothing", () => { |
| 241 | const { layer, requests } = harness({ |
| 242 | handle: (sent) => |
| 243 | sent.path === "/login/device/code" |
| 244 | ? { body: deviceCode } |
| 245 | : { body: { access_token: "ghu_new", expires_in: 28_800 } }, |
| 246 | }); |
| 247 | return Effect.gen(function* () { |
| 248 | const signIn = yield* GitHubAppSignIn.GitHubAppSignIn; |
| 249 | yield* signIn.start("github.com"); |
| 250 | const waiting = yield* Effect.forkChild(Effect.flip(signIn.wait("github.com"))); |
| 251 | yield* signIn.cancel("github.com"); |
| 252 | yield* TestClock.adjust("10 seconds"); |
| 253 | expect((yield* Fiber.join(waiting)).reason).toBe("cancelled"); |
| 254 | expect(requests.map((sent) => sent.path)).toEqual(["/login/device/code"]); |
| 255 | expect(yield* savedSignIns).toEqual({}); |
| 256 | }).pipe(Effect.provide(layer)); |
| 257 | }); |
| 258 | |
| 259 | it.effect("refuses hosts the app is not registered on", () => { |
| 260 | const { layer, requests } = harness({ handle: () => ({ body: {} }) }); |
| 261 | return Effect.gen(function* () { |
| 262 | const signIn = yield* GitHubAppSignIn.GitHubAppSignIn; |
| 263 | expect((yield* Effect.flip(signIn.start("ghe.acme.test"))).reason).toBe("unsupported"); |
| 264 | expect((yield* Effect.flip(signIn.wait("github.com"))).reason).toBe("not-started"); |
| 265 | expect(requests).toEqual([]); |
| 266 | }).pipe(Effect.provide(layer)); |
| 267 | }); |
| 268 | |
| 269 | it.effect("does nothing with the app when the server has no client ID", () => { |
| 270 | vi.stubEnv(GitHubAppSignIn.CLIENT_ID_VARIABLE, ""); |
| 271 | const { layer, requests } = harness({ |
| 272 | signIns: { "github.com": session() }, |
| 273 | handle: () => ({ body: { login: "octocat" } }), |
| 274 | }); |
| 275 | return Effect.gen(function* () { |
| 276 | const signIn = yield* GitHubAppSignIn.GitHubAppSignIn; |
| 277 | expect(signIn.enabled).toBe(false); |
| 278 | expect((yield* Effect.flip(signIn.start("github.com"))).reason).toBe("unsupported"); |
| 279 | expect(yield* (yield* GitHubAppAccess.GitHubAppAccess).reach("github.com", "acme/one")).toBe( |
| 280 | "signed-out", |
| 281 | ); |
| 282 | // A session saved while it was on stays put but is not used. |
| 283 | yield* readUser; |
| 284 | expect(requests.map((sent) => sent.token)).toEqual(["gh-token"]); |
| 285 | expect(Object.keys(yield* savedSignIns)).toEqual(["github.com"]); |
| 286 | }).pipe(Effect.provide(layer)); |
| 287 | }); |
| 288 | |
| 289 | describe("refresh", () => { |
| 290 | const refreshed = { |
| 291 | access_token: "ghu_refreshed", |
| 292 | expires_in: 28_800, |
| 293 | refresh_token: "ghr_refreshed", |
| 294 | refresh_token_expires_in: 15_897_600, |
| 295 | }; |
| 296 | |
| 297 | it.effect("refreshes an expiring token once for concurrent requests", () => { |
| 298 | const { layer, requests } = harness({ |
| 299 | signIns: { "github.com": session({ accessTokenExpiresAt: 3 * 60_000 }) }, |
| 300 | handle: () => ({ body: refreshed }), |
| 301 | }); |
| 302 | return Effect.gen(function* () { |
| 303 | const signIn = yield* GitHubAppSignIn.GitHubAppSignIn; |
| 304 | const tokens = yield* Effect.all([signIn.token("github.com"), signIn.token("github.com")], { |
| 305 | concurrency: "unbounded", |
| 306 | }); |
| 307 | expect(tokens).toEqual([Option.some("ghu_refreshed"), Option.some("ghu_refreshed")]); |
| 308 | expect(requests).toHaveLength(1); |
| 309 | expect(requests[0]?.form.get("grant_type")).toBe("refresh_token"); |
| 310 | expect(requests[0]?.form.get("refresh_token")).toBe("ghr_current"); |
| 311 | }).pipe(Effect.provide(layer)); |
| 312 | }); |
| 313 | |
| 314 | it.effect("refreshes a token GitHub refused, and only that one", () => { |
| 315 | const { layer, requests } = harness({ |
| 316 | signIns: { "github.com": session() }, |
| 317 | handle: () => ({ body: refreshed }), |
| 318 | }); |
| 319 | return Effect.gen(function* () { |
| 320 | const signIn = yield* GitHubAppSignIn.GitHubAppSignIn; |
| 321 | yield* signIn.invalidate("github.com", "gh-token"); |
| 322 | expect(yield* signIn.token("github.com")).toEqual(Option.some("ghu_current")); |
| 323 | yield* signIn.invalidate("github.com", "ghu_current"); |
| 324 | expect(yield* signIn.token("github.com")).toEqual(Option.some("ghu_refreshed")); |
| 325 | expect(requests).toHaveLength(1); |
| 326 | }).pipe(Effect.provide(layer)); |
| 327 | }); |
| 328 | |
| 329 | it.effect("signs out when GitHub refuses the refresh token", () => { |
| 330 | const { layer } = harness({ |
| 331 | signIns: { "github.com": session({ accessTokenExpiresAt: 0 }) }, |
| 332 | handle: () => ({ body: { error: "bad_refresh_token" } }), |
| 333 | }); |
| 334 | return Effect.gen(function* () { |
| 335 | const signIn = yield* GitHubAppSignIn.GitHubAppSignIn; |
| 336 | expect(yield* signIn.token("github.com")).toEqual(Option.none()); |
| 337 | expect(yield* savedSignIns).toEqual({}); |
| 338 | }).pipe(Effect.provide(layer)); |
| 339 | }); |
| 340 | |
| 341 | it.effect("keeps the session when a refresh fails for another reason", () => { |
| 342 | const { layer } = harness({ |
| 343 | signIns: { "github.com": session({ accessTokenExpiresAt: 0 }) }, |
| 344 | handle: () => ({ body: { error: "unauthorized_client" } }), |
| 345 | }); |
| 346 | return Effect.gen(function* () { |
| 347 | const signIn = yield* GitHubAppSignIn.GitHubAppSignIn; |
| 348 | expect((yield* Effect.flip(signIn.token("github.com")))._tag).toBe("GitHubAppSessionError"); |
| 349 | expect(Object.keys(yield* savedSignIns)).toEqual(["github.com"]); |
| 350 | }).pipe(Effect.provide(layer)); |
| 351 | }); |
| 352 | |
| 353 | it.effect("does not ask GitHub again after it rejects the client's credentials", () => { |
| 354 | const { layer, requests } = harness({ |
| 355 | signIns: { "github.com": session({ accessTokenExpiresAt: 0 }) }, |
| 356 | handle: () => ({ body: { error: "incorrect_client_credentials" } }), |
| 357 | }); |
| 358 | return Effect.gen(function* () { |
| 359 | const signIn = yield* GitHubAppSignIn.GitHubAppSignIn; |
| 360 | yield* Effect.exit(signIn.token("github.com")); |
| 361 | yield* Effect.exit(signIn.token("github.com")); |
| 362 | expect(requests).toHaveLength(1); |
| 363 | expect(yield* savedSignIns).toEqual({}); |
| 364 | }).pipe(Effect.provide(layer)); |
| 365 | }); |
| 366 | |
| 367 | it.effect("serves the still-valid token when a refresh ahead of expiry fails", () => { |
| 368 | const { layer } = harness({ |
| 369 | signIns: { "github.com": session({ accessTokenExpiresAt: 3 * 60_000 }) }, |
| 370 | handle: () => ({ status: 502, body: {} }), |
| 371 | }); |
| 372 | return Effect.gen(function* () { |
| 373 | const signIn = yield* GitHubAppSignIn.GitHubAppSignIn; |
| 374 | expect(yield* signIn.token("github.com")).toEqual(Option.some("ghu_current")); |
| 375 | }).pipe(Effect.provide(layer)); |
| 376 | }); |
| 377 | |
| 378 | it.effect("serves a refreshed token GitHub issued even when saving it fails", () => { |
| 379 | const { layer } = harness({ |
| 380 | signIns: { "github.com": session({ accessTokenExpiresAt: 3 * 60_000 }) }, |
| 381 | settingsWritesFail: true, |
| 382 | handle: () => ({ body: refreshed }), |
| 383 | }); |
| 384 | return Effect.gen(function* () { |
| 385 | const signIn = yield* GitHubAppSignIn.GitHubAppSignIn; |
| 386 | const pending = yield* Effect.forkChild(signIn.token("github.com")); |
| 387 | yield* TestClock.adjust("1 second"); |
| 388 | expect(yield* Fiber.join(pending)).toEqual(Option.some("ghu_refreshed")); |
| 389 | }).pipe(Effect.provide(layer)); |
| 390 | }); |
| 391 | |
| 392 | it.effect("does not bring a session back that was signed out while it refreshed", () => { |
| 393 | const released = Deferred.makeUnsafe<void>(); |
| 394 | const requested = Deferred.makeUnsafe<void>(); |
| 395 | const { layer } = harness({ |
| 396 | signIns: { "github.com": session({ accessTokenExpiresAt: 0 }) }, |
| 397 | gate: () => |
| 398 | Deferred.succeed(requested, undefined).pipe(Effect.andThen(Deferred.await(released))), |
| 399 | handle: () => ({ body: refreshed }), |
| 400 | }); |
| 401 | return Effect.gen(function* () { |
| 402 | const signIn = yield* GitHubAppSignIn.GitHubAppSignIn; |
| 403 | const settings = yield* TestSourceControlHost.TestSourceControlHostSettings; |
| 404 | const refreshing = yield* Effect.forkChild(signIn.token("github.com")); |
| 405 | yield* Deferred.await(requested); |
| 406 | yield* settings.update({ sourceControlHosts: { github: { signIns: {} } } }); |
| 407 | yield* Deferred.succeed(released, undefined); |
| 408 | expect(yield* Fiber.join(refreshing)).toEqual(Option.none()); |
| 409 | expect(yield* savedSignIns).toEqual({}); |
| 410 | }).pipe(Effect.provide(layer)); |
| 411 | }); |
| 412 | }); |
| 413 | }); |
| 414 | |
| 415 | describe("GitHub requests with the app sign-in", () => { |
| 416 | const answerUser = (sent: Sent): Reply => ({ body: { login: sent.token ?? "anonymous" } }); |
| 417 | |
| 418 | it.effect("uses the app before GH_TOKEN and gh, and a saved token before the app", () => { |
| 419 | vi.stubEnv("GH_TOKEN", "from-env"); |
| 420 | const signedIn = harness({ signIns: { "github.com": session() }, handle: answerUser }); |
| 421 | const withToken = harness({ |
| 422 | signIns: { "github.com": session() }, |
| 423 | tokens: { "github.com": "saved-pat" }, |
| 424 | handle: answerUser, |
| 425 | }); |
| 426 | return Effect.gen(function* () { |
| 427 | yield* readUser.pipe(Effect.provide(signedIn.layer)); |
| 428 | yield* readUser.pipe(Effect.provide(withToken.layer)); |
| 429 | expect(signedIn.requests.map((sent) => sent.token)).toEqual(["ghu_current"]); |
| 430 | expect(withToken.requests.map((sent) => sent.token)).toEqual(["saved-pat"]); |
| 431 | }); |
| 432 | }); |
| 433 | |
| 434 | it.effect("asks again with the user's own credential when the app gets not found", () => { |
| 435 | const { layer, requests } = harness({ |
| 436 | signIns: { "github.com": session() }, |
| 437 | handle: (sent) => |
| 438 | sent.token === "ghu_current" ? { status: 404, body: {} } : answerUser(sent), |
| 439 | }); |
| 440 | return Effect.gen(function* () { |
| 441 | const response = yield* readUser; |
| 442 | expect(JSON.parse(response.body)).toEqual({ login: "gh-token" }); |
| 443 | expect(requests.map((sent) => sent.token)).toEqual(["ghu_current", "gh-token"]); |
| 444 | }).pipe(Effect.provide(layer)); |
| 445 | }); |
| 446 | |
| 447 | it.effect("asks again when GitHub says the resource is not accessible by integration", () => { |
| 448 | const { layer, requests } = harness({ |
| 449 | signIns: { "github.com": session() }, |
| 450 | handle: (sent) => |
| 451 | sent.token === "ghu_current" |
| 452 | ? { status: 403, body: { message: "Resource not accessible by integration" } } |
| 453 | : answerUser(sent), |
| 454 | }); |
| 455 | return Effect.gen(function* () { |
| 456 | yield* readUser; |
| 457 | expect(requests.map((sent) => sent.token)).toEqual(["ghu_current", "gh-token"]); |
| 458 | }).pipe(Effect.provide(layer)); |
| 459 | }); |
| 460 | |
| 461 | it.effect("keeps the app's answer when there is no other credential", () => { |
| 462 | const { layer, requests } = harness({ |
| 463 | signIns: { "github.com": session() }, |
| 464 | ghSignedIn: false, |
| 465 | handle: () => ({ status: 404, body: {} }), |
| 466 | }); |
| 467 | return Effect.gen(function* () { |
| 468 | expect((yield* Effect.flip(readUser))._tag).toBe("GitHubApiNotFoundError"); |
| 469 | expect(requests.map((sent) => sent.token)).toEqual(["ghu_current"]); |
| 470 | }).pipe(Effect.provide(layer)); |
| 471 | }); |
| 472 | |
| 473 | it.effect("does not ask again after the user's own credential is refused", () => { |
| 474 | const { layer, requests } = harness({ handle: () => ({ status: 404, body: {} }) }); |
| 475 | return Effect.gen(function* () { |
| 476 | expect((yield* Effect.flip(readUser))._tag).toBe("GitHubApiNotFoundError"); |
| 477 | expect(requests.map((sent) => sent.token)).toEqual(["gh-token"]); |
| 478 | }).pipe(Effect.provide(layer)); |
| 479 | }); |
| 480 | |
| 481 | it.effect("uses the gh login while the app session cannot refresh, and keeps the session", () => { |
| 482 | const { layer, requests } = harness({ |
| 483 | signIns: { "github.com": session({ accessTokenExpiresAt: 0 }) }, |
| 484 | handle: (sent) => (sent.host === "github.com" ? { status: 502, body: {} } : answerUser(sent)), |
| 485 | }); |
| 486 | return Effect.gen(function* () { |
| 487 | yield* readUser; |
| 488 | expect(requests.filter((sent) => sent.path === "/user").map((sent) => sent.token)).toEqual([ |
| 489 | "gh-token", |
| 490 | ]); |
| 491 | expect(Object.keys(yield* savedSignIns)).toEqual(["github.com"]); |
| 492 | }).pipe(Effect.provide(layer)); |
| 493 | }); |
| 494 | |
| 495 | it.effect("refreshes the app token after GitHub rejects it", () => { |
| 496 | let rejected = false; |
| 497 | const { layer, requests } = harness({ |
| 498 | signIns: { "github.com": session() }, |
| 499 | handle: (sent) => { |
| 500 | if (sent.path === "/login/oauth/access_token") { |
| 501 | return { body: { access_token: "ghu_refreshed", expires_in: 28_800 } }; |
| 502 | } |
| 503 | if (sent.token === "ghu_current" && !rejected) { |
| 504 | rejected = true; |
| 505 | return { status: 401, body: {} }; |
| 506 | } |
| 507 | return answerUser(sent); |
| 508 | }, |
| 509 | }); |
| 510 | return Effect.gen(function* () { |
| 511 | expect((yield* Effect.flip(readUser))._tag).toBe("GitHubApiAuthenticationError"); |
| 512 | yield* readUser; |
| 513 | expect(requests.map((sent) => sent.token ?? sent.path)).toEqual([ |
| 514 | "ghu_current", |
| 515 | "/login/oauth/access_token", |
| 516 | "ghu_refreshed", |
| 517 | ]); |
| 518 | }).pipe(Effect.provide(layer)); |
| 519 | }); |
| 520 | }); |
| 521 | |
| 522 | describe("GitHubAppAccess", () => { |
| 523 | it.effect("reads the installations as the app, even with a saved token", () => { |
| 524 | const { layer, requests } = harness({ |
| 525 | signIns: { "github.com": session() }, |
| 526 | tokens: { "github.com": "saved-pat" }, |
| 527 | handle: installedOn, |
| 528 | }); |
| 529 | return Effect.gen(function* () { |
| 530 | const access = yield* GitHubAppAccess.GitHubAppAccess; |
| 531 | expect(yield* access.reach("github.com", "pingdotgg/t3code")).toBe("covered"); |
| 532 | expect(yield* access.reach("github.com", "acme/one")).toBe("covered"); |
| 533 | expect(yield* access.reach("github.com", "acme/two")).toBe("not-covered"); |
| 534 | expect(yield* access.reach("github.com", "https://github.com/Acme/One.git")).toBe("covered"); |
| 535 | expect(new Set(requests.map((sent) => sent.token))).toEqual(new Set(["ghu_current"])); |
| 536 | // One read of the installations serves every repository until it goes stale. |
| 537 | expect(requests.filter((sent) => sent.path === "/user/installations")).toHaveLength(1); |
| 538 | }).pipe(Effect.provide(layer)); |
| 539 | }); |
| 540 | |
| 541 | it.effect("answers signed out without a session, and covered while GitHub fails", () => { |
| 542 | const signedOut = harness({ handle: installedOn }); |
| 543 | const failing = harness({ |
| 544 | signIns: { "github.com": session() }, |
| 545 | handle: () => ({ status: 502, body: {} }), |
| 546 | }); |
| 547 | return Effect.gen(function* () { |
| 548 | expect( |
| 549 | yield* Effect.flatMap(Effect.service(GitHubAppAccess.GitHubAppAccess), (access) => |
| 550 | access.reach("github.com", "acme/one"), |
| 551 | ).pipe(Effect.provide(signedOut.layer)), |
| 552 | ).toBe("signed-out"); |
| 553 | const answers = yield* Effect.gen(function* () { |
| 554 | const access = yield* GitHubAppAccess.GitHubAppAccess; |
| 555 | return [ |
| 556 | yield* access.reach("github.com", "acme/one"), |
| 557 | yield* access.reach("github.com", "acme/two"), |
| 558 | ]; |
| 559 | }).pipe(Effect.provide(failing.layer)); |
| 560 | expect(answers).toEqual(["covered", "covered"]); |
| 561 | // A failed read is kept briefly instead of asked again per request. |
| 562 | expect(failing.requests).toHaveLength(1); |
| 563 | }); |
| 564 | }); |
| 565 | |
| 566 | it.effect("gives work on a repository the app cannot reach the user's credential", () => { |
| 567 | const { layer } = harness({ signIns: { "github.com": session() }, handle: installedOn }); |
| 568 | return Effect.gen(function* () { |
| 569 | const access = yield* GitHubAppAccess.GitHubAppAccess; |
| 570 | const tokenFor = (repository: string) => |
| 571 | access |
| 572 | .credentialFor("github.com", repository) |
| 573 | .pipe(Effect.map((held) => Redacted.value(held.token))); |
| 574 | expect(yield* tokenFor("pingdotgg/t3code")).toBe("ghu_current"); |
| 575 | expect(yield* tokenFor("someone/else")).toBe("gh-token"); |
| 576 | }).pipe(Effect.provide(layer)); |
| 577 | }); |
| 578 | |
| 579 | it.effect("pins the user's credential while the app's reach is unknown", () => { |
| 580 | const failing = (sent: Sent): Reply => |
| 581 | sent.path.startsWith("/user/installations") ? { status: 502, body: {} } : { body: {} }; |
| 582 | const withGh = harness({ signIns: { "github.com": session() }, handle: failing }); |
| 583 | const appOnly = harness({ |
| 584 | signIns: { "github.com": session() }, |
| 585 | ghSignedIn: false, |
| 586 | handle: failing, |
| 587 | }); |
| 588 | const tokenFor = Effect.flatMap(Effect.service(GitHubAppAccess.GitHubAppAccess), (access) => |
| 589 | access |
| 590 | .credentialFor("github.com", "pingdotgg/t3code") |
| 591 | .pipe(Effect.map((held) => Redacted.value(held.token))), |
| 592 | ); |
| 593 | return Effect.gen(function* () { |
| 594 | expect(yield* tokenFor.pipe(Effect.provide(withGh.layer))).toBe("gh-token"); |
| 595 | expect(yield* tokenFor.pipe(Effect.provide(appOnly.layer))).toBe("ghu_current"); |
| 596 | }); |
| 597 | }); |
| 598 | |
| 599 | it.effect("names the account the app sign-in acts as", () => { |
| 600 | const { layer } = harness({ |
| 601 | signIns: { "github.com": session() }, |
| 602 | tokens: { "github.com": "saved-pat" }, |
| 603 | handle: (sent) => ({ body: { login: sent.token === "ghu_current" ? "octocat" : "other" } }), |
| 604 | }); |
| 605 | return Effect.gen(function* () { |
| 606 | expect(yield* (yield* GitHubAppAccess.GitHubAppAccess).viewer("github.com")).toBe("octocat"); |
| 607 | }).pipe(Effect.provide(layer)); |
| 608 | }); |
| 609 | }); |