@eventuras/fides-auth-next 0.1.5 → 0.1.12
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/LICENSE +674 -0
- package/dist/cookies.js +192 -53
- package/dist/cookies.js.map +1 -0
- package/dist/index.js +18 -17
- package/dist/oidc-callback.js +52 -22
- package/dist/oidc-callback.js.map +1 -0
- package/dist/oidc-login.js +41 -15
- package/dist/oidc-login.js.map +1 -0
- package/dist/request.js +27 -17
- package/dist/request.js.map +1 -0
- package/dist/session.js +184 -44
- package/dist/session.js.map +1 -0
- package/dist/store/configure-logger.js +21 -6
- package/dist/store/configure-logger.js.map +1 -0
- package/dist/store/hooks.js +61 -19
- package/dist/store/hooks.js.map +1 -0
- package/dist/store/index.js +6 -6
- package/dist/store/session-monitor.js +80 -37
- package/dist/store/session-monitor.js.map +1 -0
- package/dist/store/store.js +174 -90
- package/dist/store/store.js.map +1 -0
- package/dist/store/use-session-monitor.js +35 -8
- package/dist/store/use-session-monitor.js.map +1 -0
- package/package.json +22 -13
- package/dist/fides-auth/dist/build-CNL3v39v.js +0 -977
- package/dist/fides-auth/dist/decode_jwt-1J26fl4I.js +0 -25
- package/dist/fides-auth/dist/decrypt-Cahlu_6Y.js +0 -88
- package/dist/fides-auth/dist/deflate-koSuX7FB.js +0 -969
- package/dist/fides-auth/dist/logger.js +0 -46
- package/dist/fides-auth/dist/oauth.js +0 -165
- package/dist/fides-auth/dist/rate-limit.js +0 -26
- package/dist/fides-auth/dist/session-refresh.js +0 -27
- package/dist/fides-auth/dist/session-validation-BxObT3wC.js +0 -64
- package/dist/fides-auth/dist/silent-login.js +0 -50
- package/dist/fides-auth/dist/utils-ByMRF7b2.js +0 -379
package/dist/cookies.js
CHANGED
|
@@ -1,81 +1,220 @@
|
|
|
1
|
-
import { cookies
|
|
2
|
-
import { Logger
|
|
1
|
+
import { cookies } from "next/headers";
|
|
2
|
+
import { Logger } from "@eventuras/logger";
|
|
3
3
|
//#region src/cookies.ts
|
|
4
|
-
|
|
4
|
+
/**
|
|
5
|
+
* Cookie helpers for Next.js authentication flows.
|
|
6
|
+
*
|
|
7
|
+
* IMPORTANT: These functions can ONLY be used in:
|
|
8
|
+
* - Server Actions (functions marked with 'use server')
|
|
9
|
+
* - Route Handlers (files in app/api directory)
|
|
10
|
+
* - Server Components (async React components)
|
|
11
|
+
*
|
|
12
|
+
* They CANNOT be used in:
|
|
13
|
+
* - Client Components (marked with 'use client')
|
|
14
|
+
* - Middleware (use NextResponse.cookies instead)
|
|
15
|
+
* - Edge Runtime without proper configuration
|
|
16
|
+
*/
|
|
17
|
+
var logger = Logger.create({ namespace: "fides-auth-next:cookies" });
|
|
18
|
+
/**
|
|
19
|
+
* Default cookie options for session cookies.
|
|
20
|
+
* - Secure in production
|
|
21
|
+
* - HTTP only
|
|
22
|
+
* - Lax same-site policy
|
|
23
|
+
* - 30 days max age
|
|
24
|
+
*/
|
|
25
|
+
var defaultSessionCookieOptions = {
|
|
5
26
|
path: "/",
|
|
6
27
|
maxAge: 3600 * 24 * 30,
|
|
7
28
|
sameSite: "lax",
|
|
8
|
-
httpOnly:
|
|
29
|
+
httpOnly: true,
|
|
9
30
|
secure: process.env.NODE_ENV === "production"
|
|
10
|
-
}
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Default cookie options for OAuth state/PKCE cookies.
|
|
34
|
+
* - Secure in production
|
|
35
|
+
* - HTTP only
|
|
36
|
+
* - Lax same-site policy
|
|
37
|
+
* - 10 minutes max age (short-lived for security)
|
|
38
|
+
*/
|
|
39
|
+
var defaultOAuthCookieOptions = {
|
|
11
40
|
path: "/",
|
|
12
41
|
maxAge: 600,
|
|
13
42
|
sameSite: "lax",
|
|
14
|
-
httpOnly:
|
|
43
|
+
httpOnly: true,
|
|
15
44
|
secure: process.env.NODE_ENV === "production"
|
|
16
45
|
};
|
|
17
|
-
|
|
46
|
+
/**
|
|
47
|
+
* Sets a cookie with the given name and value.
|
|
48
|
+
*
|
|
49
|
+
* @param name - Cookie name
|
|
50
|
+
* @param value - Cookie value
|
|
51
|
+
* @param options - Cookie options (defaults to session cookie options)
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```ts
|
|
55
|
+
* // In a server action or route handler
|
|
56
|
+
* await setAuthCookie('session', encryptedJwt);
|
|
57
|
+
*
|
|
58
|
+
* // With custom options
|
|
59
|
+
* await setAuthCookie('oauth_state', state, {
|
|
60
|
+
* maxAge: 60 * 10, // 10 minutes
|
|
61
|
+
* });
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
async function setAuthCookie(name, value, options = defaultSessionCookieOptions) {
|
|
18
65
|
try {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
...
|
|
66
|
+
const cookieStore = await cookies();
|
|
67
|
+
const cookieOptions = {
|
|
68
|
+
...defaultSessionCookieOptions,
|
|
69
|
+
...options
|
|
22
70
|
};
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
71
|
+
cookieStore.set(name, value, cookieOptions);
|
|
72
|
+
logger.debug({
|
|
73
|
+
cookieName: name,
|
|
74
|
+
maxAge: cookieOptions.maxAge,
|
|
75
|
+
secure: cookieOptions.secure
|
|
27
76
|
}, "Cookie set successfully");
|
|
28
|
-
} catch (
|
|
29
|
-
|
|
30
|
-
error
|
|
31
|
-
cookieName:
|
|
32
|
-
}, "Failed to set cookie")
|
|
77
|
+
} catch (error) {
|
|
78
|
+
logger.error({
|
|
79
|
+
error,
|
|
80
|
+
cookieName: name
|
|
81
|
+
}, "Failed to set cookie");
|
|
82
|
+
throw error;
|
|
33
83
|
}
|
|
34
84
|
}
|
|
35
|
-
|
|
85
|
+
/**
|
|
86
|
+
* Gets a cookie value by name.
|
|
87
|
+
*
|
|
88
|
+
* @param name - Cookie name
|
|
89
|
+
* @returns Cookie value or null if not found
|
|
90
|
+
*
|
|
91
|
+
* @example
|
|
92
|
+
* ```ts
|
|
93
|
+
* // In a server action or route handler
|
|
94
|
+
* const sessionCookie = await getAuthCookie('session');
|
|
95
|
+
* if (sessionCookie) {
|
|
96
|
+
* // Validate and use session
|
|
97
|
+
* }
|
|
98
|
+
* ```
|
|
99
|
+
*/
|
|
100
|
+
async function getAuthCookie(name) {
|
|
36
101
|
try {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
102
|
+
const cookie = (await cookies()).get(name);
|
|
103
|
+
if (!cookie?.value) {
|
|
104
|
+
logger.debug({ cookieName: name }, "Cookie not found");
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
logger.debug({ cookieName: name }, "Cookie retrieved");
|
|
108
|
+
return cookie.value;
|
|
109
|
+
} catch (error) {
|
|
110
|
+
logger.error({
|
|
111
|
+
error,
|
|
112
|
+
cookieName: name
|
|
113
|
+
}, "Failed to get cookie");
|
|
114
|
+
return null;
|
|
44
115
|
}
|
|
45
116
|
}
|
|
46
|
-
|
|
117
|
+
/**
|
|
118
|
+
* Deletes a cookie by name.
|
|
119
|
+
*
|
|
120
|
+
* @param name - Cookie name to delete
|
|
121
|
+
*
|
|
122
|
+
* @example
|
|
123
|
+
* ```ts
|
|
124
|
+
* // In a server action or route handler
|
|
125
|
+
* await deleteAuthCookie('session');
|
|
126
|
+
* ```
|
|
127
|
+
*/
|
|
128
|
+
async function deleteAuthCookie(name) {
|
|
47
129
|
try {
|
|
48
|
-
(await
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
130
|
+
(await cookies()).delete(name);
|
|
131
|
+
logger.debug({ cookieName: name }, "Cookie deleted successfully");
|
|
132
|
+
} catch (error) {
|
|
133
|
+
logger.error({
|
|
134
|
+
error,
|
|
135
|
+
cookieName: name
|
|
136
|
+
}, "Failed to delete cookie");
|
|
137
|
+
throw error;
|
|
54
138
|
}
|
|
55
139
|
}
|
|
56
|
-
|
|
140
|
+
/**
|
|
141
|
+
* Deletes multiple cookies at once.
|
|
142
|
+
* Useful for cleaning up OAuth flow cookies.
|
|
143
|
+
*
|
|
144
|
+
* @param names - Array of cookie names to delete
|
|
145
|
+
*
|
|
146
|
+
* @example
|
|
147
|
+
* ```ts
|
|
148
|
+
* // Clean up OAuth cookies after callback
|
|
149
|
+
* await deleteAuthCookies(['oauth_state', 'oauth_code_verifier', 'returnTo']);
|
|
150
|
+
* ```
|
|
151
|
+
*/
|
|
152
|
+
async function deleteAuthCookies(names) {
|
|
57
153
|
try {
|
|
58
|
-
|
|
59
|
-
for (
|
|
60
|
-
|
|
61
|
-
} catch (
|
|
62
|
-
|
|
63
|
-
error
|
|
64
|
-
cookieNames:
|
|
65
|
-
}, "Failed to delete cookies")
|
|
154
|
+
const cookieStore = await cookies();
|
|
155
|
+
for (const name of names) cookieStore.delete(name);
|
|
156
|
+
logger.debug({ cookieNames: names }, "Multiple cookies deleted successfully");
|
|
157
|
+
} catch (error) {
|
|
158
|
+
logger.error({
|
|
159
|
+
error,
|
|
160
|
+
cookieNames: names
|
|
161
|
+
}, "Failed to delete cookies");
|
|
162
|
+
throw error;
|
|
66
163
|
}
|
|
67
164
|
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
165
|
+
/**
|
|
166
|
+
* Sets the session cookie with proper security settings.
|
|
167
|
+
* This is a convenience wrapper around setAuthCookie.
|
|
168
|
+
*
|
|
169
|
+
* @param encryptedJwt - The encrypted JWT session token
|
|
170
|
+
* @param options - Optional cookie options (merged with defaults)
|
|
171
|
+
*
|
|
172
|
+
* @example
|
|
173
|
+
* ```ts
|
|
174
|
+
* const jwt = await createSession({ ... });
|
|
175
|
+
* await setSessionCookie(jwt);
|
|
176
|
+
* ```
|
|
177
|
+
*/
|
|
178
|
+
async function setSessionCookie(encryptedJwt, options = {}) {
|
|
179
|
+
await setAuthCookie("session", encryptedJwt, {
|
|
180
|
+
...defaultSessionCookieOptions,
|
|
181
|
+
...options
|
|
182
|
+
});
|
|
183
|
+
logger.info("Session cookie set");
|
|
73
184
|
}
|
|
74
|
-
|
|
75
|
-
|
|
185
|
+
/**
|
|
186
|
+
* Gets the current session cookie value.
|
|
187
|
+
* Returns null if no session cookie exists.
|
|
188
|
+
*
|
|
189
|
+
* @returns Encrypted JWT session token or null
|
|
190
|
+
*
|
|
191
|
+
* @example
|
|
192
|
+
* ```ts
|
|
193
|
+
* const sessionToken = await getSessionCookie();
|
|
194
|
+
* if (sessionToken) {
|
|
195
|
+
* const { status, session } = await validateSessionJwt(sessionToken);
|
|
196
|
+
* // ...
|
|
197
|
+
* }
|
|
198
|
+
* ```
|
|
199
|
+
*/
|
|
200
|
+
async function getSessionCookie() {
|
|
201
|
+
return await getAuthCookie("session");
|
|
76
202
|
}
|
|
77
|
-
|
|
78
|
-
|
|
203
|
+
/**
|
|
204
|
+
* Deletes the session cookie.
|
|
205
|
+
* Use this when logging out or when session validation fails.
|
|
206
|
+
*
|
|
207
|
+
* @example
|
|
208
|
+
* ```ts
|
|
209
|
+
* await deleteSessionCookie();
|
|
210
|
+
* redirect('/');
|
|
211
|
+
* ```
|
|
212
|
+
*/
|
|
213
|
+
async function deleteSessionCookie() {
|
|
214
|
+
await deleteAuthCookie("session");
|
|
215
|
+
logger.info("Session cookie deleted");
|
|
79
216
|
}
|
|
80
217
|
//#endregion
|
|
81
|
-
export {
|
|
218
|
+
export { defaultOAuthCookieOptions, defaultSessionCookieOptions, deleteAuthCookie, deleteAuthCookies, deleteSessionCookie, getAuthCookie, getSessionCookie, setAuthCookie, setSessionCookie };
|
|
219
|
+
|
|
220
|
+
//# sourceMappingURL=cookies.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cookies.js","names":[],"sources":["../src/cookies.ts"],"sourcesContent":["/**\n * Cookie helpers for Next.js authentication flows.\n *\n * IMPORTANT: These functions can ONLY be used in:\n * - Server Actions (functions marked with 'use server')\n * - Route Handlers (files in app/api directory)\n * - Server Components (async React components)\n *\n * They CANNOT be used in:\n * - Client Components (marked with 'use client')\n * - Middleware (use NextResponse.cookies instead)\n * - Edge Runtime without proper configuration\n */\n\nimport { Logger } from '@eventuras/logger';\nimport { cookies } from 'next/headers';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:cookies' });\n\nexport interface CookieOptions {\n /** Cookie path (default: '/') */\n path?: string;\n /** Max age in seconds */\n maxAge?: number;\n /** SameSite policy (default: 'lax') */\n sameSite?: 'strict' | 'lax' | 'none';\n /** HTTP only flag (default: true) */\n httpOnly?: boolean;\n /** Secure flag (default: true in production) */\n secure?: boolean;\n}\n\n/**\n * Default cookie options for session cookies.\n * - Secure in production\n * - HTTP only\n * - Lax same-site policy\n * - 30 days max age\n */\nexport const defaultSessionCookieOptions: CookieOptions = {\n path: '/',\n maxAge: 60 * 60 * 24 * 30, // 30 days\n sameSite: 'lax',\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n};\n\n/**\n * Default cookie options for OAuth state/PKCE cookies.\n * - Secure in production\n * - HTTP only\n * - Lax same-site policy\n * - 10 minutes max age (short-lived for security)\n */\nexport const defaultOAuthCookieOptions: CookieOptions = {\n path: '/',\n maxAge: 60 * 10, // 10 minutes\n sameSite: 'lax',\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n};\n\n/**\n * Sets a cookie with the given name and value.\n *\n * @param name - Cookie name\n * @param value - Cookie value\n * @param options - Cookie options (defaults to session cookie options)\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * await setAuthCookie('session', encryptedJwt);\n *\n * // With custom options\n * await setAuthCookie('oauth_state', state, {\n * maxAge: 60 * 10, // 10 minutes\n * });\n * ```\n */\nexport async function setAuthCookie(\n name: string,\n value: string,\n options: CookieOptions = defaultSessionCookieOptions\n): Promise<void> {\n try {\n const cookieStore = await cookies();\n const cookieOptions = { ...defaultSessionCookieOptions, ...options };\n\n cookieStore.set(name, value, cookieOptions);\n\n logger.debug({\n cookieName: name,\n maxAge: cookieOptions.maxAge,\n secure: cookieOptions.secure\n }, 'Cookie set successfully');\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to set cookie');\n throw error;\n }\n}\n\n/**\n * Gets a cookie value by name.\n *\n * @param name - Cookie name\n * @returns Cookie value or null if not found\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * const sessionCookie = await getAuthCookie('session');\n * if (sessionCookie) {\n * // Validate and use session\n * }\n * ```\n */\nexport async function getAuthCookie(name: string): Promise<string | null> {\n try {\n const cookieStore = await cookies();\n const cookie = cookieStore.get(name);\n\n if (!cookie?.value) {\n logger.debug({ cookieName: name }, 'Cookie not found');\n return null;\n }\n\n logger.debug({ cookieName: name }, 'Cookie retrieved');\n return cookie.value;\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to get cookie');\n return null;\n }\n}\n\n/**\n * Deletes a cookie by name.\n *\n * @param name - Cookie name to delete\n *\n * @example\n * ```ts\n * // In a server action or route handler\n * await deleteAuthCookie('session');\n * ```\n */\nexport async function deleteAuthCookie(name: string): Promise<void> {\n try {\n const cookieStore = await cookies();\n cookieStore.delete(name);\n\n logger.debug({ cookieName: name }, 'Cookie deleted successfully');\n } catch (error) {\n logger.error({ error, cookieName: name }, 'Failed to delete cookie');\n throw error;\n }\n}\n\n/**\n * Deletes multiple cookies at once.\n * Useful for cleaning up OAuth flow cookies.\n *\n * @param names - Array of cookie names to delete\n *\n * @example\n * ```ts\n * // Clean up OAuth cookies after callback\n * await deleteAuthCookies(['oauth_state', 'oauth_code_verifier', 'returnTo']);\n * ```\n */\nexport async function deleteAuthCookies(names: string[]): Promise<void> {\n try {\n const cookieStore = await cookies();\n\n for (const name of names) {\n cookieStore.delete(name);\n }\n\n logger.debug({ cookieNames: names }, 'Multiple cookies deleted successfully');\n } catch (error) {\n logger.error({ error, cookieNames: names }, 'Failed to delete cookies');\n throw error;\n }\n}\n\n/**\n * Sets the session cookie with proper security settings.\n * This is a convenience wrapper around setAuthCookie.\n *\n * @param encryptedJwt - The encrypted JWT session token\n * @param options - Optional cookie options (merged with defaults)\n *\n * @example\n * ```ts\n * const jwt = await createSession({ ... });\n * await setSessionCookie(jwt);\n * ```\n */\nexport async function setSessionCookie(\n encryptedJwt: string,\n options: Partial<CookieOptions> = {}\n): Promise<void> {\n await setAuthCookie('session', encryptedJwt, {\n ...defaultSessionCookieOptions,\n ...options,\n });\n\n logger.info('Session cookie set');\n}\n\n/**\n * Gets the current session cookie value.\n * Returns null if no session cookie exists.\n *\n * @returns Encrypted JWT session token or null\n *\n * @example\n * ```ts\n * const sessionToken = await getSessionCookie();\n * if (sessionToken) {\n * const { status, session } = await validateSessionJwt(sessionToken);\n * // ...\n * }\n * ```\n */\nexport async function getSessionCookie(): Promise<string | null> {\n return await getAuthCookie('session');\n}\n\n/**\n * Deletes the session cookie.\n * Use this when logging out or when session validation fails.\n *\n * @example\n * ```ts\n * await deleteSessionCookie();\n * redirect('/');\n * ```\n */\nexport async function deleteSessionCookie(): Promise<void> {\n await deleteAuthCookie('session');\n logger.info('Session cookie deleted');\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,2BAA2B,CAAC;;;;;;;;AAsBtE,IAAa,8BAA6C;CACxD,MAAM;CACN,QAAQ,OAAU,KAAK;CACvB,UAAU;CACV,UAAU;CACV,QAAA,QAAA,IAAA,aAAiC;CAClC;;;;;;;;AASD,IAAa,4BAA2C;CACtD,MAAM;CACN,QAAQ;CACR,UAAU;CACV,UAAU;CACV,QAAA,QAAA,IAAA,aAAiC;CAClC;;;;;;;;;;;;;;;;;;;AAoBD,eAAsB,cACpB,MACA,OACA,UAAyB,6BACV;CACf,IAAI;EACF,MAAM,cAAc,MAAM,SAAS;EACnC,MAAM,gBAAgB;GAAE,GAAG;GAA6B,GAAG;GAAS;EAEpE,YAAY,IAAI,MAAM,OAAO,cAAc;EAE3C,OAAO,MAAM;GACX,YAAY;GACZ,QAAQ,cAAc;GACtB,QAAQ,cAAc;GACvB,EAAE,0BAA0B;UACtB,OAAO;EACd,OAAO,MAAM;GAAE;GAAO,YAAY;GAAM,EAAE,uBAAuB;EACjE,MAAM;;;;;;;;;;;;;;;;;;AAmBV,eAAsB,cAAc,MAAsC;CACxE,IAAI;EAEF,MAAM,UAAS,MADW,SAAS,EACR,IAAI,KAAK;EAEpC,IAAI,CAAC,QAAQ,OAAO;GAClB,OAAO,MAAM,EAAE,YAAY,MAAM,EAAE,mBAAmB;GACtD,OAAO;;EAGT,OAAO,MAAM,EAAE,YAAY,MAAM,EAAE,mBAAmB;EACtD,OAAO,OAAO;UACP,OAAO;EACd,OAAO,MAAM;GAAE;GAAO,YAAY;GAAM,EAAE,uBAAuB;EACjE,OAAO;;;;;;;;;;;;;;AAeX,eAAsB,iBAAiB,MAA6B;CAClE,IAAI;EAEF,CAAA,MAD0B,SAAS,EACvB,OAAO,KAAK;EAExB,OAAO,MAAM,EAAE,YAAY,MAAM,EAAE,8BAA8B;UAC1D,OAAO;EACd,OAAO,MAAM;GAAE;GAAO,YAAY;GAAM,EAAE,0BAA0B;EACpE,MAAM;;;;;;;;;;;;;;;AAgBV,eAAsB,kBAAkB,OAAgC;CACtE,IAAI;EACF,MAAM,cAAc,MAAM,SAAS;EAEnC,KAAK,MAAM,QAAQ,OACjB,YAAY,OAAO,KAAK;EAG1B,OAAO,MAAM,EAAE,aAAa,OAAO,EAAE,wCAAwC;UACtE,OAAO;EACd,OAAO,MAAM;GAAE;GAAO,aAAa;GAAO,EAAE,2BAA2B;EACvE,MAAM;;;;;;;;;;;;;;;;AAiBV,eAAsB,iBACpB,cACA,UAAkC,EAAE,EACrB;CACf,MAAM,cAAc,WAAW,cAAc;EAC3C,GAAG;EACH,GAAG;EACJ,CAAC;CAEF,OAAO,KAAK,qBAAqB;;;;;;;;;;;;;;;;;AAkBnC,eAAsB,mBAA2C;CAC/D,OAAO,MAAM,cAAc,UAAU;;;;;;;;;;;;AAavC,eAAsB,sBAAqC;CACzD,MAAM,iBAAiB,UAAU;CACjC,OAAO,KAAK,yBAAyB"}
|
package/dist/index.js
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { checkAuth as W, createAuthStore as G, initializeAuth as K } from "./store/store.js";
|
|
12
|
-
import { createAuthStoreHooks as q } from "./store/hooks.js";
|
|
13
|
-
import { startSessionMonitor as J } from "./store/session-monitor.js";
|
|
14
|
-
import { useSessionMonitor as Y } from "./store/use-session-monitor.js";
|
|
15
|
-
import { configureAuthLogger as X } from "./store/configure-logger.js";
|
|
1
|
+
import { globalGETRateLimit, globalPOSTRateLimit } from "./request.js";
|
|
2
|
+
import { defaultOAuthCookieOptions, defaultSessionCookieOptions, deleteAuthCookie, deleteAuthCookies, deleteSessionCookie, getAuthCookie, getSessionCookie, setAuthCookie, setSessionCookie } from "./cookies.js";
|
|
3
|
+
import { clearCurrentSession, createAndPersistSession, createSession, getCurrentSession, refreshCurrentSession } from "./session.js";
|
|
4
|
+
import { handleOidcCallback } from "./oidc-callback.js";
|
|
5
|
+
import { handleOidcLogin } from "./oidc-login.js";
|
|
6
|
+
import { checkAuth, createAuthStore, initializeAuth } from "./store/store.js";
|
|
7
|
+
import { createAuthStoreHooks } from "./store/hooks.js";
|
|
8
|
+
import { startSessionMonitor } from "./store/session-monitor.js";
|
|
9
|
+
import { useSessionMonitor } from "./store/use-session-monitor.js";
|
|
10
|
+
import { configureAuthLogger } from "./store/configure-logger.js";
|
|
16
11
|
import "./store/index.js";
|
|
17
|
-
import {
|
|
18
|
-
export
|
|
12
|
+
import { TokenBucket } from "@eventuras/fides-auth/rate-limit";
|
|
13
|
+
export * from "@eventuras/fides-auth/utils";
|
|
14
|
+
export * from "@eventuras/fides-auth/session-validation";
|
|
15
|
+
export * from "@eventuras/fides-auth/session-refresh";
|
|
16
|
+
export * from "@eventuras/fides-auth/oauth";
|
|
17
|
+
export * from "@eventuras/fides-auth/silent-login";
|
|
18
|
+
export * from "@eventuras/fides-auth/types";
|
|
19
|
+
export { TokenBucket, checkAuth, clearCurrentSession, configureAuthLogger, createAndPersistSession, createAuthStore, createAuthStoreHooks, createSession, defaultOAuthCookieOptions, defaultSessionCookieOptions, deleteAuthCookie, deleteAuthCookies, deleteSessionCookie, getAuthCookie, getCurrentSession, getSessionCookie, globalGETRateLimit, globalPOSTRateLimit, handleOidcCallback, handleOidcLogin, initializeAuth, refreshCurrentSession, setAuthCookie, setSessionCookie, startSessionMonitor, useSessionMonitor };
|
package/dist/oidc-callback.js
CHANGED
|
@@ -1,33 +1,63 @@
|
|
|
1
|
-
import { globalGETRateLimit
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
1
|
+
import { globalGETRateLimit } from "./request.js";
|
|
2
|
+
import { deleteAuthCookies, getAuthCookie, setSessionCookie } from "./cookies.js";
|
|
3
|
+
import { createSession } from "./session.js";
|
|
4
|
+
import { Logger } from "@eventuras/logger";
|
|
5
|
+
import { buildSessionFromTokens, exchangeAuthorizationCode, validateReturnUrl } from "@eventuras/fides-auth/oauth";
|
|
6
6
|
//#region src/oidc-callback.ts
|
|
7
|
-
var
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
7
|
+
var logger = Logger.create({ namespace: "fides-auth-next:oidc-callback" });
|
|
8
|
+
/**
|
|
9
|
+
* Handles the OIDC callback in a Next.js route handler.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* // In app/api/auth/callback/oidc/route.ts
|
|
14
|
+
* import { handleOidcCallback } from '@eventuras/fides-auth-next/oidc-callback';
|
|
15
|
+
*
|
|
16
|
+
* export async function GET(request: Request) {
|
|
17
|
+
* return handleOidcCallback(request, {
|
|
18
|
+
* oauthConfig,
|
|
19
|
+
* applicationUrl: 'https://example.com',
|
|
20
|
+
* rolesClaim: 'roles',
|
|
21
|
+
* });
|
|
22
|
+
* }
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
async function handleOidcCallback(request, config) {
|
|
26
|
+
const { oauthConfig, applicationUrl, rolesClaim = "roles", sessionDurationDays = 7, defaultRedirectPath = "/", validateReturnTo } = config;
|
|
27
|
+
if (!await globalGETRateLimit()) {
|
|
28
|
+
logger.warn("Rate limit exceeded");
|
|
29
|
+
return new Response("Too many requests", { status: 429 });
|
|
30
|
+
}
|
|
11
31
|
try {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
32
|
+
const currentUrl = new URL(request.url);
|
|
33
|
+
const publicUrl = new URL(applicationUrl);
|
|
34
|
+
publicUrl.search = currentUrl.search;
|
|
35
|
+
const storedState = await getAuthCookie("oauth_state");
|
|
36
|
+
const storedCodeVerifier = await getAuthCookie("oauth_code_verifier");
|
|
37
|
+
if (!storedState || !storedCodeVerifier) {
|
|
38
|
+
logger.warn("Missing state or code verifier");
|
|
39
|
+
return new Response("Please restart the login process.", { status: 400 });
|
|
40
|
+
}
|
|
41
|
+
await setSessionCookie(await createSession(buildSessionFromTokens(await exchangeAuthorizationCode(oauthConfig, publicUrl, storedCodeVerifier, storedState), rolesClaim), { sessionDurationDays }));
|
|
42
|
+
const returnTo = await getAuthCookie("returnTo");
|
|
43
|
+
await deleteAuthCookies([
|
|
19
44
|
"oauth_state",
|
|
20
45
|
"oauth_code_verifier",
|
|
21
46
|
"returnTo"
|
|
22
47
|
]);
|
|
23
|
-
|
|
24
|
-
|
|
48
|
+
const redirectUrl = validateReturnUrl(returnTo, applicationUrl, defaultRedirectPath, validateReturnTo);
|
|
49
|
+
redirectUrl.searchParams.set("login", "success");
|
|
50
|
+
logger.info({ redirectUrl: redirectUrl.toString() }, "Login successful, redirecting");
|
|
51
|
+
return new Response(null, {
|
|
25
52
|
status: 302,
|
|
26
|
-
headers: { Location:
|
|
53
|
+
headers: { Location: redirectUrl.toString() }
|
|
27
54
|
});
|
|
28
|
-
} catch (
|
|
29
|
-
|
|
55
|
+
} catch (error) {
|
|
56
|
+
logger.error({ error }, "OIDC callback error");
|
|
57
|
+
return new Response("An unexpected error occurred. Please restart the login process.", { status: 500 });
|
|
30
58
|
}
|
|
31
59
|
}
|
|
32
60
|
//#endregion
|
|
33
|
-
export {
|
|
61
|
+
export { handleOidcCallback };
|
|
62
|
+
|
|
63
|
+
//# sourceMappingURL=oidc-callback.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oidc-callback.js","names":[],"sources":["../src/oidc-callback.ts"],"sourcesContent":["/**\n * Generic OIDC callback handler for Next.js route handlers.\n *\n * Orchestrates the Next.js-specific concerns (cookies, rate limiting, HTTP responses)\n * while delegating OIDC logic to @eventuras/fides-auth.\n */\n\nimport type { OAuthConfig } from '@eventuras/fides-auth/oauth';\nimport {\n buildSessionFromTokens,\n exchangeAuthorizationCode,\n validateReturnUrl,\n} from '@eventuras/fides-auth/oauth';\nimport { Logger } from '@eventuras/logger';\n\nimport {\n getAuthCookie,\n setSessionCookie,\n deleteAuthCookies,\n} from './cookies';\nimport { globalGETRateLimit } from './request';\nimport { createSession } from './session';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:oidc-callback' });\n\nexport interface OidcCallbackConfig {\n /** OAuth/OIDC configuration (issuer, clientId, clientSecret, redirect_uri, scope) */\n oauthConfig: OAuthConfig;\n\n /** Public application URL (used to reconstruct the callback URL and validate redirects) */\n applicationUrl: string;\n\n /**\n * Name of the ID token claim that contains user roles.\n * @default 'roles'\n */\n rolesClaim?: string;\n\n /**\n * Session duration in days.\n * @default 7\n */\n sessionDurationDays?: number;\n\n /**\n * Default path to redirect to after login if no returnTo cookie is set.\n * @default '/'\n */\n defaultRedirectPath?: string;\n\n /**\n * Optional function to validate the returnTo path.\n * If not provided, only same-origin paths are allowed.\n */\n validateReturnTo?: (path: string) => boolean;\n}\n\n/**\n * Handles the OIDC callback in a Next.js route handler.\n *\n * @example\n * ```ts\n * // In app/api/auth/callback/oidc/route.ts\n * import { handleOidcCallback } from '@eventuras/fides-auth-next/oidc-callback';\n *\n * export async function GET(request: Request) {\n * return handleOidcCallback(request, {\n * oauthConfig,\n * applicationUrl: 'https://example.com',\n * rolesClaim: 'roles',\n * });\n * }\n * ```\n */\nexport async function handleOidcCallback(\n request: Request,\n config: OidcCallbackConfig,\n): Promise<Response> {\n const {\n oauthConfig,\n applicationUrl,\n rolesClaim = 'roles',\n sessionDurationDays = 7,\n defaultRedirectPath = '/',\n validateReturnTo,\n } = config;\n\n // 1) Rate limit\n if (!(await globalGETRateLimit())) {\n logger.warn('Rate limit exceeded');\n return new Response('Too many requests', { status: 429 });\n }\n\n try {\n // 2) Reconstruct the public callback URL\n const currentUrl = new URL(request.url);\n const publicUrl = new URL(applicationUrl);\n publicUrl.search = currentUrl.search;\n\n // 3) Read PKCE cookies\n const storedState = await getAuthCookie('oauth_state');\n const storedCodeVerifier = await getAuthCookie('oauth_code_verifier');\n\n if (!storedState || !storedCodeVerifier) {\n logger.warn('Missing state or code verifier');\n return new Response('Please restart the login process.', { status: 400 });\n }\n\n // 4) Exchange code for tokens (generic OIDC logic in fides-auth)\n const tokens = await exchangeAuthorizationCode(\n oauthConfig,\n publicUrl,\n storedCodeVerifier,\n storedState,\n );\n\n // 5) Build session from tokens and persist\n const session = buildSessionFromTokens(tokens, rolesClaim);\n const jwt = await createSession(session, { sessionDurationDays });\n await setSessionCookie(jwt);\n\n // 7) Clean up PKCE & returnTo cookies\n const returnTo = await getAuthCookie('returnTo');\n await deleteAuthCookies(['oauth_state', 'oauth_code_verifier', 'returnTo']);\n\n // 8) Build safe redirect URL (generic validation in fides-auth)\n const redirectUrl = validateReturnUrl(\n returnTo,\n applicationUrl,\n defaultRedirectPath,\n validateReturnTo,\n );\n redirectUrl.searchParams.set('login', 'success');\n\n logger.info({ redirectUrl: redirectUrl.toString() }, 'Login successful, redirecting');\n\n return new Response(null, {\n status: 302,\n headers: { Location: redirectUrl.toString() },\n });\n } catch (error) {\n logger.error({ error }, 'OIDC callback error');\n return new Response('An unexpected error occurred. Please restart the login process.', {\n status: 500,\n });\n }\n}\n"],"mappings":";;;;;;AAuBA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,iCAAiC,CAAC;;;;;;;;;;;;;;;;;;AAmD5E,eAAsB,mBACpB,SACA,QACmB;CACnB,MAAM,EACJ,aACA,gBACA,aAAa,SACb,sBAAsB,GACtB,sBAAsB,KACtB,qBACE;CAGJ,IAAI,CAAE,MAAM,oBAAoB,EAAG;EACjC,OAAO,KAAK,sBAAsB;EAClC,OAAO,IAAI,SAAS,qBAAqB,EAAE,QAAQ,KAAK,CAAC;;CAG3D,IAAI;EAEF,MAAM,aAAa,IAAI,IAAI,QAAQ,IAAI;EACvC,MAAM,YAAY,IAAI,IAAI,eAAe;EACzC,UAAU,SAAS,WAAW;EAG9B,MAAM,cAAc,MAAM,cAAc,cAAc;EACtD,MAAM,qBAAqB,MAAM,cAAc,sBAAsB;EAErE,IAAI,CAAC,eAAe,CAAC,oBAAoB;GACvC,OAAO,KAAK,iCAAiC;GAC7C,OAAO,IAAI,SAAS,qCAAqC,EAAE,QAAQ,KAAK,CAAC;;EAc3E,MAAM,iBAAiB,MADL,cADF,uBAAuB,MARlB,0BACnB,aACA,WACA,oBACA,YACD,EAG8C,WACf,EAAS,EAAE,qBAAqB,CAAC,CACtC;EAG3B,MAAM,WAAW,MAAM,cAAc,WAAW;EAChD,MAAM,kBAAkB;GAAC;GAAe;GAAuB;GAAW,CAAC;EAG3E,MAAM,cAAc,kBAClB,UACA,gBACA,qBACA,iBACD;EACD,YAAY,aAAa,IAAI,SAAS,UAAU;EAEhD,OAAO,KAAK,EAAE,aAAa,YAAY,UAAU,EAAE,EAAE,gCAAgC;EAErF,OAAO,IAAI,SAAS,MAAM;GACxB,QAAQ;GACR,SAAS,EAAE,UAAU,YAAY,UAAU,EAAE;GAC9C,CAAC;UACK,OAAO;EACd,OAAO,MAAM,EAAE,OAAO,EAAE,sBAAsB;EAC9C,OAAO,IAAI,SAAS,mEAAmE,EACrF,QAAQ,KACT,CAAC"}
|
package/dist/oidc-login.js
CHANGED
|
@@ -1,20 +1,46 @@
|
|
|
1
|
-
import { globalGETRateLimit
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
1
|
+
import { globalGETRateLimit } from "./request.js";
|
|
2
|
+
import { defaultOAuthCookieOptions } from "./cookies.js";
|
|
3
|
+
import { cookies } from "next/headers";
|
|
4
|
+
import { Logger } from "@eventuras/logger";
|
|
5
|
+
import { buildPKCEOptions, discoverAndBuildAuthorizationUrl } from "@eventuras/fides-auth/oauth";
|
|
6
6
|
//#region src/oidc-login.ts
|
|
7
|
-
var
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
7
|
+
var logger = Logger.create({ namespace: "fides-auth-next:oidc-login" });
|
|
8
|
+
var defaultValidateReturnTo = (raw) => /^\/(?!\/)/.test(raw) ? raw : null;
|
|
9
|
+
/**
|
|
10
|
+
* Handles OIDC login initiation in a Next.js route handler.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* // In app/api/auth/login/route.ts
|
|
15
|
+
* import { handleOidcLogin } from '@eventuras/fides-auth-next/oidc-login';
|
|
16
|
+
*
|
|
17
|
+
* export async function GET(request: Request) {
|
|
18
|
+
* return handleOidcLogin(request, { oauthConfig });
|
|
19
|
+
* }
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
async function handleOidcLogin(request, config) {
|
|
23
|
+
const { oauthConfig, validateReturnTo = defaultValidateReturnTo } = config;
|
|
24
|
+
if (!await globalGETRateLimit()) {
|
|
25
|
+
logger.warn("Rate limit exceeded");
|
|
26
|
+
return new Response("Too many requests", { status: 429 });
|
|
27
|
+
}
|
|
28
|
+
const rawReturnTo = new URL(request.url).searchParams.get("returnTo");
|
|
29
|
+
const returnTo = rawReturnTo ? validateReturnTo(rawReturnTo) : null;
|
|
30
|
+
const pkce = await buildPKCEOptions(oauthConfig);
|
|
31
|
+
const authorizationUrl = await discoverAndBuildAuthorizationUrl(oauthConfig, pkce);
|
|
32
|
+
logger.info("Redirecting to OIDC provider for login");
|
|
33
|
+
const cookieStore = await cookies();
|
|
34
|
+
const cookieOpts = defaultOAuthCookieOptions;
|
|
35
|
+
cookieStore.set("oauth_state", pkce.state, cookieOpts);
|
|
36
|
+
cookieStore.set("oauth_code_verifier", pkce.code_verifier, cookieOpts);
|
|
37
|
+
if (returnTo) cookieStore.set("returnTo", returnTo, cookieOpts);
|
|
38
|
+
return new Response(null, {
|
|
15
39
|
status: 302,
|
|
16
|
-
headers: { Location:
|
|
40
|
+
headers: { Location: authorizationUrl.toString() }
|
|
17
41
|
});
|
|
18
42
|
}
|
|
19
43
|
//#endregion
|
|
20
|
-
export {
|
|
44
|
+
export { handleOidcLogin };
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=oidc-login.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oidc-login.js","names":[],"sources":["../src/oidc-login.ts"],"sourcesContent":["/**\n * Generic OIDC login initiation handler for Next.js route handlers.\n *\n * Builds PKCE parameters, persists them in cookies, and redirects\n * to the OIDC provider's authorization endpoint.\n */\n\nimport type { OAuthConfig } from '@eventuras/fides-auth/oauth';\nimport {\n buildPKCEOptions,\n discoverAndBuildAuthorizationUrl,\n} from '@eventuras/fides-auth/oauth';\nimport { Logger } from '@eventuras/logger';\nimport { cookies } from 'next/headers';\n\nimport { defaultOAuthCookieOptions } from './cookies';\nimport { globalGETRateLimit } from './request';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:oidc-login' });\n\nexport interface OidcLoginConfig {\n /** OAuth/OIDC configuration */\n oauthConfig: OAuthConfig;\n\n /**\n * Validates and sanitizes the returnTo parameter.\n * Should return a safe path or null to use the default.\n * @default Only allows relative paths starting with /\n */\n validateReturnTo?: (rawReturnTo: string) => string | null;\n}\n\nconst defaultValidateReturnTo = (raw: string): string | null =>\n /^\\/(?!\\/)/.test(raw) ? raw : null;\n\n/**\n * Handles OIDC login initiation in a Next.js route handler.\n *\n * @example\n * ```ts\n * // In app/api/auth/login/route.ts\n * import { handleOidcLogin } from '@eventuras/fides-auth-next/oidc-login';\n *\n * export async function GET(request: Request) {\n * return handleOidcLogin(request, { oauthConfig });\n * }\n * ```\n */\nexport async function handleOidcLogin(\n request: Request,\n config: OidcLoginConfig,\n): Promise<Response> {\n const { oauthConfig, validateReturnTo = defaultValidateReturnTo } = config;\n\n if (!(await globalGETRateLimit())) {\n logger.warn('Rate limit exceeded');\n return new Response('Too many requests', { status: 429 });\n }\n\n // Validate returnTo parameter\n const url = new URL(request.url);\n const rawReturnTo = url.searchParams.get('returnTo');\n const returnTo = rawReturnTo ? validateReturnTo(rawReturnTo) : null;\n\n // Build PKCE & authorization URL\n const pkce = await buildPKCEOptions(oauthConfig);\n const authorizationUrl = await discoverAndBuildAuthorizationUrl(oauthConfig, pkce);\n\n logger.info('Redirecting to OIDC provider for login');\n\n // Persist PKCE state in cookies using Next.js cookies API\n const cookieStore = await cookies();\n const cookieOpts = defaultOAuthCookieOptions;\n\n cookieStore.set('oauth_state', pkce.state, cookieOpts);\n cookieStore.set('oauth_code_verifier', pkce.code_verifier, cookieOpts);\n\n if (returnTo) {\n cookieStore.set('returnTo', returnTo, cookieOpts);\n }\n\n return new Response(null, {\n status: 302,\n headers: { Location: authorizationUrl.toString() },\n });\n}\n"],"mappings":";;;;;;AAkBA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,8BAA8B,CAAC;AAczE,IAAM,2BAA2B,QAC/B,YAAY,KAAK,IAAI,GAAG,MAAM;;;;;;;;;;;;;;AAehC,eAAsB,gBACpB,SACA,QACmB;CACnB,MAAM,EAAE,aAAa,mBAAmB,4BAA4B;CAEpE,IAAI,CAAE,MAAM,oBAAoB,EAAG;EACjC,OAAO,KAAK,sBAAsB;EAClC,OAAO,IAAI,SAAS,qBAAqB,EAAE,QAAQ,KAAK,CAAC;;CAK3D,MAAM,cAAc,IADJ,IAAI,QAAQ,IACR,CAAI,aAAa,IAAI,WAAW;CACpD,MAAM,WAAW,cAAc,iBAAiB,YAAY,GAAG;CAG/D,MAAM,OAAO,MAAM,iBAAiB,YAAY;CAChD,MAAM,mBAAmB,MAAM,iCAAiC,aAAa,KAAK;CAElF,OAAO,KAAK,yCAAyC;CAGrD,MAAM,cAAc,MAAM,SAAS;CACnC,MAAM,aAAa;CAEnB,YAAY,IAAI,eAAe,KAAK,OAAO,WAAW;CACtD,YAAY,IAAI,uBAAuB,KAAK,eAAe,WAAW;CAEtE,IAAI,UACF,YAAY,IAAI,YAAY,UAAU,WAAW;CAGnD,OAAO,IAAI,SAAS,MAAM;EACxB,QAAQ;EACR,SAAS,EAAE,UAAU,iBAAiB,UAAU,EAAE;EACnD,CAAC"}
|
package/dist/request.js
CHANGED
|
@@ -1,26 +1,36 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { Logger
|
|
1
|
+
import { headers } from "next/headers";
|
|
2
|
+
import { TokenBucket } from "@eventuras/fides-auth/rate-limit";
|
|
3
|
+
import { Logger } from "@eventuras/logger";
|
|
4
4
|
//#region src/request.ts
|
|
5
|
-
var
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
var logger = Logger.create({ namespace: "fides-auth-next:request" });
|
|
6
|
+
var globalBucket = null;
|
|
7
|
+
function getBucket() {
|
|
8
|
+
if (!globalBucket) globalBucket = new TokenBucket(100, 1);
|
|
9
|
+
return globalBucket;
|
|
8
10
|
}
|
|
9
|
-
async function
|
|
11
|
+
async function globalGETRateLimit() {
|
|
10
12
|
try {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
const clientIP = (await headers()).get("X-Forwarded-For");
|
|
14
|
+
if (clientIP === null) return true;
|
|
15
|
+
return getBucket().consume(clientIP, 1);
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (error instanceof Error && error.message.includes("worker")) logger.error({ error }, "Worker thread error in globalGETRateLimit");
|
|
18
|
+
else logger.error({ error }, "Unexpected error in globalGETRateLimit");
|
|
19
|
+
return true;
|
|
15
20
|
}
|
|
16
21
|
}
|
|
17
|
-
async function
|
|
22
|
+
async function globalPOSTRateLimit() {
|
|
18
23
|
try {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
24
|
+
const clientIP = (await headers()).get("X-Forwarded-For");
|
|
25
|
+
if (clientIP === null) return true;
|
|
26
|
+
return getBucket().consume(clientIP, 3);
|
|
27
|
+
} catch (error) {
|
|
28
|
+
if (error instanceof Error && error.message.includes("worker")) logger.error({ error }, "Worker thread error in globalPOSTRateLimit");
|
|
29
|
+
else logger.error({ error }, "Unexpected error in globalPOSTRateLimit");
|
|
30
|
+
return true;
|
|
23
31
|
}
|
|
24
32
|
}
|
|
25
33
|
//#endregion
|
|
26
|
-
export {
|
|
34
|
+
export { globalGETRateLimit, globalPOSTRateLimit };
|
|
35
|
+
|
|
36
|
+
//# sourceMappingURL=request.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request.js","names":[],"sources":["../src/request.ts"],"sourcesContent":["import { headers } from 'next/headers';\nimport {TokenBucket} from '@eventuras/fides-auth/rate-limit';\nimport { Logger } from '@eventuras/logger';\n\nconst logger = Logger.create({ namespace: 'fides-auth-next:request' });\n\n// Initialize bucket lazily to avoid worker thread issues\nlet globalBucket: TokenBucket<string> | null = null;\n\nfunction getBucket(): TokenBucket<string> {\n if (!globalBucket) {\n globalBucket = new TokenBucket<string>(100, 1);\n }\n return globalBucket;\n}\n\nexport async function globalGETRateLimit(): Promise<boolean> {\n try {\n const headerStore = await headers();\n const clientIP = headerStore.get('X-Forwarded-For');\n if (clientIP === null) {\n return true;\n }\n return getBucket().consume(clientIP, 1);\n } catch (error) {\n // If worker thread crashes, allow the request through\n if (error instanceof Error && error.message.includes('worker')) {\n logger.error({ error }, 'Worker thread error in globalGETRateLimit');\n } else {\n logger.error({ error }, 'Unexpected error in globalGETRateLimit');\n }\n return true;\n }\n}\n\nexport async function globalPOSTRateLimit(): Promise<boolean> {\n try {\n const headerStore = await headers();\n const clientIP = headerStore.get('X-Forwarded-For');\n if (clientIP === null) {\n return true;\n }\n return getBucket().consume(clientIP, 3);\n } catch (error) {\n // If worker thread crashes, allow the request through\n if (error instanceof Error && error.message.includes('worker')) {\n logger.error({ error }, 'Worker thread error in globalPOSTRateLimit');\n } else {\n logger.error({ error }, 'Unexpected error in globalPOSTRateLimit');\n }\n return true;\n }\n}\n"],"mappings":";;;;AAIA,IAAM,SAAS,OAAO,OAAO,EAAE,WAAW,2BAA2B,CAAC;AAGtE,IAAI,eAA2C;AAE/C,SAAS,YAAiC;CACxC,IAAI,CAAC,cACH,eAAe,IAAI,YAAoB,KAAK,EAAE;CAEhD,OAAO;;AAGT,eAAsB,qBAAuC;CAC3D,IAAI;EAEF,MAAM,YAAW,MADS,SAAS,EACN,IAAI,kBAAkB;EACnD,IAAI,aAAa,MACf,OAAO;EAET,OAAO,WAAW,CAAC,QAAQ,UAAU,EAAE;UAChC,OAAO;EAEd,IAAI,iBAAiB,SAAS,MAAM,QAAQ,SAAS,SAAS,EAC5D,OAAO,MAAM,EAAE,OAAO,EAAE,4CAA4C;OAEpE,OAAO,MAAM,EAAE,OAAO,EAAE,yCAAyC;EAEnE,OAAO;;;AAIX,eAAsB,sBAAwC;CAC5D,IAAI;EAEF,MAAM,YAAW,MADS,SAAS,EACN,IAAI,kBAAkB;EACnD,IAAI,aAAa,MACf,OAAO;EAET,OAAO,WAAW,CAAC,QAAQ,UAAU,EAAE;UAChC,OAAO;EAEd,IAAI,iBAAiB,SAAS,MAAM,QAAQ,SAAS,SAAS,EAC5D,OAAO,MAAM,EAAE,OAAO,EAAE,6CAA6C;OAErE,OAAO,MAAM,EAAE,OAAO,EAAE,0CAA0C;EAEpE,OAAO"}
|