authored 0.0.1 → 0.0.2
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.
- package/index.d.ts +142 -33
- package/index.js +1 -216
- package/package.json +6 -6
- package/types/index.d.ts +0 -60
- package/types/types.d.ts +0 -6
package/index.d.ts
CHANGED
|
@@ -1,35 +1,14 @@
|
|
|
1
1
|
import { Client } from "pg";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
};
|
|
13
|
-
keys: {
|
|
14
|
-
(o: object): string[];
|
|
15
|
-
(o: {}): string[];
|
|
16
|
-
};
|
|
17
|
-
items: {
|
|
18
|
-
<T>(o: {
|
|
19
|
-
[s: string]: T;
|
|
20
|
-
} | ArrayLike<T>): [string, T][];
|
|
21
|
-
(o: {}): [string, any][];
|
|
22
|
-
};
|
|
23
|
-
has: (o: object, v: PropertyKey) => boolean;
|
|
24
|
-
define: <T>(o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType<any>) => T;
|
|
25
|
-
ass: {
|
|
26
|
-
<T extends {}, U>(target: T, source: U): T & U;
|
|
27
|
-
<T extends {}, U, V>(target: T, source1: U, source2: V): T & U & V;
|
|
28
|
-
<T extends {}, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
|
|
29
|
-
(target: object, ...sources: any[]): any;
|
|
30
|
-
};
|
|
31
|
-
length: (ob: Object) => number;
|
|
32
|
-
};
|
|
2
|
+
interface obj<T> {
|
|
3
|
+
[Key: string]: T;
|
|
4
|
+
}
|
|
5
|
+
interface fs {
|
|
6
|
+
[key: string]: string | undefined | boolean | number;
|
|
7
|
+
}
|
|
8
|
+
interface bs {
|
|
9
|
+
f_timed?: number;
|
|
10
|
+
[key: string]: string | undefined | boolean | number;
|
|
11
|
+
}
|
|
33
12
|
type authConfig = {
|
|
34
13
|
COOKIE_NAME: string;
|
|
35
14
|
COOKIE_DOMAIN: string;
|
|
@@ -54,7 +33,137 @@ type dbs = "fs" | "postgres";
|
|
|
54
33
|
export declare class Auth {
|
|
55
34
|
postgresClient?: Client;
|
|
56
35
|
config: authConfig;
|
|
57
|
-
constructor(type
|
|
58
|
-
|
|
36
|
+
constructor({ type, dir }?: {
|
|
37
|
+
type?: dbs;
|
|
38
|
+
dir?: string;
|
|
39
|
+
});
|
|
40
|
+
initStorage(path: string): this;
|
|
41
|
+
get session(): AuthInterface;
|
|
42
|
+
get jwt(): FSInterface;
|
|
43
|
+
}
|
|
44
|
+
declare class callBack {
|
|
45
|
+
[Key: string]: any;
|
|
46
|
+
data: obj<string>;
|
|
47
|
+
modified: boolean;
|
|
48
|
+
new: boolean;
|
|
49
|
+
length: number;
|
|
50
|
+
constructor(initial?: obj<string>);
|
|
51
|
+
set(target: any, prop: string, val: string): boolean;
|
|
52
|
+
get(target: any, prop: string): any;
|
|
53
|
+
has(target: any, prop: string): boolean;
|
|
54
|
+
deleteProperty(target: any, val: string): boolean;
|
|
55
|
+
}
|
|
56
|
+
export declare class ServerSide extends callBack {
|
|
57
|
+
sid: string;
|
|
58
|
+
[Key: string]: any;
|
|
59
|
+
modified: boolean;
|
|
60
|
+
private readonly readOnly;
|
|
61
|
+
constructor(sid?: string, initial?: obj<string>, readonly?: boolean);
|
|
62
|
+
get session(): ServerSide;
|
|
63
|
+
}
|
|
64
|
+
declare class Signator {
|
|
65
|
+
salt: string;
|
|
66
|
+
constructor(salt: string);
|
|
67
|
+
getSignature(val: string): string;
|
|
68
|
+
deriveKey(): Buffer;
|
|
69
|
+
sign(val: string): string;
|
|
70
|
+
unsign(signedVal: string): boolean;
|
|
71
|
+
loadUnsign(vals: string): string | undefined;
|
|
72
|
+
verifySignature(val: string, sig: string): boolean;
|
|
73
|
+
}
|
|
74
|
+
declare class sidGenerator {
|
|
75
|
+
signer: Signator;
|
|
76
|
+
constructor(salt: string);
|
|
77
|
+
generate(len?: number): string;
|
|
78
|
+
}
|
|
79
|
+
export declare class AuthInterface extends sidGenerator {
|
|
80
|
+
config: authConfig;
|
|
81
|
+
constructor(config: authConfig, salt?: string);
|
|
82
|
+
openSession(sid?: string, readonly?: boolean): Promise<ServerSide>;
|
|
83
|
+
fetchSession(sid: string, readonly?: boolean): Promise<ServerSide>;
|
|
84
|
+
saveSession(sesh: ServerSide, X?: Headers, deleteMe?: boolean): Promise<void>;
|
|
85
|
+
get new(): ServerSide;
|
|
86
|
+
get readonly(): ServerSide;
|
|
87
|
+
get getExpiration(): string | null;
|
|
88
|
+
setCookie(xsesh: ServerSide, life: Date | number, _sameSite?: string): string;
|
|
89
|
+
loadHeader(req: any, readonly?: boolean): Promise<ServerSide>;
|
|
90
|
+
}
|
|
91
|
+
export declare class FSession extends ServerSide {
|
|
92
|
+
}
|
|
93
|
+
interface ffcache {
|
|
94
|
+
[key: string]: string | undefined | boolean | number;
|
|
95
|
+
f_timed?: number;
|
|
96
|
+
data: string;
|
|
97
|
+
life: number;
|
|
98
|
+
}
|
|
99
|
+
declare class FSCached<T extends bs> {
|
|
100
|
+
path: string;
|
|
101
|
+
data: Map<any, T>;
|
|
102
|
+
constructor(folderpath: string);
|
|
103
|
+
init(val: string): Promise<T | null>;
|
|
104
|
+
checkLast(time: number): Promise<boolean>;
|
|
105
|
+
get(val: string | undefined): Promise<T | null>;
|
|
106
|
+
set(val: string, data: T): Promise<void>;
|
|
107
|
+
delete(key: string): Promise<void>;
|
|
108
|
+
}
|
|
109
|
+
declare class FSInterface extends AuthInterface {
|
|
110
|
+
isJWT: boolean;
|
|
111
|
+
cacher: FSCached<ffcache>;
|
|
112
|
+
side: typeof FSession;
|
|
113
|
+
constructor(config: authConfig, cacherpath?: string, isJWT?: boolean);
|
|
114
|
+
life(key: string, lstr: number): boolean;
|
|
115
|
+
fetchSession(sid: string, readonly?: boolean): Promise<ServerSide>;
|
|
116
|
+
saveSession(sesh: ServerSide, X?: Headers, deleteMe?: boolean): Promise<void>;
|
|
117
|
+
}
|
|
118
|
+
export declare class PGCache<T extends bs> {
|
|
119
|
+
client: Client;
|
|
120
|
+
query: string;
|
|
121
|
+
f_timed: number;
|
|
122
|
+
data: Map<any, T>;
|
|
123
|
+
key: string;
|
|
124
|
+
constructor(client: Client, key: string, query: string);
|
|
125
|
+
init(val: string): Promise<T | null>;
|
|
126
|
+
checkLast(time: number): Promise<boolean>;
|
|
127
|
+
get(val: string | undefined): Promise<T | null>;
|
|
128
|
+
set(data: T): Promise<void>;
|
|
129
|
+
delete(key: string): Promise<void>;
|
|
130
|
+
}
|
|
131
|
+
export declare class JWTInterface extends sidGenerator {
|
|
132
|
+
salt: string;
|
|
133
|
+
constructor();
|
|
134
|
+
sign(payload: obj<any>): string;
|
|
135
|
+
get random(): string;
|
|
136
|
+
jwt(): ServerSide;
|
|
137
|
+
verify(payload: string, time?: {
|
|
138
|
+
days?: number;
|
|
139
|
+
hours?: number;
|
|
140
|
+
minutes?: number;
|
|
141
|
+
seconds?: number;
|
|
142
|
+
}): obj<string> | null;
|
|
143
|
+
open(token: string, time?: {
|
|
144
|
+
days?: number;
|
|
145
|
+
hours?: number;
|
|
146
|
+
minutes?: number;
|
|
147
|
+
seconds?: number;
|
|
148
|
+
}): ServerSide;
|
|
149
|
+
save(xjwts: ServerSide): string;
|
|
150
|
+
new(payload: obj<any>): string;
|
|
151
|
+
}
|
|
152
|
+
export declare class Fjson<T extends fs> {
|
|
153
|
+
fs: string;
|
|
154
|
+
f_timed: number;
|
|
155
|
+
data: Map<any, T>;
|
|
156
|
+
key: string;
|
|
157
|
+
dir: string;
|
|
158
|
+
constructor({ dir, fs, key }: {
|
|
159
|
+
dir: string;
|
|
160
|
+
fs: string;
|
|
161
|
+
key: string;
|
|
162
|
+
});
|
|
163
|
+
init(): Promise<void>;
|
|
164
|
+
get(val: string | undefined): Promise<T | null>;
|
|
165
|
+
set(data: T): Promise<void>;
|
|
166
|
+
delete(key: string): Promise<void>;
|
|
167
|
+
json(): Promise<unknown[]>;
|
|
59
168
|
}
|
|
60
169
|
export {};
|
package/index.js
CHANGED
|
@@ -1,216 +1 @@
|
|
|
1
|
-
import { randomBytes, createCipheriv, createDecipheriv } from "node:crypto";
|
|
2
|
-
import { CryptoHasher } from "bun";
|
|
3
|
-
export const $$ = {
|
|
4
|
-
set p(a) {
|
|
5
|
-
if (Array.isArray(a)) {
|
|
6
|
-
console.log(...a);
|
|
7
|
-
}
|
|
8
|
-
else {
|
|
9
|
-
console.log(a);
|
|
10
|
-
}
|
|
11
|
-
},
|
|
12
|
-
textD: new TextDecoder(),
|
|
13
|
-
};
|
|
14
|
-
export const O = {
|
|
15
|
-
vals: Object.values,
|
|
16
|
-
keys: Object.keys,
|
|
17
|
-
items: Object.entries,
|
|
18
|
-
has: Object.hasOwn,
|
|
19
|
-
define: Object.defineProperty,
|
|
20
|
-
ass: Object.assign,
|
|
21
|
-
length: (ob) => {
|
|
22
|
-
return Object.keys(ob).length;
|
|
23
|
-
},
|
|
24
|
-
};
|
|
25
|
-
export class Auth {
|
|
26
|
-
postgresClient;
|
|
27
|
-
config = {
|
|
28
|
-
COOKIE_NAME: "session",
|
|
29
|
-
COOKIE_DOMAIN: "127.0.0.1",
|
|
30
|
-
COOKIE_PATH: "/",
|
|
31
|
-
COOKIE_HTTPONLY: true,
|
|
32
|
-
COOKIE_SECURE: true,
|
|
33
|
-
REFRESH_EACH_REQUEST: false,
|
|
34
|
-
COOKIE_SAMESITE: "Strict",
|
|
35
|
-
KEY_PREFIX: "session:",
|
|
36
|
-
PERMANENT: true,
|
|
37
|
-
USE_SIGNER: false,
|
|
38
|
-
ID_LENGTH: 32,
|
|
39
|
-
FILE_THRESHOLD: 500,
|
|
40
|
-
LIFETIME: 31,
|
|
41
|
-
MAX_COOKIE_SIZE: 4093,
|
|
42
|
-
INTERFACE: "fs",
|
|
43
|
-
STORAGE: ".sessions",
|
|
44
|
-
JWT_STORAGE: ".jwt",
|
|
45
|
-
JWT_LIFETIME: 5,
|
|
46
|
-
};
|
|
47
|
-
constructor(type) {
|
|
48
|
-
this.config.INTERFACE = type;
|
|
49
|
-
}
|
|
50
|
-
initStorage(path = "./") {
|
|
51
|
-
this.config.STORAGE = path + this.config.STORAGE;
|
|
52
|
-
this.config.JWT_STORAGE = path + this.config.JWT_STORAGE;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
class callBack {
|
|
56
|
-
data;
|
|
57
|
-
modified;
|
|
58
|
-
new = true;
|
|
59
|
-
length = 0;
|
|
60
|
-
constructor(initial = {}) {
|
|
61
|
-
this.modified = true;
|
|
62
|
-
this.data = {};
|
|
63
|
-
this.length = O.length(initial);
|
|
64
|
-
if (this.length) {
|
|
65
|
-
this.new = false;
|
|
66
|
-
}
|
|
67
|
-
O.ass(this.data, initial);
|
|
68
|
-
}
|
|
69
|
-
set(target, prop, val) {
|
|
70
|
-
if (!this.readonly && target.data[prop] != val) {
|
|
71
|
-
this.modified = true;
|
|
72
|
-
target.data[prop] = val;
|
|
73
|
-
if (!(prop in target.data)) {
|
|
74
|
-
this.length++;
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
return target;
|
|
78
|
-
}
|
|
79
|
-
get(target, prop) {
|
|
80
|
-
if (prop in target) {
|
|
81
|
-
return target[prop];
|
|
82
|
-
}
|
|
83
|
-
return target.data[prop];
|
|
84
|
-
}
|
|
85
|
-
has(target, prop) {
|
|
86
|
-
if (prop in target.data) {
|
|
87
|
-
return true;
|
|
88
|
-
}
|
|
89
|
-
return false;
|
|
90
|
-
}
|
|
91
|
-
deleteProperty(target, val) {
|
|
92
|
-
if (!this.readonly && val in target.data) {
|
|
93
|
-
this.modified = true;
|
|
94
|
-
delete target.data[val];
|
|
95
|
-
}
|
|
96
|
-
return true;
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
class ServerSide extends callBack {
|
|
100
|
-
modified;
|
|
101
|
-
sid;
|
|
102
|
-
readonly;
|
|
103
|
-
constructor(sid = "", initial = {}, readonly = false) {
|
|
104
|
-
super(initial);
|
|
105
|
-
this.modified = false;
|
|
106
|
-
this.sid = sid;
|
|
107
|
-
this.readonly = readonly;
|
|
108
|
-
}
|
|
109
|
-
get session() {
|
|
110
|
-
return new Proxy(this, this);
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
function hmacDigest(salt) {
|
|
114
|
-
const hmac = new Bun.CryptoHasher("sha256", salt);
|
|
115
|
-
return hmac.digest();
|
|
116
|
-
}
|
|
117
|
-
function str2Buffer(str) {
|
|
118
|
-
return Buffer.from(str);
|
|
119
|
-
}
|
|
120
|
-
function decode(str) {
|
|
121
|
-
return $$.textD.decode(str);
|
|
122
|
-
}
|
|
123
|
-
class Signator {
|
|
124
|
-
salt;
|
|
125
|
-
constructor(salt) {
|
|
126
|
-
this.salt = salt;
|
|
127
|
-
}
|
|
128
|
-
getSignature(val) {
|
|
129
|
-
const vals = str2Buffer(val);
|
|
130
|
-
return hmacDigest(this.salt).toString("base64");
|
|
131
|
-
}
|
|
132
|
-
deriveKey() {
|
|
133
|
-
return hmacDigest(this.salt);
|
|
134
|
-
}
|
|
135
|
-
sign(val) {
|
|
136
|
-
const sig = this.getSignature(val);
|
|
137
|
-
const vals = str2Buffer(val + "." + sig);
|
|
138
|
-
return decode(vals);
|
|
139
|
-
}
|
|
140
|
-
unsign(signedVal) {
|
|
141
|
-
if (!(signedVal.indexOf(".") > -1)) {
|
|
142
|
-
throw Error("No sep found");
|
|
143
|
-
}
|
|
144
|
-
const isept = signedVal.indexOf(".");
|
|
145
|
-
const val = signedVal.slice(0, isept);
|
|
146
|
-
const sig = signedVal.slice(isept + 1);
|
|
147
|
-
return this.verifySignature(val, sig);
|
|
148
|
-
}
|
|
149
|
-
loadUnsign(vals) {
|
|
150
|
-
if (this.unsign(vals)) {
|
|
151
|
-
const sval = str2Buffer(vals);
|
|
152
|
-
const sept = str2Buffer(".").toString()[0];
|
|
153
|
-
if (!(sept in sval)) {
|
|
154
|
-
throw Error("No sep found");
|
|
155
|
-
}
|
|
156
|
-
const isept = sval.indexOf(sept);
|
|
157
|
-
const val = sval.subarray(0, isept);
|
|
158
|
-
return Buffer.from(val.toString(), "base64").toString("utf-8");
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
verifySignature(val, sig) {
|
|
162
|
-
return this.getSignature(val) == sig ? true : false;
|
|
163
|
-
}
|
|
164
|
-
generate(len = 21) {
|
|
165
|
-
const rbyte = randomBytes(len);
|
|
166
|
-
let lbyte = rbyte.toString("base64");
|
|
167
|
-
if (lbyte.endsWith("=")) {
|
|
168
|
-
lbyte = lbyte.slice(0, -1);
|
|
169
|
-
}
|
|
170
|
-
return this.sign(lbyte);
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
class AuthInterface extends Signator {
|
|
174
|
-
constructor(salt) {
|
|
175
|
-
super(salt ?? "salty");
|
|
176
|
-
}
|
|
177
|
-
async openSession(sid) {
|
|
178
|
-
if (this.unsign(sid))
|
|
179
|
-
return await this.fetchSession(sid);
|
|
180
|
-
return this.new;
|
|
181
|
-
}
|
|
182
|
-
async fetchSession(sid) {
|
|
183
|
-
return this.new;
|
|
184
|
-
}
|
|
185
|
-
async saveSession() {
|
|
186
|
-
return;
|
|
187
|
-
}
|
|
188
|
-
get new() {
|
|
189
|
-
return new ServerSide(this.generate(), {}).session;
|
|
190
|
-
}
|
|
191
|
-
get readonly() {
|
|
192
|
-
return new ServerSide(this.generate(), {}, true).session;
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
const sk = "helloworld";
|
|
196
|
-
const CH = new CryptoHasher("sha256");
|
|
197
|
-
function dSecret() {
|
|
198
|
-
return CH.copy().update(sk).digest();
|
|
199
|
-
}
|
|
200
|
-
function encrypt(text) {
|
|
201
|
-
const secretKey = dSecret();
|
|
202
|
-
const iv = randomBytes(16);
|
|
203
|
-
const cipher = createCipheriv("aes-256-cbc", secretKey, iv);
|
|
204
|
-
let encrypted = cipher.update(text, "utf8", "hex");
|
|
205
|
-
encrypted += cipher.final("hex");
|
|
206
|
-
return `${iv.toString("hex")}:${encrypted}`;
|
|
207
|
-
}
|
|
208
|
-
function decrypt(encryptedData) {
|
|
209
|
-
const secretKey = dSecret();
|
|
210
|
-
const [ivHex, encryptedText] = encryptedData.split(":");
|
|
211
|
-
const iv = Buffer.from(ivHex, "hex");
|
|
212
|
-
const decipher = createDecipheriv("aes-256-cbc", secretKey, iv);
|
|
213
|
-
let decrypted = decipher.update(encryptedText, "hex", "utf8");
|
|
214
|
-
decrypted += decipher.final("utf8");
|
|
215
|
-
return decrypted;
|
|
216
|
-
}
|
|
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/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "authored",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.2",
|
|
4
4
|
"description": "authored",
|
|
5
5
|
"author": "Marky <markjotep@gmail.com>",
|
|
6
6
|
"license": "MIT",
|
|
7
|
-
"types": "
|
|
7
|
+
"types": "index.d.ts",
|
|
8
8
|
"main": "index.js",
|
|
9
9
|
"keywords": [
|
|
10
10
|
"ts",
|
|
@@ -27,10 +27,10 @@
|
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"@types/jsonwebtoken": "^9.0.7",
|
|
30
|
-
"@types/pg": "^8.11.10"
|
|
31
|
-
"@types/bun": "latest"
|
|
30
|
+
"@types/pg": "^8.11.10"
|
|
32
31
|
},
|
|
33
32
|
"peerDependencies": {
|
|
34
33
|
"typescript": "^5.0.0"
|
|
35
|
-
}
|
|
36
|
-
|
|
34
|
+
},
|
|
35
|
+
"bun": true
|
|
36
|
+
}
|
package/types/index.d.ts
DELETED
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
import { Client } from "pg";
|
|
2
|
-
export declare const $$: {
|
|
3
|
-
p: any;
|
|
4
|
-
textD: TextDecoder;
|
|
5
|
-
};
|
|
6
|
-
export declare const O: {
|
|
7
|
-
vals: {
|
|
8
|
-
<T>(o: {
|
|
9
|
-
[s: string]: T;
|
|
10
|
-
} | ArrayLike<T>): T[];
|
|
11
|
-
(o: {}): any[];
|
|
12
|
-
};
|
|
13
|
-
keys: {
|
|
14
|
-
(o: object): string[];
|
|
15
|
-
(o: {}): string[];
|
|
16
|
-
};
|
|
17
|
-
items: {
|
|
18
|
-
<T>(o: {
|
|
19
|
-
[s: string]: T;
|
|
20
|
-
} | ArrayLike<T>): [string, T][];
|
|
21
|
-
(o: {}): [string, any][];
|
|
22
|
-
};
|
|
23
|
-
has: (o: object, v: PropertyKey) => boolean;
|
|
24
|
-
define: <T>(o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType<any>) => T;
|
|
25
|
-
ass: {
|
|
26
|
-
<T extends {}, U>(target: T, source: U): T & U;
|
|
27
|
-
<T extends {}, U, V>(target: T, source1: U, source2: V): T & U & V;
|
|
28
|
-
<T extends {}, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
|
|
29
|
-
(target: object, ...sources: any[]): any;
|
|
30
|
-
};
|
|
31
|
-
length: (ob: Object) => number;
|
|
32
|
-
};
|
|
33
|
-
type authConfig = {
|
|
34
|
-
COOKIE_NAME: string;
|
|
35
|
-
COOKIE_DOMAIN: string;
|
|
36
|
-
COOKIE_PATH: string;
|
|
37
|
-
COOKIE_HTTPONLY: boolean;
|
|
38
|
-
COOKIE_SECURE: boolean;
|
|
39
|
-
REFRESH_EACH_REQUEST: boolean;
|
|
40
|
-
COOKIE_SAMESITE: string;
|
|
41
|
-
KEY_PREFIX: string;
|
|
42
|
-
PERMANENT: boolean;
|
|
43
|
-
USE_SIGNER: boolean;
|
|
44
|
-
ID_LENGTH: number;
|
|
45
|
-
FILE_THRESHOLD: number;
|
|
46
|
-
LIFETIME: number;
|
|
47
|
-
MAX_COOKIE_SIZE: number;
|
|
48
|
-
INTERFACE: dbs;
|
|
49
|
-
STORAGE: string;
|
|
50
|
-
JWT_STORAGE: string;
|
|
51
|
-
JWT_LIFETIME: number;
|
|
52
|
-
};
|
|
53
|
-
type dbs = "fs" | "postgres";
|
|
54
|
-
export declare class Auth {
|
|
55
|
-
postgresClient?: Client;
|
|
56
|
-
config: authConfig;
|
|
57
|
-
constructor(type: dbs);
|
|
58
|
-
initStorage(path?: string): void;
|
|
59
|
-
}
|
|
60
|
-
export {};
|