-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathauthUtils.ts
More file actions
353 lines (310 loc) · 9.3 KB
/
Copy pathauthUtils.ts
File metadata and controls
353 lines (310 loc) · 9.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/**
* Centralized Authentication Utilities
*/
import type { AuthUser, SessionResponse } from '../types/auth-types';
import type { User } from '../database/schema';
import { createLogger } from '../logger';
import { SecurityError, SecurityErrorType } from 'shared/types/errors';
const logger = createLogger('AuthUtils');
/**
* Enforce the deployment-level email allowlist (ALLOWED_EMAIL).
*
* Centralized admission gate: every authentication path that admits a user
* (register, login, OAuth callback, email verification, and any future path)
* must call this before creating a user or issuing a session. Comparison is
* case-insensitive on both sides.
*/
export function enforceAllowedEmail(
env: Env,
email: string,
action: 'register' | 'login' | 'oauth',
): void {
const allowedEmail = env.ALLOWED_EMAIL ?? '';
if (!allowedEmail) return;
if (email.toLowerCase() !== allowedEmail.toLowerCase()) {
throw new SecurityError(
SecurityErrorType.UNAUTHORIZED,
`Email Whitelisting is enabled. Please use the allowed email to ${action}.`,
403,
);
}
}
/**
* Extract sessionId from cookie
*/
export function extractSessionId(request: Request): string | null {
const cookieHeader = request.headers.get('Cookie');
if (!cookieHeader) {
return null;
}
const cookies = parseCookies(cookieHeader);
return cookies['sessionId'];
}
/**
* Token extraction priorities and methods
*/
export enum TokenExtractionMethod {
AUTHORIZATION_HEADER = 'authorization_header',
COOKIE = 'cookie',
QUERY_PARAMETER = 'query_parameter',
}
/**
* Result of token extraction with metadata
*/
export interface TokenExtractionResult {
token: string | null;
method?: TokenExtractionMethod;
cookieName?: string;
}
/**
* Extract JWT token from request with multiple fallback methods
* Prioritizes Authorization header, then cookies, then query parameters
*/
export function extractToken(request: Request): string | null {
const result = extractTokenWithMetadata(request);
return result.token;
}
/**
* Extract JWT token from request with extraction method metadata
* Useful for security logging and analysis
*/
export function extractTokenWithMetadata(
request: Request,
): TokenExtractionResult {
// Priority 1: Authorization header (most secure)
const authHeader = request.headers.get('Authorization');
if (authHeader?.startsWith('Bearer ')) {
const token = authHeader.substring(7);
if (token && token.length > 0) {
return {
token,
method: TokenExtractionMethod.AUTHORIZATION_HEADER,
};
}
}
// Priority 2: Cookies (secure for browser requests)
const cookieHeader = request.headers.get('Cookie');
if (cookieHeader) {
const cookies = parseCookies(cookieHeader);
// Check common cookie names in order of preference
const cookieNames = ['accessToken', 'auth_token', 'jwt'];
for (const cookieName of cookieNames) {
if (cookies[cookieName]) {
return {
token: cookies[cookieName],
method: TokenExtractionMethod.COOKIE,
cookieName,
};
}
}
}
// NOTE: JWTs are intentionally NOT accepted from the URL query string.
// URL components leak into access logs, browser history, Referer headers and
// error-reporting breadcrumbs, where a captured token would remain valid until
// its natural expiry. WebSocket handshakes use the one-time ticket flow instead
// (see worker/middleware/auth/ticketAuth.ts).
return { token: null };
}
/**
* Parse cookie header into key-value pairs
*/
export function parseCookies(cookieHeader: string): Record<string, string> {
const cookies: Record<string, string> = {};
const pairs = cookieHeader.split(';');
for (const pair of pairs) {
const [key, value] = pair.trim().split('=');
if (key && value) {
cookies[key] = decodeURIComponent(value);
}
}
return cookies;
}
/**
* Clear authentication cookie using secure cookie options
*/
export function clearAuthCookie(name: string): string {
return createSecureCookie({
name,
value: '',
maxAge: 0,
});
}
/**
* Clear all auth cookies from response using consolidated approach
*/
export function clearAuthCookies(response: Response): void {
response.headers.append('Set-Cookie', clearAuthCookie('accessToken'));
response.headers.append('Set-Cookie', clearAuthCookie('auth_token'));
}
/**
* Enhanced cookie creation with security options
*/
export interface CookieOptions {
name: string;
value: string;
maxAge?: number; // seconds
httpOnly?: boolean;
secure?: boolean;
sameSite?: 'Strict' | 'Lax' | 'None';
path?: string;
domain?: string;
}
/**
* Create secure cookie string with all options
*/
export function createSecureCookie(options: CookieOptions): string {
const {
name,
value,
maxAge = 7 * 24 * 60 * 60, // 7 days default
secure = true,
sameSite = 'Lax',
path = '/',
domain,
} = options;
const parts = [`${name}=${encodeURIComponent(value)}`];
if (maxAge > 0) parts.push(`Max-Age=${maxAge}`);
if (path) parts.push(`Path=${path}`);
if (domain) parts.push(`Domain=${domain}`);
if (secure) parts.push('Secure');
if (sameSite) parts.push(`SameSite=${sameSite}`);
parts.push('HttpOnly');
return parts.join('; ');
}
/**
* Set auth cookies with proper security settings
*/
export function setSecureAuthCookies(
response: Response,
tokens: {
accessToken: string;
accessTokenExpiry?: number; // seconds
},
): void {
const {
accessToken,
accessTokenExpiry = 3 * 24 * 60 * 60, // 3 days
} = tokens;
// Set access token cookie
response.headers.append(
'Set-Cookie',
createSecureCookie({
name: 'accessToken',
value: accessToken,
maxAge: accessTokenExpiry,
sameSite: 'Lax',
}),
);
}
/**
* Extract request metadata for security analysis
*/
export interface RequestMetadata {
ipAddress: string;
userAgent: string;
referer?: string;
origin?: string;
acceptLanguage?: string;
// Cloudflare-specific headers
cfConnectingIp?: string;
cfRay?: string;
cfCountry?: string;
cfTimezone?: string;
}
/**
* Extract comprehensive request metadata
*/
export function extractRequestMetadata(request: Request): RequestMetadata {
const headers = request.headers;
return {
ipAddress:
headers.get('CF-Connecting-IP') ||
headers.get('X-Forwarded-For')?.split(',')[0]?.trim() ||
headers.get('X-Real-IP') ||
'unknown',
userAgent: headers.get('User-Agent') || 'unknown',
referer: headers.get('Referer') || undefined,
origin: headers.get('Origin') || undefined,
acceptLanguage: headers.get('Accept-Language') || undefined,
// Cloudflare-specific
cfConnectingIp: headers.get('CF-Connecting-IP') || undefined,
cfRay: headers.get('CF-Ray') || undefined,
cfCountry: headers.get('CF-IPCountry') || undefined,
cfTimezone: headers.get('CF-Timezone') || undefined,
};
}
export type { SessionResponse } from '../types/auth-types';
export function mapUserResponse(
user: (Partial<User> & { id: string; email: string }) | AuthUser,
): AuthUser {
// Handle AuthUser type - already in correct format
if ('isAnonymous' in user) {
return user as AuthUser;
}
// Map from User schema type
return {
id: user.id,
email: user.email,
displayName: user.displayName || undefined,
username: user.username || undefined,
avatarUrl: user.avatarUrl || undefined,
bio: user.bio || undefined,
timezone: user.timezone || undefined,
provider: user.provider || undefined,
emailVerified: user.emailVerified || undefined,
createdAt: user.createdAt || undefined,
};
}
export function formatAuthResponse(
user: AuthUser,
sessionId: string,
expiresAt: Date | null,
): SessionResponse {
const response: SessionResponse = { user, sessionId, expiresAt };
return response;
}
/**
* Validate and sanitize redirect URL to prevent open redirect attacks
* Returns null if the URL is invalid or potentially malicious
*/
export function validateRedirectUrl(redirectUrl: string, request: Request): string | null {
try {
const requestUrl = new URL(request.url);
const redirectUrlObj = redirectUrl.startsWith('/')
? new URL(redirectUrl, requestUrl.origin)
: new URL(redirectUrl);
if (redirectUrlObj.origin !== requestUrl.origin) {
logger.warn('Redirect URL rejected: different origin', {
redirectUrl,
requestOrigin: requestUrl.origin,
redirectOrigin: redirectUrlObj.origin
});
return null;
}
// Block paths that themselves initiate privileged/auth-mutating flows. Notably
// `/oauth/` and `/auth/` (Cloudflare account linking) — without these, a post-login
// open-forward can chain straight into account linking.
const forbiddenPaths = ['/api/auth/', '/logout', '/api/github-exporter/', '/oauth/', '/auth/'];
if (forbiddenPaths.some(path => redirectUrlObj.pathname.startsWith(path))) {
logger.warn('Redirect URL rejected: forbidden path', {
redirectUrl,
pathname: redirectUrlObj.pathname
});
return null;
}
// Reject nested redirect parameters that could re-trigger another flow after this
// redirect resolves (e.g. /oauth/login?return_url=/settings smuggled via a path).
const nestedRedirectParams = ['return_url', 'redirect_url', 'continue'];
if (nestedRedirectParams.some(param => redirectUrlObj.searchParams.has(param))) {
logger.warn('Redirect URL rejected: nested redirect parameter', {
redirectUrl,
pathname: redirectUrlObj.pathname
});
return null;
}
return redirectUrl;
} catch (error) {
logger.warn('Invalid redirect URL format', { redirectUrl, error });
return null;
}
}