The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { |
| 2 | SourceControlProviderKind, |
| 3 | SourceControlSignInError, |
| 4 | type SourceControlSignInFailure, |
| 5 | type SourceControlSignInPrompt, |
| 6 | } from "@t3tools/contracts"; |
| 7 | import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; |
| 8 | import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition"; |
| 9 | import * as Clock from "effect/Clock"; |
| 10 | import * as Context from "effect/Context"; |
| 11 | import * as Deferred from "effect/Deferred"; |
| 12 | import * as Duration from "effect/Duration"; |
| 13 | import * as Effect from "effect/Effect"; |
| 14 | import * as Fiber from "effect/Fiber"; |
| 15 | import * as Layer from "effect/Layer"; |
| 16 | import * as Option from "effect/Option"; |
| 17 | import * as Ref from "effect/Ref"; |
| 18 | import * as Schema from "effect/Schema"; |
| 19 | import * as Schedule from "effect/Schedule"; |
| 20 | import * as Semaphore from "effect/Semaphore"; |
| 21 | import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; |
| 22 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 23 | |
| 24 | import * as GitHubClient from "../shared/definition.ts"; |
| 25 | |
| 26 | /** |
| 27 | * The public client ID of the T3 Code for GitHub app, which the device flow needs (no secret). |
| 28 | * Unset turns the app sign-in off: no app tokens, no sign-in, nothing for clients to show. |
| 29 | */ |
| 30 | export const CLIENT_ID_VARIABLE = "T3CODE_GITHUB_APP_CLIENT_ID"; |
| 31 | |
| 32 | const KIND = SourceControlProviderKind.make("github"); |
| 33 | const REQUEST_TIMEOUT = Duration.seconds(15); |
| 34 | // Refresh ahead of expiry so a token never lapses between the check and a long request. |
| 35 | const REFRESH_MARGIN_MS = Duration.toMillis(Duration.minutes(5)); |
| 36 | |
| 37 | const GitHubAppSession = Schema.Struct({ |
| 38 | accessToken: Schema.String, |
| 39 | /** Null when the app hands out tokens that do not expire. */ |
| 40 | accessTokenExpiresAt: Schema.NullOr(Schema.Number), |
| 41 | refreshToken: Schema.NullOr(Schema.String), |
| 42 | refreshTokenExpiresAt: Schema.NullOr(Schema.Number), |
| 43 | }); |
| 44 | type GitHubAppSession = typeof GitHubAppSession.Type; |
| 45 | |
| 46 | const GitHubAppSessionJson = Schema.fromJsonString(GitHubAppSession); |
| 47 | const decodeSession = Schema.decodeUnknownOption(GitHubAppSessionJson); |
| 48 | const encodeSession = Schema.encodeSync(GitHubAppSessionJson); |
| 49 | |
| 50 | // GitHub answers both token grants with HTTP 200 and puts refusals in `error`. |
| 51 | const TokenResponse = Schema.Struct({ |
| 52 | access_token: Schema.optional(Schema.String), |
| 53 | expires_in: Schema.optional(Schema.Number), |
| 54 | refresh_token: Schema.optional(Schema.String), |
| 55 | refresh_token_expires_in: Schema.optional(Schema.Number), |
| 56 | interval: Schema.optional(Schema.Number), |
| 57 | error: Schema.optional(Schema.String), |
| 58 | error_description: Schema.optional(Schema.String), |
| 59 | }); |
| 60 | |
| 61 | const DeviceCodeResponse = Schema.Struct({ |
| 62 | device_code: Schema.optional(Schema.String), |
| 63 | user_code: Schema.optional(Schema.String), |
| 64 | verification_uri: Schema.optional(Schema.String), |
| 65 | expires_in: Schema.optional(Schema.Number), |
| 66 | interval: Schema.optional(Schema.Number), |
| 67 | error: Schema.optional(Schema.String), |
| 68 | error_description: Schema.optional(Schema.String), |
| 69 | }); |
| 70 | |
| 71 | export class GitHubAppSessionError extends Schema.TaggedError<GitHubAppSessionError>()( |
| 72 | "GitHubAppSessionError", |
| 73 | { host: Schema.String, cause: Schema.Defect() }, |
| 74 | ) { |
| 75 | override get message(): string { |
| 76 | return `Could not refresh the ${GitHubClient.APP_SIGN_IN.appName} sign-in for ${this.host}. Check the server's connection to GitHub, or sign in again in Settings → Source control & issues.`; |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | export class GitHubAppSignIn extends Context.Service< |
| 81 | GitHubAppSignIn, |
| 82 | { |
| 83 | /** Whether the server is configured with the app's client ID. */ |
| 84 | readonly enabled: boolean; |
| 85 | /** The signed-in access token for `host`, refreshed when due; none when not signed in. */ |
| 86 | readonly token: (host: string) => Effect.Effect<Option.Option<string>, GitHubAppSessionError>; |
| 87 | /** Refreshes on the next `token` when `rejected` is the token GitHub just refused. */ |
| 88 | readonly invalidate: (host: string, rejected: string) => Effect.Effect<void>; |
| 89 | readonly start: ( |
| 90 | host: string, |
| 91 | ) => Effect.Effect<SourceControlSignInPrompt, SourceControlSignInError>; |
| 92 | /** Resolves once the sign-in `start` began has saved a session. */ |
| 93 | readonly wait: (host: string) => Effect.Effect<void, SourceControlSignInError>; |
| 94 | readonly cancel: (host: string) => Effect.Effect<void>; |
| 95 | } |
| 96 | >()("@t3tools/source-control-github/server/GitHubAppSignIn") {} |
| 97 | |
| 98 | interface PendingSignIn { |
| 99 | readonly deferred: Deferred.Deferred<void, SourceControlSignInError>; |
| 100 | readonly fiber: Fiber.Fiber<boolean>; |
| 101 | } |
| 102 | |
| 103 | const signInError = (host: string, reason: SourceControlSignInFailure, detail: string) => |
| 104 | new SourceControlSignInError({ provider: KIND, host, reason, detail }); |
| 105 | |
| 106 | /** @public */ |
| 107 | export const make = Effect.gen(function* () { |
| 108 | const sourceControlHost = yield* SourceControlHost.SourceControlHost; |
| 109 | const httpClient = yield* HttpClient.HttpClient; |
| 110 | const clientId = (yield* HostProcess.Environment)[CLIENT_ID_VARIABLE]?.trim() ?? ""; |
| 111 | const enabled = clientId !== ""; |
| 112 | const scope = yield* Effect.scope; |
| 113 | const refreshLock = yield* Semaphore.make(1); |
| 114 | const refused = yield* Ref.make<ReadonlySet<string>>(new Set()); |
| 115 | const pending = yield* Ref.make<ReadonlyMap<string, PendingSignIn>>(new Map()); |
| 116 | |
| 117 | const isAppHost = (host: string) => |
| 118 | enabled && GitHubClient.APP_SIGN_IN.hosts.includes(host.trim().toLowerCase()); |
| 119 | |
| 120 | const readSignIns = sourceControlHost.settings.get.pipe( |
| 121 | Effect.map( |
| 122 | (settings) => |
| 123 | readSourceControlHostSettings( |
| 124 | GitHubClient.settings, |
| 125 | settings.sourceControlHosts[GitHubClient.definition.kind], |
| 126 | ).signIns, |
| 127 | ), |
| 128 | Effect.orElseSucceed((): Readonly<Record<string, string>> => ({})), |
| 129 | ); |
| 130 | |
| 131 | const readSession = (host: string) => |
| 132 | readSignIns.pipe(Effect.map((signIns) => decodeSession(signIns[host] ?? ""))); |
| 133 | |
| 134 | const writeSession = Effect.fn("GitHubAppSignIn.writeSession")(function* ( |
| 135 | host: string, |
| 136 | session: GitHubAppSession | null, |
| 137 | ) { |
| 138 | const signIns = { ...(yield* readSignIns) }; |
| 139 | if (session === null) delete signIns[host]; |
| 140 | else signIns[host] = encodeSession(session); |
| 141 | yield* sourceControlHost.settings.update({ |
| 142 | sourceControlHosts: { [GitHubClient.definition.kind]: { signIns } }, |
| 143 | }); |
| 144 | }); |
| 145 | |
| 146 | /** |
| 147 | * Writes `next` only while the stored session is still the one a refresh started from, so a |
| 148 | * sign-out or a newer sign-in during the request is not undone. |
| 149 | */ |
| 150 | const replaceSession = Effect.fn("GitHubAppSignIn.replaceSession")(function* ( |
| 151 | host: string, |
| 152 | from: GitHubAppSession, |
| 153 | next: GitHubAppSession | null, |
| 154 | ) { |
| 155 | const current = yield* readSession(host); |
| 156 | if (Option.isNone(current) || current.value.accessToken !== from.accessToken) return false; |
| 157 | yield* writeSession(host, next); |
| 158 | return true; |
| 159 | }); |
| 160 | |
| 161 | const postForm = <S extends Schema.Top>( |
| 162 | host: string, |
| 163 | path: string, |
| 164 | body: Record<string, string>, |
| 165 | schema: S, |
| 166 | ) => |
| 167 | httpClient |
| 168 | .execute( |
| 169 | HttpClientRequest.post(`https://${host}${path}`).pipe( |
| 170 | HttpClientRequest.setHeaders({ accept: "application/json", "user-agent": "t3code" }), |
| 171 | HttpClientRequest.bodyUrlParams(body), |
| 172 | ), |
| 173 | ) |
| 174 | .pipe( |
| 175 | Effect.flatMap(HttpClientResponse.filterStatusOk), |
| 176 | Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)), |
| 177 | Effect.timeout(REQUEST_TIMEOUT), |
| 178 | ); |
| 179 | |
| 180 | const sessionFrom = ( |
| 181 | now: number, |
| 182 | response: typeof TokenResponse.Type & { readonly access_token: string }, |
| 183 | ): GitHubAppSession => ({ |
| 184 | accessToken: response.access_token, |
| 185 | accessTokenExpiresAt: |
| 186 | response.expires_in === undefined ? null : now + response.expires_in * 1_000, |
| 187 | refreshToken: response.refresh_token ?? null, |
| 188 | refreshTokenExpiresAt: |
| 189 | response.refresh_token_expires_in === undefined |
| 190 | ? null |
| 191 | : now + response.refresh_token_expires_in * 1_000, |
| 192 | }); |
| 193 | |
| 194 | const refresh = Effect.fn("GitHubAppSignIn.refresh")(function* ( |
| 195 | host: string, |
| 196 | session: GitHubAppSession, |
| 197 | ) { |
| 198 | const now = yield* Clock.currentTimeMillis; |
| 199 | if ( |
| 200 | session.refreshToken === null || |
| 201 | (session.refreshTokenExpiresAt !== null && session.refreshTokenExpiresAt <= now) |
| 202 | ) { |
| 203 | yield* replaceSession(host, session, null).pipe(Effect.ignore); |
| 204 | return Option.none<string>(); |
| 205 | } |
| 206 | const response = yield* postForm( |
| 207 | host, |
| 208 | "/login/oauth/access_token", |
| 209 | { |
| 210 | client_id: clientId, |
| 211 | grant_type: "refresh_token", |
| 212 | refresh_token: session.refreshToken, |
| 213 | }, |
| 214 | TokenResponse, |
| 215 | ).pipe(Effect.mapError((cause) => new GitHubAppSessionError({ host, cause }))); |
| 216 | if ( |
| 217 | response.error === "bad_refresh_token" || |
| 218 | response.error === "incorrect_client_credentials" |
| 219 | ) { |
| 220 | // Final: the user revoked the app, the session lapsed, or this server's client cannot refresh it. |
| 221 | yield* Effect.logWarning("GitHub refused the app sign-in refresh; signing out.", { |
| 222 | host, |
| 223 | error: response.error, |
| 224 | }); |
| 225 | yield* replaceSession(host, session, null).pipe(Effect.ignore); |
| 226 | return Option.none<string>(); |
| 227 | } |
| 228 | if (response.access_token === undefined) { |
| 229 | return yield* new GitHubAppSessionError({ |
| 230 | host, |
| 231 | cause: new Error(`GitHub did not refresh the sign-in (${response.error ?? "no token"}).`), |
| 232 | }); |
| 233 | } |
| 234 | const next = sessionFrom(now, { |
| 235 | ...response, |
| 236 | access_token: response.access_token, |
| 237 | }); |
| 238 | // GitHub has retired the old pair, so an unsaved new one is still the only usable token. |
| 239 | const saved = yield* replaceSession(host, session, next).pipe( |
| 240 | Effect.retry({ times: 2, schedule: Schedule.spaced(Duration.millis(250)) }), |
| 241 | Effect.catch((cause) => |
| 242 | Effect.logError("Could not save the refreshed app sign-in; using it unsaved.", { |
| 243 | host, |
| 244 | cause, |
| 245 | }).pipe(Effect.as(true)), |
| 246 | ), |
| 247 | ); |
| 248 | if (saved) return Option.some(next.accessToken); |
| 249 | // Signed out or signed in again meanwhile: serve whatever is stored now. |
| 250 | return Option.map(yield* readSession(host), (current) => current.accessToken); |
| 251 | }); |
| 252 | |
| 253 | const isFresh = (session: GitHubAppSession, now: number) => |
| 254 | session.accessTokenExpiresAt === null || now < session.accessTokenExpiresAt - REFRESH_MARGIN_MS; |
| 255 | |
| 256 | const token: GitHubAppSignIn["Service"]["token"] = Effect.fn("GitHubAppSignIn.token")( |
| 257 | function* (rawHost) { |
| 258 | const host = rawHost.trim().toLowerCase(); |
| 259 | if (!isAppHost(host)) return Option.none(); |
| 260 | const session = yield* readSession(host); |
| 261 | if (Option.isNone(session)) return Option.none(); |
| 262 | const now = yield* Clock.currentTimeMillis; |
| 263 | if ( |
| 264 | isFresh(session.value, now) && |
| 265 | !(yield* Ref.get(refused)).has(session.value.accessToken) |
| 266 | ) { |
| 267 | return Option.some(session.value.accessToken); |
| 268 | } |
| 269 | return yield* refreshLock.withPermits(1)( |
| 270 | Effect.gen(function* () { |
| 271 | // Another request may have refreshed while this one queued. |
| 272 | const current = yield* readSession(host); |
| 273 | if (Option.isNone(current)) return Option.none<string>(); |
| 274 | const refusedTokens = yield* Ref.get(refused); |
| 275 | const now = yield* Clock.currentTimeMillis; |
| 276 | if (isFresh(current.value, now) && !refusedTokens.has(current.value.accessToken)) { |
| 277 | return Option.some(current.value.accessToken); |
| 278 | } |
| 279 | const usable = Option.some(current.value.accessToken).pipe( |
| 280 | Option.filter( |
| 281 | (accessToken) => |
| 282 | !refusedTokens.has(accessToken) && |
| 283 | (current.value.accessTokenExpiresAt === null || |
| 284 | now < current.value.accessTokenExpiresAt), |
| 285 | ), |
| 286 | ); |
| 287 | // A refresh ahead of expiry that fails leaves the still-valid token in use. |
| 288 | return yield* refresh(host, current.value).pipe( |
| 289 | Effect.catchTags({ |
| 290 | GitHubAppSessionError: (error) => |
| 291 | Option.isSome(usable) ? Effect.succeed(usable) : Effect.fail(error), |
| 292 | }), |
| 293 | ); |
| 294 | }), |
| 295 | ); |
| 296 | }, |
| 297 | ); |
| 298 | |
| 299 | const invalidate: GitHubAppSignIn["Service"]["invalidate"] = Effect.fn( |
| 300 | "GitHubAppSignIn.invalidate", |
| 301 | )(function* (rawHost, rejected) { |
| 302 | const session = yield* readSession(rawHost.trim().toLowerCase()); |
| 303 | // A refused fallback token says nothing about the app session. |
| 304 | if (Option.isNone(session) || session.value.accessToken !== rejected) return; |
| 305 | yield* Ref.update(refused, (current) => new Set([...current, rejected])); |
| 306 | }); |
| 307 | |
| 308 | const poll = Effect.fn("GitHubAppSignIn.poll")(function* ( |
| 309 | host: string, |
| 310 | deviceCode: string, |
| 311 | expiresAt: number, |
| 312 | initialInterval: number, |
| 313 | ) { |
| 314 | let interval = initialInterval; |
| 315 | while (true) { |
| 316 | yield* Effect.sleep(Duration.seconds(interval)); |
| 317 | const now = yield* Clock.currentTimeMillis; |
| 318 | if (now >= expiresAt) { |
| 319 | return yield* signInError(host, "expired", "The sign-in code expired. Start again."); |
| 320 | } |
| 321 | const answer = yield* postForm( |
| 322 | host, |
| 323 | "/login/oauth/access_token", |
| 324 | { |
| 325 | client_id: clientId, |
| 326 | device_code: deviceCode, |
| 327 | grant_type: "urn:ietf:params:oauth:grant-type:device_code", |
| 328 | }, |
| 329 | TokenResponse, |
| 330 | ).pipe(Effect.option); |
| 331 | // A dropped poll is retried on the next tick; the code stays valid until it expires. |
| 332 | if (Option.isNone(answer)) continue; |
| 333 | const response = answer.value; |
| 334 | if (response.access_token !== undefined) { |
| 335 | const accessToken = response.access_token; |
| 336 | return yield* writeSession( |
| 337 | host, |
| 338 | sessionFrom(yield* Clock.currentTimeMillis, { ...response, access_token: accessToken }), |
| 339 | ).pipe( |
| 340 | Effect.mapError( |
| 341 | (cause) => |
| 342 | new SourceControlSignInError({ |
| 343 | provider: KIND, |
| 344 | host, |
| 345 | reason: "failed", |
| 346 | detail: "The server could not save the sign-in.", |
| 347 | cause, |
| 348 | }), |
| 349 | ), |
| 350 | ); |
| 351 | } |
| 352 | switch (response.error) { |
| 353 | case "authorization_pending": |
| 354 | continue; |
| 355 | case "slow_down": |
| 356 | interval = response.interval ?? interval + 5; |
| 357 | continue; |
| 358 | case "expired_token": |
| 359 | return yield* signInError(host, "expired", "The sign-in code expired. Start again."); |
| 360 | case "access_denied": |
| 361 | return yield* signInError(host, "denied", "The sign-in was cancelled on GitHub."); |
| 362 | default: |
| 363 | return yield* signInError( |
| 364 | host, |
| 365 | "failed", |
| 366 | response.error_description ?? |
| 367 | `GitHub refused the sign-in (${response.error ?? "no reason given"}).`, |
| 368 | ); |
| 369 | } |
| 370 | } |
| 371 | }); |
| 372 | |
| 373 | const start: GitHubAppSignIn["Service"]["start"] = Effect.fn("GitHubAppSignIn.start")( |
| 374 | function* (rawHost) { |
| 375 | const host = rawHost.trim().toLowerCase(); |
| 376 | if (!enabled) { |
| 377 | return yield* signInError( |
| 378 | host, |
| 379 | "unsupported", |
| 380 | `This server is not set up to sign in with ${GitHubClient.APP_SIGN_IN.appName}.`, |
| 381 | ); |
| 382 | } |
| 383 | if (!isAppHost(host)) { |
| 384 | return yield* signInError( |
| 385 | host, |
| 386 | "unsupported", |
| 387 | `${GitHubClient.APP_SIGN_IN.appName} only signs in to ${GitHubClient.APP_SIGN_IN.hosts.join(", ")}. Use a token or the GitHub CLI for ${host}.`, |
| 388 | ); |
| 389 | } |
| 390 | const code = yield* postForm( |
| 391 | host, |
| 392 | "/login/device/code", |
| 393 | { client_id: clientId }, |
| 394 | DeviceCodeResponse, |
| 395 | ).pipe( |
| 396 | Effect.mapError( |
| 397 | (cause) => |
| 398 | new SourceControlSignInError({ |
| 399 | provider: KIND, |
| 400 | host, |
| 401 | reason: "failed", |
| 402 | detail: "The server could not reach GitHub to start the sign-in.", |
| 403 | cause, |
| 404 | }), |
| 405 | ), |
| 406 | ); |
| 407 | if ( |
| 408 | code.device_code === undefined || |
| 409 | code.user_code === undefined || |
| 410 | code.verification_uri === undefined || |
| 411 | code.expires_in === undefined |
| 412 | ) { |
| 413 | return yield* signInError( |
| 414 | host, |
| 415 | "failed", |
| 416 | code.error_description ?? |
| 417 | `GitHub would not start the sign-in (${code.error ?? "no reason given"}).`, |
| 418 | ); |
| 419 | } |
| 420 | const expiresAt = (yield* Clock.currentTimeMillis) + code.expires_in * 1_000; |
| 421 | const deferred = yield* Deferred.make<void, SourceControlSignInError>(); |
| 422 | const fiber = yield* poll(host, code.device_code, expiresAt, code.interval ?? 5).pipe( |
| 423 | Effect.tap(() => Ref.set(refused, new Set())), |
| 424 | Deferred.into(deferred), |
| 425 | Effect.forkIn(scope), |
| 426 | ); |
| 427 | const previous = yield* Ref.modify(pending, (current) => [ |
| 428 | current.get(host), |
| 429 | new Map(current).set(host, { deferred, fiber }), |
| 430 | ]); |
| 431 | if (previous !== undefined) { |
| 432 | yield* Deferred.fail( |
| 433 | previous.deferred, |
| 434 | signInError(host, "failed", "A newer sign-in replaced this one."), |
| 435 | ); |
| 436 | yield* Fiber.interrupt(previous.fiber); |
| 437 | } |
| 438 | return { |
| 439 | userCode: code.user_code, |
| 440 | verificationUri: code.verification_uri, |
| 441 | expiresAt, |
| 442 | } satisfies SourceControlSignInPrompt; |
| 443 | }, |
| 444 | ); |
| 445 | |
| 446 | const wait: GitHubAppSignIn["Service"]["wait"] = Effect.fn("GitHubAppSignIn.wait")( |
| 447 | function* (rawHost) { |
| 448 | const host = rawHost.trim().toLowerCase(); |
| 449 | const current = (yield* Ref.get(pending)).get(host); |
| 450 | if (current === undefined) { |
| 451 | return yield* signInError(host, "not-started", "No sign-in is in progress. Start again."); |
| 452 | } |
| 453 | return yield* Deferred.await(current.deferred); |
| 454 | }, |
| 455 | ); |
| 456 | |
| 457 | const cancel: GitHubAppSignIn["Service"]["cancel"] = Effect.fn("GitHubAppSignIn.cancel")( |
| 458 | function* (rawHost) { |
| 459 | const host = rawHost.trim().toLowerCase(); |
| 460 | const current = (yield* Ref.get(pending)).get(host); |
| 461 | if (current === undefined) return; |
| 462 | yield* Deferred.fail( |
| 463 | current.deferred, |
| 464 | signInError(host, "cancelled", "The sign-in was cancelled."), |
| 465 | ); |
| 466 | yield* Fiber.interrupt(current.fiber); |
| 467 | }, |
| 468 | ); |
| 469 | |
| 470 | return GitHubAppSignIn.of({ enabled, token, invalidate, start, wait, cancel }); |
| 471 | }); |
| 472 | |
| 473 | export const layer = Layer.effect(GitHubAppSignIn, make); |