@@ -288,6 +288,56 @@ export default { |
288 | 288 | }) |
289 | 289 | } |
290 | 290 |
|
| 291 | + /** |
| 292 | + * Used by the GitHub action to get GitHub installation access token given user PAT token (used when testing `opencode github run` locally) |
| 293 | + */ |
| 294 | + if (request.method === "POST" && method === "exchange_github_app_token_with_pat") { |
| 295 | + const body = await request.json<any>() |
| 296 | + const owner = body.owner |
| 297 | + const repo = body.repo |
| 298 | + |
| 299 | + try { |
| 300 | + // get Authorization header |
| 301 | + const authHeader = request.headers.get("Authorization") |
| 302 | + const token = authHeader?.replace(/^Bearer /, "") |
| 303 | + if (!token) throw new Error("Authorization header is required") |
| 304 | + |
| 305 | + // Verify permissions |
| 306 | + const userClient = new Octokit({ auth: token }) |
| 307 | + const { data: repoData } = await userClient.repos.get({ owner, repo }) |
| 308 | + if (!repoData.permissions.admin && !repoData.permissions.push && !repoData.permissions.maintain) |
| 309 | + throw new Error("User does not have write permissions") |
| 310 | + |
| 311 | + // Get installation token |
| 312 | + const auth = createAppAuth({ |
| 313 | + appId: Resource.GITHUB_APP_ID.value, |
| 314 | + privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value, |
| 315 | + }) |
| 316 | + const appAuth = await auth({ type: "app" }) |
| 317 | + |
| 318 | + // Lookup installation |
| 319 | + const appClient = new Octokit({ auth: appAuth.token }) |
| 320 | + const { data: installation } = await appClient.apps.getRepoInstallation({ owner, repo }) |
| 321 | + |
| 322 | + // Get installation token |
| 323 | + const installationAuth = await auth({ type: "installation", installationId: installation.id }) |
| 324 | + |
| 325 | + return new Response(JSON.stringify({ token: installationAuth.token }), { |
| 326 | + headers: { "Content-Type": "application/json" }, |
| 327 | + }) |
| 328 | + } catch (e: any) { |
| 329 | + let error = e |
| 330 | + if (e instanceof Error) { |
| 331 | + error = e.message |
| 332 | + } |
| 333 | + |
| 334 | + return new Response(JSON.stringify({ error }), { |
| 335 | + status: 401, |
| 336 | + headers: { "Content-Type": "application/json" }, |
| 337 | + }) |
| 338 | + } |
| 339 | + } |
| 340 | + |
291 | 341 | /** |
292 | 342 | * Used by the opencode CLI to check if the GitHub app is installed |
293 | 343 | */ |
|