authenik8-core 0.2.0 → 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.
Files changed (97) hide show
  1. package/README.md +6 -0
  2. package/dist/auth/guestModeService.d.ts +4 -1
  3. package/dist/auth/guestModeService.d.ts.map +1 -1
  4. package/dist/auth/guestModeService.js +31 -20
  5. package/dist/auth/guestModeService.js.map +1 -1
  6. package/dist/auth/jwtAuth.d.ts +2 -1
  7. package/dist/auth/jwtAuth.d.ts.map +1 -1
  8. package/dist/auth/jwtAuth.js +26 -8
  9. package/dist/auth/jwtAuth.js.map +1 -1
  10. package/dist/auth/refreshService.d.ts +2 -0
  11. package/dist/auth/refreshService.d.ts.map +1 -1
  12. package/dist/auth/refreshService.js +15 -7
  13. package/dist/auth/refreshService.js.map +1 -1
  14. package/dist/createAuthenik8.d.ts.map +1 -1
  15. package/dist/createAuthenik8.js +31 -13
  16. package/dist/createAuthenik8.js.map +1 -1
  17. package/dist/middleware/adminService.d.ts +1 -1
  18. package/dist/middleware/adminService.d.ts.map +1 -1
  19. package/dist/middleware/adminService.js +6 -10
  20. package/dist/middleware/adminService.js.map +1 -1
  21. package/dist/oauth/adapters/redisAdapter.d.ts +23 -0
  22. package/dist/oauth/adapters/redisAdapter.d.ts.map +1 -0
  23. package/dist/oauth/adapters/redisAdapter.js +116 -0
  24. package/dist/oauth/adapters/redisAdapter.js.map +1 -0
  25. package/dist/oauth/brain/identityEngine.d.ts.map +1 -1
  26. package/dist/oauth/brain/identityEngine.js +26 -7
  27. package/dist/oauth/brain/identityEngine.js.map +1 -1
  28. package/dist/oauth/identity/types.d.ts +6 -1
  29. package/dist/oauth/identity/types.d.ts.map +1 -1
  30. package/dist/oauth/providers/github.d.ts.map +1 -1
  31. package/dist/oauth/providers/github.js +6 -7
  32. package/dist/oauth/providers/github.js.map +1 -1
  33. package/dist/oauth/providers/google.d.ts.map +1 -1
  34. package/dist/oauth/providers/google.js +3 -28
  35. package/dist/oauth/providers/google.js.map +1 -1
  36. package/dist/oauth/types.d.ts +1 -0
  37. package/dist/oauth/types.d.ts.map +1 -1
  38. package/dist/redis/redisService.js +7 -8
  39. package/dist/redis/redisService.js.map +1 -1
  40. package/dist/security/ipService.d.ts +3 -0
  41. package/dist/security/ipService.d.ts.map +1 -1
  42. package/dist/security/ipService.js +30 -9
  43. package/dist/security/ipService.js.map +1 -1
  44. package/dist/security/limiter.d.ts +12 -1
  45. package/dist/security/limiter.d.ts.map +1 -1
  46. package/dist/security/limiter.js +29 -10
  47. package/dist/security/limiter.js.map +1 -1
  48. package/dist/storage/RedisTokenStore.d.ts.map +1 -1
  49. package/dist/storage/RedisTokenStore.js +3 -2
  50. package/dist/storage/RedisTokenStore.js.map +1 -1
  51. package/dist/storage/userStorage.js +1 -2
  52. package/dist/storage/userStorage.js.map +1 -1
  53. package/dist/types/config.d.ts +3 -0
  54. package/dist/types/config.d.ts.map +1 -1
  55. package/package.json +23 -13
  56. package/dump.rdb +0 -0
  57. package/jest.config.js +0 -11
  58. package/src/auth/guestModeService.ts +0 -31
  59. package/src/auth/jwtAuth.ts +0 -99
  60. package/src/auth/refreshService.ts +0 -155
  61. package/src/createAuthenik8.ts +0 -135
  62. package/src/dump.rdb +0 -0
  63. package/src/index.ts +0 -2
  64. package/src/middleware/adminService.ts +0 -50
  65. package/src/oauth/adapters/memoryAdapter.ts +0 -74
  66. package/src/oauth/brain/identityEngine.ts +0 -141
  67. package/src/oauth/brain/identityPolicy.ts +0 -4
  68. package/src/oauth/brain/identityResolver.ts +0 -43
  69. package/src/oauth/brain/types.ts +0 -9
  70. package/src/oauth/core.ts +0 -19
  71. package/src/oauth/identity/1 +0 -44
  72. package/src/oauth/identity/types.ts +0 -44
  73. package/src/oauth/providers/github.ts +0 -154
  74. package/src/oauth/providers/google.ts +0 -189
  75. package/src/oauth/types/identity.ts +0 -17
  76. package/src/oauth/types.ts +0 -24
  77. package/src/oauth/userStore.ts +0 -73
  78. package/src/redis/redisService.ts +0 -137
  79. package/src/security/ipService.ts +0 -180
  80. package/src/security/limiter.ts +0 -116
  81. package/src/storage/RedisTokenStore.ts +0 -110
  82. package/src/storage/userStorage.ts +0 -16
  83. package/src/tests/con.test.ts +0 -76
  84. package/src/tests/dump.rdb +0 -0
  85. package/src/tests/full.intergration.test.ts +0 -100
  86. package/src/tests/oauth.intergration.test.ts +0 -39
  87. package/src/tests/oauth1.test.ts +0 -145
  88. package/src/tests/oauth2.test.ts +0 -158
  89. package/src/tests/oauth3.test.ts +0 -171
  90. package/src/tests/testApp.ts +0 -56
  91. package/src/types/admin.ts +0 -7
  92. package/src/types/config.ts +0 -17
  93. package/src/types/public.ts +0 -48
  94. package/src/types/storage.ts +0 -15
  95. package/src/types/tokens.ts +0 -10
  96. package/src/utility/lockHelper.ts +0 -33
  97. package/tsconfig.json +0 -51
@@ -1,189 +0,0 @@
1
- import { OAuthProfile, GoogleOAuthConfig } from "../types";
2
- import { OAuth2Client } from "google-auth-library";
3
- import {Request,Response} from "express";
4
- import jwt from "jsonwebtoken";
5
- import crypto from "crypto";
6
- import type { Redis as RedisClient } from "ioredis";
7
- import type { IdentityEngine } from "../brain/types";
8
-
9
- export function createGoogleProvider(config: GoogleOAuthConfig,
10
- redisClient:RedisClient,
11
- identityEngine: IdentityEngine
12
- ) {
13
- const { clientId, clientSecret, redirectUri } = config;
14
-
15
- return {
16
-
17
- redirect:async (req:Request, res:Response): Promise<void> => {
18
- try{
19
-
20
-
21
- const state = crypto.randomBytes(32).toString("hex");
22
-
23
-
24
- const mode = req.path.includes("link") ? "link" : "login";
25
- const authUser = (req as any).user ?? null;
26
-
27
- await redisClient.setex(
28
- `oauth:state:${state}`,
29
- 300,
30
- JSON.stringify({
31
- userId: authUser?.userId ?? null,
32
- mode,
33
- })
34
- );
35
-
36
-
37
-
38
-
39
- const url = new URL("https://accounts.google.com/o/oauth2/v2/auth");
40
- url.searchParams.set("client_id", clientId);
41
- url.searchParams.set("redirect_uri", redirectUri);
42
- url.searchParams.set("response_type", "code");
43
- url.searchParams.set("scope", "openid email profile");
44
- url.searchParams.set("access_type", "offline");
45
- url.searchParams.set("prompt", "consent");
46
-
47
- url.searchParams.set("state", state)
48
-
49
-
50
- res.redirect(url.toString());
51
- return;
52
- } catch (err) {
53
- console.error("Google redirect error:", err);
54
- res.status(500).json({ error: "OAuth redirect failed" });
55
- return;
56
- }
57
- },
58
- handleCallback: async (req:Request): Promise<{
59
- profile: OAuthProfile;
60
- mode: "login" | "link";
61
- userId: string | null;
62
- }> => {
63
- const code = req.query.code as string;
64
- const client = new OAuth2Client(clientId);
65
-
66
- const state = req.query.state as string;
67
-
68
- if (!state) {
69
- throw new Error("OAuthError:Missing state");
70
- }
71
-
72
- const stored = await redisClient.get(`oauth:state:${state}`);
73
-
74
- if (!stored) {
75
- throw new Error("OAuthError:Invalid or expired state");
76
- }
77
-
78
- const { userId, mode } = JSON.parse(stored);
79
-
80
-
81
- if (!code) {
82
- throw new Error("OauthError:Missing authorization code");
83
- }
84
- const params = new URLSearchParams();
85
- params.append("client_id", clientId);
86
- params.append("client_secret", clientSecret);
87
- params.append("code", code);
88
- params.append("grant_type", "authorization_code");
89
- params.append("redirect_uri", redirectUri);
90
-
91
-
92
-
93
- // 1. Exchange code for tokens
94
- const tokenRes = await fetch("https://oauth2.googleapis.com/token", {
95
- method: "POST",
96
- headers: {
97
- "Content-Type": "application/x-www-form-urlencoded",
98
- },
99
- body:params
100
- });
101
-
102
- if(!tokenRes.ok){
103
- const err = await tokenRes.text();
104
- throw new Error(`OAuthError:Token exchange failed->${err}`)
105
- }
106
-
107
- const tokenData = await tokenRes.json();
108
- if(!tokenData.access_token){
109
-
110
- throw new Error("OAuthError:No access token returned")
111
- }
112
- if (!tokenData.id_token) {
113
- console.log("TOKEN DATA:", tokenData);
114
- throw new Error("OAuthError:No id_token returned from Google");
115
- }
116
- const ticket = await client.verifyIdToken({
117
- idToken: tokenData.id_token,
118
- audience: clientId,
119
- });
120
-
121
- const payload = ticket.getPayload();
122
-
123
- if(!payload){
124
- throw new Error("OAuthError:Invalid ID token payload");
125
- }
126
- if(!payload.email){
127
- throw new Error("OAuthError:Email not present in ID token");
128
- }
129
- if(!payload.email_verified){
130
- throw new Error("OAuthError:Email not verified");
131
- }
132
-
133
- if (
134
- payload.iss !== "https://accounts.google.com" &&
135
- payload.iss !== "accounts.google.com"
136
- ) {
137
- throw new Error("OAuthError: Invalid issuer");
138
- }
139
-
140
- const profile: OAuthProfile = {
141
- email: payload.email,
142
- name: payload.name,
143
- provider: "google",
144
- providerId: payload.sub,
145
- };
146
-
147
- const accessToken = tokenData.access_token;
148
- console.log("Token data:",tokenData);
149
- console.log("[OAuth] Fetching user profile...");
150
-
151
- console.log("FINAL ENGINE INPUT:", {
152
- profile,
153
- mode,
154
- userId,
155
- });
156
-
157
- let result
158
- try{
159
- result = await identityEngine.resolveOAuth({
160
- profile,
161
- mode,
162
- userId,
163
- })
164
-
165
- }catch(err){
166
- console.error("ENGINE ERROR:",err)
167
- throw err;
168
- }
169
- if (
170
- result.type !== "INVALID_LINK_REQUEST" &&
171
- result.type !== "EXISTING_EMAIL_CONFLICT" &&
172
- !result.user
173
- ) {
174
- throw new Error("Invalid engine result: missing user");
175
- }
176
-
177
-
178
- await redisClient.del(`oauth:state:${state}`);
179
-
180
- return {
181
- profile,
182
- mode,
183
- userId,
184
- };
185
-
186
- }
187
- }
188
- }
189
-
@@ -1,17 +0,0 @@
1
- export type Provider = "google" | "github";
2
-
3
- export type Identity = {
4
- provider: Provider;
5
- providerId: string;
6
- email?: string;
7
- verified: boolean;
8
- };
9
-
10
- export type User = {
11
- userId: string;
12
- email: string;
13
- emailVerified: boolean;
14
- providers: Identity[];
15
- createdAt: number;
16
- lastLoginAt?: number;
17
- };
@@ -1,24 +0,0 @@
1
-
2
- export type Provider ="google" | "github"
3
- export type OAuthProfile = {
4
- email: string;
5
- name?: string;
6
- provider: Provider;
7
- providerId: string;
8
- };
9
-
10
- export type GoogleOAuthConfig = {
11
- clientId: string;
12
- clientSecret: string;
13
- redirectUri: string;
14
- };
15
- export type GitHubOAuthConfig = {
16
- clientId: string;
17
- clientSecret: string;
18
- redirectUri: string;
19
- enterprise?:boolean
20
- };
21
- export type OAuthConfig = {
22
- google?: GoogleOAuthConfig;
23
- github?: GitHubOAuthConfig;
24
- };
@@ -1,73 +0,0 @@
1
- import crypto from "crypto";
2
- import { OAuthProfile } from "./types";
3
-
4
-
5
- export type Provider = "google" | "github";
6
-
7
- export type User = {
8
- id: string;
9
- email: string;
10
- role?:string;
11
- providers: {
12
- provider: Provider;
13
- providerId: string;
14
- }[];
15
- };
16
-
17
-
18
- const users: User[] = [];
19
-
20
- export async function findUserByEmail(email: string): Promise<User | undefined> {
21
- return users.find((u) => u.email === email);
22
- }
23
-
24
- export async function findUserByProvider(
25
- provider: Provider,
26
- providerId: string
27
- ): Promise<User | undefined> {
28
- return users.find((u) =>
29
- u.providers.some(
30
- (p) => p.provider === provider && p.providerId === providerId
31
- )
32
- );
33
- }
34
-
35
- export async function createUser(data: {
36
- email: string;
37
- provider: Provider;
38
- providerId: string;
39
- }): Promise<User> {
40
- const newUser: User = {
41
- id: crypto.randomUUID(),
42
- email: data.email,
43
- providers: [
44
- {
45
- provider: data.provider,
46
- providerId: data.providerId,
47
- },
48
- ],
49
- };
50
-
51
- users.push(newUser);
52
- return newUser;
53
- }
54
-
55
- export async function linkProvider(
56
- userId: string,
57
- provider: Provider,
58
- providerId: string
59
- ): Promise<void> {
60
- const user = users.find((u) => u.id === userId);
61
-
62
- if (!user) return;
63
-
64
- const alreadyLinked = user.providers.some(
65
- (p) => p.provider === provider
66
- );
67
-
68
- if (!alreadyLinked) {
69
- user.providers.push({ provider, providerId });
70
- }
71
- }
72
-
73
-
@@ -1,137 +0,0 @@
1
- import dotenv from "dotenv";
2
- import {RedisStore} from "connect-redis";
3
- import Redis ,{ Redis as RedisCon }from "ioredis";
4
- dotenv.config();
5
-
6
-
7
-
8
-
9
- interface RedisConfig{
10
- url?: string;
11
- host?: string
12
- port?: number;
13
- password?: string;
14
- maxRetriesPerRequest?:number;
15
- connectTimeout: number;
16
- }
17
-
18
- interface RedisStoreOptions{
19
- prefix?: string;
20
- ttl?: number;
21
- }
22
-
23
- interface SetupRedisOptions{
24
- redisConfig?: Partial<RedisConfig>;
25
- storeOptions?:Partial<RedisStoreOptions>;
26
- }
27
-
28
- let redisClientInstance:RedisCon | null = null
29
- let redisStoreInstance:RedisStore |null = null
30
-
31
- const DEFAULT_REDIS_CONFIG: RedisConfig = {
32
- host:process.env.REDIS_HOST ?? "127.0.0.1",
33
- port: Number(process.env.REDIS_PORT ?? "6379"),
34
- maxRetriesPerRequest: 10,
35
- connectTimeout: 5000
36
- }
37
-
38
- const DEFAULT_STORE_OPTIONS : RedisStoreOptions = {
39
- prefix: "session",
40
- ttl: 86400
41
- }
42
-
43
- const validateRedisConfig = (config:RedisConfig) => {
44
- if (!config.url && !config.host) {
45
- throw new Error("Redis configuration requires either URL or host/port");
46
- }
47
-
48
- if (config.url && !config.url.startsWith("redis://") && !config.url.startsWith("rediss://")
49
- ) {
50
- throw new Error("Redis URL must use 'redis://' protocol");
51
- }
52
-
53
- };
54
-
55
- const getRedisConfig = (options?:Partial<RedisConfig>): RedisConfig => {
56
- const port = options?.port ?
57
- Number(options.port) :
58
- process.env.REDIS_PORT ? Number(process.env.REDIS_PORT) :
59
- Number(DEFAULT_REDIS_CONFIG.port);
60
-
61
- const config: RedisConfig = {
62
- ...DEFAULT_REDIS_CONFIG,
63
- host: options?.host || process.env.REDIS_HOST|| DEFAULT_REDIS_CONFIG.host,
64
- port: port,
65
- password: options?.password || process.env.REDIS_PASSWORD|| undefined,
66
- ...options
67
- };
68
-
69
- validateRedisConfig(config);
70
- return config;
71
- };
72
-
73
- const setupRedis = async (options?: SetupRedisOptions) => {
74
-
75
- try {
76
- const config = getRedisConfig(options?.redisConfig);
77
- const storeOptions = {...DEFAULT_STORE_OPTIONS, ...options?.storeOptions}
78
-
79
- const redisClient = new Redis({
80
- host: config.host as string,
81
- port:Number(config.port) ,
82
- connectTimeout:config.connectTimeout,
83
- password :config.password,
84
- retryStrategy:(times:number)=> Math.min(times * 50,2000),
85
- maxRetriesPerRequest:config.maxRetriesPerRequest
86
- });
87
-
88
- await new Promise<void>((resolve, reject)=>{
89
- redisClient.once("ready", async () =>{
90
- try{
91
- const pong = await redisClient.ping();
92
- console.log("Redis ping response:",pong);
93
- resolve();
94
- }catch(err){
95
- reject(err);
96
- }
97
- })
98
- redisClient.once("error",(err)=>{
99
- reject(err);
100
- })
101
- });
102
-
103
- const redisStore = new RedisStore({
104
- client: redisClient,
105
- prefix:storeOptions.prefix,
106
- ttl:storeOptions.ttl
107
- });
108
-
109
-
110
- redisClient.on("error", (err:Error) => {
111
- console.error("Redis client error:", err);
112
- });
113
-
114
- redisClient.on("ready", () => {
115
- console.log("Redis client is ready");
116
- });
117
-
118
- redisClient.on("reconnecting", () => {
119
- console.log("Redis client reconnecting...");
120
- });
121
-
122
- return{ redisClient, redisStore };
123
- } catch (error) {
124
- console.error("Redis setup failed:", error);
125
- throw error;
126
- }
127
- };
128
- const initializeRedisClient =async () => {
129
- if(!redisClientInstance){
130
- const {redisClient} = await setupRedis();
131
- redisClientInstance= redisClient;
132
- }
133
- return redisClientInstance
134
- };
135
-
136
- export {setupRedis, initializeRedisClient};
137
- export type {RedisConfig, RedisStoreOptions, SetupRedisOptions}
@@ -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
-