(request: NextRequest)
| 32 | ); |
| 33 | } |
| 34 | |
| 35 | export async function GET(request: NextRequest) { |
| 36 | const token = request.nextUrl.searchParams.get('token'); |
| 37 | const verifiedToken = verifyGitHubLinkToken(token); |
| 38 | |
| 39 | if (!verifiedToken) { |
| 40 | return errorPage( |
| 41 | 'Link Expired', |
| 42 | 'Invalid or expired GitHub link. Please return to GitHub and mention Kilo again to get a fresh link.', |
| 43 | 400 |
| 44 | ); |
| 45 | } |
| 46 | |
| 47 | const { user, authFailedResponse } = await getUserFromAuth({ adminOnly: false }); |
| 48 | |
| 49 | if (authFailedResponse) { |
| 50 | const signInUrl = new URL('/users/sign_in', APP_URL); |
| 51 | signInUrl.searchParams.set('callbackPath', `/github/link?token=${token}`); |
| 52 | return NextResponse.redirect(signInUrl); |
| 53 | } |
| 54 | |
| 55 | const integration = await getPlatformIntegrationById(verifiedToken.platformIntegrationId).catch( |
| 56 | () => null |
| 57 | ); |
| 58 | |
| 59 | if (!integration) { |
| 60 | return errorPage('Link Failed', 'No matching GitHub integration was found.', 404); |
| 61 | } |
| 62 | |
| 63 | if (integration.owned_by_organization_id) { |
| 64 | const isMember = await isOrganizationMember(db, integration.owned_by_organization_id, user.id); |
| 65 | if (!isMember) { |
| 66 | return errorPage( |
| 67 | 'Access Denied', |
| 68 | 'You are not a member of the organization that owns this GitHub integration.', |
| 69 | 403 |
| 70 | ); |
| 71 | } |
| 72 | } else if (integration.owned_by_user_id && integration.owned_by_user_id !== user.id) { |
| 73 | return errorPage('Access Denied', 'You are not the owner of this GitHub integration.', 403); |
| 74 | } |
| 75 | |
| 76 | const appType = integration.github_app_type ?? 'standard'; |
| 77 | const credentials = getGitHubAppCredentials(appType); |
| 78 | const authorizeUrl = new URL(GITHUB_AUTHORIZE_URL); |
| 79 | authorizeUrl.searchParams.set('client_id', credentials.clientId); |
| 80 | authorizeUrl.searchParams.set( |
| 81 | 'redirect_uri', |
| 82 | new URL(GITHUB_CALLBACK_PATH, GITHUB_CALLBACK_BASE_URL).toString() |
| 83 | ); |
| 84 | authorizeUrl.searchParams.set( |
| 85 | 'state', |
| 86 | createGitHubBotLinkState( |
| 87 | user.id, |
| 88 | verifiedToken.installationId, |
| 89 | '/github/link', |
| 90 | appType, |
| 91 | integration.id |
no test coverage detected