UNPKG

insite-cookie

Version:

Cookie-based auth for inSite (client + server)

3 lines (2 loc) 2.14 kB
import{getWithTimeout as f}from"@nesvet/n";import{ClassMiddleware as l}from"insite-http";var n=new Map;var u=class r extends l{constructor(e={}){super();let{path:s="/cookie"}=e;this.listeners={GET:[[s,this.#e]]}}#e=(e,s)=>{let t=e.querystring;return t&&n.has(t)?s.writeHead(200,{"Content-Type":"text/plain; charset=utf-8","Set-Cookie":r.cookify(...f(n,t))}).end():!1};static make({name:e,value:s,maxAge:t,expiresAt:o,domain:a,path:m="/",secure:k=!0,httpOnly:c=!0,sameSite:h="Strict"}){let i=[`${e}=${s}`];return t!==void 0?i.push(`Max-Age=${t}`):o&&i.push(`Max-Age=${Math.round((o.getTime()-Date.now())/1e3)}`),a&&i.push(`Domain=${a}`),m&&i.push(`Path=${m}`),k&&i.push("Secure"),c&&i.push("HttpOnly"),h&&i.push(`SameSite=${h}`),i.join("; ")}static cookify(e,s){return Object.entries(e).map(([t,o])=>this.make({name:t,value:o,...s}))}};function p(r){return r?r.split(/;\s*/).reduce((e,s)=>{let[t,o]=s.split(/=/);try{e[t]=JSON.parse(o)}catch{e[t]=o}return e},{}):{}}import C from"node:crypto";import{random as g,setWithTimeout as y}from"@nesvet/n";var S={set:"~setcookie"};var x=2e3,d=class{constructor({usersServer:e,domain:s,maxAge:t}){this.usersServer=e,this.domain=s??process.env.INSITE_HOST,this.maxAge=t??this.usersServer.users.sessions.collection.expireAfterSeconds,this.usersServer.wss.on("client-connect",this.#t),this.usersServer.wss.on("client-session",this.#s)}#e=new WeakMap;usersServer;domain;maxAge;set(e,s,t){let o=`${Math.round(performance.now()*Number.MAX_SAFE_INTEGER).toString(36)}$${C.randomBytes(g(4,8)).toString("hex")}`;y(n,o,[s,t],x),e.sendMessage(S.set,o)}unset(e,s){this.set(e,s.reduce((t,o)=>(t[o]="",t),{}),{domain:this.domain,maxAge:0})}#t=(e,s)=>{if(this.#e.set(e,null),s.headers.cookie){let{sessionId:t=null}=p(s.headers.cookie);this.#e.set(e,t),t&&this.usersServer.setSession(e,t,!0)}};#s=e=>{this.#e.get(e)!==e.session?._id&&(this.#e.set(e,e.session?._id??null),e.isOpen&&e.session?this.set(e,{sessionId:e.session._id},{domain:this.domain,maxAge:this.maxAge}):this.unset(e,["sessionId"]))};static parse=p};export{u as CookieMiddleware,d as CookieSetter,p as parseCookie}; //# sourceMappingURL=index.js.map