summaryrefslogtreecommitdiff
path: root/packages/core/src/utils/user_account.ts
blob: 6701dfe3d91204160566d72877c443fadfb45f48 (plain)
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
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import path from 'node:path';
import { promises as fsp, existsSync, readFileSync } from 'node:fs';
import * as os from 'os';
import { GEMINI_DIR, GOOGLE_ACCOUNTS_FILENAME } from './paths.js';

interface UserAccounts {
  active: string | null;
  old: string[];
}

function getGoogleAccountsCachePath(): string {
  return path.join(os.homedir(), GEMINI_DIR, GOOGLE_ACCOUNTS_FILENAME);
}

async function readAccounts(filePath: string): Promise<UserAccounts> {
  try {
    const content = await fsp.readFile(filePath, 'utf-8');
    if (!content.trim()) {
      return { active: null, old: [] };
    }
    return JSON.parse(content) as UserAccounts;
  } catch (error) {
    if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
      // File doesn't exist, which is fine.
      return { active: null, old: [] };
    }
    // File is corrupted or not valid JSON, start with a fresh object.
    console.debug('Could not parse accounts file, starting fresh.', error);
    return { active: null, old: [] };
  }
}

export async function cacheGoogleAccount(email: string): Promise<void> {
  const filePath = getGoogleAccountsCachePath();
  await fsp.mkdir(path.dirname(filePath), { recursive: true });

  const accounts = await readAccounts(filePath);

  if (accounts.active && accounts.active !== email) {
    if (!accounts.old.includes(accounts.active)) {
      accounts.old.push(accounts.active);
    }
  }

  // If the new email was in the old list, remove it
  accounts.old = accounts.old.filter((oldEmail) => oldEmail !== email);

  accounts.active = email;
  await fsp.writeFile(filePath, JSON.stringify(accounts, null, 2), 'utf-8');
}

export function getCachedGoogleAccount(): string | null {
  try {
    const filePath = getGoogleAccountsCachePath();
    if (existsSync(filePath)) {
      const content = readFileSync(filePath, 'utf-8').trim();
      if (!content) {
        return null;
      }
      const accounts: UserAccounts = JSON.parse(content);
      return accounts.active;
    }
    return null;
  } catch (error) {
    console.debug('Error reading cached Google Account:', error);
    return null;
  }
}

export function getLifetimeGoogleAccounts(): number {
  try {
    const filePath = getGoogleAccountsCachePath();
    if (!existsSync(filePath)) {
      return 0;
    }

    const content = readFileSync(filePath, 'utf-8').trim();
    if (!content) {
      return 0;
    }
    const accounts: UserAccounts = JSON.parse(content);
    let count = accounts.old.length;
    if (accounts.active) {
      count++;
    }
    return count;
  } catch (error) {
    console.debug('Error reading lifetime Google Accounts:', error);
    return 0;
  }
}

export async function clearCachedGoogleAccount(): Promise<void> {
  const filePath = getGoogleAccountsCachePath();
  if (!existsSync(filePath)) {
    return;
  }

  const accounts = await readAccounts(filePath);

  if (accounts.active) {
    if (!accounts.old.includes(accounts.active)) {
      accounts.old.push(accounts.active);
    }
    accounts.active = null;
  }

  await fsp.writeFile(filePath, JSON.stringify(accounts, null, 2), 'utf-8');
}