| 112 | 'Link Failed', |
| 113 | 'This GitHub link request was started by another Kilo user.', |
| 114 | 403 |
| 115 | ); |
| 116 | } |
| 117 | |
| 118 | const stateAppType = state.githubAppType ?? 'standard'; |
| 119 | const usableCandidates = await findGitHubBotLinkIntegrations({ |
| 120 | installationId: state.installationId, |
| 121 | appType: stateAppType, |
| 122 | platformIntegrationId: state.platformIntegrationId, |
| 123 | }); |
| 124 | const legacyAllowed = |
| 125 | !isGitHubConnectionManagementEnabled() && !isGitHubSharedInstallationAdmissionEnabled(); |
| 126 | const integration = state.platformIntegrationId |
| 127 | ? usableCandidates[0] |
| 128 | : legacyAllowed && usableCandidates.length === 1 |
| 129 | ? usableCandidates[0] |
| 130 | : undefined; |
| 131 | |
| 132 | if (!integration) { |
| 133 | return htmlPage('Link Failed', 'No matching GitHub integration was found.', 404); |
| 134 | } |
| 135 | |
| 136 | if (integration.owned_by_organization_id) { |
| 137 | const isMember = await isOrganizationMember(db, integration.owned_by_organization_id, user.id); |
| 138 | if (!isMember) { |
| 139 | return htmlPage( |
| 140 | 'Link Failed', |
| 141 | 'You are not a member of the organization that owns this GitHub integration.', |
| 142 | 403 |
| 143 | ); |
| 144 | } |
| 145 | } else if (integration.owned_by_user_id !== user.id) { |
| 146 | return htmlPage('Link Failed', 'You are not the owner of this GitHub integration.', 403); |
| 147 | } |
| 148 | |
| 149 | const appType = (integration.github_app_type ?? stateAppType) as GitHubAppType; |
| 150 | const githubUser = await exchangeGitHubOAuthCode(code, appType); |
| 151 | |
| 152 | await bot.initialize(); |
| 153 | await linkKiloUser( |
| 154 | bot.getState(), |
| 155 | { |
| 156 | platform: PLATFORM.GITHUB, |
| 157 | teamId: state.installationId, |
| 158 | userId: githubUser.id, |
| 159 | githubAppType: appType, |
| 160 | }, |
| 161 | user.id |
| 162 | ); |
| 163 | |
| 164 | return htmlPage( |
| 165 | 'GitHub account linked', |
| 166 | `GitHub account ${githubUser.login} has been linked to your Kilo account.<br>You can return to GitHub and mention Kilo again.` |
| 167 | ); |
| 168 | } |
| 169 | |
| 170 | /** |
| 171 | * GitHub App Installation Callback |