File size: 7,619 Bytes
cd8bd0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
  getProviderConnections,
  createProviderConnection,
  updateProviderConnection,
} from "@/lib/localDb";
import { GeminiAuthFileError } from "@/lib/oauth/utils/geminiAuthFile";

type JsonRecord = Record<string, unknown>;

function toRecord(value: unknown): JsonRecord {
  return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};
}

function toNonEmptyString(value: unknown): string | null {
  if (typeof value !== "string") return null;
  const trimmed = value.trim();
  return trimmed ? trimmed : null;
}

function decodeJwtPayload(jwt: string): JsonRecord | null {
  try {
    const parts = jwt.split(".");
    if (parts.length !== 3) return null;
    const payload = Buffer.from(parts[1], "base64url").toString("utf8");
    return toRecord(JSON.parse(payload));
  } catch {
    return null;
  }
}

function extractJwtEmail(idToken: string): string | null {
  const payload = decodeJwtPayload(idToken);
  if (!payload) return null;
  return toNonEmptyString(payload.email);
}

// ──── Public types ────────────────────────────────────────────────────────────

export interface ParsedGeminiAuth {
  accessToken: string;
  refreshToken: string;
  idToken: string;
  scope: string;
  tokenType: string;
  expiresAt: string | null;
  email: string | null;
}

export interface EnrichedGeminiAuth extends ParsedGeminiAuth {
  projectId: string | null;
}

export interface CreateConnectionOptions {
  name?: string;
  email?: string;
  overwriteExisting?: boolean;
}

// ──── Parse & validate ────────────────────────────────────────────────────────

export function parseAndValidateGeminiAuth(raw: unknown): ParsedGeminiAuth {
  const doc = toRecord(raw);

  const accessToken = toNonEmptyString(doc.access_token);
  const refreshToken = toNonEmptyString(doc.refresh_token);
  const idToken = toNonEmptyString(doc.id_token);

  if (!accessToken) {
    throw new GeminiAuthFileError(
      "access_token is missing or empty in the oauth_creds.json",
      400,
      "missing_access_token"
    );
  }

  if (!refreshToken) {
    throw new GeminiAuthFileError(
      "refresh_token is missing or empty in the oauth_creds.json",
      400,
      "missing_refresh_token"
    );
  }

  if (!idToken) {
    throw new GeminiAuthFileError(
      "id_token is missing or empty in the oauth_creds.json",
      400,
      "missing_id_token"
    );
  }

  const expiryDateMs = doc.expiry_date;
  let expiresAt: string | null = null;
  if (typeof expiryDateMs === "number" && Number.isFinite(expiryDateMs)) {
    expiresAt = new Date(expiryDateMs).toISOString();
  }

  const scope = toNonEmptyString(doc.scope) ?? "";
  const tokenType = toNonEmptyString(doc.token_type) ?? "Bearer";
  const email = extractJwtEmail(idToken);

  return {
    accessToken,
    refreshToken,
    idToken,
    scope,
    tokenType,
    expiresAt,
    email,
  };
}

// ──── Enrich with Cloud Code Assist project info ──────────────────────────────

export async function enrichWithLoadCodeAssist(
  parsed: ParsedGeminiAuth
): Promise<EnrichedGeminiAuth> {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 8000);

  try {
    const response = await fetch("https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${parsed.accessToken}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ metadata: { ideType: "GEMINI_CLI", platform: "linux" } }),
      signal: controller.signal,
    });

    if (!response.ok) {
      return { ...parsed, projectId: null };
    }

    const data = toRecord(await response.json());
    const projectId = toNonEmptyString(data.projectId) ?? toNonEmptyString(data.cloudaiProjectId);
    return { ...parsed, projectId };
  } catch {
    return { ...parsed, projectId: null };
  } finally {
    clearTimeout(timer);
  }
}

// ──── Find existing connection ────────────────────────────────────────────────

export async function findExistingGeminiConnection(email: string): Promise<JsonRecord | null> {
  const connections = await getProviderConnections({ provider: "gemini-cli" });
  const lowerEmail = email.toLowerCase();
  return (
    (connections.find((c) => {
      const conn = c as JsonRecord;
      if (toNonEmptyString(conn.email)?.toLowerCase() === lowerEmail) return true;
      const psd = toRecord(conn.providerSpecificData);
      return toNonEmptyString(psd.bootstrapEmail)?.toLowerCase() === lowerEmail;
    }) as JsonRecord | undefined) ?? null
  );
}

// ──── Create / update connection ──────────────────────────────────────────────

export async function createConnectionFromAuthFile(
  enriched: EnrichedGeminiAuth,
  options: CreateConnectionOptions
): Promise<{ connection: JsonRecord; created: boolean }> {
  const resolvedEmail = options.email || enriched.email;

  if (resolvedEmail) {
    const existing = await findExistingGeminiConnection(resolvedEmail);

    if (existing) {
      if (!options.overwriteExisting) {
        throw new GeminiAuthFileError(
          "A Gemini CLI connection for this account already exists. Pass overwriteExisting: true to replace it.",
          409,
          "duplicate_account"
        );
      }

      const updated = await updateProviderConnection(existing.id as string, {
        accessToken: enriched.accessToken,
        refreshToken: enriched.refreshToken,
        idToken: enriched.idToken,
        expiresAt: enriched.expiresAt,
        email: resolvedEmail || (existing.email as string | undefined),
        name:
          options.name ||
          (existing.name as string | undefined) ||
          resolvedEmail ||
          "Gemini (imported)",
        testStatus: "active",
        providerSpecificData: {
          ...toRecord(existing.providerSpecificData),
          scope: enriched.scope,
          tokenType: enriched.tokenType,
          projectId: enriched.projectId ?? toRecord(existing.providerSpecificData).projectId,
          importedAt: new Date().toISOString(),
        },
      });

      return { connection: updated || existing, created: false };
    }
  } else if (!options.overwriteExisting) {
    throw new GeminiAuthFileError(
      "Cannot verify identity from the oauth_creds.json β€” id_token does not contain an email claim. Pass overwriteExisting: true to import without email verification.",
      409,
      "identity_unverified"
    );
  }

  const name = options.name || resolvedEmail || "Gemini (imported)";

  const connection = await createProviderConnection({
    provider: "gemini-cli",
    authType: "oauth",
    name,
    email: resolvedEmail || undefined,
    accessToken: enriched.accessToken,
    refreshToken: enriched.refreshToken,
    idToken: enriched.idToken,
    expiresAt: enriched.expiresAt,
    isActive: true,
    testStatus: "active",
    providerSpecificData: {
      scope: enriched.scope,
      tokenType: enriched.tokenType,
      projectId: enriched.projectId,
      importedAt: new Date().toISOString(),
    },
  });

  return { connection, created: true };
}