@mherod/get-cookie 4.2.0 → 4.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/browsers/getEncryptedChromeCookie.ts","../src/core/browsers/chrome/ChromeApplicationSupport.ts","../src/core/browsers/QuerySqliteThenTransform.ts","../src/core/browsers/listChromeProfiles.ts","../src/core/browsers/chrome/decrypt.ts","../src/core/browsers/chrome/getChromePassword.ts","../src/core/browsers/chrome/ChromeCookieQueryStrategy.ts","../src/core/browsers/firefox/FirefoxCookieQueryStrategy.ts","../src/core/browsers/safari/SafariCookieQueryStrategy.ts","../src/core/browsers/safari/BinaryCodableCookies.ts","../src/core/browsers/safari/BinaryCodableCookie.ts","../src/types/schemas.ts","../src/core/browsers/safari/BinaryCodablePage.ts","../src/core/browsers/safari/decodeBinaryCookies.ts","../src/core/cookies/queryCookies.ts","../src/core/cookies/getCookie.ts","../src/core/cookies/getChromeCookie.ts","../src/core/cookies/getFirefoxCookie.ts","../src/core/cookies/renderCookies.ts","../src/core/cookies/getGroupedRenderedCookies.ts","../src/core/cookies/getMergedRenderedCookies.ts"],"sourcesContent":["import { existsSync } from \"fs\";\nimport { join } from \"path\";\n\nimport glob from \"fast-glob\";\n\nimport { logError, logDebug, logOperationResult } from \"@utils/logHelpers\";\n\nimport type { CookieRow } from \"../../types/schemas\";\n\nimport { chromeApplicationSupport } from \"./chrome/ChromeApplicationSupport\";\nimport { querySqliteThenTransform } from \"./QuerySqliteThenTransform\";\n\ninterface ChromeCookieRow {\n encrypted_value: Buffer;\n name: string;\n host_key: string;\n expires_utc: number;\n}\n\ninterface GetEncryptedCookieOptions {\n name: string;\n domain: string;\n file?: string;\n}\n\ninterface SqlQuery {\n sql: string;\n params: string[];\n}\n\n/**\n * Validates if a path is a valid, existing file\n * @param path - Path to validate\n * @returns true if path is valid and file exists, false otherwise\n */\nfunction isValidFilePath(path: unknown): path is string {\n if (typeof path !== \"string\") {\n return false;\n }\n\n const trimmedPath = path.trim();\n if (trimmedPath.length === 0) {\n return false;\n }\n\n return existsSync(trimmedPath);\n}\n\n/**\n * Get paths to Chrome cookie files\n * @returns A promise that resolves to an array of file paths\n */\nasync function getCookieFiles(): Promise<string[]> {\n const patterns = [\n join(chromeApplicationSupport, \"Default/Cookies\"),\n join(chromeApplicationSupport, \"Profile */Cookies\"),\n join(chromeApplicationSupport, \"Profile Default/Cookies\"),\n ];\n\n const files: string[] = [];\n for (const pattern of patterns) {\n const matches = await glob(pattern);\n files.push(...matches);\n }\n\n logDebug(\"ChromeCookies\", \"Found cookie files\", {\n count: files.length,\n files,\n });\n return files;\n}\n\n/**\n * Builds the SQL query for retrieving cookies\n * @param name - Cookie name to search for\n * @param domain - Domain to filter by\n * @returns SQL query and parameters\n */\nfunction buildSqlQuery(name: string, domain: string): SqlQuery {\n const isWildcard = name === \"%\";\n const sql = isWildcard\n ? `SELECT name, encrypted_value, host_key, expires_utc FROM cookies WHERE host_key LIKE ?`\n : `SELECT name, encrypted_value, host_key, expires_utc FROM cookies WHERE name = ? AND host_key LIKE ?`;\n const params = isWildcard ? [`%${domain}%`] : [name, `%${domain}%`];\n\n return { sql, params };\n}\n\n/**\n * Processes a single cookie file to extract matching cookies\n * @param cookieFile - Path to the cookie file\n * @param name - Cookie name to search for\n * @param domain - Domain to filter by\n * @returns Array of matching cookies\n */\nasync function processCookieFile(\n cookieFile: string,\n name: string,\n domain: string,\n): Promise<CookieRow[]> {\n try {\n const { sql, params } = buildSqlQuery(name, domain);\n logDebug(\"ChromeCookies\", \"Executing query\", { sql, params });\n\n const rows = await querySqliteThenTransform<ChromeCookieRow, CookieRow>({\n file: cookieFile,\n sql,\n params,\n rowTransform: (row: ChromeCookieRow): CookieRow => ({\n name: row.name,\n domain: row.host_key,\n value: row.encrypted_value,\n expiry: row.expires_utc,\n }),\n });\n\n logOperationResult(\"QueryCookies\", true, {\n file: cookieFile,\n count: rows.length,\n });\n return rows;\n } catch (error) {\n logError(\"Failed to read cookie file\", error, { file: cookieFile });\n return [];\n }\n}\n\n/**\n * Retrieve encrypted cookies from Chrome's cookie store\n * @param options - Options for querying Chrome cookies\n * @param options.name - The name of the cookie to retrieve\n * @param options.domain - The domain to retrieve cookies from\n * @param options.file - Optional specific cookie file to query\n * @returns Promise resolving to array of encrypted cookies\n */\nexport async function getEncryptedChromeCookie({\n name,\n domain,\n file,\n}: GetEncryptedCookieOptions): Promise<CookieRow[]> {\n const cookieFiles =\n typeof file === \"string\" && file.length > 0\n ? [file]\n : await getCookieFiles();\n\n if (cookieFiles.length === 0) {\n logDebug(\"ChromeCookies\", \"No cookie files found\");\n return [];\n }\n\n const results: CookieRow[] = [];\n for (const cookieFile of cookieFiles) {\n if (!isValidFilePath(cookieFile)) {\n logDebug(\"ChromeCookies\", \"Cookie file missing or invalid\", {\n file: cookieFile,\n });\n continue;\n }\n\n const cookies = await processCookieFile(cookieFile, name, domain);\n results.push(...cookies);\n }\n\n logDebug(\"ChromeCookies\", \"Query complete\", { totalCookies: results.length });\n return results;\n}\n","import { homedir } from \"os\";\nimport { join } from \"path\";\n\n/**\n * The path to Chrome's application support directory on macOS\n * This constant is used to locate Chrome's profile and cookie storage directories\n * @throws {Error} If unable to determine user's home directory\n */\nexport const chromeApplicationSupport = (() => {\n const home = homedir();\n if (!home) {\n throw new Error(\"Unable to determine user home directory\");\n }\n return join(home, \"Library\", \"Application Support\", \"Google\", \"Chrome\");\n})();\n","// External imports\nimport BetterSqlite3, { Database } from \"better-sqlite3\";\n\n// Internal imports\nimport { logError } from \"@utils/logHelpers\";\n\ninterface QuerySqliteThenTransformOptions<TRow, TResult> {\n file: string;\n sql: string;\n params?: unknown[];\n rowFilter?: (row: TRow) => boolean;\n rowTransform?: (row: TRow) => TResult;\n}\n\nfunction openDatabase(file: string): Database {\n try {\n return new BetterSqlite3(file, { readonly: true, fileMustExist: true });\n } catch (error) {\n logError(\"Database open failed\", error, { file });\n throw error;\n }\n}\n\nfunction closeDatabase(db: Database): Promise<void> {\n try {\n db.close();\n return Promise.resolve();\n } catch (error) {\n logError(\"Database close failed\", error);\n return Promise.reject(\n error instanceof Error\n ? error\n : new Error(\"Failed to close database: Unknown error\"),\n );\n }\n}\n\n/**\n * Executes a SQL query on a SQLite database file and transforms the results\n * @param root0 - The options object containing query parameters\n * @param root0.file - The path to the SQLite database file\n * @param root0.sql - The SQL query to execute\n * @param root0.params - Optional parameters for the SQL query\n * @param root0.rowFilter - Optional function to filter rows from the result set\n * @param root0.rowTransform - Optional function to transform each row before returning\n * @returns A promise that resolves to an array of transformed results\n */\nexport async function querySqliteThenTransform<TRow, TResult>({\n file,\n sql,\n params,\n rowFilter,\n rowTransform,\n}: QuerySqliteThenTransformOptions<TRow, TResult>): Promise<TResult[]> {\n let db: Database | undefined;\n\n try {\n db = openDatabase(file);\n const stmt = db.prepare(sql);\n const rows = stmt.all(params) as TRow[];\n\n const filteredRows = rowFilter ? rows.filter(rowFilter) : rows;\n const transformedRows = rowTransform\n ? filteredRows.map(rowTransform)\n : (filteredRows as unknown as TResult[]);\n\n return transformedRows;\n } catch (error) {\n logError(\"Database query failed\", error, { file, sql });\n throw error;\n } finally {\n if (db) {\n await closeDatabase(db);\n }\n }\n}\n","// External imports\nimport { readFileSync } from \"fs\";\nimport { join } from \"path\";\n\nimport fg from \"fast-glob\";\n\n// Internal imports\nimport logger from \"@utils/logger\";\n\nimport { chromeApplicationSupport } from \"./chrome/ChromeApplicationSupport\";\n\nconst consola = logger.withTag(\"listChromeProfiles\");\n\n/**\n * Lists all Chrome profile paths that contain cookie files\n * @internal\n * @returns An array of absolute paths to Chrome cookie files\n * @throws {Error} If Chrome's application support directory cannot be accessed\n * @example\n * ```typescript\n * // Get all Chrome cookie file paths\n * const cookiePaths = listChromeProfilePaths();\n * // Returns: [\n * // '/Users/name/Library/Application Support/Chrome/Profile 1/Cookies',\n * // '/Users/name/Library/Application Support/Chrome/Profile 2/Cookies'\n * // ]\n *\n * // Handle errors\n * try {\n * const paths = listChromeProfilePaths();\n * } catch (error) {\n * console.error('Failed to access Chrome profiles:', error);\n * }\n * ```\n */\nexport function listChromeProfilePaths(): string[] {\n const files: string[] = fg.sync(`./**/Cookies`, {\n cwd: chromeApplicationSupport,\n absolute: true,\n });\n\n consola.debug(\"Found cookie files:\", files);\n return files;\n}\n\n/**\n * Chrome Local State file structure\n * @internal\n */\ninterface ChromeLocalState {\n profile: {\n info_cache: Record<string, ChromeProfileInfo>;\n };\n}\n\n/**\n * Chrome profile information structure\n * @property {string} name - The name of the profile\n * @property {number} active_time - Unix timestamp of last profile activity\n * @property {string} account_id - Unique identifier for the Chrome profile\n * @property {Record<string, unknown>} accountcapabilities - Account feature flags\n * @property {string} email - User's email address\n * @property {string} full_name - User's full name\n * @property {boolean} is_using_default_avatar - Whether using default profile picture\n * @property {boolean} is_using_default_name - Whether using default profile name\n * @property {string} last_downloaded_gaia_picture_url_with_size - Profile picture URL\n * @property {string} local_auth_credentials - Authentication credentials\n * @property {string} shortcut_name - Profile shortcut name\n * @property {string} user_name - Username associated with profile\n */\ninterface ChromeProfileInfo {\n /** The name of the profile */\n name: string;\n /** Unix timestamp of last profile activity */\n active_time: number;\n /** Unique identifier for the Chrome profile */\n account_id: string;\n /** Account feature flags */\n accountcapabilities: Record<string, unknown>;\n /** User's email address */\n email: string;\n /** User's full name */\n full_name: string;\n /** Whether using default profile picture */\n is_using_default_avatar: boolean;\n /** Whether using default profile name */\n is_using_default_name: boolean;\n /** Profile picture URL */\n last_downloaded_gaia_picture_url_with_size: string;\n /** Authentication credentials */\n local_auth_credentials: string;\n /** Profile shortcut name */\n shortcut_name: string;\n /** Username associated with profile */\n user_name: string;\n}\n\n/**\n * Lists all Chrome profiles and their associated information\n * @internal\n * @returns An array of Chrome profile information objects. Returns empty array if profiles cannot be read\n * @throws {Error} If Chrome's application support directory cannot be accessed\n * @example\n * ```typescript\n * // Get all Chrome profiles\n * const profiles = listChromeProfiles();\n * // Returns: [\n * // {\n * // name: \"Default\",\n * // email: \"user@example.com\",\n * // full_name: \"John Doe\",\n * // ...\n * // },\n * // ...\n * // ]\n *\n * // Handle empty or error case\n * const profiles = listChromeProfiles();\n * if (profiles.length === 0) {\n * console.log('No Chrome profiles found or error occurred');\n * }\n * ```\n */\nexport function listChromeProfiles(): ChromeProfileInfo[] {\n try {\n const localStatePath = join(chromeApplicationSupport, \"Local State\");\n const localState = JSON.parse(\n readFileSync(localStatePath, \"utf8\"),\n ) as ChromeLocalState;\n return Object.values(localState.profile.info_cache);\n } catch (error) {\n if (error instanceof Error) {\n consola.error(\"Failed to read Chrome profiles:\", error.message);\n } else {\n consola.error(\"Failed to read Chrome profiles: Unknown error\");\n }\n return [];\n }\n}\n","// External imports\nimport { createDecipheriv, pbkdf2 } from \"crypto\";\n\nimport { memoize } from \"lodash-es\";\n\n/**\n * Removes the v10 prefix from the encrypted value if present\n * @param value - The encrypted value\n * @returns The value without the v10 prefix\n */\nconst removeV10Prefix = memoize(\n (value: Buffer): Buffer => {\n if (\n value.length >= 3 &&\n value[0] === 0x76 && // 'v'\n value[1] === 0x31 && // '1'\n value[2] === 0x30\n ) {\n // '0'\n return value.slice(3);\n }\n return value;\n },\n (value: Buffer) => value.toString(\"hex\"),\n);\n\n/**\n * Removes PKCS7 padding from the decrypted value\n * @param decrypted - The decrypted buffer\n * @returns The buffer without padding\n */\nconst removePadding = memoize(\n (decrypted: Buffer): Buffer => {\n const padding = decrypted[decrypted.length - 1];\n if (padding && padding <= 16) {\n return decrypted.slice(0, -padding);\n }\n return decrypted;\n },\n (decrypted: Buffer) => decrypted.toString(\"hex\"),\n);\n\n/**\n * Extracts the actual value from the decoded string by removing Chrome's prefixes\n * @param decodedString - The decoded string to clean up\n * @returns The cleaned up value\n */\nfunction extractValue(decodedString: string): string {\n const cleanupPatterns = [\n /.*?0t(.+)$/, // Pattern ending in \"0t\" followed by value\n /.*?1e`(.+)$/, // Pattern ending in \"1e`\" followed by value\n /.*?[`'](.+)$/, // Any backtick or quote followed by value\n /[^\\x20-\\x7E]*([\\x20-\\x7E].+)$/, // Non-printable chars followed by printable chars\n ];\n\n for (const pattern of cleanupPatterns) {\n const match = decodedString.match(pattern);\n const value = match?.[1] ?? \"\";\n if (value.length > 0) {\n return value;\n }\n }\n return decodedString;\n}\n\n/**\n * Decrypts Chrome's encrypted cookie values\n * @param encryptedValue - The encrypted cookie value as a Buffer\n * @param password - The Chrome encryption password\n * @returns A promise that resolves to the decrypted cookie value\n * @throws {Error} If decryption fails\n * @example\n */\nexport async function decrypt(\n encryptedValue: Buffer,\n password: string,\n): Promise<string> {\n if (typeof password !== \"string\") {\n throw new Error(\"password must be a string\");\n }\n if (!Buffer.isBuffer(encryptedValue)) {\n throw new Error(\"encryptedData must be a Buffer\");\n }\n\n return new Promise((resolve, reject) => {\n pbkdf2(password, \"saltysalt\", 1003, 16, \"sha1\", (error, key) => {\n try {\n if (error) {\n reject(new Error(\"Failed to derive key: \" + error.message));\n return;\n }\n\n const value = removeV10Prefix(encryptedValue);\n if (value.length % 16 !== 0) {\n reject(new Error(\"Encrypted data length is not a multiple of 16\"));\n return;\n }\n\n // Chrome's encryption parameters\n const iv = Buffer.alloc(16, \" \"); // 16 spaces\n const decipher = createDecipheriv(\"aes-128-cbc\", key, iv);\n decipher.setAutoPadding(false);\n\n // Decrypt the value\n let decrypted = decipher.update(value);\n try {\n decipher.final();\n } catch (e) {\n reject(\n new Error(\"Failed to finalize decryption: \" + (e as Error).message),\n );\n return;\n }\n\n decrypted = removePadding(decrypted);\n const decodedString = decrypted.toString(\"utf8\");\n resolve(extractValue(decodedString));\n } catch (e) {\n reject(new Error(\"Decryption failed: \" + (e as Error).message));\n }\n });\n });\n}\n","import { memoize } from \"lodash-es\";\n\nimport { logError, logDebug } from \"@utils/logHelpers\";\n\n/**\n * Retrieves the Chrome password for decrypting cookies\n * This is only supported on macOS\n * @returns A promise that resolves to the Chrome password\n * @throws {Error} If the platform is not macOS or if password retrieval fails\n * @example\n */\nexport const getChromePassword: () => Promise<string> = memoize(async () => {\n if (process.platform !== \"darwin\") {\n logError(\n \"Chrome password retrieval failed\",\n new Error(\"This only works on macOS\"),\n {\n platform: process.platform,\n },\n );\n throw new Error(\"This only works on macOS\");\n }\n\n try {\n const { getChromePassword: getMacOSPassword } = await import(\n \"./macos/getChromePassword\"\n );\n const password = await getMacOSPassword();\n logDebug(\"ChromePassword\", \"Retrieved password successfully\", {\n platform: \"macOS\",\n });\n return password;\n } catch (error) {\n logError(\"Chrome password retrieval failed\", error, { platform: \"macOS\" });\n throw error;\n }\n});\n","import { createTaggedLogger, logError } from \"@utils/logHelpers\";\n\nimport {\n BrowserName,\n CookieQueryStrategy,\n CookieRow,\n ExportedCookie,\n} from \"../../../types/schemas\";\nimport { getEncryptedChromeCookie } from \"../getEncryptedChromeCookie\";\nimport { listChromeProfilePaths } from \"../listChromeProfiles\";\n\nimport { decrypt } from \"./decrypt\";\nimport { getChromePassword } from \"./getChromePassword\";\n\ninterface DecryptionContext {\n file: string;\n password: string;\n}\n\nfunction getExpiryDate(expiry: number | undefined | null): Date | \"Infinity\" {\n if (typeof expiry !== \"number\" || expiry <= 0) {\n return \"Infinity\";\n }\n return new Date(expiry);\n}\n\nfunction createExportedCookie(\n domain: string,\n name: string,\n value: string,\n expiry: number | undefined | null,\n file: string,\n decrypted: boolean,\n): ExportedCookie {\n return {\n domain,\n name,\n value,\n expiry: getExpiryDate(expiry),\n meta: {\n file,\n browser: \"Chrome\",\n decrypted,\n },\n };\n}\n\n/**\n * Strategy for querying cookies from Chrome browser\n * @example\n * ```typescript\n * const strategy = new ChromeCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * ```\n */\nexport class ChromeCookieQueryStrategy implements CookieQueryStrategy {\n private readonly logger = createTaggedLogger(\"ChromeCookieQueryStrategy\");\n\n /**\n * The browser name for this strategy\n */\n public readonly browserName: BrowserName = \"Chrome\";\n\n /**\n * Queries cookies from Chrome's cookie store\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @returns A promise that resolves to an array of exported cookies\n * @example\n * ```typescript\n * const strategy = new ChromeCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * console.log(cookies);\n * ```\n */\n public async queryCookies(\n name: string,\n domain: string,\n ): Promise<ExportedCookie[]> {\n try {\n this.logger.info(\"Querying cookies\", { name, domain });\n\n if (process.platform !== \"darwin\") {\n this.logger.warn(\"Platform not supported\", {\n platform: process.platform,\n });\n return [];\n }\n\n const cookieFiles = listChromeProfilePaths();\n if (cookieFiles.length === 0) {\n this.logger.warn(\"No Chrome cookie files found\");\n return [];\n }\n\n const password = await getChromePassword();\n const results = await Promise.all(\n cookieFiles.map((file) =>\n this.processFile(file, name, domain, password),\n ),\n );\n\n return results.flat();\n } catch (error) {\n if (error instanceof Error) {\n logError(\"Failed to query cookies\", error, { name, domain });\n } else {\n logError(\"Failed to query cookies\", new Error(String(error)), {\n name,\n domain,\n });\n }\n return [];\n }\n }\n\n private async processFile(\n file: string,\n name: string,\n domain: string,\n password: string,\n ): Promise<ExportedCookie[]> {\n try {\n const encryptedCookies = await getEncryptedChromeCookie({\n name,\n domain,\n file,\n });\n\n const context: DecryptionContext = { file, password };\n const results = await Promise.allSettled(\n encryptedCookies.map((cookie) => this.processCookie(cookie, context)),\n );\n\n return results\n .map((result) => (result.status === \"fulfilled\" ? result.value : null))\n .filter((cookie): cookie is ExportedCookie => cookie !== null);\n } catch (error) {\n if (error instanceof Error) {\n this.logger.error(\"Failed to process cookie file\", { error, file });\n } else {\n this.logger.error(\"Failed to process cookie file\", {\n error: String(error),\n file,\n });\n }\n return [];\n }\n }\n\n private async processCookie(\n cookie: CookieRow,\n context: DecryptionContext,\n ): Promise<ExportedCookie> {\n try {\n const value = Buffer.isBuffer(cookie.value)\n ? cookie.value\n : Buffer.from(String(cookie.value));\n\n const decryptedValue = await decrypt(value, context.password);\n return createExportedCookie(\n cookie.domain,\n cookie.name,\n decryptedValue,\n cookie.expiry,\n context.file,\n true,\n );\n } catch (error) {\n if (error instanceof Error) {\n this.logger.warn(\"Failed to decrypt cookie\", { error });\n } else {\n this.logger.warn(\"Failed to decrypt cookie\", { error: String(error) });\n }\n return createExportedCookie(\n cookie.domain,\n cookie.name,\n cookie.value.toString(\"utf-8\"),\n cookie.expiry,\n context.file,\n false,\n );\n }\n }\n}\n","import { homedir } from \"os\";\nimport { join } from \"path\";\n\nimport fg from \"fast-glob\";\n\nimport { logDebug, logWarn } from \"@utils/logHelpers\";\n\nimport {\n BrowserName,\n CookieQueryStrategy,\n ExportedCookie,\n} from \"../../../types/schemas\";\nimport { querySqliteThenTransform } from \"../QuerySqliteThenTransform\";\n\ninterface FirefoxCookieRow {\n name: string;\n value: string;\n domain: string;\n expiry: number;\n}\n\n/**\n * Find all Firefox cookie database files\n * @returns An array of file paths to Firefox cookie databases\n */\nfunction findFirefoxCookieFiles(): string[] {\n const home = homedir();\n if (!home) {\n logWarn(\"FirefoxCookieQuery\", \"Failed to get home directory\");\n return [];\n }\n\n const patterns = [\n join(home, \"Library/Application Support/Firefox/Profiles/*/cookies.sqlite\"),\n join(home, \".mozilla/firefox/*/cookies.sqlite\"),\n ];\n\n const files: string[] = [];\n for (const pattern of patterns) {\n const matches = fg.sync(pattern);\n files.push(...matches);\n }\n\n logDebug(\"FirefoxCookieQuery\", \"Found Firefox cookie files\", { files });\n return files;\n}\n\n/**\n * Strategy for querying cookies from Firefox browser\n * @example\n */\nexport class FirefoxCookieQueryStrategy implements CookieQueryStrategy {\n /**\n *\n */\n public readonly browserName: BrowserName = \"Firefox\";\n\n /**\n * Queries cookies from Firefox's cookie store\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @returns A promise that resolves to an array of exported cookies\n */\n public async queryCookies(\n name: string,\n domain: string,\n ): Promise<ExportedCookie[]> {\n const files = findFirefoxCookieFiles();\n const results: ExportedCookie[] = [];\n\n for (const file of files) {\n try {\n const cookies = await querySqliteThenTransform<\n FirefoxCookieRow,\n ExportedCookie\n >({\n file,\n sql: \"SELECT name, value, host as domain, expiry FROM moz_cookies WHERE name = ? AND host LIKE ?\",\n params: [name, `%${domain}%`],\n rowTransform: (row) => ({\n name: row.name,\n value: row.value,\n domain: row.domain,\n expiry: row.expiry > 0 ? new Date(row.expiry * 1000) : \"Infinity\",\n meta: {\n file,\n browser: \"Firefox\",\n decrypted: false,\n },\n }),\n });\n\n results.push(...cookies);\n } catch (error) {\n if (error instanceof Error) {\n logWarn(\n \"FirefoxCookieQuery\",\n `Error reading Firefox cookie file ${file}`,\n { error: error.message },\n );\n } else {\n logWarn(\n \"FirefoxCookieQuery\",\n `Error reading Firefox cookie file ${file}`,\n );\n }\n }\n }\n\n return results;\n }\n}\n","import { homedir } from \"os\";\nimport { join } from \"path\";\n\nimport { logError } from \"@utils/logHelpers\";\n\nimport type {\n BrowserName,\n CookieQueryStrategy,\n ExportedCookie,\n} from \"../../../types/schemas\";\n\nimport { decodeBinaryCookies } from \"./decodeBinaryCookies\";\n\n/**\n * Strategy for querying cookies from Safari browser\n */\nexport class SafariCookieQueryStrategy implements CookieQueryStrategy {\n /**\n * The browser name for this strategy\n */\n public readonly browserName: BrowserName = \"Safari\";\n\n /**\n * Gets the path to Safari's cookie database\n * @param home - The user's home directory\n * @returns Path to the cookie database\n */\n private getCookieDbPath(home: string): string {\n return join(\n home,\n \"Library\",\n \"Containers\",\n \"com.apple.Safari\",\n \"Data\",\n \"Library\",\n \"Cookies\",\n \"Cookies.binarycookies\",\n );\n }\n\n /**\n * Decodes cookies from Safari's binary cookie file\n * @param cookieDbPath - Path to the cookie database\n * @param name - Name of the cookie to find\n * @param domain - Domain to filter cookies by\n * @returns Array of exported cookies\n */\n private decodeCookies(\n cookieDbPath: string,\n name: string,\n domain: string,\n ): ExportedCookie[] {\n try {\n const cookies = decodeBinaryCookies(cookieDbPath);\n return cookies\n .filter(\n (cookie) =>\n (name === \"%\" || cookie.name === name) &&\n (domain === \"%\" || cookie.domain.includes(domain)),\n )\n .map((cookie) => ({\n domain: cookie.domain,\n name: cookie.name,\n value: Buffer.isBuffer(cookie.value)\n ? cookie.value.toString()\n : String(cookie.value),\n expiry:\n typeof cookie.expiry === \"number\" && cookie.expiry > 0\n ? new Date(cookie.expiry * 1000)\n : \"Infinity\",\n meta: {\n file: cookieDbPath,\n browser: \"Safari\" as const,\n decrypted: false,\n },\n }));\n } catch (error) {\n if (error instanceof Error) {\n logError(\n \"SafariCookieQueryStrategy\",\n `Error decoding ${cookieDbPath}`,\n { error, name, domain },\n );\n } else {\n logError(\n \"SafariCookieQueryStrategy\",\n `Error decoding ${cookieDbPath}`,\n { error: \"Unknown error\", name, domain },\n );\n }\n return [];\n }\n }\n\n /**\n * Query Safari's cookie storage for cookies matching the given criteria\n * @param name - Name of the cookie to find\n * @param domain - Domain to filter cookies by\n * @returns Array of matching cookies, or empty array if none found\n */\n public async queryCookies(\n name: string,\n domain: string,\n ): Promise<ExportedCookie[]> {\n const home = homedir();\n if (typeof home !== \"string\" || home.length === 0) {\n logError(\"SafariCookieQueryStrategy\", \"Failed to get home directory\");\n return Promise.resolve([]);\n }\n\n const cookieDbPath = this.getCookieDbPath(home);\n return Promise.resolve(this.decodeCookies(cookieDbPath, name || \"%\", domain || \"%\"));\n }\n}\n","import { Buffer } from 'buffer';\nimport { readFileSync } from 'fs';\nimport { homedir } from 'os';\nimport { join } from 'path';\n\nimport { BinaryCookieRow } from '../../../types/schemas';\nimport { logWarn } from '../../../utils/logHelpers';\n\nimport { BinaryCodablePage } from './BinaryCodablePage';\nimport { BinaryCodableContainer } from './interfaces/BinaryCodableContainer';\n\n/**\n * Represents a binary cookies file structure used by Safari\n */\nexport class BinaryCodableCookies {\n /**\n *\n */\n public pages: BinaryCodablePage[];\n /**\n *\n */\n public metadata: Record<string, unknown>;\n private static readonly MAGIC = Buffer.from('cook', 'utf8');\n private static readonly FOOTER = BigInt('0x071720050000004b');\n private static readonly DEFAULT_COOKIE_PATH = join(\n homedir(),\n 'Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies'\n );\n\n /**\n * Creates a new BinaryCookies instance from a buffer\n * @param buffer - The raw binary cookie file data\n */\n public constructor(buffer: Buffer) {\n const container: BinaryCodableContainer = { offset: 0, buffer };\n this.pages = [];\n this.metadata = {};\n this.decode(container);\n }\n\n /**\n * Creates a BinaryCookies instance from a file path\n * @param path - Path to the Safari Cookies.binarycookies file\n * @returns A new BinaryCookies instance\n */\n public static fromFile(path: string): BinaryCodableCookies {\n const buffer = readFileSync(path);\n return new BinaryCodableCookies(buffer);\n }\n\n /**\n * Creates a BinaryCookies instance from the default Safari cookies location\n * @returns A new BinaryCookies instance\n */\n public static fromDefaultPath(): BinaryCodableCookies {\n return BinaryCodableCookies.fromFile(BinaryCodableCookies.DEFAULT_COOKIE_PATH);\n }\n\n /**\n * Converts the binary cookie data into a validated array of cookie rows\n * @returns Array of validated cookie objects\n */\n public toCookieRows(): BinaryCookieRow[] {\n const cookies: BinaryCookieRow[] = [];\n\n for (const page of this.pages) {\n try {\n const pageCookies = page.toCookieRows();\n if (Array.isArray(pageCookies)) {\n cookies.push(...pageCookies);\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logWarn('BinaryCookies', 'Error converting page cookies', { error: errorMessage });\n }\n }\n\n return cookies;\n }\n\n private decode(container: BinaryCodableContainer): void {\n try {\n // Check magic value\n const magic = container.buffer.subarray(container.offset, container.offset + 4);\n container.offset += 4;\n if (!magic.equals(BinaryCodableCookies.MAGIC)) {\n throw new Error('Missing magic value');\n }\n\n // Read page count\n const pageCount = container.buffer.readUInt32BE(container.offset);\n container.offset += 4;\n\n // Read page sizes\n const pageSizes: number[] = [];\n for (let i = 0; i < pageCount; i++) {\n pageSizes.push(container.buffer.readUInt32BE(container.offset));\n container.offset += 4;\n }\n\n // Calculate page offsets\n let currentOffset = container.offset;\n for (const pageSize of pageSizes) {\n try {\n const pageBuffer = container.buffer.subarray(currentOffset, currentOffset + pageSize);\n const page = new BinaryCodablePage(pageBuffer);\n this.pages.push(page);\n currentOffset += pageSize;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logWarn('BinaryCookies', `Error decoding page`, { error: errorMessage });\n currentOffset += pageSize; // Skip the problematic page\n }\n }\n container.offset = currentOffset;\n\n // Read checksum\n const _checksum = container.buffer.readUInt32BE(container.offset);\n container.offset += 4;\n\n // Read footer\n const footer = container.buffer.readBigUInt64BE(container.offset);\n container.offset += 8;\n if (footer !== BinaryCodableCookies.FOOTER) {\n logWarn('BinaryCookies', 'Invalid cookie file format: wrong footer');\n }\n\n // Read metadata plist\n const _plistData = container.buffer.subarray(container.offset);\n // Note: You'll need to implement or use a plist parser library here\n this.metadata = {}; // Placeholder for plist data\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logWarn('BinaryCookies', 'Error decoding binary cookies file', { error: errorMessage });\n throw error;\n }\n }\n}\n","import { Buffer } from 'buffer';\n\nimport { BinaryCookieRow, BinaryCookieRowSchema } from '../../../types/schemas';\n\nimport { BinaryCodableContainer } from './interfaces/BinaryCodableContainer';\nimport { BinaryCodableFlags } from './interfaces/BinaryCodableFlags';\nimport { BinaryCodableOffsets } from './interfaces/BinaryCodableOffsets';\n\n/**\n * Represents a single cookie within a page\n */\nexport class BinaryCodableCookie {\n /**\n *\n */\n public version = 0;\n /**\n *\n */\n public url = '';\n /**\n *\n */\n public port?: number;\n /**\n *\n */\n public name = '';\n /**\n *\n */\n public path = '';\n /**\n *\n */\n public value = '';\n /**\n *\n */\n public comment?: string;\n /**\n *\n */\n public commentURL?: string;\n /**\n *\n */\n public flags: BinaryCodableFlags = {\n isSecure: false,\n isHTTPOnly: false,\n unknown1: false,\n unknown2: false\n };\n /**\n *\n */\n public expiration = 0;\n /**\n *\n */\n public creation = 0;\n\n /**\n * Creates a new Cookie instance from a buffer\n * @param buffer - The raw binary cookie data\n */\n public constructor(buffer: Buffer) {\n const container: BinaryCodableContainer = { offset: 0, buffer };\n this.decode(container);\n }\n\n private decodeUrlValue(value: string): string {\n let processed = value;\n let lastProcessed;\n do {\n lastProcessed = processed;\n try {\n processed = decodeURIComponent(processed);\n } catch {\n return lastProcessed;\n }\n } while (processed !== lastProcessed && processed.includes('%'));\n return processed;\n }\n\n private decodeJwtPayload(token: string): string | null {\n const parts = token.split('.');\n if (parts.length !== 3) {\n return null;\n }\n\n try {\n const payload = Buffer.from(parts[1], 'base64').toString('utf8');\n const parsed = JSON.parse(payload) as Record<string, unknown>;\n return JSON.stringify(parsed);\n } catch {\n return null;\n }\n }\n\n private parseJsonValue(value: string): string | null {\n try {\n const parsed = JSON.parse(value) as Record<string, unknown>;\n return JSON.stringify(parsed);\n } catch {\n return null;\n }\n }\n\n private processValue(value: string): string {\n // First, try URL decoding\n const decoded = this.decodeUrlValue(value);\n\n // Then, try JWT decoding if it looks like a JWT token\n if (decoded.match(/^ey[A-Za-z0-9_-]+\\.ey[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/)) {\n const jwtPayload = this.decodeJwtPayload(decoded);\n if (typeof jwtPayload === 'string' && jwtPayload.length > 0) {\n return jwtPayload;\n }\n }\n\n // Finally, try JSON parsing if it looks like JSON\n if (decoded.startsWith('{') || decoded.startsWith('[')) {\n const jsonValue = this.parseJsonValue(decoded);\n if (typeof jsonValue === 'string' && jsonValue.length > 0) {\n return jsonValue;\n }\n }\n\n return decoded;\n }\n\n /**\n * Converts the cookie to a validated cookie row\n * @returns Validated cookie row object or null if validation fails\n */\n public toCookieRow(): BinaryCookieRow | null {\n try {\n // Convert flags to number\n const flagsValue = this.convertFlags();\n\n // Extract domain from URL\n const domain = this.url.replace(/^https?:\\/\\//, '').replace(/\\/.*$/, '') || 'uk';\n\n // Keep timestamps as they are (seconds since 2001-01-01)\n // The display layer will handle the conversion to human-readable dates\n const cookieRow = BinaryCookieRowSchema.parse({\n name: this.name.replace(/^: /, ''), // Remove leading ': ' if present\n value: this.processValue(this.value) || '', // Process and ensure value is never undefined\n domain,\n path: this.path || '/',\n expiry: this.expiration,\n creation: this.creation,\n flags: flagsValue,\n version: this.version,\n port: this.port,\n comment: this.comment,\n commentURL: this.commentURL\n });\n\n return cookieRow;\n } catch (_error) {\n return null;\n }\n }\n\n private readNullTerminatedString(container: BinaryCodableContainer, offset: number): string {\n let end = offset;\n while (end < container.buffer.length && container.buffer[end] !== 0) {\n end++;\n }\n const value = container.buffer.toString('utf8', offset, end);\n return value || '';\n }\n\n private readHeader(container: BinaryCodableContainer): { size: number; hasPort: number; offsets: BinaryCodableOffsets } {\n // Cookie size (4 bytes)\n const size = container.buffer.readUInt32LE(container.offset);\n container.offset += 4;\n\n // Unknown (4 bytes)\n container.offset += 4;\n\n // Cookie flags (4 bytes)\n const flagsValue = container.buffer.readUInt32LE(container.offset);\n container.offset += 4;\n this.flags = {\n isSecure: (flagsValue & 1) !== 0,\n isHTTPOnly: (flagsValue & 4) !== 0,\n unknown1: (flagsValue & 8) !== 0,\n unknown2: (flagsValue & 16) !== 0\n };\n\n // Unknown (4 bytes)\n const hasPort = container.buffer.readUInt32LE(container.offset);\n container.offset += 4;\n\n // String offsets (24 bytes total)\n const offsets = {\n urlOffset: container.buffer.readUInt32LE(container.offset),\n nameOffset: container.buffer.readUInt32LE(container.offset + 4),\n pathOffset: container.buffer.readUInt32LE(container.offset + 8),\n valueOffset: container.buffer.readUInt32LE(container.offset + 12),\n commentOffset: container.buffer.readUInt32LE(container.offset + 16),\n commentURLOffset: container.buffer.readUInt32LE(container.offset + 20)\n };\n\n return { size, hasPort, offsets };\n }\n\n private readTimestamps(container: BinaryCodableContainer): void {\n // Read expiration time (8 bytes, little-endian double)\n const expirationBuffer = Buffer.alloc(8);\n for (let i = 0; i < 8; i++) {\n expirationBuffer[i] = container.buffer[container.offset + i];\n }\n const expiration = expirationBuffer.readDoubleLE(0);\n container.offset += 8;\n\n // Read creation time (8 bytes, little-endian double)\n const creationBuffer = Buffer.alloc(8);\n for (let i = 0; i < 8; i++) {\n creationBuffer[i] = container.buffer[container.offset + i];\n }\n const creation = creationBuffer.readDoubleLE(0);\n container.offset += 8;\n\n // Store raw timestamps (seconds since 2001-01-01)\n // For expiration time, 0 means \"session cookie\" (expires when browser closes)\n // For creation time, 0 means \"no creation time recorded\"\n this.expiration = expiration;\n this.creation = creation;\n }\n\n private readStrings(container: BinaryCodableContainer, size: number, offsets: BinaryCodableOffsets): void {\n // All offsets are relative to the start of the cookie\n const cookieStart = 0; // Offsets are relative to the cookie buffer start\n\n // Read strings in order of their offsets\n const offsetEntries = [\n { field: 'url', offset: offsets.urlOffset },\n { field: 'name', offset: offsets.nameOffset },\n { field: 'path', offset: offsets.pathOffset },\n { field: 'value', offset: offsets.valueOffset },\n { field: 'comment', offset: offsets.commentOffset }\n ].filter(entry => entry.offset > 0)\n .sort((a, b) => a.offset - b.offset);\n\n // Calculate string lengths based on offset differences\n for (let i = 0; i < offsetEntries.length; i++) {\n const { field, offset } = offsetEntries[i];\n const nextOffset = i < offsetEntries.length - 1 ? offsetEntries[i + 1].offset : size;\n const length = nextOffset - offset;\n\n // Read string up to null terminator\n let end = cookieStart + offset;\n while (end < cookieStart + offset + length && container.buffer[end] !== 0) {\n end++;\n }\n const value = container.buffer.toString('utf8', cookieStart + offset, end);\n\n switch (field) {\n case 'url':\n this.url = value;\n break;\n case 'name':\n this.name = value;\n break;\n case 'path':\n this.path = value;\n break;\n case 'value':\n this.value = value;\n break;\n case 'comment':\n this.comment = value;\n break;\n }\n }\n }\n\n private decode(container: BinaryCodableContainer): void {\n const { size, hasPort, offsets } = this.readHeader(container);\n\n // Skip past all offsets (24 bytes)\n const baseOffset = container.offset;\n container.offset = baseOffset + 24;\n\n this.readTimestamps(container);\n\n if (hasPort > 0) {\n this.port = container.buffer.readUInt16LE(container.offset);\n container.offset += 2;\n }\n\n // Reset offset for string reading\n container.offset = baseOffset;\n this.readStrings(container, size, offsets);\n }\n\n private convertFlags(): number {\n return (this.flags.isSecure ? 0x1 : 0) |\n (this.flags.isHTTPOnly ? 0x4 : 0) |\n (this.flags.unknown1 ? 0x8 : 0) |\n (this.flags.unknown2 ? 0x10 : 0);\n }\n}\n","import destr from \"destr\";\nimport { z } from \"zod\";\n\n/**\n * Zod schema for cookie domain validation.\n * Enforces standard cookie domain rules.\n * @example\n * ```typescript\n * // Valid domains\n * CookieDomainSchema.parse(\"example.com\"); // OK\n * CookieDomainSchema.parse(\".example.com\"); // OK - leading dot is valid\n * CookieDomainSchema.parse(\"sub.example.com\"); // OK\n *\n * // Invalid domains\n * CookieDomainSchema.parse(\"\"); // Error: Domain cannot be empty\n * CookieDomainSchema.parse(\"invalid domain\"); // Error: Invalid domain format\n * ```\n */\nexport const CookieDomainSchema = z\n .string()\n .trim()\n .min(1, \"Domain cannot be empty\")\n .refine(\n (domain) =>\n /^\\.?[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(\n domain,\n ),\n \"Invalid domain format\",\n );\n\n/**\n * Zod schema for cookie name validation.\n * Enforces standard cookie name rules according to RFC 6265.\n * @example\n * ```typescript\n * // Valid names\n * CookieNameSchema.parse(\"session\"); // OK\n * CookieNameSchema.parse(\"auth_token\"); // OK\n * CookieNameSchema.parse(\"user-preference\"); // OK\n *\n * // Invalid names\n * CookieNameSchema.parse(\"\"); // Error: Cookie name cannot be empty\n * CookieNameSchema.parse(\"session;\"); // Error: Invalid cookie name format\n * CookieNameSchema.parse(\"my cookie\"); // Error: Invalid cookie name format\n * ```\n */\nexport const CookieNameSchema = z\n .string()\n .trim()\n .min(1, \"Cookie name cannot be empty\")\n .refine(\n (name) =>\n name === \"%\" || /^[!#$%&'()*+\\-.:0-9A-Z \\^_`a-z|~]+$/.test(name),\n \"Invalid cookie name format - must contain only valid characters (letters, numbers, and certain symbols) or be '%' for wildcard\",\n );\n\n/**\n * Zod schema for cookie path validation.\n * Enforces standard cookie path rules according to RFC 6265.\n * @example\n * ```typescript\n * // Valid paths\n * CookiePathSchema.parse(\"/\"); // OK\n * CookiePathSchema.parse(\"/api\"); // OK\n * CookiePathSchema.parse(\"/path/to/page\"); // OK\n *\n * // Invalid paths\n * CookiePathSchema.parse(\"\"); // Error: Path cannot be empty\n * CookiePathSchema.parse(\"invalid\"); // Error: Path must start with /\n * CookiePathSchema.parse(\"/path?query\"); // Error: Invalid path format\n * ```\n */\nexport const CookiePathSchema = z\n .string()\n .trim()\n .min(1, \"Path cannot be empty\")\n .refine((path) => path.startsWith(\"/\"), \"Path must start with /\")\n .refine(\n (path) => /^\\/[!#$%&'()*+,\\-./:=@\\w~]*$/.test(path),\n \"Invalid path format - must contain only valid URL path characters\",\n )\n .default(\"/\");\n\n/**\n * Zod schema for cookie value.\n * Attempts to parse JSON values using destr for better readability.\n */\nexport const CookieValueSchema = z\n .string()\n .trim()\n .transform((value) => destr(value))\n .pipe(z.any());\n\n/**\n * Zod schema for Safari binary cookie row.\n * Validates and enforces the structure of cookie data read from Safari's Cookies.binarycookies file.\n * @example\n * ```typescript\n * const cookieData = {\n * name: \"session\",\n * value: \"abc123\",\n * domain: \"example.com\",\n * path: \"/\",\n * expiry: 1735689600,\n * creation: 1672531200,\n * flags: 0x5, // Secure + HTTPOnly\n * };\n * const validCookie = BinaryCookieRowSchema.parse(cookieData);\n * ```\n */\nexport const BinaryCookieRowSchema = z.object({\n name: CookieNameSchema,\n value: CookieValueSchema,\n domain: CookieDomainSchema,\n path: CookiePathSchema,\n expiry: z.number().int(),\n creation: z.number().int(),\n flags: z.number().optional(),\n version: z.number().int().optional(),\n port: z.number().int().optional(),\n comment: z.string().optional(),\n commentURL: z.string().optional(),\n});\n\n/**\n * Type representing a decoded Safari binary cookie.\n * This type is inferred from the BinaryCookieRowSchema and includes all cookie properties.\n * @property name - The name of the cookie (non-empty string)\n * @property value - The value stored in the cookie\n * @property domain - The domain the cookie belongs to (non-empty string)\n * @property path - The path where the cookie is valid (defaults to \"/\")\n * @property expiry - Unix timestamp when the cookie expires\n * @property creation - Unix timestamp when the cookie was created\n * @property flags - Optional bit flags (e.g., Secure, HTTPOnly)\n * @property version - Optional cookie version number\n * @property port - Optional port number restriction\n * @property comment - Optional cookie comment\n * @property commentURL - Optional URL for the cookie's comment\n */\nexport type BinaryCookieRow = z.infer<typeof BinaryCookieRowSchema>;\n\n/**\n * Schema for cookie specification parameters\n * Defines the required fields for identifying a cookie\n * @example\n * ```typescript\n * // Validate a cookie specification\n * const spec = {\n * name: 'session',\n * domain: 'example.com'\n * };\n * const result = CookieSpecSchema.safeParse(spec);\n * if (result.success) {\n * console.log('Valid cookie spec:', result.data);\n * } else {\n * console.error('Invalid cookie spec:', result.error);\n * }\n *\n * // Invalid spec (empty name)\n * const invalidSpec = {\n * name: '',\n * domain: 'example.com'\n * };\n * // Throws: \"Cookie name cannot be empty\"\n * CookieSpecSchema.parse(invalidSpec);\n * ```\n */\nexport const CookieSpecSchema = z\n .object({\n name: CookieNameSchema,\n domain: CookieDomainSchema,\n })\n .strict();\n\n/**\n * Type definition for cookie specification\n * Used for specifying which cookie to query\n * @example\n * ```typescript\n * // Basic cookie spec\n * const spec: CookieSpec = {\n * name: 'auth',\n * domain: 'api.example.com'\n * };\n *\n * // Use in function parameters\n * function queryCookie(spec: CookieSpec): Promise<ExportedCookie[]> {\n * return getCookie(spec);\n * }\n *\n * // Array of specs\n * const specs: CookieSpec[] = [\n * { name: 'session', domain: 'app.example.com' },\n * { name: 'theme', domain: 'example.com' }\n * ];\n * ```\n */\nexport type CookieSpec = z.infer<typeof CookieSpecSchema>;\n\n/**\n * Schema for metadata about a cookie\n */\nexport const CookieMetaSchema = z\n .object({\n file: z.string().trim().min(1, \"File path cannot be empty\").optional(),\n browser: z.string().trim().optional(),\n decrypted: z.boolean().optional(),\n secure: z.boolean().optional(),\n httpOnly: z.boolean().optional(),\n path: CookiePathSchema.optional(),\n })\n .catchall(z.unknown())\n .strict();\n\n/**\n * Type definition for cookie metadata\n */\nexport type CookieMeta = z.infer<typeof CookieMetaSchema>;\n\n/**\n * Schema for exported cookie data\n * Represents a cookie with all its properties and metadata\n * @example\n * ```typescript\n * // Validate an exported cookie\n * const cookie = {\n * domain: 'example.com',\n * name: 'session',\n * value: 'abc123',\n * expiry: new Date('2024-12-31'),\n * meta: {\n * file: '/path/to/cookies.db'\n * }\n * };\n * const result = ExportedCookieSchema.safeParse(cookie);\n * if (result.success) {\n * console.log('Valid cookie:', result.data);\n * } else {\n * console.error('Invalid cookie:', result.error);\n * }\n *\n * // Cookie with infinite expiry\n * const infiniteCookie = {\n * ...cookie,\n * expiry: \"Infinity\"\n * };\n * ExportedCookieSchema.parse(infiniteCookie); // OK\n * ```\n */\nexport const ExportedCookieSchema = z\n .object({\n domain: CookieDomainSchema,\n name: CookieNameSchema,\n value: CookieValueSchema,\n expiry: z\n .union([\n z.literal(\"Infinity\"),\n z.date(),\n z.number().int().positive(\"Expiry must be a positive number\"),\n ])\n .optional(),\n meta: CookieMetaSchema.optional(),\n })\n .strict();\n\n/**\n * Type definition for exported cookie data\n * Represents the structure of a cookie after it has been retrieved\n * @example\n * ```typescript\n * // Basic exported cookie\n * const cookie: ExportedCookie = {\n * domain: 'example.com',\n * name: 'session',\n * value: 'abc123',\n * expiry: new Date('2024-12-31'),\n * meta: {\n * file: '/path/to/cookies.db'\n * }\n * };\n *\n * // Process exported cookies\n * function processCookies(cookies: ExportedCookie[]): string[] {\n * return cookies.map(cookie => `${cookie.name}=${cookie.value}`);\n * }\n *\n * // Filter expired cookies\n * function filterExpired(cookies: ExportedCookie[]): ExportedCookie[] {\n * const now = new Date();\n * return cookies.filter(cookie =>\n * cookie.expiry === \"Infinity\" ||\n * (cookie.expiry instanceof Date && cookie.expiry > now)\n * );\n * }\n * ```\n */\nexport type ExportedCookie = z.infer<typeof ExportedCookieSchema>;\n\n/**\n * Schema for raw cookie data from browser stores\n */\nexport const CookieRowSchema = z\n .object({\n expiry: z.number().int().optional(),\n domain: CookieDomainSchema,\n name: CookieNameSchema,\n value: z.union([z.string(), z.instanceof(Buffer)]),\n })\n .strict();\n\n/**\n * Type definition for raw cookie data\n */\nexport type CookieRow = z.infer<typeof CookieRowSchema>;\n\n/**\n * Schema for cookie render options\n */\nexport const RenderOptionsSchema = z\n .object({\n format: z.enum([\"merged\", \"grouped\"]).optional(),\n separator: z.string().optional(),\n showFilePaths: z.boolean().optional(),\n })\n .strict();\n\n/**\n * Type definition for render options\n */\nexport type RenderOptions = z.infer<typeof RenderOptionsSchema>;\n\n/**\n * Schema for browser names\n */\nexport const BrowserNameSchema = z.enum([\n \"Chrome\",\n \"Firefox\",\n \"Safari\",\n \"internal\",\n \"unknown\",\n]);\n\n/**\n * Type definition for browser names\n */\nexport type BrowserName = z.infer<typeof BrowserNameSchema>;\n\n/**\n * Schema for cookie query strategy\n */\nexport const CookieQueryStrategySchema = z\n .object({\n browserName: BrowserNameSchema,\n queryCookies: z\n .function()\n .args(z.string(), z.string())\n .returns(z.promise(z.array(ExportedCookieSchema))),\n })\n .strict();\n\n/**\n * Type definition for cookie query strategy\n */\nexport type CookieQueryStrategy = z.infer<typeof CookieQueryStrategySchema>;\n\n/**\n * Type representing either a single cookie specification or an array of specifications.\n * Useful when you need to query multiple cookies in a single operation.\n * @example\n * ```typescript\n * // Single cookie spec\n * const single: MultiCookieSpec = {\n * domain: \"example.com\",\n * name: \"sessionId\"\n * };\n *\n * // Multiple cookie specs\n * const multiple: MultiCookieSpec = [\n * { domain: \"example.com\", name: \"sessionId\" },\n * { domain: \"api.example.com\", name: \"authToken\" }\n * ];\n * ```\n */\nexport type MultiCookieSpec = CookieSpec | CookieSpec[];\n","import { Buffer } from 'buffer';\n\nimport { BinaryCookieRow } from '../../../types/schemas';\nimport { logWarn } from '../../../utils/logHelpers';\n\nimport { BinaryCodableCookie } from './BinaryCodableCookie';\nimport { BinaryCodableContainer } from './interfaces/BinaryCodableContainer';\n\n/**\n * Represents a page of cookies within the binary cookies file\n */\nexport class BinaryCodablePage {\n /**\n *\n */\n public cookies: BinaryCodableCookie[];\n private static readonly HEADER = 0x00000100;\n private static readonly FOOTER = 0x00000000;\n\n /**\n * Creates a new Page instance from a buffer\n * @param buffer - The raw binary page data\n */\n public constructor(buffer: Buffer) {\n this.cookies = [];\n const container: BinaryCodableContainer = { offset: 0, buffer };\n this.decode(container);\n }\n\n /**\n * Converts the page's cookies into validated cookie rows\n * @returns Array of validated cookie objects\n */\n public toCookieRows(): BinaryCookieRow[] {\n const cookies: BinaryCookieRow[] = [];\n\n for (const cookie of this.cookies) {\n try {\n const cookieRow = cookie.toCookieRow();\n if (cookieRow !== null) {\n cookies.push(cookieRow);\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logWarn('BinaryCookies', 'Error converting cookie', { error: errorMessage });\n }\n }\n\n return cookies;\n }\n\n private decode(container: BinaryCodableContainer): void {\n // Read page tag (4 bytes)\n const header = container.buffer.readUInt32BE(container.offset);\n container.offset += 4;\n if (header !== BinaryCodablePage.HEADER) {\n throw new Error('Invalid page header');\n }\n\n // Read number of cookies (4 bytes)\n const cookieCount = container.buffer.readUInt32LE(container.offset);\n container.offset += 4;\n\n // Store the page start offset for calculating absolute cookie positions\n const pageStart = container.offset - 8;\n\n // Read cookie offsets (4 bytes each)\n const cookieOffsets: number[] = [];\n for (let i = 0; i < cookieCount; i++) {\n const cookieOffset = container.buffer.readUInt32LE(container.offset);\n cookieOffsets.push(cookieOffset);\n container.offset += 4;\n }\n\n // Read page end marker (4 bytes)\n const footer = container.buffer.readUInt32BE(container.offset);\n container.offset += 4;\n if (footer !== BinaryCodablePage.FOOTER) {\n throw new Error('Invalid page footer');\n }\n\n // Read cookies at their offsets\n for (let i = 0; i < cookieCount; i++) {\n try {\n const cookieOffset = cookieOffsets[i];\n // Calculate absolute offset from page start\n const absoluteOffset = pageStart + cookieOffset;\n\n // Read cookie size from the cookie header\n const cookieSize = container.buffer.readUInt32LE(absoluteOffset);\n if (cookieSize < 48) { // Minimum cookie size is 48 bytes (header)\n logWarn('BinaryCookies', `Invalid cookie size ${cookieSize} at index ${i}`);\n continue;\n }\n\n // Ensure we don't read past the buffer\n if (absoluteOffset + cookieSize > container.buffer.length) {\n logWarn('BinaryCookies', `Cookie size ${cookieSize} at index ${i} would exceed buffer length`);\n continue;\n }\n\n const cookieBuffer = container.buffer.subarray(absoluteOffset, absoluteOffset + cookieSize);\n const cookie = new BinaryCodableCookie(cookieBuffer);\n this.cookies.push(cookie);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logWarn('BinaryCookies', `Error decoding cookie at index ${i}`, { error: errorMessage });\n }\n }\n }\n}\n","import type { BinaryCookieRow } from '../../../types/schemas';\n\nimport { BinaryCodableCookies } from './BinaryCodableCookies';\n\n/**\n * Decodes a Safari binary cookie file into an array of cookie objects.\n * @param cookieDbPath - Path to the Safari Cookies.binarycookies file\n * @returns Array of decoded cookie objects\n * @throws {Error} If the file cannot be read or has invalid format\n */\nexport function decodeBinaryCookies(cookieDbPath: string): BinaryCookieRow[] {\n const cookies = BinaryCodableCookies.fromFile(cookieDbPath);\n return cookies.toCookieRows();\n}\n\n/**\n * Retrieves cookies from Safari's binary cookie store.\n * @returns Array of decoded Safari cookies\n */\nexport function getSafariCookies(): BinaryCookieRow[] {\n const cookies = BinaryCodableCookies.fromDefaultPath();\n return cookies.toCookieRows();\n}\n","import type { CookieSpec, ExportedCookie } from \"../../types/schemas\";\nimport { ChromeCookieQueryStrategy } from \"../browsers/chrome/ChromeCookieQueryStrategy\";\nimport { FirefoxCookieQueryStrategy } from \"../browsers/firefox/FirefoxCookieQueryStrategy\";\nimport { SafariCookieQueryStrategy } from \"../browsers/safari/SafariCookieQueryStrategy\";\n\n/**\n * Queries cookies from all available browser strategies (Chrome, Firefox, Safari).\n * This function acts as a unified interface to retrieve cookies across different browsers.\n * @param cookieSpec - The cookie specification to query\n * @param cookieSpec.name - The name pattern to match cookies against (can include '%' as wildcard)\n * @param cookieSpec.domain - The domain to match cookies against\n * @returns Promise resolving to array of exported cookies from all available browsers\n * @remarks\n * - Returns empty array if cookieSpec is invalid or missing required fields\n * - Aggregates results from all available browser strategies\n * - Failed browser queries are gracefully handled and excluded from results\n * - Both name and domain fields are required and must be strings\n * @example\n * ```typescript\n * const cookies = await queryCookies({\n * name: 'sessionId',\n * domain: 'example.com'\n * });\n * console.log(cookies); // Array of matching cookies from all browsers\n * ```\n */\nexport async function queryCookies(\n cookieSpec: CookieSpec,\n): Promise<ExportedCookie[]> {\n if (!cookieSpec.name || !cookieSpec.domain) {\n return [];\n }\n\n const { name, domain } = cookieSpec;\n if (typeof name !== \"string\" || typeof domain !== \"string\") {\n return [];\n }\n\n /**\n * Initialize all available browser-specific strategies\n * The order of strategies can affect performance but not functionality\n * Each strategy is responsible for its own error handling\n */\n const strategies = [\n new ChromeCookieQueryStrategy(),\n new FirefoxCookieQueryStrategy(),\n new SafariCookieQueryStrategy(),\n ];\n\n /**\n * Query all strategies in parallel and handle failures gracefully\n * Using Promise.allSettled ensures that failures in one strategy\n * don't prevent results from other strategies\n */\n const results = await Promise.allSettled(\n strategies.map((strategy) => strategy.queryCookies(name, domain)),\n );\n\n /**\n * Filter out failed promises and flatten successful results\n * Using PromiseFulfilledResult<ExportedCookie[]> ensures that only successful results are included\n */\n return results\n .filter(\n (result): result is PromiseFulfilledResult<ExportedCookie[]> =>\n result.status === \"fulfilled\",\n )\n .flatMap((result) => result.value);\n}\n\n/**\n * Default export of the queryCookies function.\n * This is the recommended way to import the function for most use cases.\n * @example\n * ```typescript\n * import queryCookies from './queryCookies';\n *\n * // Query cookies with specific name\n * const sessionCookies = await queryCookies({\n * name: 'sessionId',\n * domain: 'example.com'\n * });\n *\n * // Query all cookies for a domain using wildcard\n * const allCookies = await queryCookies({\n * name: '%',\n * domain: 'example.com'\n * });\n * ```\n */\nexport default queryCookies;\n","import type { CookieSpec, ExportedCookie } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\n\nimport { queryCookies } from \"./queryCookies\";\n\n/**\n * Retrieves browser cookies that match the specified cookie name and domain criteria.\n * This function provides a way to search and filter cookies based on given specifications.\n * @param cookieSpec - The cookie specification containing search criteria\n * @param cookieSpec.name - The name of the cookie to search for\n * @param cookieSpec.domain - (optional) The domain to filter cookies by\n * @returns An array of ExportedCookie objects that match the specification\n * @throws Will catch and handle any errors during cookie querying, logging a warning\n * to the console without throwing to the caller\n * @example\n * ```typescript\n * import { getCookie } from \"@mherod/get-cookie\";\n *\n * // Get all cookies named \"sessionId\"\n * const cookies = await getCookie({ name: \"sessionId\" });\n * // Returns: [{ name: \"sessionId\", value: \"abc123\", domain: \".example.com\", ... }]\n *\n * // Get cookies named \"userPref\" from specific domain\n * const domainCookies = await getCookie({\n * name: \"userPref\",\n * domain: \"example.com\"\n * });\n * // Returns: [{ name: \"userPref\", value: \"darkMode\", domain: \"example.com\", ... }]\n * ```\n */\nexport async function getCookie(\n cookieSpec: CookieSpec,\n): Promise<ExportedCookie[]> {\n try {\n const cookies = await queryCookies(cookieSpec);\n return cookies;\n } catch (error: unknown) {\n logger.warn(\n \"Error querying cookies:\",\n error instanceof Error ? error.message : String(error),\n );\n return [];\n }\n}\n\n/**\n * Default export of the getCookie function.\n * @example\n * ```typescript\n * import { getCookie } from \"@mherod/get-cookie\";\n * const authCookies = await getCookie({\n * name: \"auth-token\",\n * domain: \"api.example.com\"\n * });\n * ```\n */\nexport default getCookie;\n","import type { CookieSpec, ExportedCookie } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\nimport { ChromeCookieQueryStrategy } from \"../browsers/chrome/ChromeCookieQueryStrategy\";\n\n/**\n * Retrieves cookies from Chrome browser storage that match the specified criteria.\n * @param cookieSpec - The cookie specification containing search criteria\n * @param cookieSpec.name - The name of the cookie to search for\n * @param cookieSpec.domain - (optional) The domain to filter cookies by\n * @returns An array of ExportedCookie objects that match the specification\n * @throws Will catch and handle any errors during cookie querying, logging a warning\n * to the console without throwing to the caller\n * @example\n * ```typescript\n * import { getChromeCookie } from \"@mherod/get-cookie\";\n *\n * // Get all cookies named \"sessionId\" from Chrome\n * const cookies = await getChromeCookie({ name: \"sessionId\" });\n *\n * // Get cookies named \"userPref\" from specific domain in Chrome\n * const domainCookies = await getChromeCookie({\n * name: \"userPref\",\n * domain: \"example.com\"\n * });\n * ```\n */\nexport async function getChromeCookie(\n cookieSpec: CookieSpec,\n): Promise<ExportedCookie[]> {\n try {\n const strategy = new ChromeCookieQueryStrategy();\n const cookies = await strategy.queryCookies(\n cookieSpec.name,\n cookieSpec.domain,\n );\n return cookies;\n } catch (error: unknown) {\n logger.warn(\"Error querying Chrome cookies:\", error);\n return [];\n }\n}\n\n/**\n * Default export of the getChromeCookie function.\n * @example\n * ```typescript\n * import { getChromeCookie } from \"@mherod/get-cookie\";\n * const cookies = await getChromeCookie({\n * name: \"sessionId\",\n * domain: \"example.com\"\n * });\n * ```\n */\nexport default getChromeCookie;\n","import type { CookieSpec, ExportedCookie } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\nimport { FirefoxCookieQueryStrategy } from \"../browsers/firefox/FirefoxCookieQueryStrategy\";\n\n/**\n * Retrieves cookies from Firefox browser storage that match the specified criteria.\n * @param cookieSpec - The cookie specification containing search criteria\n * @param cookieSpec.name - The name of the cookie to search for\n * @param cookieSpec.domain - (optional) The domain to filter cookies by\n * @returns An array of ExportedCookie objects that match the specification\n * @throws Will catch and handle any errors during cookie querying, logging a warning\n * to the console without throwing to the caller\n * @example\n * ```typescript\n * import { getFirefoxCookie } from \"@mherod/get-cookie\";\n *\n * // Get all cookies named \"sessionId\" from Firefox\n * const cookies = await getFirefoxCookie({ name: \"sessionId\" });\n *\n * // Get cookies named \"userPref\" from specific domain in Firefox\n * const domainCookies = await getFirefoxCookie({\n * name: \"userPref\",\n * domain: \"example.com\"\n * });\n * ```\n */\nexport async function getFirefoxCookie(\n cookieSpec: CookieSpec,\n): Promise<ExportedCookie[]> {\n try {\n const strategy = new FirefoxCookieQueryStrategy();\n const cookies = await strategy.queryCookies(\n cookieSpec.name,\n cookieSpec.domain,\n );\n return cookies;\n } catch (error: unknown) {\n logger.warn(\n \"Error querying Firefox cookies:\",\n error instanceof Error ? error.message : String(error),\n );\n return [];\n }\n}\n\n/**\n * Default export of the getFirefoxCookie function.\n * @example\n * ```typescript\n * import { getFirefoxCookie } from \"@mherod/get-cookie\";\n * const sessionCookies = await getFirefoxCookie({\n * name: \"PHPSESSID\",\n * domain: \"example.com\"\n * });\n * ```\n */\nexport default getFirefoxCookie;\n","import { groupBy } from \"lodash-es\";\n\nimport { ExportedCookie, RenderOptions } from \"../../types/schemas\";\n\n/**\n * Renders cookies as a string or array of strings based on the provided format option.\n * Supports merged format for single string output or grouped format for file-based grouping.\n * @param cookies - The cookies to render\n * @param options - Options for rendering\n * @param options.format - The output format ('merged' or 'grouped')\n * @param options.showFilePaths - Whether to include file paths in grouped output\n * @param options.separator - Custom separator for cookie values\n * @returns A string for merged format, or array of strings for grouped format\n * @example\n * ```typescript\n * // Merged format (default)\n * const cookies = [\n * { value: 'sessionId=abc123' },\n * { value: 'theme=dark' }\n * ];\n * renderCookies(cookies);\n * // Returns: \"sessionId=abc123; theme=dark\"\n *\n * // Grouped format with file paths\n * const groupedCookies = [\n * { value: 'sessionId=abc123', meta: { file: 'auth.ts' } },\n * { value: 'theme=dark', meta: { file: 'preferences.ts' } }\n * ];\n * renderCookies(groupedCookies, { format: 'grouped', showFilePaths: true });\n * // Returns: [\"auth.ts: sessionId=abc123\", \"preferences.ts: theme=dark\"]\n * ```\n */\nexport function renderCookies(\n cookies: ExportedCookie[],\n options: RenderOptions = {},\n): string | string[] {\n const { format = \"merged\", showFilePaths = true, separator = \"; \" } = options;\n\n if (cookies.length === 0) {\n return format === \"merged\" ? \"\" : [];\n }\n\n if (format === \"merged\") {\n return cookies.map((c) => c.value as string).join(separator);\n }\n\n const groupedByFile = groupBy(cookies, (c) => c.meta?.file ?? \"unknown\");\n return Object.entries(groupedByFile).map(([file, fileCookies]) => {\n const values = fileCookies.map((c) => c.value as string).join(separator);\n return showFilePaths ? `${file}: ${values}` : values;\n });\n}\n","import type {\n RenderOptions,\n CookieSpec,\n ExportedCookie,\n} from \"../../types/schemas\";\nimport { ExportedCookieSchema } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\n\nimport { getCookie } from \"./getCookie\";\nimport { renderCookies } from \"./renderCookies\";\n\n/**\n * Retrieves and renders cookies in a grouped format based on their source files.\n * @param cookieSpec - The cookie specification containing search criteria\n * @param cookieSpec.name - The name of the cookie to search for\n * @param cookieSpec.domain - (optional) The domain to filter cookies by\n * @param options - Options for rendering the cookies\n * @param options.showFilePaths - Whether to include file paths in the output\n * @param options.separator - Custom separator for cookie values\n * @returns An array of strings, each representing a group of cookies from a source file\n * @example\n * ```typescript\n * // Basic usage - get all cookies named \"sessionId\" grouped by source file\n * const cookies = await getGroupedRenderedCookies({ name: \"sessionId\" });\n *\n * // Get cookies with domain filter and custom rendering options\n * const domainCookies = await getGroupedRenderedCookies(\n * {\n * name: \"userPref\",\n * domain: \"example.com\"\n * },\n * {\n * showFilePaths: true,\n * separator: \" | \"\n * }\n * );\n * ```\n */\nexport async function getGroupedRenderedCookies(\n cookieSpec: CookieSpec,\n options: Omit<RenderOptions, \"format\"> = {},\n): Promise<string[]> {\n try {\n const cookies = await getCookie(cookieSpec);\n if (!Array.isArray(cookies)) {\n return [];\n }\n\n // Validate each cookie against the schema\n const validatedCookies = cookies.filter(\n (cookie): cookie is ExportedCookie => {\n const result = ExportedCookieSchema.safeParse(cookie);\n if (!result.success) {\n logger.warn(\"Invalid cookie format:\", result.error.format());\n return false;\n }\n return true;\n },\n );\n\n return renderCookies(validatedCookies, {\n ...options,\n format: \"grouped\",\n }) as string[];\n } catch (error: unknown) {\n logger.warn(\n \"Error getting grouped rendered cookies:\",\n error instanceof Error ? error.message : String(error),\n );\n return [];\n }\n}\n\n/**\n * Default export of the getGroupedRenderedCookies function\n * @example\n * ```typescript\n * import getGroupedCookies from './getGroupedRenderedCookies';\n *\n * // Get all session cookies with custom separator\n * const sessionCookies = await getGroupedCookies(\n * { name: \"session_*\" },\n * { separator: \"\\n\" }\n * );\n *\n * // Get cookies from multiple domains\n * const multiDomainCookies = await getGroupedCookies({\n * name: \"tracking\",\n * domain: [\"site1.com\", \"site2.com\"]\n * });\n * ```\n */\nexport default getGroupedRenderedCookies;\n","import type {\n RenderOptions,\n CookieSpec,\n ExportedCookie,\n} from \"../../types/schemas\";\nimport { ExportedCookieSchema } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\n\nimport { getCookie } from \"./getCookie\";\nimport { renderCookies } from \"./renderCookies\";\n\n/**\n * Retrieves and renders cookies in a merged format\n * @param cookieSpec - The cookie specification to query\n * @param options - Optional rendering options\n * @returns Promise resolving to rendered cookie string\n * @example\n * ```typescript\n * const cookieString = await getMergedRenderedCookies(\n * { name: 'session', domain: 'example.com' },\n * { separator: '; ' }\n * );\n * console.log(cookieString); // \"session=abc123; auth=xyz789\"\n * ```\n */\nexport async function getMergedRenderedCookies(\n cookieSpec: CookieSpec,\n options?: Omit<RenderOptions, \"format\">,\n): Promise<string> {\n try {\n const cookies = await getCookie(cookieSpec);\n if (!Array.isArray(cookies)) {\n return \"\";\n }\n\n // Validate each cookie against the schema\n const validatedCookies = cookies.filter(\n (cookie): cookie is ExportedCookie => {\n const result = ExportedCookieSchema.safeParse(cookie);\n if (!result.success) {\n logger.warn(\"Invalid cookie format:\", result.error.format());\n return false;\n }\n return true;\n },\n );\n\n const result = renderCookies(validatedCookies, {\n ...options,\n format: \"merged\",\n });\n return typeof result === \"string\" ? result : \"\";\n } catch (error: unknown) {\n logger.warn(\n \"Error getting merged rendered cookies:\",\n error instanceof Error ? error.message : String(error),\n );\n return \"\";\n }\n}\n\n/**\n * Default export of the getMergedRenderedCookies function.\n * @example\n * ```typescript\n * import { getMergedRenderedCookies } from './getMergedRenderedCookies';\n * const cookies = await getMergedRenderedCookies({\n * name: 'sessionId',\n * domain: 'example.com'\n * });\n * ```\n */\nexport default getMergedR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H,CAAU,EAC1C,GAAI,CAAC,MAAM,QAAQE,CAAO,EACxB,MAAO,GAIT,IAAME,EAAmBF,EAAQ,OAC9BG,GAAqC,CACpC,IAAMC,EAASC,EAAqB,UAAUF,CAAM,EACpD,OAAKC,EAAO,QAIL,IAHLE,EAAO,KAAK,yBAA0BF,EAAO,MAAM,OAAO,CAAC,EACpD,GAGX,CACF,EAEMA,EAASG,EAAcL,EAAkB,CAC7C,GAAGH,EACH,OAAQ,QACV,CAAC,EACD,OAAO,OAAOK,GAAW,SAAWA,EAAS,EAC/C,OAASI,EAAgB,CACvB,OAAAF,EAAO,KACL,yCACAE,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CACvD,EACO,EACT,CACF","names":["existsSync","join","glob","homedir","join","chromeApplicationSupport","home","BetterSqlite3","openDatabase","file","BetterSqlite3","error","logError","closeDatabase","db","querySqliteThenTransform","sql","params","rowFilter","rowTransform","rows","filteredRows","isValidFilePath","path","trimmedPath","existsSync","getCookieFiles","patterns","join","chromeApplicationSupport","files","pattern","matches","glob","logDebug","buildSqlQuery","name","domain","isWildcard","sql","params","processCookieFile","cookieFile","rows","querySqliteThenTransform","row","logOperationResult","error","logError","getEncryptedChromeCookie","file","cookieFiles","results","cookies","readFileSync","join","fg","consola","logger_default","listChromeProfilePaths","files","fg","chromeApplicationSupport","createDecipheriv","pbkdf2","memoize","removeV10Prefix","value","removePadding","decrypted","padding","extractValue","decodedString","cleanupPatterns","pattern","decrypt","encryptedValue","password","resolve","reject","error","key","iv","decipher","e","memoize","getChromePassword","memoize","logError","getMacOSPassword","password","logDebug","error","getExpiryDate","expiry","createExportedCookie","domain","name","value","file","decrypted","ChromeCookieQueryStrategy","createTaggedLogger","cookieFiles","listChromeProfilePaths","password","getChromePassword","error","logError","encryptedCookies","getEncryptedChromeCookie","context","cookie","result","decryptedValue","decrypt","homedir","join","fg","findFirefoxCookieFiles","home","homedir","logWarn","patterns","join","files","pattern","matches","fg","logDebug","FirefoxCookieQueryStrategy","name","domain","results","file","cookies","querySqliteThenTransform","row","error","homedir","join","Buffer","readFileSync","homedir","join","Buffer","destr","z","CookieDomainSchema","domain","CookieNameSchema","name","CookiePathSchema","path","CookieValueSchema","value","BinaryCookieRowSchema","CookieSpecSchema","CookieMetaSchema","ExportedCookieSchema","CookieRowSchema","RenderOptionsSchema","BrowserNameSchema","CookieQueryStrategySchema","BinaryCodableCookie","buffer","container","value","processed","lastProcessed","token","parts","payload","Buffer","parsed","decoded","jwtPayload","jsonValue","flagsValue","domain","BinaryCookieRowSchema","offset","end","size","hasPort","offsets","expirationBuffer","i","expiration","creationBuffer","creation","offsetEntries","entry","a","b","field","length","baseOffset","_BinaryCodablePage","buffer","container","cookies","cookie","cookieRow","error","errorMessage","logWarn","header","cookieCount","pageStart","cookieOffsets","i","cookieOffset","footer","absoluteOffset","cookieSize","cookieBuffer","BinaryCodableCookie","BinaryCodablePage","_BinaryCodableCookies","buffer","container","path","readFileSync","cookies","page","pageCookies","error","errorMessage","logWarn","magic","pageCount","pageSizes","i","currentOffset","pageSize","pageBuffer","BinaryCodablePage","_checksum","footer","_plistData","Buffer","join","homedir","BinaryCodableCookies","decodeBinaryCookies","cookieDbPath","BinaryCodableCookies","SafariCookieQueryStrategy","home","join","cookieDbPath","name","domain","decodeBinaryCookies","cookie","error","logError","homedir","queryCookies","cookieSpec","name","domain","strategies","ChromeCookieQueryStrategy","FirefoxCookieQueryStrategy","SafariCookieQueryStrategy","strategy","result","getCookie","cookieSpec","queryCookies","error","logger_default","getChromeCookie","cookieSpec","ChromeCookieQueryStrategy","error","logger_default","getFirefoxCookie","cookieSpec","FirefoxCookieQueryStrategy","error","logger_default","groupBy","renderCookies","cookies","options","format","showFilePaths","separator","c","groupedByFile","file","fileCookies","values","getGroupedRenderedCookies","cookieSpec","options","cookies","getCookie","validatedCookies","cookie","result","ExportedCookieSchema","logger_default","renderCookies","error","getMergedRenderedCookies","cookieSpec","options","cookies","getCookie","validatedCookies","cookie","result","ExportedCookieSchema","logger_default","renderCookies","error"]}
1
+ {"version":3,"sources":["../src/utils/logger.ts","../src/config.ts","../src/utils/logHelpers.ts","../src/core/browsers/getEncryptedChromeCookie.ts","../src/core/browsers/chrome/ChromeApplicationSupport.ts","../src/core/browsers/QuerySqliteThenTransform.ts","../src/core/browsers/listChromeProfiles.ts","../src/core/browsers/chrome/decrypt.ts","../src/core/browsers/chrome/getChromePassword.ts","../src/utils/execSimple.ts","../src/core/browsers/chrome/macos/getChromePassword.ts","../src/core/browsers/chrome/ChromeCookieQueryStrategy.ts","../src/core/browsers/firefox/FirefoxCookieQueryStrategy.ts","../src/core/browsers/safari/SafariCookieQueryStrategy.ts","../src/core/browsers/safari/BinaryCodableCookies.ts","../src/core/browsers/safari/BinaryCodableCookie.ts","../src/types/schemas.ts","../src/core/browsers/safari/BinaryCodablePage.ts","../src/core/browsers/safari/decodeBinaryCookies.ts","../src/core/cookies/queryCookies.ts","../src/core/cookies/getCookie.ts","../src/core/cookies/getChromeCookie.ts","../src/core/cookies/getFirefoxCookie.ts","../src/core/cookies/renderCookies.ts","../src/core/cookies/getGroupedRenderedCookies.ts","../src/core/cookies/getMergedRenderedCookies.ts"],"sourcesContent":["import { type ConsolaInstance, createConsola } from \"consola\";\n\nimport { env } from \"../config\";\n\n/**\n * Standard log levels and their usage:\n * - debug: Detailed information for debugging\n * - info: General operational information\n * - success: Successful operations\n * - warn: Warning conditions\n * - error: Error conditions that might still allow the app to continue\n * - fatal: Critical errors that prevent the app from continuing\n */\nconst consola = createConsola({\n fancy: true,\n formatOptions: {\n showLogLevel: false,\n colors: true,\n date: false,\n compact: true,\n columns:\n typeof process.stdout.columns === \"number\" ? process.stdout.columns : 80,\n },\n level: env.LOG_LEVEL === \"debug\" ? 5 : 2,\n});\n\n/**\n * Indicates whether debug logging is enabled\n * @example\n * if (isDebug) {\n * logger.debug(\"Detailed debugging information\");\n * }\n */\nexport const isDebug = env.LOG_LEVEL === \"debug\";\n\n/**\n * Configured logger instance with standardized formatting and colored output.\n * Used for consistent logging throughout the application.\n * @example\n * // Basic usage\n * logger.info('Operation started');\n * logger.success('Task completed');\n * logger.error('Failed to process', error);\n *\n * // Tagged logging for module context\n * const moduleLogger = logger.withTag('ModuleName');\n * moduleLogger.info('Module specific log');\n *\n * // Structured logging\n * logger.info('User action', {\n * userId: '123',\n * action: 'login',\n * timestamp: new Date()\n * });\n *\n * // Error logging with full context\n * logger.error('Operation failed', {\n * error: error,\n * context: 'operation name',\n * input: data\n * });\n */\nconst logger: ConsolaInstance = consola;\n\n/**\n *\n */\nexport default logger;\n","import { homedir } from \"os\";\n\nimport { config } from \"dotenv\";\nimport { z } from \"zod\";\n\n// Load environment variables from .env file\nconfig();\n\nconst EnvironmentSchema = z.object({\n LOG_LEVEL: z.enum([\"debug\", \"info\", \"warn\", \"error\"]).default(\"info\"),\n HOME: z\n .string()\n .optional()\n .transform((val) => val ?? process.env.USERPROFILE ?? \"\")\n .pipe(z.string().min(1)),\n});\n\n/**\n * Validated environment variables with type safety and fallbacks\n * @example\n * // Using the environment variables\n * if (env.LOG_LEVEL === \"debug\") {\n * console.log(\"Debug mode enabled\");\n * }\n *\n * // Accessing home directory\n * const cookiePath = join(env.HOME, \"Library/Cookies\");\n */\nexport const env = EnvironmentSchema.parse({\n LOG_LEVEL: process.env.LOG_LEVEL,\n HOME: homedir(),\n});\n","import { type ConsolaInstance } from \"consola\";\n\nimport logger from \"./logger\";\n\n/**\n * Helper functions for common logging patterns.\n * @module\n * @example\n * ```typescript\n * import { logOperationResult, logError } from './logHelpers';\n *\n * try {\n * const result = await someOperation();\n * logOperationResult('Operation', true, { data: result });\n * } catch (error) {\n * logError('Operation failed', error);\n * }\n * ```\n */\n\ninterface OperationContext {\n [key: string]: unknown;\n}\n\n/**\n * Log the result of an operation with consistent formatting\n * @param operation - The name of the operation\n * @param success - Whether the operation was successful\n * @param context - Additional context to log\n */\nexport function logOperationResult(\n operation: string,\n success: boolean,\n context?: OperationContext,\n): void {\n if (success) {\n logger.success(`${operation} succeeded`, context);\n } else {\n logger.error(`${operation} failed`, context);\n }\n}\n\n/**\n * Log an error with consistent formatting\n * @param message - The error message\n * @param error - The error object\n * @param context - Additional context to log\n */\nexport function logError(\n message: string,\n error: unknown,\n context?: OperationContext,\n): void {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error(message, { ...context, error: errorMessage });\n}\n\n/**\n * Log a warning with consistent formatting\n * @param component - The component generating the warning\n * @param message - The warning message\n * @param context - Additional context to log\n */\nexport function logWarn(\n component: string,\n message: string,\n context?: OperationContext,\n): void {\n logger.warn(`[${component}] ${message}`, context);\n}\n\n/**\n * Create a logger instance with a component tag\n * @param component - The component name to tag logs with\n * @returns A logger instance that prefixes all messages with the component tag\n * @example\n * ```typescript\n * const dbLogger = createTaggedLogger('Database');\n * dbLogger.info('Connection established');\n * ```\n */\nexport function createTaggedLogger(component: string): ConsolaInstance {\n return logger.withTag(component);\n}\n\n// Re-export the base logger for direct usage\n/**\n * Re-export of the base logger for direct usage.\n */\nexport { default as logger } from \"./logger\";\n","import { existsSync } from \"fs\";\nimport { join } from \"path\";\n\nimport glob from \"fast-glob\";\n\nimport {\n logError,\n logOperationResult,\n createTaggedLogger,\n} from \"@utils/logHelpers\";\n\nimport type { CookieRow } from \"../../types/schemas\";\n\nimport { chromeApplicationSupport } from \"./chrome/ChromeApplicationSupport\";\nimport { querySqliteThenTransform } from \"./QuerySqliteThenTransform\";\n\nconst logger = createTaggedLogger(\"getEncryptedChromeCookie\");\n\ninterface ChromeCookieRow {\n encrypted_value: Buffer;\n name: string;\n host_key: string;\n expires_utc: number;\n}\n\ninterface GetEncryptedCookieOptions {\n name: string;\n domain: string;\n file?: string;\n}\n\ninterface SqlQuery {\n sql: string;\n params: string[];\n}\n\n/**\n * Validates if a path is a valid, existing file\n * @param path - Path to validate\n * @returns true if path is valid and file exists, false otherwise\n */\nfunction isValidFilePath(path: unknown): path is string {\n if (typeof path !== \"string\") {\n return false;\n }\n\n const trimmedPath = path.trim();\n if (trimmedPath.length === 0) {\n return false;\n }\n\n return existsSync(trimmedPath);\n}\n\n/**\n * Get paths to Chrome cookie files\n * @returns A promise that resolves to an array of file paths\n */\nasync function getCookieFiles(): Promise<string[]> {\n const patterns = [\n join(chromeApplicationSupport, \"Default/Cookies\"),\n join(chromeApplicationSupport, \"Profile */Cookies\"),\n join(chromeApplicationSupport, \"Profile Default/Cookies\"),\n ];\n\n const files: string[] = [];\n for (const pattern of patterns) {\n const matches = await glob(pattern);\n files.push(...matches);\n }\n\n logger.debug(\"ChromeCookies\", \"Found cookie files\", {\n count: files.length,\n files,\n });\n return files;\n}\n\n/**\n * Builds the SQL query for retrieving cookies\n * @param name - Cookie name to search for\n * @param domain - Domain to filter by\n * @returns SQL query and parameters\n */\nfunction buildSqlQuery(name: string, domain: string): SqlQuery {\n const isWildcard = name === \"%\";\n const sql = isWildcard\n ? `SELECT name, encrypted_value, host_key, expires_utc FROM cookies WHERE host_key LIKE ?`\n : `SELECT name, encrypted_value, host_key, expires_utc FROM cookies WHERE name = ? AND host_key LIKE ?`;\n const params = isWildcard ? [`%${domain}%`] : [name, `%${domain}%`];\n\n return { sql, params };\n}\n\n/**\n * Processes a single cookie file to extract matching cookies\n * @param cookieFile - Path to the cookie file\n * @param name - Cookie name to search for\n * @param domain - Domain to filter by\n * @returns Array of matching cookies\n */\nasync function processCookieFile(\n cookieFile: string,\n name: string,\n domain: string,\n): Promise<CookieRow[]> {\n try {\n const { sql, params } = buildSqlQuery(name, domain);\n logger.debug(\"ChromeCookies\", \"Executing query\", { sql, params });\n\n const rows = await querySqliteThenTransform<ChromeCookieRow, CookieRow>({\n file: cookieFile,\n sql,\n params,\n rowTransform: (row: ChromeCookieRow): CookieRow => ({\n name: row.name,\n domain: row.host_key,\n value: row.encrypted_value,\n expiry: row.expires_utc,\n }),\n });\n\n logOperationResult(\"QueryCookies\", true, {\n file: cookieFile,\n count: rows.length,\n });\n return rows;\n } catch (error) {\n logError(\"Failed to read cookie file\", error, { file: cookieFile });\n return [];\n }\n}\n\n/**\n * Retrieve encrypted cookies from Chrome's cookie store\n * @param options - Options for querying Chrome cookies\n * @param options.name - The name of the cookie to retrieve\n * @param options.domain - The domain to retrieve cookies from\n * @param options.file - Optional specific cookie file to query\n * @returns Promise resolving to array of encrypted cookies\n */\nexport async function getEncryptedChromeCookie({\n name,\n domain,\n file,\n}: GetEncryptedCookieOptions): Promise<CookieRow[]> {\n const cookieFiles =\n typeof file === \"string\" && file.length > 0\n ? [file]\n : await getCookieFiles();\n\n if (cookieFiles.length === 0) {\n logger.debug(\"ChromeCookies\", \"No cookie files found\");\n return [];\n }\n\n const results: CookieRow[] = [];\n for (const cookieFile of cookieFiles) {\n if (!isValidFilePath(cookieFile)) {\n logger.debug(\"ChromeCookies\", \"Cookie file missing or invalid\", {\n file: cookieFile,\n });\n continue;\n }\n\n const cookies = await processCookieFile(cookieFile, name, domain);\n results.push(...cookies);\n }\n\n logger.debug(\"ChromeCookies\", \"Query complete\", {\n totalCookies: results.length,\n });\n return results;\n}\n","import { homedir } from \"os\";\nimport { join } from \"path\";\n\n/**\n * The path to Chrome's application support directory on macOS\n * This constant is used to locate Chrome's profile and cookie storage directories\n * @throws {Error} If unable to determine user's home directory\n */\nexport const chromeApplicationSupport = (() => {\n const home = homedir();\n if (!home) {\n throw new Error(\"Unable to determine user home directory\");\n }\n return join(home, \"Library\", \"Application Support\", \"Google\", \"Chrome\");\n})();\n","// External imports\nimport BetterSqlite3, { Database } from \"better-sqlite3\";\n\n// Internal imports\nimport { logError } from \"@utils/logHelpers\";\n\ninterface QuerySqliteThenTransformOptions<TRow, TResult> {\n file: string;\n sql: string;\n params?: unknown[];\n rowFilter?: (row: TRow) => boolean;\n rowTransform?: (row: TRow) => TResult;\n}\n\nfunction openDatabase(file: string): Database {\n try {\n return new BetterSqlite3(file, { readonly: true, fileMustExist: true });\n } catch (error) {\n logError(\"Database open failed\", error, { file });\n throw error;\n }\n}\n\nfunction closeDatabase(db: Database): Promise<void> {\n try {\n db.close();\n return Promise.resolve();\n } catch (error) {\n logError(\"Database close failed\", error);\n return Promise.reject(\n error instanceof Error\n ? error\n : new Error(\"Failed to close database: Unknown error\"),\n );\n }\n}\n\n/**\n * Executes a SQL query on a SQLite database file and transforms the results\n * @param root0 - The options object containing query parameters\n * @param root0.file - The path to the SQLite database file\n * @param root0.sql - The SQL query to execute\n * @param root0.params - Optional parameters for the SQL query\n * @param root0.rowFilter - Optional function to filter rows from the result set\n * @param root0.rowTransform - Optional function to transform each row before returning\n * @returns A promise that resolves to an array of transformed results\n */\nexport async function querySqliteThenTransform<TRow, TResult>({\n file,\n sql,\n params,\n rowFilter,\n rowTransform,\n}: QuerySqliteThenTransformOptions<TRow, TResult>): Promise<TResult[]> {\n let db: Database | undefined;\n\n try {\n db = openDatabase(file);\n const stmt = db.prepare(sql);\n const rows = stmt.all(params) as TRow[];\n\n const filteredRows = rowFilter ? rows.filter(rowFilter) : rows;\n const transformedRows = rowTransform\n ? filteredRows.map(rowTransform)\n : (filteredRows as unknown as TResult[]);\n\n return transformedRows;\n } catch (error) {\n logError(\"Database query failed\", error, { file, sql });\n throw error;\n } finally {\n if (db) {\n await closeDatabase(db);\n }\n }\n}\n","// External imports\nimport { readFileSync } from \"fs\";\nimport { join } from \"path\";\n\nimport fg from \"fast-glob\";\n\n// Internal imports\nimport { createTaggedLogger } from \"../../utils/logHelpers\";\n\nimport { chromeApplicationSupport } from \"./chrome/ChromeApplicationSupport\";\n\nconst logger = createTaggedLogger(\"listChromeProfiles\");\n\n/**\n * Lists all Chrome profile paths that contain cookie files\n * @internal\n * @returns An array of absolute paths to Chrome cookie files\n * @throws {Error} If Chrome's application support directory cannot be accessed\n * @example\n * ```typescript\n * // Get all Chrome cookie file paths\n * const cookiePaths = listChromeProfilePaths();\n * // Returns: [\n * // '/Users/name/Library/Application Support/Chrome/Profile 1/Cookies',\n * // '/Users/name/Library/Application Support/Chrome/Profile 2/Cookies'\n * // ]\n *\n * // Handle errors\n * try {\n * const paths = listChromeProfilePaths();\n * } catch (error) {\n * logger.error('Failed to access Chrome profiles', { error });\n * }\n * ```\n */\nexport function listChromeProfilePaths(): string[] {\n const files: string[] = fg.sync(`./**/Cookies`, {\n cwd: chromeApplicationSupport,\n absolute: true,\n });\n\n logger.debug(\"Found cookie files:\", files);\n return files;\n}\n\n/**\n * Chrome Local State file structure\n * @internal\n */\ninterface ChromeLocalState {\n profile: {\n info_cache: Record<string, ChromeProfileInfo>;\n };\n}\n\n/**\n * Chrome profile information structure\n * @property {string} name - The name of the profile\n * @property {number} active_time - Unix timestamp of last profile activity\n * @property {string} account_id - Unique identifier for the Chrome profile\n * @property {Record<string, unknown>} accountcapabilities - Account feature flags\n * @property {string} email - User's email address\n * @property {string} full_name - User's full name\n * @property {boolean} is_using_default_avatar - Whether using default profile picture\n * @property {boolean} is_using_default_name - Whether using default profile name\n * @property {string} last_downloaded_gaia_picture_url_with_size - Profile picture URL\n * @property {string} local_auth_credentials - Authentication credentials\n * @property {string} shortcut_name - Profile shortcut name\n * @property {string} user_name - Username associated with profile\n */\ninterface ChromeProfileInfo {\n /** The name of the profile */\n name: string;\n /** Unix timestamp of last profile activity */\n active_time: number;\n /** Unique identifier for the Chrome profile */\n account_id: string;\n /** Account feature flags */\n accountcapabilities: Record<string, unknown>;\n /** User's email address */\n email: string;\n /** User's full name */\n full_name: string;\n /** Whether using default profile picture */\n is_using_default_avatar: boolean;\n /** Whether using default profile name */\n is_using_default_name: boolean;\n /** Profile picture URL */\n last_downloaded_gaia_picture_url_with_size: string;\n /** Authentication credentials */\n local_auth_credentials: string;\n /** Profile shortcut name */\n shortcut_name: string;\n /** Username associated with profile */\n user_name: string;\n}\n\n/**\n * Lists all Chrome profiles and their associated information\n * @internal\n * @returns An array of Chrome profile information objects. Returns empty array if profiles cannot be read\n * @throws {Error} If Chrome's application support directory cannot be accessed\n * @example\n * ```typescript\n * // Get all Chrome profiles\n * const profiles = listChromeProfiles();\n * // Returns: [\n * // {\n * // name: \"Default\",\n * // email: \"user@example.com\",\n * // full_name: \"John Doe\",\n * // ...\n * // },\n * // ...\n * // ]\n *\n * // Handle empty or error case\n * const profiles = listChromeProfiles();\n * if (profiles.length === 0) {\n * logger.warn('No Chrome profiles found');\n * }\n * ```\n */\nexport function listChromeProfiles(): ChromeProfileInfo[] {\n try {\n const localStatePath = join(chromeApplicationSupport, \"Local State\");\n const localState = JSON.parse(\n readFileSync(localStatePath, \"utf8\"),\n ) as ChromeLocalState;\n return Object.values(localState.profile.info_cache);\n } catch (error) {\n logger.debug(\"Failed to access Chrome profiles\", { error });\n return [];\n }\n}\n","// External imports\nimport { createDecipheriv, pbkdf2 } from \"crypto\";\n\nimport { memoize } from \"lodash-es\";\n\n/**\n * Removes the v10 prefix from the encrypted value if present\n * @param value - The encrypted value\n * @returns The value without the v10 prefix\n */\nconst removeV10Prefix = memoize(\n (value: Buffer): Buffer => {\n if (\n value.length >= 3 &&\n value[0] === 0x76 && // 'v'\n value[1] === 0x31 && // '1'\n value[2] === 0x30\n ) {\n // '0'\n return value.slice(3);\n }\n return value;\n },\n (value: Buffer) => value.toString(\"hex\"),\n);\n\n/**\n * Removes PKCS7 padding from the decrypted value\n * @param decrypted - The decrypted buffer\n * @returns The buffer without padding\n */\nconst removePadding = memoize(\n (decrypted: Buffer): Buffer => {\n const padding = decrypted[decrypted.length - 1];\n if (padding && padding <= 16) {\n return decrypted.slice(0, -padding);\n }\n return decrypted;\n },\n (decrypted: Buffer) => decrypted.toString(\"hex\"),\n);\n\n/**\n * Extracts the actual value from the decoded string by removing Chrome's prefixes\n * @param decodedString - The decoded string to clean up\n * @returns The cleaned up value\n */\nfunction extractValue(decodedString: string): string {\n const cleanupPatterns = [\n /.*?0t(.+)$/, // Pattern ending in \"0t\" followed by value\n /.*?1e`(.+)$/, // Pattern ending in \"1e`\" followed by value\n /.*?[`'](.+)$/, // Any backtick or quote followed by value\n /[^\\x20-\\x7E]*([\\x20-\\x7E].+)$/, // Non-printable chars followed by printable chars\n ];\n\n for (const pattern of cleanupPatterns) {\n const match = decodedString.match(pattern);\n const value = match?.[1] ?? \"\";\n if (value.length > 0) {\n return value;\n }\n }\n return decodedString;\n}\n\n/**\n * Decrypts Chrome's encrypted cookie values\n * @param encryptedValue - The encrypted cookie value as a Buffer\n * @param password - The Chrome encryption password\n * @returns A promise that resolves to the decrypted cookie value\n * @throws {Error} If decryption fails\n * @example\n */\nexport async function decrypt(\n encryptedValue: Buffer,\n password: string,\n): Promise<string> {\n if (typeof password !== \"string\") {\n throw new Error(\"password must be a string\");\n }\n if (!Buffer.isBuffer(encryptedValue)) {\n throw new Error(\"encryptedData must be a Buffer\");\n }\n\n return new Promise((resolve, reject) => {\n pbkdf2(password, \"saltysalt\", 1003, 16, \"sha1\", (error, key) => {\n try {\n if (error) {\n reject(new Error(\"Failed to derive key: \" + error.message));\n return;\n }\n\n const value = removeV10Prefix(encryptedValue);\n if (value.length % 16 !== 0) {\n reject(new Error(\"Encrypted data length is not a multiple of 16\"));\n return;\n }\n\n // Chrome's encryption parameters\n const iv = Buffer.alloc(16, \" \"); // 16 spaces\n const decipher = createDecipheriv(\"aes-128-cbc\", key, iv);\n decipher.setAutoPadding(false);\n\n // Decrypt the value\n let decrypted = decipher.update(value);\n try {\n decipher.final();\n } catch (e) {\n reject(\n new Error(\"Failed to finalize decryption: \" + (e as Error).message),\n );\n return;\n }\n\n decrypted = removePadding(decrypted);\n const decodedString = decrypted.toString(\"utf8\");\n resolve(extractValue(decodedString));\n } catch (e) {\n reject(new Error(\"Decryption failed: \" + (e as Error).message));\n }\n });\n });\n}\n","import { platform } from \"os\";\n\nimport { getChromePassword as getMacOSPassword } from \"./macos/getChromePassword\";\n\n/**\n * Gets the Chrome Safe Storage password for the current platform.\n * This password is used to decrypt cookies stored in Chrome's cookie database.\n * Currently only supports macOS, where the password is stored in the system keychain.\n * @returns A promise that resolves to the Chrome Safe Storage password\n * @throws {Error} If the password cannot be retrieved or the platform is not supported\n */\nexport async function getChromePassword(): Promise<string> {\n switch (platform()) {\n case \"darwin\": {\n return getMacOSPassword();\n }\n default:\n throw new Error(`Platform ${platform()} is not supported`);\n }\n}\n","// External imports\nimport { exec, ExecOptions } from \"child_process\";\nimport { promisify } from \"util\";\n\n// Internal imports\nimport { logError } from \"./logHelpers\";\n\nconst execPromise = promisify(exec);\n\n/**\n * Custom error class for command execution failures.\n * @property {string} command - The command that failed to execute\n * @property {Error} [originalError] - The underlying error that caused the failure\n * @throws CommandExecutionError Always throws with appropriate error context\n * @example\n * ```typescript\n * throw new CommandExecutionError(\n * 'Command timed out',\n * 'git status',\n * originalError\n * );\n * ```\n */\nclass CommandExecutionError extends Error {\n public constructor(\n message: string,\n public readonly command: string,\n public readonly originalError?: Error,\n ) {\n super(message);\n this.name = \"CommandExecutionError\";\n }\n}\n\n/**\n * Executes a shell command and returns its output.\n * @param command - The command to execute\n * @param options - Optional execution options\n * @returns Promise resolving to command output\n * @throws CommandExecutionError if execution fails\n * @example\n * ```typescript\n * try {\n * const { stdout } = await execSimple('git status');\n * logger.info('Git status:', stdout);\n * } catch (error) {\n * if (error instanceof CommandExecutionError) {\n * logger.error('Git command failed:', error.message);\n * }\n * }\n * ```\n */\nexport async function execSimple(\n command: string,\n options?: ExecOptions,\n): Promise<{ stdout: string; stderr: string }> {\n try {\n const result = await execPromise(command, {\n ...options,\n encoding: \"utf8\",\n });\n return {\n stdout: result.stdout.toString(),\n stderr: result.stderr.toString(),\n };\n } catch (error) {\n logError(\"Command execution failed\", error, { command });\n throw new CommandExecutionError(\n error instanceof Error ? error.message : String(error),\n command,\n error instanceof Error ? error : undefined,\n );\n }\n}\n","import { execSimple } from \"../../../../utils/execSimple\";\n\n/**\n * Retrieves the Chrome Safe Storage password from the macOS keychain\n * @returns A promise that resolves to the Chrome Safe Storage password\n * @throws {Error} If the password cannot be retrieved from the keychain\n */\nexport async function getChromePassword(): Promise<string> {\n const command = 'security find-generic-password -w -s \"Chrome Safe Storage\"';\n const result = await execSimple(command);\n return result.stdout.trim();\n}\n","import { createTaggedLogger, logError } from \"@utils/logHelpers\";\n\nimport {\n BrowserName,\n CookieQueryStrategy,\n CookieRow,\n ExportedCookie,\n} from \"../../../types/schemas\";\nimport { getEncryptedChromeCookie } from \"../getEncryptedChromeCookie\";\nimport { listChromeProfilePaths } from \"../listChromeProfiles\";\n\nimport { decrypt } from \"./decrypt\";\nimport { getChromePassword } from \"./getChromePassword\";\n\ninterface DecryptionContext {\n file: string;\n password: string;\n}\n\nfunction getExpiryDate(expiry: number | undefined | null): Date | \"Infinity\" {\n if (typeof expiry !== \"number\" || expiry <= 0) {\n return \"Infinity\";\n }\n return new Date(expiry);\n}\n\nfunction createExportedCookie(\n domain: string,\n name: string,\n value: string,\n expiry: number | undefined | null,\n file: string,\n decrypted: boolean,\n): ExportedCookie {\n return {\n domain,\n name,\n value,\n expiry: getExpiryDate(expiry),\n meta: {\n file,\n browser: \"Chrome\",\n decrypted,\n },\n };\n}\n\n/**\n * Strategy for querying cookies from Chrome browser\n * @example\n * ```typescript\n * const strategy = new ChromeCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * ```\n */\nexport class ChromeCookieQueryStrategy implements CookieQueryStrategy {\n private readonly logger = createTaggedLogger(\"ChromeCookieQueryStrategy\");\n\n /**\n * The browser name for this strategy\n */\n public readonly browserName: BrowserName = \"Chrome\";\n\n /**\n * Queries cookies from Chrome's cookie store\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @param store - Optional path to a specific cookie store file\n * @returns A promise that resolves to an array of exported cookies\n * @example\n * ```typescript\n * const strategy = new ChromeCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * console.log(cookies);\n * ```\n */\n public async queryCookies(\n name: string,\n domain: string,\n store?: string,\n ): Promise<ExportedCookie[]> {\n try {\n this.logger.info(\"Querying cookies\", { name, domain, store });\n\n if (process.platform !== \"darwin\") {\n this.logger.warn(\"Platform not supported\", {\n platform: process.platform,\n });\n return [];\n }\n\n const cookieFiles = store ?? listChromeProfilePaths();\n const files = Array.isArray(cookieFiles) ? cookieFiles : [cookieFiles];\n if (files.length === 0) {\n this.logger.warn(\"No Chrome cookie files found\");\n return [];\n }\n\n const password = await getChromePassword();\n const results = await Promise.all(\n files.map((file) => this.processFile(file, name, domain, password)),\n );\n\n return results.flat();\n } catch (error) {\n if (error instanceof Error) {\n logError(\"Failed to query cookies\", error, { name, domain });\n } else {\n logError(\"Failed to query cookies\", new Error(String(error)), {\n name,\n domain,\n });\n }\n return [];\n }\n }\n\n private async processFile(\n file: string,\n name: string,\n domain: string,\n password: string,\n ): Promise<ExportedCookie[]> {\n try {\n const encryptedCookies = await getEncryptedChromeCookie({\n name,\n domain,\n file,\n });\n\n const context: DecryptionContext = { file, password };\n const results = await Promise.allSettled(\n encryptedCookies.map((cookie) => this.processCookie(cookie, context)),\n );\n\n return results\n .map((result) => (result.status === \"fulfilled\" ? result.value : null))\n .filter((cookie): cookie is ExportedCookie => cookie !== null);\n } catch (error) {\n if (error instanceof Error) {\n this.logger.error(\"Failed to process cookie file\", { error, file });\n } else {\n this.logger.error(\"Failed to process cookie file\", {\n error: String(error),\n file,\n });\n }\n return [];\n }\n }\n\n private async processCookie(\n cookie: CookieRow,\n context: DecryptionContext,\n ): Promise<ExportedCookie> {\n try {\n const value = Buffer.isBuffer(cookie.value)\n ? cookie.value\n : Buffer.from(String(cookie.value));\n\n const decryptedValue = await decrypt(value, context.password);\n return createExportedCookie(\n cookie.domain,\n cookie.name,\n decryptedValue,\n cookie.expiry,\n context.file,\n true,\n );\n } catch (error) {\n if (error instanceof Error) {\n this.logger.warn(\"Failed to decrypt cookie\", { error });\n } else {\n this.logger.warn(\"Failed to decrypt cookie\", { error: String(error) });\n }\n return createExportedCookie(\n cookie.domain,\n cookie.name,\n cookie.value.toString(\"utf-8\"),\n cookie.expiry,\n context.file,\n false,\n );\n }\n }\n}\n","import { homedir } from \"os\";\nimport { join } from \"path\";\n\nimport fg from \"fast-glob\";\n\nimport { createTaggedLogger, logWarn } from \"@utils/logHelpers\";\n\nconst logger = createTaggedLogger(\"FirefoxCookieQueryStrategy\");\n\nimport {\n BrowserName,\n CookieQueryStrategy,\n ExportedCookie,\n} from \"../../../types/schemas\";\nimport { querySqliteThenTransform } from \"../QuerySqliteThenTransform\";\n\ninterface FirefoxCookieRow {\n name: string;\n value: string;\n domain: string;\n expiry: number;\n}\n\n/**\n * Find all Firefox cookie database files\n * @returns An array of file paths to Firefox cookie databases\n */\nfunction findFirefoxCookieFiles(): string[] {\n const home = homedir();\n if (!home) {\n logWarn(\"FirefoxCookieQuery\", \"Failed to get home directory\");\n return [];\n }\n\n const patterns = [\n join(home, \"Library/Application Support/Firefox/Profiles/*/cookies.sqlite\"),\n join(home, \".mozilla/firefox/*/cookies.sqlite\"),\n ];\n\n const files: string[] = [];\n for (const pattern of patterns) {\n const matches = fg.sync(pattern);\n files.push(...matches);\n }\n\n logger.debug(\"Found Firefox cookie files\", { files });\n return files;\n}\n\n/**\n * Strategy for querying cookies from Firefox browser\n * @example\n */\nexport class FirefoxCookieQueryStrategy implements CookieQueryStrategy {\n /**\n *\n */\n public readonly browserName: BrowserName = \"Firefox\";\n\n /**\n * Queries cookies from Firefox's cookie store\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @param store - Optional path to a specific cookie store file\n * @returns A promise that resolves to an array of exported cookies\n */\n public async queryCookies(\n name: string,\n domain: string,\n store?: string,\n ): Promise<ExportedCookie[]> {\n const files = store ?? findFirefoxCookieFiles();\n const fileList = Array.isArray(files) ? files : [files];\n const results: ExportedCookie[] = [];\n\n for (const file of fileList) {\n try {\n const cookies = await querySqliteThenTransform<\n FirefoxCookieRow,\n ExportedCookie\n >({\n file,\n sql: \"SELECT name, value, host as domain, expiry FROM moz_cookies WHERE name = ? AND host LIKE ?\",\n params: [name, `%${domain}%`],\n rowTransform: (row) => ({\n name: row.name,\n value: row.value,\n domain: row.domain,\n expiry: row.expiry > 0 ? new Date(row.expiry * 1000) : \"Infinity\",\n meta: {\n file,\n browser: \"Firefox\",\n decrypted: false,\n },\n }),\n });\n\n results.push(...cookies);\n } catch (error) {\n if (error instanceof Error) {\n logWarn(\n \"FirefoxCookieQuery\",\n `Error reading Firefox cookie file ${file}`,\n { error: error.message },\n );\n } else {\n logWarn(\n \"FirefoxCookieQuery\",\n `Error reading Firefox cookie file ${file}`,\n );\n }\n }\n }\n\n return results;\n }\n}\n","import { homedir } from \"os\";\nimport { join } from \"path\";\n\nimport { logError } from \"@utils/logHelpers\";\n\nimport type {\n BrowserName,\n CookieQueryStrategy,\n ExportedCookie,\n} from \"../../../types/schemas\";\n\nimport { decodeBinaryCookies } from \"./decodeBinaryCookies\";\n\n/**\n * Strategy for querying cookies from Safari browser\n */\nexport class SafariCookieQueryStrategy implements CookieQueryStrategy {\n /**\n * The browser name for this strategy\n */\n public readonly browserName: BrowserName = \"Safari\";\n\n /**\n * Gets the path to Safari's cookie database\n * @param home - The user's home directory\n * @returns Path to the cookie database\n */\n private getCookieDbPath(home: string): string {\n return join(\n home,\n \"Library\",\n \"Containers\",\n \"com.apple.Safari\",\n \"Data\",\n \"Library\",\n \"Cookies\",\n \"Cookies.binarycookies\",\n );\n }\n\n /**\n * Formats the domain by removing leading dot if present\n * @param domain - Domain to format\n * @returns Formatted domain\n */\n private formatDomain(domain: string): string {\n return domain.startsWith(\".\") ? domain.slice(1) : domain;\n }\n\n /**\n * Formats the expiry date\n * @param expiry - Expiry timestamp\n * @returns Formatted expiry date\n */\n private formatExpiry(expiry: number): Date | \"Infinity\" {\n if (expiry <= 0) {\n return \"Infinity\";\n }\n return new Date(expiry * 1000);\n }\n\n /**\n * Checks if a flag bit is set\n * @param flags - The flags value\n * @param bit - The bit to check\n * @returns True if the bit is set, false otherwise\n */\n private isFlagSet(flags: number | undefined | null, bit: number): boolean {\n if (typeof flags !== \"number\" || isNaN(flags) || flags <= 0) {\n return false;\n }\n return (flags & bit) === bit;\n }\n\n /**\n * Formats the creation timestamp\n * @param creation - Creation timestamp\n * @returns Formatted creation timestamp or undefined\n */\n private formatCreation(\n creation: number | undefined | null,\n ): number | undefined {\n if (typeof creation !== \"number\" || isNaN(creation) || creation <= 0) {\n return undefined;\n }\n return creation * 1000;\n }\n\n /**\n * Decodes cookies from Safari's binary cookie file\n * @param cookieDbPath - Path to the cookie database\n * @param name - Name of the cookie to find\n * @param domain - Domain to filter cookies by\n * @returns Array of exported cookies\n */\n private decodeCookies(\n cookieDbPath: string,\n name: string,\n domain: string,\n ): ExportedCookie[] {\n try {\n const cookies = decodeBinaryCookies(cookieDbPath);\n return cookies\n .filter(\n (cookie) =>\n (name === \"%\" || cookie.name === name) &&\n (domain === \"%\" ||\n this.formatDomain(cookie.domain).includes(domain)),\n )\n .map((cookie) => ({\n domain: this.formatDomain(cookie.domain),\n name: cookie.name,\n value: Buffer.isBuffer(cookie.value)\n ? cookie.value.toString()\n : String(cookie.value),\n expiry: this.formatExpiry(cookie.expiry),\n meta: {\n file: cookieDbPath,\n browser: \"Safari\" as const,\n decrypted: false,\n secure: this.isFlagSet(cookie.flags, 0x1),\n httpOnly: this.isFlagSet(cookie.flags, 0x4),\n path: cookie.path,\n version: cookie.version,\n comment: cookie.comment,\n commentURL: cookie.commentURL,\n port: cookie.port,\n creation: this.formatCreation(cookie.creation),\n },\n }));\n } catch (error) {\n if (error instanceof Error) {\n logError(\n \"SafariCookieQueryStrategy\",\n `Error decoding ${cookieDbPath}`,\n { error, name, domain },\n );\n } else {\n logError(\n \"SafariCookieQueryStrategy\",\n `Error decoding ${cookieDbPath}`,\n { error: \"Unknown error\", name, domain },\n );\n }\n return [];\n }\n }\n\n /**\n * Query Safari's cookie storage for cookies matching the given criteria\n * @param name - Name of the cookie to find\n * @param domain - Domain to filter cookies by\n * @param store - Optional store path\n * @returns Array of matching cookies, or empty array if none found\n */\n public async queryCookies(\n name: string,\n domain: string,\n store?: string,\n ): Promise<ExportedCookie[]> {\n const home = homedir();\n if (typeof home !== \"string\" || home.length === 0) {\n logError(\"SafariCookieQueryStrategy\", \"Failed to get home directory\");\n return Promise.resolve([]);\n }\n\n const cookieDbPath = store ?? this.getCookieDbPath(home);\n return Promise.resolve(\n this.decodeCookies(cookieDbPath, name || \"%\", domain || \"%\"),\n );\n }\n}\n","import { Buffer } from \"buffer\";\nimport { readFileSync } from \"fs\";\nimport { homedir } from \"os\";\nimport { join } from \"path\";\n\nimport { BinaryCookieRow } from \"../../../types/schemas\";\nimport { logWarn, createTaggedLogger } from \"../../../utils/logHelpers\";\n\nimport { BinaryCodablePage } from \"./BinaryCodablePage\";\nimport { BinaryCodableContainer } from \"./interfaces/BinaryCodableContainer\";\n\nconst logger = createTaggedLogger(\"BinaryCodableCookies\");\n\n/**\n * Represents a binary cookies file structure used by Safari\n */\nexport class BinaryCodableCookies {\n /**\n *\n */\n public pages: BinaryCodablePage[];\n /**\n *\n */\n public metadata: Record<string, unknown>;\n private static readonly MAGIC = Buffer.from(\"cook\", \"utf8\");\n private static readonly FOOTER = BigInt(\"0x071720050000004b\");\n private static readonly DEFAULT_COOKIE_PATH = join(\n homedir(),\n \"Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies\",\n );\n\n /**\n * Creates a new BinaryCookies instance from a buffer\n * @param buffer - The raw binary cookie file data\n */\n public constructor(buffer: Buffer) {\n const container: BinaryCodableContainer = { offset: 0, buffer };\n this.pages = [];\n this.metadata = {};\n this.decode(container);\n }\n\n /**\n * Creates a BinaryCookies instance from a file path\n * @param path - Path to the Safari Cookies.binarycookies file\n * @returns A new BinaryCookies instance\n */\n public static fromFile(path: string): BinaryCodableCookies {\n const buffer = readFileSync(path);\n return new BinaryCodableCookies(buffer);\n }\n\n /**\n * Creates a BinaryCookies instance from the default Safari cookies location\n * @returns A new BinaryCookies instance\n */\n public static fromDefaultPath(): BinaryCodableCookies {\n return BinaryCodableCookies.fromFile(\n BinaryCodableCookies.DEFAULT_COOKIE_PATH,\n );\n }\n\n /**\n * Converts the binary cookie data into a validated array of cookie rows\n * @returns Array of validated cookie objects\n */\n public toCookieRows(): BinaryCookieRow[] {\n const cookies: BinaryCookieRow[] = [];\n\n for (const page of this.pages) {\n try {\n const pageCookies = page.toCookieRows();\n if (Array.isArray(pageCookies)) {\n cookies.push(...pageCookies);\n }\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n logWarn(\"BinaryCookies\", \"Error converting page cookies\", {\n error: errorMessage,\n });\n }\n }\n\n return cookies;\n }\n\n private decode(container: BinaryCodableContainer): void {\n try {\n // Check magic value\n const magic = container.buffer.subarray(\n container.offset,\n container.offset + 4,\n );\n container.offset += 4;\n logger.debug(\"Magic bytes:\", magic.toString());\n if (!magic.equals(BinaryCodableCookies.MAGIC)) {\n throw new Error(\"Missing magic value\");\n }\n\n // Read page count\n const pageCount = container.buffer.readUInt32BE(container.offset);\n logger.debug(\"Page count:\", pageCount);\n container.offset += 4;\n\n // Read page sizes\n const pageSizes: number[] = [];\n for (let i = 0; i < pageCount; i++) {\n const pageSize = container.buffer.readUInt32BE(container.offset);\n pageSizes.push(pageSize);\n logger.debug(`Page ${i} size:`, pageSize);\n container.offset += 4;\n }\n\n // Calculate page offsets\n let currentOffset = container.offset;\n logger.debug(\"Starting page data at offset:\", currentOffset);\n for (const pageSize of pageSizes) {\n try {\n logger.debug(\n \"Reading page at offset:\",\n currentOffset,\n \"with size:\",\n pageSize,\n );\n const pageBuffer = container.buffer.subarray(\n currentOffset,\n currentOffset + pageSize,\n );\n const page = new BinaryCodablePage(pageBuffer);\n this.pages.push(page);\n currentOffset += pageSize;\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n logger.warn(\"Error decoding page:\", { error: errorMessage });\n currentOffset += pageSize; // Skip the problematic page\n }\n }\n container.offset = currentOffset;\n\n // Read checksum\n const checksum = container.buffer.readUInt32BE(container.offset);\n logger.debug(\"Checksum:\", checksum.toString(16));\n container.offset += 4;\n\n // Read footer\n const footer = container.buffer.readBigUInt64BE(container.offset);\n logger.debug(\"Footer:\", footer.toString(16));\n container.offset += 8;\n if (footer !== BinaryCodableCookies.FOOTER) {\n logWarn(\"BinaryCookies\", \"Invalid cookie file format: wrong footer\");\n }\n\n // Read metadata plist\n const _plistData = container.buffer.subarray(container.offset);\n // Note: You'll need to implement or use a plist parser library here\n this.metadata = {}; // Placeholder for plist data\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n logWarn(\"BinaryCookies\", \"Error decoding binary cookies file\", {\n error: errorMessage,\n });\n throw error;\n }\n }\n}\n","import { Buffer } from \"buffer\";\n\nimport { BinaryCookieRow, BinaryCookieRowSchema } from \"../../../types/schemas\";\nimport { createTaggedLogger } from \"../../../utils/logHelpers\";\n\nimport { BinaryCodableContainer } from \"./interfaces/BinaryCodableContainer\";\nimport { BinaryCodableFlags } from \"./interfaces/BinaryCodableFlags\";\nimport { BinaryCodableOffsets } from \"./interfaces/BinaryCodableOffsets\";\n\nconst logger = createTaggedLogger(\"BinaryCodableCookie\");\n\n/**\n * Represents a single cookie within a page\n */\nexport class BinaryCodableCookie {\n /**\n *\n */\n public version = 0;\n /**\n *\n */\n public url = \"\";\n /**\n *\n */\n public port?: number;\n /**\n *\n */\n public name = \"\";\n /**\n *\n */\n public path = \"\";\n /**\n *\n */\n public value = \"\";\n /**\n *\n */\n public comment?: string;\n /**\n *\n */\n public commentURL?: string;\n /**\n *\n */\n public flags: BinaryCodableFlags = {\n isSecure: false,\n isHTTPOnly: false,\n unknown1: false,\n unknown2: false,\n };\n /**\n *\n */\n public expiration = 0;\n /**\n *\n */\n public creation = 0;\n\n /**\n * Creates a new Cookie instance from a buffer\n * @param buffer - The raw binary cookie data\n */\n public constructor(buffer: Buffer) {\n const container: BinaryCodableContainer = { offset: 0, buffer };\n this.decode(container);\n }\n\n private decodeUrlValue(value: string): string {\n let processed = value;\n let lastProcessed;\n do {\n lastProcessed = processed;\n try {\n processed = decodeURIComponent(processed);\n } catch {\n return lastProcessed;\n }\n } while (processed !== lastProcessed && processed.includes(\"%\"));\n return processed;\n }\n\n private decodeJwtPayload(token: string): string | null {\n const parts = token.split(\".\");\n if (parts.length !== 3) {\n return null;\n }\n\n try {\n const payload = Buffer.from(parts[1], \"base64\").toString(\"utf8\");\n const parsed = JSON.parse(payload) as Record<string, unknown>;\n return JSON.stringify(parsed);\n } catch {\n return null;\n }\n }\n\n private parseJsonValue(value: string): string | null {\n try {\n const parsed = JSON.parse(value) as Record<string, unknown>;\n return JSON.stringify(parsed);\n } catch {\n return null;\n }\n }\n\n private processValue(value: string): string {\n // First, try URL decoding\n const decoded = this.decodeUrlValue(value);\n\n // Then, try JWT decoding if it looks like a JWT token\n if (decoded.match(/^ey[A-Za-z0-9_-]+\\.ey[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/)) {\n const jwtPayload = this.decodeJwtPayload(decoded);\n if (typeof jwtPayload === \"string\" && jwtPayload.length > 0) {\n return jwtPayload;\n }\n }\n\n // Finally, try JSON parsing if it looks like JSON\n if (decoded.startsWith(\"{\") || decoded.startsWith(\"[\")) {\n const jsonValue = this.parseJsonValue(decoded);\n if (typeof jsonValue === \"string\" && jsonValue.length > 0) {\n return jsonValue;\n }\n }\n\n return decoded;\n }\n\n /**\n * Converts the cookie to a validated cookie row\n * @returns Validated cookie row object or null if validation fails\n */\n public toCookieRow(): BinaryCookieRow | null {\n try {\n // Convert flags to number\n const flagsValue = this.convertFlags();\n\n // Extract domain from URL\n const domain =\n this.url.replace(/^https?:\\/\\//, \"\").replace(/\\/.*$/, \"\") || \"uk\";\n\n // Convert timestamps from Mac epoch (seconds since 2001-01-01) to Unix epoch (seconds since 1970-01-01)\n const macToUnixOffset = 978307200; // Seconds between 1970-01-01 and 2001-01-01\n const expiryUnix =\n this.expiration > 0\n ? this.expiration + macToUnixOffset\n : this.expiration;\n const creationUnix =\n this.creation > 0 ? this.creation + macToUnixOffset : this.creation;\n\n // Create cookie row with converted timestamps\n const cookieRow = BinaryCookieRowSchema.parse({\n name: this.name.replace(/^: /, \"\"), // Remove leading ': ' if present\n value: this.processValue(this.value) || \"\", // Process and ensure value is never undefined\n domain,\n path: this.path || \"/\",\n expiry: expiryUnix,\n creation: creationUnix,\n flags: flagsValue,\n version: this.version,\n port: this.port,\n comment: this.comment,\n commentURL: this.commentURL,\n });\n\n return cookieRow;\n } catch (_error) {\n return null;\n }\n }\n\n private readNullTerminatedString(\n container: BinaryCodableContainer,\n offset: number,\n ): string {\n let end = offset;\n while (end < container.buffer.length && container.buffer[end] !== 0) {\n end++;\n }\n const value = container.buffer.toString(\"utf8\", offset, end);\n return value || \"\";\n }\n\n private readHeader(container: BinaryCodableContainer): {\n size: number;\n hasPort: number;\n offsets: BinaryCodableOffsets;\n } {\n // Cookie size (4 bytes)\n const size = container.buffer.readUInt32LE(container.offset);\n logger.debug(\"Cookie size:\", size);\n container.offset += 4;\n\n // Version (4 bytes)\n const version = container.buffer.readUInt32LE(container.offset);\n logger.debug(\"Cookie version:\", version);\n container.offset += 4;\n\n // Cookie flags (4 bytes)\n const flagsValue = container.buffer.readUInt32LE(container.offset);\n logger.debug(\"Cookie flags:\", flagsValue.toString(2).padStart(8, \"0\"));\n container.offset += 4;\n this.flags = {\n isSecure: (flagsValue & 1) !== 0,\n isHTTPOnly: (flagsValue & 4) !== 0,\n unknown1: (flagsValue & 8) !== 0,\n unknown2: (flagsValue & 16) !== 0,\n };\n\n // Has port (4 bytes)\n const hasPort = container.buffer.readUInt32LE(container.offset);\n logger.debug(\"Has port:\", hasPort);\n container.offset += 4;\n\n // String offsets (24 bytes total)\n const offsets = {\n urlOffset: container.buffer.readUInt32LE(container.offset),\n nameOffset: container.buffer.readUInt32LE(container.offset + 4),\n pathOffset: container.buffer.readUInt32LE(container.offset + 8),\n valueOffset: container.buffer.readUInt32LE(container.offset + 12),\n commentOffset: container.buffer.readUInt32LE(container.offset + 16),\n commentURLOffset: container.buffer.readUInt32LE(container.offset + 20),\n };\n logger.debug(\"String offsets:\", offsets);\n\n return { size, hasPort, offsets };\n }\n\n private readTimestamps(container: BinaryCodableContainer): void {\n // Read expiration time (8 bytes, little-endian double)\n const expirationBuffer = Buffer.alloc(8);\n for (let i = 0; i < 8; i++) {\n expirationBuffer[i] = container.buffer[container.offset + i];\n }\n const expiration = expirationBuffer.readDoubleLE(0);\n container.offset += 8;\n\n // Read creation time (8 bytes, little-endian double)\n const creationBuffer = Buffer.alloc(8);\n for (let i = 0; i < 8; i++) {\n creationBuffer[i] = container.buffer[container.offset + i];\n }\n const creation = creationBuffer.readDoubleLE(0);\n container.offset += 8;\n\n // Store raw timestamps (seconds since 2001-01-01)\n // For expiration time, 0 means \"session cookie\" (expires when browser closes)\n // For creation time, 0 means \"no creation time recorded\"\n this.expiration = expiration;\n this.creation = creation;\n }\n\n private readStrings(\n container: BinaryCodableContainer,\n size: number,\n offsets: BinaryCodableOffsets,\n ): void {\n // All offsets are relative to the start of the cookie\n const cookieStart = 0; // Offsets are relative to the cookie buffer start\n logger.debug(\"Reading strings from cookie buffer of size:\", size);\n\n // Read strings in order of their offsets\n const offsetEntries = [\n { field: \"url\", offset: offsets.urlOffset },\n { field: \"name\", offset: offsets.nameOffset },\n { field: \"path\", offset: offsets.pathOffset },\n { field: \"value\", offset: offsets.valueOffset },\n { field: \"comment\", offset: offsets.commentOffset },\n ]\n .filter((entry) => entry.offset > 0)\n .sort((a, b) => a.offset - b.offset);\n\n logger.debug(\n \"Reading strings in order:\",\n offsetEntries.map((e) => e.field),\n );\n\n // Calculate string lengths based on offset differences\n for (let i = 0; i < offsetEntries.length; i++) {\n const { field, offset } = offsetEntries[i];\n const nextOffset =\n i < offsetEntries.length - 1 ? offsetEntries[i + 1].offset : size;\n const length = nextOffset - offset;\n\n // Read string up to null terminator\n let end = cookieStart + offset;\n while (\n end < cookieStart + offset + length &&\n container.buffer[end] !== 0\n ) {\n end++;\n }\n const value = container.buffer.toString(\n \"utf8\",\n cookieStart + offset,\n end,\n );\n logger.debug(`Read ${field}:`, value);\n\n switch (field) {\n case \"url\":\n this.url = value;\n break;\n case \"name\":\n this.name = value;\n break;\n case \"path\":\n this.path = value;\n break;\n case \"value\":\n this.value = value;\n break;\n case \"comment\":\n this.comment = value;\n break;\n }\n }\n }\n\n private decode(container: BinaryCodableContainer): void {\n const { size, hasPort, offsets } = this.readHeader(container);\n\n // Skip past all offsets (24 bytes)\n const baseOffset = container.offset;\n container.offset = baseOffset + 24;\n\n this.readTimestamps(container);\n\n if (hasPort > 0) {\n this.port = container.buffer.readUInt16LE(container.offset);\n container.offset += 2;\n }\n\n // Reset offset for string reading\n container.offset = baseOffset;\n this.readStrings(container, size, offsets);\n }\n\n private convertFlags(): number {\n return (\n (this.flags.isSecure ? 0x1 : 0) |\n (this.flags.isHTTPOnly ? 0x4 : 0) |\n (this.flags.unknown1 ? 0x8 : 0) |\n (this.flags.unknown2 ? 0x10 : 0)\n );\n }\n}\n","import destr from \"destr\";\nimport { z } from \"zod\";\n\n/**\n * Zod schema for cookie domain validation.\n * Enforces standard cookie domain rules.\n * @example\n * ```typescript\n * // Valid domains\n * CookieDomainSchema.parse(\"example.com\"); // OK\n * CookieDomainSchema.parse(\".example.com\"); // OK - leading dot is valid\n * CookieDomainSchema.parse(\"sub.example.com\"); // OK\n *\n * // Invalid domains\n * CookieDomainSchema.parse(\"\"); // Error: Domain cannot be empty\n * CookieDomainSchema.parse(\"invalid domain\"); // Error: Invalid domain format\n * ```\n */\nexport const CookieDomainSchema = z\n .string()\n .trim()\n .min(1, \"Domain cannot be empty\")\n .refine(\n (domain) =>\n /^\\.?[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(\n domain,\n ),\n \"Invalid domain format\",\n );\n\n/**\n * Zod schema for cookie name validation.\n * Enforces standard cookie name rules according to RFC 6265.\n * @example\n * ```typescript\n * // Valid names\n * CookieNameSchema.parse(\"session\"); // OK\n * CookieNameSchema.parse(\"auth_token\"); // OK\n * CookieNameSchema.parse(\"user-preference\"); // OK\n *\n * // Invalid names\n * CookieNameSchema.parse(\"\"); // Error: Cookie name cannot be empty\n * CookieNameSchema.parse(\"session;\"); // Error: Invalid cookie name format\n * CookieNameSchema.parse(\"my cookie\"); // Error: Invalid cookie name format\n * ```\n */\nexport const CookieNameSchema = z\n .string()\n .trim()\n .min(1, \"Cookie name cannot be empty\")\n .refine(\n (name) => name === \"%\" || /^[!#$%&'()*+\\-.:0-9A-Z \\^_`a-z|~]+$/.test(name),\n \"Invalid cookie name format - must contain only valid characters (letters, numbers, and certain symbols) or be '%' for wildcard\",\n );\n\n/**\n * Zod schema for cookie path validation.\n * Enforces standard cookie path rules according to RFC 6265.\n * @example\n * ```typescript\n * // Valid paths\n * CookiePathSchema.parse(\"/\"); // OK\n * CookiePathSchema.parse(\"/api\"); // OK\n * CookiePathSchema.parse(\"/path/to/page\"); // OK\n *\n * // Invalid paths\n * CookiePathSchema.parse(\"\"); // Error: Path cannot be empty\n * CookiePathSchema.parse(\"invalid\"); // Error: Path must start with /\n * CookiePathSchema.parse(\"/path?query\"); // Error: Invalid path format\n * ```\n */\nexport const CookiePathSchema = z\n .string()\n .trim()\n .min(1, \"Path cannot be empty\")\n .refine((path) => path.startsWith(\"/\"), \"Path must start with /\")\n .refine(\n (path) => /^\\/[!#$%&'()*+,\\-./:=@\\w~]*$/.test(path),\n \"Invalid path format - must contain only valid URL path characters\",\n )\n .default(\"/\");\n\n/**\n * Zod schema for cookie value.\n * Attempts to parse JSON values using destr for better readability.\n */\nexport const CookieValueSchema = z\n .string()\n .trim()\n .transform((value) => destr(value))\n .pipe(z.any());\n\n/**\n * Zod schema for Safari binary cookie row.\n * Validates and enforces the structure of cookie data read from Safari's Cookies.binarycookies file.\n * @example\n * ```typescript\n * const cookieData = {\n * name: \"session\",\n * value: \"abc123\",\n * domain: \"example.com\",\n * path: \"/\",\n * expiry: 1735689600,\n * creation: 1672531200,\n * flags: 0x5, // Secure + HTTPOnly\n * };\n * const validCookie = BinaryCookieRowSchema.parse(cookieData);\n * ```\n */\nexport const BinaryCookieRowSchema = z.object({\n name: CookieNameSchema,\n value: CookieValueSchema,\n domain: CookieDomainSchema,\n path: CookiePathSchema,\n expiry: z.number().int(),\n creation: z.number().int(),\n flags: z.number().optional(),\n version: z.number().int().optional(),\n port: z.number().int().optional(),\n comment: z.string().optional(),\n commentURL: z.string().optional(),\n});\n\n/**\n * Type representing a decoded Safari binary cookie.\n * This type is inferred from the BinaryCookieRowSchema and includes all cookie properties.\n * @property name - The name of the cookie (non-empty string)\n * @property value - The value stored in the cookie\n * @property domain - The domain the cookie belongs to (non-empty string)\n * @property path - The path where the cookie is valid (defaults to \"/\")\n * @property expiry - Unix timestamp when the cookie expires\n * @property creation - Unix timestamp when the cookie was created\n * @property flags - Optional bit flags (e.g., Secure, HTTPOnly)\n * @property version - Optional cookie version number\n * @property port - Optional port number restriction\n * @property comment - Optional cookie comment\n * @property commentURL - Optional URL for the cookie's comment\n */\nexport type BinaryCookieRow = z.infer<typeof BinaryCookieRowSchema>;\n\n/**\n * Schema for cookie specification parameters\n * Defines the required fields for identifying a cookie\n * @example\n * ```typescript\n * // Validate a cookie specification\n * const spec = {\n * name: 'session',\n * domain: 'example.com'\n * };\n * const result = CookieSpecSchema.safeParse(spec);\n * if (result.success) {\n * logger.info('Valid cookie spec:', result.data);\n * } else {\n * logger.error('Invalid cookie spec:', result.error);\n * }\n *\n * // Invalid spec (empty name)\n * const invalidSpec = {\n * name: '',\n * domain: 'example.com'\n * };\n * // Throws: \"Cookie name cannot be empty\"\n * CookieSpecSchema.parse(invalidSpec);\n * ```\n */\nexport const CookieSpecSchema = z\n .object({\n name: CookieNameSchema,\n domain: CookieDomainSchema,\n })\n .strict();\n\n/**\n * Type definition for cookie specification\n * Used for specifying which cookie to query\n * @example\n * ```typescript\n * // Basic cookie spec\n * const spec: CookieSpec = {\n * name: 'auth',\n * domain: 'api.example.com'\n * };\n *\n * // Use in function parameters\n * function queryCookie(spec: CookieSpec): Promise<ExportedCookie[]> {\n * return getCookie(spec);\n * }\n *\n * // Array of specs\n * const specs: CookieSpec[] = [\n * { name: 'session', domain: 'app.example.com' },\n * { name: 'theme', domain: 'example.com' }\n * ];\n * ```\n */\nexport type CookieSpec = z.infer<typeof CookieSpecSchema>;\n\n/**\n * Schema for metadata about a cookie\n */\nexport const CookieMetaSchema = z\n .object({\n file: z.string().trim().min(1, \"File path cannot be empty\").optional(),\n browser: z.string().trim().optional(),\n decrypted: z.boolean().optional(),\n secure: z.boolean().optional(),\n httpOnly: z.boolean().optional(),\n path: CookiePathSchema.optional(),\n })\n .catchall(z.unknown())\n .strict();\n\n/**\n * Type definition for cookie metadata\n */\nexport type CookieMeta = z.infer<typeof CookieMetaSchema>;\n\n/**\n * Schema for exported cookie data\n * Represents a cookie with all its properties and metadata\n * @example\n * ```typescript\n * // Validate an exported cookie\n * const cookie = {\n * domain: 'example.com',\n * name: 'session',\n * value: 'abc123',\n * expiry: new Date('2024-12-31'),\n * meta: {\n * file: '/path/to/cookies.db'\n * }\n * };\n * const result = ExportedCookieSchema.safeParse(cookie);\n * if (result.success) {\n * logger.info('Valid cookie:', result.data);\n * } else {\n * logger.error('Invalid cookie:', result.error);\n * }\n *\n * // Cookie with infinite expiry\n * const infiniteCookie = {\n * ...cookie,\n * expiry: \"Infinity\"\n * };\n * ExportedCookieSchema.parse(infiniteCookie); // OK\n * ```\n */\nexport const ExportedCookieSchema = z\n .object({\n domain: CookieDomainSchema,\n name: CookieNameSchema,\n value: CookieValueSchema,\n expiry: z\n .union([\n z.literal(\"Infinity\"),\n z.date(),\n z.number().int().positive(\"Expiry must be a positive number\"),\n ])\n .optional(),\n meta: CookieMetaSchema.optional(),\n })\n .strict();\n\n/**\n * Type definition for exported cookie data\n * Represents the structure of a cookie after it has been retrieved\n * @example\n * ```typescript\n * // Basic exported cookie\n * const cookie: ExportedCookie = {\n * domain: 'example.com',\n * name: 'session',\n * value: 'abc123',\n * expiry: new Date('2024-12-31'),\n * meta: {\n * file: '/path/to/cookies.db'\n * }\n * };\n *\n * // Process exported cookies\n * function processCookies(cookies: ExportedCookie[]): string[] {\n * return cookies.map(cookie => `${cookie.name}=${cookie.value}`);\n * }\n *\n * // Filter expired cookies\n * function filterExpired(cookies: ExportedCookie[]): ExportedCookie[] {\n * const now = new Date();\n * return cookies.filter(cookie =>\n * cookie.expiry === \"Infinity\" ||\n * (cookie.expiry instanceof Date && cookie.expiry > now)\n * );\n * }\n * ```\n */\nexport type ExportedCookie = z.infer<typeof ExportedCookieSchema>;\n\n/**\n * Schema for raw cookie data from browser stores\n */\nexport const CookieRowSchema = z\n .object({\n expiry: z.number().int().optional(),\n domain: CookieDomainSchema,\n name: CookieNameSchema,\n value: z.union([z.string(), z.instanceof(Buffer)]),\n })\n .strict();\n\n/**\n * Type definition for raw cookie data\n */\nexport type CookieRow = z.infer<typeof CookieRowSchema>;\n\n/**\n * Schema for cookie render options\n */\nexport const RenderOptionsSchema = z\n .object({\n format: z.enum([\"merged\", \"grouped\"]).optional(),\n separator: z.string().optional(),\n showFilePaths: z.boolean().optional(),\n })\n .strict();\n\n/**\n * Type definition for render options\n */\nexport type RenderOptions = z.infer<typeof RenderOptionsSchema>;\n\n/**\n * Schema for browser names\n */\nexport const BrowserNameSchema = z.enum([\n \"Chrome\",\n \"Firefox\",\n \"Safari\",\n \"internal\",\n \"unknown\",\n]);\n\n/**\n * Type definition for browser names\n */\nexport type BrowserName = z.infer<typeof BrowserNameSchema>;\n\n/**\n * Schema for cookie query strategy\n */\nexport const CookieQueryStrategySchema = z\n .object({\n browserName: BrowserNameSchema,\n queryCookies: z\n .function()\n .args(z.string(), z.string(), z.string().optional())\n .returns(z.promise(z.array(ExportedCookieSchema))),\n })\n .strict();\n\n/**\n * Type definition for cookie query strategy\n */\nexport type CookieQueryStrategy = z.infer<typeof CookieQueryStrategySchema>;\n\n/**\n * Type representing either a single cookie specification or an array of specifications.\n * Useful when you need to query multiple cookies in a single operation.\n * @example\n * ```typescript\n * // Single cookie spec\n * const single: MultiCookieSpec = {\n * domain: \"example.com\",\n * name: \"sessionId\"\n * };\n *\n * // Multiple cookie specs\n * const multiple: MultiCookieSpec = [\n * { domain: \"example.com\", name: \"sessionId\" },\n * { domain: \"api.example.com\", name: \"authToken\" }\n * ];\n * ```\n */\nexport type MultiCookieSpec = CookieSpec | CookieSpec[];\n\n/**\n *\n */\nexport interface CookieQueryOptions<\n T extends CookieQueryStrategy = CookieQueryStrategy,\n> {\n strategy: T;\n limit?: number;\n removeExpired?: boolean;\n store?: string;\n}\n","import { Buffer } from \"buffer\";\n\nimport { BinaryCookieRow } from \"../../../types/schemas\";\nimport { logWarn } from \"../../../utils/logHelpers\";\nimport { createTaggedLogger } from \"../../../utils/logHelpers\";\n\nimport { BinaryCodableCookie } from \"./BinaryCodableCookie\";\nimport { BinaryCodableContainer } from \"./interfaces/BinaryCodableContainer\";\n\nconst logger = createTaggedLogger(\"BinaryCodablePage\");\n\n/**\n * Represents a page of cookies within the binary cookies file\n */\nexport class BinaryCodablePage {\n /**\n *\n */\n public cookies: BinaryCodableCookie[];\n private static readonly HEADER = 0x00000100;\n private static readonly FOOTER = 0x00000000;\n\n /**\n * Creates a new Page instance from a buffer\n * @param buffer - The raw binary page data\n */\n public constructor(buffer: Buffer) {\n this.cookies = [];\n const container: BinaryCodableContainer = { offset: 0, buffer };\n this.decode(container);\n }\n\n /**\n * Converts the page's cookies into validated cookie rows\n * @returns Array of validated cookie objects\n */\n public toCookieRows(): BinaryCookieRow[] {\n const cookies: BinaryCookieRow[] = [];\n\n for (const cookie of this.cookies) {\n try {\n const cookieRow = cookie.toCookieRow();\n if (cookieRow !== null) {\n cookies.push(cookieRow);\n }\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n logWarn(\"BinaryCookies\", \"Error converting cookie\", {\n error: errorMessage,\n });\n }\n }\n\n return cookies;\n }\n\n private decode(container: BinaryCodableContainer): void {\n // Read page tag (4 bytes)\n const header = container.buffer.readUInt32BE(container.offset);\n logger.debug(\"Page header:\", header.toString(16));\n container.offset += 4;\n if (header !== BinaryCodablePage.HEADER) {\n throw new Error(\"Invalid page header\");\n }\n\n // Read number of cookies (4 bytes)\n const cookieCount = container.buffer.readUInt32LE(container.offset);\n logger.debug(\"Cookie count:\", cookieCount);\n container.offset += 4;\n\n // Store the page start offset for calculating absolute cookie positions\n const pageStart = container.offset - 8;\n logger.debug(\"Page start offset:\", pageStart);\n\n // Read cookie offsets (4 bytes each)\n const cookieOffsets: number[] = [];\n for (let i = 0; i < cookieCount; i++) {\n const cookieOffset = container.buffer.readUInt32LE(container.offset);\n cookieOffsets.push(cookieOffset);\n logger.debug(`Cookie ${i} offset:`, cookieOffset);\n container.offset += 4;\n }\n\n // Read page end marker (4 bytes)\n const footer = container.buffer.readUInt32BE(container.offset);\n logger.debug(\"Page footer:\", footer.toString(16));\n container.offset += 4;\n if (footer !== BinaryCodablePage.FOOTER) {\n throw new Error(\"Invalid page footer\");\n }\n\n // Read cookies at their offsets\n for (let i = 0; i < cookieCount; i++) {\n try {\n const cookieOffset = cookieOffsets[i];\n logger.debug(`Reading cookie ${i} at offset:`, cookieOffset);\n\n // Read cookie size from the cookie header\n const cookieSize = container.buffer.readUInt32LE(cookieOffset);\n logger.debug(`Cookie ${i} size:`, cookieSize);\n if (cookieSize < 48) {\n // Minimum cookie size is 48 bytes (header)\n logger.warn(`Invalid cookie size ${cookieSize} at index ${i}`);\n continue;\n }\n\n // Ensure we don't read past the buffer\n if (cookieOffset + cookieSize > container.buffer.length) {\n logger.warn(\n `Cookie size ${cookieSize} at index ${i} would exceed buffer length ${container.buffer.length}`,\n );\n continue;\n }\n\n const cookieBuffer = container.buffer.subarray(\n cookieOffset,\n cookieOffset + cookieSize,\n );\n const cookie = new BinaryCodableCookie(cookieBuffer);\n this.cookies.push(cookie);\n } catch (error) {\n logger.warn(\"Invalid cookie data\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n}\n","import type { BinaryCookieRow } from \"../../../types/schemas\";\n\nimport { BinaryCodableCookies } from \"./BinaryCodableCookies\";\n\n/**\n * Decodes a Safari binary cookie file into an array of cookie objects.\n * @param cookieDbPath - Path to the Safari Cookies.binarycookies file\n * @returns Array of decoded cookie objects\n * @throws {Error} If the file cannot be read or has invalid format\n */\nexport function decodeBinaryCookies(cookieDbPath: string): BinaryCookieRow[] {\n const cookies = BinaryCodableCookies.fromFile(cookieDbPath);\n return cookies.toCookieRows();\n}\n\n/**\n * Retrieves cookies from Safari's binary cookie store.\n * @returns Array of decoded Safari cookies\n */\nexport function getSafariCookies(): BinaryCookieRow[] {\n const cookies = BinaryCodableCookies.fromDefaultPath();\n return cookies.toCookieRows();\n}\n","import type { CookieSpec, ExportedCookie } from \"../../types/schemas\";\nimport { ChromeCookieQueryStrategy } from \"../browsers/chrome/ChromeCookieQueryStrategy\";\nimport { FirefoxCookieQueryStrategy } from \"../browsers/firefox/FirefoxCookieQueryStrategy\";\nimport { SafariCookieQueryStrategy } from \"../browsers/safari/SafariCookieQueryStrategy\";\n\n/**\n * Queries cookies from all available browser strategies (Chrome, Firefox, Safari).\n * This function acts as a unified interface to retrieve cookies across different browsers.\n * @param cookieSpec - The cookie specification to query\n * @param cookieSpec.name - The name pattern to match cookies against (can include '%' as wildcard)\n * @param cookieSpec.domain - The domain to match cookies against\n * @returns Promise resolving to array of exported cookies from all available browsers\n * @remarks\n * - Returns empty array if cookieSpec is invalid or missing required fields\n * - Aggregates results from all available browser strategies\n * - Failed browser queries are gracefully handled and excluded from results\n * - Both name and domain fields are required and must be strings\n * @example\n * ```typescript\n * const cookies = await queryCookies({\n * name: 'sessionId',\n * domain: 'example.com'\n * });\n * console.log(cookies); // Array of matching cookies from all browsers\n * ```\n */\nexport async function queryCookies(\n cookieSpec: CookieSpec,\n): Promise<ExportedCookie[]> {\n if (!cookieSpec.name || !cookieSpec.domain) {\n return [];\n }\n\n const { name, domain } = cookieSpec;\n if (typeof name !== \"string\" || typeof domain !== \"string\") {\n return [];\n }\n\n /**\n * Initialize all available browser-specific strategies\n * The order of strategies can affect performance but not functionality\n * Each strategy is responsible for its own error handling\n */\n const strategies = [\n new ChromeCookieQueryStrategy(),\n new FirefoxCookieQueryStrategy(),\n new SafariCookieQueryStrategy(),\n ];\n\n /**\n * Query all strategies in parallel and handle failures gracefully\n * Using Promise.allSettled ensures that failures in one strategy\n * don't prevent results from other strategies\n */\n const results = await Promise.allSettled(\n strategies.map((strategy) => strategy.queryCookies(name, domain)),\n );\n\n /**\n * Filter out failed promises and flatten successful results\n * Using PromiseFulfilledResult<ExportedCookie[]> ensures that only successful results are included\n */\n return results\n .filter(\n (result): result is PromiseFulfilledResult<ExportedCookie[]> =>\n result.status === \"fulfilled\",\n )\n .flatMap((result) => result.value);\n}\n\n/**\n * Default export of the queryCookies function.\n * This is the recommended way to import the function for most use cases.\n * @example\n * ```typescript\n * import queryCookies from './queryCookies';\n *\n * // Query cookies with specific name\n * const sessionCookies = await queryCookies({\n * name: 'sessionId',\n * domain: 'example.com'\n * });\n *\n * // Query all cookies for a domain using wildcard\n * const allCookies = await queryCookies({\n * name: '%',\n * domain: 'example.com'\n * });\n * ```\n */\nexport default queryCookies;\n","import type { CookieSpec, ExportedCookie } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\n\nimport { queryCookies } from \"./queryCookies\";\n\n/**\n * Retrieves browser cookies that match the specified cookie name and domain criteria.\n * This function provides a way to search and filter cookies based on given specifications.\n * @param cookieSpec - The cookie specification containing search criteria\n * @param cookieSpec.name - The name of the cookie to search for\n * @param cookieSpec.domain - (optional) The domain to filter cookies by\n * @returns An array of ExportedCookie objects that match the specification\n * @throws Will catch and handle any errors during cookie querying, logging a warning\n * to the console without throwing to the caller\n * @example\n * ```typescript\n * import { getCookie } from \"@mherod/get-cookie\";\n *\n * // Get all cookies named \"sessionId\"\n * const cookies = await getCookie({ name: \"sessionId\" });\n * // Returns: [{ name: \"sessionId\", value: \"abc123\", domain: \".example.com\", ... }]\n *\n * // Get cookies named \"userPref\" from specific domain\n * const domainCookies = await getCookie({\n * name: \"userPref\",\n * domain: \"example.com\"\n * });\n * // Returns: [{ name: \"userPref\", value: \"darkMode\", domain: \"example.com\", ... }]\n * ```\n */\nexport async function getCookie(\n cookieSpec: CookieSpec,\n): Promise<ExportedCookie[]> {\n try {\n const cookies = await queryCookies(cookieSpec);\n return cookies;\n } catch (error: unknown) {\n logger.warn(\n \"Error querying cookies:\",\n error instanceof Error ? error.message : String(error),\n );\n return [];\n }\n}\n\n/**\n * Default export of the getCookie function.\n * @example\n * ```typescript\n * import { getCookie } from \"@mherod/get-cookie\";\n * const authCookies = await getCookie({\n * name: \"auth-token\",\n * domain: \"api.example.com\"\n * });\n * ```\n */\nexport default getCookie;\n","import type { CookieSpec, ExportedCookie } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\nimport { ChromeCookieQueryStrategy } from \"../browsers/chrome/ChromeCookieQueryStrategy\";\n\n/**\n * Retrieves cookies from Chrome browser storage that match the specified criteria.\n * @param cookieSpec - The cookie specification containing search criteria\n * @param cookieSpec.name - The name of the cookie to search for\n * @param cookieSpec.domain - (optional) The domain to filter cookies by\n * @returns An array of ExportedCookie objects that match the specification\n * @throws Will catch and handle any errors during cookie querying, logging a warning\n * to the console without throwing to the caller\n * @example\n * ```typescript\n * import { getChromeCookie } from \"@mherod/get-cookie\";\n *\n * // Get all cookies named \"sessionId\" from Chrome\n * const cookies = await getChromeCookie({ name: \"sessionId\" });\n *\n * // Get cookies named \"userPref\" from specific domain in Chrome\n * const domainCookies = await getChromeCookie({\n * name: \"userPref\",\n * domain: \"example.com\"\n * });\n * ```\n */\nexport async function getChromeCookie(\n cookieSpec: CookieSpec,\n): Promise<ExportedCookie[]> {\n try {\n const strategy = new ChromeCookieQueryStrategy();\n const cookies = await strategy.queryCookies(\n cookieSpec.name,\n cookieSpec.domain,\n );\n return cookies;\n } catch (error: unknown) {\n logger.warn(\"Error querying Chrome cookies:\", error);\n return [];\n }\n}\n\n/**\n * Default export of the getChromeCookie function.\n * @example\n * ```typescript\n * import { getChromeCookie } from \"@mherod/get-cookie\";\n * const cookies = await getChromeCookie({\n * name: \"sessionId\",\n * domain: \"example.com\"\n * });\n * ```\n */\nexport default getChromeCookie;\n","import type { CookieSpec, ExportedCookie } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\nimport { FirefoxCookieQueryStrategy } from \"../browsers/firefox/FirefoxCookieQueryStrategy\";\n\n/**\n * Retrieves cookies from Firefox browser storage that match the specified criteria.\n * @param cookieSpec - The cookie specification containing search criteria\n * @param cookieSpec.name - The name of the cookie to search for\n * @param cookieSpec.domain - (optional) The domain to filter cookies by\n * @returns An array of ExportedCookie objects that match the specification\n * @throws Will catch and handle any errors during cookie querying, logging a warning\n * to the console without throwing to the caller\n * @example\n * ```typescript\n * import { getFirefoxCookie } from \"@mherod/get-cookie\";\n *\n * // Get all cookies named \"sessionId\" from Firefox\n * const cookies = await getFirefoxCookie({ name: \"sessionId\" });\n *\n * // Get cookies named \"userPref\" from specific domain in Firefox\n * const domainCookies = await getFirefoxCookie({\n * name: \"userPref\",\n * domain: \"example.com\"\n * });\n * ```\n */\nexport async function getFirefoxCookie(\n cookieSpec: CookieSpec,\n): Promise<ExportedCookie[]> {\n try {\n const strategy = new FirefoxCookieQueryStrategy();\n const cookies = await strategy.queryCookies(\n cookieSpec.name,\n cookieSpec.domain,\n );\n return cookies;\n } catch (error: unknown) {\n logger.warn(\n \"Error querying Firefox cookies:\",\n error instanceof Error ? error.message : String(error),\n );\n return [];\n }\n}\n\n/**\n * Default export of the getFirefoxCookie function.\n * @example\n * ```typescript\n * import { getFirefoxCookie } from \"@mherod/get-cookie\";\n * const sessionCookies = await getFirefoxCookie({\n * name: \"PHPSESSID\",\n * domain: \"example.com\"\n * });\n * ```\n */\nexport default getFirefoxCookie;\n","import { groupBy } from \"lodash-es\";\n\nimport { ExportedCookie, RenderOptions } from \"../../types/schemas\";\n\n/**\n * Renders cookies as a string or array of strings based on the provided format option.\n * Supports merged format for single string output or grouped format for file-based grouping.\n * @param cookies - The cookies to render\n * @param options - Options for rendering\n * @param options.format - The output format ('merged' or 'grouped')\n * @param options.showFilePaths - Whether to include file paths in grouped output\n * @param options.separator - Custom separator for cookie values\n * @returns A string for merged format, or array of strings for grouped format\n * @example\n * ```typescript\n * // Merged format (default)\n * const cookies = [\n * { value: 'sessionId=abc123' },\n * { value: 'theme=dark' }\n * ];\n * renderCookies(cookies);\n * // Returns: \"sessionId=abc123; theme=dark\"\n *\n * // Grouped format with file paths\n * const groupedCookies = [\n * { value: 'sessionId=abc123', meta: { file: 'auth.ts' } },\n * { value: 'theme=dark', meta: { file: 'preferences.ts' } }\n * ];\n * renderCookies(groupedCookies, { format: 'grouped', showFilePaths: true });\n * // Returns: [\"auth.ts: sessionId=abc123\", \"preferences.ts: theme=dark\"]\n * ```\n */\nexport function renderCookies(\n cookies: ExportedCookie[],\n options: RenderOptions = {},\n): string | string[] {\n const { format = \"merged\", showFilePaths = true, separator = \"; \" } = options;\n\n if (cookies.length === 0) {\n return format === \"merged\" ? \"\" : [];\n }\n\n if (format === \"merged\") {\n return cookies.map((c) => c.value as string).join(separator);\n }\n\n const groupedByFile = groupBy(cookies, (c) => c.meta?.file ?? \"unknown\");\n return Object.entries(groupedByFile).map(([file, fileCookies]) => {\n const values = fileCookies.map((c) => c.value as string).join(separator);\n return showFilePaths ? `${file}: ${values}` : values;\n });\n}\n","import type {\n RenderOptions,\n CookieSpec,\n ExportedCookie,\n} from \"../../types/schemas\";\nimport { ExportedCookieSchema } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\n\nimport { getCookie } from \"./getCookie\";\nimport { renderCookies } from \"./renderCookies\";\n\n/**\n * Retrieves and renders cookies in a grouped format based on their source files.\n * @param cookieSpec - The cookie specification containing search criteria\n * @param cookieSpec.name - The name of the cookie to search for\n * @param cookieSpec.domain - (optional) The domain to filter cookies by\n * @param options - Options for rendering the cookies\n * @param options.showFilePaths - Whether to include file paths in the output\n * @param options.separator - Custom separator for cookie values\n * @returns An array of strings, each representing a group of cookies from a source file\n * @example\n * ```typescript\n * // Basic usage - get all cookies named \"sessionId\" grouped by source file\n * const cookies = await getGroupedRenderedCookies({ name: \"sessionId\" });\n *\n * // Get cookies with domain filter and custom rendering options\n * const domainCookies = await getGroupedRenderedCookies(\n * {\n * name: \"userPref\",\n * domain: \"example.com\"\n * },\n * {\n * showFilePaths: true,\n * separator: \" | \"\n * }\n * );\n * ```\n */\nexport async function getGroupedRenderedCookies(\n cookieSpec: CookieSpec,\n options: Omit<RenderOptions, \"format\"> = {},\n): Promise<string[]> {\n try {\n const cookies = await getCookie(cookieSpec);\n if (!Array.isArray(cookies)) {\n return [];\n }\n\n // Validate each cookie against the schema\n const validatedCookies = cookies.filter(\n (cookie): cookie is ExportedCookie => {\n const result = ExportedCookieSchema.safeParse(cookie);\n if (!result.success) {\n logger.warn(\"Invalid cookie format:\", result.error.format());\n return false;\n }\n return true;\n },\n );\n\n return renderCookies(validatedCookies, {\n ...options,\n format: \"grouped\",\n }) as string[];\n } catch (error: unknown) {\n logger.warn(\n \"Error getting grouped rendered cookies:\",\n error instanceof Error ? error.message : String(error),\n );\n return [];\n }\n}\n\n/**\n * Default export of the getGroupedRenderedCookies function\n * @example\n * ```typescript\n * import getGroupedCookies from './getGroupedRenderedCookies';\n *\n * // Get all session cookies with custom separator\n * const sessionCookies = await getGroupedCookies(\n * { name: \"session_*\" },\n * { separator: \"\\n\" }\n * );\n *\n * // Get cookies from multiple domains\n * const multiDomainCookies = await getGroupedCookies({\n * name: \"tracking\",\n * domain: [\"site1.com\", \"site2.com\"]\n * });\n * ```\n */\nexport default getGroupedRenderedCookies;\n","import type {\n RenderOptions,\n CookieSpec,\n ExportedCookie,\n} from \"../../types/schemas\";\nimport { ExportedCookieSchema } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\n\nimport { getCookie } from \"./getCookie\";\nimport { renderCookies } from \"./renderCookies\";\n\n/**\n * Retrieves and renders cookies in a merged format\n * @param cookieSpec - The cookie specification to query\n * @param options - Optional rendering options\n * @returns Promise resolving to rendered cookie string\n * @example\n * ```typescript\n * const cookieString = await getMergedRenderedCookies(\n * { name: 'session', domain: 'example.com' },\n * { separator: '; ' }\n * );\n * console.log(cookieString); // \"session=abc123; auth=xyz789\"\n * ```\n */\nexport async function getMergedRenderedCookies(\n cookieSpec: CookieSpec,\n options?: Omit<RenderOptions, \"format\">,\n): Promise<string> {\n try {\n const cookies = await getCookie(cookieSpec);\n if (!Array.isArray(cookies)) {\n return \"\";\n }\n\n // Validate each cookie against the schema\n const validatedCookies = cookies.filter(\n (cookie): cookie is ExportedCookie => {\n const result = ExportedCookieSchema.safeParse(cookie);\n if (!result.success) {\n logger.warn(\"Invalid cookie format:\", result.error.format());\n return false;\n }\n return true;\n },\n );\n\n const result = renderCookies(validatedCookies, {\n ...options,\n format: \"merged\",\n });\n return typeof result === \"string\" ? result : \"\";\n } catch (error: unknown) {\n logger.warn(\n \"Error getting merged rendered cookies:\",\n error instanceof Error ? error.message : String(error),\n );\n return \"\";\n }\n}\n\n/**\n * Default export of the getMergedRenderedCookies function.\n * @example\n * ```typescript\n * import { getMergedRenderedCookies } from './getMergedRenderedCookies';\n * const cookies = await getMergedRenderedCookies({\n * name: 'sessionId',\n * domain: 'example.com'\n * });\n * ```\n */\nexport default getMergedRenderedCookies;\n"],"mappings":"AAAA,OAA+B,iBAAAA,OAAqB,UCApD,OAAS,WAAAC,OAAe,KAExB,OAAS,UAAAC,OAAc,SACvB,OAAS,KAAAC,MAAS,MAGlBD,GAAO,EAEP,IAAME,GAAoBD,EAAE,OAAO,CACjC,UAAWA,EAAE,KAAK,CAAC,QAAS,OAAQ,OAAQ,OAAO,CAAC,EAAE,QAAQ,MAAM,EACpE,KAAMA,EACH,OAAO,EACP,SAAS,EACT,UAAWE,GAAQA,GAAO,QAAQ,IAAI,aAAe,EAAE,EACvD,KAAKF,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CAC3B,CAAC,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S,EAC/C,OAASI,EAAgB,CACvB,OAAAF,EAAO,KACL,yCACAE,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CACvD,EACO,EACT,CACF","names":["createConsola","homedir","config","z","EnvironmentSchema","val","env","consola","createConsola","env","isDebug","logger","logger_default","logOperationResult","operation","success","context","logger_default","logError","message","error","errorMessage","logWarn","component","createTaggedLogger","existsSync","join","glob","homedir","join","chromeApplicationSupport","home","BetterSqlite3","openDatabase","file","BetterSqlite3","error","logError","closeDatabase","db","querySqliteThenTransform","sql","params","rowFilter","rowTransform","rows","filteredRows","logger","createTaggedLogger","isValidFilePath","path","trimmedPath","existsSync","getCookieFiles","patterns","join","chromeApplicationSupport","files","pattern","matches","glob","buildSqlQuery","name","domain","isWildcard","sql","params","processCookieFile","cookieFile","rows","querySqliteThenTransform","row","logOperationResult","error","logError","getEncryptedChromeCookie","file","cookieFiles","results","cookies","readFileSync","join","fg","logger","createTaggedLogger","listChromeProfilePaths","files","fg","chromeApplicationSupport","createDecipheriv","pbkdf2","memoize","removeV10Prefix","value","removePadding","decrypted","padding","extractValue","decodedString","cleanupPatterns","pattern","decrypt","encryptedValue","password","resolve","reject","error","key","iv","decipher","e","platform","exec","promisify","execPromise","promisify","exec","CommandExecutionError","message","command","originalError","execSimple","options","result","error","logError","getChromePassword","execSimple","getChromePassword","platform","getExpiryDate","expiry","createExportedCookie","domain","name","value","file","decrypted","ChromeCookieQueryStrategy","createTaggedLogger","store","cookieFiles","listChromeProfilePaths","files","password","getChromePassword","error","logError","encryptedCookies","getEncryptedChromeCookie","context","cookie","result","decryptedValue","decrypt","homedir","join","fg","logger","createTaggedLogger","findFirefoxCookieFiles","home","homedir","logWarn","patterns","join","files","pattern","matches","fg","FirefoxCookieQueryStrategy","name","domain","store","fileList","results","file","cookies","querySqliteThenTransform","row","error","homedir","join","Buffer","readFileSync","homedir","join","Buffer","destr","z","CookieDomainSchema","domain","CookieNameSchema","name","CookiePathSchema","path","CookieValueSchema","value","BinaryCookieRowSchema","CookieSpecSchema","CookieMetaSchema","ExportedCookieSchema","CookieRowSchema","RenderOptionsSchema","BrowserNameSchema","CookieQueryStrategySchema","logger","createTaggedLogger","BinaryCodableCookie","buffer","container","value","processed","lastProcessed","token","parts","payload","Buffer","parsed","decoded","jwtPayload","jsonValue","flagsValue","domain","macToUnixOffset","expiryUnix","creationUnix","BinaryCookieRowSchema","offset","end","size","version","hasPort","offsets","expirationBuffer","i","expiration","creationBuffer","creation","offsetEntries","entry","a","b","e","field","length","baseOffset","logger","createTaggedLogger","_BinaryCodablePage","buffer","container","cookies","cookie","cookieRow","error","errorMessage","logWarn","header","cookieCount","pageStart","cookieOffsets","i","cookieOffset","footer","cookieSize","cookieBuffer","BinaryCodableCookie","BinaryCodablePage","logger","createTaggedLogger","_BinaryCodableCookies","buffer","container","path","readFileSync","cookies","page","pageCookies","error","errorMessage","logWarn","magic","pageCount","pageSizes","i","pageSize","currentOffset","pageBuffer","BinaryCodablePage","checksum","footer","_plistData","Buffer","join","homedir","BinaryCodableCookies","decodeBinaryCookies","cookieDbPath","BinaryCodableCookies","SafariCookieQueryStrategy","home","join","domain","expiry","flags","bit","creation","cookieDbPath","name","decodeBinaryCookies","cookie","error","logError","store","homedir","queryCookies","cookieSpec","name","domain","strategies","ChromeCookieQueryStrategy","FirefoxCookieQueryStrategy","SafariCookieQueryStrategy","strategy","result","getCookie","cookieSpec","queryCookies","error","logger_default","getChromeCookie","cookieSpec","ChromeCookieQueryStrategy","error","logger_default","getFirefoxCookie","cookieSpec","FirefoxCookieQueryStrategy","error","logger_default","groupBy","renderCookies","cookies","options","format","showFilePaths","separator","c","groupedByFile","file","fileCookies","values","getGroupedRenderedCookies","cookieSpec","options","cookies","getCookie","validatedCookies","cookie","result","ExportedCookieSchema","logger_default","renderCookies","error","getMergedRenderedCookies","cookieSpec","options","cookies","getCookie","validatedCookies","cookie","result","ExportedCookieSchema","logger_default","renderCookies","error"]}