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

CookieDatabase.ts

67 lines2.5 KB

1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Path from "effect/Path";
4import * as SqlClient from "effect/sql/SqlClient";
5​
6import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
7​
8export interface ImportedCookie {
9 readonly url: string;
10 readonly name: string;
11 readonly value: string;
12 /**
13 * A host-only cookie leaves this undefined: Electron treats any `domain` it is given as marking a
14 * domain cookie and re-adds the dot, which would widen the cookie to every subdomain of the host
15 * it was scoped to, and rejects `__Host-` cookies, which require it to be absent.
16 */
17 readonly domain: string | undefined;
18 readonly path: string;
19 readonly secure: boolean;
20 readonly httpOnly: boolean;
21 readonly expirationDate: number | undefined;
22 readonly sameSite: "unspecified" | "no_restriction" | "lax" | "strict";
24​
25export interface CookieReadResult {
26 readonly cookies: ReadonlyArray<ImportedCookie>;
27 readonly undecryptable: number;
28 readonly undecryptableHosts: ReadonlyArray<string>;
30​
31export const cookieScope = (
32 host: string,
33 path: string,
34 secure: boolean,
35): { readonly url: string; readonly domain: string | undefined } => {
36 const isDomainCookie = host.startsWith(".");
37 const unwrappedHost = bareHost(host);
38 const authority =
39 unwrappedHost.includes(":") && !(unwrappedHost.startsWith("[") && unwrappedHost.endsWith("]"))
40 ? `[${unwrappedHost}]`
41 : unwrappedHost;
42 return {
43 url: `${secure ? "https" : "http"}://${authority}${path}`,
44 domain: isDomainCookie ? host : undefined,
45 };
46};
47​
48export const bareHost = (host: string): string => (host.startsWith(".") ? host.slice(1) : host);
49​
50/**
51 * Both engines keep the file open with WAL while the browser runs, so reading in place can observe
52 * a torn write. Copying also guarantees we never open the browser's own file for writing.
53 */
54export const snapshotCookieDatabase = Effect.fn("CookieDatabase.snapshotCookieDatabase")(function* (
55 cookiePath: string,
56 tempPrefix = "t3code-cookie-import-",
57) {
58 const fileSystem = yield* FileSystem.FileSystem;
59 const path = yield* Path.Path;
60 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: tempPrefix });
61 const target = path.join(directory, path.basename(cookiePath));
62 yield* Effect.gen(function* () {
63 const sql = yield* SqlClient.SqlClient;
64 yield* sql`VACUUM INTO ${target}`;
65 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: cookiePath, readonly: true })));
66 return target;
67});