@mherod/get-cookie 4.3.1 → 4.4.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/.claude/settings.local.json +3 -0
- package/.dependency-cruiser.js +277 -0
- package/README.md +106 -48
- package/biome.json +39 -16
- package/dist/cli.cjs +76 -3
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +76 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +647 -126
- package/dist/index.d.ts +647 -126
- package/dist/index.js +76 -2
- package/dist/index.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/eslint.config.js +23 -2
- package/examples/auth-tokens.ts +143 -0
- package/examples/chrome-cookies-demo.sh +117 -0
- package/examples/chrome-profile-demo.sh +126 -0
- package/examples/comprehensive-demo.ts +202 -0
- package/examples/curl-demo.sh +102 -0
- package/examples/curl-integration.sh +276 -0
- package/examples/curl-with-url.sh +136 -0
- package/examples/deduplication-demo.sh +110 -0
- package/examples/final-chrome-demo.sh +115 -0
- package/examples/github-api.sh +101 -0
- package/examples/github-private-access.sh +118 -0
- package/examples/list-profiles-demo.sh +120 -0
- package/examples/proper-curl-usage.sh +120 -0
- package/examples/simple-curl.sh +95 -0
- package/examples/test-expired-filtering.sh +68 -0
- package/examples/test-github-access.sh +245 -0
- package/examples/test-github-auth-improved.sh +136 -0
- package/examples/working-curl.sh +117 -0
- package/examples/working-github-auth.sh +87 -0
- package/package.json +26 -8
- package/tsconfig.cli.json +5 -1
- package/tsup.cli.ts +31 -1
- package/tsup.lib.ts +11 -1
package/dist/cli.cjs
CHANGED
|
@@ -1,6 +1,79 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var fa=Object.create;var wr=Object.defineProperty;var pa=Object.getOwnPropertyDescriptor;var ua=Object.getOwnPropertyNames;var la=Object.getPrototypeOf,ma=Object.prototype.hasOwnProperty;var ca=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ua(e))!ma.call(r,i)&&i!==t&&wr(r,i,{get:()=>e[i],enumerable:!(o=pa(e,i))||o.enumerable});return r};var R=(r,e,t)=>(t=r!=null?fa(la(r)):{},ca(e||!r||!r.__esModule?wr(t,"default",{value:r,enumerable:!0}):t,r));function da(r){let e=r.split("."),t=[];t.push({name:"%",domain:r});for(let o=1;o<e.length-1;o++){let i=e.slice(o).join(".");t.push({name:"%",domain:i})}return t}function ar(r){if(!r.includes("://"))try{return ar(`https://${r}`)}catch{return[{name:"%",domain:r}]}try{let e=new URL(r);return da(e.hostname)}catch{return[{name:"%",domain:r}]}}var kr=R(require("minimist"),1);function vr(r){let e=(0,kr.default)(r,{string:["browser","profile","url","domain","name","output","store"],boolean:["help","version","verbose","dump","dump-grouped","render","render-grouped","force"],alias:{b:"browser",p:"profile",u:"url",d:"dump",D:"domain",n:"name",h:"help",v:"verbose",f:"force",G:"dump-grouped",r:"render",R:"render-grouped"}}),{_:t,...o}=e;return{values:o,positionals:t}}var Pr=require("consola");var Sr=require("os"),Er=require("dotenv"),fe=require("zod");(0,Er.config)();var ga=fe.z.object({LOG_LEVEL:fe.z.enum(["debug","info","warn","error"]).default("info"),HOME:fe.z.string().optional().transform(r=>r??process.env.USERPROFILE??"").pipe(fe.z.string().min(1))}),ir=ga.parse({LOG_LEVEL:process.env.LOG_LEVEL,HOME:(0,Sr.homedir)()});var ya=(0,Pr.createConsola)({fancy:!0,formatOptions:{showLogLevel:!1,colors:!0,date:!1,compact:!0,columns:typeof process.stdout.columns=="number"?process.stdout.columns:80},level:ir.LOG_LEVEL==="debug"?5:2}),mp=ir.LOG_LEVEL==="debug",ha=ya,u=ha;function Or(r,e,t){e?u.success(`${r} succeeded`,t):u.error(`${r} failed`,t)}function I(r,e,t){let o=e instanceof Error?e.message:String(e);u.error(r,{...t,error:o})}function W(r,e,t){u.warn(`[${r}] ${e}`,t)}function h(r){return u.withTag(r)}var pe=class{canHandle(e){return!0}handle(e){let t=new Set(e.map(o=>o.value));for(let o of t)u.log(o)}};var Ce=class{canHandle(e){return e.dump===!0||e.d===!0}handle(e){u.log(e)}};var xa=typeof global=="object"&&global&&global.Object===Object&&global,we=xa;var ba=typeof self=="object"&&self&&self.Object===Object&&self,Ca=we||ba||Function("return this")(),x=Ca;var wa=x.Symbol,w=wa;var Ar=Object.prototype,ka=Ar.hasOwnProperty,va=Ar.toString,ue=w?w.toStringTag:void 0;function Sa(r){var e=ka.call(r,ue),t=r[ue];try{r[ue]=void 0;var o=!0}catch{}var i=va.call(r);return o&&(e?r[ue]=t:delete r[ue]),i}var _r=Sa;var Ea=Object.prototype,Pa=Ea.toString;function Oa(r){return Pa.call(r)}var Tr=Oa;var Aa="[object Null]",_a="[object Undefined]",Rr=w?w.toStringTag:void 0;function Ta(r){return r==null?r===void 0?_a:Aa:Rr&&Rr in Object(r)?_r(r):Tr(r)}var S=Ta;function Ra(r){return r!=null&&typeof r=="object"}var E=Ra;var Ia="[object Symbol]";function Ba(r){return typeof r=="symbol"||E(r)&&S(r)==Ia}var K=Ba;function La(r,e){for(var t=-1,o=r==null?0:r.length,i=Array(o);++t<o;)i[t]=e(r[t],t,r);return i}var Ir=La;var Fa=Array.isArray,y=Fa;var Da=1/0,Br=w?w.prototype:void 0,Lr=Br?Br.toString:void 0;function Fr(r){if(typeof r=="string")return r;if(y(r))return Ir(r,Fr)+"";if(K(r))return Lr?Lr.call(r):"";var e=r+"";return e=="0"&&1/r==-Da?"-0":e}var Dr=Fr;function Na(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var V=Na;function Ma(r){return r}var Nr=Ma;var ja="[object AsyncFunction]",Ua="[object Function]",qa="[object GeneratorFunction]",Ha="[object Proxy]";function za(r){if(!V(r))return!1;var e=S(r);return e==Ua||e==qa||e==ja||e==Ha}var ke=za;var $a=x["__core-js_shared__"],ve=$a;var Mr=function(){var r=/[^.]+$/.exec(ve&&ve.keys&&ve.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function Qa(r){return!!Mr&&Mr in r}var jr=Qa;var Ga=Function.prototype,Wa=Ga.toString;function Ka(r){if(r!=null){try{return Wa.call(r)}catch{}try{return r+""}catch{}}return""}var A=Ka;var Va=/[\\^$.*+?()[\]{}|]/g,Ja=/^\[object .+?Constructor\]$/,Za=Function.prototype,Xa=Object.prototype,Ya=Za.toString,ei=Xa.hasOwnProperty,ri=RegExp("^"+Ya.call(ei).replace(Va,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ti(r){if(!V(r)||jr(r))return!1;var e=ke(r)?ri:Ja;return e.test(A(r))}var Ur=ti;function oi(r,e){return r?.[e]}var qr=oi;function ai(r,e){var t=qr(r,e);return Ur(t)?t:void 0}var C=ai;var ii=C(x,"WeakMap"),Se=ii;var si=function(){try{var r=C(Object,"defineProperty");return r({},"",{}),r}catch{}}(),sr=si;var ni=9007199254740991,fi=/^(?:0|[1-9]\d*)$/;function pi(r,e){var t=typeof r;return e=e??ni,!!e&&(t=="number"||t!="symbol"&&fi.test(r))&&r>-1&&r%1==0&&r<e}var Ee=pi;function ui(r,e,t){e=="__proto__"&&sr?sr(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0}):r[e]=t}var Hr=ui;function li(r,e){return r===e||r!==r&&e!==e}var Pe=li;var mi=9007199254740991;function ci(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=mi}var J=ci;function di(r){return r!=null&&J(r.length)&&!ke(r)}var Oe=di;var gi=Object.prototype;function yi(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||gi;return r===t}var zr=yi;function hi(r,e){for(var t=-1,o=Array(r);++t<r;)o[t]=e(t);return o}var $r=hi;var xi="[object Arguments]";function bi(r){return E(r)&&S(r)==xi}var nr=bi;var Qr=Object.prototype,Ci=Qr.hasOwnProperty,wi=Qr.propertyIsEnumerable,ki=nr(function(){return arguments}())?nr:function(r){return E(r)&&Ci.call(r,"callee")&&!wi.call(r,"callee")},Ae=ki;function vi(){return!1}var Gr=vi;var Vr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Wr=Vr&&typeof module=="object"&&module&&!module.nodeType&&module,Si=Wr&&Wr.exports===Vr,Kr=Si?x.Buffer:void 0,Ei=Kr?Kr.isBuffer:void 0,Pi=Ei||Gr,le=Pi;var Oi="[object Arguments]",Ai="[object Array]",_i="[object Boolean]",Ti="[object Date]",Ri="[object Error]",Ii="[object Function]",Bi="[object Map]",Li="[object Number]",Fi="[object Object]",Di="[object RegExp]",Ni="[object Set]",Mi="[object String]",ji="[object WeakMap]",Ui="[object ArrayBuffer]",qi="[object DataView]",Hi="[object Float32Array]",zi="[object Float64Array]",$i="[object Int8Array]",Qi="[object Int16Array]",Gi="[object Int32Array]",Wi="[object Uint8Array]",Ki="[object Uint8ClampedArray]",Vi="[object Uint16Array]",Ji="[object Uint32Array]",g={};g[Hi]=g[zi]=g[$i]=g[Qi]=g[Gi]=g[Wi]=g[Ki]=g[Vi]=g[Ji]=!0;g[Oi]=g[Ai]=g[Ui]=g[_i]=g[qi]=g[Ti]=g[Ri]=g[Ii]=g[Bi]=g[Li]=g[Fi]=g[Di]=g[Ni]=g[Mi]=g[ji]=!1;function Zi(r){return E(r)&&J(r.length)&&!!g[S(r)]}var Jr=Zi;function Xi(r){return function(e){return r(e)}}var Zr=Xi;var Xr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,me=Xr&&typeof module=="object"&&module&&!module.nodeType&&module,Yi=me&&me.exports===Xr,fr=Yi&&we.process,es=function(){try{var r=me&&me.require&&me.require("util").types;return r||fr&&fr.binding&&fr.binding("util")}catch{}}(),pr=es;var Yr=pr&&pr.isTypedArray,rs=Yr?Zr(Yr):Jr,_e=rs;var ts=Object.prototype,os=ts.hasOwnProperty;function as(r,e){var t=y(r),o=!t&&Ae(r),i=!t&&!o&&le(r),a=!t&&!o&&!i&&_e(r),s=t||o||i||a,n=s?$r(r.length,String):[],p=n.length;for(var f in r)(e||os.call(r,f))&&!(s&&(f=="length"||i&&(f=="offset"||f=="parent")||a&&(f=="buffer"||f=="byteLength"||f=="byteOffset")||Ee(f,p)))&&n.push(f);return n}var et=as;function is(r,e){return function(t){return r(e(t))}}var rt=is;var ss=rt(Object.keys,Object),tt=ss;var ns=Object.prototype,fs=ns.hasOwnProperty;function ps(r){if(!zr(r))return tt(r);var e=[];for(var t in Object(r))fs.call(r,t)&&t!="constructor"&&e.push(t);return e}var ot=ps;function us(r){return Oe(r)?et(r):ot(r)}var Z=us;var ls=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ms=/^\w*$/;function cs(r,e){if(y(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||K(r)?!0:ms.test(r)||!ls.test(r)||e!=null&&r in Object(e)}var X=cs;var ds=C(Object,"create"),_=ds;function gs(){this.__data__=_?_(null):{},this.size=0}var at=gs;function ys(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var it=ys;var hs="__lodash_hash_undefined__",xs=Object.prototype,bs=xs.hasOwnProperty;function Cs(r){var e=this.__data__;if(_){var t=e[r];return t===hs?void 0:t}return bs.call(e,r)?e[r]:void 0}var st=Cs;var ws=Object.prototype,ks=ws.hasOwnProperty;function vs(r){var e=this.__data__;return _?e[r]!==void 0:ks.call(e,r)}var nt=vs;var Ss="__lodash_hash_undefined__";function Es(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=_&&e===void 0?Ss:e,this}var ft=Es;function Y(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var o=r[e];this.set(o[0],o[1])}}Y.prototype.clear=at;Y.prototype.delete=it;Y.prototype.get=st;Y.prototype.has=nt;Y.prototype.set=ft;var ur=Y;function Ps(){this.__data__=[],this.size=0}var pt=Ps;function Os(r,e){for(var t=r.length;t--;)if(Pe(r[t][0],e))return t;return-1}var B=Os;var As=Array.prototype,_s=As.splice;function Ts(r){var e=this.__data__,t=B(e,r);if(t<0)return!1;var o=e.length-1;return t==o?e.pop():_s.call(e,t,1),--this.size,!0}var ut=Ts;function Rs(r){var e=this.__data__,t=B(e,r);return t<0?void 0:e[t][1]}var lt=Rs;function Is(r){return B(this.__data__,r)>-1}var mt=Is;function Bs(r,e){var t=this.__data__,o=B(t,r);return o<0?(++this.size,t.push([r,e])):t[o][1]=e,this}var ct=Bs;function ee(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var o=r[e];this.set(o[0],o[1])}}ee.prototype.clear=pt;ee.prototype.delete=ut;ee.prototype.get=lt;ee.prototype.has=mt;ee.prototype.set=ct;var L=ee;var Ls=C(x,"Map"),F=Ls;function Fs(){this.size=0,this.__data__={hash:new ur,map:new(F||L),string:new ur}}var dt=Fs;function Ds(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}var gt=Ds;function Ns(r,e){var t=r.__data__;return gt(e)?t[typeof e=="string"?"string":"hash"]:t.map}var D=Ns;function Ms(r){var e=D(this,r).delete(r);return this.size-=e?1:0,e}var yt=Ms;function js(r){return D(this,r).get(r)}var ht=js;function Us(r){return D(this,r).has(r)}var xt=Us;function qs(r,e){var t=D(this,r),o=t.size;return t.set(r,e),this.size+=t.size==o?0:1,this}var bt=qs;function re(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var o=r[e];this.set(o[0],o[1])}}re.prototype.clear=dt;re.prototype.delete=yt;re.prototype.get=ht;re.prototype.has=xt;re.prototype.set=bt;var Q=re;var Hs="Expected a function";function lr(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(Hs);var t=function(){var o=arguments,i=e?e.apply(this,o):o[0],a=t.cache;if(a.has(i))return a.get(i);var s=r.apply(this,o);return t.cache=a.set(i,s)||a,s};return t.cache=new(lr.Cache||Q),t}lr.Cache=Q;var Ct=lr;var zs=500;function $s(r){var e=Ct(r,function(o){return t.size===zs&&t.clear(),o}),t=e.cache;return e}var wt=$s;var Qs=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Gs=/\\(\\)?/g,Ws=wt(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(Qs,function(t,o,i,a){e.push(i?a.replace(Gs,"$1"):o||t)}),e}),kt=Ws;function Ks(r){return r==null?"":Dr(r)}var vt=Ks;function Vs(r,e){return y(r)?r:X(r,e)?[r]:kt(vt(r))}var Te=Vs;var Js=1/0;function Zs(r){if(typeof r=="string"||K(r))return r;var e=r+"";return e=="0"&&1/r==-Js?"-0":e}var N=Zs;function Xs(r,e){e=Te(e,r);for(var t=0,o=e.length;r!=null&&t<o;)r=r[N(e[t++])];return t&&t==o?r:void 0}var Re=Xs;function Ys(r,e,t){var o=r==null?void 0:Re(r,e);return o===void 0?t:o}var St=Ys;function en(r,e){for(var t=-1,o=e.length,i=r.length;++t<o;)r[i+t]=e[t];return r}var Et=en;function rn(){this.__data__=new L,this.size=0}var Pt=rn;function tn(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}var Ot=tn;function on(r){return this.__data__.get(r)}var At=on;function an(r){return this.__data__.has(r)}var _t=an;var sn=200;function nn(r,e){var t=this.__data__;if(t instanceof L){var o=t.__data__;if(!F||o.length<sn-1)return o.push([r,e]),this.size=++t.size,this;t=this.__data__=new Q(o)}return t.set(r,e),this.size=t.size,this}var Tt=nn;function te(r){var e=this.__data__=new L(r);this.size=e.size}te.prototype.clear=Pt;te.prototype.delete=Ot;te.prototype.get=At;te.prototype.has=_t;te.prototype.set=Tt;var oe=te;function fn(r,e){for(var t=-1,o=r==null?0:r.length,i=0,a=[];++t<o;){var s=r[t];e(s,t,r)&&(a[i++]=s)}return a}var Rt=fn;function pn(){return[]}var It=pn;var un=Object.prototype,ln=un.propertyIsEnumerable,Bt=Object.getOwnPropertySymbols,mn=Bt?function(r){return r==null?[]:(r=Object(r),Rt(Bt(r),function(e){return ln.call(r,e)}))}:It,Lt=mn;function cn(r,e,t){var o=e(r);return y(r)?o:Et(o,t(r))}var Ft=cn;function dn(r){return Ft(r,Z,Lt)}var mr=dn;var gn=C(x,"DataView"),Ie=gn;var yn=C(x,"Promise"),Be=yn;var hn=C(x,"Set"),Le=hn;var Dt="[object Map]",xn="[object Object]",Nt="[object Promise]",Mt="[object Set]",jt="[object WeakMap]",Ut="[object DataView]",bn=A(Ie),Cn=A(F),wn=A(Be),kn=A(Le),vn=A(Se),G=S;(Ie&&G(new Ie(new ArrayBuffer(1)))!=Ut||F&&G(new F)!=Dt||Be&&G(Be.resolve())!=Nt||Le&&G(new Le)!=Mt||Se&&G(new Se)!=jt)&&(G=function(r){var e=S(r),t=e==xn?r.constructor:void 0,o=t?A(t):"";if(o)switch(o){case bn:return Ut;case Cn:return Dt;case wn:return Nt;case kn:return Mt;case vn:return jt}return e});var cr=G;var Sn=x.Uint8Array,dr=Sn;var En="__lodash_hash_undefined__";function Pn(r){return this.__data__.set(r,En),this}var qt=Pn;function On(r){return this.__data__.has(r)}var Ht=On;function Fe(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new Q;++e<t;)this.add(r[e])}Fe.prototype.add=Fe.prototype.push=qt;Fe.prototype.has=Ht;var zt=Fe;function An(r,e){for(var t=-1,o=r==null?0:r.length;++t<o;)if(e(r[t],t,r))return!0;return!1}var $t=An;function _n(r,e){return r.has(e)}var Qt=_n;var Tn=1,Rn=2;function In(r,e,t,o,i,a){var s=t&Tn,n=r.length,p=e.length;if(n!=p&&!(s&&p>n))return!1;var f=a.get(r),l=a.get(e);if(f&&l)return f==e&&l==r;var c=-1,d=!0,k=t&Rn?new zt:void 0;for(a.set(r,e),a.set(e,r);++c<n;){var b=r[c],v=e[c];if(o)var T=s?o(v,b,c,e,r,a):o(b,v,c,r,e,a);if(T!==void 0){if(T)continue;d=!1;break}if(k){if(!$t(e,function(z,$){if(!Qt(k,$)&&(b===z||i(b,z,t,o,a)))return k.push($)})){d=!1;break}}else if(!(b===v||i(b,v,t,o,a))){d=!1;break}}return a.delete(r),a.delete(e),d}var De=In;function Bn(r){var e=-1,t=Array(r.size);return r.forEach(function(o,i){t[++e]=[i,o]}),t}var Gt=Bn;function Ln(r){var e=-1,t=Array(r.size);return r.forEach(function(o){t[++e]=o}),t}var Wt=Ln;var Fn=1,Dn=2,Nn="[object Boolean]",Mn="[object Date]",jn="[object Error]",Un="[object Map]",qn="[object Number]",Hn="[object RegExp]",zn="[object Set]",$n="[object String]",Qn="[object Symbol]",Gn="[object ArrayBuffer]",Wn="[object DataView]",Kt=w?w.prototype:void 0,gr=Kt?Kt.valueOf:void 0;function Kn(r,e,t,o,i,a,s){switch(t){case Wn:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case Gn:return!(r.byteLength!=e.byteLength||!a(new dr(r),new dr(e)));case Nn:case Mn:case qn:return Pe(+r,+e);case jn:return r.name==e.name&&r.message==e.message;case Hn:case $n:return r==e+"";case Un:var n=Gt;case zn:var p=o&Fn;if(n||(n=Wt),r.size!=e.size&&!p)return!1;var f=s.get(r);if(f)return f==e;o|=Dn,s.set(r,e);var l=De(n(r),n(e),o,i,a,s);return s.delete(r),l;case Qn:if(gr)return gr.call(r)==gr.call(e)}return!1}var Vt=Kn;var Vn=1,Jn=Object.prototype,Zn=Jn.hasOwnProperty;function Xn(r,e,t,o,i,a){var s=t&Vn,n=mr(r),p=n.length,f=mr(e),l=f.length;if(p!=l&&!s)return!1;for(var c=p;c--;){var d=n[c];if(!(s?d in e:Zn.call(e,d)))return!1}var k=a.get(r),b=a.get(e);if(k&&b)return k==e&&b==r;var v=!0;a.set(r,e),a.set(e,r);for(var T=s;++c<p;){d=n[c];var z=r[d],$=e[d];if(o)var Cr=s?o($,z,d,e,r,a):o(z,$,d,r,e,a);if(!(Cr===void 0?z===$||i(z,$,t,o,a):Cr)){v=!1;break}T||(T=d=="constructor")}if(v&&!T){var xe=r.constructor,be=e.constructor;xe!=be&&"constructor"in r&&"constructor"in e&&!(typeof xe=="function"&&xe instanceof xe&&typeof be=="function"&&be instanceof be)&&(v=!1)}return a.delete(r),a.delete(e),v}var Jt=Xn;var Yn=1,Zt="[object Arguments]",Xt="[object Array]",Ne="[object Object]",ef=Object.prototype,Yt=ef.hasOwnProperty;function rf(r,e,t,o,i,a){var s=y(r),n=y(e),p=s?Xt:cr(r),f=n?Xt:cr(e);p=p==Zt?Ne:p,f=f==Zt?Ne:f;var l=p==Ne,c=f==Ne,d=p==f;if(d&&le(r)){if(!le(e))return!1;s=!0,l=!1}if(d&&!l)return a||(a=new oe),s||_e(r)?De(r,e,t,o,i,a):Vt(r,e,p,t,o,i,a);if(!(t&Yn)){var k=l&&Yt.call(r,"__wrapped__"),b=c&&Yt.call(e,"__wrapped__");if(k||b){var v=k?r.value():r,T=b?e.value():e;return a||(a=new oe),i(v,T,t,o,a)}}return d?(a||(a=new oe),Jt(r,e,t,o,i,a)):!1}var eo=rf;function ro(r,e,t,o,i){return r===e?!0:r==null||e==null||!E(r)&&!E(e)?r!==r&&e!==e:eo(r,e,t,o,ro,i)}var Me=ro;var tf=1,of=2;function af(r,e,t,o){var i=t.length,a=i,s=!o;if(r==null)return!a;for(r=Object(r);i--;){var n=t[i];if(s&&n[2]?n[1]!==r[n[0]]:!(n[0]in r))return!1}for(;++i<a;){n=t[i];var p=n[0],f=r[p],l=n[1];if(s&&n[2]){if(f===void 0&&!(p in r))return!1}else{var c=new oe;if(o)var d=o(f,l,p,r,e,c);if(!(d===void 0?Me(l,f,tf|of,o,c):d))return!1}}return!0}var to=af;function sf(r){return r===r&&!V(r)}var je=sf;function nf(r){for(var e=Z(r),t=e.length;t--;){var o=e[t],i=r[o];e[t]=[o,i,je(i)]}return e}var oo=nf;function ff(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}var Ue=ff;function pf(r){var e=oo(r);return e.length==1&&e[0][2]?Ue(e[0][0],e[0][1]):function(t){return t===r||to(t,r,e)}}var ao=pf;function uf(r,e){return r!=null&&e in Object(r)}var io=uf;function lf(r,e,t){e=Te(e,r);for(var o=-1,i=e.length,a=!1;++o<i;){var s=N(e[o]);if(!(a=r!=null&&t(r,s)))break;r=r[s]}return a||++o!=i?a:(i=r==null?0:r.length,!!i&&J(i)&&Ee(s,i)&&(y(r)||Ae(r)))}var so=lf;function mf(r,e){return r!=null&&so(r,e,io)}var no=mf;var cf=1,df=2;function gf(r,e){return X(r)&&je(e)?Ue(N(r),e):function(t){var o=St(t,r);return o===void 0&&o===e?no(t,r):Me(e,o,cf|df)}}var fo=gf;function yf(r){return function(e){return e?.[r]}}var po=yf;function hf(r){return function(e){return Re(e,r)}}var uo=hf;function xf(r){return X(r)?po(N(r)):uo(r)}var lo=xf;function bf(r){return typeof r=="function"?r:r==null?Nr:typeof r=="object"?y(r)?fo(r[0],r[1]):ao(r):lo(r)}var mo=bf;function Cf(r,e,t,o){for(var i=-1,a=r==null?0:r.length;++i<a;){var s=r[i];e(o,s,t(s),r)}return o}var co=Cf;function wf(r){return function(e,t,o){for(var i=-1,a=Object(e),s=o(e),n=s.length;n--;){var p=s[r?n:++i];if(t(a[p],p,a)===!1)break}return e}}var go=wf;var kf=go(),yo=kf;function vf(r,e){return r&&yo(r,e,Z)}var ho=vf;function Sf(r,e){return function(t,o){if(t==null)return t;if(!Oe(t))return r(t,o);for(var i=t.length,a=e?i:-1,s=Object(t);(e?a--:++a<i)&&o(s[a],a,s)!==!1;);return t}}var xo=Sf;var Ef=xo(ho),bo=Ef;function Pf(r,e,t,o){return bo(r,function(i,a,s){e(o,i,t(i),s)}),o}var Co=Pf;function Of(r,e){return function(t,o){var i=y(t)?co:Co,a=e?e():{};return i(t,r,mo(o,2),a)}}var wo=Of;var Af=Object.prototype,_f=Af.hasOwnProperty,Tf=wo(function(r,e,t){_f.call(r,t)?r[t].push(e):Hr(r,t,[e])}),ce=Tf;var qe=class{canHandle(e){return e["dump-grouped"]===!0||e.D===!0}handle(e){let t=ce(e,o=>o.meta?.file??"unknown");u.log(JSON.stringify(t,null,2))}};function He(r,e={}){let{format:t="merged",showFilePaths:o=!0,separator:i="; "}=e;if(r.length===0)return t==="merged"?"":[];if(t==="merged")return r.map(s=>s.value).join(i);let a=ce(r,s=>s.meta?.file??"unknown");return Object.entries(a).map(([s,n])=>{let p=n.map(f=>f.value).join(i);return o?`${s}: ${p}`:p})}var ze=class{canHandle(e){return e["render-grouped"]===!0||e.R===!0}handle(e){u.log(He(e,{format:"grouped"}))}};var $e=class{canHandle(e){return e.output==="json"}handle(e){u.log(JSON.stringify(e,null,2))}};var Qe=class{canHandle(e){return e.render===!0||e["render-merged"]===!0||e.r===!0}handle(e){u.log(He(e,{format:"merged"}))}};var Ge=class{constructor(){this.validOutputFormats=["json"];this.handlers=[new Ce,new qe,new Qe,new ze,new $e,new pe]}validateOutputFormat(e){if(e.output!==void 0&&!this.validOutputFormats.includes(e.output)){let t=this.validOutputFormats.join(", ");throw new Error(`Invalid output format: '${e.output}'. Valid formats are: ${t}`)}}getHandler(e){return this.validateOutputFormat(e),this.handlers.find(t=>t.canHandle(e))??new pe}};var We=class{constructor(e){this.strategy=e}async queryCookies(e,t){return await this.strategy.queryCookies(e.name,e.domain,t?.store,t?.force)}};async function ko(r,e,t=[]){return r.length===0?t:(await Promise.all(r.map(async i=>{try{return await e(i)}catch{return t}}))).flat()}var de=class{constructor(e){this.strategies=e;this.logger=h("CompositeCookieQueryStrategy");this.browserName="internal"}handleStrategyError(e,t){e instanceof Error?this.logger.error("Strategy failed",{error:e,strategy:t}):this.logger.error("Strategy failed with unknown error",{error:String(e),strategy:t})}async queryCookies(e,t,o,i){try{return this.logger.info("Querying cookies from all strategies",{name:e,domain:t,store:o,force:i,strategyCount:this.strategies.length}),await ko(this.strategies,async a=>{try{return await a.queryCookies(e,t,o,i)}catch(s){return this.handleStrategyError(s,a),[]}},[])}catch(a){return a instanceof Error?this.logger.error("Failed to query cookies",{error:a}):this.logger.error("Failed to query cookies with unknown error",{error:String(a)}),[]}}};var Rf={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},success:()=>{},fatal:()=>{},log:()=>{}},M=class{constructor(e,t){this.browserName=t;let o=h(e);this.logger=o||Rf}async queryCookies(e,t,o,i){try{return this.logger.info("Querying cookies",{name:e,domain:t,store:o,force:i}),await this.executeQuery(e,t,o,i)}catch(a){return a instanceof Error?this.logger.error("Failed to query cookies",{error:a.message,browser:this.browserName,strategy:this.constructor.name,name:e,domain:t,store:o,force:i}):this.logger.error("Failed to query cookies",{error:String(a),browser:this.browserName,strategy:this.constructor.name,name:e,domain:t,store:o,force:i}),[]}}};var So=require("fs"),Ze=require("path"),Eo=R(require("fast-glob"),1);var vo=R(require("better-sqlite3"),1);var Ke=h("QuerySqliteThenTransform");function If(r){return new Promise(e=>setTimeout(e,r))}function Bf(r){if(r instanceof Error){let e=r.message.toLowerCase();return e.includes("database is locked")||e.includes("database locked")||e.includes("sqlite_busy")}return!1}function Lf(r){try{let e=new vo.default(r,{readonly:!0,fileMustExist:!0});try{e.pragma("journal_mode = WAL"),Ke.debug("Set WAL mode for database",{file:r})}catch(t){Ke.warn("Failed to set WAL mode, continuing with default",{file:r,error:t instanceof Error?t.message:String(t)})}return e}catch(e){throw I("Database open failed",e,{file:r}),e}}function Ff(r){try{return r.close(),Promise.resolve()}catch(e){return I("Database close failed",e),Promise.reject(e instanceof Error?e:new Error("Failed to close database: Unknown error"))}}async function Df(r){let{file:e,sql:t,params:o,rowFilter:i,rowTransform:a}=r,s;try{s=Lf(e);let p=s.prepare(t).all(o),f=i?p.filter(i):p;return a?f.map(a):f}finally{s&&await Ff(s)}}async function Ve(r){let{file:e,sql:t,retryAttempts:o=3}=r,i=[100,500,1e3],a;for(let s=0;s<o;s++)try{let n=await Df(r);return s>0&&Ke.info("Database query succeeded after retry",{file:e,attempt:s+1,totalAttempts:o}),n}catch(n){if(a=n,Bf(n)&&s<o-1){let p=i[s]||1e3;Ke.warn("Database locked, retrying after delay",{file:e,attempt:s+1,totalAttempts:o,delay:p,error:n instanceof Error?n.message:String(n)}),await If(p);continue}throw I("Database query failed",n,{file:e,sql:t,attempt:s+1}),n}throw a}var ge=require("os"),Je=require("path"),j=(()=>{let r=(0,ge.homedir)();if(!r)throw new Error("Unable to determine user home directory");switch((0,ge.platform)()){case"darwin":return(0,Je.join)(r,"Library","Application Support","Google","Chrome");case"win32":return(0,Je.join)(r,"AppData","Local","Google","Chrome","User Data");case"linux":return(0,Je.join)(r,".config","google-chrome");default:throw new Error(`Platform ${(0,ge.platform)()} is not supported`)}})();var ye=h("getEncryptedChromeCookie");function Nf(r){if(typeof r!="string")return!1;let e=r.trim();return e.length===0?!1:(0,So.existsSync)(e)}async function Mf(){let r=[(0,Ze.join)(j,"Default/Cookies"),(0,Ze.join)(j,"Profile */Cookies"),(0,Ze.join)(j,"Profile Default/Cookies")],e=[];for(let t of r){let o=await(0,Eo.default)(t);e.push(...o)}return ye.debug("ChromeCookies","Found cookie files",{count:e.length,files:e}),e}function jf(r,e){let t=r==="%",o=t?"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 ?",i=t?[`%${e}%`]:[r,`%${e}%`];return{sql:o,params:i}}async function Uf(r,e,t){try{let{sql:o,params:i}=jf(e,t);ye.debug("ChromeCookies","Executing query",{sql:o,params:i});let a=await Ve({file:r,sql:o,params:i,rowTransform:s=>({name:s.name,domain:s.host_key,value:s.encrypted_value,expiry:s.expires_utc})});return Or("QueryCookies",!0,{file:r,count:a.length}),a}catch(o){return I("Failed to read cookie file",o,{file:r}),[]}}async function Po({name:r,domain:e,file:t}){let o=typeof t=="string"&&t.length>0?[t]:await Mf();if(o.length===0)return ye.debug("ChromeCookies","No cookie files found"),[];let i=[];for(let a of o){if(!Nf(a)){ye.debug("ChromeCookies","Cookie file missing or invalid",{file:a});continue}let s=await Uf(a,r,e);i.push(...s)}return ye.debug("ChromeCookies","Query complete",{totalCookies:i.length}),i}var qf=require("fs"),Hf=require("path"),Oo=R(require("fast-glob"),1);var zf=h("listChromeProfiles");function Ao(){let r=Oo.default.sync("./**/Cookies",{cwd:j,absolute:!0});return zf.debug("Found cookie files:",r),r}var Xe=require("crypto"),yr=require("os");var _o=require("crypto");function To(r,e){let t=Buffer.from("v10");if(!r.subarray(0,3).equals(t))throw new Error("Not a v10 encrypted cookie");let o=r.subarray(3),i=12,a=16;if(o.length<i+a)throw new Error("Invalid v10 cookie: too short");let s=o.subarray(0,i),n=o.subarray(i,o.length-a),p=o.subarray(o.length-a),f=(0,_o.createDecipheriv)("aes-256-gcm",e,s);return f.setAuthTag(p),Buffer.concat([f.update(n),f.final()]).toString("utf8")}function Ro(r){let e=Buffer.from("v10");return r.length>=3&&r.subarray(0,3).equals(e)}function Io(r,e){let t=new Map;return o=>{let i=e?e(o):o.toString("hex");if(t.has(i)){let s=t.get(i);if(s!==void 0)return s}let a=r(o);return t.set(i,a),a}}var $f=Io(r=>r.length>=3&&r[0]===118&&r[1]===49&&r[2]===48?r.slice(3):r,r=>r.toString("hex")),Qf=Io(r=>{let e=r[r.length-1];return e&&e<=16?r.slice(0,-e):r},r=>r.toString("hex"));function Gf(r){let e=r.match(/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/i);if(e)return e[1];let t=[/([A-Z]{3})$/,/([a-z]{2}_[A-Z]{2})$/,/(\d{3}-\d{7}-\d{7})$/];for(let i of t){let a=r.match(i);if(a)return a[1]}let o=[/.*?0t(.+)$/,/.*?1e`(.+)$/,/.*?[`'](.+)$/,/[^\x20-\x7E]*([\x20-\x7E]+)$/,/.*?([a-zA-Z0-9_\-\.]+)$/];for(let i of o){let s=r.match(i)?.[1]??"";if(s.length>0)return s}return r}async function Bo(r,e,t){if((0,yr.platform)()==="win32"&&Ro(r)&&r.length>=31&&Buffer.isBuffer(e))return To(r,e);if((0,yr.platform)()==="darwin"&&!r.slice(0,3).toString().match(/^v\d\d$/))return Promise.resolve(r.toString("utf8"));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,i)=>{(0,Xe.pbkdf2)(e,"saltysalt",1003,16,"sha1",(a,s)=>{try{if(a){i(new Error(`Failed to derive key: ${a.message}`));return}let n=$f(r);if(n.length%16!==0){i(new Error("Encrypted data length is not a multiple of 16"));return}let p=Buffer.alloc(16," "),f=(0,Xe.createDecipheriv)("aes-128-cbc",s,p);f.setAutoPadding(!1);let l=f.update(n);try{f.final()}catch(b){i(new Error(`Failed to finalize decryption: ${b.message}`));return}l=Qf(l);let k=((t||0)>=24&&l.length>32?l.slice(32):l).toString("utf8");o(Gf(k))}catch(n){i(new Error(`Decryption failed: ${n.message}`))}})})}var xr=require("os");var Lo=require("child_process"),Fo=require("util");var Wf=(0,Fo.promisify)(Lo.exec),hr=class extends Error{constructor(t,o,i){super(t);this.command=o;this.originalError=i;this.name="CommandExecutionError"}};async function U(r,e){try{let t=await Wf(r,{...e,encoding:"utf8"});return{stdout:t.stdout.toString(),stderr:t.stderr.toString()}}catch(t){throw I("Command execution failed",t,{command:r}),new hr(t instanceof Error?t.message:String(t),r,t instanceof Error?t:void 0)}}async function Do(){try{let t=(await U("secret-tool lookup application chrome-libsecret-password-v2 || secret-tool lookup application chrome")).stdout.trim();if(t)return t}catch{}try{let t=(await U(`python3 -c "import keyring; print(keyring.get_password('Chrome Safe Storage', 'Chrome'))"`)).stdout.trim();if(t&&t!=="None")return t}catch{}try{let t=(await U('kwallet-query kdewallet -f "Chrome Safe Storage" -r Chrome')).stdout.trim();if(t)return t}catch{}return"peanuts"}async function No(){return(await U('security find-generic-password -w -s "Chrome Safe Storage"')).stdout.trim()}var Mo=require("fs"),jo=require("path");async function Kf(r){let e=Buffer.from("DPAPI");if(!r.subarray(0,5).equals(e))throw new Error("Invalid DPAPI key prefix");let t=r.subarray(5);if(process.platform==="win32")try{let o=await import("@primno/dpapi").then(i=>i).catch(()=>null);if(o)return o.unprotectData(t)}catch(o){console.warn("DPAPI module not available, using fallback:",o)}throw new Error("Windows DPAPI decryption requires native bindings. Install @primno/dpapi package for Windows support.")}async function Uo(){try{let r=(0,jo.join)(j,"Local State"),e=(0,Mo.readFileSync)(r,"utf8"),t=JSON.parse(e);if(!t.os_crypt?.encrypted_key)throw new Error("No encrypted key found in Chrome Local State");let o=Buffer.from(t.os_crypt.encrypted_key,"base64");return(await Kf(o)).toString("latin1")}catch(r){throw new Error(`Failed to retrieve Chrome password on Windows: ${r instanceof Error?r.message:String(r)}`)}}async function qo(){switch((0,xr.platform)()){case"darwin":return await No();case"win32":return await Uo();case"linux":return await Do();default:throw new Error(`Platform ${(0,xr.platform)()} is not supported`)}}function Vf(r){return typeof r!="number"||r<=0?"Infinity":new Date(r)}function Ho(r,e,t,o,i,a){return{domain:r,name:e,value:t,expiry:Vf(o),meta:{file:i,browser:"Chrome",decrypted:a}}}var ae=class extends M{constructor(){super("ChromeCookieQueryStrategy","Chrome")}async executeQuery(e,t,o,i){let a=["darwin","win32","linux"];if(!a.includes(process.platform))return this.logger.warn("Platform not supported",{platform:process.platform,supportedPlatforms:a}),[];let s=o??Ao(),n=Array.isArray(s)?s:[s];if(n.length===0)return this.logger.warn("No Chrome cookie files found"),[];let p=await qo();return(await Promise.all(n.map(l=>this.processFile(l,e,t,p)))).flat()}async processFile(e,t,o,i){try{let a=await Po({name:t,domain:o,file:e}),s=0;try{let f=await import("better-sqlite3"),l=new f.default(e,{readonly:!0});try{let c=l.prepare("SELECT value FROM meta WHERE key = ?").get("version");s=c?Number.parseInt(c.value,10):0}finally{l.close()}}catch(f){this.logger.debug("Could not retrieve meta version, defaulting to 0",{error:f})}let n={file:e,password:i,metaVersion:s};return(await Promise.allSettled(a.map(f=>this.processCookie(f,n)))).map(f=>f.status==="fulfilled"?f.value:null).filter(f=>f!==null)}catch(a){return a instanceof Error?this.logger.error("Failed to process cookie file",{error:a.message,file:e,name:t,domain:o}):this.logger.error("Failed to process cookie file",{error:String(a),file:e,name:t,domain:o}),[]}}async processCookie(e,t){try{let o=Buffer.isBuffer(e.value)?e.value:Buffer.from(String(e.value)),i=await Bo(o,t.password,t.metaVersion);return Ho(e.domain,e.name,i,e.expiry,t.file,!0)}catch(o){return o instanceof Error?this.logger.warn("Failed to decrypt cookie",{error:o}):this.logger.warn("Failed to decrypt cookie",{error:String(o)}),Ho(e.domain,e.name,e.value.toString("utf-8"),e.expiry,t.file,!1)}}};var Go=require("os"),br=require("path"),Wo=R(require("fast-glob"),1);var zo=h("ProcessDetector");function Jf(r,e){let t=r.trim().split(/\s+/);if(t.length<2)return null;let o=Number.parseInt(t[1],10);return Number.isNaN(o)?null:{pid:o,command:t.slice(10).join(" ")||e,details:r.trim()}}async function $o(){try{let r="ps aux | grep -i firefox | grep -v grep",{stdout:e}=await U(r);if(!e||e.trim()==="")return[];let t=[],o=e.split(`
|
|
3
|
-
`).filter(i=>i.trim()!=="");for(let i of o){let a=Jf(i,"firefox");a&&t.push(a)}return zo.debug("Firefox process detection completed",{processCount:t.length,processes:t.map(i=>({pid:i.pid,command:i.command}))}),t}catch(r){return zo.warn("Failed to detect Firefox processes",{error:r instanceof Error?r.message:String(r)}),[]}}function Qo(r,e){if(e.length===0)return"";let t=e.length,o=r.charAt(0).toUpperCase()+r.slice(1);return`${o} is currently running (${t} process${t>1?"es":""} detected). For reliable cookie access, consider closing ${o} and trying again. Alternatively, use the --force flag to attempt access despite the lock.`}function Zf(r){let e=(0,Go.homedir)();if(!e)return r.warn("Failed to get home directory"),[];let t=[(0,br.join)(e,"Library/Application Support/Firefox/Profiles/*/cookies.sqlite"),(0,br.join)(e,".mozilla/firefox/*/cookies.sqlite")],o=[];for(let i of t){let a=Wo.default.sync(i);o.push(...a)}return r.debug("Found Firefox cookie files",{files:o}),o}var ie=class extends M{constructor(){super("FirefoxCookieQueryStrategy","Firefox")}async handleDatabaseLockError(e,t){if(e instanceof Error&&e.message.toLowerCase().includes("database is locked"))try{let o=await $o();if(o.length>0){let i=Qo("firefox",o);this.logger.warn("Firefox process conflict detected",{file:t,processCount:o.length,advice:i})}else this.logger.warn("Database locked but no Firefox processes detected",{file:t,suggestion:"Another process may be accessing the database"})}catch(o){this.logger.debug("Failed to check Firefox processes",{error:o instanceof Error?o.message:String(o)})}}async executeQuery(e,t,o,i){let a=o??Zf(this.logger),s=Array.isArray(a)?a:[a],n=[];for(let p of s)try{let f=await Ve({file:p,sql:"SELECT name, value, host as domain, expiry FROM moz_cookies WHERE name = ? AND host LIKE ?",params:[e,`%${t}%`],rowTransform:l=>({name:l.name,value:l.value,domain:l.domain,expiry:l.expiry>0?new Date(l.expiry*1e3):"Infinity",meta:{file:p,browser:"Firefox",decrypted:!1}})});n.push(...f)}catch(f){await this.handleDatabaseLockError(f,p),f instanceof Error?this.logger.warn(`Error reading Firefox cookie file ${p}`,{error:f.message,file:p,name:e,domain:t}):this.logger.warn(`Error reading Firefox cookie file ${p}`,{error:String(f),file:p,name:e,domain:t})}return n}};var oa=require("os"),aa=require("path");var Xo=require("buffer"),Yo=require("fs"),ea=require("os"),ra=require("path");var he=require("buffer");var Ko=R(require("destr"),1),m=require("zod"),Ye=m.z.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"),er=m.z.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"),Vo=m.z.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("/"),Jo=m.z.string().trim().transform(r=>(0,Ko.default)(r)).pipe(m.z.any()),Zo=m.z.object({name:er,value:Jo,domain:Ye,path:Vo,expiry:m.z.number().int(),creation:m.z.number().int(),flags:m.z.number().optional(),version:m.z.number().int().optional(),port:m.z.number().int().optional(),comment:m.z.string().optional(),commentURL:m.z.string().optional()}),Ny=m.z.object({name:er,domain:Ye}).strict(),Xf=m.z.object({file:m.z.string().trim().min(1,"File path cannot be empty").optional(),browser:m.z.string().trim().optional(),decrypted:m.z.boolean().optional(),secure:m.z.boolean().optional(),httpOnly:m.z.boolean().optional(),path:Vo.optional()}).catchall(m.z.unknown()).strict(),Yf=m.z.object({domain:Ye,name:er,value:Jo,expiry:m.z.union([m.z.literal("Infinity"),m.z.date(),m.z.number().int().positive("Expiry must be a positive number")]).optional(),meta:Xf.optional()}).strict(),My=m.z.object({expiry:m.z.number().int().optional(),domain:Ye,name:er,value:m.z.union([m.z.string(),m.z.instanceof(Buffer)])}).strict(),jy=m.z.object({format:m.z.enum(["merged","grouped"]).optional(),separator:m.z.string().optional(),showFilePaths:m.z.boolean().optional()}).strict(),ep=m.z.enum(["Chrome","Firefox","Safari","internal","unknown"]),Uy=m.z.object({browserName:ep,queryCookies:m.z.function().args(m.z.string(),m.z.string(),m.z.string().optional(),m.z.boolean().optional()).returns(m.z.promise(m.z.array(Yf)))}).strict();var q=h("BinaryCodableCookie"),rr=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 t={offset:0,buffer:e};this.decode(t)}decodeUrlValue(e){let t=e,o;do{o=t;try{t=decodeURIComponent(t)}catch{return o}}while(t!==o&&t.includes("%"));return t}decodeJwtPayload(e){let t=e.split(".");if(t.length!==3)return null;try{let o=he.Buffer.from(t[1],"base64").toString("utf8"),i=JSON.parse(o);return JSON.stringify(i)}catch{return null}}parseJsonValue(e){try{let t=JSON.parse(e);return JSON.stringify(t)}catch{return null}}processValue(e){if(e===null)return"null";if(e===void 0)return"undefined";if(he.Buffer.isBuffer(e))return e.toString();if(typeof e!="string")return String(e);let t=this.decodeUrlValue(e);if(t.match(/^ey[A-Za-z0-9_-]+\.ey[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/)){let o=this.decodeJwtPayload(t);if(typeof o=="string"&&o.length>0)return o}if(t.startsWith("{")||t.startsWith("[")){let o=this.parseJsonValue(t);if(typeof o=="string"&&o.length>0)return o}return t}convertMacTimestamp(e){return e<=0?e:e>=0&&e<=1e9&&Number.isFinite(e)?e+978307200:0}toCookieRow(){try{let e=this.convertFlags(),t=this.url.replace(/^https?:\/\//,"").replace(/\/.*$/,"")||"uk",o=this.convertMacTimestamp(this.expiration),i=this.convertMacTimestamp(this.creation);return Zo.parse({name:this.name.replace(/^: /,""),value:this.processValue(this.value)||"",domain:t,path:this.path||"/",expiry:o,creation:i,flags:e,version:this.version,port:this.port,comment:this.comment,commentURL:this.commentURL})}catch{return null}}readNullTerminatedString(e,t){let o=t;for(;o<e.buffer.length&&e.buffer[o]!==0;)o++;return e.buffer.toString("utf8",t,o)||""}readHeader(e){let t=e.buffer.readUInt32LE(e.offset);q.debug("Cookie size:",t),e.offset+=4;let o=e.buffer.readUInt32LE(e.offset);q.debug("Cookie version:",o),e.offset+=4;let i=e.buffer.readUInt32LE(e.offset);q.debug("Cookie flags:",i.toString(2).padStart(8,"0")),e.offset+=4,this.flags={isSecure:(i&1)!==0,isHTTPOnly:(i&4)!==0,unknown1:(i&8)!==0,unknown2:(i&16)!==0};let a=e.buffer.readUInt32LE(e.offset);q.debug("Has port:",a),e.offset+=4;let s={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 q.debug("String offsets:",s),{size:t,hasPort:a,offsets:s}}readTimestamps(e){let t=he.Buffer.alloc(8);for(let s=0;s<8;s++)t[s]=e.buffer[e.offset+s];let o=t.readDoubleLE(0);e.offset+=8;let i=he.Buffer.alloc(8);for(let s=0;s<8;s++)i[s]=e.buffer[e.offset+s];let a=i.readDoubleLE(0);e.offset+=8,this.expiration=o,this.creation=a}readStrings(e,t,o){q.debug("Reading strings from cookie buffer of size:",t);let a=[{field:"url",offset:o.urlOffset},{field:"name",offset:o.nameOffset},{field:"path",offset:o.pathOffset},{field:"value",offset:o.valueOffset},{field:"comment",offset:o.commentOffset}].filter(s=>s.offset>0).sort((s,n)=>s.offset-n.offset);q.debug("Reading strings in order:",a.map(s=>s.field));for(let s=0;s<a.length;s++){let{field:n,offset:p}=a[s],l=(s<a.length-1?a[s+1].offset:t)-p,c=0+p;for(;c<0+p+l&&e.buffer[c]!==0;)c++;let d=e.buffer.toString("utf8",0+p,c);switch(q.debug(`Read ${n}:`,d),n){case"url":this.url=d;break;case"name":this.name=d;break;case"path":this.path=d;break;case"value":this.value=d;break;case"comment":this.comment=d;break}}}decode(e){let{size:t,hasPort:o,offsets:i}=this.readHeader(e),a=e.offset;e.offset=a+24,this.readTimestamps(e),o>0&&(this.port=e.buffer.readUInt16LE(e.offset),e.offset+=2),e.offset=a,this.readStrings(e,t,i)}convertFlags(){return(this.flags.isSecure?1:0)|(this.flags.isHTTPOnly?4:0)|(this.flags.unknown1?8:0)|(this.flags.unknown2?16:0)}};var P=h("BinaryCodablePage"),se=class se{constructor(e){this.cookies=[];let t={offset:0,buffer:e};this.decode(t)}toCookieRows(){let e=[];for(let t of this.cookies)try{let o=t.toCookieRow();o!==null&&e.push(o)}catch(o){let i=o instanceof Error?o.message:String(o);W("BinaryCookies","Error converting cookie",{error:i})}return e}decode(e){let t=e.buffer.readUInt32BE(e.offset);if(P.debug("Page header:",t.toString(16)),e.offset+=4,t!==se.HEADER)throw new Error("Invalid page header");let o=e.buffer.readUInt32LE(e.offset);P.debug("Cookie count:",o),e.offset+=4;let i=e.offset-8;P.debug("Page start offset:",i);let a=[];for(let n=0;n<o;n++){let p=e.buffer.readUInt32LE(e.offset);a.push(p),P.debug(`Cookie ${n} offset:`,p),e.offset+=4}let s=e.buffer.readUInt32BE(e.offset);if(P.debug("Page footer:",s.toString(16)),e.offset+=4,s!==se.FOOTER)throw new Error("Invalid page footer");for(let n=0;n<o;n++)try{let p=a[n];P.debug(`Reading cookie ${n} at offset:`,p);let f=e.buffer.readUInt32LE(p);if(P.debug(`Cookie ${n} size:`,f),f<48){P.warn(`Invalid cookie size ${f} at index ${n}`);continue}if(p+f>e.buffer.length){P.warn(`Cookie size ${f} at index ${n} would exceed buffer length ${e.buffer.length}`);continue}let l=e.buffer.subarray(p,p+f),c=new rr(l);this.cookies.push(c)}catch(p){P.warn("Invalid cookie data",{error:p instanceof Error?p.message:String(p)})}}};se.HEADER=256,se.FOOTER=0;var tr=se;var H=h("BinaryCodableCookies"),O=class O{constructor(e){let t={offset:0,buffer:e};this.pages=[],this.metadata={},this.decode(t)}static fromFile(e){let t=(0,Yo.readFileSync)(e);return new O(t)}static fromDefaultPath(){return O.fromFile(O.DEFAULT_COOKIE_PATH)}toCookieRows(){let e=[];for(let t of this.pages)try{let o=t.toCookieRows();Array.isArray(o)&&e.push(...o)}catch(o){let i=o instanceof Error?o.message:String(o);W("BinaryCookies","Error converting page cookies",{error:i})}return e}decode(e){try{let t=e.buffer.subarray(e.offset,e.offset+4);if(e.offset+=4,H.debug("Magic bytes:",t.toString()),!t.equals(O.MAGIC))throw new Error("Missing magic value");let o=e.buffer.readUInt32BE(e.offset);H.debug("Page count:",o),e.offset+=4;let i=[];for(let f=0;f<o;f++){let l=e.buffer.readUInt32BE(e.offset);i.push(l),H.debug(`Page ${f} size:`,l),e.offset+=4}let a=e.offset;H.debug("Starting page data at offset:",a);for(let f of i)try{H.debug("Reading page at offset:",a,"with size:",f);let l=e.buffer.subarray(a,a+f),c=new tr(l);this.pages.push(c),a+=f}catch(l){let c=l instanceof Error?l.message:String(l);H.warn("Error decoding page:",{error:c}),a+=f}e.offset=a;let s=e.buffer.readUInt32BE(e.offset);H.debug("Checksum:",s.toString(16)),e.offset+=4;let n=e.buffer.readBigUInt64BE(e.offset);H.debug("Footer:",n.toString(16)),e.offset+=8,n!==O.FOOTER&&W("BinaryCookies","Invalid cookie file format: wrong footer");let p=e.buffer.subarray(e.offset);this.metadata={}}catch(t){let o=t instanceof Error?t.message:String(t);throw W("BinaryCookies","Error decoding binary cookies file",{error:o}),t}}};O.MAGIC=Xo.Buffer.from("cook","utf8"),O.FOOTER=BigInt("0x071720050000004b"),O.DEFAULT_COOKIE_PATH=(0,ra.join)((0,ea.homedir)(),"Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies");var or=O;function ta(r){return or.fromFile(r).toCookieRows()}var ne=class extends M{constructor(){super("SafariCookieQueryStrategy","Safari")}getCookieDbPath(e){return(0,aa.join)(e,"Library","Containers","com.apple.Safari","Data","Library","Cookies","Cookies.binarycookies")}formatDomain(e){return e.startsWith(".")?e.slice(1):e}formatExpiry(e){if(e==null){let i=new Date;return Object.defineProperty(i,"valueOf",{value:()=>Number.NaN}),Object.defineProperty(i,"getTime",{value:()=>Number.NaN}),i}return typeof e!="number"||Number.isNaN(e)||e<=0?"Infinity":e<0||e>4102444800?(this.logger.warn("Invalid expiry timestamp, treating as session cookie",{expiry:e}),"Infinity"):new Date(e*1e3)}isFlagSet(e,t){return typeof e!="number"||Number.isNaN(e)||e<=0?!1:(e&t)===t}formatCreation(e){if(typeof e!="number"||Number.isNaN(e)||e<=0)return;if(e<0||e>4102444800){this.logger.warn("Invalid creation timestamp, ignoring",{creation:e});return}return e*1e3}processValue(e){return e===null?"null":e===void 0?"undefined":Buffer.isBuffer(e)?e.toString():String(e)}decodeCookies(e,t,o){try{return ta(e).filter(a=>(t==="%"||a.name===t)&&(o==="%"||this.formatDomain(a.domain).includes(o))).map(a=>({domain:this.formatDomain(a.domain),name:a.name,value:this.processValue(a.value),expiry:this.formatExpiry(a.expiry),meta:{file:e,browser:"Safari",decrypted:!1,secure:this.isFlagSet(a.flags,1),httpOnly:this.isFlagSet(a.flags,4),path:a.path,version:a.version,comment:a.comment,commentURL:a.commentURL,port:a.port,creation:this.formatCreation(a.creation)}}))}catch(i){return i instanceof Error?this.logger.error(`Error decoding ${e}`,{error:i.message,file:e,name:t,domain:o}):this.logger.error(`Error decoding ${e}`,{error:String(i),file:e,name:t,domain:o}),[]}}executeQuery(e,t,o,i){try{this.logger.info("Querying cookies",{name:e,domain:t,store:o});let a=(0,oa.homedir)();if(typeof a!="string"||a.length===0)return this.logger.error("Failed to get home directory"),Promise.resolve([]);let s=o??this.getCookieDbPath(a);return Promise.resolve(this.decodeCookies(s,e||"%",t||"%"))}catch(a){return a instanceof Error?this.logger.error("Failed to query cookies",{error:a.message,name:e,domain:t}):this.logger.error("Failed to query cookies",{error:String(a),name:e,domain:t}),Promise.resolve([])}}};var ia={strategies:new Map([["safari",ne],["firefox",ie],["chrome",ae]]),createStrategy(r){if(typeof r!="string")return new de([new ne,new ie,new ae]);let e=this.strategies.get(r.toLowerCase());return e!==void 0?new e:new de([new ne,new ie,new ae])}};async function rp(r,e,t){let o=[];for(let i of e){let a=await r.queryCookies(i,t);if(o=[...o,...a],typeof t.limit=="number"&&t.limit>0&&o.length>=t.limit){o=o.slice(0,t.limit);break}}return o}async function sa(r,e,t,o=!1,i){try{let a=typeof r.browser=="string"?r.browser:void 0,s=typeof r.force=="boolean"?r.force:!1,n=ia.createStrategy(a),p=new We(n),f=Array.isArray(e)?e:[e],l=await rp(p,f,{limit:t,removeExpired:o,store:i,strategy:n,force:s});if(l.length===0){u.error("No results");return}new Ge().getHandler(r).handle(l)}catch(a){a instanceof Error?u.error(a.message):u.error("An unknown error occurred")}}function tp(){u.log("Usage: get-cookie [name] [domain] [options]"),u.log(""),u.log("Examples:"),u.log(" get-cookie auth example.com # Get specific cookie"),u.log(" get-cookie % github.com --output json # Get all cookies as JSON"),u.log(" get-cookie --url https://example.com # Extract from URL"),u.log(""),u.log("Options:"),u.log(" -h, --help Show this help message"),u.log(" -v, --verbose Enable verbose output"),u.log(" -f, --force Force operation despite warnings (e.g., locked databases)"),u.log(""),u.log("Query options:"),u.log(" -n, --name PATTERN Cookie name pattern (% for wildcard)"),u.log(" -D, --domain PATTERN Cookie domain pattern"),u.log(" -u, --url URL URL to extract cookie specs from"),u.log(" --browser BROWSER Target specific browser (chrome|firefox|safari)"),u.log(" --store PATH Path to a specific cookie store file"),u.log(""),u.log("Output options:"),u.log(" --output FORMAT Output format (json)"),u.log(" -d, --dump Dump all cookie details"),u.log(" -G, --dump-grouped Dump all results, grouped by profile"),u.log(" -r, --render Render all results in formatted output")}function op(r,e){return{name:r||"%",domain:e||"%"}}function na(r){return r==="*"?"%":r}function ap(r,e){let t=r.url;if(typeof t=="string"){let a=ar(t);return Array.isArray(a)?a:(u.error("Invalid cookie specs from URL"),[])}let o=na(r.name||e[0]||"%"),i=na(r.domain||e[1]||"%");return[op(o,i)]}async function ip(r,e){let t=ap(r,e);r.verbose===!0&&u.log("cookieSpecs",t);try{await sa(r,t,void 0,r.removeExpired===!0,r.store)}catch(o){o instanceof Error?u.error("Error querying cookies:",o.message):u.error("An unknown error occurred while querying cookies")}}async function sp(){let r=process.argv.slice(2),{values:e,positionals:t}=vr(r);if(e.help===!0){tp();return}await ip(e,t)}sp().catch(r=>{r instanceof Error?u.error("Fatal error:",r.message):u.error("An unknown fatal error occurred"),process.exit(1)});
|
|
2
|
+
'use strict';var os$1=require('os'),dotenv=require('dotenv'),zod=require('zod'),consola=require('consola'),path=require('path'),child_process=require('child_process'),util=require('util'),fs$1=require('fs'),gi=require('fast-glob'),yi=require('minimist'),Gn=require('readline'),crypto=require('crypto'),events=require('events'),Pf=require('better-sqlite3'),buffer=require('buffer'),Lf=require('destr');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var gi__default=/*#__PURE__*/_interopDefault(gi);var yi__default=/*#__PURE__*/_interopDefault(yi);var Gn__default=/*#__PURE__*/_interopDefault(Gn);var Pf__default=/*#__PURE__*/_interopDefault(Pf);var Lf__default=/*#__PURE__*/_interopDefault(Lf);var ni=Object.defineProperty;var Be=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var H=(r,e)=>()=>(r&&(e=r(r=0)),e);var Nr=(r,e)=>{for(var t in e)ni(r,t,{get:e[t],enumerable:true});};var ai,Mr,Ct=H(()=>{dotenv.config();ai=zod.z.object({LOG_LEVEL:zod.z.enum(["debug","info","warn","error"]).default("info"),HOME:zod.z.string().optional().transform(r=>r??process.env.USERPROFILE??"").pipe(zod.z.string().min(1))}),Mr=ai.parse({LOG_LEVEL:process.env.LOG_LEVEL,HOME:os$1.homedir()});});var li,fi,f,N=H(()=>{Ct();li=consola.createConsola({formatOptions:{showLogLevel:false,colors:true,date:false,compact:true,columns:typeof process.stdout.columns=="number"?process.stdout.columns:80},level:Mr.LOG_LEVEL==="debug"?5:2}),Mr.LOG_LEVEL==="debug",fi=li,f=fi;});function Oe(r,e,t){let o=e instanceof Error?e.message:String(e);f.error(r,{...t,error:o});}function le(r,e,t){f.warn(`[${r}] ${e}`,t);}function h(r){return f.withTag(r)}var E=H(()=>{N();N();});function b(){return St??(St=os$1.platform()),St}function U(){return b()==="darwin"}function I(){return b()==="win32"}function $r(){let r=b();return r==="darwin"||r==="win32"||r==="linux"}function fe(){if(!$r())throw new Error(`Unsupported platform: ${b()}. Supported platforms are: darwin, win32, linux`)}var St,O=H(()=>{});var Te,qr=H(()=>{O();Te=(()=>{let r=os$1.homedir();if(!r)throw new Error("Unable to determine user home directory");switch(fe(),b()){case "darwin":return path.join(r,"Library","Application Support","Google","Chrome");case "win32":return path.join(r,"AppData","Local","Google","Chrome","User Data");case "linux":return path.join(r,".config","google-chrome");default:throw new Error(`Platform ${b()} is not supported`)}})();});async function W(r,e){try{let t=await Ml(r,{...e,encoding:"utf8"});return {stdout:t.stdout.toString(),stderr:t.stderr.toString()}}catch(t){throw Oe("Command execution failed",t,{command:r}),new Xr(t instanceof Error?t.message:String(t),r,t instanceof Error?t:void 0)}}var Ml,Xr,Pr=H(()=>{E();Ml=util.promisify(child_process.exec),Xr=class extends Error{constructor(t,o,n){super(t);this.command=o;this.originalError=n;this.name="CommandExecutionError";}};});var $n={};Nr($n,{getChromePassword:()=>yf});function hf(encryptedKey){let DPAPI_PREFIX=Buffer.from("DPAPI");if(!encryptedKey.subarray(0,5).equals(DPAPI_PREFIX))throw new Error("Invalid DPAPI key prefix");let encryptedData=encryptedKey.subarray(5);if(I())try{let moduleName="@primno/dpapi",dpapi=eval(`require("${moduleName}")`);if(typeof dpapi.unprotectData=="function")return dpapi.unprotectData(encryptedData)}catch(r){process.env.VERBOSE!==void 0&&process.env.VERBOSE!==""&&console.warn("DPAPI module not available:",r);}throw new Error("Windows DPAPI decryption requires native bindings. Install @primno/dpapi package for Windows support.")}function yf(){try{let r=path.join(Te,"Local State"),e=fs$1.readFileSync(r,"utf8"),t=JSON.parse(e);if(!t.os_crypt.encrypted_key)throw new Error("No encrypted key found in Chrome Local State");let o=Buffer.from(t.os_crypt.encrypted_key,"base64");return hf(o).toString("latin1")}catch(r){throw new Error(`Failed to retrieve Chrome password on Windows: ${r instanceof Error?r.message:String(r)}`)}}var Qn=H(()=>{O();qr();});var qn={};Nr(qn,{getChromePassword:()=>xf});async function xf(){try{let t=(await W("secret-tool lookup application chrome-libsecret-password-v2 || secret-tool lookup application chrome")).stdout.trim();if(t)return t}catch{}try{let t=(await W(`python3 -c "import keyring; print(keyring.get_password('Chrome Safe Storage', 'Chrome'))"`)).stdout.trim();if(t&&t!=="None")return t}catch{}try{let t=(await W('kwallet-query kdewallet -f "Chrome Safe Storage" -r Chrome')).stdout.trim();if(t)return t}catch{}return "peanuts"}var Hn=H(()=>{Pr();});var jn={};Nr(jn,{CookieQueryBuilder:()=>ee,createQueryBuilder:()=>kf,isSqlBrowser:()=>vf});function kf(r){return new ee(r)}function vf(r){return r in Un}var Un,ee,lt=H(()=>{Un={chrome:{tableName:"cookies",nameColumn:"name",valueColumn:"value",domainColumn:"host_key",expiryColumn:"expires_utc",encryptedValueColumn:"encrypted_value",pathColumn:"path",secureColumn:"is_secure",httpOnlyColumn:"is_httponly"},chromium:{tableName:"cookies",nameColumn:"name",valueColumn:"value",domainColumn:"host_key",expiryColumn:"expires_utc",encryptedValueColumn:"encrypted_value",pathColumn:"path",secureColumn:"is_secure",httpOnlyColumn:"is_httponly"},edge:{tableName:"cookies",nameColumn:"name",valueColumn:"value",domainColumn:"host_key",expiryColumn:"expires_utc",encryptedValueColumn:"encrypted_value",pathColumn:"path",secureColumn:"is_secure",httpOnlyColumn:"is_httponly"},opera:{tableName:"cookies",nameColumn:"name",valueColumn:"value",domainColumn:"host_key",expiryColumn:"expires_utc",encryptedValueColumn:"encrypted_value",pathColumn:"path",secureColumn:"is_secure",httpOnlyColumn:"is_httponly"},brave:{tableName:"cookies",nameColumn:"name",valueColumn:"value",domainColumn:"host_key",expiryColumn:"expires_utc",encryptedValueColumn:"encrypted_value",pathColumn:"path",secureColumn:"is_secure",httpOnlyColumn:"is_httponly"},arc:{tableName:"cookies",nameColumn:"name",valueColumn:"value",domainColumn:"host_key",expiryColumn:"expires_utc",encryptedValueColumn:"encrypted_value",pathColumn:"path",secureColumn:"is_secure",httpOnlyColumn:"is_httponly"},firefox:{tableName:"moz_cookies",nameColumn:"name",valueColumn:"value",domainColumn:"host",expiryColumn:"expiry",pathColumn:"path",secureColumn:"isSecure",httpOnlyColumn:"isHttpOnly"}},ee=class{constructor(e){if(this.browser=e,this.schema=Un[e],!this.schema)throw new Error(`Unsupported browser type: ${e}`)}buildSelectQuery(e){let{name:t,domain:o,exactDomain:n,limit:i,includeExpired:s}=e,a=this.schema,l=this.buildSelectColumns(),{whereClause:u,params:c}=this.buildWhereClause(t,o,n,s),m=`SELECT ${l} FROM ${a.tableName}`;return u&&(m+=` WHERE ${u}`),m+=` ORDER BY ${a.expiryColumn} DESC`,i&&i>0&&(m+=` LIMIT ${i}`),{sql:m,params:c,description:`Query ${this.browser} cookies: name=${t}, domain=${o}`}}buildBatchSelectQuery(e){if(e.length===0)throw new Error("At least one spec is required for batch query");let t=this.schema,o=this.buildSelectColumns(),n=[],i=[];for(let u of e){let{whereClause:c,params:m}=this.buildWhereClause(u.name,u.domain,u.exactDomain,u.includeExpired);c&&(n.push(`(${c})`),i.push(...m));}let s=n.join(" OR "),a=`SELECT ${o} FROM ${t.tableName}`;s&&(a+=` WHERE ${s}`),a+=` ORDER BY ${t.expiryColumn} DESC`;let l=e.reduce((u,c)=>c.limit&&c.limit>0?u?Math.min(u,c.limit):c.limit:u,void 0);return l&&l>0&&(a+=` LIMIT ${l*e.length}`),{sql:a,params:i,description:`Batch query ${this.browser} cookies for ${e.length} specs`}}buildMetaQuery(e){if(this.browser==="firefox")throw new Error("Firefox does not have a meta table");return {sql:"SELECT value FROM meta WHERE key = ?",params:[e],description:`Get metadata: ${e}`}}buildTableExistsQuery(){return {sql:"SELECT name FROM sqlite_master WHERE type='table' AND name=?",params:[this.schema.tableName],description:`Check if ${this.schema.tableName} table exists`}}buildSelectColumns(){let e=this.schema,t=[e.nameColumn,e.domainColumn,e.expiryColumn];return e.encryptedValueColumn&&this.browser!=="firefox"?t.push(e.encryptedValueColumn):t.push(e.valueColumn),e.pathColumn&&t.push(e.pathColumn),e.secureColumn&&t.push(e.secureColumn),e.httpOnlyColumn&&t.push(e.httpOnlyColumn),t.map(o=>{switch(o){case e.domainColumn:return `${o} AS domain`;case e.expiryColumn:return `${o} AS expiry`;case e.encryptedValueColumn:return `${o} AS encrypted_value`;case e.valueColumn:return `${o} AS value`;case e.nameColumn:return `${o} AS name`;case e.pathColumn:return `${o} AS path`;case e.secureColumn:return `${o} AS is_secure`;case e.httpOnlyColumn:return `${o} AS is_httponly`;default:return o}}).join(", ")}buildWhereClause(e,t,o,n){let i=this.schema,s=[],a=[];if(e==="%"||(e.includes("%")||e.includes("_")?(s.push(`${i.nameColumn} LIKE ?`),a.push(e)):(s.push(`${i.nameColumn} = ?`),a.push(e))),t&&(o?(s.push(`${i.domainColumn} = ?`),a.push(t)):t.startsWith(".")?(s.push(`${i.domainColumn} LIKE ?`),a.push(`%${t}`)):(s.push(`(${i.domainColumn} = ? OR ${i.domainColumn} = ? OR ${i.domainColumn} LIKE ?)`),a.push(t,`.${t}`,`%.${t}`))),!n)if(this.browser==="firefox"){let l=Math.floor(Date.now()/1e3);s.push(`${i.expiryColumn} > ?`),a.push(l);}else s.push(`${i.expiryColumn} > 0`);return {whereClause:s.join(" AND "),params:a}}static validateQueryParams(e){let{name:t,domain:o,limit:n}=e;if(typeof t!="string"||t.length===0)throw new Error("Cookie name must be a non-empty string");if(typeof o!="string"||o.length===0)throw new Error("Domain must be a non-empty string");let i=["SELECT","INSERT","UPDATE","DELETE","DROP","CREATE","ALTER","--",";"],s=(a,l)=>{let u=a.toUpperCase();for(let c of i)if(u.includes(c))throw new Error(`Invalid ${l}: contains SQL keyword '${c}'`)};if(s(t,"name"),s(o,"domain"),n!==void 0&&(!Number.isInteger(n)||n<=0||n>1e4))throw new Error("Limit must be a positive integer between 1 and 10000")}getBrowserType(){return this.browser}getSchema(){return Object.freeze({...this.schema})}};});E();qr();var kt=h("listChromeProfiles");function vt(){let r=gi__default.default.sync("./**/Cookies",{cwd:Te,absolute:true});return kt.debug("Found cookie files:",r),r}function Et(){try{let r=path.join(Te,"Local State"),e=JSON.parse(fs$1.readFileSync(r,"utf8"));return Object.values(e.profile.info_cache)}catch(r){return kt.debug("Failed to access Chrome profiles",{error:r}),[]}}function hi(r){let e=r.split("."),t=[];t.push({name:"%",domain:r});for(let o=1;o<e.length-1;o++){let n=e.slice(o).join(".");t.push({name:"%",domain:n});}return t}function Hr(r){if(!r.includes("://"))try{return Hr(`https://${r}`)}catch{return [{name:"%",domain:r}]}try{let e=new URL(r);return hi(e.hostname)}catch{return [{name:"%",domain:r}]}}function Pt(r){let e=yi__default.default(r,{string:["browser","profile","url","domain","name","output","store"],boolean:["help","version","verbose","dump","dump-grouped","render","render-grouped","force","include-expired","include-all","list-profiles"],alias:{b:"browser",p:"profile",u:"url",d:"dump",D:"domain",n:"name",h:"help",v:"verbose",f:"force",G:"dump-grouped",r:"render",R:"render-grouped"},unknown:n=>{if(!n.startsWith("-"))return true;if(!["--browser","-b","--profile","-p","--url","-u","--domain","-D","--name","-n","--output","--store","--help","-h","--version","--verbose","-v","--dump","-d","--dump-grouped","-G","--render","-r","--render-grouped","-R","--force","-f","--include-expired","--include-all","--list-profiles"].some(a=>n.startsWith(a)))throw new Error(`Unknown option: ${n}`);return true}}),{_:t,...o}=e;return {values:o,positionals:t}}N();function B(r){return r instanceof Error?r.message:typeof r=="string"?r:r!=null&&typeof r=="object"&&"message"in r?String(r.message):String(r)}function xi(r){let e=B(r);if(r instanceof Error){let t={message:e};return r.stack!==void 0&&(t.stack=r.stack),r.name!==void 0&&(t.name=r.name),"code"in r&&r.code!==void 0&&(t.code=String(r.code)),t}return {message:e}}function P(r,e){return B(r).toLowerCase().includes(e.toLowerCase())}var Ve={locked:["database is locked","database locked","sqlite_busy"],busy:["busy"],permission:["eperm","permission denied","operation not permitted","eacces"],not_found:["enoent","no such file","not found"]};function Ke(r,e){return e.some(t=>r.includes(t))}function Bt(r){let e=B(r).toLowerCase();return Ke(e,Ve.locked)?"locked":Ke(e,Ve.busy)?"busy":Ke(e,Ve.permission)?"permission":Ke(e,Ve.not_found)?"not_found":null}function ce(r,e){let t=xi(r);return {...e,error:t.message,errorName:t.name,errorCode:t.code,...process.env.NODE_ENV!=="production"&&t.stack!==void 0&&t.stack!==""?{errorStack:t.stack}:{}}}E();N();var Ae=class{canHandle(e){return true}handle(e){let t=new Set(e.map(o=>o.value));for(let o of t)f.log(o);}};N();var Je=class{canHandle(e){return e.dump===true||e.d===true}handle(e){f.log(e);}};var wi=typeof global=="object"&&global&&global.Object===Object&&global,Ye=wi;var bi=typeof self=="object"&&self&&self.Object===Object&&self,Ci=Ye||bi||Function("return this")(),S=Ci;var Si=S.Symbol,R=Si;var Ot=Object.prototype,ki=Ot.hasOwnProperty,vi=Ot.toString,Re=R?R.toStringTag:void 0;function Ei(r){var e=ki.call(r,Re),t=r[Re];try{r[Re]=void 0;var o=!0;}catch{}var n=vi.call(r);return o&&(e?r[Re]=t:delete r[Re]),n}var Tt=Ei;var Pi=Object.prototype,Bi=Pi.toString;function Oi(r){return Bi.call(r)}var At=Oi;var Ti="[object Null]",Ai="[object Undefined]",Rt=R?R.toStringTag:void 0;function Ri(r){return r==null?r===void 0?Ai:Ti:Rt&&Rt in Object(r)?Tt(r):At(r)}var F=Ri;function _i(r){return r!=null&&typeof r=="object"}var L=_i;var Di="[object Symbol]";function Ii(r){return typeof r=="symbol"||L(r)&&F(r)==Di}var pe=Ii;function Fi(r,e){for(var t=-1,o=r==null?0:r.length,n=Array(o);++t<o;)n[t]=e(r[t],t,r);return n}var _t=Fi;var Li=Array.isArray,C=Li;var Dt=R?R.prototype:void 0,It=Dt?Dt.toString:void 0;function Ft(r){if(typeof r=="string")return r;if(C(r))return _t(r,Ft)+"";if(pe(r))return It?It.call(r):"";var e=r+"";return e=="0"&&1/r==-Infinity?"-0":e}var Lt=Ft;function Mi(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var me=Mi;function $i(r){return r}var Nt=$i;var Qi="[object AsyncFunction]",qi="[object Function]",Hi="[object GeneratorFunction]",Ui="[object Proxy]";function ji(r){if(!me(r))return false;var e=F(r);return e==qi||e==Hi||e==Qi||e==Ui}var Ze=ji;var zi=S["__core-js_shared__"],Xe=zi;var Mt=function(){var r=/[^.]+$/.exec(Xe&&Xe.keys&&Xe.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function Wi(r){return !!Mt&&Mt in r}var $t=Wi;var Gi=Function.prototype,Vi=Gi.toString;function Ki(r){if(r!=null){try{return Vi.call(r)}catch{}try{return r+""}catch{}}return ""}var j=Ki;var Ji=/[\\^$.*+?()[\]{}|]/g,Yi=/^\[object .+?Constructor\]$/,Zi=Function.prototype,Xi=Object.prototype,es=Zi.toString,rs=Xi.hasOwnProperty,ts=RegExp("^"+es.call(rs).replace(Ji,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function os(r){if(!me(r)||$t(r))return false;var e=Ze(r)?ts:Yi;return e.test(j(r))}var Qt=os;function ns(r,e){return r?.[e]}var qt=ns;function is(r,e){var t=qt(r,e);return Qt(t)?t:void 0}var T=is;var ss=T(S,"WeakMap"),er=ss;var as=function(){try{var r=T(Object,"defineProperty");return r({},"",{}),r}catch{}}(),Ur=as;var us=9007199254740991,ls=/^(?:0|[1-9]\d*)$/;function fs(r,e){var t=typeof r;return e=e??us,!!e&&(t=="number"||t!="symbol"&&ls.test(r))&&r>-1&&r%1==0&&r<e}var rr=fs;function cs(r,e,t){e=="__proto__"&&Ur?Ur(r,e,{configurable:true,enumerable:true,value:t,writable:true}):r[e]=t;}var Ht=cs;function ps(r,e){return r===e||r!==r&&e!==e}var tr=ps;var ms=9007199254740991;function ds(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=ms}var de=ds;function gs(r){return r!=null&&de(r.length)&&!Ze(r)}var or=gs;var hs=Object.prototype;function ys(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||hs;return r===t}var Ut=ys;function xs(r,e){for(var t=-1,o=Array(r);++t<r;)o[t]=e(t);return o}var jt=xs;var ws="[object Arguments]";function bs(r){return L(r)&&F(r)==ws}var jr=bs;var zt=Object.prototype,Cs=zt.hasOwnProperty,Ss=zt.propertyIsEnumerable,ks=jr(function(){return arguments}())?jr:function(r){return L(r)&&Cs.call(r,"callee")&&!Ss.call(r,"callee")},nr=ks;function vs(){return false}var Wt=vs;var Kt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Gt=Kt&&typeof module=="object"&&module&&!module.nodeType&&module,Es=Gt&&Gt.exports===Kt,Vt=Es?S.Buffer:void 0,Ps=Vt?Vt.isBuffer:void 0,Bs=Ps||Wt,_e=Bs;var Os="[object Arguments]",Ts="[object Array]",As="[object Boolean]",Rs="[object Date]",_s="[object Error]",Ds="[object Function]",Is="[object Map]",Fs="[object Number]",Ls="[object Object]",Ns="[object RegExp]",Ms="[object Set]",$s="[object String]",Qs="[object WeakMap]",qs="[object ArrayBuffer]",Hs="[object DataView]",Us="[object Float32Array]",js="[object Float64Array]",zs="[object Int8Array]",Ws="[object Int16Array]",Gs="[object Int32Array]",Vs="[object Uint8Array]",Ks="[object Uint8ClampedArray]",Js="[object Uint16Array]",Ys="[object Uint32Array]",x={};x[Us]=x[js]=x[zs]=x[Ws]=x[Gs]=x[Vs]=x[Ks]=x[Js]=x[Ys]=true;x[Os]=x[Ts]=x[qs]=x[As]=x[Hs]=x[Rs]=x[_s]=x[Ds]=x[Is]=x[Fs]=x[Ls]=x[Ns]=x[Ms]=x[$s]=x[Qs]=false;function Zs(r){return L(r)&&de(r.length)&&!!x[F(r)]}var Jt=Zs;function Xs(r){return function(e){return r(e)}}var Yt=Xs;var Zt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,De=Zt&&typeof module=="object"&&module&&!module.nodeType&&module,ea=De&&De.exports===Zt,zr=ea&&Ye.process,ra=function(){try{var r=De&&De.require&&De.require("util").types;return r||zr&&zr.binding&&zr.binding("util")}catch{}}(),Wr=ra;var Xt=Wr&&Wr.isTypedArray,ta=Xt?Yt(Xt):Jt,ir=ta;var oa=Object.prototype,na=oa.hasOwnProperty;function ia(r,e){var t=C(r),o=!t&&nr(r),n=!t&&!o&&_e(r),i=!t&&!o&&!n&&ir(r),s=t||o||n||i,a=s?jt(r.length,String):[],l=a.length;for(var u in r)(e||na.call(r,u))&&!(s&&(u=="length"||n&&(u=="offset"||u=="parent")||i&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||rr(u,l)))&&a.push(u);return a}var eo=ia;function sa(r,e){return function(t){return r(e(t))}}var ro=sa;var aa=ro(Object.keys,Object),to=aa;var ua=Object.prototype,la=ua.hasOwnProperty;function fa(r){if(!Ut(r))return to(r);var e=[];for(var t in Object(r))la.call(r,t)&&t!="constructor"&&e.push(t);return e}var oo=fa;function ca(r){return or(r)?eo(r):oo(r)}var ge=ca;var pa=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ma=/^\w*$/;function da(r,e){if(C(r))return false;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||pe(r)?true:ma.test(r)||!pa.test(r)||e!=null&&r in Object(e)}var he=da;var ga=T(Object,"create"),z=ga;function ha(){this.__data__=z?z(null):{},this.size=0;}var no=ha;function ya(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var io=ya;var xa="__lodash_hash_undefined__",wa=Object.prototype,ba=wa.hasOwnProperty;function Ca(r){var e=this.__data__;if(z){var t=e[r];return t===xa?void 0:t}return ba.call(e,r)?e[r]:void 0}var so=Ca;var Sa=Object.prototype,ka=Sa.hasOwnProperty;function va(r){var e=this.__data__;return z?e[r]!==void 0:ka.call(e,r)}var ao=va;var Ea="__lodash_hash_undefined__";function Pa(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=z&&e===void 0?Ea:e,this}var uo=Pa;function ye(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var o=r[e];this.set(o[0],o[1]);}}ye.prototype.clear=no;ye.prototype.delete=io;ye.prototype.get=so;ye.prototype.has=ao;ye.prototype.set=uo;var Gr=ye;function Ba(){this.__data__=[],this.size=0;}var lo=Ba;function Oa(r,e){for(var t=r.length;t--;)if(tr(r[t][0],e))return t;return -1}var G=Oa;var Ta=Array.prototype,Aa=Ta.splice;function Ra(r){var e=this.__data__,t=G(e,r);if(t<0)return false;var o=e.length-1;return t==o?e.pop():Aa.call(e,t,1),--this.size,true}var fo=Ra;function _a(r){var e=this.__data__,t=G(e,r);return t<0?void 0:e[t][1]}var co=_a;function Da(r){return G(this.__data__,r)>-1}var po=Da;function Ia(r,e){var t=this.__data__,o=G(t,r);return o<0?(++this.size,t.push([r,e])):t[o][1]=e,this}var mo=Ia;function xe(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var o=r[e];this.set(o[0],o[1]);}}xe.prototype.clear=lo;xe.prototype.delete=fo;xe.prototype.get=co;xe.prototype.has=po;xe.prototype.set=mo;var V=xe;var Fa=T(S,"Map"),K=Fa;function La(){this.size=0,this.__data__={hash:new Gr,map:new(K||V),string:new Gr};}var go=La;function Na(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}var ho=Na;function Ma(r,e){var t=r.__data__;return ho(e)?t[typeof e=="string"?"string":"hash"]:t.map}var J=Ma;function $a(r){var e=J(this,r).delete(r);return this.size-=e?1:0,e}var yo=$a;function Qa(r){return J(this,r).get(r)}var xo=Qa;function qa(r){return J(this,r).has(r)}var wo=qa;function Ha(r,e){var t=J(this,r),o=t.size;return t.set(r,e),this.size+=t.size==o?0:1,this}var bo=Ha;function we(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var o=r[e];this.set(o[0],o[1]);}}we.prototype.clear=go;we.prototype.delete=yo;we.prototype.get=xo;we.prototype.has=wo;we.prototype.set=bo;var ie=we;var Ua="Expected a function";function Vr(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(Ua);var t=function(){var o=arguments,n=e?e.apply(this,o):o[0],i=t.cache;if(i.has(n))return i.get(n);var s=r.apply(this,o);return t.cache=i.set(n,s)||i,s};return t.cache=new(Vr.Cache||ie),t}Vr.Cache=ie;var Co=Vr;var ja=500;function za(r){var e=Co(r,function(o){return t.size===ja&&t.clear(),o}),t=e.cache;return e}var So=za;var Wa=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Ga=/\\(\\)?/g,Va=So(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(Wa,function(t,o,n,i){e.push(n?i.replace(Ga,"$1"):o||t);}),e}),ko=Va;function Ka(r){return r==null?"":Lt(r)}var vo=Ka;function Ja(r,e){return C(r)?r:he(r,e)?[r]:ko(vo(r))}var sr=Ja;function Za(r){if(typeof r=="string"||pe(r))return r;var e=r+"";return e=="0"&&1/r==-Infinity?"-0":e}var Y=Za;function Xa(r,e){e=sr(e,r);for(var t=0,o=e.length;r!=null&&t<o;)r=r[Y(e[t++])];return t&&t==o?r:void 0}var ar=Xa;function eu(r,e,t){var o=r==null?void 0:ar(r,e);return o===void 0?t:o}var Eo=eu;function ru(r,e){for(var t=-1,o=e.length,n=r.length;++t<o;)r[n+t]=e[t];return r}var Po=ru;function tu(){this.__data__=new V,this.size=0;}var Bo=tu;function ou(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}var Oo=ou;function nu(r){return this.__data__.get(r)}var To=nu;function iu(r){return this.__data__.has(r)}var Ao=iu;var su=200;function au(r,e){var t=this.__data__;if(t instanceof V){var o=t.__data__;if(!K||o.length<su-1)return o.push([r,e]),this.size=++t.size,this;t=this.__data__=new ie(o);}return t.set(r,e),this.size=t.size,this}var Ro=au;function be(r){var e=this.__data__=new V(r);this.size=e.size;}be.prototype.clear=Bo;be.prototype.delete=Oo;be.prototype.get=To;be.prototype.has=Ao;be.prototype.set=Ro;var Ce=be;function uu(r,e){for(var t=-1,o=r==null?0:r.length,n=0,i=[];++t<o;){var s=r[t];e(s,t,r)&&(i[n++]=s);}return i}var _o=uu;function lu(){return []}var Do=lu;var fu=Object.prototype,cu=fu.propertyIsEnumerable,Io=Object.getOwnPropertySymbols,pu=Io?function(r){return r==null?[]:(r=Object(r),_o(Io(r),function(e){return cu.call(r,e)}))}:Do,Fo=pu;function mu(r,e,t){var o=e(r);return C(r)?o:Po(o,t(r))}var Lo=mu;function du(r){return Lo(r,ge,Fo)}var Kr=du;var gu=T(S,"DataView"),ur=gu;var hu=T(S,"Promise"),lr=hu;var yu=T(S,"Set"),fr=yu;var No="[object Map]",xu="[object Object]",Mo="[object Promise]",$o="[object Set]",Qo="[object WeakMap]",qo="[object DataView]",wu=j(ur),bu=j(K),Cu=j(lr),Su=j(fr),ku=j(er),se=F;(ur&&se(new ur(new ArrayBuffer(1)))!=qo||K&&se(new K)!=No||lr&&se(lr.resolve())!=Mo||fr&&se(new fr)!=$o||er&&se(new er)!=Qo)&&(se=function(r){var e=F(r),t=e==xu?r.constructor:void 0,o=t?j(t):"";if(o)switch(o){case wu:return qo;case bu:return No;case Cu:return Mo;case Su:return $o;case ku:return Qo}return e});var Jr=se;var vu=S.Uint8Array,Yr=vu;var Eu="__lodash_hash_undefined__";function Pu(r){return this.__data__.set(r,Eu),this}var Ho=Pu;function Bu(r){return this.__data__.has(r)}var Uo=Bu;function cr(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new ie;++e<t;)this.add(r[e]);}cr.prototype.add=cr.prototype.push=Ho;cr.prototype.has=Uo;var jo=cr;function Ou(r,e){for(var t=-1,o=r==null?0:r.length;++t<o;)if(e(r[t],t,r))return true;return false}var zo=Ou;function Tu(r,e){return r.has(e)}var Wo=Tu;var Au=1,Ru=2;function _u(r,e,t,o,n,i){var s=t&Au,a=r.length,l=e.length;if(a!=l&&!(s&&l>a))return false;var u=i.get(r),c=i.get(e);if(u&&c)return u==e&&c==r;var m=-1,g=true,d=t&Ru?new jo:void 0;for(i.set(r,e),i.set(e,r);++m<a;){var v=r[m],w=e[m];if(o)var D=s?o(w,v,m,e,r,i):o(v,w,m,r,e,i);if(D!==void 0){if(D)continue;g=false;break}if(d){if(!zo(e,function(oe,ne){if(!Wo(d,ne)&&(v===oe||n(v,oe,t,o,i)))return d.push(ne)})){g=false;break}}else if(!(v===w||n(v,w,t,o,i))){g=false;break}}return i.delete(r),i.delete(e),g}var pr=_u;function Du(r){var e=-1,t=Array(r.size);return r.forEach(function(o,n){t[++e]=[n,o];}),t}var Go=Du;function Iu(r){var e=-1,t=Array(r.size);return r.forEach(function(o){t[++e]=o;}),t}var Vo=Iu;var Fu=1,Lu=2,Nu="[object Boolean]",Mu="[object Date]",$u="[object Error]",Qu="[object Map]",qu="[object Number]",Hu="[object RegExp]",Uu="[object Set]",ju="[object String]",zu="[object Symbol]",Wu="[object ArrayBuffer]",Gu="[object DataView]",Ko=R?R.prototype:void 0,Zr=Ko?Ko.valueOf:void 0;function Vu(r,e,t,o,n,i,s){switch(t){case Gu:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return false;r=r.buffer,e=e.buffer;case Wu:return !(r.byteLength!=e.byteLength||!i(new Yr(r),new Yr(e)));case Nu:case Mu:case qu:return tr(+r,+e);case $u:return r.name==e.name&&r.message==e.message;case Hu:case ju:return r==e+"";case Qu:var a=Go;case Uu:var l=o&Fu;if(a||(a=Vo),r.size!=e.size&&!l)return false;var u=s.get(r);if(u)return u==e;o|=Lu,s.set(r,e);var c=pr(a(r),a(e),o,n,i,s);return s.delete(r),c;case zu:if(Zr)return Zr.call(r)==Zr.call(e)}return false}var Jo=Vu;var Ku=1,Ju=Object.prototype,Yu=Ju.hasOwnProperty;function Zu(r,e,t,o,n,i){var s=t&Ku,a=Kr(r),l=a.length,u=Kr(e),c=u.length;if(l!=c&&!s)return false;for(var m=l;m--;){var g=a[m];if(!(s?g in e:Yu.call(e,g)))return false}var d=i.get(r),v=i.get(e);if(d&&v)return d==e&&v==r;var w=true;i.set(r,e),i.set(e,r);for(var D=s;++m<l;){g=a[m];var oe=r[g],ne=e[g];if(o)var bt=s?o(ne,oe,g,e,r,i):o(oe,ne,g,r,e,i);if(!(bt===void 0?oe===ne||n(oe,ne,t,o,i):bt)){w=false;break}D||(D=g=="constructor");}if(w&&!D){var ze=r.constructor,We=e.constructor;ze!=We&&"constructor"in r&&"constructor"in e&&!(typeof ze=="function"&&ze instanceof ze&&typeof We=="function"&&We instanceof We)&&(w=false);}return i.delete(r),i.delete(e),w}var Yo=Zu;var Xu=1,Zo="[object Arguments]",Xo="[object Array]",mr="[object Object]",el=Object.prototype,en=el.hasOwnProperty;function rl(r,e,t,o,n,i){var s=C(r),a=C(e),l=s?Xo:Jr(r),u=a?Xo:Jr(e);l=l==Zo?mr:l,u=u==Zo?mr:u;var c=l==mr,m=u==mr,g=l==u;if(g&&_e(r)){if(!_e(e))return false;s=true,c=false;}if(g&&!c)return i||(i=new Ce),s||ir(r)?pr(r,e,t,o,n,i):Jo(r,e,l,t,o,n,i);if(!(t&Xu)){var d=c&&en.call(r,"__wrapped__"),v=m&&en.call(e,"__wrapped__");if(d||v){var w=d?r.value():r,D=v?e.value():e;return i||(i=new Ce),n(w,D,t,o,i)}}return g?(i||(i=new Ce),Yo(r,e,t,o,n,i)):false}var rn=rl;function tn(r,e,t,o,n){return r===e?true:r==null||e==null||!L(r)&&!L(e)?r!==r&&e!==e:rn(r,e,t,o,tn,n)}var dr=tn;var tl=1,ol=2;function nl(r,e,t,o){var n=t.length,i=n,s=!o;if(r==null)return !i;for(r=Object(r);n--;){var a=t[n];if(s&&a[2]?a[1]!==r[a[0]]:!(a[0]in r))return false}for(;++n<i;){a=t[n];var l=a[0],u=r[l],c=a[1];if(s&&a[2]){if(u===void 0&&!(l in r))return false}else {var m=new Ce;if(o)var g=o(u,c,l,r,e,m);if(!(g===void 0?dr(c,u,tl|ol,o,m):g))return false}}return true}var on=nl;function il(r){return r===r&&!me(r)}var gr=il;function sl(r){for(var e=ge(r),t=e.length;t--;){var o=e[t],n=r[o];e[t]=[o,n,gr(n)];}return e}var nn=sl;function al(r,e){return function(t){return t==null?false:t[r]===e&&(e!==void 0||r in Object(t))}}var hr=al;function ul(r){var e=nn(r);return e.length==1&&e[0][2]?hr(e[0][0],e[0][1]):function(t){return t===r||on(t,r,e)}}var sn=ul;function ll(r,e){return r!=null&&e in Object(r)}var an=ll;function fl(r,e,t){e=sr(e,r);for(var o=-1,n=e.length,i=false;++o<n;){var s=Y(e[o]);if(!(i=r!=null&&t(r,s)))break;r=r[s];}return i||++o!=n?i:(n=r==null?0:r.length,!!n&&de(n)&&rr(s,n)&&(C(r)||nr(r)))}var un=fl;function cl(r,e){return r!=null&&un(r,e,an)}var ln=cl;var pl=1,ml=2;function dl(r,e){return he(r)&&gr(e)?hr(Y(r),e):function(t){var o=Eo(t,r);return o===void 0&&o===e?ln(t,r):dr(e,o,pl|ml)}}var fn=dl;function gl(r){return function(e){return e?.[r]}}var cn=gl;function hl(r){return function(e){return ar(e,r)}}var pn=hl;function yl(r){return he(r)?cn(Y(r)):pn(r)}var mn=yl;function xl(r){return typeof r=="function"?r:r==null?Nt:typeof r=="object"?C(r)?fn(r[0],r[1]):sn(r):mn(r)}var dn=xl;function wl(r,e,t,o){for(var n=-1,i=r==null?0:r.length;++n<i;){var s=r[n];e(o,s,t(s),r);}return o}var gn=wl;function bl(r){return function(e,t,o){for(var n=-1,i=Object(e),s=o(e),a=s.length;a--;){var l=s[r?a:++n];if(t(i[l],l,i)===false)break}return e}}var hn=bl;var Cl=hn(),yn=Cl;function Sl(r,e){return r&&yn(r,e,ge)}var xn=Sl;function kl(r,e){return function(t,o){if(t==null)return t;if(!or(t))return r(t,o);for(var n=t.length,i=e?n:-1,s=Object(t);(e?i--:++i<n)&&o(s[i],i,s)!==false;);return t}}var wn=kl;var vl=wn(xn),bn=vl;function El(r,e,t,o){return bn(r,function(n,i,s){e(o,n,t(n),s);}),o}var Cn=El;function Pl(r,e){return function(t,o){var n=C(t)?gn:Cn,i=e?e():{};return n(t,r,dn(o),i)}}var Sn=Pl;var Bl=Object.prototype,Ol=Bl.hasOwnProperty,Tl=Sn(function(r,e,t){Ol.call(r,t)?r[t].push(e):Ht(r,t,[e]);}),Ie=Tl;N();var yr=class{canHandle(e){return e["dump-grouped"]===true||e.D===true}handle(e){let t=Ie(e,o=>o.meta?.file??"unknown");f.log(JSON.stringify(t,null,2));}};function xr(r,e={}){let{format:t="merged",showFilePaths:o=true,separator:n="; "}=e;if(r.length===0)return t==="merged"?"":[];if(t==="merged")return r.map(s=>`${s.name}=${s.value}`).join(n);let i=Ie(r,s=>s.meta?.file??"unknown");return Object.entries(i).map(([s,a])=>{let l=a.map(u=>`${u.name}=${u.value}`).join(n);return o?`${s}: ${l}`:l})}N();var wr=class{canHandle(e){return e["render-grouped"]===true||e.R===true}handle(e){f.log(xr(e,{format:"grouped"}));}};N();var br=class{canHandle(e){return e.output==="json"}handle(e){f.log(JSON.stringify(e,null,2));}};N();var Cr=class{canHandle(e){return e.render===true||e["render-merged"]===true||e.r===true}handle(e){f.log(xr(e,{format:"merged"}));}};var Sr=class{constructor(){this.validOutputFormats=["json"];this.handlers=[new Je,new yr,new Cr,new wr,new br,new Ae];}validateOutputFormat(e){if(e.output!==void 0&&!this.validOutputFormats.includes(e.output)){let t=this.validOutputFormats.join(", ");throw new Error(`Invalid output format: '${e.output}'. Valid formats are: ${t}`)}}getHandler(e){return this.validateOutputFormat(e),this.handlers.find(t=>t.canHandle(e))??new Ae}};var kr=class{constructor(e){this.strategy=e;}async queryCookies(e,t){return this.strategy.queryCookies(e.name,e.domain,t?.store,t?.force)}};E();var Se=h("BrowserDetector"),vr={c:99,o1:111,o2:111,k:107},_l=[{browser:"firefox",pattern:r=>r.includes("cookies.sqlite")},{browser:"chrome",pattern:r=>r.includes("cookies")&&r.endsWith(".db")},{browser:"safari",pattern:r=>r.includes("cookies.binarycookies")}];function Dl(r){try{let e=fs$1.readFileSync(r);return e.length>=4&&e[0]===vr.c&&e[1]===vr.o1&&e[2]===vr.o2&&e[3]===vr.k}catch(e){return Se.debug("Failed to read file for magic bytes check",{path:r,error:e}),false}}function Il(r){let e=r.toLowerCase();for(let{browser:t,pattern:o}of _l)if(o(e))return Se.debug("Detected browser from filename",{browser:t,filename:e}),t}function Er(r){if(!r||!fs$1.existsSync(r)){Se.debug("Store path does not exist",{storePath:r});return}if(Dl(r))return Se.info("Detected Safari binary cookies from magic bytes"),"safari";let e=Il(r);if(e)return Se.info("Detected browser from filename pattern",{browser:e}),e;Se.debug("Could not detect browser type from store",{storePath:r});}function kn(r){return ["chrome","firefox","safari","edge","arc","opera","opera-gx"].includes(r)}E();O();function vn(r){let e=os$1.homedir();if(!e)throw new Error("Unable to determine user home directory");fe();let t=b(),n={chrome:{windows:path.join(e,"AppData","Local","Google","Chrome","User Data"),macos:path.join(e,"Library","Application Support","Google","Chrome"),linux:path.join(e,".config","google-chrome")},chromium:{windows:path.join(e,"AppData","Local","Chromium","User Data"),macos:path.join(e,"Library","Application Support","Chromium"),linux:path.join(e,".config","chromium")},brave:{windows:path.join(e,"AppData","Local","BraveSoftware","Brave-Browser","User Data"),macos:path.join(e,"Library","Application Support","BraveSoftware","Brave-Browser"),linux:path.join(e,".config","BraveSoftware","Brave-Browser")},edge:{windows:path.join(e,"AppData","Local","Microsoft","Edge","User Data"),macos:path.join(e,"Library","Application Support","Microsoft Edge"),linux:path.join(e,".config","microsoft-edge")},arc:{windows:path.join(e,"AppData","Local","Arc","User Data"),macos:path.join(e,"Library","Application Support","Arc","User Data"),linux:path.join(e,".config","arc")},opera:{windows:path.join(e,"AppData","Roaming","Opera Software","Opera Stable"),macos:path.join(e,"Library","Application Support","com.operasoftware.Opera"),linux:path.join(e,".config","opera")},"opera-gx":{windows:path.join(e,"AppData","Roaming","Opera Software","Opera GX Stable"),macos:path.join(e,"Library","Application Support","com.operasoftware.OperaGX"),linux:path.join(e,".config","opera-gx")},vivaldi:{windows:path.join(e,"AppData","Local","Vivaldi","User Data"),macos:path.join(e,"Library","Application Support","Vivaldi"),linux:path.join(e,".config","vivaldi")},whale:{windows:path.join(e,"AppData","Local","Naver","Naver Whale","User Data"),macos:path.join(e,"Library","Application Support","Naver","Whale"),linux:path.join(e,".config","naver-whale")}}[r];switch(t){case "win32":return n.windows;case "darwin":return n.macos;case "linux":return n.linux;default:throw new Error(`Platform ${t} is not supported`)}}O();Pr();E();O();var En=h("ProcessDetector");function $l(r,e){let t=r.trim().split(/\s+/);if(t.length<2)return null;let o=t[1];if(o===void 0||o==="")return null;let n=Number.parseInt(o,10);if(Number.isNaN(n))return null;let i=t.slice(10).join(" ");return {pid:n,command:i!==""?i:e,details:r.trim()}}function Ql(r,e){let t=r.split(",").map(i=>i.replace(/"/g,"").trim());if(t.length<2)return null;let o=t[1];if(o===void 0||o==="")return null;let n=Number.parseInt(o,10);return Number.isNaN(n)?null:{pid:n,command:t[0]??e,details:r.trim()}}async function et(r,e){try{let t;if(I()){let s={firefox:"firefox.exe",chrome:"chrome.exe","google chrome":"chrome.exe",chromium:"chromium.exe",safari:"safari.exe",edge:"msedge.exe"},a=s[r.toLowerCase()]??s[e.toLowerCase()]??`${r.toLowerCase()}.exe`;t=`tasklist /FI "IMAGENAME eq ${a}" /FO CSV | findstr /i "${a}"`;}else t=`ps aux | grep -i '${e}' | grep -v grep`;let{stdout:o}=await W(t);if(!o||o.trim()==="")return [];let n=[],i=o.split(`
|
|
3
|
+
`).filter(s=>s.trim()!=="");for(let s of i){let a=I()?Ql(s,r.toLowerCase()):$l(s,r.toLowerCase());a&&n.push(a);}return En.debug(`${r} process detection completed`,{processCount:n.length,processes:n.map(s=>({pid:s.pid,command:s.command})),platform:b()}),n}catch(t){return En.debug(`Failed to detect ${r} processes`,{error:B(t),platform:b()}),[]}}async function Pn(){return et("Firefox","firefox")}async function Bn(){return et("Chrome","google chrome\\|chromium")}async function On(){return et("Safari","/Applications/Safari.app/Contents/MacOS/Safari")}function Tn(r,e){if(e.length===0)return "";let t=e.length,o=r.charAt(0).toUpperCase()+r.slice(1);return `${o} is currently running (${t} process${t>1?"es":""} detected). For reliable cookie access, consider closing ${o} and trying again. Alternatively, use the --force flag to attempt access despite the lock.`}function An(r){if(r==null||typeof r!="number"||Number.isNaN(r))return;if(r<=0)return "Infinity";let e=r/1e6-11644473600;return e<0||e>3250368e4?"Infinity":new Date(e*1e3)}E();var ql={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{},success:()=>{},fatal:()=>{},log:()=>{}},Z=class{constructor(e,t){this.browserName=t;let o=h(e);this.logger=o||ql;}async queryCookies(e,t,o,n){try{return this.logger.info("Querying cookies",{name:e,domain:t,store:o,force:n}),await this.executeQuery(e,t,o,n)}catch(i){return i instanceof Error?this.logger.error("Failed to query cookies",{error:i.message,browser:this.browserName,strategy:this.constructor.name,name:e,domain:t,store:o,force:n}):this.logger.error("Failed to query cookies",{error:String(i),browser:this.browserName,strategy:this.constructor.name,name:e,domain:t,store:o,force:n}),[]}}};E();O();var rt=util.promisify(child_process.exec),k=h("BrowserControl");function zl(){let r=process.env.CI==="true"||process.env.CI==="1",e=process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID!==void 0;return process.stdin.isTTY&&process.stdout.isTTY&&!r&&!e}var tt={Firefox:"Firefox",Chrome:"Google Chrome",Safari:"Safari"};async function ot(r){try{let e=tt[r];if(!e)return k.debug("Browser not supported for macOS control",{browserName:r}),!1;let t=`tell application "System Events" to (name of processes) contains "${e}"`,{stdout:o}=await rt(`osascript -e '${t}'`);return o.trim()==="true"}catch(e){return k.debug("Failed to check if browser is running",{browserName:r,error:e}),false}}async function Wl(r){try{let e=tt[r];if(!e)return k.debug("Browser not supported for macOS control",{browserName:r}),!1;let t=`tell application "${e}" to quit`;return await rt(`osascript -e '${t}'`),await new Promise(n=>setTimeout(n,2e3)),await ot(r)?(k.warn("Browser did not quit gracefully",{browserName:r}),!1):(k.info("Browser quit successfully",{browserName:r}),!0)}catch(e){return k.error("Failed to quit browser",{browserName:r,error:e}),false}}async function Gl(r){try{let e=tt[r];if(!e){k.debug("Browser not supported for macOS control",{browserName:r});return}if(r==="Firefox"){let t=`
|
|
4
|
+
tell application "${e}"
|
|
5
|
+
activate
|
|
6
|
+
end tell
|
|
7
|
+
tell application "System Events"
|
|
8
|
+
keystroke "d" using {command down, shift down}
|
|
9
|
+
delay 0.5
|
|
10
|
+
key code 36
|
|
11
|
+
end tell
|
|
12
|
+
`;await rt(`osascript -e '${t}'`),k.debug("Attempted to save Firefox session",{browserName:r});}else r==="Chrome"?k.debug("Chrome will restore tabs automatically",{browserName:r}):k.debug("Safari will restore tabs automatically",{browserName:r});}catch(e){k.debug("Failed to save browser session",{browserName:r,error:e});}}async function Vl(r){if(!zl())return k.debug("Non-interactive environment detected, skipping prompt",{browserName:r,CI:process.env.CI,NODE_ENV:process.env.NODE_ENV,JEST_WORKER_ID:process.env.JEST_WORKER_ID,stdin_tty:process.stdin.isTTY,stdout_tty:process.stdout.isTTY}),false;let e=Gn__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(`
|
|
13
|
+
\u26A0\uFE0F ${r} is currently running and blocking cookie access.
|
|
14
|
+
Would you like to close ${r}? Your tabs will be restored when you reopen it. (y/N): `,o=>{e.close(),t(o.toLowerCase()==="y"||o.toLowerCase()==="yes");});})}async function Rn(r,e={}){if(!U())return k.debug("Browser control only supported on macOS"),false;try{if(!await ot(r))return k.debug("Browser is not running",{browserName:r}),!0;if(e.interactive===!0&&e.force!==!0&&!await Vl(r))return k.info("User cancelled browser close",{browserName:r}),!1;await Gl(r);let o=await Wl(r);return o?k.success(`${r} closed successfully. Tabs will be restored on next launch.`):k.warn(`Failed to close ${r}. You may need to close it manually.`),o}catch(t){return k.error("Failed to control browser",{browserName:r,error:t}),false}}async function _n(r,e=1e4){if(!U())return false;let t=Date.now(),o=500;for(;Date.now()-t<e;){if(!await ot(r))return true;await new Promise(i=>setTimeout(i,o));}return false}E();O();var Br=util.promisify(child_process.execFile),A=h("FileHandleDetector");function Yl(r){let e=r.trim().split(/\s+/);if(e.length<2)return null;let t=e[1];if(t===void 0||t==="")return null;let o=Number.parseInt(t,10);if(Number.isNaN(o))return null;let n={pid:o,command:e[2]??"unknown"},i=e[0];i!==void 0&&i!==""&&(n.user=i);let s=e[3];return s!==void 0&&s!==""&&(n.mode=s),n}function Zl(r){return r!==null&&typeof r=="object"&&"ProcessId"in r&&"ProcessName"in r}function Xl(r){let e=[];try{let t=JSON.parse(r),o=Array.isArray(t)?t:[t];for(let n of o){if(!Zl(n))continue;let i=n.ProcessId,s=n.ProcessName;typeof i=="string"&&i!==""&&e.push({command:typeof s=="string"?s:"unknown",pid:Number.parseInt(i,10)});}}catch(t){A.debug("Failed to parse PowerShell output",{error:B(t)});}return e}async function ef(r){try{let{stdout:e}=await Br("lsof",[r],{encoding:"utf8"});if(!e||e.trim()==="")return [];let t=e.split(`
|
|
15
|
+
`).slice(1),o=[];for(let n of t){let i=n.trim().split(/\s+/),s=i[0],a=i[1],l=i[2],u=i[3];if(s!==void 0&&s!==""&&a!==void 0&&a!==""&&i.length>=4){let c=Number.parseInt(a,10);if(!Number.isNaN(c)){let m={command:s,pid:c};l!==void 0&&l!==""&&(m.user=l),u!==void 0&&u!==""&&(m.fd=u,m.mode=u.includes("w")?"write":"read"),o.push(m);}}}return A.debug("Detected file handles with lsof",{file:r,handleCount:o.length}),o}catch(e){let t=B(e);return P(e,"ENOENT")?A.debug("lsof not available on this system"):P(e,"No such file")?A.debug("File does not exist",{file:r}):A.debug("lsof detection failed",{error:t}),[]}}async function rf(r){try{let e=await Br("fuser",["-v",r],{encoding:"utf8"}),t=e.stderr||e.stdout||"";if(t.trim()==="")return [];let o=[],n=t.split(`
|
|
16
|
+
`).slice(1);for(let i of n){let s=Yl(i);s&&o.push(s);}return A.debug("Detected file handles with fuser",{file:r,handleCount:o.length}),o}catch(e){let t=B(e);return P(e,"ENOENT")?A.debug("fuser not available on this system"):A.debug("fuser detection failed",{error:t}),[]}}async function tf(r){try{let e=r.replace(/'/g,"''"),t=`
|
|
17
|
+
$ErrorActionPreference = 'SilentlyContinue'
|
|
18
|
+
$handles = @()
|
|
19
|
+
|
|
20
|
+
# Try to find processes with the file open
|
|
21
|
+
Get-Process | ForEach-Object {
|
|
22
|
+
try {
|
|
23
|
+
$proc = $_
|
|
24
|
+
# Check if any modules match the file path
|
|
25
|
+
$modules = $proc.Modules | Where-Object { $_.FileName -eq '${e}' }
|
|
26
|
+
if ($modules) {
|
|
27
|
+
$handles += [PSCustomObject]@{
|
|
28
|
+
ProcessName = $proc.ProcessName
|
|
29
|
+
ProcessId = $proc.Id
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
} catch {
|
|
33
|
+
# Skip processes we can't access
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
# Also try using Get-CimInstance for better file handle detection
|
|
38
|
+
try {
|
|
39
|
+
$query = "SELECT * FROM CIM_DataFile WHERE Name='${e.replace(/\\/g,"\\\\")}'"
|
|
40
|
+
$file = Get-CimInstance -Query $query -ErrorAction SilentlyContinue
|
|
41
|
+
if ($file) {
|
|
42
|
+
$assoc = Get-CimAssociatedInstance -InputObject $file -ResultClassName Win32_Process
|
|
43
|
+
foreach ($proc in $assoc) {
|
|
44
|
+
$handles += [PSCustomObject]@{
|
|
45
|
+
ProcessName = $proc.Name
|
|
46
|
+
ProcessId = $proc.ProcessId
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
} catch {
|
|
51
|
+
# WMI query failed, ignore
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
$handles | ConvertTo-Json -Compress
|
|
55
|
+
`,{stdout:o}=await Br("powershell",["-NoProfile","-NonInteractive","-Command",t],{encoding:"utf8",maxBuffer:1024*1024});if(!o||o.trim()===""||o.trim()==="null")return [];let n=Xl(o);return A.debug("Detected file handles with PowerShell",{file:r,handleCount:n.length}),n}catch(e){return A.debug("Windows handle detection failed",{error:B(e)}),[]}}async function of(r){try{let{stdout:e}=await Br("handle",["-nobanner",r],{encoding:"utf8"});if(!e||e.trim()==="")return [];let t=[],o=e.split(`
|
|
56
|
+
`);for(let n of o){let i=n.match(/^(.+?)\s+pid:\s+(\d+)\s+type:\s+(\w+)\s+.+:\s+(.+)$/i);if(i?.[1]!==void 0&&i?.[1]!==""&&i?.[2]!==void 0&&i?.[2]!==""){let s=Number.parseInt(i[2],10);if(!Number.isNaN(s)){let a={command:i[1],pid:s};i?.[3]!==void 0&&i[3]!==""&&(a.fd=i[3]),a.mode="unknown",t.push(a);}}}return A.debug("Detected file handles with handle.exe",{file:r,handleCount:t.length}),t}catch{return []}}async function nt(r){let e=b();if(A.debug("Detecting file handles",{file:r,platform:e}),I()){let o=await of(r);return o.length>0?o:tf(r)}let t=await ef(r);return t.length===0&&(t=await rf(r)),t.length>0&&A.info("File has open handles",{file:r,handleCount:t.length,processes:t.map(o=>({pid:o.pid,command:o.command,mode:o.mode}))}),t}async function Dn(r){let e=await nt(r);if(e.length===0)return "File is not locked";let t=e.map(o=>`${o.command} (PID: ${o.pid}${o.user!==void 0&&o.user!==""?`, User: ${o.user}`:""}${o.mode!==void 0&&o.mode!==""?`, Mode: ${o.mode}`:""})`).join(", ");return `File is locked by ${e.length} process${e.length>1?"es":""}: ${t}`}O();var Fe=util.promisify(child_process.execFile),ke=class r{constructor(){this.browserExecutables=this.initializeBrowserExecutables();}isBrowserSupported(e){let t=this.browserExecutables[e];return !!(t&&t.length>0)}getBrowserExecutables(e){return this.browserExecutables[e]||[]}async isBrowserInstalled(e){let t=this.getBrowserExecutables(e);for(let o of t)try{let n=I()?"where":"which";return await Fe(n,[o],{timeout:1e3}),!0}catch{}return false}async executeCommand(e,t=[]){try{await Fe(e,t,{timeout:5e3,windowsHide:!0});}catch(o){this.isNodeError(o)&&o.code!=="ENOENT"&&console.debug(`Browser launch warning: ${r.getErrorMessage(o)}`);}}isNodeError(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"}static getErrorMessage(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}},st=class extends ke{initializeBrowserExecutables(){return {Firefox:["Firefox"],Chrome:["Google Chrome"],Safari:["Safari"]}}async launchBrowser(e){let o={Firefox:"Firefox",Chrome:"Google Chrome",Safari:"Safari"}[e];if(!o)throw new Error(`${e} not supported on macOS`);await this.executeCommand("osascript",["-e",`tell application "${o}" to activate`]);}getPlatformName(){return "macOS"}},at=class extends ke{initializeBrowserExecutables(){return {Firefox:["firefox.exe","Firefox"],Chrome:["chrome.exe","Google Chrome"],Safari:[]}}async launchBrowser(e){let t=this.getBrowserExecutables(e);if(t.length===0)throw new Error(`${e} not available on Windows`);for(let o of t)if(await this.tryLaunchExecutable(o))return;throw new Error(`Failed to launch ${e} on Windows`)}async tryLaunchExecutable(e){try{return await Fe("cmd.exe",["/c","start","",e],{timeout:5e3,windowsHide:!0}),!0}catch{return false}}getPlatformName(){return "Windows"}},Or=class extends ke{initializeBrowserExecutables(){return {Firefox:["firefox","firefox-bin"],Chrome:["google-chrome","google-chrome-stable","chromium","chromium-browser"],Safari:[]}}async launchBrowser(e){let t=this.getBrowserExecutables(e);if(t.length===0)throw new Error(`${e} not available on Linux`);await this.tryLaunchExecutables(t)||await this.tryXdgOpenFallback(e);}async tryLaunchExecutables(e){for(let t of e)try{return await Fe(t,[],{timeout:5e3}),!0}catch{}return false}async tryXdgOpenFallback(e){try{await Fe("xdg-open",["http://localhost"],{timeout:5e3});}catch(t){throw new Error(`Failed to launch ${e} on Linux: ${ke.getErrorMessage(t)}`)}}getPlatformName(){return "Linux"}},it=null;function In(r){if(it!==null&&r===void 0)return it;let e=b(),t=af(e);return (it=t),t}function af(r){switch(r){case "darwin":return new st;case "win32":return new at;case "linux":case "freebsd":case "openbsd":return new Or;default:return new Or}}var X=class{constructor(e,t,o){this.logger=e;this.browserName=t;this.platformControl=o??In();}async handleBrowserConflict(e,t,o,n=false){return e instanceof Error?this.isLockError(e)?(await this.logFileHandleInfo(t,o),this.handleProcessConflict(t,o,n)):{resolved:false,shouldRelaunch:false}:{resolved:false,shouldRelaunch:false}}isLockError(e){let t=Bt(e);return t==="locked"||t==="permission"}async logFileHandleInfo(e,t){try{let o=await nt(e);if(o.length>0){let n=await Dn(e);this.logger.debug("Database locked by specific processes",{file:e,lockInfo:n,handleCount:o.length,handles:o.map(i=>({pid:i.pid,command:i.command,mode:i.mode,user:i.user}))}),t.length===0&&this.logger.info("File is locked but no browser processes detected - another tool may be accessing the database",{lockingProcesses:o.map(i=>`${i.command} (PID: ${i.pid})`).join(", ")});}}catch(o){this.logger.debug("Could not detect file handles",{error:o instanceof Error?o.message:String(o)});}}async handleProcessConflict(e,t,o){try{if(t.length>0)return await this.handleBrowserProcesses(e,t,o);this.logger.debug("Database/file locked but no browser processes detected",{file:e,browserName:this.browserName,suggestion:"Another process may be accessing the file"});}catch(n){this.logger.debug("Failed to check browser processes",{error:n instanceof Error?n.message:String(n)});}return {resolved:false,shouldRelaunch:false}}async handleBrowserProcesses(e,t,o){let n=t.map(s=>({...s,details:`PID: ${s.pid}, Command: ${s.command}`})),i=Tn(this.browserName.toLowerCase(),n);return this.logger.debug(`${this.browserName} process conflict detected`,{file:e,processCount:t.length,advice:i}),o?this.attemptBrowserClose():Promise.resolve({resolved:false,shouldRelaunch:false})}async attemptBrowserClose(){return this.logger.info(`Attempting to close ${this.browserName} gracefully...`),await Rn(this.browserName,{interactive:true,force:false})?(await _n(this.browserName,5e3),{resolved:true,shouldRelaunch:true}):{resolved:false,shouldRelaunch:false}}async relaunchBrowser(){this.logger.info(`Relaunching ${this.browserName}...`);try{if(!this.platformControl.isBrowserSupported(this.browserName)){this.logger.debug(`${this.browserName} is not available on ${this.platformControl.getPlatformName()}`);return}await this.platformControl.launchBrowser(this.browserName),this.logger.success(`${this.browserName} has been relaunched with your tabs restored`);}catch(e){this.logger.debug(`Could not relaunch ${this.browserName} automatically`,{error:B(e),platform:this.platformControl.getPlatformName()});}}};O();function Fn(r,e){let t=Buffer.from("v10");if(!r.subarray(0,3).equals(t))throw new Error("Not a v10 encrypted cookie");let o=r.subarray(3),n=12,i=16;if(o.length<n+i)throw new Error("Invalid v10 cookie: too short");let s=o.subarray(0,n),a=o.subarray(n,o.length-i),l=o.subarray(o.length-i),u=crypto.createDecipheriv("aes-256-gcm",e,s);return u.setAuthTag(l),Buffer.concat([u.update(a),u.final()]).toString("utf8")}function Ln(r){let e=Buffer.from("v10");return r.length>=3&&r.subarray(0,3).equals(e)}function Nn(r,e){let t=new Map;return o=>{let n=e?e(o):o.toString("hex");if(t.has(n)){let s=t.get(n);if(s!==void 0)return s}let i=r(o);return t.set(n,i),i}}var cf=Nn(r=>r.length>=3&&r[0]===118&&r[1]===49&&r[2]===48?r.slice(3):r,r=>r.toString("hex")),pf=Nn(r=>{let e=r[r.length-1];return e&&e<=16?r.slice(0,-e):r},r=>r.toString("hex"));function mf(r){let e=r.match(/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/i);if(e?.[1])return e[1];let t=[/([A-Z]{3})$/,/([a-z]{2}_[A-Z]{2})$/,/(\d{3}-\d{7}-\d{7})$/];for(let n of t){let i=r.match(n);if(i?.[1])return i[1]}let o=[/.*?0t(.+)$/,/.*?1e`(.+)$/,/.*?[`'](.+)$/,/[^\x20-\x7E]*([\x20-\x7E]+)$/,/.*?([a-zA-Z0-9_\-.]+)$/];for(let n of o){let s=r.match(n)?.[1]??"";if(s.length>0)return s}return r}async function Mn(r,e,t){if(I()&&Ln(r)&&r.length>=31&&Buffer.isBuffer(e))return Fn(r,e);if(U()&&!r.slice(0,3).toString().match(/^v\d\d$/))return Promise.resolve(r.toString("utf8"));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,n)=>{crypto.pbkdf2(e,"saltysalt",1003,16,"sha1",(i,s)=>{try{if(i){n(new Error(`Failed to derive key: ${i.message}`));return}let a=cf(r);if(a.length%16!==0){n(new Error("Encrypted data length is not a multiple of 16"));return}let l=Buffer.alloc(16," "),u=crypto.createDecipheriv("aes-128-cbc",s,l);u.setAutoPadding(!1);let c=u.update(a);try{u.final();}catch(v){n(new Error(`Failed to finalize decryption: ${v.message}`));return}c=pf(c);let d=((t??0)>=24&&c.length>32?c.slice(32):c).toString("utf8");o(mf(d));}catch(a){n(new Error(`Decryption failed: ${a.message}`));}});})}O();Pr();var wf={chrome:"Chrome Safe Storage",chromium:"Chromium Safe Storage",brave:"Brave Safe Storage",edge:"Microsoft Edge Safe Storage",arc:"Arc Safe Storage",opera:"Opera Safe Storage","opera-gx":"Opera Safe Storage",vivaldi:"Vivaldi Safe Storage",whale:"Whale Safe Storage"};async function bf(r){let e=wf[r];if(!e)throw new Error(`Unknown browser type: ${r}`);try{let t=`security find-generic-password -w -s "${e}"`;return (await W(t)).stdout.trim()}catch(t){if(r!=="chrome"){let o='security find-generic-password -w -s "Chrome Safe Storage"';try{return (await W(o)).stdout.trim()}catch{}}throw new Error(`Failed to get ${r} password from keychain: ${t}`)}}async function Cf(){let{getChromePassword:r}=await Promise.resolve().then(()=>(Qn(),$n));return r()}async function Sf(){let{getChromePassword:r}=await Promise.resolve().then(()=>(Hn(),qn));return r()}async function ut(r="chrome"){switch(fe(),b()){case "darwin":return bf(r);case "win32":return Cf();case "linux":return Sf();default:throw new Error(`Platform ${b()} is not supported`)}}lt();E();var M=h("DatabaseConnectionManager"),ct=class extends events.EventEmitter{constructor(e={}){super(),this.connections=new Map,this.queryMetrics=[],this.totalQueries=0,this.cacheHits=0,this.connectionReuses=0,this.lastCleanupTime=Date.now(),this.config={maxConnections:e.maxConnections??5,connectionTimeout:e.connectionTimeout??5e3,idleTimeout:e.idleTimeout??3e4,enableMonitoring:e.enableMonitoring??true,retryAttempts:e.retryAttempts??3,retryDelay:e.retryDelay??100,queryTimeout:e.queryTimeout??3e3};}async getConnection(e){let t=Date.now();t-this.lastCleanupTime>3e4&&(this.cleanupIdleConnections(),this.lastCleanupTime=t);let o=this.connections.get(e);return o&&!o.inUse?(o.inUse=true,o.lastAccessed=Date.now(),this.connectionReuses++,M.debug("Reusing existing connection",{filepath:e,queryCount:o.queryCount}),o.database):(this.connections.size>=this.config.maxConnections&&await this.evictLeastRecentlyUsed(),this.createConnection(e))}async createConnection(e){let t=Date.now(),o;for(let n=0;n<this.config.retryAttempts;n++)try{let i=new Pf__default.default(e,{readonly:!0,fileMustExist:!0});i.pragma(`busy_timeout = ${this.config.queryTimeout}`);let s={database:i,filepath:e,inUse:!0,lastAccessed:Date.now(),queryCount:0,totalQueryTime:0,created:Date.now()};this.connections.set(e,s);let a=Date.now()-t;return M.debug("Created new connection",{filepath:e,connectionTime:a,attempt:n+1}),this.emit("connection:created",{filepath:e,connectionTime:a}),i}catch(i){if(o=i,this.isDatabaseLocked(i)){M.warn("Database locked, retrying",{filepath:e,attempt:n+1,maxAttempts:this.config.retryAttempts}),await this.delay(this.config.retryDelay*2**n);continue}throw i}throw o||new Error(`Failed to connect to database: ${e}`)}async executeQuery(e,t,o){let n=Date.now(),i=await this.getConnection(e),s=this.connections.get(e);try{let a=t(i),l=Date.now()-n;if(s&&(s.queryCount++,s.totalQueryTime+=l),this.totalQueries++,this.cacheHits++,l>100&&M.debug("Slow query detected",{query:o||"Unknown query",duration:l,filepath:e}),this.config.enableMonitoring){let u={query:o||"Unknown query",duration:l,rowCount:Array.isArray(a)?a.length:1,filepath:e,timestamp:Date.now(),success:!0};this.recordMetrics(u);}return a}catch(a){let l=Date.now()-n;if(this.totalQueries++,this.config.enableMonitoring){let u={query:o||"Unknown query",duration:l,rowCount:0,filepath:e,timestamp:Date.now(),success:false,error:a.message};this.recordMetrics(u);}throw a}finally{s&&(s.inUse=false,s.lastAccessed=Date.now());}}releaseConnection(e){let t=this.connections.get(e);t&&(t.inUse=false,t.lastAccessed=Date.now(),M.debug("Released connection",{filepath:e}));}closeConnection(e){let t=this.connections.get(e);if(t)try{t.database.close(),this.connections.delete(e),M.debug("Closed connection",{filepath:e,queryCount:t.queryCount,lifetime:Date.now()-t.created}),this.emit("connection:closed",{filepath:e});}catch(o){Oe("Failed to close connection",o,{filepath:e});}}closeAll(){for(let[e,t]of this.connections)try{t.database.close(),M.debug("Closed connection",{filepath:e});}catch(o){Oe("Failed to close connection",o,{filepath:e});}this.connections.clear(),M.info("Closed all connections",{totalQueries:this.totalQueries,connectionReuses:this.connectionReuses});}getStatistics(){let e=0,t=0,o=0;for(let n of this.connections.values())e+=n.totalQueryTime,t+=n.queryCount,n.inUse&&o++;return {totalConnections:this.connections.size,activeConnections:o,idleConnections:this.connections.size-o,totalQueries:this.totalQueries,averageQueryTime:t>0?e/t:0,cacheHitRate:this.totalQueries>0?this.cacheHits/this.totalQueries:0,connectionReuse:this.connectionReuses}}getQueryMetrics(e=100){return this.queryMetrics.slice(-e)}clearMetrics(){this.queryMetrics.length=0;}cleanupIdleConnections(){let e=Date.now(),t=[];for(let[o,n]of this.connections)!n.inUse&&e-n.lastAccessed>this.config.idleTimeout&&t.push(o);for(let o of t)this.closeConnection(o);t.length>0&&M.debug("Cleaned up idle connections",{count:t.length});}async evictLeastRecentlyUsed(){let e=null,t=Date.now();for(let[o,n]of this.connections)!n.inUse&&n.lastAccessed<t&&(e=o,t=n.lastAccessed);e?(this.closeConnection(e),M.debug("Evicted LRU connection",{filepath:e})):await this.delay(100);}recordMetrics(e){this.queryMetrics.push(e),this.queryMetrics.length>1e3&&this.queryMetrics.splice(0,this.queryMetrics.length-1e3),this.emit("query:executed",e);}isDatabaseLocked(e){if(e instanceof Error){let t=e.message.toLowerCase();return t.includes("database is locked")||t.includes("database locked")||t.includes("sqlite_busy")}return false}async delay(e){return new Promise(t=>setTimeout(t,e))}},Le=null,ft=null;function ve(r){return Le||(Le=new ct(r),ft||(ft=()=>{Le&&Le.closeAll();},process.on("exit",ft))),Le}E();var pt=h("QueryMonitor"),dt=class{constructor(e={}){this.options={slowQueryThreshold:e.slowQueryThreshold??100,verbose:e.verbose??false,trackHistory:e.trackHistory??true,maxHistorySize:e.maxHistorySize??1e3},this.queryHistory=[],this.totalQueries=0,this.totalDuration=0,this.slowQueries=0,this.errors=0;}executeQuery(e,t,o=[],n){let i={sql:t,params:o,startTime:Date.now()};n!==void 0&&(i.filepath=n);try{let a=e.prepare(t).all(...o);return i.endTime=Date.now(),i.duration=i.endTime-i.startTime,i.rowCount=a.length,this.recordExecution(i),a}catch(s){throw i.endTime=Date.now(),i.duration=i.endTime-i.startTime,i.error=s,this.recordExecution(i),s}}executeGet(e,t,o=[],n){let i={sql:t,params:o,startTime:Date.now()};n!==void 0&&(i.filepath=n);try{let a=e.prepare(t).get(...o);return i.endTime=Date.now(),i.duration=i.endTime-i.startTime,i.rowCount=a?1:0,this.recordExecution(i),a}catch(s){throw i.endTime=Date.now(),i.duration=i.endTime-i.startTime,i.error=s,this.recordExecution(i),s}}prepareStatement(e,t,o){let n=e.prepare(t);return new gt(n,t,this,o)}recordExecution(e){this.totalQueries++,e.duration!==void 0&&(this.totalDuration+=e.duration,e.duration>this.options.slowQueryThreshold&&(this.slowQueries++,pt.debug("Slow query detected",{sql:e.sql,duration:e.duration,rowCount:e.rowCount,filepath:e.filepath}))),e.error?(this.errors++,this.options.verbose&&pt.error("Query failed",{sql:e.sql,error:e.error.message,filepath:e.filepath})):this.options.verbose&&pt.debug("Query executed",{sql:e.sql,duration:e.duration,rowCount:e.rowCount}),this.options.trackHistory&&(this.queryHistory.push(e),this.queryHistory.length>this.options.maxHistorySize&&this.queryHistory.splice(0,this.queryHistory.length-this.options.maxHistorySize));}getStatistics(){return {totalQueries:this.totalQueries,averageDuration:this.totalQueries>0?this.totalDuration/this.totalQueries:0,slowQueries:this.slowQueries,slowQueryRate:this.totalQueries>0?this.slowQueries/this.totalQueries:0,errors:this.errors,errorRate:this.totalQueries>0?this.errors/this.totalQueries:0,historySize:this.queryHistory.length}}getHistory(e){return e?this.queryHistory.slice(-e):[...this.queryHistory]}clearHistory(){this.queryHistory.length=0;}reset(){this.clearHistory(),this.totalQueries=0,this.totalDuration=0,this.slowQueries=0,this.errors=0;}},gt=class{constructor(e,t,o,n){this.statement=e;this.sql=t;this.monitor=o;this.filepath=n;}all(...e){return this.monitor.executeQuery({prepare:()=>this.statement},this.sql,e,this.filepath)}get(...e){return this.monitor.executeGet({prepare:()=>this.statement},this.sql,e,this.filepath)}getStatement(){return this.statement}},mt=null;function Ne(r){return mt||(mt=new dt(r)),mt}function zn(r,e,t,o,n,i,s){return {domain:r,name:e,value:t,expiry:An(o),meta:{file:n,browser:i,decrypted:s}}}var Ee=class extends Z{constructor(e,t,o="chrome"){super(e,"Chrome"),this.browserDisplayName=t,this.browserType=o,this.lockHandler=new X(this.logger,"Chrome");}async batchQueryCookies(e){if(!this.isPlatformSupported())return [];let t=this.getCookieFiles();if(t.length===0)return this.logger.debug(`No ${this.browserDisplayName} cookie files found`),[];try{let o=await ut(this.browserType),n=[];for(let i of t){let s=await this.processBatchFile(i,e,o);n.push(...s);}return n}catch(o){return this.logger.error(`Failed to get ${this.browserDisplayName} password for batch query`,{error:this.getErrorMessage(o)}),[]}}async processBatchFile(e,t,o){try{let n=ve(),i=Ne(),s=new ee("chrome"),a=t.map(d=>({name:d.name,domain:d.domain,browser:"chrome"})),l=s.buildBatchSelectQuery(a),u=await n.executeQuery(e,d=>i.executeQuery(d,l.sql,l.params,e).map(w=>({name:w.name,domain:w.domain,value:w.encrypted_value,expiry:w.expiry})),l.description||l.sql),c=await this.getMetaVersion(e),m={file:e,password:o,browser:this.browserDisplayName,metaVersion:c};return (await Promise.allSettled(u.map(async d=>this.processCookie(d,m)))).filter(d=>d.status==="fulfilled").map(d=>d.value)}catch(n){return this.logger.warn(`Error batch processing ${this.browserDisplayName} cookie file ${e}`,{error:this.getErrorMessage(n),file:e,specsCount:t.length}),[]}}getBrowserName(){return this.browserDisplayName}async executeQuery(e,t,o,n){if(!this.isPlatformSupported())return [];let i=this.getCookieFiles(o);if(i.length===0)return this.logger.debug(`No ${this.browserDisplayName} cookie files found`),[];try{let s=await ut(this.browserType),a=[];for(let l of i){let u=await this.processFileWithRetry(l,e,t,s,n);a.push(...u);}return a}catch(s){return this.logger.error(`Failed to get ${this.browserDisplayName} password`,{error:this.getErrorMessage(s)}),[]}}isPlatformSupported(){return $r()?true:(this.logger.warn("Platform not supported",{platform:b(),supportedPlatforms:["darwin","win32","linux"]}),false)}getCookieFiles(e){let t=e??this.getCookieFilePaths();return Array.isArray(t)?t:[t]}getErrorMessage(e){return e instanceof Error?e.message:String(e)}async processFileWithRetry(e,t,o,n,i){try{return await this.processFile(e,t,o,n)}catch(s){let a=await this.handleFileError(s,e,t,o,i);return a.resolved?this.retryAfterBrowserClose(e,t,o,n,a.shouldRelaunch):[]}}async handleFileError(e,t,o,n,i){let s=await Bn(),a=await this.lockHandler.handleBrowserConflict(e,t,s,i!==true);return a.resolved||this.logger.warn(`Error reading ${this.browserDisplayName} cookie file ${t}`,{error:this.getErrorMessage(e),file:t,name:o,domain:n}),a}async retryAfterBrowserClose(e,t,o,n,i){try{this.logger.info(`Retrying ${this.browserDisplayName} cookie extraction after browser close...`);let s=await this.processFile(e,t,o,n);return this.logger.success(`Successfully extracted cookies after closing ${this.browserDisplayName}`),i&&await this.lockHandler.relaunchBrowser(),s}catch(s){return this.logger.error(`Failed to extract cookies even after closing ${this.browserDisplayName}`,{error:this.getErrorMessage(s),file:e}),i&&await this.lockHandler.relaunchBrowser(),[]}}async processFile(e,t,o,n){try{let i=ve(),s=Ne(),l=new ee("chrome").buildSelectQuery({name:t,domain:o,browser:"chrome"}),u=await i.executeQuery(e,d=>s.executeQuery(d,l.sql,l.params,e).map(w=>({name:w.name,domain:w.domain,value:w.encrypted_value,expiry:w.expiry})),l.sql),c=await this.getMetaVersion(e),m={file:e,password:n,browser:this.browserDisplayName,metaVersion:c};return (await Promise.allSettled(u.map(async d=>this.processCookie(d,m)))).map(d=>d.status==="fulfilled"?d.value:null).filter(d=>d!==null)}catch(i){return this.logger.error(`Failed to process ${this.browserDisplayName} cookie file`,{error:this.getErrorMessage(i),file:e,name:t,domain:o}),[]}}async getMetaVersion(e){try{let t=ve(),n=new ee("chrome").buildMetaQuery("version"),i=await t.executeQuery(e,s=>s.prepare(n.sql).get(...n.params),"Get meta version");return i?Number.parseInt(i.value,10):0}catch(t){return this.logger.debug("Could not retrieve meta version, defaulting to 0",{error:this.getErrorMessage(t)}),0}}async processCookie(e,t){try{let o=Buffer.isBuffer(e.value)?e.value:Buffer.from(String(e.value)),n=await Mn(o,t.password,t.metaVersion);return zn(e.domain,e.name,n,e.expiry,t.file,t.browser,!0)}catch(o){return this.logger.warn(`Failed to decrypt ${t.browser} cookie`,{error:this.getErrorMessage(o)}),zn(e.domain,e.name,e.value.toString("utf-8"),e.expiry,t.file,t.browser,false)}}};var $=class extends Ee{constructor(e="chrome"){let t=e.charAt(0).toUpperCase()+e.slice(1);super(`${t}CookieQueryStrategy`,t,e),this.browser=e;}getCookieFilePaths(e){if(e!==void 0&&e!=="")return [e];try{let t=vn(this.browser),o=gi__default.default.sync("./**/Cookies",{cwd:t,absolute:!0});return this.logger.debug(`Found ${o.length} cookie files for ${this.browser}`),o}catch(t){return this.logger.warn(`Failed to find ${this.browser} cookie files`,{error:this.getErrorMessage(t)}),[]}}};var Me=class extends ${constructor(){super("arc");}};var ae=class extends Ee{constructor(e){super("ChromeCookieQueryStrategy","Chrome"),e!==void 0&&(this.profileName=e);}getCookieFilePaths(e){if(e!==void 0&&e!=="")return [e];let t=vt();if(this.profileName)try{let o=Be("fs"),n=Be("path");if(t.length===0)return this.logger.warn("No Chrome cookie files found"),[];let i=t[0];if(!i)return [];let s=path.dirname(path.dirname(i)),a=n.join(s,"Local State");if(o.existsSync(a)){let u=JSON.parse(o.readFileSync(a,"utf8")).profile?.info_cache||{},c;for(let[m,g]of Object.entries(u))if(g.name?.toLowerCase()===this.profileName.toLowerCase()){c=m;break}if(!c){for(let m of Object.keys(u))if(m.toLowerCase()===this.profileName.toLowerCase()){c=m;break}}if(c)t=t.filter(m=>path.dirname(m).endsWith(c)),t.length===0?this.logger.warn(`No cookie files found for profile: ${this.profileName} (directory: ${c})`):this.logger.debug(`Found ${t.length} cookie file(s) for profile: ${this.profileName}`);else return this.logger.debug("Profile not found in Chrome Local State",{requestedProfile:this.profileName,availableProfiles:Object.entries(u).map(([m,g])=>({directory:m,name:g.name}))}),[]}}catch(o){this.logger.warn(`Failed to read Chrome profile info: ${o}`);}return Array.isArray(t)?t:[t]}};async function Wn(r,e,t=[]){return r.length===0?t:(await Promise.all(r.map(async n=>{try{return await e(n)}catch{return t}}))).flat()}E();var Tr=class{constructor(e){this.strategies=e;this.logger=h("CompositeCookieQueryStrategy");this.browserName="internal";}handleStrategyError(e,t){e instanceof Error?this.logger.error("Strategy failed",{error:e,strategy:t}):this.logger.error("Strategy failed with unknown error",{error:String(e),strategy:t});}async queryCookies(e,t,o,n){try{return this.logger.info("Querying cookies from all strategies",{name:e,domain:t,store:o,force:n,strategyCount:this.strategies.length}),await Wn(this.strategies,async i=>{try{return await i.queryCookies(e,t,o,n)}catch(s){return this.handleStrategyError(s,i),[]}},[])}catch(i){return i instanceof Error?this.logger.error("Failed to query cookies",{error:i}):this.logger.error("Failed to query cookies with unknown error",{error:String(i)}),[]}}};var $e=class extends ${constructor(){super("edge");}};O();function Af(r){let e=os$1.homedir();if(!e)return r.warn("Failed to get home directory"),[];let t=b(),o=[],n=[];switch(t){case "darwin":o.push(path.join(e,"Library/Application Support/Firefox")),n.push(path.join(e,"Library/Application Support/Firefox/Profiles/*/cookies.sqlite"));break;case "win32":{o.push(path.join(e,"AppData","Roaming","Mozilla","Firefox")),n.push(path.join(e,"AppData","Roaming","Mozilla","Firefox","Profiles","*","cookies.sqlite"));let a=path.join(e,"AppData","Roaming","Mozilla","Firefox Developer Edition");fs$1.existsSync(a)&&(o.push(a),n.push(path.join(a,"Profiles","*","cookies.sqlite")));let l=path.join(e,"AppData","Roaming","Mozilla","Firefox ESR");fs$1.existsSync(l)&&(o.push(l),n.push(path.join(l,"Profiles","*","cookies.sqlite")));let u=path.join(e,"AppData","Local","Mozilla","Firefox");fs$1.existsSync(u)&&(o.push(u),n.push(path.join(u,"Profiles","*","cookies.sqlite")));break}case "linux":o.push(path.join(e,".mozilla/firefox")),n.push(path.join(e,".mozilla/firefox/*/cookies.sqlite"));break;default:return r.debug("Unsupported platform for Firefox cookie extraction",{platform:t}),[]}if(o.filter(a=>fs$1.existsSync(a)).length===0)return r.debug("No Firefox profile directories found - Firefox may not be installed",{checked:o,platform:t}),[];let s=[];for(let a of n){let l=gi__default.default.sync(a);s.push(...l);}return r.debug("Found Firefox cookie files",{files:s}),s}var Qe=class extends Z{constructor(){super("FirefoxCookieQueryStrategy","Firefox"),this.lockHandler=new X(this.logger,"Firefox");}async createCookieQueryConfig(e,t,o){let{CookieQueryBuilder:n}=await Promise.resolve().then(()=>(lt(),jn)),s=new n("firefox").buildSelectQuery({name:e,domain:t,browser:"firefox"});return {file:o,sql:s.sql,params:s.params,rowTransform:a=>({name:a.name,value:a.value,domain:a.domain,expiry:a.expiry>0?new Date(a.expiry*1e3):"Infinity",meta:{file:o,browser:"Firefox",decrypted:false}})}}async handleCookieExtractionError(e,t,o,n,i){let s=await Pn(),a=await this.lockHandler.handleBrowserConflict(e,t,s,o!==true);return a.resolved?{retryAfterClose:true,shouldRelaunch:a.shouldRelaunch}:(this.logExtractError(e,t,n,i),{retryAfterClose:false,shouldRelaunch:false})}logExtractError(e,t,o,n){let i=e instanceof Error?e.message:String(e);this.logger.debug(`Error reading Firefox cookie file ${t}`,{error:i,file:t,name:o,domain:n});}async performRetryAfterClose(e,t){this.logger.info("Retrying Firefox cookie extraction after browser close...");try{let o=await this.executeQueryWithNewUtilities(e);return this.logger.success("Successfully extracted cookies after closing Firefox"),t&&await this.lockHandler.relaunchBrowser(),o}catch(o){return this.logger.error("Failed to extract cookies even after closing Firefox",{error:o instanceof Error?o.message:String(o),file:e.file}),t&&await this.lockHandler.relaunchBrowser(),[]}}async processCookieFile(e,t,o,n){let i=await this.createCookieQueryConfig(t,o,e);try{return await this.executeQueryWithNewUtilities(i)}catch(s){let a=await this.handleCookieExtractionError(s,e,n,t,o);return a.retryAfterClose?this.performRetryAfterClose(i,a.shouldRelaunch):[]}}async executeQueryWithNewUtilities(e){let t=ve({retryAttempts:1,retryDelay:0,queryTimeout:100,enableMonitoring:true}),o=Ne();return t.executeQuery(e.file,n=>o.executeQuery(n,e.sql,e.params,e.file).map(e.rowTransform),e.sql)}async executeQuery(e,t,o,n){let i=o??Af(this.logger),s=Array.isArray(i)?i:[i];if(s.length===0)return this.logger.debug("No Firefox cookie files to query"),[];let a=[];for(let l of s){let u=await this.processCookieFile(l,e,t,n);a.push(...u);}return a}};var qe=class extends ${constructor(){super("opera");}};var He=class extends ${constructor(){super("opera-gx");}};O();E();O();var yt=util.promisify(child_process.exec),Ue=h("SystemPermissions");async function Df(){try{await yt('open "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles"'),Ue.info("Opened System Settings > Privacy & Security > Full Disk Access");}catch{try{await yt('open "x-apple.systempreferences:com.apple.preference.security?Privacy"'),Ue.info("Opened System Settings > Privacy & Security");}catch{await yt("open -b com.apple.systempreferences"),Ue.info("Opened System Settings");}}}function If(){let r=process.env.TERM_PROGRAM;return r==="iTerm.app"?"iTerm":r==="Apple_Terminal"?"Terminal":r==="vscode"?"Visual Studio Code":r??"your terminal application"}async function Ff(r,e){let t=Gn__default.default.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{console.log(`
|
|
57
|
+
\u26A0\uFE0F ${e} cookie access is blocked by macOS security.
|
|
58
|
+
|
|
59
|
+
To grant access, ${r} needs permission to read ${e} data.
|
|
60
|
+
|
|
61
|
+
Would you like to:
|
|
62
|
+
1. Open System Settings to grant permission (recommended)
|
|
63
|
+
2. Skip ${e} cookies for now
|
|
64
|
+
3. Exit
|
|
65
|
+
|
|
66
|
+
Please enter your choice (1/2/3): `),t.question("",n=>{t.close(),o(n.trim()==="1");});})}async function xt(r,e){if(!U()||!(P(r,"eperm")||P(r,"operation not permitted")||P(r,"permission denied")||P(r,"authorization denied")))return false;let o=e.appName||If();if(Ue.warn(`${e.browserName} cookie access denied by macOS`,{app:o,error:B(r)}),e.interactive!==false){if(await Ff(o,e.browserName)){await Df(),console.log(`
|
|
67
|
+
\u2705 System Settings opened to Privacy & Security
|
|
68
|
+
|
|
69
|
+
Please follow these steps:
|
|
70
|
+
1. Look for "${o}" in the list
|
|
71
|
+
2. If not present, click the "+" button and add it
|
|
72
|
+
3. Enable the toggle next to "${o}"
|
|
73
|
+
4. You may need to restart ${o} after granting permission
|
|
74
|
+
5. Then run this command again
|
|
75
|
+
|
|
76
|
+
Press Enter when you've completed these steps...`);let i=Gn__default.default.createInterface({input:process.stdin,output:process.stdout});return await new Promise(s=>{i.question("",()=>{i.close(),s();});}),true}}else Ue.info(`To grant ${e.browserName} access, add ${o} to System Settings > Privacy & Security > Full Disk Access`);return false}async function wt(r){try{let{exec:e}=await import('child_process'),{promisify:t}=await import('util');return await t(e)(`cat "${r}" > /dev/null 2>&1`),!0}catch{return false}}E();E();var Rr=zod.z.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"),_r=zod.z.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"),Vn=zod.z.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("/"),Kn=zod.z.string().trim().transform(r=>Lf__default.default(r)).pipe(zod.z.any()),Jn=zod.z.object({name:_r,value:Kn,domain:Rr,path:Vn,expiry:zod.z.number().int(),creation:zod.z.number().int(),flags:zod.z.number().optional(),version:zod.z.number().int().optional(),port:zod.z.number().int().optional(),comment:zod.z.string().optional(),commentURL:zod.z.string().optional()}),Nf=zod.z.object({name:_r,domain:Rr}).strict(),Mf=zod.z.object({file:zod.z.string().trim().min(1,"File path cannot be empty").optional(),browser:zod.z.string().trim().optional(),decrypted:zod.z.boolean().optional(),secure:zod.z.boolean().optional(),httpOnly:zod.z.boolean().optional(),path:Vn.optional()}).catchall(zod.z.unknown()).strict(),$f=zod.z.object({domain:Rr,name:_r,value:Kn,expiry:zod.z.union([zod.z.literal("Infinity"),zod.z.date(),zod.z.number().int().positive("Expiry must be a positive number")]).optional(),meta:Mf.optional()}).strict();zod.z.object({expiry:zod.z.number().int().optional(),domain:Rr,name:_r,value:zod.z.union([zod.z.string(),zod.z.instanceof(Buffer)])}).strict();zod.z.object({format:zod.z.enum(["merged","grouped"]).optional(),separator:zod.z.string().optional(),showFilePaths:zod.z.boolean().optional()}).strict();var Qf=zod.z.enum(["Chrome","Firefox","Safari","internal","unknown"]),qf=zod.z.object({browserName:Qf,queryCookies:zod.z.function().args(zod.z.string(),zod.z.string(),zod.z.string().optional(),zod.z.boolean().optional()).returns(zod.z.promise(zod.z.array($f)))}).strict(),Hf=zod.z.object({limit:zod.z.number().int().positive().optional(),removeExpired:zod.z.boolean().optional(),includeExpired:zod.z.boolean().optional(),store:zod.z.string().optional(),force:zod.z.boolean().optional()});Hf.extend({strategy:qf.optional()});var Uf=zod.z.enum(["chrome","chromium","edge","firefox","opera","brave","arc"]);Nf.extend({browser:Uf,exactDomain:zod.z.boolean().optional(),caseSensitive:zod.z.boolean().optional(),limit:zod.z.number().int().positive().optional(),includeExpired:zod.z.boolean().optional()});E();var re=h("BinaryCodableCookie"),Ir=class{constructor(e){this.version=0;this.url="";this.name="";this.path="";this.value="";this.flags={isSecure:false,isHTTPOnly:false,unknown1:false,unknown2:false};this.expiration=0;this.creation=0;let t={offset:0,buffer:e};this.decode(t);}decodeUrlValue(e){let t=e,o;do{o=t;try{t=decodeURIComponent(t);}catch{return o}}while(t!==o&&t.includes("%"));return t}decodeJwtPayload(e){let t=e.split(".");if(t.length!==3)return null;try{let o=t[1];if(!o)return null;let n=buffer.Buffer.from(o,"base64").toString("utf8"),i=JSON.parse(n);return JSON.stringify(i)}catch{return null}}parseJsonValue(e){try{let t=JSON.parse(e);return JSON.stringify(t)}catch{return null}}processValue(e){let t=this.handlePrimitiveValues(e);if(t!==null)return t;let o=e,n=this.decodeUrlValue(o);return this.trySpecializedDecoding(n)}handlePrimitiveValues(e){return e===null?"null":e===void 0?"undefined":buffer.Buffer.isBuffer(e)?e.toString():typeof e!="string"?this.safeStringify(e):null}trySpecializedDecoding(e){let t=this.tryJwtDecoding(e);if(t!==null)return t;let o=this.tryJsonDecoding(e);return o!==null?o:e}tryJwtDecoding(e){if(e.match(/^ey[A-Za-z0-9_-]+\.ey[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/)){let t=this.decodeJwtPayload(e);if(typeof t=="string"&&t.length>0)return t}return null}tryJsonDecoding(e){if(e.startsWith("{")||e.startsWith("[")){let t=this.parseJsonValue(e);if(typeof t=="string"&&t.length>0)return t}return null}safeStringify(e){try{return typeof e=="object"&&e!==null?JSON.stringify(e):String(e)}catch{return String(e)}}convertMacTimestamp(e){return e<=0?e:e>=0&&e<=1e9&&Number.isFinite(e)?e+978307200:0}toCookieRow(){try{let e=this.convertFlags(),t=this.url.replace(/^https?:\/\//,"").replace(/\/.*$/,"")||"uk",o=this.convertMacTimestamp(this.expiration),n=this.convertMacTimestamp(this.creation);return Jn.parse({name:this.name.replace(/^: /,""),value:this.processValue(this.value)||"",domain:t,path:this.path||"/",expiry:o,creation:n,flags:e,version:this.version,port:this.port,comment:this.comment,commentURL:this.commentURL})}catch{return null}}readHeader(e){let t=e.buffer.readUInt32LE(e.offset);re.debug("Cookie size:",t),e.offset+=4;let o=e.buffer.readUInt32LE(e.offset);re.debug("Cookie version:",o),e.offset+=4;let n=e.buffer.readUInt32LE(e.offset);re.debug("Cookie flags:",n.toString(2).padStart(8,"0")),e.offset+=4,this.flags={isSecure:(n&1)!==0,isHTTPOnly:(n&4)!==0,unknown1:(n&8)!==0,unknown2:(n&16)!==0};let i=e.buffer.readUInt32LE(e.offset);re.debug("Has port:",i),e.offset+=4;let s={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 re.debug("String offsets:",s),{size:t,hasPort:i,offsets:s}}readTimestamps(e){let t=buffer.Buffer.alloc(8);for(let s=0;s<8;s++)t[s]=e.buffer[e.offset+s];let o=t.readDoubleLE(0);e.offset+=8;let n=buffer.Buffer.alloc(8);for(let s=0;s<8;s++)n[s]=e.buffer[e.offset+s];let i=n.readDoubleLE(0);e.offset+=8,this.expiration=o,this.creation=i;}readStrings(e,t,o){re.debug("Reading strings from cookie buffer of size:",t);let i=[{field:"url",offset:o.urlOffset},{field:"name",offset:o.nameOffset},{field:"path",offset:o.pathOffset},{field:"value",offset:o.valueOffset},{field:"comment",offset:o.commentOffset}].filter(s=>s.offset>0).sort((s,a)=>s.offset-a.offset);re.debug("Reading strings in order:",i.map(s=>s.field));for(let s=0;s<i.length;s++){let a=i[s],{field:l,offset:u}=a,m=(s<i.length-1?i[s+1].offset:t)-u,g=0+u;for(;g<0+u+m&&e.buffer[g]!==0;)g++;let d=e.buffer.toString("utf8",0+u,g);switch(re.debug(`Read ${l}:`,d),l){case "url":this.url=d;break;case "name":this.name=d;break;case "path":this.path=d;break;case "value":this.value=d;break;case "comment":this.comment=d;break}}}decode(e){let{size:t,hasPort:o,offsets:n}=this.readHeader(e),i=e.offset;e.offset=i+24,this.readTimestamps(e),o>0&&(this.port=e.buffer.readUInt16LE(e.offset),e.offset+=2),e.offset=i,this.readStrings(e,t,n);}convertFlags(){return (this.flags.isSecure?1:0)|(this.flags.isHTTPOnly?4:0)|(this.flags.unknown1?8:0)|(this.flags.unknown2?16:0)}};var Q=h("BinaryCodablePage"),Pe=class Pe{constructor(e){this.cookies=[];let t={offset:0,buffer:e};this.decode(t);}toCookieRows(){let e=[];for(let t of this.cookies)try{let o=t.toCookieRow();o!==null&&e.push(o);}catch(o){let n=o instanceof Error?o.message:String(o);le("BinaryCookies","Error converting cookie",{error:n});}return e}decode(e){let t=e.buffer.readUInt32BE(e.offset);if(Q.debug("Page header:",t.toString(16)),e.offset+=4,t!==Pe.HEADER)throw new Error("Invalid page header");let o=e.buffer.readUInt32LE(e.offset);Q.debug("Cookie count:",o),e.offset+=4;let n=e.offset-8;Q.debug("Page start offset:",n);let i=[];for(let a=0;a<o;a++){let l=e.buffer.readUInt32LE(e.offset);i.push(l),Q.debug(`Cookie ${a} offset:`,l),e.offset+=4;}let s=e.buffer.readUInt32BE(e.offset);if(Q.debug("Page footer:",s.toString(16)),e.offset+=4,s!==Pe.FOOTER)throw new Error("Invalid page footer");for(let a=0;a<o;a++)try{let l=i[a];Q.debug(`Reading cookie ${a} at offset:`,l);let u=e.buffer.readUInt32LE(l);if(Q.debug(`Cookie ${a} size:`,u),u<48){Q.warn(`Invalid cookie size ${u} at index ${a}`);continue}if(l+u>e.buffer.length){Q.warn(`Cookie size ${u} at index ${a} would exceed buffer length ${e.buffer.length}`);continue}let c=e.buffer.subarray(l,l+u),m=new Ir(c);this.cookies.push(m);}catch(l){Q.warn("Invalid cookie data",{error:l instanceof Error?l.message:String(l)});}}};Pe.HEADER=256,Pe.FOOTER=0;var Fr=Pe;var te=h("BinaryCodableCookies"),q=class q{constructor(e){let t={offset:0,buffer:e};this.pages=[],this.metadata={},this.decode(t);}static fromFile(e){let t=fs$1.readFileSync(e);return new q(t)}static fromDefaultPath(){return q.fromFile(q.DEFAULT_COOKIE_PATH)}toCookieRows(){let e=[];for(let t of this.pages)try{let o=t.toCookieRows();Array.isArray(o)&&e.push(...o);}catch(o){let n=o instanceof Error?o.message:String(o);le("BinaryCookies","Error converting page cookies",{error:n});}return e}decode(e){try{let t=e.buffer.subarray(e.offset,e.offset+4);if(e.offset+=4,te.debug("Magic bytes:",t.toString()),!t.equals(q.MAGIC))throw new Error("Missing magic value");let o=e.buffer.readUInt32BE(e.offset);te.debug("Page count:",o),e.offset+=4;let n=[];for(let l=0;l<o;l++){let u=e.buffer.readUInt32BE(e.offset);n.push(u),te.debug(`Page ${l} size:`,u),e.offset+=4;}let i=e.offset;te.debug("Starting page data at offset:",i);for(let l of n)try{te.debug("Reading page at offset:",i,"with size:",l);let u=e.buffer.subarray(i,i+l),c=new Fr(u);this.pages.push(c),i+=l;}catch(u){let c=u instanceof Error?u.message:String(u);te.warn("Error decoding page:",{error:c}),i+=l;}e.offset=i;let s=e.buffer.readUInt32BE(e.offset);te.debug("Checksum:",s.toString(16)),e.offset+=4;let a=e.buffer.readBigUInt64BE(e.offset);te.debug("Footer:",a.toString(16)),e.offset+=8,a!==q.FOOTER&&le("BinaryCookies","Invalid cookie file format: wrong footer"),this.metadata={};}catch(t){let o=t instanceof Error?t.message:String(t);throw le("BinaryCookies","Error decoding binary cookies file",{error:o}),t}}};q.MAGIC=buffer.Buffer.from("cook","utf8"),q.FOOTER=BigInt("0x071720050000004b"),q.DEFAULT_COOKIE_PATH=path.join(os$1.homedir(),"Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies");var Lr=q;function Yn(r){return Lr.fromFile(r).toCookieRows()}var je=class extends Z{constructor(){super("SafariCookieQueryStrategy","Safari"),this.lockHandler=new X(this.logger,"Safari");}getCookieDbPath(e){return path.join(e,"Library","Containers","com.apple.Safari","Data","Library","Cookies","Cookies.binarycookies")}formatDomain(e){return e==null||typeof e!="string"?"":e.startsWith(".")?e.slice(1):e}formatExpiry(e){return e==null?void 0:typeof e!="number"||Number.isNaN(e)||e<=0?"Infinity":e<0||e>4102444800?(this.logger.warn("Invalid expiry timestamp, treating as session cookie",{expiry:e}),"Infinity"):new Date(e*1e3)}isFlagSet(e,t){return typeof e!="number"||Number.isNaN(e)||e<=0?false:(e&t)===t}formatCreation(e){if(typeof e!="number"||Number.isNaN(e)||e<=0)return;if(e<0||e>4102444800){this.logger.warn("Invalid creation timestamp, ignoring",{creation:e});return}return e*1e3}processValue(e){if(e===null)return "null";if(e===void 0)return "undefined";if(Buffer.isBuffer(e))return e.toString();if(typeof e=="object")try{return JSON.stringify(e)}catch{return "[object]"}return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"[unknown value]"}async decodeCookies(e,t,o,n){try{if(!await this.checkAndHandlePermissions(e,n))return [];let s=Yn(e);return this.processCookies(s,t,o,e)}catch(i){return this.handleDecodingError(i,e,t,o,n)}}async checkAndHandlePermissions(e,t){return await wt(e)?true:(this.logger.warn("Cannot access Safari cookies due to macOS permissions",{file:e,suggestion:"Terminal application needs Full Disk Access permission"}),await xt(new Error("EPERM: operation not permitted"),{appName:process.env.TERM_PROGRAM??"Terminal",browserName:"Safari",interactive:t!==true})?await wt(e)?true:(this.logger.error("Still cannot access Safari cookies after permission attempt",{file:e,advice:"Please restart your terminal application after granting Full Disk Access"}),false):false)}processCookies(e,t,o,n){return e.filter(i=>this.matchesCriteria(i,t,o)).map(i=>this.mapToExportedCookie(i,n))}matchesCriteria(e,t,o){if(!this.isCookieObject(e))return false;let n=this.formatDomain(e.domain);if(n==="")return false;let i=t==="%"||e.name===t,s=o==="%"||n.includes(o);return i&&s}isCookieObject(e){return typeof e=="object"&&e!==null&&"name"in e&&typeof e.name=="string"}mapToExportedCookie(e,t){let o=e;return {domain:this.formatDomain(o.domain),name:o.name,value:this.processValue(o.value),expiry:this.formatExpiry(o.expiry),meta:{file:t,browser:"Safari",decrypted:false,secure:this.isFlagSet(o.flags,1),httpOnly:this.isFlagSet(o.flags,4),path:o.path??void 0,version:o.version===void 0?void 0:o.version,comment:o.comment??void 0,commentURL:o.commentURL??void 0,port:o.port===void 0?void 0:o.port,creation:this.formatCreation(o.creation)}}}async handleDecodingError(e,t,o,n,i){return P(e,"EPERM")||P(e,"operation not permitted")||P(e,"Permission denied")?await this.handlePermissionError(e,t,o,n,i):this.logDecodingError(e,t,o,n),[]}async handlePermissionError(e,t,o,n,i){await xt(e,{appName:process.env.TERM_PROGRAM??"Terminal",browserName:"Safari",interactive:i!==true})?this.logger.info("Permission flow completed. Please run the command again after granting access."):this.logger.warn(`Permission denied accessing Safari cookies at ${t}`,ce(e,{file:t,name:o,domain:n,advice:"Grant Full Disk Access to your terminal in System Settings > Privacy & Security"}));}logDecodingError(e,t,o,n){this.logger.error(`Error decoding ${t}`,ce(e,{file:t,name:o,domain:n}));}async executeQuery(e,t,o,n){if(!U())return this.logger.debug("Safari strategy skipped on non-macOS platform"),[];try{this.logger.info("Querying cookies",{name:e,domain:t,store:o});let i=os$1.homedir();if(!this.isValidHomeDirectory(i))return [];let s=o??this.getCookieDbPath(i),a=e||"%",l=t||"%",u=await this.attemptDecodeWithLockHandling(s,a,l,n);return u.success?u.cookies:u.shouldRetry?this.retryAfterBrowserClose(s,a,l,n,u.shouldRelaunch):[]}catch(i){return this.logQueryError(i,e,t),[]}}isValidHomeDirectory(e){return typeof e!="string"||e.length===0?(this.logger.error("Failed to get home directory"),false):true}async attemptDecodeWithLockHandling(e,t,o,n){try{return {success:!0,cookies:await this.decodeCookies(e,t,o,n),shouldRetry:!1,shouldRelaunch:!1}}catch(i){return this.handleLockConflict(i,e,n)}}async handleLockConflict(e,t,o){if(!this.isLockError(e))throw e;let n=await On(),i=await this.lockHandler.handleBrowserConflict(e,t,n,o!==true);return i.resolved?{success:false,cookies:[],shouldRetry:true,shouldRelaunch:i.shouldRelaunch}:(this.logger.warn("Safari cookie file locked",ce(e,{file:t,advice:"Safari may be accessing the cookie file. Try closing Safari and running again."})),{success:false,cookies:[],shouldRetry:false,shouldRelaunch:false})}isLockError(e){return P(e,"EPERM")||P(e,"operation not permitted")||P(e,"Permission denied")||P(e,"EBUSY")}async retryAfterBrowserClose(e,t,o,n,i){try{this.logger.info("Retrying Safari cookie extraction after browser close...");let s=await this.decodeCookies(e,t,o,n);return this.logger.success("Successfully extracted cookies after closing Safari"),i===!0&&await this.lockHandler.relaunchBrowser(),s}catch(s){return this.handleRetryFailure(s,e,i)}}async handleRetryFailure(e,t,o){return this.logger.error("Failed to extract cookies even after closing Safari",ce(e,{file:t})),o===true&&await this.lockHandler.relaunchBrowser(),[]}logQueryError(e,t,o){this.logger.error("Failed to query cookies",ce(e,{name:t,domain:o}));}};var ue=h("StrategyFactory"),Jf={safari:je,firefox:Qe,chrome:ae,edge:$e,arc:Me,opera:qe,"opera-gx":He};function Zn(r){let e=Jf[r];return e?(ue.debug("Creating browser strategy",{browser:r}),new e):(ue.warn("Unknown browser type, falling back to default",{browser:r}),new ae)}function Yf(){ue.debug("Creating composite strategy with all browsers");let r=[new ae,new $e,new Me,new qe,new He,new Qe,new je];return new Tr(r)}function Xn(r){let{browser:e,storePath:t,profile:o}=r||{};if(t&&!e){let n=Er(t);if(n)return ue.info("Auto-detected browser from store path",{browser:n,storePath:t}),Zn(n)}if(e){let n=e.toLowerCase();if(kn(n))return n==="chrome"&&o?(ue.debug("Creating Chrome strategy with profile",{profile:o}),new ae(o)):Zn(n);ue.warn("Invalid browser type specified",{browser:e});}return ue.debug("Creating composite strategy as default"),Yf()}var ei={detectStoreType(r){return Er(r)},createStrategy(r,e,t){let o={};return r!==void 0&&(o.browser=r),e!==void 0&&(o.storePath=e),t!==void 0&&(o.profile=t),Xn(o)}};async function Zf(r,e,t){let o=[];for(let n of e){let i=await r.queryCookies(n,t);if(o=[...o,...i],typeof t.limit=="number"&&t.limit>0&&o.length>=t.limit){o=o.slice(0,t.limit);break}}if(t.deduplicateCookies&&o.length>0){let n=new Map;for(let i of o){let s=`${i.name}:${i.domain}`,a=n.get(s);a?i.value.length>a.value.length&&n.set(s,i):n.set(s,i);}o=Array.from(n.values());}return o}function Xf(r,e,t,o,n,i){let s={removeExpired:t,deduplicateCookies:o,strategy:e},a=typeof r.force=="boolean"?r.force:false;return i!==void 0&&(s.store=i),a&&(s.force=a),s}async function ri(r,e,t,o=false,n,i=true){try{let s=typeof r.browser=="string"?r.browser:void 0,a=typeof r.profile=="string"?r.profile:void 0,l=ei.createStrategy(s,n,a),u=new kr(l),c=Array.isArray(e)?e:[e],m=Xf(r,l,o,i,t,n),g=await Zf(u,c,m);if(g.length===0){f.error("No results");let w=typeof r.profile=="string"?r.profile:void 0,D=typeof r.browser=="string"?r.browser:void 0;w&&D&&(f.error(`Could not find cookies for profile: ${w}`),f.error(`Try 'get-cookie --browser ${D} --list-profiles' to see available profiles`));return}new Sr().getHandler(r).handle(g);}catch(s){f.error(B(s));}}function ti(){f.log("Usage: get-cookie [name] [domain] [options]"),f.log("Build: 2025-09-07 17:25:20 UTC (release/4.4.0)"),f.log(""),f.log("Examples:"),f.log(" get-cookie auth example.com # Get specific cookie"),f.log(" get-cookie % github.com --output json # Get all cookies as JSON"),f.log(" get-cookie --url https://example.com # Extract from URL"),f.log(""),f.log("Options:"),f.log(" -h, --help Show this help message"),f.log(" -v, --verbose Enable verbose output"),f.log(" -f, --force Force operation despite warnings (e.g., locked databases)"),f.log(" --list-profiles List available browser profiles (use with --browser)"),f.log(""),f.log("Query options:"),f.log(" -n, --name PATTERN Cookie name pattern (% for wildcard)"),f.log(" -D, --domain PATTERN Cookie domain pattern"),f.log(" -u, --url URL URL to extract cookie specs from"),f.log(" --browser BROWSER Target specific browser (chrome|edge|arc|opera|opera-gx|firefox|safari)"),f.log(" --profile NAME Target specific Chrome profile by name (e.g., 'Default', 'Profile 1')"),f.log(" --store PATH Path to a specific cookie store file"),f.log(" --include-expired Include expired cookies (filtered by default)"),f.log(" --include-all Include all duplicate cookies (newest only by default)"),f.log(""),f.log("Output options:"),f.log(" --output FORMAT Output format (json)"),f.log(" -d, --dump Dump all cookie details"),f.log(" -G, --dump-grouped Dump all results, grouped by profile"),f.log(" -r, --render Render all results in formatted output");}function ec(r,e){return {name:r||"%",domain:e||"%"}}function oi(r){return r==="*"?"%":r}function rc(r){if(!r){f.error("Please specify a browser with --browser"),f.log("Example: get-cookie --browser chrome --list-profiles");return}let e=r.toLowerCase();if(e==="chrome"||e==="edge"||e==="arc"||e==="opera"||e==="opera-gx")try{let t=Et();if(t.length===0){f.log(`No ${r} profiles found`);return}f.log(`${r} profiles:`),f.log("");let o=Be("fs"),n=Be("path"),i=Be("os"),s,a=process.platform;if(a==="darwin"){let u=i.homedir();switch(e){case "chrome":s=n.join(u,"Library","Application Support","Google","Chrome");break;case "edge":s=n.join(u,"Library","Application Support","Microsoft Edge");break;case "arc":s=n.join(u,"Library","Application Support","Arc");break;case "opera":s=n.join(u,"Library","Application Support","com.operasoftware.Opera");break;case "opera-gx":s=n.join(u,"Library","Application Support","com.operasoftware.OperaGX");break;default:s=n.join(u,"Library","Application Support","Google","Chrome");}}else if(a==="win32"){let u=process.env.LOCALAPPDATA||n.join(i.homedir(),"AppData","Local");switch(e){case "chrome":s=n.join(u,"Google","Chrome","User Data");break;case "edge":s=n.join(u,"Microsoft","Edge","User Data");break;default:s=n.join(u,"Google","Chrome","User Data");}}else {let u=i.homedir();switch(e){case "chrome":s=n.join(u,".config","google-chrome");break;default:s=n.join(u,".config","google-chrome");}}let l=n.join(s,"Local State");if(o.existsSync(l)){let c=JSON.parse(o.readFileSync(l,"utf8")).profile?.info_cache||{};for(let[m,g]of Object.entries(c)){let d=g;f.log(` \u2022 ${d.name}`),f.log(` Directory: ${m}`),d.user_name&&f.log(` User: ${d.user_name}`),f.log("");}}else t.forEach(u=>{f.log(` \u2022 ${u.name}`),u.user_name&&f.log(` User: ${u.user_name}`),f.log("");});}catch(t){f.error(`Failed to list ${r} profiles:`,t instanceof Error?t.message:"Unknown error");}else e==="firefox"?(f.log("Firefox profile listing is not yet implemented"),f.log("Firefox stores profiles in different locations based on the platform")):e==="safari"?(f.log("Safari does not use named profiles"),f.log("Safari uses the system keychain for the current user")):f.error(`Unknown browser: ${r}`);}function tc(r,e){let t=r.url;if(typeof t=="string"){let i=Hr(t);return Array.isArray(i)?i:(f.error("Invalid cookie specs from URL"),[])}let o=oi(r.name??e[0]??"%"),n=oi(r.domain??e[1]??"%");return [ec(o,n)]}async function oc(r,e){let t=tc(r,e);r.verbose===true&&f.log("cookieSpecs",t);try{let o=r["include-expired"]!==!0,n=r["include-all"]!==!0;await ri(r,t,void 0,o,r.store,n);}catch(o){o instanceof Error?f.error("Error querying cookies:",o.message):f.error("An unknown error occurred while querying cookies");}}async function nc(){let r=process.argv.slice(2);if(r.length===0){ti();return}let{values:e,positionals:t}=Pt(r);if(e.help===true){ti();return}if(e["list-profiles"]===true){let o=typeof e.browser=="string"?e.browser:void 0;rc(o);return}await oc(e,t);}nc().catch(r=>{r instanceof Error?f.error("Fatal error:",r.message):f.error("An unknown fatal error occurred"),process.exit(1);});
|
|
4
77
|
/*! Bundled license information:
|
|
5
78
|
|
|
6
79
|
lodash-es/lodash.js:
|
|
@@ -13,5 +86,5 @@ lodash-es/lodash.js:
|
|
|
13
86
|
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
|
|
14
87
|
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
|
|
15
88
|
*)
|
|
16
|
-
|
|
89
|
+
*///# sourceMappingURL=cli.cjs.map
|
|
17
90
|
//# sourceMappingURL=cli.cjs.map
|