authored 0.0.2 → 0.0.3

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.
@@ -1,4 +1,6 @@
1
- import { Client } from "pg";
1
+ import { Client } from 'pg';
2
+
3
+ declare function decodeSID(str: string): string;
2
4
  interface obj<T> {
3
5
  [Key: string]: T;
4
6
  }
@@ -30,7 +32,7 @@ type authConfig = {
30
32
  JWT_LIFETIME: number;
31
33
  };
32
34
  type dbs = "fs" | "postgres";
33
- export declare class Auth {
35
+ declare class Auth {
34
36
  postgresClient?: Client;
35
37
  config: authConfig;
36
38
  constructor({ type, dir }?: {
@@ -53,7 +55,7 @@ declare class callBack {
53
55
  has(target: any, prop: string): boolean;
54
56
  deleteProperty(target: any, val: string): boolean;
55
57
  }
56
- export declare class ServerSide extends callBack {
58
+ declare class ServerSide extends callBack {
57
59
  sid: string;
58
60
  [Key: string]: any;
59
61
  modified: boolean;
@@ -76,7 +78,7 @@ declare class sidGenerator {
76
78
  constructor(salt: string);
77
79
  generate(len?: number): string;
78
80
  }
79
- export declare class AuthInterface extends sidGenerator {
81
+ declare class AuthInterface extends sidGenerator {
80
82
  config: authConfig;
81
83
  constructor(config: authConfig, salt?: string);
82
84
  openSession(sid?: string, readonly?: boolean): Promise<ServerSide>;
@@ -88,7 +90,7 @@ export declare class AuthInterface extends sidGenerator {
88
90
  setCookie(xsesh: ServerSide, life: Date | number, _sameSite?: string): string;
89
91
  loadHeader(req: any, readonly?: boolean): Promise<ServerSide>;
90
92
  }
91
- export declare class FSession extends ServerSide {
93
+ declare class FSession extends ServerSide {
92
94
  }
93
95
  interface ffcache {
94
96
  [key: string]: string | undefined | boolean | number;
@@ -115,7 +117,7 @@ declare class FSInterface extends AuthInterface {
115
117
  fetchSession(sid: string, readonly?: boolean): Promise<ServerSide>;
116
118
  saveSession(sesh: ServerSide, X?: Headers, deleteMe?: boolean): Promise<void>;
117
119
  }
118
- export declare class PGCache<T extends bs> {
120
+ declare class PGCache<T extends bs> {
119
121
  client: Client;
120
122
  query: string;
121
123
  f_timed: number;
@@ -128,7 +130,7 @@ export declare class PGCache<T extends bs> {
128
130
  set(data: T): Promise<void>;
129
131
  delete(key: string): Promise<void>;
130
132
  }
131
- export declare class JWTInterface extends sidGenerator {
133
+ declare class JWTInterface extends sidGenerator {
132
134
  salt: string;
133
135
  constructor();
134
136
  sign(payload: obj<any>): string;
@@ -149,7 +151,7 @@ export declare class JWTInterface extends sidGenerator {
149
151
  save(xjwts: ServerSide): string;
150
152
  new(payload: obj<any>): string;
151
153
  }
152
- export declare class Fjson<T extends fs> {
154
+ declare class Fjson<T extends fs> {
153
155
  fs: string;
154
156
  f_timed: number;
155
157
  data: Map<any, T>;
@@ -166,4 +168,5 @@ export declare class Fjson<T extends fs> {
166
168
  delete(key: string): Promise<void>;
167
169
  json(): Promise<unknown[]>;
168
170
  }
169
- export {};
171
+
172
+ export { Auth, AuthInterface, FSession, Fjson, JWTInterface, PGCache, ServerSide, decodeSID };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{randomBytes as _}from"crypto";var{CryptoHasher:b,file:R,gunzipSync:y,gzipSync:g,write:N}=globalThis.Bun;import{promises as m,mkdirSync as c,writeFileSync as v}from"fs";import{sign as T,verify as o}from"jsonwebtoken";var f=(Y)=>Array.from({length:Y},(Z,$)=>$);var r=f(10).join(""),t=new RegExp(/(\d+)(\d*)/,"m");var M=Object.values;var{entries:I,hasOwn:a}=Object;var D=Object.assign,F=(Y)=>{return Object.keys(Y).length};var V=(Y)=>{return Buffer.from(Y)},j=(...Y)=>{let Z=new Bun.CryptoHasher("sha256",G());return Y.forEach(($)=>{Z.update($)}),Z.digest()};var G=()=>{let Y=process.env.SECRET_KEY;if(!Y)throw new Error("'SECRET_KEY' not found in .env file");return Y};class H{date;constructor(Y){this.date=Y?new Date(Y):new Date}delta(Y=null,Z=!1){let $=H.delta(this.date.getTime(),Y);return Z?new Date($):$}timed(Y){if(!Y)return this.date;return[["year","FullYear"],["month","Month"],["day","Date"],["hour","Hours"],["minute","Minutes"],["second","Seconds"]].reduce(($,[U,W])=>{let Q=Y[U];return Q?new Date($[`set${W}`]($[`get${W}`]()+Q)):$},new Date(this.date))}static delta(Y,Z=null){return Z?Z-Y:Y-Date.now()}static get now(){return Date.now()}}function K(Y){let Z=new b("md5");return Z.update(Y),Z.digest("hex")}var h=new TextDecoder,n={cookie:(Y,Z="",{maxAge:$,expires:U,path:W,domain:Q,secure:q,httpOnly:L,sameSite:E})=>{if($ instanceof Date)$=$.getSeconds();if(U instanceof Date)U=U.toUTCString();else if(U===0)U=new Date().toUTCString();return[["Domain",Q],["Expires",U],["Max-Age",$],["Secure",q],["HttpOnly",L],["Path",W],["SameSite",E]].reduce((B,[X,A])=>{if(A!==void 0)B.push(`${X}=${A}`);return B},[`${Y}=${Z}`]).join("; ")}},O={file:(Y,Z)=>{try{v(Y,Z??"",{flag:"wx"})}catch($){}return!0},dir:(Y)=>{return c(Y,{recursive:!0}),!0},decode(Y){return h.decode(Y)}};function p(Y=64){return new b("sha256").update(_(Y)).digest("hex")}class l{postgresClient;config={COOKIE_NAME:"session",COOKIE_DOMAIN:"127.0.0.1",COOKIE_PATH:"/",COOKIE_HTTPONLY:!0,COOKIE_SECURE:!0,REFRESH_EACH_REQUEST:!1,COOKIE_SAMESITE:"Strict",KEY_PREFIX:"session:",PERMANENT:!0,USE_SIGNER:!1,ID_LENGTH:32,FILE_THRESHOLD:500,LIFETIME:31,MAX_COOKIE_SIZE:4093,INTERFACE:"fs",STORAGE:".sessions",JWT_STORAGE:".jwt",JWT_LIFETIME:5};constructor({type:Y="fs",dir:Z}={}){Y&&(this.config.INTERFACE=Y),Z&&this.initStorage(Z)}initStorage(Y){return this.config.STORAGE=Y+"/"+this.config.STORAGE,this.config.JWT_STORAGE=Y+"/"+this.config.JWT_STORAGE,this}get session(){return new C(this.config,this.config.STORAGE)}get jwt(){return new C(this.config,this.config.JWT_STORAGE)}}class w{data;modified;new=!0;length=0;constructor(Y={}){if(this.modified=!0,this.data={},this.length=F(Y),this.length)this.new=!1;D(this.data,Y)}set(Y,Z,$){if(!this.readonly&&Y.data[Z]!=$){if(this.modified=!0,!(Z in Y.data))this.length++;return Y.data[Z]=$,!0}return!1}get(Y,Z){if(Z in Y)return Y[Z];return Y.data[Z]}has(Y,Z){if(Z in Y.data)return!0;return!1}deleteProperty(Y,Z){if(!this.readonly&&Z in Y.data)this.modified=!0,delete Y.data[Z],this.length--;return!0}}class J extends w{sid;modified;readOnly;constructor(Y="",Z={},$=!1){super(Z);this.sid=Y;this.modified=!1,this.readOnly=$}get session(){return new Proxy(this,this)}}class u{salt;constructor(Y){this.salt=Y}getSignature(Y){let Z=this.deriveKey().toString();return j(Z,Y).toString("base64")}deriveKey(){return j(this.salt)}sign(Y){let Z=this.getSignature(Y),$=V(Y+"."+Z);return O.decode($)}unsign(Y){if(!(Y.indexOf(".")>-1))throw Error("No sep found");let Z=Y.indexOf("."),$=Y.slice(0,Z),U=Y.slice(Z+1);return this.verifySignature($,U)}loadUnsign(Y){if(this.unsign(Y)){let Z=V(Y),$=V(".").toString()[0];if(!($ in Z))throw Error("No sep found");let U=Z.indexOf($),W=Z.subarray(0,U);return Buffer.from(W.toString(),"base64").toString("utf-8")}}verifySignature(Y,Z){return this.getSignature(Y)==Z?!0:!1}}class P{signer;constructor(Y){this.signer=new u(Y)}generate(Y=21){let $=_(Y).toString("base64");if($.endsWith("="))$=$.slice(0,-1);return this.signer.sign($)}}class x extends P{config;constructor(Y,Z){super(Z??"salty");this.config=Y}async openSession(Y,Z){if(Y&&this.signer.unsign(Y))return await this.fetchSession(Y,Z);return this.new}async fetchSession(Y,Z){return this.new}async saveSession(Y,Z,$=!1){return}get new(){return new J(this.generate(),{}).session}get readonly(){return new J(this.generate(),{},!0).session}get getExpiration(){let Y=new Date,Z=this.config.LIFETIME;return Y.setDate(Y.getDate()+Z).toString()}setCookie(Y,Z,$=""){let U=null,W={};if(this.config.COOKIE_SAMESITE)U=this.config.COOKIE_SAMESITE;if($)U=$;if(Z===0)W.maxAge=Z.toString();else W.expires=Z;return n.cookie(this.config.COOKIE_NAME,Y.sid,{domain:"",path:this.config.COOKIE_PATH,httpOnly:this.config.COOKIE_HTTPONLY,secure:this.config.COOKIE_SECURE,sameSite:U,...W})}async loadHeader(Y,Z){let $=async(W)=>{let Q="";if(W)Q=W.split(";").reduce((E,z)=>{let[B,X]=z.trim().split(/=(.*)/s);return E[B]=X,E},{}).session;let q=Q;return await this.openSession(q,Z)},U=Y.headers;if(U){if("get"in U)return await $(U.get("cookie"));else if("cookie"in U)return await $(U.cookie)}return this.new}}class k extends J{}class S{path;data;constructor(Y){this.data=new Map,this.path=Y+"/"}async init(Y){let Z=K(Y),$=this.path+Z,U=R($);if(await U.exists()){let W=await U.arrayBuffer();try{let Q=JSON.parse(O.decode(y(W)));return Q.f_timed=Date.now(),this.data.set(Z,Q),Q}catch(Q){}}return null}async checkLast(Y){let Z=new Date(Y);if(Z.setMinutes(Z.getMinutes()+60),Z.getTime()<Date.now())return!0;return!1}async get(Y){if(Y){let Z=this.data.get(Y);if(Z==null)return await this.init(Y);else{if(Z&&"f_timed"in Z){if(await this.checkLast(Z.f_timed))return await this.init(Y)}return Z}}return null}async set(Y,Z){let $=K(Y),U=this.path+$;O.file(U,""),await N(U,g(JSON.stringify(Z))),Z.f_timed=Date.now(),this.data.set(Y,Z)}async delete(Y){let Z=K(Y);this.data.delete(Z);let $=this.path+Z;R($).exists().then(async(U)=>{await m.unlink($)}).catch()}}class C extends x{isJWT;cacher;side=k;constructor(Y,Z=".sessions",$=!1){super(Y);this.isJWT=$;this.cacher=new S(Z)}life(Y,Z){let{LIFETIME:$,JWT_LIFETIME:U}=this.config;if(new H(Z).timed({day:this.isJWT?U:$}).getTime()-new Date().getTime()>0)return!0;else return this.cacher.delete(Y),!1}async fetchSession(Y,Z){let $=this.config.KEY_PREFIX+Y,U=await this.cacher.get($),W={};if(U){let Q=!0;if("life"in U)Q=this.life($,U.life);W=Q?JSON.parse(U.data):{}}return new this.side(Y,W,Z).session}async saveSession(Y,Z,$=!1){let U=(Q)=>{if(Z){let q=this.setCookie(Y,Q);if(Z)Z.set("Set-Cookie",q)}},W=this.config.KEY_PREFIX+Y.sid;if(!Y.length){if(!Y.new&&(Y.modified||$))this.cacher.delete(W),U(0);return}if(Y.new&&Y.modified){let Q=new H().timed({day:this.config.LIFETIME}),q=JSON.stringify(Y.data);await this.cacher.set(W,{data:q,life:H.now}),U(Q)}return}}class d{client;query;f_timed;data;key;constructor(Y,Z,$){this.query=$,this.key=Z,this.f_timed=Date.now(),this.data=new Map,this.client=Y}async init(Y){let Z=await this.client.query({text:this.query+` where ${this.key} = $1`,values:[Y]});for(let[$,U]of this.data)if(!U)this.data.delete($);if(Z.rowCount){let $=Z.rows[0];return $.f_timed=Date.now(),this.data.set(Y,$),$}else return this.data.set(Y,null),null}async checkLast(Y){let Z=new Date(Y);if(Z.setMinutes(Z.getMinutes()+15),Z.getTime()<Date.now())return!0;return!1}async get(Y){if(Y){let Z=this.data.get(Y);if(Z==null)return await this.init(Y);else{if(Z&&"f_timed"in Z){if(await this.checkLast(Z.f_timed))return await this.init(Y)}return Z}}return null}async set(Y){if(this.key in Y)Y.f_timed=Date.now(),this.data.set(Y[this.key],Y)}async delete(Y){this.data.delete(Y)}}class i extends P{salt;constructor(){super("salty_jwt");this.salt="salty_jwt"}sign(Y){let Z={issuer:this.salt};return T({data:Y},G(),Z)}get random(){let Y={issuer:this.salt},Z={data:p()};return T(Z,G(),Y)}jwt(){let Y=this.generate();return new J(Y).session}verify(Y,Z){try{let $=o(Y,G());if($){let{data:U,iat:W,iss:Q}=$;if(Q==this.salt)if(Z){let{days:q,hours:L,minutes:E,seconds:z}=Z,B=new Date(W*1000);if(q)B=new Date(B.setDate(B.getDate()+q));else if(L)B=new Date(B.setHours(B.getHours()+L));else if(E)B=new Date(B.setMinutes(B.getMinutes()+E));else if(z)B=new Date(B.setSeconds(B.getSeconds()+z));if(B.getTime()-Date.now()>0)return U}else return U}}catch($){}return null}open(Y,Z){if(Y){let $=this.verify(Y,Z);if($)return new J(Y,$,!0).session}return this.jwt()}save(Y){let Z=Y.data;if("access_token"in Z)delete Z.access_token;return this.sign(Z)}new(Y){return this.sign(Y)}}class s{fs;f_timed;data;key;dir;constructor({dir:Y,fs:Z,key:$}){this.dir=Y+"/ffs",this.key=$,this.f_timed=Date.now(),this.data=new Map,this.fs=this.dir+`/${Z}.json`}async init(){if(O.dir(this.dir)&&O.file(this.fs,"{}"))R(this.fs).text().then((Y)=>{let Z=JSON.parse(Y);this.data=new Map(I(Z))}).catch((Y)=>{})}async get(Y){let Z=this.data.get(Y);if(Z)return Z;return null}async set(Y){if(this.key in Y){let Z=await R(this.fs).text();if(Z){let $=JSON.parse(Z),U=Y[this.key];$[U]=Y,await N(this.fs,JSON.stringify($))}this.data.set(Y[this.key],Y)}}async delete(Y){if(await this.get(Y)){let Z=await R(this.fs).text();if(Z){let $=JSON.parse(Z.toString());if(Y in $)delete $[Y],await N(this.fs,JSON.stringify($));this.data.delete(Y)}}}async json(){let Y=await R(this.fs).text(),Z=JSON.parse(Y);return M(Z)}}export{K as decodeSID,J as ServerSide,d as PGCache,i as JWTInterface,s as Fjson,k as FSession,x as AuthInterface,l as Auth};
package/package.json CHANGED
@@ -1,11 +1,19 @@
1
1
  {
2
2
  "name": "authored",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "authored",
5
5
  "author": "Marky <markjotep@gmail.com>",
6
6
  "license": "MIT",
7
- "types": "index.d.ts",
8
- "main": "index.js",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "scripts": {
13
+ "cp_core": "mkdir -p ./src/core; cp -L ../_misc/@.ts ./src/core; cp -L ../_misc/@n.ts ./src/core;",
14
+ "link__": "mkdir -p ./src/core; ln -sf ../../../_misc/@.ts ./src/core; ln -sf ../../../_misc/@n.ts ./src/core; ln -sf ../_misc/tsconfig.json ./",
15
+ "build": "tsc && bun build ./src/index.ts --outdir ./dist --minify --packages external --target bun && rollup -c ./util/rollup.config.js"
16
+ },
9
17
  "keywords": [
10
18
  "ts",
11
19
  "bun"
@@ -18,9 +26,6 @@
18
26
  "url": "https://github.com/MARKjotep/authored/issues"
19
27
  },
20
28
  "homepage": "https://github.com/MARKjotep/authored#readme",
21
- "scripts": {
22
- "build": "tsc ; dist=../../DIST/authored/ ; cp -r package.json $dist ; cp -r ./types/types.d.ts $dist/types; bun install --cwd $dist; "
23
- },
24
29
  "dependencies": {
25
30
  "jsonwebtoken": "^9.0.2",
26
31
  "pg": "^8.13.1"
@@ -32,5 +37,6 @@
32
37
  "peerDependencies": {
33
38
  "typescript": "^5.0.0"
34
39
  },
35
- "bun": true
40
+ "bun": true,
41
+ "type": "module"
36
42
  }
package/index.js DELETED
@@ -1 +0,0 @@
1
- import{randomBytes as T}from"node:crypto";import{CryptoHasher as k,file as H,gunzipSync as c,gzipSync as o,write as C}from"bun";import{promises as h}from"node:fs";import{sign as b,verify as p}from"jsonwebtoken";import{CryptoHasher as x,file as O}from"bun";import{mkdirSync as S,writeFileSync as m}from"node:fs";var f=new TextDecoder,E={bool:(Y)=>typeof Y==="boolean",str:(Y)=>typeof Y==="string",arr:(Y)=>Array.isArray(Y),file:async(Y,Z)=>{try{m(Y,Z??"",{flag:"wx"})}catch($){}return!0},dir:(Y)=>{return S(Y,{recursive:!0}),!0},number:(Y)=>{return!isNaN(parseFloat(Y))&&isFinite(Y)},dict:(Y)=>{return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)},arraybuff:(Y)=>{return Y instanceof Uint8Array||Y instanceof ArrayBuffer||typeof Y==="string"}};var z={vals:Object.values,keys:Object.keys,items:Object.entries,has:Object.hasOwn,define:Object.defineProperty,ass:Object.assign,length:(Y)=>{return Object.keys(Y).length}},g={numSequence:(Y)=>Array.from({length:Y},(Z,$)=>$)},B={charU:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",charL:"abcdefghijklmnopqrstuvwxyz",nums:g.numSequence(9).join(""),rbytes:new RegExp(/(\d+)(\d*)/,"m"),strip:(Y,Z)=>Y.replace(new RegExp(`^${Z}|${Z}\$`,"g"),""),decode(Y){return f.decode(Y)},buffer(Y){return Buffer.from(Y)},digest(...Y){let Z=new Bun.CryptoHasher("sha256",L.secret());return Y.forEach(($)=>{Z.update($)}),Z.digest()},stringify(Y){return JSON.stringify(Y)},parse(Y){return JSON.parse(Y)}};class R{date;constructor(Y){this.date=Y?new Date(Y):new Date}delta(Y=null,Z=!1){let $=R.delta(this.date.getTime(),Y);return Z?new Date($):$}timed(Y){let Z=this.date.getTime(),$=this.date;if(Y){let{year:U,month:W,day:K,hour:Q,minute:q,second:P}=Y;if(U)$=new Date($.setFullYear($.getFullYear()+U));if(W)$=new Date($.setMonth($.getMonth()+W));if(K)$=new Date($.setDate($.getDate()+K));if(Q)$=new Date($.setHours($.getHours()+Q));if(q)$=new Date($.setMinutes($.getMinutes()+q));if(P)$=new Date($.setSeconds($.getSeconds()+P))}return $}static delta(Y,Z=null){if(Z)return Z-Y;else return Y-Date.now()}static get now(){return Date.now()}}var L={ok:12,secret:()=>{let Y=process.env.SECRET_KEY;if(!Y)throw new Error("'SECRET_KEY' not found in .env file");return Y},tls:(Y)=>{return z.items(process.env).filter((Z)=>{if(Z[0].startsWith("TLS_"))return Z}).reduce((Z,$)=>{let[U,W]=$;if(W){let K=U.replace("TLS_","").toLowerCase();Z[K]=O(Y+"/"+W)}return Z},{})},byteRange:(Y,Z)=>{let $=0,U=Y-1,[W,K]=Z.replace(/bytes=/,"").split("-");return $=parseInt(W,10),U=K?parseInt(K,10):U,[$,U,Y]},mimeType:(Y)=>{return O(Y).type},args:(Y,Z)=>{return Y.reduce(($,U,W)=>{return $[U]=Z[W],$},{})}},M={attr:(Y)=>{return z.items(Y).reduce((Z,[$,U])=>{return Z.push(E.bool(U)?$:`${$}="${U}"`),Z},[""]).join(" ")},head:(Y)=>{if(Y)return z.items(Y).reduce((Z,[$,U])=>{if(E.str(U))Z.push(`<${$}>${U}</${$}>`);else if(E.arr(U)){let W=U.reduce((K,Q)=>{let q="";if($=="script"){let P="";if("importmap"in Q)Q.type="importmap",P=JSON.stringify(Q.importmap),delete Q.importmap;else if("body"in Q)P=Q.body,delete Q.body;q=`${P}</${$}>`}return K.push(`<${$}${M.attr(Q)}>${q}`),K},[]);Z.push(...W)}return Z},[]);return[]},cookie:(Y,Z="",{maxAge:$,expires:U,path:W,domain:K,secure:Q,httpOnly:q,sameSite:P})=>{if($ instanceof Date)$=$.getSeconds();if(U instanceof Date)U=U.toUTCString();else if(U===0)U=new Date().toUTCString();return[["Domain",K],["Expires",U],["Max-Age",$],["Secure",Q],["HttpOnly",q],["Path",W],["SameSite",P]].reduce((j,[G,I])=>{if(I!==void 0)j.push(`${G}=${I}`);return j},[`${Y}=${Z}`]).join("; ")},html:(Y,Z,$)=>{let U=y.ID(5),W=Z,K=`<!DOCTYPE html><html lang="${$}">`;return K+=`<head>${W}</head>`,K+=`<body id="${U}">${Y}</body>`,K+="</html>",K}};function V(Y){let Z=new x("md5");return Z.update(Y),Z.digest("hex")}var y={ID:(Y)=>{let{charU:Z,charL:$,nums:U}=B,W=Z+$,K="",Q=0;while(Q<Y){let q=W+(Q==0?"":U),P=q.length;K+=q.charAt(Math.floor(Math.random()*P)),Q+=1}return K}};function n(Y=64){return new k("sha256").update(T(Y)).digest("hex")}class v{postgresClient;config={COOKIE_NAME:"session",COOKIE_DOMAIN:"127.0.0.1",COOKIE_PATH:"/",COOKIE_HTTPONLY:!0,COOKIE_SECURE:!0,REFRESH_EACH_REQUEST:!1,COOKIE_SAMESITE:"Strict",KEY_PREFIX:"session:",PERMANENT:!0,USE_SIGNER:!1,ID_LENGTH:32,FILE_THRESHOLD:500,LIFETIME:31,MAX_COOKIE_SIZE:4093,INTERFACE:"fs",STORAGE:".sessions",JWT_STORAGE:".jwt",JWT_LIFETIME:5};constructor({type:Y="fs",dir:Z}={}){Y&&(this.config.INTERFACE=Y),Z&&this.initStorage(Z)}initStorage(Y){return this.config.STORAGE=Y+"/"+this.config.STORAGE,this.config.JWT_STORAGE=Y+"/"+this.config.JWT_STORAGE,this}get session(){return new A(this.config,this.config.STORAGE)}get jwt(){return new A(this.config,this.config.JWT_STORAGE)}}class F{data;modified;new=!0;length=0;constructor(Y={}){if(this.modified=!0,this.data={},this.length=z.length(Y),this.length)this.new=!1;z.ass(this.data,Y)}set(Y,Z,$){if(!this.readonly&&Y.data[Z]!=$){if(this.modified=!0,!(Z in Y.data))this.length++;return Y.data[Z]=$,!0}return!1}get(Y,Z){if(Z in Y)return Y[Z];return Y.data[Z]}has(Y,Z){if(Z in Y.data)return!0;return!1}deleteProperty(Y,Z){if(!this.readonly&&Z in Y.data)this.modified=!0,delete Y.data[Z],this.length--;return!0}}class N extends F{Y;modified;readOnly;constructor(Y="",Z={},$=!1){super(Z);this.sid=Y;this.modified=!1,this.readOnly=$}get session(){return new Proxy(this,this)}}class _{Y;constructor(Y){this.salt=Y}getSignature(Y){let Z=this.deriveKey().toString();return B.digest(Z,Y).toString("base64")}deriveKey(){return B.digest(this.salt)}sign(Y){let Z=this.getSignature(Y),$=B.buffer(Y+"."+Z);return B.decode($)}unsign(Y){if(!(Y.indexOf(".")>-1))throw Error("No sep found");let Z=Y.indexOf("."),$=Y.slice(0,Z),U=Y.slice(Z+1);return this.verifySignature($,U)}loadUnsign(Y){if(this.unsign(Y)){let Z=B.buffer(Y),$=B.buffer(".").toString()[0];if(!($ in Z))throw Error("No sep found");let U=Z.indexOf($),W=Z.subarray(0,U);return Buffer.from(W.toString(),"base64").toString("utf-8")}}verifySignature(Y,Z){return this.getSignature(Y)==Z?!0:!1}}class X{signer;constructor(Y){this.signer=new _(Y)}generate(Y=21){let $=T(Y).toString("base64");if($.endsWith("="))$=$.slice(0,-1);return this.signer.sign($)}}class w extends X{Y;constructor(Y,Z){super(Z??"salty");this.config=Y}async openSession(Y,Z){if(Y&&this.signer.unsign(Y))return await this.fetchSession(Y,Z);return this.new}async fetchSession(Y,Z){return this.new}async saveSession(Y,Z,$=!1){return}get new(){return new N(this.generate(),{}).session}get readonly(){return new N(this.generate(),{},!0).session}get getExpiration(){let Y=new Date,Z=this.config.LIFETIME;return Y.setDate(Y.getDate()+Z).toString()}setCookie(Y,Z,$=""){let U=null,W={};if(this.config.COOKIE_SAMESITE)U=this.config.COOKIE_SAMESITE;if($)U=$;if(Z===0)W.maxAge=Z.toString();else W.expires=Z;return M.cookie(this.config.COOKIE_NAME,Y.sid,{domain:"",path:this.config.COOKIE_PATH,httpOnly:this.config.COOKIE_HTTPONLY,secure:this.config.COOKIE_SECURE,sameSite:U,...W})}async loadHeader(Y,Z){let $=async(W)=>{let K="";if(W)K=W.split(";").reduce((P,J)=>{let[j,G]=J.trim().split(/=(.*)/s);return P[j]=G,P},{}).session;let Q=K;return await this.openSession(Q,Z)},U=Y.headers;if(U){if("get"in U)return await $(U.get("cookie"));else if("cookie"in U)return await $(U.cookie)}return this.new}}class u extends N{}class D{path;data;constructor(Y){this.data=new Map,this.path=Y+"/"}async init(Y){let Z=V(Y),$=this.path+Z,U=H($);if(await U.exists()){let W=await U.arrayBuffer();try{let K=JSON.parse(B.decode(c(W)));return K.f_timed=Date.now(),this.data.set(Z,K),K}catch(K){}}return null}async checkLast(Y){let Z=new Date(Y);if(Z.setMinutes(Z.getMinutes()+60),Z.getTime()<Date.now())return!0;return!1}async get(Y){if(Y){let Z=this.data.get(Y);if(Z==null)return await this.init(Y);else{if(Z&&"f_timed"in Z){if(await this.checkLast(Z.f_timed))return await this.init(Y)}return Z}}return null}async set(Y,Z){let $=V(Y),U=this.path+$;await E.file(U,""),await C(U,o(JSON.stringify(Z))),Z.f_timed=Date.now(),this.data.set(Y,Z)}async delete(Y){let Z=V(Y);this.data.delete(Z);let $=this.path+Z;H($).exists().then(async(U)=>{await h.unlink($)}).catch()}}class A extends w{$;cacher;side=u;constructor(Y,Z=".sessions",$=!1){super(Y);this.isJWT=$;this.cacher=new D(Z)}life(Y,Z){let{LIFETIME:$,JWT_LIFETIME:U}=this.config;if(new R(Z).timed({day:this.isJWT?U:$}).getTime()-new Date().getTime()>0)return!0;else return this.cacher.delete(Y),!1}async fetchSession(Y,Z){let $=this.config.KEY_PREFIX+Y,U=await this.cacher.get($),W={};if(U){let K=!0;if("life"in U)K=this.life($,U.life);W=K?JSON.parse(U.data):{}}return new this.side(Y,W,Z).session}async saveSession(Y,Z,$=!1){let U=(K)=>{if(Z){let Q=this.setCookie(Y,K);if(Z)Z.set("Set-Cookie",Q)}},W=this.config.KEY_PREFIX+Y.sid;if(!Y.length){if(!Y.new&&(Y.modified||$))this.cacher.delete(W),U(0);return}if(Y.new&&Y.modified){let K=new R().timed({day:this.config.LIFETIME}),Q=JSON.stringify(Y.data);await this.cacher.set(W,{data:Q,life:R.now}),U(K)}return}}class l{client;query;f_timed;data;key;constructor(Y,Z,$){this.query=$,this.key=Z,this.f_timed=Date.now(),this.data=new Map,this.client=Y}async init(Y){let Z=await this.client.query({text:this.query+` where ${this.key} = \$1`,values:[Y]});for(let[$,U]of this.data)if(!U)this.data.delete($);if(Z.rowCount){let $=Z.rows[0];return $.f_timed=Date.now(),this.data.set(Y,$),$}else return this.data.set(Y,null),null}async checkLast(Y){let Z=new Date(Y);if(Z.setMinutes(Z.getMinutes()+15),Z.getTime()<Date.now())return!0;return!1}async get(Y){if(Y){let Z=this.data.get(Y);if(Z==null)return await this.init(Y);else{if(Z&&"f_timed"in Z){if(await this.checkLast(Z.f_timed))return await this.init(Y)}return Z}}return null}async set(Y){if(this.key in Y)Y.f_timed=Date.now(),this.data.set(Y[this.key],Y)}async delete(Y){this.data.delete(Y)}}class i extends X{salt;constructor(){super("salty_jwt");this.salt="salty_jwt"}sign(Y){let Z={issuer:this.salt};return b({data:Y},L.secret(),Z)}get random(){let Y={issuer:this.salt},Z={data:n()};return b(Z,L.secret(),Y)}jwt(){let Y=this.generate();return new N(Y).session}verify(Y,Z){try{let $=p(Y,L.secret());if($){let{data:U,iat:W,iss:K}=$;if(K==this.salt)if(Z){let{days:Q,hours:q,minutes:P,seconds:J}=Z,j=new Date(W*1000);if(Q)j=new Date(j.setDate(j.getDate()+Q));else if(q)j=new Date(j.setHours(j.getHours()+q));else if(P)j=new Date(j.setMinutes(j.getMinutes()+P));else if(J)j=new Date(j.setSeconds(j.getSeconds()+J));if(j.getTime()-Date.now()>0)return U}else return U}}catch($){}return null}open(Y,Z){if(Y){let $=this.verify(Y,Z);if($)return new N(Y,$,!0).session}return this.jwt()}save(Y){let Z=Y.data;if("access_token"in Z)delete Z.access_token;return this.sign(Z)}new(Y){return this.sign(Y)}}class d{fs;f_timed;data;key;dir;constructor({dir:Y,fs:Z,key:$}){this.dir=Y+"/ffs",this.key=$,this.f_timed=Date.now(),this.data=new Map,this.fs=this.dir+`/${Z}.json`}async init(){if(E.dir(this.dir)&&await E.file(this.fs,"{}"))H(this.fs).text().then((Y)=>{let Z=JSON.parse(Y);this.data=new Map(z.items(Z))}).catch((Y)=>{})}async get(Y){let Z=this.data.get(Y);if(Z)return Z;return null}async set(Y){if(this.key in Y){let Z=await H(this.fs).text();if(Z){let $=JSON.parse(Z),U=Y[this.key];$[U]=Y,await C(this.fs,JSON.stringify($))}this.data.set(Y[this.key],Y)}}async delete(Y){if(await this.get(Y)){let Z=await H(this.fs).text();if(Z){let $=JSON.parse(Z.toString());if(Y in $)delete $[Y],await C(this.fs,JSON.stringify($));this.data.delete(Y)}}}async json(){let Y=await H(this.fs).text(),Z=JSON.parse(Y);return z.vals(Z)}}export{N as ServerSide,l as PGCache,i as JWTInterface,d as Fjson,u as FSession,w as AuthInterface,v as Auth};
package/jsconfig.json DELETED
@@ -1,27 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- // Enable latest features
4
- "lib": ["ESNext", "DOM"],
5
- "target": "ESNext",
6
- "module": "ESNext",
7
- "moduleDetection": "force",
8
- "jsx": "react-jsx",
9
- "allowJs": true,
10
-
11
- // Bundler mode
12
- "moduleResolution": "bundler",
13
- "allowImportingTsExtensions": true,
14
- "verbatimModuleSyntax": true,
15
- "noEmit": true,
16
-
17
- // Best practices
18
- "strict": true,
19
- "skipLibCheck": true,
20
- "noFallthroughCasesInSwitch": true,
21
-
22
- // Some stricter flags (disabled by default)
23
- "noUnusedLocals": false,
24
- "noUnusedParameters": false,
25
- "noPropertyAccessFromIndexSignature": false
26
- }
27
- }