-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathroute.ts
More file actions
248 lines (220 loc) 路 7.03 KB
/
Copy pathroute.ts
File metadata and controls
248 lines (220 loc) 路 7.03 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
import { createHash } from 'node:crypto';
import { captureException, captureMessage } from '@sentry/nextjs';
import { NextResponse } from 'next/server';
import { recordSignupSideEffects } from '@/lib/auth/signup-side-effects';
import {
createAuthRedirectResponse,
getLocaleFromRedirectPath,
getSafeAuthRedirectPath,
} from '@/lib/supabase/auth-redirect';
import { AUTH_CALLBACK_COOKIE_NAME } from '@/lib/supabase/constants';
import { createClient } from '@/lib/supabase/server';
import { routing } from '@/src/i18n/routing';
const getOauthCodeFingerprint = (code: string | null) => {
if (!code) {
return {
hasCode: false,
codeLength: 0,
codeFingerprint: null,
};
}
return {
hasCode: true,
codeLength: code.length,
codeFingerprint: createHash('sha256')
.update(code)
.digest('hex')
.slice(0, 12),
};
};
const getErrorStringProperty = (
error: unknown,
property: 'code' | 'message' | 'name',
) => {
if (error instanceof Error && property !== 'code') {
return error[property];
}
if (typeof error !== 'object' || error === null || !(property in error)) {
return '';
}
return String((error as Record<string, unknown>)[property] ?? '');
};
const getErrorMessage = (error: unknown) => {
if (error instanceof Error) {
return error.message;
}
return String(error);
};
const isPkceCodeVerifierMissingError = (error: unknown) => {
const errorName = getErrorStringProperty(error, 'name');
const errorMessage = getErrorStringProperty(error, 'message');
return (
errorName === 'AuthPKCECodeVerifierMissingError' ||
// Defensive fallback for serialized Supabase errors that preserve only message text.
errorMessage.includes('PKCE code verifier not found')
);
};
const isExpiredAuthFlowStateError = (error: unknown) => {
const errorName = getErrorStringProperty(error, 'name');
const errorCode = getErrorStringProperty(error, 'code');
const errorMessage = getErrorStringProperty(error, 'message').toLowerCase();
return (
(errorName === 'AuthApiError' &&
(errorCode === 'flow_state_expired' ||
errorCode === 'flow_state_not_found')) ||
errorMessage.includes('invalid flow state') ||
errorMessage.includes('flow state has expired')
);
};
const getOauthCallbackCookieContext = (request: Request) => {
const cookieHeader = request.headers.get('cookie') ?? '';
const cookieNames = cookieHeader
.split(';')
.map((cookie) => cookie.split('=')[0]?.trim())
.filter((name): name is string => Boolean(name));
const supabaseCookieNames = cookieNames.filter((name) => {
const lowerName = name.toLowerCase();
return lowerName.startsWith('sb-') || lowerName.includes('supabase');
});
return {
hasCookieHeader: Boolean(cookieHeader),
cookieCount: cookieNames.length,
supabaseCookieCount: supabaseCookieNames.length,
hasSupabaseAuthCookie: supabaseCookieNames.some((name) =>
name.includes('auth-token'),
),
hasSupabaseCodeVerifierCookie: supabaseCookieNames.some((name) =>
name.includes('code-verifier'),
),
hasAuthCallbackMarkerCookie: cookieNames.includes(
AUTH_CALLBACK_COOKIE_NAME,
),
};
};
export async function GET(request: Request) {
// The `/auth/callback` route is required for the server-side auth flow implemented
// by the SSR package. It exchanges an auth code for the user's session.
// https://supabase.com/docs/guides/auth/server-side/nextjs
const requestUrl = new URL(request.url);
const code = requestUrl.searchParams.get('code');
const origin = requestUrl.origin;
const redirectTo = requestUrl.searchParams.get('redirect_to');
const safeRedirectPath = getSafeAuthRedirectPath(redirectTo, origin);
const locale = getLocaleFromRedirectPath(safeRedirectPath);
const loginPath = `/${locale}/login`;
const oauthCodeContext = getOauthCodeFingerprint(code);
const oauthCookieContext = getOauthCallbackCookieContext(request);
const reportKnownOauthCallbackFailure = (
message: string,
errorType: string,
error: unknown,
) => {
captureMessage(message, {
level: 'warning',
tags: {
area: 'auth',
flow: 'oauth-callback',
error_type: errorType,
},
extra: {
redirectTo,
locale,
...oauthCodeContext,
...oauthCookieContext,
errorCode: getErrorStringProperty(error, 'code') || null,
errorMessage: getErrorMessage(error),
errorName: getErrorStringProperty(error, 'name') || null,
},
});
return NextResponse.redirect(`${origin}${loginPath}`);
};
const reportPkceCodeVerifierMissing = (error: unknown) =>
reportKnownOauthCallbackFailure(
'OAuth callback missing PKCE code verifier.',
'pkce-code-verifier-missing',
error,
);
const reportExpiredAuthFlowState = (error: unknown) =>
reportKnownOauthCallbackFailure(
'OAuth callback flow state expired.',
'flow-state-expired',
error,
);
try {
if (!code) {
return NextResponse.redirect(`${origin}${loginPath}`);
}
const supabase = await createClient();
const {
data: { user },
error: exchangeError,
} = await supabase.auth.exchangeCodeForSession(code);
if (exchangeError) {
if (isPkceCodeVerifierMissingError(exchangeError)) {
return reportPkceCodeVerifierMissing(exchangeError);
}
if (isExpiredAuthFlowStateError(exchangeError)) {
return reportExpiredAuthFlowState(exchangeError);
}
captureException(exchangeError, {
tags: {
area: 'auth',
flow: 'oauth-callback',
},
extra: {
redirectTo,
locale,
...oauthCodeContext,
...oauthCookieContext,
},
});
return NextResponse.redirect(`${origin}${loginPath}`);
}
if (!user?.email) {
captureMessage('OAuth callback completed without a user email.', {
level: 'error',
tags: {
area: 'auth',
flow: 'oauth-callback',
},
extra: {
redirectTo,
locale,
userId: user?.id ?? null,
},
});
return NextResponse.redirect(`${origin}${loginPath}`);
}
await recordSignupSideEffects(
user,
user.app_metadata.provider === 'email' ? 'email' : 'social',
);
if (safeRedirectPath) {
return createAuthRedirectResponse(`${origin}${safeRedirectPath}`);
}
// URL to redirect to after sign up process completes
return createAuthRedirectResponse(
`${origin}/${routing.defaultLocale}/dashboard`,
);
} catch (error) {
if (isPkceCodeVerifierMissingError(error)) {
return reportPkceCodeVerifierMissing(error);
}
if (isExpiredAuthFlowStateError(error)) {
return reportExpiredAuthFlowState(error);
}
captureException(error, {
tags: {
area: 'auth',
flow: 'oauth-callback',
},
extra: {
redirectTo,
locale,
...oauthCodeContext,
...oauthCookieContext,
},
});
return NextResponse.redirect(`${origin}${loginPath}`);
}
}