@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 173 lines 6.62 KB
Raw
1 import type { CredentialsStoreService } from "alchemy/Auth/Credentials";
2 import { withLock } from "alchemy/Auth/Lock";
3 import { profileStateStoresDirPath } from "alchemy/Auth/Paths";
4 import * as Effect from "effect/Effect";
5 import * as Schema from "effect/Schema";
6
7 /**
8 * Cache of the Cloudflare-deployed HTTP state stores' endpoints + bearer
9 * tokens, at `~/.alchemy/profiles/{profile}/state-stores/cloudflare.json`.
10 *
11 * Kept in this leaf module (rather than `StateStore/State.ts`) so the
12 * Cloudflare auth provider can invalidate the cache on
13 * `profile edit` / provider logout without importing the heavy state-store
14 * module and creating an import cycle
15 * (`StateStore/State.ts` -> `Providers.ts` -> `Auth/AuthProvider.ts`).
16 */
17 export const CREDENTIALS_FILE = "cloudflare";
18
19 /**
20 * The single-store cache earlier releases keep at
21 * `~/.alchemy/credentials/{profile}/cloudflare-state-store.json`. Copied into
22 * {@link CREDENTIALS_FILE} once and never written, so those releases keep
23 * working.
24 */
25 export const LEGACY_CREDENTIALS_FILE = "cloudflare-state-store";
26
27 const stateStores = (store: CredentialsStoreService) => store.scoped(profileStateStoresDirPath);
28
29 /**
30 * On-disk shape of the cached Cloudflare state-store credentials.
31 *
32 * Extends the generic `HttpStateStoreCredentials` (`{ url, authToken }`)
33 * with the `accountId` the credentials were minted against. The `url` already
34 * encodes the account (via the `*.workers.dev` subdomain), so a cache written
35 * while logged into account A keeps pointing at account A's state store even
36 * after the user re-authenticates against account B. Persisting `accountId`
37 * lets `state()` detect that mismatch and re-derive.
38 *
39 * `accountId` is optional so legacy files written before this field existed
40 * still parse — they are treated as stale (see
41 * {@link isStateStoreCredentialsStale}) and re-derived on next use.
42 */
43 export const StoredStateStoreCredentials = Schema.Struct({
44 url: Schema.String,
45 /** Bearer token used to authenticate every request. */
46 authToken: Schema.String,
47 /** Cloudflare account ID the `url`/`authToken` were minted against. */
48 accountId: Schema.optional(Schema.String),
49 });
50 export type StoredStateStoreCredentials = typeof StoredStateStoreCredentials.Type;
51
52 /**
53 * `true` when cached state-store credentials must not be trusted for the
54 * current account:
55 *
56 * - the file predates the `accountId` field (legacy cache — exactly the
57 * artifact that caused deploys to silently target the wrong account), or
58 * - it was minted against a different account than the one now in use.
59 *
60 * A stale cache is discarded and re-derived from the current account.
61 */
62 export const isStateStoreCredentialsStale = (
63 credentials: StoredStateStoreCredentials,
64 currentAccountId: string,
65 ): boolean => credentials.accountId == null || credentials.accountId !== currentAccountId;
66
67 /** The default state store's name; a legacy file holds its credentials alone. */
68 const DEFAULT_STORE = "alchemy-state-store";
69
70 /**
71 * Every state store's cached credentials for a profile, by store name, in
72 * the one {@link CREDENTIALS_FILE}: {@link clearStoreCredentials} (on
73 * `profile edit`, logout, or an account change) clears them all.
74 */
75 const StoredStateStores = Schema.Struct({
76 stores: Schema.Record(Schema.String, StoredStateStoreCredentials),
77 });
78
79 /** It is only a cache, so a file that can't be read counts as empty. */
80 const readStores = (store: CredentialsStoreService, profile: string) =>
81 stateStores(store)
82 .read(profile, CREDENTIALS_FILE, StoredStateStores)
83 .pipe(
84 Effect.map((file): Record<string, StoredStateStoreCredentials> => file?.stores ?? {}),
85 Effect.orElseSucceed((): Record<string, StoredStateStoreCredentials> => ({})),
86 );
87
88 const writeStores = (
89 store: CredentialsStoreService,
90 profile: string,
91 stores: Record<string, StoredStateStoreCredentials>,
92 ) => stateStores(store).write(profile, CREDENTIALS_FILE, StoredStateStores, { stores });
93
94 /**
95 * Copy the legacy file, which holds the default store's credentials alone,
96 * into {@link CREDENTIALS_FILE} the first time a profile's cache is used.
97 * The legacy file is left in place. It is only a cache, so one that can't be
98 * read is skipped.
99 */
100 const migrateLegacy = (store: CredentialsStoreService, profile: string) =>
101 Effect.gen(function* () {
102 const current = yield* stateStores(store)
103 .read(profile, CREDENTIALS_FILE, StoredStateStores)
104 .pipe(Effect.orElseSucceed(() => null));
105 if (current !== undefined) return;
106 const legacy = yield* store
107 .read(profile, LEGACY_CREDENTIALS_FILE, StoredStateStoreCredentials)
108 .pipe(Effect.orElseSucceed(() => undefined));
109 if (legacy !== undefined) yield* writeStores(store, profile, { [DEFAULT_STORE]: legacy });
110 });
111
112 /** One state store's cached credentials, if any. */
113 export const readStoreCredentials = (
114 store: CredentialsStoreService,
115 profile: string,
116 storeName: string,
117 ) =>
118 withFileLock(
119 profile,
120 migrateLegacy(store, profile).pipe(
121 Effect.andThen(readStores(store, profile)),
122 Effect.map((stores) => stores[storeName]),
123 ),
124 );
125
126 /**
127 * Serialize read-modify-writes of a profile's file across fibers and
128 * processes, so two stores bootstrapping at once keep both entries. Its own
129 * lock, not the profile-credentials one, which callers may already hold.
130 */
131 const withFileLock = <A, E, R>(profile: string, effect: Effect.Effect<A, E, R>) =>
132 withLock(`cloudflare-state-store-${profile}`, effect, {
133 label: "Cloudflare state-store credentials",
134 });
135
136 /** Cache one state store's credentials beside the profile's other stores. */
137 export const writeStoreCredentials = (
138 store: CredentialsStoreService,
139 profile: string,
140 storeName: string,
141 credentials: StoredStateStoreCredentials,
142 ) =>
143 withFileLock(
144 profile,
145 migrateLegacy(store, profile).pipe(
146 Effect.andThen(readStores(store, profile)),
147 Effect.flatMap((stores) =>
148 writeStores(store, profile, { ...stores, [storeName]: credentials }),
149 ),
150 ),
151 );
152
153 /** Drop one state store's cached credentials. */
154 export const deleteStoreCredentials = (
155 store: CredentialsStoreService,
156 profile: string,
157 storeName: string,
158 ) =>
159 withFileLock(
160 profile,
161 migrateLegacy(store, profile).pipe(
162 Effect.andThen(readStores(store, profile)),
163 Effect.flatMap(({ [storeName]: _, ...rest }) => writeStores(store, profile, rest)),
164 ),
165 );
166
167 /**
168 * Drop every state store's cached credentials for a profile. Leaves an empty
169 * file rather than none, so the legacy cache is not migrated again. One
170 * atomic write, so it needs no lock.
171 */
172 export const clearStoreCredentials = (store: CredentialsStoreService, profile: string) =>
173 writeStores(store, profile, {});