@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/.husky/commit-msg +0 -0
- package/.husky/pre-commit +0 -0
- package/.husky/pre-push +0 -0
- package/README.md +76 -117
- package/dist/cli.cjs +1 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/eslint.config.js +6 -1
- package/examples/basic-usage.ts +9 -10
- package/examples/cli-examples.sh +0 -0
- package/package.json +29 -19
- package/dist/chunk-GVQTX3C5.js +0 -2
- package/dist/chunk-GVQTX3C5.js.map +0 -1
- package/dist/getChromePassword-6XZINNNO.js +0 -2
- package/dist/getChromePassword-6XZINNNO.js.map +0 -1
package/dist/index.d.cts
CHANGED
|
@@ -12,9 +12,9 @@ import { z } from 'zod';
|
|
|
12
12
|
* };
|
|
13
13
|
* const result = CookieSpecSchema.safeParse(spec);
|
|
14
14
|
* if (result.success) {
|
|
15
|
-
*
|
|
15
|
+
* logger.info('Valid cookie spec:', result.data);
|
|
16
16
|
* } else {
|
|
17
|
-
*
|
|
17
|
+
* logger.error('Invalid cookie spec:', result.error);
|
|
18
18
|
* }
|
|
19
19
|
*
|
|
20
20
|
* // Invalid spec (empty name)
|
|
@@ -77,9 +77,9 @@ type CookieSpec = z.infer<typeof CookieSpecSchema>;
|
|
|
77
77
|
* };
|
|
78
78
|
* const result = ExportedCookieSchema.safeParse(cookie);
|
|
79
79
|
* if (result.success) {
|
|
80
|
-
*
|
|
80
|
+
* logger.info('Valid cookie:', result.data);
|
|
81
81
|
* } else {
|
|
82
|
-
*
|
|
82
|
+
* logger.error('Invalid cookie:', result.error);
|
|
83
83
|
* }
|
|
84
84
|
*
|
|
85
85
|
* // Cookie with infinite expiry
|
|
@@ -209,7 +209,7 @@ type BrowserName = z.infer<typeof BrowserNameSchema>;
|
|
|
209
209
|
*/
|
|
210
210
|
declare const CookieQueryStrategySchema: z.ZodObject<{
|
|
211
211
|
browserName: z.ZodEnum<["Chrome", "Firefox", "Safari", "internal", "unknown"]>;
|
|
212
|
-
queryCookies: z.ZodFunction<z.ZodTuple<[z.ZodString, z.ZodString], z.ZodUnknown>, z.ZodPromise<z.ZodArray<z.ZodObject<{
|
|
212
|
+
queryCookies: z.ZodFunction<z.ZodTuple<[z.ZodString, z.ZodString, z.ZodOptional<z.ZodString>], z.ZodUnknown>, z.ZodPromise<z.ZodArray<z.ZodObject<{
|
|
213
213
|
domain: z.ZodEffects<z.ZodString, string, string>;
|
|
214
214
|
name: z.ZodEffects<z.ZodString, string, string>;
|
|
215
215
|
value: z.ZodPipeline<z.ZodEffects<z.ZodString, unknown, string>, z.ZodAny>;
|
|
@@ -265,7 +265,7 @@ declare const CookieQueryStrategySchema: z.ZodObject<{
|
|
|
265
265
|
}>, "many">>>;
|
|
266
266
|
}, "strict", z.ZodTypeAny, {
|
|
267
267
|
browserName: "unknown" | "Chrome" | "Firefox" | "Safari" | "internal";
|
|
268
|
-
queryCookies: (args_0: string, args_1: string, ...args: unknown[]) => Promise<{
|
|
268
|
+
queryCookies: (args_0: string, args_1: string, args_2: string | undefined, ...args: unknown[]) => Promise<{
|
|
269
269
|
name: string;
|
|
270
270
|
domain: string;
|
|
271
271
|
value?: any;
|
|
@@ -281,7 +281,7 @@ declare const CookieQueryStrategySchema: z.ZodObject<{
|
|
|
281
281
|
}[]>;
|
|
282
282
|
}, {
|
|
283
283
|
browserName: "unknown" | "Chrome" | "Firefox" | "Safari" | "internal";
|
|
284
|
-
queryCookies: (args_0: string, args_1: string, ...args: unknown[]) => Promise<{
|
|
284
|
+
queryCookies: (args_0: string, args_1: string, args_2: string | undefined, ...args: unknown[]) => Promise<{
|
|
285
285
|
name: string;
|
|
286
286
|
value: string;
|
|
287
287
|
domain: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -12,9 +12,9 @@ import { z } from 'zod';
|
|
|
12
12
|
* };
|
|
13
13
|
* const result = CookieSpecSchema.safeParse(spec);
|
|
14
14
|
* if (result.success) {
|
|
15
|
-
*
|
|
15
|
+
* logger.info('Valid cookie spec:', result.data);
|
|
16
16
|
* } else {
|
|
17
|
-
*
|
|
17
|
+
* logger.error('Invalid cookie spec:', result.error);
|
|
18
18
|
* }
|
|
19
19
|
*
|
|
20
20
|
* // Invalid spec (empty name)
|
|
@@ -77,9 +77,9 @@ type CookieSpec = z.infer<typeof CookieSpecSchema>;
|
|
|
77
77
|
* };
|
|
78
78
|
* const result = ExportedCookieSchema.safeParse(cookie);
|
|
79
79
|
* if (result.success) {
|
|
80
|
-
*
|
|
80
|
+
* logger.info('Valid cookie:', result.data);
|
|
81
81
|
* } else {
|
|
82
|
-
*
|
|
82
|
+
* logger.error('Invalid cookie:', result.error);
|
|
83
83
|
* }
|
|
84
84
|
*
|
|
85
85
|
* // Cookie with infinite expiry
|
|
@@ -209,7 +209,7 @@ type BrowserName = z.infer<typeof BrowserNameSchema>;
|
|
|
209
209
|
*/
|
|
210
210
|
declare const CookieQueryStrategySchema: z.ZodObject<{
|
|
211
211
|
browserName: z.ZodEnum<["Chrome", "Firefox", "Safari", "internal", "unknown"]>;
|
|
212
|
-
queryCookies: z.ZodFunction<z.ZodTuple<[z.ZodString, z.ZodString], z.ZodUnknown>, z.ZodPromise<z.ZodArray<z.ZodObject<{
|
|
212
|
+
queryCookies: z.ZodFunction<z.ZodTuple<[z.ZodString, z.ZodString, z.ZodOptional<z.ZodString>], z.ZodUnknown>, z.ZodPromise<z.ZodArray<z.ZodObject<{
|
|
213
213
|
domain: z.ZodEffects<z.ZodString, string, string>;
|
|
214
214
|
name: z.ZodEffects<z.ZodString, string, string>;
|
|
215
215
|
value: z.ZodPipeline<z.ZodEffects<z.ZodString, unknown, string>, z.ZodAny>;
|
|
@@ -265,7 +265,7 @@ declare const CookieQueryStrategySchema: z.ZodObject<{
|
|
|
265
265
|
}>, "many">>>;
|
|
266
266
|
}, "strict", z.ZodTypeAny, {
|
|
267
267
|
browserName: "unknown" | "Chrome" | "Firefox" | "Safari" | "internal";
|
|
268
|
-
queryCookies: (args_0: string, args_1: string, ...args: unknown[]) => Promise<{
|
|
268
|
+
queryCookies: (args_0: string, args_1: string, args_2: string | undefined, ...args: unknown[]) => Promise<{
|
|
269
269
|
name: string;
|
|
270
270
|
domain: string;
|
|
271
271
|
value?: any;
|
|
@@ -281,7 +281,7 @@ declare const CookieQueryStrategySchema: z.ZodObject<{
|
|
|
281
281
|
}[]>;
|
|
282
282
|
}, {
|
|
283
283
|
browserName: "unknown" | "Chrome" | "Firefox" | "Safari" | "internal";
|
|
284
|
-
queryCookies: (args_0: string, args_1: string, ...args: unknown[]) => Promise<{
|
|
284
|
+
queryCookies: (args_0: string, args_1: string, args_2: string | undefined, ...args: unknown[]) => Promise<{
|
|
285
285
|
name: string;
|
|
286
286
|
value: string;
|
|
287
287
|
domain: string;
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as u,b as _,c as l,d as y,e as U,f as d}from"./chunk-GVQTX3C5.js";import{existsSync as ie}from"fs";import{join as D}from"path";import se from"fast-glob";import{homedir as Y}from"os";import{join as ee}from"path";var C=(()=>{let t=Y();if(!t)throw new Error("Unable to determine user home directory");return ee(t,"Library","Application Support","Google","Chrome")})();import oe from"better-sqlite3";function re(t){try{return new oe(t,{readonly:!0,fileMustExist:!0})}catch(e){throw l("Database open failed",e,{file:t}),e}}function te(t){try{return t.close(),Promise.resolve()}catch(e){return l("Database close failed",e),Promise.reject(e instanceof Error?e:new Error("Failed to close database: Unknown error"))}}async function R({file:t,sql:e,params:o,rowFilter:r,rowTransform:s}){let i;try{i=re(t);let c=i.prepare(e).all(o),f=r?c.filter(r):c;return s?f.map(s):f}catch(n){throw l("Database query failed",n,{file:t,sql:e}),n}finally{i&&await te(i)}}function ne(t){if(typeof t!="string")return!1;let e=t.trim();return e.length===0?!1:ie(e)}async function ae(){let t=[D(C,"Default/Cookies"),D(C,"Profile */Cookies"),D(C,"Profile Default/Cookies")],e=[];for(let o of t){let r=await se(o);e.push(...r)}return y("ChromeCookies","Found cookie files",{count:e.length,files:e}),e}function fe(t,e){let o=t==="%",r=o?"SELECT name, encrypted_value, host_key, expires_utc FROM cookies WHERE host_key LIKE ?":"SELECT name, encrypted_value, host_key, expires_utc FROM cookies WHERE name = ? AND host_key LIKE ?",s=o?[`%${e}%`]:[t,`%${e}%`];return{sql:r,params:s}}async function ce(t,e,o){try{let{sql:r,params:s}=fe(e,o);y("ChromeCookies","Executing query",{sql:r,params:s});let i=await R({file:t,sql:r,params:s,rowTransform:n=>({name:n.name,domain:n.host_key,value:n.encrypted_value,expiry:n.expires_utc})});return _("QueryCookies",!0,{file:t,count:i.length}),i}catch(r){return l("Failed to read cookie file",r,{file:t}),[]}}async function z({name:t,domain:e,file:o}){let r=typeof o=="string"&&o.length>0?[o]:await ae();if(r.length===0)return y("ChromeCookies","No cookie files found"),[];let s=[];for(let i of r){if(!ne(i)){y("ChromeCookies","Cookie file missing or invalid",{file:i});continue}let n=await ce(i,t,e);s.push(...n)}return y("ChromeCookies","Query complete",{totalCookies:s.length}),s}import{readFileSync as We}from"fs";import{join as Je}from"path";import me from"fast-glob";var le=u.withTag("listChromeProfiles");function A(){let t=me.sync("./**/Cookies",{cwd:C,absolute:!0});return le.debug("Found cookie files:",t),t}import{createDecipheriv as pe,pbkdf2 as ue}from"crypto";import{memoize as Q}from"lodash-es";var de=Q(t=>t.length>=3&&t[0]===118&&t[1]===49&&t[2]===48?t.slice(3):t,t=>t.toString("hex")),ge=Q(t=>{let e=t[t.length-1];return e&&e<=16?t.slice(0,-e):t},t=>t.toString("hex"));function ye(t){let e=[/.*?0t(.+)$/,/.*?1e`(.+)$/,/.*?[`'](.+)$/,/[^\x20-\x7E]*([\x20-\x7E].+)$/];for(let o of e){let s=t.match(o)?.[1]??"";if(s.length>0)return s}return t}async function N(t,e){if(typeof e!="string")throw new Error("password must be a string");if(!Buffer.isBuffer(t))throw new Error("encryptedData must be a Buffer");return new Promise((o,r)=>{ue(e,"saltysalt",1003,16,"sha1",(s,i)=>{try{if(s){r(new Error("Failed to derive key: "+s.message));return}let n=de(t);if(n.length%16!==0){r(new Error("Encrypted data length is not a multiple of 16"));return}let c=Buffer.alloc(16," "),f=pe("aes-128-cbc",i,c);f.setAutoPadding(!1);let m=f.update(n);try{f.final()}catch(g){r(new Error("Failed to finalize decryption: "+g.message));return}m=ge(m);let p=m.toString("utf8");o(ye(p))}catch(n){r(new Error("Decryption failed: "+n.message))}})})}import{memoize as ke}from"lodash-es";var $=ke(async()=>{if(process.platform!=="darwin")throw l("Chrome password retrieval failed",new Error("This only works on macOS"),{platform:process.platform}),new Error("This only works on macOS");try{let{getChromePassword:t}=await import("./getChromePassword-6XZINNNO.js"),e=await t();return y("ChromePassword","Retrieved password successfully",{platform:"macOS"}),e}catch(t){throw l("Chrome password retrieval failed",t,{platform:"macOS"}),t}});function he(t){return typeof t!="number"||t<=0?"Infinity":new Date(t)}function M(t,e,o,r,s,i){return{domain:t,name:e,value:o,expiry:he(r),meta:{file:s,browser:"Chrome",decrypted:i}}}var w=class{constructor(){this.logger=U("ChromeCookieQueryStrategy");this.browserName="Chrome"}async queryCookies(e,o){try{if(this.logger.info("Querying cookies",{name:e,domain:o}),process.platform!=="darwin")return this.logger.warn("Platform not supported",{platform:process.platform}),[];let r=A();if(r.length===0)return this.logger.warn("No Chrome cookie files found"),[];let s=await $();return(await Promise.all(r.map(n=>this.processFile(n,e,o,s)))).flat()}catch(r){return r instanceof Error?l("Failed to query cookies",r,{name:e,domain:o}):l("Failed to query cookies",new Error(String(r)),{name:e,domain:o}),[]}}async processFile(e,o,r,s){try{let i=await z({name:o,domain:r,file:e}),n={file:e,password:s};return(await Promise.allSettled(i.map(f=>this.processCookie(f,n)))).map(f=>f.status==="fulfilled"?f.value:null).filter(f=>f!==null)}catch(i){return i instanceof Error?this.logger.error("Failed to process cookie file",{error:i,file:e}):this.logger.error("Failed to process cookie file",{error:String(i),file:e}),[]}}async processCookie(e,o){try{let r=Buffer.isBuffer(e.value)?e.value:Buffer.from(String(e.value)),s=await N(r,o.password);return M(e.domain,e.name,s,e.expiry,o.file,!0)}catch(r){return r instanceof Error?this.logger.warn("Failed to decrypt cookie",{error:r}):this.logger.warn("Failed to decrypt cookie",{error:String(r)}),M(e.domain,e.name,e.value.toString("utf-8"),e.expiry,o.file,!1)}}};import{homedir as Ce}from"os";import{join as j}from"path";import we from"fast-glob";function be(){let t=Ce();if(!t)return d("FirefoxCookieQuery","Failed to get home directory"),[];let e=[j(t,"Library/Application Support/Firefox/Profiles/*/cookies.sqlite"),j(t,".mozilla/firefox/*/cookies.sqlite")],o=[];for(let r of e){let s=we.sync(r);o.push(...s)}return y("FirefoxCookieQuery","Found Firefox cookie files",{files:o}),o}var b=class{constructor(){this.browserName="Firefox"}async queryCookies(e,o){let r=be(),s=[];for(let i of r)try{let n=await R({file:i,sql:"SELECT name, value, host as domain, expiry FROM moz_cookies WHERE name = ? AND host LIKE ?",params:[e,`%${o}%`],rowTransform:c=>({name:c.name,value:c.value,domain:c.domain,expiry:c.expiry>0?new Date(c.expiry*1e3):"Infinity",meta:{file:i,browser:"Firefox",decrypted:!1}})});s.push(...n)}catch(n){n instanceof Error?d("FirefoxCookieQuery",`Error reading Firefox cookie file ${i}`,{error:n.message}):d("FirefoxCookieQuery",`Error reading Firefox cookie file ${i}`)}return s}};import{homedir as Oe}from"os";import{join as Fe}from"path";import{Buffer as ve}from"buffer";import{readFileSync as Re}from"fs";import{homedir as Be}from"os";import{join as Pe}from"path";import{Buffer as L}from"buffer";import xe from"destr";import{z as a}from"zod";var B=a.string().trim().min(1,"Domain cannot be empty").refine(t=>/^\.?[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(t),"Invalid domain format"),P=a.string().trim().min(1,"Cookie name cannot be empty").refine(t=>t==="%"||/^[!#$%&'()*+\-.:0-9A-Z \^_`a-z|~]+$/.test(t),"Invalid cookie name format - must contain only valid characters (letters, numbers, and certain symbols) or be '%' for wildcard"),V=a.string().trim().min(1,"Path cannot be empty").refine(t=>t.startsWith("/"),"Path must start with /").refine(t=>/^\/[!#$%&'()*+,\-./:=@\w~]*$/.test(t),"Invalid path format - must contain only valid URL path characters").default("/"),H=a.string().trim().transform(t=>xe(t)).pipe(a.any()),W=a.object({name:P,value:H,domain:B,path:V,expiry:a.number().int(),creation:a.number().int(),flags:a.number().optional(),version:a.number().int().optional(),port:a.number().int().optional(),comment:a.string().optional(),commentURL:a.string().optional()}),bo=a.object({name:P,domain:B}).strict(),Ee=a.object({file:a.string().trim().min(1,"File path cannot be empty").optional(),browser:a.string().trim().optional(),decrypted:a.boolean().optional(),secure:a.boolean().optional(),httpOnly:a.boolean().optional(),path:V.optional()}).catchall(a.unknown()).strict(),S=a.object({domain:B,name:P,value:H,expiry:a.union([a.literal("Infinity"),a.date(),a.number().int().positive("Expiry must be a positive number")]).optional(),meta:Ee.optional()}).strict(),xo=a.object({expiry:a.number().int().optional(),domain:B,name:P,value:a.union([a.string(),a.instanceof(Buffer)])}).strict(),Eo=a.object({format:a.enum(["merged","grouped"]).optional(),separator:a.string().optional(),showFilePaths:a.boolean().optional()}).strict(),Se=a.enum(["Chrome","Firefox","Safari","internal","unknown"]),So=a.object({browserName:Se,queryCookies:a.function().args(a.string(),a.string()).returns(a.promise(a.array(S)))}).strict();var O=class{constructor(e){this.version=0;this.url="";this.name="";this.path="";this.value="";this.flags={isSecure:!1,isHTTPOnly:!1,unknown1:!1,unknown2:!1};this.expiration=0;this.creation=0;let o={offset:0,buffer:e};this.decode(o)}decodeUrlValue(e){let o=e,r;do{r=o;try{o=decodeURIComponent(o)}catch{return r}}while(o!==r&&o.includes("%"));return o}decodeJwtPayload(e){let o=e.split(".");if(o.length!==3)return null;try{let r=L.from(o[1],"base64").toString("utf8"),s=JSON.parse(r);return JSON.stringify(s)}catch{return null}}parseJsonValue(e){try{let o=JSON.parse(e);return JSON.stringify(o)}catch{return null}}processValue(e){let o=this.decodeUrlValue(e);if(o.match(/^ey[A-Za-z0-9_-]+\.ey[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/)){let r=this.decodeJwtPayload(o);if(typeof r=="string"&&r.length>0)return r}if(o.startsWith("{")||o.startsWith("[")){let r=this.parseJsonValue(o);if(typeof r=="string"&&r.length>0)return r}return o}toCookieRow(){try{let e=this.convertFlags(),o=this.url.replace(/^https?:\/\//,"").replace(/\/.*$/,"")||"uk";return W.parse({name:this.name.replace(/^: /,""),value:this.processValue(this.value)||"",domain:o,path:this.path||"/",expiry:this.expiration,creation:this.creation,flags:e,version:this.version,port:this.port,comment:this.comment,commentURL:this.commentURL})}catch{return null}}readNullTerminatedString(e,o){let r=o;for(;r<e.buffer.length&&e.buffer[r]!==0;)r++;return e.buffer.toString("utf8",o,r)||""}readHeader(e){let o=e.buffer.readUInt32LE(e.offset);e.offset+=4,e.offset+=4;let r=e.buffer.readUInt32LE(e.offset);e.offset+=4,this.flags={isSecure:(r&1)!==0,isHTTPOnly:(r&4)!==0,unknown1:(r&8)!==0,unknown2:(r&16)!==0};let s=e.buffer.readUInt32LE(e.offset);e.offset+=4;let i={urlOffset:e.buffer.readUInt32LE(e.offset),nameOffset:e.buffer.readUInt32LE(e.offset+4),pathOffset:e.buffer.readUInt32LE(e.offset+8),valueOffset:e.buffer.readUInt32LE(e.offset+12),commentOffset:e.buffer.readUInt32LE(e.offset+16),commentURLOffset:e.buffer.readUInt32LE(e.offset+20)};return{size:o,hasPort:s,offsets:i}}readTimestamps(e){let o=L.alloc(8);for(let n=0;n<8;n++)o[n]=e.buffer[e.offset+n];let r=o.readDoubleLE(0);e.offset+=8;let s=L.alloc(8);for(let n=0;n<8;n++)s[n]=e.buffer[e.offset+n];let i=s.readDoubleLE(0);e.offset+=8,this.expiration=r,this.creation=i}readStrings(e,o,r){let i=[{field:"url",offset:r.urlOffset},{field:"name",offset:r.nameOffset},{field:"path",offset:r.pathOffset},{field:"value",offset:r.valueOffset},{field:"comment",offset:r.commentOffset}].filter(n=>n.offset>0).sort((n,c)=>n.offset-c.offset);for(let n=0;n<i.length;n++){let{field:c,offset:f}=i[n],p=(n<i.length-1?i[n+1].offset:o)-f,g=0+f;for(;g<0+f+p&&e.buffer[g]!==0;)g++;let h=e.buffer.toString("utf8",0+f,g);switch(c){case"url":this.url=h;break;case"name":this.name=h;break;case"path":this.path=h;break;case"value":this.value=h;break;case"comment":this.comment=h;break}}}decode(e){let{size:o,hasPort:r,offsets:s}=this.readHeader(e),i=e.offset;e.offset=i+24,this.readTimestamps(e),r>0&&(this.port=e.buffer.readUInt16LE(e.offset),e.offset+=2),e.offset=i,this.readStrings(e,o,s)}convertFlags(){return(this.flags.isSecure?1:0)|(this.flags.isHTTPOnly?4:0)|(this.flags.unknown1?8:0)|(this.flags.unknown2?16:0)}};var x=class x{constructor(e){this.cookies=[];let o={offset:0,buffer:e};this.decode(o)}toCookieRows(){let e=[];for(let o of this.cookies)try{let r=o.toCookieRow();r!==null&&e.push(r)}catch(r){let s=r instanceof Error?r.message:String(r);d("BinaryCookies","Error converting cookie",{error:s})}return e}decode(e){let o=e.buffer.readUInt32BE(e.offset);if(e.offset+=4,o!==x.HEADER)throw new Error("Invalid page header");let r=e.buffer.readUInt32LE(e.offset);e.offset+=4;let s=e.offset-8,i=[];for(let c=0;c<r;c++){let f=e.buffer.readUInt32LE(e.offset);i.push(f),e.offset+=4}let n=e.buffer.readUInt32BE(e.offset);if(e.offset+=4,n!==x.FOOTER)throw new Error("Invalid page footer");for(let c=0;c<r;c++)try{let f=i[c],m=s+f,p=e.buffer.readUInt32LE(m);if(p<48){d("BinaryCookies",`Invalid cookie size ${p} at index ${c}`);continue}if(m+p>e.buffer.length){d("BinaryCookies",`Cookie size ${p} at index ${c} would exceed buffer length`);continue}let g=e.buffer.subarray(m,m+p),h=new O(g);this.cookies.push(h)}catch(f){let m=f instanceof Error?f.message:String(f);d("BinaryCookies",`Error decoding cookie at index ${c}`,{error:m})}}};x.HEADER=256,x.FOOTER=0;var F=x;var k=class k{constructor(e){let o={offset:0,buffer:e};this.pages=[],this.metadata={},this.decode(o)}static fromFile(e){let o=Re(e);return new k(o)}static fromDefaultPath(){return k.fromFile(k.DEFAULT_COOKIE_PATH)}toCookieRows(){let e=[];for(let o of this.pages)try{let r=o.toCookieRows();Array.isArray(r)&&e.push(...r)}catch(r){let s=r instanceof Error?r.message:String(r);d("BinaryCookies","Error converting page cookies",{error:s})}return e}decode(e){try{let o=e.buffer.subarray(e.offset,e.offset+4);if(e.offset+=4,!o.equals(k.MAGIC))throw new Error("Missing magic value");let r=e.buffer.readUInt32BE(e.offset);e.offset+=4;let s=[];for(let m=0;m<r;m++)s.push(e.buffer.readUInt32BE(e.offset)),e.offset+=4;let i=e.offset;for(let m of s)try{let p=e.buffer.subarray(i,i+m),g=new F(p);this.pages.push(g),i+=m}catch(p){let g=p instanceof Error?p.message:String(p);d("BinaryCookies","Error decoding page",{error:g}),i+=m}e.offset=i;let n=e.buffer.readUInt32BE(e.offset);e.offset+=4;let c=e.buffer.readBigUInt64BE(e.offset);e.offset+=8,c!==k.FOOTER&&d("BinaryCookies","Invalid cookie file format: wrong footer");let f=e.buffer.subarray(e.offset);this.metadata={}}catch(o){let r=o instanceof Error?o.message:String(o);throw d("BinaryCookies","Error decoding binary cookies file",{error:r}),o}}};k.MAGIC=ve.from("cook","utf8"),k.FOOTER=BigInt("0x071720050000004b"),k.DEFAULT_COOKIE_PATH=Pe(Be(),"Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies");var T=k;function Z(t){return T.fromFile(t).toCookieRows()}var I=class{constructor(){this.browserName="Safari"}getCookieDbPath(e){return Fe(e,"Library","Containers","com.apple.Safari","Data","Library","Cookies","Cookies.binarycookies")}decodeCookies(e,o,r){try{return Z(e).filter(i=>(o==="%"||i.name===o)&&(r==="%"||i.domain.includes(r))).map(i=>({domain:i.domain,name:i.name,value:Buffer.isBuffer(i.value)?i.value.toString():String(i.value),expiry:typeof i.expiry=="number"&&i.expiry>0?new Date(i.expiry*1e3):"Infinity",meta:{file:e,browser:"Safari",decrypted:!1}}))}catch(s){return s instanceof Error?l("SafariCookieQueryStrategy",`Error decoding ${e}`,{error:s,name:o,domain:r}):l("SafariCookieQueryStrategy",`Error decoding ${e}`,{error:"Unknown error",name:o,domain:r}),[]}}async queryCookies(e,o){let r=Oe();if(typeof r!="string"||r.length===0)return l("SafariCookieQueryStrategy","Failed to get home directory"),Promise.resolve([]);let s=this.getCookieDbPath(r);return Promise.resolve(this.decodeCookies(s,e||"%",o||"%"))}};async function q(t){if(!t.name||!t.domain)return[];let{name:e,domain:o}=t;if(typeof e!="string"||typeof o!="string")return[];let r=[new w,new b,new I];return(await Promise.allSettled(r.map(i=>i.queryCookies(e,o)))).filter(i=>i.status==="fulfilled").flatMap(i=>i.value)}async function E(t){try{return await q(t)}catch(e){return u.warn("Error querying cookies:",e instanceof Error?e.message:String(e)),[]}}async function J(t){try{return await new w().queryCookies(t.name,t.domain)}catch(e){return u.warn("Error querying Chrome cookies:",e),[]}}async function G(t){try{return await new b().queryCookies(t.name,t.domain)}catch(e){return u.warn("Error querying Firefox cookies:",e instanceof Error?e.message:String(e)),[]}}import{groupBy as Te}from"lodash-es";function v(t,e={}){let{format:o="merged",showFilePaths:r=!0,separator:s="; "}=e;if(t.length===0)return o==="merged"?"":[];if(o==="merged")return t.map(n=>n.value).join(s);let i=Te(t,n=>n.meta?.file??"unknown");return Object.entries(i).map(([n,c])=>{let f=c.map(m=>m.value).join(s);return r?`${n}: ${f}`:f})}async function K(t,e={}){try{let o=await E(t);if(!Array.isArray(o))return[];let r=o.filter(s=>{let i=S.safeParse(s);return i.success?!0:(u.warn("Invalid cookie format:",i.error.format()),!1)});return v(r,{...e,format:"grouped"})}catch(o){return u.warn("Error getting grouped rendered cookies:",o instanceof Error?o.message:String(o)),[]}}async function X(t,e){try{let o=await E(t);if(!Array.isArray(o))return"";let r=o.filter(i=>{let n=S.safeParse(i);return n.success?!0:(u.warn("Invalid cookie format:",n.error.format()),!1)}),s=v(r,{...e,format:"merged"});return typeof s=="string"?s:""}catch(o){return u.warn("Error getting merged rendered cookies:",o instanceof Error?o.message:String(o)),""}}export{J as getChromeCookie,E as getCookie,G as getFirefoxCookie,K as getGroupedRenderedCookies,X as getMergedRenderedCookies};
|
|
1
|
+
import{createConsola as ue}from"consola";import{homedir as fe}from"os";import{config as ce}from"dotenv";import{z as F}from"zod";ce();var me=F.object({LOG_LEVEL:F.enum(["debug","info","warn","error"]).default("info"),HOME:F.string().optional().transform(r=>r??process.env.USERPROFILE??"").pipe(F.string().min(1))}),q=me.parse({LOG_LEVEL:process.env.LOG_LEVEL,HOME:fe()});var pe=ue({fancy:!0,formatOptions:{showLogLevel:!1,colors:!0,date:!1,compact:!0,columns:typeof process.stdout.columns=="number"?process.stdout.columns:80},level:q.LOG_LEVEL==="debug"?5:2}),ro=q.LOG_LEVEL==="debug",le=pe,u=le;function M(r,e,o){e?u.success(`${r} succeeded`,o):u.error(`${r} failed`,o)}function p(r,e,o){let t=e instanceof Error?e.message:String(e);u.error(r,{...o,error:t})}function y(r,e,o){u.warn(`[${r}] ${e}`,o)}function g(r){return u.withTag(r)}import{existsSync as ke}from"fs";import{join as A}from"path";import be from"fast-glob";import{homedir as ge}from"os";import{join as de}from"path";var x=(()=>{let r=ge();if(!r)throw new Error("Unable to determine user home directory");return de(r,"Library","Application Support","Google","Chrome")})();import ye from"better-sqlite3";function he(r){try{return new ye(r,{readonly:!0,fileMustExist:!0})}catch(e){throw p("Database open failed",e,{file:r}),e}}function Ce(r){try{return r.close(),Promise.resolve()}catch(e){return p("Database close failed",e),Promise.reject(e instanceof Error?e:new Error("Failed to close database: Unknown error"))}}async function L({file:r,sql:e,params:o,rowFilter:t,rowTransform:s}){let i;try{i=he(r);let c=i.prepare(e).all(o),f=t?c.filter(t):c;return s?f.map(s):f}catch(n){throw p("Database query failed",n,{file:r,sql:e}),n}finally{i&&await Ce(i)}}var B=g("getEncryptedChromeCookie");function we(r){if(typeof r!="string")return!1;let e=r.trim();return e.length===0?!1:ke(e)}async function xe(){let r=[A(x,"Default/Cookies"),A(x,"Profile */Cookies"),A(x,"Profile Default/Cookies")],e=[];for(let o of r){let t=await be(o);e.push(...t)}return B.debug("ChromeCookies","Found cookie files",{count:e.length,files:e}),e}function Ee(r,e){let o=r==="%",t=o?"SELECT name, encrypted_value, host_key, expires_utc FROM cookies WHERE host_key LIKE ?":"SELECT name, encrypted_value, host_key, expires_utc FROM cookies WHERE name = ? AND host_key LIKE ?",s=o?[`%${e}%`]:[r,`%${e}%`];return{sql:t,params:s}}async function Se(r,e,o){try{let{sql:t,params:s}=Ee(e,o);B.debug("ChromeCookies","Executing query",{sql:t,params:s});let i=await L({file:r,sql:t,params:s,rowTransform:n=>({name:n.name,domain:n.host_key,value:n.encrypted_value,expiry:n.expires_utc})});return M("QueryCookies",!0,{file:r,count:i.length}),i}catch(t){return p("Failed to read cookie file",t,{file:r}),[]}}async function j({name:r,domain:e,file:o}){let t=typeof o=="string"&&o.length>0?[o]:await xe();if(t.length===0)return B.debug("ChromeCookies","No cookie files found"),[];let s=[];for(let i of t){if(!we(i)){B.debug("ChromeCookies","Cookie file missing or invalid",{file:i});continue}let n=await Se(i,r,e);s.push(...n)}return B.debug("ChromeCookies","Query complete",{totalCookies:s.length}),s}import{readFileSync as Eo}from"fs";import{join as vo}from"path";import ve from"fast-glob";var Re=g("listChromeProfiles");function V(){let r=ve.sync("./**/Cookies",{cwd:x,absolute:!0});return Re.debug("Found cookie files:",r),r}import{createDecipheriv as Be,pbkdf2 as Oe}from"crypto";import{memoize as H}from"lodash-es";var Pe=H(r=>r.length>=3&&r[0]===118&&r[1]===49&&r[2]===48?r.slice(3):r,r=>r.toString("hex")),Fe=H(r=>{let e=r[r.length-1];return e&&e<=16?r.slice(0,-e):r},r=>r.toString("hex"));function Le(r){let e=[/.*?0t(.+)$/,/.*?1e`(.+)$/,/.*?[`'](.+)$/,/[^\x20-\x7E]*([\x20-\x7E].+)$/];for(let o of e){let s=r.match(o)?.[1]??"";if(s.length>0)return s}return r}async function G(r,e){if(typeof e!="string")throw new Error("password must be a string");if(!Buffer.isBuffer(r))throw new Error("encryptedData must be a Buffer");return new Promise((o,t)=>{Oe(e,"saltysalt",1003,16,"sha1",(s,i)=>{try{if(s){t(new Error("Failed to derive key: "+s.message));return}let n=Pe(r);if(n.length%16!==0){t(new Error("Encrypted data length is not a multiple of 16"));return}let c=Buffer.alloc(16," "),f=Be("aes-128-cbc",i,c);f.setAutoPadding(!1);let m=f.update(n);try{f.final()}catch(d){t(new Error("Failed to finalize decryption: "+d.message));return}m=Fe(m);let l=m.toString("utf8");o(Le(l))}catch(n){t(new Error("Decryption failed: "+n.message))}})})}import{platform as J}from"os";import{exec as Te}from"child_process";import{promisify as Ie}from"util";var De=Ie(Te),$=class extends Error{constructor(o,t,s){super(o);this.command=t;this.originalError=s;this.name="CommandExecutionError"}};async function W(r,e){try{let o=await De(r,{...e,encoding:"utf8"});return{stdout:o.stdout.toString(),stderr:o.stderr.toString()}}catch(o){throw p("Command execution failed",o,{command:r}),new $(o instanceof Error?o.message:String(o),r,o instanceof Error?o:void 0)}}async function Z(){return(await W('security find-generic-password -w -s "Chrome Safe Storage"')).stdout.trim()}async function K(){switch(J()){case"darwin":return Z();default:throw new Error(`Platform ${J()} is not supported`)}}function Ue(r){return typeof r!="number"||r<=0?"Infinity":new Date(r)}function X(r,e,o,t,s,i){return{domain:r,name:e,value:o,expiry:Ue(t),meta:{file:s,browser:"Chrome",decrypted:i}}}var E=class{constructor(){this.logger=g("ChromeCookieQueryStrategy");this.browserName="Chrome"}async queryCookies(e,o,t){try{if(this.logger.info("Querying cookies",{name:e,domain:o,store:t}),process.platform!=="darwin")return this.logger.warn("Platform not supported",{platform:process.platform}),[];let s=t??V(),i=Array.isArray(s)?s:[s];if(i.length===0)return this.logger.warn("No Chrome cookie files found"),[];let n=await K();return(await Promise.all(i.map(f=>this.processFile(f,e,o,n)))).flat()}catch(s){return s instanceof Error?p("Failed to query cookies",s,{name:e,domain:o}):p("Failed to query cookies",new Error(String(s)),{name:e,domain:o}),[]}}async processFile(e,o,t,s){try{let i=await j({name:o,domain:t,file:e}),n={file:e,password:s};return(await Promise.allSettled(i.map(f=>this.processCookie(f,n)))).map(f=>f.status==="fulfilled"?f.value:null).filter(f=>f!==null)}catch(i){return i instanceof Error?this.logger.error("Failed to process cookie file",{error:i,file:e}):this.logger.error("Failed to process cookie file",{error:String(i),file:e}),[]}}async processCookie(e,o){try{let t=Buffer.isBuffer(e.value)?e.value:Buffer.from(String(e.value)),s=await G(t,o.password);return X(e.domain,e.name,s,e.expiry,o.file,!0)}catch(t){return t instanceof Error?this.logger.warn("Failed to decrypt cookie",{error:t}):this.logger.warn("Failed to decrypt cookie",{error:String(t)}),X(e.domain,e.name,e.value.toString("utf-8"),e.expiry,o.file,!1)}}};import{homedir as _e}from"os";import{join as Y}from"path";import ze from"fast-glob";var qe=g("FirefoxCookieQueryStrategy");function Ae(){let r=_e();if(!r)return y("FirefoxCookieQuery","Failed to get home directory"),[];let e=[Y(r,"Library/Application Support/Firefox/Profiles/*/cookies.sqlite"),Y(r,".mozilla/firefox/*/cookies.sqlite")],o=[];for(let t of e){let s=ze.sync(t);o.push(...s)}return qe.debug("Found Firefox cookie files",{files:o}),o}var S=class{constructor(){this.browserName="Firefox"}async queryCookies(e,o,t){let s=t??Ae(),i=Array.isArray(s)?s:[s],n=[];for(let c of i)try{let f=await L({file:c,sql:"SELECT name, value, host as domain, expiry FROM moz_cookies WHERE name = ? AND host LIKE ?",params:[e,`%${o}%`],rowTransform:m=>({name:m.name,value:m.value,domain:m.domain,expiry:m.expiry>0?new Date(m.expiry*1e3):"Infinity",meta:{file:c,browser:"Firefox",decrypted:!1}})});n.push(...f)}catch(f){f instanceof Error?y("FirefoxCookieQuery",`Error reading Firefox cookie file ${c}`,{error:f.message}):y("FirefoxCookieQuery",`Error reading Firefox cookie file ${c}`)}return n}};import{homedir as Ge}from"os";import{join as We}from"path";import{Buffer as Me}from"buffer";import{readFileSync as je}from"fs";import{homedir as Ve}from"os";import{join as He}from"path";import{Buffer as Q}from"buffer";import $e from"destr";import{z as a}from"zod";var T=a.string().trim().min(1,"Domain cannot be empty").refine(r=>/^\.?[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(r),"Invalid domain format"),I=a.string().trim().min(1,"Cookie name cannot be empty").refine(r=>r==="%"||/^[!#$%&'()*+\-.:0-9A-Z \^_`a-z|~]+$/.test(r),"Invalid cookie name format - must contain only valid characters (letters, numbers, and certain symbols) or be '%' for wildcard"),ee=a.string().trim().min(1,"Path cannot be empty").refine(r=>r.startsWith("/"),"Path must start with /").refine(r=>/^\/[!#$%&'()*+,\-./:=@\w~]*$/.test(r),"Invalid path format - must contain only valid URL path characters").default("/"),oe=a.string().trim().transform(r=>$e(r)).pipe(a.any()),re=a.object({name:I,value:oe,domain:T,path:ee,expiry:a.number().int(),creation:a.number().int(),flags:a.number().optional(),version:a.number().int().optional(),port:a.number().int().optional(),comment:a.string().optional(),commentURL:a.string().optional()}),tr=a.object({name:I,domain:T}).strict(),Qe=a.object({file:a.string().trim().min(1,"File path cannot be empty").optional(),browser:a.string().trim().optional(),decrypted:a.boolean().optional(),secure:a.boolean().optional(),httpOnly:a.boolean().optional(),path:ee.optional()}).catchall(a.unknown()).strict(),O=a.object({domain:T,name:I,value:oe,expiry:a.union([a.literal("Infinity"),a.date(),a.number().int().positive("Expiry must be a positive number")]).optional(),meta:Qe.optional()}).strict(),ir=a.object({expiry:a.number().int().optional(),domain:T,name:I,value:a.union([a.string(),a.instanceof(Buffer)])}).strict(),sr=a.object({format:a.enum(["merged","grouped"]).optional(),separator:a.string().optional(),showFilePaths:a.boolean().optional()}).strict(),Ne=a.enum(["Chrome","Firefox","Safari","internal","unknown"]),nr=a.object({browserName:Ne,queryCookies:a.function().args(a.string(),a.string(),a.string().optional()).returns(a.promise(a.array(O)))}).strict();var k=g("BinaryCodableCookie"),D=class{constructor(e){this.version=0;this.url="";this.name="";this.path="";this.value="";this.flags={isSecure:!1,isHTTPOnly:!1,unknown1:!1,unknown2:!1};this.expiration=0;this.creation=0;let o={offset:0,buffer:e};this.decode(o)}decodeUrlValue(e){let o=e,t;do{t=o;try{o=decodeURIComponent(o)}catch{return t}}while(o!==t&&o.includes("%"));return o}decodeJwtPayload(e){let o=e.split(".");if(o.length!==3)return null;try{let t=Q.from(o[1],"base64").toString("utf8"),s=JSON.parse(t);return JSON.stringify(s)}catch{return null}}parseJsonValue(e){try{let o=JSON.parse(e);return JSON.stringify(o)}catch{return null}}processValue(e){let o=this.decodeUrlValue(e);if(o.match(/^ey[A-Za-z0-9_-]+\.ey[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/)){let t=this.decodeJwtPayload(o);if(typeof t=="string"&&t.length>0)return t}if(o.startsWith("{")||o.startsWith("[")){let t=this.parseJsonValue(o);if(typeof t=="string"&&t.length>0)return t}return o}toCookieRow(){try{let e=this.convertFlags(),o=this.url.replace(/^https?:\/\//,"").replace(/\/.*$/,"")||"uk",t=978307200,s=this.expiration>0?this.expiration+t:this.expiration,i=this.creation>0?this.creation+t:this.creation;return re.parse({name:this.name.replace(/^: /,""),value:this.processValue(this.value)||"",domain:o,path:this.path||"/",expiry:s,creation:i,flags:e,version:this.version,port:this.port,comment:this.comment,commentURL:this.commentURL})}catch{return null}}readNullTerminatedString(e,o){let t=o;for(;t<e.buffer.length&&e.buffer[t]!==0;)t++;return e.buffer.toString("utf8",o,t)||""}readHeader(e){let o=e.buffer.readUInt32LE(e.offset);k.debug("Cookie size:",o),e.offset+=4;let t=e.buffer.readUInt32LE(e.offset);k.debug("Cookie version:",t),e.offset+=4;let s=e.buffer.readUInt32LE(e.offset);k.debug("Cookie flags:",s.toString(2).padStart(8,"0")),e.offset+=4,this.flags={isSecure:(s&1)!==0,isHTTPOnly:(s&4)!==0,unknown1:(s&8)!==0,unknown2:(s&16)!==0};let i=e.buffer.readUInt32LE(e.offset);k.debug("Has port:",i),e.offset+=4;let n={urlOffset:e.buffer.readUInt32LE(e.offset),nameOffset:e.buffer.readUInt32LE(e.offset+4),pathOffset:e.buffer.readUInt32LE(e.offset+8),valueOffset:e.buffer.readUInt32LE(e.offset+12),commentOffset:e.buffer.readUInt32LE(e.offset+16),commentURLOffset:e.buffer.readUInt32LE(e.offset+20)};return k.debug("String offsets:",n),{size:o,hasPort:i,offsets:n}}readTimestamps(e){let o=Q.alloc(8);for(let n=0;n<8;n++)o[n]=e.buffer[e.offset+n];let t=o.readDoubleLE(0);e.offset+=8;let s=Q.alloc(8);for(let n=0;n<8;n++)s[n]=e.buffer[e.offset+n];let i=s.readDoubleLE(0);e.offset+=8,this.expiration=t,this.creation=i}readStrings(e,o,t){k.debug("Reading strings from cookie buffer of size:",o);let i=[{field:"url",offset:t.urlOffset},{field:"name",offset:t.nameOffset},{field:"path",offset:t.pathOffset},{field:"value",offset:t.valueOffset},{field:"comment",offset:t.commentOffset}].filter(n=>n.offset>0).sort((n,c)=>n.offset-c.offset);k.debug("Reading strings in order:",i.map(n=>n.field));for(let n=0;n<i.length;n++){let{field:c,offset:f}=i[n],l=(n<i.length-1?i[n+1].offset:o)-f,d=0+f;for(;d<0+f+l&&e.buffer[d]!==0;)d++;let w=e.buffer.toString("utf8",0+f,d);switch(k.debug(`Read ${c}:`,w),c){case"url":this.url=w;break;case"name":this.name=w;break;case"path":this.path=w;break;case"value":this.value=w;break;case"comment":this.comment=w;break}}}decode(e){let{size:o,hasPort:t,offsets:s}=this.readHeader(e),i=e.offset;e.offset=i+24,this.readTimestamps(e),t>0&&(this.port=e.buffer.readUInt16LE(e.offset),e.offset+=2),e.offset=i,this.readStrings(e,o,s)}convertFlags(){return(this.flags.isSecure?1:0)|(this.flags.isHTTPOnly?4:0)|(this.flags.unknown1?8:0)|(this.flags.unknown2?16:0)}};var h=g("BinaryCodablePage"),v=class v{constructor(e){this.cookies=[];let o={offset:0,buffer:e};this.decode(o)}toCookieRows(){let e=[];for(let o of this.cookies)try{let t=o.toCookieRow();t!==null&&e.push(t)}catch(t){let s=t instanceof Error?t.message:String(t);y("BinaryCookies","Error converting cookie",{error:s})}return e}decode(e){let o=e.buffer.readUInt32BE(e.offset);if(h.debug("Page header:",o.toString(16)),e.offset+=4,o!==v.HEADER)throw new Error("Invalid page header");let t=e.buffer.readUInt32LE(e.offset);h.debug("Cookie count:",t),e.offset+=4;let s=e.offset-8;h.debug("Page start offset:",s);let i=[];for(let c=0;c<t;c++){let f=e.buffer.readUInt32LE(e.offset);i.push(f),h.debug(`Cookie ${c} offset:`,f),e.offset+=4}let n=e.buffer.readUInt32BE(e.offset);if(h.debug("Page footer:",n.toString(16)),e.offset+=4,n!==v.FOOTER)throw new Error("Invalid page footer");for(let c=0;c<t;c++)try{let f=i[c];h.debug(`Reading cookie ${c} at offset:`,f);let m=e.buffer.readUInt32LE(f);if(h.debug(`Cookie ${c} size:`,m),m<48){h.warn(`Invalid cookie size ${m} at index ${c}`);continue}if(f+m>e.buffer.length){h.warn(`Cookie size ${m} at index ${c} would exceed buffer length ${e.buffer.length}`);continue}let l=e.buffer.subarray(f,f+m),d=new D(l);this.cookies.push(d)}catch(f){h.warn("Invalid cookie data",{error:f instanceof Error?f.message:String(f)})}}};v.HEADER=256,v.FOOTER=0;var U=v;var b=g("BinaryCodableCookies"),C=class C{constructor(e){let o={offset:0,buffer:e};this.pages=[],this.metadata={},this.decode(o)}static fromFile(e){let o=je(e);return new C(o)}static fromDefaultPath(){return C.fromFile(C.DEFAULT_COOKIE_PATH)}toCookieRows(){let e=[];for(let o of this.pages)try{let t=o.toCookieRows();Array.isArray(t)&&e.push(...t)}catch(t){let s=t instanceof Error?t.message:String(t);y("BinaryCookies","Error converting page cookies",{error:s})}return e}decode(e){try{let o=e.buffer.subarray(e.offset,e.offset+4);if(e.offset+=4,b.debug("Magic bytes:",o.toString()),!o.equals(C.MAGIC))throw new Error("Missing magic value");let t=e.buffer.readUInt32BE(e.offset);b.debug("Page count:",t),e.offset+=4;let s=[];for(let m=0;m<t;m++){let l=e.buffer.readUInt32BE(e.offset);s.push(l),b.debug(`Page ${m} size:`,l),e.offset+=4}let i=e.offset;b.debug("Starting page data at offset:",i);for(let m of s)try{b.debug("Reading page at offset:",i,"with size:",m);let l=e.buffer.subarray(i,i+m),d=new U(l);this.pages.push(d),i+=m}catch(l){let d=l instanceof Error?l.message:String(l);b.warn("Error decoding page:",{error:d}),i+=m}e.offset=i;let n=e.buffer.readUInt32BE(e.offset);b.debug("Checksum:",n.toString(16)),e.offset+=4;let c=e.buffer.readBigUInt64BE(e.offset);b.debug("Footer:",c.toString(16)),e.offset+=8,c!==C.FOOTER&&y("BinaryCookies","Invalid cookie file format: wrong footer");let f=e.buffer.subarray(e.offset);this.metadata={}}catch(o){let t=o instanceof Error?o.message:String(o);throw y("BinaryCookies","Error decoding binary cookies file",{error:t}),o}}};C.MAGIC=Me.from("cook","utf8"),C.FOOTER=BigInt("0x071720050000004b"),C.DEFAULT_COOKIE_PATH=He(Ve(),"Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies");var _=C;function te(r){return _.fromFile(r).toCookieRows()}var z=class{constructor(){this.browserName="Safari"}getCookieDbPath(e){return We(e,"Library","Containers","com.apple.Safari","Data","Library","Cookies","Cookies.binarycookies")}formatDomain(e){return e.startsWith(".")?e.slice(1):e}formatExpiry(e){return e<=0?"Infinity":new Date(e*1e3)}isFlagSet(e,o){return typeof e!="number"||isNaN(e)||e<=0?!1:(e&o)===o}formatCreation(e){if(!(typeof e!="number"||isNaN(e)||e<=0))return e*1e3}decodeCookies(e,o,t){try{return te(e).filter(i=>(o==="%"||i.name===o)&&(t==="%"||this.formatDomain(i.domain).includes(t))).map(i=>({domain:this.formatDomain(i.domain),name:i.name,value:Buffer.isBuffer(i.value)?i.value.toString():String(i.value),expiry:this.formatExpiry(i.expiry),meta:{file:e,browser:"Safari",decrypted:!1,secure:this.isFlagSet(i.flags,1),httpOnly:this.isFlagSet(i.flags,4),path:i.path,version:i.version,comment:i.comment,commentURL:i.commentURL,port:i.port,creation:this.formatCreation(i.creation)}}))}catch(s){return s instanceof Error?p("SafariCookieQueryStrategy",`Error decoding ${e}`,{error:s,name:o,domain:t}):p("SafariCookieQueryStrategy",`Error decoding ${e}`,{error:"Unknown error",name:o,domain:t}),[]}}async queryCookies(e,o,t){let s=Ge();if(typeof s!="string"||s.length===0)return p("SafariCookieQueryStrategy","Failed to get home directory"),Promise.resolve([]);let i=t??this.getCookieDbPath(s);return Promise.resolve(this.decodeCookies(i,e||"%",o||"%"))}};async function N(r){if(!r.name||!r.domain)return[];let{name:e,domain:o}=r;if(typeof e!="string"||typeof o!="string")return[];let t=[new E,new S,new z];return(await Promise.allSettled(t.map(i=>i.queryCookies(e,o)))).filter(i=>i.status==="fulfilled").flatMap(i=>i.value)}async function R(r){try{return await N(r)}catch(e){return u.warn("Error querying cookies:",e instanceof Error?e.message:String(e)),[]}}async function ie(r){try{return await new E().queryCookies(r.name,r.domain)}catch(e){return u.warn("Error querying Chrome cookies:",e),[]}}async function se(r){try{return await new S().queryCookies(r.name,r.domain)}catch(e){return u.warn("Error querying Firefox cookies:",e instanceof Error?e.message:String(e)),[]}}import{groupBy as Ze}from"lodash-es";function P(r,e={}){let{format:o="merged",showFilePaths:t=!0,separator:s="; "}=e;if(r.length===0)return o==="merged"?"":[];if(o==="merged")return r.map(n=>n.value).join(s);let i=Ze(r,n=>n.meta?.file??"unknown");return Object.entries(i).map(([n,c])=>{let f=c.map(m=>m.value).join(s);return t?`${n}: ${f}`:f})}async function ne(r,e={}){try{let o=await R(r);if(!Array.isArray(o))return[];let t=o.filter(s=>{let i=O.safeParse(s);return i.success?!0:(u.warn("Invalid cookie format:",i.error.format()),!1)});return P(t,{...e,format:"grouped"})}catch(o){return u.warn("Error getting grouped rendered cookies:",o instanceof Error?o.message:String(o)),[]}}async function ae(r,e){try{let o=await R(r);if(!Array.isArray(o))return"";let t=o.filter(i=>{let n=O.safeParse(i);return n.success?!0:(u.warn("Invalid cookie format:",n.error.format()),!1)}),s=P(t,{...e,format:"merged"});return typeof s=="string"?s:""}catch(o){return u.warn("Error getting merged rendered cookies:",o instanceof Error?o.message:String(o)),""}}export{ie as getChromeCookie,R as getCookie,se as getFirefoxCookie,ne as getGroupedRenderedCookies,ae as getMergedRenderedCookies};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|