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

main
ts 389 lines 16.8 KB
Raw
1 /**
2 * The credential-demand seam for credential-free `alchemy dev`.
3 *
4 * A dev run whose plan is entirely local must never touch (or prompt for)
5 * cloud credentials. When the plan DOES need the cloud — a resource opted
6 * out of local emulation via `Alchemy.remote()`, a local Worker binding
7 * that proxies to a remote resource (`dev: { remote: true }`), or the
8 * deletion of a row that was last reconciled live — credentials are
9 * validated up front, BEFORE apply begins: the gate resolves each demanded
10 * provider's credentials through the same precedence the run will use. The
11 * seam never starts a login flow: missing credentials fail with the typed
12 * {@link CredentialsRequired} error naming the demanding resources and
13 * pointing at `alchemy profile edit` — the profile command is the only
14 * place logins happen.
15 *
16 * How deep the up-front resolution goes is PROVIDER-DEPENDENT — it runs
17 * the provider's `read`, no more:
18 *
19 * - Cloudflare's `read` eagerly checks OAuth expiry, silently refreshes,
20 * and persists under the profile lock — so a dead refresh token fails
21 * here as a typed `NeedsReauth`, and child processes (which only ever
22 * read what a parent persisted) start with a warm token.
23 * - AWS's `read` returns a credentials RECIPE whose inner effect stays
24 * unevaluated (SSO tokens are loaded lazily by consumers), so an
25 * expired SSO token passes the gate and still surfaces mid-run. Local-mode
26 * AWS providers carry a floci-scoped environment of their own (see
27 * `AWS/Local/FlociServices.ts`) and ensure the emulator there.
28 *
29 * The demand scan keys on provider MODE, not plan action — noop live rows
30 * still demand (their runtime proxies need live credentials to serve), so
31 * a watch restart re-runs this resolution even for an unchanged plan.
32 *
33 * Non-dev runs (`alchemy deploy` / `destroy`) never enter this seam:
34 * state-store init and live providers drive the pre-existing lazy
35 * credential-resolution flow unchanged.
36 */
37 import * as Config from "effect/Config";
38 import * as Data from "effect/Data";
39 import * as Effect from "effect/Effect";
40 import * as Option from "effect/Option";
41 import * as Result from "effect/Result";
42 import * as Schema from "effect/Schema";
43 import type { BindingNode, Plan } from "../Plan.ts";
44 import { UserFacingError } from "../UserFacingError.ts";
45 import { profileCommandHint } from "../Util/interactive.ts";
46 import { AuthError, AuthProviders, NeedsReauth, presentEnvironment } from "./AuthProvider.ts";
47 import {
48 ALCHEMY_PROFILE,
49 DEFAULT_PROFILE_NAME,
50 ProfileStore,
51 SuppressMissingProviderConfig,
52 } from "./Profile.ts";
53 import { CredentialsUnavailable, resolveProviderConfig } from "./Resolve.ts";
54
55 /** Why a plan row demands live (cloud) credentials during a dev run. */
56 export type CredentialDemandReason =
57 /** The resource's resolved provider mode is `"live"` (`Alchemy.remote()`). */
58 | "remote"
59 /** Binding data carries a truthy `devRemote` entry — the local runtime proxies this binding to the real cloud. */
60 | "remote-binding"
61 /** The plan deletes a row stamped `providerMode: "live"` — the live provider must run to delete it. */
62 | "live-delete";
63
64 export interface DemandingResource {
65 /** FQN of the demanding resource within the stack. */
66 readonly fqn: string;
67 readonly reason: CredentialDemandReason;
68 }
69
70 /**
71 * All the resources of one cloud provider that demand live credentials.
72 * `provider` is the auth-provider name, derived from the resource Type's
73 * leading namespace segment (`"AWS.S3.Bucket"` → `"AWS"`, matching the
74 * name the cloud's auth provider registers under).
75 */
76 export interface CredentialDemand {
77 readonly provider: string;
78 readonly resources: readonly DemandingResource[];
79 }
80
81 /**
82 * A dev-mode plan needs cloud credentials and none are configured for the
83 * active profile. The message names the demanding resources and the exact
84 * `alchemy profile edit` invocation that fixes it.
85 */
86 export class CredentialsRequired extends Data.TaggedError("CredentialsRequired")<{
87 message: string;
88 /** Auth-provider name whose credentials are missing (e.g. `"AWS"`). */
89 provider: string;
90 /** FQNs of the resources demanding the credentials. */
91 resources: string[];
92 /** Short summary of why the credentials are needed. */
93 reason: string;
94 }> {
95 readonly [UserFacingError] = true;
96 }
97
98 /**
99 * Live providers resolve credentials lazily, on their first cloud call. A
100 * failed resolution fails (or, for alchemy services typed as never failing,
101 * dies) with {@link CredentialsUnavailable}. Applied around every provider
102 * lifecycle call, this fails the operation with {@link CredentialsRequired}
103 * naming the resource instead.
104 */
105 export const failCredentialsRequired = (fqn: string) =>
106 Effect.fn(function* <A, E, R>(self: Effect.Effect<A, E, R>) {
107 const isUnavailable = Schema.is(CredentialsUnavailable);
108 // Annotated: the catch handler returns this or a re-fail of E, and a
109 // union of Effects does not unify on its own.
110 const required = (
111 unavailable: CredentialsUnavailable,
112 ): Effect.Effect<never, E | CredentialsRequired> =>
113 Effect.fail(
114 new CredentialsRequired({
115 provider: unavailable.provider,
116 resources: [fqn],
117 reason: "runs against the real cloud",
118 message: unavailable.message,
119 }),
120 );
121 return yield* self.pipe(
122 // oxlint-disable-next-line effecttsgo/catch-conditional-refail-to-catch-if -- catchIf cannot narrow a generic E
123 Effect.catch((error) => (isUnavailable(error) ? required(error) : Effect.fail(error))),
124 Effect.catchDefect((defect) =>
125 isUnavailable(defect) ? required(defect) : Effect.die(defect),
126 ),
127 );
128 });
129
130 const describeReason = (reason: CredentialDemandReason): string => {
131 switch (reason) {
132 case "remote":
133 return "runs against the real cloud via Alchemy.remote()";
134 case "remote-binding":
135 return "has a binding that proxies to a remote resource (dev: { remote: true })";
136 case "live-delete":
137 return "deletes an instance that was deployed to the real cloud";
138 }
139 };
140
141 /** `"AWS.S3.Bucket"` → `"AWS"` (the auth-provider name). */
142 const cloudOf = (type: string): string => type.split(".")[0] ?? type;
143
144 const resourceLines = (demand: CredentialDemand): string =>
145 demand.resources.map((r) => ` - ${r.fqn} (${describeReason(r.reason)})`).join("\n");
146
147 /**
148 * Build the typed {@link CredentialsRequired} failure for a demand.
149 * Exported so tests can pin the message format.
150 */
151 export const credentialsRequired = (
152 demand: CredentialDemand,
153 profileName: string,
154 ): Effect.Effect<never, CredentialsRequired> =>
155 Effect.gen(function* () {
156 const command = yield* profileCommandHint(
157 `alchemy profile edit --profile ${profileName} --add ${demand.provider}`,
158 );
159 return yield* new CredentialsRequired({
160 provider: demand.provider,
161 resources: demand.resources.map((r) => r.fqn),
162 reason: [...new Set(demand.resources.map((r) => r.reason))].join(", "),
163 message:
164 `${demand.provider} credentials are required, but none are configured ` +
165 `for profile '${profileName}'.\n` +
166 `These resources require ${demand.provider} credentials:\n` +
167 `${resourceLines(demand)}\n` +
168 `Run \`${command}\` to configure ` +
169 "credentials, or set CI=1 to use environment-variable credentials.",
170 });
171 });
172
173 /**
174 * The slice of binding data the demand scan cares about: local runtimes
175 * mark cloud-proxied bindings with a truthy `devRemote` entry.
176 */
177 const RemoteBindingData = Schema.Struct({
178 devRemote: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)),
179 });
180
181 const decodeRemoteBindingData = Schema.decodeUnknownResult(RemoteBindingData);
182
183 const bindingDemandsRemote = (bindings: readonly BindingNode[] | undefined): boolean =>
184 (bindings ?? []).some((binding) => {
185 // A binding being REMOVED needs no runtime proxy — the restarted
186 // local instance simply no longer carries it.
187 if (binding.action === "delete") return false;
188 const data = decodeRemoteBindingData(binding.data);
189 return (
190 Result.isSuccess(data) &&
191 Object.values(data.success.devRemote ?? {}).some((remote) => remote === true)
192 );
193 });
194
195 /**
196 * Scan a plan for rows that need live (cloud) credentials during a dev
197 * run, grouped by cloud provider:
198 *
199 * 1. resources whose resolved provider mode is `"live"` (`Alchemy.remote()`)
200 * 2. resources whose binding data carries a truthy `devRemote` entry
201 * (the local runtime proxies that binding to the real cloud)
202 * 3. planned deletions of rows stamped `providerMode: "live"`
203 *
204 * Pure and side-effect-free — callers gate on the run being a dev run
205 * (in a live run every dual-provider row resolves `"live"` and the
206 * pre-existing lazy credential flow applies instead).
207 *
208 * Mode-agnostic rows (`mode === undefined`, single-implementation
209 * providers that run live even in dev) are deliberately NOT collected:
210 * they resolve credentials lazily exactly as they do today.
211 */
212 export const collectCredentialDemands = (plan: Plan): CredentialDemand[] => {
213 const byProvider = new Map<string, Map<string, CredentialDemandReason>>();
214 const add = (type: string, fqn: string, reason: CredentialDemandReason): void => {
215 const provider = cloudOf(type);
216 const resources = byProvider.get(provider) ?? new Map<string, CredentialDemandReason>();
217 if (!resources.has(fqn)) resources.set(fqn, reason);
218 byProvider.set(provider, resources);
219 };
220 for (const [fqn, node] of Object.entries(plan.resources)) {
221 if (node.mode === "live") {
222 add(node.resource.Type, fqn, "remote");
223 } else if (bindingDemandsRemote(node.bindings)) {
224 add(node.resource.Type, fqn, "remote-binding");
225 }
226 }
227 for (const [fqn, node] of Object.entries(plan.deletions)) {
228 if (node !== undefined && node.mode === "live") {
229 add(node.resource.Type, fqn, "live-delete");
230 }
231 }
232 return [...byProvider.entries()].map(([provider, resources]) => ({
233 provider,
234 resources: [...resources.entries()].map(([fqn, reason]) => ({
235 fqn,
236 reason,
237 })),
238 }));
239 };
240
241 /**
242 * Re-fail a warm-up resolution error with the demand attached, so the user
243 * sees WHY a dev run wanted cloud credentials. Tags are preserved —
244 * consumers match `NeedsReauth`/`AuthError` by tag, never by message.
245 */
246 const attachDemandContext =
247 (demand: CredentialDemand) =>
248 <A, R>(
249 self: Effect.Effect<A, AuthError | NeedsReauth, R>,
250 ): Effect.Effect<A, AuthError | NeedsReauth, R> =>
251 self.pipe(
252 Effect.mapError((error) => {
253 const message =
254 `${error.message}\n` +
255 `These resources require ${demand.provider} credentials:\n` +
256 resourceLines(demand);
257 return error._tag === "NeedsReauth"
258 ? NeedsReauth.make({
259 provider: error.provider,
260 profile: error.profile,
261 message,
262 cause: error.cause,
263 })
264 : AuthError.make({ message, cause: error.cause });
265 }),
266 );
267
268 /**
269 * Validate credentials for every demand. Never starts a login flow —
270 * logging in belongs to `alchemy profile edit` exclusively:
271 *
272 * - configured for the active profile → resolve the credentials through
273 * the exact precedence the run will use ({@link resolveProviderConfig}:
274 * CI environment, explicit env vars, then the profile). Resolution
275 * runs the provider's `read` — how much that validates and warms is
276 * provider-dependent (see the module header): Cloudflare eagerly
277 * refreshes and persists so a dead refresh token fails HERE as a
278 * typed {@link NeedsReauth} naming the demanding resources, while
279 * AWS's lazy credential recipe defers SSO-token failures to mid-run.
280 * - missing → typed {@link CredentialsRequired} failure with the exact
281 * `alchemy profile edit` invocation to run
282 * - CI → validates the provider's environment credentials directly,
283 * matching every other CI path without creating profile state
284 *
285 * Demands whose cloud has no registered auth provider are skipped (bare
286 * engine runs with test providers demand nothing). All context is
287 * resolved optionally, so the effect is safe to run in any environment —
288 * and a plan with zero demand touches no credentials at all.
289 */
290 export const demandCredentials = Effect.fn("Alchemy.demandCredentials")(function* (
291 demands: readonly CredentialDemand[],
292 ) {
293 if (demands.length === 0) return;
294 const registry = Option.getOrUndefined(yield* Effect.serviceOption(AuthProviders));
295 const profile = Option.getOrUndefined(yield* Effect.serviceOption(ProfileStore));
296 if (registry === undefined || profile === undefined) return;
297 const ci = yield* Config.Boolean("CI").pipe(Config.withDefault(false));
298 // CI credentials come exclusively from the environment. Do not require
299 // or inspect a local profile first: CI runners intentionally have no
300 // profile manifest, and doing so would also risk consulting a developer's
301 // stored profiles when this path is exercised locally under Doppler.
302 const configuredProfile = yield* Config.option(ALCHEMY_PROFILE);
303 const profileName = Option.getOrElse(configuredProfile, () => DEFAULT_PROFILE_NAME);
304 yield* Effect.forEach(
305 demands,
306 (demand) =>
307 Effect.gen(function* () {
308 const auth = registry[demand.provider];
309 if (auth == null) return;
310 if (ci) {
311 if (auth.readEnvironment === undefined) {
312 return yield* credentialsRequired(demand, profileName);
313 }
314 return yield* auth.readEnvironment.pipe(attachDemandContext(demand));
315 }
316 // Read-only precheck of the two non-CI configuration sources the
317 // resolution precedence below consults: environment credentials
318 // (which win regardless of the selected profile), or a profile
319 // entry. "Nothing configured" fails with the actionable
320 // {@link CredentialsRequired} here, WITHOUT entering
321 // `resolveProviderConfig`: its profile path goes through
322 // `ensureProfile`, which fails a nonexistent profile with a
323 // generic ProfileError that would bury which resources demanded
324 // credentials and what command fixes it.
325 const envUsable =
326 auth.readEnvironment !== undefined &&
327 (yield* presentEnvironment(auth.environment)) !== undefined;
328 const existing = yield* profile.getProfile(profileName);
329 if (existing?.providers[auth.name] == null && !envUsable) {
330 return yield* credentialsRequired(demand, profileName);
331 }
332 // Something IS configured — resolve through the same precedence
333 // the run's lazy credential flow uses, so the gate can never
334 // pass something resolution would later reject (or vice versa).
335 // Suppressed missing-config mode turns a check/resolve race into
336 // the typed tag below instead of a generic AuthError; it also
337 // mutes the env-credentials warning here — the run's own
338 // resolution still emits it.
339 const resolved = yield* resolveProviderConfig(demand.provider).pipe(
340 Effect.provideService(AuthProviders, registry),
341 Effect.provideService(ProfileStore, profile),
342 Effect.provideService(SuppressMissingProviderConfig, true),
343 Effect.catchTags({
344 MissingProviderConfig: () => credentialsRequired(demand, profileName),
345 ProfileError: (error) => AuthError.make({ message: error.message, cause: error }),
346 }),
347 );
348 yield* resolved.resolve.pipe(attachDemandContext(demand));
349 }),
350 { concurrency: 4, discard: true },
351 );
352 });
353
354 /**
355 * Plan-time seam for `Alchemy.remote()` rows. The planner probes every new
356 * resource with its provider's `read` (engine-level adoption) — for a
357 * live-mode row in a dev run that is a real cloud call, made BEFORE
358 * {@link demandPlanCredentials} could run in apply. Demanding here first
359 * turns "nothing configured" into the typed {@link CredentialsRequired}
360 * (naming the rows and the exact `alchemy profile edit` command) instead
361 * of whatever raw error the first credential-less read produces. Bindings
362 * and live deletions are still gated in apply — nothing reads for them
363 * during plan.
364 */
365 export const demandRemoteCredentials = (
366 resources: ReadonlyArray<{ readonly Type: string; readonly FQN: string }>,
367 ) => {
368 const byProvider = new Map<string, DemandingResource[]>();
369 for (const resource of resources) {
370 const provider = cloudOf(resource.Type);
371 byProvider.set(provider, [
372 ...(byProvider.get(provider) ?? []),
373 { fqn: resource.FQN, reason: "remote" },
374 ]);
375 }
376 return demandCredentials(
377 [...byProvider.entries()].map(([provider, resources]) => ({
378 provider,
379 resources,
380 })),
381 );
382 };
383
384 /**
385 * The one-call seam wired into the dev path: scan the plan for live
386 * demand and, if any, run {@link demandCredentials} BEFORE apply begins.
387 */
388 export const demandPlanCredentials = (plan: Plan) =>
389 demandCredentials(collectCredentialDemands(plan));