The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Config from "effect/Config"; |
| 2 | import * as Context from "effect/Context"; |
| 3 | import * as DateTime from "effect/DateTime"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as FileSystem from "effect/FileSystem"; |
| 6 | import * as Layer from "effect/Layer"; |
| 7 | import * as Option from "effect/Option"; |
| 8 | import * as Path from "effect/Path"; |
| 9 | import type { PlatformError } from "effect/PlatformError"; |
| 10 | import * as Result from "effect/Result"; |
| 11 | import * as Schema from "effect/Schema"; |
| 12 | import { UserFacingError } from "../UserFacingError.ts"; |
| 13 | import { writeFileAtomic } from "../Util/AtomicFile.ts"; |
| 14 | import { profileCommandHint } from "../Util/interactive.ts"; |
| 15 | import { AuthError, type AuthProvider } from "./AuthProvider.ts"; |
| 16 | import { withLock } from "./Lock.ts"; |
| 17 | import { |
| 18 | configFilePath, |
| 19 | credentialsDirPath, |
| 20 | profileCredentialsDirPath, |
| 21 | profileDirPath, |
| 22 | profileProviderFilePath, |
| 23 | profilesDirPath, |
| 24 | rootDir, |
| 25 | } from "./Paths.ts"; |
| 26 | import * as V0 from "./ProfileMigrationV0.ts"; |
| 27 | |
| 28 | export { |
| 29 | configFilePath, |
| 30 | credentialsDirPath, |
| 31 | profileCredentialsDirPath, |
| 32 | profileDirPath, |
| 33 | profileProviderFilePath, |
| 34 | profilesDirPath, |
| 35 | rootDir, |
| 36 | } from "./Paths.ts"; |
| 37 | |
| 38 | /** Config key selecting a directory under `~/.alchemy/profiles`. */ |
| 39 | export const ALCHEMY_PROFILE = Config.String("ALCHEMY_PROFILE"); |
| 40 | |
| 41 | /** Version of the synthesized in-memory manifest returned by readManifest. */ |
| 42 | export const PROFILE_MANIFEST_VERSION = 3; |
| 43 | |
| 44 | /** Stable format identifier for an individual provider profile document. */ |
| 45 | export const PROFILE_FORMAT = "alchemy.profile/v1" as const; |
| 46 | |
| 47 | export const DEFAULT_PROFILE_NAME = "default"; |
| 48 | export const DEFAULT_PROFILE_ID = "default"; |
| 49 | |
| 50 | /** |
| 51 | * The minimum contract shared by provider-owned values. Providers refine this |
| 52 | * with their own Effect Schema codec. The method is deliberately an open |
| 53 | * string: adding an auth method never changes Alchemy's storage schema. |
| 54 | */ |
| 55 | export const ProviderConfigSchema = Schema.Record(Schema.String, Schema.Unknown); |
| 56 | |
| 57 | export interface ProviderConfig { |
| 58 | readonly method?: string; |
| 59 | readonly [key: string]: unknown; |
| 60 | } |
| 61 | |
| 62 | /** User-facing, non-secret annotations. Provider schemas may refine it. */ |
| 63 | export const ProfileMetadataSchema = Schema.Record(Schema.String, Schema.Unknown); |
| 64 | export type ProfileMetadata = typeof ProfileMetadataSchema.Type; |
| 65 | |
| 66 | /** |
| 67 | * Base on-disk schema. Only this envelope is owned by Alchemy core; the |
| 68 | * selected AuthProvider decodes `metadata` and `values` with its own schemas. |
| 69 | */ |
| 70 | export const ProviderProfileFileSchema = Schema.StructWithRest( |
| 71 | Schema.Struct({ |
| 72 | format: Schema.Literal(PROFILE_FORMAT), |
| 73 | provider: Schema.String, |
| 74 | metadata: ProfileMetadataSchema, |
| 75 | values: ProviderConfigSchema, |
| 76 | }), |
| 77 | [Schema.Record(Schema.String, Schema.Unknown)], |
| 78 | ); |
| 79 | |
| 80 | export type ProviderProfileFile = typeof ProviderProfileFileSchema.Type; |
| 81 | |
| 82 | /** Compose the base envelope with a custom provider's typed schemas. */ |
| 83 | export const makeProviderProfileSchema = <Metadata, Values>( |
| 84 | provider: string, |
| 85 | metadata: Schema.Codec<Metadata>, |
| 86 | values: Schema.Codec<Values>, |
| 87 | ) => |
| 88 | Schema.Struct({ |
| 89 | format: Schema.Literal(PROFILE_FORMAT), |
| 90 | provider: Schema.Literal(provider), |
| 91 | metadata, |
| 92 | values, |
| 93 | }); |
| 94 | |
| 95 | /** |
| 96 | * Aggregate view used by the profile UI. It is synthesized from provider |
| 97 | * files and is never persisted as a central manifest. |
| 98 | */ |
| 99 | export interface Profile { |
| 100 | readonly id: string; |
| 101 | readonly providers: Record<string, ProviderConfig>; |
| 102 | } |
| 103 | |
| 104 | export interface ProfileManifest { |
| 105 | readonly version: typeof PROFILE_MANIFEST_VERSION; |
| 106 | readonly profiles: Record<string, Profile>; |
| 107 | } |
| 108 | |
| 109 | export interface ProfileSelection { |
| 110 | readonly name: string; |
| 111 | readonly source: "configuration" | "default"; |
| 112 | } |
| 113 | |
| 114 | export class ProfileError extends Schema.TaggedError<ProfileError>()("ProfileError", { |
| 115 | message: Schema.String, |
| 116 | cause: Schema.optional(Schema.Defect()), |
| 117 | }) { |
| 118 | readonly [UserFacingError] = true; |
| 119 | } |
| 120 | |
| 121 | export class MissingProviderConfig extends Schema.TaggedError<MissingProviderConfig>()( |
| 122 | "MissingProviderConfig", |
| 123 | { |
| 124 | provider: Schema.String, |
| 125 | profileName: Schema.String, |
| 126 | message: Schema.String, |
| 127 | }, |
| 128 | ) {} |
| 129 | |
| 130 | export const SuppressMissingProviderConfig = Context.Reference<boolean>( |
| 131 | "Auth/SuppressMissingProviderConfig", |
| 132 | { defaultValue: () => false }, |
| 133 | ); |
| 134 | |
| 135 | const emptyManifest = (): ProfileManifest => ({ |
| 136 | version: PROFILE_MANIFEST_VERSION, |
| 137 | profiles: { |
| 138 | [DEFAULT_PROFILE_NAME]: { id: DEFAULT_PROFILE_ID, providers: {} }, |
| 139 | }, |
| 140 | }); |
| 141 | |
| 142 | export const createProfileHint = (name?: string) => |
| 143 | Effect.map( |
| 144 | profileCommandHint(`alchemy profile create ${name ?? "<name>"}`), |
| 145 | (command) => `Run \`${command}\`.`, |
| 146 | ); |
| 147 | |
| 148 | const profileNotFound = Effect.fn(function* (name: string) { |
| 149 | return ProfileError.make({ |
| 150 | message: `Profile '${name}' does not exist. ${yield* createProfileHint(name)}`, |
| 151 | }); |
| 152 | }); |
| 153 | |
| 154 | export const cannotDeleteDefaultProfile = () => |
| 155 | ProfileError.make({ |
| 156 | message: `Cannot delete the built-in '${DEFAULT_PROFILE_NAME}' profile.`, |
| 157 | }); |
| 158 | |
| 159 | export const cannotRenameDefaultProfile = () => |
| 160 | ProfileError.make({ |
| 161 | message: `Cannot rename the built-in '${DEFAULT_PROFILE_NAME}' profile.`, |
| 162 | }); |
| 163 | |
| 164 | const PROFILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; |
| 165 | |
| 166 | export const validateProfileName = (name: string): Effect.Effect<string, ProfileError> => |
| 167 | PROFILE_NAME_PATTERN.test(name) |
| 168 | ? Effect.succeed(name) |
| 169 | : Effect.fail( |
| 170 | ProfileError.make({ |
| 171 | message: |
| 172 | `Invalid profile name '${name}'. Profile names must start with an ASCII letter or number, ` + |
| 173 | "contain only letters, numbers, '.', '_' or '-', and be at most 64 characters.", |
| 174 | }), |
| 175 | ); |
| 176 | |
| 177 | const validateProviderName = (name: string): Effect.Effect<string, ProfileError> => |
| 178 | PROFILE_NAME_PATTERN.test(name) |
| 179 | ? Effect.succeed(name) |
| 180 | : Effect.fail( |
| 181 | ProfileError.make({ |
| 182 | message: `Invalid provider id '${name}'. Provider ids must be safe as filenames.`, |
| 183 | }), |
| 184 | ); |
| 185 | |
| 186 | export interface ProfileStoreService { |
| 187 | readonly readManifest: Effect.Effect<ProfileManifest, ProfileError | PlatformError>; |
| 188 | readonly getProfile: ( |
| 189 | name: string, |
| 190 | ) => Effect.Effect<Profile | undefined, ProfileError | PlatformError>; |
| 191 | readonly ensureProfile: (name: string) => Effect.Effect<Profile, ProfileError | PlatformError>; |
| 192 | readonly createProfile: (name: string) => Effect.Effect<void, ProfileError | PlatformError>; |
| 193 | readonly renameProfile: ( |
| 194 | name: string, |
| 195 | newName: string, |
| 196 | ) => Effect.Effect<void, ProfileError | PlatformError>; |
| 197 | readonly current: Effect.Effect<ProfileSelection, ProfileError | PlatformError>; |
| 198 | readonly setProviderConfig: ( |
| 199 | profile: string, |
| 200 | provider: string, |
| 201 | values: ProviderConfig, |
| 202 | ) => Effect.Effect<void, ProfileError | PlatformError>; |
| 203 | readonly deleteProviderConfig: ( |
| 204 | profile: string, |
| 205 | provider: string, |
| 206 | ) => Effect.Effect<boolean, ProfileError | PlatformError>; |
| 207 | readonly deleteProfile: (name: string) => Effect.Effect<boolean, ProfileError | PlatformError>; |
| 208 | readonly loadProviderConfig: <Config extends { method: string }>( |
| 209 | auth: AuthProvider<Config>, |
| 210 | profileName: string, |
| 211 | ) => Effect.Effect<Config, AuthError | MissingProviderConfig | ProfileError | PlatformError>; |
| 212 | } |
| 213 | |
| 214 | export class ProfileStore extends Context.Service<ProfileStore, ProfileStoreService>()( |
| 215 | "Alchemy::ProfileStore", |
| 216 | ) {} |
| 217 | |
| 218 | export const ProfileStoreLive = Layer.effect( |
| 219 | ProfileStore, |
| 220 | Effect.gen(function* () { |
| 221 | const fs = yield* FileSystem.FileSystem; |
| 222 | const pathService = yield* Path.Path; |
| 223 | |
| 224 | yield* fs.makeDirectory(profileDirPath(DEFAULT_PROFILE_NAME), { |
| 225 | recursive: true, |
| 226 | }); |
| 227 | yield* fs.chmod(profileDirPath(DEFAULT_PROFILE_NAME), 0o700); |
| 228 | |
| 229 | const provideLockServices = <A, E>( |
| 230 | effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>, |
| 231 | ): Effect.Effect<A, E> => |
| 232 | effect.pipe( |
| 233 | Effect.provideService(FileSystem.FileSystem, fs), |
| 234 | Effect.provideService(Path.Path, pathService), |
| 235 | ); |
| 236 | |
| 237 | const decodeJson = (file: string) => |
| 238 | fs.readFileString(file).pipe( |
| 239 | Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))), |
| 240 | Effect.mapError((cause) => |
| 241 | ProfileError.make({ |
| 242 | message: `Could not parse '${file}'.`, |
| 243 | cause, |
| 244 | }), |
| 245 | ), |
| 246 | ); |
| 247 | |
| 248 | const backupInvalidProfileFile = (file: string, reason: unknown) => |
| 249 | provideLockServices( |
| 250 | withLock( |
| 251 | "profiles-invalid", |
| 252 | Effect.gen(function* () { |
| 253 | if (!(yield* fs.exists(file))) return undefined; |
| 254 | const stamp = DateTime.formatIso(yield* DateTime.now) |
| 255 | .replaceAll(":", "-") |
| 256 | .replaceAll(".", "-"); |
| 257 | const backup = `${file}.invalid-${stamp}.bak`; |
| 258 | yield* fs.rename(file, backup); |
| 259 | yield* Effect.logWarning( |
| 260 | `Invalid profile file '${file}' was backed up to '${backup}' and skipped.`, |
| 261 | reason, |
| 262 | ); |
| 263 | return backup; |
| 264 | }), |
| 265 | ), |
| 266 | ); |
| 267 | |
| 268 | const writeProviderFile = ( |
| 269 | profile: string, |
| 270 | provider: string, |
| 271 | values: ProviderConfig, |
| 272 | previous?: ProviderProfileFile, |
| 273 | ) => |
| 274 | Effect.gen(function* () { |
| 275 | yield* validateProfileName(profile); |
| 276 | yield* validateProviderName(provider); |
| 277 | const dir = profileDirPath(profile); |
| 278 | yield* fs.makeDirectory(dir, { recursive: true }); |
| 279 | yield* fs.chmod(dir, 0o700); |
| 280 | const document: ProviderProfileFile = { |
| 281 | format: PROFILE_FORMAT, |
| 282 | provider, |
| 283 | metadata: previous?.metadata ?? {}, |
| 284 | values, |
| 285 | }; |
| 286 | yield* writeFileAtomic( |
| 287 | fs, |
| 288 | profileProviderFilePath(profile, provider), |
| 289 | JSON.stringify(document, null, 2), |
| 290 | 0o600, |
| 291 | ); |
| 292 | }); |
| 293 | |
| 294 | const readLegacyProviderValues = (profile: string, provider: string, values: ProviderConfig) => |
| 295 | Effect.gen(function* () { |
| 296 | const plan = V0.planSidecar(provider, values); |
| 297 | if (plan._tag === "Inline") return plan.values; |
| 298 | |
| 299 | let credentialFile: string | undefined; |
| 300 | for (const candidate of plan.candidates) { |
| 301 | const file = pathService.join(profileCredentialsDirPath(profile), `${candidate}.json`); |
| 302 | if (yield* fs.exists(file)) { |
| 303 | credentialFile = file; |
| 304 | break; |
| 305 | } |
| 306 | } |
| 307 | if (credentialFile === undefined) return plan.fallback; |
| 308 | |
| 309 | const decoded = yield* Effect.result( |
| 310 | decodeJson(credentialFile).pipe( |
| 311 | Effect.flatMap(Schema.decodeUnknownEffect(ProviderConfigSchema)), |
| 312 | ), |
| 313 | ); |
| 314 | if (Result.isFailure(decoded)) { |
| 315 | yield* Effect.logWarning( |
| 316 | `Could not decode legacy credentials from '${credentialFile}'; migrating the manifest values and preserving the sidecar in the v0 backup.`, |
| 317 | decoded.failure, |
| 318 | ); |
| 319 | return plan.fallback; |
| 320 | } |
| 321 | return V0.mergeSidecar(provider, values, decoded.success); |
| 322 | }); |
| 323 | |
| 324 | const migrateCentralManifestLocked = provideLockServices( |
| 325 | withLock( |
| 326 | "profiles-migrate", |
| 327 | Effect.gen(function* () { |
| 328 | const legacy = configFilePath(); |
| 329 | if (!(yield* fs.exists(legacy))) return; |
| 330 | const jsonResult = yield* Effect.result(decodeJson(legacy)); |
| 331 | if (Result.isFailure(jsonResult)) { |
| 332 | yield* backupInvalidProfileFile(legacy, jsonResult.failure); |
| 333 | return; |
| 334 | } |
| 335 | const header = Schema.decodeUnknownOption(Schema.Struct({ version: Schema.Number }))( |
| 336 | jsonResult.success, |
| 337 | ); |
| 338 | // The short-lived centralized versions were never released and do |
| 339 | // not need a compatibility path. Leave them untouched. |
| 340 | if (Option.isSome(header) && header.value.version !== 0) return; |
| 341 | const storedResult = yield* Effect.result( |
| 342 | Schema.decodeUnknownEffect(V0.V0ManifestSchema)(jsonResult.success), |
| 343 | ); |
| 344 | if (Result.isFailure(storedResult)) { |
| 345 | yield* backupInvalidProfileFile(legacy, storedResult.failure); |
| 346 | return; |
| 347 | } |
| 348 | const stored = storedResult.success; |
| 349 | for (const [name, entry] of Object.entries(stored.profiles)) { |
| 350 | const validName = yield* Effect.result(validateProfileName(name)); |
| 351 | if (Result.isFailure(validName)) { |
| 352 | yield* Effect.logWarning( |
| 353 | `Skipping invalid v0 profile name '${name}'. It remains available in the v0 backup.`, |
| 354 | ); |
| 355 | continue; |
| 356 | } |
| 357 | const providersResult = yield* Effect.result( |
| 358 | Schema.decodeUnknownEffect(Schema.Record(Schema.String, Schema.Unknown))(entry), |
| 359 | ); |
| 360 | if (Result.isFailure(providersResult)) { |
| 361 | yield* Effect.logWarning( |
| 362 | `Skipping invalid v0 profile '${name}'. It remains available in the v0 backup.`, |
| 363 | providersResult.failure, |
| 364 | ); |
| 365 | continue; |
| 366 | } |
| 367 | yield* fs.makeDirectory(profileDirPath(name), { recursive: true }); |
| 368 | yield* fs.chmod(profileDirPath(name), 0o700); |
| 369 | for (const [provider, rawValues] of Object.entries(providersResult.success)) { |
| 370 | const validProvider = yield* Effect.result(validateProviderName(provider)); |
| 371 | if (Result.isFailure(validProvider)) { |
| 372 | yield* Effect.logWarning( |
| 373 | `Skipping invalid v0 provider name '${provider}' in profile '${name}'. It remains available in the v0 backup.`, |
| 374 | ); |
| 375 | continue; |
| 376 | } |
| 377 | const valuesResult = yield* Effect.result( |
| 378 | Schema.decodeUnknownEffect(ProviderConfigSchema)(rawValues), |
| 379 | ); |
| 380 | if (Result.isFailure(valuesResult)) { |
| 381 | const fallback = V0.undecodableValues(provider); |
| 382 | if (fallback !== undefined) { |
| 383 | const target = profileProviderFilePath(name, provider); |
| 384 | if (!(yield* fs.exists(target))) { |
| 385 | yield* writeProviderFile(name, provider, fallback); |
| 386 | } |
| 387 | continue; |
| 388 | } |
| 389 | yield* Effect.logWarning( |
| 390 | `Skipping invalid v0 provider '${provider}' in profile '${name}'. It remains available in the v0 backup.`, |
| 391 | valuesResult.failure, |
| 392 | ); |
| 393 | continue; |
| 394 | } |
| 395 | const values = valuesResult.success; |
| 396 | if (values.method === "env") continue; |
| 397 | // Known legacy sidecars become inline provider values. |
| 398 | const migratedValues = yield* readLegacyProviderValues(name, provider, values); |
| 399 | const target = profileProviderFilePath(name, provider); |
| 400 | if (!(yield* fs.exists(target))) { |
| 401 | yield* writeProviderFile(name, provider, migratedValues); |
| 402 | } |
| 403 | } |
| 404 | } |
| 405 | const stamp = DateTime.formatIso(yield* DateTime.now) |
| 406 | .replaceAll(":", "-") |
| 407 | .replaceAll(".", "-"); |
| 408 | const backup = pathService.join(rootDir(), `.profiles-v0-${stamp}`); |
| 409 | yield* fs.makeDirectory(backup, { recursive: true }); |
| 410 | yield* fs.chmod(backup, 0o700); |
| 411 | yield* fs.rename(legacy, pathService.join(backup, "profiles.json")); |
| 412 | const credentials = credentialsDirPath(); |
| 413 | if (yield* fs.exists(credentials)) { |
| 414 | yield* fs.rename(credentials, pathService.join(backup, "credentials")); |
| 415 | } |
| 416 | }), |
| 417 | ), |
| 418 | ); |
| 419 | |
| 420 | /** |
| 421 | * Expand the released v0 store and preserve every original file. Checked |
| 422 | * once per process, on the first profile read, rather than on every read. |
| 423 | */ |
| 424 | const migrateCentralManifest = yield* Effect.cached(migrateCentralManifestLocked); |
| 425 | |
| 426 | const readProviderFile = (profile: string, file: string) => |
| 427 | Effect.gen(function* () { |
| 428 | const fullPath = pathService.join(profileDirPath(profile), file); |
| 429 | const json = yield* decodeJson(fullPath); |
| 430 | const document = yield* Schema.decodeUnknownEffect(ProviderProfileFileSchema)(json).pipe( |
| 431 | Effect.mapError((cause) => |
| 432 | ProfileError.make({ |
| 433 | message: `Invalid provider profile at '${fullPath}'.`, |
| 434 | cause, |
| 435 | }), |
| 436 | ), |
| 437 | ); |
| 438 | const filenameProvider = file.slice(0, -".json".length); |
| 439 | if (document.provider.toLowerCase() !== filenameProvider) { |
| 440 | return yield* ProfileError.make({ |
| 441 | message: `Provider '${document.provider}' in '${fullPath}' does not match lowercase filename '${filenameProvider}'.`, |
| 442 | }); |
| 443 | } |
| 444 | return document; |
| 445 | }); |
| 446 | |
| 447 | const readManifest = Effect.gen(function* () { |
| 448 | yield* migrateCentralManifest; |
| 449 | const manifest = emptyManifest(); |
| 450 | const names = yield* fs |
| 451 | .readDirectory(profilesDirPath()) |
| 452 | .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed<string[]>([]))); |
| 453 | for (const name of names) { |
| 454 | if (!PROFILE_NAME_PATTERN.test(name)) continue; |
| 455 | const info = yield* fs.stat(profileDirPath(name)); |
| 456 | if (info.type !== "Directory") continue; |
| 457 | const providers: Record<string, ProviderConfig> = {}; |
| 458 | const files = yield* fs.readDirectory(profileDirPath(name)); |
| 459 | for (const file of files.sort()) { |
| 460 | if (!file.endsWith(".json")) continue; |
| 461 | const read = yield* Effect.result(readProviderFile(name, file)); |
| 462 | if (Result.isFailure(read)) { |
| 463 | yield* backupInvalidProfileFile( |
| 464 | pathService.join(profileDirPath(name), file), |
| 465 | read.failure, |
| 466 | ); |
| 467 | continue; |
| 468 | } |
| 469 | providers[read.success.provider] = read.success.values; |
| 470 | } |
| 471 | manifest.profiles[name] = { id: name, providers }; |
| 472 | } |
| 473 | return manifest; |
| 474 | }); |
| 475 | |
| 476 | const getProfile = (name: string) => |
| 477 | validateProfileName(name).pipe( |
| 478 | Effect.andThen(readManifest), |
| 479 | Effect.map((manifest) => manifest.profiles[name]), |
| 480 | ); |
| 481 | |
| 482 | const ensureProfile = (name: string) => |
| 483 | getProfile(name).pipe( |
| 484 | Effect.flatMap((profile) => |
| 485 | profile === undefined |
| 486 | ? Effect.flatMap(profileNotFound(name), Effect.fail) |
| 487 | : Effect.succeed(profile), |
| 488 | ), |
| 489 | ); |
| 490 | |
| 491 | const createProfile = (name: string) => |
| 492 | validateProfileName(name).pipe( |
| 493 | Effect.flatMap(() => |
| 494 | provideLockServices( |
| 495 | withLock( |
| 496 | "profiles", |
| 497 | Effect.gen(function* () { |
| 498 | const existing = (yield* readManifest).profiles[name]; |
| 499 | if (existing !== undefined) { |
| 500 | return yield* ProfileError.make({ |
| 501 | message: `Profile '${name}' already exists.`, |
| 502 | }); |
| 503 | } |
| 504 | yield* fs.makeDirectory(profileDirPath(name), { |
| 505 | recursive: true, |
| 506 | }); |
| 507 | yield* fs.chmod(profileDirPath(name), 0o700); |
| 508 | }), |
| 509 | ), |
| 510 | ), |
| 511 | ), |
| 512 | ); |
| 513 | |
| 514 | const renameProfile = (name: string, newName: string) => |
| 515 | Effect.gen(function* () { |
| 516 | if (name === DEFAULT_PROFILE_NAME) { |
| 517 | return yield* cannotRenameDefaultProfile(); |
| 518 | } |
| 519 | yield* validateProfileName(name); |
| 520 | yield* validateProfileName(newName); |
| 521 | yield* provideLockServices( |
| 522 | withLock( |
| 523 | "profiles", |
| 524 | Effect.gen(function* () { |
| 525 | const manifest = yield* readManifest; |
| 526 | if (manifest.profiles[name] === undefined) { |
| 527 | return yield* ProfileError.make({ |
| 528 | message: `Profile '${name}' does not exist.`, |
| 529 | }); |
| 530 | } |
| 531 | if (manifest.profiles[newName] !== undefined) { |
| 532 | return yield* ProfileError.make({ |
| 533 | message: `Profile '${newName}' already exists.`, |
| 534 | }); |
| 535 | } |
| 536 | yield* fs.rename(profileDirPath(name), profileDirPath(newName)); |
| 537 | const oldCredentials = profileCredentialsDirPath(name); |
| 538 | if (yield* fs.exists(oldCredentials)) { |
| 539 | yield* fs.rename(oldCredentials, profileCredentialsDirPath(newName)); |
| 540 | } |
| 541 | }), |
| 542 | ), |
| 543 | ); |
| 544 | }); |
| 545 | |
| 546 | const current: Effect.Effect<ProfileSelection, ProfileError | PlatformError> = Effect.gen( |
| 547 | function* () { |
| 548 | const configured = yield* Config.option(ALCHEMY_PROFILE).pipe( |
| 549 | Effect.mapError((cause) => |
| 550 | ProfileError.make({ |
| 551 | message: "Could not resolve ALCHEMY_PROFILE.", |
| 552 | cause, |
| 553 | }), |
| 554 | ), |
| 555 | ); |
| 556 | if (Option.isSome(configured)) { |
| 557 | return { |
| 558 | name: yield* validateProfileName(configured.value), |
| 559 | source: "configuration" as const, |
| 560 | }; |
| 561 | } |
| 562 | return { name: DEFAULT_PROFILE_NAME, source: "default" as const }; |
| 563 | }, |
| 564 | ); |
| 565 | |
| 566 | const setProviderConfig = (profile: string, provider: string, values: ProviderConfig) => |
| 567 | Effect.gen(function* () { |
| 568 | yield* validateProfileName(profile); |
| 569 | yield* validateProviderName(provider); |
| 570 | yield* provideLockServices( |
| 571 | withLock( |
| 572 | "profiles", |
| 573 | Effect.gen(function* () { |
| 574 | if ((yield* readManifest).profiles[profile] === undefined) { |
| 575 | return yield* Effect.flatMap(profileNotFound(profile), Effect.fail); |
| 576 | } |
| 577 | const file = profileProviderFilePath(profile, provider); |
| 578 | let previous: ProviderProfileFile | undefined; |
| 579 | if (yield* fs.exists(file)) { |
| 580 | const read = yield* Effect.result( |
| 581 | readProviderFile(profile, `${provider.toLowerCase()}.json`), |
| 582 | ); |
| 583 | if (Result.isFailure(read)) { |
| 584 | yield* backupInvalidProfileFile(file, read.failure); |
| 585 | } else { |
| 586 | previous = read.success; |
| 587 | } |
| 588 | } |
| 589 | yield* writeProviderFile(profile, provider, values, previous); |
| 590 | }), |
| 591 | ), |
| 592 | ); |
| 593 | }); |
| 594 | |
| 595 | const deleteProviderConfig = (profile: string, provider: string) => |
| 596 | Effect.gen(function* () { |
| 597 | yield* validateProfileName(profile); |
| 598 | yield* validateProviderName(provider); |
| 599 | return yield* provideLockServices( |
| 600 | withLock( |
| 601 | "profiles", |
| 602 | Effect.gen(function* () { |
| 603 | const file = profileProviderFilePath(profile, provider); |
| 604 | if (!(yield* fs.exists(file))) return false; |
| 605 | yield* fs.remove(file); |
| 606 | return true; |
| 607 | }), |
| 608 | ), |
| 609 | ); |
| 610 | }); |
| 611 | |
| 612 | const deleteProfile = (name: string): Effect.Effect<boolean, ProfileError | PlatformError> => |
| 613 | Effect.gen(function* () { |
| 614 | yield* validateProfileName(name); |
| 615 | if (name === DEFAULT_PROFILE_NAME) { |
| 616 | return yield* cannotDeleteDefaultProfile(); |
| 617 | } |
| 618 | return yield* provideLockServices( |
| 619 | withLock( |
| 620 | "profiles", |
| 621 | Effect.gen(function* () { |
| 622 | const dir = profileDirPath(name); |
| 623 | if (!(yield* fs.exists(dir))) return false; |
| 624 | yield* fs.remove(dir, { recursive: true }); |
| 625 | const credentials = profileCredentialsDirPath(name); |
| 626 | if (yield* fs.exists(credentials)) { |
| 627 | yield* fs.remove(credentials, { recursive: true }); |
| 628 | } |
| 629 | return true; |
| 630 | }), |
| 631 | ), |
| 632 | ); |
| 633 | }); |
| 634 | |
| 635 | const loadProviderConfig = <Config extends { method: string }>( |
| 636 | auth: AuthProvider<Config>, |
| 637 | profileName: string, |
| 638 | ) => |
| 639 | Effect.gen(function* () { |
| 640 | const existing = yield* ensureProfile(profileName); |
| 641 | const stored = existing.providers[auth.name]; |
| 642 | if (stored !== undefined) { |
| 643 | return yield* auth.decodeConfig(profileName, stored); |
| 644 | } |
| 645 | if (yield* SuppressMissingProviderConfig) { |
| 646 | return yield* MissingProviderConfig.make({ |
| 647 | provider: auth.name, |
| 648 | profileName, |
| 649 | message: `Provider '${auth.name}' is not configured in profile '${profileName}'.`, |
| 650 | }); |
| 651 | } |
| 652 | const command = yield* profileCommandHint( |
| 653 | `alchemy profile edit --profile ${profileName} --add ${auth.name}`, |
| 654 | ); |
| 655 | return yield* AuthError.make({ |
| 656 | message: `Provider '${auth.name}' is not configured in profile '${profileName}'. Run \`${command}\`.`, |
| 657 | }); |
| 658 | }); |
| 659 | |
| 660 | return { |
| 661 | readManifest, |
| 662 | getProfile, |
| 663 | ensureProfile, |
| 664 | createProfile, |
| 665 | renameProfile, |
| 666 | current, |
| 667 | setProviderConfig, |
| 668 | deleteProviderConfig, |
| 669 | deleteProfile, |
| 670 | loadProviderConfig, |
| 671 | } satisfies ProfileStoreService; |
| 672 | }), |
| 673 | ); |
| 674 | |
| 675 | /** |
| 676 | * Re-read a provider's stored configuration, failing only with |
| 677 | * {@link AuthError}. Silent refreshes rotate single-use refresh tokens, so |
| 678 | * {@link AuthProvider.read}/{@link AuthProvider.details} take this effect and |
| 679 | * run it under the profile's credentials lock instead of a config read before |
| 680 | * it. |
| 681 | */ |
| 682 | export const reloadProviderConfig = <Config extends { method: string }>( |
| 683 | store: ProfileStoreService, |
| 684 | auth: AuthProvider<Config>, |
| 685 | profileName: string, |
| 686 | ): Effect.Effect<Config, AuthError> => |
| 687 | store.loadProviderConfig(auth, profileName).pipe( |
| 688 | Effect.mapError((cause) => |
| 689 | cause._tag === "AuthError" |
| 690 | ? cause |
| 691 | : AuthError.make({ |
| 692 | message: `Could not reload ${auth.name} configuration for profile '${profileName}'.`, |
| 693 | cause, |
| 694 | }), |
| 695 | ), |
| 696 | ); |
| 697 | |
| 698 | /** The name of the currently selected profile. */ |
| 699 | export const currentProfileName: Effect.Effect<string, ProfileError | PlatformError, ProfileStore> = |
| 700 | ProfileStore.use((store) => store.current).pipe(Effect.map((selection) => selection.name)); |