import suffixes from './public-suffixes.json' with { type: 'json' }; import { cookieMatchesHost, type BrowserCookie } from './browser-state.ts'; /** Cookie domain acceptance uses the public suffix list, including its wildcard and exception rules. */ let rules: Set | undefined; function publicSuffix(domain: string): boolean { rules ??= new Set(suffixes.rules.map(rule => { const prefix = rule.startsWith('!') ? '!' : rule.startsWith('*.') ? '*.' : ''; return `${prefix}${new URL(`https://${rule.slice(prefix.length)}`).hostname}`; })); const labels = domain.split('.'); let size = 1; for (let i = 0; i < labels.length; i++) { const suffix = labels.slice(i).join('.'); if (rules.has(`!${suffix}`)) return labels.length === labels.length - i - 1; if (rules.has(suffix)) size = Math.max(size, labels.length - i); if (i > 0 && rules.has(`*.${suffix}`)) size = Math.max(size, labels.length - i + 1); } return labels.length === size; } const domainMatches = (host: string, domain: string): boolean => host === domain || host.endsWith(`.${domain}`); const pathMatches = (path: string, scope: string): boolean => path === scope || (path.startsWith(scope) && (scope.endsWith('/') || path[scope.length] === '/')); /** A seed's HTTP cookie jar; cookies remain at the real URL even when transport goes to a twin. */ export class BrowserCookieJar { private cookies: BrowserCookie[]; constructor(cookies: BrowserCookie[] = []) { this.cookies = structuredClone(cookies); } snapshot(now: number): BrowserCookie[] { this.cookies = this.cookies.filter(c => c.expires === -1 || c.expires > now / 1000); return structuredClone(this.cookies); } header(url: URL, now: number): string { return this.snapshot(now).filter(c => (!c.secure || url.protocol === 'https:') && cookieMatchesHost(c, url.hostname) && pathMatches(url.pathname, c.path)) .sort((a, b) => b.path.length - a.path.length).map(c => `${c.name}=${c.value}`).join('; '); } set(line: string, url: URL, now: number): void { const [pair = '', ...attributes] = line.split(';'); const eq = pair.indexOf('='); if (eq < 1) return; const name = pair.slice(0, eq).trim(); const value = pair.slice(eq + 1).trim(); if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name) || /[\x00-\x1f\x7f;\u0100-\uffff]/.test(value)) return; const attrs = new Map(); for (const part of attributes) { const at = part.indexOf('='); attrs.set((at < 0 ? part : part.slice(0, at)).trim().toLowerCase(), at < 0 ? '' : part.slice(at + 1).trim()); } let domain = url.hostname; const asked = attrs.get('domain'); if (asked) { if (/[\s:/\\?#@%]/.test(asked)) return; let normalized: string; try { normalized = new URL(`https://${asked.replace(/^\./, '')}`).hostname; } catch { return; } if (!domainMatches(url.hostname, normalized) || publicSuffix(normalized)) return; domain = `.${normalized}`; } const last = url.pathname.lastIndexOf('/'); const fallback = last > 0 ? url.pathname.slice(0, last) : '/'; const path = attrs.get('path')?.startsWith('/') ? attrs.get('path')! : fallback; if (/[\x00-\x20\x7f;\u0100-\uffff]/.test(path)) return; const secure = attrs.has('secure'); if (secure && url.protocol !== 'https:') return; const same = attrs.get('samesite')?.toLowerCase(); const sameSite = same === 'strict' ? 'Strict' : same === 'none' ? 'None' : 'Lax'; if (sameSite === 'None' && !secure) return; if (name.startsWith('__Secure-') && !secure) return; if (name.startsWith('__Host-') && (!secure || asked || attrs.get('path') !== '/')) return; let expires = -1; const date = attrs.get('expires'); if (date && Number.isFinite(Date.parse(date))) expires = Date.parse(date) / 1000; const age = attrs.get('max-age'); if (age && /^-?\d+$/.test(age)) { const seconds = Number(age); expires = seconds <= 0 ? 0 : Math.min(8640000000000, now / 1000 + seconds); } const existing = this.cookies.findIndex(c => c.name === name && c.domain.replace(/^\./, '') === domain.replace(/^\./, '') && c.path === path); // An insecure response cannot replace a secure cookie with an overlapping scope. if (url.protocol !== 'https:' && this.cookies.some(c => c.name === name && c.secure && domainMatches(domain.replace(/^\./, ''), c.domain.replace(/^\./, '')) && pathMatches(path, c.path))) return; const cookie: BrowserCookie = { name, value, domain, path, expires, secure, httpOnly: attrs.has('httponly'), sameSite }; if (existing < 0) this.cookies.push(cookie); else this.cookies[existing] = cookie; this.snapshot(now); } }