From f3600a40e076184402405f77a77296ce925df0fd Mon Sep 17 00:00:00 2001
From: Xiao Gui <xgui3783@gmail.com>
Date: Fri, 11 Feb 2022 15:16:38 +0100
Subject: [PATCH] bugfix: sane url use redis for rate limiting

---
 deploy/saneUrl/index.js | 26 ++++++++++++++++++--------
 1 file changed, 18 insertions(+), 8 deletions(-)

diff --git a/deploy/saneUrl/index.js b/deploy/saneUrl/index.js
index 010f28e87..7402902f1 100644
--- a/deploy/saneUrl/index.js
+++ b/deploy/saneUrl/index.js
@@ -4,7 +4,7 @@ const { GitlabSnippetStore: Store, NotFoundError } = require('./store')
 const { Store: DepcStore } = require('./depcObjStore')
 const RateLimit = require('express-rate-limit')
 const RedisStore = require('rate-limit-redis')
-const { redisURL } = require('../lruStore')
+const lruStore = require('../lruStore')
 const { ProxyStore, NotExactlyPromiseAny } = require('./util')
 
 let store
@@ -23,12 +23,22 @@ const {
   DISABLE_LIMITER,
 } = process.env
 
-const limiter = new RateLimit({
-  windowMs: 1e3 * 5,
-  max: 5,
-  ...( redisURL ? { store: new RedisStore({ redisURL }) } : {} )
-})
-const passthrough = (_, __, next) => next()
+function limiterMiddleware(){
+  let limiter
+  return async (req, res, next) => {
+    if (DISABLE_LIMITER) return next()
+    if (limiter) return limiter(req, res, next)
+    await lruStore._initPr
+    const { redisURL } = lruStore
+    limiter = new RateLimit({
+      windowMs: 1e3 * 5,
+      max: 5,
+      store: redisURL ? new RedisStore({ redisURL }) : null
+    })
+    return limiter(req, res, next)
+  }
+}
+
 
 const acceptHtmlProg = /text\/html/i
 
@@ -85,7 +95,7 @@ router.get('/:name', async (req, res) => {
 })
 
 router.post('/:name',
-  DISABLE_LIMITER ? passthrough : limiter,
+  limiterMiddleware(),
   express.json(),
   async (req, res) => {
     if (req.headers['x-noop']) return res.status(200).end()
-- 
GitLab