The best way to control Claude Code, Codex and more from any computer or phone

main
ts 196 lines 7.14 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as FileSystem from "effect/FileSystem";
3 import * as PlatformError from "effect/PlatformError";
4 import * as Schema from "effect/Schema";
5
6 import { cookieScope, type ImportedCookie } from "./CookieDatabase.ts";
7
8 /** Safari's timestamps count seconds from 2001-01-01, not the UNIX epoch. */
9 const APPLE_EPOCH_OFFSET_SECONDS = 978_307_200;
10
11 const COOKIE_PAGE_HEADER_SIZE = 12;
12 const COOKIE_RECORD_HEADER_SIZE = 56;
13
14 const FLAG_SECURE = 0x1;
15 const FLAG_HTTP_ONLY = 0x4;
16
17 export const SafariCookieReadFailure = Schema.Literals(["needsFullDiskAccess", "readFailed"]);
18 export type SafariCookieReadFailure = typeof SafariCookieReadFailure.Type;
19
20 export class SafariCookieReadError extends Schema.TaggedError<SafariCookieReadError>()(
21 "SafariCookieReadError",
22 {
23 reason: SafariCookieReadFailure,
24 cookieDatabasePath: Schema.optional(Schema.String),
25 cause: Schema.optional(Schema.Defect()),
26 },
27 ) {
28 override get message(): string {
29 return this.cookieDatabasePath === undefined
30 ? `Could not read Safari cookies: ${this.reason}.`
31 : `Could not read Safari cookies at ${this.cookieDatabasePath}: ${this.reason}.`;
32 }
33 }
34
35 const isSafariCookieReadError = Schema.is(SafariCookieReadError);
36
37 function readCString(buffer: Buffer, start: number): string {
38 const end = buffer.indexOf(0, start);
39 return buffer.toString("utf8", start, end === -1 ? buffer.length : end);
40 }
41
42 export function parseBinaryCookies(buffer: Buffer): ReadonlyArray<ImportedCookie> {
43 if (buffer.length < 8 || buffer.toString("latin1", 0, 4) !== "cook") {
44 throw new SafariCookieReadError({ reason: "readFailed" });
45 }
46
47 const pageCount = buffer.readUInt32BE(4);
48 // Buffer.subarray silently clamps invalid bounds, so reject truncated pages and overlapping records.
49 if (8 + pageCount * 4 > buffer.length) {
50 throw new SafariCookieReadError({ reason: "readFailed" });
51 }
52 const pageSizes: number[] = [];
53 for (let index = 0; index < pageCount; index += 1) {
54 pageSizes.push(buffer.readUInt32BE(8 + index * 4));
55 }
56
57 const cookies: ImportedCookie[] = [];
58 let pageStart = 8 + pageCount * 4;
59
60 for (const pageSize of pageSizes) {
61 if (pageSize < COOKIE_PAGE_HEADER_SIZE || pageStart + pageSize > buffer.length) {
62 throw new SafariCookieReadError({ reason: "readFailed" });
63 }
64 const page = buffer.subarray(pageStart, pageStart + pageSize);
65 pageStart += pageSize;
66
67 // Page bodies switch to little-endian after the big-endian header.
68 const cookieCount = page.readUInt32LE(4);
69 const offsetTableEnd = COOKIE_PAGE_HEADER_SIZE + cookieCount * 4;
70 if (offsetTableEnd > page.length) {
71 throw new SafariCookieReadError({ reason: "readFailed" });
72 }
73 // Reject offsets into the header, table, or earlier records to avoid fabricated cookies.
74 const accepted: Array<readonly [start: number, end: number]> = [];
75 for (let index = 0; index < cookieCount; index += 1) {
76 const cookieStart = page.readUInt32LE(8 + index * 4);
77 if (cookieStart < offsetTableEnd || cookieStart + COOKIE_RECORD_HEADER_SIZE > page.length) {
78 throw new SafariCookieReadError({ reason: "readFailed" });
79 }
80 const recordSize = page.readUInt32LE(cookieStart);
81 const cookieEnd = cookieStart + recordSize;
82 if (
83 recordSize < COOKIE_RECORD_HEADER_SIZE ||
84 cookieEnd > page.length ||
85 accepted.some(([start, end]) => cookieStart < end && cookieEnd > start)
86 ) {
87 throw new SafariCookieReadError({ reason: "readFailed" });
88 }
89 accepted.push([cookieStart, cookieEnd]);
90 const cookie = page.subarray(cookieStart, cookieEnd);
91
92 const flags = cookie.readUInt32LE(8);
93 const urlOffset = cookie.readUInt32LE(16);
94 const nameOffset = cookie.readUInt32LE(20);
95 const pathOffset = cookie.readUInt32LE(24);
96 const valueOffset = cookie.readUInt32LE(28);
97 const expiry = cookie.readDoubleLE(40);
98
99 if (
100 [urlOffset, nameOffset, pathOffset, valueOffset].some(
101 (offset) => offset < COOKIE_RECORD_HEADER_SIZE || offset >= cookie.length,
102 )
103 ) {
104 throw new SafariCookieReadError({ reason: "readFailed" });
105 }
106 const domain = readCString(cookie, urlOffset);
107 const name = readCString(cookie, nameOffset);
108 const path = readCString(cookie, pathOffset);
109 const value = readCString(cookie, valueOffset);
110 if (domain === "" || name === "") continue;
111
112 const secure = (flags & FLAG_SECURE) !== 0;
113 const expirationDate =
114 expiry > 0 ? Math.floor(expiry) + APPLE_EPOCH_OFFSET_SECONDS : undefined;
115
116 cookies.push({
117 ...cookieScope(domain, path || "/", secure),
118 name,
119 value,
120 path: path || "/",
121 secure,
122 httpOnly: (flags & FLAG_HTTP_ONLY) !== 0,
123 expirationDate,
124 // Safari's SameSite flag encoding is undocumented; guessing None would widen cookie scope.
125 sameSite: "lax",
126 });
127 }
128 }
129
130 // Pages end with an 8-byte checksum and an optional length-prefixed plist.
131 const trailer = buffer.length - pageStart;
132 const validTrailer =
133 trailer === 0 ||
134 trailer === 8 ||
135 (trailer >= 12 && trailer === 8 + 4 + buffer.readUInt32BE(pageStart + 8));
136 if (!validTrailer) {
137 throw new SafariCookieReadError({ reason: "readFailed" });
138 }
139
140 return cookies;
141 }
142
143 export const isPermissionDenied = (error: PlatformError.PlatformError): boolean => {
144 // TCC returns EPERM (Effect Unknown); EACCES is a POSIX denial that Full Disk Access cannot fix.
145 const code = (error.reason as { cause?: { code?: unknown } }).cause?.code;
146 return code === "EPERM";
147 };
148
149 /** stat succeeds without Full Disk Access, so presence alone does not prove readable cookies. */
150 export const safariAccessDenied = Effect.fnUntraced(function* (cookiePath: string) {
151 const fileSystem = yield* FileSystem.FileSystem;
152 return yield* fileSystem.open(cookiePath, { flag: "r" }).pipe(
153 Effect.as(false),
154 Effect.catch((cause) => Effect.succeed(isPermissionDenied(cause))),
155 Effect.scoped,
156 );
157 });
158
159 export const safariAccessGranted = Effect.fnUntraced(function* (cookiePath: string) {
160 const fileSystem = yield* FileSystem.FileSystem;
161 return yield* fileSystem.open(cookiePath, { flag: "r" }).pipe(
162 Effect.as(true),
163 Effect.orElseSucceed(() => false),
164 Effect.scoped,
165 );
166 });
167
168 export const readSafariCookies = Effect.fn("SafariCookies.readSafariCookies")(function* (
169 cookiePath: string,
170 ) {
171 const fileSystem = yield* FileSystem.FileSystem;
172 const contents = yield* fileSystem.readFile(cookiePath).pipe(
173 Effect.mapError((cause) => {
174 return new SafariCookieReadError({
175 reason: isPermissionDenied(cause) ? "needsFullDiskAccess" : "readFailed",
176 cookieDatabasePath: cookiePath,
177 cause,
178 });
179 }),
180 );
181 return yield* Effect.try({
182 try: () => parseBinaryCookies(Buffer.from(contents)),
183 catch: (cause) =>
184 isSafariCookieReadError(cause)
185 ? new SafariCookieReadError({
186 reason: cause.reason,
187 cookieDatabasePath: cookiePath,
188 cause,
189 })
190 : new SafariCookieReadError({
191 reason: "readFailed",
192 cookieDatabasePath: cookiePath,
193 cause,
194 }),
195 });
196 });