@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 303 lines 10.9 KB
Raw
1 import { Retry } from "@distilled.cloud/prisma";
2 import {
3 type GetBucketKeysResponse,
4 deleteBucketKey,
5 getBucketKeys,
6 createBucketKey,
7 } from "@distilled.cloud/prisma/management";
8 import { isResolved } from "alchemy/Diff";
9 import * as ProviderLayer from "alchemy/Local/ProviderLayer";
10 import * as Provider from "alchemy/Provider";
11 import { Resource } from "alchemy/Resource";
12 import * as Data from "effect/Data";
13 import * as Effect from "effect/Effect";
14 import * as Redacted from "effect/Redacted";
15 import type { Bucket } from "./Bucket.ts";
16 import { attrOrRedactedString, attrOrString, devId, devProvider } from "./internal/DevStub.ts";
17 import { physicalInstanceName } from "./internal/EnvName.ts";
18 import { type ObservedBucketKey, requiredSecretValue } from "./internal/Observed.ts";
19 import { PrismaPaginationError } from "./internal/Pagination.ts";
20 import {
21 concreteIdsChanged,
22 isInputObject,
23 isPrismaDevId,
24 resolveBucketId,
25 unresolvedBucketIdOf,
26 } from "./internal/Refs.ts";
27 import type { Providers } from "./Providers.ts";
28 import type { BucketKeyRole } from "./Types.ts";
29
30 export interface BucketAccessKeyProps {
31 /**
32 * Bucket ID or `bucket.bucketId` output this key grants access to.
33 */
34 bucket: string | Bucket;
35 /**
36 * Human-readable key name prefix. Alchemy appends the resource instance
37 * identity so an interrupted create can be recovered by name instead of
38 * minting a second, unenumerable key.
39 *
40 * @default the resource's logical ID
41 */
42 name?: string;
43 /**
44 * Access role for the key: `"read"` or `"read_write"`.
45 */
46 role: BucketKeyRole;
47 }
48
49 export interface BucketAccessKey extends Resource<
50 "Prisma.BucketAccessKey",
51 BucketAccessKeyProps,
52 {
53 /**
54 * Prisma bucket key ID.
55 */
56 bucketAccessKeyId: string;
57 /**
58 * Bucket ID the key belongs to, persisted so deletion can address both
59 * path parameters.
60 */
61 bucketId: string;
62 /**
63 * S3 access key ID.
64 */
65 accessKeyId: string;
66 /**
67 * S3 secret access key, redacted in state. Prisma returns it exactly
68 * once at creation and never again, so the persisted state is the
69 * authoritative copy.
70 */
71 secretAccessKey: Redacted.Redacted<string>;
72 /**
73 * S3-compatible endpoint URL for the bucket's region.
74 */
75 endpoint: string;
76 /**
77 * Provider-side S3 bucket name (e.g. `user-<id>`). S3 clients must use
78 * this as the bucket name, not the display name chosen on the bucket.
79 */
80 bucketName: string;
81 },
82 never,
83 Providers
84 > {}
85
86 /**
87 * An access key for a Prisma Object Store bucket, yielding S3 credentials.
88 *
89 * Prisma returns the secret access key only in the create response, so
90 * Alchemy stores it as a `Redacted` value and treats persisted state as
91 * authoritative: once created, the secret is never re-read from the API.
92 * Changing the bucket, name, or role replaces the key with fresh
93 * credentials.
94 *
95 * ### Creating a Bucket Access Key
96 * **Example:** Read-write credentials for a bucket
97 * ```typescript
98 * const key = yield* Prisma.BucketAccessKey("uploads-key", {
99 * bucket,
100 * role: "read_write",
101 * });
102 * ```
103 *
104 * ### Binding to Platforms
105 * **Example:** Pass S3 credentials to Compute env
106 * ```typescript
107 * const app = yield* Prisma.Compute("api", {
108 * project,
109 * path: "./apps/api",
110 * env: {
111 * S3_ENDPOINT: key.endpoint,
112 * S3_BUCKET: key.bucketName,
113 * S3_ACCESS_KEY_ID: key.accessKeyId,
114 * S3_SECRET_ACCESS_KEY: key.secretAccessKey,
115 * },
116 * });
117 * ```
118 *
119 * @resource
120 * @product Bucket
121 */
122 export const BucketAccessKey = Resource<BucketAccessKey>("Prisma.BucketAccessKey");
123
124 const BUCKET_ACCESS_KEY_STABLES = [
125 "bucketAccessKeyId",
126 "bucketId",
127 "accessKeyId",
128 "secretAccessKey",
129 "endpoint",
130 "bucketName",
131 ] satisfies Extract<keyof BucketAccessKey["Attributes"], string>[];
132
133 /**
134 * Raised when more than one key on a bucket carries the deterministic name
135 * of a single resource instance, so no key can be recovered unambiguously.
136 */
137 export class AmbiguousBucketAccessKeyError extends Data.TaggedError(
138 "AmbiguousBucketAccessKeyError",
139 )<{
140 bucketId: string;
141 resourceName: string;
142 count: number;
143 message: string;
144 }> {}
145
146 // Distilled emits the cursor-paginated list operations as plain ops, so
147 // callers walk `pagination` themselves (see `src/Neon/Project.ts`).
148 const listKeys = (bucketId: string) =>
149 Effect.gen(function* () {
150 const keys: GetBucketKeysResponse["data"][number][] = [];
151 let cursor: string | undefined;
152 while (true) {
153 const page = yield* getBucketKeys(
154 cursor === undefined ? { bucketId, limit: 100 } : { bucketId, limit: 100, cursor },
155 );
156 keys.push(...page.data);
157 const nextCursor = page.pagination.nextCursor;
158 if (!page.pagination.hasMore) break;
159 if (nextCursor === null) {
160 return yield* new PrismaPaginationError({
161 message:
162 "Invalid Prisma Management API pagination response from getBucketKeys: hasMore was true without a non-empty nextCursor",
163 });
164 }
165 cursor = nextCursor;
166 }
167 return keys;
168 }).pipe(Effect.catchTag("NotFound", () => Effect.succeed([])));
169
170 const uniqueKeyNamed = (bucketId: string, expectedName: string) =>
171 listKeys(bucketId).pipe(
172 Effect.flatMap((keys) => {
173 const matches = keys.filter((key: ObservedBucketKey) => key.name === expectedName);
174 return matches.length > 1
175 ? Effect.fail(
176 new AmbiguousBucketAccessKeyError({
177 bucketId,
178 resourceName: expectedName,
179 count: matches.length,
180 message: `Prisma bucket '${bucketId}' has ${matches.length} keys named '${expectedName}'; refusing to select one arbitrarily`,
181 }),
182 )
183 : Effect.succeed(matches[0]);
184 }),
185 );
186
187 const ProviderLive = () =>
188 Provider.effect(
189 BucketAccessKey,
190 Effect.gen(function* () {
191 return {
192 stables: BUCKET_ACCESS_KEY_STABLES,
193 // Bucket keys cannot be listed account-wide, and bucket deletion
194 // revokes them server-side, so nuke has nothing to enumerate here.
195 list: () => Effect.succeed([]),
196 diff: Effect.fn(function* ({ olds, news, output }) {
197 if (!isInputObject(news)) return undefined;
198 if (isPrismaDevId(output?.bucketAccessKeyId)) {
199 return { action: "update" } as const;
200 }
201 const oldBucketId = output?.bucketId ?? unresolvedBucketIdOf(olds.bucket);
202 const newBucketId = isResolved(news.bucket)
203 ? unresolvedBucketIdOf(news.bucket)
204 : undefined;
205 if (concreteIdsChanged(oldBucketId, newBucketId)) {
206 return { action: "replace" } as const;
207 }
208 // A key's name and role are fixed at creation, so changes replace
209 // the key and mint fresh credentials.
210 if (isResolved(news.role) && news.role !== olds.role) {
211 return { action: "replace" } as const;
212 }
213 if (isResolved(news.name) && news.name !== undefined && news.name !== olds.name) {
214 return { action: "replace" } as const;
215 }
216 return undefined;
217 }),
218 read: Effect.fn(function* ({ output }) {
219 // The secret access key can never be re-read from the API, so the
220 // persisted state stays authoritative for credentials; the list
221 // endpoint only confirms the key still exists.
222 if (!output || isPrismaDevId(output.bucketAccessKeyId)) return output;
223 const keys = yield* listKeys(output.bucketId);
224 return keys.some((key: ObservedBucketKey) => key.id === output.bucketAccessKeyId)
225 ? output
226 : undefined;
227 }),
228 reconcile: Effect.fn(function* ({ id, instanceId, news, output }) {
229 const persisted = output && !isPrismaDevId(output.bucketAccessKeyId) ? output : undefined;
230 if (persisted) {
231 // Prisma returns the secret exactly once, at creation. Persisted
232 // state is authoritative afterwards — but only while the key
233 // still exists; a revoked key falls through to mint fresh
234 // credentials.
235 const keys = yield* listKeys(persisted.bucketId);
236 if (keys.some((key: ObservedBucketKey) => key.id === persisted.bucketAccessKeyId)) {
237 return persisted;
238 }
239 }
240 const bucketId = yield* resolveBucketId(news.bucket);
241 const expectedName = physicalInstanceName(news.name ?? id, instanceId);
242 // A crash after create but before state persist leaves a key under
243 // the deterministic name whose secret was never persisted and can
244 // never be recovered. Revoke it and mint a fresh key rather than
245 // leaking an unusable credential.
246 const orphan = yield* uniqueKeyNamed(bucketId, expectedName);
247 if (orphan) {
248 yield* deleteBucketKey({
249 bucketId,
250 keyId: orphan.id,
251 }).pipe(Effect.catchTag("NotFound", () => Effect.void));
252 }
253 const created = yield* createBucketKey({
254 bucketId,
255 name: expectedName,
256 role: news.role,
257 }).pipe(
258 // The secret is revealed exactly once, so a replayed create
259 // would leak an unusable key; opt out of the retry policy.
260 Retry.none,
261 Effect.map((response) => response.data),
262 );
263 return {
264 bucketAccessKeyId: created.id,
265 bucketId,
266 accessKeyId: requiredSecretValue(created.accessKeyId),
267 secretAccessKey: Redacted.make(requiredSecretValue(created.secretAccessKey)),
268 endpoint: created.endpoint,
269 bucketName: created.bucketName,
270 } satisfies BucketAccessKey["Attributes"];
271 }),
272 delete: Effect.fn(function* ({ output }) {
273 if (isPrismaDevId(output.bucketAccessKeyId)) return;
274 // Bucket deletion revokes remaining keys server-side, so the key
275 // may already be gone when the bucket was destroyed first.
276 yield* deleteBucketKey({
277 bucketId: output.bucketId,
278 keyId: output.bucketAccessKeyId,
279 }).pipe(Effect.catchTag("NotFound", () => Effect.void));
280 }),
281 };
282 }),
283 );
284
285 const ProviderLocal = () =>
286 devProvider(BucketAccessKey, BUCKET_ACCESS_KEY_STABLES, ({ id, news, output }) => ({
287 bucketAccessKeyId: devId("bucket-access-key", id),
288 bucketId: attrOrString(news.bucket, "bucketId") ?? devId("bucket", id),
289 accessKeyId: devId("access-key", id),
290 // Keep the fabricated secret stable across dev reconciles, mirroring
291 // the reveal-once live behavior where persisted state is authoritative.
292 secretAccessKey:
293 attrOrRedactedString(output, "secretAccessKey") ??
294 Redacted.make(devId("secret-access-key", id)),
295 endpoint: "http://localhost",
296 bucketName: `dev-${id}`,
297 }));
298
299 export const BucketAccessKeyProvider = () =>
300 ProviderLayer.dual(BucketAccessKey, {
301 local: () => ProviderLocal(),
302 live: () => ProviderLive(),
303 });