| 1 | import { DEFAULT_API_BASE_URL } from "@distilled.cloud/stripe"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as Redacted from "effect/Redacted"; |
| 4 | import { getEnv, getEnvRedactedRequired } from "../Auth/Env.ts"; |
| 5 | import { |
| 6 | makeStoredAuthProvider, |
| 7 | storedSecret, |
| 8 | storedValueText, |
| 9 | type StoredAuthConfig, |
| 10 | } from "../Auth/StoredAuthProvider.ts"; |
| 11 | |
| 12 | export const STRIPE_AUTH_PROVIDER_NAME = "Stripe"; |
| 13 | export const STRIPE_API_KEY_ENV = "STRIPE_API_KEY"; |
| 14 | export const STRIPE_API_BASE_URL_ENV = "STRIPE_API_BASE_URL"; |
| 15 | |
| 16 | export type StripeAuthConfig = StoredAuthConfig; |
| 17 | |
| 18 | export type StripeResolvedCredentials = { |
| 19 | type: "apiKey"; |
| 20 | apiKey: Redacted.Redacted<string>; |
| 21 | apiBaseUrl: string; |
| 22 | source: { type: StripeAuthConfig["method"] | "env"; details?: string }; |
| 23 | }; |
| 24 | |
| 25 | const stripeAuth = makeStoredAuthProvider<StripeResolvedCredentials>({ |
| 26 | provider: STRIPE_AUTH_PROVIDER_NAME, |
| 27 | fields: [ |
| 28 | { name: "apiKey", label: "Stripe Secret API Key", secret: true }, |
| 29 | { |
| 30 | name: "apiBaseUrl", |
| 31 | label: "Stripe API base URL", |
| 32 | optional: true, |
| 33 | placeholder: DEFAULT_API_BASE_URL, |
| 34 | }, |
| 35 | ], |
| 36 | toResolved: (values) => ({ |
| 37 | type: "apiKey", |
| 38 | apiKey: storedSecret(values.apiKey) ?? Redacted.make(""), |
| 39 | apiBaseUrl: storedValueText(values.apiBaseUrl) ?? DEFAULT_API_BASE_URL, |
| 40 | source: { type: "stored" }, |
| 41 | }), |
| 42 | readEnvironment: Effect.all({ |
| 43 | apiKey: getEnvRedactedRequired(STRIPE_API_KEY_ENV), |
| 44 | apiBaseUrl: getEnv(STRIPE_API_BASE_URL_ENV), |
| 45 | }).pipe( |
| 46 | Effect.map(({ apiKey, apiBaseUrl }) => ({ |
| 47 | type: "apiKey" as const, |
| 48 | apiKey, |
| 49 | apiBaseUrl: apiBaseUrl ?? DEFAULT_API_BASE_URL, |
| 50 | source: { |
| 51 | type: "env" as const, |
| 52 | details: apiBaseUrl |
| 53 | ? `${STRIPE_API_KEY_ENV}, ${STRIPE_API_BASE_URL_ENV}` |
| 54 | : STRIPE_API_KEY_ENV, |
| 55 | }, |
| 56 | })), |
| 57 | ), |
| 58 | environment: [ |
| 59 | { name: STRIPE_API_KEY_ENV, required: true, secret: true }, |
| 60 | { name: STRIPE_API_BASE_URL_ENV, required: false }, |
| 61 | ], |
| 62 | }); |
| 63 | |
| 64 | /** |
| 65 | * Layer that registers the Stripe {@link AuthProvider} into the |
| 66 | * {@link AuthProviders} registry. Include this in the Stripe `providers()` |
| 67 | * layer so the alchemy CLI can discover it. |
| 68 | * |
| 69 | * Auth is a Stripe secret API key (`STRIPE_API_KEY`, typically `sk_test_…` |
| 70 | * or `sk_live_…`). There is no OAuth flow. An optional |
| 71 | * `STRIPE_API_BASE_URL` overrides the API root (default |
| 72 | * `https://api.stripe.com`). |
| 73 | */ |
| 74 | export const StripeAuth = stripeAuth.layer; |