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 Crypto from "effect/Crypto";
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 { Cursor, InMemoryCredentialStore } 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 crypto = yield* Crypto.Crypto;
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 pendingStore = new InMemoryCredentialStore();
164 const urls = yield* Queue.unbounded<string>();
165 yield* Queue.take(urls).pipe(
166 Effect.flatMap((authorizationUrl) =>
167 lock.withPermits(1)(
168 Effect.gen(function* () {
169 if (active !== flow) return;
170 yield* publish(flow, {
171 phase: "waiting",
172 authorizationUrl,
173 message:
174 "Open the Cursor sign-in page and finish signing in. This page updates automatically.",
175 });
176 }),
177 ),
178 ),
179 Effect.forever,
180 Effect.forkScoped,
181 );
182 yield* Effect.tryPromise({
183 try: (signal) =>
184 (options.login ?? Cursor.auth.login)({
185 openBrowser: false,
186 store: pendingStore,
187 signal,
188 apiKeyName: `T3 Code - ${options.displayName}`,
189 onLoginUrl: (authorizationUrl) => {
190 if (active === flow) Queue.offerUnsafe(urls, authorizationUrl);
191 },
192 }),
193 catch: (cause) =>
194 new ProviderSetupError({
195 instanceId: options.instanceId,
196 operation: "start",
197 detail: "Cursor sign-in failed. Start sign-in again.",
198 cause,
199 }),
200 });
201 // Commit and publish together; interrupting a store Promise cannot stop a late write.
202 yield* lock.withPermits(1)(
203 Effect.gen(function* () {
204 if (active !== flow) return;
205 yield* publish(flow, {
206 phase: "verifying",
207 authorizationUrl: null,
208 message: "Checking Cursor sign-in.",
209 });
210 yield* Effect.tryPromise({
211 try: async () => {
212 const credentials = await pendingStore.load();
213 if (!credentials) throw new Error("Cursor login did not return credentials");
214 await options.store.save(credentials);
215 },
216 catch: (cause) =>
217 new ProviderSetupError({
218 instanceId: options.instanceId,
219 operation: "start",
220 detail: "Could not save the Cursor sign-in. Try again.",
221 cause,
222 }),
223 });
224 const verified = yield* options.onChanged(true).pipe(Effect.exit);
225 if (Exit.isFailure(verified)) {
226 yield* Effect.tryPromise({
227 try: () => options.store.clear(),
228 catch: (cause) =>
229 new ProviderSetupError({
230 instanceId: options.instanceId,
231 operation: "start",
232 detail: "Could not clear the rejected Cursor sign-in. Try signing out.",
233 cause,
234 }),
235 });
236 return yield* Effect.failCause(verified.cause);
237 }
238 active = undefined;
239 operation = "idle";
240 yield* publish(flow, {
241 phase: "succeeded",
242 authorizationUrl: null,
243 expiresAt: null,
244 message: "Signed in with Cursor.",
245 });
246 }).pipe(Effect.uninterruptible),
247 );
248 },
249 (effect, flow, stopSessions) =>
250 effect.pipe(
251 Effect.scoped,
252 Effect.timeoutOrElse({
253 duration: AUTH_TIMEOUT_MS,
254 orElse: () =>
255 Effect.fail(
256 new ProviderSetupError({
257 instanceId: options.instanceId,
258 operation: "start",
259 detail: "Cursor sign-in expired. Start sign-in again.",
260 }),
261 ),
262 }),
263 Effect.exit,
264 Effect.flatMap((result) =>
265 lock.withPermits(1)(
266 Effect.gen(function* () {
267 if (active !== flow) return;
268 active = undefined;
269 operation = "idle";
270 yield* publish(flow, {
271 phase: Exit.isSuccess(result) ? "succeeded" : "failed",
272 authorizationUrl: null,
273 expiresAt: null,
274 message: Exit.isSuccess(result)
275 ? "Signed in with Cursor."
276 : Option.match(Cause.findErrorOption(result.cause), {
277 onNone: () => "Cursor sign-in failed or expired. Start sign-in again.",
278 onSome: (error) => error.detail,
279 }),
280 });
281 }),
282 ),
283 ),
284 ),
285 );
286
287 const requireFlow = Effect.fn("CursorAuth.requireFlow")(function* (
288 owner: string,
289 id: string,
290 name: string,
291 ) {
292 if (!active || active.owner !== owner || active.id !== id) {
293 return yield* new ProviderSetupError({
294 instanceId: options.instanceId,
295 operation: name,
296 detail: "This sign-in is no longer active in this client.",
297 });
298 }
299 return active;
300 });
301
302 const controller: ProviderAuthController = {
303 credentialBinding: options.credentialBinding ?? {
304 owner: "t3",
305 key: `cursor:${options.instanceId}`,
306 },
307 isChangingCredentials: Effect.sync(() => operation !== "idle"),
308 start: (owner, stopSessions = Effect.void) =>
309 lock.withPermits(1)(
310 Effect.uninterruptible(
311 Effect.gen(function* () {
312 if (!options.enabled)
313 return yield* new ProviderSetupError({
314 instanceId: options.instanceId,
315 operation: "start",
316 detail: "Enable Cursor before signing in.",
317 });
318 if (configuredKey)
319 return yield* new ProviderSetupError({
320 instanceId: options.instanceId,
321 operation: "start",
322 detail:
323 "Remove CURSOR_API_KEY from this provider's environment before using browser sign-in.",
324 });
325 if (active?.owner === owner && operation === "login") return snapshot.value.state;
326 if (operation !== "idle")
327 return yield* new ProviderSetupError({
328 instanceId: options.instanceId,
329 operation: "start",
330 detail: "Cursor setup is already in progress.",
331 });
332 const id = yield* crypto.randomUUIDv4().pipe(
333 Effect.mapError(
334 (cause) =>
335 new ProviderSetupError({
336 instanceId: options.instanceId,
337 operation: "start",
338 detail: "Could not start Cursor sign-in. Try again.",
339 cause,
340 }),
341 ),
342 );
343 const expiresAt = DateTime.formatIso(
344 DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + AUTH_TIMEOUT_MS),
345 );
346 const flow: AuthFlow = { id, owner };
347 active = flow;
348 operation = "login";
349 const state: ProviderAuthState = {
350 ...emptyState,
351 phase: "starting",
352 flowId: id,
353 expiresAt,
354 message: "Starting Cursor sign-in.",
355 };
356 yield* SubscriptionRef.set(snapshot, { owner, state });
357 flow.fiber = yield* runLogin(flow, stopSessions).pipe(
358 Effect.interruptible,
359 Effect.forkIn(scope),
360 );
361 return state;
362 }),
363 ),
364 ),
365 complete: () =>
366 Effect.fail(
367 new ProviderSetupError({
368 instanceId: options.instanceId,
369 operation: "complete",
370 detail: "Finish signing in on the Cursor website. No redirect URL is needed.",
371 }),
372 ),
373 cancel: (owner, id) =>
374 Effect.uninterruptible(
375 Effect.gen(function* () {
376 const flow = yield* lock.withPermits(1)(
377 Effect.gen(function* () {
378 const flow = yield* requireFlow(owner, id, "cancel");
379 active = undefined;
380 operation = "stopping";
381 yield* publish(flow, {
382 phase: "cancelled",
383 authorizationUrl: null,
384 expiresAt: null,
385 message: "Cursor sign-in was cancelled.",
386 });
387 return flow;
388 }),
389 );
390 if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
391 operation = "idle";
392 return snapshot.value.state;
393 }),
394 ),
395 logout: (stopSessions) =>
396 Effect.uninterruptible(
397 Effect.gen(function* () {
398 const flow = yield* lock.withPermits(1)(
399 Effect.gen(function* () {
400 if (configuredKey)
401 return yield* new ProviderSetupError({
402 instanceId: options.instanceId,
403 operation: "logout",
404 detail:
405 "Remove CURSOR_API_KEY from this provider's environment to disconnect it.",
406 });
407 if (operation !== "idle" && operation !== "login")
408 return yield* new ProviderSetupError({
409 instanceId: options.instanceId,
410 operation: "logout",
411 detail: "Cursor setup is already stopping.",
412 });
413 operation = "stopping";
414 const flow = active;
415 active = undefined;
416 return flow;
417 }),
418 );
419 const result = yield* Effect.gen(function* () {
420 if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);
421 yield* stopSessions.pipe(Effect.ensuring(stopSessionsWithCredentials));
422 yield* Effect.tryPromise({
423 try: () => options.store.clear(),
424 catch: (cause) =>
425 new ProviderSetupError({
426 instanceId: options.instanceId,
427 operation: "logout",
428 detail: "Could not clear the Cursor sign-in. Try again.",
429 cause,
430 }),
431 });
432 yield* options.onChanged(false);
433 }).pipe(Effect.exit);
434 operation = "idle";
435 const state: ProviderAuthState = {
436 ...emptyState,
437 phase: Exit.isSuccess(result) ? "idle" : "failed",
438 message: Exit.isSuccess(result)
439 ? "Signed out of Cursor."
440 : "Cursor sign-out failed. Try again.",
441 };
442 yield* SubscriptionRef.set(snapshot, { owner: null, state });
443 if (Exit.isFailure(result)) return yield* Effect.failCause(result.cause);
444 return state;
445 }),
446 ),
447 subscribe: (owner) =>
448 SubscriptionRef.changes(snapshot).pipe(
449 Stream.map((current) => {
450 const state = {
451 ...current.state,
452 credentialOwner: "t3" as const,
453 methods: [
454 {
455 id: "browser",
456 name: "Sign in with Cursor",
457 description: null,
458 type: "agent" as const,
459 },
460 ],
461 interaction:
462 current.state.phase === "waiting" &&
463 current.state.authorizationUrl &&
464 current.state.flowId
465 ? {
466 type: "browser" as const,
467 id: current.state.flowId,
468 url: current.state.authorizationUrl,
469 requiresConsent: false,
470 }
471 : null,
472 };
473 if (current.owner === null || current.owner === owner) return state;
474 return {
475 ...state,
476 interaction: null,
477 flowId: null,
478 authorizationUrl: null,
479 expiresAt: null,
480 message: active ? "Sign-in is in progress in another client." : current.state.message,
481 };
482 }),
483 ),
484 isLogoutPrompt: (text, hasAttachments) => !hasAttachments && text.trim() === "/logout",
485 };
486
487 yield* Effect.addFinalizer(() =>
488 Effect.gen(function* () {
489 operation = "closed";
490 const flow = active;
491 active = undefined;
492 if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);
493 yield* stopSessionsWithCredentials;
494 }),
495 );
496
497 return {
498 controller,
499 readApiKey,
500 requireApiKey,
501 withAccess,
502 usesApiKey: configuredKey !== undefined,
503 } satisfies CursorAuth;
504});