@sentio/cli 4.3.1 → 4.4.0-rc.2
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 +13310 -13236
- package/package.json +1 -1
- package/src/commands/login-server.ts +105 -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,98 @@ 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
|
-
|
|
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 redemption: Promise<string> | undefined
|
|
24
|
+
let responses = 0
|
|
25
|
+
let settled = false
|
|
26
|
+
const controller = new AbortController()
|
|
27
|
+
const finish = (error?: Error) => {
|
|
28
|
+
if (settled) return
|
|
29
|
+
settled = true
|
|
30
|
+
controller.abort()
|
|
31
|
+
clearTimeout(timeout)
|
|
32
|
+
process.off('SIGINT', interrupted)
|
|
33
|
+
server.close()
|
|
34
|
+
server.closeAllConnections()
|
|
35
|
+
if (error) reject(error)
|
|
36
|
+
else resolve()
|
|
42
37
|
}
|
|
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
|
-
}
|
|
38
|
+
const interrupted = () => finish(new Error('Login cancelled'))
|
|
39
|
+
const timeout = setTimeout(
|
|
40
|
+
() => finish(new Error('Login timed out. Run login again.')),
|
|
41
|
+
params.timeoutMs ?? 5 * 60_000
|
|
42
|
+
)
|
|
43
|
+
process.once('SIGINT', interrupted)
|
|
44
|
+
app.get('/callback', async (req, res) => {
|
|
45
|
+
res.setHeader('Cache-Control', 'no-store')
|
|
46
|
+
if (typeof req.query.state !== 'string' || req.query.state !== params.state) {
|
|
47
|
+
res.status(400).end('Invalid authorization state')
|
|
48
|
+
return
|
|
49
|
+
}
|
|
50
|
+
responses++
|
|
51
|
+
const respond = (message: string, error?: Error) => {
|
|
52
|
+
// Browsers may interrupt and retry the navigation during redemption.
|
|
53
|
+
// Flush every waiting response before closing the shared listener.
|
|
54
|
+
let completed = false
|
|
55
|
+
const complete = () => {
|
|
56
|
+
if (completed) return
|
|
57
|
+
completed = true
|
|
58
|
+
if (--responses === 0) finish(error)
|
|
59
|
+
}
|
|
60
|
+
if (res.destroyed) return complete()
|
|
61
|
+
res.once('close', complete)
|
|
62
|
+
res.status(error ? 400 : 200).end(message, complete)
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
if (req.query.error) throw new Error('Authorization was not completed')
|
|
66
|
+
if (typeof req.query.code !== 'string' || !req.query.code) throw new Error('Missing authorization code')
|
|
67
|
+
redemption ??= exchangeCodeAndSave(
|
|
68
|
+
getFinalizedHost(params.sentioHost),
|
|
69
|
+
req.query.code,
|
|
70
|
+
params.codeVerifier,
|
|
71
|
+
params.authConfig,
|
|
72
|
+
controller.signal
|
|
73
|
+
).then((username) => {
|
|
74
|
+
console.log(chalk.green(`Login success with ${username}`))
|
|
75
|
+
return username
|
|
76
|
+
})
|
|
77
|
+
await redemption
|
|
78
|
+
respond('Login success, please go back to CLI to continue')
|
|
79
|
+
} catch (error) {
|
|
80
|
+
respond('Login failed. Check the terminal and try again.', error as Error)
|
|
81
|
+
}
|
|
82
|
+
})
|
|
83
|
+
const server = app.listen(params.serverPort, '127.0.0.1')
|
|
84
|
+
server.once('error', finish)
|
|
85
|
+
server.once('listening', () => {
|
|
86
|
+
const address = server.address() as { port: number }
|
|
87
|
+
params.onReady(address.port).catch(finish)
|
|
88
|
+
})
|
|
89
|
+
})
|
|
90
|
+
}
|
|
69
91
|
|
|
70
92
|
/**
|
|
71
93
|
* Exchanges an OAuth authorization code for an access token, verifies the account,
|
|
72
94
|
* creates an API key, and saves everything to local config.
|
|
73
95
|
* Returns the username on success, throws on failure.
|
|
74
96
|
*/
|
|
75
|
-
export async function exchangeCodeAndSave(
|
|
97
|
+
export async function exchangeCodeAndSave(
|
|
98
|
+
host: string,
|
|
99
|
+
code: string,
|
|
100
|
+
codeVerifier: string,
|
|
101
|
+
authConfig: AuthConfig,
|
|
102
|
+
signal?: AbortSignal
|
|
103
|
+
): Promise<string> {
|
|
76
104
|
// exchange token
|
|
77
|
-
const tokenResRaw = await getToken(
|
|
105
|
+
const tokenResRaw = await getToken(authConfig, code, codeVerifier, signal)
|
|
78
106
|
if (!tokenResRaw.ok) {
|
|
79
107
|
throw new Error(
|
|
80
108
|
`Failed to get access token: ${tokenResRaw.status} ${tokenResRaw.statusText}, ${await tokenResRaw.text()}`
|
|
@@ -82,49 +110,48 @@ export async function exchangeCodeAndSave(host: string, code: string, codeVerifi
|
|
|
82
110
|
}
|
|
83
111
|
const tokenRes = (await tokenResRaw.json()) as { access_token: string }
|
|
84
112
|
const accessToken = tokenRes.access_token
|
|
113
|
+
if (typeof accessToken !== 'string' || !accessToken) throw new Error('Missing access token')
|
|
85
114
|
|
|
86
115
|
// check if the account is ready
|
|
87
|
-
const userResRaw = await getUser(host, accessToken)
|
|
116
|
+
const userResRaw = await getUser(host, accessToken, signal)
|
|
88
117
|
if (!userResRaw.ok) {
|
|
89
118
|
if (userResRaw.status == 401) {
|
|
90
119
|
throw new Error('The account does not exist, please sign up on sentio first')
|
|
91
120
|
}
|
|
92
121
|
throw new Error(`Failed to get user info: ${userResRaw.status} ${userResRaw.statusText}`)
|
|
93
122
|
}
|
|
94
|
-
const userRes = (await userResRaw.json()) as { emailVerified: boolean }
|
|
95
|
-
if (!userRes.emailVerified) {
|
|
123
|
+
const userRes = (await userResRaw.json()) as { email?: string; emailVerified: boolean }
|
|
124
|
+
if (userRes.email && !userRes.emailVerified) {
|
|
96
125
|
throw new Error('Your account is not verified, please verify your email first')
|
|
97
126
|
}
|
|
98
127
|
|
|
99
128
|
// create API key
|
|
100
129
|
const apiKeyName = `${os.hostname()}-${crypto.randomBytes(4).toString('hex')}`
|
|
101
|
-
const createApiKeyResRaw = await createApiKey(host, apiKeyName, 'sdk_generated', accessToken)
|
|
130
|
+
const createApiKeyResRaw = await createApiKey(host, apiKeyName, 'sdk_generated', accessToken, signal)
|
|
102
131
|
if (!createApiKeyResRaw.ok) {
|
|
103
132
|
throw new Error(`Failed to create API key: ${createApiKeyResRaw.status} ${createApiKeyResRaw.statusText}`)
|
|
104
133
|
}
|
|
105
134
|
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
|
-
}
|
|
135
|
+
if (typeof key !== 'string' || !key) throw new Error('Missing API key')
|
|
136
|
+
signal?.throwIfAborted()
|
|
137
|
+
WriteLoginCredentials(host, key, accessToken, decodeJwtExpiry(accessToken))
|
|
113
138
|
|
|
114
139
|
return username
|
|
115
140
|
}
|
|
116
141
|
|
|
117
|
-
async function getToken(
|
|
118
|
-
const authConf = getAuthConfig(host)
|
|
142
|
+
async function getToken(authConf: AuthConfig, code: string, codeVerifier: string, signal?: AbortSignal) {
|
|
119
143
|
const params = new url.URLSearchParams({
|
|
120
144
|
grant_type: 'authorization_code',
|
|
121
145
|
client_id: authConf.clientId,
|
|
122
146
|
code_verifier: codeVerifier,
|
|
123
147
|
code: code,
|
|
124
|
-
redirect_uri: authConf.redirectUri
|
|
148
|
+
redirect_uri: authConf.redirectUri,
|
|
149
|
+
...(authConf.resourceParameter === 'resource' ? { resource: authConf.audience } : {})
|
|
125
150
|
})
|
|
126
|
-
return fetch(
|
|
151
|
+
return fetch(authConf.tokenEndpoint, {
|
|
127
152
|
method: 'POST',
|
|
153
|
+
redirect: 'error',
|
|
154
|
+
signal: AbortSignal.any([AbortSignal.timeout(20_000), ...(signal ? [signal] : [])]),
|
|
128
155
|
headers: {
|
|
129
156
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|
130
157
|
},
|
|
@@ -132,11 +159,14 @@ async function getToken(host: string, code: string, codeVerifier: string) {
|
|
|
132
159
|
})
|
|
133
160
|
}
|
|
134
161
|
|
|
135
|
-
async function createApiKey(host: string, name: string, source: string, accessToken: string) {
|
|
162
|
+
async function createApiKey(host: string, name: string, source: string, accessToken: string, signal?: AbortSignal) {
|
|
136
163
|
const createApiKeyUrl = getApiUrl('/api/v1/keys', host)
|
|
137
164
|
return fetch(createApiKeyUrl.href, {
|
|
138
165
|
method: 'POST',
|
|
166
|
+
redirect: 'error',
|
|
167
|
+
signal: AbortSignal.any([AbortSignal.timeout(20_000), ...(signal ? [signal] : [])]),
|
|
139
168
|
headers: {
|
|
169
|
+
'Content-Type': 'application/json',
|
|
140
170
|
Authorization: 'Bearer ' + accessToken,
|
|
141
171
|
version: getCliVersion()
|
|
142
172
|
},
|
|
@@ -148,10 +178,12 @@ async function createApiKey(host: string, name: string, source: string, accessTo
|
|
|
148
178
|
})
|
|
149
179
|
}
|
|
150
180
|
|
|
151
|
-
async function getUser(host: string, accessToken: string) {
|
|
181
|
+
async function getUser(host: string, accessToken: string, signal?: AbortSignal) {
|
|
152
182
|
const getUserUrl = getApiUrl('/api/v1/users', host)
|
|
153
183
|
return fetch(getUserUrl.href, {
|
|
154
184
|
method: 'GET',
|
|
185
|
+
redirect: 'error',
|
|
186
|
+
signal: AbortSignal.any([AbortSignal.timeout(20_000), ...(signal ? [signal] : [])]),
|
|
155
187
|
headers: {
|
|
156
188
|
Authorization: 'Bearer ' + accessToken,
|
|
157
189
|
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
|
|