runlight 0.4.3 → 0.5.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.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +1 -1
  4. data/assets/build.json +4 -4
  5. data/assets/dashboard.js +12 -12
  6. data/assets/locales.json +5 -5
  7. data/assets/picker.js +1 -1
  8. data/assets/tracker.js +1 -1
  9. data/lib/runlight/accounts/accounts.rb +40 -10
  10. data/lib/runlight/accounts/crypto.rb +6 -3
  11. data/lib/runlight/accounts/lockout.rb +98 -0
  12. data/lib/runlight/accounts/throttle.rb +70 -16
  13. data/lib/runlight/accounts/web.rb +71 -28
  14. data/lib/runlight/body.rb +13 -0
  15. data/lib/runlight/core.rb +194 -28
  16. data/lib/runlight/data/sources.rb +1 -2
  17. data/lib/runlight/db/connect.rb +2 -2
  18. data/lib/runlight/db/db.rb +52 -32
  19. data/lib/runlight/geo.rb +2 -2
  20. data/lib/runlight/http/response.rb +22 -3
  21. data/lib/runlight/icon.rb +2 -1
  22. data/lib/runlight/importers/csv_visits.rb +13 -3
  23. data/lib/runlight/importers/dub.rb +2 -1
  24. data/lib/runlight/importers/index.rb +2 -1
  25. data/lib/runlight/importers/umami.rb +3 -0
  26. data/lib/runlight/importers/visits.rb +16 -5
  27. data/lib/runlight/importers/write.rb +50 -12
  28. data/lib/runlight/links.rb +10 -1
  29. data/lib/runlight/mcp.rb +10 -1
  30. data/lib/runlight/oauth.rb +34 -23
  31. data/lib/runlight/payload.rb +26 -7
  32. data/lib/runlight/rack_app.rb +7 -1
  33. data/lib/runlight/routes.rb +51 -21
  34. data/lib/runlight/server/cli.rb +9 -0
  35. data/lib/runlight/server/db_ip.rb +287 -45
  36. data/lib/runlight/server/standalone.rb +41 -5
  37. data/lib/runlight/sources.rb +3 -2
  38. data/lib/runlight/store/sql.rb +14 -0
  39. data/lib/runlight/store/sql_store.rb +88 -59
  40. data/lib/runlight/ua.rb +14 -4
  41. data/lib/runlight/version.rb +1 -1
  42. data/lib/runlight/weak_keys.rb +31 -0
  43. data/lib/runlight.rb +2 -0
  44. metadata +6 -4
data/assets/picker.js CHANGED
@@ -1 +1 @@
1
- (function(){var p=window,o=document,d="__RUNLIGHT_PICK_TARGET__";if(/^https?:\/\//.test(d)){var g="__RUNLIGHT_PICK_RETURN__",x="__RUNLIGHT_PICK_NONCE__",m=g.indexOf(d+"/")===0&&/^[a-f0-9]{32}$/.test(x),b=p.opener;if(!(!m&&!b)){var C=JSON.parse("__RUNLIGHT_PICK_HOSTS__");if(!(C.length&&C.indexOf(location.hostname.toLowerCase().replace(/^www\./,""))<0)){var w={en:["Click what you want to count","Use this","Pick again","Cancel","Matches {n} on this page","Sent to Runlight. You can close this tab."],fr:["Cliquez sur ce que vous voulez compter","Utiliser","Choisir \xE0 nouveau","Annuler","{n} sur cette page","Envoy\xE9 \xE0 Runlight. Vous pouvez fermer cet onglet."],es:["Haz clic en lo que quieres contar","Usar esto","Elegir otra vez","Cancelar","{n} en esta p\xE1gina","Enviado a Runlight. Puedes cerrar esta pesta\xF1a."],de:["Klicke auf das, was gez\xE4hlt werden soll","Verwenden","Neu w\xE4hlen","Abbrechen","{n} auf dieser Seite","An Runlight gesendet. Du kannst diesen Tab schlie\xDFen."],pt:["Clique no que quer contar","Usar","Escolher de novo","Cancelar","{n} nesta p\xE1gina","Enviado ao Runlight. Pode fechar esta aba."]},N=(/[?&]runlight_lang=([a-z]{2})/.exec(location.search)||[])[1],c=w[N]||w.en,_=function(t){return/^[a-zA-Z][\w-]{1,40}$/.test(t)&&!/\d{3,}|^(css|sc|jsx|svelte|astro)-|__\w{5,}/.test(t)},y=function(t){return p.CSS&&CSS.escape?CSS.escape(t):t.replace(/[^\w-]/g,"\\$&")},S=function(t){try{return o.querySelectorAll(t).length===1}catch(e){return!1}},A=function(t){for(var e=[],n=t;n&&n.nodeType===1&&n!==o.documentElement;n=n.parentElement){if(n.id&&_(n.id)){e.unshift("#"+y(n.id));break}var r=n.tagName.toLowerCase(),i=n.getAttribute("data-runlight")||n.getAttribute("data-testid");if(i)r+="["+(n.hasAttribute("data-runlight")?"data-runlight":"data-testid")+'="'+i.replace(/"/g,'\\"')+'"]';else{var q=Array.prototype.filter.call(n.classList,_).slice(0,2);q.length&&(r+="."+q.map(y).join("."))}e.unshift(r);var R=e.join(" > ");if(S(R)||e.length>=4)return R;var T=n.parentElement;if(T){var L=Array.prototype.filter.call(T.children,function(I){return I.tagName===n.tagName});if(L.length>1&&(e[0]+=":nth-of-type("+(L.indexOf(n)+1)+")"),S(e.join(" > ")))return e.join(" > ")}}return e.join(" > ")},s=o.createElement("div");s.style.cssText="position:fixed;inset:0;z-index:2147483647;pointer-events:none";var u=s.attachShadow?s.attachShadow({mode:"open"}):s;u.innerHTML="<style>.box{position:fixed;border:2px solid #2563eb;background:rgba(37,99,235,.1);border-radius:4px;pointer-events:none;transition:all .06s}.bar{position:fixed;left:50%;bottom:20px;transform:translateX(-50%);display:flex;align-items:center;gap:10px;max-width:min(720px,calc(100vw - 32px));padding:10px 12px 10px 16px;border-radius:12px;background:#111;color:#fff;font:14px/1.4 system-ui,sans-serif;box-shadow:0 8px 30px rgba(0,0,0,.3);pointer-events:auto}.msg{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}code{font:12px ui-monospace,monospace;color:#93c5fd}button{height:32px;padding:0 12px;border:0;border-radius:8px;font:inherit;cursor:pointer;background:#333;color:#fff}button.go{background:#fff;color:#111}</style><div class='box' hidden></div><div class='bar'><span class='msg'></span><span class='acts'></span></div>",o.documentElement.appendChild(s);var h=u.querySelector(".box"),l=u.querySelector(".msg"),f=u.querySelector(".acts"),a=null,v=function(t,e,n){var r=o.createElement("button");r.textContent=t,e&&(r.className=e),r.addEventListener("click",n),f.appendChild(r)},E=function(t){if(!t)return h.hidden=!0;var e=t.getBoundingClientRect();h.hidden=!1,h.style.cssText+=";left:"+(e.left-2)+"px;top:"+(e.top-2)+"px;width:"+(e.width+4)+"px;height:"+(e.height+4)+"px"},k=function(){a=null,l.innerHTML="<span></span> \xB7 <code></code>",l.querySelector("span").textContent=c[0],l.querySelector("code").textContent=d.replace(/^https?:\/\//,""),f.textContent="",v(c[3],"",function(){p.close()})},U=function(t){var e=A(t),n=t.closest("a[href]"),r=0;try{r=o.querySelectorAll(e).length}catch(i){}a={selector:e,href:n?n.href:"",text:(t.textContent||"").trim().slice(0,80)},l.innerHTML="<code></code> \xB7 "+c[4].replace("{n}",r),l.querySelector("code").textContent=e,f.textContent="",v(c[2],"",k),v(c[1],"go",function(){if(l.textContent=c[5],f.textContent="",m){var i=o.createElement("a");i.rel="noreferrer",i.href=g+"#n="+x+"&s="+encodeURIComponent(a.selector)+"&h="+encodeURIComponent(a.href)+"&t="+encodeURIComponent(a.text),u.appendChild(i),i.click();return}b.postMessage({runlight:"pick",selector:a.selector,href:a.href,text:a.text},d),setTimeout(function(){p.close()},900)})};o.addEventListener("mouseover",function(t){a||E(t.target)},!0),["click","mousedown","mouseup","pointerdown","submit"].forEach(function(t){o.addEventListener(t,function(e){e.composedPath&&e.composedPath()[0]&&s.contains&&e.composedPath().indexOf(s)>=0||(e.preventDefault(),e.stopPropagation(),t==="click"&&!a&&(E(e.target),U(e.target)))},!0)}),k()}}}})();
1
+ (function(){var c=window,o=document,d="__RUNLIGHT_PICK_TARGET__";if(/^https?:\/\//.test(d)){var g="__RUNLIGHT_PICK_RETURN__",x="__RUNLIGHT_PICK_NONCE__",m=g.indexOf(d+"/")===0&&/^[a-f0-9]{32}$/.test(x),b=c.opener;if(!(!m&&!b)){var C=JSON.parse("__RUNLIGHT_PICK_HOSTS__");if(!(C.length&&C.indexOf(location.hostname.toLowerCase().replace(/^www\./,""))<0)){c.runlight&&(c.runlight.pick=1);var w={en:["Click what you want to count","Use this","Pick again","Cancel","Matches {n} on this page","Sent to Runlight. You can close this tab."],fr:["Cliquez sur ce que vous voulez compter","Utiliser","Choisir \xE0 nouveau","Annuler","{n} sur cette page","Envoy\xE9 \xE0 Runlight. Vous pouvez fermer cet onglet."],es:["Haz clic en lo que quieres contar","Usar esto","Elegir otra vez","Cancelar","{n} en esta p\xE1gina","Enviado a Runlight. Puedes cerrar esta pesta\xF1a."],de:["Klicke auf das, was gez\xE4hlt werden soll","Verwenden","Neu w\xE4hlen","Abbrechen","{n} auf dieser Seite","An Runlight gesendet. Du kannst diesen Tab schlie\xDFen."],pt:["Clique no que quer contar","Usar","Escolher de novo","Cancelar","{n} nesta p\xE1gina","Enviado ao Runlight. Pode fechar esta aba."]},N=(/[?&]runlight_lang=([a-z]{2})/.exec(location.search)||[])[1],l=w[N]||w.en,_=function(t){return/^[a-zA-Z][\w-]{1,40}$/.test(t)&&!/\d{3,}|^(css|sc|jsx|svelte|astro)-|__\w{5,}/.test(t)},y=function(t){return c.CSS&&CSS.escape?CSS.escape(t):t.replace(/[^\w-]/g,"\\$&")},S=function(t){try{return o.querySelectorAll(t).length===1}catch(e){return!1}},A=function(t){for(var e=[],n=t;n&&n.nodeType===1&&n!==o.documentElement;n=n.parentElement){if(n.id&&_(n.id)){e.unshift("#"+y(n.id));break}var r=n.tagName.toLowerCase(),i=n.getAttribute("data-runlight")||n.getAttribute("data-testid");if(i)r+="["+(n.hasAttribute("data-runlight")?"data-runlight":"data-testid")+'="'+i.replace(/"/g,'\\"')+'"]';else{var q=Array.prototype.filter.call(n.classList,_).slice(0,2);q.length&&(r+="."+q.map(y).join("."))}e.unshift(r);var R=e.join(" > ");if(S(R)||e.length>=4)return R;var T=n.parentElement;if(T){var L=Array.prototype.filter.call(T.children,function(I){return I.tagName===n.tagName});if(L.length>1&&(e[0]+=":nth-of-type("+(L.indexOf(n)+1)+")"),S(e.join(" > ")))return e.join(" > ")}}return e.join(" > ")},s=o.createElement("div");s.style.cssText="position:fixed;inset:0;z-index:2147483647;pointer-events:none";var p=s.attachShadow?s.attachShadow({mode:"open"}):s;p.innerHTML="<style>.box{position:fixed;border:2px solid #2563eb;background:rgba(37,99,235,.1);border-radius:4px;pointer-events:none;transition:all .06s}.bar{position:fixed;left:50%;bottom:20px;transform:translateX(-50%);display:flex;align-items:center;gap:10px;max-width:min(720px,calc(100vw - 32px));padding:10px 12px 10px 16px;border-radius:12px;background:#111;color:#fff;font:14px/1.4 system-ui,sans-serif;box-shadow:0 8px 30px rgba(0,0,0,.3);pointer-events:auto}.msg{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}code{font:12px ui-monospace,monospace;color:#93c5fd}button{height:32px;padding:0 12px;border:0;border-radius:8px;font:inherit;cursor:pointer;background:#333;color:#fff}button.go{background:#fff;color:#111}</style><div class='box' hidden></div><div class='bar'><span class='msg'></span><span class='acts'></span></div>",o.documentElement.appendChild(s);var h=p.querySelector(".box"),u=p.querySelector(".msg"),f=p.querySelector(".acts"),a=null,v=function(t,e,n){var r=o.createElement("button");r.textContent=t,e&&(r.className=e),r.addEventListener("click",n),f.appendChild(r)},E=function(t){if(!t)return h.hidden=!0;var e=t.getBoundingClientRect();h.hidden=!1,h.style.cssText+=";left:"+(e.left-2)+"px;top:"+(e.top-2)+"px;width:"+(e.width+4)+"px;height:"+(e.height+4)+"px"},k=function(){a=null,u.innerHTML="<span></span> \xB7 <code></code>",u.querySelector("span").textContent=l[0],u.querySelector("code").textContent=d.replace(/^https?:\/\//,""),f.textContent="",v(l[3],"",function(){c.close()})},U=function(t){var e=A(t),n=t.closest("a[href]"),r=0;try{r=o.querySelectorAll(e).length}catch(i){}a={selector:e,href:n?n.href:"",text:(t.textContent||"").trim().slice(0,80)},u.innerHTML="<code></code> \xB7 "+l[4].replace("{n}",r),u.querySelector("code").textContent=e,f.textContent="",v(l[2],"",k),v(l[1],"go",function(){if(u.textContent=l[5],f.textContent="",m){var i=o.createElement("a");i.rel="noreferrer",i.href=g+"#n="+x+"&s="+encodeURIComponent(a.selector)+"&h="+encodeURIComponent(a.href)+"&t="+encodeURIComponent(a.text),p.appendChild(i),i.click();return}b.postMessage({runlight:"pick",selector:a.selector,href:a.href,text:a.text},d),setTimeout(function(){c.close()},900)})};o.addEventListener("mouseover",function(t){a||E(t.target)},!0),["click","mousedown","mouseup","pointerdown","submit"].forEach(function(t){o.addEventListener(t,function(e){e.composedPath&&e.composedPath()[0]&&s.contains&&e.composedPath().indexOf(s)>=0||(e.preventDefault(),e.stopPropagation(),t==="click"&&!a&&(E(e.target),U(e.target)))},!0)}),k()}}}})();
data/assets/tracker.js CHANGED
@@ -1 +1 @@
1
- (function(){var n=window,a=document,m=navigator,i=location,k=a.currentScript;if(k){var s=function(e){return k.getAttribute("data-"+e)},R=k.src.replace(/s\.js(\?.*)?$/,""),E=R+"e",q=E.indexOf(i.origin+"/")?"text/plain":"application/json",L=s("site"),A=s("hash")!==null,H=s("manual")!==null,T=s("before-send"),$=function(e){return new RegExp("^"+e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$")},K=(s("exclude")||"").split(",").filter(Boolean).map(function(e){return $(e.trim())}),N=!1,z=n.runlight&&n.runlight.q||[],b="__RUNLIGHT_RULES__",B=typeof b=="object"&&(b[L]||b[i.hostname.replace(/^www\./,"")]||b["*"])||[],F=/[?&]runlight=pick\b/.test(i.search)&&/[?&]runlight_ticket=/.test(i.search);if(F){var M=a.createElement("script");M.src=R+"pick.js"+i.search,a.head.appendChild(M)}var D=!1;try{var C=/[?&]runlight=(ignore|track)\b/.exec(i.search),x=localStorage;C&&(C[1]==="ignore"?x.setItem("runlight_ignore","1"):x.removeItem("runlight_ignore")),D=x.getItem("runlight_ignore")==="1"}catch(e){}var Q=F||m.webdriver||D||s("dnt")!==null&&(m.doNotTrack==="1"||n.doNotTrack==="1"),S=function(e,t){if(!(N||Q)){var r={k:e,u:w};L&&(r.s=L);for(var o in t)r[o]=t[o];if(T!==null)try{if(r=n[T](r),!r||r.constructor!==Object)return}catch(g){return}var l=new Blob([JSON.stringify(r)],{type:q});try{if(m.sendBeacon(E,l))return}catch(g){}n.fetch&&fetch(E,{method:"POST",body:l,keepalive:!0}).catch(function(){})}},W=function(){var e=new Uint8Array(6);return crypto.getRandomValues(e),Array.from(e,function(t){return(t+256).toString(36).slice(-2)}).join("")},G=s("404")!==null,w="",c="",f=0,d=0,y=0,X=function(){return a.visibilityState==="visible"&&a.hasFocus()},J=function(){d&&(f+=Date.now()-d),d=0},v=function(){!d&&X()&&(d=Date.now())},_=function(){J(),c&&f>=1e3&&(S("engagement",{i:c,e:f,d:y}),f=0)},P=function(){var e=a.documentElement,t=Math.max(e.scrollHeight,a.body?a.body.scrollHeight:0),r=n.scrollY+n.innerHeight,o=t>0?Math.min(100,Math.round(r/t*100)):100;o>y&&(y=o)},Z=function(){return i.origin+i.pathname+i.search+(A?i.hash:"")},h=function(e){var t=typeof e=="string"?new URL(e,i.href).href:Z();if(t!==w){var r=w||a.referrer;_(),w=t;var o=new URL(t).pathname;N=K.some(function(l){return l.test(o)}),c=W(),f=0,y=0,P(),v(),S("pageview",{i:c,r,t:a.title,w:screen.width,h:screen.height,l:m.language}),G&&u("404",{path:i.pathname}),G=!1}},u=function(e,t){typeof e!="string"||!e||S("event",{i:c,n:e,p:t&&typeof t=="object"?t:void 0})},V=function(e){var t=history[e];history[e]=function(){var r=t.apply(this,arguments);return setTimeout(h),r}};H||(V("pushState"),V("replaceState"),n.addEventListener("popstate",h),A&&n.addEventListener("hashchange",h)),a.addEventListener("visibilitychange",function(){a.visibilityState==="hidden"?_():v()}),n.addEventListener("pagehide",_),n.addEventListener("blur",J),n.addEventListener("focus",v),n.addEventListener("scroll",function(){P(),v()},{passive:!0}),a.addEventListener("pointerdown",v,!0),a.addEventListener("keydown",v,!0);var ee=/\.(pdf|zip|gz|tgz|dmg|pkg|exe|msi|apk|docx?|xlsx?|pptx?|csv|txt|rtf|epub|mp3|wav|mp4|mov|avi|mkv|psd|ai|svg|key|numbers|pages)$/i;a.addEventListener("click",function(e){var t=e.target;if(!(!t||!t.closest)){for(var r=t.closest("a[href]"),o=0;o<B.length;o++)try{var l=B[o],g=l[1];(l[0]==="s"?t.closest(g):r&&$(g).test(g.charAt(0)==="/"?r.pathname:r.href))&&u(l[2])}catch(te){}var p=t.closest("[data-runlight]");if(p){for(var Y={},U=0;U<p.attributes.length;U++){var I=p.attributes[U];I.name.indexOf("data-runlight-")===0&&(Y[I.name.slice(14)]=I.value)}u(p.getAttribute("data-runlight"),Y)}if(!(!r||p)){var O=r.href;/^https?:/.test(O)&&(s("downloads")!=="false"&&ee.test(r.pathname)?u("File download",{url:O}):s("outbound")!=="false"&&r.host!==i.host&&u("Outbound link",{url:O}))}}},!0),n.runlight=u,u.pageview=h,H||h();for(var j=0;j<z.length;j++)u.apply(null,z[j])}})();
1
+ (function(){var n=window,t=document,w=navigator,s=location,j=t.currentScript;if(j){var h=e=>j.getAttribute("data-"+e),b=e=>h(e)!==null,y=Date.now,o=(e,r,a,i)=>e.addEventListener(r,a,i),N=j.src.replace(/s\.js(\?.*)?$/,""),E=N+"e",Y=E.indexOf(s.origin+"/")?"text/plain":"application/json",O=h("site"),z=b("hash"),R=b("manual"),B=h("before-send"),F=e=>new RegExp("^"+e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$"),K=(h("exclude")||"").split(",").filter(Boolean).map(e=>F(e.trim())),M=!1,Q=n.runlight&&n.runlight.q||[],k="__RUNLIGHT_RULES__",W=typeof k=="object"&&(k[O]||k[s.hostname.replace(/^www\./,"")]||k["*"])||[],q=w.webdriver||b("dnt")&&(w.doNotTrack==1||n.doNotTrack==1),U=(/[?&]runlight=(ignore|track|pick)\b/.exec(s.search)||[])[1];try{var _=localStorage,A="runlight_ignore";U==="ignore"&&_.setItem(A,y()),U==="track"&&_.removeItem(A);var C=_.getItem(A);(C==1||y()-C<31536e6)&&(q=!0)}catch(e){}var D=()=>{f="",R||v()},H=U==="pick";if(H){var x=t.createElement("script");x.src=N+"pick.js"+s.search,x.onload=x.onerror=()=>{H=l.pick,D()},t.head.appendChild(x)}var I=(e,r)=>{if(!(M||q||H||t.prerendering)){var a=Object.assign({k:e,u:f},O&&{s:O},r);if(B!==null)try{if(a=n[B](a),!a||a.constructor!==Object)return}catch(d){return}var i=new Blob([JSON.stringify(a)],{type:Y});try{if(w.sendBeacon(E,i))return}catch(d){}n.fetch&&fetch(E,{method:"POST",body:i,keepalive:!0}).catch(()=>{})}},G=b("404"),f="",p="",g=0,m=0,S=0,J=()=>{m&&(g+=y()-m),m=0},u=()=>{!m&&!t.hidden&&t.hasFocus()&&(m=y())},L=()=>{J(),p&&g>=1e3&&(I("engagement",{i:p,e:g,d:S}),g=0)},P=()=>{var e=t.documentElement,r=Math.max(e.scrollHeight,t.body?t.body.scrollHeight:0),a=n.scrollY+n.innerHeight,i=r>0?Math.min(100,Math.round(a/r*100)):100;i>S&&(S=i)},v=e=>{if(t.prerendering)return o(t,"prerenderingchange",()=>v(e));var r=typeof e=="string"?new URL(e,s.href).href:s.origin+s.pathname+s.search+(z?s.hash:"");if(r!==f){var a=f||t.referrer;L(),f=r,M=K.some(i=>i.test(new URL(r).pathname)),p=Array.from(crypto.getRandomValues(new Uint8Array(6)),i=>(i+256).toString(36).slice(-2)).join(""),g=0,S=0,P(),u(),I("pageview",{i:p,r:a,t:t.title,w:screen.width,h:screen.height,l:w.language}),G&&l("404",{path:s.pathname}),G=!1}},l=(e,r)=>{typeof e!="string"||!e||I("event",{i:p,n:e,p:r&&typeof r=="object"?r:void 0})},V=(e,r)=>{var a=history[e];history[e]=function(){var i=s.pathname,d=a.apply(this,arguments);return(!r||i!==s.pathname)&&setTimeout(v),d}};R||(V("pushState"),V("replaceState",1),o(n,"popstate",v),z&&o(n,"hashchange",v),o(n,"pageshow",e=>e.persisted&&D())),o(t,"visibilitychange",()=>{t.hidden?L():u()}),o(n,"pagehide",L),o(n,"blur",J),o(n,"focus",u),o(n,"scroll",()=>{P(),u()},{passive:!0}),o(t,"pointerdown",u,!0),o(t,"keydown",u,!0);var X=/\.(pdf|zip|gz|tgz|dmg|pkg|exe|msi|apk|docx?|xlsx?|pptx?|csv|txt|rtf|epub|mp3|wav|mp4|mov|avi|mkv|psd|ai|svg|key|numbers|pages)$/i;o(t,"click",e=>{var r=e.target;if(!(!r||!r.closest)){var a=r.closest("a[href]");W.forEach(c=>{try{var $=c[1];(c[0]==="s"?r.closest($):a&&F($).test($[0]==="/"?a.pathname:a.href))&&l(c[2])}catch(Z){}});var i=r.closest("[data-runlight]");if(i){var d={};Array.from(i.attributes).forEach(c=>{c.name.indexOf("data-runlight-")||(d[c.name.slice(14)]=c.value)}),l(i.getAttribute("data-runlight"),d)}if(!(!a||i)){var T=a.href;/^https?:/.test(T)&&(h("downloads")!=="false"&&X.test(a.pathname)?l("File download",{url:T}):h("outbound")!=="false"&&a.host!==s.host&&l("Outbound link",{url:T}))}}},!0),n.runlight=l,l.pageview=v,R||v(),Q.forEach(e=>l.apply(null,e))}})();
@@ -29,7 +29,9 @@ module Runlight
29
29
 
30
30
  # What passes for an email address, with JavaScript's \s.
31
31
  EMAIL = /\A[^#{Js::SPACE}@<>"]+@[^#{Js::SPACE}@<>"]+\.[^#{Js::SPACE}@<>"]+\z/
32
- private_constant :EMAIL
32
+ # The longest an address can be. Anything longer is refused before the pattern reads it.
33
+ MAX_EMAIL = 320
34
+ private_constant :EMAIL, :MAX_EMAIL
33
35
 
34
36
  # A password checked against nothing, so a wrong email takes as long as a wrong password. Made when first needed.
35
37
  @decoy = nil
@@ -37,19 +39,41 @@ module Runlight
37
39
  # Password checks run at once, in this process, and the most that may wait for one.
38
40
  CHECKING = 4
39
41
  WAITING = 64
42
+ # Password checks a process runs in a minute. A check holds Ruby's global lock for its whole length (about
43
+ # 150 ms at today's cost), so while one runs nothing else in the process does, the app's own requests
44
+ # among them when Runlight is mounted in one. Thirty a minute keeps sign-ins to a tenth of the process's
45
+ # time or so however many are tried. Browsers that signed in to the account before, and people already
46
+ # signed in who are asked for their password again, have thirty of their own, so a flood of tries from
47
+ # strangers cannot use up theirs. Nil is no limit.
48
+ CHECKS_PER_MINUTE = 30
40
49
  SLOTS = Mutex.new
41
50
  FREED = ConditionVariable.new
42
51
  private_constant :SLOTS, :FREED
43
52
  @running = 0
44
53
  @waiting = 0
54
+ @checks_per_minute = CHECKS_PER_MINUTE
55
+ # When each of the last minute's checks began, for strangers (false) and for known browsers (true).
56
+ @checked = { false => [], true => [] }
45
57
 
46
58
  class << self
47
59
  attr_accessor :decoy
48
60
 
61
+ # The budget of password checks a minute, CHECKS_PER_MINUTE unless set otherwise; nil for no limit.
62
+ attr_accessor :checks_per_minute
63
+
49
64
  # Runs a password check when one of the few slots is free, so a flood of sign-ins cannot take every core.
50
- # Past the queue's length it refuses at once, with an AccountError coded "busy".
51
- def slot
65
+ # Past the queue's length, or past the minute's budget of checks (`known` picks which of the two), it
66
+ # refuses at once, with an AccountError coded "busy".
67
+ def slot(known = false)
52
68
  SLOTS.synchronize do
69
+ unless @checks_per_minute.nil?
70
+ at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
71
+ spent = @checked[known ? true : false]
72
+ spent.shift while !spent.empty? && at - spent[0] >= 60
73
+ raise AccountError.new("Runlight is busy checking other sign-ins. Try again in a moment.", "busy") if spent.length >= @checks_per_minute
74
+
75
+ spent << at
76
+ end
53
77
  if @running >= CHECKING
54
78
  raise AccountError.new("Runlight is busy checking other sign-ins. Try again in a moment.", "busy") if @waiting >= WAITING
55
79
 
@@ -273,7 +297,7 @@ module Runlight
273
297
  init
274
298
  raise AccountError.new("Choose member or viewer for one site", "role_scope") if !site.nil? && (site.empty? || !%w[member viewer].include?(role))
275
299
  address = Js.lower(Js.trim(email))
276
- raise AccountError.new("Enter an email address", "email_invalid") unless address.match?(EMAIL)
300
+ raise AccountError.new("Enter an email address", "email_invalid") unless Js.length(address) <= MAX_EMAIL && address.match?(EMAIL)
277
301
  if Js.length(password) < MIN_PASSWORD
278
302
  raise AccountError.new("Use a password of at least #{MIN_PASSWORD} characters", "password_short", { "min" => MIN_PASSWORD.to_s })
279
303
  end
@@ -362,18 +386,21 @@ module Runlight
362
386
 
363
387
  # The account for an email and password, or nil. Takes the same time either way. Only a few checks run at
364
388
  # once; with too many waiting it raises an AccountError coded "busy".
365
- def sign_in(email, password)
389
+ # `known` says the try comes from a browser that signed in to the account before, or from someone already
390
+ # signed in, whose checks have a budget of their own.
391
+ def sign_in(email, password, known: false)
366
392
  user = by_email(email)
367
393
  if user.nil?
368
394
  hash = self.class.decoy ||= Crypto.hash_password(Crypto.hex(Crypto.random_bytes(16)))
369
- self.class.slot { Crypto.check_password(password, hash) }
395
+ self.class.slot(known) { Crypto.check_password(password, hash) }
370
396
  return nil
371
397
  end
372
- return nil unless self.class.slot { Crypto.check_password(password, user["hash"]) }
398
+ return nil unless self.class.slot(known) { Crypto.check_password(password, user["hash"]) }
373
399
  return user unless Crypto.weaker_than_now?(user["hash"])
374
400
 
375
401
  # A hash from before the cost rose is made again now that the password is here, unless it changed meanwhile.
376
- hash = self.class.slot { Crypto.hash_password(password) }
402
+ # The password was right, so making it again is not counted against the minute's checks.
403
+ hash = Crypto.hash_password(password)
377
404
  @store.db.run("UPDATE rl_users SET hash = ? WHERE id = ? AND hash = ?", [hash, user["id"], user["hash"]])
378
405
  by_id(user["id"]) || user
379
406
  end
@@ -524,7 +551,10 @@ module Runlight
524
551
  end
525
552
  read = Js.truthy?(row["totp_recovery"]) ? row["totp_recovery"].to_s : nil
526
553
  hashes = read.nil? ? [] : Json.decode(read)
527
- at = hashes.index(Crypto.recovery_hash(given))
554
+ # Every hash is compared, each in time that does not depend on where it differs.
555
+ mine = Crypto.recovery_hash(given)
556
+ at = nil
557
+ hashes.each_with_index { |hash, i| at = i if Crypto.same_text(hash.to_s, mine) }
528
558
  return false if at.nil?
529
559
 
530
560
  hashes.delete_at(at)
@@ -569,7 +599,7 @@ module Runlight
569
599
  def invite_now(email, role, invited_by, now, site = nil)
570
600
  raise AccountError.new("Choose member or viewer for one site", "role_scope") if !site.nil? && (site.empty? || !%w[member viewer].include?(role))
571
601
  address = Js.lower(Js.trim(email))
572
- raise AccountError.new("Enter an email address", "email_invalid") unless address.match?(EMAIL)
602
+ raise AccountError.new("Enter an email address", "email_invalid") unless Js.length(address) <= MAX_EMAIL && address.match?(EMAIL)
573
603
  raise AccountError.new("#{address} already has an account", "account_exists", { "email" => address }) unless by_email(address).nil?
574
604
 
575
605
  code = Crypto.base64url(Crypto.random_bytes(24))
@@ -251,10 +251,13 @@ module Runlight
251
251
  # The time step a code matches, one step either side for clocks that drift, newer than `after`; else nil.
252
252
  def match_step(secret, code, now, after)
253
253
  current = now.floor.div(STEP_MS)
254
- [current, current - 1, current + 1].each do |step|
255
- return step if step > after && totp(secret, step) == code
254
+ # Every step is worked out and compared in time that does not depend on where the code differs. The
255
+ # current step is checked last, so it is the one kept if two should match.
256
+ found = nil
257
+ [current + 1, current - 1, current].each do |step|
258
+ found = step if same_text(totp(secret, step), code) && step > after
256
259
  end
257
- nil
260
+ found
258
261
  end
259
262
 
260
263
  # The address an authenticator app reads from the QR code.
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Runlight
4
+ module Accounts
5
+ # Counts wrong second-factor codes under a key and locks it for longer each time the tries run out: five
6
+ # tries, then fifteen minutes, then thirty, then an hour, doubling up to a day. A right code clears the
7
+ # key, and so does a week with no lock and no try. A lock always ends, at most a day later, so nobody is
8
+ # shut out for good.
9
+ #
10
+ # TypeScript keeps the counts in its process. Here they live in the database's settings, as
11
+ # "lockout:<name>:<id>" holding {count, until, locks, forget}, so every process of an install shares them
12
+ # and a restart does not hand out five more tries. A key is an account's id (with "\ndevice" for a browser
13
+ # that signed in to it before), never anything made from a caller's address, and it is kept as a hash.
14
+ # One that is forgotten is deleted when it is next read, by the scheduled check, and by each process once
15
+ # an hour (sweep).
16
+ class Lockout
17
+ PREFIX = "lockout:"
18
+ private_constant :PREFIX
19
+
20
+ def initialize(store, name, limit = 5, window_ms = 15 * 60_000, longest_ms = 86_400_000, forget_ms = 7 * 86_400_000)
21
+ @store = store
22
+ @name = name
23
+ @limit = limit
24
+ @window_ms = window_ms
25
+ @longest_ms = longest_ms
26
+ @forget_ms = forget_ms
27
+ end
28
+
29
+ # Deletes every key long forgotten, for the scheduled check and each process's hourly sweep.
30
+ def self.sweep(store, now)
31
+ store.settings_starting_with(PREFIX).each do |row|
32
+ entry = Json.try_decode(row["value"])
33
+ forget = entry.is_a?(Hash) ? Js.number(entry["forget"].nil? ? 0 : entry["forget"]) : 0
34
+ store.set_setting(row["key"], nil) unless forget.is_a?(Numeric) && forget.to_f.finite? && forget > now
35
+ end
36
+ end
37
+
38
+ # Counts a try before the code is checked, so a burst cannot get past the limit. False, counting
39
+ # nothing, while the key is locked. The try that uses up the last one starts the lock.
40
+ def take(key, now)
41
+ name = setting(key)
42
+ # Checked and counted in one turn, so tries at once from other threads and processes wait for it.
43
+ turn do
44
+ entry = read(name)
45
+ entry = nil if !entry.nil? && entry["forget"] <= now
46
+ next false if !entry.nil? && entry["count"] >= @limit && entry["until"] > now
47
+
48
+ if entry.nil?
49
+ entry = { "count" => 0, "until" => now + @window_ms, "locks" => 0, "forget" => 0 }
50
+ elsif entry["until"] <= now
51
+ entry["count"] = 0
52
+ entry["until"] = now + @window_ms
53
+ end
54
+ entry["count"] += 1
55
+ if entry["count"] >= @limit
56
+ entry["until"] = now + [@window_ms * (2**[entry["locks"], 40].min), @longest_ms].min
57
+ entry["locks"] += 1
58
+ end
59
+ entry["forget"] = entry["until"] + @forget_ms
60
+ @store.set_setting(name, Json.encode(entry))
61
+ true
62
+ end
63
+ end
64
+
65
+ # Forgets a key, for a code that turned out right.
66
+ def clear(key)
67
+ @store.set_setting(setting(key), nil)
68
+ nil
69
+ end
70
+
71
+ private
72
+
73
+ def setting(key)
74
+ "#{PREFIX}#{@name}:#{Hashing.sha256("#{@name}\n#{key}")[0, 32]}"
75
+ end
76
+
77
+ def read(name)
78
+ saved = @store.setting(name)
79
+ entry = saved.nil? ? nil : Json.try_decode(saved)
80
+ return nil unless entry.is_a?(Hash)
81
+
82
+ %w[count until locks forget].to_h { |field| [field, whole(entry[field])] }
83
+ end
84
+
85
+ # A saved number, whole, and 0 for anything that is not a number.
86
+ def whole(value)
87
+ n = Js.number(value.nil? ? 0 : value)
88
+ n.is_a?(Float) && !n.finite? ? 0 : n.to_i
89
+ end
90
+
91
+ # One change at a time, across threads and processes, as the accounts take turns.
92
+ def turn(&block)
93
+ db = @store.db
94
+ db.respond_to?(:turn) ? db.turn { block.call } : db.exclusive { block.call }
95
+ end
96
+ end
97
+ end
98
+ end
@@ -6,13 +6,19 @@ module Runlight
6
6
  # Keys are hashed with a key made for each UTC day, so the counts never hold
7
7
  # an address or an email as it was given.
8
8
  #
9
- # TypeScript keeps the counts in its process. Here they live in the database's
10
- # settings, as "throttle:<name>:<id>" holding {count, until}, and the hashing
11
- # key as "throttle-key:<UTC day>", so every process of an install shares the
12
- # same counts. Some keys are addresses, and nothing derived from one lasts
13
- # longer than a day: an expired count is deleted when it is read and by the
14
- # scheduled check (sweep), and a day's hashing key goes once the day is over
15
- # (yesterday's is kept only long enough to carry a count across midnight).
9
+ # TypeScript keeps the counts in its process. Here the counts keyed by an
10
+ # account live in the database's settings, as "throttle:<name>:<id>" holding
11
+ # {count, until}, and the hashing key as "throttle-key:<UTC day>", so every
12
+ # process of an install shares the same counts. An expired count is deleted
13
+ # when it is read, by the scheduled check, and by each process once an hour
14
+ # (sweep), a count taken back to nothing is deleted at once, and a day's
15
+ # hashing key goes once the day is over (yesterday's is kept only long
16
+ # enough to carry a count across midnight).
17
+ #
18
+ # A count keyed by a caller's address (`memory: true`) is never written
19
+ # anywhere: it lives in this process alone, as TypeScript's do, under a key
20
+ # made when the process started, and goes when its window ends. Each process
21
+ # then counts on its own, as the tracker's rate limit does.
16
22
  class Throttle
17
23
  KEY = "throttle-key:"
18
24
  # The one hashing key from before keys were made per day.
@@ -20,13 +26,28 @@ module Runlight
20
26
  DAY_MS = 86_400_000
21
27
  # How long after midnight yesterday's key carries a count over: the longest window a throttle counts in.
22
28
  CARRY_MS = 15 * 60_000
23
- private_constant :KEY, :LEGACY_KEY, :DAY_MS, :CARRY_MS
29
+ # The counts earlier versions kept in the settings under a hash of an address.
30
+ ADDRESS_NAMES = %w[address ip].freeze
31
+ private_constant :KEY, :LEGACY_KEY, :DAY_MS, :CARRY_MS, :ADDRESS_NAMES
24
32
 
25
- def initialize(store, name, limit = 10, window_ms = 15 * 60_000)
33
+ def initialize(store, name, limit = 10, window_ms = 15 * 60_000, memory: false)
26
34
  @store = store
27
35
  @name = name
28
36
  @limit = limit
29
37
  @window_ms = window_ms
38
+ # With memory, id to {count, until}, the key the ids are made with, and one change at a time.
39
+ @held = memory ? {} : nil
40
+ @held_key = memory ? Hashing.random_id(16) : nil
41
+ @lock = Mutex.new
42
+ end
43
+
44
+ # Deletes what earlier versions wrote to the settings under a hash of a caller's address: the sign-in
45
+ # counts per address, and the count of app registrations.
46
+ def self.forget_addresses(store)
47
+ ADDRESS_NAMES.each do |name|
48
+ store.settings_starting_with("throttle:#{name}:").each { |row| store.set_setting(row["key"], nil) }
49
+ end
50
+ store.set_setting("oauth-registrations", nil) unless store.setting("oauth-registrations").nil?
30
51
  end
31
52
 
32
53
  # Deletes every count that has run out and the hashing keys of days gone, for the scheduled check.
@@ -56,6 +77,8 @@ module Runlight
56
77
 
57
78
  def blocked(key, now)
58
79
  today, yesterday = ids(key, now)
80
+ return turn { blocked_entry?(entry(today, now)) } if @held
81
+
59
82
  entry = entry(today, now) || (yesterday && entry(yesterday, now))
60
83
  blocked_entry?(entry)
61
84
  end
@@ -84,7 +107,8 @@ module Runlight
84
107
  next unless entry && entry["count"].positive?
85
108
 
86
109
  entry["count"] -= 1
87
- save(ids[0], entry)
110
+ # A count back at nothing says nothing, so it is not kept until its window ends.
111
+ entry["count"].zero? ? drop(ids[0]) : save(ids[0], entry)
88
112
  end
89
113
  nil
90
114
  end
@@ -96,7 +120,8 @@ module Runlight
96
120
  end
97
121
 
98
122
  def clear(key, now)
99
- ids(key, now).compact.each { |id| @store.set_setting("#{prefix}#{id}", nil) }
123
+ found = ids(key, now).compact
124
+ @held ? turn { found.each { |id| drop(id) } } : found.each { |id| drop(id) }
100
125
  nil
101
126
  end
102
127
 
@@ -123,12 +148,17 @@ module Runlight
123
148
 
124
149
  # One change to the counts at a time, across threads and processes, as the accounts take turns.
125
150
  def turn(&block)
151
+ return @lock.synchronize(&block) if @held
152
+
126
153
  db = @store.db
127
154
  db.respond_to?(:turn) ? db.turn { block.call } : db.exclusive { block.call }
128
155
  end
129
156
 
130
157
  # The key's id under today's hashing key, and under yesterday's while that is still kept (else nil).
131
158
  def ids(key, now)
159
+ # In memory there are no days: the one key lasts as long as the process.
160
+ return [keyed(@held_key, key), nil] if @held
161
+
132
162
  yesterday = salt(now - DAY_MS, false)
133
163
  [keyed(salt(now), key), yesterday.nil? ? nil : keyed(yesterday, key)]
134
164
  end
@@ -143,6 +173,13 @@ module Runlight
143
173
 
144
174
  # A count that has not run out, or nil. One that has is deleted as it is read.
145
175
  def entry(id, now)
176
+ if @held
177
+ entry = @held[id]
178
+ return entry if entry.nil? || entry["until"] > now
179
+
180
+ @held.delete(id)
181
+ return nil
182
+ end
146
183
  saved = @store.setting("#{prefix}#{id}")
147
184
  return nil if saved.nil?
148
185
 
@@ -150,7 +187,7 @@ module Runlight
150
187
  entry = entry.is_a?(Hash) ? { "count" => int(entry["count"]), "until" => int(entry["until"]) } : nil
151
188
  return entry if entry && entry["until"] > now
152
189
 
153
- @store.set_setting("#{prefix}#{id}", nil)
190
+ drop(id)
154
191
  nil
155
192
  end
156
193
 
@@ -175,9 +212,17 @@ module Runlight
175
212
  end
176
213
 
177
214
  def save(id, entry)
215
+ return @held[id] = entry if @held
216
+
178
217
  @store.set_setting("#{prefix}#{id}", Json.encode(entry))
179
218
  end
180
219
 
220
+ def drop(id)
221
+ return @held.delete(id) if @held
222
+
223
+ @store.set_setting("#{prefix}#{id}", nil)
224
+ end
225
+
181
226
  def blocked_entry?(entry)
182
227
  !entry.nil? && entry["count"] >= @limit
183
228
  end
@@ -197,12 +242,21 @@ module Runlight
197
242
  # or the count of a name someone is close to blocking. Run when a new entry is made, since only then can
198
243
  # there be more.
199
244
  def prune(now)
245
+ if @held
246
+ # In memory this is cheap to skip: once a minute is often enough, unless the ceiling is reached.
247
+ return if @held.size <= Accounts::MAX_THROTTLED && !@pruned_at.nil? && now >= @pruned_at && now - @pruned_at < 60_000
248
+
249
+ @pruned_at = now
250
+ end
200
251
  entries = []
201
- @store.settings_starting_with(prefix).each do |row|
202
- entry = Json.try_decode(row["value"])
252
+ saved = if @held then @held.map { |id, entry| { "key" => id, "value" => entry } }
253
+ else @store.settings_starting_with(prefix).map { |row| { "key" => row["key"].delete_prefix(prefix), "value" => Json.try_decode(row["value"]) } }
254
+ end
255
+ saved.each do |row|
256
+ entry = row["value"]
203
257
  until_ms = entry.is_a?(Hash) ? int(entry["until"]) : 0
204
258
  if until_ms <= now
205
- @store.set_setting(row["key"], nil)
259
+ drop(row["key"])
206
260
  next
207
261
  end
208
262
  entries << { "key" => row["key"], "until" => until_ms, "count" => int(entry["count"]) }
@@ -211,7 +265,7 @@ module Runlight
211
265
 
212
266
  # Fewest tries first, and among equals the oldest: each entry's window started windowMs before its end.
213
267
  fewest = entries.each_with_index.sort_by { |e, i| [e["count"], e["until"], i] }.map(&:first)
214
- fewest.first(entries.length - (Accounts::MAX_THROTTLED * 0.9).floor).each { |e| @store.set_setting(e["key"], nil) }
268
+ fewest.first(entries.length - (Accounts::MAX_THROTTLED * 0.9).floor).each { |e| drop(e["key"]) }
215
269
  end
216
270
  end
217
271
  end