forked from NoeFabris/opencode-antigravity-auth
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstorage.ts
More file actions
845 lines (753 loc) · 23.2 KB
/
storage.ts
File metadata and controls
845 lines (753 loc) · 23.2 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
import { promises as fs } from "node:fs";
import {
existsSync,
readFileSync,
writeFileSync,
appendFileSync,
mkdirSync,
renameSync,
copyFileSync,
unlinkSync,
} from "node:fs";
import { dirname, join } from "node:path";
import { homedir } from "node:os";
import { randomBytes } from "node:crypto";
import lockfile from "proper-lockfile";
import type { HeaderStyle } from "../constants";
import { createLogger } from "./logger";
const log = createLogger("storage");
/**
* Files/directories that should be gitignored in the config directory.
* These contain sensitive data or machine-specific state.
*/
export const GITIGNORE_ENTRIES = [
".gitignore",
"antigravity-accounts.json",
"antigravity-accounts.json.*.tmp",
"antigravity-signature-cache.json",
"antigravity-logs/",
];
/**
* Ensures a .gitignore file exists in the config directory with entries
* for sensitive files. Creates the file if missing, or appends missing
* entries if it already exists.
*/
export async function ensureGitignore(configDir: string): Promise<void> {
const gitignorePath = join(configDir, ".gitignore");
try {
let content: string;
let existingLines: string[] = [];
try {
content = await fs.readFile(gitignorePath, "utf-8");
existingLines = content.split("\n").map((line) => line.trim());
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
return;
}
content = "";
}
const missingEntries = GITIGNORE_ENTRIES.filter(
(entry) => !existingLines.includes(entry),
);
if (missingEntries.length === 0) {
return;
}
if (content === "") {
await fs.writeFile(
gitignorePath,
missingEntries.join("\n") + "\n",
"utf-8",
);
log.info("Created .gitignore in config directory");
} else {
const suffix = content.endsWith("\n") ? "" : "\n";
await fs.appendFile(
gitignorePath,
suffix + missingEntries.join("\n") + "\n",
"utf-8",
);
log.info("Updated .gitignore with missing entries", {
added: missingEntries,
});
}
} catch {
// Non-critical feature
}
}
/**
* Synchronous version of ensureGitignore for use in sync code paths.
*/
export function ensureGitignoreSync(configDir: string): void {
const gitignorePath = join(configDir, ".gitignore");
try {
let content: string;
let existingLines: string[] = [];
if (existsSync(gitignorePath)) {
content = readFileSync(gitignorePath, "utf-8");
existingLines = content.split("\n").map((line) => line.trim());
} else {
content = "";
}
const missingEntries = GITIGNORE_ENTRIES.filter(
(entry) => !existingLines.includes(entry),
);
if (missingEntries.length === 0) {
return;
}
if (content === "") {
writeFileSync(gitignorePath, missingEntries.join("\n") + "\n", "utf-8");
log.info("Created .gitignore in config directory");
} else {
const suffix = content.endsWith("\n") ? "" : "\n";
appendFileSync(
gitignorePath,
suffix + missingEntries.join("\n") + "\n",
"utf-8",
);
log.info("Updated .gitignore with missing entries", {
added: missingEntries,
});
}
} catch {
// Non-critical feature
}
}
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" | "validation-required";
export interface AccountMetadataV3 {
email?: string;
refreshToken: string;
projectId?: string;
managedProjectId?: string;
addedAt: number;
lastUsed: number;
enabled?: boolean;
lastSwitchReason?: "rate-limit" | "initial" | "rotation";
rateLimitResetTimes?: RateLimitStateV3;
coolingDownUntil?: number;
cooldownReason?: CooldownReason;
/** Per-account device fingerprint for rate limit mitigation */
fingerprint?: import("./fingerprint").Fingerprint;
fingerprintHistory?: import("./fingerprint").FingerprintVersion[];
/** Set when Google asks the user to verify this account before requests can continue. */
verificationRequired?: boolean;
verificationRequiredAt?: number;
verificationRequiredReason?: string;
verificationUrl?: string;
/** Cached soft quota data */
cachedQuota?: Record<string, { remainingFraction?: number; resetTime?: string; modelCount: number }>;
cachedQuotaUpdatedAt?: number;
}
export interface AccountStorageV3 {
version: 3;
accounts: AccountMetadataV3[];
activeIndex: number;
activeIndexByFamily?: {
claude?: number;
gemini?: number;
};
}
export interface AccountStorageV4 {
version: 4;
accounts: AccountMetadataV3[];
activeIndex: number;
activeIndexByFamily?: {
claude?: number;
gemini?: number;
};
}
type AnyAccountStorage =
| AccountStorageV1
| AccountStorage
| AccountStorageV3
| AccountStorageV4;
/**
* Gets the legacy Windows config directory (%APPDATA%\opencode).
* Used for migration from older plugin versions.
*/
function getLegacyWindowsConfigDir(): string {
return join(
process.env.APPDATA || join(homedir(), "AppData", "Roaming"),
"opencode",
);
}
/**
* Gets the config directory path, with the following precedence:
* 1. OPENCODE_CONFIG_DIR env var (if set)
* 2. ~/.config/opencode (all platforms, including Windows)
*
* On Windows, also checks for legacy %APPDATA%\opencode path for migration.
*/
function getConfigDir(): string {
// 1. Check for explicit override via env var
if (process.env.OPENCODE_CONFIG_DIR) {
return process.env.OPENCODE_CONFIG_DIR;
}
// 2. Use ~/.config/opencode on all platforms (including Windows)
const xdgConfig = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
return join(xdgConfig, "opencode");
}
/**
* Migrates config from legacy Windows location to the new path.
* Moves the file if legacy exists and new doesn't.
* Returns true if migration was performed.
*/
function migrateLegacyWindowsConfig(): boolean {
if (process.platform !== "win32") {
return false;
}
const newPath = join(getConfigDir(), "antigravity-accounts.json");
const legacyPath = join(
getLegacyWindowsConfigDir(),
"antigravity-accounts.json",
);
// Only migrate if legacy exists and new doesn't
if (!existsSync(legacyPath) || existsSync(newPath)) {
return false;
}
try {
// Ensure new config directory exists
const newConfigDir = getConfigDir();
mkdirSync(newConfigDir, { recursive: true });
// Try rename first (atomic, but fails across filesystems)
try {
renameSync(legacyPath, newPath);
log.info("Migrated Windows config via rename", { from: legacyPath, to: newPath });
} catch {
// Fallback: copy then delete (for cross-filesystem moves)
copyFileSync(legacyPath, newPath);
unlinkSync(legacyPath);
log.info("Migrated Windows config via copy+delete", { from: legacyPath, to: newPath });
}
return true;
} catch (error) {
log.warn("Failed to migrate legacy Windows config, will use legacy path", {
legacyPath,
newPath,
error: String(error),
});
return false;
}
}
/**
* Gets the storage path, migrating from legacy Windows location if needed.
* On Windows, attempts to move legacy config to new path for alignment.
*/
function getStoragePathWithMigration(): string {
const newPath = join(getConfigDir(), "antigravity-accounts.json");
// On Windows, attempt to migrate legacy config to new location
if (process.platform === "win32") {
migrateLegacyWindowsConfig();
// If migration failed and legacy still exists, fall back to it
if (!existsSync(newPath)) {
const legacyPath = join(
getLegacyWindowsConfigDir(),
"antigravity-accounts.json",
);
if (existsSync(legacyPath)) {
log.info("Using legacy Windows config path (migration failed)", {
legacyPath,
newPath,
});
return legacyPath;
}
}
}
return newPath;
}
export function getStoragePath(): string {
return getStoragePathWithMigration();
}
/**
* Gets the config directory path. Exported for use by other modules.
*/
export { getConfigDir };
const LOCK_OPTIONS = {
stale: 10000,
retries: {
retries: 5,
minTimeout: 100,
maxTimeout: 1000,
factor: 2,
},
};
function getLockPath(path: string): string {
return `${path}.lock`;
}
async function tryRecoverLegacyLockfile(path: string): Promise<boolean> {
const lockPath = getLockPath(path);
try {
const lockStat = await fs.lstat(lockPath);
if (!lockStat.isFile()) {
return false;
}
await fs.unlink(lockPath);
log.warn("Removed legacy lock file that blocked account storage lock", { lockPath });
return true;
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== "ENOENT") {
log.warn("Failed to remove legacy account storage lock file", {
lockPath,
error: String(error),
});
}
return false;
}
}
async function acquireFileLock(path: string): Promise<() => Promise<void>> {
try {
return await lockfile.lock(path, LOCK_OPTIONS);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== "ELOCKED" && code !== "EEXIST") {
throw error;
}
const recovered = await tryRecoverLegacyLockfile(path);
if (!recovered) {
throw error;
}
return await lockfile.lock(path, LOCK_OPTIONS);
}
}
/**
* Ensures the file has secure permissions (0600) on POSIX systems.
* This is a best-effort operation and ignores errors on Windows/unsupported FS.
*/
async function ensureSecurePermissions(path: string): Promise<void> {
try {
await fs.chmod(path, 0o600);
} catch {
// Ignore errors (e.g. Windows, file doesn't exist, FS doesn't support chmod)
}
}
async function ensureFileExists(path: string): Promise<void> {
try {
await fs.access(path);
} catch {
await fs.mkdir(dirname(path), { recursive: true });
await fs.writeFile(
path,
JSON.stringify({ version: 4, accounts: [], activeIndex: 0 }, null, 2),
{ encoding: "utf-8", mode: 0o600 },
);
}
}
async function withFileLock<T>(path: string, fn: () => Promise<T>): Promise<T> {
await ensureFileExists(path);
let release: (() => Promise<void>) | null = null;
try {
release = await acquireFileLock(path);
return await fn();
} finally {
if (release) {
try {
await release();
} catch (unlockError) {
log.warn("Failed to release lock", { error: String(unlockError) });
}
}
}
}
export function mergeAccountStorage(
existing: AccountStorageV4,
incoming: AccountStorageV4,
): AccountStorageV4 {
const accountMap = new Map<string, AccountMetadataV3>();
for (const acc of existing.accounts) {
if (acc.refreshToken) {
accountMap.set(acc.refreshToken, acc);
}
}
for (const acc of incoming.accounts) {
if (acc.refreshToken) {
const existingAcc = accountMap.get(acc.refreshToken);
if (existingAcc) {
const incomingRateLimitResetTimes = acc.rateLimitResetTimes;
const mergedRateLimitResetTimes = incomingRateLimitResetTimes === undefined
? existingAcc.rateLimitResetTimes
: Object.keys(incomingRateLimitResetTimes).length === 0
? undefined
: {
...existingAcc.rateLimitResetTimes,
...incomingRateLimitResetTimes,
};
accountMap.set(acc.refreshToken, {
...existingAcc,
...acc,
// Existing disk values take priority so manual overrides survive auth refresh merges.
projectId: existingAcc.projectId ?? acc.projectId,
managedProjectId: existingAcc.managedProjectId ?? acc.managedProjectId,
// An explicit empty object means limits were cleared and should overwrite older disk state.
rateLimitResetTimes: mergedRateLimitResetTimes,
lastUsed: Math.max(existingAcc.lastUsed || 0, acc.lastUsed || 0),
});
} else {
accountMap.set(acc.refreshToken, acc);
}
}
}
return {
version: 4,
accounts: Array.from(accountMap.values()),
activeIndex: incoming.activeIndex,
activeIndexByFamily: incoming.activeIndexByFamily,
};
}
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 function migrateV3ToV4(v3: AccountStorageV3): AccountStorageV4 {
return {
version: 4,
accounts: v3.accounts.map((acc) => ({
...acc,
fingerprint: undefined,
fingerprintHistory: undefined,
})),
activeIndex: v3.activeIndex,
activeIndexByFamily: v3.activeIndexByFamily,
};
}
export async function loadAccounts(): Promise<AccountStorageV4 | null> {
try {
const path = getStoragePath();
// Ensure permissions are correct on load (fixes existing files)
await ensureSecurePermissions(path);
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: AccountStorageV4;
if (data.version === 1) {
log.info("Migrating account storage from v1 to v4");
const v2 = migrateV1ToV2(data);
const v3 = migrateV2ToV3(v2);
storage = migrateV3ToV4(v3);
try {
await saveAccounts(storage);
log.info("Migration to v4 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 v4");
const v3 = migrateV2ToV3(data);
storage = migrateV3ToV4(v3);
try {
await saveAccounts(storage);
log.info("Migration to v4 complete");
} catch (saveError) {
log.warn("Failed to persist migrated storage", {
error: String(saveError),
});
}
} else if (data.version === 3) {
log.info("Migrating account storage from v3 to v4");
storage = migrateV3ToV4(data);
try {
await saveAccounts(storage);
log.info("Migration to v4 complete");
} catch (saveError) {
log.warn("Failed to persist migrated storage", {
error: String(saveError),
});
}
} else if (data.version === 4) {
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: 4,
accounts: deduplicatedAccounts,
activeIndex,
activeIndexByFamily: storage.activeIndexByFamily,
};
} 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: AccountStorageV4): Promise<void> {
const path = getStoragePath();
const configDir = dirname(path);
await fs.mkdir(configDir, { recursive: true });
await ensureGitignore(configDir);
await withFileLock(path, async () => {
const existing = await loadAccountsUnsafe();
const merged = existing ? mergeAccountStorage(existing, storage) : storage;
const tempPath = `${path}.${randomBytes(6).toString("hex")}.tmp`;
const content = JSON.stringify(merged, null, 2);
try {
await fs.writeFile(tempPath, content, { encoding: "utf-8", mode: 0o600 });
await fs.rename(tempPath, path);
} catch (error) {
// Clean up temp file on failure to prevent accumulation
try {
await fs.unlink(tempPath);
} catch {
// Ignore cleanup errors (file may not exist)
}
throw error;
}
});
}
/**
* Save accounts storage by replacing the entire file (no merge).
* Use this for destructive operations like delete where we need to
* remove accounts that would otherwise be merged back from existing storage.
*/
export async function saveAccountsReplace(storage: AccountStorageV4): Promise<void> {
const path = getStoragePath();
const configDir = dirname(path);
await fs.mkdir(configDir, { recursive: true });
await ensureGitignore(configDir);
await withFileLock(path, async () => {
const tempPath = `${path}.${randomBytes(6).toString("hex")}.tmp`;
const content = JSON.stringify(storage, null, 2);
try {
await fs.writeFile(tempPath, content, { encoding: "utf-8", mode: 0o600 });
await fs.rename(tempPath, path);
} catch (error) {
try {
await fs.unlink(tempPath);
} catch {
// Ignore cleanup errors
}
throw error;
}
});
}
async function loadAccountsUnsafe(): Promise<AccountStorageV4 | null> {
try {
const path = getStoragePath();
// Ensure permissions are correct on load (fixes existing files)
await ensureSecurePermissions(path);
const content = await fs.readFile(path, "utf-8");
const parsed = JSON.parse(content);
if (parsed.version === 1) {
return migrateV3ToV4(migrateV2ToV3(migrateV1ToV2(parsed)));
}
if (parsed.version === 2) {
return migrateV3ToV4(migrateV2ToV3(parsed));
}
if (parsed.version === 3) {
return migrateV3ToV4(parsed);
}
return {
...parsed,
accounts: deduplicateAccountsByEmail(parsed.accounts),
};
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "ENOENT") {
return null;
}
return null;
}
}
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) });
}
}
}