|
| 1 | +import type { Server } from 'node:http'; |
| 2 | +import type { AddressInfo } from 'node:net'; |
| 3 | + |
| 4 | +import chalk from 'chalk'; |
| 5 | +import computerName from 'computer-name'; |
| 6 | +import cors from 'cors'; |
| 7 | +import express from 'express'; |
| 8 | +import open from 'open'; |
| 9 | + |
| 10 | +import { cryptoRandomObjectId } from '@apify/utilities'; |
| 11 | + |
| 12 | +import { ApifyCommand } from '../../lib/command-framework/apify-command.js'; |
| 13 | +import { Flags } from '../../lib/command-framework/flags.js'; |
| 14 | +import { AUTH_FILE_PATH } from '../../lib/consts.js'; |
| 15 | +import { updateUserId } from '../../lib/hooks/telemetry/useTelemetryState.js'; |
| 16 | +import { useMaskedInput } from '../../lib/hooks/user-confirmations/useMaskedInput.js'; |
| 17 | +import { useSelectFromList } from '../../lib/hooks/user-confirmations/useSelectFromList.js'; |
| 18 | +import { error, info, success } from '../../lib/outputs.js'; |
| 19 | +import { getLocalUserInfo, getLoggedClient, tildify } from '../../lib/utils.js'; |
| 20 | + |
| 21 | +const CONSOLE_BASE_URL = 'https://console.apify.com/settings/integrations'; |
| 22 | +// const CONSOLE_BASE_URL = 'http://localhost:3000/settings/integrations'; |
| 23 | +const CONSOLE_URL_ORIGIN = new URL(CONSOLE_BASE_URL).origin; |
| 24 | + |
| 25 | +const API_BASE_URL = CONSOLE_BASE_URL.includes('localhost') ? 'http://localhost:3333' : undefined; |
| 26 | + |
| 27 | +// Not really checked right now, but it might come useful if we ever need to do some breaking changes |
| 28 | +const API_VERSION = 'v1'; |
| 29 | + |
| 30 | +const tryToLogin = async (token: string) => { |
| 31 | + const isUserLogged = await getLoggedClient(token, API_BASE_URL); |
| 32 | + const userInfo = await getLocalUserInfo(); |
| 33 | + |
| 34 | + if (isUserLogged) { |
| 35 | + await updateUserId(userInfo.id!); |
| 36 | + |
| 37 | + success({ |
| 38 | + message: `You are logged in to Apify as ${userInfo.username || userInfo.id}. ${chalk.gray(`Your token is stored at ${AUTH_FILE_PATH()}.`)}`, |
| 39 | + }); |
| 40 | + } else { |
| 41 | + error({ |
| 42 | + message: 'Login to Apify failed, the provided API token is not valid.', |
| 43 | + }); |
| 44 | + } |
| 45 | + return isUserLogged; |
| 46 | +}; |
| 47 | + |
| 48 | +export class AuthLoginCommand extends ApifyCommand<typeof AuthLoginCommand> { |
| 49 | + static override name = 'login' as const; |
| 50 | + |
| 51 | + static override description = |
| 52 | + `Authenticates your Apify account and saves credentials to '${tildify(AUTH_FILE_PATH())}'.\n` + |
| 53 | + `All other commands use these stored credentials.\n\n` + |
| 54 | + `Run 'apify logout' to remove authentication.`; |
| 55 | + |
| 56 | + static override flags = { |
| 57 | + token: Flags.string({ |
| 58 | + char: 't', |
| 59 | + description: 'Apify API token', |
| 60 | + required: false, |
| 61 | + }), |
| 62 | + method: Flags.string({ |
| 63 | + char: 'm', |
| 64 | + description: 'Method of logging in to Apify', |
| 65 | + choices: ['console', 'manual'], |
| 66 | + required: false, |
| 67 | + }), |
| 68 | + }; |
| 69 | + |
| 70 | + async run() { |
| 71 | + const { token, method } = this.flags; |
| 72 | + |
| 73 | + if (token) { |
| 74 | + await tryToLogin(token); |
| 75 | + return; |
| 76 | + } |
| 77 | + |
| 78 | + let selectedMethod = method; |
| 79 | + |
| 80 | + if (!method) { |
| 81 | + const answer = await useSelectFromList({ |
| 82 | + message: 'Choose how you want to log in to Apify', |
| 83 | + choices: [ |
| 84 | + { |
| 85 | + value: 'console', |
| 86 | + name: 'Through Apify Console in your default browser', |
| 87 | + short: 'Through Apify Console', |
| 88 | + }, |
| 89 | + { |
| 90 | + value: 'manual', |
| 91 | + name: 'Enter API token manually', |
| 92 | + short: 'Manually', |
| 93 | + }, |
| 94 | + ] as const, |
| 95 | + loop: true, |
| 96 | + }); |
| 97 | + |
| 98 | + selectedMethod = answer; |
| 99 | + } |
| 100 | + |
| 101 | + if (selectedMethod === 'console') { |
| 102 | + let server: Server; |
| 103 | + const app = express(); |
| 104 | + |
| 105 | + // To send requests from browser to localhost, CORS has to be configured properly |
| 106 | + app.use( |
| 107 | + cors({ |
| 108 | + origin: CONSOLE_URL_ORIGIN, |
| 109 | + allowedHeaders: ['Content-Type', 'Authorization'], |
| 110 | + }), |
| 111 | + ); |
| 112 | + |
| 113 | + // Turn off keepalive, otherwise closing the server when command is finished is lagging |
| 114 | + app.use((_, res, next) => { |
| 115 | + res.set('Connection', 'close'); |
| 116 | + next(); |
| 117 | + }); |
| 118 | + |
| 119 | + app.use(express.json()); |
| 120 | + |
| 121 | + // Basic authorization via a random token, which is passed to the Apify Console, |
| 122 | + // and that sends it back via the `token` query param, or `Authorization` header |
| 123 | + const authToken = cryptoRandomObjectId(); |
| 124 | + app.use((req, res, next) => { |
| 125 | + let { token: serverToken } = req.query; |
| 126 | + if (!serverToken) { |
| 127 | + const authorizationHeader = req.get('Authorization'); |
| 128 | + if (authorizationHeader) { |
| 129 | + const [schema, tokenFromHeader, ...extra] = authorizationHeader.trim().split(/\s+/); |
| 130 | + if (schema.toLowerCase() === 'bearer' && tokenFromHeader && extra.length === 0) { |
| 131 | + serverToken = tokenFromHeader; |
| 132 | + } |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + if (serverToken !== authToken) { |
| 137 | + res.status(401); |
| 138 | + res.send('Authorization failed'); |
| 139 | + } else { |
| 140 | + next(); |
| 141 | + } |
| 142 | + }); |
| 143 | + |
| 144 | + const apiRouter = express.Router(); |
| 145 | + app.use(`/api/${API_VERSION}`, apiRouter); |
| 146 | + |
| 147 | + apiRouter.post('/login-token', async (req, res) => { |
| 148 | + try { |
| 149 | + if (req.body.apiToken) { |
| 150 | + await tryToLogin(req.body.apiToken); |
| 151 | + } else { |
| 152 | + throw new Error('Request did not contain API token'); |
| 153 | + } |
| 154 | + res.end(); |
| 155 | + } catch (err) { |
| 156 | + const errorMessage = `Login to Apify failed with error: ${(err as Error).message}`; |
| 157 | + error({ message: errorMessage }); |
| 158 | + res.status(500); |
| 159 | + res.send(errorMessage); |
| 160 | + } |
| 161 | + server.close(); |
| 162 | + }); |
| 163 | + |
| 164 | + apiRouter.post('/exit', (req, res) => { |
| 165 | + if (req.body.isWindowClosed) { |
| 166 | + error({ |
| 167 | + message: 'Login to Apify failed, the console window was closed.', |
| 168 | + }); |
| 169 | + } else if (req.body.actionCanceled) { |
| 170 | + error({ |
| 171 | + message: 'Login to Apify failed, the action was canceled in the Apify Console.', |
| 172 | + }); |
| 173 | + } else { |
| 174 | + error({ message: 'Login to Apify failed.' }); |
| 175 | + } |
| 176 | + |
| 177 | + res.end(); |
| 178 | + server.close(); |
| 179 | + }); |
| 180 | + |
| 181 | + // Listening on port 0 will assign a random available port |
| 182 | + server = app.listen(0); |
| 183 | + const { port } = server.address() as AddressInfo; |
| 184 | + |
| 185 | + const consoleUrl = new URL(CONSOLE_BASE_URL); |
| 186 | + consoleUrl.searchParams.set('localCliCommand', 'login'); |
| 187 | + consoleUrl.searchParams.set('localCliPort', `${port}`); |
| 188 | + consoleUrl.searchParams.set('localCliToken', authToken); |
| 189 | + consoleUrl.searchParams.set('localCliApiVersion', API_VERSION); |
| 190 | + try { |
| 191 | + consoleUrl.searchParams.set('localCliComputerName', encodeURIComponent(computerName())); |
| 192 | + } catch { |
| 193 | + // Ignore errors from fetching computer name as it's not critical |
| 194 | + } |
| 195 | + |
| 196 | + info({ message: `Opening Apify Console at "${consoleUrl.href}"...` }); |
| 197 | + await open(consoleUrl.href); |
| 198 | + } else { |
| 199 | + console.log( |
| 200 | + 'Enter your Apify API token. You can find it at https://console.apify.com/settings/integrations', |
| 201 | + ); |
| 202 | + |
| 203 | + const tokenAnswer = await useMaskedInput({ message: 'token:' }); |
| 204 | + await tryToLogin(tokenAnswer); |
| 205 | + } |
| 206 | + } |
| 207 | +} |
0 commit comments