@mherod/get-cookie 2.0.0-rc.2 → 2.0.0-rc.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mherod/get-cookie",
3
- "version": "2.0.0-rc.2",
3
+ "version": "2.0.0-rc.3",
4
4
  "description": "Node.js module for querying a local user's Chrome cookie",
5
5
  "source": "src/index.ts",
6
6
  "bin": "dist/cli.js",
@@ -66,7 +66,8 @@
66
66
  "lodash": "^4.17.21",
67
67
  "lru-cache": "^7.14.0",
68
68
  "minimist": "^1.2.6",
69
- "sqlite3": "^5.1.1"
69
+ "sqlite3": "^5.1.1",
70
+ "tough-cookie": "^4.1.2"
70
71
  },
71
72
  "devDependencies": {
72
73
  "@parcel/packager-ts": "^2.7.0",
@@ -75,6 +76,7 @@
75
76
  "@types/lodash": "^4.14.186",
76
77
  "@types/minimist": "^1.2.2",
77
78
  "@types/node": "^18.8.2",
79
+ "@types/tough-cookie": "^4.0.2",
78
80
  "@types/user-agents": "^1.0.2",
79
81
  "jest": "^29.0.3",
80
82
  "parcel": "^2.7.0",
package/src/CookieRow.ts CHANGED
@@ -1,4 +1,4 @@
1
- export interface CookieRow {
1
+ export default interface CookieRow {
2
2
  domain: string;
3
3
  name: string;
4
4
  value: Buffer;
package/src/CookieSpec.ts CHANGED
@@ -1,4 +1,4 @@
1
- export interface CookieSpec {
1
+ export default interface CookieSpec {
2
2
  name: string;
3
3
  domain: string;
4
4
  }
@@ -1,4 +1,4 @@
1
- export interface ExportedCookie {
1
+ export default interface ExportedCookie {
2
2
  domain: string;
3
3
  name: string;
4
4
  value: string;
@@ -1,3 +1,5 @@
1
+ // noinspection JSUnusedGlobalSymbols
2
+
1
3
  import { Response } from "cross-fetch";
2
4
 
3
5
  export default interface FetchResponse extends Response {
@@ -1,4 +1,4 @@
1
- import { CookieRow } from "./CookieRow";
1
+ import CookieRow from "./CookieRow";
2
2
 
3
3
  export function isCookieRow(obj: any): obj is CookieRow {
4
4
  return (
@@ -1,4 +1,4 @@
1
- import { ExportedCookie } from "./ExportedCookie";
1
+ import ExportedCookie from "./ExportedCookie";
2
2
 
3
3
  export function isExportedCookie(obj: any): obj is ExportedCookie {
4
4
  return (
@@ -0,0 +1,5 @@
1
+ import { CookieJar, MemoryCookieStore } from "tough-cookie";
2
+
3
+ export const memoryCookieStore = new MemoryCookieStore();
4
+
5
+ export const cookieJar = new CookieJar(memoryCookieStore);
@@ -1,4 +1,4 @@
1
- import { CookieSpec } from "./CookieSpec";
1
+ import CookieSpec from "./CookieSpec";
2
2
 
3
3
  export function specialCases({ name, domain }: CookieSpec): {
4
4
  specifiedName: boolean;
@@ -9,8 +9,8 @@ import { doSqliteQuery1 } from "../doSqliteQuery1";
9
9
  import { merge } from "lodash";
10
10
  import { isCookieRow } from "../IsCookieRow";
11
11
  import { isExportedCookie } from "../IsExportedCookie";
12
- import { CookieRow } from "../CookieRow";
13
- import { ExportedCookie } from "../ExportedCookie";
12
+ import CookieRow from "../CookieRow";
13
+ import ExportedCookie from "../ExportedCookie";
14
14
 
15
15
  export default class ChromeCookieQueryStrategy implements CookieQueryStrategy {
16
16
  async queryCookies(name: string, domain: string): Promise<ExportedCookie[]> {
@@ -2,8 +2,9 @@ import ChromeCookieQueryStrategy from "./ChromeCookieQueryStrategy";
2
2
  import FirefoxCookieQueryStrategy from "./FirefoxCookieQueryStrategy";
3
3
  import SafariCookieQueryStrategy from "./SafariCookieQueryStrategy";
4
4
  import CookieQueryStrategy from "./CookieQueryStrategy";
5
- import { ExportedCookie } from "../ExportedCookie";
5
+ import ExportedCookie from "../ExportedCookie";
6
6
  import LRUCache from "lru-cache";
7
+ import MemoryCookieStoreQueryStrategy from "./MemoryCookieJarQueryStrategy";
7
8
 
8
9
  const cache = new LRUCache<string, ExportedCookie[]>({
9
10
  ttl: 1000 * 2,
@@ -17,6 +18,7 @@ export default class CompositeCookieQueryStrategy
17
18
 
18
19
  constructor() {
19
20
  this.#strategies = [
21
+ MemoryCookieStoreQueryStrategy,
20
22
  ChromeCookieQueryStrategy,
21
23
  FirefoxCookieQueryStrategy,
22
24
  SafariCookieQueryStrategy,
@@ -1,4 +1,4 @@
1
- import { ExportedCookie } from "../ExportedCookie";
1
+ import ExportedCookie from "../ExportedCookie";
2
2
 
3
3
  export default interface CookieQueryStrategy {
4
4
  queryCookies(name: string, domain: string): Promise<ExportedCookie[]>;
@@ -4,9 +4,9 @@ import { env, HOME } from "../global";
4
4
  import { existsSync } from "fs";
5
5
  import { findAllFiles } from "../findAllFiles";
6
6
  import { doSqliteQuery1 } from "../doSqliteQuery1";
7
- import { ExportedCookie } from "../ExportedCookie";
8
- import { CookieRow } from "../CookieRow";
9
- import { CookieSpec } from "../CookieSpec";
7
+ import ExportedCookie from "../ExportedCookie";
8
+ import CookieRow from "../CookieRow";
9
+ import CookieSpec from "../CookieSpec";
10
10
  import { specialCases } from "../SpecialCases";
11
11
 
12
12
  export default class FirefoxCookieQueryStrategy implements CookieQueryStrategy {
@@ -0,0 +1,53 @@
1
+ import ExportedCookie from "../ExportedCookie";
2
+ import CookieQueryStrategy from "./CookieQueryStrategy";
3
+ import { Cookie } from "tough-cookie";
4
+ import CookieSpec from "../CookieSpec";
5
+ import { memoryCookieStore } from "../MemoryCookieStore";
6
+
7
+ export default class MemoryCookieStoreQueryStrategy
8
+ implements CookieQueryStrategy
9
+ {
10
+ async queryCookies(name: string, domain: string): Promise<ExportedCookie[]> {
11
+ if (name == "%" && domain == "%") {
12
+ const cookies: Cookie[] = await memoryCookieStore.getAllCookies();
13
+ return cookies.map((cookie) => {
14
+ return this.#extracted(cookie, { name, domain });
15
+ });
16
+ }
17
+
18
+ const path = "/";
19
+
20
+ if (name == "%") {
21
+ const cookies: Cookie[] = await memoryCookieStore.findCookies(
22
+ domain,
23
+ path
24
+ );
25
+ return cookies.map((cookie) => {
26
+ return this.#extracted(cookie, { name, domain });
27
+ });
28
+ }
29
+
30
+ const cookie: Cookie | null = await memoryCookieStore.findCookie(
31
+ domain,
32
+ path,
33
+ name
34
+ );
35
+
36
+ if (cookie) {
37
+ return [this.#extracted(cookie, { name, domain })];
38
+ } else {
39
+ return [];
40
+ }
41
+ }
42
+
43
+ #extracted(cookie: Cookie, cookieSpec: CookieSpec): ExportedCookie {
44
+ return {
45
+ domain: cookie.domain ?? cookieSpec.domain,
46
+ name: cookie.key ?? cookieSpec.name,
47
+ value: cookie.value,
48
+ meta: {
49
+ file: "memory",
50
+ },
51
+ };
52
+ }
53
+ }
@@ -1,5 +1,5 @@
1
1
  import CookieQueryStrategy from "./CookieQueryStrategy";
2
- import { ExportedCookie } from "../ExportedCookie";
2
+ import ExportedCookie from "../ExportedCookie";
3
3
 
4
4
  export default class SafariCookieQueryStrategy implements CookieQueryStrategy {
5
5
  async queryCookies(name: string, domain: string): Promise<ExportedCookie[]> {
package/src/cli.ts CHANGED
@@ -2,42 +2,50 @@
2
2
 
3
3
  import minimist from "minimist";
4
4
  import { argv } from "./argv";
5
- import { env } from "./global";
6
5
  import { queryCookies } from "./queryCookies";
7
6
  import { groupBy } from "lodash";
8
- import { green, yellow } from "colorette";
7
+ import { green, red, yellow } from "colorette";
9
8
  import { resultsRendered } from "./resultsRendered";
10
9
  import { fetchWithCookies } from "./fetchWithCookies";
11
10
  import { unpackHeaders } from "./unpackHeaders";
11
+ import CookieSpec from "./CookieSpec";
12
12
 
13
- const parsedArgs: minimist.ParsedArgs = minimist(argv);
13
+ const parsedArgs: minimist.ParsedArgs = minimist(argv.slice(2));
14
14
 
15
- async function cliQueryCookies(name: string, domain: string) {
15
+ async function cliQueryCookies({ name, domain }: CookieSpec) {
16
16
  try {
17
17
  const results = await queryCookies({ name, domain });
18
- if (results.length > 0) {
19
- if (argv.includes("--combined-string")) {
20
- console.log(yellow(resultsRendered(results)));
21
- } else if (argv.includes("--render") || argv.includes("-r")) {
22
- console.log(yellow(resultsRendered(results)));
23
- } else if (argv.includes("--dump") || argv.includes("-d")) {
24
- console.log(results);
25
- } else if (argv.includes("--dump-grouped")) {
26
- const groupedByFile = groupBy(results, (r) => r.meta?.file);
27
- console.log(green(JSON.stringify(groupedByFile, null, 2)));
28
- } else if (argv.includes("--combined-string-grouped")) {
29
- const groupedByFile = groupBy(results, (r) => r.meta?.file);
30
- for (const file of Object.keys(groupedByFile)) {
31
- let results = groupedByFile[file];
32
- console.log(green(file) + ": ", yellow(resultsRendered(results)));
33
- }
34
- } else {
35
- for (const result of results) {
36
- console.log(result.value);
37
- }
18
+ if (results == null || results.length == 0) {
19
+ console.error(red("No results"));
20
+ return;
21
+ }
22
+ if (parsedArgs["dump"] || parsedArgs["d"]) {
23
+ console.log(results);
24
+ return;
25
+ }
26
+ if (parsedArgs["dump-grouped"] || parsedArgs["D"]) {
27
+ const groupedByFile = groupBy(results, (r) => r.meta?.file);
28
+ console.log(green(JSON.stringify(groupedByFile, null, 2)));
29
+ return;
30
+ }
31
+ if (
32
+ parsedArgs["render"] ||
33
+ parsedArgs["render-merged"] ||
34
+ parsedArgs["r"]
35
+ ) {
36
+ console.log(yellow(resultsRendered(results)));
37
+ return;
38
+ }
39
+ if (parsedArgs["render-grouped"] || parsedArgs["R"]) {
40
+ const groupedByFile = groupBy(results, (r) => r.meta?.file);
41
+ for (const file of Object.keys(groupedByFile)) {
42
+ let results = groupedByFile[file];
43
+ console.log(green(file) + ": ", yellow(resultsRendered(results)));
38
44
  }
39
- } else {
40
- console.error("No results");
45
+ return;
46
+ }
47
+ for (const result of results) {
48
+ console.log(result.value);
41
49
  }
42
50
  } catch (e) {
43
51
  console.error(e);
@@ -45,74 +53,62 @@ async function cliQueryCookies(name: string, domain: string) {
45
53
  }
46
54
 
47
55
  function main() {
48
- if (argv && argv.length > 2) {
49
- const arg2 = argv[2];
50
- const arg3 = argv[3];
51
- if (arg2 == "--fetch" || arg2 == "-f") {
52
- const f = parsedArgs["f"];
53
- let url: URL;
54
- try {
55
- url = new URL(f);
56
- } catch (e) {
57
- console.error("Invalid URL", arg3);
58
- return;
56
+ if (parsedArgs["help"] || parsedArgs["h"]) {
57
+ console.log(`Usage: ${argv[1]} [name] [domain] [options] `);
58
+ console.log(`Options:`);
59
+ console.log(` -h, --help: Show this help`);
60
+ console.log(` -v, --verbose: Show verbose output`);
61
+ console.log(` -d, --dump: Dump all results`);
62
+ console.log(` -D, --dump-grouped: Dump all results, grouped by profile`);
63
+ console.log(` -r, --render: Render all results`);
64
+ return;
65
+ }
66
+
67
+ const fetchUrl: string = parsedArgs["fetch"] || parsedArgs["F"];
68
+ if (fetchUrl) {
69
+ let url: URL;
70
+ try {
71
+ url = new URL(<string>fetchUrl);
72
+ } catch (e) {
73
+ console.error("Invalid URL", fetchUrl);
74
+ return;
75
+ }
76
+ const headerArgs: string[] | string = parsedArgs["H"];
77
+ const headers = unpackHeaders(headerArgs);
78
+ const onfulfilled = (res: Response) => {
79
+ if (parsedArgs["dump-response-headers"]) {
80
+ res.headers.forEach((value: string, key: string) => {
81
+ console.log(`${key}: ${value}`);
82
+ });
59
83
  }
60
- const headerArgs: string[] | string = parsedArgs["H"];
61
- const headers = unpackHeaders(headerArgs);
62
- const onfulfilled = (res: Response) => {
63
- return res.text().then((r) => {
84
+ if (parsedArgs["dump-response-body"]) {
85
+ res.text().then((r) => {
64
86
  console.log(r);
65
87
  });
66
- };
67
- fetchWithCookies(
68
- url,
69
- {
70
- //
71
- headers,
72
- }
73
- //
74
- ).then(
75
- onfulfilled,
76
- console.error
77
- //
78
- );
88
+ }
79
89
  return;
80
- }
81
- let domain;
82
- if (arg3 != null && arg3.indexOf(".") > -1) {
83
- domain = arg3;
84
- } else {
85
- domain = "%";
86
- }
87
-
88
- const tru = `${true}`;
89
-
90
- if (argv.includes("--require-jwt")) {
91
- env.REQUIRE_JWT = tru;
92
- }
93
- if (argv.includes("--verbose")) {
94
- env.VERBOSE = tru;
95
- }
96
- if (argv.includes("--chrome-only")) {
97
- env.CHROME_ONLY = tru;
98
- }
99
- if (argv.includes("--firefox-only")) {
100
- env.FIREFOX_ONLY = tru;
101
- }
102
- if (argv.includes("--ignore-expired")) {
103
- env.IGNORE_EXPIRED = tru;
104
- }
105
-
106
- if (argv.includes("--single")) {
107
- env.SINGLE = tru;
108
- }
90
+ };
91
+ fetchWithCookies(
92
+ url,
93
+ {
94
+ //
95
+ headers,
96
+ }
97
+ //
98
+ ).then(
99
+ onfulfilled,
100
+ console.error
101
+ //
102
+ );
103
+ return;
104
+ }
109
105
 
110
- if (env.VERBOSE) {
111
- console.log("Verbose mode", argv);
112
- }
106
+ const cookieSpec: CookieSpec = {
107
+ name: parsedArgs["name"] || parsedArgs["_"][0] || "%",
108
+ domain: parsedArgs["domain"] || parsedArgs["_"][1] || "%",
109
+ };
113
110
 
114
- cliQueryCookies(arg2, domain).catch(console.error);
115
- }
111
+ cliQueryCookies(cookieSpec).catch(console.error);
116
112
  }
117
113
 
118
114
  main();
@@ -1,6 +1,6 @@
1
1
  import * as fs from "fs";
2
2
  import * as sqlite3 from "sqlite3";
3
- import { CookieRow } from "./CookieRow";
3
+ import CookieRow from "./CookieRow";
4
4
  import { merge } from "lodash";
5
5
 
6
6
  interface DoSqliteQuery1Params {
@@ -1,16 +1,18 @@
1
1
  // noinspection JSUnusedGlobalSymbols
2
2
 
3
- import { fetch } from "cross-fetch";
3
+ import { fetch as fetchImpl } from "cross-fetch";
4
4
  import { merge } from "lodash";
5
5
  // noinspection SpellCheckingInspection
6
6
  import destr from "destr";
7
- import FetchResponse from "./FetchResponse";
7
+ import CookieSpec from "./CookieSpec";
8
8
  import { getGroupedRenderedCookies } from "./getGroupedRenderedCookies";
9
+ import { cookieJar } from "./MemoryCookieStore";
9
10
 
10
11
  export async function fetchWithCookies(
11
12
  url: RequestInfo | URL,
12
- options: RequestInit | undefined = {}
13
- ): Promise<FetchResponse> {
13
+ options: RequestInit | undefined = {},
14
+ fetch: Function = fetchImpl
15
+ ): Promise<Response> {
14
16
  const defaultOptions: RequestInit = {
15
17
  headers: {
16
18
  "User-Agent":
@@ -23,10 +25,13 @@ export async function fetchWithCookies(
23
25
  const domain = url1.hostname.replace(/^.*(\.\w+\.\w+)$/, (match, p1) => {
24
26
  return `%${p1}`;
25
27
  });
26
- const cookies: string[] = await getGroupedRenderedCookies({
28
+ const cookieSpec: CookieSpec = {
27
29
  name: "%",
28
30
  domain: domain,
29
- }).catch(() => []);
31
+ };
32
+ const cookies: string[] = await getGroupedRenderedCookies(cookieSpec).catch(
33
+ () => []
34
+ );
30
35
  const cookie = cookies.pop();
31
36
  const newOptions1: RequestInit = merge(defaultOptions, options, {
32
37
  headers: {
@@ -35,29 +40,64 @@ export async function fetchWithCookies(
35
40
  });
36
41
  try {
37
42
  const res: Response = await fetch(url2, newOptions1);
38
- const newUrl = res.headers.get("location") as string;
43
+ const headers: [string, string][] = [];
44
+ res.headers.forEach((value, key) => {
45
+ headers.push([key, value]);
46
+ });
47
+ for (const [key, value] of headers) {
48
+ if (key === "set-cookie") {
49
+ await cookieJar.setCookie(value, url2);
50
+ // const cookie = tough.parse(value);
51
+ // if (cookie instanceof Cookie) {
52
+ // await memoryCookieStore.putCookie(cookie);
53
+ // }
54
+ }
55
+ }
56
+
57
+ const newUrl: string = res.headers.get("location") as string;
39
58
  if (res.redirected || (newUrl && newUrl !== url2)) {
40
59
  return fetchWithCookies(newUrl, newOptions1);
41
60
  }
42
- const arrayBuffer1 = res.arrayBuffer();
43
- const arrayBuffer = async () => arrayBuffer1;
44
- const buffer = async () => arrayBuffer().then(Buffer.from);
45
- const text = async () => buffer().then((buffer) => buffer.toString("utf8"));
46
- const json = async () => text().then(destr);
47
- const formData = async () =>
48
- text().then((text) => new URLSearchParams(text));
61
+
62
+ const arrayBuffer1: Promise<ArrayBuffer> = res.arrayBuffer();
63
+
64
+ async function arrayBuffer(): Promise<ArrayBuffer> {
65
+ return arrayBuffer1;
66
+ }
67
+
68
+ async function buffer(): Promise<Buffer> {
69
+ return arrayBuffer().then(Buffer.from);
70
+ }
71
+
72
+ async function text(): Promise<string> {
73
+ return buffer().then((buffer) => buffer.toString("utf8"));
74
+ }
75
+
76
+ async function json(): Promise<any> {
77
+ return text().then((text) => destr(text));
78
+ }
79
+
80
+ async function formData(): Promise<FormData> {
81
+ const urlSearchParams: URLSearchParams = await text().then(
82
+ (text) => new URLSearchParams(text)
83
+ );
84
+ const formData = new FormData();
85
+ for (const [key, value] of urlSearchParams.entries()) {
86
+ formData.append(key, value);
87
+ }
88
+ return formData;
89
+ }
90
+
91
+ const res1: Response = res;
49
92
  const source2 = {
50
- status: res.status,
51
- statusText: res.statusText,
52
- headers: res.headers,
53
93
  arrayBuffer,
54
- buffer,
55
94
  text,
56
95
  json,
96
+ buffer,
57
97
  formData,
58
98
  //
59
99
  };
60
- return merge({}, res, source2);
100
+ return merge(res1, source2);
61
101
  } catch (e) {
62
102
  throw e;
63
103
  }
@@ -2,8 +2,8 @@ import { queryCookies } from "./queryCookies";
2
2
  import CompositeCookieQueryStrategy from "./browsers/CompositeCookieQueryStrategy";
3
3
  import { groupBy } from "lodash";
4
4
  import { resultsRendered } from "./resultsRendered";
5
- import { CookieSpec } from "./CookieSpec";
6
- import { ExportedCookie } from "./ExportedCookie";
5
+ import CookieSpec from "./CookieSpec";
6
+ import ExportedCookie from "./ExportedCookie";
7
7
 
8
8
  export async function getGroupedRenderedCookies(
9
9
  //
package/src/index.ts CHANGED
@@ -5,8 +5,8 @@ import { queryCookies } from "./queryCookies";
5
5
  import FirefoxCookieQueryStrategy from "./browsers/FirefoxCookieQueryStrategy";
6
6
  import ChromeCookieQueryStrategy from "./browsers/ChromeCookieQueryStrategy";
7
7
  import CompositeCookieQueryStrategy from "./browsers/CompositeCookieQueryStrategy";
8
- import { CookieSpec } from "./CookieSpec";
9
- import { ExportedCookie } from "./ExportedCookie";
8
+ import CookieSpec from "./CookieSpec";
9
+ import ExportedCookie from "./ExportedCookie";
10
10
  import { getGroupedRenderedCookies } from "./getGroupedRenderedCookies";
11
11
  import { fetchWithCookies } from "./fetchWithCookies";
12
12
 
@@ -3,8 +3,8 @@ import { uniqBy } from "lodash";
3
3
  import CompositeCookieQueryStrategy from "./browsers/CompositeCookieQueryStrategy";
4
4
  import CookieQueryStrategy from "./browsers/CookieQueryStrategy";
5
5
  import isValidJwt from "./isValidJwt";
6
- import { CookieSpec } from "./CookieSpec";
7
- import { ExportedCookie } from "./ExportedCookie";
6
+ import CookieSpec from "./CookieSpec";
7
+ import ExportedCookie from "./ExportedCookie";
8
8
 
9
9
  export async function queryCookies(
10
10
  { name, domain }: CookieSpec,
@@ -1,5 +1,5 @@
1
1
  import { uniqBy } from "lodash";
2
- import { ExportedCookie } from "./ExportedCookie";
2
+ import ExportedCookie from "./ExportedCookie";
3
3
 
4
4
  export function resultsRendered(results: ExportedCookie[]) {
5
5
  return uniqBy(results, (r) => r.name)
@@ -1,13 +1,16 @@
1
- export function unpackHeaders(headerArgs: string[] | string) {
1
+ export function unpackHeaders(headerArgs: string[] | string | null) {
2
2
  const headers: any = {};
3
+ if (headerArgs == null) {
4
+ return headers;
5
+ }
3
6
  if (Array.isArray(headerArgs)) {
4
7
  for (const h of headerArgs) {
5
8
  const [key, value] = h.split("=");
6
9
  headers[key] = value;
7
10
  }
8
- } else {
9
- const [key, value] = headerArgs.split("=");
10
- headers[key] = value;
11
+ return headers;
11
12
  }
13
+ const [key, value] = headerArgs.split("=");
14
+ headers[key] = value;
12
15
  return headers;
13
16
  }
package/dist/cli.js DELETED
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- var e=require("minimist"),r=require("lodash"),n=require("lru-cache"),t=require("fs"),o=require("crypto"),i=require("path"),a=require("child_process"),s=require("sqlite3"),c=require("jsonwebtoken"),l=require("tty"),u=require("cross-fetch"),g=require("destr");function f(e){return e&&e.__esModule?e.default:e}const d=process.argv??[],h={};(0,r.merge)(h,process.env);const m=h.HOME;if(!m)throw new Error("HOME environment variable is not set");async function y(e){return new Promise(((r,n)=>{(0,a.exec)(e,{encoding:"binary",maxBuffer:5120},((e,t,o)=>{e||o?n(e):t&&r(t.trim())}))}))}async function w({path:e,name:r,maxDepth:n=2}){const o=e.split("/").length;h.VERBOSE&&console.log(`Searching for ${r} in ${e}`);const i=[];let a;try{a=t.readdirSync(e)}catch(r){return h.VERBOSE&&console.log(`Error reading ${e}`,r),[]}for(const s of a){const a=e+"/"+s;let c;try{c=t.statSync(a)}catch(e){h.VERBOSE&&console.error(`Error getting stat for ${a}`,e);continue}if(c.isDirectory()){if(a.split("/").length<o+n)try{const e=await w({path:a,name:r,maxDepth:2});i.push(...e)}catch(e){h.VERBOSE&&console.error(e)}}else s===r&&i.push(a)}return h.VERBOSE&&i.length>0&&(console.log(`Found ${i.length} ${r} files`),console.log(i)),i}async function E({file:e,sql:n,rowTransform:o}){if(!e||e&&!t.existsSync(e))throw new Error(`doSqliteQuery1: file ${e} does not exist`);const i=new s.Database(e);return new Promise(((t,a)=>{i.all(n,((n,i)=>{if(n)return void a(n);const s=i;if(null!=s&&0!==s.length)if(Array.isArray(s)){const n=s.map((n=>{const t={meta:{file:e}},i=o(n);return(0,r.merge)(t,i)}));t(n)}else process.env.VERBOSE&&console.log(`doSqliteQuery1: rows ${JSON.stringify(s)}`),t([s]);else t([])}))}))}function p(e){return void 0!==e.domain&&void 0!==e.name&&void 0!==e.value}function B(e){return void 0!==e.domain&&void 0!==e.name&&void 0!==e.value}class b{async queryCookies(e,n){if("darwin"!==process.platform)throw new Error("This only works on macOS");return h.FIREFOX_ONLY?[]:async function({name:e,domain:n="%",requireJwt:a=!1}){const s=await async function(e,r){try{const n=(await w({path:O,name:"Cookies"})).map((n=>async function(e,r,n){try{return await async function({name:e,domain:r,file:n=i.join(O,"Default","Cookies")}){if(!(0,t.existsSync)(n))throw new Error(`File ${n} does not exist`);if(h.VERBOSE){const t=n.split("/").slice(-3).join("/");console.log(`Trying Chrome (at ${t}) cookie ${e} for domain ${r}`)}let o;o="SELECT encrypted_value, name, host_key FROM cookies";const a=/^([*%])$/i,s=null==e.match(a),c=null==r.match(a);(s||c)&&(o+=" WHERE ",s&&(o+=`name = '${e}'`,c&&(o+=" AND ")),c&&(o+=`host_key LIKE '${r}';`));return E({file:n,sql:o,rowTransform:e=>({domain:e.host_key,name:e.name,value:e.encrypted_value})})}({name:e,domain:r,file:n})}catch(e){return h.VERBOSE&&console.log("Error getting encrypted cookie",e),[]}}(e,r,n)));return(await Promise.all(n)).flat().filter(p)}catch(e){return h.VERBOSE&&console.log("error",e),[]}}(e,n),c=await async function(){return y('security find-generic-password -w -s "Chrome Safe Storage"')}(),l=s.filter((({value:e})=>null!=e&&e.length>0)).map((async e=>{const n=e.value,t=await async function(e,r){let n;try{n=await async function(e,r){if("string"!=typeof e)throw new Error("password must be a string: "+e);let n;if(n=r,null==n||"object"!=typeof n)throw new Error("encryptedData must be a object: "+n);if(!(n instanceof Buffer)){if(!(Array.isArray(n)&&n[0]instanceof Buffer))throw new Error("encryptedData must be a Buffer: "+n);[n]=n,h.VERBOSE&&console.log(`encryptedData is an array of buffers, selected first: ${n}`),n=Buffer.from(n)}h.VERBOSE&&console.log(`Trying to decrypt with password ${e}`);return new Promise(((r,t)=>{o.pbkdf2(e,"saltysalt",1003,16,"sha1",((e,i)=>{try{if(e)return h.VERBOSE&&console.log("Error doing pbkdf2",e),void t(e);if(16!==i.length)return h.VERBOSE&&console.log("Error doing pbkdf2, buffer length is not 16",i.length),void t(new Error("Buffer length is not 16"));const a=new Array(17).join(" "),s=Buffer.from(a,"binary"),c=o.createDecipheriv("aes-128-cbc",i,s);if(c.setAutoPadding(!1),n&&n.slice&&(n=n.slice(3)),n.length%16!=0)return h.VERBOSE&&console.log("Error doing pbkdf2, encryptedData length is not a multiple of 16",n.length),void t(new Error("encryptedData length is not a multiple of 16"));let l=c.update(n);try{c.final("utf-8")}catch(e){return h.VERBOSE&&console.log("Error doing decipher.final()",e),void t(e)}const u=l[l.length-1];u&&(l=l.slice(0,0-u));const g=l.toString("utf8");r(g)}catch(e){t(e)}}))}))}(e,r)}catch(e){h.VERBOSE&&console.log("Error decrypting cookie",e),n=null}return n??r.toString("utf-8")}(c,n),i={};return(0,r.merge)(i,e.meta??{}),{domain:e.domain,name:e.name,value:t,meta:i}})),u=(await Promise.all(l)).filter(B);h.VERBOSE&&console.log("results",u);return u}({requireJwt:!1,name:e,domain:n})}}const O=i.join(m,"Library","Application Support","Google","Chrome");function S({name:e,domain:r}){const n=/^([*%])$/i;return{specifiedName:null==e.match(n),specifiedDomain:null==r.match(n)}}class R{async queryCookies(e,r){if("darwin"!==process.platform)throw new Error("This only works on macOS");if(h.CHROME_ONLY)return[];const n=await this.#e({name:e,domain:r});return Array.isArray(n)?n.map((e=>({domain:e.domain,name:e.name,value:e.value.toString("utf8")}))):[]}async#e({name:e,domain:r}){const n=await w({path:i.join(m,"Library","Application Support","Firefox","Profiles"),name:"cookies.sqlite"});return(await Promise.all(n.map((async n=>await this.#r(n,e,r))))).flat()}async#r(e,r,n){if(e&&!(0,t.existsSync)(e))throw new Error(`File ${e} does not exist`);let o;o="SELECT value, name, host FROM moz_cookies";const{specifiedName:i,specifiedDomain:a}=S({name:r,domain:n});(i||a)&&(o+=" WHERE ",i&&(o+=`name = '${r}'`,a&&(o+=" AND ")),a&&(o+=`host LIKE '${n}';`));const s=e=>{const r=e.value;return{domain:e.domain,name:e.name,value:Buffer.from(r,"utf8")}};try{return await E({file:e,sql:o,rowTransform:s})}catch(r){return console.error(`Error querying ${e}`,r),[]}}}class k{async queryCookies(e,r){return[]}}const v=new(f(n))({ttl:2e3,max:10});class C{#n;constructor(){this.#n=[b,R,k].map((e=>new e))}async queryCookies(e,r){const n=`${e}:${r}`,t=v.get(n);if(t)return t;const o=(await Promise.all(this.#n.map((async n=>n.queryCookies(e,r).catch((()=>[])))))).flat();return v.set(`${e}:${r}`,o),o}}function q(e){try{const r=f(c).decode(e,{complete:!0});h.VERBOSE&&console.log(r);const n=r?.payload;if(n){const e=n.exp;if(e){if((new Date).getTime()/1e3>e)return!1}}return!0}catch(e){return!1}}async function $({name:e,domain:n},t=new C){const o=await t.queryCookies(e,n),i=(0,r.uniqBy)(o,JSON.stringify),a=[];for(const e of i){q(e.value)&&a.push(e)}const s=h.REQUIRE_JWT?a:i;return h.SINGLE?[s[0]]:s}const{env:x={},argv:L=[],platform:T=""}="undefined"==typeof process?{}:process,V="NO_COLOR"in x||L.includes("--no-color"),A="FORCE_COLOR"in x||L.includes("--color"),D="win32"===T,_="dumb"===x.TERM,I=l&&l.isatty&&l.isatty(1)&&x.TERM&&!_,N=!V&&(A||D&&!_||I||"CI"in x&&("GITHUB_ACTIONS"in x||"GITLAB_CI"in x||"CIRCLECI"in x)),M=(e,r,n,t,o=r.substring(0,e)+t,i=r.substring(e+n.length),a=i.indexOf(n))=>o+(a<0?i:M(a,i,n,t)),j=(e,r,n=e,t=e.length+1)=>o=>o||""!==o&&void 0!==o?((e,r,n,t,o)=>e<0?n+r+t:n+M(e,r,t,o)+t)((""+o).indexOf(r,t),o,e,r,n):"",F=(e,r,n)=>j(`[${e}m`,`[${r}m`,n),G={reset:F(0,0),bold:F(1,22,""),dim:F(2,22,""),italic:F(3,23),underline:F(4,24),inverse:F(7,27),hidden:F(8,28),strikethrough:F(9,29),black:F(30,39),red:F(31,39),green:F(32,39),yellow:F(33,39),blue:F(34,39),magenta:F(35,39),cyan:F(36,39),white:F(37,39),gray:F(90,39),bgBlack:F(40,49),bgRed:F(41,49),bgGreen:F(42,49),bgYellow:F(43,49),bgBlue:F(44,49),bgMagenta:F(45,49),bgCyan:F(46,49),bgWhite:F(47,49),blackBright:F(90,39),redBright:F(91,39),greenBright:F(92,39),yellowBright:F(93,39),blueBright:F(94,39),magentaBright:F(95,39),cyanBright:F(96,39),whiteBright:F(97,39),bgBlackBright:F(100,49),bgRedBright:F(101,49),bgGreenBright:F(102,49),bgYellowBright:F(103,49),bgBlueBright:F(104,49),bgMagentaBright:F(105,49),bgCyanBright:F(106,49),bgWhiteBright:F(107,49)},{reset:P,bold:W,dim:H,italic:U,underline:Y,inverse:J,hidden:K,strikethrough:Q,black:X,red:z,green:Z,yellow:ee,blue:re,magenta:ne,cyan:te,white:oe,gray:ie,bgBlack:ae,bgRed:se,bgGreen:ce,bgYellow:le,bgBlue:ue,bgMagenta:ge,bgCyan:fe,bgWhite:de,blackBright:he,redBright:me,greenBright:ye,yellowBright:we,blueBright:Ee,magentaBright:pe,cyanBright:Be,whiteBright:be,bgBlackBright:Oe,bgRedBright:Se,bgGreenBright:Re,bgYellowBright:ke,bgBlueBright:ve,bgMagentaBright:Ce,bgCyanBright:qe,bgWhiteBright:$e}=(({useColor:e=N}={})=>e?G:Object.keys(G).reduce(((e,r)=>({...e,[r]:String})),{}))();function xe(e){return(0,r.uniqBy)(e,(e=>e.name)).map((e=>e.name+"="+e.value)).join("; ")}async function Le({name:e,domain:n}){const t=await $({name:e,domain:n},new C);if(Array.isArray(t)&&t.length>0){const t=await $({name:e,domain:n}),o=(0,r.groupBy)(t,(e=>e.meta?.file));return Object.keys(o).map((e=>xe(o[e])))}throw new Error("Cookie not found")}async function Te(e,n={}){const t=`${e}`,o=new URL(t).hostname.replace(/^.*(\.\w+\.\w+)$/,((e,r)=>`%${r}`)),i=(await Le({name:"%",domain:o}).catch((()=>[]))).pop(),a=(0,r.merge)({headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"},redirect:"manual"},n,{headers:{Cookie:i}});try{const e=await(0,u.fetch)(t,a),n=e.headers.get("location");if(e.redirected||n&&n!==t)return Te(n,a);const o=e.arrayBuffer(),i=async()=>o,s=async()=>i().then(Buffer.from),c=async()=>s().then((e=>e.toString("utf8"))),l=async()=>c().then(f(g)),d=async()=>c().then((e=>new URLSearchParams(e))),h={status:e.status,statusText:e.statusText,headers:e.headers,arrayBuffer:i,buffer:s,text:c,json:l,formData:d};return(0,r.merge)({},e,h)}catch(e){throw e}}function Ve(e){const r={};if(Array.isArray(e))for(const n of e){const[e,t]=n.split("=");r[e]=t}else{const[n,t]=e.split("=");r[n]=t}return r}const Ae=f(e)(d);!function(){if(d&&d.length>2){const e=d[2],n=d[3];if("--fetch"==e||"-f"==e){const e=Ae.f;let r;try{r=new URL(e)}catch(e){return void console.error("Invalid URL",n)}const t=e=>e.text().then((e=>{console.log(e)}));return void Te(r,{headers:Ve(Ae.H)}).then(t,console.error)}let t;t=null!=n&&n.indexOf(".")>-1?n:"%";const o="true";d.includes("--require-jwt")&&(h.REQUIRE_JWT=o),d.includes("--verbose")&&(h.VERBOSE=o),d.includes("--chrome-only")&&(h.CHROME_ONLY=o),d.includes("--firefox-only")&&(h.FIREFOX_ONLY=o),d.includes("--ignore-expired")&&(h.IGNORE_EXPIRED=o),d.includes("--single")&&(h.SINGLE=o),h.VERBOSE&&console.log("Verbose mode",d),async function(e,n){try{const t=await $({name:e,domain:n});if(t.length>0)if(d.includes("--combined-string"))console.log(ee(xe(t)));else if(d.includes("--render")||d.includes("-r"))console.log(ee(xe(t)));else if(d.includes("--dump")||d.includes("-d"))console.log(t);else if(d.includes("--dump-grouped")){const e=(0,r.groupBy)(t,(e=>e.meta?.file));console.log(Z(JSON.stringify(e,null,2)))}else if(d.includes("--combined-string-grouped")){const e=(0,r.groupBy)(t,(e=>e.meta?.file));for(const r of Object.keys(e)){let n=e[r];console.log(Z(r)+": ",ee(xe(n)))}}else for(const e of t)console.log(e.value);else console.error("No results")}catch(e){console.error(e)}}(e,t).catch(console.error)}}();
3
- //# sourceMappingURL=cli.js.map