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

main
ts 215 lines 7.03 KB
Raw
1 import { expect, it } from "@alchemy.run/test";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import * as ConfigProvider from "effect/ConfigProvider";
4 import * as Effect from "effect/Effect";
5 import * as FileSystem from "effect/FileSystem";
6 import * as Layer from "effect/Layer";
7 import * as Schema from "effect/Schema";
8 import { AuthProviderLayer, AuthProvidersLive, NeedsReauth } from "@/Auth/AuthProvider.ts";
9 import {
10 type CredentialDemand,
11 type CredentialsRequired,
12 demandCredentials,
13 } from "@/Auth/Demand.ts";
14 import { ProfileStore, ProfileStoreLive } from "@/Auth/Profile.ts";
15
16 const PROBE = "DemandProbe";
17
18 /**
19 * Every credential touch goes through `read` — the counter is how the tests
20 * prove both directions: warm-up runs it exactly once per demanded provider,
21 * and a zero-demand run never runs it at all.
22 */
23 const state = { reads: 0, mode: "ok" as "ok" | "needs-reauth" };
24
25 const ProbeAuth = AuthProviderLayer<{ method: "stored" }, string>()(PROBE, {
26 configSchema: Schema.Struct({ method: Schema.Literal("stored") }),
27 configure: () => Effect.succeed({ method: "stored" as const }),
28 login: () => Effect.void,
29 logout: () => Effect.void,
30 details: () => Effect.succeed({ lines: [] }),
31 read: (profileName) =>
32 Effect.suspend(() => {
33 state.reads += 1;
34 return state.mode === "ok"
35 ? Effect.succeed("probe-credentials")
36 : Effect.fail(
37 new NeedsReauth({
38 provider: PROBE,
39 profile: profileName,
40 message: "Probe refresh token is dead.",
41 }),
42 );
43 }),
44 });
45
46 const ENV_PROBE = "DemandEnvProbe";
47 const ENV_PROBE_TOKEN = "DEMAND_PROBE_TOKEN";
48 const envState = { reads: 0 };
49
50 /** A provider that also supports environment credentials. */
51 const EnvProbeAuth = AuthProviderLayer<{ method: "stored" }, string>()(ENV_PROBE, {
52 configSchema: Schema.Struct({ method: Schema.Literal("stored") }),
53 configure: () => Effect.succeed({ method: "stored" as const }),
54 login: () => Effect.void,
55 logout: () => Effect.void,
56 details: () => Effect.succeed({ lines: [] }),
57 read: () => Effect.succeed("profile-credentials"),
58 readEnvironment: Effect.sync(() => {
59 envState.reads += 1;
60 return "env-credentials";
61 }),
62 environment: [{ name: ENV_PROBE_TOKEN, required: true, secret: true }],
63 });
64
65 const makeTestLayer = (config: Record<string, unknown> = {}) =>
66 Layer.mergeAll(ProfileStoreLive, ProbeAuth, EnvProbeAuth).pipe(
67 Layer.provideMerge(
68 Layer.mergeAll(
69 AuthProvidersLive,
70 // Fully replaces the ambient provider: an exported CI=1 (or
71 // ALCHEMY_PROFILE) in the developer's shell must not leak into the
72 // demand seam under test.
73 ConfigProvider.layer(ConfigProvider.fromUnknown(config)),
74 NodeServices.layer,
75 ),
76 ),
77 );
78
79 /**
80 * Point `ALCHEMY_HOME` at a scoped temp directory so the store never
81 * touches the developer's real `~/.alchemy`. Tests using this must be
82 * `exclusive` — the env var is process-global.
83 */
84 const withTempHome = <A, E, R>(
85 effect: Effect.Effect<A, E, R>,
86 config: Record<string, unknown> = {},
87 ) =>
88 Effect.gen(function* () {
89 state.reads = 0;
90 state.mode = "ok";
91 envState.reads = 0;
92 const fs = yield* FileSystem.FileSystem;
93 const dir = yield* fs.makeTempDirectoryScoped({
94 prefix: "alchemy-demand-",
95 });
96 const previous = process.env.ALCHEMY_HOME;
97 yield* Effect.acquireRelease(
98 Effect.sync(() => {
99 process.env.ALCHEMY_HOME = dir;
100 }),
101 () =>
102 Effect.sync(() => {
103 if (previous === undefined) delete process.env.ALCHEMY_HOME;
104 else process.env.ALCHEMY_HOME = previous;
105 }),
106 );
107 return yield* effect.pipe(Effect.provide(makeTestLayer(config)));
108 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
109
110 const configureProbe = Effect.gen(function* () {
111 const profile = yield* ProfileStore;
112 yield* profile.setProviderConfig("default", PROBE, { method: "stored" });
113 });
114
115 const demand: CredentialDemand = {
116 provider: PROBE,
117 resources: [{ fqn: "Website", reason: "remote" }],
118 };
119
120 it.live(
121 "zero demand touches no credentials at all",
122 () =>
123 withTempHome(
124 Effect.gen(function* () {
125 yield* configureProbe;
126 yield* demandCredentials([]);
127 expect(state.reads).toBe(0);
128 }),
129 ),
130 { tags: ["unit", "local"], exclusive: true },
131 );
132
133 it.live(
134 "a demanded provider is warmed up through its real read path",
135 () =>
136 withTempHome(
137 Effect.gen(function* () {
138 yield* configureProbe;
139 yield* demandCredentials([demand]);
140 expect(state.reads).toBe(1);
141 }),
142 ),
143 { tags: ["unit", "local"], exclusive: true },
144 );
145
146 it.live(
147 "a dead token fails typed before apply, naming the demanding resources",
148 () =>
149 withTempHome(
150 Effect.gen(function* () {
151 yield* configureProbe;
152 state.mode = "needs-reauth";
153 const error = yield* Effect.flip(demandCredentials([demand]));
154 expect(error._tag).toBe("NeedsReauth");
155 expect(error.message).toContain("Probe refresh token is dead.");
156 expect(error.message).toContain(`These resources require ${PROBE} credentials:`);
157 expect(error.message).toContain("Website");
158 expect(error.message).toContain("Alchemy.remote()");
159 }),
160 ),
161 { tags: ["unit", "local"], exclusive: true },
162 );
163
164 it.live(
165 "an unconfigured provider fails with CredentialsRequired and never reads",
166 () =>
167 withTempHome(
168 Effect.gen(function* () {
169 const error = (yield* Effect.flip(demandCredentials([demand]))) as CredentialsRequired;
170 expect(error._tag).toBe("CredentialsRequired");
171 expect(error.resources).toEqual(["Website"]);
172 expect(error.message).toContain(`--add ${PROBE}`);
173 expect(state.reads).toBe(0);
174 }),
175 ),
176 { tags: ["unit", "local"], exclusive: true },
177 );
178
179 it.live(
180 "a nonexistent explicit profile fails with the actionable CredentialsRequired",
181 () =>
182 withTempHome(
183 Effect.gen(function* () {
184 const error = (yield* Effect.flip(demandCredentials([demand]))) as CredentialsRequired;
185 // NOT a generic ProfileError: the user must still learn which
186 // resources demanded credentials and which command fixes it.
187 expect(error._tag).toBe("CredentialsRequired");
188 expect(error.message).toContain("ghost");
189 expect(error.message).toContain("Website");
190 expect(state.reads).toBe(0);
191 }),
192 { ALCHEMY_PROFILE: "ghost" },
193 ),
194 { tags: ["unit", "local"], exclusive: true },
195 );
196
197 it.live(
198 "exported env credentials satisfy the gate when no profile is selected",
199 () =>
200 withTempHome(
201 Effect.gen(function* () {
202 yield* demandCredentials([
203 {
204 provider: ENV_PROBE,
205 resources: [{ fqn: "Api", reason: "remote" }],
206 },
207 ]);
208 // The gate warmed through the provider's environment path — the
209 // same source the run's lazy resolution will use.
210 expect(envState.reads).toBe(1);
211 }),
212 { [ENV_PROBE_TOKEN]: "token" },
213 ),
214 { tags: ["unit", "local"], exclusive: true },
215 );