The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | // @effect-diagnostics nodeBuiltinImport:off - `node:crypto` implements the |
| 2 | // OSCrypt primitives Chromium uses; Effect has no equivalent. |
| 3 | import * as NodeCrypto from "node:crypto"; |
| 4 | |
| 5 | import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as FileSystem from "effect/FileSystem"; |
| 8 | import * as Path from "effect/Path"; |
| 9 | import * as Schema from "effect/Schema"; |
| 10 | import * as Scope from "effect/Scope"; |
| 11 | import * as SqlClient from "effect/sql/SqlClient"; |
| 12 | import { ChildProcessSpawner } from "effect/process"; |
| 13 | |
| 14 | import { |
| 15 | ChromiumKeyError, |
| 16 | ChromiumKeyFailure, |
| 17 | readWindowsKey, |
| 18 | resolveChromiumKeys, |
| 19 | type ChromiumKeyMaterial, |
| 20 | } from "./ChromiumKeys.ts"; |
| 21 | import { |
| 22 | bareHost, |
| 23 | cookieScope, |
| 24 | snapshotCookieDatabase, |
| 25 | type CookieReadResult, |
| 26 | type ImportedCookie, |
| 27 | } from "./CookieDatabase.ts"; |
| 28 | |
| 29 | /** OSCrypt's CBC mode uses a fixed IV of 16 spaces rather than a per-record one. */ |
| 30 | const AES_CBC_IV = Buffer.alloc(16, 0x20); |
| 31 | const AES_GCM_NONCE_LENGTH = 12; |
| 32 | const AES_GCM_TAG_LENGTH = 16; |
| 33 | const isChromiumKeyError = Schema.is(ChromiumKeyError); |
| 34 | |
| 35 | export const ChromiumCookieReadReason = Schema.Literals([ |
| 36 | ...ChromiumKeyFailure.literals, |
| 37 | "browserRunning", |
| 38 | ]); |
| 39 | export type ChromiumCookieReadReason = typeof ChromiumCookieReadReason.Type; |
| 40 | |
| 41 | export class ChromiumCookieReadError extends Schema.TaggedError<ChromiumCookieReadError>()( |
| 42 | "ChromiumCookieReadError", |
| 43 | { |
| 44 | reason: ChromiumCookieReadReason, |
| 45 | cookieDatabasePath: Schema.String, |
| 46 | cause: Schema.optional(Schema.Defect()), |
| 47 | }, |
| 48 | ) { |
| 49 | override get message(): string { |
| 50 | return `Could not read Chromium cookies at ${this.cookieDatabasePath}: ${this.reason}.`; |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | const CookieRow = Schema.Struct({ |
| 55 | host_key: Schema.String, |
| 56 | name: Schema.String, |
| 57 | value: Schema.String, |
| 58 | encrypted_value: Schema.Uint8Array, |
| 59 | path: Schema.String, |
| 60 | expires_seconds: Schema.Number, |
| 61 | is_secure: Schema.Number, |
| 62 | is_httponly: Schema.Number, |
| 63 | samesite: Schema.Number, |
| 64 | top_frame_site_key: Schema.String, |
| 65 | }); |
| 66 | const decodeCookieRows = Schema.decodeUnknownEffect(Schema.Array(CookieRow)); |
| 67 | const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); |
| 68 | const SchemaVersion = Schema.Union([ |
| 69 | NonNegativeInt, |
| 70 | Schema.FiniteFromString.pipe(Schema.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))), |
| 71 | ]); |
| 72 | const decodeSchemaVersion = Schema.decodeUnknownEffect( |
| 73 | Schema.Tuple([Schema.Struct({ value: SchemaVersion })]), |
| 74 | ); |
| 75 | |
| 76 | /** Preserve unspecified SameSite; guessing no_restriction would widen cookie scope. */ |
| 77 | const sameSiteFromColumn = (value: number): ImportedCookie["sameSite"] => { |
| 78 | if (value === 0) return "no_restriction"; |
| 79 | if (value === 1) return "lax"; |
| 80 | if (value === 2) return "strict"; |
| 81 | return "unspecified"; |
| 82 | }; |
| 83 | |
| 84 | /** Convert microseconds in SQL: node:sqlite refuses integers beyond JavaScript's safe range. */ |
| 85 | const WEBKIT_EPOCH_OFFSET_SECONDS = 11_644_473_600; |
| 86 | const toUnixSeconds = (webkitSeconds: number): number | undefined => { |
| 87 | if (webkitSeconds <= 0) return undefined; |
| 88 | return webkitSeconds - WEBKIT_EPOCH_OFFSET_SECONDS; |
| 89 | }; |
| 90 | |
| 91 | // Chromium 127+ prefixes plaintext with the host-key SHA-256 to bind its domain. |
| 92 | const stripDomainBinding = ( |
| 93 | plaintext: Buffer, |
| 94 | domain: string, |
| 95 | schemaVersion: number, |
| 96 | ): Buffer | null => { |
| 97 | if (schemaVersion < 24) return plaintext; |
| 98 | const domainHash = NodeCrypto.createHash("sha256").update(domain).digest(); |
| 99 | return plaintext.length >= 32 && plaintext.subarray(0, 32).equals(domainHash) |
| 100 | ? plaintext.subarray(32) |
| 101 | : null; |
| 102 | }; |
| 103 | |
| 104 | const decryptCbc = ( |
| 105 | payload: Buffer, |
| 106 | key: Buffer, |
| 107 | domain: string, |
| 108 | schemaVersion: number, |
| 109 | ): string | null => { |
| 110 | try { |
| 111 | const decipher = NodeCrypto.createDecipheriv("aes-128-cbc", key, AES_CBC_IV); |
| 112 | decipher.setAutoPadding(true); |
| 113 | const plaintext = Buffer.concat([decipher.update(payload), decipher.final()]); |
| 114 | return stripDomainBinding(plaintext, domain, schemaVersion)?.toString("utf8") ?? null; |
| 115 | } catch { |
| 116 | return null; |
| 117 | } |
| 118 | }; |
| 119 | |
| 120 | const decryptGcm = ( |
| 121 | payload: Buffer, |
| 122 | key: Buffer, |
| 123 | domain: string, |
| 124 | schemaVersion: number, |
| 125 | ): string | null => { |
| 126 | if (payload.length < AES_GCM_NONCE_LENGTH + AES_GCM_TAG_LENGTH) return null; |
| 127 | try { |
| 128 | const nonce = payload.subarray(0, AES_GCM_NONCE_LENGTH); |
| 129 | const ciphertext = payload.subarray(AES_GCM_NONCE_LENGTH, -AES_GCM_TAG_LENGTH); |
| 130 | const tag = payload.subarray(-AES_GCM_TAG_LENGTH); |
| 131 | const decipher = NodeCrypto.createDecipheriv("aes-256-gcm", key, nonce); |
| 132 | decipher.setAuthTag(tag); |
| 133 | const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]); |
| 134 | return stripDomainBinding(plaintext, domain, schemaVersion)?.toString("utf8") ?? null; |
| 135 | } catch { |
| 136 | return null; |
| 137 | } |
| 138 | }; |
| 139 | |
| 140 | export function decryptChromiumValue( |
| 141 | encrypted: Uint8Array, |
| 142 | keys: ChromiumKeyMaterial, |
| 143 | domain: string, |
| 144 | schemaVersion = 23, |
| 145 | platform: NodeJS.Platform = "linux", |
| 146 | ): string | null { |
| 147 | const buffer = Buffer.from(encrypted); |
| 148 | if (buffer.length === 0) return ""; |
| 149 | const prefix = buffer.subarray(0, 3).toString("latin1"); |
| 150 | const payload = buffer.subarray(3); |
| 151 | |
| 152 | // Windows v10 uses AES-256-GCM; app-bound v20 records have no key here. |
| 153 | if (platform === "win32") { |
| 154 | return prefix === "v10" && keys.gcmV10 |
| 155 | ? decryptGcm(payload, keys.gcmV10, domain, schemaVersion) |
| 156 | : null; |
| 157 | } |
| 158 | |
| 159 | // Retry the empty-passphrase key used by some Linux clients (crbug.com/1195256). |
| 160 | if (prefix === "v10") { |
| 161 | if (!keys.cbcV10) return null; |
| 162 | return ( |
| 163 | decryptCbc(payload, keys.cbcV10, domain, schemaVersion) ?? |
| 164 | (keys.cbcEmpty ? decryptCbc(payload, keys.cbcEmpty, domain, schemaVersion) : null) |
| 165 | ); |
| 166 | } |
| 167 | if (prefix === "v11") { |
| 168 | if (!keys.cbcV11) return null; |
| 169 | return ( |
| 170 | decryptCbc(payload, keys.cbcV11, domain, schemaVersion) ?? |
| 171 | (keys.cbcEmpty ? decryptCbc(payload, keys.cbcEmpty, domain, schemaVersion) : null) |
| 172 | ); |
| 173 | } |
| 174 | if (platform === "darwin" || platform === "linux") { |
| 175 | return stripDomainBinding(buffer, domain, schemaVersion)?.toString("utf8") ?? null; |
| 176 | } |
| 177 | return null; |
| 178 | } |
| 179 | |
| 180 | export const readChromiumCookieDatabase = Effect.fn("ChromiumCookies.readChromiumCookieDatabase")( |
| 181 | function* (snapshotPath: string, keys: ChromiumKeyMaterial, platform: NodeJS.Platform) { |
| 182 | const result = yield* Effect.gen(function* () { |
| 183 | const sql = yield* SqlClient.SqlClient; |
| 184 | // Chromium razes a damaged jar to a file with no tables and rebuilds it on its next write. |
| 185 | const tables = |
| 186 | yield* sql`select 1 from sqlite_master where type = 'table' and name = 'cookies'`; |
| 187 | if (tables.length === 0) return { rows: [], schemaVersion: 0 }; |
| 188 | const schemaVersion = yield* sql`select value from meta where key = 'version' limit 1`.pipe( |
| 189 | Effect.flatMap(decodeSchemaVersion), |
| 190 | Effect.map(([row]) => row.value), |
| 191 | ); |
| 192 | const raw = |
| 193 | schemaVersion >= 15 |
| 194 | ? yield* sql`select host_key, name, value, encrypted_value, path, |
| 195 | expires_utc / 1000000 as expires_seconds, is_secure, is_httponly, |
| 196 | samesite, top_frame_site_key from cookies` |
| 197 | : yield* sql`select host_key, name, value, encrypted_value, path, |
| 198 | expires_utc / 1000000 as expires_seconds, is_secure, is_httponly, |
| 199 | samesite, '' as top_frame_site_key from cookies`; |
| 200 | return { rows: yield* decodeCookieRows(raw), schemaVersion }; |
| 201 | }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath, readonly: true }))); |
| 202 | |
| 203 | const cookies: ImportedCookie[] = []; |
| 204 | let undecryptable = 0; |
| 205 | const undecryptableHosts = new Set<string>(); |
| 206 | for (const row of result.rows) { |
| 207 | if (row.top_frame_site_key !== "") { |
| 208 | undecryptable += 1; |
| 209 | undecryptableHosts.add(bareHost(row.host_key)); |
| 210 | continue; |
| 211 | } |
| 212 | const value = |
| 213 | row.encrypted_value.length === 0 |
| 214 | ? row.value |
| 215 | : decryptChromiumValue( |
| 216 | row.encrypted_value, |
| 217 | keys, |
| 218 | row.host_key, |
| 219 | result.schemaVersion, |
| 220 | platform, |
| 221 | ); |
| 222 | if (value === null) { |
| 223 | undecryptable += 1; |
| 224 | undecryptableHosts.add(bareHost(row.host_key)); |
| 225 | continue; |
| 226 | } |
| 227 | const secure = row.is_secure === 1; |
| 228 | const scope = cookieScope(row.host_key, row.path, secure); |
| 229 | cookies.push({ |
| 230 | url: scope.url, |
| 231 | name: row.name, |
| 232 | value, |
| 233 | domain: scope.domain, |
| 234 | path: row.path, |
| 235 | secure, |
| 236 | httpOnly: row.is_httponly === 1, |
| 237 | expirationDate: toUnixSeconds(row.expires_seconds), |
| 238 | sameSite: sameSiteFromColumn(row.samesite), |
| 239 | }); |
| 240 | } |
| 241 | if ( |
| 242 | cookies.length === 0 && |
| 243 | keys.cbcV11Error !== undefined && |
| 244 | result.rows.some( |
| 245 | (row) => |
| 246 | row.top_frame_site_key === "" && |
| 247 | Buffer.from(row.encrypted_value.subarray(0, 3)).toString("latin1") === "v11", |
| 248 | ) |
| 249 | ) { |
| 250 | return yield* keys.cbcV11Error; |
| 251 | } |
| 252 | return { |
| 253 | cookies, |
| 254 | undecryptable, |
| 255 | undecryptableHosts: [...undecryptableHosts], |
| 256 | } satisfies CookieReadResult; |
| 257 | }, |
| 258 | ); |
| 259 | |
| 260 | export interface ChromiumCookieSource { |
| 261 | readonly cookieDatabasePath: string; |
| 262 | readonly keychainService: string | undefined; |
| 263 | readonly keychainAccount: string | undefined; |
| 264 | readonly linuxSecretApplication: string | undefined; |
| 265 | readonly windowsLocalStatePath?: string; |
| 266 | readonly platform: NodeJS.Platform; |
| 267 | } |
| 268 | |
| 269 | export const readChromiumCookies = Effect.fn("ChromiumCookies.readChromiumCookies")(function* ( |
| 270 | source: ChromiumCookieSource, |
| 271 | ): Effect.fn.Return< |
| 272 | CookieReadResult, |
| 273 | ChromiumCookieReadError, |
| 274 | FileSystem.FileSystem | Path.Path | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner |
| 275 | > { |
| 276 | const keys = yield* ( |
| 277 | source.platform === "win32" && source.windowsLocalStatePath |
| 278 | ? readWindowsKey(source.windowsLocalStatePath).pipe(Effect.map((gcmV10) => ({ gcmV10 }))) |
| 279 | : resolveChromiumKeys({ |
| 280 | platform: source.platform, |
| 281 | keychainService: source.keychainService, |
| 282 | keychainAccount: source.keychainAccount, |
| 283 | linuxSecretApplication: source.linuxSecretApplication, |
| 284 | }) |
| 285 | ).pipe( |
| 286 | Effect.mapError( |
| 287 | (cause: ChromiumKeyError) => |
| 288 | new ChromiumCookieReadError({ |
| 289 | reason: cause.reason, |
| 290 | cookieDatabasePath: source.cookieDatabasePath, |
| 291 | cause, |
| 292 | }), |
| 293 | ), |
| 294 | ); |
| 295 | |
| 296 | const snapshotPath = yield* snapshotCookieDatabase(source.cookieDatabasePath).pipe( |
| 297 | Effect.mapError( |
| 298 | (cause) => |
| 299 | new ChromiumCookieReadError({ |
| 300 | reason: "readFailed", |
| 301 | cookieDatabasePath: source.cookieDatabasePath, |
| 302 | cause, |
| 303 | }), |
| 304 | ), |
| 305 | ); |
| 306 | |
| 307 | return yield* readChromiumCookieDatabase(snapshotPath, keys, source.platform).pipe( |
| 308 | Effect.mapError( |
| 309 | (cause) => |
| 310 | new ChromiumCookieReadError({ |
| 311 | reason: isChromiumKeyError(cause) ? cause.reason : "readFailed", |
| 312 | cookieDatabasePath: source.cookieDatabasePath, |
| 313 | cause, |
| 314 | }), |
| 315 | ), |
| 316 | ); |
| 317 | }); |