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, 06:00 UTC
| 1 | import { expect, it } from "@alchemy.run/test"; |
| 2 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 3 | import * as Clock from "effect/Clock"; |
| 4 | import * as ConfigProvider from "effect/ConfigProvider"; |
| 5 | import * as Context from "effect/Context"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as FileSystem from "effect/FileSystem"; |
| 8 | import * as Layer from "effect/Layer"; |
| 9 | import * as Logger from "effect/Logger"; |
| 10 | import * as Option from "effect/Option"; |
| 11 | import * as Ref from "effect/Ref"; |
| 12 | import * as Schema from "effect/Schema"; |
| 13 | import path from "pathe"; |
| 14 | import { |
| 15 | AuthError, |
| 16 | AuthProvider, |
| 17 | AuthProviderLayer, |
| 18 | AuthProviders, |
| 19 | AuthProvidersLive, |
| 20 | getAuthProvider, |
| 21 | NeedsReauth, |
| 22 | } from "@/Auth/AuthProvider.ts"; |
| 23 | import { inspectProvider } from "@/Auth/Inspect.ts"; |
| 24 | import { |
| 25 | configFilePath, |
| 26 | credentialsDirPath, |
| 27 | makeProviderProfileSchema, |
| 28 | PROFILE_FORMAT, |
| 29 | profileCredentialsDirPath, |
| 30 | profileDirPath, |
| 31 | profileProviderFilePath, |
| 32 | ProfileError, |
| 33 | ProfileStore, |
| 34 | ProfileStoreLive, |
| 35 | reloadProviderConfig, |
| 36 | SuppressMissingProviderConfig, |
| 37 | validateProfileName, |
| 38 | } from "@/Auth/Profile.ts"; |
| 39 | import { resolveProfileName, resolveProviderConfig } from "@/Auth/Resolve.ts"; |
| 40 | import * as Interaction from "@/Interaction.ts"; |
| 41 | import { messageForCapabilities } from "@/Util/interactive.ts"; |
| 42 | |
| 43 | const FAKE_PROVIDER = "FakeAuthProvider"; |
| 44 | |
| 45 | it.effect( |
| 46 | "selects guidance from injected interaction capabilities", |
| 47 | () => |
| 48 | Effect.gen(function* () { |
| 49 | expect( |
| 50 | yield* messageForCapabilities(Effect.succeed({ input: true }), "interactive", "plain"), |
| 51 | ).toBe("interactive"); |
| 52 | expect( |
| 53 | yield* messageForCapabilities(Effect.succeed({ input: false }), "interactive", "plain"), |
| 54 | ).toBe("plain"); |
| 55 | }), |
| 56 | { tags: ["unit", "local"] }, |
| 57 | ); |
| 58 | |
| 59 | // Records whether the lock-wrapped `configure` was ever entered. A missing |
| 60 | // profile must short-circuit before provider configuration starts. |
| 61 | const state = { configureCalls: 0 }; |
| 62 | |
| 63 | const FakeAuth = AuthProviderLayer<{ method: "stored" }, undefined>()(FAKE_PROVIDER, { |
| 64 | configSchema: Schema.Struct({ method: Schema.Literal("stored") }), |
| 65 | configure: () => |
| 66 | Effect.sync(() => { |
| 67 | state.configureCalls += 1; |
| 68 | return { method: "stored" as const }; |
| 69 | }), |
| 70 | login: () => Effect.void, |
| 71 | logout: () => Effect.void, |
| 72 | details: () => Effect.succeed({ lines: [] }), |
| 73 | read: () => Effect.succeed(undefined), |
| 74 | }); |
| 75 | |
| 76 | const ENV_PROVIDER = "FakeEnvAuthProvider"; |
| 77 | |
| 78 | /** A provider that supports both profile and environment credentials. */ |
| 79 | const fakeEnvImpl = { |
| 80 | configSchema: Schema.Struct({ method: Schema.Literal("stored") }), |
| 81 | configure: () => Effect.succeed({ method: "stored" as const }), |
| 82 | login: () => Effect.void, |
| 83 | logout: () => Effect.void, |
| 84 | details: () => Effect.succeed({ lines: [] }), |
| 85 | read: () => Effect.succeed("profile-credentials"), |
| 86 | readEnvironment: Effect.succeed("environment-credentials"), |
| 87 | environment: [{ name: "FAKE_ENV_TOKEN", required: true, secret: true }], |
| 88 | }; |
| 89 | |
| 90 | const FakeEnvAuth = AuthProviderLayer<{ method: "stored" }, string>()(ENV_PROVIDER, fakeEnvImpl); |
| 91 | |
| 92 | const ROTATING_PROVIDER = "FakeRotatingAuthProvider"; |
| 93 | |
| 94 | /** |
| 95 | * Refresh tokens are single-use, as with Cloudflare OAuth: refreshing |
| 96 | * persists a new token, and presenting a spent one revokes the grant. |
| 97 | */ |
| 98 | type RotationState = { readonly refreshes: number; readonly spent: ReadonlySet<string> }; |
| 99 | |
| 100 | class Rotation extends Context.Service<Rotation, Ref.Ref<RotationState>>()("Test/Rotation") {} |
| 101 | |
| 102 | const RotationLive = Layer.effect( |
| 103 | Rotation, |
| 104 | Ref.make<RotationState>({ refreshes: 0, spent: new Set() }), |
| 105 | ); |
| 106 | |
| 107 | type RotatingConfig = { method: "oauth"; refresh: string; expires: number }; |
| 108 | |
| 109 | const FakeRotatingAuth = AuthProviderLayer<RotatingConfig, string>()( |
| 110 | ROTATING_PROVIDER, |
| 111 | Effect.gen(function* () { |
| 112 | const rotation = yield* Rotation; |
| 113 | const rotate = Effect.fn(function* ( |
| 114 | profileName: string, |
| 115 | config: RotatingConfig, |
| 116 | updateConfig?: (config: RotatingConfig) => Effect.Effect<void, AuthError>, |
| 117 | ) { |
| 118 | const now = yield* Clock.currentTimeMillis; |
| 119 | if (config.expires > now) return config.refresh; |
| 120 | const next = yield* Ref.modify(rotation, (state) => |
| 121 | state.spent.has(config.refresh) |
| 122 | ? [undefined, state] |
| 123 | : [ |
| 124 | `r${state.refreshes + 1}`, |
| 125 | { refreshes: state.refreshes + 1, spent: new Set([...state.spent, config.refresh]) }, |
| 126 | ], |
| 127 | ); |
| 128 | if (next === undefined) { |
| 129 | return yield* NeedsReauth.make({ |
| 130 | provider: ROTATING_PROVIDER, |
| 131 | profile: profileName, |
| 132 | message: `refresh token ${config.refresh} was already used`, |
| 133 | }); |
| 134 | } |
| 135 | yield* ( |
| 136 | updateConfig?.({ method: "oauth", refresh: next, expires: now + 3_600_000 }) ?? Effect.void |
| 137 | ); |
| 138 | return next; |
| 139 | }); |
| 140 | return { |
| 141 | configSchema: Schema.Struct({ |
| 142 | method: Schema.Literal("oauth"), |
| 143 | refresh: Schema.String, |
| 144 | expires: Schema.Number, |
| 145 | }), |
| 146 | configure: () => Effect.succeed({ method: "oauth" as const, refresh: "r0", expires: 0 }), |
| 147 | login: ( |
| 148 | _profileName: string, |
| 149 | config: RotatingConfig, |
| 150 | _updateConfig?: (config: RotatingConfig) => Effect.Effect<void, AuthError>, |
| 151 | reload?: Effect.Effect<RotatingConfig, AuthError>, |
| 152 | ) => Effect.map(reload ?? Effect.succeed(config), (current) => ({ ...current, expires: 1 })), |
| 153 | logout: () => Effect.void, |
| 154 | details: ( |
| 155 | profileName: string, |
| 156 | config: RotatingConfig, |
| 157 | updateConfig?: (config: RotatingConfig) => Effect.Effect<void, AuthError>, |
| 158 | ) => |
| 159 | Effect.map(rotate(profileName, config, updateConfig), (token) => ({ |
| 160 | lines: [{ key: "token", value: token }], |
| 161 | })), |
| 162 | read: rotate, |
| 163 | }; |
| 164 | }), |
| 165 | ); |
| 166 | |
| 167 | const makeTestLayer = (config: Record<string, unknown> = {}) => |
| 168 | Layer.mergeAll(ProfileStoreLive, FakeAuth, FakeEnvAuth, FakeRotatingAuth).pipe( |
| 169 | Layer.provideMerge(RotationLive), |
| 170 | Layer.provideMerge( |
| 171 | Layer.mergeAll( |
| 172 | AuthProvidersLive, |
| 173 | ConfigProvider.layer(ConfigProvider.fromUnknown(config)), |
| 174 | NodeServices.layer, |
| 175 | ), |
| 176 | ), |
| 177 | ); |
| 178 | |
| 179 | /** |
| 180 | * Point `ALCHEMY_HOME` at a scoped temp directory for the duration of |
| 181 | * `effect`, so store operations never touch the developer's real |
| 182 | * `~/.alchemy`. Tests using this must be `exclusive` — the env var is |
| 183 | * process-global. |
| 184 | */ |
| 185 | const withTempHome = <A, E, R>( |
| 186 | effect: Effect.Effect<A, E, R>, |
| 187 | config: Record<string, unknown> = {}, |
| 188 | ) => |
| 189 | Effect.gen(function* () { |
| 190 | const fs = yield* FileSystem.FileSystem; |
| 191 | const dir = yield* fs.makeTempDirectoryScoped({ prefix: "alchemy-auth-" }); |
| 192 | const previous = process.env.ALCHEMY_HOME; |
| 193 | yield* Effect.acquireRelease( |
| 194 | Effect.sync(() => { |
| 195 | process.env.ALCHEMY_HOME = dir; |
| 196 | }), |
| 197 | () => |
| 198 | Effect.sync(() => { |
| 199 | if (previous === undefined) delete process.env.ALCHEMY_HOME; |
| 200 | else process.env.ALCHEMY_HOME = previous; |
| 201 | }), |
| 202 | ); |
| 203 | return yield* effect.pipe(Effect.provide(makeTestLayer(config))); |
| 204 | }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)); |
| 205 | |
| 206 | it.live( |
| 207 | "loadProviderConfig requires profiles to be explicitly created", |
| 208 | () => |
| 209 | withTempHome( |
| 210 | Effect.gen(function* () { |
| 211 | state.configureCalls = 0; |
| 212 | const profile = yield* ProfileStore; |
| 213 | const auth = yield* getAuthProvider<{ method: "stored" }, undefined>(FAKE_PROVIDER); |
| 214 | |
| 215 | const error = yield* profile.loadProviderConfig(auth, "non-existent").pipe(Effect.flip); |
| 216 | |
| 217 | expect(error).toBeInstanceOf(ProfileError); |
| 218 | expect((error as ProfileError).message).toContain("profile create"); |
| 219 | // The lock-wrapped `configure` must never run. |
| 220 | expect(state.configureCalls).toBe(0); |
| 221 | }), |
| 222 | ), |
| 223 | { tags: ["unit", "local"], exclusive: true }, |
| 224 | ); |
| 225 | |
| 226 | it.live( |
| 227 | "loadProviderConfig never configures a missing provider implicitly", |
| 228 | () => |
| 229 | withTempHome( |
| 230 | Effect.gen(function* () { |
| 231 | state.configureCalls = 0; |
| 232 | const profile = yield* ProfileStore; |
| 233 | const auth = yield* getAuthProvider<{ method: "stored" }, undefined>(FAKE_PROVIDER); |
| 234 | yield* profile.createProfile("explicit-login"); |
| 235 | |
| 236 | const error = yield* profile.loadProviderConfig(auth, "explicit-login").pipe(Effect.flip); |
| 237 | |
| 238 | expect(error).toBeInstanceOf(AuthError); |
| 239 | expect((error as AuthError).message).toContain( |
| 240 | `alchemy profile edit --profile explicit-login --add ${FAKE_PROVIDER}`, |
| 241 | ); |
| 242 | expect(state.configureCalls).toBe(0); |
| 243 | }), |
| 244 | ), |
| 245 | { tags: ["unit", "local"], exclusive: true }, |
| 246 | ); |
| 247 | |
| 248 | it.live( |
| 249 | "the built-in default profile always exists", |
| 250 | () => |
| 251 | withTempHome( |
| 252 | Effect.gen(function* () { |
| 253 | const profile = yield* ProfileStore; |
| 254 | const fs = yield* FileSystem.FileSystem; |
| 255 | // Never written to disk, yet the reader still presents `default` |
| 256 | // with its deterministic id. |
| 257 | const manifest = yield* profile.readManifest; |
| 258 | expect(Object.keys(manifest.profiles)).toEqual(["default"]); |
| 259 | expect(manifest.profiles.default!.id).toBe("default"); |
| 260 | expect(yield* fs.exists(profileDirPath("default"))).toBe(true); |
| 261 | expect(yield* profile.ensureProfile("default")).toEqual({ id: "default", providers: {} }); |
| 262 | // With no explicit selection every command lands on `default`. |
| 263 | const selection = yield* profile.current; |
| 264 | expect(selection).toEqual({ name: "default", source: "default" }); |
| 265 | }), |
| 266 | ), |
| 267 | { tags: ["unit", "local"], exclusive: true }, |
| 268 | ); |
| 269 | |
| 270 | it.live( |
| 271 | "the default profile cannot be deleted, renamed, or shadowed", |
| 272 | () => |
| 273 | withTempHome( |
| 274 | Effect.gen(function* () { |
| 275 | const fs = yield* FileSystem.FileSystem; |
| 276 | const profile = yield* ProfileStore; |
| 277 | // Creating a profile only creates its directory. The built-in |
| 278 | // default remains synthesized until it has a provider file. |
| 279 | yield* profile.createProfile("work"); |
| 280 | |
| 281 | const renameError = yield* profile.renameProfile("default", "other").pipe(Effect.flip); |
| 282 | expect(renameError).toBeInstanceOf(ProfileError); |
| 283 | expect((renameError as ProfileError).message).toContain("Cannot rename"); |
| 284 | |
| 285 | const deleteError = yield* profile.deleteProfile("default").pipe(Effect.flip); |
| 286 | expect(deleteError).toBeInstanceOf(ProfileError); |
| 287 | expect((deleteError as ProfileError).message).toContain("Cannot delete"); |
| 288 | |
| 289 | const createError = yield* profile.createProfile("default").pipe(Effect.flip); |
| 290 | expect((createError as ProfileError).message).toContain("already exists"); |
| 291 | |
| 292 | const shadowError = yield* profile.renameProfile("work", "default").pipe(Effect.flip); |
| 293 | expect((shadowError as ProfileError).message).toContain("already exists"); |
| 294 | |
| 295 | expect(yield* fs.exists(profileDirPath("work"))).toBe(true); |
| 296 | expect(yield* fs.exists(configFilePath())).toBe(false); |
| 297 | }), |
| 298 | ), |
| 299 | { tags: ["unit", "local"], exclusive: true }, |
| 300 | ); |
| 301 | |
| 302 | it.live( |
| 303 | "migrates centralized manifests into provider files", |
| 304 | () => |
| 305 | withTempHome( |
| 306 | Effect.gen(function* () { |
| 307 | const fs = yield* FileSystem.FileSystem; |
| 308 | const profile = yield* ProfileStore; |
| 309 | yield* fs.makeDirectory(path.dirname(configFilePath()), { recursive: true }); |
| 310 | yield* fs.writeFileString( |
| 311 | configFilePath(), |
| 312 | JSON.stringify({ |
| 313 | version: 0, |
| 314 | futureField: { anything: true }, |
| 315 | profiles: { legacy: { Cloudflare: { method: "oauth", scopes: ["d1.write"] } } }, |
| 316 | }), |
| 317 | ); |
| 318 | |
| 319 | const manifest = yield* profile.readManifest; |
| 320 | expect(manifest.profiles.legacy!.id).toBe("legacy"); |
| 321 | expect(manifest.profiles.legacy!.providers.Cloudflare).toEqual({ method: "oauth" }); |
| 322 | expect(manifest.profiles.default!.id).toBe("default"); |
| 323 | |
| 324 | const providerFile = JSON.parse( |
| 325 | yield* fs.readFileString(profileProviderFilePath("legacy", "Cloudflare")), |
| 326 | ); |
| 327 | expect(providerFile).toEqual({ |
| 328 | format: PROFILE_FORMAT, |
| 329 | provider: "Cloudflare", |
| 330 | metadata: {}, |
| 331 | values: { method: "oauth" }, |
| 332 | }); |
| 333 | expect(yield* fs.exists(configFilePath())).toBe(false); |
| 334 | expect( |
| 335 | (yield* fs.readDirectory(path.dirname(configFilePath()))).filter((entry) => |
| 336 | entry.startsWith(".profiles-v0-"), |
| 337 | ), |
| 338 | ).toHaveLength(1); |
| 339 | }), |
| 340 | ), |
| 341 | { tags: ["unit", "local"], exclusive: true }, |
| 342 | ); |
| 343 | |
| 344 | it.live( |
| 345 | "folds v0 credential sidecars into provider files", |
| 346 | () => |
| 347 | withTempHome( |
| 348 | Effect.gen(function* () { |
| 349 | const fs = yield* FileSystem.FileSystem; |
| 350 | const profile = yield* ProfileStore; |
| 351 | const sidecars = profileCredentialsDirPath("legacy"); |
| 352 | yield* fs.makeDirectory(sidecars, { recursive: true }); |
| 353 | const sidecar = (name: string, contents: unknown) => |
| 354 | fs.writeFileString( |
| 355 | path.join(sidecars, `${name}.json`), |
| 356 | typeof contents === "string" ? contents : JSON.stringify(contents), |
| 357 | ); |
| 358 | // The earliest GitHub sidecar name. |
| 359 | yield* sidecar("gh-stored", { type: "stored", token: "ghp" }); |
| 360 | // Axiom's v0 `apiToken` is now `token`. |
| 361 | yield* sidecar("axiom-stored", { type: "stored", apiToken: "xaat", orgId: "org" }); |
| 362 | yield* sidecar("cloudflare-stored", { |
| 363 | credentialType: "apiToken", |
| 364 | apiToken: "cf", |
| 365 | accountId: "acct", |
| 366 | }); |
| 367 | // Providers with several methods pick the sidecar by `method`. |
| 368 | yield* sidecar("railway-oauth", { accessToken: "rw" }); |
| 369 | yield* sidecar("hetzner-stored", "{not-json"); |
| 370 | yield* fs.writeFileString( |
| 371 | configFilePath(), |
| 372 | JSON.stringify({ |
| 373 | version: 0, |
| 374 | profiles: { |
| 375 | legacy: { |
| 376 | GitHub: { method: "stored", storageKey: "gh" }, |
| 377 | Axiom: { method: "stored" }, |
| 378 | Cloudflare: { method: "stored" }, |
| 379 | Railway: { method: "oauth" }, |
| 380 | Neon: { method: "stored" }, |
| 381 | Hetzner: { method: "stored" }, |
| 382 | }, |
| 383 | }, |
| 384 | }), |
| 385 | ); |
| 386 | |
| 387 | const providers = (yield* profile.readManifest).profiles.legacy!.providers; |
| 388 | expect(providers.GitHub).toEqual({ method: "stored", token: "ghp" }); |
| 389 | expect(providers.Axiom).toEqual({ method: "stored", token: "xaat", orgId: "org" }); |
| 390 | expect(providers.Cloudflare).toEqual({ |
| 391 | method: "stored", |
| 392 | credentialType: "apiToken", |
| 393 | apiToken: "cf", |
| 394 | accountId: "acct", |
| 395 | }); |
| 396 | expect(providers.Railway).toEqual({ method: "oauth", accessToken: "rw" }); |
| 397 | // A missing or unreadable sidecar keeps the manifest values; the |
| 398 | // original stays in the v0 backup. |
| 399 | expect(providers.Neon).toEqual({ method: "stored" }); |
| 400 | expect(providers.Hetzner).toEqual({ method: "stored" }); |
| 401 | expect(yield* fs.exists(credentialsDirPath())).toBe(false); |
| 402 | }), |
| 403 | ), |
| 404 | { tags: ["unit", "local"], exclusive: true }, |
| 405 | ); |
| 406 | |
| 407 | it.live( |
| 408 | "drops a v0 Cloudflare entry whose sidecar is incomplete", |
| 409 | () => |
| 410 | withTempHome( |
| 411 | Effect.gen(function* () { |
| 412 | const fs = yield* FileSystem.FileSystem; |
| 413 | const profile = yield* ProfileStore; |
| 414 | const sidecars = profileCredentialsDirPath("legacy"); |
| 415 | yield* fs.makeDirectory(sidecars, { recursive: true }); |
| 416 | // The earliest Cloudflare sidecar name, missing its account. |
| 417 | yield* fs.writeFileString( |
| 418 | path.join(sidecars, "cf-stored.json"), |
| 419 | JSON.stringify({ credentialType: "apiToken", apiToken: "cf" }), |
| 420 | ); |
| 421 | yield* fs.writeFileString( |
| 422 | configFilePath(), |
| 423 | JSON.stringify({ |
| 424 | version: 0, |
| 425 | profiles: { legacy: { Cloudflare: { method: "stored" } } }, |
| 426 | }), |
| 427 | ); |
| 428 | |
| 429 | const providers = (yield* profile.readManifest).profiles.legacy!.providers; |
| 430 | expect(providers.Cloudflare).toEqual({}); |
| 431 | }), |
| 432 | ), |
| 433 | { tags: ["unit", "local"], exclusive: true }, |
| 434 | ); |
| 435 | |
| 436 | it.live( |
| 437 | "ignores unreleased centralized manifest versions", |
| 438 | () => |
| 439 | withTempHome( |
| 440 | Effect.gen(function* () { |
| 441 | const fs = yield* FileSystem.FileSystem; |
| 442 | const profile = yield* ProfileStore; |
| 443 | yield* fs.makeDirectory(path.dirname(configFilePath()), { recursive: true }); |
| 444 | yield* fs.writeFileString( |
| 445 | configFilePath(), |
| 446 | JSON.stringify({ version: 1, defaultProfile: "work", profiles: { work: {} } }), |
| 447 | ); |
| 448 | |
| 449 | // Only released v0 is migrated. The short-lived centralized v1/v2 |
| 450 | // formats are left untouched and do not enter the directory store. |
| 451 | const manifest = yield* profile.readManifest; |
| 452 | expect(manifest.profiles.work).toBeUndefined(); |
| 453 | expect((yield* profile.current).name).toBe("default"); |
| 454 | |
| 455 | yield* profile.createProfile("scratch"); |
| 456 | expect(yield* fs.exists(profileDirPath("work"))).toBe(false); |
| 457 | expect(yield* fs.exists(profileDirPath("scratch"))).toBe(true); |
| 458 | expect(yield* fs.exists(configFilePath())).toBe(true); |
| 459 | }), |
| 460 | ), |
| 461 | { tags: ["unit", "local"], exclusive: true }, |
| 462 | ); |
| 463 | |
| 464 | it.live( |
| 465 | "backs up invalid provider files and continues loading the profile", |
| 466 | () => |
| 467 | withTempHome( |
| 468 | Effect.gen(function* () { |
| 469 | const fs = yield* FileSystem.FileSystem; |
| 470 | const profiles = yield* ProfileStore; |
| 471 | yield* fs.writeFileString(profileProviderFilePath("default", "Cloudflare"), "{not-json"); |
| 472 | yield* fs.writeFileString( |
| 473 | profileProviderFilePath("default", "Other"), |
| 474 | JSON.stringify({ |
| 475 | format: PROFILE_FORMAT, |
| 476 | provider: "Other", |
| 477 | metadata: {}, |
| 478 | values: { method: "stored" }, |
| 479 | }), |
| 480 | ); |
| 481 | |
| 482 | const manifest = yield* profiles.readManifest; |
| 483 | expect(manifest.profiles.default!.providers.Cloudflare).toBeUndefined(); |
| 484 | expect(manifest.profiles.default!.providers.Other).toEqual({ method: "stored" }); |
| 485 | const files = yield* fs.readDirectory(profileDirPath("default")); |
| 486 | expect(files).toContain("other.json"); |
| 487 | expect(files.some((file) => file.startsWith("cloudflare.json.invalid-"))).toBe(true); |
| 488 | }), |
| 489 | ), |
| 490 | { tags: ["unit", "local"], exclusive: true }, |
| 491 | ); |
| 492 | |
| 493 | it.live( |
| 494 | "backs up an invalid provider file before reconfiguration replaces it", |
| 495 | () => |
| 496 | withTempHome( |
| 497 | Effect.gen(function* () { |
| 498 | const fs = yield* FileSystem.FileSystem; |
| 499 | const profiles = yield* ProfileStore; |
| 500 | const file = profileProviderFilePath("default", "Cloudflare"); |
| 501 | yield* fs.writeFileString(file, "{not-json"); |
| 502 | |
| 503 | yield* profiles.setProviderConfig("default", "Cloudflare", { method: "oauth" }); |
| 504 | |
| 505 | expect(JSON.parse(yield* fs.readFileString(file))).toEqual({ |
| 506 | format: PROFILE_FORMAT, |
| 507 | provider: "Cloudflare", |
| 508 | metadata: {}, |
| 509 | values: { method: "oauth" }, |
| 510 | }); |
| 511 | expect( |
| 512 | (yield* fs.readDirectory(profileDirPath("default"))).some((entry) => |
| 513 | entry.startsWith("cloudflare.json.invalid-"), |
| 514 | ), |
| 515 | ).toBe(true); |
| 516 | }), |
| 517 | ), |
| 518 | { tags: ["unit", "local"], exclusive: true }, |
| 519 | ); |
| 520 | |
| 521 | it.live( |
| 522 | "legacy env-method entries are dropped on read", |
| 523 | () => |
| 524 | withTempHome( |
| 525 | Effect.gen(function* () { |
| 526 | const fs = yield* FileSystem.FileSystem; |
| 527 | const profile = yield* ProfileStore; |
| 528 | const auth = yield* getAuthProvider<{ method: "stored" }, undefined>(FAKE_PROVIDER); |
| 529 | yield* fs.makeDirectory(path.dirname(configFilePath()), { recursive: true }); |
| 530 | yield* fs.writeFileString( |
| 531 | configFilePath(), |
| 532 | JSON.stringify({ |
| 533 | version: 0, |
| 534 | profiles: { ci: { [FAKE_PROVIDER]: { method: "env" }, Other: { method: "stored" } } }, |
| 535 | }), |
| 536 | ); |
| 537 | |
| 538 | // The env-backed entry never surfaces: not in the read manifest... |
| 539 | const manifest = yield* profile.readManifest; |
| 540 | expect(manifest.profiles.ci!.providers[FAKE_PROVIDER]).toBeUndefined(); |
| 541 | expect(manifest.profiles.ci!.providers.Other).toEqual({ method: "stored" }); |
| 542 | |
| 543 | // ...and credential resolution reports "not configured" with the |
| 544 | // hint to connect the provider, not a legacy-env special case. |
| 545 | const error = yield* profile.loadProviderConfig(auth, "ci").pipe(Effect.flip); |
| 546 | expect(error).toBeInstanceOf(AuthError); |
| 547 | expect((error as AuthError).message).toContain("--add"); |
| 548 | |
| 549 | expect(yield* fs.exists(profileProviderFilePath("ci", FAKE_PROVIDER))).toBe(false); |
| 550 | expect(yield* fs.exists(profileProviderFilePath("ci", "Other"))).toBe(true); |
| 551 | }), |
| 552 | ), |
| 553 | { tags: ["unit", "local"], exclusive: true }, |
| 554 | ); |
| 555 | |
| 556 | it.effect( |
| 557 | "accepts portable profile names", |
| 558 | () => |
| 559 | Effect.gen(function* () { |
| 560 | expect(yield* validateProfileName("production-admin")).toBe("production-admin"); |
| 561 | expect(yield* validateProfileName("team.prod_2")).toBe("team.prod_2"); |
| 562 | }), |
| 563 | { tags: ["unit", "local"] }, |
| 564 | ); |
| 565 | |
| 566 | it.effect( |
| 567 | "lets custom providers refine metadata and values", |
| 568 | () => |
| 569 | Effect.gen(function* () { |
| 570 | const CustomProfile = makeProviderProfileSchema( |
| 571 | "Acme", |
| 572 | Schema.Struct({ team: Schema.String }), |
| 573 | Schema.Union([ |
| 574 | Schema.Struct({ method: Schema.Literal("token"), token: Schema.String }), |
| 575 | Schema.Struct({ |
| 576 | method: Schema.Literal("oauth"), |
| 577 | access: Schema.String, |
| 578 | refresh: Schema.String, |
| 579 | scopes: Schema.Array(Schema.String), |
| 580 | }), |
| 581 | ]), |
| 582 | ); |
| 583 | expect( |
| 584 | yield* Schema.decodeUnknownEffect(CustomProfile)({ |
| 585 | format: PROFILE_FORMAT, |
| 586 | provider: "Acme", |
| 587 | metadata: { team: "platform" }, |
| 588 | values: { method: "token", token: "secret" }, |
| 589 | }), |
| 590 | ).toEqual({ |
| 591 | format: PROFILE_FORMAT, |
| 592 | provider: "Acme", |
| 593 | metadata: { team: "platform" }, |
| 594 | values: { method: "token", token: "secret" }, |
| 595 | }); |
| 596 | }), |
| 597 | { tags: ["unit", "local"] }, |
| 598 | ); |
| 599 | |
| 600 | it.effect( |
| 601 | "rejects profile names that can escape the credential directory", |
| 602 | () => |
| 603 | Effect.gen(function* () { |
| 604 | for (const name of ["..", "../..", "team/prod", "/tmp/profile", ""]) { |
| 605 | const error = yield* validateProfileName(name).pipe(Effect.flip); |
| 606 | expect(error).toBeInstanceOf(ProfileError); |
| 607 | } |
| 608 | }), |
| 609 | { tags: ["unit", "local"] }, |
| 610 | ); |
| 611 | |
| 612 | it.effect( |
| 613 | "preserves CLI and explicit env-file precedence over the process profile", |
| 614 | () => |
| 615 | Effect.gen(function* () { |
| 616 | yield* Effect.acquireRelease( |
| 617 | Effect.sync(() => { |
| 618 | const previous = process.env.ALCHEMY_PROFILE; |
| 619 | delete process.env.ALCHEMY_PROFILE; |
| 620 | return previous; |
| 621 | }), |
| 622 | (previous) => |
| 623 | Effect.sync(() => { |
| 624 | if (previous === undefined) delete process.env.ALCHEMY_PROFILE; |
| 625 | else process.env.ALCHEMY_PROFILE = previous; |
| 626 | }), |
| 627 | ); |
| 628 | const fs = yield* FileSystem.FileSystem; |
| 629 | const file = yield* fs.makeTempFileScoped(); |
| 630 | yield* fs.writeFileString(file, "ALCHEMY_PROFILE=from-env-file\n"); |
| 631 | |
| 632 | expect(yield* resolveProfileName(Option.some(file), undefined)).toBe("from-env-file"); |
| 633 | expect(yield* resolveProfileName(Option.some(file), "from-cli")).toBe("from-cli"); |
| 634 | |
| 635 | yield* Effect.sync(() => { |
| 636 | process.env.ALCHEMY_PROFILE = "from-process"; |
| 637 | }); |
| 638 | expect(yield* resolveProfileName(Option.some(file), undefined)).toBe("from-env-file"); |
| 639 | expect(yield* resolveProfileName(Option.some(file), "from-cli")).toBe("from-cli"); |
| 640 | }).pipe(Effect.scoped, Effect.provide(makeTestLayer())), |
| 641 | { tags: ["unit", "local"], exclusive: true }, |
| 642 | ); |
| 643 | |
| 644 | it.live( |
| 645 | "environment notices share a provider cache and reset when its layer is rebuilt", |
| 646 | () => { |
| 647 | const messages: unknown[] = []; |
| 648 | const run = withTempHome( |
| 649 | Effect.gen(function* () { |
| 650 | yield* AuthProvider<{ method: "stored" }, string>()("OtherNoticeProvider", fakeEnvImpl); |
| 651 | const resolve = resolveProviderConfig(ENV_PROVIDER); |
| 652 | yield* resolve.pipe(Effect.provideService(SuppressMissingProviderConfig, true)); |
| 653 | expect(messages).toEqual([]); |
| 654 | const results = yield* Effect.all( |
| 655 | Array.from({ length: 10 }, () => resolve), |
| 656 | { concurrency: "unbounded" }, |
| 657 | ); |
| 658 | for (const result of results) { |
| 659 | expect(yield* result.resolve).toBe("environment-credentials"); |
| 660 | } |
| 661 | yield* resolveProviderConfig("OtherNoticeProvider"); |
| 662 | expect(messages).toEqual([ |
| 663 | ["FakeEnvAuthProvider: using environment variables (FAKE_ENV_TOKEN)."], |
| 664 | ["OtherNoticeProvider: using environment variables (FAKE_ENV_TOKEN)."], |
| 665 | ]); |
| 666 | }), |
| 667 | { FAKE_ENV_TOKEN: "from-env" }, |
| 668 | ); |
| 669 | return Effect.gen(function* () { |
| 670 | yield* run; |
| 671 | messages.length = 0; |
| 672 | yield* run; |
| 673 | }).pipe( |
| 674 | Effect.provide( |
| 675 | Logger.layer([ |
| 676 | Logger.make<unknown, void>((options) => { |
| 677 | messages.push(options.message); |
| 678 | }), |
| 679 | ]), |
| 680 | ), |
| 681 | ); |
| 682 | }, |
| 683 | { tags: ["unit", "local"], exclusive: true }, |
| 684 | ); |
| 685 | |
| 686 | it.live( |
| 687 | "concurrent resolves of an expired credential refresh it once", |
| 688 | () => |
| 689 | withTempHome( |
| 690 | Effect.gen(function* () { |
| 691 | const profile = yield* ProfileStore; |
| 692 | yield* profile.setProviderConfig("default", ROTATING_PROVIDER, { |
| 693 | method: "oauth", |
| 694 | refresh: "r0", |
| 695 | expires: 0, |
| 696 | }); |
| 697 | // Each resolution loads the profile up front, as two processes |
| 698 | // (say `plan` and a state read) starting together would. |
| 699 | const first = yield* resolveProviderConfig<RotatingConfig, string>(ROTATING_PROVIDER); |
| 700 | const second = yield* resolveProviderConfig<RotatingConfig, string>(ROTATING_PROVIDER); |
| 701 | |
| 702 | const tokens = yield* Effect.all([first.resolve, second.resolve], { |
| 703 | concurrency: "unbounded", |
| 704 | }); |
| 705 | |
| 706 | expect(tokens).toEqual(["r1", "r1"]); |
| 707 | expect((yield* Ref.get(yield* Rotation)).refreshes).toBe(1); |
| 708 | // A later resolve in the same process reads the rotated token too. |
| 709 | expect(yield* first.resolve).toBe("r1"); |
| 710 | expect((yield* Ref.get(yield* Rotation)).refreshes).toBe(1); |
| 711 | }), |
| 712 | ), |
| 713 | { tags: ["unit", "local"], exclusive: true }, |
| 714 | ); |
| 715 | |
| 716 | it.live( |
| 717 | "concurrent inspections of an expired credential refresh it once", |
| 718 | () => |
| 719 | withTempHome( |
| 720 | Effect.gen(function* () { |
| 721 | const profile = yield* ProfileStore; |
| 722 | const registered = yield* AuthProviders; |
| 723 | const stale = { method: "oauth", refresh: "r0", expires: 0 }; |
| 724 | yield* profile.setProviderConfig("default", ROTATING_PROVIDER, stale); |
| 725 | const persist = (updated: Record<string, unknown>) => |
| 726 | profile |
| 727 | .setProviderConfig("default", ROTATING_PROVIDER, updated) |
| 728 | .pipe(Effect.mapError((cause) => AuthError.make({ message: cause.message, cause }))); |
| 729 | // Both inspections start from the config read before either refresh, |
| 730 | // as two `alchemy profile show` processes started together would. |
| 731 | const inspect = inspectProvider("default", ROTATING_PROVIDER, stale, registered, persist); |
| 732 | const connections = yield* Effect.all([inspect, inspect], { |
| 733 | concurrency: "unbounded", |
| 734 | }).pipe(Effect.provide(Interaction.layerNonInteractive())); |
| 735 | |
| 736 | expect(connections.map((c) => c.status)).toEqual(["connected", "connected"]); |
| 737 | expect((yield* Ref.get(yield* Rotation)).refreshes).toBe(1); |
| 738 | }), |
| 739 | ), |
| 740 | { tags: ["unit", "local"], exclusive: true }, |
| 741 | ); |
| 742 | |
| 743 | it.live( |
| 744 | "login hands the provider a reload of the stored config", |
| 745 | () => |
| 746 | withTempHome( |
| 747 | Effect.gen(function* () { |
| 748 | const profile = yield* ProfileStore; |
| 749 | yield* profile.setProviderConfig("default", ROTATING_PROVIDER, { |
| 750 | method: "oauth", |
| 751 | refresh: "r7", |
| 752 | expires: 0, |
| 753 | }); |
| 754 | const auth = yield* getAuthProvider<RotatingConfig, string>(ROTATING_PROVIDER); |
| 755 | |
| 756 | const refreshed = yield* auth |
| 757 | .login( |
| 758 | "default", |
| 759 | { method: "oauth", refresh: "r0", expires: 0 }, |
| 760 | undefined, |
| 761 | reloadProviderConfig(profile, auth, "default"), |
| 762 | ) |
| 763 | .pipe(Effect.provide(Interaction.layerNonInteractive())); |
| 764 | |
| 765 | expect(refreshed).toMatchObject({ refresh: "r7" }); |
| 766 | }), |
| 767 | ), |
| 768 | { tags: ["unit", "local"], exclusive: true }, |
| 769 | ); |
| 770 | |
| 771 | it.live( |
| 772 | "provider variables present in config resolve without a profile", |
| 773 | () => |
| 774 | withTempHome( |
| 775 | Effect.gen(function* () { |
| 776 | const resolved = yield* resolveProviderConfig(ENV_PROVIDER); |
| 777 | expect(resolved.source).toBe("environment"); |
| 778 | expect(yield* resolved.resolve).toBe("environment-credentials"); |
| 779 | }), |
| 780 | // Environment credentials are read through the config provider — |
| 781 | // the process environment, `.env`, and `--env-file` alike. |
| 782 | { FAKE_ENV_TOKEN: "from-env" }, |
| 783 | ), |
| 784 | { tags: ["unit", "local"], exclusive: true }, |
| 785 | ); |
| 786 | |
| 787 | it.live( |
| 788 | "provider environment variables take precedence over a selected profile", |
| 789 | () => |
| 790 | withTempHome( |
| 791 | Effect.gen(function* () { |
| 792 | // ALCHEMY_PROFILE (the --profile mechanism) selects a profile, but |
| 793 | // a fully present environment contract still wins — the profile |
| 794 | // is never consulted, so its unconfigured provider cannot fail. |
| 795 | const resolved = yield* resolveProviderConfig(ENV_PROVIDER); |
| 796 | expect(resolved.source).toBe("environment"); |
| 797 | expect(resolved.profileName).toBeUndefined(); |
| 798 | expect(yield* resolved.resolve).toBe("environment-credentials"); |
| 799 | }), |
| 800 | { ALCHEMY_PROFILE: "default", FAKE_ENV_TOKEN: "from-env" }, |
| 801 | ), |
| 802 | { tags: ["unit", "local"], exclusive: true }, |
| 803 | ); |
| 804 | |
| 805 | it.live( |
| 806 | "providers mix: one from environment variables, the rest from the profile", |
| 807 | () => |
| 808 | withTempHome( |
| 809 | Effect.gen(function* () { |
| 810 | const profile = yield* ProfileStore; |
| 811 | yield* profile.setProviderConfig("default", FAKE_PROVIDER, { method: "stored" }); |
| 812 | // Precedence is decided per provider, not per run: the provider |
| 813 | // whose contract is present resolves from the environment while a |
| 814 | // provider without those variables still comes from the profile. |
| 815 | const fromEnv = yield* resolveProviderConfig(ENV_PROVIDER); |
| 816 | expect(fromEnv.source).toBe("environment"); |
| 817 | const fromProfile = yield* resolveProviderConfig(FAKE_PROVIDER); |
| 818 | expect(fromProfile.source).toBe("profile"); |
| 819 | expect(fromProfile.profileName).toBe("default"); |
| 820 | }), |
| 821 | { FAKE_ENV_TOKEN: "from-env" }, |
| 822 | ), |
| 823 | { tags: ["unit", "local"], exclusive: true }, |
| 824 | ); |
| 825 | |
| 826 | it.live( |
| 827 | "CI resolves environment credentials without touching profiles", |
| 828 | () => |
| 829 | withTempHome( |
| 830 | Effect.gen(function* () { |
| 831 | // No process.env presence required: CI reads through the config |
| 832 | // provider (env + --env-file) and never consults the profile. |
| 833 | const resolved = yield* resolveProviderConfig(ENV_PROVIDER); |
| 834 | expect(resolved.source).toBe("environment"); |
| 835 | expect(resolved.profileName).toBeUndefined(); |
| 836 | }), |
| 837 | { CI: true, ALCHEMY_PROFILE: "default" }, |
| 838 | ), |
| 839 | { tags: ["unit", "local"], exclusive: true }, |
| 840 | ); |
| 841 | |
| 842 | it.live( |
| 843 | "an invalid stored provider entry fails with a reconfigure hint", |
| 844 | () => |
| 845 | withTempHome( |
| 846 | Effect.gen(function* () { |
| 847 | const fs = yield* FileSystem.FileSystem; |
| 848 | const profile = yield* ProfileStore; |
| 849 | const auth = yield* getAuthProvider<{ method: "stored" }, undefined>(FAKE_PROVIDER); |
| 850 | yield* fs.makeDirectory(path.dirname(configFilePath()), { recursive: true }); |
| 851 | yield* fs.writeFileString( |
| 852 | configFilePath(), |
| 853 | JSON.stringify({ |
| 854 | version: 0, |
| 855 | profiles: { ci: { [FAKE_PROVIDER]: { method: "bogus" } } }, |
| 856 | }), |
| 857 | ); |
| 858 | |
| 859 | const error = yield* profile.loadProviderConfig(auth, "ci").pipe(Effect.flip); |
| 860 | expect(error).toBeInstanceOf(AuthError); |
| 861 | expect((error as AuthError).message).toContain("--reconfigure"); |
| 862 | }), |
| 863 | ), |
| 864 | { tags: ["unit", "local"], exclusive: true }, |
| 865 | ); |