@mherod/get-cookie 4.2.2 → 4.3.0

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.d.cts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ import * as consola from 'consola';
2
3
 
3
4
  /**
4
5
  * Schema for cookie specification parameters
@@ -209,7 +210,7 @@ type BrowserName = z.infer<typeof BrowserNameSchema>;
209
210
  */
210
211
  declare const CookieQueryStrategySchema: z.ZodObject<{
211
212
  browserName: z.ZodEnum<["Chrome", "Firefox", "Safari", "internal", "unknown"]>;
212
- queryCookies: z.ZodFunction<z.ZodTuple<[z.ZodString, z.ZodString, z.ZodOptional<z.ZodString>], z.ZodUnknown>, z.ZodPromise<z.ZodArray<z.ZodObject<{
213
+ queryCookies: z.ZodFunction<z.ZodTuple<[z.ZodString, z.ZodString, z.ZodOptional<z.ZodString>, z.ZodOptional<z.ZodBoolean>], z.ZodUnknown>, z.ZodPromise<z.ZodArray<z.ZodObject<{
213
214
  domain: z.ZodEffects<z.ZodString, string, string>;
214
215
  name: z.ZodEffects<z.ZodString, string, string>;
215
216
  value: z.ZodPipeline<z.ZodEffects<z.ZodString, unknown, string>, z.ZodAny>;
@@ -265,7 +266,7 @@ declare const CookieQueryStrategySchema: z.ZodObject<{
265
266
  }>, "many">>>;
266
267
  }, "strict", z.ZodTypeAny, {
267
268
  browserName: "unknown" | "Chrome" | "Firefox" | "Safari" | "internal";
268
- queryCookies: (args_0: string, args_1: string, args_2: string | undefined, ...args: unknown[]) => Promise<{
269
+ queryCookies: (args_0: string, args_1: string, args_2: string | undefined, args_3: boolean | undefined, ...args: unknown[]) => Promise<{
269
270
  name: string;
270
271
  domain: string;
271
272
  value?: any;
@@ -281,7 +282,7 @@ declare const CookieQueryStrategySchema: z.ZodObject<{
281
282
  }[]>;
282
283
  }, {
283
284
  browserName: "unknown" | "Chrome" | "Firefox" | "Safari" | "internal";
284
- queryCookies: (args_0: string, args_1: string, args_2: string | undefined, ...args: unknown[]) => Promise<{
285
+ queryCookies: (args_0: string, args_1: string, args_2: string | undefined, args_3: boolean | undefined, ...args: unknown[]) => Promise<{
285
286
  name: string;
286
287
  value: string;
287
288
  domain: string;
@@ -348,96 +349,289 @@ type MultiCookieSpec = CookieSpec | CookieSpec[];
348
349
  declare function getCookie(cookieSpec: CookieSpec): Promise<ExportedCookie[]>;
349
350
 
350
351
  /**
351
- * Retrieves cookies from Chrome browser storage that match the specified criteria.
352
- * @param cookieSpec - The cookie specification containing search criteria
353
- * @param cookieSpec.name - The name of the cookie to search for
354
- * @param cookieSpec.domain - (optional) The domain to filter cookies by
355
- * @returns An array of ExportedCookie objects that match the specification
356
- * @throws Will catch and handle any errors during cookie querying, logging a warning
357
- * to the console without throwing to the caller
358
- * @example
359
- * ```typescript
360
- * import { getChromeCookie } from "@mherod/get-cookie";
361
- *
362
- * // Get all cookies named "sessionId" from Chrome
363
- * const cookies = await getChromeCookie({ name: "sessionId" });
364
- *
365
- * // Get cookies named "userPref" from specific domain in Chrome
366
- * const domainCookies = await getChromeCookie({
367
- * name: "userPref",
368
- * domain: "example.com"
369
- * });
370
- * ```
352
+ * Base class for cookie query strategies.
353
+ * Provides common functionality and standardized error handling for browser-specific implementations.
354
+ * @implements {CookieQueryStrategy}
355
+ * @abstract
371
356
  */
372
- declare function getChromeCookie(cookieSpec: CookieSpec): Promise<ExportedCookie[]>;
357
+ declare abstract class BaseCookieQueryStrategy implements CookieQueryStrategy {
358
+ readonly browserName: BrowserName;
359
+ /**
360
+ * Logger instance for this strategy
361
+ * @protected
362
+ */
363
+ protected readonly logger: consola.ConsolaInstance;
364
+ /**
365
+ * Creates a new instance of BaseCookieQueryStrategy
366
+ * @param strategyName - The name of the strategy for logging purposes
367
+ * @param browserName - The name of the browser this strategy is for
368
+ */
369
+ constructor(strategyName: string, browserName: BrowserName);
370
+ /**
371
+ * Queries cookies from the browser's cookie store
372
+ * @param name - The name pattern to match cookies against
373
+ * @param domain - The domain pattern to match cookies against
374
+ * @param store - Optional path to a specific cookie store file
375
+ * @param force - Whether to force operations despite warnings (e.g., locked databases)
376
+ * @returns A promise that resolves to an array of exported cookies
377
+ */
378
+ queryCookies(name: string, domain: string, store?: string, force?: boolean): Promise<ExportedCookie[]>;
379
+ /**
380
+ * Executes the browser-specific query logic
381
+ * @abstract
382
+ * @param name - The name pattern to match cookies against
383
+ * @param domain - The domain pattern to match cookies against
384
+ * @param store - Optional path to a specific cookie store file
385
+ * @param force - Whether to force operations despite warnings (e.g., locked databases)
386
+ * @returns A promise that resolves to an array of exported cookies
387
+ * @protected
388
+ */
389
+ protected abstract executeQuery(name: string, domain: string, store?: string, force?: boolean): Promise<ExportedCookie[]>;
390
+ }
373
391
 
374
392
  /**
375
- * Retrieves cookies from Firefox browser storage that match the specified criteria.
376
- * @param cookieSpec - The cookie specification containing search criteria
377
- * @param cookieSpec.name - The name of the cookie to search for
378
- * @param cookieSpec.domain - (optional) The domain to filter cookies by
379
- * @returns An array of ExportedCookie objects that match the specification
380
- * @throws Will catch and handle any errors during cookie querying, logging a warning
381
- * to the console without throwing to the caller
393
+ * Strategy for querying cookies from Chrome browser.
394
+ * This class extends the BaseCookieQueryStrategy and implements Chrome-specific
395
+ * cookie extraction logic.
382
396
  * @example
383
397
  * ```typescript
384
- * import { getFirefoxCookie } from "@mherod/get-cookie";
385
- *
386
- * // Get all cookies named "sessionId" from Firefox
387
- * const cookies = await getFirefoxCookie({ name: "sessionId" });
388
- *
389
- * // Get cookies named "userPref" from specific domain in Firefox
390
- * const domainCookies = await getFirefoxCookie({
391
- * name: "userPref",
392
- * domain: "example.com"
393
- * });
398
+ * const strategy = new ChromeCookieQueryStrategy();
399
+ * const cookies = await strategy.queryCookies('session', 'example.com');
394
400
  * ```
395
401
  */
396
- declare function getFirefoxCookie(cookieSpec: CookieSpec): Promise<ExportedCookie[]>;
402
+ declare class ChromeCookieQueryStrategy extends BaseCookieQueryStrategy {
403
+ /**
404
+ * Creates a new instance of ChromeCookieQueryStrategy
405
+ */
406
+ constructor();
407
+ /**
408
+ * Executes the Chrome-specific query logic
409
+ * @param name - The name pattern to match cookies against
410
+ * @param domain - The domain pattern to match cookies against
411
+ * @param store - Optional path to a specific cookie store file
412
+ * @param _force - Whether to force operations despite warnings (e.g., locked databases)
413
+ * @returns A promise that resolves to an array of exported cookies
414
+ * @protected
415
+ * @example
416
+ * ```typescript
417
+ * // This method is called internally by queryCookies
418
+ * const cookies = await strategy.queryCookies('session', 'example.com');
419
+ * console.log(cookies);
420
+ * ```
421
+ */
422
+ protected executeQuery(name: string, domain: string, store?: string, _force?: boolean): Promise<ExportedCookie[]>;
423
+ private processFile;
424
+ private processCookie;
425
+ }
397
426
 
398
427
  /**
399
- * Retrieves and renders cookies in a grouped format based on their source files.
400
- * @param cookieSpec - The cookie specification containing search criteria
401
- * @param cookieSpec.name - The name of the cookie to search for
402
- * @param cookieSpec.domain - (optional) The domain to filter cookies by
403
- * @param options - Options for rendering the cookies
404
- * @param options.showFilePaths - Whether to include file paths in the output
405
- * @param options.separator - Custom separator for cookie values
406
- * @returns An array of strings, each representing a group of cookies from a source file
428
+ * Chromium browser configuration and path management
429
+ * Supports Chrome, Chromium, Brave, Edge, Opera, Vivaldi, and Whale browsers
430
+ * across Windows, macOS, and Linux platforms
431
+ */
432
+ /**
433
+ * Supported Chromium-based browsers
434
+ */
435
+ declare const CHROMIUM_BASED_BROWSERS: readonly ["chrome", "chromium", "brave", "edge", "opera", "vivaldi", "whale"];
436
+ type ChromiumBrowser = (typeof CHROMIUM_BASED_BROWSERS)[number];
437
+
438
+ /**
439
+ * Strategy for querying cookies from Chromium-based browsers (Chrome, Brave, Edge, etc.)
440
+ * This class extends the BaseCookieQueryStrategy and implements Chromium-specific
441
+ * cookie extraction logic that works across multiple browsers.
442
+ */
443
+ declare class ChromiumCookieQueryStrategy extends BaseCookieQueryStrategy {
444
+ private browser;
445
+ /**
446
+ * Creates a new instance of ChromiumCookieQueryStrategy
447
+ * @param browser - The Chromium-based browser to query (chrome, brave, edge, etc.)
448
+ */
449
+ constructor(browser?: ChromiumBrowser);
450
+ /**
451
+ * Lists all cookie file paths for the specified browser
452
+ */
453
+ private listBrowserCookiePaths;
454
+ /**
455
+ * Executes the Chromium-specific query logic
456
+ */
457
+ protected executeQuery(name: string, domain: string, store?: string, _force?: boolean): Promise<ExportedCookie[]>;
458
+ private processFile;
459
+ private processCookie;
460
+ }
461
+
462
+ /**
463
+ * Strategy for querying cookies from Firefox browser.
464
+ * This class extends the BaseCookieQueryStrategy and implements Firefox-specific
465
+ * cookie extraction logic. It searches for cookie databases in standard Firefox
466
+ * profile locations and extracts cookies matching the specified name and domain.
407
467
  * @example
408
468
  * ```typescript
409
- * // Basic usage - get all cookies named "sessionId" grouped by source file
410
- * const cookies = await getGroupedRenderedCookies({ name: "sessionId" });
469
+ * import { FirefoxCookieQueryStrategy } from './FirefoxCookieQueryStrategy';
411
470
  *
412
- * // Get cookies with domain filter and custom rendering options
413
- * const domainCookies = await getGroupedRenderedCookies(
414
- * {
415
- * name: "userPref",
416
- * domain: "example.com"
417
- * },
418
- * {
419
- * showFilePaths: true,
420
- * separator: " | "
421
- * }
422
- * );
471
+ * const strategy = new FirefoxCookieQueryStrategy();
472
+ * const cookies = await strategy.queryCookies('sessionid', 'example.com');
473
+ * console.log(cookies);
423
474
  * ```
424
475
  */
425
- declare function getGroupedRenderedCookies(cookieSpec: CookieSpec, options?: Omit<RenderOptions, "format">): Promise<string[]>;
476
+ declare class FirefoxCookieQueryStrategy extends BaseCookieQueryStrategy {
477
+ /**
478
+ * Creates a new instance of FirefoxCookieQueryStrategy
479
+ */
480
+ constructor();
481
+ /**
482
+ * Check if an error indicates a database lock and provide helpful advice
483
+ * @param error - The error to check
484
+ * @param file - The database file that was locked
485
+ * @returns Promise that resolves after providing advice
486
+ * @private
487
+ */
488
+ private handleDatabaseLockError;
489
+ /**
490
+ * Executes the Firefox-specific query logic
491
+ * @param name - The name pattern to match cookies against
492
+ * @param domain - The domain pattern to match cookies against
493
+ * @param store - Optional path to a specific cookie store file
494
+ * @param _force - Whether to force operations despite warnings (e.g., locked databases)
495
+ * @returns A promise that resolves to an array of exported cookies
496
+ * @protected
497
+ */
498
+ protected executeQuery(name: string, domain: string, store?: string, _force?: boolean): Promise<ExportedCookie[]>;
499
+ }
500
+
501
+ /**
502
+ * Strategy for querying cookies from Safari browser.
503
+ * This class extends the BaseCookieQueryStrategy and implements Safari-specific
504
+ * cookie extraction logic.
505
+ */
506
+ declare class SafariCookieQueryStrategy extends BaseCookieQueryStrategy {
507
+ /**
508
+ * Creates a new instance of SafariCookieQueryStrategy
509
+ */
510
+ constructor();
511
+ /**
512
+ * Gets the path to Safari's cookie database
513
+ * @param home - The user's home directory
514
+ * @returns Path to the cookie database
515
+ */
516
+ private getCookieDbPath;
517
+ /**
518
+ * Formats the domain by removing leading dot if present
519
+ * @param domain - Domain to format
520
+ * @returns Formatted domain
521
+ */
522
+ private formatDomain;
523
+ /**
524
+ * Formats the expiry date
525
+ * @param expiry - Expiry timestamp (Unix epoch seconds)
526
+ * @returns Formatted expiry date or "Infinity"
527
+ */
528
+ private formatExpiry;
529
+ /**
530
+ * Checks if a flag bit is set
531
+ * @param flags - The flags value
532
+ * @param bit - The bit to check
533
+ * @returns True if the bit is set, false otherwise
534
+ */
535
+ private isFlagSet;
536
+ /**
537
+ * Formats the creation timestamp
538
+ * @param creation - Creation timestamp (Unix epoch seconds)
539
+ * @returns Formatted creation timestamp in milliseconds or undefined
540
+ */
541
+ private formatCreation;
542
+ /**
543
+ * Processes a cookie value to ensure it's a string
544
+ * @param value - The cookie value to process
545
+ * @returns The processed value as a string
546
+ */
547
+ private processValue;
548
+ /**
549
+ * Decodes cookies from Safari's binary cookie file
550
+ * @param cookieDbPath - Path to the cookie database
551
+ * @param name - Name of the cookie to find
552
+ * @param domain - Domain to filter cookies by
553
+ * @returns Array of exported cookies
554
+ */
555
+ private decodeCookies;
556
+ /**
557
+ * Executes the Safari-specific query logic
558
+ * @param name - Name of the cookie to find
559
+ * @param domain - Domain to filter cookies by
560
+ * @param store - Optional store path
561
+ * @param _force - Whether to force operations despite warnings (e.g., locked databases)
562
+ * @returns Array of matching cookies, or empty array if none found
563
+ * @protected
564
+ */
565
+ protected executeQuery(name: string, domain: string, store?: string, _force?: boolean): Promise<ExportedCookie[]>;
566
+ }
426
567
 
427
568
  /**
428
- * Retrieves and renders cookies in a merged format
429
- * @param cookieSpec - The cookie specification to query
430
- * @param options - Optional rendering options
431
- * @returns Promise resolving to rendered cookie string
569
+ * A composite strategy that combines multiple cookie query strategies.
570
+ * This class implements the CookieQueryStrategy interface and allows querying cookies
571
+ * from multiple browser-specific strategies simultaneously.
432
572
  * @example
433
573
  * ```typescript
434
- * const cookieString = await getMergedRenderedCookies(
435
- * { name: 'session', domain: 'example.com' },
436
- * { separator: '; ' }
437
- * );
438
- * console.log(cookieString); // "session=abc123; auth=xyz789"
574
+ * const strategy = new CompositeCookieQueryStrategy([
575
+ * new ChromeCookieQueryStrategy(),
576
+ * new FirefoxCookieQueryStrategy(),
577
+ * new SafariCookieQueryStrategy()
578
+ * ]);
579
+ * const cookies = await strategy.queryCookies('sessionId', 'example.com');
439
580
  * ```
440
581
  */
441
- declare function getMergedRenderedCookies(cookieSpec: CookieSpec, options?: Omit<RenderOptions, "format">): Promise<string>;
582
+ declare class CompositeCookieQueryStrategy implements CookieQueryStrategy {
583
+ private strategies;
584
+ private readonly logger;
585
+ /**
586
+ * The browser name identifier for this strategy
587
+ * @remarks Always returns 'internal' as this is a composite strategy
588
+ */
589
+ readonly browserName: BrowserName;
590
+ /**
591
+ * Creates a new instance of CompositeCookieQueryStrategy
592
+ * @param strategies - Array of browser-specific strategies to use for querying cookies
593
+ * @remarks
594
+ * - Each strategy in the array should implement the CookieQueryStrategy interface
595
+ * - The order of strategies determines the order of cookie querying
596
+ * - Failed strategies will be gracefully handled and skipped
597
+ * @example
598
+ * ```typescript
599
+ * const strategy = new CompositeCookieQueryStrategy([
600
+ * new ChromeCookieQueryStrategy(),
601
+ * new FirefoxCookieQueryStrategy()
602
+ * ]);
603
+ * ```
604
+ */
605
+ constructor(strategies: CookieQueryStrategy[]);
606
+ /**
607
+ * Handles strategy-specific errors and logs them appropriately
608
+ * @internal
609
+ * @param error - The error that occurred during strategy execution
610
+ * @param strategy - The strategy that failed
611
+ */
612
+ private handleStrategyError;
613
+ /**
614
+ * Queries cookies using all available strategies in parallel
615
+ * @param name - The name pattern to match cookies against
616
+ * @param domain - The domain pattern to match cookies against
617
+ * @param store - The store pattern to match cookies against
618
+ * @param force - Whether to force operations despite warnings (e.g., locked databases)
619
+ * @returns Promise resolving to combined array of cookies from all strategies
620
+ * @remarks
621
+ * - Failures in individual strategies are logged but don't affect other strategies
622
+ * - Results are combined from all successful strategy queries
623
+ * - Empty arrays are returned for failed strategy queries
624
+ * @example
625
+ * ```typescript
626
+ * const strategy = new CompositeCookieQueryStrategy([
627
+ * new ChromeCookieQueryStrategy(),
628
+ * new FirefoxCookieQueryStrategy()
629
+ * ]);
630
+ * const cookies = await strategy.queryCookies('sessionId', 'example.com');
631
+ * console.log(cookies); // Combined results from all browsers
632
+ * ```
633
+ */
634
+ queryCookies(name: string, domain: string, store?: string, force?: boolean): Promise<ExportedCookie[]>;
635
+ }
442
636
 
443
- export { type BrowserName, type CookieQueryStrategy, type CookieSpec, type ExportedCookie, type MultiCookieSpec, type RenderOptions, getChromeCookie, getCookie, getFirefoxCookie, getGroupedRenderedCookies, getMergedRenderedCookies };
637
+ export { type BrowserName, ChromeCookieQueryStrategy, ChromiumCookieQueryStrategy, CompositeCookieQueryStrategy, type CookieQueryStrategy, type CookieSpec, type ExportedCookie, FirefoxCookieQueryStrategy, type MultiCookieSpec, type RenderOptions, SafariCookieQueryStrategy, getCookie };