omp-multi-auth 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -99,7 +99,9 @@ Create `.omp/multi-auth.json` in a project to restrict which subscription provid
99
99
 
100
100
  API-key providers support full multi-account operation. Add an account with `/multi-auth add`, select the provider, then authenticate via `/multi-auth login` (or `/login <name>`) and paste your API key when prompted. Each account stores its own key independently in OMP auth storage.
101
101
 
102
- Cursor and GitLab Duo require custom handlers and are not exposed.
102
+ - `cursor`: Cursor dashboard API keys (`crsr_...`/`cursor_...`) exchanged for short-lived session JWTs and automatically refreshed.
103
+
104
+ GitLab Duo requires custom handlers and is not exposed.
103
105
 
104
106
  ## Built-in limits
105
107
 
@@ -3,9 +3,9 @@
3
3
  // ========================================================================
4
4
  import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "fs";
5
5
  import { dirname, join } from "path";
6
- import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext, AuthStorage } from "@oh-my-pi/pi-coding-agent";
6
+ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
7
7
  import { getAgentDir } from "@oh-my-pi/pi-coding-agent";
8
- import { getModels, getAuthStorage, subProviderName, type SubEntry, type MultiAuthConfig, type ProjectConfig, type EffectiveConfig, type AuthStorageEntry } from "./core.ts";
8
+ import { getModels, getAuthStorage, adaptAuthStorage, subProviderName, type SubEntry, type MultiAuthConfig, type ProjectConfig, type EffectiveConfig, type AuthStorageEntry, type AuthStorage } from "./core.ts";
9
9
  import type { Api, Model } from "@oh-my-pi/pi-ai";
10
10
  import { PROVIDER_TEMPLATES, SUPPORTED_PROVIDERS, getBaseProvider, subDisplayName } from "./providers.ts";
11
11
 
@@ -271,7 +271,8 @@ export function normalizeEntries(entries: SubEntry[]): SubEntry[] {
271
271
  }
272
272
 
273
273
  export function subAccountIdentifier(authStorage: AuthStorage, providerName: string): string | undefined {
274
- const auth = authStorage.get(providerName) as AuthStorageEntry | undefined;
274
+ const storage = adaptAuthStorage(authStorage);
275
+ const auth = storage.get(providerName) as AuthStorageEntry | undefined;
275
276
  for (const value of [auth?.email, auth?.accountId]) {
276
277
  if (typeof value !== "string") continue;
277
278
  const identifier = value.trim();
@@ -280,9 +281,10 @@ export function subAccountIdentifier(authStorage: AuthStorage, providerName: str
280
281
  return undefined;
281
282
  }
282
283
  export function formatSubscriptionStatus(entry: SubEntry, authStorage: AuthStorage): string {
284
+ const storage = adaptAuthStorage(authStorage);
283
285
  const providerName = subProviderName(entry);
284
- if (!authStorage.hasAuth(providerName)) return "not logged in";
285
- const identifier = subAccountIdentifier(authStorage, providerName);
286
+ if (!storage.hasAuth(providerName)) return "not logged in";
287
+ const identifier = subAccountIdentifier(storage, providerName);
286
288
  return identifier ? `logged in ${identifier}` : "logged in";
287
289
  }
288
290
 
@@ -299,10 +301,11 @@ export function formatSubscriptionMeta(
299
301
  config: MultiAuthConfig,
300
302
  authStorage: AuthStorage,
301
303
  ): string {
304
+ const storage = adaptAuthStorage(authStorage);
302
305
  const name = subProviderName(entry);
303
- const hasAuth = authStorage.hasAuth(name);
306
+ const hasAuth = storage.hasAuth(name);
304
307
  const status = hasAuth ? "[logged in]" : "[not logged in]";
305
- const identifier = hasAuth ? subAccountIdentifier(authStorage, name) : undefined;
308
+ const identifier = hasAuth ? subAccountIdentifier(storage, name) : undefined;
306
309
  const source = getSubscriptionSource(config, entry);
307
310
  return `${status}${identifier ? ` ${identifier}` : ""} (${source})`;
308
311
  }
@@ -1,5 +1,5 @@
1
1
  // Cross-module types and zero-dependency helpers.
2
- import type { ExtensionCommandContext, ExtensionContext, AuthStorage } from "@oh-my-pi/pi-coding-agent";
2
+ import type { ExtensionCommandContext, ExtensionContext, AuthStorage as HostAuthStorage } from "@oh-my-pi/pi-coding-agent";
3
3
  import { getBundledModels, type GeneratedProvider } from "@oh-my-pi/pi-catalog";
4
4
  import type { Api, Model } from "@oh-my-pi/pi-ai";
5
5
  import type { GoogleQuotaAccountSnapshot, CodexUsageSnapshot } from "./quota.ts";
@@ -21,8 +21,151 @@ export interface AuthStorageEntry {
21
21
  [key: string]: unknown;
22
22
  }
23
23
 
24
+ export interface MultiAuthStorage {
25
+ hasAuth(providerName: string): boolean;
26
+ get(providerName: string): AuthStorageEntry | undefined;
27
+ logout(providerName: string): Promise<void>;
28
+ remove?(providerName: string): Promise<void>;
29
+ getOAuthAccess?(
30
+ providerName: string,
31
+ sessionId?: string,
32
+ options?: { signal?: AbortSignal },
33
+ ): Promise<{ accessToken: string; projectId?: string; [key: string]: unknown } | undefined>;
34
+ [key: string]: unknown;
35
+ }
36
+
37
+ export type AuthStorage = (HostAuthStorage | MultiAuthStorage) & MultiAuthStorage;
38
+
39
+ export function adaptAuthStorage(raw: unknown): MultiAuthStorage {
40
+ if (!raw || typeof raw !== "object") return raw as MultiAuthStorage;
41
+ if ((raw as { __isAdapted?: boolean }).__isAdapted) return raw as MultiAuthStorage;
42
+
43
+ const target = raw as Record<string, any>;
44
+ const adapter: Record<string, any> = {
45
+ __isAdapted: true,
46
+ hasAuth(providerName: string): boolean {
47
+ if (typeof target.hasAuth === "function") {
48
+ return Boolean(target.hasAuth(providerName));
49
+ }
50
+ if (target.keys && typeof target.keys.source === "function") {
51
+ if (target.keys.source(providerName) !== undefined) {
52
+ return true;
53
+ }
54
+ if (typeof target.keys.keyless === "function" && target.keys.keyless(providerName)) {
55
+ return true;
56
+ }
57
+ }
58
+ if (target.credentials) {
59
+ if (typeof target.credentials.has === "function" && target.credentials.has(providerName)) {
60
+ return true;
61
+ }
62
+ if (typeof target.credentials.get === "function" && target.credentials.get(providerName) !== undefined) {
63
+ return true;
64
+ }
65
+ }
66
+ if (typeof target.has === "function" && target.has(providerName)) {
67
+ return true;
68
+ }
69
+ if (typeof target.get === "function" && target.get(providerName) !== undefined) {
70
+ return true;
71
+ }
72
+ return false;
73
+ },
74
+ get(providerName: string): AuthStorageEntry | undefined {
75
+ let cred: any = undefined;
76
+ if (typeof target.get === "function") {
77
+ cred = target.get(providerName);
78
+ } else if (target.credentials && typeof target.credentials.get === "function") {
79
+ cred = target.credentials.get(providerName);
80
+ }
81
+ if (cred) {
82
+ if (target.oauth && typeof target.oauth.identity === "function" && (!cred.email && !cred.accountId)) {
83
+ try {
84
+ const id = target.oauth.identity(providerName);
85
+ if (id) {
86
+ return {
87
+ ...cred,
88
+ email: cred.email ?? id.email,
89
+ accountId: cred.accountId ?? id.accountId,
90
+ };
91
+ }
92
+ } catch {
93
+ // ignore
94
+ }
95
+ }
96
+ return cred;
97
+ }
98
+ if (target.oauth && typeof target.oauth.identity === "function") {
99
+ try {
100
+ const id = target.oauth.identity(providerName);
101
+ if (id?.email || id?.accountId) {
102
+ return {
103
+ type: "oauth",
104
+ email: id.email,
105
+ accountId: id.accountId,
106
+ };
107
+ }
108
+ } catch {
109
+ // ignore
110
+ }
111
+ }
112
+ return undefined;
113
+ },
114
+ async logout(providerName: string): Promise<void> {
115
+ if (typeof target.logout === "function") {
116
+ await target.logout(providerName);
117
+ return;
118
+ }
119
+ if (target.credentials && typeof target.credentials.remove === "function") {
120
+ await target.credentials.remove(providerName);
121
+ return;
122
+ }
123
+ if (typeof target.remove === "function") {
124
+ await target.remove(providerName);
125
+ return;
126
+ }
127
+ },
128
+ async remove(providerName: string): Promise<void> {
129
+ if (typeof target.remove === "function") {
130
+ await target.remove(providerName);
131
+ return;
132
+ }
133
+ if (target.credentials && typeof target.credentials.remove === "function") {
134
+ await target.credentials.remove(providerName);
135
+ return;
136
+ }
137
+ if (typeof target.logout === "function") {
138
+ await target.logout(providerName);
139
+ return;
140
+ }
141
+ },
142
+ async getOAuthAccess(providerName: string, sessionId?: string, options?: any) {
143
+ if (typeof target.getOAuthAccess === "function") {
144
+ return target.getOAuthAccess(providerName, sessionId, options);
145
+ }
146
+ if (target.oauth && typeof target.oauth.access === "function") {
147
+ return target.oauth.access(providerName, sessionId, options);
148
+ }
149
+ return undefined;
150
+ },
151
+ };
152
+
153
+ return new Proxy(target, {
154
+ get(base, prop, receiver) {
155
+ if (typeof prop === "string" && prop in adapter) {
156
+ return adapter[prop];
157
+ }
158
+ const value = Reflect.get(base, prop, receiver);
159
+ if (typeof value === "function") {
160
+ return value.bind(base);
161
+ }
162
+ return value;
163
+ },
164
+ }) as MultiAuthStorage;
165
+ }
166
+
24
167
  export function getAuthStorage(ctx: ExtensionContext | ExtensionCommandContext): AuthStorage {
25
- return ctx.modelRegistry.authStorage;
168
+ return adaptAuthStorage(ctx.modelRegistry?.authStorage) as AuthStorage;
26
169
  }
27
170
 
28
171
  export interface QuotaAccount {
@@ -88,6 +88,56 @@ export function buildApiKeyOAuth(displayName: string, index: number, placeholder
88
88
  };
89
89
  }
90
90
 
91
+ const CURSOR_EXCHANGE_URL = "https://api2.cursor.sh/auth/exchange_user_api_key";
92
+
93
+ function cursorJwtExpiryMs(jwt: string): number {
94
+ const fallback = Date.now() + 55 * 60 * 1000;
95
+ const parts = jwt.split(".");
96
+ if (parts.length !== 3) return fallback;
97
+ try {
98
+ const payload = JSON.parse(atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"))) as { exp?: number };
99
+ return typeof payload.exp === "number" ? payload.exp * 1000 : fallback;
100
+ } catch {
101
+ return fallback;
102
+ }
103
+ }
104
+
105
+ async function exchangeCursorApiKey(apiKey: string, signal?: AbortSignal): Promise<OAuthCredentials> {
106
+ const resp = await fetch(CURSOR_EXCHANGE_URL, {
107
+ method: "POST",
108
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
109
+ body: "{}",
110
+ signal,
111
+ });
112
+ if (!resp.ok) {
113
+ const text = await resp.text().catch(() => "");
114
+ throw new Error(`Cursor API key exchange failed (${resp.status}): ${text || resp.statusText}`);
115
+ }
116
+ const data = (await resp.json()) as { accessToken?: string };
117
+ if (!data.accessToken) throw new Error("Cursor API key exchange returned no accessToken");
118
+ return { access: data.accessToken, refresh: apiKey, expires: cursorJwtExpiryMs(data.accessToken) };
119
+ }
120
+
121
+ export function buildCursorApiKeyOAuth(index: number): ProviderOAuth {
122
+ return {
123
+ name: `Cursor #${index}`,
124
+ async login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
125
+ const apiKey = (await callbacks.onPrompt({
126
+ message: "Paste your Cursor API key (crsr_...):",
127
+ placeholder: "crsr_...",
128
+ })).trim();
129
+ if (!apiKey) throw new Error(`No API key entered for Cursor #${index}`);
130
+ return exchangeCursorApiKey(apiKey);
131
+ },
132
+ async refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
133
+ return exchangeCursorApiKey(credentials.refresh || credentials.access);
134
+ },
135
+ getApiKey(credentials: OAuthCredentials): string {
136
+ return credentials.access;
137
+ },
138
+ };
139
+ }
140
+
91
141
 
92
142
 
93
143
  // GitHub Copilot base URL derivation, ported from the pi-ai OAuth flow
@@ -319,6 +369,13 @@ export const PROVIDER_TEMPLATES: Record<string, ProviderTemplate> = {
319
369
  },
320
370
  },
321
371
 
372
+ cursor: {
373
+ displayName: "Cursor (API key)",
374
+ buildOAuth(index: number) {
375
+ return buildCursorApiKeyOAuth(index);
376
+ },
377
+ },
378
+
322
379
  };
323
380
 
324
381
  for (const spec of API_KEY_PROVIDERS) {
@@ -1,11 +1,11 @@
1
1
  // ========================================================================
2
2
  // Built-in quota checking
3
3
  // ========================================================================
4
- import type { ExtensionCommandContext, ExtensionContext, AuthStorage } from "@oh-my-pi/pi-coding-agent";
4
+ import type { ExtensionCommandContext, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
5
5
  import { BorderedLoader } from "@oh-my-pi/pi-coding-agent";
6
6
  import type { Api, Model } from "@oh-my-pi/pi-ai";
7
7
  import { getBaseProvider, subDisplayName, PROVIDER_TEMPLATES } from "./providers.ts";
8
- import { getAuthStorage, getModels, subProviderName, type AuthStorageEntry, type MultiAuthConfig, type QuotaAccount, type QuotaCheckResult, type QuotaStatusKind, type ProviderQuotaChecker } from "./core.ts";
8
+ import { getAuthStorage, adaptAuthStorage, getModels, subProviderName, type AuthStorageEntry, type MultiAuthConfig, type QuotaAccount, type QuotaCheckResult, type QuotaStatusKind, type ProviderQuotaChecker, type AuthStorage } from "./core.ts";
9
9
  import { loadGlobalConfig, loadProjectConfig, parseEnvConfig, mergeConfigs, normalizeEntries } from "./config.ts";
10
10
  import { getWrappedSelectIndex, showWrappedSelect } from "./ui.ts";
11
11
  import type { SelectItem } from "@oh-my-pi/pi-tui";
@@ -738,7 +738,10 @@ export async function resolveGoogleQuotaAccess(
738
738
  return { accessToken: auth.access!, projectId };
739
739
  }
740
740
 
741
- const access = await authStorage.getOAuthAccess(account.providerName, undefined, { signal });
741
+ const storage = adaptAuthStorage(authStorage);
742
+ const access = await (typeof storage.getOAuthAccess === "function"
743
+ ? storage.getOAuthAccess(account.providerName, undefined, { signal })
744
+ : undefined);
742
745
  if (!access) {
743
746
  throw new Error("Unable to refresh Google OAuth credentials. Log in again.");
744
747
  }
@@ -982,6 +985,7 @@ export function normalizeQuotaAllowedProviderNames(cwd: string): string[] | unde
982
985
  }
983
986
 
984
987
  export function collectQuotaAccounts(ctx: ExtensionContext, authStorage: AuthStorage): QuotaAccount[] {
988
+ const storage = adaptAuthStorage(authStorage);
985
989
  const config = loadGlobalConfig();
986
990
  const envEntries = parseEnvConfig();
987
991
  const allSubs = normalizeEntries(mergeConfigs(config, envEntries));
@@ -997,12 +1001,12 @@ export function collectQuotaAccounts(ctx: ExtensionContext, authStorage: AuthSto
997
1001
  providerName,
998
1002
  baseProvider: getBaseProvider(providerName) || providerName,
999
1003
  displayName,
1000
- auth: authStorage.get(providerName) as AuthStorageEntry | undefined,
1004
+ auth: storage.get(providerName) as AuthStorageEntry | undefined,
1001
1005
  });
1002
1006
  };
1003
1007
 
1004
1008
  for (const checker of PROVIDER_QUOTA_CHECKERS) {
1005
- if (authStorage.hasAuth(checker.baseProvider)) {
1009
+ if (storage.hasAuth(checker.baseProvider)) {
1006
1010
  pushAccount(
1007
1011
  checker.baseProvider,
1008
1012
  PROVIDER_TEMPLATES[checker.baseProvider]?.displayName || checker.baseProvider,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omp-multi-auth",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "description": "Multi-account OAuth login for omp (Oh My Pi) -- add and manage multiple accounts per provider from one place.",
6
6
  "keywords": [