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.
- checksums.yaml +4 -4
- data/LICENSE +1 -1
- data/README.md +1 -1
- data/assets/build.json +4 -4
- data/assets/dashboard.js +12 -12
- data/assets/locales.json +5 -5
- data/assets/picker.js +1 -1
- data/assets/tracker.js +1 -1
- data/lib/runlight/accounts/accounts.rb +40 -10
- data/lib/runlight/accounts/crypto.rb +6 -3
- data/lib/runlight/accounts/lockout.rb +98 -0
- data/lib/runlight/accounts/throttle.rb +70 -16
- data/lib/runlight/accounts/web.rb +71 -28
- data/lib/runlight/body.rb +13 -0
- data/lib/runlight/core.rb +194 -28
- data/lib/runlight/data/sources.rb +1 -2
- data/lib/runlight/db/connect.rb +2 -2
- data/lib/runlight/db/db.rb +52 -32
- data/lib/runlight/geo.rb +2 -2
- data/lib/runlight/http/response.rb +22 -3
- data/lib/runlight/icon.rb +2 -1
- data/lib/runlight/importers/csv_visits.rb +13 -3
- data/lib/runlight/importers/dub.rb +2 -1
- data/lib/runlight/importers/index.rb +2 -1
- data/lib/runlight/importers/umami.rb +3 -0
- data/lib/runlight/importers/visits.rb +16 -5
- data/lib/runlight/importers/write.rb +50 -12
- data/lib/runlight/links.rb +10 -1
- data/lib/runlight/mcp.rb +10 -1
- data/lib/runlight/oauth.rb +34 -23
- data/lib/runlight/payload.rb +26 -7
- data/lib/runlight/rack_app.rb +7 -1
- data/lib/runlight/routes.rb +51 -21
- data/lib/runlight/server/cli.rb +9 -0
- data/lib/runlight/server/db_ip.rb +287 -45
- data/lib/runlight/server/standalone.rb +41 -5
- data/lib/runlight/sources.rb +3 -2
- data/lib/runlight/store/sql.rb +14 -0
- data/lib/runlight/store/sql_store.rb +88 -59
- data/lib/runlight/ua.rb +14 -4
- data/lib/runlight/version.rb +1 -1
- data/lib/runlight/weak_keys.rb +31 -0
- data/lib/runlight.rb +2 -0
- metadata +6 -4
data/assets/picker.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(){var
|
|
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,
|
|
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
|
-
|
|
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
|
|
51
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
255
|
-
|
|
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
|
-
|
|
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
|
|
10
|
-
# settings, as "throttle:<name>:<id>" holding
|
|
11
|
-
# key as "throttle-key:<UTC day>", so every
|
|
12
|
-
#
|
|
13
|
-
#
|
|
14
|
-
#
|
|
15
|
-
# (yesterday's is kept only long
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
@
|
|
202
|
-
|
|
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
|
-
|
|
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|
|
|
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
|