UNPKG

@lucidcms/core

Version:

The core of the Lucid CMS. It's responsible for spinning up the API and serving the CMS.

2 lines 2.12 kB
import{copy as e}from"../../i18n/copy.mjs";import t from"../../../constants/constants.mjs";import n from"../../../utils/errors/lucid-api-error.mjs";import r from"../../kv/cache-keys.mjs";import i from"../utils/create-service-context.mjs";import{supportsKVIncrement as a}from"../../kv/utils.mjs";import{createMiddleware as o}from"hono/factory";const s=async(e,t)=>{if(t)return typeof t==`function`?t(e):t},c=c=>o(async(o,l)=>{if(c.skip&&await c.skip(o)){await l();return}let u=i(o),d=u.kv,f=await s(o,c.scope),p;if(c.keyGenerator){let e=await c.keyGenerator(o);p=r.rateLimit.record(e)}else{switch(c.mode){case`user`:{let t=o.get(`auth`);if(!t)throw new n({type:`authorisation`,code:`authorisation`,message:e(`server:core.rate.limit.authentication.required`),status:401});p=r.rateLimit.user(t.id);break}case`client`:{let t=o.get(`clientIntegrationAuth`);if(!t)throw new n({type:`authorisation`,message:e(`server:core.rate.limit.authentication.required`),status:401});p=r.rateLimit.client(t.id);break}default:{let t=o.get(`runtimeContext`).getConnectionInfo(o);if(!t.address)throw new n({type:`authorisation`,message:e(`server:core.rate.limit.ip.address.required`),status:401});p=r.rateLimit.ip(t.address);break}}f&&(p+=`:${f}`)}let m,h;if(a(d)){let e=Math.max(1,Math.ceil(c.windowMs/1e3)),t=await d.increment(u,{key:`${p}:counter`,expirationTtl:e});m=t.value,h=t.expirationTtl??e}else{let e=Date.now(),n=await d.get(u,{key:p}),r;r=n&&n.resetTime>e?{count:n.count+1,resetTime:n.resetTime}:{count:1,resetTime:e+c.windowMs};let i=Math.max(1,Math.ceil((r.resetTime-e)/1e3)+t.rateLimit.ttlBufferSeconds);await d.set(u,{key:p,value:r,expirationTtl:i}),m=r.count,h=Math.max(0,Math.ceil((r.resetTime-e)/1e3))}let g=Math.max(0,c.limit-m);if(o.header(`RateLimit-Limit`,c.limit.toString()),o.header(`RateLimit-Remaining`,g.toString()),o.header(`RateLimit-Reset`,h.toString()),m>c.limit)throw o.header(`Retry-After`,h.toString()),new n({type:`rate_limit`,code:`rate_limit`,message:e(`server:core.rate.limit.exceeded.message`,{data:{resetSeconds:h}}),status:429});await l()});export{c as default}; //# sourceMappingURL=rate-limiter.mjs.map