authenik8-core 1.0.3 → 1.0.22
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 +6 -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/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/redis/redisService.js +7 -8
- 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 +12 -1
- package/dist/security/limiter.d.ts.map +1 -1
- package/dist/security/limiter.js +29 -10
- 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
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
|
-
});
|
package/src/tests/oauth1.test.ts
DELETED
|
@@ -1,145 +0,0 @@
|
|
|
1
|
-
import dotenv from "dotenv";
|
|
2
|
-
import express, { Request, Response, NextFunction } from "express";
|
|
3
|
-
import { createAuthenik8 } from "../createAuthenik8";
|
|
4
|
-
import { TokenPayload } from "../types/tokens";
|
|
5
|
-
import { createIdentityEngine } from "../oauth/brain/identityEngine";
|
|
6
|
-
import { memoryAdapter } from "../oauth/adapters/memoryAdapter";
|
|
7
|
-
|
|
8
|
-
const tokenService = {
|
|
9
|
-
signAccessToken: () => "test_access_token",
|
|
10
|
-
generateRefreshToken: async () => "test_refresh_token",
|
|
11
|
-
};
|
|
12
|
-
const identityEngine = createIdentityEngine(memoryAdapter,tokenService);
|
|
13
|
-
|
|
14
|
-
dotenv.config();
|
|
15
|
-
|
|
16
|
-
const app = express();
|
|
17
|
-
|
|
18
|
-
declare global {
|
|
19
|
-
namespace Express {
|
|
20
|
-
interface Request {
|
|
21
|
-
user?: TokenPayload;
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
async function start() {
|
|
27
|
-
const auth = await createAuthenik8({
|
|
28
|
-
jwtSecret: "test",
|
|
29
|
-
refreshSecret: "test",
|
|
30
|
-
oauth: {
|
|
31
|
-
google: {
|
|
32
|
-
clientId: process.env.GOOGLE_CLIENT_ID!,
|
|
33
|
-
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
|
34
|
-
redirectUri: "http://localhost:4000/callback",
|
|
35
|
-
},
|
|
36
|
-
github: {
|
|
37
|
-
clientId: process.env.GITHUB_CLIENT_ID!,
|
|
38
|
-
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
|
|
39
|
-
redirectUri: "http://localhost:4000/auth/github/callback",
|
|
40
|
-
},
|
|
41
|
-
},
|
|
42
|
-
});
|
|
43
|
-
|
|
44
|
-
function requireAuth(req: Request, res: Response, next: NextFunction) {
|
|
45
|
-
const token = req.headers.authorization?.split(" ")[1];
|
|
46
|
-
|
|
47
|
-
if (!token) return res.status(401).json({ error: "Unauthorized" });
|
|
48
|
-
|
|
49
|
-
try {
|
|
50
|
-
req.user = auth.verifyToken(token);
|
|
51
|
-
next();
|
|
52
|
-
} catch {
|
|
53
|
-
return res.status(401).json({ error: "Invalid token" });
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// =========================
|
|
58
|
-
// GOOGLE LOGIN
|
|
59
|
-
// =========================
|
|
60
|
-
|
|
61
|
-
app.get("/auth/google", (req, res) => {
|
|
62
|
-
auth.oauth!.google!.redirect(req, res);
|
|
63
|
-
});
|
|
64
|
-
|
|
65
|
-
app.get("/callback", async (req, res) => {
|
|
66
|
-
try {
|
|
67
|
-
const {profile,mode, userId} = await auth.oauth!.google!.handleCallback(req);
|
|
68
|
-
|
|
69
|
-
console.log("ENGINE INPUT:", {
|
|
70
|
-
mode,
|
|
71
|
-
userId,
|
|
72
|
-
});
|
|
73
|
-
const result = await identityEngine.resolveOAuth({
|
|
74
|
-
profile,
|
|
75
|
-
mode,
|
|
76
|
-
userId,
|
|
77
|
-
});
|
|
78
|
-
|
|
79
|
-
return res.json({
|
|
80
|
-
provider: "google",
|
|
81
|
-
message: "Google login successful",
|
|
82
|
-
...result,
|
|
83
|
-
});
|
|
84
|
-
|
|
85
|
-
} catch (err) {
|
|
86
|
-
return res.status(500).json({
|
|
87
|
-
error: err instanceof Error ? err.message : "Unknown error",
|
|
88
|
-
});
|
|
89
|
-
}
|
|
90
|
-
});
|
|
91
|
-
|
|
92
|
-
// =========================
|
|
93
|
-
// GITHUB LOGIN
|
|
94
|
-
// =========================
|
|
95
|
-
|
|
96
|
-
app.get("/auth/github", (req, res) => {
|
|
97
|
-
auth.oauth!.github!.redirect(req, res);
|
|
98
|
-
});
|
|
99
|
-
|
|
100
|
-
app.get("/auth/github/callback", async (req, res) => {
|
|
101
|
-
try {
|
|
102
|
-
const result = await auth.oauth!.github!.handleCallback(req);
|
|
103
|
-
|
|
104
|
-
return res.json({
|
|
105
|
-
provider: "github",
|
|
106
|
-
message: "GitHub login successful",
|
|
107
|
-
...result,
|
|
108
|
-
});
|
|
109
|
-
} catch (err) {
|
|
110
|
-
return res.status(500).json({
|
|
111
|
-
error: err instanceof Error ? err.message : "Unknown error",
|
|
112
|
-
});
|
|
113
|
-
}
|
|
114
|
-
});
|
|
115
|
-
|
|
116
|
-
// =========================
|
|
117
|
-
// LINK FLOW (GITHUB)
|
|
118
|
-
// =========================
|
|
119
|
-
|
|
120
|
-
app.get("/auth/github/link", requireAuth, (req, res) => {
|
|
121
|
-
auth.oauth!.github!.redirect(req, res);
|
|
122
|
-
});
|
|
123
|
-
|
|
124
|
-
app.get("/auth/github/link/callback", requireAuth, async (req, res) => {
|
|
125
|
-
try {
|
|
126
|
-
const result = await auth.oauth!.github!.handleCallback(req);
|
|
127
|
-
|
|
128
|
-
return res.json({
|
|
129
|
-
provider: "github",
|
|
130
|
-
message: "GitHub account linked successfully",
|
|
131
|
-
...result,
|
|
132
|
-
});
|
|
133
|
-
} catch (err) {
|
|
134
|
-
return res.status(400).json({
|
|
135
|
-
error: err instanceof Error ? err.message : "Linking error",
|
|
136
|
-
});
|
|
137
|
-
}
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
start().then(() => {
|
|
142
|
-
app.listen(4000, () => {
|
|
143
|
-
console.log("OAuth test server running on http://localhost:4000");
|
|
144
|
-
});
|
|
145
|
-
});
|