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

main
mdx 225 lines 8.48 KB
Raw
1 ---
2 title: Custom Auth Provider
3 description: Add profile and CI credentials for a third-party API with a generated AuthProvider.
4 ---
5
6 The [Custom Provider](/infrastructure-as-code/custom-provider) guide builds a
7 Stripe `Product` provider whose lifecycle handlers need an API key. This guide
8 builds a lazy `StripeCredentials` service backed
9 by an Auth Provider, so the key comes from the configured
10 [Profile](/environments/profiles), from env vars in CI, or from a refreshable
11 session, never from props or hardcoded config. For a token-shaped credential
12 the whole provider is generated by `makeStoredAuthProvider` from a field list;
13 the in-repo [Neon provider](https://github.com/alchemy-run/alchemy/blob/main/packages/neon/src/AuthProvider.ts)
14 is exactly this shape.
15
16 For the profile method contract, CI resolver, registry, and lazy resolution,
17 see [Auth Providers](/environments/auth-providers).
18
19 ## Declare a lazy credentials service
20
21 The service value is an `Effect`, not a resolved struct:
22
23 ```typescript
24 // src/stripe/Credentials.ts
25 import * as Context from "effect/Context";
26 import * as Effect from "effect/Effect";
27 import * as Redacted from "effect/Redacted";
28
29 export class StripeCredentials extends Context.Service<
30 StripeCredentials,
31 Effect.Effect<{ apiKey: Redacted.Redacted<string> }>
32 >()("StripeCredentials") {}
33 ```
34
35 Provider Layers are built on every CLI invocation — before any Profile is
36 configured — so nothing may resolve at Layer construction. Consumers run the
37 Effect only when an operation executes, and a session-backed implementation can
38 put refresh logic inside it. Every built-in credentials service has this shape
39 (`CloudflareEnvironment`, `AWSEnvironment`, the distilled SDK `Credentials`
40 tags).
41
42 ## Generate the Auth Provider
43
44 `makeStoredAuthProvider` turns a field list into a complete provider:
45 interactive prompts, flag-driven configuration
46 (`--method stored --set apiKey=...`), schema-validated persistence at
47 `~/.alchemy/credentials/{profile}/stripe-stored.json`, `login`/`logout`,
48 structured `details` for `alchemy profile show`, and a typed `NeedsReauth`
49 failure when the credential file is missing.
50
51 ```typescript
52 // src/stripe/AuthProvider.ts
53 import { AuthError } from "alchemy/Auth/AuthProvider";
54 import { makeStoredAuthProvider } from "alchemy/Auth/StoredAuthProvider";
55 import { getEnvRedactedRequired } from "alchemy/Auth/Env";
56 import * as Effect from "effect/Effect";
57 import * as Redacted from "effect/Redacted";
58
59 export const STRIPE_AUTH_PROVIDER_NAME = "Stripe";
60
61 export type StripeResolvedCredentials = {
62 type: "apiKey";
63 apiKey: Redacted.Redacted<string>;
64 source: { type: "stored" | "env" };
65 };
66
67 export const { layer: StripeAuth, storedSchema: StripeStoredCredentials } =
68 makeStoredAuthProvider<StripeResolvedCredentials>({
69 provider: STRIPE_AUTH_PROVIDER_NAME,
70 fields: [
71 {
72 name: "apiKey",
73 label: "Stripe Secret API Key",
74 secret: true,
75 validate: (value) =>
76 value.startsWith("sk_") ? undefined : "Expected an sk_... key",
77 },
78 ],
79 toResolved: (values, source) => ({
80 type: "apiKey",
81 apiKey: Redacted.make(values.apiKey!),
82 source: { type: source },
83 }),
84 readEnvironment: getEnvRedactedRequired("STRIPE_API_KEY").pipe(
85 Effect.map((apiKey) => ({
86 type: "apiKey" as const,
87 apiKey,
88 source: { type: "env" as const },
89 })),
90 ),
91 environment: [
92 {
93 name: "STRIPE_API_KEY",
94 required: true,
95 secret: true,
96 description: "Stripe secret API key.",
97 },
98 ],
99 });
100 ```
101
102 `fields` drive interactive prompts and `--set`; each field name is also the
103 property persisted in the credentials file, alongside `method: "stored"`
104 (the `--method` value). Validation applies to both paths.
105 The generated `storedSchema` validates credential reads and writes.
106 `readEnvironment` resolves CI credentials, while `environment` documents
107 the variables it consumes. Missing stored credentials appear as
108 `NeedsReauth` in the profile UI.
109
110 ## Bridge the Auth Provider to the credentials service
111
112 `lazyCredentials` connects the two: it resolves through the registered
113 provider (environment credentials, then CI, then the selected Profile) on
114 first use, caches the result, and maps it onto the service's shape:
115
116 ```typescript
117 // src/stripe/Credentials.ts (additions)
118 import { lazyCredentials } from "alchemy/Auth/Resolve";
119 import * as Layer from "effect/Layer";
120 import {
121 STRIPE_AUTH_PROVIDER_NAME,
122 type StripeResolvedCredentials,
123 } from "./AuthProvider.ts";
124
125 export const fromAuthProvider = () =>
126 Layer.effect(
127 StripeCredentials,
128 lazyCredentials<StripeResolvedCredentials>()(STRIPE_AUTH_PROVIDER_NAME, (creds) => ({
129 apiKey: creds.apiKey,
130 })).pipe(
131 // `StripeCredentials` is typed as never failing, so a failure dies; the
132 // engine still reports it as `CredentialsRequired`.
133 Effect.map(Effect.orDie),
134 ),
135 );
136 ```
137
138 Nothing resolves until a handler runs the service's Effect, and within one
139 process `read` (and its file lock) runs once. Credentials that expire pass
140 `{ expiresAt }` so a long dev session re-resolves instead of keeping a dead
141 token. A failed resolution fails with `CredentialsUnavailable`, which the
142 engine reports as `CredentialsRequired`; when the service is a client SDK's
143 own `Credentials` tag, name its error channel as the second type argument
144 (`lazyCredentials<Resolved, ConfigError>()`).
145
146 ## Bundle into `providers()`
147
148 Merge the auth machinery into the same `providers()` Layer that carries the
149 resource providers, mirroring
150 [`Neon/Providers.ts`](https://github.com/alchemy-run/alchemy/blob/main/packages/neon/src/Providers.ts):
151
152 ```typescript
153 // src/stripe/Providers.ts
154 import { CredentialsStoreLive } from "alchemy/Auth/Credentials";
155 import { ProfileStoreLive } from "alchemy/Auth/Profile";
156 import * as Provider from "alchemy/Provider";
157 import * as Layer from "effect/Layer";
158 import { StripeAuth } from "./AuthProvider.ts";
159 import * as Credentials from "./Credentials.ts";
160 import { StripeProduct, StripeProductProvider } from "./Product.ts";
161
162 export class Providers extends Provider.ProviderCollection<Providers>()(
163 "Stripe",
164 ) {}
165
166 export const providers = () =>
167 Layer.effect(Providers, Provider.collection([StripeProduct])).pipe(
168 Layer.provide(StripeProductProvider()),
169 Layer.provideMerge(Credentials.fromAuthProvider()),
170 Layer.provideMerge(StripeAuth),
171 Layer.provideMerge(ProfileStoreLive),
172 Layer.provideMerge(CredentialsStoreLive),
173 Layer.orDie,
174 );
175 ```
176
177 `StripeAuth` registers the provider so the alchemy CLI discovers it;
178 `ProfileStoreLive` and `CredentialsStoreLive` give the auth machinery its
179 file-system services. (Providers that call APIs through an Effect `HttpClient`
180 also merge `FetchHttpClient.layer` here, as Neon does.)
181
182 ## Consume it from a lifecycle handler
183
184 Inside `reconcile` (or `delete`, `read`), double-yield the service — the first
185 `yield*` gets the lazy Effect out of the service, the second runs it:
186
187 ```typescript
188 // src/stripe/Product.ts
189 reconcile: Effect.fn(function* ({ news, output }) {
190 const { apiKey } = yield* yield* StripeCredentials;
191 const stripe = new Stripe(Redacted.value(apiKey));
192 // observe / ensure / sync — see the Custom Provider guide
193 }),
194 ```
195
196 This is the same idiom the built-ins use — `yield* AWSEnvironment.current`,
197 `yield* yield* CloudflareEnvironment` — and it's what keeps credentials
198 demanded exactly when an operation runs, never at Layer construction.
199
200 ## Try it
201
202 ```sh
203 alchemy deploy # first run: prompts for credentials, saves them to the profile
204 alchemy profile refresh --provider Stripe # re-authenticate without changing the method
205 alchemy profile edit --reconfigure Stripe # replace the stored credentials interactively
206
207 # non-interactive (agents, scripts): value from env, stdin, or a literal
208 alchemy profile edit --add stripe --method stored --set apiKey=env:STRIPE_API_KEY
209 op read op://vault/stripe/key | alchemy profile edit --add stripe --method stored --set apiKey=-
210
211 alchemy profile show # renders your provider's details
212 alchemy provider check-env --provider stripe # CI preflight for STRIPE_API_KEY
213 ```
214
215 In CI, profile resolution is bypassed, so setting `STRIPE_API_KEY` is all a
216 pipeline needs and no profile file is created.
217
218 ## Where next
219
220 - [Auth Providers](/environments/auth-providers) documents the profile contract,
221 CI resolver, registry, and lazy resolution.
222 - [Custom Provider](/infrastructure-as-code/custom-provider) — the lifecycle
223 handlers these credentials feed.
224 - [Profiles](/environments/profiles) — switching, inspecting, and storing the
225 per-provider config.