This repository was archived by the owner on Feb 4, 2025. It is now read-only.
forked from netlify/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.js
More file actions
353 lines (311 loc) · 10.2 KB
/
Copy pathcommand.js
File metadata and controls
353 lines (311 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
const process = require('process')
const { URL } = require('url')
const { format, inspect } = require('util')
const resolveConfig = require('@netlify/config')
const { flags: flagsLib } = require('@oclif/command')
const oclifParser = require('@oclif/parser')
const merge = require('lodash/merge')
const argv = require('minimist')(process.argv.slice(2))
const API = require('netlify')
const { getAgent } = require('../lib/http-agent')
const { startSpinner, clearSpinner } = require('../lib/spinner')
const chalkInstance = require('./chalk')
const getGlobalConfig = require('./get-global-config')
const openBrowser = require('./open-browser')
const StateConfig = require('./state-config')
const { track, identify } = require('./telemetry')
const { TrackedCommand } = require('./telemetry/tracked-command')
const { NETLIFY_AUTH_TOKEN, NETLIFY_API_URL } = process.env
// Netlify CLI client id. Lives in bot@netlify.com
// Todo setup client for multiple environments
const CLIENT_ID = 'd6f37de6614df7ae58664cfca524744d73807a377f5ee71f1a254f78412e3750'
// 'api' command uses JSON output by default
// 'functions:invoke' need to return the data from the function as is
const isDefaultJson = () => argv._[0] === 'functions:invoke' || (argv._[0] === 'api' && argv.list !== true)
const getToken = async (tokenFromFlag) => {
// 1. First honor command flag --auth
if (tokenFromFlag) {
return [tokenFromFlag, 'flag']
}
// 2. then Check ENV var
if (NETLIFY_AUTH_TOKEN && NETLIFY_AUTH_TOKEN !== 'null') {
return [NETLIFY_AUTH_TOKEN, 'env']
}
// 3. If no env var use global user setting
const globalConfig = await getGlobalConfig()
const userId = globalConfig.get('userId')
const tokenFromConfig = globalConfig.get(`users.${userId}.auth.token`)
if (tokenFromConfig) {
return [tokenFromConfig, 'config']
}
return [null, 'not found']
}
// 5 Minutes
const TOKEN_TIMEOUT = 3e5
const pollForToken = async ({ api, ticket, exitWithError, chalk }) => {
const spinner = startSpinner({ text: 'Waiting for authorization...' })
try {
const accessToken = await api.getAccessToken(ticket, { timeout: TOKEN_TIMEOUT })
if (!accessToken) {
exitWithError('Could not retrieve access token')
}
return accessToken
} catch (error) {
if (error.name === 'TimeoutError') {
exitWithError(
`Timed out waiting for authorization. If you do not have a ${chalk.bold.greenBright(
'Netlify',
)} account, please create one at ${chalk.magenta(
'https://app.netlify.com/signup',
)}, then run ${chalk.cyanBright('netlify login')} again.`,
)
} else {
exitWithError(error)
}
} finally {
clearSpinner({ spinner })
}
}
class BaseCommand extends TrackedCommand {
// Initialize context
async init() {
await super.init()
const cwd = argv.cwd || process.cwd()
// Grab netlify API token
const authViaFlag = getAuthArg(argv)
const [token] = await this.getConfigToken(authViaFlag)
// Get site id & build state
const state = new StateConfig(cwd)
const apiUrlOpts = {}
if (NETLIFY_API_URL) {
const apiUrl = new URL(NETLIFY_API_URL)
apiUrlOpts.scheme = apiUrl.protocol.slice(0, -1)
apiUrlOpts.host = apiUrl.host
apiUrlOpts.pathPrefix = NETLIFY_API_URL === `${apiUrl.protocol}//${apiUrl.host}` ? '/api/v1' : apiUrl.pathname
}
const cachedConfig = await this.getConfig({ cwd, state, token, ...apiUrlOpts })
const { configPath, config, buildDir, repositoryRoot, siteInfo } = cachedConfig
const { flags } = this.parse(BaseCommand)
const agent = await getAgent({
log: this.log,
exit: this.exit,
httpProxy: flags.httpProxy,
certificateFile: flags.httpProxyCertificateFilename,
})
const apiOpts = { ...apiUrlOpts, agent }
const globalConfig = await getGlobalConfig()
this.netlify = {
// api methods
api: new API(token || '', apiOpts),
repositoryRoot,
// current site context
site: {
root: buildDir,
configPath,
get id() {
return state.get('siteId')
},
set id(id) {
state.set('siteId', id)
},
},
// Site information retrieved using the API
siteInfo,
// Configuration from netlify.[toml/yml]
config,
// Used to avoid calling @netlify/config again
cachedConfig,
// global cli config
globalConfig,
// state of current site dir
state,
}
}
// Find and resolve the Netlify configuration
async getConfig({ cwd, host, offline = argv.offline, pathPrefix, scheme, state, token }) {
try {
return await resolveConfig({
config: argv.config,
cwd,
context: argv.context || this.commandContext,
debug: argv.debug,
siteId: argv.siteId || (typeof argv.site === 'string' && argv.site) || state.get('siteId'),
token,
mode: 'cli',
host,
pathPrefix,
scheme,
offline,
})
} catch (error) {
const isUserError = error.type === 'userError'
// If we're failing due to an error thrown by us, it might be because the token we're using is invalid.
// To account for that, we try to retrieve the config again, this time without a token, to avoid making
// any API calls.
//
// @todo Replace this with a mechanism for calling `resolveConfig` with more granularity (i.e. having
// the option to say that we don't need API data.)
if (isUserError && !offline && token) {
return this.getConfig({ cwd, offline: true, state, token })
}
const message = isUserError ? error.message : error.stack
console.error(message)
this.exit(1)
}
}
async isLoggedIn() {
try {
await this.netlify.api.getCurrentUser()
return true
} catch (_) {
return false
}
}
logJson(message = '') {
if (argv.json || isDefaultJson()) {
process.stdout.write(JSON.stringify(message, null, 2))
}
}
log(message = '', ...args) {
/* If --silent or --json flag passed disable logger */
if (argv.silent || argv.json || isDefaultJson()) {
return
}
message = typeof message === 'string' ? message : inspect(message)
process.stdout.write(`${format(message, ...args)}\n`)
}
/* Modified flag parser to support global --auth, --json, & --silent flags */
parse(opts, args = this.argv) {
/* Set flags object for commands without flags */
if (!opts.flags) {
opts.flags = {}
}
/* enrich parse with global flags */
const globalFlags = {}
if (!opts.flags.silent) {
globalFlags.silent = {
parse: (value) => value,
description: 'Silence CLI output',
allowNo: false,
type: 'boolean',
}
}
if (!opts.flags.json) {
globalFlags.json = {
parse: (value) => value,
description: 'Output return values as JSON',
allowNo: false,
type: 'boolean',
}
}
if (!opts.flags.auth) {
globalFlags.auth = {
parse: (value) => value,
description: 'Netlify auth token',
input: [],
multiple: false,
type: 'option',
}
}
// enrich with flags here
opts.flags = { ...opts.flags, ...globalFlags }
return oclifParser.parse(args, {
context: this,
...opts,
})
}
get chalk() {
// If --json flag disable chalk colors
return chalkInstance(argv.json)
}
/**
* Get user netlify API token
* @param {string} - [tokenFromFlag] - value passed in by CLI flag
* @return {Promise<[string, string]>} - Promise containing tokenValue & location of resolved Netlify API token
*/
getConfigToken(tokenFromFlag) {
return getToken(tokenFromFlag)
}
async authenticate(tokenFromFlag) {
const [token] = await this.getConfigToken(tokenFromFlag)
if (token) {
return token
}
return this.expensivelyAuthenticate()
}
async expensivelyAuthenticate() {
const webUI = process.env.NETLIFY_WEB_UI || 'https://app.netlify.com'
this.log(`Logging into your Netlify account...`)
// Create ticket for auth
const ticket = await this.netlify.api.createTicket({
clientId: CLIENT_ID,
})
// Open browser for authentication
const authLink = `${webUI}/authorize?response_type=ticket&ticket=${ticket.id}`
this.log(`Opening ${authLink}`)
await openBrowser({ url: authLink, log: this.log })
const accessToken = await pollForToken({
api: this.netlify.api,
ticket,
exitWithError: this.error,
chalk: this.chalk,
})
const { id: userId, full_name: name, email } = await this.netlify.api.getCurrentUser()
const userData = merge(this.netlify.globalConfig.get(`users.${userId}`), {
id: userId,
name,
email,
auth: {
token: accessToken,
github: {
user: undefined,
token: undefined,
},
},
})
// Set current userId
this.netlify.globalConfig.set('userId', userId)
// Set user data
this.netlify.globalConfig.set(`users.${userId}`, userData)
await identify({
name,
email,
userId,
})
await track('user_login', {
email,
})
// Log success
this.log()
this.log(`${this.chalk.greenBright('You are now logged into your Netlify account!')}`)
this.log()
this.log(`Run ${this.chalk.cyanBright('netlify status')} for account details`)
this.log()
this.log(`To see all available commands run: ${this.chalk.cyanBright('netlify help')}`)
this.log()
return accessToken
}
}
const getAuthArg = function (cliArgs) {
// If deploy command. Support shorthand 'a' flag
if (cliArgs && cliArgs._ && cliArgs._[0] === 'deploy') {
return cliArgs.auth || cliArgs.a
}
return cliArgs.auth
}
BaseCommand.strict = false
BaseCommand.flags = {
debug: flagsLib.boolean({
description: 'Print debugging information',
}),
httpProxy: flagsLib.string({
description: 'Proxy server address to route requests through.',
default: process.env.HTTP_PROXY || process.env.HTTPS_PROXY,
}),
httpProxyCertificateFilename: flagsLib.string({
description: 'Certificate file to use when connecting using a proxy server',
default: process.env.NETLIFY_PROXY_CERTIFICATE_FILENAME,
}),
}
BaseCommand.getToken = getToken
module.exports = BaseCommand