Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SafariCookies.ts

217 lines8.3 KB

1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as PlatformError from "effect/PlatformError";
4import * as Schema from "effect/Schema";
5​
6import { cookieScope, type ImportedCookie } from "./CookieDatabase.ts";
7​
8/** Safari's timestamps count seconds from 2001-01-01, not the UNIX epoch. */
9const APPLE_EPOCH_OFFSET_SECONDS = 978_307_200;
10​
11/** `u32 0x00000100`, `u32le cookieCount`, then one `u32le` offset per cookie. */
12const COOKIE_PAGE_HEADER_SIZE = 12;
13const COOKIE_RECORD_HEADER_SIZE = 56;
14​
15const FLAG_SECURE = 0x1;
16const FLAG_HTTP_ONLY = 0x4;
17​
18export const SafariCookieReadFailure = Schema.Literals(["needsFullDiskAccess", "readFailed"]);
19export type SafariCookieReadFailure = typeof SafariCookieReadFailure.Type;
20​
21export class SafariCookieReadError extends Schema.TaggedError<SafariCookieReadError>()(
22 "SafariCookieReadError",
23 {
24 reason: SafariCookieReadFailure,
25 cookieDatabasePath: Schema.optional(Schema.String),
26 cause: Schema.optional(Schema.Defect()),
27 },
28) {
29 override get message(): string {
30 return this.cookieDatabasePath === undefined
31 ? `Could not read Safari cookies: ${this.reason}.`
32 : `Could not read Safari cookies at ${this.cookieDatabasePath}: ${this.reason}.`;
33 }
35​
36const isSafariCookieReadError = Schema.is(SafariCookieReadError);
37​
38function readCString(buffer: Buffer, start: number): string {
39 const end = buffer.indexOf(0, start);
40 return buffer.toString("utf8", start, end === -1 ? buffer.length : end);
42​
43export function parseBinaryCookies(buffer: Buffer): ReadonlyArray<ImportedCookie> {
44 if (buffer.length < 8 || buffer.toString("latin1", 0, 4) !== "cook") {
45 throw new SafariCookieReadError({ reason: "readFailed" });
46 }
47​
48 const pageCount = buffer.readUInt32BE(4);
49 // `Buffer.subarray` clamps silently, so accepting a short page or an overlong
50 // record would return a cookie set that is quietly missing entries or
51 // carrying fields read out of the next record — a partial import the user has
52 // no way to notice.
53 if (8 + pageCount * 4 > buffer.length) {
54 throw new SafariCookieReadError({ reason: "readFailed" });
55 }
56 const pageSizes: number[] = [];
57 for (let index = 0; index < pageCount; index += 1) {
58 pageSizes.push(buffer.readUInt32BE(8 + index * 4));
59 }
60​
61 const cookies: ImportedCookie[] = [];
62 let pageStart = 8 + pageCount * 4;
63​
64 for (const pageSize of pageSizes) {
65 if (pageSize < COOKIE_PAGE_HEADER_SIZE || pageStart + pageSize > buffer.length) {
66 throw new SafariCookieReadError({ reason: "readFailed" });
67 }
68 const page = buffer.subarray(pageStart, pageStart + pageSize);
69 pageStart += pageSize;
70​
71 // Page bodies switch to little-endian after the big-endian header.
72 const cookieCount = page.readUInt32LE(4);
73 const offsetTableEnd = COOKIE_PAGE_HEADER_SIZE + cookieCount * 4;
74 if (offsetTableEnd > page.length) {
75 throw new SafariCookieReadError({ reason: "readFailed" });
76 }
77 // Every record accepted so far, so a later offset cannot point back into
78 // one of them: the page header, the offset table, and earlier records are
79 // all bytes that would otherwise parse as a fabricated cookie.
80 const accepted: Array<readonly [start: number, end: number]> = [];
81 for (let index = 0; index < cookieCount; index += 1) {
82 const cookieStart = page.readUInt32LE(8 + index * 4);
83 if (cookieStart < offsetTableEnd || cookieStart + COOKIE_RECORD_HEADER_SIZE > page.length) {
84 throw new SafariCookieReadError({ reason: "readFailed" });
85 }
86 const recordSize = page.readUInt32LE(cookieStart);
87 const cookieEnd = cookieStart + recordSize;
88 if (
89 recordSize < COOKIE_RECORD_HEADER_SIZE ||
90 cookieEnd > page.length ||
91 accepted.some(([start, end]) => cookieStart < end && cookieEnd > start)
92 ) {
93 throw new SafariCookieReadError({ reason: "readFailed" });
94 }
95 accepted.push([cookieStart, cookieEnd]);
96 const cookie = page.subarray(cookieStart, cookieEnd);
97​
98 const flags = cookie.readUInt32LE(8);
99 const urlOffset = cookie.readUInt32LE(16);
100 const nameOffset = cookie.readUInt32LE(20);
101 const pathOffset = cookie.readUInt32LE(24);
102 const valueOffset = cookie.readUInt32LE(28);
103 const expiry = cookie.readDoubleLE(40);
104​
105 if (
106 [urlOffset, nameOffset, pathOffset, valueOffset].some(
107 (offset) => offset < COOKIE_RECORD_HEADER_SIZE || offset >= cookie.length,
108 )
109 ) {
110 throw new SafariCookieReadError({ reason: "readFailed" });
111 }
112 const domain = readCString(cookie, urlOffset);
113 const name = readCString(cookie, nameOffset);
114 const path = readCString(cookie, pathOffset);
115 const value = readCString(cookie, valueOffset);
116 if (domain === "" || name === "") continue;
117​
118 const secure = (flags & FLAG_SECURE) !== 0;
119 const expirationDate =
120 expiry > 0 ? Math.floor(expiry) + APPLE_EPOCH_OFFSET_SECONDS : undefined;
121​
122 cookies.push({
123 // Safari marks domain cookies with a leading dot like the other
124 // engines, so the shared scope rule applies: host-only cookies keep
125 // `domain` undefined, or Electron widens them to every subdomain.
126 ...cookieScope(domain, path || "/", secure),
127 name,
128 value,
129 path: path || "/",
130 secure,
131 httpOnly: (flags & FLAG_HTTP_ONLY) !== 0,
132 expirationDate,
133 // Bits 3–5 of the flags carry something SameSite-shaped, but no public
134 // description of them agrees and real jars do not match any of them
135 // cleanly. Lax is the modern browser default; claiming "none" would
136 // widen every imported cookie's scope.
137 sameSite: "lax",
138 });
139 }
140 }
141​
142 // Safari writes an 8-byte checksum after the pages, then an optional
143 // length-prefixed property list.
144 const trailer = buffer.length - pageStart;
145 const validTrailer =
146 trailer === 0 ||
147 trailer === 8 ||
148 (trailer >= 12 && trailer === 8 + 4 + buffer.readUInt32BE(pageStart + 8));
149 if (!validTrailer) {
150 throw new SafariCookieReadError({ reason: "readFailed" });
151 }
152​
153 return cookies;
155​
156export const isPermissionDenied = (error: PlatformError.PlatformError): boolean => {
157 // TCC denies with EPERM, which Effect tags `Unknown` rather than
158 // `PermissionDenied` — so the errno is what identifies it. EACCES (and the
159 // `PermissionDenied` tag it maps to) is an ordinary POSIX permission or
160 // ACL failure that granting Full Disk Access cannot fix, so it stays a plain
161 // read failure rather than sending the user to a grant that won't help.
162 const code = (error.reason as { cause?: { code?: unknown } }).cause?.code;
163 return code === "EPERM";
164};
165​
166/**
167 * `stat` succeeds on the jar inside Safari's container even without Full Disk
168 * Access — that is what lets the listing find it — so presence alone cannot
169 * tell granted from denied.
170 * */
171export const safariAccessDenied = Effect.fnUntraced(function* (cookiePath: string) {
172 const fileSystem = yield* FileSystem.FileSystem;
173 return yield* fileSystem.open(cookiePath, { flag: "r" }).pipe(
174 Effect.as(false),
175 Effect.catch((cause) => Effect.succeed(isPermissionDenied(cause))),
176 Effect.scoped,
177 );
178});
179​
180export const safariAccessGranted = Effect.fnUntraced(function* (cookiePath: string) {
181 const fileSystem = yield* FileSystem.FileSystem;
182 return yield* fileSystem.open(cookiePath, { flag: "r" }).pipe(
183 Effect.as(true),
184 Effect.orElseSucceed(() => false),
185 Effect.scoped,
186 );
187});
188​
189export const readSafariCookies = Effect.fn("SafariCookies.readSafariCookies")(function* (
190 cookiePath: string,
191) {
192 const fileSystem = yield* FileSystem.FileSystem;
193 const contents = yield* fileSystem.readFile(cookiePath).pipe(
194 Effect.mapError((cause) => {
195 return new SafariCookieReadError({
196 reason: isPermissionDenied(cause) ? "needsFullDiskAccess" : "readFailed",
197 cookieDatabasePath: cookiePath,
198 cause,
199 });
200 }),
201 );
202 return yield* Effect.try({
203 try: () => parseBinaryCookies(Buffer.from(contents)),
204 catch: (cause) =>
205 isSafariCookieReadError(cause)
206 ? new SafariCookieReadError({
207 reason: cause.reason,
208 cookieDatabasePath: cookiePath,
209 cause,
210 })
211 : new SafariCookieReadError({
212 reason: "readFailed",
213 cookieDatabasePath: cookiePath,
214 cause,
215 }),
216 });
217});