forked from NoeFabris/opencode-antigravity-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.ts
More file actions
303 lines (264 loc) · 8.96 KB
/
Copy pathstorage.ts
File metadata and controls
303 lines (264 loc) · 8.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import { promises as fs } from "node:fs";
import { dirname, join } from "node:path";
import { homedir } from "node:os";
import type { HeaderStyle } from "../constants";
import { createLogger } from "./logger";
const log = createLogger("storage");
export type ModelFamily = "claude" | "gemini";
export type { HeaderStyle };
export interface RateLimitState {
claude?: number;
gemini?: number;
}
export interface RateLimitStateV3 {
claude?: number;
"gemini-antigravity"?: number;
"gemini-cli"?: number;
[key: string]: number | undefined;
}
export interface AccountMetadataV1 {
email?: string;
refreshToken: string;
projectId?: string;
managedProjectId?: string;
addedAt: number;
lastUsed: number;
isRateLimited?: boolean;
rateLimitResetTime?: number;
lastSwitchReason?: "rate-limit" | "initial" | "rotation";
}
export interface AccountStorageV1 {
version: 1;
accounts: AccountMetadataV1[];
activeIndex: number;
}
export interface AccountMetadata {
email?: string;
refreshToken: string;
projectId?: string;
managedProjectId?: string;
addedAt: number;
lastUsed: number;
lastSwitchReason?: "rate-limit" | "initial" | "rotation";
rateLimitResetTimes?: RateLimitState;
}
export interface AccountStorage {
version: 2;
accounts: AccountMetadata[];
activeIndex: number;
}
export type CooldownReason = "auth-failure" | "network-error" | "project-error";
export interface AccountMetadataV3 {
email?: string;
refreshToken: string;
projectId?: string;
managedProjectId?: string;
addedAt: number;
lastUsed: number;
lastSwitchReason?: "rate-limit" | "initial" | "rotation";
rateLimitResetTimes?: RateLimitStateV3;
coolingDownUntil?: number;
cooldownReason?: CooldownReason;
}
export interface AccountStorageV3 {
version: 3;
accounts: AccountMetadataV3[];
activeIndex: number;
activeIndexByFamily?: {
claude?: number;
gemini?: number;
};
}
type AnyAccountStorage = AccountStorageV1 | AccountStorage | AccountStorageV3;
function getConfigDir(): string {
const platform = process.platform;
if (platform === "win32") {
return join(process.env.APPDATA || join(homedir(), "AppData", "Roaming"), "opencode");
}
const xdgConfig = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
return join(xdgConfig, "opencode");
}
export function getStoragePath(): string {
return join(getConfigDir(), "antigravity-accounts.json");
}
export function deduplicateAccountsByEmail<T extends { email?: string; lastUsed?: number; addedAt?: number }>(accounts: T[]): T[] {
const emailToNewestIndex = new Map<string, number>();
const indicesToKeep = new Set<number>();
// First pass: find the newest account for each email (by lastUsed, then addedAt)
for (let i = 0; i < accounts.length; i++) {
const acc = accounts[i];
if (!acc) continue;
if (!acc.email) {
// No email - keep this account (can't deduplicate without email)
indicesToKeep.add(i);
continue;
}
const existingIndex = emailToNewestIndex.get(acc.email);
if (existingIndex === undefined) {
emailToNewestIndex.set(acc.email, i);
continue;
}
// Compare to find which is newer
const existing = accounts[existingIndex];
if (!existing) {
emailToNewestIndex.set(acc.email, i);
continue;
}
// Prefer higher lastUsed, then higher addedAt
// Compare fields separately to avoid integer overflow with large timestamps
const currLastUsed = acc.lastUsed || 0;
const existLastUsed = existing.lastUsed || 0;
const currAddedAt = acc.addedAt || 0;
const existAddedAt = existing.addedAt || 0;
const isNewer = currLastUsed > existLastUsed ||
(currLastUsed === existLastUsed && currAddedAt > existAddedAt);
if (isNewer) {
emailToNewestIndex.set(acc.email, i);
}
}
// Add all the newest email-based indices to the keep set
for (const idx of emailToNewestIndex.values()) {
indicesToKeep.add(idx);
}
// Build the deduplicated list, preserving original order for kept items
const result: T[] = [];
for (let i = 0; i < accounts.length; i++) {
if (indicesToKeep.has(i)) {
const acc = accounts[i];
if (acc) {
result.push(acc);
}
}
}
return result;
}
function migrateV1ToV2(v1: AccountStorageV1): AccountStorage {
return {
version: 2,
accounts: v1.accounts.map((acc) => {
const rateLimitResetTimes: RateLimitState = {};
if (acc.isRateLimited && acc.rateLimitResetTime && acc.rateLimitResetTime > Date.now()) {
rateLimitResetTimes.claude = acc.rateLimitResetTime;
rateLimitResetTimes.gemini = acc.rateLimitResetTime;
}
return {
email: acc.email,
refreshToken: acc.refreshToken,
projectId: acc.projectId,
managedProjectId: acc.managedProjectId,
addedAt: acc.addedAt,
lastUsed: acc.lastUsed,
lastSwitchReason: acc.lastSwitchReason,
rateLimitResetTimes: Object.keys(rateLimitResetTimes).length > 0 ? rateLimitResetTimes : undefined,
};
}),
activeIndex: v1.activeIndex,
};
}
export function migrateV2ToV3(v2: AccountStorage): AccountStorageV3 {
return {
version: 3,
accounts: v2.accounts.map((acc) => {
const rateLimitResetTimes: RateLimitStateV3 = {};
if (acc.rateLimitResetTimes?.claude && acc.rateLimitResetTimes.claude > Date.now()) {
rateLimitResetTimes.claude = acc.rateLimitResetTimes.claude;
}
if (acc.rateLimitResetTimes?.gemini && acc.rateLimitResetTimes.gemini > Date.now()) {
rateLimitResetTimes["gemini-antigravity"] = acc.rateLimitResetTimes.gemini;
}
return {
email: acc.email,
refreshToken: acc.refreshToken,
projectId: acc.projectId,
managedProjectId: acc.managedProjectId,
addedAt: acc.addedAt,
lastUsed: acc.lastUsed,
lastSwitchReason: acc.lastSwitchReason,
rateLimitResetTimes: Object.keys(rateLimitResetTimes).length > 0 ? rateLimitResetTimes : undefined,
};
}),
activeIndex: v2.activeIndex,
};
}
export async function loadAccounts(): Promise<AccountStorageV3 | null> {
try {
const path = getStoragePath();
const content = await fs.readFile(path, "utf-8");
const data = JSON.parse(content) as AnyAccountStorage;
if (!Array.isArray(data.accounts)) {
log.warn("Invalid storage format, ignoring");
return null;
}
let storage: AccountStorageV3;
if (data.version === 1) {
log.info("Migrating account storage from v1 to v3");
const v2 = migrateV1ToV2(data);
storage = migrateV2ToV3(v2);
try {
await saveAccounts(storage);
log.info("Migration to v3 complete");
} catch (saveError) {
log.warn("Failed to persist migrated storage", { error: String(saveError) });
}
} else if (data.version === 2) {
log.info("Migrating account storage from v2 to v3");
storage = migrateV2ToV3(data);
try {
await saveAccounts(storage);
log.info("Migration to v3 complete");
} catch (saveError) {
log.warn("Failed to persist migrated storage", { error: String(saveError) });
}
} else if (data.version === 3) {
storage = data;
} else {
log.warn("Unknown storage version, ignoring", {
version: (data as { version?: unknown }).version,
});
return null;
}
// Validate accounts have required fields
const validAccounts = storage.accounts.filter((a): a is AccountMetadataV3 => {
return !!a && typeof a === "object" && typeof (a as AccountMetadataV3).refreshToken === "string";
});
// Deduplicate accounts by email (keeps newest entry for each email)
const deduplicatedAccounts = deduplicateAccountsByEmail(validAccounts);
// Clamp activeIndex to valid range after deduplication
let activeIndex = typeof storage.activeIndex === "number" && Number.isFinite(storage.activeIndex) ? storage.activeIndex : 0;
if (deduplicatedAccounts.length > 0) {
activeIndex = Math.min(activeIndex, deduplicatedAccounts.length - 1);
activeIndex = Math.max(activeIndex, 0);
} else {
activeIndex = 0;
}
return {
version: 3,
accounts: deduplicatedAccounts,
activeIndex,
};
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "ENOENT") {
return null;
}
log.error("Failed to load account storage", { error: String(error) });
return null;
}
}
export async function saveAccounts(storage: AccountStorageV3): Promise<void> {
const path = getStoragePath();
await fs.mkdir(dirname(path), { recursive: true });
const content = JSON.stringify(storage, null, 2);
await fs.writeFile(path, content, "utf-8");
}
export async function clearAccounts(): Promise<void> {
try {
const path = getStoragePath();
await fs.unlink(path);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== "ENOENT") {
log.error("Failed to clear account storage", { error: String(error) });
}
}
}