(request: NextRequest)
| 101 | const { user, authFailedResponse } = await getUserFromAuth({ adminOnly: false }); |
| 102 | if (authFailedResponse) { |
| 103 | return NextResponse.redirect(new URL('/users/sign_in', APP_URL)); |
| 104 | } |
| 105 | |
| 106 | const searchParams = request.nextUrl.searchParams; |
| 107 | const state = searchParams.get('state'); |
| 108 | const code = searchParams.get('code'); |
| 109 | const error = searchParams.get('error'); |
| 110 | const errorDescription = searchParams.get('error_description'); |
| 111 | |
| 112 | const verifiedState = verifyGoogleOAuthState(state); |
| 113 | if (!verifiedState) { |
| 114 | captureMessage('Google callback invalid or tampered state', { |
| 115 | level: 'warning', |
| 116 | tags: { endpoint: 'google/callback', source: 'google_oauth' }, |
| 117 | extra: oauthSentryContext(searchParams), |
| 118 | }); |
| 119 | return NextResponse.redirect(new URL('/claw/settings?error=invalid_state', APP_URL)); |
| 120 | } |
| 121 | |
| 122 | if (verifiedState.userId !== user.id) { |
| 123 | captureMessage('Google callback user mismatch (possible CSRF)', { |
| 124 | level: 'warning', |
| 125 | tags: { endpoint: 'google/callback', source: 'google_oauth' }, |
| 126 | extra: { |
| 127 | stateUserId: verifiedState.userId, |
| 128 | sessionUserId: user.id, |
| 129 | }, |
| 130 | }); |
| 131 | |
| 132 | return NextResponse.redirect(new URL('/claw/settings?error=unauthorized', APP_URL)); |
| 133 | } |
| 134 | |
| 135 | if (verifiedState.owner.type === 'org') { |
| 136 | await ensureMemberOrganizationAccess(user, verifiedState.owner.id); |
| 137 | } else if (verifiedState.owner.id !== user.id) { |
| 138 | return NextResponse.redirect(new URL('/claw/settings?error=unauthorized', APP_URL)); |
| 139 | } |
| 140 | |
| 141 | const oauthErrorCode = sanitizeOAuthProviderError(error, errorDescription); |
| 142 | if (oauthErrorCode) { |
| 143 | captureMessage('Google OAuth error', { |
| 144 | level: 'warning', |
| 145 | tags: { endpoint: 'google/callback', source: 'google_oauth' }, |
| 146 | extra: oauthSentryContext(searchParams), |
| 147 | }); |
| 148 | |
| 149 | return NextResponse.redirect( |
| 150 | new URL(buildGoogleRedirectPath(verifiedState, `error=${oauthErrorCode}`), APP_URL) |
| 151 | ); |
| 152 | } |
| 153 | |
| 154 | const oauthCode = sanitizeOAuthCode(code); |
| 155 | if (!oauthCode) { |
| 156 | captureMessage('Google callback missing code', { |
| 157 | level: 'warning', |
| 158 | tags: { endpoint: 'google/callback', source: 'google_oauth' }, |
| 159 | extra: oauthSentryContext(searchParams), |
| 160 | }); |
no test coverage detected