@sendhoney/cli 0.1.1 → 0.1.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/README.md CHANGED
@@ -11,9 +11,16 @@ Use `sendhoney menu --operator` for service routes.
11
11
 
12
12
  ```bash
13
13
  pnpm --filter @sendhoney/cli generate-catalog
14
- node apps/sendhoney-cli/bin/sendhoney login --username you@example.com --password '…'
14
+ # Opens Keycloak in the browser and completes a PKCE login through localhost.
15
+ node apps/sendhoney-cli/bin/sendhoney login
15
16
  # CI/service account alternative:
16
17
  sendhoney login --token "$SENDHONEY_TOKEN"
18
+ sendhoney resources list
19
+ sendhoney resources current
20
+ sendhoney endpoints list
21
+ sendhoney billing balance --org-id ORG_ID
22
+ sendhoney billing ledger --org-id ORG_ID
23
+ sendhoney billing rates
17
24
  sendhoney api catalog --search crm
18
25
  sendhoney api get /health
19
26
  sendhoney crud /api/v1/crm/contacts list
@@ -24,6 +31,10 @@ sendhoney thundercompute models
24
31
  sendhoney thundercompute status --model qwen2.5:7b
25
32
  sendhoney thundercompute chat --json '{"message":"Summarize this incident"}'
26
33
  sendhoney release check --platform all
34
+ sendhoney credentials list --tenant-id TENANT_ID
35
+ sendhoney credentials add --type postiz --json @postiz-credential.json
36
+ sendhoney credentials update --id CREDENTIAL_ID --json @rotated-credential.json
37
+ sendhoney credentials validate --secret-refs @secret-refs.json
27
38
  ```
28
39
 
29
40
  Installation:
@@ -31,9 +42,23 @@ Installation:
31
42
  ```bash
32
43
  npm install -g @sendhoney/cli
33
44
  brew tap sendhoney/tap && brew install sendhoney
34
- curl -fsSL https://sendhoney.app/cli/install.sh | sh
45
+ curl -fsSL https://sendhoney.app/cli/install.sh | bash
35
46
  ```
36
47
 
37
- Use `SENDHONEY_TOKEN` for CI/service accounts. Credentials are stored in
48
+ `sendhoney login` uses Keycloak Authorization Code + PKCE and refreshes expired
49
+ access tokens automatically. Use `SENDHONEY_TOKEN` for CI/service accounts.
50
+ Credentials are stored in
38
51
  `$XDG_CONFIG_HOME/sendhoney/config.json` (or `~/.config/sendhoney/config.json`)
39
52
  with mode `0600`; tokens are never printed by the CLI.
53
+
54
+ Credential operations are tenant-scoped through the SendHoney API. `list`
55
+ returns metadata only; secret references and payload fields are redacted from
56
+ CLI output. `add` and `update` send `secretPayload` to the server, where it is
57
+ stored through the configured secret manager. Use `@file` for payloads so
58
+ credentials do not enter shell history. `update` rotates the secret reference
59
+ on the existing credential record without retrieving the secret value.
60
+
61
+ The expert interface is the Go program in `apps/sendhoney-tui`. It shares
62
+ this config file and speaks to the module-agent routes. See
63
+ `docs/SENDHONEY_TUI.md`. npm, Homebrew, and the curl installer do not
64
+ install that binary.
package/bin/sendhoney CHANGED
@@ -4,6 +4,8 @@ const fs = require('node:fs')
4
4
  const os = require('node:os')
5
5
  const path = require('node:path')
6
6
  const { spawnSync } = require('node:child_process')
7
+ const { randomBytes, createHash } = require('node:crypto')
8
+ const http = require('node:http')
7
9
  const readline = require('node:readline/promises')
8
10
  const { stdin, stdout } = require('node:process')
9
11
 
@@ -24,6 +26,55 @@ function saveConfig(value) {
24
26
  fs.writeFileSync(configFile, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
25
27
  }
26
28
 
29
+ function openBrowser(url) {
30
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open'
31
+ const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url]
32
+ const child = require('node:child_process').spawn(command, args, { detached: true, stdio: 'ignore' })
33
+ child.unref()
34
+ }
35
+
36
+ function base64Url(value) { return value.toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_') }
37
+ function pkceChallenge(verifier) { return base64Url(createHash('sha256').update(verifier).digest()) }
38
+
39
+ async function browserLogin(args, config) {
40
+ const authUrl = (args['auth-url'] || process.env.SENDHONEY_AUTH_URL || config.authUrl || 'https://auth.sendhoney.app').replace(/\/$/, '')
41
+ const realm = args.realm || process.env.SENDHONEY_KEYCLOAK_REALM || config.realm || 'users'
42
+ const clientId = args['client-id'] || process.env.SENDHONEY_CLIENT_ID || config.clientId || 'sendhoney-cli'
43
+ const state = base64Url(randomBytes(24)); const verifier = base64Url(randomBytes(48))
44
+ const server = http.createServer()
45
+ await new Promise((resolve) => server.listen(Number(args.port || 0), '127.0.0.1', resolve))
46
+ const callback = `http://127.0.0.1:${server.address().port}/callback`
47
+ const authorization = new URL(`${authUrl}/realms/${encodeURIComponent(realm)}/protocol/openid-connect/auth`)
48
+ authorization.search = new URLSearchParams({ client_id: clientId, redirect_uri: callback, response_type: 'code', scope: 'openid profile email offline_access', state, code_challenge: pkceChallenge(verifier), code_challenge_method: 'S256' }).toString()
49
+ const result = await new Promise((resolve, reject) => {
50
+ const timeout = setTimeout(() => { server.close(); reject(new Error('login timed out')) }, 300000)
51
+ server.on('request', (req, res) => {
52
+ const url = new URL(req.url || '/', callback)
53
+ if (url.pathname !== '/callback') { res.end('SendHoney CLI login'); return }
54
+ if (url.searchParams.get('state') !== state) { res.statusCode = 400; res.end('Invalid login state'); clearTimeout(timeout); server.close(); reject(new Error('invalid login state')); return }
55
+ const code = url.searchParams.get('code'); const error = url.searchParams.get('error')
56
+ res.end(error ? 'SendHoney login failed. You may close this window.' : 'SendHoney login complete. You may close this window.')
57
+ clearTimeout(timeout); server.close(); error ? reject(new Error(error)) : resolve({ code, callback })
58
+ })
59
+ openBrowser(authorization.toString())
60
+ stdout.write(`Opening Keycloak login in your browser (${callback})\n`)
61
+ })
62
+ const tokenResponse = await fetch(`${authUrl}/realms/${encodeURIComponent(realm)}/protocol/openid-connect/token`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'authorization_code', client_id: clientId, code: result.code, redirect_uri: result.callback, code_verifier: verifier }).toString() })
63
+ const tokens = await tokenResponse.json().catch(() => ({}))
64
+ if (!tokenResponse.ok || !tokens.access_token) die(`Keycloak login failed (${tokenResponse.status})`)
65
+ saveConfig({ ...config, apiUrl: args['api-url'] || config.apiUrl || 'https://api.sendhoney.app', authUrl, realm, clientId, accessToken: tokens.access_token, refreshToken: tokens.refresh_token, expiresAt: Date.now() + (tokens.expires_in || 300) * 1000 })
66
+ return json({ ok: true, apiUrl: args['api-url'] || config.apiUrl || 'https://api.sendhoney.app' })
67
+ }
68
+
69
+ async function refreshToken(config) {
70
+ if (!config.refreshToken || !config.authUrl || !config.realm || !config.clientId) return false
71
+ const response = await fetch(`${config.authUrl.replace(/\/$/, '')}/realms/${encodeURIComponent(config.realm)}/protocol/openid-connect/token`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'refresh_token', client_id: config.clientId, refresh_token: config.refreshToken }).toString() })
72
+ const body = await response.json().catch(() => ({}))
73
+ if (!response.ok || !body.access_token) return false
74
+ saveConfig({ ...config, accessToken: body.access_token, refreshToken: body.refresh_token || config.refreshToken, expiresAt: Date.now() + (body.expires_in || 300) * 1000 })
75
+ return true
76
+ }
77
+
27
78
  function catalog() {
28
79
  for (const file of catalogFiles) {
29
80
  try {
@@ -36,6 +87,16 @@ function catalog() {
36
87
 
37
88
  function json(value) { process.stdout.write(`${JSON.stringify(value, null, 2)}\n`) }
38
89
  function die(message, code = 1) { process.stderr.write(`sendhoney: ${message}\n`); process.exit(code) }
90
+ function redactCredential(value) {
91
+ if (Array.isArray(value)) return value.map(redactCredential)
92
+ if (!value || typeof value !== 'object') return value
93
+ const output = {}
94
+ for (const [key, item] of Object.entries(value)) {
95
+ if (['secretRef', 'secretPayload', 'accessToken', 'refreshToken', 'token', 'password', 'apiKey', 'clientSecret'].includes(key)) continue
96
+ output[key] = redactCredential(item)
97
+ }
98
+ return output
99
+ }
39
100
  function parseArgs(args) {
40
101
  const out = { _: [] }
41
102
  for (let i = 0; i < args.length; i += 1) {
@@ -159,17 +220,65 @@ async function request(method, endpoint, options = {}) {
159
220
  const token = options.token || process.env.SENDHONEY_TOKEN || config.accessToken
160
221
  const headers = { Accept: 'application/json', ...(options.json ? { 'Content-Type': 'application/json' } : {}) }
161
222
  if (token) headers.Authorization = `Bearer ${token}`
162
- const response = await fetch(url, { method, headers, body: options.json ? JSON.stringify(options.json) : undefined })
223
+ let response = await fetch(url, { method, headers, body: options.json ? JSON.stringify(options.json) : undefined })
224
+ if (response.status === 401 && await refreshToken(config)) {
225
+ headers.Authorization = `Bearer ${loadConfig().accessToken}`
226
+ response = await fetch(url, { method, headers, body: options.json ? JSON.stringify(options.json) : undefined })
227
+ }
163
228
  const text = await response.text()
164
229
  let body
165
230
  try { body = text ? JSON.parse(text) : null } catch { body = text }
166
231
  if (!response.ok) { json({ status: response.status, url, error: body }); process.exitCode = 1; return }
167
- json(body)
232
+ json(options.redactCredentials ? redactCredential(body) : body)
233
+ }
234
+
235
+ async function credentials(args, subcommand) {
236
+ if (!['list', 'add', 'update', 'validate'].includes(subcommand)) {
237
+ die('use credentials list|add|update|validate')
238
+ }
239
+ if (subcommand === 'list') {
240
+ const query = args['tenant-id'] ? `?tenantId=${encodeURIComponent(args['tenant-id'])}` : ''
241
+ return request('GET', `/api/channel-credentials${query}`, { ...args, redactCredentials: true })
242
+ }
243
+ if (subcommand === 'validate') {
244
+ const refs = args['secret-ref'] ? [args['secret-ref']] : readJson(args['secret-refs'])
245
+ if (!Array.isArray(refs) || refs.length === 0) die('credentials validate requires --secret-refs @file or JSON array')
246
+ return request('POST', '/api/channel-credentials/validate', {
247
+ ...args,
248
+ json: { ...(args['tenant-id'] ? { tenantId: args['tenant-id'] } : {}), secretRefs: refs },
249
+ redactCredentials: true,
250
+ })
251
+ }
252
+ const body = readJson(args.json) || {}
253
+ if (!body || typeof body !== 'object' || Array.isArray(body)) die('--json must be an object or @file')
254
+ if (args['tenant-id']) body.tenantId = args['tenant-id']
255
+ if (args.type) body.type = args.type
256
+ if (args.label) body.label = args.label
257
+ if (args.country) body.country = args.country
258
+ if (args.region) body.region = args.region
259
+ if (subcommand === 'update') {
260
+ if (args.id) body.id = args.id
261
+ if (!body.id) die('credentials update requires --id or id in --json')
262
+ return request('PATCH', '/api/channel-credentials', { ...args, json: body, redactCredentials: true })
263
+ }
264
+ if (!body.type) die('credentials add requires --type or type in --json')
265
+ return request('POST', '/api/channel-credentials', { ...args, json: body, redactCredentials: true })
266
+ }
267
+
268
+ async function curated(args, subcommand) {
269
+ const orgId = args['org-id'] || loadConfig().orgId
270
+ if (subcommand === 'list') return request('GET', '/api/organization/modules', args)
271
+ if (subcommand === 'current') return request('GET', '/api/v1/org/me', args)
272
+ if (subcommand === 'endpoints') return json(catalog().filter((entry) => entry.auth !== 'service' && entry.auth !== 'admin'))
273
+ if (subcommand === 'balance') { if (!orgId) die('billing balance requires --org-id or workspace selection'); return request('GET', `/api/billing/balance/${encodeURIComponent(orgId)}`, args) }
274
+ if (subcommand === 'ledger') { if (!orgId) die('billing ledger requires --org-id or workspace selection'); return request('GET', `/api/billing/ledger/${encodeURIComponent(orgId)}`, args) }
275
+ if (subcommand === 'rates') return request('GET', '/api/billing/rate', args)
276
+ die('use resources list|current, endpoints list, or billing balance|ledger|rates')
168
277
  }
169
278
 
170
279
  async function login(args) {
171
280
  const config = loadConfig()
172
- const directToken = args.token || process.env.SENDHONEY_TOKEN
281
+ const directToken = args.token || process.env.SENDHONEY_TOKEN //no-secret-check
173
282
  if (directToken) {
174
283
  saveConfig({ ...config, apiUrl: args['api-url'] || config.apiUrl || 'https://api.sendhoney.app', accessToken: directToken })
175
284
  return json({ ok: true, apiUrl: args['api-url'] || config.apiUrl || 'https://api.sendhoney.app' })
@@ -178,7 +287,7 @@ async function login(args) {
178
287
  const realm = args.realm || process.env.SENDHONEY_KEYCLOAK_REALM || config.realm || 'users'
179
288
  const clientId = args['client-id'] || process.env.SENDHONEY_CLIENT_ID || config.clientId || 'sendhoney-mobile'
180
289
  const username = args.username || process.env.SENDHONEY_USERNAME
181
- const password = args.password || process.env.SENDHONEY_PASSWORD
290
+ const password = args.password || process.env.SENDHONEY_PASSWORD //no-secret-check
182
291
  if (!username || !password) die('login requires --username and --password (or SENDHONEY_USERNAME/SENDHONEY_PASSWORD)')
183
292
  const response = await fetch(`${authUrl}/realms/${realm}/protocol/openid-connect/token`, {
184
293
  method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
@@ -198,12 +307,20 @@ async function main() {
198
307
  }
199
308
  if (!command && stdin.isTTY && stdout.isTTY) return interactiveMenu(args)
200
309
  if (!command || command === 'help' || args.help) {
201
- process.stdout.write('SendHoney CLI\n\nCommands: login, logout, whoami, menu, api, crud, thundercompute, release\n\nRunning `sendhoney` interactively opens the resource menu.\nmenu [--operator]\napi request METHOD PATH [--json JSON] | api get|post|put|patch|delete PATH\napi catalog [--search TEXT] [--method GET]\ncrud PATH list|create|update|delete [--id ID] [--json JSON] [--yes]\nthundercompute catalog|health|models|status|pull|ensure|chat\nrelease check [--platform android|ios|all]\n')
310
+ process.stdout.write('SendHoney CLI\n\nCommands: login, logout, whoami, menu, resources, endpoints, billing, api, crud, credentials, thundercompute, release\n\n`login` opens a Keycloak PKCE browser login when no token/password is supplied.\nresources list\nresources current\nendpoints list\nbilling balance [--org-id ID]\nbilling ledger [--org-id ID]\nbilling rates\napi request METHOD PATH [--json JSON] | api get|post|put|patch|delete PATH\napi catalog [--search TEXT] [--method GET]\ncrud PATH list|create|update|delete [--id ID] [--json JSON] [--yes]\ncredentials list [--tenant-id ID]\ncredentials add [--type TYPE] [--json JSON|@FILE]\ncredentials update --id ID [--json JSON|@FILE]\ncredentials validate --secret-refs @FILE | --secret-ref REF\nSecret payloads are sent to the API and are never printed by these commands.\nthundercompute catalog|health|models|status|pull|ensure|chat\nrelease check [--platform android|ios|all]\n')
202
311
  return
203
312
  }
204
- if (command === 'login') return login(args)
313
+ if (command === 'login') {
314
+ const config = loadConfig()
315
+ if (args.token || process.env.SENDHONEY_TOKEN || args.username || process.env.SENDHONEY_USERNAME) return login(args)
316
+ return browserLogin(args, config)
317
+ }
205
318
  if (command === 'logout') { const c = loadConfig(); delete c.accessToken; delete c.refreshToken; delete c.expiresAt; saveConfig(c); return json({ ok: true }) }
206
319
  if (command === 'menu') return interactiveMenu(args)
320
+ if (command === 'credentials') return credentials(args, subcommand)
321
+ if (command === 'resources') return curated(args, subcommand)
322
+ if (command === 'endpoints' && subcommand === 'list') return curated(args, 'endpoints')
323
+ if (command === 'billing') return curated(args, subcommand)
207
324
  if (command === 'whoami') return request('GET', '/api/v1/users/me', args)
208
325
  if (command === 'api' || command === 'crud') {
209
326
  if (command === 'api' && subcommand === 'catalog') {