The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,130 lines 41 KB
Raw
1 import * as NodeCrypto from "node:crypto";
2 import * as NodeOs from "node:os";
3 import * as DistilledAuth from "@distilled.cloud/aws/Auth";
4 import type { CredentialsError } from "@distilled.cloud/aws/Credentials";
5 import {
6 AwsCredentialProviderError,
7 Credentials,
8 ExpiredSSOToken,
9 InvalidSSOToken,
10 } from "@distilled.cloud/aws/Credentials";
11 import * as STS from "@distilled.cloud/aws/sts";
12 import {
13 AuthError,
14 AuthProviderLayer,
15 NeedsReauth,
16 reconfigureHint,
17 refreshHint,
18 type ConfigureField,
19 type ConfigureMethod,
20 type ProviderDetailLine,
21 } from "alchemy/Auth/AuthProvider";
22 import { displayRedacted } from "alchemy/Auth/Credentials";
23 import {
24 getEnv,
25 getEnvRedacted,
26 getEnvRedactedRequired,
27 getEnvRequired,
28 mapPromptCancellation,
29 } from "alchemy/Auth/Env";
30 import {
31 storedSecret,
32 storedValueText,
33 validateFieldValues,
34 } from "alchemy/Auth/StoredAuthProvider";
35 import * as Interaction from "alchemy/Interaction";
36 import { exec } from "alchemy/Util/exec";
37 import * as EffectConsole from "effect/Console";
38 import * as Deferred from "effect/Deferred";
39 import * as Effect from "effect/Effect";
40 import * as Fiber from "effect/Fiber";
41 import * as FileSystem from "effect/FileSystem";
42 import type * as HttpClient from "effect/http/HttpClient";
43 import * as Layer from "effect/Layer";
44 import * as Match from "effect/Match";
45 import * as Option from "effect/Option";
46 import * as Path from "effect/Path";
47 import { ChildProcess } from "effect/process";
48 import type { ChildProcessSpawner } from "effect/process/ChildProcessSpawner";
49 import * as Redacted from "effect/Redacted";
50 import * as Ref from "effect/Ref";
51 import * as Schema from "effect/Schema";
52 import * as Stream from "effect/Stream";
53 import * as Endpoint from "./Endpoint.ts";
54 import * as Floci from "./Local/Floci.ts";
55 import * as Region from "./Region.ts";
56
57 export const AWS_AUTH_PROVIDER_NAME = "AWS";
58 export const DEFAULT_LOCAL_ENDPOINT = `http://localhost:${Floci.DEFAULT_FLOCI_PORT}`;
59
60 /**
61 * Dummy account stamped on every floci environment.
62 * A custom `AWS_ENDPOINT_URL` on env/sso/login credentials does NOT use this —
63 * those keep the real account from STS / `AWS_ACCOUNT_ID`.
64 */
65 export const LOCAL_ACCOUNT_ID = "000000000000";
66
67 /**
68 * distilled's SSO credential loader `Console.log`s its expired-token
69 * diagnostic in addition to failing with the typed `ExpiredSSOToken`. The
70 * typed error already carries the same message (and the profile UI surfaces
71 * it as a reauth diagnostic), so the raw console write only smears over the
72 * Interaction renderer. Provide this no-op Console on every distilled
73 * `loadProfileCredentials` call so distilled has nowhere to print.
74 */
75 const noop = () => {};
76 export const silentConsole: EffectConsole.Console = {
77 assert: noop,
78 clear: noop,
79 count: noop,
80 countReset: noop,
81 debug: noop,
82 dir: noop,
83 dirxml: noop,
84 error: noop,
85 group: noop,
86 groupCollapsed: noop,
87 groupEnd: noop,
88 info: noop,
89 log: noop,
90 table: noop,
91 time: noop,
92 timeEnd: noop,
93 timeLog: noop,
94 trace: noop,
95 warn: noop,
96 };
97
98 /** Typed values stored in an AWS provider profile document. */
99 export const AwsAuthConfigSchema = Schema.Union([
100 Schema.Struct({
101 method: Schema.Literal("sso"),
102 ssoProfile: Schema.String,
103 authorizationMethod: Schema.optional(
104 Schema.Union([Schema.Literal("oauth"), Schema.Literal("device")]),
105 ),
106 }),
107 Schema.Struct({
108 method: Schema.Literal("console-login"),
109 loginProfile: Schema.String,
110 /** Backfilled from STS on first use so later runs skip the call. */
111 accountId: Schema.optional(Schema.String),
112 }),
113 Schema.Struct({
114 method: Schema.Literal("stored"),
115 accountId: Schema.optional(Schema.String),
116 accessKeyId: Schema.String,
117 secretAccessKey: Schema.String,
118 sessionToken: Schema.optional(Schema.String),
119 region: Schema.String,
120 }),
121 ]);
122 export type AwsAuthConfig = typeof AwsAuthConfigSchema.Type;
123
124 const options: Array<{
125 value: AwsAuthConfig["method"];
126 label: string;
127 description?: string;
128 }> = [
129 {
130 value: "sso",
131 label: "SSO",
132 description: "sign in with an AWS IAM Identity Center profile",
133 },
134 {
135 value: "console-login",
136 label: "Console login",
137 description: "sign in with AWS Management Console credentials (aws login)",
138 },
139 {
140 value: "stored",
141 label: "Access Keys",
142 description: "enter an access key and secret directly",
143 },
144 ];
145
146 /** `--set` fields for `--method stored` (static access keys, persisted). */
147 const keysFields: ReadonlyArray<ConfigureField> = [
148 { name: "accessKeyId", label: "AWS Access Key ID" },
149 { name: "secretAccessKey", label: "AWS Secret Access Key", secret: true },
150 {
151 name: "sessionToken",
152 label: "AWS Session Token",
153 secret: true,
154 optional: true,
155 },
156 { name: "region", label: "AWS Region", placeholder: "us-east-1" },
157 ];
158
159 /** `--set` fields for `--method sso` (nothing persisted; profile validated). */
160 const ssoFields: ReadonlyArray<ConfigureField> = [
161 { name: "ssoProfile", label: "AWS profile name (from ~/.aws/config)" },
162 ];
163
164 /** `--set` fields for `--method console-login` (nothing persisted; profile validated). */
165 const loginFields: ReadonlyArray<ConfigureField> = [
166 { name: "loginProfile", label: "AWS profile name (from ~/.aws/config)" },
167 ];
168
169 const configureMethods: ReadonlyArray<ConfigureMethod> = [
170 { method: "stored", fields: keysFields },
171 { method: "sso", fields: ssoFields },
172 { method: "console-login", fields: loginFields },
173 ];
174
175 export interface AwsResolvedCredentials {
176 accountId: string;
177 credentials: Effect.Effect<AwsCredentials, CredentialsError>;
178 region: string;
179 endpoint?: string;
180 source: {
181 type: AwsAuthConfig["method"] | "env";
182 details?: string;
183 };
184 }
185
186 interface AwsCredentials {
187 accessKeyId: Redacted.Redacted<string>;
188 secretAccessKey: Redacted.Redacted<string>;
189 sessionToken: Redacted.Redacted<string> | undefined;
190 region: string;
191 }
192
193 /**
194 * An explicitly-set `AWS_REGION` env var wins over the region recorded in an
195 * AWS CLI profile (`~/.aws/config`) or in stored credentials. `AWS_DEFAULT_REGION`
196 * deliberately does NOT override — it is a *default* for when no region is
197 * configured anywhere, and the profile's region is explicit configuration.
198 */
199 export const applyEnvRegionOverride = <C extends { region: string }>(
200 creds: C,
201 ): Effect.Effect<C, AuthError> =>
202 getEnv("AWS_REGION").pipe(
203 Effect.map((envRegion) => (envRegion ? { ...creds, region: envRegion } : creds)),
204 );
205
206 /** The account behind a set of credentials, via STS `GetCallerIdentity`. */
207 export const getAccountId = ({
208 accessKeyId,
209 secretAccessKey,
210 sessionToken,
211 region,
212 }: {
213 accessKeyId: Redacted.Redacted<string>;
214 secretAccessKey: Redacted.Redacted<string>;
215 sessionToken?: Redacted.Redacted<string>;
216 region: string;
217 }) =>
218 STS.getCallerIdentity({}).pipe(
219 Effect.provide(
220 Layer.mergeAll(
221 Layer.succeed(
222 Credentials,
223 Effect.succeed({
224 accessKeyId,
225 secretAccessKey,
226 sessionToken,
227 region,
228 }),
229 ),
230 // Provide Region directly from the resolved inputs. Relying on the
231 // ambient Region provider (Region.fromEnvironment) here would
232 // deadlock: it derives the region from AWSEnvironment, which is the
233 // very service still being constructed by this STS call.
234 Region.of(region),
235 // Provide `Endpoint.none` rather than leaving it unset: falling
236 // through to the ambient `Endpoint.fromEnvironment` reads it off
237 // AWSEnvironment — the very service this STS call is
238 // constructing — and deadlocks the fiber on its own in-flight
239 // cache (no I/O, no timer, no output). Same reason as
240 // `Region.of` above.
241 Endpoint.none,
242 ),
243 ),
244 Effect.flatMap((self) =>
245 self.Account ? Effect.succeed(self.Account) : Effect.die(new Error("No account ID found")),
246 ),
247 );
248
249 /**
250 * Layer that registers the AWS {@link AuthProvider} into the
251 * {@link AuthProviders} registry when built. Include this in the AWS
252 * `providers()` layer so the alchemy CLI can discover it.
253 */
254 export const AwsAuth = AuthProviderLayer<AwsAuthConfig, AwsResolvedCredentials>()(
255 AWS_AUTH_PROVIDER_NAME,
256 Effect.gen(function* () {
257 const loginStored = Effect.fn(function* () {
258 const accessKeyId = yield* Interaction.text({
259 message: "AWS Access Key ID",
260 validate: (v) => (v.length === 0 ? "Required" : undefined),
261 }).pipe(mapPromptCancellation);
262
263 const secretAccessKey = yield* Interaction.password({
264 message: "AWS Secret Access Key",
265 validate: (v) => (v.length === 0 ? "Required" : undefined),
266 }).pipe(mapPromptCancellation);
267
268 const sessionToken = yield* Interaction.password({
269 message: "AWS Session Token (optional; press Enter to skip)",
270 placeholder: "(none)",
271 }).pipe(mapPromptCancellation);
272
273 const region = yield* Interaction.text({
274 message: "AWS Region",
275 placeholder: "us-east-1",
276 defaultValue: "us-east-1",
277 }).pipe(mapPromptCancellation);
278
279 const accountId = yield* getAccountId({
280 accessKeyId: Redacted.make(accessKeyId),
281 secretAccessKey: Redacted.make(secretAccessKey),
282 sessionToken: sessionToken ? Redacted.make(sessionToken) : undefined,
283 region,
284 });
285
286 yield* Interaction.success("AWS credentials saved.");
287
288 return {
289 method: "stored" as const,
290 accountId,
291 accessKeyId,
292 secretAccessKey,
293 sessionToken: sessionToken || undefined,
294 region,
295 };
296 });
297
298 const configureInteractive = () =>
299 Interaction.select({
300 message: "AWS authentication method",
301 options,
302 }).pipe(
303 Effect.flatMap((method) =>
304 Match.value(method).pipe(
305 Match.when("sso", () =>
306 Effect.gen(function* () {
307 const ssoProfile = yield* Interaction.text({
308 message: "AWS profile name (from ~/.aws/config)",
309 placeholder: "default",
310 defaultValue: "default",
311 });
312 const authorizationMethod = yield* Interaction.select({
313 message: "AWS SSO authorization method",
314 options: [
315 {
316 value: "oauth" as const,
317 label: "Browser OAuth",
318 description: "authorize in this device's browser",
319 },
320 {
321 value: "device" as const,
322 label: "Device code",
323 description: "authorize with a short code on any device",
324 },
325 ],
326 });
327
328 const config = {
329 method: "sso" as const,
330 ssoProfile: ssoProfile ?? "default",
331 authorizationMethod,
332 };
333
334 yield* loginSSO(config, authorizationMethod);
335
336 return config;
337 }),
338 ),
339 Match.when("console-login", () =>
340 Effect.gen(function* () {
341 const loginProfile = yield* Interaction.text({
342 message: "AWS profile name (from ~/.aws/config)",
343 placeholder: "default",
344 defaultValue: "default",
345 });
346 const config = {
347 method: "console-login" as const,
348 loginProfile: loginProfile ?? "default",
349 };
350 yield* loginConsole(config);
351 return config;
352 }),
353 ),
354 Match.when("stored", () => loginStored()),
355 Match.exhaustive,
356 ),
357 ),
358 );
359
360 // The declared requirements are the union of the interactive path
361 // (ChildProcessSpawner for `aws sso login`) and `configureWith`'s
362 // (FileSystem/Path for ~/.aws/config probing) — the contract shares one
363 // ConfigureReq type parameter between the two entry points.
364 const configureCredentials = (): Effect.Effect<
365 AwsAuthConfig,
366 AuthError,
367 | ChildProcessSpawner
368 | HttpClient.HttpClient
369 | FileSystem.FileSystem
370 | Path.Path
371 | Interaction.Interaction
372 > =>
373 configureInteractive().pipe(
374 Effect.mapError((e) =>
375 Schema.is(AuthError)(e)
376 ? e
377 : AuthError.make({
378 message: "failed to configure credentials",
379 cause: e,
380 }),
381 ),
382 );
383
384 const configureWith = (
385 profileName: string,
386 input: {
387 readonly method: string;
388 readonly values: Record<string, string>;
389 },
390 ) =>
391 Match.value(input.method).pipe(
392 Match.when("stored", () =>
393 Effect.gen(function* () {
394 const values = yield* validateFieldValues(
395 AWS_AUTH_PROVIDER_NAME,
396 keysFields,
397 input.values,
398 );
399 // validateFieldValues guarantees the required fields are present.
400 const accessKeyId = storedSecret(values.accessKeyId);
401 const secretAccessKey = storedSecret(values.secretAccessKey);
402 const sessionToken = storedSecret(values.sessionToken);
403 const region = storedValueText(values.region) ?? "";
404 if (accessKeyId === undefined || secretAccessKey === undefined) {
405 return yield* AuthError.make({
406 message: "AWS: required key fields are missing.",
407 });
408 }
409 const accountId = yield* getAccountId({
410 accessKeyId,
411 secretAccessKey,
412 sessionToken,
413 region,
414 }).pipe(
415 Effect.mapError((cause) =>
416 AuthError.make({
417 message: "AWS: failed to verify credentials via STS GetCallerIdentity.",
418 cause,
419 }),
420 ),
421 );
422 return {
423 method: "stored" as const,
424 accountId,
425 accessKeyId: Redacted.value(accessKeyId),
426 secretAccessKey: Redacted.value(secretAccessKey),
427 sessionToken: sessionToken === undefined ? undefined : Redacted.value(sessionToken),
428 region,
429 };
430 }),
431 ),
432 Match.when("sso", () =>
433 Effect.gen(function* () {
434 const values = yield* validateFieldValues(
435 AWS_AUTH_PROVIDER_NAME,
436 ssoFields,
437 input.values,
438 );
439 const ssoProfile = storedValueText(values.ssoProfile) ?? "";
440 const auth = yield* DistilledAuth.Default;
441 const profile = yield* auth
442 .loadProfile(ssoProfile)
443 .pipe(Effect.orElseSucceed(() => undefined));
444 if (profile == null) {
445 return yield* AuthError.make({
446 message: `AWS SSO profile '${ssoProfile}' was not found in ~/.aws/config. Configure it with \`aws configure sso\` first, then log in. ${refreshHint(AWS_AUTH_PROVIDER_NAME, profileName)}`,
447 });
448 }
449 // Nothing is persisted for SSO — credentials come from the AWS
450 // SSO cache. `aws sso login` is interactive, so it is NOT run
451 // here; the user runs `alchemy profile refresh` afterwards.
452 return { method: "sso" as const, ssoProfile };
453 }),
454 ),
455 Match.when("console-login", () =>
456 Effect.gen(function* () {
457 const values = yield* validateFieldValues(
458 AWS_AUTH_PROVIDER_NAME,
459 loginFields,
460 input.values,
461 );
462 const loginProfile = storedValueText(values.loginProfile) ?? "";
463 yield* loadLoginProfile(loginProfile);
464 // Nothing is persisted — the AWS CLI owns the console session.
465 // `aws login` is interactive, so it is NOT run here; the user
466 // runs `alchemy profile refresh` afterwards.
467 return { method: "console-login" as const, loginProfile };
468 }),
469 ),
470 Match.orElse(() =>
471 Effect.fail(
472 AuthError.make({
473 message: `AWS: unknown method '${input.method}'. Valid methods: stored, sso, console-login.`,
474 }),
475 ),
476 ),
477 );
478
479 const resolveCredentials = (
480 profileName: string,
481 config: AwsAuthConfig,
482 updateConfig?: (config: AwsAuthConfig) => Effect.Effect<void, AuthError>,
483 ) =>
484 Effect.gen(function* () {
485 const reauth = refreshHint(AWS_AUTH_PROVIDER_NAME, profileName);
486 return yield* Match.value(config).pipe(
487 Match.when({ method: "stored" }, (config) =>
488 Effect.gen(function* () {
489 const credentials: AwsCredentials = {
490 accessKeyId: Redacted.make(config.accessKeyId),
491 secretAccessKey: Redacted.make(config.secretAccessKey),
492 sessionToken:
493 config.sessionToken === undefined
494 ? undefined
495 : Redacted.make(config.sessionToken),
496 region: config.region,
497 };
498 const accountId = config.accountId ?? (yield* getAccountId(credentials));
499 if (config.accountId === undefined && updateConfig !== undefined) {
500 yield* updateConfig({ ...config, accountId });
501 }
502 return {
503 accountId,
504 credentials: Effect.succeed(credentials),
505 region: config.region,
506 source: { type: "stored" as const },
507 } satisfies AwsResolvedCredentials;
508 }),
509 ),
510 Match.when({ method: "sso" }, (config) =>
511 Effect.gen(function* () {
512 const auth = yield* DistilledAuth.Default;
513 const profile = yield* auth
514 .loadProfile(config.ssoProfile)
515 .pipe(Effect.orElseSucceed(() => undefined));
516 if (profile?.sso_account_id == null) {
517 const reconfigure = reconfigureHint(AWS_AUTH_PROVIDER_NAME, profileName);
518 return yield* AuthError.make({
519 message:
520 profile == null
521 ? `AWS SSO profile '${config.ssoProfile}' was not found in ~/.aws/config. Configure it with \`aws configure sso\`. ${reconfigure}`
522 : `AWS SSO profile '${config.ssoProfile}' has no sso_account_id in ~/.aws/config. Add it. ${reconfigure}`,
523 });
524 }
525 // `applyEnvRegionOverride` below only overrides an existing
526 // region, so an env-provided region must be consulted here for
527 // profiles that don't record one.
528 const region = profile.region ?? (yield* getEnv("AWS_REGION"));
529 if (!region) {
530 return yield* AuthError.make({
531 message: `AWS SSO profile '${config.ssoProfile}' has no region in ~/.aws/config and AWS_REGION is not set.`,
532 });
533 }
534 return {
535 accountId: profile.sso_account_id,
536 // Rewrite the message of an expired/invalid SSO token to the
537 // alchemy refresh hint, but PRESERVE the error tags: the inner
538 // effect must stay a `CredentialsError` for downstream
539 // consumers (AWSEnvironment), while `details` and other
540 // in-provider consumers match these tags to surface a typed
541 // `NeedsReauth` instead of a generic failure.
542 credentials: auth.loadProfileCredentials(config.ssoProfile).pipe(
543 Effect.provideService(EffectConsole.Console, silentConsole),
544 Effect.mapError((error) => {
545 if (error._tag === "Alchemy::AWS::ExpiredSSOToken") {
546 return new ExpiredSSOToken({
547 message: `AWS SSO credentials need to be refreshed. ${reauth}`,
548 profile: error.profile,
549 });
550 }
551 if (error._tag === "Alchemy::AWS::InvalidSSOToken") {
552 return new InvalidSSOToken({
553 message: `AWS SSO credentials need to be refreshed. ${reauth}`,
554 sso_session: error.sso_session,
555 });
556 }
557 return error;
558 }),
559 ),
560 region,
561 source: { type: "sso" as const, details: config.ssoProfile },
562 } satisfies AwsResolvedCredentials;
563 }),
564 ),
565 Match.when({ method: "console-login" }, (config) =>
566 Effect.gen(function* () {
567 const reconfigure = reconfigureHint(AWS_AUTH_PROVIDER_NAME, profileName);
568 const auth = yield* DistilledAuth.Default;
569 const profile = yield* loadLoginProfile(config.loginProfile).pipe(
570 Effect.mapError((cause) =>
571 AuthError.make({
572 message: `${cause.message} ${reconfigure}`,
573 cause,
574 }),
575 ),
576 );
577 const region =
578 profile.region ??
579 (yield* getEnv("AWS_REGION")) ??
580 (yield* getEnv("AWS_DEFAULT_REGION"));
581 if (!region) {
582 return yield* AuthError.make({
583 message: `AWS profile '${config.loginProfile}' has no region. Set one with \`aws configure set region <region> --profile ${config.loginProfile}\` or set AWS_REGION.`,
584 });
585 }
586 // Lazy: distilled reads the token `aws login` cached under
587 // `~/.aws/login/cache` and renews it itself when it nears
588 // expiry. A dead session surfaces as a credential-provider
589 // error; rewrite its message to the alchemy refresh hint but
590 // PRESERVE the tag (see the SSO branch) so `details` can
591 // surface a typed NeedsReauth.
592 const credentials = auth.loadProfileCredentials(config.loginProfile).pipe(
593 Effect.mapError((error) =>
594 error._tag === "AWS::CredentialProviderError"
595 ? new AwsCredentialProviderError({
596 message: `AWS console login credentials need to be refreshed. ${reauth}`,
597 provider: error.provider,
598 cause: error,
599 })
600 : error,
601 ),
602 );
603 const accountId =
604 config.accountId ??
605 (yield* getEnvRequired("AWS_ACCOUNT_ID").pipe(
606 Effect.catch(() => Effect.flatMap(credentials, getAccountId)),
607 ));
608 if (config.accountId === undefined && updateConfig !== undefined) {
609 yield* updateConfig({ ...config, accountId });
610 }
611 return {
612 accountId,
613 credentials,
614 region,
615 source: {
616 type: "console-login" as const,
617 details: config.loginProfile,
618 },
619 } satisfies AwsResolvedCredentials;
620 }),
621 ),
622 Match.exhaustive,
623 // Pass diagnosable failures through untouched: NeedsReauth (stored
624 // credentials missing) and the specific AuthErrors raised above
625 // (missing SSO profile / sso_account_id / region, missing
626 // login_session) carry the real
627 // diagnosis. Only genuinely unexpected failures (store I/O, the
628 // STS accountId backfill) get wrapped.
629 Effect.mapError((e) =>
630 e._tag === "AuthError"
631 ? e
632 : AuthError.make({
633 message: "failed to resolve AWS credentials",
634 cause: e,
635 }),
636 ),
637 Effect.flatMap(applyEnvRegionOverride),
638 Effect.map((creds): AwsResolvedCredentials => ({
639 ...creds,
640 credentials: creds.credentials.pipe(
641 Effect.map((credentials) => ({
642 ...credentials,
643 region: creds.region,
644 })),
645 ),
646 })),
647 );
648 });
649
650 const details = (
651 profileName: string,
652 config: AwsAuthConfig,
653 updateConfig?: (config: AwsAuthConfig) => Effect.Effect<void, AuthError>,
654 ) =>
655 Effect.gen(function* () {
656 const creds = yield* resolveCredentials(profileName, config, updateConfig);
657 const reauth = refreshHint(AWS_AUTH_PROVIDER_NAME, profileName);
658 // Resolve the live credentials. An expired/invalid SSO token or
659 // console-login session only surfaces here (the inner effect is lazy),
660 // so convert those into a typed NeedsReauth instead of a generic error.
661 const { accessKeyId, secretAccessKey, sessionToken } = yield* creds.credentials.pipe(
662 Effect.mapError((error) => {
663 const consoleLoginExpired =
664 creds.source.type === "console-login" &&
665 error._tag === "AWS::CredentialProviderError";
666 return error._tag === "Alchemy::AWS::ExpiredSSOToken" ||
667 error._tag === "Alchemy::AWS::InvalidSSOToken" ||
668 consoleLoginExpired
669 ? NeedsReauth.make({
670 provider: AWS_AUTH_PROVIDER_NAME,
671 profile: profileName,
672 message: `AWS ${consoleLoginExpired ? "console login" : "SSO"} credentials need to be refreshed. ${reauth}`,
673 cause: error,
674 })
675 : AuthError.make({
676 message: "failed to load AWS credentials",
677 cause: error,
678 });
679 }),
680 );
681 const lines: Array<ProviderDetailLine> = [
682 { key: "accessKeyId", value: displayRedacted(accessKeyId) },
683 { key: "secretAccessKey", value: displayRedacted(secretAccessKey) },
684 ];
685 if (sessionToken) {
686 lines.push({
687 key: "sessionToken",
688 value: displayRedacted(sessionToken),
689 });
690 }
691 if (creds.region) {
692 lines.push({ key: "region", value: creds.region });
693 }
694 const source = creds.source;
695 lines.push({
696 key: "source",
697 value: "details" in source ? `${source.type} - ${source.details}` : source.type,
698 });
699 return { lines };
700 });
701
702 const logout = (_profileName: string, config: AwsAuthConfig) =>
703 Match.value(config).pipe(
704 Match.when({ method: "sso" }, (config) =>
705 Interaction.info(`AWS: running 'aws sso logout --profile ${config.ssoProfile}'...`).pipe(
706 Effect.zip(runSsoCommand("logout", config.ssoProfile)),
707 Effect.zip(clearDistilledSsoCache(config.ssoProfile)),
708 Effect.match({
709 onSuccess: () => Interaction.success("AWS: SSO logout complete"),
710 onFailure: (e) => Interaction.warning(`AWS: SSO logout failed: \`${e.message}\``),
711 }),
712 ),
713 ),
714 Match.when({ method: "console-login" }, (config) =>
715 Interaction.info(`AWS: running 'aws logout --profile ${config.loginProfile}'...`).pipe(
716 Effect.zip(runAws(["logout", "--profile", config.loginProfile])),
717 Effect.match({
718 onSuccess: () => Interaction.success("AWS: console logout complete"),
719 onFailure: (e) => Interaction.warning(`AWS: console logout failed: \`${e.message}\``),
720 }),
721 ),
722 ),
723 Match.when({ method: "stored" }, () => Effect.void),
724 Match.exhaustive,
725 );
726
727 const login = (profileName: string, config: AwsAuthConfig) =>
728 Match.value(config).pipe(
729 Match.when({ method: "sso" }, (config) =>
730 loginSSO(config, config.authorizationMethod ?? "oauth"),
731 ),
732 Match.when({ method: "console-login" }, (config) => loginConsole(config)),
733 Match.when({ method: "stored" }, (config) => Effect.succeed(config)),
734 Match.exhaustive,
735 Effect.mapError((e) => AuthError.make({ message: `login failed: ${e.message}`, cause: e })),
736 );
737
738 const readEnvironment = Effect.gen(function* () {
739 const accessKeyId = yield* getEnvRedactedRequired("AWS_ACCESS_KEY_ID");
740 const secretAccessKey = yield* getEnvRedactedRequired("AWS_SECRET_ACCESS_KEY");
741 const sessionToken = yield* getEnvRedacted("AWS_SESSION_TOKEN");
742 const region = yield* getEnv("AWS_REGION").pipe(
743 Effect.flatMap((value) => (value ? Effect.succeed(value) : getEnv("AWS_DEFAULT_REGION"))),
744 );
745 if (!region) {
746 return yield* AuthError.make({
747 message: "AWS CI region not found. Set AWS_REGION or AWS_DEFAULT_REGION.",
748 });
749 }
750 const accountId = yield* getEnvRequired("AWS_ACCOUNT_ID").pipe(
751 Effect.catch(() =>
752 getAccountId({
753 accessKeyId,
754 secretAccessKey,
755 sessionToken,
756 region,
757 }),
758 ),
759 );
760 return {
761 accountId,
762 credentials: Effect.succeed({
763 accessKeyId,
764 secretAccessKey,
765 sessionToken,
766 region,
767 }),
768 region,
769 source: { type: "env" as const },
770 } satisfies AwsResolvedCredentials;
771 }).pipe(
772 Effect.mapError((cause) =>
773 Schema.is(AuthError)(cause)
774 ? cause
775 : AuthError.make({
776 message: "Failed to resolve AWS credentials from the CI environment.",
777 cause,
778 }),
779 ),
780 );
781
782 return {
783 configSchema: AwsAuthConfigSchema,
784 configure: configureCredentials,
785 configureWith,
786 configureMethods,
787 login,
788 logout,
789 details,
790 read: resolveCredentials,
791 readEnvironment,
792 environment: [
793 {
794 name: "AWS_ACCESS_KEY_ID",
795 required: true,
796 secret: true,
797 },
798 {
799 name: "AWS_SECRET_ACCESS_KEY",
800 required: true,
801 secret: true,
802 },
803 {
804 name: "AWS_SESSION_TOKEN",
805 required: false,
806 secret: true,
807 description: "Required when the access key is a temporary STS key.",
808 },
809 {
810 name: "AWS_REGION",
811 required: true,
812 alternatives: ["AWS_DEFAULT_REGION"],
813 description: "Region the stack deploys into.",
814 },
815 {
816 name: "AWS_ACCOUNT_ID",
817 required: false,
818 description: "Derived via STS GetCallerIdentity when unset.",
819 },
820 ],
821 };
822 }),
823 );
824
825 const runSsoCommand = (command: "login" | "logout", ssoProfile: string) =>
826 Effect.gen(function* () {
827 const handle = yield* ChildProcess.make("aws", ["sso", command, "--profile", ssoProfile], {
828 shell: false,
829 stdin: "inherit",
830 stdout: "inherit",
831 stderr: "inherit",
832 });
833 const exit = yield* handle.exitCode;
834 if (exit !== 0) {
835 return yield* AuthError.make({
836 message: `aws sso ${command} exited with code ${exit}`,
837 });
838 }
839 }).pipe(Effect.scoped);
840
841 /** Run a non-interactive `aws` command, failing on a non-zero exit. */
842 const runAws = (args: ReadonlyArray<string>) =>
843 exec(ChildProcess.make("aws", [...args])).pipe(
844 Effect.scoped,
845 Effect.flatMap(({ exitCode, stdout, stderr }) => {
846 if (exitCode === 0) return Effect.void;
847 const detail = stderr.trim() || stdout.trim();
848 return AuthError.make({
849 message: `aws ${args.join(" ")} exited with code ${exitCode}${detail === "" ? "" : `: ${detail}`}`,
850 });
851 }),
852 );
853
854 /**
855 * A `~/.aws/config` profile written by `aws login` (AWS CLI v2.32+). SSO and
856 * other profile kinds are rejected: `aws login` refuses to overwrite them.
857 */
858 const loadLoginProfile = (loginProfile: string) =>
859 DistilledAuth.loadProfile(loginProfile).pipe(
860 Effect.orElseSucceed(() => undefined),
861 Effect.flatMap((profile) =>
862 profile?.login_session
863 ? Effect.succeed(profile)
864 : AuthError.make({
865 message: `AWS profile '${loginProfile}' has no login_session in ~/.aws/config. Run \`aws login --profile ${loginProfile}\` (AWS CLI v2.32+).`,
866 }),
867 ),
868 );
869
870 const AwsSsoLoginOutput = Schema.Struct({
871 url: Schema.optional(Schema.String),
872 authUrl: Schema.optional(Schema.String),
873 authorizationUrl: Schema.optional(Schema.String),
874 verificationUri: Schema.optional(Schema.String),
875 verificationUriComplete: Schema.optional(Schema.String),
876 code: Schema.optional(Schema.String),
877 userCode: Schema.optional(Schema.String),
878 });
879
880 export const parseAwsSsoLoginOutput = (output: string) => {
881 try {
882 const decoded = Schema.decodeUnknownOption(AwsSsoLoginOutput)(JSON.parse(output) as unknown);
883 if (Option.isSome(decoded)) {
884 const event = decoded.value;
885 return {
886 url:
887 event.authorizationUrl ??
888 event.authUrl ??
889 event.verificationUriComplete ??
890 event.verificationUri ??
891 event.url,
892 code: event.userCode ?? event.code,
893 };
894 }
895 } catch {
896 // `sso login` accepts the global `--output json` option but current AWS
897 // CLI releases still render this custom command's authorization prompt as
898 // text. Keep accepting structured output if AWS starts honoring the flag.
899 }
900 return {
901 url: output.match(/https?:\/\/[^\s]+/)?.[0],
902 code: output.match(/Then enter the code:\s*([A-Z0-9-]+)/i)?.[1],
903 };
904 };
905
906 const loginSSO = (
907 config: Extract<AwsAuthConfig, { method: "sso" }>,
908 authorizationMethod: "oauth" | "device" = "oauth",
909 ) =>
910 Effect.scoped(
911 Effect.gen(function* () {
912 const interaction = yield* Interaction.Interaction;
913 const authorizationUrl = yield* Deferred.make<string>();
914 const deviceCode = yield* Deferred.make<string>();
915 const stdout = yield* Ref.make("");
916 const stderr = yield* Ref.make("");
917 const handle = yield* ChildProcess.make(
918 "aws",
919 [
920 "sso",
921 "login",
922 "--profile",
923 config.ssoProfile,
924 "--no-browser",
925 "--output",
926 "json",
927 ...(authorizationMethod === "device" ? ["--use-device-code"] : []),
928 ],
929 {
930 shell: false,
931 stdin: "ignore",
932 stdout: "pipe",
933 stderr: "pipe",
934 },
935 );
936 const collectStdout = handle.stdout.pipe(
937 Stream.decodeText(),
938 Stream.runForEach((chunk) =>
939 Effect.gen(function* () {
940 const combined = yield* Ref.updateAndGet(stdout, (current) => current + chunk);
941 const { url, code } = parseAwsSsoLoginOutput(combined);
942 if (url !== undefined) {
943 yield* Deferred.succeed(authorizationUrl, url);
944 }
945 if (code !== undefined) {
946 yield* Deferred.succeed(deviceCode, code);
947 }
948 }),
949 ),
950 );
951 const collectStderr = handle.stderr.pipe(
952 Stream.decodeText(),
953 Stream.runForEach((chunk) => Ref.update(stderr, (current) => current + chunk)),
954 );
955 const process = Effect.gen(function* () {
956 const [exitCode] = yield* Effect.all([handle.exitCode, collectStdout, collectStderr], {
957 concurrency: 3,
958 });
959 if (exitCode !== 0) {
960 const detail = (yield* Ref.get(stderr)).trim();
961 return yield* AuthError.make({
962 message: `aws sso login exited with code ${exitCode}${detail === "" ? "" : `: ${detail}`}`,
963 });
964 }
965 });
966 const processFiber = yield* Effect.forkScoped(process);
967 const url = yield* Deferred.await(authorizationUrl).pipe(
968 Effect.raceFirst(
969 Fiber.join(processFiber).pipe(
970 Effect.flatMap(() =>
971 Effect.fail(
972 AuthError.make({
973 message: "AWS SSO login completed without providing an authorization URL.",
974 }),
975 ),
976 ),
977 ),
978 ),
979 );
980 const code =
981 authorizationMethod === "device"
982 ? yield* Deferred.await(deviceCode).pipe(
983 Effect.raceFirst(
984 Fiber.join(processFiber).pipe(
985 Effect.flatMap(() =>
986 Effect.fail(
987 AuthError.make({
988 message:
989 "AWS SSO device login completed without providing an authorization code.",
990 }),
991 ),
992 ),
993 ),
994 ),
995 )
996 : undefined;
997 yield* Interaction.browserLogin({
998 provider: "AWS",
999 waitingLabel:
1000 authorizationMethod === "device"
1001 ? "waiting for device authorization (up to 5 minutes)…"
1002 : "waiting for browser authorization (up to 5 minutes)…",
1003 url,
1004 code,
1005 waitFor: Fiber.join(processFiber),
1006 });
1007 yield* interaction.output.success("AWS SSO: login complete");
1008 }),
1009 );
1010
1011 /**
1012 * `aws login` (AWS CLI v2.32+) opens the browser itself and waits on a
1013 * localhost callback. There is no `--no-browser` flag, so this pipes the
1014 * CLI's URL prompt into the same authorization screen as SSO login and
1015 * passes `--region` so the CLI does not take over the terminal to ask.
1016 * The profile's region is written afterwards when it did not already
1017 * have one — `aws login` only persists a region it prompted for itself.
1018 */
1019 const loginConsole = (config: Extract<AwsAuthConfig, { method: "console-login" }>) =>
1020 Effect.scoped(
1021 Effect.gen(function* () {
1022 const interaction = yield* Interaction.Interaction;
1023 const existing = yield* DistilledAuth.loadProfile(config.loginProfile).pipe(
1024 Effect.orElseSucceed(() => undefined),
1025 );
1026 const region =
1027 existing?.region ??
1028 (yield* getEnv("AWS_REGION")) ??
1029 (yield* getEnv("AWS_DEFAULT_REGION")) ??
1030 (yield* interaction.prompt
1031 .text({
1032 message: "AWS Region",
1033 placeholder: "us-east-1",
1034 defaultValue: "us-east-1",
1035 })
1036 .pipe(mapPromptCancellation)) ??
1037 "us-east-1";
1038
1039 const authorizationUrl = yield* Deferred.make<string>();
1040 const stdout = yield* Ref.make("");
1041 const stderr = yield* Ref.make("");
1042 const handle = yield* ChildProcess.make(
1043 "aws",
1044 ["login", "--profile", config.loginProfile, "--region", region],
1045 {
1046 shell: false,
1047 stdin: "ignore",
1048 stdout: "pipe",
1049 stderr: "pipe",
1050 },
1051 );
1052 const collectStdout = handle.stdout.pipe(
1053 Stream.decodeText(),
1054 Stream.runForEach((chunk) =>
1055 Effect.gen(function* () {
1056 const combined = yield* Ref.updateAndGet(stdout, (current) => current + chunk);
1057 const { url } = parseAwsSsoLoginOutput(combined);
1058 if (url !== undefined) {
1059 yield* Deferred.succeed(authorizationUrl, url);
1060 }
1061 }),
1062 ),
1063 );
1064 const collectStderr = handle.stderr.pipe(
1065 Stream.decodeText(),
1066 Stream.runForEach((chunk) => Ref.update(stderr, (current) => current + chunk)),
1067 );
1068 const process = Effect.gen(function* () {
1069 const [exitCode] = yield* Effect.all([handle.exitCode, collectStdout, collectStderr], {
1070 concurrency: 3,
1071 });
1072 if (exitCode !== 0) {
1073 const detail = (yield* Ref.get(stderr)).trim();
1074 return yield* AuthError.make({
1075 message: `aws login exited with code ${exitCode}${detail === "" ? "" : `: ${detail}`}`,
1076 });
1077 }
1078 });
1079 const processFiber = yield* Effect.forkScoped(process);
1080 const url = yield* Deferred.await(authorizationUrl).pipe(
1081 Effect.raceFirst(
1082 Fiber.join(processFiber).pipe(
1083 Effect.flatMap(() =>
1084 Effect.fail(
1085 AuthError.make({
1086 message: "AWS console login completed without providing an authorization URL.",
1087 }),
1088 ),
1089 ),
1090 ),
1091 ),
1092 );
1093 yield* Interaction.browserLogin({
1094 provider: "AWS",
1095 waitingLabel: "waiting for browser authorization (up to 10 minutes)…",
1096 url,
1097 waitFor: Fiber.join(processFiber),
1098 });
1099 if (existing?.region === undefined) {
1100 yield* runAws(["configure", "set", "region", region, "--profile", config.loginProfile]);
1101 }
1102 yield* interaction.output.success("AWS: console login complete");
1103 }),
1104 );
1105
1106 /**
1107 * `aws sso logout` only clears AWS CLI's own caches — it does not know about the
1108 * `<sha1(sso_session)>.credentials.json` file that `@distilled.cloud/aws`
1109 * writes alongside the SSO token. Without this cleanup, `loadProfileCredentials`
1110 * short-circuits on the stale distilled cache file after logout and appears to
1111 * stay logged in until the role creds hit their TTL.
1112 */
1113 const clearDistilledSsoCache = (ssoProfile: string) =>
1114 Effect.gen(function* () {
1115 const auth = yield* DistilledAuth.Default;
1116 const profile = yield* auth.loadProfile(ssoProfile);
1117 const ssoSession = (profile as { sso_session?: string }).sso_session;
1118 if (!ssoSession) return;
1119 const fs = yield* FileSystem.FileSystem;
1120 const path = yield* Path.Path;
1121 const hash = NodeCrypto.createHash("sha1").update(ssoSession).digest("hex");
1122 const cacheFile = path.join(
1123 NodeOs.homedir(),
1124 ".aws",
1125 "sso",
1126 "cache",
1127 `${hash}.credentials.json`,
1128 );
1129 yield* fs.remove(cacheFile).pipe(Effect.ignore);
1130 }).pipe(Effect.ignore);