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