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

main
ts 359 lines 11.1 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 GetAppsSecrets,
4 GetAppsSecretsFind,
5 CreateAppsSecret,
6 CreateAppsSecretsDelete,
7 type AppsSecret as StripeAppsSecret,
8 type GetAppsSecretsFindRequestScope,
9 type GetAppsSecretsRequestScope,
10 type CreateAppsSecretsDeleteRequestScope,
11 type CreateAppsSecretRequestScope,
12 } from "@distilled.cloud/stripe/stripe";
13 import { isResolved } from "alchemy/Diff";
14 import { createPhysicalName } from "alchemy/PhysicalName";
15 import * as Provider from "alchemy/Provider";
16 import { Resource } from "alchemy/Resource";
17 import * as Data from "effect/Data";
18 import * as Effect from "effect/Effect";
19 import { isMissingStripeResource } from "./missing.ts";
20 import type { Providers } from "./Providers.ts";
21
22 const NAME_MAX_LENGTH = 250;
23 const LIST_PAGE_SIZE = 100;
24 const LIST_MAX_PAGES = 100;
25
26 /** The secret scope type. */
27 export type AppsSecretScopeType = "account" | "user";
28
29 /** Specifies the scoping of the secret. */
30 export interface AppsSecretScope {
31 /**
32 * The secret scope type. `account` secrets are shared by all Dashboard
33 * users and the app backend. `user` secrets are visible to the app
34 * backend and one Dashboard user.
35 */
36 type: AppsSecretScopeType;
37 /**
38 * The user ID. Required when `type` is `user`, and must not be set when
39 * `type` is `account`.
40 */
41 user?: string;
42 }
43
44 export interface AppsSecretProps {
45 /**
46 * A name for the secret that's unique within the scope. If omitted, a
47 * unique name is generated from the stack, stage, and logical id.
48 * Changing it replaces the secret.
49 */
50 name?: string;
51 /**
52 * The plaintext secret value to be stored.
53 */
54 payload: string;
55 /**
56 * Specifies the scoping of the secret. Changing type or user replaces
57 * the secret.
58 * @default { type: "account" }
59 */
60 scope?: AppsSecretScope;
61 /**
62 * Unix timestamp after which the secret deletes.
63 */
64 expiresAt?: number;
65 }
66
67 export type AppsSecret = Resource<
68 "Stripe.AppsSecret",
69 AppsSecretProps,
70 {
71 /** Stripe secret id (`appsecret_…` or `secret_…`). */
72 id: string;
73 /** Name unique within the scope. */
74 name: string;
75 /** Scoping of the secret. */
76 scope: AppsSecretScope;
77 /** Unix timestamp after which the secret deletes, if set. */
78 expiresAt: number | undefined;
79 /** Whether this secret has been deleted. */
80 deleted: boolean | undefined;
81 /** Unix timestamp when the secret was created. */
82 created: number;
83 /** Whether the secret exists in live mode. */
84 livemode: boolean;
85 },
86 never,
87 Providers
88 >;
89
90 /**
91 * A Stripe Apps Secret — a named secret in the Stripe Apps Secret Store,
92 * used by UI extensions and app backends. Secrets are unique per
93 * `(name, scope)`. Create is upsert: posting the same name and scope
94 * replaces payload and expiry. Name and scope are identity; changing
95 * them replaces the secret. Destroy deletes it.
96 *
97 * Apps secrets have no metadata. Identity is name + scope. `list()`
98 * enumerates account-scoped secrets (user-scoped secrets require a user
99 * id and are not returned).
100 *
101 * @see https://docs.stripe.com/stripe-apps/store-secrets
102 *
103 * ### Creating a Secret
104 * **Example:** Account-scoped secret
105 * ```typescript
106 * const apiKey = yield* Stripe.AppsSecret("third-party-api", {
107 * name: "third-party-api",
108 * payload: "sk_live_example",
109 * scope: { type: "account" },
110 * });
111 * ```
112 *
113 * **Example:** Generated name
114 * ```typescript
115 * const apiKey = yield* Stripe.AppsSecret("third-party-api", {
116 * payload: "sk_live_example",
117 * });
118 * ```
119 *
120 * ### Updating a Secret
121 * **Example:** Rotate payload
122 * ```typescript
123 * const apiKey = yield* Stripe.AppsSecret("third-party-api", {
124 * name: "third-party-api",
125 * payload: "sk_live_rotated",
126 * scope: { type: "account" },
127 * });
128 * ```
129 *
130 * ### User-scoped secrets
131 * **Example:** Per-user OAuth token
132 * ```typescript
133 * const oauth = yield* Stripe.AppsSecret("user-oauth", {
134 * name: "oauth-token",
135 * payload: "tok_example",
136 * scope: { type: "user", user: "usr_123" },
137 * });
138 * ```
139 *
140 * @resource
141 * @product Secrets
142 */
143 export const AppsSecret = Resource<AppsSecret>("Stripe.AppsSecret");
144
145 export class AppsSecretNotResolved extends Data.TaggedError("Stripe.AppsSecretNotResolved")<{
146 resourceName: string;
147 }> {}
148
149 type AppsSecretAttributes = AppsSecret["Attributes"];
150
151 const accountScope = (): AppsSecretScope => ({ type: "account" });
152
153 const toScope = (scope: AppsSecretScope | undefined): AppsSecretScope => {
154 const type = scope?.type ?? "account";
155 if (type === "user" && scope?.user !== undefined) {
156 return { type, user: scope.user };
157 }
158 return { type };
159 };
160
161 const toWireScope = (
162 scope: AppsSecretScope,
163 ): CreateAppsSecretRequestScope &
164 GetAppsSecretsFindRequestScope &
165 GetAppsSecretsRequestScope &
166 CreateAppsSecretsDeleteRequestScope =>
167 scope.user !== undefined ? { type: scope.type, user: scope.user } : { type: scope.type };
168
169 const fromObservedScope = (scope: StripeAppsSecret["scope"]): AppsSecretScope =>
170 scope.user !== undefined ? { type: scope.type, user: scope.user } : { type: scope.type };
171
172 const scopesEqual = (left: AppsSecretScope, right: AppsSecretScope): boolean =>
173 left.type === right.type && (left.user ?? undefined) === (right.user ?? undefined);
174
175 const toName = (id: string, name: string | undefined, existing?: string) =>
176 Effect.gen(function* () {
177 return name ?? existing ?? (yield* createPhysicalName({ id, maxLength: NAME_MAX_LENGTH }));
178 });
179
180 const toAttrs = (secret: StripeAppsSecret): AppsSecretAttributes => ({
181 id: secret.id,
182 name: secret.name,
183 scope: fromObservedScope(secret.scope),
184 expiresAt: secret.expires_at ?? undefined,
185 deleted: secret.deleted,
186 created: secret.created,
187 livemode: secret.livemode,
188 });
189
190 const isMissingSecret = isMissingStripeResource;
191
192 const isPresent = (secret: StripeAppsSecret | undefined): secret is StripeAppsSecret =>
193 secret !== undefined && secret.deleted !== true;
194
195 const findByName = (name: string, scope: AppsSecretScope) =>
196 GetAppsSecretsFind({
197 name,
198 scope: toWireScope(scope),
199 expand: ["payload"],
200 }).pipe(
201 Effect.map((secret) => (isPresent(secret) ? secret : undefined)),
202 Effect.catchIf(isMissingSecret, () => Effect.undefined),
203 );
204
205 const listByScope = Effect.fn(function* (scope: AppsSecretScope) {
206 const secrets: StripeAppsSecret[] = [];
207 let startingAfter: string | undefined;
208 for (let page = 0; page < LIST_MAX_PAGES; page++) {
209 const response = yield* GetAppsSecrets({
210 scope: toWireScope(scope),
211 limit: LIST_PAGE_SIZE,
212 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
213 });
214 secrets.push(...response.data);
215 if (!response.has_more || response.data.length === 0) {
216 break;
217 }
218 startingAfter = response.data[response.data.length - 1]?.id;
219 if (startingAfter === undefined) {
220 break;
221 }
222 }
223 return secrets.filter(isPresent);
224 });
225
226 const observe = Effect.fn(function* (input: {
227 id?: string;
228 name?: string;
229 scope: AppsSecretScope;
230 }) {
231 if (input.name !== undefined) {
232 const byName = yield* findByName(input.name, input.scope);
233 if (byName !== undefined) return byName;
234 }
235 if (input.id !== undefined) {
236 const secrets = yield* listByScope(input.scope);
237 const byId = secrets.find((secret) => secret.id === input.id);
238 if (byId !== undefined) {
239 const expanded = yield* findByName(byId.name, fromObservedScope(byId.scope));
240 if (expanded !== undefined) return expanded;
241 return byId;
242 }
243 }
244 return undefined;
245 });
246
247 const shouldReplace = (
248 news: AppsSecretProps,
249 output: AppsSecretAttributes | undefined,
250 ): boolean => {
251 if (output === undefined) return false;
252 if (news.name !== undefined && news.name !== output.name) return true;
253 if (news.scope !== undefined && !scopesEqual(toScope(news.scope), output.scope)) {
254 return true;
255 }
256 return false;
257 };
258
259 export const AppsSecretProvider = () =>
260 Provider.succeed(AppsSecret, {
261 stables: ["name", "scope", "livemode"],
262
263 diff: Effect.fn(function* ({ news, output }) {
264 if (!isResolved(news)) return undefined;
265 if (shouldReplace(news, output)) {
266 return { action: "replace" as const };
267 }
268 return undefined;
269 }),
270
271 read: Effect.fn(function* ({ output, olds }) {
272 const name = output?.name ?? (typeof olds?.name === "string" ? olds.name : undefined);
273 const scope = toScope(
274 output?.scope ??
275 (olds?.scope !== undefined && typeof olds.scope === "object"
276 ? (olds.scope as AppsSecretScope)
277 : undefined),
278 );
279 const existing = yield* observe({
280 id: output?.id,
281 name,
282 scope,
283 });
284 if (existing === undefined) return undefined;
285 // No metadata. Identity is name + scope; a match is treated as owned.
286 return toAttrs(existing);
287 }),
288
289 list: Effect.fn(function* () {
290 // Apps secrets have no metadata. List is account-scoped secrets;
291 // user-scoped rows require a user id and are not enumerated. Deleted
292 // rows are omitted so they do not re-enter nuke.
293 const secrets = yield* listByScope(accountScope());
294 return secrets.map(toAttrs);
295 }),
296
297 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
298 const name = yield* toName(id, news.name, output?.name);
299 const scope = toScope(news.scope ?? output?.scope);
300 const desiredExpiresAt = news.expiresAt;
301
302 let current = yield* observe({
303 id: output?.id,
304 name,
305 scope,
306 });
307 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
308 current = undefined;
309 }
310
311 const put = (idempotencyKey: string) =>
312 CreateAppsSecret({
313 name,
314 payload: news.payload,
315 scope: toWireScope(scope),
316 ...(desiredExpiresAt !== undefined ? { expires_at: desiredExpiresAt } : {}),
317 }).pipe(
318 withRequestOptions({
319 idempotencyKey,
320 }),
321 );
322
323 if (current === undefined) {
324 current = yield* put(`alchemy-apps-secret-${instanceId}`).pipe(
325 Effect.catchIf(
326 (e) => e._tag === "InvalidRequestError" || e._tag === "Conflict",
327 (e) =>
328 observe({ name, scope }).pipe(
329 Effect.flatMap((found) =>
330 found !== undefined ? Effect.succeed(found) : Effect.fail(e),
331 ),
332 ),
333 ),
334 );
335 }
336
337 if (current === undefined) {
338 return yield* new AppsSecretNotResolved({ resourceName: name });
339 }
340
341 const observedPayload = current.payload ?? undefined;
342 const payloadChanged = observedPayload !== undefined && observedPayload !== news.payload;
343 const expiresChanged = (current.expires_at ?? undefined) !== desiredExpiresAt;
344
345 if (!payloadChanged && !expiresChanged) {
346 return toAttrs(current);
347 }
348
349 current = yield* put(`alchemy-apps-secret-${instanceId}-sync`);
350 return toAttrs(current);
351 }),
352
353 delete: Effect.fn(function* ({ output }) {
354 yield* CreateAppsSecretsDelete({
355 name: output.name,
356 scope: toWireScope(output.scope),
357 }).pipe(Effect.catchIf(isMissingSecret, () => Effect.void));
358 }),
359 });