@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 215 lines 7.85 KB
Raw
1 import * as secretsStore from "@distilled.cloud/cloudflare/secrets-store";
2 import * as ProviderLayer from "alchemy/Local/ProviderLayer";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Option from "effect/Option";
7 import * as Stream from "effect/Stream";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import { localAccountId } from "../LocalAccount.ts";
10 import { generateLocalId } from "../LocalRuntime.ts";
11 import type { Providers } from "../Providers.ts";
12
13 export type Store = Resource<
14 "Cloudflare.SecretsStore",
15 {},
16 {
17 storeId: string;
18 storeName: string;
19 accountId: string;
20 },
21 never,
22 Providers
23 >;
24
25 /**
26 * A Cloudflare Secrets Store, a per-account container for secrets that
27 * can be bound into Workers with full redaction and audit support.
28 *
29 * Cloudflare enforces a limit of **one Secrets Store per account**.
30 * Deleting a store changes its ID and permanently destroys all secrets
31 * inside it. Because of this, the provider always **adopts** an existing
32 * store rather than creating a new one, and **never deletes** the store
33 * on teardown. The `read` lifecycle reports the existing account store
34 * (if any) as plain attrs, so the engine silently adopts it on cold
35 * start and `create` is only ever invoked when no store exists yet.
36 * Once it exists it is treated as account-level infrastructure that
37 * outlives any single stack.
38 * ### Creating a Store
39 * **Example:** Basic Secrets Store (adopts existing or creates one)
40 * ```typescript
41 * const store = yield* Cloudflare.SecretsStore.Store("MyStore");
42 * ```
43 *
44 * **Example:** Adopt a specific named store
45 * ```typescript
46 * const store = yield* Cloudflare.SecretsStore.Store("MyStore", {
47 * name: "production-secrets",
48 * });
49 * ```
50 *
51 * @resource
52 * @product Secrets Store
53 * @category Storage & Databases
54 */
55 export const Store = Resource<Store>("Cloudflare.SecretsStore");
56
57 export const StoreProviderLive = () =>
58 Provider.succeed(Store, {
59 stables: ["storeId", "storeName", "accountId"],
60 // The engine calls `read` whenever there's no prior state. Cloudflare
61 // allows exactly one Secrets Store per account, so any account that's
62 // ever provisioned one must reuse it. Returning the existing store as
63 // plain attrs makes the engine silently adopt it; `create` is only
64 // ever invoked when no store exists yet.
65 read: Effect.fn(function* ({ output }) {
66 const { accountId } = yield* yield* CloudflareEnvironment;
67 const acct = output?.accountId ?? accountId;
68 const match = output?.storeId
69 ? yield* findStoreById(acct, output.storeId)
70 : yield* firstStore(acct);
71 if (!match) return undefined;
72 return {
73 storeId: match.id,
74 storeName: match.name,
75 accountId: acct,
76 };
77 }),
78 reconcile: Effect.fn(function* ({ output }) {
79 const { accountId } = yield* yield* CloudflareEnvironment;
80 const acct = output?.accountId ?? accountId;
81
82 // Observe — Cloudflare permits exactly one Secrets Store per
83 // account. Reuse the cached store if it still exists, otherwise
84 // reuse the first one listed.
85 const cached = output?.storeId ? yield* findStoreById(acct, output.storeId) : undefined;
86 const observed = cached ?? (yield* firstStore(acct));
87
88 if (observed) {
89 return {
90 storeId: observed.id,
91 storeName: observed.name,
92 accountId: acct,
93 };
94 }
95
96 // Ensure — no store yet. Create the default. Cloudflare reports
97 // a concurrent create as `MaximumStoresExceeded`; tolerate by
98 // re-listing and adopting the now-existing store.
99 const response = yield* secretsStore
100 .createStore({
101 accountId: acct,
102 // `default_secrets_store` is the name Cloudflare uses for an
103 // account's default Secrets Store.
104 name: "default_secrets_store",
105 })
106 .pipe(Effect.catchTag("MaximumStoresExceeded", () => Effect.undefined));
107
108 if (response) {
109 return {
110 storeId: response.id,
111 storeName: response.name,
112 accountId: acct,
113 };
114 }
115
116 const first = yield* firstStore(acct);
117 if (first) {
118 return {
119 storeId: first.id,
120 storeName: first.name,
121 accountId: acct,
122 };
123 }
124
125 return yield* Effect.die(
126 new Error(
127 `Cloudflare reported MaximumStoresExceeded for account ${acct} but no store could be listed.`,
128 ),
129 );
130 }),
131 // Account-scoped collection. Cloudflare exposes a paginated
132 // `secrets_store/stores` list op; enumerate every page and hydrate each
133 // store into the exact `read` Attributes shape. Cloudflare currently
134 // permits only one (default) store per account, so this is usually a
135 // single-element array, but the enumeration is exhaustive regardless.
136 list: Effect.fn(function* () {
137 const { accountId } = yield* yield* CloudflareEnvironment;
138 return yield* secretsStore.listStores.pages({ accountId }).pipe(
139 Stream.runCollect,
140 Effect.map((chunk) =>
141 Array.from(chunk).flatMap((page) =>
142 (page.result ?? []).map((store) => ({
143 storeId: store.id,
144 storeName: store.name,
145 accountId: store.accountId ?? accountId,
146 })),
147 ),
148 ),
149 );
150 }),
151 delete: Effect.fn(function* () {
152 // Intentional no-op. Cloudflare only allows one Secrets Store per
153 // account and deleting it permanently destroys all secrets inside.
154 // The store is treated as shared, account-level infrastructure that
155 // should never be torn down by a single stack.
156 }),
157 });
158
159 /**
160 * Local (dev) provider — the store is purely virtual: a `dev:` id keyed
161 * into the local workerd Secrets Store simulator. The local `Secret`
162 * provider seeds values into it and `toRuntimeBinding` lowers a
163 * `secrets_store_secret` binding whose store id is `dev:`-prefixed onto the
164 * local secrets-store service; data persists under
165 * `.alchemy/local/secrets-store`.
166 */
167 export const StoreProviderLocal = () =>
168 Provider.succeed(Store, {
169 stables: ["accountId"],
170 diff: Effect.fn(function* ({ output }) {
171 const accountId = yield* localAccountId;
172 if (!output?.storeId) return { action: "update" } as const;
173 if (output.accountId !== accountId) {
174 return { action: "replace" } as const;
175 }
176 // Fall through to the engine's default prop diff.
177 }),
178 read: Effect.fn(function* ({ output }) {
179 // Purely virtual — the persisted state row is the source of truth.
180 return output ?? undefined;
181 }),
182 reconcile: Effect.fn(function* ({ output }) {
183 const accountId = yield* localAccountId;
184 return {
185 storeId: output?.storeId ?? generateLocalId(),
186 // Mirror the name Cloudflare uses for an account's default store.
187 storeName: output?.storeName ?? "default_secrets_store",
188 accountId: output?.accountId ?? accountId,
189 };
190 }),
191 delete: Effect.fn(function* () {
192 // The simulator's on-disk data is keyed by the dev id; dropping the
193 // state row is enough — orphaned data is reclaimed with `.alchemy`.
194 }),
195 });
196
197 export const SecretsStoreProvider = () =>
198 ProviderLayer.dual(Store, {
199 local: () => StoreProviderLocal(),
200 live: () => StoreProviderLive(),
201 });
202
203 /** First store on the account (Cloudflare permits at most one). */
204 const firstStore = (accountId: string) =>
205 secretsStore.listStores
206 .items({ accountId })
207 .pipe(Stream.runHead, Effect.map(Option.getOrUndefined));
208
209 /** Look a store up by id, terminating pagination on the first match. */
210 const findStoreById = (accountId: string, storeId: string) =>
211 secretsStore.listStores.items({ accountId }).pipe(
212 Stream.filter((s) => s.id === storeId),
213 Stream.runHead,
214 Effect.map(Option.getOrUndefined),
215 );