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