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

main
ts 165 lines 6.61 KB
Raw
1 import {
2 AwsCredentialProviderError,
3 Credentials,
4 type ResolvedCredentials,
5 } from "@distilled.cloud/aws/Credentials";
6 import { Region } from "@distilled.cloud/aws/Region";
7 import * as sts from "@distilled.cloud/aws/sts";
8 import { cacheUntilExpiry } from "alchemy/Auth/CredentialsCache";
9 import * as Effect from "effect/Effect";
10 import * as FetchHttpClient from "effect/http/FetchHttpClient";
11 import * as Layer from "effect/Layer";
12 import * as Redacted from "effect/Redacted";
13 import * as Schedule from "effect/Schedule";
14 import { AWSEnvironment } from "./Environment.ts";
15
16 // NB: do not re-export `fromEnv` here — it is unavailable under the
17 // browser/workerd bundle condition (`credentials.browser`), which would break
18 // any Cloudflare Worker that transitively imports this module.
19 export { Credentials, fromCredentials } from "@distilled.cloud/aws/Credentials";
20
21 declare module "@distilled.cloud/aws/Credentials" {
22 interface Credentials {
23 readonly kind: "Credentials";
24 }
25 }
26
27 /**
28 * Lazy `Credentials` layer derived from the surrounding {@link AWSEnvironment}.
29 * Credentials are resolved on first access (not during layer construction),
30 * matching the existing @distilled.cloud/aws semantics.
31 */
32 export const fromEnvironment = Layer.effect(
33 Credentials,
34 Effect.gen(function* () {
35 return Effect.flatMap(yield* AWSEnvironment, (env) => env.credentials);
36 }),
37 );
38
39 /**
40 * Build a single-flight, expiry-aware assumed-role credentials **resolver**,
41 * constructing the cache exactly once.
42 *
43 * The OUTER effect builds the cache and returns the INNER resolver; run the
44 * outer ONCE (e.g. when a binding initializes) and reuse the returned resolver
45 * for every request. That is what makes the cache actually cache: each request
46 * runs the shared resolver, which only calls `AssumeRole` when the cached
47 * credentials are missing or within the refresh window — never per request.
48 *
49 * `roleArn` and `base` are accepted as effects/layers so the long-lived signing
50 * credentials and role ARN can be read lazily at refresh time (e.g. from a
51 * deployed Worker's environment), rather than captured eagerly.
52 */
53 export const makeAssumeRoleResolver = (options: {
54 /** ARN of the IAM Role to assume (resolved lazily on each refresh). */
55 readonly roleArn: Effect.Effect<string>;
56 /** Layer supplying the long-lived credentials used to sign `AssumeRole`. */
57 readonly base: Layer.Layer<Credentials>;
58 /** STS role session name. @default "alchemy" */
59 readonly roleSessionName?: string;
60 /**
61 * Region for the STS endpoint. STS `AssumeRole` is global, so this only
62 * selects the regional STS endpoint. @default "us-east-1"
63 */
64 readonly region?: string;
65 }): Effect.Effect<Effect.Effect<ResolvedCredentials, AwsCredentialProviderError>> =>
66 Effect.gen(function* () {
67 const resolve = Effect.gen(function* () {
68 const roleArn = yield* options.roleArn;
69 const response = yield* sts
70 .assumeRole({
71 RoleArn: roleArn,
72 RoleSessionName: options.roleSessionName ?? "alchemy",
73 })
74 .pipe(
75 // A freshly-created IAM user/role/access-key is eventually
76 // consistent: the first `AssumeRole` calls can fail with
77 // `AccessDenied` until the trust policy + permissions propagate.
78 // Retry those for up to ~30s.
79 Effect.retry({
80 while: (error) =>
81 (error as { name?: string }).name === "AccessDeniedException" ||
82 (error as { _tag?: string })._tag === "AccessDeniedException",
83 schedule: Schedule.exponential("1 second"),
84 times: 8,
85 }),
86 );
87 const creds = response.Credentials;
88 if (!creds) {
89 return yield* new AwsCredentialProviderError({
90 message: "STS AssumeRole returned no credentials",
91 provider: "assume-role",
92 });
93 }
94 return {
95 accessKeyId: Redacted.make(creds.AccessKeyId),
96 secretAccessKey: Redacted.isRedacted(creds.SecretAccessKey)
97 ? creds.SecretAccessKey
98 : Redacted.make(creds.SecretAccessKey),
99 sessionToken: Redacted.make(creds.SessionToken),
100 region: options.region ?? "us-east-1",
101 expiration: creds.Expiration?.getTime(),
102 } satisfies ResolvedCredentials;
103 }).pipe(
104 // Sign AssumeRole with the static base credentials, and provide a
105 // (regional) STS endpoint + HttpClient so the resolve effect is
106 // self-contained (`R = never`).
107 Effect.provide(
108 options.base.pipe(
109 Layer.provideMerge(Layer.succeed(Region, Effect.succeed(options.region ?? "us-east-1"))),
110 Layer.provideMerge(FetchHttpClient.layer),
111 ),
112 ),
113 Effect.mapError((cause) =>
114 cause instanceof AwsCredentialProviderError
115 ? cause
116 : new AwsCredentialProviderError({
117 message: "STS AssumeRole failed",
118 provider: "assume-role",
119 cause,
120 }),
121 ),
122 );
123
124 // Expiry-aware and single-flight: N concurrent callers observing
125 // stale/expiring credentials trigger exactly ONE `AssumeRole` call.
126 return yield* cacheUntilExpiry(resolve, (creds) => creds.expiration);
127 });
128
129 /**
130 * A `Credentials` layer that assumes an IAM Role via STS and serves the
131 * returned temporary credentials (cached until shortly before expiry).
132 *
133 * `base` supplies the long-lived credentials used to *sign* the `AssumeRole`
134 * call — typically static IAM-user access keys (see
135 * {@link fromCredentials}). The `AssumeRole` request itself is signed against
136 * `base`, while the temporary credentials it returns become the resolved
137 * `Credentials` for every downstream AWS call.
138 *
139 * The cache is built once when the layer is constructed; build/provide this
140 * layer ONCE and reuse it. To share the same cache across many `Effect.provide`
141 * sites without re-providing the layer, build {@link makeAssumeRoleResolver}
142 * directly and supply the resolver via `Layer.succeed(Credentials, resolver)`.
143 */
144 export const fromAssumeRole = (options: {
145 /** ARN of the IAM Role to assume. */
146 readonly roleArn: string;
147 /** Static credentials used to sign the `AssumeRole` call. */
148 readonly base: Layer.Layer<Credentials>;
149 /** STS role session name. @default "alchemy" */
150 readonly roleSessionName?: string;
151 /**
152 * Region for the STS endpoint. STS `AssumeRole` is global, so this only
153 * selects the regional STS endpoint. @default "us-east-1"
154 */
155 readonly region?: string;
156 }): Layer.Layer<Credentials> =>
157 Layer.effect(
158 Credentials,
159 makeAssumeRoleResolver({
160 roleArn: Effect.succeed(options.roleArn),
161 base: options.base,
162 roleSessionName: options.roleSessionName,
163 region: options.region,
164 }),
165 );