@sendhoney/cli 0.1.5 → 0.1.8

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.
Files changed (3) hide show
  1. package/README.md +5 -1
  2. package/bin/sendhoney +46 -13
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -63,6 +63,9 @@ sendhoney credentials validate --secret-refs @secret-refs.json
63
63
  sendhoney login
64
64
  sendhoney resources current
65
65
 
66
+ # Inspect the local non-secret session state
67
+ sendhoney auth status
68
+
66
69
  # Generate the decoded.africa widget snippet using the saved organization
67
70
  sendhoney widget install --widget-type both
68
71
 
@@ -85,6 +88,7 @@ sendhoney widget install --org-id ORG_ID --widget-type both --file ./dist/index.
85
88
  | `login [--token TOKEN] \| [--username USER --password PASS]` | Keycloak PKCE browser login or direct token/password auth |
86
89
  | `logout` | Clear stored credentials |
87
90
  | `whoami` | Return the authenticated user profile |
91
+ | `auth status` | Show authenticated state, expiry, user, organization, and resolved org ID without tokens |
88
92
  | `menu [--operator]` | Interactive resource menu grouped by domain |
89
93
  | `resources list \| current` | List organization modules / current org |
90
94
  | `endpoints list` | List published API endpoints |
@@ -108,7 +112,7 @@ sendhoney widget install --org-id ORG_ID --widget-type both --file ./dist/index.
108
112
 
109
113
  `sendhoney login` uses Keycloak Authorization Code + PKCE and refreshes expired access tokens automatically. Use `SENDHONEY_TOKEN` for CI / service accounts.
110
114
 
111
- 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.
115
+ 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. After browser login, the CLI exchanges the PKCE code, hydrates the Keycloak user profile and current organization, and stores the resolved `orgId` in the local session. `sendhoney widget install` can therefore use the saved organization without a second ID lookup.
112
116
 
113
117
  ---
114
118
 
package/bin/sendhoney CHANGED
@@ -36,6 +36,16 @@ function openBrowser(url) {
36
36
  function base64Url(value) { return value.toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_') }
37
37
  function pkceChallenge(verifier) { return base64Url(createHash('sha256').update(verifier).digest()) }
38
38
 
39
+ function loginCallbackPage(success) {
40
+ const title = success ? 'Return to your terminal' : 'Sign-in could not be completed'
41
+ const message = success
42
+ ? 'SendHoney received the authorization. The CLI is exchanging it securely now; return to your terminal for the final login result.'
43
+ : 'The SendHoney CLI could not complete sign-in. Close this window and try again from your terminal.'
44
+ const icon = success ? '✓' : '!'
45
+ const accent = success ? '#0f766e' : '#b42318'
46
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title} · SendHoney</title><style>*,*:before,*:after{box-sizing:border-box}body{margin:0;min-height:100vh;display:grid;place-items:center;padding:24px;background:#f7fbfb;color:#102a2a;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}.card{width:min(100%,480px);padding:40px;border:1px solid #d9e9e7;border-radius:24px;background:#fff;box-shadow:0 20px 60px #0f766e18;text-align:center}.brand{display:inline-flex;align-items:center;gap:10px;margin-bottom:32px;color:#0f766e;font-size:18px;font-weight:800;letter-spacing:-.02em}.mark{display:grid;place-items:center;width:32px;height:32px;border-radius:10px;background:#0f766e;color:#fff;font-size:20px}.status{display:grid;place-items:center;width:64px;height:64px;margin:0 auto 22px;border-radius:20px;background:${accent}18;color:${accent};font-size:32px;font-weight:800}.title{margin:0;font-size:30px;letter-spacing:-.04em}.message{margin:14px auto 0;max-width:30rem;color:#587070;font-size:16px;line-height:1.6}.hint{margin-top:28px;color:#789090;font-size:13px}</style></head><body><main class="card"><div class="brand"><span class="mark">S</span><span>SendHoney</span></div><div class="status">${icon}</div><h1 class="title">${title}</h1><p class="message">${message}</p><p class="hint">You may safely close this tab.</p></main></body></html>`
47
+ }
48
+
39
49
  async function browserLogin(args, config) {
40
50
  const authUrl = (args['auth-url'] || process.env.SENDHONEY_AUTH_URL || config.authUrl || 'https://auth.sendhoney.app').replace(/\/$/, '')
41
51
  const realm = args.realm || process.env.SENDHONEY_KEYCLOAK_REALM || config.realm || 'users'
@@ -53,7 +63,8 @@ async function browserLogin(args, config) {
53
63
  if (url.pathname !== '/') { res.end('SendHoney CLI login'); return }
54
64
  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
65
  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.')
66
+ res.setHeader('Content-Type', 'text/html; charset=utf-8')
67
+ res.end(loginCallbackPage(!error))
57
68
  clearTimeout(timeout); server.close(); error ? reject(new Error(error)) : resolve({ code, callback })
58
69
  })
59
70
  const loginUrl = authorization.toString()
@@ -63,9 +74,9 @@ async function browserLogin(args, config) {
63
74
  })
64
75
  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() })
65
76
  const tokens = await tokenResponse.json().catch(() => ({}))
66
- if (!tokenResponse.ok || !tokens.access_token) die(`Keycloak login failed (${tokenResponse.status})`)
67
- 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 })
68
- return json({ ok: true, apiUrl: args['api-url'] || config.apiUrl || 'https://api.sendhoney.app' })
77
+ if (!tokenResponse.ok || !tokens.access_token) die(`Keycloak login failed (${tokenResponse.status}): ${tokens.error_description || tokens.error || 'no access token'}`)
78
+ const session = await persistLoginSession(config, args, { authUrl, realm, clientId }, tokens)
79
+ return json({ ok: true, authenticated: true, orgId: session.orgId || undefined, apiUrl: session.apiUrl })
69
80
  }
70
81
 
71
82
  async function refreshToken(config) {
@@ -93,6 +104,32 @@ function organizationIdFrom(value) {
93
104
  if (!value || typeof value !== 'object') return ''
94
105
  return String(value.orgId || value.organizationId || value.tenantId || value.organization?.id || value.organization?.orgId || value.workspace?.organizationId || value.organizations?.[0]?.id || '').trim()
95
106
  }
107
+
108
+ async function persistLoginSession(config, args, auth, tokens) {
109
+ const apiUrl = args['api-url'] || config.apiUrl || 'https://api.sendhoney.app'
110
+ const headers = { Accept: 'application/json', Authorization: `Bearer ${tokens.access_token}` }
111
+ const [userResponse, orgResponse] = await Promise.all([
112
+ fetch(`${auth.authUrl}/realms/${encodeURIComponent(auth.realm)}/protocol/openid-connect/userinfo`, { headers }).catch(() => null),
113
+ fetch(`${apiUrl.replace(/\/$/, '')}/api/v1/org/me`, { headers }).catch(() => null),
114
+ ])
115
+ const user = userResponse ? await userResponse.json().catch(() => ({})) : {}
116
+ const organization = orgResponse ? await orgResponse.json().catch(() => ({})) : {}
117
+ const orgId = organizationIdFrom(organization)
118
+ const session = { authenticated: true, authenticatedAt: new Date().toISOString(), user, organization, orgId: orgId || undefined }
119
+ saveConfig({
120
+ ...config, apiUrl, authUrl: auth.authUrl, realm: auth.realm, clientId: auth.clientId,
121
+ accessToken: tokens.access_token, refreshToken: tokens.refresh_token || config.refreshToken,
122
+ idToken: tokens.id_token, expiresAt: Date.now() + (tokens.expires_in || 300) * 1000,
123
+ ...(orgId ? { orgId } : {}), session,
124
+ })
125
+ return { apiUrl, orgId }
126
+ }
127
+
128
+ function authStatus() {
129
+ const config = loadConfig()
130
+ const expiresAt = Number(config.expiresAt || 0)
131
+ json({ authenticated: Boolean(config.accessToken) && (!expiresAt || expiresAt > Date.now()), expiresAt: expiresAt ? new Date(expiresAt).toISOString() : undefined, orgId: config.orgId || config.session?.orgId, user: config.session?.user, organization: config.session?.organization, configFile })
132
+ }
96
133
  function redactCredential(value) {
97
134
  if (Array.isArray(value)) return value.map(redactCredential)
98
135
  if (!value || typeof value !== 'object') return value
@@ -343,7 +380,7 @@ async function login(args) {
343
380
  }
344
381
  const authUrl = (args['auth-url'] || process.env.SENDHONEY_AUTH_URL || config.authUrl || 'https://auth.sendhoney.app').replace(/\/$/, '')
345
382
  const realm = args.realm || process.env.SENDHONEY_KEYCLOAK_REALM || config.realm || 'users'
346
- const clientId = args['client-id'] || process.env.SENDHONEY_CLIENT_ID || config.clientId || 'sendhoney-mobile'
383
+ const clientId = args['client-id'] || process.env.SENDHONEY_CLIENT_ID || config.clientId || 'sendhoney-cli'
347
384
  const username = args.username || process.env.SENDHONEY_USERNAME
348
385
  const password = args.password || process.env.SENDHONEY_PASSWORD //no-secret-check
349
386
  if (!username || !password) die('login requires --username and --password (or SENDHONEY_USERNAME/SENDHONEY_PASSWORD)')
@@ -353,13 +390,8 @@ async function login(args) {
353
390
  })
354
391
  const body = await response.json().catch(() => ({}))
355
392
  if (!response.ok || !body.access_token) die(`login failed (${response.status}): ${body.error_description || body.error || 'no access token'}`)
356
- const nextConfig = { ...config, apiUrl: args['api-url'] || config.apiUrl || 'https://api.sendhoney.app', authUrl, realm, clientId, accessToken: body.access_token, refreshToken: body.refresh_token, expiresAt: Date.now() + (body.expires_in || 300) * 1000 }
357
- saveConfig(nextConfig)
358
- const orgResponse = await fetch(`${nextConfig.apiUrl.replace(/\/$/, '')}/api/v1/org/me`, { headers: { Accept: 'application/json', Authorization: `Bearer ${body.access_token}` } }).catch(() => null)
359
- const orgBody = orgResponse ? await orgResponse.json().catch(() => ({})) : {}
360
- const orgId = organizationIdFrom(orgBody)
361
- if (orgId) saveConfig({ ...nextConfig, orgId })
362
- json({ ok: true, username, apiUrl: args['api-url'] || config.apiUrl || 'https://api.sendhoney.app' })
393
+ const session = await persistLoginSession(config, args, { authUrl, realm, clientId }, body)
394
+ json({ ok: true, username, authenticated: true, orgId: session.orgId || undefined, apiUrl: session.apiUrl })
363
395
  }
364
396
 
365
397
  async function main() {
@@ -378,7 +410,8 @@ async function main() {
378
410
  if (args.token || process.env.SENDHONEY_TOKEN || args.username || process.env.SENDHONEY_USERNAME) return login(args)
379
411
  return browserLogin(args, config)
380
412
  }
381
- if (command === 'logout') { const c = loadConfig(); delete c.accessToken; delete c.refreshToken; delete c.expiresAt; saveConfig(c); return json({ ok: true }) }
413
+ if (command === 'logout') { const c = loadConfig(); delete c.accessToken; delete c.refreshToken; delete c.idToken; delete c.expiresAt; delete c.session; saveConfig(c); return json({ ok: true }) }
414
+ if (command === 'auth' && subcommand === 'status') return authStatus()
382
415
  if (command === 'menu') return interactiveMenu(args)
383
416
  if (command === 'credentials') return credentials(args, subcommand)
384
417
  if (command === 'widget' && subcommand === 'install') return widgetInstall(args)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sendhoney/cli",
3
- "version": "0.1.5",
3
+ "version": "0.1.8",
4
4
  "description": "SendHoney platform CLI for authenticated API, CRUD, release, and ThunderCompute operations.",
5
5
  "private": false,
6
6
  "bin": { "sendhoney": "bin/sendhoney" },