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