Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- in-browser client side html5 webproxy environment (sub_env_api.js) (unfinished)
- NOTE: this is a work in progress, it is currently unfinished and not fully or at all functional.
- This sub-environment api was written by the Transcendentian.
- It is open-source, so you may use it, modify it etc.
- right now it (this script) needs (requires) my main.js (https://docs.google.com/uc?id=0Bxb5iFgmM3V6eTRINGZ0Zm1zMkk) to be already (pre) loaded in order for it to run.
- The purpose of this api is to load and run webpages and/or resources in a sub-environment of another webpage. Uses include, a proxy page that runs javascript without the website being proxied knowing that it's being proxied, hugely expanded cors capabilities (is disabled in the sub environment) (example: draw a cross-origin image to a canvas and then access ctx.getImageData() );
- */
- //properly undepricate __proto__:
- (function(w){var O=w.Object,Op=O?O.prototype:!1,po="__proto__",dGS=["__define","etter__"],eP="etPrototypeOf";
- if(!(po in w)){
- Op[dGS.join("G")](po,function(){return O["g"+eP](this);});
- Op[dGS.join("S")](po,function(v){O["g"+eP](this,v);});
- }}(self));
- //if(typeof self.phpact!="function")TJA.require("https://docs.google.com/uc?id=0Bxb5iFgmM3V6azZVQmpTb295bGM"); //include 2php.js
- //String.prototype.iindexOf=function(s){return this.toLowerCase().indexOf(s.toLowerCase());};//non-case-sensative indexOf
- var rp=function(s,f,r){return s.split(f).join(r);},//replace
- /* PHP code:
- https://pastebin.com/raw/TQ0Jt7pK
- no longer using php code, using https://raw-http-api.thetranscendent.repl.co/ instead
- */
- p2_="code_g2.php",
- prsHdrs=function(hs){var ho={},h,ci;
- hs=hs.split("\r\n");
- while(hs.length){h=hs.pop();if((ci=h.indexOf(": "))+1)ho[h.substr(0,ci).toLowerCase()]=h.substr(ci+2);}
- return ho;
- },
- allcookies=[],
- HttpReq=function(meh,url,callback,ehdrs,bdy){
- var cb2=function(r){var bgn=TJA.unArrBuf(r.slice(0,20)),rsp={"ERRS":[],"headers":{},"sc":0};
- if(bgn.substr(0,4)=="HL: "){var LL=bgn.indexOf("\r\n"),HL=bgn.substring(4,LL)*1;if(HL){
- var RHL=HL+2+LL,HS=TJA.unArrBuf(r.slice(LL+2,RHL)),
- fl,CU,rul=[],rdr=HS.split("\r\n\r\n"); rdr.pop();
- rsp.body=r.slice(RHL);
- if(rdr.length){HS=rdr[rdr.length-1];
- rdr.slice(1).forEach(function(rd){var lns=rd.split("\r\n"),fl=lns[0].split(" ");CU=fl[1];rul.push(fl[1]);lns.shift();
- lns.forEach(function(rl){if(rl.length>12&&rl.substr(0,12).toLowerCase()=="set-cookie: "){
- //save cookies
- var buf=rl.substr(12),fe=buf.indexOf("="),si=buf.indexOf(";"),dt,buft,ph,tc={"name":buf.substr(0,fe),"value":buf.substring(fe+1,si)};buf=buf.substr(si+1);
- dt=TJA.gurl(buft=buf.toLowerCase(), "expires=", ";");
- tc.exp=dt.length?(new Date(dt)).getTime():"sess";
- if((!dt.length)||(new Date()).getTime()<tc.exp){
- tc.domain=TJA.gurl(buft, "domain=", ";");
- if(!tc.domain.length) tc.domain=TJA.gurl(fl[1], "://", "/");
- tc.path=(ph=TJA.gurl(buf, "path=", ";")).length?ph:fl[1].substr(fl[1].indexOf("/",9));
- allcookies.push(tc);
- }
- }});
- });
- rsp.redirects=rul;
- }
- rsp.currentUrl=CU||url;
- rsp.headers=prsHdrs(HS);
- rsp.sc=HS.split("\r\n")[1].split(" ")[1];
- }else rsp.body=r.slice(LL+2);}
- callback.call(this,rsp);},
- u2=phpact.bu+"/"+p2_+"/"+url,hdr=[["x-nope","cookie,referer,origin,x-real-ip"]];
- if(typeof ehdrs=="object")for(var H in ehdrs)hdr.push(["X-A-"+H,ehdrs[H]]);
- TJA.XHR(meh,u2,cb2,hdr,bdy).onerror=function(){var st=this.status;
- if(st===0||st>390){
- //phpact('$tmp=fopen("'+p2_+'","w");fwrite($tmp,file_get_contents("https://pastebin.com/raw/TQ0Jt7pK"));fclose($tmp);echo "Did.";', function(r){if((r=TJA.unArrBuf(r))=="Did.")TJA.XHR(meh,u2,cb2,hdr,bdy);else alert("Error: "+r);});
- //no phpact, using repl now, use start the repl
- }
- };
- };
- // BEGIN AWESOME:
- var blobs={},haz_url=[], //The blobs object includes fetched files as blobs, with the 'real' url as the property name. use blobs[url].burl to get a blob url of a cached file; haz_url is an Array of Element constructors that need href or src, each item has format {"n":constructor_funct(){}.name,"m":"href"||"src"}
- Omap=new WeakMap(); //match iframes to their 'real' origins, url-fetching HTML elements to their real urls
- /*note: this section is part of the "engine" code,
- it will only run one time when the proxy system is loading
- then the virtual proxied pages that are running in the proxy system will all rely on
- functions and properties that are defined in the "engine"
- */
- /* use new Proxy() insteand of fantasmic
- fantasmic=function(O,p,rgf,rsf,o2){ //O==object, p=property, rgf=replace get function, rsf=replace set function;
- var od=Object.getOwnPropertyDescriptor(O,p),y,G=od.get,S=od.set;
- if(y=typeof rgf=="function")od.get=function(){rgf.call(this,G);};
- if(y=typeof rsf=="function")od.set=function(v){rsf.call(this,S,v);};
- if(y)Object.defineProperty(o2||O,p,od);
- //please note, rgf & rsf accept an extra argument, the first, the old function they replace, and in rsf the set-to value is the 2nd argument instead of the first like a regular getter
- return od;},
- fillN=function(to,so,not){not=not||{}; //put fill'n in some objects (use to make passthrus)
- //forget it, use new Proxy()
- },
- siMLp=function Simple_ML_parser(s){
- //forget it, use nullIframe
- },
- siMLs=function Simple_ML_stringify(ML){//forget it, use nullIframe
- }; */
- //need src (get/set)ter: HTMLVideoElement,HTMLTrackElement,HTMLSourceElement,HTMLScriptElement,HTMLMediaElement,HTMLInputElement,Image,HTMLImageElement,HTMLIFrameElement,HTMLFrameElement,HTMLEmbedElement,Audio,HTMLAudioElement,webkitSpeechGrammar
- //need href /\ : URL,StyleSheet,SVGUseElement,SVGTextPathElement,SVGScriptElement,SVGRadialGradientElement,SVGPatternElement,SVGLinearGradientElement,SVGImageElement,SVGGradientElement,SVGFilterElement,SVGFEImageElement,SVGAElement,HTMLLinkElement,HTMLBaseElement,HTMLAreaElement,HTMLAnchorElement,CSSStyleSheet,CSSImportRule,SVGMPathElement
- /*note: the .href and .src and form.action properties always returns the "effective" url in javascript even if full URL is not set
- ex: anchor1.href="/aa";
- anchor1.href will now return "https://www.example.com/aa"
- HTMLBaseElement can fix this for all except form.action
- //awesome works:
- self.a1=["a","b","c"];
- var [do1,v2,v3]=a1;
- do1
- "a"
- v2
- "b"
- v3
- "c"
- */
- var ref_ifr=document.createElement("iframe"); //use this as a reference for a browsers window's normal state
- document.body.appendChild(ref_ifr);ref_ifr.style.display="none";
- (function(){ //main iframe (use to get initial window properties)
- var ins=new WeakSet(),cw=ref_ifr.contentWindow,ifrp=Object.getOwnPropertyNames(cw);
- for(let v of ifrp){var V=cw[v],Vp,m;if(typeof V=="function"&&(Vp=V.prototype)&&v!="HTMLAnchorElement"&&((m="src" in Vp)||"href" in Vp)){m=m?"src":"href";
- var pd=Object.getOwnPropertyDescriptor(Vp,m);
- if(pd&&(!ins.has(pd))){pd.n=v;pd.m=m;haz_url.push(pd);ins.add(pd);}
- }else if(v.substr(0,2)=="on"){}
- }
- })();
- //don't 4get HTMLFormElement.action
- //note: a global, real-top-level function that takes the sub_env window's "self" object & 'fake' url as an arguments and outputs any array of: [alt_self,new_ndp]
- //will include at beggining of all sub-page <head> s:
- var sph_bgn=function(SELF,_url){ //include document.sub_env=sph_bgn(self,"url to show in js"); contents at beggining of <head> of fetched html, because of document.location, the document object must be replaced with a passthru (Proxy) copy, so simply don't include sub_env in the passthru
- //
- var alt_self={"document":{"__proto__":SELF.document.__proto__},"top":{/*top it off*/}, /* << to name a few; wait.. make this a pass thru 2 the real stuff, filtering out only location/url related stuff. Don't 4get to filter src, href, and therefore (get/set)Attribute. make document.origin && self.origin (get/set)ers*/
- "location":{"__proto__":Location,"ancestorOrigins":{"__proto__":DOMStringList,"length":0},"assign":function(v){location2.s(SELF.location.assign,v);}}
- },
- new_ndp=function(so){ //new non-deleteable-properties; source-object; (replaces 'var' declaration); like Object.assign(self,{}) except better
- for(var p in so){Object.defineProperty(alt_self,p,{value:so[p],writable:!0,enumerable:!0});}
- };
- //note: may use random names for those 2 vars in altered sub_env code /\ /\
- if("sessionStorage" in SELF){//sessionStorage is full url including ? querry but not #hash; localStorage is origin only including protocol
- Object.assign(alt_self.location)
- }
- var wait_=function(f){if(typeof f=="function")while(f())!0;},
- KNOT=("location,document,origin,self,window,top").split(","),
- vaaAaar=function(P){if(KNOT.indexOf(P)<0&&(!(P in SELF)))Object.defineProperty(SELF,P,{"get":function(){return alt_self[P];},"set":function(v){alt_self[P]=v;}});
- },
- /*NOTE: use new URL(path,base); https://developer.mozilla.org/en-US/docs/Web/API/URL to create a base object to help make the new fake location object; have no way for scripts running in sub env to run location="http://example.com", only self.location="http://example.com" will work because of the way get/setters are defined
- maybe use something like
- const location={};
- try{ loction="a" }catch(e){ var stk=e.stack.substr(e.stack.indexOf(" at ")+4).split(":"); [functionname,line,character]
- //find and manually assign location
- }
- Object.keys(URL.prototype)
- (14) ["href", "origin", "protocol", "username", "password", "host", "hostname", "port", "pathname", "search",
- "searchParams",
- "hash",
- "toJSON",
- "toString"]
- Object.keys(location)
- (14) [
- "replace", "assign",
- "href",
- "ancestorOrigins",
- "origin", "protocol", "host", "hostname", "port", "pathname", "search", "hash", "reload", "toString"]
- don't 4get:
- location.toString=function(){ return "proxied location"; };
- so that location+"" will produce expected output
- */
- location2={"s":function(oLs,url){ /*use a general location change function for this & for link click*/ },"g":function(oLg){ /*location get function for document.location*/ return alt_self.location;}},
- Elp=SELF.Element.prototype,
- EvTp=SELF.EventTarget.prototype,
- oldie={aEvntLst:Elp.addEventListener,rEvntLst:Elp.removeEventListener,/*gEvntLsts:SELF.getEventListeners,*/pstMsg:SELF.postMessage,
- inrHTML:Object.getOwnPropertyDescriptor(Elp,"innerHTML"),
- sAtr:Elp.setAttribute,gAtr:Elp.getAttribute},
- ClkE_=function(e){var tar=e.target||e.srcElement; if(tar.nodeName=="A"){e.preventDefault();
- //do link stuff (make main page fetch link resource); I can use this so that I don't have to change Anchor Element "href"s
- }};
- SELF.addEventListener("click",ClkE_,!1); //catch link-click in event bubble phase
- //fourtunately oldie.gEvntLsts returns a regular Object with each event type that has listener(s) as a regular Array, of regular Objects like: {listener:func, useCapture: false, passive: false, once: false, type: "message"}
- // no no no , we don't do getEventListeners because it's not a 'real' function, it is a dev-tools api only
- (EvTp.addEventListener=function(e,f,c){if(e=="message"){
- //do something with e.source (the source window) to get fake origin?
- var F_=function(E){/* call f with element as 'this' */},use_=Omap.get(f);F_.real=f;if(!use_)Omap.set(f,use_={'elms':(new WeakMap()),'n':0}); if(!use_.elms.has(this)){use_.elms.set(this,F_);use_.elms.n++;}
- oldie.aEvntLst.call(this,e,F_,c); //woah, a 2 diminsional WeakMap [Listener].elms[TargetElement]
- }else oldie.aEvntLst.apply(this,arguments);}).toString=SELF.toString.bind(oldie.aEvntLst);
- (EvTp.removeEventListener=function(e,f,c){if(e=="message"){
- //remove my hidden function
- var elms=Omap.get(f).elms,hf; if(elms){
- oldie.rEvntLst.call(this,e,hf=elms.get(this),c);
- if(hf){elms.n--; //count instances of a function on different elements and remove the function key in Omap when there are no Listeners Listening
- elms.delete(this); if(elms.n<1)Omap.delete(f); } }
- }else oldie.rEvntLst.apply(this,arguments);
- }).toString=SELF.toString.bind(oldie.rEvntLst);
- /*(SELF.getEventListeners=function(){Lrs=oldie.gEvntLsts.apply(this,arguments);
- if(Lrs.message)Lrs.message.forEach(function(v,i,a){a[i]=v.real;});
- if(Lrs.click)Lrs.click=Lrs.click.clean(ClkE_); //clean is from main.js
- return Lrs;}).toString=SELF.toString.bind(oldie.gEvntLsts);*/
- //this function \/ helps 'declare' global variables (need because of self.newvarname=1;) << I don't think this works
- var DkLrI=setInterval(function DkLr(){
- for(var p in alt_self)vaaAaar(p);
- },0);
- Object.defineProperty(alt_self.document,fantasmic(self,"location",location2.g,location2.s,alt_self));
- var atrd=function(A,T){var a=["src","href"],M;return ((M=a.indexOf(A.toLowerCase()))+1)&&T.nodeName!="A"?a[M]:!1;},
- g_hs=function(rgf,at){ /*do get href/src*/ },
- s_hs=function(rsf,url,at){ /*do set href/src*/ }; //'at' means is attribute, element is 'this'
- (Elp.setAttribute=function(a,v){var m;if(m=atrd(a,this)){
- s_hs.call(this,oldie.sAtr,v,m);
- }else oldie.sAtr.call(this,a,v);}).toString=SELF.toString.bind(oldie.sAtr);
- (Elp.getAttribute=function(a){var m,r;if(m=atrd(a,this)){
- r=g_hs.call(this,oldie.gAtr,m);
- }else r=oldie.gAtr.call(this,a,v);return r;}).toString=SELF.toString.bind(oldie.gAtr);
- haz_url.forEach(function(O){
- fantasmic(SELF[O.n],O.m,g_hs,s_hs);
- });
- //also fix href/src & extra end & beggining line (scripts only) in innerHTML outerHTML (use Elp which is Element.prototype) childNodes & document.all clean extra script element out; don't 4get XMLHttpRequest; Use WeakMap. (get set has delete)() to set objects as keys (this will come in handy for storing inaccesable value data associated to an object & property) : var name Omap
- /* 'target' Element property needs to be checked by functions that work with <A> and <FORM> elements
- _blank Opens the linked document in a new window
- _self Opens the linked document in the same frame as it was clicked (this is default)
- _parent Opens the linked document in the parent frameset
- _top Opens the linked document in the full body of the window
- framename Opens the linked document in a named iframe
- */
- return [alt_self,new_ndp];
- },
- rel_pth=function(r,p){
- var iOf="indexOf",S="substr",bgn=function(a,s){return a[iOf](s)===0;},rci=r[iOf]("://"),ptc=r[S](0,rci),afptc=r[S](rci+3),host=afptc[S](0,afptc[iOf]("/")),domn=ptc+"://"+host,qi=r[iOf]("?");
- if(bgn(p,"http://")||bgn(p,"https://")||bgn(p,"data:")||bgn("about:")) return p;
- if(bgn(p,"?")) return ((qi+1)?r[S](0,qi):r)+p;
- if(p[0]=="/") return domn+p;
- if(bgn(p,"://")) return ptc+p;
- if(r[r.length-1]!="/") r=r[S](0,r.lastIndexOf("/")+1);
- while(bgn(p,"../")){if(r[r.length-1]=="/")r=r[S](0,r.length-1);p=p[S](3);if(r.length>(domn.length+3))r=r[S](0,r.lastIndexOf("/")+1);}
- return r+p;
- };
- //use anonymous function for context (will need to fix 'global var' declarations so they attach to the new global object):
- // ^ ^ do that by replacing string of var declarations with JSON, ex: var a=21,be="bee",c=['hi']; translates to: new_ndp(self,{a:21,be:"bee",c:['hi']});
- var trapper_func=
- (function(){const self=alt_self,document=self.document; var window=self,location=self.location; //finish this line
- //insert fetched webpage <script> code here ( use these 2 lines \/ /\ as wrapper @ beggining & and of <script> )
- })();
- //note: beware of: iframe.contentWindow & contentDocument & window.open() & document. open, write, close () & document.referrer & new Worker() & XMLHttpRequest; For include, just use the <script> wrapper inside included scripts to.
- //don't forget to fake "blocked cross origin frame" errors
- //This turning out to be a really awesome sub-environment API
- /*
- definer func = trapper func
- one instance of the "document, self, location" proxies (new Proxy) for every fake "window/tab" instance
- access within the definer (sets the proxy objects to replace the real objects) inside the definer annoymouse function
- (the function used to loophole redefining those built-in objects)
- by using throw-away object properties that get deleted on the next line
- for vars that get defined by snared code (what's running on/in the proxy that is being tricked by the proxy) inside my definer function
- to be accessible on the "self" object proxy, use another annoymouse function inside the definer function with eval inside it and
- the object proxy can access all the eval-in-definer instances
- don't forget to put "var arguments=undefined;" at beggining of definer function
- */
- (function(){
- //use this to parse html and extract proxy modifications from .innerHTML or .outerHTML
- //note better idea: use iframe sandbox=noscripts as the proxied page iframe and run scripts exteranally in my script proxy engine, accessing the DOM of the proxied page from outside it's iframe, then no inner/outer HTML modifications are nesisary
- var nullIframe=document.createElement("iframe");
- document.body.appendChild(nullIframe);
- var HtmlParse=nullIframe.contentDocument;
- nullIframe.remove();
- var real=Object.getOwnPropertyDescriptors(Element.prototype),
- rplProp=["src","href","origin"];
- Elp.__defineGetter__("innerHTML",function(){
- var Huse=(this.nodeName=="HTML")?HtmlParse.documentElement:HtmlParse.body;
- Huse.innerHTML=real.innerHTML.get.call(this);
- for(let elm of Huse.all){
- if(elm.nodeName=="SCRIPT"){ let iH=elm.innerHTML;
- if(iH.length>3)elm.innerHTML=iH.substring(iH.indexOf("\n")+1,iH.lastIndexOf("\n")); //take out 1st and last lines because they contain my proxy code
- }else if(elm.nodeName=="FORM"){
- elm.action=rl2prxy.URL(elm.action); //replace real url with the url I want the proxied code to think it's running at
- }
- }
- return Huse.innerHTML;
- });
- })();
Add Comment
Please, Sign In to add comment