@sendhoney/cli 0.1.13 → 0.1.15

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,9 @@ SendHoney platform CLI for authenticated API, CRUD, release, and ThunderCompute
11
11
  npm install -g @sendhoney/cli
12
12
 
13
13
  # npm (pinned)
14
- npm install -g @sendhoney/cli@0.1.13
14
+ npm install -g @sendhoney/cli@0.1.14
15
15
 
16
- sendhoney --version # should print 0.1.13
16
+ sendhoney --version # should print 0.1.14
17
17
 
18
18
  # Homebrew
19
19
  brew tap sendhoney/tap && brew install sendhoney
@@ -61,6 +61,9 @@ sendhoney credentials add --type postiz --json @postiz-credential.json
61
61
  sendhoney credentials update --id CREDENTIAL_ID --json @rotated-credential.json
62
62
  sendhoney credentials validate --secret-refs @secret-refs.json
63
63
 
64
+ # Enable contact center and other modules for an organization
65
+ sendhoney resources enable-modules --org-id ORG_ID --modules contact_center,crm
66
+
64
67
  # Log in and resolve the current workspace organization automatically
65
68
  sendhoney login
66
69
  sendhoney resources current
@@ -92,7 +95,7 @@ sendhoney widget install --org-id ORG_ID --widget-type both --file ./dist/index.
92
95
  | `whoami` | Return the authenticated user profile |
93
96
  | `auth status` | Show authenticated state, expiry, user, organization, and resolved org ID without tokens |
94
97
  | `menu [--operator]` | Interactive resource menu grouped by domain |
95
- | `resources list \| current` | List organization modules / current org |
98
+ | `resources list \| current \| enable-modules` | List organization modules / current org / enable modules |
96
99
  | `endpoints list` | List published API endpoints |
97
100
  | `billing balance [--org-id ID]` | Organization billing balance |
98
101
  | `billing ledger [--org-id ID]` | Organization billing ledger |
@@ -108,14 +111,107 @@ sendhoney widget install --org-id ORG_ID --widget-type both --file ./dist/index.
108
111
  | `thundercompute catalog\|health\|models\|status\|pull\|ensure\|chat` | ThunderCompute / RunPod AI model operations |
109
112
  | `release check [--platform android\|ios\|all]` | Check mobile release readiness |
110
113
 
114
+ ## Module management
115
+
116
+ Organizations must explicitly enable modules (e.g., CRM, Contact Center, Inventory) before they appear in the mobile app or web dashboard. Use the CLI to enable modules for an organization:
117
+
118
+ ```bash
119
+ # Enable contact center and CRM modules
120
+ sendhoney resources enable-modules --org-id ORG_ID --modules contact_center,crm
121
+
122
+ # Enable multiple modules at once
123
+ sendhoney resources enable-modules --org-id ORG_ID --modules contact_center,crm,inventory,books
124
+ ```
125
+
126
+ ### Available module slugs
127
+
128
+ Use these exact slugs with `--modules` (comma-separated, no spaces):
129
+
130
+ | Module | Slug | Description |
131
+ |--------|------|-------------|
132
+ | CRM | `crm` | Accounts, contacts, opportunities, cases |
133
+ | Contact Center | `contact_center` | Team inboxes, AI assist, voice/WebRTC |
134
+ | Inventory | `inventory` | Warehouse, stock, goods receipt |
135
+ | Books/Finance | `books` | Accounting, billing, payments |
136
+ | HR | `hr` | Recruitment, payroll, workforce |
137
+ | Logistics | `logistics` | Fleet, delivery, field ops |
138
+ | Healthcare | `healthcare` | Facilities, patients, standards |
139
+ | FMCG | `fmcg` | Fast-moving consumer goods workflows |
140
+ | Storage | `storage` | Document/object storage |
141
+ | Incentive Schemes | `incentive_schemes` | Loyalty, rewards, commissions |
142
+
143
+ ### Troubleshooting: Contact Center not visible in mobile app
144
+
145
+ If the Contact Center module doesn't appear for a user (e.g., `graham@decoded.africa`):
146
+
147
+ 1. **Find the organization ID**:
148
+ ```bash
149
+ sendhoney auth status
150
+ # Look for "orgId" in the output
151
+ ```
152
+
153
+ 2. **Enable the Contact Center module**:
154
+ ```bash
155
+ sendhoney resources enable-modules --org-id <ORG_ID> --modules contact_center
156
+ ```
157
+
158
+ 3. **Verify modules are active**:
159
+ ```bash
160
+ sendhoney resources list
161
+ # Should show contact_center in the enabled modules
162
+ ```
163
+
164
+ 4. **Restart the mobile app** to refresh the module list (it caches for 5 minutes).
165
+
166
+ The mobile app normalizes module names (e.g., `contact-center-team-inboxes` → `contact_center`), so enabling `contact_center` activates all contact center sub-modules.
167
+
111
168
  ---
112
169
 
113
170
  ## Authentication
114
171
 
115
- `sendhoney login` uses Keycloak Authorization Code + PKCE and refreshes expired access tokens automatically. On success it prints the authenticated user, resolved `orgId`, and organization data. Use `SENDHONEY_TOKEN` for CI / service accounts.
172
+ `sendhoney login` uses Keycloak Authorization Code + PKCE and refreshes expired access tokens automatically. The loopback callback completes immediately after the code exchange; workspace hydration then retries automatically with bounded backoff. On success it prints the authenticated user, resolved `orgId`, and organization data. If the workspace API is unavailable, `auth status` reports `AUTHENTICATED_WORKSPACE_PENDING` without requiring another browser action. Use `SENDHONEY_TOKEN` for CI / service accounts.
116
173
 
117
174
  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.
118
175
 
176
+ ### Troubleshooting organization resolution
177
+
178
+ If `sendhoney auth status` shows `"workspaceState": "AUTHENTICATED_WORKSPACE_PENDING"` and `"organization": { "error": "unauthorized" }` after successful login, the Keycloak access token is missing the `email` claim. The gateway requires this claim to call `/api/v1/org/me` and resolve your organization.
179
+
180
+ **Fix**: In Keycloak admin console, for the `sendhoney-cli` client in the `users` realm:
181
+ 1. Go to **Clients** → `sendhoney-cli` → **Mappers**
182
+ 2. Click **Create** → Select **User Property** mapper
183
+ 3. Configure:
184
+ - **Name**: `email`
185
+ - **User Property**: `email`
186
+ - **Token Claim Name**: `email`
187
+ - **Claim JSON Type**: `String`
188
+ - **Add to access token**: ON
189
+ - **Add to ID token**: ON
190
+ - **Add to userinfo**: ON
191
+ 4. Save and re-run `sendhoney login`
192
+
193
+ Verify the fix by decoding your access token (e.g., at jwt.io) — it should contain `"email": "your@email.com"`.
194
+
195
+ ### Troubleshooting: Modules not visible in mobile app
196
+
197
+ If a user (e.g., `graham@decoded.africa`) logs into the mobile app but doesn't see activated modules (including Contact Center):
198
+
199
+ 1. **The organization must have modules explicitly enabled** — modules are not enabled by default
200
+ 2. **Use the CLI to enable modules**:
201
+ ```bash
202
+ sendhoney resources enable-modules --org-id <ORG_ID> --modules contact_center,crm
203
+ ```
204
+ 3. **Contact Center sub-modules** (`contact-center-team-inboxes`, `contact-center-ai-assist`, `contact-center-voice-webrtc`) are all activated by enabling the parent `contact_center` slug
205
+ 4. **Mobile app caches modules for 5 minutes** — restart the app or pull-to-refresh after enabling
206
+
207
+ ### Diagnostic command
208
+
209
+ ```bash
210
+ sendhoney auth status
211
+ ```
212
+
213
+ Shows authenticated state, token expiry, user profile, organization data, and resolved `orgId` without printing tokens.
214
+
119
215
  ---
120
216
 
121
217
  ## Credentials
package/bin/sendhoney CHANGED
@@ -77,9 +77,14 @@ async function browserLogin(args, config) {
77
77
  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, redirect_uri: callback, code_verifier: verifier }).toString() })
78
78
  const tokens = await tokenResponse.json().catch(() => ({}))
79
79
  if (!tokenResponse.ok || !tokens.access_token) throw new Error(`Keycloak login failed (${tokenResponse.status}): ${tokens.error_description || tokens.error || 'no access token'}`)
80
- const session = await persistLoginSession(config, args, { authUrl, realm, clientId }, tokens)
80
+ const session = await persistLoginSession(config, args, { authUrl, realm, clientId }, tokens, { hydrate: false })
81
81
  res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(loginCallbackPage(true, session.organization || {}))
82
- clearTimeout(timeout); server.close(); resolve({ tokens, session })
82
+ clearTimeout(timeout); server.close()
83
+ stdout.write('✓ Keycloak authentication complete. Resolving workspace…\n')
84
+ const hydratedSession = await hydrateWorkspaceWithRetries(config, args, { authUrl, realm, clientId }, tokens, session)
85
+ if (hydratedSession.orgId) stdout.write(`✓ Workspace ready: ${hydratedSession.organization?.name || hydratedSession.orgId}\n`)
86
+ else stdout.write('! Authentication succeeded, but workspace resolution is still pending.\n')
87
+ resolve({ tokens, session: hydratedSession })
83
88
  } catch (failure) {
84
89
  res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(loginCallbackPage(false)); clearTimeout(timeout); server.close(); reject(failure)
85
90
  }
@@ -118,12 +123,16 @@ function organizationIdFrom(value) {
118
123
  return String(value.orgId || value.org_id || value.organizationId || value.tenantId || value.organization?.id || value.organization?.orgId || value.workspace?.organizationId || value.organizations?.[0]?.id || '').trim()
119
124
  }
120
125
 
121
- async function persistLoginSession(config, args, auth, tokens) {
126
+ const workspaceRetryDelays = [0, 1000, 2000, 4000, 8000]
127
+
128
+ function sleep(milliseconds) { return new Promise((resolve) => setTimeout(resolve, milliseconds)) }
129
+
130
+ async function persistLoginSession(config, args, auth, tokens, { hydrate = true } = {}) {
122
131
  const apiUrl = args['api-url'] || config.apiUrl || 'https://api.sendhoney.app'
123
132
  const headers = { Accept: 'application/json', Authorization: `Bearer ${tokens.access_token}` }
124
133
  const [userResponse, orgResponse] = await Promise.all([
125
134
  fetch(`${auth.authUrl}/realms/${encodeURIComponent(auth.realm)}/protocol/openid-connect/userinfo`, { headers }).catch(() => null),
126
- fetch(`${apiUrl.replace(/\/$/, '')}/api/v1/org/me`, { headers }).catch(() => null),
135
+ hydrate ? fetch(`${apiUrl.replace(/\/$/, '')}/api/v1/org/me`, { headers }).catch(() => null) : Promise.resolve(null),
127
136
  ])
128
137
  const user = userResponse ? await userResponse.json().catch(() => ({})) : {}
129
138
  let organization = orgResponse ? await orgResponse.json().catch(() => ({})) : {}
@@ -138,20 +147,37 @@ async function persistLoginSession(config, args, auth, tokens) {
138
147
  organization = { ...onboarding, ...fullOrganization, orgId }
139
148
  }
140
149
  }
141
- const session = { authenticated: true, authenticatedAt: new Date().toISOString(), user, organization, orgId: orgId || undefined }
150
+ const session = {
151
+ authenticated: true,
152
+ authenticatedAt: new Date().toISOString(),
153
+ workspaceState: orgId ? 'AUTHENTICATED_WORKSPACE_READY' : 'AUTHENTICATED_WORKSPACE_PENDING',
154
+ user,
155
+ organization,
156
+ orgId: orgId || undefined,
157
+ }
142
158
  saveConfig({
143
159
  ...config, apiUrl, authUrl: auth.authUrl, realm: auth.realm, clientId: auth.clientId,
144
160
  accessToken: tokens.access_token, refreshToken: tokens.refresh_token || config.refreshToken,
145
161
  idToken: tokens.id_token, expiresAt: Date.now() + (tokens.expires_in || 300) * 1000,
146
162
  ...(orgId ? { orgId } : {}), session,
147
163
  })
148
- return { apiUrl, orgId, user, organization }
164
+ return { apiUrl, orgId, user, organization, workspaceState: session.workspaceState }
165
+ }
166
+
167
+ async function hydrateWorkspaceWithRetries(config, args, auth, tokens, initialSession) {
168
+ let session = initialSession
169
+ for (const delay of workspaceRetryDelays) {
170
+ if (delay) await sleep(delay)
171
+ session = await persistLoginSession(config, args, auth, tokens)
172
+ if (session.orgId) return session
173
+ }
174
+ return session
149
175
  }
150
176
 
151
177
  function authStatus() {
152
178
  const config = loadConfig()
153
179
  const expiresAt = Number(config.expiresAt || 0)
154
- 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 })
180
+ json({ authenticated: Boolean(config.accessToken) && (!expiresAt || expiresAt > Date.now()), workspaceState: config.session?.workspaceState || (config.orgId ? 'AUTHENTICATED_WORKSPACE_READY' : 'AUTHENTICATED_WORKSPACE_PENDING'), expiresAt: expiresAt ? new Date(expiresAt).toISOString() : undefined, orgId: config.orgId || config.session?.orgId, user: config.session?.user, organization: config.session?.organization, configFile })
155
181
  }
156
182
  function redactCredential(value) {
157
183
  if (Array.isArray(value)) return value.map(redactCredential)
@@ -387,11 +413,17 @@ async function curated(args, subcommand) {
387
413
  const orgId = args['org-id'] || loadConfig().orgId
388
414
  if (subcommand === 'list') return request('GET', '/api/organization/modules', args)
389
415
  if (subcommand === 'current') return request('GET', '/api/v1/org/me', args)
416
+ if (subcommand === 'enable-modules') {
417
+ if (!orgId) die('resources enable-modules requires --org-id or workspace selection')
418
+ const modules = args.modules ? String(args.modules).split(',').map(s => s.trim()) : []
419
+ if (!modules.length) die('resources enable-modules requires --modules comma-separated list')
420
+ return request('PUT', '/api/organization/access-profile', { ...args, json: { tenantId: orgId, enabledModules: modules } })
421
+ }
390
422
  if (subcommand === 'endpoints') return json(catalog().filter((entry) => entry.auth !== 'service' && entry.auth !== 'admin'))
391
423
  if (subcommand === 'balance') { if (!orgId) die('billing balance requires --org-id or workspace selection'); return request('GET', `/api/billing/balance/${encodeURIComponent(orgId)}`, args) }
392
424
  if (subcommand === 'ledger') { if (!orgId) die('billing ledger requires --org-id or workspace selection'); return request('GET', `/api/billing/ledger/${encodeURIComponent(orgId)}`, args) }
393
425
  if (subcommand === 'rates') return request('GET', '/api/billing/rate', args)
394
- die('use resources list|current, endpoints list, or billing balance|ledger|rates')
426
+ die('use resources list|current|enable-modules, endpoints list, or billing balance|ledger|rates')
395
427
  }
396
428
 
397
429
  async function login(args) {
@@ -413,7 +445,8 @@ async function login(args) {
413
445
  })
414
446
  const body = await response.json().catch(() => ({}))
415
447
  if (!response.ok || !body.access_token) die(`login failed (${response.status}): ${body.error_description || body.error || 'no access token'}`)
416
- const session = await persistLoginSession(config, args, { authUrl, realm, clientId }, body)
448
+ const initialSession = await persistLoginSession(config, args, { authUrl, realm, clientId }, body, { hydrate: false })
449
+ const session = await hydrateWorkspaceWithRetries(config, args, { authUrl, realm, clientId }, body, initialSession)
417
450
  json({ ok: true, username, authenticated: true, user: session.user, organization: session.organization, orgId: session.orgId || undefined, apiUrl: session.apiUrl })
418
451
  }
419
452
 
@@ -425,7 +458,7 @@ async function main() {
425
458
  }
426
459
  if (!command && stdin.isTTY && stdout.isTTY) return interactiveMenu(args)
427
460
  if (!command || command === 'help' || args.help) {
428
- process.stdout.write('SendHoney CLI\n\nCommands: login, logout, whoami, menu, resources, endpoints, billing, api, crud, credentials, widget, 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\nwidget install [--org-id ID] [--next-app path/to/app] [--file path/to/index.html] [--widget-type chat|video|both]\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')
461
+ process.stdout.write('SendHoney CLI\n\nCommands: login, logout, whoami, menu, resources, endpoints, billing, api, crud, credentials, widget, thundercompute, release\n\n`login` opens a Keycloak PKCE browser login when no token/password is supplied.\nresources list\nresources current\nresources enable-modules --org-id ID --modules contact_center,crm\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\nwidget install [--org-id ID] [--next-app path/to/app] [--file path/to/index.html] [--widget-type chat|video|both]\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')
429
462
  return
430
463
  }
431
464
  if (command === 'login') {