Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

auth.test.ts

298 lines11.8 KB

1import type { SdkLoginOptions, StoredSdkCredentials } from "@cursor/sdk";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { expect, it } from "@effect/vitest";
4import { ProviderInstanceId, ProviderSetupError, type ProviderAuthState } from "@t3tools/contracts";
5import * as Clock from "effect/Clock";
6import * as Deferred from "effect/Deferred";
7import * as Effect from "effect/Effect";
8import * as Exit from "effect/Exit";
9import * as Fiber from "effect/Fiber";
10import * as Option from "effect/Option";
11import * as Stream from "effect/Stream";
12​
13import { makeCursorAuth, type CursorAuthOptions } from "./auth.ts";
14import { loadCursorSdk } from "./sdk.ts";
15​
16const { InMemoryCredentialStore } = loadCursorSdk();
17​
18const instanceId = ProviderInstanceId.make("cursor-personal");
19const owner = "owner-client";
20const otherOwner = "other-client";
21const authorizationUrl = "https://cursor.com/loginDeepControl?challenge=test-challenge";
22​
23const makeHarness = Effect.fn("makeCursorAuthHarness")(function* (
24 overrides: Partial<CursorAuthOptions> = {},
25) {
26 const store = new InMemoryCredentialStore();
27 const complete = Promise.withResolvers<void>();
28 const returned = Promise.withResolvers<void>();
29 const now = yield* Clock.currentTimeMillis;
30 const credentials: StoredSdkCredentials = {
31 version: 1,
32 backendUrl: "https://api2.cursor.sh",
33 apiKey: "browser-key",
34 createdAtMs: now,
35 apiKeyExpiresAtMs: now + 86_400_000,
36 email: "cursor@example.com",
37 };
38 let loginOptions: SdkLoginOptions | undefined;
39 const changes: boolean[] = [];
40 const auth = yield* makeCursorAuth({
41 instanceId,
42 displayName: "Personal Cursor",
43 enabled: true,
44 store,
45 onChanged: (signedIn) =>
46 Effect.sync(() => {
47 changes.push(signedIn);
48 }),
49 login: async (options) => {
50 loginOptions = options;
51 options.onLoginUrl?.(authorizationUrl);
52 await complete.promise;
53 await options.store?.save(credentials);
54 returned.resolve();
55 return {
56 apiKey: credentials.apiKey,
57 apiKeyExpiresAtMs: credentials.apiKeyExpiresAtMs!,
58 email: credentials.email!,
59 };
60 },
61 ...overrides,
62 });
63 return {
64 auth,
65 store,
66 complete,
67 returned,
68 credentials,
69 changes,
70 loginOptions: () => loginOptions,
71 };
72});
73​
74type Auth = Effect.Success<ReturnType<typeof makeCursorAuth>>;
75const phase = (auth: Auth, phase: ProviderAuthState["phase"], session = owner) =>
76 auth.controller.subscribe(session).pipe(
77 Stream.filter((state) => state.phase === phase),
78 Stream.runHead,
79 Effect.map(Option.getOrThrow),
80 );
81​
82it.layer(NodeServices.layer)("CursorAuth", (it) => {
83 it.effect("closes SDK sessions and interrupts in-flight credential work before signing out", () =>
84 Effect.gen(function* () {
85 const harness = yield* makeHarness();
86 yield* Effect.promise(() => harness.store.save(harness.credentials));
87 const acquired = yield* Deferred.make<void>();
88 let closedSession = false;
89 let closedRequest = false;
90 yield* harness.auth.withAccess(
91 Effect.acquireRelease(Effect.succeed("session"), () =>
92 Effect.sync(() => {
93 closedSession = true;
94 }),
95 ),
96 );
97 const request = yield* harness.auth
98 .withAccess(
99 Effect.gen(function* () {
100 yield* Effect.addFinalizer(() =>
101 Effect.sync(() => {
102 closedRequest = true;
103 }),
104 );
105 yield* Deferred.succeed(acquired, undefined);
106 return yield* Effect.never;
107 }),
108 )
109 .pipe(Effect.forkScoped);
110 yield* Deferred.await(acquired);
111 yield* harness.auth.controller.logout(Effect.void);
112 expect(closedSession).toBe(true);
113 expect(closedRequest).toBe(true);
114 expect(Exit.isFailure(yield* Fiber.await(request))).toBe(true);
115 expect(yield* harness.auth.readApiKey).toBeUndefined();
116 }).pipe(Effect.scoped),
117 );
118​
119 it.effect("completes a remote browser login, saves its key and refreshes provider status", () =>
120 Effect.gen(function* () {
121 const harness = yield* makeHarness();
122 let stopped = false;
123 expect(yield* harness.auth.readApiKey).toBeUndefined();
124 const starting = yield* harness.auth.controller.start(
125 owner,
126 Effect.sync(() => {
127 stopped = true;
128 }),
129 );
130 const waiting = yield* phase(harness.auth, "waiting");
131 expect(stopped).toBe(true);
132 expect(waiting.authorizationUrl).toBe(authorizationUrl);
133 expect(waiting.flowId).toBe(starting.flowId);
134 expect(harness.loginOptions()?.openBrowser).toBe(false);
135 expect((yield* harness.auth.controller.start(owner)).flowId).toBe(starting.flowId);
136 expect(Exit.isFailure(yield* Effect.exit(harness.auth.requireApiKey))).toBe(true);
137 yield* Effect.sync(() => harness.complete.resolve());
138 const succeeded = yield* phase(harness.auth, "succeeded");
139 expect(succeeded.authorizationUrl).toBeNull();
140 expect(yield* harness.auth.requireApiKey).toBe("browser-key");
141 expect(harness.changes).toEqual([true]);
142 expect(Object.values(succeeded)).not.toContain("browser-key");
143 expect(yield* Effect.promise(() => harness.store.load())).toEqual(harness.credentials);
144 }).pipe(Effect.scoped),
145 );
146​
147 it.effect("keeps the login link private to its owner and rejects other clients' mutations", () =>
148 Effect.gen(function* () {
149 const { auth } = yield* makeHarness();
150 yield* auth.controller.start(owner);
151 const waiting = yield* phase(auth, "waiting");
152 const foreign = yield* phase(auth, "waiting", otherOwner);
153 expect(foreign).toMatchObject({ flowId: null, authorizationUrl: null, expiresAt: null });
154 expect(Exit.isFailure(yield* Effect.exit(auth.controller.start(otherOwner)))).toBe(true);
155 expect(
156 Exit.isFailure(yield* Effect.exit(auth.controller.cancel(otherOwner, waiting.flowId!))),
157 ).toBe(true);
158 expect(
159 Exit.isFailure(
160 yield* Effect.exit(
161 auth.controller.complete(owner, {
162 flowId: waiting.flowId!,
163 callbackUrl: "http://localhost/callback",
164 }),
165 ),
166 ),
167 ).toBe(true);
168 expect((yield* phase(auth, "waiting")).authorizationUrl).toBe(authorizationUrl);
169 }).pipe(Effect.scoped),
170 );
171​
172 it.effect("aborts cancellation and ignores a late successful SDK login", () =>
173 Effect.gen(function* () {
174 const harness = yield* makeHarness();
175 yield* harness.auth.controller.start(owner);
176 const waiting = yield* phase(harness.auth, "waiting");
177 const cancelled = yield* harness.auth.controller.cancel(owner, waiting.flowId!);
178 expect(cancelled.phase).toBe("cancelled");
179 expect(cancelled.authorizationUrl).toBeNull();
180 expect(harness.loginOptions()?.signal?.aborted).toBe(true);
181 yield* Effect.sync(() => harness.complete.resolve());
182 yield* Effect.promise(() => harness.returned.promise);
183 expect(yield* harness.auth.readApiKey).toBeUndefined();
184 expect(harness.changes).toEqual([]);
185 }).pipe(Effect.scoped),
186 );
187​
188 it.effect("discards a credential rejected by verification and permits a fresh login", () =>
189 Effect.gen(function* () {
190 const rejectionMessage =
191 "Cursor needs a paid plan to run in T3 Code. Upgrade this account or sign in with a different one.";
192 let rejected = true;
193 const harness = yield* makeHarness({
194 onChanged: (signedIn) =>
195 signedIn && rejected
196 ? Effect.fail(
197 new ProviderSetupError({
198 instanceId,
199 operation: "start",
200 detail: rejectionMessage,
201 }),
202 )
203 : Effect.void,
204 });
205 yield* harness.auth.controller.start(owner);
206 yield* phase(harness.auth, "waiting");
207 yield* Effect.sync(() => harness.complete.resolve());
208 const failed = yield* phase(harness.auth, "failed");
209 expect(failed.message).toBe(rejectionMessage);
210 expect(yield* Effect.promise(() => harness.store.load())).toBeUndefined();
211 expect(yield* harness.auth.readApiKey).toBeUndefined();
212 expect(Exit.isFailure(yield* Effect.exit(harness.auth.requireApiKey))).toBe(true);
213 rejected = false;
214 yield* harness.auth.controller.start(owner);
215 yield* phase(harness.auth, "succeeded");
216 expect(yield* harness.auth.requireApiKey).toBe("browser-key");
217 }).pipe(Effect.scoped),
218 );
219​
220 it.effect("clears only this instance's credential after its sessions stop", () =>
221 Effect.gen(function* () {
222 const harness = yield* makeHarness();
223 const other = yield* makeHarness({ instanceId: ProviderInstanceId.make("cursor-work") });
224 yield* Effect.promise(() => harness.store.save(harness.credentials));
225 yield* Effect.promise(() => other.store.save({ ...other.credentials, apiKey: "other-key" }));
226 const state = yield* harness.auth.controller.logout(
227 Effect.gen(function* () {
228 expect(yield* harness.auth.readApiKey).toBe("browser-key");
229 expect(Exit.isFailure(yield* Effect.exit(harness.auth.requireApiKey))).toBe(true);
230 }),
231 );
232 expect(state.message).toBe("Signed out of Cursor.");
233 expect(yield* harness.auth.readApiKey).toBeUndefined();
234 expect(yield* other.auth.requireApiKey).toBe("other-key");
235 expect(harness.changes).toEqual([false]);
236 }).pipe(Effect.scoped),
237 );
238​
239 it.effect("cancels a pending sign-in on logout without saving its eventual key", () =>
240 Effect.gen(function* () {
241 const harness = yield* makeHarness();
242 yield* harness.auth.controller.start(owner);
243 yield* phase(harness.auth, "waiting");
244 yield* harness.auth.controller.logout(Effect.void);
245 expect(harness.loginOptions()?.signal?.aborted).toBe(true);
246 yield* Effect.sync(() => harness.complete.resolve());
247 yield* Effect.promise(() => harness.returned.promise);
248 expect(yield* harness.auth.readApiKey).toBeUndefined();
249 }).pipe(Effect.scoped),
250 );
251​
252 it.effect("retains credentials if sessions cannot be stopped for logout", () =>
253 Effect.gen(function* () {
254 const harness = yield* makeHarness();
255 yield* Effect.promise(() => harness.store.save(harness.credentials));
256 const result = yield* Effect.exit(
257 harness.auth.controller.logout(
258 Effect.fail(
259 new ProviderSetupError({
260 instanceId,
261 operation: "stop",
262 detail: "Unable to stop sessions",
263 }),
264 ),
265 ),
266 );
267 expect(Exit.isFailure(result)).toBe(true);
268 expect(yield* harness.auth.requireApiKey).toBe("browser-key");
269 }).pipe(Effect.scoped),
270 );
271​
272 it.effect(
273 "prefers explicit API keys and prevents browser login from silently overriding them",
274 () =>
275 Effect.gen(function* () {
276 const harness = yield* makeHarness({ apiKey: " explicit-key " });
277 yield* Effect.promise(() => harness.store.save(harness.credentials));
278 expect(yield* harness.auth.requireApiKey).toBe("explicit-key");
279 expect(Exit.isFailure(yield* Effect.exit(harness.auth.controller.start(owner)))).toBe(true);
280 expect(
281 Exit.isFailure(yield* Effect.exit(harness.auth.controller.logout(Effect.void))),
282 ).toBe(true);
283 expect(harness.loginOptions()).toBeUndefined();
284 expect((yield* Effect.promise(() => harness.store.load()))?.apiKey).toBe("browser-key");
285 }).pipe(Effect.scoped),
286 );
287​
288 it.effect("ignores expired browser credentials and rejects disabled sign-in", () =>
289 Effect.gen(function* () {
290 const harness = yield* makeHarness({ enabled: false });
291 yield* Effect.promise(() =>
292 harness.store.save({ ...harness.credentials, apiKeyExpiresAtMs: 0 }),
293 );
294 expect(yield* harness.auth.readApiKey).toBeUndefined();
295 expect(Exit.isFailure(yield* Effect.exit(harness.auth.controller.start(owner)))).toBe(true);
296 }).pipe(Effect.scoped),
297 );
298});