@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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentio/cli",
3
- "version": "4.3.1",
3
+ "version": "4.4.0-rc.2",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,11 +1,9 @@
1
1
  import express from 'express'
2
- import { getAuthConfig, getFinalizedHost } from '../config.js'
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 { WriteKey, WriteAccessToken } from '../key.js'
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
- /** Called on successful login instead of process.exit() when provided. */
17
- onSuccess?: () => void
18
- /** Called on login failure instead of process.exit() when provided. */
19
- onFailure?: (err: Error) => void
14
+ state: string
15
+ authConfig: AuthConfig
16
+ onReady: (port: number) => Promise<void>
17
+ timeoutMs?: number
20
18
  }
21
19
 
22
- const app = express()
23
-
24
- let server: http.Server
25
- let authParams: AuthParams
26
-
27
- export function startServer(params: AuthParams) {
28
- authParams = params
29
- server = app.listen(params.serverPort)
30
- }
31
-
32
- app.get('/callback', async (req, res) => {
33
- const fail = function (message: string) {
34
- console.error(chalk.red(message))
35
- res.end(message)
36
- server.close()
37
- server.closeAllConnections()
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 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
- const host = getFinalizedHost(authParams.sentioHost)
46
- const code = req.query.code
47
- if (!code || (code as string).length == 0) {
48
- fail('Failed to get authorization code')
49
- return
50
- }
51
-
52
- try {
53
- const username = await exchangeCodeAndSave(host, code as string, authParams.codeVerifier)
54
- res.end('Login success, please go back to CLI to continue')
55
- console.log(chalk.green(`Login success with ${username}`))
56
- } catch (e) {
57
- fail((e as Error).message)
58
- return
59
- }
60
-
61
- server.close()
62
- server.closeAllConnections()
63
- if (authParams.onSuccess) {
64
- authParams.onSuccess()
65
- } else {
66
- setTimeout(() => process.exit(), 1000)
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(host: string, code: string, codeVerifier: string): Promise<string> {
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(host, code, codeVerifier)
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
- WriteKey(host, key)
107
-
108
- // store access token with expiry for commands that require admin permissions
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(host: string, code: string, codeVerifier: string) {
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(`${authConf.domain}/oauth/token`, {
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()
@@ -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
- if (options.status) {
25
- loginStatus(options)
26
- } else {
27
- login(options)
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
- console.log(chalk.blue('login to ' + host))
71
- const apiKey = options.apiKey
72
- checkKey(host, apiKey).then(async (res) => {
73
- if (res.status == 200) {
74
- WriteKey(host, apiKey)
75
- const { username } = (await res.json()) as { username: string }
76
- console.log(chalk.green(`login success with ${username}`))
77
- } else {
78
- console.error(chalk.red('login failed, code:', res.status, res.statusText))
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
- const verifier = base64URLEncode(crypto.randomBytes(32))
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
- * Launches the interactive browser-based OAuth login flow and waits for it to complete.
114
- * Stores the API key and access token in the local config upon success.
115
- * Throws if login fails or the host has no auth config (e.g. local dev environments).
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
- console.log(chalk.blue('Opening browser for login...'))
130
- open(authURL.toString()).catch((reason) => {
131
- console.error(chalk.yellow('Unable to open browser automatically.'))
132
- console.error(chalk.yellow('Open this URL in your browser: ' + authURL.toString()))
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
- startServer({
136
- serverPort: port,
137
- sentioHost: host,
138
- codeVerifier: verifier,
139
- onSuccess: resolve,
140
- onFailure: reject
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, authURL: string, codeVerifier: string) {
146
- console.log(chalk.blue('\nOpen the following URL in your browser to complete login:'))
147
- console.log(chalk.cyan(authURL))
148
- console.log(chalk.blue('\nAfter completing login, copy the authorization code from the redirect URL'))
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
- rl.question('Authorization code: ', async (input) => {
153
- rl.close()
154
- const code = input.trim()
155
- if (!code) {
156
- console.error(chalk.red('No code provided, login aborted.'))
157
- process.exit(1)
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
- try {
160
- const username = await exchangeCodeAndSave(host, code, codeVerifier)
161
- console.log(chalk.green(`Login success with ${username}`))
162
- } catch (e) {
163
- console.error(chalk.red('Login failed: ' + (e as Error).message))
164
- process.exit(1)
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
- conf: { domain: string; clientId: string; audience: string; redirectUri: string },
171
- challenge: string
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
- audience: conf.audience,
181
- prompt: 'login'
182
- })
183
- authURL.search = params.toString()
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 function getAuthConfig(host: string): {
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 WriteAccessToken(host: string, token: string, expiresAt: number) {
48
+ export function WriteLoginCredentials(host: string, apiKey: string, token: string, expiresAt?: number) {
48
49
  const config = readConfig()
49
- config[host] = { ...config[host], access_token: token, access_token_expires_at: expiresAt }
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