From 165e6741bdeef908592ffbd4636f4bacb82b1e79 Mon Sep 17 00:00:00 2001 From: kwaroran Date: Mon, 28 Apr 2025 16:40:28 +0900 Subject: [PATCH] feat: add request api with rate limiting and URL validation in Lua engine --- src/ts/process/lua.ts | 46 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/ts/process/lua.ts b/src/ts/process/lua.ts index 727cfb59..64841e93 100644 --- a/src/ts/process/lua.ts +++ b/src/ts/process/lua.ts @@ -18,6 +18,8 @@ let luaFactory:LuaFactory let LuaSafeIds = new Set() let LuaEditDisplayIds = new Set() let LuaLowLevelIds = new Set() +let lastRequestResetTime = 0 +let lastRequestsCount = 0 interface LuaEngineState { code?: string; @@ -205,6 +207,50 @@ export async function runLua(code:string, arg:{ return await processer.similaritySearch(source) }) + luaEngine.global.set('request', async (id:string, url:string) => { + if(!LuaLowLevelIds.has(id)){ + return + } + + if(lastRequestResetTime + 60000 < Date.now()){ + lastRequestsCount = 0 + lastRequestResetTime = Date.now() + } + + if(lastRequestsCount > 8){ + return { + status: 429, + data: 'Too many requests. you can request 8 times per minute' + } + } + + lastRequestsCount++ + + try { + //for security and other reasons, only get request in 120 char is allowed + if(url.length > 120){ + return { + status: 413, + data: 'URL to large. max is 120 characters' + } + } + + //browser fetch + const d = await fetch(url) + const text = await d.text() + return { + status: d.status, + data: text + } + + } catch (error) { + return { + status: 400, + data: 'internal error' + } + } + }) + luaEngine.global.set('generateImage', async (id:string, value:string, negValue:string = '') => { if(!LuaLowLevelIds.has(id)){ return