authenik8-core 1.0.3 → 1.0.29
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/README.md +7 -0
- package/dist/auth/guestModeService.d.ts +4 -1
- package/dist/auth/guestModeService.d.ts.map +1 -1
- package/dist/auth/guestModeService.js +31 -20
- package/dist/auth/guestModeService.js.map +1 -1
- package/dist/auth/jwtAuth.d.ts +2 -1
- package/dist/auth/jwtAuth.d.ts.map +1 -1
- package/dist/auth/jwtAuth.js +26 -8
- package/dist/auth/jwtAuth.js.map +1 -1
- package/dist/auth/refreshService.d.ts +2 -0
- package/dist/auth/refreshService.d.ts.map +1 -1
- package/dist/auth/refreshService.js +12 -5
- package/dist/auth/refreshService.js.map +1 -1
- package/dist/createAuthenik8.d.ts.map +1 -1
- package/dist/createAuthenik8.js +31 -13
- package/dist/createAuthenik8.js.map +1 -1
- package/dist/middleware/adminService.d.ts +1 -1
- package/dist/middleware/adminService.d.ts.map +1 -1
- package/dist/middleware/adminService.js +6 -10
- package/dist/middleware/adminService.js.map +1 -1
- package/dist/oauth/adapters/memoryAdapter.d.ts.map +1 -1
- package/dist/oauth/adapters/memoryAdapter.js +5 -4
- package/dist/oauth/adapters/memoryAdapter.js.map +1 -1
- package/dist/oauth/adapters/redisAdapter.d.ts +23 -0
- package/dist/oauth/adapters/redisAdapter.d.ts.map +1 -0
- package/dist/oauth/adapters/redisAdapter.js +116 -0
- package/dist/oauth/adapters/redisAdapter.js.map +1 -0
- package/dist/oauth/brain/identityEngine.d.ts.map +1 -1
- package/dist/oauth/brain/identityEngine.js +26 -7
- package/dist/oauth/brain/identityEngine.js.map +1 -1
- package/dist/oauth/identity/types.d.ts +6 -1
- package/dist/oauth/identity/types.d.ts.map +1 -1
- package/dist/oauth/providers/github.d.ts.map +1 -1
- package/dist/oauth/providers/github.js +6 -7
- package/dist/oauth/providers/github.js.map +1 -1
- package/dist/oauth/providers/google.d.ts.map +1 -1
- package/dist/oauth/providers/google.js +3 -28
- package/dist/oauth/providers/google.js.map +1 -1
- package/dist/oauth/types.d.ts +1 -0
- package/dist/oauth/types.d.ts.map +1 -1
- package/dist/oauth/userStore.d.ts +1 -0
- package/dist/oauth/userStore.d.ts.map +1 -1
- package/dist/oauth/userStore.js +6 -1
- package/dist/oauth/userStore.js.map +1 -1
- package/dist/redis/redisService.d.ts +3 -1
- package/dist/redis/redisService.d.ts.map +1 -1
- package/dist/redis/redisService.js +10 -9
- package/dist/redis/redisService.js.map +1 -1
- package/dist/security/ipService.d.ts +3 -0
- package/dist/security/ipService.d.ts.map +1 -1
- package/dist/security/ipService.js +30 -9
- package/dist/security/ipService.js.map +1 -1
- package/dist/security/limiter.d.ts +16 -1
- package/dist/security/limiter.d.ts.map +1 -1
- package/dist/security/limiter.js +34 -13
- package/dist/security/limiter.js.map +1 -1
- package/dist/storage/RedisTokenStore.d.ts.map +1 -1
- package/dist/storage/RedisTokenStore.js +3 -2
- package/dist/storage/RedisTokenStore.js.map +1 -1
- package/dist/storage/userStorage.js +1 -2
- package/dist/storage/userStorage.js.map +1 -1
- package/dist/types/config.d.ts +3 -0
- package/dist/types/config.d.ts.map +1 -1
- package/package.json +23 -13
- package/dump.rdb +0 -0
- package/jest.config.js +0 -11
- package/src/auth/guestModeService.ts +0 -31
- package/src/auth/jwtAuth.ts +0 -99
- package/src/auth/refreshService.ts +0 -157
- package/src/createAuthenik8.ts +0 -135
- package/src/dump.rdb +0 -0
- package/src/index.ts +0 -2
- package/src/middleware/adminService.ts +0 -50
- package/src/oauth/adapters/memoryAdapter.ts +0 -74
- package/src/oauth/brain/identityEngine.ts +0 -141
- package/src/oauth/brain/identityPolicy.ts +0 -4
- package/src/oauth/brain/identityResolver.ts +0 -43
- package/src/oauth/brain/types.ts +0 -9
- package/src/oauth/core.ts +0 -19
- package/src/oauth/identity/1 +0 -44
- package/src/oauth/identity/types.ts +0 -44
- package/src/oauth/providers/github.ts +0 -154
- package/src/oauth/providers/google.ts +0 -189
- package/src/oauth/types/identity.ts +0 -17
- package/src/oauth/types.ts +0 -24
- package/src/oauth/userStore.ts +0 -73
- package/src/redis/redisService.ts +0 -137
- package/src/security/ipService.ts +0 -180
- package/src/security/limiter.ts +0 -116
- package/src/storage/RedisTokenStore.ts +0 -110
- package/src/storage/userStorage.ts +0 -16
- package/src/tests/con.test.ts +0 -76
- package/src/tests/dump.rdb +0 -0
- package/src/tests/full.intergration.test.ts +0 -100
- package/src/tests/oauth.intergration.test.ts +0 -39
- package/src/tests/oauth1.test.ts +0 -145
- package/src/tests/oauth2.test.ts +0 -158
- package/src/tests/oauth3.test.ts +0 -171
- package/src/tests/testApp.ts +0 -56
- package/src/types/admin.ts +0 -7
- package/src/types/config.ts +0 -17
- package/src/types/public.ts +0 -48
- package/src/types/storage.ts +0 -15
- package/src/types/tokens.ts +0 -10
- package/src/utility/lockHelper.ts +0 -33
- package/tsconfig.json +0 -51
|
@@ -1,180 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
import helmet from "helmet";
|
|
3
|
-
import Redis from "ioredis";
|
|
4
|
-
import type {StringValue} from "ms"
|
|
5
|
-
import { RequestHandler } from "express";
|
|
6
|
-
import {RateLimiterRedis} from "rate-limiter-flexible";
|
|
7
|
-
import { Request, Response, NextFunction } from "express";
|
|
8
|
-
import { HelmetOptions } from "helmet";
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
const WHITELIST_KEY ="whitelist:ips";
|
|
12
|
-
const IP_EXPIRATION_SECONDS = 7 * 24 * 60 * 60;
|
|
13
|
-
const DEFAULT_JWT_EXPIRY = "1h"
|
|
14
|
-
|
|
15
|
-
interface CSPDirectives{
|
|
16
|
-
[key: string]: Array<string | boolean>;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
interface DynamicWhiteList{
|
|
20
|
-
isAllowed : (ip:string)=> Promise<boolean>;
|
|
21
|
-
addIp: (ip: string)=> Promise<void>;
|
|
22
|
-
removeIp: (ip: string)=> Promise<void>;
|
|
23
|
-
getAll:() => Promise<string[]>;
|
|
24
|
-
middleware: () => (req:Request, res: Response, next:any)=> Promise<void>;
|
|
25
|
-
listIP:(ip:string)=> Promise<void>;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
const JWT_SECRET =process.env.JWT_SECRET || "Boo";
|
|
29
|
-
const EXPIRY = "1h";
|
|
30
|
-
|
|
31
|
-
export interface SecurityOptions{
|
|
32
|
-
redisClient?: Redis;
|
|
33
|
-
jwtSecret?:string;
|
|
34
|
-
jwtExpiry?:StringValue;
|
|
35
|
-
rateLimitPoints?:number;
|
|
36
|
-
rateLimitDuration?:number;
|
|
37
|
-
rateLimitBlock?:number;
|
|
38
|
-
rateLimiterEnabled?:boolean;
|
|
39
|
-
enableWhitelist?:boolean;
|
|
40
|
-
enableRateLimiter?:boolean;
|
|
41
|
-
enableHelmet?:boolean;
|
|
42
|
-
whiteListEnabled?:boolean;
|
|
43
|
-
helmetEnabled?:boolean;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export class SecurityModule{
|
|
47
|
-
private redisClient:Redis;
|
|
48
|
-
private jwtSecret:string;
|
|
49
|
-
private jwtExpiry:StringValue;
|
|
50
|
-
private rateLimiter?: RateLimiterRedis;
|
|
51
|
-
private whiteListEnabled:boolean;
|
|
52
|
-
private helmetEnabled:boolean;
|
|
53
|
-
private rateLimiterEnabled:boolean;
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
constructor(options: SecurityOptions = {})
|
|
57
|
-
{
|
|
58
|
-
this.jwtSecret=options.jwtSecret || process.env.JWT_SECRET || "Boo" ;
|
|
59
|
-
this.jwtExpiry = options.jwtExpiry || DEFAULT_JWT_EXPIRY;
|
|
60
|
-
this.whiteListEnabled = options.whiteListEnabled ?? true;
|
|
61
|
-
this.helmetEnabled = options.helmetEnabled ?? true;
|
|
62
|
-
this.rateLimiterEnabled = options.rateLimiterEnabled ?? true;
|
|
63
|
-
|
|
64
|
-
this.redisClient = options.redisClient || new Redis({
|
|
65
|
-
host:process.env.REDIS_HOST || "127.0.0.1",
|
|
66
|
-
port:Number(process.env.REDIS_PORT || 6379),
|
|
67
|
-
enableOfflineQueue: false,
|
|
68
|
-
retryStrategy:(times)=> Math.min(times * 50 , 2000),
|
|
69
|
-
maxRetriesPerRequest:10,
|
|
70
|
-
})
|
|
71
|
-
|
|
72
|
-
if(this.rateLimiterEnabled){
|
|
73
|
-
this.rateLimiter = new RateLimiterRedis({
|
|
74
|
-
storeClient: this.redisClient,
|
|
75
|
-
keyPrefix:"rate_limit",
|
|
76
|
-
points:options.rateLimitPoints || 100,
|
|
77
|
-
duration:options.rateLimitDuration || 60,
|
|
78
|
-
blockDuration: options.rateLimitBlock || 300,
|
|
79
|
-
|
|
80
|
-
})
|
|
81
|
-
}
|
|
82
|
-
this.redisClient.on("error",(err)=>
|
|
83
|
-
console.error("Security Redis error:",err)
|
|
84
|
-
);
|
|
85
|
-
this.redisClient.on("connect",() =>{
|
|
86
|
-
console.log("SecurityRedis Connected to:",this.redisClient.options.host);
|
|
87
|
-
|
|
88
|
-
})
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
async isAllowed(ip:string):Promise<boolean>{
|
|
93
|
-
if(!this.whiteListEnabled)
|
|
94
|
-
return true;
|
|
95
|
-
|
|
96
|
-
try{
|
|
97
|
-
const exists = await this.redisClient.sismember(WHITELIST_KEY,ip);
|
|
98
|
-
if (exists ===1) return true;
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
if( ip === "::1" || ip === "127.0.0.1")
|
|
102
|
-
return true;
|
|
103
|
-
const entries = await this.redisClient.smembers(WHITELIST_KEY)
|
|
104
|
-
|
|
105
|
-
for (const entry of entries){
|
|
106
|
-
if(entry.includes("/"))
|
|
107
|
-
{
|
|
108
|
-
const CIDR = (await import("ip-cidr")).default;
|
|
109
|
-
if(new CIDR(entry).contains(ip)) return true;
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
return false;
|
|
113
|
-
|
|
114
|
-
}catch(err){
|
|
115
|
-
console.error("whitelist check error:",err);
|
|
116
|
-
return false;
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
async addIP(ipOrCIDR:string,ttl:number =IP_EXPIRATION_SECONDS){
|
|
121
|
-
await this.redisClient.sadd(WHITELIST_KEY,ipOrCIDR);
|
|
122
|
-
await this.redisClient.expire(WHITELIST_KEY,ttl)
|
|
123
|
-
}
|
|
124
|
-
async removeIP(ipOrCIDR:string){
|
|
125
|
-
await this.redisClient.srem(WHITELIST_KEY,ipOrCIDR);
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
async listIPs(): Promise<string[]>{
|
|
129
|
-
return await this.redisClient.smembers(WHITELIST_KEY);
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
whiteListMiddleware(){
|
|
133
|
-
return async(req: Request,res:Response, next:NextFunction)=>{
|
|
134
|
-
if(!this.whiteListEnabled) return next();
|
|
135
|
-
|
|
136
|
-
const clientIP = req.headers["x-forwarded-for"]?.toString().split(",")[0]?.trim() || req.ip!;
|
|
137
|
-
|
|
138
|
-
if(await this.isAllowed(clientIP!))return next();
|
|
139
|
-
res.status(403).json({error:"Access denied"});
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
rateLimiterMiddleware(){
|
|
143
|
-
return (req:Request, res:Response, next:NextFunction)=>{
|
|
144
|
-
if (!this.rateLimiter || !this.rateLimiterEnabled)return next();
|
|
145
|
-
const ip = req.ip || req.socket.remoteAddress || "unknown";
|
|
146
|
-
this.rateLimiter.consume(ip).then(()=> next()).catch(()=> res.status(429).send("Too many Requests"));
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
helmetMiddleware():RequestHandler{
|
|
151
|
-
if(!this.helmetEnabled){
|
|
152
|
-
return(req: Request, res:Response, next:NextFunction)=> next();}
|
|
153
|
-
|
|
154
|
-
const helmetDirectives={
|
|
155
|
-
defaultSrc:["'self'"],
|
|
156
|
-
scriptSrc:["'self'","'unsafe-inline'","trusted-cdn.com"],
|
|
157
|
-
styleSrc:["'self'"],
|
|
158
|
-
imgSrc:["'self'","data:","trusted-cdn.com"],
|
|
159
|
-
fontSrc:["'self'","trusted-cdn.com"],
|
|
160
|
-
connectSrc:["'self'","api.trusted-domain.com"],
|
|
161
|
-
frameSrc:["'none'"],
|
|
162
|
-
objectSrc:["'none'"],
|
|
163
|
-
upgradeInsecureRequests: [],
|
|
164
|
-
reportUri: "/csp-violation-report",
|
|
165
|
-
};
|
|
166
|
-
|
|
167
|
-
return helmet({
|
|
168
|
-
contentSecurityPolicy:{
|
|
169
|
-
directives:helmetDirectives, reportOnly:process.env.NODE_ENV !== "production"},
|
|
170
|
-
hsts:{maxAge:315366000,
|
|
171
|
-
includeSubDomains:true,preload:true},
|
|
172
|
-
xxsFilter:true,
|
|
173
|
-
noSniff:true,
|
|
174
|
-
frameguard:{action:"deny"},
|
|
175
|
-
referrerPolicy:{policy:"same-origin"},
|
|
176
|
-
}as HelmetOptions);
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
|
package/src/security/limiter.ts
DELETED
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
import dotenv from "dotenv";
|
|
2
|
-
import Redis,{Redis as RedisClient} from "ioredis"
|
|
3
|
-
import {setupRedis} from "../redis/redisService"
|
|
4
|
-
import {Request, Response, NextFunction} from "express"
|
|
5
|
-
dotenv.config()
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
class TokenBucket{
|
|
9
|
-
private redis: RedisClient
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
constructor(redisClient:RedisClient){
|
|
13
|
-
this.redis = redisClient;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
async consume(key:string, capacity:number, refillRate:number): Promise<{
|
|
17
|
-
allowed:boolean;
|
|
18
|
-
remaining:number;
|
|
19
|
-
retryAfter?:number;
|
|
20
|
-
}>{
|
|
21
|
-
const now = Date.now();
|
|
22
|
-
const results = await this.redis
|
|
23
|
-
.pipeline()
|
|
24
|
-
.hgetall(`rate_limit:${key}`)
|
|
25
|
-
.exec();
|
|
26
|
-
const data= results?.[0]?.[1] ?? {}
|
|
27
|
-
const bucket = data as {tokens?: string;lastRefill?: string}
|
|
28
|
-
|| {} ;
|
|
29
|
-
const currentToken = parseFloat(bucket.tokens || capacity.toString ());
|
|
30
|
-
const lastRefill = parseFloat(bucket.lastRefill || now.toString())
|
|
31
|
-
const timeElapsed= (now - lastRefill) / 1000;
|
|
32
|
-
const newToken = Math.min(capacity, currentToken + (timeElapsed * refillRate))
|
|
33
|
-
|
|
34
|
-
if (newToken < 1){
|
|
35
|
-
return{
|
|
36
|
-
allowed:false,
|
|
37
|
-
remaining:Math.floor(newToken),
|
|
38
|
-
retryAfter:Math.ceil((1 - newToken) / refillRate)
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
await this.redis.hset(`rate_limit:${key}`,{
|
|
42
|
-
tokens:(newToken - 1).toString(),
|
|
43
|
-
lastRefill: now.toString()
|
|
44
|
-
})
|
|
45
|
-
this.redis.expire(`rate_limit:${key}`, 3600)
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
return {allowed:true ,remaining:Math.floor(newToken - 1)};
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
let tokenBucket: TokenBucket;
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
export const initializeRateLimiter = async () => {
|
|
57
|
-
const redisClient = (await setupRedis()).redisClient;
|
|
58
|
-
tokenBucket = new TokenBucket(redisClient);
|
|
59
|
-
};
|
|
60
|
-
const createRatelimiter = (config:{
|
|
61
|
-
capacity:number;
|
|
62
|
-
refillRate: number;
|
|
63
|
-
keyGenerator: (req:Request)=> string;
|
|
64
|
-
})=>{
|
|
65
|
-
return async(req:Request, res:Response, next:NextFunction): Promise<void> =>{
|
|
66
|
-
const key = config.keyGenerator(req);
|
|
67
|
-
const {allowed, remaining, retryAfter}= await tokenBucket.consume(
|
|
68
|
-
key,
|
|
69
|
-
config.capacity,
|
|
70
|
-
config.refillRate
|
|
71
|
-
)
|
|
72
|
-
res.set({
|
|
73
|
-
"X-RateLimit-Limit": config.capacity.toString(),
|
|
74
|
-
"X-RateLimit-Remaining":remaining.toString(),
|
|
75
|
-
...(!allowed && {"Retry-After": retryAfter?.toString() || "1"})
|
|
76
|
-
})
|
|
77
|
-
if(allowed){
|
|
78
|
-
|
|
79
|
-
return next();
|
|
80
|
-
}else{
|
|
81
|
-
res.status(429).json({
|
|
82
|
-
error:`Too many requests`
|
|
83
|
-
})
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
const RATE_LIMIT_CONFIGS= {
|
|
90
|
-
OTP:{
|
|
91
|
-
keyPrefix:"otp_limiter",
|
|
92
|
-
refillRate: 0.1,
|
|
93
|
-
capacity:3,
|
|
94
|
-
keyGenerator: (req:Request)=>{
|
|
95
|
-
const email =req.body?.email;
|
|
96
|
-
return email || req.ip || "unknown"
|
|
97
|
-
}
|
|
98
|
-
},
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
LOGIN:{
|
|
102
|
-
keyPrefix:"login_limiter",
|
|
103
|
-
capacity:10,
|
|
104
|
-
refillRate:2,
|
|
105
|
-
keyGenerator:(req: Request): string => req.ip || "unknown"
|
|
106
|
-
}
|
|
107
|
-
};
|
|
108
|
-
|
|
109
|
-
initializeRateLimiter().catch((err) => {
|
|
110
|
-
console.error("Failed to initialize rate limiters:", err);
|
|
111
|
-
process.exit(1);
|
|
112
|
-
})
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
export const OTPLimiterMiddleware =createRatelimiter(RATE_LIMIT_CONFIGS.OTP);
|
|
116
|
-
export const LoginLimiterMiddleware = () => createRatelimiter(RATE_LIMIT_CONFIGS.LOGIN);
|
|
@@ -1,110 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
import { Redis } from "ioredis";
|
|
3
|
-
|
|
4
|
-
export class RedisTokenStore {
|
|
5
|
-
private prefix = "auth:v1";
|
|
6
|
-
|
|
7
|
-
constructor(private redis: Redis,private debug = false) {}
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
private key(...parts:string[]){
|
|
11
|
-
return `${this.prefix}:${parts.join(":")}`;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
private log(action:string,key:string, value?:any){
|
|
15
|
-
if (this.debug){
|
|
16
|
-
console.log(`[Redis ${action}]`,{key, value})
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
async storeRefreshToken(token:string,userId:string,ttl:number){
|
|
20
|
-
const key = this.key("refresh", userId);
|
|
21
|
-
await this.redis.set(key,userId, "EX",ttl);
|
|
22
|
-
this.log("SET", key, userId)
|
|
23
|
-
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
async getRefreshToken(userId:string){
|
|
27
|
-
const key = this.key("refresh",userId);
|
|
28
|
-
const value = await this.redis.get(key);
|
|
29
|
-
this.log("GET",key , value);
|
|
30
|
-
return value;
|
|
31
|
-
}
|
|
32
|
-
async getset(key: string, value: string, expiry?: number): Promise<string | null> {
|
|
33
|
-
|
|
34
|
-
const previous = await this.redis.getset(key, value);
|
|
35
|
-
|
|
36
|
-
if (expiry) {
|
|
37
|
-
await this.redis.expire(key, expiry);
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
this.log("GETSET", key, { previous, new: value });
|
|
41
|
-
return previous;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
async deleteRefreshToken(userId:string){
|
|
45
|
-
const key = this.key("refresh",userId);
|
|
46
|
-
await this.redis.del(key);
|
|
47
|
-
this.log("DEL",key);
|
|
48
|
-
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
async blacklistToken(userId: string, ttl: number) {
|
|
52
|
-
const key = this.key("blacklist", userId);
|
|
53
|
-
await this.redis.set(key, "1", "EX", ttl);
|
|
54
|
-
this.log("SET", key, "blacklisted");
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
async isBlacklisted(userId: string) {
|
|
58
|
-
const key = this.key("blacklist", userId);
|
|
59
|
-
const exists = await this.redis.exists(key);
|
|
60
|
-
this.log("CHECK", key, exists);
|
|
61
|
-
return exists === 1;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
// Rate Limiting
|
|
65
|
-
async incrementRateLimit(ip: string, ttl: number) {
|
|
66
|
-
const key = this.key("rate", ip);
|
|
67
|
-
|
|
68
|
-
const count = await this.redis.incr(key);
|
|
69
|
-
if (count === 1) {
|
|
70
|
-
await this.redis.expire(key, ttl);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
this.log("INCR", key, count);
|
|
74
|
-
return count;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
// IP Whitelist
|
|
78
|
-
async addToWhitelist(ip: string) {
|
|
79
|
-
const key = this.key("whitelist", ip);
|
|
80
|
-
await this.redis.set(key, "1");
|
|
81
|
-
this.log("SET", key, "whitelisted");
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
async removeFromWhitelist(ip: string) {
|
|
85
|
-
const key = this.key("whitelist", ip);
|
|
86
|
-
await this.redis.del(key);
|
|
87
|
-
this.log("DEL", key);
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
async isWhitelisted(ip: string) {
|
|
91
|
-
const key = this.key("whitelist", ip);
|
|
92
|
-
const exists = await this.redis.exists(key);
|
|
93
|
-
this.log("CHECK", key, exists);
|
|
94
|
-
return exists === 1;
|
|
95
|
-
}
|
|
96
|
-
async set(key: string, value: string, expiry?: number): Promise<void> {
|
|
97
|
-
console.log("REDIS SET:", key, value);
|
|
98
|
-
|
|
99
|
-
if (expiry) {
|
|
100
|
-
await this.redis.set(key, value, "EX", expiry);
|
|
101
|
-
} else {
|
|
102
|
-
await this.redis.set(key, value);
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
async get(key: string): Promise<string | null> {
|
|
108
|
-
return this.redis.get(key);
|
|
109
|
-
}
|
|
110
|
-
}
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import {UserStore} from "../types/storage"
|
|
2
|
-
|
|
3
|
-
export class Store{
|
|
4
|
-
constructor(private userStore:UserStore){}
|
|
5
|
-
|
|
6
|
-
async register(email:string, password:string){
|
|
7
|
-
const exists = await this.userStore.findByEmail(email)
|
|
8
|
-
|
|
9
|
-
if (exists){
|
|
10
|
-
throw new Error("If a record of user exists an email will be sent");
|
|
11
|
-
}
|
|
12
|
-
return
|
|
13
|
-
this.userStore.create({email,password});
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
}
|
package/src/tests/con.test.ts
DELETED
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
import { createAuthenik8 } from "../createAuthenik8";
|
|
2
|
-
import request from "supertest";
|
|
3
|
-
import express from "express";
|
|
4
|
-
import Redis from "ioredis";
|
|
5
|
-
|
|
6
|
-
describe("Refresh Token Concurrency (Integration)", () => {
|
|
7
|
-
let app: express.Express;
|
|
8
|
-
let auth: Awaited<ReturnType<typeof createAuthenik8>>; // or just `any` but this is better
|
|
9
|
-
let refreshToken: string;
|
|
10
|
-
let redisClient: Redis;
|
|
11
|
-
|
|
12
|
-
beforeAll(async () => {
|
|
13
|
-
// Create and verify a connected Redis client (use a separate DB for tests)
|
|
14
|
-
redisClient = new Redis({ host: "localhost", port: 6379, db: 1 });
|
|
15
|
-
await redisClient.ping(); // ensure connection is established
|
|
16
|
-
|
|
17
|
-
// Pass the connected client as `redis` (not `redisClient`)
|
|
18
|
-
auth = await createAuthenik8({
|
|
19
|
-
jwtSecret: "test-secret",
|
|
20
|
-
refreshSecret: "refresh-secret",
|
|
21
|
-
jwtExpiry: "15m",
|
|
22
|
-
redis: redisClient, // ✅ correct property name
|
|
23
|
-
});
|
|
24
|
-
|
|
25
|
-
app = express();
|
|
26
|
-
app.use(express.json());
|
|
27
|
-
|
|
28
|
-
// Login route – must be async and await the refresh token generation
|
|
29
|
-
app.post("/login", async (req, res) => {
|
|
30
|
-
const token = auth.signToken({ userId: "user_1", email: "test@test.com" });
|
|
31
|
-
refreshToken = await auth.generateRefreshToken({ userId: "user_1", email: "test@test.com" });
|
|
32
|
-
res.json({ token, refreshToken });
|
|
33
|
-
});
|
|
34
|
-
|
|
35
|
-
// Refresh route – unchanged but uses the proper error handling
|
|
36
|
-
app.post("/refresh", async (req, res) => {
|
|
37
|
-
try {
|
|
38
|
-
const result = await auth.refreshToken(req.body.refreshToken);
|
|
39
|
-
res.json(result);
|
|
40
|
-
} catch (err: any) {
|
|
41
|
-
console.error("Refresh error",err)
|
|
42
|
-
|
|
43
|
-
if(err.name === "InvalidTokenError"){
|
|
44
|
-
return res.status(401).json({error:err.message})
|
|
45
|
-
}
|
|
46
|
-
return res.status( 500).json({ error: err.message });
|
|
47
|
-
}
|
|
48
|
-
});
|
|
49
|
-
});
|
|
50
|
-
|
|
51
|
-
afterAll(async () => {
|
|
52
|
-
// Clean up the test database and close the client
|
|
53
|
-
await redisClient.flushdb();
|
|
54
|
-
await redisClient.quit();
|
|
55
|
-
});
|
|
56
|
-
|
|
57
|
-
it("should allow only one of two concurrent refresh requests", async () => {
|
|
58
|
-
// Login to obtain a valid refresh token
|
|
59
|
-
await request(app).post("/login").send({});
|
|
60
|
-
|
|
61
|
-
// Fire two concurrent refresh requests
|
|
62
|
-
const [res1, res2] = await Promise.all([
|
|
63
|
-
request(app).post("/refresh").send({ refreshToken }),
|
|
64
|
-
request(app).post("/refresh").send({ refreshToken }),
|
|
65
|
-
]);
|
|
66
|
-
|
|
67
|
-
// Exactly one should succeed (200) and one should fail with 401
|
|
68
|
-
const statuses = [res1.status, res2.status].sort();
|
|
69
|
-
expect(statuses).toEqual([200, 401]);
|
|
70
|
-
|
|
71
|
-
// The successful response must contain new tokens
|
|
72
|
-
const successRes = res1.status === 200 ? res1 : res2;
|
|
73
|
-
expect(successRes.body).toHaveProperty("accessToken");
|
|
74
|
-
expect(successRes.body).toHaveProperty("refreshToken");
|
|
75
|
-
});
|
|
76
|
-
});
|
package/src/tests/dump.rdb
DELETED
|
Binary file
|
|
@@ -1,100 +0,0 @@
|
|
|
1
|
-
// tests/full.integration.test.ts
|
|
2
|
-
import { createTestApp } from "./testApp";
|
|
3
|
-
|
|
4
|
-
describe("Authenik8 Full Integration", () => {
|
|
5
|
-
let request: any;
|
|
6
|
-
let auth: any;
|
|
7
|
-
|
|
8
|
-
let accessToken: string;
|
|
9
|
-
let refreshToken: string;
|
|
10
|
-
|
|
11
|
-
beforeAll(async () => {
|
|
12
|
-
const setup = await createTestApp();
|
|
13
|
-
request = setup.request;
|
|
14
|
-
auth = setup.auth;
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
afterAll(async () => {
|
|
18
|
-
if (auth.redis) {
|
|
19
|
-
await auth.redis.flushdb();
|
|
20
|
-
await auth.redis.quit();
|
|
21
|
-
}
|
|
22
|
-
});
|
|
23
|
-
|
|
24
|
-
// LOGIN
|
|
25
|
-
test("should login and receive tokens", async () => {
|
|
26
|
-
const res = await request.post("/login");
|
|
27
|
-
|
|
28
|
-
expect(res.status).toBe(200);
|
|
29
|
-
expect(res.body).toHaveProperty("accessToken");
|
|
30
|
-
expect(res.body).toHaveProperty("refreshToken");
|
|
31
|
-
|
|
32
|
-
accessToken = res.body.accessToken;
|
|
33
|
-
refreshToken = res.body.refreshToken;
|
|
34
|
-
});
|
|
35
|
-
|
|
36
|
-
// PROTECTED ROUTE
|
|
37
|
-
test("should access protected route with valid token", async () => {
|
|
38
|
-
const res = await request
|
|
39
|
-
.get("/protected")
|
|
40
|
-
.set("Authorization", `Bearer ${accessToken}`);
|
|
41
|
-
|
|
42
|
-
expect(res.status).toBe(200);
|
|
43
|
-
expect(res.body).toHaveProperty("data", "secure data");
|
|
44
|
-
});
|
|
45
|
-
|
|
46
|
-
// NO TOKEN
|
|
47
|
-
test("should reject request without token", async () => {
|
|
48
|
-
const res = await request.get("/protected");
|
|
49
|
-
|
|
50
|
-
expect(res.status).toBe(401);
|
|
51
|
-
});
|
|
52
|
-
|
|
53
|
-
// REFRESH TOKEN
|
|
54
|
-
test("should refresh access token", async () => {
|
|
55
|
-
const res = await request
|
|
56
|
-
.post("/refresh")
|
|
57
|
-
.send({ refreshToken });
|
|
58
|
-
|
|
59
|
-
expect(res.status).toBe(200);
|
|
60
|
-
expect(res.body).toHaveProperty("accessToken");
|
|
61
|
-
expect(res.body).toHaveProperty("refreshToken");
|
|
62
|
-
|
|
63
|
-
// update tokens
|
|
64
|
-
accessToken = res.body.accessToken;
|
|
65
|
-
refreshToken = res.body.refreshToken;
|
|
66
|
-
|
|
67
|
-
if (res.body.refreshToken) {
|
|
68
|
-
refreshToken = res.body.refreshToken;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
// ROTATION (IMPORTANT)
|
|
74
|
-
test("should NOT allow reuse of old refresh token", async () => {
|
|
75
|
-
const originalToken = refreshToken;
|
|
76
|
-
|
|
77
|
-
// first use → rotates token
|
|
78
|
-
const firstRes = await request
|
|
79
|
-
.post("/refresh")
|
|
80
|
-
.send({ refreshToken: originalToken });
|
|
81
|
-
|
|
82
|
-
expect(firstRes.status).toBe(200);
|
|
83
|
-
|
|
84
|
-
const newToken = firstRes.body.refreshToken;
|
|
85
|
-
|
|
86
|
-
// second use with OLD token → should fail
|
|
87
|
-
const res = await request
|
|
88
|
-
.post("/refresh")
|
|
89
|
-
.send({ refreshToken: originalToken });
|
|
90
|
-
|
|
91
|
-
expect(res.status).toBe(401);
|
|
92
|
-
|
|
93
|
-
// sanity check: new token should work
|
|
94
|
-
const validRes = await request
|
|
95
|
-
.post("/refresh")
|
|
96
|
-
.send({ refreshToken: newToken });
|
|
97
|
-
|
|
98
|
-
expect(validRes.status).toBe(200);
|
|
99
|
-
});
|
|
100
|
-
});
|
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import request from "supertest";
|
|
2
|
-
import express from "express";
|
|
3
|
-
import { createAuthenik8 } from "../createAuthenik8";
|
|
4
|
-
|
|
5
|
-
test("OAuth callback issues tokens", async () => {
|
|
6
|
-
const app = express();
|
|
7
|
-
|
|
8
|
-
const auth = await createAuthenik8({
|
|
9
|
-
jwtSecret: "test",
|
|
10
|
-
refreshSecret: "test",
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
// 🔥 Mock OAuth provider
|
|
14
|
-
auth.oauth = {
|
|
15
|
-
google: {
|
|
16
|
-
handleCallback: async () => ({
|
|
17
|
-
profile: {
|
|
18
|
-
email: "test@example.com",
|
|
19
|
-
name: "Test User",
|
|
20
|
-
provider: "google",
|
|
21
|
-
providerId: "123",
|
|
22
|
-
},
|
|
23
|
-
}),
|
|
24
|
-
},
|
|
25
|
-
} as any;
|
|
26
|
-
|
|
27
|
-
app.get("/callback", async (req, res) => {
|
|
28
|
-
const { profile } = await auth.oauth!.google!.handleCallback(req);
|
|
29
|
-
const tokens = await auth.issueTokensFromProfile(profile);
|
|
30
|
-
|
|
31
|
-
res.json(tokens);
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
const res = await request(app).get("/callback");
|
|
35
|
-
|
|
36
|
-
expect(res.status).toBe(200);
|
|
37
|
-
expect(res.body.accessToken).toBeDefined();
|
|
38
|
-
expect(res.body.refreshToken).toBeDefined();
|
|
39
|
-
});
|