@@ -5,6 +5,7 @@ import { jwtVerify, createRemoteJWKSet } from "jose"
55import { createAppAuth } from "@octokit/auth-app"
66import { Octokit } from "@octokit/rest"
77import { Resource } from "sst"
8+ import { parseRepositoryClaim } from "./github"
89
910type Env = {
1011 SYNC_SERVER : DurableObjectNamespace < SyncServer >
@@ -269,42 +270,41 @@ export default new Hono<{ Bindings: Env }>()
269270
270271 // verify token
271272 const JWKS = createRemoteJWKSet ( new URL ( JWKS_URL ) )
272- let owner , repo
273+ let repository : ReturnType < typeof parseRepositoryClaim >
273274 try {
274275 const { payload } = await jwtVerify ( token , JWKS , {
275276 issuer : GITHUB_ISSUER ,
276277 audience : EXPECTED_AUDIENCE ,
277278 } )
278- const sub = payload . sub // e.g. 'repo:my-org/my-repo:ref:refs/heads/main'
279- const parts = sub . split ( ":" ) [ 1 ] . split ( "/" )
280- owner = parts [ 0 ]
281- repo = parts [ 1 ]
279+ repository = parseRepositoryClaim ( payload )
282280 } catch ( err ) {
283281 console . error ( "Token verification failed:" , err )
284282 return c . json ( { error : "Invalid or expired token" } , { status : 403 } )
285283 }
286284
287- // Create app JWT token
288- const auth = createAppAuth ( {
289- appId : Resource . GITHUB_APP_ID . value ,
290- privateKey : Resource . GITHUB_APP_PRIVATE_KEY . value ,
291- } )
292- const appAuth = await auth ( { type : "app" } )
293-
294- // Lookup installation
295- const octokit = new Octokit ( { auth : appAuth . token } )
296- const { data : installation } = await octokit . apps . getRepoInstallation ( {
297- owner,
298- repo,
299- } )
300-
301- // Get installation token
302- const installationAuth = await auth ( {
303- type : "installation" ,
304- installationId : installation . id ,
305- } )
306-
307- return c . json ( { token : installationAuth . token } )
285+ try {
286+ const auth = createAppAuth ( {
287+ appId : Resource . GITHUB_APP_ID . value ,
288+ privateKey : Resource . GITHUB_APP_PRIVATE_KEY . value ,
289+ } )
290+ const appAuth = await auth ( { type : "app" } )
291+ const octokit = new Octokit ( { auth : appAuth . token } )
292+ const { data : installation } = await octokit . apps . getRepoInstallation ( {
293+ owner : repository . owner ,
294+ repo : repository . repo ,
295+ } )
296+ const installationAuth = await auth ( {
297+ type : "installation" ,
298+ installationId : installation . id ,
299+ } )
300+ return c . json ( { token : installationAuth . token } )
301+ } catch ( error ) {
302+ console . error ( "GitHub App token exchange failed:" , error )
303+ return c . json (
304+ { error : `Failed to exchange GitHub App token for ${ repository . owner } /${ repository . repo } ` } ,
305+ { status : 502 } ,
306+ )
307+ }
308308 } )
309309 /**
310310 * Used by the GitHub action to get GitHub installation access token given user PAT token (used when testing `opencode github run` locally)
0 commit comments