|
| 1 | +import { blue, green } from 'colorette'; |
| 2 | +import * as childProcess from 'child_process'; |
| 3 | +import { ReuniteApiClient } from '../reunite/api/api-client'; |
| 4 | + |
| 5 | +export type AuthToken = { |
| 6 | + access_token: string; |
| 7 | + refresh_token?: string; |
| 8 | + token_type?: string; |
| 9 | + expires_in?: number; |
| 10 | +}; |
| 11 | + |
| 12 | +export class RedoclyOAuthDeviceFlow { |
| 13 | + private apiClient: ReuniteApiClient; |
| 14 | + |
| 15 | + constructor(private baseUrl: string, private clientName: string, private version: string) { |
| 16 | + this.apiClient = new ReuniteApiClient(this.version, 'login'); |
| 17 | + } |
| 18 | + |
| 19 | + async run() { |
| 20 | + const code = await this.getDeviceCode(); |
| 21 | + process.stdout.write( |
| 22 | + 'Attempting to automatically open the SSO authorization page in your default browser.\n' |
| 23 | + ); |
| 24 | + process.stdout.write( |
| 25 | + 'If the browser does not open or you wish to use a different device to authorize this request, open the following URL:\n\n' |
| 26 | + ); |
| 27 | + process.stdout.write(blue(code.verificationUri)); |
| 28 | + process.stdout.write(`\n\n`); |
| 29 | + process.stdout.write(`Then enter the code:\n\n`); |
| 30 | + process.stdout.write(blue(code.userCode)); |
| 31 | + process.stdout.write(`\n\n`); |
| 32 | + |
| 33 | + this.openBrowser(code.verificationUriComplete); |
| 34 | + |
| 35 | + const accessToken = await this.pollingAccessToken( |
| 36 | + code.deviceCode, |
| 37 | + code.interval, |
| 38 | + code.expiresIn |
| 39 | + ); |
| 40 | + process.stdout.write(green('✅ Logged in\n\n')); |
| 41 | + |
| 42 | + return accessToken; |
| 43 | + } |
| 44 | + |
| 45 | + private openBrowser(url: string) { |
| 46 | + try { |
| 47 | + const cmd = |
| 48 | + process.platform === 'win32' |
| 49 | + ? `start ${url}` |
| 50 | + : process.platform === 'darwin' |
| 51 | + ? `open ${url}` |
| 52 | + : `xdg-open ${url}`; |
| 53 | + |
| 54 | + childProcess.execSync(cmd); |
| 55 | + } catch { |
| 56 | + // silently fail if browser cannot be opened |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + async verifyToken(accessToken: string) { |
| 61 | + try { |
| 62 | + const response = await this.sendRequest('/session', 'GET', undefined, { |
| 63 | + Cookie: `accessToken=${accessToken};`, |
| 64 | + }); |
| 65 | + |
| 66 | + return !!response.user; |
| 67 | + } catch { |
| 68 | + return false; |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + async verifyApiKey(apiKey: string) { |
| 73 | + try { |
| 74 | + const response = await this.sendRequest('/api-keys-verify', 'POST', { |
| 75 | + apiKey, |
| 76 | + }); |
| 77 | + return !!response.success; |
| 78 | + } catch { |
| 79 | + return false; |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + async refreshToken(refreshToken: string) { |
| 84 | + const response = await this.sendRequest(`/device-rotate-token`, 'POST', { |
| 85 | + grant_type: 'refresh_token', |
| 86 | + client_name: this.clientName, |
| 87 | + refresh_token: refreshToken, |
| 88 | + }); |
| 89 | + |
| 90 | + if (!response.access_token) { |
| 91 | + throw new Error('Failed to refresh token'); |
| 92 | + } |
| 93 | + return { |
| 94 | + access_token: response.access_token, |
| 95 | + refresh_token: response.refresh_token, |
| 96 | + expires_in: response.expires_in, |
| 97 | + }; |
| 98 | + } |
| 99 | + |
| 100 | + private async pollingAccessToken( |
| 101 | + deviceCode: string, |
| 102 | + interval: number, |
| 103 | + expiresIn: number |
| 104 | + ): Promise<AuthToken> { |
| 105 | + return new Promise((resolve, reject) => { |
| 106 | + const intervalId = setInterval(async () => { |
| 107 | + const response = await this.getAccessToken(deviceCode); |
| 108 | + if (response.access_token) { |
| 109 | + clearInterval(intervalId); |
| 110 | + clearTimeout(timeoutId); |
| 111 | + resolve(response); |
| 112 | + } |
| 113 | + if (response.error && response.error !== 'authorization_pending') { |
| 114 | + clearInterval(intervalId); |
| 115 | + clearTimeout(timeoutId); |
| 116 | + reject(response.error_description); |
| 117 | + } |
| 118 | + }, interval * 1000); |
| 119 | + |
| 120 | + const timeoutId = setTimeout(async () => { |
| 121 | + clearInterval(intervalId); |
| 122 | + clearTimeout(timeoutId); |
| 123 | + reject('Authorization has expired. Please try again.'); |
| 124 | + }, expiresIn * 1000); |
| 125 | + }); |
| 126 | + } |
| 127 | + |
| 128 | + private async getAccessToken(deviceCode: string) { |
| 129 | + return await this.sendRequest('/device-token', 'POST', { |
| 130 | + client_name: this.clientName, |
| 131 | + device_code: deviceCode, |
| 132 | + grant_type: 'urn:ietf:params:oauth:grant-type:device_code', |
| 133 | + }); |
| 134 | + } |
| 135 | + |
| 136 | + private async getDeviceCode() { |
| 137 | + const { |
| 138 | + device_code: deviceCode, |
| 139 | + user_code: userCode, |
| 140 | + verification_uri: verificationUri, |
| 141 | + verification_uri_complete: verificationUriComplete, |
| 142 | + interval = 10, |
| 143 | + expires_in: expiresIn = 300, |
| 144 | + } = await this.sendRequest('/device-authorize', 'POST', { |
| 145 | + client_name: this.clientName, |
| 146 | + }); |
| 147 | + |
| 148 | + return { |
| 149 | + deviceCode, |
| 150 | + userCode, |
| 151 | + verificationUri, |
| 152 | + verificationUriComplete, |
| 153 | + interval, |
| 154 | + expiresIn, |
| 155 | + }; |
| 156 | + } |
| 157 | + |
| 158 | + private async sendRequest( |
| 159 | + url: string, |
| 160 | + method: string = 'GET', |
| 161 | + body: Record<string, unknown> | undefined = undefined, |
| 162 | + headers: Record<string, string> = {} |
| 163 | + ) { |
| 164 | + url = `${this.baseUrl}${url}`; |
| 165 | + const response = await this.apiClient.request(url, { |
| 166 | + body: body ? JSON.stringify(body) : body, |
| 167 | + method, |
| 168 | + headers: { 'Content-Type': 'application/json', ...headers }, |
| 169 | + }); |
| 170 | + if (response.status === 204) { |
| 171 | + return { success: true }; |
| 172 | + } |
| 173 | + return await response.json(); |
| 174 | + } |
| 175 | +} |
0 commit comments