@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, 06:00 UTC

main
ts 225 lines 7.54 KB
Raw
1 import type { ConfigError } from "@distilled.cloud/core/errors";
2 import {
3 Credentials,
4 DEFAULT_API_BASE_URL,
5 type Config as StripeCredentialsConfig,
6 } from "@distilled.cloud/stripe";
7 import * as Binding from "alchemy/Binding";
8 import * as Output from "alchemy/Output";
9 import { type ResourceLike } from "alchemy/Resource";
10 import type { RuntimeContext } from "alchemy/RuntimeContext";
11 import * as Effect from "effect/Effect";
12 import * as FetchHttpClient from "effect/http/FetchHttpClient";
13 import * as HttpClient from "effect/http/HttpClient";
14 import * as Layer from "effect/Layer";
15 import * as Option from "effect/Option";
16 import * as Redacted from "effect/Redacted";
17 import { RestrictedApiKey, type StripePermission } from "./RestrictedApiKey.ts";
18
19 /**
20 * Shared scaffolding for HTTP Stripe bindings.
21 *
22 * Stripe has no native Worker binding. Secrets and resource ids are
23 * registered via `yield* token.value` / `yield* resource.id` so
24 * RuntimeContext.set + packEnvValueKeepRedacted emit `secret_text`.
25 * Do not push raw `{ type: "secret_text", text }` items — the Worker
26 * provider forwards those to the wire un-resolved. Do not
27 * `Output.asEffect` + unwrap at bind time — that resolves before the
28 * RestrictedApiKey exists.
29 *
30 * NOT exported from `index.ts`.
31 */
32
33 export interface StripeIdResource {
34 readonly LogicalId: string;
35 readonly id: unknown;
36 }
37
38 export interface StripeAuth {
39 authorize: <A, E>(
40 eff: Effect.Effect<A, E, Credentials | HttpClient.HttpClient>,
41 ) => Effect.Effect<A, E, RuntimeContext>;
42 }
43
44 /**
45 * Accessor for a bound RestrictedApiKey value. The `yield*` of `token.value`
46 * is RuntimeContext.set — it does not resolve the secret at plan time.
47 */
48 const stripeRuntimeLayer = (
49 credentials: Effect.Effect<StripeCredentialsConfig>,
50 ): Layer.Layer<Credentials | HttpClient.HttpClient> =>
51 Layer.succeed(Credentials, credentials).pipe(Layer.provideMerge(FetchHttpClient.layer));
52
53 export const authorizeWith =
54 (token: { value: Effect.Effect<Redacted.Redacted<string>> }) =>
55 <A, E>(
56 eff: Effect.Effect<A, E, Credentials | HttpClient.HttpClient>,
57 ): Effect.Effect<A, E, RuntimeContext> =>
58 token.value.pipe(
59 Effect.flatMap((apiKey) =>
60 eff.pipe(
61 Effect.provide(
62 stripeRuntimeLayer(
63 Effect.succeed({
64 apiKey,
65 apiBaseUrl: DEFAULT_API_BASE_URL,
66 } satisfies StripeCredentialsConfig),
67 ),
68 ),
69 ),
70 ),
71 ) as Effect.Effect<A, E, RuntimeContext>;
72
73 export const makeStripeAuth = (options: {
74 credentials: Effect.Effect<StripeCredentialsConfig, ConfigError> | undefined;
75 http: HttpClient.HttpClient | undefined;
76 }): StripeAuth => ({
77 authorize: <A, E>(
78 eff: Effect.Effect<A, E, Credentials | HttpClient.HttpClient>,
79 ): Effect.Effect<A, E, RuntimeContext> => {
80 if (options.credentials === undefined || options.http === undefined) {
81 return Effect.die(
82 "Stripe HTTP binding missing Credentials or HttpClient at plan time",
83 ) as Effect.Effect<A, E, RuntimeContext>;
84 }
85 return eff.pipe(
86 Effect.provide(
87 Layer.mergeAll(
88 Layer.succeed(Credentials, options.credentials),
89 Layer.succeed(HttpClient.HttpClient, options.http),
90 ),
91 ),
92 ) as Effect.Effect<A, E, RuntimeContext>;
93 },
94 });
95
96 export const resolveStripeAuth = Effect.gen(function* () {
97 const credentials = yield* Effect.serviceOption(Credentials).pipe(
98 Effect.map(Option.getOrUndefined),
99 );
100 const http = yield* Effect.serviceOption(HttpClient.HttpClient).pipe(
101 Effect.map(Option.getOrUndefined),
102 );
103 return makeStripeAuth({ credentials, http });
104 });
105
106 /**
107 * Bind an Output (or plain string) at init. `yield*` this at bind time so
108 * RuntimeContext.set runs; the inner Effect is the runtime getter.
109 * Never unwrap the Output to a string here.
110 */
111 export const asStringEffect = (value: unknown): Effect.Effect<Effect.Effect<string>> => {
112 if (typeof value === "string") {
113 return Effect.succeed(Effect.succeed(value));
114 }
115 if (Output.isOutput(value)) {
116 return value.asEffect() as Effect.Effect<Effect.Effect<string>>;
117 }
118 if (Effect.isEffect(value)) {
119 // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- resource id Effects resolve without requirements
120 return Effect.succeed(value as Effect.Effect<string>);
121 }
122 return Effect.die("Stripe binding expected a resolved resource id");
123 };
124
125 /** Like {@link asStringEffect} for optional string fields. */
126 export const asOptionalStringEffect = (
127 value: unknown,
128 ): Effect.Effect<Effect.Effect<string | undefined>> => {
129 if (value === undefined || value === null || value === "") {
130 return Effect.succeed(Effect.undefined);
131 }
132 return asStringEffect(value).pipe(
133 Effect.map((inner) => inner.pipe(Effect.map((s) => (s.length > 0 ? s : undefined)))),
134 );
135 };
136
137 /**
138 * Mint (or reuse) the host's RestrictedApiKey and attach permissions.
139 * Returns a runtime accessor for the key value (`yield* token.value`).
140 * That Output is the plan-to-runtime transport on every host — do not
141 * also `host.bind({ env })`.
142 */
143 const missingHostToken = {
144 value: Effect.die("Stripe token accessed without a host") as Effect.Effect<
145 Redacted.Redacted<string>
146 >,
147 };
148
149 export const attachStripeToken = (
150 resource: ResourceLike | undefined,
151 permissions: readonly StripePermission[],
152 bindId: string,
153 ) =>
154 Effect.gen(function* () {
155 const host = yield* Binding.Host;
156 if (host === undefined) {
157 return missingHostToken;
158 }
159 const Token = yield* RestrictedApiKey;
160 const token = yield* Token(`${host.LogicalId}StripeToken`, {});
161 if (!globalThis.__ALCHEMY_RUNTIME__) {
162 const sid =
163 resource !== undefined ? `${bindId}:${resource.LogicalId}` : `${bindId}:${host.LogicalId}`;
164 yield* token.bind(sid, {
165 permissions: [...permissions],
166 });
167 }
168 return { value: yield* token.value };
169 });
170
171 export const makeHttpStripeIdBinding = <
172 I extends Record<IdField, string>,
173 A,
174 E,
175 IdField extends string,
176 >(options: {
177 tag: string;
178 operation: (input: I) => Effect.Effect<A, E, Credentials | HttpClient.HttpClient>;
179 idField: IdField;
180 permissions: readonly StripePermission[];
181 }) =>
182 Effect.gen(function* () {
183 const ambient = yield* resolveStripeAuth;
184
185 return Effect.fn(function* (resource: StripeIdResource) {
186 const host = yield* Binding.Host;
187 const bound = yield* attachStripeToken(
188 resource as unknown as ResourceLike,
189 options.permissions,
190 options.tag,
191 );
192 const id = yield* asStringEffect(resource.id);
193 const auth = host !== undefined ? authorizeWith(bound) : ambient.authorize;
194
195 return Effect.fn(`${options.tag}(${resource.LogicalId})`)(function* (
196 request?: Omit<I, IdField>,
197 ) {
198 return yield* auth(
199 options.operation({
200 ...(request as object),
201 [options.idField]: yield* id,
202 } as I),
203 );
204 });
205 });
206 });
207
208 export const makeHttpStripeAccountBinding = <I, A, E>(options: {
209 tag: string;
210 operation: (input: I) => Effect.Effect<A, E, Credentials | HttpClient.HttpClient>;
211 permissions: readonly StripePermission[];
212 }) =>
213 Effect.gen(function* () {
214 const ambient = yield* resolveStripeAuth;
215
216 return Effect.fn(function* () {
217 const host = yield* Binding.Host;
218 const bound = yield* attachStripeToken(undefined, options.permissions, options.tag);
219 const auth = host !== undefined ? authorizeWith(bound) : ambient.authorize;
220
221 return Effect.fn(options.tag)(function* (request: I) {
222 return yield* auth(options.operation(request));
223 });
224 });
225 });