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