feat: add support for Grok Web and Perplexity Web providers

This commit is contained in:
decolua
2026-04-22 11:58:53 +07:00
parent eeb2dc9e30
commit abb04c5366
17 changed files with 1583 additions and 13 deletions

View File

@@ -516,6 +516,39 @@ async function testApiKeyConnection(connection, effectiveProxy = null) {
const res = await fetchWithConnectionProxy("https://llm.chutes.ai/v1/models", { headers: { Authorization: `Bearer ${connection.apiKey}` } }, effectiveProxy);
return { valid: res.ok, error: res.ok ? null : "Invalid API key" };
}
case "grok-web": {
const token = connection.apiKey.startsWith("sso=") ? connection.apiKey.slice(4) : connection.apiKey;
const randomHex = (n) => Array.from(crypto.getRandomValues(new Uint8Array(n)), (b) => b.toString(16).padStart(2, "0")).join("");
const statsigId = Buffer.from("e:TypeError: Cannot read properties of null (reading 'children')").toString("base64");
const res = await fetchWithConnectionProxy("https://grok.com/rest/app-chat/conversations/new", {
method: "POST",
headers: {
Accept: "*/*", "Content-Type": "application/json",
Cookie: `sso=${token}`, Origin: "https://grok.com", Referer: "https://grok.com/",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
"x-statsig-id": statsigId, "x-xai-request-id": crypto.randomUUID(),
traceparent: `00-${randomHex(16)}-${randomHex(8)}-00`,
},
body: JSON.stringify({ temporary: true, modelName: "grok-4", message: "ping", fileAttachments: [], imageAttachments: [], disableSearch: false, enableImageGeneration: false, sendFinalMetadata: true }),
}, effectiveProxy);
const valid = res.status !== 401 && res.status !== 403;
return { valid, error: valid ? null : "Invalid SSO cookie" };
}
case "perplexity-web": {
let sessionToken = connection.apiKey;
if (sessionToken.startsWith("__Secure-next-auth.session-token=")) sessionToken = sessionToken.slice("__Secure-next-auth.session-token=".length);
const res = await fetchWithConnectionProxy("https://www.perplexity.ai/api/auth/session", {
method: "GET",
headers: {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
Cookie: `__Secure-next-auth.session-token=${sessionToken}`,
},
}, effectiveProxy);
if (!res.ok) return { valid: false, error: "Invalid session cookie" };
const data = await res.json().catch(() => null);
const valid = !!(data && data.user);
return { valid, error: valid ? null : "Session expired — re-paste cookie" };
}
default:
return { valid: false, error: "Provider test not supported" };
}
@@ -549,7 +582,7 @@ export async function testSingleConnection(id) {
const start = Date.now();
let result;
if (connection.authType === "apikey") {
if (connection.authType === "apikey" || connection.authType === "cookie") {
result = await testApiKeyConnection(connection, effectiveProxy);
} else {
result = await testOAuthConnection(connection, effectiveProxy);

View File

@@ -7,7 +7,7 @@ import {
getProxyPoolById,
} from "@/models";
import { APIKEY_PROVIDERS } from "@/shared/constants/config";
import { FREE_TIER_PROVIDERS, isOpenAICompatibleProvider, isAnthropicCompatibleProvider } from "@/shared/constants/providers";
import { FREE_TIER_PROVIDERS, WEB_COOKIE_PROVIDERS, isOpenAICompatibleProvider, isAnthropicCompatibleProvider } from "@/shared/constants/providers";
export const dynamic = "force-dynamic";
@@ -99,8 +99,10 @@ export async function POST(request) {
const proxyPoolId = proxyPoolResult.proxyPoolId;
// Validation
const isWebCookieProvider = !!WEB_COOKIE_PROVIDERS[provider];
const isValidProvider = APIKEY_PROVIDERS[provider] ||
FREE_TIER_PROVIDERS[provider] ||
isWebCookieProvider ||
isOpenAICompatibleProvider(provider) ||
isAnthropicCompatibleProvider(provider);
@@ -108,7 +110,7 @@ export async function POST(request) {
return NextResponse.json({ error: "Invalid provider" }, { status: 400 });
}
if (!apiKey) {
return NextResponse.json({ error: "API Key is required" }, { status: 400 });
return NextResponse.json({ error: `${isWebCookieProvider ? "Cookie value" : "API Key"} is required` }, { status: 400 });
}
if (!name) {
return NextResponse.json({ error: "Name is required" }, { status: 400 });
@@ -164,7 +166,7 @@ export async function POST(request) {
const newConnection = await createProviderConnection({
provider,
authType: "apikey",
authType: isWebCookieProvider ? "cookie" : "apikey",
name,
apiKey,
priority: priority || 1,

View File

@@ -255,6 +255,98 @@ export async function POST(request) {
break;
}
case "grok-web": {
const token = apiKey.startsWith("sso=") ? apiKey.slice(4) : apiKey;
// Cloudflare-bypass: send POST with same browser fingerprint headers as GrokWebExecutor
const randomHex = (n) => {
const a = new Uint8Array(n);
crypto.getRandomValues(a);
return Array.from(a, (b) => b.toString(16).padStart(2, "0")).join("");
};
const statsigId = Buffer.from("e:TypeError: Cannot read properties of null (reading 'children')").toString("base64");
const traceId = randomHex(16);
const spanId = randomHex(8);
const res = await fetch("https://grok.com/rest/app-chat/conversations/new", {
method: "POST",
headers: {
Accept: "*/*",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "no-cache",
"Content-Type": "application/json",
Cookie: `sso=${token}`,
Origin: "https://grok.com",
Pragma: "no-cache",
Referer: "https://grok.com/",
"Sec-Ch-Ua": '"Google Chrome";v="136", "Chromium";v="136", "Not(A:Brand";v="24"',
"Sec-Ch-Ua-Mobile": "?0",
"Sec-Ch-Ua-Platform": '"macOS"',
"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/136.0.0.0 Safari/537.36",
"x-statsig-id": statsigId,
"x-xai-request-id": crypto.randomUUID(),
traceparent: `00-${traceId}-${spanId}-00`,
},
body: JSON.stringify({
temporary: true, modelName: "grok-4", modelMode: "MODEL_MODE_GROK_4", message: "ping",
fileAttachments: [], imageAttachments: [],
disableSearch: false, enableImageGeneration: false, returnImageBytes: false,
returnRawGrokInXaiRequest: false, enableImageStreaming: false, imageGenerationCount: 0,
forceConcise: false, toolOverrides: {}, enableSideBySide: true, sendFinalMetadata: true,
isReasoning: false, disableTextFollowUps: true, disableMemory: true,
forceSideBySide: false, isAsyncChat: false, disableSelfHarmShortCircuit: false,
}),
});
// Cookie valid = any non-401/403 response (200, 400, 429 all mean cookie accepted)
if (res.status === 401 || res.status === 403) {
isValid = false;
error = "Invalid SSO cookie — re-paste from grok.com DevTools → Cookies → sso";
} else {
isValid = true;
}
break;
}
case "perplexity-web": {
let sessionToken = apiKey;
if (sessionToken.startsWith("__Secure-next-auth.session-token=")) {
sessionToken = sessionToken.slice("__Secure-next-auth.session-token=".length);
}
const tz = typeof Intl !== "undefined" ? Intl.DateTimeFormat().resolvedOptions().timeZone : "UTC";
const res = await fetch("https://www.perplexity.ai/rest/sse/perplexity_ask", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "text/event-stream",
Origin: "https://www.perplexity.ai",
Referer: "https://www.perplexity.ai/",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
"X-App-ApiClient": "default",
"X-App-ApiVersion": "2.18",
Cookie: `__Secure-next-auth.session-token=${sessionToken}`,
},
body: JSON.stringify({
query_str: "ping",
params: {
query_str: "ping", search_focus: "internet", mode: "concise", model_preference: "pplx_pro",
sources: ["web"], attachments: [],
frontend_uuid: crypto.randomUUID(), frontend_context_uuid: crypto.randomUUID(),
version: "2.18", language: "en-US", timezone: tz,
search_recency_filter: null, is_incognito: true, use_schematized_api: true, last_backend_uuid: null,
},
}),
});
if (res.status === 401 || res.status === 403) {
isValid = false;
error = "Invalid session cookie — re-paste __Secure-next-auth.session-token from perplexity.ai";
} else {
isValid = true;
}
break;
}
default:
return NextResponse.json({ error: "Provider validation not supported" }, { status: 400 });
}