-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathrefresh.ts
More file actions
759 lines (682 loc) · 29.2 KB
/
Copy pathrefresh.ts
File metadata and controls
759 lines (682 loc) · 29.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
/**
* Live refresh of account info (models/config, ASI access, rate limits, experiments).
*
* Architecture — three pluggable tiers, tried in order:
*
* 1. got-scraping — pure JS HTTP client (Apify's got fork). Reorders TLS
* extensions + HTTP/2 SETTINGS + header ordering to look Chrome-ish.
* ~200ms round trip. Always available (shipped as a regular dep).
*
* 2. impit (optional) — Rust-backed JA3/JA4 impersonation via rustls-patched +
* reqwest. Closer to real Chrome than got-scraping. Only attempted if the
* user has installed it into ~/.perplexity-mcp/native-deps/ (Settings
* → Speed Boost). ~300-500ms.
*
* 3. browser — headless Patchright. Guaranteed to work because Chromium
* speaks the same TLS as whatever solved Turnstile at login time. ~3-5s.
*
* Each tier returns the same TierResult shape so the orchestrator can just
* walk them in order. A CF challenge (HTML response instead of JSON) counts
* as "try the next tier". Anything else (network error, 5xx, unparseable)
* also cascades.
*/
import { readFileSync, writeFileSync, existsSync, statSync, mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
import {
PERPLEXITY_URL,
MODELS_CONFIG_ENDPOINT,
ASI_ACCESS_ENDPOINT,
RATE_LIMIT_ENDPOINT,
EXPERIMENTS_ENDPOINT,
USER_INFO_ENDPOINT,
findBrowser,
findChromeExecutable,
getOrCreateContext,
getSavedCookies,
resolveBrowserExecutable,
type AccountInfo,
type ModelsConfigResponse,
type ASIAccessResponse,
type RateLimitResponse,
type UserInfoResponse,
type PlaywrightCookie,
} from "./config.js";
import { getActiveName, getConfigDir, getProfilePaths } from "./profiles.js";
function getActiveProfileName(): string {
return process.env.PERPLEXITY_PROFILE || getActiveName() || "default";
}
function getModelsCacheFile(): string {
return getProfilePaths(getActiveProfileName()).modelsCache;
}
function getLegacyCookiesFile(): string {
return join(getProfilePaths(getActiveProfileName()).dir, "cookies.json");
}
function getImpitRuntimeDirPath(): string {
return join(getConfigDir(), "native-deps");
}
const STEALTH_ARGS = [
"--disable-blink-features=AutomationControlled",
// NOTE: `--disable-web-security` was removed (2026-04-27 public-hardening
// audit). All in-page `fetch()` calls used by the cookie-refresh tier hit
// the same Perplexity origin, so CORS is not a factor; keeping the flag
// would needlessly weaken the browser's same-origin policy. The off-origin
// ASI download path lives in client.ts and now uses APIRequestContext.
//
// NOTE: `--disable-features=IsolateOrigins,site-per-process` and
// `--disable-site-isolation-trials` were removed (2026-04-27 public-
// hardening audit). They disable Chromium's Site Isolation process model,
// which is a renderer-architecture feature invisible to JavaScript on the
// page (no documented fingerprint surface — Patchright's
// `chromiumSwitches.js` does not include them). The cookie-refresh path
// never enumerates frames or cross-origin iframes, so the only effect of
// keeping them was a silent reduction in the browser's Spectre/UXSS
// defense-in-depth.
"--no-first-run",
"--no-default-browser-check",
"--disable-infobars",
"--disable-extensions",
"--disable-popup-blocking",
];
const USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36";
const CHROME_CLIENT_HINTS: Record<string, string> = {
"sec-ch-ua": '"Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
"sec-ch-ua-platform-version": '"15.0.0"',
"sec-ch-ua-arch": '"x86"',
"sec-ch-ua-bitness": '"64"',
"sec-ch-ua-full-version": '"138.0.7204.184"',
"sec-ch-ua-full-version-list":
'"Not)A;Brand";v="8.0.0.0", "Chromium";v="138.0.7204.184", "Google Chrome";v="138.0.7204.184"',
"sec-ch-ua-model": '""',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-app-apiclient": "default",
"x-app-apiversion": "2.18",
"x-perplexity-request-try-number": "1",
"x-perplexity-request-reason": "use-preferred-search-models",
accept: "*/*",
"accept-language": "en-US,en;q=0.9",
referer: `${PERPLEXITY_URL}/`,
origin: PERPLEXITY_URL,
};
export type RefreshTier = "got-scraping" | "impit" | "browser";
export interface RefreshResult {
ok: boolean;
source: "live" | "no-cookies" | "cf-challenge" | "failed";
tier: RefreshTier | null;
modelCount: number;
accountTier: "Max" | "Pro" | "Enterprise" | "Free" | "Unknown";
error?: string;
cachePath: string;
elapsedMs: number;
tierAttempts?: Array<{ tier: RefreshTier; ok: boolean; elapsedMs: number; error?: string }>;
}
export interface RefreshOptions {
log?: (line: string) => void;
timeoutMs?: number;
/** Force a particular tier for testing. Omit for normal cascade. */
forceTier?: RefreshTier;
}
interface TierPayload {
models: ModelsConfigResponse;
asi: ASIAccessResponse | null;
rateLimits: RateLimitResponse | null;
experiments: Record<string, any> | null;
userInfo: UserInfoResponse | null;
/** Fresh cookies pulled off the successful tier (for cookies.json write-back). */
freshCookies?: PlaywrightCookie[];
}
interface TierResult {
ok: boolean;
payload?: TierPayload;
error?: string;
challenged?: boolean;
elapsedMs: number;
}
function noopLog(_: string) {}
function buildCookieHeader(cookies: PlaywrightCookie[]): string {
return cookies
.filter((c) => c.domain?.includes("perplexity.ai"))
.map((c) => `${c.name}=${c.value}`)
.join("; ");
}
function detectCfChallenge(body: string): boolean {
if (!body) return false;
const head = body.slice(0, 2000).toLowerCase();
return (
head.includes("just a moment") ||
head.includes("cf-mitigated") ||
head.includes("enable javascript and cookies to continue") ||
(head.includes("<html") && head.includes("cloudflare"))
);
}
/* ═══════════════════════════════════════════════════════════════ */
/* Tier 1 — got-scraping */
/* ═══════════════════════════════════════════════════════════════ */
async function tierGotScraping(cookies: PlaywrightCookie[], log: (l: string) => void, timeoutMs: number): Promise<TierResult> {
const started = Date.now();
let gotScraping: typeof import("got-scraping").gotScraping;
try {
({ gotScraping } = await import("got-scraping"));
} catch (err) {
return { ok: false, error: `got-scraping missing: ${(err as Error).message}`, elapsedMs: Date.now() - started };
}
const cookieHeader = buildCookieHeader(cookies);
const headers: Record<string, string> = {
cookie: cookieHeader,
"user-agent": USER_AGENT,
...CHROME_CLIENT_HINTS,
};
const fetchJson = async <T>(url: string, name: string): Promise<T | { __challenged: true } | null> => {
try {
const res = await gotScraping({
url,
headers,
timeout: { request: timeoutMs },
throwHttpErrors: false,
responseType: "text",
headerGeneratorOptions: {
browsers: [{ name: "chrome", minVersion: 130 }],
operatingSystems: ["windows"],
},
});
const body = typeof res.body === "string" ? res.body : String(res.body ?? "");
if (res.statusCode !== 200) {
log(`got-scraping: ${name} status=${res.statusCode}`);
if (detectCfChallenge(body)) return { __challenged: true };
return null;
}
const ct = res.headers["content-type"] ?? "";
if (!String(ct).includes("application/json")) {
log(`got-scraping: ${name} non-JSON content-type=${ct}`);
if (detectCfChallenge(body)) return { __challenged: true };
return null;
}
return JSON.parse(body) as T;
} catch (err) {
log(`got-scraping: ${name} threw ${(err as Error).message}`);
return null;
}
};
const [models, asi, rateLimits, experiments, userInfo] = await Promise.all([
fetchJson<ModelsConfigResponse>(MODELS_CONFIG_ENDPOINT, "models/config"),
fetchJson<ASIAccessResponse>(ASI_ACCESS_ENDPOINT, "asi-access"),
fetchJson<RateLimitResponse>(RATE_LIMIT_ENDPOINT, "rate-limit"),
fetchJson<Record<string, any>>(EXPERIMENTS_ENDPOINT, "experiments"),
fetchJson<UserInfoResponse>(USER_INFO_ENDPOINT, "user/info"),
]);
// Any CF challenge on the critical endpoint → treat as tier failure (cascade).
const challenged = !!(models && (models as any).__challenged);
if (challenged) {
return { ok: false, challenged: true, error: "CF challenge via got-scraping", elapsedMs: Date.now() - started };
}
if (!models) {
return { ok: false, error: "got-scraping: models/config fetch failed", elapsedMs: Date.now() - started };
}
return {
ok: true,
payload: {
models: models as ModelsConfigResponse,
asi: asi && !(asi as any).__challenged ? (asi as ASIAccessResponse) : null,
rateLimits: rateLimits && !(rateLimits as any).__challenged ? (rateLimits as RateLimitResponse) : null,
experiments: experiments && !(experiments as any).__challenged ? (experiments as Record<string, any>) : null,
userInfo: userInfo && !(userInfo as any).__challenged ? (userInfo as UserInfoResponse) : null,
},
elapsedMs: Date.now() - started,
};
}
/* ═══════════════════════════════════════════════════════════════ */
/* Tier 2 — impit (optional, user-installed) */
/* ═══════════════════════════════════════════════════════════════ */
/**
* Minimal shape of the `impit` module that we actually call.
* Full types aren't declared in our tsconfig because impit is NOT a build-time
* dependency — it's installed at runtime by the user via "Install Speed Boost".
*/
export interface ImpitModule {
Impit: new (opts: { browser: string; ignoreTlsErrors?: boolean; proxyUrl?: string }) => {
fetch(
url: string,
init?: {
method?: string;
body?: string | Uint8Array;
headers?: Record<string, string>;
signal?: AbortSignal;
redirect?: "follow" | "manual" | "error";
}
): Promise<{
status: number;
headers: Headers | Record<string, string>;
text(): Promise<string>;
json(): Promise<unknown>;
}>;
};
}
/**
* Dynamically import impit from the user's native-deps directory.
* Returns null if impit isn't installed there.
*
* Note on createRequire: when this code is bundled into the extension host
* (CJS via tsup), `import.meta.url` is undefined, which makes
* `createRequire(import.meta.url)` throw — the previous implementation
* silently caught that and reported "impit not installed" even when the
* package was on disk. Rooting `createRequire` at the impit module's own
* absolute path works in both CJS- and ESM-bundled output (Node accepts a
* file path string per the docs) and resolves impit's peer native binding
* from native-deps/node_modules correctly.
*/
export async function loadImpit(): Promise<ImpitModule | null> {
// Order matters. impit 0.13+ ships TWO entry files:
// index.wrapper.js — the user-facing API, exposes the `Impit` class that
// canonicalizes headers from {object} → [[k,v]] tuples
// before forwarding to the native binding. THIS is what
// package.json["main"] points at.
// index.js — the raw NAPI binding loader; calling .fetch() with
// a plain object on this throws "Given napi value is
// not an array on RequestInit.headers" because the
// binding-side check only accepts arrays.
// Older impit versions only had index.js (the wrapper didn't exist yet) —
// those continue to work because the binding accepted objects then.
// dist/index.js is the legacy 0.10.x layout for completeness.
const candidates = [
join(getImpitRuntimeDirPath(), "node_modules", "impit", "index.wrapper.js"),
join(getImpitRuntimeDirPath(), "node_modules", "impit", "index.js"),
join(getImpitRuntimeDirPath(), "node_modules", "impit", "dist", "index.js"),
];
const failures: string[] = [];
for (const p of candidates) {
if (!existsSync(p)) continue;
try {
const { createRequire } = await import("node:module");
const req = createRequire(p);
return req(p) as ImpitModule;
} catch (err) {
failures.push(`${p}: ${(err as Error).message ?? err}`);
}
}
// Surface the real reason on stderr so log scrapes show the cause when the
// package is on disk but a require throws (broken native binding, mismatched
// ABI). Silent return-null masked the createRequire bug above for months.
if (failures.length) {
try { console.error(`[impit] load failed: ${failures.join(" | ")}`); } catch { /* ignore */ }
}
return null;
}
export function isImpitAvailable(): boolean {
const marker = join(getImpitRuntimeDirPath(), "node_modules", "impit", "package.json");
return existsSync(marker);
}
/**
* Browser-free authenticated fetch via impit. Used as a fast path for REST
* endpoints that only need cookies + a Chrome-ish TLS fingerprint
* (e.g. /rest/thread/list_ask_threads). Callers should fall back to the
* browser path on any non-success outcome.
*
* Returns null when impit isn't installed/loadable or the request threw at
* the network level. Returns `{ challenged: true }` when the response body
* looks like a Cloudflare interstitial.
*/
export async function impitFetchJson(
url: string,
init: { method?: string; body?: unknown; headers?: Record<string, string> } = {},
cookies: PlaywrightCookie[],
timeoutMs = 15000,
): Promise<{ status: number; data: unknown; challenged?: boolean } | null> {
const impitMod = await loadImpit();
if (!impitMod) return null;
let client: InstanceType<ImpitModule["Impit"]>;
try {
client = new impitMod.Impit({ browser: "chrome", ignoreTlsErrors: false });
} catch {
return null;
}
const hasBody = init.body !== undefined && init.body !== null;
const headers: Record<string, string> = {
cookie: buildCookieHeader(cookies),
"user-agent": USER_AGENT,
...CHROME_CLIENT_HINTS,
accept: "application/json, text/plain, */*",
...(hasBody ? { "content-type": "application/json" } : {}),
...(init.headers ?? {}),
};
try {
const ctrl = new AbortController();
const to = setTimeout(() => ctrl.abort(), timeoutMs);
const res = await client.fetch(url, {
method: init.method ?? "GET",
headers,
body: hasBody ? JSON.stringify(init.body) : undefined,
signal: ctrl.signal,
});
clearTimeout(to);
const text = await res.text();
if (detectCfChallenge(text)) {
return { status: res.status, data: null, challenged: true };
}
let data: unknown = text;
if (text) {
try { data = JSON.parse(text); } catch { /* leave as text */ }
}
return { status: res.status, data };
} catch {
return null;
}
}
async function tierImpit(cookies: PlaywrightCookie[], log: (l: string) => void, timeoutMs: number): Promise<TierResult> {
const started = Date.now();
const impitMod = await loadImpit();
if (!impitMod) {
return { ok: false, error: "impit not installed (optional speed boost)", elapsedMs: Date.now() - started };
}
let client: InstanceType<ImpitModule["Impit"]>;
try {
client = new impitMod.Impit({ browser: "chrome", ignoreTlsErrors: false });
} catch (err) {
return { ok: false, error: `impit init failed: ${(err as Error).message}`, elapsedMs: Date.now() - started };
}
const cookieHeader = buildCookieHeader(cookies);
const headers: Record<string, string> = {
cookie: cookieHeader,
"user-agent": USER_AGENT,
...CHROME_CLIENT_HINTS,
};
const fetchJson = async <T>(url: string, name: string): Promise<T | { __challenged: true } | null> => {
try {
const ctrl = new AbortController();
const to = setTimeout(() => ctrl.abort(), timeoutMs);
const res = await client.fetch(url, { headers, signal: ctrl.signal });
clearTimeout(to);
const body = await res.text();
if (res.status !== 200) {
log(`impit: ${name} status=${res.status}`);
if (detectCfChallenge(body)) return { __challenged: true };
return null;
}
const rhdrs: any = res.headers;
const ct = typeof rhdrs?.get === "function" ? rhdrs.get("content-type") ?? "" : rhdrs?.["content-type"] ?? "";
if (!String(ct).includes("application/json")) {
log(`impit: ${name} non-JSON content-type=${ct}`);
if (detectCfChallenge(body)) return { __challenged: true };
return null;
}
return JSON.parse(body) as T;
} catch (err) {
log(`impit: ${name} threw ${(err as Error).message}`);
return null;
}
};
const [models, asi, rateLimits, experiments, userInfo] = await Promise.all([
fetchJson<ModelsConfigResponse>(MODELS_CONFIG_ENDPOINT, "models/config"),
fetchJson<ASIAccessResponse>(ASI_ACCESS_ENDPOINT, "asi-access"),
fetchJson<RateLimitResponse>(RATE_LIMIT_ENDPOINT, "rate-limit"),
fetchJson<Record<string, any>>(EXPERIMENTS_ENDPOINT, "experiments"),
fetchJson<UserInfoResponse>(USER_INFO_ENDPOINT, "user/info"),
]);
const challenged = !!(models && (models as any).__challenged);
if (challenged) {
return { ok: false, challenged: true, error: "CF challenge via impit", elapsedMs: Date.now() - started };
}
if (!models) {
return { ok: false, error: "impit: models/config fetch failed", elapsedMs: Date.now() - started };
}
return {
ok: true,
payload: {
models: models as ModelsConfigResponse,
asi: asi && !(asi as any).__challenged ? (asi as ASIAccessResponse) : null,
rateLimits: rateLimits && !(rateLimits as any).__challenged ? (rateLimits as RateLimitResponse) : null,
experiments: experiments && !(experiments as any).__challenged ? (experiments as Record<string, any>) : null,
userInfo: userInfo && !(userInfo as any).__challenged ? (userInfo as UserInfoResponse) : null,
},
elapsedMs: Date.now() - started,
};
}
/* ═══════════════════════════════════════════════════════════════ */
/* Tier 3 — headless Patchright browser (fallback, guaranteed) */
/* ═══════════════════════════════════════════════════════════════ */
async function tierBrowser(cookies: PlaywrightCookie[], log: (l: string) => void, timeoutMs: number): Promise<TierResult> {
const started = Date.now();
try {
await resolveBrowserExecutable();
} catch (err) {
return { ok: false, error: (err as Error).message, elapsedMs: Date.now() - started };
}
let chromium: typeof import("patchright").chromium;
try {
chromium = (await import("patchright")).chromium;
} catch (err) {
return { ok: false, error: `patchright missing: ${(err as Error).message}`, elapsedMs: Date.now() - started };
}
const probe = findBrowser();
const label = probe
? `${probe.channel}${probe.path.toLowerCase().includes("brave") ? " (brave)" : ""}`
: "bundled";
log(`browser: launching headless ${label}`);
const browser = await chromium.launch({
headless: true,
args: STEALTH_ARGS,
...(probe ? { executablePath: probe.path } : {}),
...(probe && ["chrome", "msedge", "chromium"].includes(probe.channel) ? { channel: probe.channel as any } : {}),
ignoreDefaultArgs: ["--enable-automation"],
});
try {
const context = await getOrCreateContext(browser, {
viewport: { width: 1920, height: 1080 },
userAgent: USER_AGENT,
});
await context.addCookies(cookies as any);
const page = await context.newPage();
const navResp = await page.goto(PERPLEXITY_URL, { waitUntil: "domcontentloaded", timeout: timeoutMs }).catch((e) => {
log(`browser: goto failed ${(e as Error).message}`);
return null;
});
const status = navResp?.status() ?? 0;
const title = await page.title().catch(() => "");
log(`browser: navigation status=${status}, title="${title}"`);
if (title.includes("Just a moment") || title.toLowerCase().includes("cloudflare")) {
return { ok: false, challenged: true, error: "CF challenge via browser — cookies expired", elapsedMs: Date.now() - started };
}
const fetchJson = async <T>(url: string, name: string): Promise<T | null> => {
try {
const result: any = await page.evaluate(async (u: string) => {
try {
const r = await fetch(u, { credentials: "include" });
const ct = r.headers.get("content-type") ?? "";
if (!r.ok || !ct.includes("application/json")) {
return { ok: false, status: r.status, contentType: ct };
}
return { ok: true, body: await r.json() };
} catch (e: any) {
return { ok: false, error: e?.message ?? String(e) };
}
}, url);
if (!result?.ok) {
log(`browser: ${name} non-OK status=${result?.status ?? "n/a"} ct=${result?.contentType ?? "n/a"} err=${result?.error ?? "n/a"}`);
return null;
}
return result.body as T;
} catch (err) {
log(`browser: ${name} evaluate threw: ${(err as Error).message}`);
return null;
}
};
const [models, asi, rateLimits, experiments, userInfo] = await Promise.all([
fetchJson<ModelsConfigResponse>(MODELS_CONFIG_ENDPOINT, "models/config"),
fetchJson<ASIAccessResponse>(ASI_ACCESS_ENDPOINT, "asi-access"),
fetchJson<RateLimitResponse>(RATE_LIMIT_ENDPOINT, "rate-limit"),
fetchJson<Record<string, any>>(EXPERIMENTS_ENDPOINT, "experiments"),
fetchJson<UserInfoResponse>(USER_INFO_ENDPOINT, "user/info"),
]);
if (!models) {
return { ok: false, error: "browser: models/config fetch failed inside page", elapsedMs: Date.now() - started };
}
log(
`browser: fetched — models=${Object.keys(models.models || {}).length}, asi=${!!asi}, ` +
`rateLimits=${!!rateLimits}, experiments=${experiments ? Object.keys(experiments).length + " keys" : "null"}, ` +
`userInfo=${userInfo ? JSON.stringify(userInfo) : "null"}`
);
const freshCookies = await context
.cookies(PERPLEXITY_URL)
.then((arr) =>
arr.map((c) => ({
name: c.name,
value: c.value,
domain: c.domain,
path: c.path,
secure: c.secure,
httpOnly: c.httpOnly,
sameSite: c.sameSite,
})) as PlaywrightCookie[]
)
.catch(() => undefined);
return {
ok: true,
payload: { models, asi, rateLimits, experiments, userInfo, freshCookies },
elapsedMs: Date.now() - started,
};
} finally {
await browser.close().catch(() => undefined);
}
}
/* ═══════════════════════════════════════════════════════════════ */
/* Orchestrator */
/* ═══════════════════════════════════════════════════════════════ */
export async function refreshAccountInfo(opts: RefreshOptions = {}): Promise<RefreshResult> {
const log = opts.log ?? noopLog;
const started = Date.now();
const timeoutMs = opts.timeoutMs ?? 25000;
const modelsCacheFile = getModelsCacheFile();
const legacyCookiesFile = getLegacyCookiesFile();
const savedCookies = await getSavedCookies();
if (savedCookies.length === 0) {
return {
ok: false,
source: "no-cookies",
tier: null,
modelCount: 0,
accountTier: "Unknown",
error: "No saved cookies — run Perplexity: Login first.",
cachePath: modelsCacheFile,
elapsedMs: Date.now() - started,
};
}
const attempts: RefreshResult["tierAttempts"] = [];
type TierFn = (c: PlaywrightCookie[], l: (l: string) => void, t: number) => Promise<TierResult>;
const tierMap: Record<RefreshTier, TierFn> = {
"got-scraping": tierGotScraping,
impit: tierImpit,
browser: tierBrowser,
};
const pipeline: Array<[RefreshTier, TierFn]> = opts.forceTier
? [[opts.forceTier, tierMap[opts.forceTier]]]
: (() => {
const chain: Array<[RefreshTier, TierFn]> = [["got-scraping", tierGotScraping]];
if (isImpitAvailable()) chain.push(["impit", tierImpit]);
chain.push(["browser", tierBrowser]);
return chain;
})();
let successful: { tier: RefreshTier; result: TierResult } | null = null;
let lastChallenged = false;
for (const [name, fn] of pipeline) {
log(`refresh: attempting tier=${name}`);
const result = await fn(savedCookies, log, timeoutMs);
attempts.push({ tier: name, ok: result.ok, elapsedMs: result.elapsedMs, error: result.error });
if (result.ok) {
successful = { tier: name, result };
log(`refresh: tier=${name} succeeded in ${result.elapsedMs}ms`);
break;
}
lastChallenged = lastChallenged || !!result.challenged;
log(`refresh: tier=${name} failed in ${result.elapsedMs}ms (${result.error ?? "unknown"})`);
}
if (!successful) {
return {
ok: false,
source: lastChallenged ? "cf-challenge" : "failed",
tier: null,
modelCount: 0,
accountTier: "Unknown",
error: lastChallenged
? "All tiers hit Cloudflare challenge. Run Perplexity: Login to re-solve Turnstile."
: "All refresh tiers failed. See logs.",
cachePath: modelsCacheFile,
elapsedMs: Date.now() - started,
tierAttempts: attempts,
};
}
const { tier, result } = successful;
const payload = result.payload!;
const existing = readExistingCache(modelsCacheFile);
// Prefer /rest/user/info flags (direct, stable) over /rest/experiments
// which returns many unrelated server-side A/B flags and has been seen to
// drop the subscription fields intermittently. Experiments is still used
// for server_is_max (not mirrored in user/info).
const isEnterpriseFromUser = payload.userInfo?.is_enterprise === true;
const isEnterpriseFromExp = payload.experiments?.server_is_enterprise === true;
const isProFromExp = payload.experiments?.server_is_pro === true;
const isMaxFromExp = payload.experiments?.server_is_max === true;
const canUseComputer = payload.asi?.can_use_computer ?? existing?.canUseComputer ?? false;
const info: AccountInfo = {
// If Computer mode is accessible but no experiments flag fires, infer Pro —
// Computer is gated to paid tiers, so the account is at least Pro.
isPro: isProFromExp || (canUseComputer && !isMaxFromExp && !isEnterpriseFromUser && !isEnterpriseFromExp),
isMax: isMaxFromExp,
isEnterprise: isEnterpriseFromUser || isEnterpriseFromExp,
canUseComputer,
modelsConfig: payload.models,
rateLimits: payload.rateLimits ?? existing?.rateLimits ?? null,
};
mkdirSync(dirname(modelsCacheFile), { recursive: true });
writeFileSync(modelsCacheFile, JSON.stringify(info, null, 2));
log(`refresh: wrote ${modelsCacheFile} (${Object.keys(payload.models.models || {}).length} models)`);
// Write back fresh cookies if the tier produced them (only the browser tier does).
if (payload.freshCookies && payload.freshCookies.length > 0) {
try {
mkdirSync(dirname(legacyCookiesFile), { recursive: true });
writeFileSync(
legacyCookiesFile,
JSON.stringify({ allCookies: payload.freshCookies, savedAt: new Date().toISOString() }, null, 2)
);
log(`refresh: persisted ${payload.freshCookies.length} fresh cookies to ${legacyCookiesFile}`);
} catch (err) {
log(`refresh: could not persist fresh cookies (non-fatal): ${(err as Error).message}`);
}
}
return {
ok: true,
source: "live",
tier,
modelCount: Object.keys(payload.models.models || {}).length,
accountTier: deriveTier(info),
cachePath: modelsCacheFile,
elapsedMs: Date.now() - started,
tierAttempts: attempts,
};
}
function deriveTier(info: AccountInfo): RefreshResult["accountTier"] {
if (info.isMax) return "Max";
if (info.isEnterprise) return "Enterprise";
if (info.isPro) return "Pro";
return "Free";
}
function readExistingCache(modelsCacheFile = getModelsCacheFile()): AccountInfo | null {
if (!existsSync(modelsCacheFile)) return null;
try {
return JSON.parse(readFileSync(modelsCacheFile, "utf8")) as AccountInfo;
} catch {
return null;
}
}
export function getModelsCacheInfo(): { path: string; exists: boolean; mtime: Date | null; ageHours: number | null } {
const path = getModelsCacheFile();
const exists = existsSync(path);
const mtime = exists ? statSync(path).mtime : null;
const ageHours = mtime ? (Date.now() - mtime.getTime()) / 3_600_000 : null;
return { path, exists, mtime, ageHours };
}
export function getImpitRuntimeDir(): string {
return getImpitRuntimeDirPath();
}