Open History to see the last commit
1import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
2import * as Effect from "effect/Effect";
3import * as Schema from "effect/Schema";
4import * as SqlClient from "effect/sql/SqlClient";
5
6import { cookieScope, snapshotCookieDatabase, type ImportedCookie } from "./CookieDatabase.ts";
7
8export class FirefoxCookieReadError extends Schema.TaggedError<FirefoxCookieReadError>()(
9 "FirefoxCookieReadError",
10 {
11 cookieDatabasePath: Schema.String,
12 cause: Schema.Defect(),
13 },
14) {
15 override get message(): string {
16 return `Could not read Firefox cookies at ${this.cookieDatabasePath}.`;
17 }
18}
19
20/**
21 * Unset is not the same thing as None — None is an explicit opt-in to
22 * cross-site use — so it is imported as Electron's `unspecified`, which lets
23 * the target browser apply its own default exactly as Firefox did. Anything
24 * unrecognised also lands there rather than on `no_restriction`, since guessing
25 * "none" would widen a cookie's scope on import.
26 */
27const SAMESITE_NONE = 0;
28const SAMESITE_LAX = 1;
29const SAMESITE_STRICT = 2;
30
31/**
32 * Schemas 10–14 carried a second column, `rawSameSite`: the value the cookie
33 * actually declared, beside a `sameSite` that Firefox had already defaulted to
34 * Lax. Reading such a database before Firefox has migrated it must apply the
35 * same rule, or an undeclared cookie is imported as an explicit Lax.
36 */
37const FIREFOX_RAW_SAMESITE_FIRST_SCHEMA = 10;
38const FIREFOX_RAW_SAMESITE_LAST_SCHEMA = 14;
39
40const sameSiteFromColumn = (
41 value: number | null,
42 rawValue: number | null,
43): ImportedCookie["sameSite"] => {
44 // Schema 9 added the column with no default, so older rows carry NULL.
45 if (value === null) return "unspecified";
46 if (value === SAMESITE_LAX && rawValue === SAMESITE_NONE) return "unspecified";
47 if (value === SAMESITE_NONE) return "no_restriction";
48 if (value === SAMESITE_LAX) return "lax";
49 if (value === SAMESITE_STRICT) return "strict";
50 return "unspecified";
51};
52
53const CookieRow = Schema.Struct({
54 host: Schema.String,
55 name: Schema.String,
56 value: Schema.String,
57 path: Schema.String,
58 expiry: Schema.Number,
59 isSecure: Schema.Number,
60 isHttpOnly: Schema.Number,
61 sameSite: Schema.NullOr(Schema.Number),
62 rawSameSite: Schema.NullOr(Schema.Number),
63});
64const decodeCookieRows = Schema.decodeUnknownEffect(Schema.Array(CookieRow));
65
66/**
67 * Firefox schema 16 (Firefox 129) moved `expiry` from seconds to milliseconds
68 * — the migration is `UPDATE moz_cookies SET expiry = expiry * 1000`. Electron
69 * wants seconds, so the unit is decided by `PRAGMA user_version` rather than
70 * assumed: importing a pre-16 profile as milliseconds would expire every cookie
71 * at once, and a post-16 one as seconds would keep them for ~1000× too long.
72 */
73const FIREFOX_EXPIRY_MILLISECONDS_SCHEMA = 16;
74
75const UserVersionRow = Schema.Struct({ user_version: Schema.Number });
76const decodeUserVersion = Schema.decodeUnknownEffect(Schema.Array(UserVersionRow));
77
78const expiryToSeconds = (expiry: number, schemaVersion: number): number | undefined => {
79 if (expiry <= 0) return undefined;
80 return schemaVersion >= FIREFOX_EXPIRY_MILLISECONDS_SCHEMA ? Math.floor(expiry / 1000) : expiry;
81};
82
83export const readFirefoxCookies = Effect.fn("FirefoxCookies.readFirefoxCookies")(
84 function* (cookieDatabasePath: string) {
85 const snapshotPath = yield* snapshotCookieDatabase(cookieDatabasePath);
86
87 const { rows, schemaVersion } = yield* Effect.gen(function* () {
88 const sql = yield* SqlClient.SqlClient;
89 const [versionRow] = yield* decodeUserVersion(yield* sql`pragma user_version`);
90 const schemaVersion = versionRow?.user_version ?? 0;
91 const hasRawSameSite =
92 schemaVersion >= FIREFOX_RAW_SAMESITE_FIRST_SCHEMA &&
93 schemaVersion <= FIREFOX_RAW_SAMESITE_LAST_SCHEMA;
94 // Firefox isolates cookies per container and per private window via
95 // `originAttributes` (`^userContextId=2`, `^privateBrowsingId=1`);
96 // Electron has no equivalent, so importing them all would collapse
97 // several identities onto one host/name/path and hand the profile an
98 // arbitrary container's session.
99 const raw = hasRawSameSite
100 ? yield* sql`
101 select host, name, value, path, expiry, isSecure, isHttpOnly, sameSite, rawSameSite
102 from moz_cookies
103 where originAttributes = ''
104 `
105 : yield* sql`
106 select host, name, value, path, expiry, isSecure, isHttpOnly, sameSite,
107 null as rawSameSite
108 from moz_cookies
109 where originAttributes = ''
110 `;
111 return { rows: yield* decodeCookieRows(raw), schemaVersion };
112 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath, readonly: true })));
113
114 return rows.map((row) => {
115 const secure = row.isSecure === 1;
116 const scope = cookieScope(row.host, row.path, secure);
117 return {
118 url: scope.url,
119 name: row.name,
120 value: row.value,
121 domain: scope.domain,
122 path: row.path,
123 secure,
124 httpOnly: row.isHttpOnly === 1,
125 expirationDate: expiryToSeconds(row.expiry, schemaVersion),
126 sameSite: sameSiteFromColumn(row.sameSite, row.rawSameSite),
127 } satisfies ImportedCookie;
128 });
129 },
130 (effect, cookieDatabasePath) =>
131 effect.pipe(
132 Effect.mapError((cause) => new FirefoxCookieReadError({ cookieDatabasePath, cause })),
133 ),
134);