Open History to see the last commit
1import type { SdkCredentialStore, SdkLoginOptions, SdkLoginResult } from "@cursor/sdk";
2import {
3 ProviderSetupError,
4 type ProviderAuthState,
5 type ProviderInstanceId,
6} from "@t3tools/contracts";
7import * as Cause from "effect/Cause";
8import * as Clock from "effect/Clock";
9import * as SecureRandom from "effect/crypto/SecureRandom";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as Fiber from "effect/Fiber";
14import * as Option from "effect/Option";
15import * as Queue from "effect/Queue";
16import * as Scope from "effect/Scope";
17import * as Semaphore from "effect/Semaphore";
18import * as Stream from "effect/Stream";
19import * as SubscriptionRef from "effect/SubscriptionRef";
20
21import { loadCursorSdk } from "./sdk.ts";
22import type { ProviderAuthController } from "@t3tools/provider-core/server/auth";
23
24const AUTH_TIMEOUT_MS = 300_000;
25
26interface AuthFlow {
27 readonly id: string;
28 readonly owner: string;
29 fiber?: Fiber.Fiber<void>;
30}
31
32export interface CursorAuth {
33 readonly controller: ProviderAuthController;
34 readonly readApiKey: Effect.Effect<string | undefined, ProviderSetupError>;
35 readonly requireApiKey: Effect.Effect<string, ProviderSetupError>;
36 readonly usesApiKey: boolean;
37 readonly withAccess: <A, E, R>(
38 task: Effect.Effect<A, E, R>,
39 ) => Effect.Effect<A, E | ProviderSetupError, R | Scope.Scope>;
40}
41
42export interface CursorAuthOptions {
43 readonly instanceId: ProviderInstanceId;
44 readonly displayName: string;
45 readonly enabled: boolean;
46 readonly apiKey?: string;
47 readonly store: SdkCredentialStore;
48 readonly credentialBinding?: NonNullable<ProviderAuthController["credentialBinding"]>;
49 readonly onChanged: (signedIn: boolean) => Effect.Effect<void, ProviderSetupError>;
50 readonly login?: (options: SdkLoginOptions) => Promise<SdkLoginResult>;
51}
52
53export const makeCursorAuth = Effect.fn("makeCursorAuth")(function* (options: CursorAuthOptions) {
54 const scope = yield* Scope.Scope;
55 const random = yield* SecureRandom.SecureRandom;
56 const lock = yield* Semaphore.make(1);
57 const configuredKey = options.apiKey?.trim() || undefined;
58 const emptyState: ProviderAuthState = {
59 instanceId: options.instanceId,
60 phase: "idle",
61 flowId: null,
62 authorizationUrl: null,
63 expiresAt: null,
64 message: null,
65 };
66 const snapshot = yield* SubscriptionRef.make({ owner: null as string | null, state: emptyState });
67 let active: AuthFlow | undefined;
68 let operation: "idle" | "login" | "stopping" | "closed" = "idle";
69 const sessions = new Set<Scope.Closeable>();
70
71 const publish = (flow: AuthFlow, patch: Partial<ProviderAuthState>) =>
72 SubscriptionRef.update(snapshot, (current) => ({
73 owner: flow.owner,
74 state: { ...current.state, ...patch },
75 }));
76
77 const readApiKey = Effect.gen(function* () {
78 if (configuredKey) return configuredKey;
79 const credentials = yield* Effect.tryPromise({
80 try: () => options.store.load(),
81 catch: (cause) =>
82 new ProviderSetupError({
83 instanceId: options.instanceId,
84 operation: "credentials",
85 detail: "Could not read the Cursor sign-in. Try signing in again.",
86 cause,
87 }),
88 });
89 const now = yield* Clock.currentTimeMillis;
90 return credentials &&
91 (credentials.apiKeyExpiresAtMs === undefined || credentials.apiKeyExpiresAtMs > now)
92 ? credentials.apiKey
93 : undefined;
94 });
95
96 const requireApiKey = Effect.gen(function* () {
97 if (operation !== "idle") {
98 return yield* new ProviderSetupError({
99 instanceId: options.instanceId,
100 operation: "credentials",
101 detail: "Cursor sign-in or sign-out is in progress. Try again after it finishes.",
102 });
103 }
104 const apiKey = yield* readApiKey;
105 if (!apiKey) {
106 return yield* new ProviderSetupError({
107 instanceId: options.instanceId,
108 operation: "credentials",
109 detail: "Sign in with Cursor or add CURSOR_API_KEY in provider settings.",
110 });
111 }
112 return apiKey;
113 });
114
115 // Closing admission before draining these scopes prevents cached credentials surviving sign-out.
116 const withAccess: CursorAuth["withAccess"] = (task) =>
117 Effect.uninterruptibleMask((restore) =>
118 Effect.gen(function* () {
119 const parent = yield* Scope.Scope;
120 const child = yield* lock.withPermits(1)(
121 Effect.gen(function* () {
122 if (operation !== "idle")
123 return yield* new ProviderSetupError({
124 instanceId: options.instanceId,
125 operation: "session",
126 detail: "Cursor sign-in or sign-out is in progress. Try again after it finishes.",
127 });
128 const child = yield* Scope.make();
129 sessions.add(child);
130 yield* Scope.addFinalizer(
131 child,
132 Effect.sync(() => {
133 sessions.delete(child);
134 }),
135 );
136 yield* Scope.addFinalizer(parent, Scope.close(child, Exit.void));
137 return child;
138 }),
139 );
140 const fiber = yield* restore(task).pipe(
141 Effect.provideService(Scope.Scope, child),
142 Effect.forkIn(child),
143 );
144 return yield* restore(Fiber.await(fiber)).pipe(
145 Effect.flatMap((result) => result),
146 Effect.onExit((result) =>
147 Exit.isFailure(result) ? Scope.close(child, Exit.void) : Effect.void,
148 ),
149 );
150 }),
151 );
152 const stopSessionsWithCredentials = Effect.suspend(() =>
153 Effect.forEach(Array.from(sessions), (session) => Scope.close(session, Exit.void), {
154 discard: true,
155 concurrency: "unbounded",
156 }),
157 );
158
159 const runLogin = Effect.fn("CursorAuth.runLogin")(
160 function* (flow: AuthFlow, stopSessions: Effect.Effect<void, ProviderSetupError>) {
161 yield* stopSessions.pipe(Effect.ensuring(stopSessionsWithCredentials));
162 // The SDK first writes into memory. Cancellation must not save a late login result.
163 const { Cursor, InMemoryCredentialStore } = yield* Effect.try({
164 try: loadCursorSdk,
165 catch: (cause) =>
166 new ProviderSetupError({
167 instanceId: options.instanceId,
168 operation: "start",
169 detail: "Could not load the Cursor SDK. Try signing in again.",
170 cause,
171 }),
172 });
173 const pendingStore = new InMemoryCredentialStore();
174 const urls = yield* Queue.unbounded<string>();
175 yield* Queue.take(urls).pipe(
176 Effect.flatMap((authorizationUrl) =>
177 lock.withPermits(1)(
178 Effect.gen(function* () {
179 if (active !== flow) return;
180 yield* publish(flow, {
181 phase: "waiting",
182 authorizationUrl,
183 message:
184 "Open the Cursor sign-in page and finish signing in. This page updates automatically.",
185 });
186 }),
187 ),
188 ),
189 Effect.forever,
190 Effect.forkScoped,
191 );
192 yield* Effect.tryPromise({
193 try: (signal) =>
194 (options.login ?? Cursor.auth.login)({
195 openBrowser: false,
196 store: pendingStore,
197 signal,
198 apiKeyName: `T3 Code - ${options.displayName}`,
199 onLoginUrl: (authorizationUrl) => {
200 if (active === flow) Queue.offerUnsafe(urls, authorizationUrl);
201 },
202 }),
203 catch: (cause) =>
204 new ProviderSetupError({
205 instanceId: options.instanceId,
206 operation: "start",
207 detail: "Cursor sign-in failed. Start sign-in again.",
208 cause,
209 }),
210 });
211 // Commit and publish together; interrupting a store Promise cannot stop a late write.
212 yield* lock.withPermits(1)(
213 Effect.gen(function* () {
214 if (active !== flow) return;
215 yield* publish(flow, {
216 phase: "verifying",
217 authorizationUrl: null,
218 message: "Checking Cursor sign-in.",
219 });
220 yield* Effect.tryPromise({
221 try: async () => {
222 const credentials = await pendingStore.load();
223 if (!credentials) throw new Error("Cursor login did not return credentials");
224 await options.store.save(credentials);
225 },
226 catch: (cause) =>
227 new ProviderSetupError({
228 instanceId: options.instanceId,
229 operation: "start",
230 detail: "Could not save the Cursor sign-in. Try again.",
231 cause,
232 }),
233 });
234 const verified = yield* options.onChanged(true).pipe(Effect.exit);
235 if (Exit.isFailure(verified)) {
236 yield* Effect.tryPromise({
237 try: () => options.store.clear(),
238 catch: (cause) =>
239 new ProviderSetupError({
240 instanceId: options.instanceId,
241 operation: "start",
242 detail: "Could not clear the rejected Cursor sign-in. Try signing out.",
243 cause,
244 }),
245 });
246 return yield* Effect.failCause(verified.cause);
247 }
248 active = undefined;
249 operation = "idle";
250 yield* publish(flow, {
251 phase: "succeeded",
252 authorizationUrl: null,
253 expiresAt: null,
254 message: "Signed in with Cursor.",
255 });
256 }).pipe(Effect.uninterruptible),
257 );
258 },
259 (effect, flow, _stopSessions) =>
260 effect.pipe(
261 Effect.scoped,
262 Effect.timeoutOrElse({
263 duration: AUTH_TIMEOUT_MS,
264 orElse: () =>
265 Effect.fail(
266 new ProviderSetupError({
267 instanceId: options.instanceId,
268 operation: "start",
269 detail: "Cursor sign-in expired. Start sign-in again.",
270 }),
271 ),
272 }),
273 Effect.exit,
274 Effect.flatMap((result) =>
275 lock.withPermits(1)(
276 Effect.gen(function* () {
277 if (active !== flow) return;
278 active = undefined;
279 operation = "idle";
280 yield* publish(flow, {
281 phase: Exit.isSuccess(result) ? "succeeded" : "failed",
282 authorizationUrl: null,
283 expiresAt: null,
284 message: Exit.isSuccess(result)
285 ? "Signed in with Cursor."
286 : Option.match(Cause.findErrorOption(result.cause), {
287 onNone: () => "Cursor sign-in failed or expired. Start sign-in again.",
288 onSome: (error) => error.detail,
289 }),
290 });
291 }),
292 ),
293 ),
294 ),
295 );
296
297 const requireFlow = Effect.fn("CursorAuth.requireFlow")(function* (
298 owner: string,
299 id: string,
300 name: string,
301 ) {
302 if (!active || active.owner !== owner || active.id !== id) {
303 return yield* new ProviderSetupError({
304 instanceId: options.instanceId,
305 operation: name,
306 detail: "This sign-in is no longer active in this client.",
307 });
308 }
309 return active;
310 });
311
312 const controller: ProviderAuthController = {
313 credentialBinding: options.credentialBinding ?? {
314 owner: "t3",
315 key: `cursor:${options.instanceId}`,
316 },
317 isChangingCredentials: Effect.sync(() => operation !== "idle"),
318 start: (owner, stopSessions = Effect.void) =>
319 lock.withPermits(1)(
320 Effect.uninterruptible(
321 Effect.gen(function* () {
322 if (!options.enabled)
323 return yield* new ProviderSetupError({
324 instanceId: options.instanceId,
325 operation: "start",
326 detail: "Enable Cursor before signing in.",
327 });
328 if (configuredKey)
329 return yield* new ProviderSetupError({
330 instanceId: options.instanceId,
331 operation: "start",
332 detail:
333 "Remove CURSOR_API_KEY from this provider's environment before using browser sign-in.",
334 });
335 if (active?.owner === owner && operation === "login") return snapshot.value.state;
336 if (operation !== "idle")
337 return yield* new ProviderSetupError({
338 instanceId: options.instanceId,
339 operation: "start",
340 detail: "Cursor setup is already in progress.",
341 });
342 const id = yield* random.uuidV4().pipe(
343 Effect.mapError(
344 (cause) =>
345 new ProviderSetupError({
346 instanceId: options.instanceId,
347 operation: "start",
348 detail: "Could not start Cursor sign-in. Try again.",
349 cause,
350 }),
351 ),
352 );
353 const expiresAt = DateTime.formatIso(
354 DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + AUTH_TIMEOUT_MS),
355 );
356 const flow: AuthFlow = { id, owner };
357 active = flow;
358 operation = "login";
359 const state: ProviderAuthState = {
360 ...emptyState,
361 phase: "starting",
362 flowId: id,
363 expiresAt,
364 message: "Starting Cursor sign-in.",
365 };
366 yield* SubscriptionRef.set(snapshot, { owner, state });
367 flow.fiber = yield* runLogin(flow, stopSessions).pipe(
368 Effect.interruptible,
369 Effect.forkIn(scope),
370 );
371 return state;
372 }),
373 ),
374 ),
375 complete: () =>
376 Effect.fail(
377 new ProviderSetupError({
378 instanceId: options.instanceId,
379 operation: "complete",
380 detail: "Finish signing in on the Cursor website. No redirect URL is needed.",
381 }),
382 ),
383 cancel: (owner, id) =>
384 Effect.uninterruptible(
385 Effect.gen(function* () {
386 const flow = yield* lock.withPermits(1)(
387 Effect.gen(function* () {
388 const flow = yield* requireFlow(owner, id, "cancel");
389 active = undefined;
390 operation = "stopping";
391 yield* publish(flow, {
392 phase: "cancelled",
393 authorizationUrl: null,
394 expiresAt: null,
395 message: "Cursor sign-in was cancelled.",
396 });
397 return flow;
398 }),
399 );
400 if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
401 operation = "idle";
402 return snapshot.value.state;
403 }),
404 ),
405 logout: (stopSessions) =>
406 Effect.uninterruptible(
407 Effect.gen(function* () {
408 const flow = yield* lock.withPermits(1)(
409 Effect.gen(function* () {
410 if (configuredKey)
411 return yield* new ProviderSetupError({
412 instanceId: options.instanceId,
413 operation: "logout",
414 detail:
415 "Remove CURSOR_API_KEY from this provider's environment to disconnect it.",
416 });
417 if (operation !== "idle" && operation !== "login")
418 return yield* new ProviderSetupError({
419 instanceId: options.instanceId,
420 operation: "logout",
421 detail: "Cursor setup is already stopping.",
422 });
423 operation = "stopping";
424 const flow = active;
425 active = undefined;
426 return flow;
427 }),
428 );
429 const result = yield* Effect.gen(function* () {
430 if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);
431 yield* stopSessions.pipe(Effect.ensuring(stopSessionsWithCredentials));
432 yield* Effect.tryPromise({
433 try: () => options.store.clear(),
434 catch: (cause) =>
435 new ProviderSetupError({
436 instanceId: options.instanceId,
437 operation: "logout",
438 detail: "Could not clear the Cursor sign-in. Try again.",
439 cause,
440 }),
441 });
442 yield* options.onChanged(false);
443 }).pipe(Effect.exit);
444 operation = "idle";
445 const state: ProviderAuthState = {
446 ...emptyState,
447 phase: Exit.isSuccess(result) ? "idle" : "failed",
448 message: Exit.isSuccess(result)
449 ? "Signed out of Cursor."
450 : "Cursor sign-out failed. Try again.",
451 };
452 yield* SubscriptionRef.set(snapshot, { owner: null, state });
453 if (Exit.isFailure(result)) return yield* Effect.failCause(result.cause);
454 return state;
455 }),
456 ),
457 subscribe: (owner) =>
458 SubscriptionRef.changes(snapshot).pipe(
459 Stream.map((current) => {
460 const state = {
461 ...current.state,
462 credentialOwner: "t3" as const,
463 methods: [
464 {
465 id: "browser",
466 name: "Sign in with Cursor",
467 description: null,
468 type: "agent" as const,
469 },
470 ],
471 interaction:
472 current.state.phase === "waiting" &&
473 current.state.authorizationUrl &&
474 current.state.flowId
475 ? {
476 type: "browser" as const,
477 id: current.state.flowId,
478 url: current.state.authorizationUrl,
479 requiresConsent: false,
480 }
481 : null,
482 };
483 if (current.owner === null || current.owner === owner) return state;
484 return {
485 ...state,
486 interaction: null,
487 flowId: null,
488 authorizationUrl: null,
489 expiresAt: null,
490 message: active ? "Sign-in is in progress in another client." : current.state.message,
491 };
492 }),
493 ),
494 isLogoutPrompt: (text, hasAttachments) => !hasAttachments && text.trim() === "/logout",
495 };
496
497 yield* Effect.addFinalizer(() =>
498 Effect.gen(function* () {
499 operation = "closed";
500 const flow = active;
501 active = undefined;
502 if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);
503 yield* stopSessionsWithCredentials;
504 }),
505 );
506
507 return {
508 controller,
509 readApiKey,
510 requireApiKey,
511 withAccess,
512 usesApiKey: configuredKey !== undefined,
513 } satisfies CursorAuth;
514});