-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathcookie-jar.js
More file actions
383 lines (365 loc) · 13.4 KB
/
Copy pathcookie-jar.js
File metadata and controls
383 lines (365 loc) · 13.4 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
// Minimal RFC 6265-style cookie jar for the impit-driven login flow.
//
// Why hand-rolled:
// - We need writable + round-trippable to the existing PlaywrightCookie shape
// (see ./config.ts) so the final `vault.set(profile, "cookies", jar.toPlaywrightShape())`
// is a drop-in replacement for what Patchright produces today.
// - We deliberately avoid pulling in `tough-cookie`. The mcp-server bundle's
// tsup config externalises tough-cookie *only* because it ships indirectly
// via patchright; adding it as a first-class dep would force another
// externalize-vs-bundle decision and grow the VSIX. The 6265 subset we need
// fits in ~150 lines.
//
// Coverage of the spec is intentionally partial. We implement what the
// Perplexity OAuth callback chain actually exercises:
// - Set-Cookie parsing: name=value plus Domain, Path, Expires, Max-Age,
// Secure, HttpOnly, SameSite attributes (case-insensitive attribute names,
// RFC-compliant unquoted values).
// - Cookie identity = (name, domain, path); same triple replaces.
// - Domain matching with leading-dot semantics (RFC 6265 §5.1.3).
// - Path matching (prefix, RFC 6265 §5.1.4 — simplified).
// - Expires + Max-Age (Max-Age wins).
// - Secure attribute filters out non-HTTPS request URLs.
// - HttpOnly is preserved on round-trip but does NOT filter `buildCookieHeader`
// (we are not a browser; impit is the only consumer and treats us as a UA).
// - Path-length-descending sort for Cookie header serialisation (§5.4).
//
// Things we deliberately do NOT do (out of scope for the impit login):
// - Public-suffix-list checks on Domain.
// - SameSite enforcement (we round-trip the attribute but don't gate sends).
// - Cookie size / count limits.
// - __Host- / __Secure- prefix validation (Perplexity uses __Secure- but
// we just preserve it as-is on the name).
/**
* @typedef {Object} PlaywrightCookie
* @property {string} name
* @property {string} value
* @property {string} domain
* @property {string} path
* @property {number} [expires] Unix epoch seconds; -1 for session cookies (Patchright convention).
* @property {boolean} [secure]
* @property {boolean} [httpOnly]
* @property {"Strict"|"Lax"|"None"} [sameSite]
*/
const SESSION_EXPIRES = -1;
/**
* Parse a single Set-Cookie value. Returns null when the header is malformed
* (no name, missing `=`, or the cookie name is empty after trimming).
*
* Defaults applied here:
* - domain: exact host of `requestUrl` (no leading dot — host-only cookie).
* - path: "/" if the request URL has no path or the path has no slash.
*
* The returned object always has all attributes resolved so the caller can
* blindly merge.
*
* @param {string} header
* @param {URL} requestUrlObj
* @returns {{name:string,value:string,domain:string,path:string,expires:number,secure:boolean,httpOnly:boolean,sameSite?:"Strict"|"Lax"|"None",hostOnly:boolean}|null}
*/
function parseSetCookie(header, requestUrlObj) {
if (typeof header !== "string" || header.length === 0) return null;
// RFC 6265 forbids `,` inside a single Set-Cookie except inside Expires (which
// uses `Wdy, DD-Mon-...`). We never get a comma-joined header from the
// node:http parser when we use raw arrays, so we trust the caller to pass
// each Set-Cookie value separately. `consumeSetCookieHeader` arranges that.
const parts = header.split(";");
const first = parts.shift();
if (!first) return null;
const eq = first.indexOf("=");
if (eq < 0) return null;
const name = first.slice(0, eq).trim();
const value = first.slice(eq + 1).trim();
if (!name) return null;
let domain = requestUrlObj.hostname.toLowerCase();
let hostOnly = true;
let path = defaultPath(requestUrlObj.pathname);
let expires = SESSION_EXPIRES;
let maxAgeSeconds = null;
let secure = false;
let httpOnly = false;
/** @type {"Strict"|"Lax"|"None"|undefined} */
let sameSite;
for (const raw of parts) {
if (!raw) continue;
const trimmed = raw.trim();
if (!trimmed) continue;
const aEq = trimmed.indexOf("=");
const attrName = (aEq < 0 ? trimmed : trimmed.slice(0, aEq)).trim().toLowerCase();
const attrValue = aEq < 0 ? "" : trimmed.slice(aEq + 1).trim();
switch (attrName) {
case "domain": {
if (!attrValue) break;
// RFC 6265 §5.2.3: leading dot is ignored, but the cookie becomes a
// domain-cookie (matches subdomains). We track that via `hostOnly`.
const stripped = attrValue.replace(/^\./, "").toLowerCase();
if (stripped) {
domain = stripped;
hostOnly = false;
}
break;
}
case "path": {
if (attrValue.startsWith("/")) path = attrValue;
break;
}
case "expires": {
const ts = Date.parse(attrValue);
if (!Number.isNaN(ts)) expires = Math.floor(ts / 1000);
break;
}
case "max-age": {
// RFC 6265 §5.2.2: leading "-" or "0" => delete. We surface that as
// `expires = 0` so the jar's prune logic treats the cookie as expired.
if (/^-?\d+$/.test(attrValue)) {
maxAgeSeconds = Number(attrValue);
}
break;
}
case "secure":
secure = true;
break;
case "httponly":
httpOnly = true;
break;
case "samesite": {
const v = attrValue.toLowerCase();
if (v === "strict") sameSite = "Strict";
else if (v === "lax") sameSite = "Lax";
else if (v === "none") sameSite = "None";
break;
}
default:
// Unknown attributes are ignored per spec.
break;
}
}
if (maxAgeSeconds !== null) {
// Max-Age wins over Expires. <=0 means delete now.
expires = maxAgeSeconds <= 0 ? 0 : Math.floor(Date.now() / 1000) + maxAgeSeconds;
}
return { name, value, domain, path, expires, secure, httpOnly, sameSite, hostOnly };
}
/**
* Default-path algorithm from RFC 6265 §5.1.4.
* - "" or no leading slash → "/"
* - "/foo/bar" → "/foo"
* - "/foo" → "/"
*/
function defaultPath(uriPath) {
if (!uriPath || !uriPath.startsWith("/")) return "/";
const lastSlash = uriPath.lastIndexOf("/");
if (lastSlash <= 0) return "/";
return uriPath.slice(0, lastSlash);
}
function isExpired(cookie, nowSeconds) {
if (cookie.expires === undefined) return false;
if (cookie.expires === SESSION_EXPIRES) return false;
return cookie.expires <= nowSeconds;
}
/**
* Domain-match per RFC 6265 §5.1.3. Either:
* - exact match (case-insensitive), OR
* - cookie domain is a suffix of host AND host has a `.` before the suffix
* AND the cookie was set with an explicit Domain attribute (i.e. not host-only).
*
* @param {string} cookieDomain lower-case, no leading dot
* @param {boolean} hostOnly
* @param {string} requestHost lower-case
*/
function domainMatches(cookieDomain, hostOnly, requestHost) {
if (cookieDomain === requestHost) return true;
if (hostOnly) return false;
if (!requestHost.endsWith(cookieDomain)) return false;
const idx = requestHost.length - cookieDomain.length;
if (idx <= 0) return false;
return requestHost[idx - 1] === ".";
}
/**
* Path-match per RFC 6265 §5.1.4.
* - cookie path === request path, OR
* - cookie path is a prefix and ends with "/", OR
* - cookie path is a prefix and the next char of request path is "/".
*/
function pathMatches(cookiePath, requestPath) {
if (cookiePath === requestPath) return true;
if (!requestPath.startsWith(cookiePath)) return false;
if (cookiePath.endsWith("/")) return true;
return requestPath[cookiePath.length] === "/";
}
function cookieKey(name, domain, path) {
return `${name} ${domain.toLowerCase()} ${path}`;
}
/**
* Coerce a PlaywrightCookie back into the internal entry shape. Used by
* the constructor and `set()`. We always produce hostOnly=false when domain
* starts with `.` in the source array (Patchright emits leading-dot domains
* for domain cookies); strip the dot here so the rest of the matching logic
* runs on a normalised form.
*/
function entryFromPlaywright(c) {
let domain = (c.domain || "").toLowerCase();
let hostOnly = true;
if (domain.startsWith(".")) {
domain = domain.slice(1);
hostOnly = false;
}
const expires = typeof c.expires === "number" ? c.expires : SESSION_EXPIRES;
return {
name: String(c.name),
value: String(c.value),
domain,
path: c.path || "/",
expires,
secure: !!c.secure,
httpOnly: !!c.httpOnly,
sameSite: c.sameSite,
hostOnly,
};
}
export class CookieJar {
/**
* @param {PlaywrightCookie[]} [initialCookies]
*/
constructor(initialCookies = []) {
/** @type {Map<string, ReturnType<typeof entryFromPlaywright>>} */
this._store = new Map();
if (Array.isArray(initialCookies)) {
for (const c of initialCookies) {
if (!c || typeof c.name !== "string") continue;
const entry = entryFromPlaywright(c);
this._store.set(cookieKey(entry.name, entry.domain, entry.path), entry);
}
}
}
/**
* Apply one or more Set-Cookie headers from a response. Accepts either a
* single string or an array (e.g. `res.headers.getSetCookie?.()` /
* `res.headers.raw()['set-cookie']`).
*
* @param {string|string[]|null|undefined} header
* @param {string} requestUrl
*/
consumeSetCookieHeader(header, requestUrl) {
if (!header) return;
let url;
try {
url = new URL(requestUrl);
} catch {
return;
}
const headers = Array.isArray(header) ? header : [header];
for (const h of headers) {
const parsed = parseSetCookie(h, url);
if (!parsed) continue;
const key = cookieKey(parsed.name, parsed.domain, parsed.path);
// Max-Age=0 / Expires-in-past after an explicit attribute → delete.
// (We still keep cookies that became expired via wall-clock drift; only
// the *server* explicitly setting expiry-at-or-before-now is a delete.)
if (parsed.expires !== SESSION_EXPIRES && parsed.expires <= 0) {
this._store.delete(key);
continue;
}
this._store.set(key, parsed);
}
}
/**
* Build a `Cookie:` header value for `requestUrl`. Returns "" if no cookies
* apply (so the caller can do `if (h) headers.cookie = h`).
*
* @param {string} requestUrl
* @returns {string}
*/
buildCookieHeader(requestUrl) {
let url;
try {
url = new URL(requestUrl);
} catch {
return "";
}
const isHttps = url.protocol === "https:";
const host = url.hostname.toLowerCase();
const reqPath = url.pathname || "/";
const now = Math.floor(Date.now() / 1000);
const matched = [];
for (const cookie of this._store.values()) {
if (isExpired(cookie, now)) continue;
if (cookie.secure && !isHttps) continue;
if (!domainMatches(cookie.domain, cookie.hostOnly, host)) continue;
if (!pathMatches(cookie.path, reqPath)) continue;
matched.push(cookie);
}
// RFC 6265 §5.4: longer paths first; ties broken by earlier-created first.
// We don't track creation time, so insertion order via Map iteration acts
// as the secondary sort (Array.prototype.sort is stable on modern Node).
matched.sort((a, b) => b.path.length - a.path.length);
return matched.map((c) => `${c.name}=${c.value}`).join("; ");
}
/**
* Snapshot of every cookie in the jar (including expired ones — callers that
* persist to disk want the full set so a refresh can simply overwrite).
*
* @returns {PlaywrightCookie[]}
*/
toPlaywrightShape() {
const out = [];
for (const c of this._store.values()) {
/** @type {PlaywrightCookie} */
const pc = {
name: c.name,
value: c.value,
// Round-trip leading-dot for domain cookies so Patchright + the
// existing `getSavedCookies()` consumers see the same shape they do
// today.
domain: c.hostOnly ? c.domain : `.${c.domain}`,
path: c.path,
expires: c.expires,
secure: c.secure,
httpOnly: c.httpOnly,
};
if (c.sameSite) pc.sameSite = c.sameSite;
out.push(pc);
}
return out;
}
/**
* Explicit setter, mostly for tests and for the rare case where the caller
* already has a fully-formed cookie record (e.g. seeding cf_clearance from
* the vault). `attributes` may include any of the PlaywrightCookie fields
* except name/value.
*
* @param {string} name
* @param {string} value
* @param {Partial<PlaywrightCookie> & { hostOnly?: boolean }} [attributes]
*/
set(name, value, attributes = {}) {
const domainRaw = (attributes.domain || "").toLowerCase();
let domain = domainRaw;
let hostOnly;
if (typeof attributes.hostOnly === "boolean") {
hostOnly = attributes.hostOnly;
if (domain.startsWith(".")) domain = domain.slice(1);
} else if (domain.startsWith(".")) {
hostOnly = false;
domain = domain.slice(1);
} else {
hostOnly = true;
}
if (!domain) {
// Without a domain we can't sensibly key the cookie; refuse silently.
return;
}
const entry = {
name: String(name),
value: String(value),
domain,
path: attributes.path || "/",
expires: typeof attributes.expires === "number" ? attributes.expires : SESSION_EXPIRES,
secure: !!attributes.secure,
httpOnly: !!attributes.httpOnly,
sameSite: attributes.sameSite,
hostOnly,
};
this._store.set(cookieKey(entry.name, entry.domain, entry.path), entry);
}
}