|
| 1 | +import { errorHandler } from '@backstage/backend-common'; |
| 2 | +import { Config } from '@backstage/config'; |
| 3 | +import express from 'express'; |
| 4 | +import Router from 'express-promise-router'; |
| 5 | +import { Logger } from 'winston'; |
| 6 | +import axios, { type AxiosResponse } from 'axios'; |
| 7 | + |
| 8 | +export interface RouterOptions { |
| 9 | + logger: Logger; |
| 10 | + config: Config; |
| 11 | +} |
| 12 | + |
| 13 | +export async function createRouter( |
| 14 | + options: RouterOptions, |
| 15 | +): Promise<express.Router> { |
| 16 | + const { logger, config } = options; |
| 17 | + |
| 18 | + const router = Router(); |
| 19 | + router.use(express.json()); |
| 20 | + |
| 21 | + // OAuth callback endpoint |
| 22 | + router.get('/oauth/callback', async (req, res) => { |
| 23 | + const { code } = req.query; |
| 24 | + |
| 25 | + if (!code || typeof code !== 'string') { |
| 26 | + logger.error('OAuth callback missing authorization code'); |
| 27 | + res.status(400).send('Missing authorization code'); |
| 28 | + return; |
| 29 | + } |
| 30 | + |
| 31 | + const coderConfig = config.getOptionalConfig('coder'); |
| 32 | + const accessUrl = coderConfig?.getString('deployment.accessUrl') || ''; |
| 33 | + const clientId = coderConfig?.getString('oauth.clientId') || ''; |
| 34 | + const clientSecret = coderConfig?.getString('oauth.clientSecret') || ''; |
| 35 | + const redirectUri = `${req.protocol}://${req.get( |
| 36 | + 'host', |
| 37 | + )}/api/auth/coder/oauth/callback`; |
| 38 | + |
| 39 | + let tokenResponse: AxiosResponse<{ access_token?: string }, unknown>; |
| 40 | + try { |
| 41 | + // Exchange authorization code for access token |
| 42 | + tokenResponse = await axios.post( |
| 43 | + `${accessUrl}/oauth2/tokens`, |
| 44 | + new URLSearchParams({ |
| 45 | + grant_type: 'authorization_code', |
| 46 | + code, |
| 47 | + redirect_uri: redirectUri, |
| 48 | + client_id: clientId, |
| 49 | + client_secret: clientSecret, |
| 50 | + }), |
| 51 | + { |
| 52 | + headers: { |
| 53 | + 'Content-Type': 'application/x-www-form-urlencoded', |
| 54 | + }, |
| 55 | + }, |
| 56 | + ); |
| 57 | + } catch (error) { |
| 58 | + logger.error('OAuth token exchange failed', error); |
| 59 | + res |
| 60 | + .status(500) |
| 61 | + .send( |
| 62 | + `<html><body><h1>Authentication failed</h1><p>${ |
| 63 | + error instanceof Error ? error.message : 'Unknown error' |
| 64 | + }</p></body></html>`, |
| 65 | + ); |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + const { access_token } = tokenResponse.data; |
| 70 | + if (!access_token) { |
| 71 | + const message = 'Coder deployment did not respond with access token'; |
| 72 | + logger.error(message); |
| 73 | + res.status(502).send( |
| 74 | + `<!DOCTYPE html> |
| 75 | + <html> |
| 76 | + <head> |
| 77 | + <title>Authentication Failed</title> |
| 78 | + </head> |
| 79 | + <body> |
| 80 | + <h1>Authentication failed</h1> |
| 81 | + <p>${message}</p> |
| 82 | + </body> |
| 83 | + </html>`, |
| 84 | + ); |
| 85 | + return; |
| 86 | + } |
| 87 | + |
| 88 | + // Return HTML that sends the token to the opener window via postMessage |
| 89 | + res.setHeader('Content-Security-Policy', "script-src 'unsafe-inline'"); |
| 90 | + res.send(` |
| 91 | + <!DOCTYPE html> |
| 92 | + <html> |
| 93 | + <head> |
| 94 | + <title>Authentication Successful</title> |
| 95 | + </head> |
| 96 | + <body> |
| 97 | + <p>Authentication successful! This window will close automatically...</p> |
| 98 | + <script> |
| 99 | + (function() { |
| 100 | + // Send token to opener window via postMessage |
| 101 | + if (window.opener) { |
| 102 | + var targetOrigin; |
| 103 | + try { |
| 104 | + // Try to get the opener's origin |
| 105 | + targetOrigin = window.opener.location.origin; |
| 106 | + } catch (e) { |
| 107 | + // If we can't access it due to cross-origin, use wildcard |
| 108 | + // This is safe since we're only sending to our own opener |
| 109 | + targetOrigin = '*'; |
| 110 | + } |
| 111 | + |
| 112 | + window.opener.postMessage( |
| 113 | + { type: 'coder-oauth-success', token: '${access_token}' }, |
| 114 | + targetOrigin |
| 115 | + ); |
| 116 | + setTimeout(function() { window.close(); }, 500); |
| 117 | + } else { |
| 118 | + document.body.innerHTML = '<p>Authentication successful! You can close this window.</p>'; |
| 119 | + } |
| 120 | + })(); |
| 121 | + </script> |
| 122 | + </body> |
| 123 | + </html> |
| 124 | + `); |
| 125 | + |
| 126 | + logger.info('OAuth authentication successful'); |
| 127 | + }); |
| 128 | + |
| 129 | + router.get('/health', (_, response) => { |
| 130 | + logger.info('Health check'); |
| 131 | + response.json({ status: 'ok' }); |
| 132 | + }); |
| 133 | + |
| 134 | + router.use(errorHandler()); |
| 135 | + return router; |
| 136 | +} |
0 commit comments