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

auth.ts

493 lines17.4 KB

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>;
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>;
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>;
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 = (flow: AuthFlow, stopSessions: Effect.Effect<void, ProviderSetupError>) =>
158 Effect.gen(function* () {
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 }).pipe(
247 Effect.scoped,
248 Effect.timeoutOrElse({
249 duration: AUTH_TIMEOUT_MS,
250 orElse: () =>
251 Effect.fail(
252 new ProviderSetupError({
253 instanceId: options.instanceId,
254 operation: "start",
255 detail: "Cursor sign-in expired. Start sign-in again.",
256 }),
257 ),
258 }),
259 Effect.exit,
260 Effect.flatMap((result) =>
261 lock.withPermits(1)(
262 Effect.gen(function* () {
263 if (active !== flow) return;
264 active = undefined;
265 operation = "idle";
266 yield* publish(flow, {
267 phase: Exit.isSuccess(result) ? "succeeded" : "failed",
268 authorizationUrl: null,
269 expiresAt: null,
270 message: Exit.isSuccess(result)
271 ? "Signed in with Cursor."
272 : "Cursor sign-in failed or expired. Start sign-in again.",
273 });
274 }),
275 ),
276 ),
277 );
278​
279 const requireFlow = (owner: string, id: string, name: string) =>
280 Effect.gen(function* () {
281 if (!active || active.owner !== owner || active.id !== id) {
282 return yield* new ProviderSetupError({
283 instanceId: options.instanceId,
284 operation: name,
285 detail: "This sign-in is no longer active in this client.",
286 });
287 }
288 return active;
289 });
290​
291 const controller: ProviderAuthController = {
292 credentialBinding: options.credentialBinding ?? {
293 owner: "t3",
294 key: `cursor:${options.instanceId}`,
295 },
296 isChangingCredentials: Effect.sync(() => operation !== "idle"),
297 start: (owner, stopSessions = Effect.void) =>
298 lock.withPermits(1)(
299 Effect.uninterruptible(
300 Effect.gen(function* () {
301 if (!options.enabled)
302 return yield* new ProviderSetupError({
303 instanceId: options.instanceId,
304 operation: "start",
305 detail: "Enable Cursor before signing in.",
306 });
307 if (configuredKey)
308 return yield* new ProviderSetupError({
309 instanceId: options.instanceId,
310 operation: "start",
311 detail:
312 "Remove CURSOR_API_KEY from this provider's environment before using browser sign-in.",
313 });
314 if (active?.owner === owner && operation === "login") return snapshot.value.state;
315 if (operation !== "idle")
316 return yield* new ProviderSetupError({
317 instanceId: options.instanceId,
318 operation: "start",
319 detail: "Cursor setup is already in progress.",
320 });
321 const id = yield* crypto.randomUUIDv4().pipe(
322 Effect.mapError(
323 (cause) =>
324 new ProviderSetupError({
325 instanceId: options.instanceId,
326 operation: "start",
327 detail: "Could not start Cursor sign-in. Try again.",
328 cause,
329 }),
330 ),
331 );
332 const expiresAt = DateTime.formatIso(
333 DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + AUTH_TIMEOUT_MS),
334 );
335 const flow: AuthFlow = { id, owner };
336 active = flow;
337 operation = "login";
338 const state: ProviderAuthState = {
339 ...emptyState,
340 phase: "starting",
341 flowId: id,
342 expiresAt,
343 message: "Starting Cursor sign-in.",
344 };
345 yield* SubscriptionRef.set(snapshot, { owner, state });
346 flow.fiber = yield* runLogin(flow, stopSessions).pipe(
347 Effect.interruptible,
348 Effect.forkIn(scope),
349 );
350 return state;
351 }),
352 ),
353 ),
354 complete: () =>
355 Effect.fail(
356 new ProviderSetupError({
357 instanceId: options.instanceId,
358 operation: "complete",
359 detail: "Finish signing in on the Cursor website. No redirect URL is needed.",
360 }),
361 ),
362 cancel: (owner, id) =>
363 Effect.uninterruptible(
364 Effect.gen(function* () {
365 const flow = yield* lock.withPermits(1)(
366 Effect.gen(function* () {
367 const flow = yield* requireFlow(owner, id, "cancel");
368 active = undefined;
369 operation = "stopping";
370 yield* publish(flow, {
371 phase: "cancelled",
372 authorizationUrl: null,
373 expiresAt: null,
374 message: "Cursor sign-in was cancelled.",
375 });
376 return flow;
377 }),
378 );
379 if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
380 operation = "idle";
381 return snapshot.value.state;
382 }),
383 ),
384 logout: (stopSessions) =>
385 Effect.uninterruptible(
386 Effect.gen(function* () {
387 const flow = yield* lock.withPermits(1)(
388 Effect.gen(function* () {
389 if (configuredKey)
390 return yield* new ProviderSetupError({
391 instanceId: options.instanceId,
392 operation: "logout",
393 detail:
394 "Remove CURSOR_API_KEY from this provider's environment to disconnect it.",
395 });
396 if (operation !== "idle" && operation !== "login")
397 return yield* new ProviderSetupError({
398 instanceId: options.instanceId,
399 operation: "logout",
400 detail: "Cursor setup is already stopping.",
401 });
402 operation = "stopping";
403 const flow = active;
404 active = undefined;
405 return flow;
406 }),
407 );
408 const result = yield* Effect.gen(function* () {
409 if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);
410 yield* stopSessions.pipe(Effect.ensuring(stopSessionsWithCredentials));
411 yield* Effect.tryPromise({
412 try: () => options.store.clear(),
413 catch: (cause) =>
414 new ProviderSetupError({
415 instanceId: options.instanceId,
416 operation: "logout",
417 detail: "Could not clear the Cursor sign-in. Try again.",
418 cause,
419 }),
420 });
421 yield* options.onChanged(false);
422 }).pipe(Effect.exit);
423 operation = "idle";
424 const state: ProviderAuthState = {
425 ...emptyState,
426 phase: Exit.isSuccess(result) ? "idle" : "failed",
427 message: Exit.isSuccess(result)
428 ? "Signed out of Cursor."
429 : "Cursor sign-out failed. Try again.",
430 };
431 yield* SubscriptionRef.set(snapshot, { owner: null, state });
432 if (Exit.isFailure(result)) return yield* Effect.failCause(result.cause);
433 return state;
434 }),
435 ),
436 subscribe: (owner) =>
437 SubscriptionRef.changes(snapshot).pipe(
438 Stream.map((current) => {
439 const state = {
440 ...current.state,
441 credentialOwner: "t3" as const,
442 methods: [
443 {
444 id: "browser",
445 name: "Sign in with Cursor",
446 description: null,
447 type: "agent" as const,
448 },
449 ],
450 interaction:
451 current.state.phase === "waiting" &&
452 current.state.authorizationUrl &&
453 current.state.flowId
454 ? {
455 type: "browser" as const,
456 id: current.state.flowId,
457 url: current.state.authorizationUrl,
458 requiresConsent: false,
459 }
460 : null,
461 };
462 if (current.owner === null || current.owner === owner) return state;
463 return {
464 ...state,
465 interaction: null,
466 flowId: null,
467 authorizationUrl: null,
468 expiresAt: null,
469 message: active ? "Sign-in is in progress in another client." : current.state.message,
470 };
471 }),
472 ),
473 isLogoutPrompt: (text, hasAttachments) => !hasAttachments && text.trim() === "/logout",
474 };
475​
476 yield* Effect.addFinalizer(() =>
477 Effect.gen(function* () {
478 operation = "closed";
479 const flow = active;
480 active = undefined;
481 if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);
482 yield* stopSessionsWithCredentials;
483 }),
484 );
485​
486 return {
487 controller,
488 readApiKey,
489 requireApiKey,
490 withAccess,
491 usesApiKey: configuredKey !== undefined,
492 } satisfies CursorAuth;
493});