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

auth.test.ts

300 lines12.0 KB

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