Open History to see the last commit
1import * as NodeModule from "node:module";
2
3const CACHE_MS = 5 * 60_000;
4
5const requireForKeyring = NodeModule.createRequire(import.meta.url);
6
7/** Rejected when nobody answers the macOS Keychain prompt in time. */
8export class CursorKeychainTimeoutError extends Error {
9 constructor() {
10 super("Timed out waiting for Keychain access.");
11 }
12}
13
14/**
15 * Share one Keychain request across usage history and limits in this server process.
16 *
17 * macOS shows the access prompt on the server's own screen, which a remote
18 * client cannot answer, so callers give up after `timeoutMs`. The read stays in
19 * flight: the next call reuses it instead of stacking a second prompt, and picks
20 * up the token once someone allows access.
21 */
22export function makeCachedCursorAccessTokenReader(
23 read: () => Promise<string | null>,
24 now: () => number = Date.now,
25 timeoutMs = 30_000,
26): () => Promise<string | null> {
27 let cached: { token: string; until: number } | null = null;
28 let pending: Promise<string | null> | null = null;
29 return () => {
30 if (cached && cached.until > now()) return Promise.resolve(cached.token);
31 pending ??= read()
32 .then((token) => {
33 cached = token ? { token, until: now() + CACHE_MS } : null;
34 return token;
35 })
36 .finally(() => {
37 pending = null;
38 });
39 const deadline = AbortSignal.timeout(timeoutMs);
40 return Promise.race([
41 pending,
42 new Promise<never>((_, reject) => {
43 deadline.addEventListener("abort", () => reject(new CursorKeychainTimeoutError()), {
44 once: true,
45 });
46 }),
47 ]);
48 };
49}
50
51/** Read the Cursor CLI's default macOS credential without invoking the shared security binary. */
52export const readMacCursorAccessToken = makeCachedCursorAccessTokenReader(async () => {
53 const { AsyncEntry } = requireForKeyring("@napi-rs/keyring") as typeof import("@napi-rs/keyring");
54 return (await new AsyncEntry("cursor-access-token", "cursor-user").getPassword()) ?? null;
55});