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 | AuthError, |
| 3 | AuthProviderLayer, |
| 4 | NeedsReauth, |
| 5 | refreshHint, |
| 6 | type ConfigureField, |
| 7 | type ConfigureMethod, |
| 8 | type ProviderDetails, |
| 9 | } from "alchemy/Auth/AuthProvider"; |
| 10 | import { displayRedacted } from "alchemy/Auth/Credentials"; |
| 11 | import { getEnvRedacted, mapPromptCancellation } from "alchemy/Auth/Env"; |
| 12 | import { |
| 13 | storedSecret, |
| 14 | storedValueText, |
| 15 | validateFieldValues, |
| 16 | } from "alchemy/Auth/StoredAuthProvider"; |
| 17 | import * as Interaction from "alchemy/Interaction"; |
| 18 | import * as Data from "effect/Data"; |
| 19 | import * as Effect from "effect/Effect"; |
| 20 | import * as Match from "effect/Match"; |
| 21 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 22 | import { ChildProcessSpawner } from "effect/process/ChildProcessSpawner"; |
| 23 | import * as Redacted from "effect/Redacted"; |
| 24 | import * as Schema from "effect/Schema"; |
| 25 | import * as Stream from "effect/Stream"; |
| 26 | import { githubHostname, normalizeGitHubBaseUrl, resolveGitHubBaseUrlFromEnv } from "./BaseUrl.ts"; |
| 27 | |
| 28 | const options: Array<{ |
| 29 | value: GitHubAuthConfig["method"]; |
| 30 | label: string; |
| 31 | description?: string; |
| 32 | }> = [ |
| 33 | { |
| 34 | value: "gh-cli", |
| 35 | label: "GitHub CLI", |
| 36 | description: "delegate to `gh auth token` (run `gh auth login` first)", |
| 37 | }, |
| 38 | { |
| 39 | value: "stored", |
| 40 | label: "Personal Access Token", |
| 41 | description: "enter PAT interactively and store it in the profile", |
| 42 | }, |
| 43 | ]; |
| 44 | |
| 45 | /** Typed values stored in a GitHub provider profile document. */ |
| 46 | export const GitHubAuthConfigSchema = Schema.Union([ |
| 47 | Schema.Struct({ |
| 48 | method: Schema.Literal("stored"), |
| 49 | token: Schema.String, |
| 50 | baseUrl: Schema.optionalKey(Schema.String), |
| 51 | }), |
| 52 | Schema.Struct({ |
| 53 | method: Schema.Literal("gh-cli"), |
| 54 | // v0 delegated to `gh auth token` and therefore had no inline token. |
| 55 | // Keep that migration state readable; the first credential resolution |
| 56 | // captures the token inline through updateConfig. |
| 57 | token: Schema.optionalKey(Schema.String), |
| 58 | baseUrl: Schema.optionalKey(Schema.String), |
| 59 | }), |
| 60 | ]); |
| 61 | export type GitHubAuthConfig = typeof GitHubAuthConfigSchema.Type; |
| 62 | |
| 63 | export interface GitHubResolvedCredentials { |
| 64 | type: "token"; |
| 65 | token: Redacted.Redacted<string>; |
| 66 | /** |
| 67 | * Normalized REST API base URL for GitHub Enterprise (e.g. |
| 68 | * `https://github.example.com/api/v3` or `https://api.acme.ghe.com`). |
| 69 | * `undefined` means github.com. |
| 70 | */ |
| 71 | baseUrl?: string; |
| 72 | source: { type: GitHubAuthConfig["method"] | "env"; details?: string }; |
| 73 | } |
| 74 | |
| 75 | export const GITHUB_AUTH_PROVIDER_NAME = "GitHub"; |
| 76 | |
| 77 | class GhCliError extends Data.TaggedError("GhCliError")<{ |
| 78 | readonly message: string; |
| 79 | }> {} |
| 80 | |
| 81 | const readEnvTokenFor = ( |
| 82 | baseUrl: string | undefined, |
| 83 | ): Effect.Effect<GitHubResolvedCredentials, AuthError> => |
| 84 | Effect.gen(function* () { |
| 85 | const candidates = |
| 86 | baseUrl !== undefined |
| 87 | ? ["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN", "GITHUB_ACCESS_TOKEN", "GITHUB_TOKEN"] |
| 88 | : ["GITHUB_ACCESS_TOKEN", "GITHUB_TOKEN"]; |
| 89 | for (const key of candidates) { |
| 90 | const token = yield* getEnvRedacted(key); |
| 91 | if (token) { |
| 92 | return { |
| 93 | type: "token" as const, |
| 94 | token, |
| 95 | baseUrl, |
| 96 | source: { type: "env" as const, details: key }, |
| 97 | }; |
| 98 | } |
| 99 | } |
| 100 | return yield* AuthError.make({ |
| 101 | message: `GitHub env credentials not found. Set ${candidates.join(", ")}.`, |
| 102 | }); |
| 103 | }); |
| 104 | |
| 105 | /** Resolve standalone GitHub credentials from environment variables. */ |
| 106 | export const readEnvCredentials = ( |
| 107 | configBaseUrl?: string, |
| 108 | ): Effect.Effect<GitHubResolvedCredentials, AuthError> => |
| 109 | Effect.gen(function* () { |
| 110 | const baseUrl = configBaseUrl ?? (yield* resolveGitHubBaseUrlFromEnv); |
| 111 | return yield* readEnvTokenFor(baseUrl); |
| 112 | }); |
| 113 | |
| 114 | /** |
| 115 | * Build the Layer that registers the GitHub {@link AuthProvider} into the |
| 116 | * {@link AuthProviders} registry. Included in the GitHub `providers()` layer |
| 117 | * so the alchemy CLI can discover it. |
| 118 | * |
| 119 | * Supported methods: |
| 120 | * - `gh-cli`: shells out to `gh auth token` (recommended). |
| 121 | * - `stored`: prompts for a PAT and stores it inline in the provider file. |
| 122 | * |
| 123 | * GitHub Enterprise (Server or Cloud with data residency) is supported by |
| 124 | * every method: `alchemy profile edit --reconfigure GitHub` prompts for the host, or set |
| 125 | * `GITHUB_BASE_URL` / `GITHUB_API_URL` / `GH_HOST` in the environment. The |
| 126 | * host is normalized into the REST API base URL the SDK calls, and |
| 127 | * `gh auth token` is invoked with `--hostname` so the CLI returns the token |
| 128 | * for the right host. |
| 129 | * |
| 130 | * Browser/device OAuth is intentionally not implemented: GitHub's |
| 131 | * OAuth App flow requires a `client_secret` we cannot ship, and |
| 132 | * device flow is exactly what `gh auth login` already does. |
| 133 | */ |
| 134 | export interface GitHubAuthOptions { |
| 135 | /** |
| 136 | * Hard-code the GitHub host or API base URL (e.g. `github.example.com` |
| 137 | * or `https://github.example.com/api/v3`). When set, it takes precedence |
| 138 | * over the profile's configured host and the environment for every auth |
| 139 | * method, the configure flow stops prompting for a host, and the `gh` CLI |
| 140 | * method authenticates against this host. `GitHub.providers({ baseUrl })` |
| 141 | * threads its option here. |
| 142 | */ |
| 143 | readonly baseUrl?: string; |
| 144 | } |
| 145 | |
| 146 | export const makeGitHubAuth = (authOptions?: GitHubAuthOptions) => |
| 147 | AuthProviderLayer<GitHubAuthConfig, GitHubResolvedCredentials>()( |
| 148 | GITHUB_AUTH_PROVIDER_NAME, |
| 149 | Effect.gen(function* () { |
| 150 | // Prompts use the top-level `Interaction.*` forms, NOT `yield* Interaction.Interaction`: resolving the service |
| 151 | // at impl build would put the terminal in the registration layer's |
| 152 | // requirements, and child processes (which only ever call `read`) build |
| 153 | // this layer with no interaction services at all. |
| 154 | const cp = yield* ChildProcessSpawner; |
| 155 | |
| 156 | // Hard-coded host from `providers({ baseUrl })`, resolved once at layer |
| 157 | // build. Kept as an object so "no option" (undefined) is distinct from |
| 158 | // "option normalized to the github.com default" ({ baseUrl: undefined }) |
| 159 | // — both matter: the latter still pins the host and mutes the prompt. |
| 160 | const fixed = |
| 161 | authOptions?.baseUrl !== undefined |
| 162 | ? { |
| 163 | baseUrl: yield* normalizeGitHubBaseUrl(authOptions.baseUrl).pipe(Effect.orDie), |
| 164 | } |
| 165 | : undefined; |
| 166 | |
| 167 | // The host every method authenticates against: the hard-coded value |
| 168 | // wins, then the profile's configured host, then the environment. |
| 169 | const effectiveBaseUrl = ( |
| 170 | config: GitHubAuthConfig, |
| 171 | ): Effect.Effect<string | undefined, AuthError> => |
| 172 | fixed !== undefined |
| 173 | ? Effect.succeed(fixed.baseUrl) |
| 174 | : config.baseUrl !== undefined |
| 175 | ? Effect.succeed(config.baseUrl) |
| 176 | : resolveGitHubBaseUrlFromEnv; |
| 177 | |
| 178 | const ghCliToken = (hostname?: string): Effect.Effect<string, AuthError> => |
| 179 | Effect.gen(function* () { |
| 180 | const handle = yield* cp.spawn( |
| 181 | ChildProcess.make( |
| 182 | "gh", |
| 183 | ["auth", "token", ...(hostname !== undefined ? ["--hostname", hostname] : [])], |
| 184 | { shell: false }, |
| 185 | ), |
| 186 | ); |
| 187 | const [exitCode, stdout, stderr] = yield* Effect.all( |
| 188 | [ |
| 189 | handle.exitCode, |
| 190 | handle.stdout.pipe(Stream.decodeText, Stream.mkString), |
| 191 | handle.stderr.pipe(Stream.decodeText, Stream.mkString), |
| 192 | ], |
| 193 | { concurrency: 3 }, |
| 194 | ); |
| 195 | if (exitCode !== 0) { |
| 196 | return yield* new GhCliError({ |
| 197 | message: `gh auth token exited with ${exitCode}: ${stderr.trim() || stdout.trim()}`, |
| 198 | }); |
| 199 | } |
| 200 | const token = stdout.trim(); |
| 201 | if (!token) { |
| 202 | return yield* new GhCliError({ message: "gh auth token returned empty output" }); |
| 203 | } |
| 204 | return token; |
| 205 | }).pipe( |
| 206 | Effect.scoped, |
| 207 | Effect.mapError((e) => |
| 208 | e instanceof GhCliError |
| 209 | ? AuthError.make({ message: e.message, cause: e }) |
| 210 | : AuthError.make({ |
| 211 | message: |
| 212 | "Could not invoke `gh`. Install GitHub CLI from https://cli.github.com/ and run `gh auth login`.", |
| 213 | cause: e, |
| 214 | }), |
| 215 | ), |
| 216 | ); |
| 217 | |
| 218 | const loginStored = Effect.fn(function* (baseUrl?: string) { |
| 219 | const token = yield* Interaction.password({ |
| 220 | message: "GitHub Personal Access Token", |
| 221 | description: "Requires `repo` scope and `workflow` for GitHub Actions.", |
| 222 | validate: (v) => (v.length === 0 ? "Required" : undefined), |
| 223 | }).pipe(mapPromptCancellation); |
| 224 | yield* Interaction.success("GitHub: credentials saved."); |
| 225 | return { method: "stored" as const, token, baseUrl }; |
| 226 | }); |
| 227 | |
| 228 | // Optional GitHub Enterprise host. Blank means github.com; anything else |
| 229 | // is normalized into the REST API base URL (GHES gets `/api/v3` |
| 230 | // appended, data-residency hosts get the `api.` prefix). |
| 231 | const promptBaseUrl = Interaction.text({ |
| 232 | message: "GitHub host", |
| 233 | description: |
| 234 | "Leave blank for github.com; use a hostname such as github.example.com for GitHub Enterprise.", |
| 235 | placeholder: "github.com", |
| 236 | defaultValue: "", |
| 237 | }).pipe( |
| 238 | mapPromptCancellation, |
| 239 | Effect.flatMap((input) => { |
| 240 | const trimmed = (input ?? "").trim(); |
| 241 | return trimmed === "" ? Effect.undefined : normalizeGitHubBaseUrl(trimmed); |
| 242 | }), |
| 243 | ); |
| 244 | |
| 245 | const configureInteractive = (_profileName: string) => |
| 246 | Effect.gen(function* () { |
| 247 | const method = yield* Interaction.select({ |
| 248 | message: "GitHub authentication method", |
| 249 | options, |
| 250 | }); |
| 251 | // The host prompt is skipped when providers({ baseUrl }) pinned it — |
| 252 | // nothing is stored in the profile config; `read` re-applies the |
| 253 | // pinned value from code on every resolution. |
| 254 | const baseUrl = fixed !== undefined ? undefined : yield* promptBaseUrl; |
| 255 | const verifyHost = fixed !== undefined ? fixed.baseUrl : baseUrl; |
| 256 | return yield* Match.value(method).pipe( |
| 257 | Match.when("gh-cli", () => |
| 258 | ghCliToken(verifyHost !== undefined ? githubHostname(verifyHost) : undefined).pipe( |
| 259 | Effect.map((token) => ({ |
| 260 | method: "gh-cli" as const, |
| 261 | token, |
| 262 | baseUrl, |
| 263 | })), |
| 264 | Effect.mapError((e) => |
| 265 | AuthError.make({ |
| 266 | message: `gh CLI not available: ${e.message}`, |
| 267 | cause: e, |
| 268 | }), |
| 269 | ), |
| 270 | ), |
| 271 | ), |
| 272 | Match.when("stored", () => loginStored(baseUrl)), |
| 273 | Match.exhaustive, |
| 274 | ); |
| 275 | }); |
| 276 | |
| 277 | const configureCredentials = (profileName: string) => |
| 278 | configureInteractive(profileName).pipe( |
| 279 | Effect.mapError((e) => |
| 280 | AuthError.make({ |
| 281 | message: "failed to configure credentials", |
| 282 | cause: e, |
| 283 | }), |
| 284 | ), |
| 285 | ); |
| 286 | |
| 287 | const resolveCredentials = ( |
| 288 | profileName: string, |
| 289 | config: GitHubAuthConfig, |
| 290 | updateConfig?: (config: GitHubAuthConfig) => Effect.Effect<void, AuthError>, |
| 291 | ): Effect.Effect<GitHubResolvedCredentials, AuthError | NeedsReauth> => |
| 292 | Match.value(config).pipe( |
| 293 | Match.when( |
| 294 | { method: "stored" }, |
| 295 | Effect.fn(function* (c) { |
| 296 | const baseUrl = yield* effectiveBaseUrl(c); |
| 297 | return { |
| 298 | type: "token" as const, |
| 299 | token: Redacted.make(c.token), |
| 300 | baseUrl, |
| 301 | source: { type: "stored" as const }, |
| 302 | }; |
| 303 | }), |
| 304 | ), |
| 305 | Match.when( |
| 306 | { method: "gh-cli" }, |
| 307 | Effect.fn(function* (c) { |
| 308 | const baseUrl = yield* effectiveBaseUrl(c); |
| 309 | const token = |
| 310 | c.token ?? |
| 311 | (yield* ghCliToken( |
| 312 | baseUrl !== undefined ? githubHostname(baseUrl) : undefined, |
| 313 | ).pipe( |
| 314 | Effect.mapError((cause) => |
| 315 | NeedsReauth.make({ |
| 316 | provider: GITHUB_AUTH_PROVIDER_NAME, |
| 317 | profile: profileName, |
| 318 | message: `GitHub CLI credentials need to be refreshed. ${refreshHint(GITHUB_AUTH_PROVIDER_NAME, profileName)}`, |
| 319 | cause, |
| 320 | }), |
| 321 | ), |
| 322 | )); |
| 323 | if (c.token === undefined && updateConfig !== undefined) { |
| 324 | yield* updateConfig({ ...c, token }); |
| 325 | } |
| 326 | return { |
| 327 | type: "token" as const, |
| 328 | token: Redacted.make(token), |
| 329 | baseUrl, |
| 330 | source: { type: "gh-cli" as const }, |
| 331 | }; |
| 332 | }), |
| 333 | ), |
| 334 | Match.exhaustive, |
| 335 | ); |
| 336 | |
| 337 | const logout = (_profileName: string, config: GitHubAuthConfig) => |
| 338 | Match.value(config).pipe( |
| 339 | Match.when({ method: "gh-cli" }, () => Effect.void), |
| 340 | Match.when({ method: "stored" }, () => Effect.void), |
| 341 | Match.exhaustive, |
| 342 | ); |
| 343 | |
| 344 | const login = (_profileName: string, config: GitHubAuthConfig) => |
| 345 | Match.value(config).pipe( |
| 346 | Match.when({ method: "gh-cli" }, (c) => |
| 347 | effectiveBaseUrl(c).pipe( |
| 348 | Effect.flatMap((baseUrl) => |
| 349 | ghCliToken(baseUrl !== undefined ? githubHostname(baseUrl) : undefined), |
| 350 | ), |
| 351 | Effect.tap(() => Interaction.success("GitHub: gh CLI authentication available.")), |
| 352 | Effect.map((token) => ({ ...c, token })), |
| 353 | ), |
| 354 | ), |
| 355 | Match.when({ method: "stored" }, (c) => Effect.succeed(c)), |
| 356 | Match.exhaustive, |
| 357 | Effect.mapError((e) => AuthError.make({ message: "login failed", cause: e })), |
| 358 | ); |
| 359 | |
| 360 | const details = ( |
| 361 | profileName: string, |
| 362 | config: GitHubAuthConfig, |
| 363 | updateConfig?: (config: GitHubAuthConfig) => Effect.Effect<void, AuthError>, |
| 364 | ): Effect.Effect<ProviderDetails, AuthError | NeedsReauth> => |
| 365 | resolveCredentials(profileName, config, updateConfig).pipe( |
| 366 | Effect.map((creds) => { |
| 367 | const sourceStr = creds.source.details |
| 368 | ? `${creds.source.type} - ${creds.source.details}` |
| 369 | : creds.source.type; |
| 370 | return { |
| 371 | lines: [ |
| 372 | { key: "token", value: displayRedacted(creds.token, 6) }, |
| 373 | { key: "source", value: sourceStr }, |
| 374 | ...(creds.baseUrl !== undefined ? [{ key: "baseUrl", value: creds.baseUrl }] : []), |
| 375 | ], |
| 376 | }; |
| 377 | }), |
| 378 | ); |
| 379 | |
| 380 | // Flag-driven configuration covers the "stored" (PAT) method only; |
| 381 | // "gh-cli" requires an interactive `gh auth login` session and is |
| 382 | // deliberately absent from configureMethods. |
| 383 | const storedFields: ReadonlyArray<ConfigureField> = [ |
| 384 | { |
| 385 | name: "token", |
| 386 | label: "GitHub Personal Access Token", |
| 387 | description: "Requires `repo` scope and `workflow` for GitHub Actions.", |
| 388 | secret: true, |
| 389 | }, |
| 390 | { |
| 391 | name: "baseUrl", |
| 392 | label: "GitHub host", |
| 393 | description: |
| 394 | "Leave blank for github.com; use a hostname such as github.example.com for GitHub Enterprise.", |
| 395 | optional: true, |
| 396 | }, |
| 397 | ]; |
| 398 | |
| 399 | const configureMethods: ReadonlyArray<ConfigureMethod> = [ |
| 400 | { method: "stored", fields: storedFields }, |
| 401 | ]; |
| 402 | |
| 403 | const configureWith = ( |
| 404 | _profileName: string, |
| 405 | input: { |
| 406 | readonly method: string; |
| 407 | readonly values: Record<string, string>; |
| 408 | }, |
| 409 | ): Effect.Effect<GitHubAuthConfig, AuthError, Interaction.Interaction> => |
| 410 | input.method === "stored" |
| 411 | ? validateFieldValues(GITHUB_AUTH_PROVIDER_NAME, storedFields, input.values).pipe( |
| 412 | Effect.flatMap( |
| 413 | Effect.fn(function* (values) { |
| 414 | // A hard-coded providers({ baseUrl }) pins the host; nothing |
| 415 | // is stored in the profile config in that case (mirrors the |
| 416 | // interactive configure flow). |
| 417 | const baseUrl = |
| 418 | fixed !== undefined |
| 419 | ? undefined |
| 420 | : values.baseUrl !== undefined |
| 421 | ? yield* normalizeGitHubBaseUrl(storedValueText(values.baseUrl) ?? "") |
| 422 | : undefined; |
| 423 | const token = Redacted.value(storedSecret(values.token) ?? Redacted.make("")); |
| 424 | yield* Interaction.success("GitHub: credentials saved."); |
| 425 | return { method: "stored" as const, token, baseUrl }; |
| 426 | }), |
| 427 | ), |
| 428 | ) |
| 429 | : Effect.fail( |
| 430 | AuthError.make({ |
| 431 | message: `GitHub: unknown method '${input.method}'. Valid methods: stored. (gh-cli is interactive-only.)`, |
| 432 | }), |
| 433 | ); |
| 434 | |
| 435 | return { |
| 436 | configSchema: GitHubAuthConfigSchema, |
| 437 | configure: configureCredentials, |
| 438 | configureWith, |
| 439 | configureMethods, |
| 440 | logout, |
| 441 | login, |
| 442 | details, |
| 443 | read: resolveCredentials, |
| 444 | readEnvironment: readEnvCredentials(fixed !== undefined ? fixed.baseUrl : undefined), |
| 445 | environment: [ |
| 446 | { |
| 447 | name: "GITHUB_ACCESS_TOKEN", |
| 448 | required: true, |
| 449 | secret: true, |
| 450 | alternatives: ["GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"], |
| 451 | description: |
| 452 | "Personal access token. The enterprise variants are only consulted when a GitHub Enterprise host is configured.", |
| 453 | }, |
| 454 | { |
| 455 | name: "GITHUB_BASE_URL", |
| 456 | required: false, |
| 457 | alternatives: ["GITHUB_API_URL", "GH_HOST"], |
| 458 | description: "GitHub Enterprise host or REST API base URL.", |
| 459 | }, |
| 460 | ], |
| 461 | }; |
| 462 | }), |
| 463 | ); |
| 464 | |
| 465 | /** |
| 466 | * The default GitHub AuthProvider layer — {@link makeGitHubAuth} with no |
| 467 | * hard-coded host. Use `GitHub.providers({ baseUrl })` (or |
| 468 | * `makeGitHubAuth({ baseUrl })` directly) to pin a GitHub Enterprise host. |
| 469 | */ |
| 470 | export const GitHubAuth = makeGitHubAuth(); |