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