@sentio/cli 4.3.1-rc.1 → 4.4.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +13305 -13236
- package/package.json +1 -1
- package/src/commands/login-server.ts +100 -73
- package/src/commands/login.ts +80 -106
- package/src/config.ts +61 -1
- package/src/key.ts +8 -4
package/package.json
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
import express from 'express'
|
|
2
|
-
import {
|
|
2
|
+
import { getFinalizedHost, type AuthConfig } from '../config.js'
|
|
3
3
|
import url from 'url'
|
|
4
|
-
import fetch from 'node-fetch'
|
|
5
4
|
import { getApiUrl, getCliVersion } from '../utils.js'
|
|
6
|
-
import {
|
|
5
|
+
import { WriteLoginCredentials } from '../key.js'
|
|
7
6
|
import chalk from 'chalk'
|
|
8
|
-
import http from 'http'
|
|
9
7
|
import os from 'os'
|
|
10
8
|
import * as crypto from 'crypto'
|
|
11
9
|
|
|
@@ -13,68 +11,93 @@ interface AuthParams {
|
|
|
13
11
|
serverPort: number
|
|
14
12
|
sentioHost: string
|
|
15
13
|
codeVerifier: string
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
14
|
+
state: string
|
|
15
|
+
authConfig: AuthConfig
|
|
16
|
+
onReady: (port: number) => Promise<void>
|
|
17
|
+
timeoutMs?: number
|
|
20
18
|
}
|
|
21
19
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
let
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
if (authParams.onFailure) {
|
|
39
|
-
authParams.onFailure(new Error(message))
|
|
40
|
-
} else {
|
|
41
|
-
setTimeout(() => process.exit(), 1000)
|
|
20
|
+
export function startServer(params: AuthParams): Promise<void> {
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
const app = express()
|
|
23
|
+
let redeeming = false
|
|
24
|
+
let settled = false
|
|
25
|
+
const controller = new AbortController()
|
|
26
|
+
const finish = (error?: Error) => {
|
|
27
|
+
if (settled) return
|
|
28
|
+
settled = true
|
|
29
|
+
controller.abort()
|
|
30
|
+
clearTimeout(timeout)
|
|
31
|
+
process.off('SIGINT', interrupted)
|
|
32
|
+
server.close()
|
|
33
|
+
server.closeAllConnections()
|
|
34
|
+
if (error) reject(error)
|
|
35
|
+
else resolve()
|
|
42
36
|
}
|
|
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
|
-
|
|
37
|
+
const interrupted = () => finish(new Error('Login cancelled'))
|
|
38
|
+
const timeout = setTimeout(
|
|
39
|
+
() => finish(new Error('Login timed out. Run login again.')),
|
|
40
|
+
params.timeoutMs ?? 5 * 60_000
|
|
41
|
+
)
|
|
42
|
+
process.once('SIGINT', interrupted)
|
|
43
|
+
app.get('/callback', async (req, res) => {
|
|
44
|
+
res.setHeader('Cache-Control', 'no-store')
|
|
45
|
+
if (typeof req.query.state !== 'string' || req.query.state !== params.state) {
|
|
46
|
+
res.status(400).end('Invalid authorization state')
|
|
47
|
+
return
|
|
48
|
+
}
|
|
49
|
+
if (redeeming) {
|
|
50
|
+
res.status(409).end('Authorization already in progress')
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
redeeming = true
|
|
54
|
+
const respond = (message: string, error?: Error) => {
|
|
55
|
+
// A browser can close the tab while the token request is still running.
|
|
56
|
+
// Completing login must not depend on delivering a response to that tab.
|
|
57
|
+
const complete = () => finish(error)
|
|
58
|
+
if (res.destroyed) return complete()
|
|
59
|
+
res.once('close', complete)
|
|
60
|
+
res.status(error ? 400 : 200).end(message, complete)
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
if (req.query.error) throw new Error('Authorization was not completed')
|
|
64
|
+
if (typeof req.query.code !== 'string' || !req.query.code) throw new Error('Missing authorization code')
|
|
65
|
+
const username = await exchangeCodeAndSave(
|
|
66
|
+
getFinalizedHost(params.sentioHost),
|
|
67
|
+
req.query.code,
|
|
68
|
+
params.codeVerifier,
|
|
69
|
+
params.authConfig,
|
|
70
|
+
controller.signal
|
|
71
|
+
)
|
|
72
|
+
console.log(chalk.green(`Login success with ${username}`))
|
|
73
|
+
respond('Login success, please go back to CLI to continue')
|
|
74
|
+
} catch (error) {
|
|
75
|
+
respond('Login failed. Check the terminal and try again.', error as Error)
|
|
76
|
+
}
|
|
77
|
+
})
|
|
78
|
+
const server = app.listen(params.serverPort, '127.0.0.1')
|
|
79
|
+
server.once('error', finish)
|
|
80
|
+
server.once('listening', () => {
|
|
81
|
+
const address = server.address() as { port: number }
|
|
82
|
+
params.onReady(address.port).catch(finish)
|
|
83
|
+
})
|
|
84
|
+
})
|
|
85
|
+
}
|
|
69
86
|
|
|
70
87
|
/**
|
|
71
88
|
* Exchanges an OAuth authorization code for an access token, verifies the account,
|
|
72
89
|
* creates an API key, and saves everything to local config.
|
|
73
90
|
* Returns the username on success, throws on failure.
|
|
74
91
|
*/
|
|
75
|
-
export async function exchangeCodeAndSave(
|
|
92
|
+
export async function exchangeCodeAndSave(
|
|
93
|
+
host: string,
|
|
94
|
+
code: string,
|
|
95
|
+
codeVerifier: string,
|
|
96
|
+
authConfig: AuthConfig,
|
|
97
|
+
signal?: AbortSignal
|
|
98
|
+
): Promise<string> {
|
|
76
99
|
// exchange token
|
|
77
|
-
const tokenResRaw = await getToken(
|
|
100
|
+
const tokenResRaw = await getToken(authConfig, code, codeVerifier, signal)
|
|
78
101
|
if (!tokenResRaw.ok) {
|
|
79
102
|
throw new Error(
|
|
80
103
|
`Failed to get access token: ${tokenResRaw.status} ${tokenResRaw.statusText}, ${await tokenResRaw.text()}`
|
|
@@ -82,49 +105,48 @@ export async function exchangeCodeAndSave(host: string, code: string, codeVerifi
|
|
|
82
105
|
}
|
|
83
106
|
const tokenRes = (await tokenResRaw.json()) as { access_token: string }
|
|
84
107
|
const accessToken = tokenRes.access_token
|
|
108
|
+
if (typeof accessToken !== 'string' || !accessToken) throw new Error('Missing access token')
|
|
85
109
|
|
|
86
110
|
// check if the account is ready
|
|
87
|
-
const userResRaw = await getUser(host, accessToken)
|
|
111
|
+
const userResRaw = await getUser(host, accessToken, signal)
|
|
88
112
|
if (!userResRaw.ok) {
|
|
89
113
|
if (userResRaw.status == 401) {
|
|
90
114
|
throw new Error('The account does not exist, please sign up on sentio first')
|
|
91
115
|
}
|
|
92
116
|
throw new Error(`Failed to get user info: ${userResRaw.status} ${userResRaw.statusText}`)
|
|
93
117
|
}
|
|
94
|
-
const userRes = (await userResRaw.json()) as { emailVerified: boolean }
|
|
95
|
-
if (!userRes.emailVerified) {
|
|
118
|
+
const userRes = (await userResRaw.json()) as { email?: string; emailVerified: boolean }
|
|
119
|
+
if (userRes.email && !userRes.emailVerified) {
|
|
96
120
|
throw new Error('Your account is not verified, please verify your email first')
|
|
97
121
|
}
|
|
98
122
|
|
|
99
123
|
// create API key
|
|
100
124
|
const apiKeyName = `${os.hostname()}-${crypto.randomBytes(4).toString('hex')}`
|
|
101
|
-
const createApiKeyResRaw = await createApiKey(host, apiKeyName, 'sdk_generated', accessToken)
|
|
125
|
+
const createApiKeyResRaw = await createApiKey(host, apiKeyName, 'sdk_generated', accessToken, signal)
|
|
102
126
|
if (!createApiKeyResRaw.ok) {
|
|
103
127
|
throw new Error(`Failed to create API key: ${createApiKeyResRaw.status} ${createApiKeyResRaw.statusText}`)
|
|
104
128
|
}
|
|
105
129
|
const { key, username } = (await createApiKeyResRaw.json()) as { key: string; username: string }
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
const expiresAt = decodeJwtExpiry(accessToken)
|
|
110
|
-
if (expiresAt !== undefined) {
|
|
111
|
-
WriteAccessToken(host, accessToken, expiresAt)
|
|
112
|
-
}
|
|
130
|
+
if (typeof key !== 'string' || !key) throw new Error('Missing API key')
|
|
131
|
+
signal?.throwIfAborted()
|
|
132
|
+
WriteLoginCredentials(host, key, accessToken, decodeJwtExpiry(accessToken))
|
|
113
133
|
|
|
114
134
|
return username
|
|
115
135
|
}
|
|
116
136
|
|
|
117
|
-
async function getToken(
|
|
118
|
-
const authConf = getAuthConfig(host)
|
|
137
|
+
async function getToken(authConf: AuthConfig, code: string, codeVerifier: string, signal?: AbortSignal) {
|
|
119
138
|
const params = new url.URLSearchParams({
|
|
120
139
|
grant_type: 'authorization_code',
|
|
121
140
|
client_id: authConf.clientId,
|
|
122
141
|
code_verifier: codeVerifier,
|
|
123
142
|
code: code,
|
|
124
|
-
redirect_uri: authConf.redirectUri
|
|
143
|
+
redirect_uri: authConf.redirectUri,
|
|
144
|
+
...(authConf.resourceParameter === 'resource' ? { resource: authConf.audience } : {})
|
|
125
145
|
})
|
|
126
|
-
return fetch(
|
|
146
|
+
return fetch(authConf.tokenEndpoint, {
|
|
127
147
|
method: 'POST',
|
|
148
|
+
redirect: 'error',
|
|
149
|
+
signal: AbortSignal.any([AbortSignal.timeout(20_000), ...(signal ? [signal] : [])]),
|
|
128
150
|
headers: {
|
|
129
151
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|
130
152
|
},
|
|
@@ -132,11 +154,14 @@ async function getToken(host: string, code: string, codeVerifier: string) {
|
|
|
132
154
|
})
|
|
133
155
|
}
|
|
134
156
|
|
|
135
|
-
async function createApiKey(host: string, name: string, source: string, accessToken: string) {
|
|
157
|
+
async function createApiKey(host: string, name: string, source: string, accessToken: string, signal?: AbortSignal) {
|
|
136
158
|
const createApiKeyUrl = getApiUrl('/api/v1/keys', host)
|
|
137
159
|
return fetch(createApiKeyUrl.href, {
|
|
138
160
|
method: 'POST',
|
|
161
|
+
redirect: 'error',
|
|
162
|
+
signal: AbortSignal.any([AbortSignal.timeout(20_000), ...(signal ? [signal] : [])]),
|
|
139
163
|
headers: {
|
|
164
|
+
'Content-Type': 'application/json',
|
|
140
165
|
Authorization: 'Bearer ' + accessToken,
|
|
141
166
|
version: getCliVersion()
|
|
142
167
|
},
|
|
@@ -148,10 +173,12 @@ async function createApiKey(host: string, name: string, source: string, accessTo
|
|
|
148
173
|
})
|
|
149
174
|
}
|
|
150
175
|
|
|
151
|
-
async function getUser(host: string, accessToken: string) {
|
|
176
|
+
async function getUser(host: string, accessToken: string, signal?: AbortSignal) {
|
|
152
177
|
const getUserUrl = getApiUrl('/api/v1/users', host)
|
|
153
178
|
return fetch(getUserUrl.href, {
|
|
154
179
|
method: 'GET',
|
|
180
|
+
redirect: 'error',
|
|
181
|
+
signal: AbortSignal.any([AbortSignal.timeout(20_000), ...(signal ? [signal] : [])]),
|
|
155
182
|
headers: {
|
|
156
183
|
Authorization: 'Bearer ' + accessToken,
|
|
157
184
|
version: getCliVersion()
|
package/src/commands/login.ts
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { Command } from '@commander-js/extra-typings'
|
|
2
|
-
import { getAuthConfig, getFinalizedHost } from '../config.js'
|
|
2
|
+
import { getAuthConfig, getFinalizedHost, type AuthConfig } from '../config.js'
|
|
3
3
|
import { startServer, exchangeCodeAndSave } from './login-server.js'
|
|
4
|
-
import readline from 'readline'
|
|
4
|
+
import readline from 'node:readline/promises'
|
|
5
5
|
import url, { URL } from 'url'
|
|
6
6
|
import * as crypto from 'crypto'
|
|
7
7
|
import chalk from 'chalk'
|
|
8
8
|
import { WriteKey, ReadKey, ReadAccessToken, isAccessTokenExpired } from '../key.js'
|
|
9
|
-
import fetch from 'node-fetch'
|
|
10
9
|
import open from 'open'
|
|
11
10
|
import { CommandOptionsType } from './types.js'
|
|
12
11
|
import { getApiUrl } from '../utils.js'
|
|
@@ -20,11 +19,13 @@ export function createLoginCommand() {
|
|
|
20
19
|
.option('--api-key <key>', '(Optional) Your API key')
|
|
21
20
|
.option('--status', 'Show current login status')
|
|
22
21
|
.option('--no-browser', 'Print the auth URL and accept the authorization code manually (for headless environments)')
|
|
23
|
-
.action((options) => {
|
|
24
|
-
|
|
25
|
-
loginStatus(options)
|
|
26
|
-
|
|
27
|
-
|
|
22
|
+
.action(async (options) => {
|
|
23
|
+
try {
|
|
24
|
+
if (options.status) await loginStatus(options)
|
|
25
|
+
else await login(options)
|
|
26
|
+
} catch (error) {
|
|
27
|
+
console.error(chalk.red('Login failed: ' + (error as Error).message))
|
|
28
|
+
process.exitCode = 1
|
|
28
29
|
}
|
|
29
30
|
})
|
|
30
31
|
}
|
|
@@ -63,124 +64,97 @@ async function loginStatus(options: CommandOptionsType<typeof createLoginCommand
|
|
|
63
64
|
}
|
|
64
65
|
}
|
|
65
66
|
|
|
66
|
-
function login(options: CommandOptionsType<typeof createLoginCommand>) {
|
|
67
|
+
async function login(options: CommandOptionsType<typeof createLoginCommand>) {
|
|
67
68
|
const host = getFinalizedHost(options.host)
|
|
68
|
-
|
|
69
69
|
if (options.apiKey) {
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
})
|
|
70
|
+
const response = await checkKey(host, options.apiKey)
|
|
71
|
+
if (!response.ok) throw new Error(`API key validation failed: ${response.status}`)
|
|
72
|
+
const { username } = (await response.json()) as { username: string }
|
|
73
|
+
WriteKey(host, options.apiKey)
|
|
74
|
+
console.log(chalk.green(`Login success with ${username}`))
|
|
75
|
+
return
|
|
76
|
+
}
|
|
77
|
+
const attempt = await createLoginAttempt(host)
|
|
78
|
+
if (options.browser === false) {
|
|
79
|
+
await loginNoBrowser(host, attempt)
|
|
81
80
|
} else {
|
|
82
|
-
|
|
83
|
-
const challenge = base64URLEncode(sha256(verifier))
|
|
84
|
-
|
|
85
|
-
const conf = getAuthConfig(host)
|
|
86
|
-
if (conf.domain === '') {
|
|
87
|
-
console.error(chalk.red('invalid host, try login with an API key if it is a dev env'))
|
|
88
|
-
return
|
|
89
|
-
}
|
|
90
|
-
const authURL = buildAuthURL(conf, challenge)
|
|
91
|
-
|
|
92
|
-
if (options.browser === false) {
|
|
93
|
-
loginNoBrowser(host, authURL.toString(), verifier)
|
|
94
|
-
return
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
console.log('Continue your authorization in the browser')
|
|
98
|
-
open(authURL.toString()).catch((reason) => {
|
|
99
|
-
console.error(chalk.yellow('Unable to open browser: ' + reason))
|
|
100
|
-
console.error(chalk.yellow('Falling back to manual login...'))
|
|
101
|
-
loginNoBrowser(host, authURL.toString(), verifier)
|
|
102
|
-
})
|
|
103
|
-
|
|
104
|
-
startServer({
|
|
105
|
-
serverPort: port,
|
|
106
|
-
sentioHost: options.host || '',
|
|
107
|
-
codeVerifier: verifier
|
|
108
|
-
})
|
|
81
|
+
await loginInBrowser(host, attempt)
|
|
109
82
|
}
|
|
110
83
|
}
|
|
111
84
|
|
|
112
|
-
/**
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
*/
|
|
117
|
-
export function loginInteractiveAndWait(host: string): Promise<void> {
|
|
118
|
-
return new Promise((resolve, reject) => {
|
|
119
|
-
const conf = getAuthConfig(host)
|
|
120
|
-
if (conf.domain === '') {
|
|
121
|
-
reject(new Error('No auth config for this host. Use --api-key for local/dev environments.'))
|
|
122
|
-
return
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
const verifier = base64URLEncode(crypto.randomBytes(32))
|
|
126
|
-
const challenge = base64URLEncode(sha256(verifier))
|
|
127
|
-
const authURL = buildAuthURL(conf, challenge)
|
|
85
|
+
/** Reauthenticate when a command needs an expired privileged access token. */
|
|
86
|
+
export async function loginInteractiveAndWait(host: string): Promise<void> {
|
|
87
|
+
await loginInBrowser(host, await createLoginAttempt(host))
|
|
88
|
+
}
|
|
128
89
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
90
|
+
async function createLoginAttempt(host: string) {
|
|
91
|
+
const conf = await getAuthConfig(host)
|
|
92
|
+
const verifier = base64URLEncode(crypto.randomBytes(32))
|
|
93
|
+
const state = 'sentio-cli:' + base64URLEncode(crypto.randomBytes(32))
|
|
94
|
+
return { conf, verifier, state, authURL: buildAuthURL(conf, base64URLEncode(sha256(verifier)), state) }
|
|
95
|
+
}
|
|
134
96
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
97
|
+
async function loginInBrowser(host: string, attempt: Awaited<ReturnType<typeof createLoginAttempt>>) {
|
|
98
|
+
// Bind before opening the browser, and own the listener until success,
|
|
99
|
+
// cancellation, an OAuth error or timeout. Nothing listens on external interfaces.
|
|
100
|
+
await startServer({
|
|
101
|
+
serverPort: port,
|
|
102
|
+
sentioHost: host,
|
|
103
|
+
codeVerifier: attempt.verifier,
|
|
104
|
+
state: attempt.state,
|
|
105
|
+
authConfig: attempt.conf,
|
|
106
|
+
onReady: async () => {
|
|
107
|
+
console.log('Continue your authorization in the browser')
|
|
108
|
+
try {
|
|
109
|
+
await open(attempt.authURL.toString())
|
|
110
|
+
} catch {
|
|
111
|
+
console.log('Open this URL in your browser: ' + attempt.authURL.toString())
|
|
112
|
+
}
|
|
113
|
+
}
|
|
142
114
|
})
|
|
143
115
|
}
|
|
144
116
|
|
|
145
|
-
function loginNoBrowser(host: string,
|
|
146
|
-
console.log(chalk.blue('
|
|
147
|
-
console.log(chalk.cyan(authURL))
|
|
148
|
-
console.log(
|
|
149
|
-
console.log(chalk.blue('(it is the value of the `code` query parameter) and paste it below.\n'))
|
|
150
|
-
|
|
117
|
+
async function loginNoBrowser(host: string, attempt: Awaited<ReturnType<typeof createLoginAttempt>>) {
|
|
118
|
+
console.log(chalk.blue('Open this URL in a browser to complete login:'))
|
|
119
|
+
console.log(chalk.cyan(attempt.authURL.toString()))
|
|
120
|
+
console.log('After signing in, paste the callback URL or its code parameter below.')
|
|
151
121
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
|
|
152
|
-
|
|
153
|
-
rl.
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
122
|
+
try {
|
|
123
|
+
const input = (await rl.question('Authorization code or callback URL: ')).trim()
|
|
124
|
+
if (!input) throw new Error('No code provided, login aborted.')
|
|
125
|
+
let code = input
|
|
126
|
+
if (/^https?:\/\//.test(input)) {
|
|
127
|
+
const callback = new URL(input)
|
|
128
|
+
const expected = attempt.conf.redirectUri
|
|
129
|
+
if (
|
|
130
|
+
![expected, `http://localhost:${port}/callback`].includes(callback.origin + callback.pathname) ||
|
|
131
|
+
callback.searchParams.get('state') !== attempt.state
|
|
132
|
+
)
|
|
133
|
+
throw new Error('Invalid authorization callback state or URL')
|
|
134
|
+
if (callback.searchParams.has('error')) throw new Error('Authorization was not completed')
|
|
135
|
+
code = callback.searchParams.get('code') ?? ''
|
|
158
136
|
}
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
}
|
|
166
|
-
})
|
|
137
|
+
if (!code) throw new Error('Missing authorization code')
|
|
138
|
+
const username = await exchangeCodeAndSave(host, code, attempt.verifier, attempt.conf)
|
|
139
|
+
console.log(chalk.green(`Login success with ${username}`))
|
|
140
|
+
} finally {
|
|
141
|
+
rl.close()
|
|
142
|
+
}
|
|
167
143
|
}
|
|
168
144
|
|
|
169
|
-
function buildAuthURL(
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
): URL {
|
|
173
|
-
const authURL = new URL(conf.domain + `/authorize?`)
|
|
174
|
-
const params = new url.URLSearchParams({
|
|
145
|
+
export function buildAuthURL(conf: AuthConfig, challenge: string, state: string): URL {
|
|
146
|
+
const authURL = new URL(conf.authorizationEndpoint)
|
|
147
|
+
authURL.search = new url.URLSearchParams({
|
|
175
148
|
response_type: 'code',
|
|
176
149
|
code_challenge: challenge,
|
|
177
150
|
code_challenge_method: 'S256',
|
|
178
151
|
client_id: conf.clientId,
|
|
179
152
|
redirect_uri: conf.redirectUri,
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
153
|
+
[conf.resourceParameter]: conf.audience,
|
|
154
|
+
scope: conf.scope,
|
|
155
|
+
prompt: 'login',
|
|
156
|
+
state
|
|
157
|
+
}).toString()
|
|
184
158
|
return authURL
|
|
185
159
|
}
|
|
186
160
|
|
package/src/config.ts
CHANGED
|
@@ -51,7 +51,66 @@ export function getFinalizedHost(host: string | undefined): string {
|
|
|
51
51
|
return HostMap[host] ?? host
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
export
|
|
54
|
+
export interface AuthConfig {
|
|
55
|
+
clientId: string
|
|
56
|
+
audience: string
|
|
57
|
+
redirectUri: string
|
|
58
|
+
authorizationEndpoint: string
|
|
59
|
+
tokenEndpoint: string
|
|
60
|
+
resourceParameter: 'audience' | 'resource'
|
|
61
|
+
scope: string
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function getAuthConfig(host: string): Promise<AuthConfig> {
|
|
65
|
+
const origin = new URL(host).origin
|
|
66
|
+
const response = await fetch(new URL('/api/cli/auth', origin), {
|
|
67
|
+
redirect: 'error',
|
|
68
|
+
signal: AbortSignal.timeout(10_000)
|
|
69
|
+
})
|
|
70
|
+
// Keep installations whose server has not deployed discovery on their existing
|
|
71
|
+
// login flow. Outages or invalid config must never select a different issuer.
|
|
72
|
+
if (response.status === 404) {
|
|
73
|
+
const { domain, clientId, audience, redirectUri } = getLegacyAuthConfig(host)
|
|
74
|
+
return {
|
|
75
|
+
clientId,
|
|
76
|
+
audience,
|
|
77
|
+
redirectUri,
|
|
78
|
+
authorizationEndpoint: domain + '/authorize',
|
|
79
|
+
tokenEndpoint: domain + '/oauth/token',
|
|
80
|
+
resourceParameter: 'audience',
|
|
81
|
+
scope: 'openid profile email'
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (!response.ok) throw new Error(`Unable to load login configuration (${response.status}). Try again later.`)
|
|
85
|
+
return validateAuthConfig(await response.json(), origin)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function validateAuthConfig(value: unknown, origin: string): AuthConfig {
|
|
89
|
+
const config = value as AuthConfig
|
|
90
|
+
if (
|
|
91
|
+
!config ||
|
|
92
|
+
(['clientId', 'audience', 'redirectUri', 'authorizationEndpoint', 'tokenEndpoint', 'scope'] as const).some(
|
|
93
|
+
(key) => typeof config[key] !== 'string' || !config[key]
|
|
94
|
+
) ||
|
|
95
|
+
!['audience', 'resource'].includes(config.resourceParameter)
|
|
96
|
+
)
|
|
97
|
+
throw new Error('Invalid login configuration')
|
|
98
|
+
for (const field of ['authorizationEndpoint', 'tokenEndpoint', 'redirectUri'] as const) {
|
|
99
|
+
const url = new URL(config[field])
|
|
100
|
+
if (
|
|
101
|
+
url.username ||
|
|
102
|
+
url.password ||
|
|
103
|
+
url.hash ||
|
|
104
|
+
(url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1'].includes(url.hostname)))
|
|
105
|
+
) {
|
|
106
|
+
throw new Error('Login configuration requires secure URLs')
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (new URL(config.redirectUri).origin !== origin) throw new Error('Invalid login callback origin')
|
|
110
|
+
return config
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function getLegacyAuthConfig(host: string): {
|
|
55
114
|
domain: string
|
|
56
115
|
clientId: string
|
|
57
116
|
audience: string
|
|
@@ -84,6 +143,7 @@ export function getAuthConfig(host: string): {
|
|
|
84
143
|
default:
|
|
85
144
|
break
|
|
86
145
|
}
|
|
146
|
+
if (!domain) throw new Error('No login configuration for this host. Use --api-key instead.')
|
|
87
147
|
return { domain, clientId, audience, redirectUri }
|
|
88
148
|
}
|
|
89
149
|
|
package/src/key.ts
CHANGED
|
@@ -29,9 +29,10 @@ function readConfig(): SentioKeyConfig {
|
|
|
29
29
|
|
|
30
30
|
function writeConfig(config: SentioKeyConfig) {
|
|
31
31
|
if (!fs.existsSync(sentioDir)) {
|
|
32
|
-
fs.mkdirSync(sentioDir, { recursive: true })
|
|
32
|
+
fs.mkdirSync(sentioDir, { recursive: true, mode: 0o700 })
|
|
33
33
|
}
|
|
34
|
-
fs.writeFileSync(configFile, JSON.stringify(config, null, 2))
|
|
34
|
+
fs.writeFileSync(configFile, JSON.stringify(config, null, 2), { mode: 0o600 })
|
|
35
|
+
fs.chmodSync(configFile, 0o600)
|
|
35
36
|
}
|
|
36
37
|
|
|
37
38
|
export function WriteKey(host: string, api_key: string) {
|
|
@@ -44,9 +45,12 @@ export function ReadKey(host: string): string | undefined {
|
|
|
44
45
|
return readConfig()[host]?.api_keys
|
|
45
46
|
}
|
|
46
47
|
|
|
47
|
-
export function
|
|
48
|
+
export function WriteLoginCredentials(host: string, apiKey: string, token: string, expiresAt?: number) {
|
|
48
49
|
const config = readConfig()
|
|
49
|
-
config[host] = {
|
|
50
|
+
config[host] = {
|
|
51
|
+
api_keys: apiKey,
|
|
52
|
+
...(expiresAt !== undefined ? { access_token: token, access_token_expires_at: expiresAt } : {})
|
|
53
|
+
}
|
|
50
54
|
writeConfig(config)
|
|
51
55
|
}
|
|
52
56
|
|