@sendhoney/cli 0.1.1 → 0.1.3

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
@@ -1,19 +1,49 @@
1
- # SendHoney CLI
1
+ # @sendhoney/cli
2
2
 
3
- Authenticated API and operations CLI for SendHoney tech teams. It follows the
4
- small launcher pattern used by the GameDay and Decoded CLIs, while keeping API
5
- behavior server-side.
3
+ SendHoney platform CLI for authenticated API, CRUD, release, and ThunderCompute operations. Follows the small launcher pattern used by the GameDay and Decoded CLIs, while keeping API behavior server-side.
6
4
 
7
- Run `sendhoney` with no arguments for the interactive resource menu. It groups
8
- the generated endpoint contract by domain and resource, hides service-only
9
- routes by default, prompts for route parameters and JSON, and confirms deletes.
10
- Use `sendhoney menu --operator` for service routes.
5
+ ---
6
+
7
+ ## Install
11
8
 
12
9
  ```bash
10
+ # npm (latest)
11
+ npm install -g @sendhoney/cli
12
+
13
+ # npm (pinned)
14
+ npm install -g @sendhoney/cli@0.1.3
15
+
16
+ # Homebrew
17
+ brew tap sendhoney/tap && brew install sendhoney
18
+
19
+ # curl installer
20
+ curl -fsSL https://sendhoney.app/cli/install.sh | bash
21
+ ```
22
+
23
+ ---
24
+
25
+ ## Quick start
26
+
27
+ ```bash
28
+ # 1. Generate the endpoint contract catalog
13
29
  pnpm --filter @sendhoney/cli generate-catalog
14
- node apps/sendhoney-cli/bin/sendhoney login --username you@example.com --password '…'
15
- # CI/service account alternative:
30
+
31
+ # 2. Log in (opens Keycloak PKCE in the browser via localhost)
32
+ sendhoney login
33
+
34
+ # 3. CI / service account alternative (token never printed)
16
35
  sendhoney login --token "$SENDHONEY_TOKEN"
36
+
37
+ # 4. Browse and call API resources interactively
38
+ sendhoney menu
39
+
40
+ # 5. Non-interactive examples
41
+ sendhoney resources list
42
+ sendhoney resources current
43
+ sendhoney endpoints list
44
+ sendhoney billing balance --org-id ORG_ID
45
+ sendhoney billing ledger --org-id ORG_ID
46
+ sendhoney billing rates
17
47
  sendhoney api catalog --search crm
18
48
  sendhoney api get /health
19
49
  sendhoney crud /api/v1/crm/contacts list
@@ -24,16 +54,78 @@ sendhoney thundercompute models
24
54
  sendhoney thundercompute status --model qwen2.5:7b
25
55
  sendhoney thundercompute chat --json '{"message":"Summarize this incident"}'
26
56
  sendhoney release check --platform all
57
+ sendhoney credentials list --tenant-id TENANT_ID
58
+ sendhoney credentials add --type postiz --json @postiz-credential.json
59
+ sendhoney credentials update --id CREDENTIAL_ID --json @rotated-credential.json
60
+ sendhoney credentials validate --secret-refs @secret-refs.json
27
61
  ```
28
62
 
29
- Installation:
63
+ ---
64
+
65
+ ## Commands
66
+
67
+ | Command | Description |
68
+ |---------|-------------|
69
+ | `login [--token TOKEN] \| [--username USER --password PASS]` | Keycloak PKCE browser login or direct token/password auth |
70
+ | `logout` | Clear stored credentials |
71
+ | `whoami` | Return the authenticated user profile |
72
+ | `menu [--operator]` | Interactive resource menu grouped by domain |
73
+ | `resources list \| current` | List organization modules / current org |
74
+ | `endpoints list` | List published API endpoints |
75
+ | `billing balance [--org-id ID]` | Organization billing balance |
76
+ | `billing ledger [--org-id ID]` | Organization billing ledger |
77
+ | `billing rates` | Billing rate card |
78
+ | `api catalog [--search TEXT] [--method GET]` | Search/filter endpoint catalog |
79
+ | `api get\|post\|put\|patch\|delete PATH [--json JSON]` | Direct API request |
80
+ | `crud PATH list\|create\|update\|delete [--id ID] [--json JSON] [--yes]` | Generic CRUD against any API path |
81
+ | `credentials list [--tenant-id ID]` | List tenant-scoped channel credentials (metadata only) |
82
+ | `credentials add [--type TYPE] [--json JSON\|@FILE]` | Add a new credential |
83
+ | `credentials update --id ID [--json JSON\|@FILE]` | Rotate/update an existing credential |
84
+ | `credentials validate --secret-refs @FILE \| --secret-ref REF` | Validate secret references |
85
+ | `thundercompute catalog\|health\|models\|status\|pull\|ensure\|chat` | ThunderCompute / RunPod AI model operations |
86
+ | `release check [--platform android\|ios\|all]` | Check mobile release readiness |
87
+
88
+ ---
89
+
90
+ ## Authentication
91
+
92
+ `sendhoney login` uses Keycloak Authorization Code + PKCE and refreshes expired access tokens automatically. Use `SENDHONEY_TOKEN` for CI / service accounts.
93
+
94
+ Credentials are stored in `$XDG_CONFIG_HOME/sendhoney/config.json` (or `~/.config/sendhoney/config.json`) with mode `0600`; tokens are never printed by the CLI.
95
+
96
+ ---
97
+
98
+ ## Credentials
99
+
100
+ Credential operations are tenant-scoped through the SendHoney API. `list` returns metadata only; secret references and payload fields are redacted from CLI output. `add` and `update` send `secretPayload` to the server, where it is stored through the configured secret manager. Use `@file` for payloads so credentials do not enter shell history. `update` rotates the secret reference on the existing credential record without retrieving the secret value.
101
+
102
+ ---
103
+
104
+ ## Expert interface
105
+
106
+ The expert interface is the Go program in `apps/sendhoney-tui`. It shares this config file and speaks to the module-agent routes. See `docs/SENDHONEY_TUI.md`. npm, Homebrew, and the curl installer do not install that binary.
107
+
108
+ ---
109
+
110
+ ## Publishing
111
+
112
+ Maintained in the `sendhoney-api-monorepo-oatpp-v2` repo under `apps/sendhoney-cli`.
113
+ Publish to npmjs via **staged publishing** (matches the SendHoney deployment flow):
114
+
115
+ 1. Stage the package (uploaded to npm staging, not yet public):
116
+ ```bash
117
+ pnpm --filter @sendhoney/cli generate-catalog
118
+ cd apps/sendhoney-cli
119
+ npm stage publish --access public
120
+ ```
121
+ 2. Log in to https://www.npmjs.com
122
+ 3. Go to https://www.npmjs.com/package/@sendhoney/cli
123
+ 4. Promote the staged version from **Staging → Public**
124
+
125
+ Alternatively, run the publish script which stages and prints the promotion link:
30
126
 
31
127
  ```bash
32
- npm install -g @sendhoney/cli
33
- brew tap sendhoney/tap && brew install sendhoney
34
- curl -fsSL https://sendhoney.app/cli/install.sh | sh
128
+ ./scripts/publish-sendhoney-cli.sh
35
129
  ```
36
130
 
37
- Use `SENDHONEY_TOKEN` for CI/service accounts. Credentials are stored in
38
- `$XDG_CONFIG_HOME/sendhoney/config.json` (or `~/.config/sendhoney/config.json`)
39
- with mode `0600`; tokens are never printed by the CLI.
131
+ npm disallows republishing an already-published version, so always bump `version` in `package.json` before staging.
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') {