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

main
ts 375 lines 14.2 KB
Raw
1 import { GitHubAuthConfigSchema } from "@alchemy.run/github/AuthProvider";
2 import { expect, it } from "@alchemy.run/test";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import { AuthProvidersLive } from "alchemy/Auth/AuthProvider";
5 import {
6 PROFILE_FORMAT,
7 profileProviderFilePath,
8 ProfileStore,
9 ProfileStoreLive,
10 } from "alchemy/Auth/Profile";
11 import * as ConfigProvider from "effect/ConfigProvider";
12 import * as Effect from "effect/Effect";
13 import * as FileSystem from "effect/FileSystem";
14 import * as Layer from "effect/Layer";
15 import * as Schema from "effect/Schema";
16 import path from "pathe";
17
18 const FIXTURE_HOME = path.join(import.meta.dirname, "fixtures/v0-home");
19
20 const testLayer = () =>
21 ProfileStoreLive.pipe(
22 Layer.provideMerge(
23 Layer.mergeAll(
24 AuthProvidersLive,
25 ConfigProvider.layer(ConfigProvider.fromUnknown({})),
26 NodeServices.layer,
27 ),
28 ),
29 );
30
31 /**
32 * Point `ALCHEMY_HOME` at a scoped temp directory seeded from a fixture
33 * tree, so store operations never touch the developer's real `~/.alchemy`.
34 * Tests using this must be `exclusive` — the env var is process-global.
35 */
36 const withFixtureHome = <A, E, R>(
37 fixture: string | undefined,
38 effect: (home: string) => Effect.Effect<A, E, R>,
39 ) =>
40 Effect.gen(function* () {
41 const fs = yield* FileSystem.FileSystem;
42 const dir = yield* fs.makeTempDirectoryScoped({
43 prefix: "alchemy-migrate-",
44 });
45 if (fixture !== undefined) {
46 yield* fs.copyFile(path.join(fixture, "profiles.json"), path.join(dir, "profiles.json"));
47 yield* fs.copy(path.join(fixture, "credentials"), path.join(dir, "credentials"));
48 }
49 const previous = process.env.ALCHEMY_HOME;
50 yield* Effect.acquireRelease(
51 Effect.sync(() => {
52 process.env.ALCHEMY_HOME = dir;
53 }),
54 () =>
55 Effect.sync(() => {
56 if (previous === undefined) delete process.env.ALCHEMY_HOME;
57 else process.env.ALCHEMY_HOME = previous;
58 }),
59 );
60 return yield* effect(dir).pipe(Effect.provide(testLayer()));
61 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
62
63 it.live(
64 "migrates a full v0 store: entries kept, credentials dropped into a backup",
65 () =>
66 withFixtureHome(FIXTURE_HOME, (home) =>
67 Effect.gen(function* () {
68 const fs = yield* FileSystem.FileSystem;
69 const store = yield* ProfileStore;
70
71 // The first read performs the on-disk migration.
72 const manifest = yield* store.readManifest;
73
74 // Every profile and provider entry survives (ids backfilled from the
75 // profile name), except legacy `method: "env"` entries.
76 expect(Object.keys(manifest.profiles).sort()).toEqual(["default", "work"]);
77 expect(manifest.profiles.default?.id).toBe("default");
78 expect(manifest.profiles.work?.id).toBe("work");
79 expect(manifest.profiles.default?.providers.Cloudflare).toEqual({
80 method: "oauth",
81 });
82 expect(manifest.profiles.default?.providers.AWS?.method).toBe("sso");
83 expect(manifest.profiles.default?.providers.GitHub).toEqual({
84 method: "gh-cli",
85 });
86 expect(
87 Schema.decodeUnknownSync(GitHubAuthConfigSchema)(
88 manifest.profiles.default?.providers.GitHub,
89 ),
90 ).toEqual({ method: "gh-cli" });
91 expect(manifest.profiles.default?.providers.Neon).toBeUndefined();
92 expect(manifest.profiles.work?.providers.GitHub?.method).toBe("stored");
93 expect(manifest.profiles.work?.providers.Axiom?.method).toBe("stored");
94 expect(manifest.profiles.work?.providers.Cloudflare).toEqual({
95 method: "stored",
96 credentialType: "apiKey",
97 apiKey: "v0-cf-global-api-key",
98 email: "worker@example.com",
99 accountId: "0123456789abcdef0123456789abcdef",
100 });
101 expect(manifest.profiles.work?.providers.GitHub?.token).toBe("ghp_v0token");
102 expect(manifest.profiles.work?.providers.Axiom).toEqual({
103 method: "stored",
104 token: "xaat-v0-token",
105 apiBaseUrl: "https://api.axiom.co",
106 });
107
108 // Each provider is now its own document. Compatible provider values
109 // survive. Cloudflare OAuth is deliberately emptied because its old
110 // grant is obsolete; stored API key credentials remain compatible.
111 const aws = JSON.parse(yield* fs.readFileString(profileProviderFilePath("default", "AWS")));
112 expect(aws).toEqual({
113 format: PROFILE_FORMAT,
114 provider: "AWS",
115 metadata: {},
116 values: { method: "sso", ssoProfile: "dev" },
117 });
118 const oauthCloudflare = JSON.parse(
119 yield* fs.readFileString(profileProviderFilePath("default", "Cloudflare")),
120 );
121 expect(oauthCloudflare.values).toEqual({ method: "oauth" });
122 const storedCloudflare = JSON.parse(
123 yield* fs.readFileString(profileProviderFilePath("work", "Cloudflare")),
124 );
125 expect(storedCloudflare.values).toEqual(manifest.profiles.work?.providers.Cloudflare);
126 expect((yield* fs.readDirectory(path.join(home, "profiles/default"))).sort()).toEqual([
127 "aws.json",
128 "cloudflare.json",
129 "github.json",
130 ]);
131 expect(yield* fs.exists(profileProviderFilePath("default", "Neon"))).toBe(false);
132 expect(yield* fs.exists(path.join(home, "profiles.json"))).toBe(false);
133
134 // The original manifest and every credential file are preserved in
135 // a timestamped backup for manual recovery.
136 const backups = (yield* fs.readDirectory(home)).filter((entry) =>
137 entry.startsWith(".profiles-v0-"),
138 );
139 expect(backups).toHaveLength(1);
140 const backupDir = path.join(home, backups[0]!);
141 const backedUp = JSON.parse(
142 yield* fs.readFileString(path.join(backupDir, "profiles.json")),
143 );
144 expect(backedUp.version).toBe(0);
145 // v0 profiles are flat provider maps (no `providers` wrapper).
146 expect(backedUp.profiles.default.Neon.method).toBe("env");
147 const oauth = JSON.parse(
148 yield* fs.readFileString(path.join(backupDir, "credentials/default/cf-oauth.json")),
149 );
150 expect(oauth.refresh).toBe("v0-refresh-token");
151 for (const file of [
152 "credentials/default/cloudflare-state-store.json",
153 "credentials/work/gh-stored.json",
154 "credentials/work/axiom-stored.json",
155 "credentials/work/cf-stored.json",
156 ]) {
157 expect(yield* fs.exists(path.join(backupDir, file))).toBe(true);
158 }
159
160 // The live credential store is gone; all obsolete sidecars live only
161 // in the recoverable v0 backup.
162 expect(yield* fs.exists(path.join(home, "credentials"))).toBe(false);
163
164 // Idempotent: a second read is a plain current-version read — no new
165 // backup dir, and the existing one is untouched.
166 const again = yield* store.readManifest;
167 expect(again.profiles.work?.providers.GitHub?.method).toBe("stored");
168 expect(again.profiles.work?.providers.Cloudflare).toEqual(
169 manifest.profiles.work?.providers.Cloudflare,
170 );
171 expect(
172 (yield* fs.readDirectory(home)).filter((entry) => entry.startsWith(".profiles-v0-")),
173 ).toHaveLength(1);
174 expect(
175 JSON.parse(yield* fs.readFileString(path.join(backupDir, "profiles.json"))).version,
176 ).toBe(0);
177 }),
178 ),
179 { tags: ["unit", "provider:github", "local"], exclusive: true },
180 );
181
182 it.live(
183 "leaves the directory-backed store untouched",
184 () =>
185 withFixtureHome(undefined, (home) =>
186 Effect.gen(function* () {
187 const fs = yield* FileSystem.FileSystem;
188 const providerFile = profileProviderFilePath("work", "Neon");
189 yield* fs.makeDirectory(path.dirname(providerFile), {
190 recursive: true,
191 });
192 yield* fs.writeFileString(
193 providerFile,
194 JSON.stringify({
195 format: PROFILE_FORMAT,
196 provider: "Neon",
197 metadata: { label: "production" },
198 values: { method: "stored", apiKey: "current-key" },
199 }),
200 );
201
202 const store = yield* ProfileStore;
203 const manifest = yield* store.readManifest;
204
205 expect(manifest.profiles.work?.id).toBe("work");
206 expect(manifest.profiles.work?.providers.Neon).toEqual({
207 method: "stored",
208 apiKey: "current-key",
209 });
210 expect(
211 (yield* fs.readDirectory(home)).filter((entry) => entry.startsWith(".profiles-v0-")),
212 ).toHaveLength(0);
213 expect(JSON.parse(yield* fs.readFileString(providerFile)).metadata).toEqual({
214 label: "production",
215 });
216 }),
217 ),
218 { tags: ["unit", "local"], exclusive: true },
219 );
220
221 it.live(
222 "salvages valid v0 providers when another entry or sidecar is invalid",
223 () =>
224 withFixtureHome(FIXTURE_HOME, (home) =>
225 Effect.gen(function* () {
226 const fs = yield* FileSystem.FileSystem;
227 const legacyFile = path.join(home, "profiles.json");
228 const legacy = JSON.parse(yield* fs.readFileString(legacyFile));
229 legacy.profiles.work.Broken = "not-an-object";
230 yield* fs.writeFileString(legacyFile, JSON.stringify(legacy));
231 yield* fs.writeFileString(
232 path.join(home, "credentials/work/axiom-stored.json"),
233 "{not-json",
234 );
235
236 const manifest = yield* (yield* ProfileStore).readManifest;
237 expect(manifest.profiles.default?.providers.AWS).toEqual({
238 method: "sso",
239 ssoProfile: "dev",
240 });
241 expect(manifest.profiles.work?.providers.GitHub?.token).toBe("ghp_v0token");
242 expect(manifest.profiles.work?.providers.Axiom).toEqual({
243 method: "stored",
244 });
245 expect(manifest.profiles.work?.providers.Broken).toBeUndefined();
246
247 const backup = (yield* fs.readDirectory(home)).find((entry) =>
248 entry.startsWith(".profiles-v0-"),
249 );
250 expect(backup).toBeDefined();
251 expect(
252 yield* fs.readFileString(path.join(home, backup!, "credentials/work/axiom-stored.json")),
253 ).toBe("{not-json");
254 }),
255 ),
256 { tags: ["unit", "local"], exclusive: true },
257 );
258
259 it.live(
260 "inlines every recognized v0 credential sidecar",
261 () =>
262 withFixtureHome(undefined, (home) =>
263 Effect.gen(function* () {
264 const fs = yield* FileSystem.FileSystem;
265 const staticCredentials = {
266 "aws-stored": {
267 accessKeyId: "AKIAFIXTURE",
268 secretAccessKey: "aws-secret",
269 region: "us-east-1",
270 },
271 "axiom-stored": {
272 type: "apiToken",
273 apiToken: "axiom-token",
274 orgId: "axiom-org",
275 },
276 "fly-stored": { apiKey: "fly-token" },
277 "github-stored": { type: "pat", token: "github-token" },
278 "hetzner-stored": { token: "hetzner-token" },
279 "neon-stored": { apiKey: "neon-key" },
280 "planetscale-stored": {
281 type: "apiToken",
282 tokenId: "ps-token-id",
283 token: "ps-token",
284 organization: "ps-org",
285 },
286 "prisma-stored": { serviceToken: "prisma-token" },
287 "railway-stored": { type: "token", token: "railway-token" },
288 };
289 const oauthCredentials = {
290 "planetscale-oauth": {
291 type: "oauth",
292 clientId: "ps-client",
293 access: "ps-access",
294 refresh: "ps-refresh",
295 expires: 4_102_444_800_000,
296 scopes: ["read_organizations"],
297 },
298 "railway-oauth": { type: "token", token: "railway-oauth-token" },
299 };
300 yield* fs.writeFileString(
301 path.join(home, "profiles.json"),
302 JSON.stringify({
303 version: 0,
304 profiles: {
305 static: {
306 AWS: { method: "stored" },
307 Axiom: { method: "stored" },
308 Fly: { method: "stored" },
309 GitHub: { method: "stored" },
310 Hetzner: { method: "stored" },
311 Neon: { method: "stored" },
312 Planetscale: { method: "stored" },
313 Prisma: { method: "stored" },
314 Railway: { method: "stored" },
315 },
316 oauth: {
317 Planetscale: { method: "oauth", organization: "ps-org" },
318 Railway: { method: "oauth" },
319 },
320 },
321 }),
322 );
323 for (const [profile, credentials] of Object.entries({
324 static: staticCredentials,
325 oauth: oauthCredentials,
326 })) {
327 const dir = path.join(home, "credentials", profile);
328 yield* fs.makeDirectory(dir, { recursive: true });
329 for (const [key, values] of Object.entries(credentials)) {
330 yield* fs.writeFileString(path.join(dir, `${key}.json`), JSON.stringify(values));
331 }
332 }
333
334 const manifest = yield* (yield* ProfileStore).readManifest;
335 expect(manifest.profiles.static?.providers).toEqual({
336 AWS: {
337 method: "stored",
338 accessKeyId: "AKIAFIXTURE",
339 secretAccessKey: "aws-secret",
340 region: "us-east-1",
341 },
342 Axiom: {
343 method: "stored",
344 token: "axiom-token",
345 orgId: "axiom-org",
346 },
347 Fly: { method: "stored", apiKey: "fly-token" },
348 GitHub: { method: "stored", token: "github-token" },
349 Hetzner: { method: "stored", token: "hetzner-token" },
350 Neon: { method: "stored", apiKey: "neon-key" },
351 Planetscale: {
352 method: "stored",
353 tokenId: "ps-token-id",
354 token: "ps-token",
355 organization: "ps-org",
356 },
357 Prisma: { method: "stored", serviceToken: "prisma-token" },
358 Railway: { method: "stored", token: "railway-token" },
359 });
360 expect(manifest.profiles.oauth?.providers).toEqual({
361 Planetscale: {
362 method: "oauth",
363 organization: "ps-org",
364 clientId: "ps-client",
365 access: "ps-access",
366 refresh: "ps-refresh",
367 expires: 4_102_444_800_000,
368 scopes: ["read_organizations"],
369 },
370 Railway: { method: "oauth", token: "railway-oauth-token" },
371 });
372 }),
373 ),
374 { tags: ["unit", "local"], exclusive: true },
375 );