@devries-cameron20 / t3code Mirror · read-only
Fork 0

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, 04:45 UTC

main
ts 810 lines 31.6 KB
Raw
1 import * as cfAccounts from "@distilled.cloud/cloudflare/accounts";
2 import * as CfCredentialsModule from "@distilled.cloud/cloudflare/Credentials";
3 import * as cfMemberships from "@distilled.cloud/cloudflare/memberships";
4 import {
5 AuthError,
6 AuthProviderLayer,
7 NeedsReauth,
8 reconfigureHint,
9 refreshHint,
10 type ConfigureField,
11 type ConfigureMethod,
12 } from "alchemy/Auth/AuthProvider";
13 import { deviceOAuth } from "alchemy/Auth/BrowserOAuth";
14 import { CredentialsStore, displayRedacted } from "alchemy/Auth/Credentials";
15 import { getEnvRedacted, getEnvRequired, mapPromptCancellation } from "alchemy/Auth/Env";
16 import { withProfileCredentialsLock } from "alchemy/Auth/Lock";
17 import {
18 storedSecret,
19 storedValueText,
20 validateFieldValues,
21 } from "alchemy/Auth/StoredAuthProvider";
22 import * as Interaction from "alchemy/Interaction";
23 import * as Clock from "effect/Clock";
24 import * as Duration from "effect/Duration";
25 import * as Effect from "effect/Effect";
26 import * as FetchHttpClient from "effect/http/FetchHttpClient";
27 import * as HttpClient from "effect/http/HttpClient";
28 import * as Layer from "effect/Layer";
29 import * as Match from "effect/Match";
30 import * as Redacted from "effect/Redacted";
31 import * as Schema from "effect/Schema";
32 import * as Stream from "effect/Stream";
33 import { clearStoreCredentials } from "../StateStore/CredentialsFile.ts";
34 import {
35 CLOUDFLARE_AUTH_PROVIDER_NAME,
36 CloudflareAuthConfigSchema,
37 validateAccountId,
38 validateAccountIdField,
39 type CloudflareAuthConfig,
40 type CloudflareResolvedCredentials,
41 } from "./AuthConfig.ts";
42 import * as OAuthClient from "./OAuthClient.ts";
43 import {
44 ALL_SCOPE_IDS,
45 BASIC_SCOPES,
46 customOAuthScopeDefaults,
47 OAUTH_SCOPE_GROUPS,
48 OAUTH_SCOPE_NAMES,
49 OFFLINE_ACCESS_SCOPE,
50 partitionOAuthScopes,
51 } from "./OAuthScopes.ts";
52
53 const options: Array<{
54 value: CloudflareAuthConfig["method"];
55 label: string;
56 description?: string;
57 }> = [
58 {
59 value: "oauth",
60 label: "OAuth",
61 description: "recommended — browser device login with automatic token refresh",
62 },
63 {
64 value: "stored",
65 label: "API Token or API Key",
66 description: "use an API token or global API key",
67 },
68 ];
69
70 const withOAuthCredentials = <A, E, R>(
71 accessToken: string,
72 effect: Effect.Effect<A, E, R | CfCredentialsModule.Credentials | HttpClient.HttpClient>,
73 ): Effect.Effect<A, E, R> =>
74 Effect.provide(
75 effect,
76 Layer.mergeAll(
77 CfCredentialsModule.fromOAuth({
78 load: Effect.succeed({ accessToken: Redacted.make(accessToken) }),
79 refresh: () => Effect.die("refresh not expected during account selection"),
80 }),
81 FetchHttpClient.layer,
82 ),
83 );
84
85 /**
86 * Accounts visible to a user-scoped OAuth token. `GET /accounts` returns an
87 * EMPTY list for these tokens (it only lists accounts an account-scoped
88 * credential can read), so memberships are the authoritative account list —
89 * the same endpoint wrangler uses. `GET /accounts` remains as a fallback for
90 * tokens authorized without `memberships.read` (custom scope selections).
91 */
92 const listVisibleAccounts: Effect.Effect<
93 ReadonlyArray<{ id: string; name: string }>,
94 unknown,
95 CfCredentialsModule.Credentials | HttpClient.HttpClient
96 > = Effect.gen(function* () {
97 // Both endpoints page at 20 by default; walk every page so users with more
98 // accounts than that can pick any of them.
99 const membershipAccounts = yield* cfMemberships.listMemberships.items({ perPage: 50 }).pipe(
100 Stream.runCollect,
101 Effect.map((memberships) =>
102 Array.from(memberships).flatMap((membership) =>
103 membership.account != null &&
104 (membership.status == null || membership.status === "accepted")
105 ? [membership.account]
106 : [],
107 ),
108 ),
109 Effect.catch((error) =>
110 Effect.logDebug("Cloudflare: listing memberships failed", error).pipe(
111 Effect.as([] as Array<{ id: string; name: string }>),
112 ),
113 ),
114 );
115 if (membershipAccounts.length > 0) return membershipAccounts;
116 const accounts = Array.from(
117 yield* cfAccounts.listAccounts.items({ perPage: 50 }).pipe(Stream.runCollect),
118 );
119 yield* Effect.logDebug(
120 `Cloudflare: memberships listed 0 accounts; /accounts listed ${accounts.length}`,
121 );
122 return accounts;
123 });
124
125 const selectAccount = (accessToken: string) =>
126 Effect.gen(function* () {
127 const accounts = yield* listVisibleAccounts;
128 if (accounts.length === 0) {
129 return yield* AuthError.make({
130 message:
131 "No Cloudflare accounts are visible to this credential. " +
132 "Ensure the authorized OAuth scopes include 'memberships.read'.",
133 });
134 }
135 const [account] = accounts;
136 if (accounts.length === 1 && account !== undefined) {
137 yield* Interaction.info(`Using Cloudflare account ${account.name}.`);
138 return account.id;
139 }
140 return yield* Interaction.select({
141 message: "Select a Cloudflare account",
142 searchable: true,
143 options: accounts.map((a) => ({ value: a.id, label: a.name, description: a.id })),
144 }).pipe(mapPromptCancellation);
145 }).pipe((e) => withOAuthCredentials(accessToken, e));
146
147 const promptAccountId = () =>
148 Effect.gen(function* () {
149 const interaction = yield* Interaction.Interaction;
150 return yield* interaction.prompt
151 .text({ message: "Cloudflare Account ID", validate: validateAccountIdField })
152 .pipe(mapPromptCancellation);
153 });
154
155 const accountIdField: ConfigureField = {
156 name: "accountId",
157 label: "Cloudflare Account ID",
158 validate: validateAccountIdField,
159 };
160
161 /**
162 * `--set` fields for `--method stored`. The persisted `credentialType` is
163 * inferred from which secret is supplied: `apiToken` alone, or `apiKey`
164 * together with `email`.
165 */
166 const storedFields: ReadonlyArray<ConfigureField> = [
167 {
168 name: "apiToken",
169 label: "Cloudflare API Token",
170 description: "Pass either apiToken, or apiKey together with email.",
171 secret: true,
172 optional: true,
173 },
174 { name: "apiKey", label: "Cloudflare API Key", secret: true, optional: true },
175 { name: "email", label: "Cloudflare Email", optional: true },
176 accountIdField,
177 ];
178
179 /**
180 * Flag-driven configuration methods. OAuth is deliberately absent — it is
181 * interactive-only (browser grant).
182 */
183 const configureMethods: ReadonlyArray<ConfigureMethod> = [
184 { method: "stored", fields: storedFields },
185 ];
186
187 const promptOAuthScopes = (currentConfig?: CloudflareAuthConfig) =>
188 Effect.gen(function* () {
189 const interaction = yield* Interaction.Interaction;
190 const mode = yield* interaction.prompt
191 .select({
192 message: "Cloudflare OAuth scopes",
193 initialValue: "all" as const,
194 options: [
195 {
196 value: "all" as const,
197 label: "All Scopes",
198 description: "authorize every available Cloudflare permission",
199 },
200 {
201 value: "basic" as const,
202 label: "Basic Scopes",
203 description: "covers typical Alchemy use cases",
204 },
205 {
206 value: "custom" as const,
207 label: "Custom Scopes",
208 description: "choose individual permissions",
209 },
210 ],
211 })
212 .pipe(mapPromptCancellation);
213 if (mode === "basic") return [...BASIC_SCOPES];
214 if (mode === "all") return [...ALL_SCOPE_IDS];
215 return yield* interaction.prompt
216 .multiSelect({
217 message: "Select OAuth scopes",
218 initialValues: customOAuthScopeDefaults(currentConfig),
219 searchable: true,
220 descriptionPlacement: "inline",
221 options: OAUTH_SCOPE_GROUPS.flatMap((group) =>
222 group.scopes.map((value) => ({
223 value,
224 label: OAUTH_SCOPE_NAMES[value],
225 description: value,
226 group: group.label,
227 })),
228 ),
229 required: true,
230 })
231 .pipe(mapPromptCancellation);
232 });
233
234 /**
235 * Layer that registers the Cloudflare {@link AuthProvider} into the
236 * {@link AuthProviders} registry when built. Include this in the Cloudflare
237 * `providers()` layer so the alchemy CLI can discover it.
238 */
239 export const CloudflareAuth = AuthProviderLayer<
240 CloudflareAuthConfig,
241 CloudflareResolvedCredentials
242 >()(
243 CLOUDFLARE_AUTH_PROVIDER_NAME,
244 Effect.gen(function* () {
245 const store = yield* CredentialsStore;
246
247 const oauthLogin = (_profileName: string, scopes: string[]) =>
248 Effect.gen(function* () {
249 const authorization = yield* OAuthClient.deviceAuthorize([...scopes, OFFLINE_ACCESS_SCOPE]);
250
251 const credentials = yield* deviceOAuth({
252 provider: "Cloudflare",
253 authorization,
254 token: OAuthClient.deviceToken(authorization),
255 });
256 yield* Interaction.success("Connected to Cloudflare with OAuth.");
257 return credentials;
258 });
259
260 const loginStored = Effect.fn(function* () {
261 const credentialType = yield* Interaction.select({
262 message: "Cloudflare credential type",
263 options: [
264 { value: "apiToken" as const, label: "API Token", description: "recommended" },
265 { value: "apiKey" as const, label: "API Key + Email" },
266 ],
267 }).pipe(mapPromptCancellation);
268
269 return yield* Match.value(credentialType).pipe(
270 Match.when("apiToken", () =>
271 Effect.gen(function* () {
272 const apiToken = yield* Interaction.password({
273 message: "Cloudflare API Token",
274 validate: (v) => (v.length === 0 ? "Required" : undefined),
275 }).pipe(mapPromptCancellation, Effect.map(Redacted.make));
276 const accountId = yield* promptAccountId();
277
278 yield* Interaction.success("Cloudflare: credentials saved.");
279 return {
280 method: "stored" as const,
281 credentialType: "apiToken" as const,
282 apiToken: Redacted.value(apiToken),
283 accountId,
284 };
285 }),
286 ),
287 Match.when("apiKey", () =>
288 Effect.gen(function* () {
289 const apiKey = yield* Interaction.password({
290 message: "Cloudflare API Key",
291 validate: (v) => (v.length === 0 ? "Required" : undefined),
292 }).pipe(mapPromptCancellation, Effect.map(Redacted.make));
293
294 const email = yield* Interaction.text({
295 message: "Cloudflare Email",
296 validate: (v) => (v.length === 0 ? "Required" : undefined),
297 }).pipe(mapPromptCancellation, Effect.map(Redacted.make));
298 const accountId = yield* promptAccountId();
299
300 yield* Interaction.success("Cloudflare: credentials saved.");
301 return {
302 method: "stored" as const,
303 credentialType: "apiKey" as const,
304 apiKey: Redacted.value(apiKey),
305 email: Redacted.value(email),
306 accountId,
307 };
308 }),
309 ),
310 Match.exhaustive,
311 );
312 });
313
314 const configureOAuth = Effect.fn(function* (
315 profileName: string,
316 currentConfig?: CloudflareAuthConfig,
317 ) {
318 const scopes = yield* promptOAuthScopes(currentConfig);
319
320 const oauthCreds = yield* oauthLogin(profileName, [...scopes]);
321
322 const accountId = yield* oauthCreds.access.pipe(
323 Redacted.value,
324 selectAccount,
325 // Keep AuthError messages intact — they carry the actionable
326 // diagnosis (e.g. "no accounts visible"); only wrap raw API errors.
327 Effect.mapError((e) =>
328 Schema.is(AuthError)(e)
329 ? e
330 : AuthError.make({ message: "Cloudflare: could not list accounts", cause: e }),
331 ),
332 );
333
334 return {
335 method: "oauth" as const,
336 scopes: [...scopes],
337 accountId,
338 clientId: oauthCreds.clientId,
339 access: Redacted.value(oauthCreds.access),
340 refresh: Redacted.value(oauthCreds.refresh),
341 expires: oauthCreds.expires,
342 };
343 });
344
345 const configureInteractive = (profileName: string, currentConfig?: CloudflareAuthConfig) =>
346 Interaction.select({ message: "Cloudflare authentication method", options }).pipe(
347 Effect.flatMap((method) =>
348 Match.value(method).pipe(
349 Match.when("oauth", () => configureOAuth(profileName, currentConfig)),
350 Match.when("stored", () => loginStored()),
351 Match.exhaustive,
352 ),
353 ),
354 );
355
356 const configureCredentials = (profileName: string, currentConfig?: CloudflareAuthConfig) =>
357 Effect.gen(function* () {
358 const config = yield* configureInteractive(profileName, currentConfig);
359 // Re-configuring auth may point this profile at a different
360 // Cloudflare account. The cached state-store credentials
361 // (`~/.alchemy/profiles/{profile}/state-stores/cloudflare.json`)
362 // are minted per-account, so drop them here; the next deploy
363 // re-derives them against the freshly-configured account.
364 yield* clearStoreCredentials(store, profileName).pipe(Effect.ignore);
365 return config;
366 }).pipe(
367 // AuthError messages are already user-facing; re-wrapping them in a
368 // generic banner is what hid "no accounts visible" behind
369 // "failed to configure credentials".
370 Effect.mapError((e) =>
371 Schema.is(AuthError)(e)
372 ? e
373 : AuthError.make({ message: "failed to configure credentials", cause: e }),
374 ),
375 );
376
377 const resolveCredentials = (
378 profileName: string,
379 config: CloudflareAuthConfig,
380 updateConfig?: (config: CloudflareAuthConfig) => Effect.Effect<void, AuthError>,
381 ) =>
382 Effect.gen(function* () {
383 const reauth = refreshHint(CLOUDFLARE_AUTH_PROVIDER_NAME, profileName);
384 return yield* Match.value(config).pipe(
385 Match.when({ method: "stored", credentialType: "apiToken" }, (c) =>
386 validateAccountId(c.accountId, `stored for profile '${profileName}'`).pipe(
387 Effect.map((accountId) => ({
388 type: "apiToken" as const,
389 apiToken: Redacted.make(c.apiToken),
390 accountId,
391 source: { type: "stored" as const },
392 })),
393 ),
394 ),
395 Match.when({ method: "stored", credentialType: "apiKey" }, (c) =>
396 validateAccountId(c.accountId, `stored for profile '${profileName}'`).pipe(
397 Effect.map((accountId) => ({
398 type: "apiKey" as const,
399 apiKey: Redacted.make(c.apiKey),
400 email: Redacted.make(c.email),
401 accountId,
402 source: { type: "stored" as const },
403 })),
404 ),
405 ),
406 Match.when({ method: "oauth" }, (cfg) =>
407 Effect.gen(function* () {
408 if (!("scopes" in cfg)) {
409 return yield* NeedsReauth.make({
410 provider: CLOUDFLARE_AUTH_PROVIDER_NAME,
411 profile: profileName,
412 message: `Cloudflare OAuth scopes need to be selected. ${reauth}`,
413 });
414 }
415 const accountId = yield* validateAccountId(
416 cfg.accountId,
417 `configured for profile '${profileName}'`,
418 );
419 const creds: OAuthClient.OAuthCredentials = {
420 type: "oauth",
421 clientId: cfg.clientId,
422 access: Redacted.make(cfg.access),
423 refresh: Redacted.make(cfg.refresh),
424 expires: cfg.expires,
425 scopes: cfg.scopes,
426 };
427 // Grants issued to the legacy client keep refreshing against
428 // it; only a manual `profile refresh` migrates them.
429 const client = OAuthClient.clientFor(creds);
430 if (client === undefined) {
431 return yield* NeedsReauth.make({
432 provider: CLOUDFLARE_AUTH_PROVIDER_NAME,
433 profile: profileName,
434 message: `Cloudflare OAuth credentials for profile '${profileName}' were issued to an incompatible OAuth client and have been removed. ${reauth}`,
435 });
436 }
437 // Refresh proactively if the token has expired (or is within
438 // 10s of expiring). Persist the refreshed creds so subsequent
439 // resolves don't repeat the round-trip.
440 const now = yield* Clock.currentTimeMillis;
441 const fresh =
442 creds.expires > now + 10_000
443 ? creds
444 : yield* client.refresh(creds).pipe(
445 Effect.mapError((e) =>
446 NeedsReauth.make({
447 provider: CLOUDFLARE_AUTH_PROVIDER_NAME,
448 profile: profileName,
449 message: `Cloudflare OAuth refresh failed. ${reauth}`,
450 cause: e,
451 }),
452 ),
453 );
454 if (fresh !== creds) {
455 yield* (
456 updateConfig?.({
457 method: "oauth",
458 accountId,
459 clientId: fresh.clientId,
460 access: Redacted.value(fresh.access),
461 refresh: Redacted.value(fresh.refresh),
462 expires: fresh.expires,
463 scopes: fresh.scopes,
464 }) ?? Effect.void
465 );
466 }
467 return {
468 type: "oauth" as const,
469 accessToken: fresh.access,
470 expires: fresh.expires,
471 accountId,
472 source: { type: "oauth" as const },
473 };
474 }),
475 ),
476 Match.exhaustive,
477 );
478 });
479
480 const readEnvironment = Effect.gen(function* () {
481 const accountId = yield* getEnvRequired("CLOUDFLARE_ACCOUNT_ID").pipe(
482 Effect.flatMap((id) => validateAccountId(id, "from CLOUDFLARE_ACCOUNT_ID")),
483 );
484 const apiToken = yield* getEnvRedacted("CLOUDFLARE_API_TOKEN");
485 if (apiToken) {
486 return { type: "apiToken" as const, apiToken, accountId, source: { type: "env" as const } };
487 }
488 const apiKey = yield* getEnvRedacted("CLOUDFLARE_API_KEY");
489 const email =
490 (yield* getEnvRedacted("CLOUDFLARE_EMAIL")) ??
491 (yield* getEnvRedacted("CLOUDFLARE_ACCOUNT_EMAIL"));
492 if (apiKey && email) {
493 return {
494 type: "apiKey" as const,
495 apiKey,
496 email,
497 accountId,
498 source: { type: "env" as const },
499 };
500 }
501 return yield* AuthError.make({
502 message:
503 "Cloudflare CI credentials not found. Set CLOUDFLARE_API_TOKEN, or CLOUDFLARE_API_KEY with CLOUDFLARE_EMAIL/CLOUDFLARE_ACCOUNT_EMAIL.",
504 });
505 });
506
507 const logout = (profileName: string, config: CloudflareAuthConfig) =>
508 Match.value(config).pipe(
509 Match.when({ method: "stored" }, () => Effect.void),
510 Match.when({ method: "oauth" }, (config) => {
511 if (!("scopes" in config)) return Effect.void;
512 const credentials: OAuthClient.OAuthCredentials = {
513 type: "oauth",
514 clientId: config.clientId,
515 access: Redacted.make(config.access),
516 refresh: Redacted.make(config.refresh),
517 expires: config.expires,
518 scopes: config.scopes,
519 };
520 const client = OAuthClient.clientFor(credentials);
521 return client !== undefined
522 ? client
523 .revoke(credentials)
524 .pipe(
525 Effect.catchTag("OAuthNetworkError", (err) =>
526 Interaction.warning(`Cloudflare: could not revoke OAuth token: ${err.message}`),
527 ),
528 )
529 : Effect.void;
530 }),
531 Match.exhaustive,
532 // The cached state-store credentials are derived from the account we
533 // just logged out of, so drop them regardless of auth method.
534 Effect.andThen(clearStoreCredentials(store, profileName).pipe(Effect.ignore)),
535 );
536
537 const login = (
538 profileName: string,
539 config: CloudflareAuthConfig,
540 updateConfig?: (config: CloudflareAuthConfig) => Effect.Effect<void, AuthError>,
541 reload?: Effect.Effect<CloudflareAuthConfig, AuthError>,
542 ) =>
543 Match.value(config).pipe(
544 Match.when({ method: "stored" }, (config) => Effect.succeed(config)),
545 Match.when({ method: "oauth" }, (c) =>
546 "scopes" in c
547 ? Effect.gen(function* () {
548 const creds: OAuthClient.OAuthCredentials = {
549 type: "oauth",
550 clientId: c.clientId,
551 access: Redacted.make(c.access),
552 refresh: Redacted.make(c.refresh),
553 expires: c.expires,
554 scopes: c.scopes,
555 };
556 const reconfigure = reconfigureHint(CLOUDFLARE_AUTH_PROVIDER_NAME, profileName);
557 // Any path that falls back to a full browser login rebuilds the
558 // authorize URL from the profile's stored scopes. Those scopes
559 // may predate the current OAuth client (or a catalog change), and
560 // one unknown scope makes the whole authorize URL invalid — so
561 // sanitize before generating a URL, never after it fails.
562 const fullLogin = Effect.gen(function* () {
563 const { valid } = partitionOAuthScopes(c.scopes);
564 if (valid.length === 0) {
565 return yield* AuthError.make({
566 message:
567 `The OAuth scopes stored for profile '${profileName}' are no longer offered by Alchemy's Cloudflare OAuth client. ` +
568 `Scopes must be picked again. ${reconfigure}`,
569 });
570 }
571 const refreshed = yield* oauthLogin(profileName, valid);
572 return {
573 ...c,
574 scopes: valid,
575 clientId: refreshed.clientId,
576 access: Redacted.value(refreshed.access),
577 refresh: Redacted.value(refreshed.refresh),
578 expires: refreshed.expires,
579 };
580 });
581
582 // Grants from any other client (including the legacy one) are
583 // re-authorized against the current client with the same
584 // scopes rather than refreshed.
585 const migrateToCurrentClient = Interaction.info(
586 "Cloudflare: re-authorizing OAuth credentials with the new client.",
587 ).pipe(Effect.as({ type: "browser" as const }));
588
589 // The silent refresh rotates a single-use refresh token, so
590 // its read-refresh-persist section runs under the profile
591 // lock — a concurrent `read` refreshing the same token would
592 // double-spend it. It refreshes with the token stored now,
593 // read under the lock, not the one `config` was read with.
594 // The lock is held only for this API round-trip, never
595 // across the browser wait below.
596 const outcome =
597 creds.type === "oauth" && OAuthClient.usesCurrentClient(creds)
598 ? yield* withProfileCredentialsLock(
599 profileName,
600 Effect.gen(function* () {
601 const current = yield* reload ?? Effect.succeed(c);
602 if (current.method !== "oauth" || !("scopes" in current)) {
603 return { type: "browser" as const };
604 }
605 const currentCredentials: OAuthClient.OAuthCredentials = {
606 type: "oauth",
607 clientId: current.clientId,
608 access: Redacted.make(current.access),
609 refresh: Redacted.make(current.refresh),
610 expires: current.expires,
611 scopes: current.scopes,
612 };
613 if (!OAuthClient.usesCurrentClient(currentCredentials)) {
614 return yield* migrateToCurrentClient;
615 }
616 return yield* Interaction.info(
617 "Cloudflare: refreshing OAuth credentials...",
618 ).pipe(
619 Effect.andThen(OAuthClient.refresh(currentCredentials)),
620 Effect.flatMap((credentials) => {
621 const config = {
622 ...current,
623 clientId: credentials.clientId,
624 access: Redacted.value(credentials.access),
625 refresh: Redacted.value(credentials.refresh),
626 expires: credentials.expires,
627 scopes: credentials.scopes,
628 };
629 // Saved here, under the lock, when the caller can
630 // take it; otherwise handed back for the caller to save.
631 const unsaved: Effect.Effect<typeof config | undefined, AuthError> =
632 updateConfig === undefined
633 ? Effect.succeed(config)
634 : Effect.as(updateConfig(config), undefined);
635 return unsaved.pipe(
636 Effect.map((config) => ({ type: "refreshed" as const, config })),
637 );
638 }),
639 Effect.tap(() =>
640 Interaction.success("Cloudflare: OAuth credentials refreshed."),
641 ),
642 Effect.catchTag(
643 [
644 "OAuthError",
645 "OAuthNetworkError",
646 "OAuthServerUnavailable",
647 "OAuthInvalidResponse",
648 ],
649 () => Effect.succeed({ type: "browser" as const }),
650 ),
651 );
652 }),
653 )
654 : yield* migrateToCurrentClient;
655 if (outcome.type === "browser") {
656 return yield* fullLogin;
657 }
658 return outcome.config;
659 })
660 : configureOAuth(profileName, c),
661 ),
662 Match.exhaustive,
663 // A blanket mapError must never swallow the NeedsReauth tag —
664 // the profile UI matches on it to render "needs re-login".
665 Effect.mapError((e) =>
666 Schema.is(NeedsReauth)(e) ? e : AuthError.make({ message: "login failed", cause: e }),
667 ),
668 );
669
670 const details = (
671 profileName: string,
672 config: CloudflareAuthConfig,
673 updateConfig?: (config: CloudflareAuthConfig) => Effect.Effect<void, AuthError>,
674 ) =>
675 Effect.all([
676 resolveCredentials(profileName, config, updateConfig),
677 Clock.currentTimeMillis,
678 ]).pipe(
679 Effect.map(([creds, now]) => {
680 const resolvedSource: CloudflareResolvedCredentials["source"] = creds.source;
681 const source = {
682 key: "source",
683 value: resolvedSource.details
684 ? `${resolvedSource.type} - ${resolvedSource.details}`
685 : resolvedSource.type,
686 };
687 return {
688 lines: Match.value(creds).pipe(
689 Match.when({ type: "apiToken" }, (c) => [
690 { key: "apiToken", value: displayRedacted(c.apiToken, 9) },
691 { key: "accountId", value: c.accountId },
692 source,
693 ]),
694 Match.when({ type: "apiKey" }, (c) => [
695 { key: "apiKey", value: displayRedacted(c.apiKey) },
696 { key: "email", value: displayRedacted(c.email) },
697 { key: "accountId", value: c.accountId },
698 source,
699 ]),
700 Match.when({ type: "oauth" }, (c) => {
701 const remainingMs = c.expires - now;
702 const expiresAt = new Date(c.expires).toISOString();
703 const expiresStr =
704 remainingMs <= 0
705 ? `expired (${expiresAt})`
706 : `in ${Duration.format(Duration.millis(remainingMs))} (${expiresAt})`;
707 return [
708 { key: "accessToken", value: displayRedacted(c.accessToken) },
709 { key: "expires", value: expiresStr },
710 { key: "accountId", value: c.accountId },
711 source,
712 ];
713 }),
714 Match.exhaustive,
715 ),
716 };
717 }),
718 );
719
720 /**
721 * Persist flag-provided stored credentials (`--method stored`). Writes
722 * the same `cloudflare-stored` file the interactive stored path writes;
723 * OAuth is interactive-only and not accepted here.
724 */
725 const configureWith = (
726 profileName: string,
727 input: { readonly method: string; readonly values: Record<string, string> },
728 ): Effect.Effect<CloudflareAuthConfig, AuthError> => {
729 const persist = (config: CloudflareAuthConfig) =>
730 clearStoreCredentials(store, profileName).pipe(Effect.ignore, Effect.as(config));
731 if (input.method !== "stored") {
732 return Effect.fail(
733 AuthError.make({
734 message: `Cloudflare: unknown method '${input.method}'. Valid methods: stored. (OAuth is interactive-only.)`,
735 }),
736 );
737 }
738 return validateFieldValues(CLOUDFLARE_AUTH_PROVIDER_NAME, storedFields, input.values).pipe(
739 Effect.flatMap((values) => {
740 const accountId = (storedValueText(values.accountId) ?? "").trim().toLowerCase();
741 const apiToken = storedSecret(values.apiToken);
742 const apiKey = storedSecret(values.apiKey);
743 const email = storedValueText(values.email);
744 if (apiToken !== undefined && apiKey === undefined && email === undefined) {
745 return persist({
746 method: "stored",
747 credentialType: "apiToken",
748 apiToken: Redacted.value(apiToken),
749 accountId,
750 });
751 }
752 if (apiToken === undefined && apiKey !== undefined && email !== undefined) {
753 return persist({
754 method: "stored",
755 credentialType: "apiKey",
756 apiKey: Redacted.value(apiKey),
757 email,
758 accountId,
759 });
760 }
761 return Effect.fail(
762 AuthError.make({
763 message:
764 "Cloudflare: pass either --set apiToken=<token>, or both --set apiKey=<key> and --set email=<email>.",
765 }),
766 );
767 }),
768 );
769 };
770
771 return {
772 configSchema: CloudflareAuthConfigSchema,
773 configure: configureCredentials,
774 configureWith,
775 configureMethods,
776 logout,
777 login,
778 details,
779 read: resolveCredentials,
780 readEnvironment,
781 environment: [
782 {
783 name: "CLOUDFLARE_ACCOUNT_ID",
784 required: true,
785 description: "Account the stack deploys into.",
786 },
787 {
788 name: "CLOUDFLARE_API_TOKEN",
789 required: true,
790 secret: true,
791 alternatives: ["CLOUDFLARE_API_KEY"],
792 description:
793 "API token (preferred). Not consulted when unset and CLOUDFLARE_API_KEY + CLOUDFLARE_EMAIL are provided instead.",
794 },
795 {
796 name: "CLOUDFLARE_API_KEY",
797 required: false,
798 secret: true,
799 description: "Global API key; used with CLOUDFLARE_EMAIL when no API token is set.",
800 },
801 {
802 name: "CLOUDFLARE_EMAIL",
803 required: false,
804 alternatives: ["CLOUDFLARE_ACCOUNT_EMAIL"],
805 description: "Account email paired with CLOUDFLARE_API_KEY.",
806 },
807 ],
808 };
809 }),
810 );