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

SafariCookies.test.ts

443 lines16.8 KB

1// @effect-diagnostics nodeBuiltinImport:off - Hand-builds Safari's binary jar
2// format byte by byte.
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, describe, expect, it } from "@effect/vitest";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as PlatformError from "effect/PlatformError";
8​
9import {
10 isPermissionDenied,
11 parseBinaryCookies,
12 readSafariCookies,
13 safariAccessDenied,
14 SafariCookieReadError,
15} from "./SafariCookies.ts";
16​
17const APPLE_EPOCH_OFFSET_SECONDS = 978_307_200;
18​
19interface FixtureCookie {
20 readonly domain: string;
21 readonly name: string;
22 readonly path: string;
23 readonly value: string;
24 readonly flags: number;
25 /** Seconds since 2001-01-01, as Safari stores them. */
26 readonly expiry: number;
28​
29/** Encodes one cookie exactly as Safari lays it out. */
30function encodeCookie(cookie: FixtureCookie): Buffer {
31 const strings = [cookie.domain, cookie.name, cookie.path, cookie.value];
32 const headerSize = 56;
33 const offsets: number[] = [];
34 let cursor = headerSize;
35 for (const value of strings) {
36 offsets.push(cursor);
37 cursor += Buffer.byteLength(value) + 1;
38 }
39 const size = cursor;
40​
41 const buffer = Buffer.alloc(size);
42 buffer.writeUInt32LE(size, 0);
43 buffer.writeUInt32LE(0, 4);
44 buffer.writeUInt32LE(cookie.flags, 8);
45 buffer.writeUInt32LE(0, 12);
46 buffer.writeUInt32LE(offsets[0]!, 16);
47 buffer.writeUInt32LE(offsets[1]!, 20);
48 buffer.writeUInt32LE(offsets[2]!, 24);
49 buffer.writeUInt32LE(offsets[3]!, 28);
50 buffer.writeUInt32LE(0, 32);
51 buffer.writeUInt32LE(0, 36);
52 buffer.writeDoubleLE(cookie.expiry, 40);
53 buffer.writeDoubleLE(0, 48);
54 strings.forEach((value, index) => {
55 buffer.write(value, offsets[index]!, "utf8");
56 });
57 return buffer;
59​
60/** Builds a single-page `Cookies.binarycookies` file. */
61function encodeBinaryCookies(cookies: ReadonlyArray<FixtureCookie>): Buffer {
62 const encoded = cookies.map(encodeCookie);
63 const headerSize = 12 + encoded.length * 4;
64 const offsets: number[] = [];
65 let cursor = headerSize;
66 for (const cookie of encoded) {
67 offsets.push(cursor);
68 cursor += cookie.length;
69 }
70​
71 const page = Buffer.alloc(cursor);
72 page.writeUInt32BE(0x0000_0100, 0);
73 page.writeUInt32LE(encoded.length, 4);
74 offsets.forEach((offset, index) => page.writeUInt32LE(offset, 8 + index * 4));
75 encoded.forEach((cookie, index) => cookie.copy(page, offsets[index]!));
76​
77 const header = Buffer.alloc(8 + 4);
78 header.write("cook", 0, "latin1");
79 header.writeUInt32BE(1, 4);
80 header.writeUInt32BE(page.length, 8);
81 return Buffer.concat([header, page]);
83​
84describe("parseBinaryCookies", () => {
85 it("reads Safari's format and rebases its 2001 epoch", () => {
86 const file = encodeBinaryCookies([
87 {
88 domain: ".apple.com",
89 name: "session",
90 path: "/",
91 value: "abc",
92 // secure | httpOnly
93 flags: 0x1 | 0x4,
94 expiry: 800_000_000,
95 },
96 {
97 domain: "example.test",
98 name: "plain",
99 path: "/app",
100 value: "v",
101 flags: 0,
102 expiry: 0,
103 },
104 ]);
105​
106 expect(parseBinaryCookies(file)).toEqual([
107 {
108 url: "https://apple.com/",
109 name: "session",
110 value: "abc",
111 domain: ".apple.com",
112 path: "/",
113 secure: true,
114 httpOnly: true,
115 // Safari counts from 2001-01-01, Electron from 1970.
116 expirationDate: 800_000_000 + APPLE_EPOCH_OFFSET_SECONDS,
117 // The format predates SameSite; Lax is the safe modern default.
118 sameSite: "lax",
119 },
120 {
121 url: "http://example.test/app",
122 name: "plain",
123 value: "v",
124 // Host-only: no leading dot in the jar, so no `domain` for Electron,
125 // which would otherwise re-add the dot and widen it to subdomains.
126 domain: undefined,
127 path: "/app",
128 secure: false,
129 httpOnly: false,
130 expirationDate: undefined,
131 sameSite: "lax",
132 },
133 ]);
134 });
135​
136 it("keeps __Host- cookies host-only so Electron accepts them", () => {
137 const file = encodeBinaryCookies([
138 { domain: "example.test", name: "__Host-id", path: "/", value: "v", flags: 0x1, expiry: 0 },
139 ]);
140​
141 expect(parseBinaryCookies(file)[0]).toMatchObject({
142 url: "https://example.test/",
143 name: "__Host-id",
144 domain: undefined,
145 });
146 });
147​
148 it("brackets IPv6 hosts in the cookie URL", () => {
149 const file = encodeBinaryCookies([
150 { domain: "::1", name: "local", path: "/", value: "v", flags: 0, expiry: 0 },
151 ]);
152​
153 expect(parseBinaryCookies(file)[0]).toMatchObject({
154 url: "http://[::1]/",
155 domain: undefined,
156 });
157 });
158​
159 it("reads cookies spread across multiple pages", () => {
160 // Safari pages its cookie file, and a single-page reader would silently
161 // return only the first slice.
162 const first = encodeBinaryCookies([
163 { domain: "a.test", name: "one", path: "/", value: "1", flags: 0, expiry: 1 },
164 ]);
165 const second = encodeBinaryCookies([
166 { domain: "b.test", name: "two", path: "/", value: "2", flags: 0, expiry: 1 },
167 ]);
168 // Splice the two single-page files into one two-page file.
169 const firstPage = first.subarray(12);
170 const secondPage = second.subarray(12);
171 const header = Buffer.alloc(16);
172 header.write("cook", 0, "latin1");
173 header.writeUInt32BE(2, 4);
174 header.writeUInt32BE(firstPage.length, 8);
175 header.writeUInt32BE(secondPage.length, 12);
176​
177 const parsed = parseBinaryCookies(Buffer.concat([header, firstPage, secondPage]));
178​
179 expect(parsed.map((cookie) => cookie.name)).toEqual(["one", "two"]);
180 });
181​
182 it("rejects a page that runs past the end of the file", () => {
183 // `Buffer.subarray` clamps rather than throwing, so an overlong first page
184 // swallows the second one's bytes and advances the cursor past the end.
185 // Every cookie after the boundary then vanishes from a "successful" import.
186 const first = encodeBinaryCookies([
187 { domain: "a.test", name: "one", path: "/", value: "1", flags: 0, expiry: 1 },
188 ]);
189 const second = encodeBinaryCookies([
190 { domain: "b.test", name: "two", path: "/", value: "2", flags: 0, expiry: 1 },
191 ]);
192 const firstPage = first.subarray(12);
193 const secondPage = second.subarray(12);
194 const header = Buffer.alloc(16);
195 header.write("cook", 0, "latin1");
196 header.writeUInt32BE(2, 4);
197 // Declares more bytes for page one than the file holds in total.
198 header.writeUInt32BE(firstPage.length + secondPage.length + 32, 8);
199 header.writeUInt32BE(secondPage.length, 12);
200​
201 expect(() => parseBinaryCookies(Buffer.concat([header, firstPage, secondPage]))).toThrow(
202 SafariCookieReadError,
203 );
204 });
205​
206 it("rejects a record whose declared size runs past its page", () => {
207 const valid = encodeBinaryCookies([
208 { domain: "a.test", name: "n", path: "/", value: "v", expiry: 1_000, flags: 0 },
209 ]);
210 // The record's own length is what bounds its string offsets; an inflated
211 // one lets them read the following record's bytes as this cookie's value.
212 const pageStart = 8 + 4;
213 const recordStart = pageStart + valid.readUInt32LE(pageStart + 8);
214 const corrupt = Buffer.from(valid);
215 corrupt.writeUInt32LE(0xffff, recordStart);
216​
217 expect(() => parseBinaryCookies(corrupt)).toThrow(SafariCookieReadError);
218 });
219​
220 it("rejects records truncated inside the 56-byte header", () => {
221 const valid = encodeBinaryCookies([
222 { domain: "a.test", name: "n", path: "/", value: "v", expiry: 1_000, flags: 0 },
223 ]);
224 const pageStart = 8 + 4;
225 const recordStart = pageStart + valid.readUInt32LE(pageStart + 8);
226​
227 for (let size = 48; size < 56; size += 1) {
228 const corrupt = Buffer.from(valid);
229 corrupt.writeUInt32LE(size, recordStart);
230 expect(() => parseBinaryCookies(corrupt), `record size ${size}`).toThrow(
231 SafariCookieReadError,
232 );
233 }
234 });
235​
236 it("rejects record offsets that point into the page header or an earlier record", () => {
237 const valid = encodeBinaryCookies([
238 { domain: "a.test", name: "n", path: "/", value: "v", expiry: 1_000, flags: 0 },
239 { domain: "b.test", name: "m", path: "/", value: "w", expiry: 1_000, flags: 0 },
240 ]);
241 const pageStart = 8 + 4;
242 const firstRecord = valid.readUInt32LE(pageStart + 8);
243​
244 // Pointing the second offset at the page's offset table would let those
245 // table bytes parse as a fabricated record.
246 const intoTable = Buffer.from(valid);
247 intoTable.writeUInt32LE(4, pageStart + 12);
248 expect(() => parseBinaryCookies(intoTable)).toThrow(SafariCookieReadError);
249​
250 // Pointing it back at the first record makes the same bytes count twice.
251 const overlapping = Buffer.from(valid);
252 overlapping.writeUInt32LE(firstRecord, pageStart + 12);
253 expect(() => parseBinaryCookies(overlapping)).toThrow(SafariCookieReadError);
254​
255 // And a well-formed two-record page still parses.
256 expect(parseBinaryCookies(valid)).toHaveLength(2);
257 });
258​
259 it("rejects string offsets that point into the record header", () => {
260 const valid = encodeBinaryCookies([
261 { domain: "a.test", name: "n", path: "/", value: "v", expiry: 1_000, flags: 0 },
262 ]);
263 const pageStart = 8 + 4;
264 const recordStart = pageStart + valid.readUInt32LE(pageStart + 8);
265​
266 for (const offsetField of [16, 20, 24, 28]) {
267 const corrupt = Buffer.from(valid);
268 corrupt.writeUInt32LE(55, recordStart + offsetField);
269 expect(() => parseBinaryCookies(corrupt), `offset field ${offsetField}`).toThrow(
270 SafariCookieReadError,
271 );
272 }
273 });
274​
275 it("accepts the checksum and property-list trailer Safari writes", () => {
276 const file = encodeBinaryCookies([
277 { domain: "a.test", name: "c", path: "/", value: "v", flags: 0, expiry: 0 },
278 ]);
279 const checksum = Buffer.alloc(8);
280 const plist = Buffer.from("bplist00 stub");
281 const plistLength = Buffer.alloc(4);
282 plistLength.writeUInt32BE(plist.length, 0);
283​
284 expect(parseBinaryCookies(Buffer.concat([file, checksum]))).toHaveLength(1);
285 expect(parseBinaryCookies(Buffer.concat([file, checksum, plistLength, plist]))).toHaveLength(1);
286 });
287​
288 it("rejects a jar whose page table stops short of its contents", () => {
289 // A second, undeclared page after the first would be silently dropped —
290 // the cookies it holds vanish from the import with no error — so a file
291 // the header does not fully describe is refused instead.
292 const first = encodeBinaryCookies([
293 { domain: "a.test", name: "c", path: "/", value: "v", flags: 0, expiry: 0 },
294 ]);
295 const extraPage = encodeBinaryCookies([
296 { domain: "b.test", name: "d", path: "/", value: "w", flags: 0, expiry: 0 },
297 ]).subarray(12);
298​
299 expect(() => parseBinaryCookies(Buffer.concat([first, extraPage]))).toThrow(
300 SafariCookieReadError,
301 );
302 // A trailer that claims a property list it doesn't contain is refused too.
303 const badLength = Buffer.alloc(4);
304 badLength.writeUInt32BE(99, 0);
305 expect(() =>
306 parseBinaryCookies(Buffer.concat([first, Buffer.alloc(8), badLength, Buffer.from("x")])),
307 ).toThrow(SafariCookieReadError);
308 });
309​
310 it("rejects a file that is not binarycookies", () => {
311 expect(() => parseBinaryCookies(Buffer.from("not a cookie jar"))).toThrow(
312 SafariCookieReadError,
313 );
314 });
315});
316​
317describe("readSafariCookies", () => {
318 it.effect("adds the cookie path and parser cause to malformed jar failures", () =>
319 Effect.gen(function* () {
320 const fileSystem = yield* FileSystem.FileSystem;
321 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-safari-" });
322 const jar = `${directory}/Cookies.binarycookies`;
323 yield* fileSystem.writeFileString(jar, "not a cookie jar");
324​
325 const error = yield* readSafariCookies(jar).pipe(Effect.flip);
326​
327 assert.equal(error.reason, "readFailed");
328 assert.equal(error.cookieDatabasePath, jar);
329 assert.instanceOf(error.cause, SafariCookieReadError);
330 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
331 );
332​
333 it.effect("reports a TCC denial as a permission the user can grant", () =>
334 Effect.gen(function* () {
335 // What Full Disk Access actually looks like: the file is there, the read
336 // is refused with EPERM. Effect tags that `Unknown`, not
337 // `PermissionDenied`, so the reader has to look at the errno. Reporting
338 // it as a generic failure would send the user looking for a missing
339 // browser instead of a checkbox.
340 const denied = PlatformError.systemError({
341 _tag: "Unknown",
342 module: "FileSystem",
343 method: "readFile",
344 pathOrDescriptor: "/protected/Cookies.binarycookies",
345 cause: Object.assign(new Error("operation not permitted"), { code: "EPERM" }),
346 });
347​
348 const error = yield* readSafariCookies("/protected/Cookies.binarycookies").pipe(
349 Effect.flip,
350 Effect.provide(FileSystem.layerNoop({ readFile: () => Effect.fail(denied) })),
351 );
352​
353 assert.equal(error.reason, "needsFullDiskAccess");
354 }),
355 );
356​
357 it.effect("reports an ordinary permission failure as a plain read failure", () =>
358 Effect.gen(function* () {
359 const fileSystem = yield* FileSystem.FileSystem;
360 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-safari-" });
361 const jar = `${directory}/Cookies.binarycookies`;
362 yield* fileSystem.writeFile(jar, new Uint8Array([0x63, 0x6f, 0x6f, 0x6b]));
363 // A mode-bits refusal is EACCES: granting Full Disk Access cannot fix
364 // it, so it must not be routed to that grant.
365 yield* fileSystem.chmod(jar, 0o000);
366​
367 const error = yield* readSafariCookies(jar).pipe(Effect.flip);
368​
369 assert.equal(error.reason, "readFailed");
370 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
371 );
372​
373 it.effect("reports a missing jar as a plain read failure", () =>
374 Effect.gen(function* () {
375 const fileSystem = yield* FileSystem.FileSystem;
376 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-safari-" });
377​
378 const error = yield* readSafariCookies(`${directory}/absent.binarycookies`).pipe(Effect.flip);
379​
380 assert.equal(error.reason, "readFailed");
381 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
382 );
383});
384​
385describe("safariAccessDenied", () => {
386 const eperm = PlatformError.systemError({
387 _tag: "Unknown",
388 module: "FileSystem",
389 method: "open",
390 pathOrDescriptor: "/protected/Cookies.binarycookies",
391 cause: Object.assign(new Error("operation not permitted"), { code: "EPERM" }),
392 });
393 const denied = (error: PlatformError.PlatformError) =>
394 FileSystem.layerNoop({ open: () => Effect.fail(error) });
395​
396 it.effect("reports TCC's EPERM as a missing Full Disk Access grant", () =>
397 Effect.gen(function* () {
398 // `stat` finds the jar without the grant, so only an open tells the
399 // listing whether the import would actually be allowed.
400 assert.isTrue(
401 yield* safariAccessDenied("/protected/Cookies.binarycookies").pipe(
402 Effect.provide(denied(eperm)),
403 ),
404 );
405 }),
406 );
407​
408 it.effect("does not read a readable jar, or any other failure, as denied", () =>
409 Effect.gen(function* () {
410 const fileSystem = yield* FileSystem.FileSystem;
411 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-safari-" });
412 const jar = `${directory}/Cookies.binarycookies`;
413 yield* fileSystem.writeFile(jar, new Uint8Array([0x63, 0x6f, 0x6f, 0x6b]));
414 assert.isFalse(yield* safariAccessDenied(jar));
415 // Missing entirely is "not installed", not "denied".
416 assert.isFalse(yield* safariAccessDenied(`${directory}/absent.binarycookies`));
417 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
418 );
419});
420​
421describe("isPermissionDenied", () => {
422 // Shapes taken from a real `FileSystem.readFile` failure on macOS — verified
423 // against Safari's TCC-protected jar, whose denial is EPERM, tagged
424 // `Unknown` rather than `PermissionDenied`.
425 const platformError = (reasonTag: string, code: string): PlatformError.PlatformError =>
426 ({ _tag: "PlatformError", reason: { _tag: reasonTag, cause: { code } } }) as never;
427​
428 it("treats a TCC EPERM denial as permission denied", () => {
429 // The regression: EPERM is tagged `Unknown`, so checking the tag alone
430 // reported Safari's Full Disk Access refusal as a generic read failure.
431 expect(isPermissionDenied(platformError("Unknown", "EPERM"))).toBe(true);
432 });
433​
434 it("does not send an ordinary EACCES failure to the Full Disk Access grant", () => {
435 // A POSIX permission or ACL refusal cannot be fixed by granting Full Disk
436 // Access, so it stays a plain read failure; only TCC's EPERM routes there.
437 expect(isPermissionDenied(platformError("PermissionDenied", "EACCES"))).toBe(false);
438 });
439​
440 it("does not treat an unrelated failure as permission denied", () => {
441 expect(isPermissionDenied(platformError("Unknown", "EIO"))).toBe(false);
442 });
443});