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