@sentio/cli 4.3.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/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.1",
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,93 @@ 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 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
- 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
- })
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(host: string, code: string, codeVerifier: string): Promise<string> {
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(host, code, codeVerifier)
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
- 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
- }
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(host: string, code: string, codeVerifier: string) {
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(`${authConf.domain}/oauth/token`, {
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()
@@ -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