@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 473 lines 16.3 KB
Raw
1 import { Retry } from "@distilled.cloud/prisma";
2 import {
3 type GetEnvironmentVariablesResponse,
4 deleteEnvironmentVariable,
5 getEnvironmentVariables,
6 getEnvironmentVariable,
7 updateEnvironmentVariable,
8 createEnvironmentVariable,
9 } from "@distilled.cloud/prisma/management";
10 import { Unowned } from "alchemy/AdoptPolicy";
11 import { isResolved } from "alchemy/Diff";
12 import * as ProviderLayer from "alchemy/Local/ProviderLayer";
13 import * as Provider from "alchemy/Provider";
14 import { Resource } from "alchemy/Resource";
15 import * as Data from "effect/Data";
16 import * as Effect from "effect/Effect";
17 import * as Redacted from "effect/Redacted";
18 import { DEV_TIMESTAMP, attrOrString, devId, devProvider } from "./internal/DevStub.ts";
19 import type { ObservedEnvironmentVariable } from "./internal/Observed.ts";
20 import { PrismaPaginationError } from "./internal/Pagination.ts";
21 import {
22 concreteIdsChanged,
23 isInputObject,
24 isPrismaDevId,
25 resolveProjectId,
26 unresolvedProjectIdOf,
27 } from "./internal/Refs.ts";
28 import type { Project } from "./Project.ts";
29 import type { Providers } from "./Providers.ts";
30
31 export class EnvironmentVariableConflict extends Data.TaggedError("EnvironmentVariableConflict")<{
32 readonly message: string;
33 readonly cause?: unknown;
34 }> {}
35
36 export class EnvironmentVariableInvalidProps extends Data.TaggedError(
37 "EnvironmentVariableInvalidProps",
38 )<{
39 readonly message: string;
40 readonly cause?: unknown;
41 }> {}
42
43 export interface EnvironmentVariableProps {
44 /**
45 * Project ID or `project.projectId` output that owns this variable.
46 */
47 project: string | Project;
48 /**
49 * Preview branch ID for a branch override. Omit for project-level templates.
50 */
51 branchId?: string;
52 /**
53 * Environment variable class.
54 */
55 class: "production" | "preview";
56 /**
57 * Environment variable key.
58 */
59 key: string;
60 /**
61 * Secret value. Must be wrapped with `Redacted.make(...)` so the engine
62 * redacts it before resource props are persisted to state.
63 */
64 value: Redacted.Redacted<string>;
65 }
66
67 export interface EnvironmentVariable extends Resource<
68 "Prisma.EnvironmentVariable",
69 EnvironmentVariableProps,
70 {
71 /**
72 * Prisma environment variable ID.
73 */
74 environmentVariableId: string;
75 /**
76 * Project ID that owns the variable.
77 */
78 projectId: string;
79 /**
80 * Branch ID for branch overrides, or null for project templates.
81 */
82 branchId: string | null;
83 /**
84 * Environment variable class.
85 */
86 class: "production" | "preview";
87 /**
88 * Environment variable key.
89 */
90 key: string;
91 /**
92 * Secret value, redacted in state.
93 */
94 value: Redacted.Redacted<string>;
95 /**
96 * Key identifier for the encrypted stored value.
97 */
98 valueKid: string;
99 /**
100 * Whether Prisma manages this variable internally.
101 */
102 isManagedBySystem: boolean;
103 /**
104 * ISO timestamp when the variable was created.
105 */
106 createdAt: string;
107 /**
108 * ISO timestamp when the variable was last updated.
109 */
110 updatedAt: string;
111 },
112 never,
113 Providers
114 > {}
115
116 /**
117 * A Prisma compute environment variable.
118 *
119 * Values are write-only in Prisma. Alchemy stores them as `Redacted` values
120 * and reapplies the desired value to repair drift.
121 *
122 * ### Creating a Variable
123 * **Example:** Project-level production variable
124 * ```typescript
125 * yield* Prisma.EnvironmentVariable("api-url", {
126 * project: project.projectId,
127 * // No branchId: this is a project-level template.
128 * class: "production",
129 * key: "API_URL",
130 * value: Redacted.make("https://api.example.com"),
131 * });
132 * ```
133 *
134 * **Example:** Preview branch override
135 * ```typescript
136 * yield* Prisma.EnvironmentVariable("preview-api-url", {
137 * project,
138 * branchId: preview.branchId,
139 * // Branch overrides always use the preview class.
140 * class: "preview",
141 * key: "API_URL",
142 * value: Redacted.make("https://preview.example.com"),
143 * });
144 * ```
145 *
146 * @resource
147 * @product Compute
148 */
149 export const EnvironmentVariable = Resource<EnvironmentVariable>("Prisma.EnvironmentVariable");
150
151 const ENV_KEY_PATTERN = /^[A-Z_][A-Z0-9_]*$/;
152 const ENV_VALUE_MAX_BYTES = 8 * 1024;
153
154 const validateEnvironmentVariableKey = (key: string) =>
155 Effect.gen(function* () {
156 if (key.length < 1 || key.length > 256 || !ENV_KEY_PATTERN.test(key)) {
157 return yield* new EnvironmentVariableInvalidProps({
158 message: `Prisma environment variable key '${key}' must match POSIX env-var key shape: [A-Z_][A-Z0-9_]* and be at most 256 characters.`,
159 });
160 }
161 });
162
163 const validateEnvironmentVariableWrite = (key: string, value: Redacted.Redacted<string>) =>
164 Effect.gen(function* () {
165 yield* validateEnvironmentVariableKey(key);
166 const raw = Redacted.value(value);
167 if (raw.length === 0) {
168 return yield* new EnvironmentVariableInvalidProps({
169 message: `Prisma environment variable '${key}' value must be non-empty.`,
170 });
171 }
172 const byteLength = yield* Effect.sync(() => new TextEncoder().encode(raw).byteLength);
173 if (byteLength > ENV_VALUE_MAX_BYTES) {
174 return yield* new EnvironmentVariableInvalidProps({
175 message: `Prisma environment variable '${key}' value exceeds ${ENV_VALUE_MAX_BYTES} bytes.`,
176 });
177 }
178 });
179
180 // Distilled emits the cursor-paginated list operations as plain ops, so
181 // callers walk `pagination` themselves (see `src/Neon/Project.ts`).
182 const listVariables = (
183 query: {
184 readonly projectId?: string;
185 readonly class?: "production" | "preview";
186 readonly key?: string;
187 readonly branchId?: string;
188 readonly limit?: number;
189 } = {},
190 ) =>
191 Effect.gen(function* () {
192 const variables: GetEnvironmentVariablesResponse["data"][number][] = [];
193 let cursor: string | undefined;
194 while (true) {
195 const page = yield* getEnvironmentVariables(
196 cursor === undefined ? query : { ...query, cursor },
197 );
198 variables.push(...page.data);
199 const nextCursor = page.pagination.nextCursor;
200 if (!page.pagination.hasMore) break;
201 if (nextCursor === null) {
202 return yield* new PrismaPaginationError({
203 message:
204 "Invalid Prisma Management API pagination response from getEnvironmentVariables: hasMore was true without a non-empty nextCursor",
205 });
206 }
207 cursor = nextCursor;
208 }
209 return variables;
210 });
211
212 const findVariable = (
213 projectId: string,
214 cls: "production" | "preview",
215 key: string,
216 branchId?: string | null,
217 ) =>
218 listVariables({
219 projectId,
220 class: cls,
221 key,
222 ...(branchId ? { branchId } : {}),
223 limit: 100,
224 }).pipe(
225 Effect.flatMap((variables) => {
226 const matches = variables.filter((variable) => variable.branchId === (branchId ?? null));
227 return matches.length > 1
228 ? Effect.fail(
229 new EnvironmentVariableConflict({
230 message: `Multiple Prisma environment variables match '${key}' in the requested scope; refusing to select one arbitrarily.`,
231 }),
232 )
233 : Effect.succeed(matches[0]);
234 }),
235 );
236
237 const attrsFrom = (
238 variable: ObservedEnvironmentVariable,
239 value: Redacted.Redacted<string>,
240 ): EnvironmentVariable["Attributes"] => ({
241 environmentVariableId: variable.id,
242 projectId: variable.projectId,
243 branchId: variable.branchId,
244 class: variable.class,
245 key: variable.key,
246 value,
247 valueKid: variable.valueKid,
248 isManagedBySystem: variable.isManagedBySystem,
249 createdAt: variable.createdAt,
250 updatedAt: variable.updatedAt,
251 });
252
253 const systemManagedVariableError = (key: string) =>
254 new Error(
255 `Prisma environment variable '${key}' is managed by Prisma and cannot be managed by Alchemy.`,
256 );
257
258 const ensureUserManagedVariable = (variable: ObservedEnvironmentVariable) =>
259 Effect.gen(function* () {
260 if (variable.isManagedBySystem) {
261 return yield* Effect.fail(systemManagedVariableError(variable.key));
262 }
263 });
264
265 const ensureVariableIdentity = (
266 variable: ObservedEnvironmentVariable,
267 expected: {
268 projectId: string;
269 branchId: string | null;
270 class: "production" | "preview";
271 key: string;
272 },
273 ) =>
274 variable.projectId === expected.projectId &&
275 variable.branchId === expected.branchId &&
276 variable.class === expected.class &&
277 variable.key === expected.key
278 ? Effect.void
279 : Effect.fail(
280 new EnvironmentVariableConflict({
281 message: `Prisma environment variable '${variable.id}' has immutable identity project '${variable.projectId}', branch '${variable.branchId ?? "null"}', class '${variable.class}', key '${variable.key}', but this resource requires project '${expected.projectId}', branch '${expected.branchId ?? "null"}', class '${expected.class}', key '${expected.key}'. Refusing to update or delete a mismatched secret.`,
282 }),
283 );
284
285 const ProviderLive = () =>
286 Provider.effect(
287 EnvironmentVariable,
288 Effect.gen(function* () {
289 return {
290 stables: ["environmentVariableId"],
291 list: () =>
292 listVariables().pipe(
293 Effect.map((variables) =>
294 variables
295 // System-managed variables are project-owned and cannot be
296 // deleted through this API.
297 .filter((variable) => !variable.isManagedBySystem)
298 .map((variable) =>
299 // The API deliberately never returns plaintext. `delete`
300 // needs only identity/metadata, so nuke uses an impossible
301 // empty placeholder rather than pretending to know a secret.
302 attrsFrom(variable, Redacted.make("")),
303 ),
304 ),
305 ),
306 diff: Effect.fn(function* ({ olds, news, output }) {
307 if (!isInputObject(news)) return undefined;
308 if (isPrismaDevId(output?.environmentVariableId)) {
309 return { action: "update" } as const;
310 }
311 const oldProjectId = output?.projectId ?? unresolvedProjectIdOf(olds.project);
312 const newProjectId = isResolved(news.project)
313 ? unresolvedProjectIdOf(news.project)
314 : undefined;
315 if (
316 concreteIdsChanged(oldProjectId, newProjectId) ||
317 (isResolved(news.branchId) && news.branchId !== olds.branchId) ||
318 (isResolved(news.class) && news.class !== olds.class) ||
319 (isResolved(news.key) && news.key !== olds.key)
320 ) {
321 return { action: "replace" } as const;
322 }
323 // Values are write-only: the Management API never returns
324 // plaintext, so equality with `olds` cannot prove the live secret
325 // is still correct. Re-apply every resolved desired value to heal
326 // out-of-band secret drift on ordinary deploys.
327 if (isResolved(news.value)) {
328 return { action: "update" } as const;
329 }
330 return undefined;
331 }),
332 read: Effect.fn(function* ({ output, olds }) {
333 const variableId = isPrismaDevId(output?.environmentVariableId)
334 ? undefined
335 : output?.environmentVariableId;
336 const findVariableInProject = Effect.gen(function* () {
337 const projectId = unresolvedProjectIdOf(olds.project);
338 return projectId
339 ? yield* findVariable(projectId, olds.class, olds.key, olds.branchId)
340 : undefined;
341 });
342 const variable = variableId
343 ? yield* getEnvironmentVariable({
344 envVarId: variableId,
345 }).pipe(
346 Effect.map((response) => response.data),
347 Effect.catchTag("NotFound", () => Effect.undefined),
348 )
349 : yield* findVariableInProject;
350 if (!variable) return undefined;
351 const attrs = attrsFrom(
352 variable,
353 // A cold read cannot observe the secret. Never copy the desired
354 // value into output: doing so would make the forced adoption
355 // reconcile falsely conclude the cloud already contains it.
356 output?.value ?? Redacted.make(""),
357 );
358 return variableId === undefined ? Unowned(attrs) : attrs;
359 }),
360 reconcile: Effect.fn(function* ({ news, output }) {
361 if (news.branchId !== undefined && news.class !== "preview") {
362 return yield* new EnvironmentVariableInvalidProps({
363 message: 'Prisma branch-scoped environment variables must use class: "preview".',
364 });
365 }
366 yield* validateEnvironmentVariableWrite(news.key, news.value);
367 const projectId = yield* resolveProjectId(news.project);
368 const variableId = isPrismaDevId(output?.environmentVariableId)
369 ? undefined
370 : output?.environmentVariableId;
371 let variable = variableId
372 ? yield* getEnvironmentVariable({
373 envVarId: variableId,
374 }).pipe(
375 Effect.map((response) => response.data),
376 Effect.catchTag("NotFound", () => Effect.undefined),
377 )
378 : undefined;
379 const value = news.value;
380 let created = false;
381 if (!variable) {
382 const result = yield* createEnvironmentVariable({
383 projectId,
384 ...(news.branchId ? { branchId: news.branchId } : {}),
385 class: news.class,
386 key: news.key,
387 value: Redacted.value(value),
388 }).pipe(
389 // A replayed create would mint a second variable; the retry
390 // policy cannot see the request, so opt out explicitly.
391 Retry.none,
392 Effect.map((response) => ({
393 variable: response.data,
394 created: true,
395 })),
396 Effect.catchTag("Conflict", () =>
397 Effect.fail(
398 new EnvironmentVariableConflict({
399 message: `Prisma environment variable '${news.key}' appeared after the adoption check. Refusing to overwrite its secret; rerun with adoption enabled if it is the intended variable.`,
400 }),
401 ),
402 ),
403 );
404 variable = result.variable;
405 created = result.created;
406 }
407 yield* ensureVariableIdentity(variable, {
408 projectId,
409 branchId: news.branchId ?? null,
410 class: news.class,
411 key: news.key,
412 });
413 yield* ensureUserManagedVariable(variable);
414 if (!created) {
415 variable = (yield* updateEnvironmentVariable({
416 envVarId: variable.id,
417 value: Redacted.value(value),
418 })).data;
419 }
420 return attrsFrom(variable, value);
421 }),
422 delete: Effect.fn(function* ({ output, session }) {
423 if (isPrismaDevId(output.environmentVariableId)) return;
424 const variable = yield* getEnvironmentVariable({
425 envVarId: output.environmentVariableId,
426 }).pipe(
427 Effect.map((response) => response.data),
428 Effect.catchTag("NotFound", () => Effect.undefined),
429 );
430 if (!variable) return;
431 yield* ensureVariableIdentity(variable, {
432 projectId: output.projectId,
433 branchId: output.branchId,
434 class: output.class,
435 key: output.key,
436 });
437 if (variable.isManagedBySystem) {
438 // Prisma-owned environment variables are provider-managed system
439 // state and are not deletable through this resource lifecycle.
440 if (session !== undefined) {
441 yield* session.note(
442 `Skipping direct delete for system-managed Prisma environment variable '${variable.key}'.`,
443 );
444 }
445 return;
446 }
447 yield* deleteEnvironmentVariable({
448 envVarId: variable.id,
449 }).pipe(Effect.catchTag("NotFound", () => Effect.void));
450 }),
451 };
452 }),
453 );
454
455 const ProviderLocal = () =>
456 devProvider(EnvironmentVariable, ["environmentVariableId"], ({ id, news }) => ({
457 environmentVariableId: devId("environment-variable", id),
458 projectId: attrOrString(news.project, "projectId"),
459 branchId: news.branchId ?? null,
460 class: news.class,
461 key: news.key,
462 value: news.value,
463 valueKid: devId("value-kid", id),
464 isManagedBySystem: false,
465 createdAt: DEV_TIMESTAMP,
466 updatedAt: DEV_TIMESTAMP,
467 }));
468
469 export const EnvironmentVariableProvider = () =>
470 ProviderLayer.dual(EnvironmentVariable, {
471 local: () => ProviderLocal(),
472 live: () => ProviderLive(),
473 });