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
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
// Web-cookie provider key validators (part B): muse-spark-web, adapta-web, claude-web, gemini-web,
// copilot-web, t3-web, jules, inner-ai. Extracted from validation.ts (god-file decomposition) β€”
// top-level functions with no dispatcher-state captures; behavior is byte-identical to the inline defs.
import { applyCustomUserAgent } from "./headers";
import { toValidationErrorResult, validationRead, validationWrite } from "./transport";
import { normalizeSessionCookieHeader } from "@/lib/providers/webCookieAuth";
import { buildJulesApiUrl } from "@/lib/cloudAgent/julesApi.ts";
import {
  META_AI_ASBD_ID,
  META_AI_FRIENDLY_NAME,
  META_AI_REQUEST_ANALYTICS_TAGS,
  META_AI_USER_AGENT,
  buildMetaAiValidationBody,
} from "./metaAi";

export async function validateMuseSparkWebProvider({ apiKey, providerSpecificData = {} }: any) {
  try {
    const cookieHeader = normalizeSessionCookieHeader(apiKey, "ecto_1_sess");
    const response = await validationWrite("https://www.meta.ai/api/graphql", {
      method: "POST",
      headers: applyCustomUserAgent(
        {
          "Content-Type": "application/json",
          Accept: "text/event-stream",
          "Accept-Language": "en-US,en;q=0.9",
          Cookie: cookieHeader,
          Origin: "https://www.meta.ai",
          Referer: "https://www.meta.ai/",
          "Sec-Fetch-Dest": "empty",
          "Sec-Fetch-Mode": "cors",
          "Sec-Fetch-Site": "same-origin",
          "User-Agent": META_AI_USER_AGENT,
          "X-ASBD-ID": META_AI_ASBD_ID,
          "X-FB-Friendly-Name": META_AI_FRIENDLY_NAME,
          "X-FB-Request-Analytics-Tags": META_AI_REQUEST_ANALYTICS_TAGS,
        },
        providerSpecificData
      ),
      body: JSON.stringify(buildMetaAiValidationBody()),
    });

    const responseText = await response.text();
    if (response.status === 401 || response.status === 403) {
      return {
        valid: false,
        error: "Invalid Meta AI session cookie β€” re-paste abra_sess from meta.ai",
      };
    }

    if (/authentication required to send messages|login is required|sign in/i.test(responseText)) {
      return {
        valid: false,
        error: "Invalid Meta AI session cookie β€” re-paste abra_sess from meta.ai",
      };
    }

    if (
      response.status === 429 ||
      /limit exceeded|rate limit|too many requests/i.test(responseText)
    ) {
      return { valid: true, error: null };
    }

    if (response.ok) {
      return { valid: true, error: null };
    }

    if (response.status >= 500) {
      return { valid: false, error: `Meta AI unavailable (${response.status})` };
    }

    return { valid: false, error: `Validation failed: ${response.status}` };
  } catch (error: any) {
    return toValidationErrorResult(error);
  }
}

export async function validateAdaptaWebProvider({ apiKey, providerSpecificData = {} }: any) {
  try {
    const raw = typeof apiKey === "string" ? apiKey.trim() : "";
    if (!raw)
      return { valid: false, error: "Paste your __client cookie from .clerk.agent.adapta.one" };
    const eqIdx = raw.indexOf("=");
    const clientJwt = eqIdx > 0 && !raw.startsWith("eyJ") ? raw.slice(eqIdx + 1).trim() : raw;

    const response = await validationRead("https://clerk.agent.adapta.one/v1/client", {
      headers: applyCustomUserAgent(
        {
          Cookie: `__client=${clientJwt}`,
          "User-Agent":
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
          Origin: "https://agent.adapta.one",
        },
        providerSpecificData
      ),
    });

    if (response.status === 401 || response.status === 403) {
      return {
        valid: false,
        error: "Invalid or expired __client cookie β€” re-paste from .clerk.agent.adapta.one",
      };
    }

    if (!response.ok) {
      return { valid: false, error: `Adapta Clerk returned HTTP ${response.status}` };
    }

    const body = await response.json().catch(() => null);
    const sessions: Array<{ id: string; status: string }> = body?.response?.sessions ?? [];
    const hasActive = sessions.some((s) => s.status === "active");
    if (!hasActive) {
      return {
        valid: false,
        error: "No active Adapta session β€” your __client cookie may be expired",
      };
    }

    return { valid: true, error: null };
  } catch (error: any) {
    return toValidationErrorResult(error);
  }
}

export async function validateClaudeWebProvider({ apiKey, providerSpecificData = {} }: any) {
  try {
    const cookieHeader = normalizeSessionCookieHeader(String(apiKey || ""), "sessionKey");
    if (!cookieHeader) {
      return { valid: false, error: "Paste your sessionKey cookie from claude.ai" };
    }

    const { tlsFetchClaude, TlsClientUnavailableError } =
      await import("@omniroute/open-sse/services/claudeTlsClient.ts");

    let response: { status: number; text: string | null };
    try {
      response = await tlsFetchClaude("https://claude.ai/api/organizations", {
        method: "GET",
        headers: applyCustomUserAgent(
          {
            Accept: "application/json",
            "Accept-Language": "en-US,en;q=0.9",
            "Cache-Control": "no-cache",
            Cookie: cookieHeader,
            Origin: "https://claude.ai",
            Pragma: "no-cache",
            Referer: "https://claude.ai/new",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
            "User-Agent":
              "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            "anthropic-client-platform": "web_claude_ai",
          },
          providerSpecificData
        ),
        timeoutMs: 30_000,
      });
    } catch (err: any) {
      if (err instanceof TlsClientUnavailableError) {
        return {
          valid: false,
          error: `${err.message} (claude-web requires this β€” without it, Cloudflare blocks every request)`,
        };
      }
      throw err;
    }

    if (response.status === 200) {
      return { valid: true, error: null };
    }

    if (response.status === 401 || response.status === 403) {
      return {
        valid: false,
        error:
          "Invalid or expired session cookie β€” re-paste sessionKey from claude.ai DevTools β†’ Cookies",
      };
    }

    if (response.status === 429) {
      return { valid: true, error: null };
    }

    if (response.status >= 500) {
      return { valid: false, error: `Claude.ai unavailable (${response.status})` };
    }

    return { valid: false, error: `Claude.ai validation failed (${response.status})` };
  } catch (error: any) {
    return toValidationErrorResult(error);
  }
}

// ── Gemini Web cookie validator ──
export async function validateGeminiWebProvider({ apiKey, providerSpecificData = {} }: any) {
  try {
    const raw = String(apiKey || "").trim();
    if (!raw) {
      return { valid: false, error: "Paste your __Secure-1PSID cookie from gemini.google.com" };
    }

    // Accept full cookie blob or bare value
    let cookieHeader = raw;
    if (!raw.includes("=")) {
      cookieHeader = `__Secure-1PSID=${raw}`;
    }

    const response = await validationRead("https://gemini.google.com/app", {
      headers: applyCustomUserAgent(
        {
          Accept: "text/html,application/xhtml+xml",
          Cookie: cookieHeader,
          Origin: "https://gemini.google.com",
          Referer: "https://gemini.google.com/",
        },
        providerSpecificData
      ),
    });

    if (response.status === 401 || response.status === 403) {
      return {
        valid: false,
        error:
          "Invalid or expired __Secure-1PSID cookie β€” re-paste from gemini.google.com DevTools β†’ Cookies",
      };
    }

    // 200/302 = valid, anything < 500 that isn't auth failure is acceptable
    if (response.status < 500) {
      return { valid: true, error: null };
    }

    return { valid: false, error: `Gemini validation failed (${response.status})` };
  } catch (error: any) {
    return toValidationErrorResult(error);
  }
}

// ── Copilot Web token validator ──
export async function validateCopilotWebProvider({ apiKey, providerSpecificData = {} }: any) {
  try {
    const raw = String(apiKey || "").trim();
    if (!raw) {
      return {
        valid: false,
        error: "Paste your access_token from copilot.microsoft.com DevTools β†’ Cookies",
      };
    }

    // Extract token β€” may be bare JWT, cookie string with access_token=, or Bearer prefix
    const { extractAccessToken } = await import("@omniroute/open-sse/executors/copilot-web.ts");
    const token = extractAccessToken(raw);
    if (!token) {
      return { valid: false, error: "Could not extract access_token from input" };
    }

    // Probe Copilot's conversation API to verify token
    const response = await validationWrite(
      "https://copilot.microsoft.com/c/api/conversations?language=en",
      {
        method: "GET",
        headers: applyCustomUserAgent(
          {
            Accept: "application/json",
            Authorization: `Bearer ${token}`,
            Origin: "https://copilot.microsoft.com",
            Referer: "https://copilot.microsoft.com/",
          },
          providerSpecificData
        ),
      }
    );

    if (response.status === 401 || response.status === 403) {
      return {
        valid: false,
        error:
          "Invalid or expired access_token β€” re-paste from copilot.microsoft.com DevTools β†’ Cookies",
      };
    }

    if (response.status >= 500) {
      return { valid: false, error: `Copilot unavailable (${response.status})` };
    }

    // 200, 400, 404 etc. all indicate the token was accepted
    return { valid: true, error: null };
  } catch (error: any) {
    return toValidationErrorResult(error);
  }
}

// ── t3.chat Web cookie validator ──
export async function validateT3WebProvider({ apiKey, providerSpecificData = {} }: any) {
  try {
    const raw = String(apiKey || "").trim();
    if (!raw) {
      return {
        valid: false,
        error: "Paste your Cookie header and convex-session-id from t3.chat",
      };
    }

    // The cookie field may contain "cookies=<Cookie header>\nconvexSessionId=<id>"
    // or just the Cookie header value. Try to parse.
    let cookieHeader = raw;
    let convexSessionId = "";

    if (raw.includes("convexSessionId") || raw.includes("convex-session-id")) {
      // Structured format: "cookies=...; convexSessionId=..."
      const parts = raw.split(/[,;\n]/).map((s: string) => s.trim());
      const cookieParts: string[] = [];
      for (const part of parts) {
        if (part.startsWith("convexSessionId=") || part.startsWith("convex-session-id=")) {
          convexSessionId = part.split("=").slice(1).join("=");
        } else if (part.startsWith("cookies=")) {
          cookieParts.push(part.slice("cookies=".length));
        } else if (part.includes("=")) {
          cookieParts.push(part);
        }
      }
      if (cookieParts.length) cookieHeader = cookieParts.join("; ");
    }

    // Build final cookie with convex-session-id if found
    const finalCookie = convexSessionId
      ? `${cookieHeader}; convex-session-id=${convexSessionId}`
      : cookieHeader;

    const response = await validationRead("https://t3.chat", {
      headers: applyCustomUserAgent(
        {
          Accept: "text/html",
          Cookie: finalCookie,
        },
        providerSpecificData
      ),
    });

    // t3.chat returns 200/302/404 for valid sessions, 5xx for down
    if (response.status >= 500) {
      return { valid: false, error: `t3.chat unavailable (${response.status})` };
    }

    return { valid: true, error: null };
  } catch (error: any) {
    return toValidationErrorResult(error);
  }
}

/** Jules API β€” GET /v1alpha/sources with X-Goog-Api-Key (see developers.google.com/jules/api). */
export async function validateJulesProvider({ apiKey }: { apiKey: string }) {
  try {
    const response = await validationWrite(buildJulesApiUrl("/sources"), {
      method: "GET",
      headers: {
        "X-Goog-Api-Key": apiKey,
      },
    });

    if (response.status === 401 || response.status === 403) {
      return { valid: false, error: "Invalid API key" };
    }

    if (response.ok) {
      return { valid: true, error: null };
    }

    const errorText = await response.text().catch(() => "");
    return {
      valid: false,
      error: errorText.trim() || `Jules API returned ${response.status}`,
    };
  } catch (error: unknown) {
    return toValidationErrorResult(error);
  }
}

export async function validateInnerAiProvider({ apiKey, providerSpecificData = {} }: any) {
  try {
    const raw = typeof apiKey === "string" ? apiKey.trim() : "";
    if (!raw) {
      return {
        valid: false,
        error: "Paste your token cookie and email β€” format: eyJ... user@example.com",
      };
    }

    // Parse token and optional email (format: "TOKEN EMAIL")
    const eqIdx = raw.indexOf("=");
    const stripped = eqIdx > 0 && !raw.startsWith("eyJ") ? raw.slice(eqIdx + 1).trim() : raw;
    const lastSpace = stripped.lastIndexOf(" ");
    let token = stripped;
    let credEmail = "";
    if (lastSpace > 0) {
      const possibleEmail = stripped.slice(lastSpace + 1).trim();
      if (possibleEmail.includes("@")) {
        token = stripped.slice(0, lastSpace).trim();
        credEmail = possibleEmail;
      }
    }

    if (!credEmail) {
      return {
        valid: false,
        error:
          "Email is required β€” paste token followed by a space and your email: eyJ... user@example.com",
      };
    }

    // Validate JWT structure (3 parts separated by dots)
    const parts = token.split(".");
    if (parts.length < 3) {
      return {
        valid: false,
        error:
          "Invalid token format β€” paste only the token cookie value from .innerai.com (starts with eyJ…)",
      };
    }

    // Decode payload and check expiry
    const b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
    let payload: Record<string, unknown> = {};
    try {
      payload = JSON.parse(Buffer.from(b64, "base64").toString("utf8"));
    } catch {
      return { valid: false, error: "Could not parse Inner.ai token β€” re-paste from DevTools" };
    }

    if (typeof payload.exp === "number" && payload.exp * 1000 < Date.now()) {
      return {
        valid: false,
        error:
          "Inner.ai token has expired β€” re-login at app.innerai.com and re-paste the token cookie",
      };
    }

    // Verify the token carries at least one known Inner.ai identity field
    const hasIdentity =
      payload.device_id ??
      payload.deviceId ??
      payload["device-id"] ??
      payload.did ??
      payload.user_id ??
      payload.userId ??
      payload.sub;
    if (!hasIdentity) {
      return {
        valid: false,
        error:
          "Token does not look like an Inner.ai session token β€” re-paste from DevTools β†’ Cookies β†’ .innerai.com",
      };
    }

    return { valid: true, error: null };
  } catch (error: any) {
    return toValidationErrorResult(error);
  }
}