| 24 | } |
| 25 | |
| 26 | export async function login(options: LoginOptions): Promise<void> { |
| 27 | const server = http.createServer() |
| 28 | server.listen({ host: 'localhost', port: 0 }) |
| 29 | |
| 30 | const addressInfo = await events.once(server, 'listening').then(() => server.address() as AddressInfo) |
| 31 | const state = new LoginState('localhost', addressInfo.port, options.utmMedium) |
| 32 | |
| 33 | const authResult = new Promise<void>((resolve, reject) => { |
| 34 | server.on('request', async (req, res) => { |
| 35 | try { |
| 36 | const url = new URL(`http://${state.host}${req.url}`) |
| 37 | await state.handleCallback(url) |
| 38 | } catch (error) { |
| 39 | res.statusCode = 400 |
| 40 | const message = error instanceof Error ? error.message : String(error) |
| 41 | res.end(message) |
| 42 | reject(error) |
| 43 | return |
| 44 | } |
| 45 | |
| 46 | res.setHeader('Content-Type', 'text/html') |
| 47 | res.end(` |
| 48 | <html> |
| 49 | <head> |
| 50 | <title>Login</title> |
| 51 | </head> |
| 52 | <body> |
| 53 | <p>Success!</p> |
| 54 | <p>You may now close this page.</p> |
| 55 | </body> |
| 56 | </html> |
| 57 | `) |
| 58 | |
| 59 | setImmediate(() => { |
| 60 | server.close() |
| 61 | }) |
| 62 | |
| 63 | resolve() |
| 64 | }) |
| 65 | }) |
| 66 | |
| 67 | await state.login() |
| 68 | await authResult |
| 69 | } |
| 70 | |
| 71 | export class LoginState { |
| 72 | private latestVerifier?: string |