@jacebenson/jsn 5.5.1 → 5.5.2-dev.174.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.
Files changed (51) hide show
  1. package/README.md +30 -2
  2. package/package.json +1 -1
  3. package/src/app.js +15 -2
  4. package/src/auth/mfa.js +85 -0
  5. package/src/cli-adapter.js +18 -4
  6. package/src/cli.js +26 -8
  7. package/src/commands/_generic.js +10 -2
  8. package/src/commands/_ticket.js +12 -4
  9. package/src/commands/approvals.js +1 -0
  10. package/src/commands/auth.js +15 -8
  11. package/src/commands/cases.js +1 -1
  12. package/src/commands/cmdb.js +1 -1
  13. package/src/commands/discover.js +1 -0
  14. package/src/commands/docs/client.js +17 -7
  15. package/src/commands/docs/community.js +4 -4
  16. package/src/commands/docs/db.js +26 -11
  17. package/src/commands/docs/docs.js +30 -13
  18. package/src/commands/docs/embed.js +2 -2
  19. package/src/commands/docs/index-worker.js +1 -1
  20. package/src/commands/docs/index.js +4 -3
  21. package/src/commands/docs/ingest.js +4 -4
  22. package/src/commands/docs/install.js +19 -17
  23. package/src/commands/docs/local.js +6 -4
  24. package/src/commands/docs/refresh.js +3 -3
  25. package/src/commands/docs/releases.js +27 -0
  26. package/src/commands/docs/search.js +3 -3
  27. package/src/commands/docs/serve.js +3 -3
  28. package/src/commands/docs/server.js +13 -10
  29. package/src/commands/docs/service-snapshot.js +3 -3
  30. package/src/commands/docs/snapshot.js +32 -11
  31. package/src/commands/docs/sync-service.js +8 -6
  32. package/src/commands/docs/sync.js +24 -15
  33. package/src/commands/flows.js +70 -5
  34. package/src/commands/knowledge.js +1 -0
  35. package/src/commands/records.js +12 -3
  36. package/src/commands/setup.js +20 -8
  37. package/src/commands/tickets.js +11 -3
  38. package/src/errors.js +23 -1
  39. package/src/flow-create.js +1237 -57
  40. package/src/flow-inspection.js +26 -2
  41. package/src/help.js +95 -21
  42. package/src/helpers.js +20 -1
  43. package/src/output.js +19 -5
  44. package/src/prompts.js +9 -0
  45. package/src/record-command-profiles.js +8 -4
  46. package/src/record-profiles.js +1 -0
  47. package/src/records-engine.js +2 -1
  48. package/src/sdk.js +157 -15
  49. package/src/setup-preferences.js +3 -3
  50. package/src/table-read-params.js +9 -0
  51. package/src/welcome.js +34 -36
package/src/sdk.js CHANGED
@@ -1,9 +1,12 @@
1
1
  // ServiceNow REST API client
2
2
 
3
3
  import { batchRead } from './sdk-batch.js';
4
+ import { tableReadParams } from './table-read-params.js';
4
5
  import { gunzipSync } from 'node:zlib';
5
6
  import { AppError, CodeAPI, CodeAuth, errAuth, errAuthHint, errAPI, errNetwork, errUsage } from './errors.js';
6
- import { getStringField } from './helpers.js';
7
+ import { canPrompt, getStringField } from './helpers.js';
8
+ import { errMfaRequired, errMfaRejected, isTerminalAuthError } from './errors.js';
9
+ import { buildMfaVerificationBody, extractMfaFormTokens, normalizeTotpCode, parseLoginStatus } from './auth/mfa.js';
7
10
  import { getAction, getStepTypes, createAction, updateAction, testAction } from './processflow-actions.js';
8
11
  import { readSkippedBaseline, revertSkippedUpdate } from './skipped-update-provider.js';
9
12
  import {
@@ -35,6 +38,28 @@ function serializeCookies(cookieJar) {
35
38
  return [...cookieJar].map(([name, value]) => `${name}=${value}`).join('; ');
36
39
  }
37
40
 
41
+ // REST resources that authenticate from the request's own headers. Every CLI
42
+ // invocation is a fresh Node process, so `_warmSession()` always pays 2-3
43
+ // sequential requests to mint UI cookies these paths never read — measured on a
44
+ // live instance, `jsn records list` spent 4 round-trips on one list. Anything
45
+ // else (script processors, GraphQL, the concourse picker, xmlhttp.do, update-set
46
+ // export/import, binary attachment uploads) keeps the session bootstrap it
47
+ // needs, and JSN_ALWAYS_WARM_SESSION=1 restores it for every path.
48
+ // Basic is the exception: normal requests must first detect any TOTP challenge
49
+ // before a pending operation can be sent. See docs/AUTH_LIFECYCLE.md.
50
+ const STATELESS_REST_PREFIXES = ['/api/now/table/', '/api/now/stats/', '/api/now/v1/batch'];
51
+
52
+ export function needsUiSession(url, { stateful = false, forceSession = false } = {}) {
53
+ if (stateful || forceSession) return true;
54
+ let pathname;
55
+ try {
56
+ pathname = new URL(url).pathname;
57
+ } catch {
58
+ return true;
59
+ }
60
+ return !STATELESS_REST_PREFIXES.some(prefix => pathname.startsWith(prefix));
61
+ }
62
+
38
63
  // Build the sys.scripts.do POST body for background script execution.
39
64
  // Extracted for testability (issue #177): maps script-mode options to the
40
65
  // form fields on ServiceNow's Script Background form. Defaults preserve the
@@ -60,12 +85,20 @@ export class SDKClient {
60
85
  this.onMutation = opts.onMutation;
61
86
  this.timeout = opts.timeout || DEFAULT_TIMEOUT;
62
87
  this.domain = opts.domain || '';
88
+ this.includeReferenceLinks = opts.includeReferenceLinks === true;
63
89
  // Expected identity, used only to reject a recovery that lands on a
64
90
  // different account. Never serialized.
65
91
  this.username = opts.username || '';
66
92
  this.oauthCookies = null;
67
93
  this._sessionPromise = null;
68
94
  this.sessionUserToken = '';
95
+ this._sessionFailure = null;
96
+ this._mfaRecognized = false;
97
+ this.canInteract = opts.canInteract || canPrompt;
98
+ this.promptMfaCode = opts.promptMfaCode || (async config => {
99
+ const { mfaCode } = await import('./prompts.js');
100
+ return mfaCode(config);
101
+ });
69
102
  // Session state is versioned so concurrent requests can tell "my headers
70
103
  // are from the session that was just replaced" apart from "this rejection
71
104
  // is new". One recovery is in flight per client at a time.
@@ -73,7 +106,7 @@ export class SDKClient {
73
106
  this._recoveryPromise = null;
74
107
  }
75
108
 
76
- async _setAuth(req, { skipOAuthSession = false } = {}) {
109
+ async _setAuth(req, { skipOAuthSession = false, basicSession = false } = {}) {
77
110
  if (!this.authProvider) {
78
111
  throw errAuth('No authentication configured');
79
112
  }
@@ -89,14 +122,21 @@ export class SDKClient {
89
122
  }
90
123
  switch (creds.auth_method) {
91
124
  case 'basic':
92
- if (!skipOAuthSession) {
125
+ // Basic credentials may demand a login challenge even on stateless
126
+ // REST. Only explicit internal bootstrap requests bypass this gate.
127
+ if (this._sessionFailure) throw this._sessionFailure;
128
+ if (!skipOAuthSession || basicSession || this._mfaRecognized) {
93
129
  const cookies = await this._warmSession();
94
- if (cookies) {
130
+ // Stateless REST historically uses Basic. A non-challenge UI
131
+ // bootstrap (even one minting guest cookies/tokens) must not replace
132
+ // working REST credentials. Only verified MFA overrides that policy.
133
+ if (cookies && (!skipOAuthSession || this._mfaRecognized)) {
95
134
  req.headers.set('Cookie', cookies);
96
135
  if (this.sessionUserToken) req.headers.set('X-UserToken', this.sessionUserToken);
97
136
  break;
98
137
  }
99
138
  }
139
+ if (this._mfaRecognized) throw errMfaRejected();
100
140
  req.headers.set('Authorization', 'Basic ' + Buffer.from(`${creds.username}:${creds.password}`).toString('base64'));
101
141
  break;
102
142
  case 'token':
@@ -140,7 +180,7 @@ export class SDKClient {
140
180
  return value;
141
181
  });
142
182
  } catch (error) {
143
- if (event) await this._reportMutation({ ...event, outcome: error.status >= 400 && error.status < 500 && error.status !== 408
183
+ if (event && !error?.notSent && error?.name !== 'PromptCancelled') await this._reportMutation({ ...event, outcome: error.status >= 400 && error.status < 500 && error.status !== 408
144
184
  ? 'failed' : 'unknown', http_status: error.status || null });
145
185
  throw error;
146
186
  }
@@ -171,12 +211,20 @@ export class SDKClient {
171
211
  // Headers for this attempt belong to the session as it is right now.
172
212
  const generation = this._sessionGeneration;
173
213
  const controller = new AbortController();
174
- const timer = setTimeout(() => controller.abort(), timeout);
214
+ let timer;
175
215
  let rejection;
176
216
  try {
177
217
  const req = new Request(endpoint, { ...opts, signal: controller.signal });
178
218
  if (prepare) prepare(req);
179
- await this._setAuth(req, { skipOAuthSession });
219
+ // Header-authenticated REST skips UI warming for OAuth/token/GCK.
220
+ // Basic must still check for TOTP before dispatch; internal bootstrap
221
+ // requests explicitly bypass that check to avoid recursion.
222
+ const skipSession = skipOAuthSession || !needsUiSession(endpoint, {
223
+ stateful,
224
+ forceSession: process.env.JSN_ALWAYS_WARM_SESSION === '1',
225
+ });
226
+ await this._setAuth(req, { skipOAuthSession: skipSession, basicSession: !skipOAuthSession });
227
+ timer = setTimeout(() => controller.abort(), timeout);
180
228
  const response = await fetch(req);
181
229
  if (!skipOAuthSession && this.recovery) {
182
230
  // A 401 is definitive; only then is the body sniffed for a login
@@ -348,7 +396,8 @@ export class SDKClient {
348
396
 
349
397
  // Public raw-response seam for callers that must inspect non-2xx bodies.
350
398
  async fetchResponse(endpoint, opts = {}) {
351
- return this._fetchWithAuth(endpoint, opts);
399
+ const { timeout = this.timeout, stateful = false, ...requestOptions } = opts;
400
+ return this._withAuthenticatedRequest(endpoint, requestOptions, { timeout, stateful });
352
401
  }
353
402
 
354
403
  async rawRequest(endpoint, opts = {}) {
@@ -380,7 +429,7 @@ export class SDKClient {
380
429
  }
381
430
 
382
431
  async list(table, params = {}, opts = {}) {
383
- const query = new URLSearchParams(params).toString();
432
+ const query = tableReadParams(params, this).toString();
384
433
  const endpoint = `${this.baseURL}/api/now/table/${table}${query ? '?' + query : ''}`;
385
434
  const result = await this.request(endpoint, { method: 'GET', ...opts });
386
435
  return result?.result || [];
@@ -391,7 +440,7 @@ export class SDKClient {
391
440
  // table. Capture paths use this so an unexpected body becomes an unavailable
392
441
  // source instead of a complete-looking empty inventory.
393
442
  async listStrict(table, params = {}, opts = {}) {
394
- const query = new URLSearchParams(params).toString();
443
+ const query = tableReadParams(params, this).toString();
395
444
  const endpoint = `${this.baseURL}/api/now/table/${table}${query ? '?' + query : ''}`;
396
445
  const response = await this.request(endpoint, { method: 'GET', ...opts });
397
446
  if (!response || typeof response !== 'object' || !Array.isArray(response.result)) {
@@ -1159,9 +1208,13 @@ export class SDKClient {
1159
1208
  }
1160
1209
 
1161
1210
  async _warmSession() {
1211
+ if (this._sessionFailure) throw this._sessionFailure;
1162
1212
  if (this.oauthCookies) return this.oauthCookies;
1163
1213
  if (!this._sessionPromise) {
1164
- this._sessionPromise = this._initializeSession().finally(() => {
1214
+ this._sessionPromise = this._initializeSession().catch(error => {
1215
+ if (isTerminalAuthError(error)) this._sessionFailure = error;
1216
+ throw error;
1217
+ }).finally(() => {
1165
1218
  this._sessionPromise = null;
1166
1219
  });
1167
1220
  }
@@ -1169,6 +1222,7 @@ export class SDKClient {
1169
1222
  }
1170
1223
 
1171
1224
  async _initializeSession() {
1225
+ let challenged = false;
1172
1226
  try {
1173
1227
  const creds = await this.authProvider.getCredentials();
1174
1228
  if (creds.auth_method === 'oauth') {
@@ -1192,7 +1246,7 @@ export class SDKClient {
1192
1246
  }
1193
1247
  const endpoint = `${this.baseURL}/angular.do`;
1194
1248
  const cookieJar = new Map();
1195
- const loginResp = await this._fetchWithAuth(`${endpoint}?sysparm_type=view_form.login`, {
1249
+ const loginStatus = await this._mfaExchange('/angular.do?sysparm_type=view_form.login', {
1196
1250
  method: 'POST',
1197
1251
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1198
1252
  body: new URLSearchParams({
@@ -1201,8 +1255,17 @@ export class SDKClient {
1201
1255
  user_name: creds.username,
1202
1256
  user_password: creds.password,
1203
1257
  }).toString(),
1204
- });
1205
- collectSetCookies(cookieJar, loginResp);
1258
+ }, cookieJar, async response => parseLoginStatus(await response.text()));
1259
+ challenged = loginStatus?.status === 'mfa_code_required';
1260
+ if (challenged) {
1261
+ this._mfaRecognized = true;
1262
+ const token = await this._completeMfaChallenge(cookieJar, creds.username);
1263
+ if (!serializeCookies(cookieJar)) throw errMfaRejected();
1264
+ this.sessionUserToken = token;
1265
+ this.oauthCookies = serializeCookies(cookieJar);
1266
+ return this.oauthCookies;
1267
+ }
1268
+ if (this._mfaRecognized) throw errMfaRejected();
1206
1269
  const refreshResp = await this._fetchWithAuth(`${endpoint}?sysparm_type=get_user`, {
1207
1270
  method: 'POST',
1208
1271
  headers: serializeCookies(cookieJar) ? { Cookie: serializeCookies(cookieJar) } : {},
@@ -1212,11 +1275,90 @@ export class SDKClient {
1212
1275
  const cookies = serializeCookies(cookieJar);
1213
1276
  this.oauthCookies = cookies;
1214
1277
  return cookies;
1215
- } catch {
1278
+ } catch (error) {
1279
+ if (challenged || this._mfaRecognized) throw isTerminalAuthError(error) ? error : errMfaRejected();
1216
1280
  return '';
1217
1281
  }
1218
1282
  }
1219
1283
 
1284
+ // Each network exchange, including its body, has a deadline independent of
1285
+ // human code entry. The race also bounds streams that do not honor abort.
1286
+ async _mfaExchange(path, options, cookieJar, consume = response => response) {
1287
+ const controller = new AbortController();
1288
+ let timer;
1289
+ const deadline = new Promise((resolve, reject) => {
1290
+ timer = setTimeout(() => {
1291
+ controller.abort();
1292
+ reject(errMfaRejected());
1293
+ }, this.timeout);
1294
+ });
1295
+ try {
1296
+ return await Promise.race([deadline, (async () => {
1297
+ const response = await fetch(new Request(`${this.baseURL}${path}`, {
1298
+ ...options, redirect: 'manual', signal: controller.signal,
1299
+ headers: { ...options.headers, Cookie: serializeCookies(cookieJar) },
1300
+ }));
1301
+ collectSetCookies(cookieJar, response);
1302
+ try {
1303
+ return await consume(response);
1304
+ } finally {
1305
+ if (!response.bodyUsed) await response.body?.cancel?.();
1306
+ }
1307
+ })()]);
1308
+ } finally {
1309
+ clearTimeout(timer);
1310
+ }
1311
+ }
1312
+
1313
+ async _completeMfaChallenge(cookieJar, username) {
1314
+ if (!this.canInteract()) throw errMfaRequired();
1315
+ for (let attempt = 1; attempt <= 3; attempt++) {
1316
+ const code = normalizeTotpCode(await this.promptMfaCode({
1317
+ message: attempt === 1 ? 'Enter the 6-digit authenticator code:' : `Code rejected. Enter a new code (${attempt}/3):`,
1318
+ }));
1319
+ if (!code) continue;
1320
+ const tokens = await this._mfaExchange('/validate_multifactor_auth_code.do', { method: 'GET' }, cookieJar, async response => {
1321
+ if (!response.ok) throw errMfaRejected();
1322
+ return extractMfaFormTokens(await response.text());
1323
+ });
1324
+ if (!tokens.csrf || !tokens.processNonce) throw errMfaRejected();
1325
+ const accepted = await this._mfaExchange('/validate_mfa_code.do', {
1326
+ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1327
+ body: buildMfaVerificationBody({ ...tokens, code }).toString(),
1328
+ }, cookieJar, response => {
1329
+ if (response.headers.get('x-mfa_token') === 'invalid') return false;
1330
+ const location = response.headers.get('location') || '';
1331
+ const destination = new URL(location, this.baseURL);
1332
+ if (response.status !== 302 || !location || destination.origin !== new URL(this.baseURL).origin
1333
+ || /login|logout|expired|multifactor|validate_mfa/i.test(destination.pathname)) throw errMfaRejected();
1334
+ return true;
1335
+ });
1336
+ if (!accepted) continue;
1337
+ const token = await this._mfaExchange('/angular.do?sysparm_type=get_user', { method: 'POST' }, cookieJar, async response => {
1338
+ const body = await response.text();
1339
+ const token = response.headers.get('x-usertoken-response');
1340
+ if (!response.ok || !token || /\bguest\b|login\.do|session_expired/i.test(body)) throw errMfaRejected();
1341
+ return token;
1342
+ });
1343
+ // A token is not identity proof. Use the same cookie/CSRF session and
1344
+ // compare the authenticated current user with the selected Basic user.
1345
+ const params = new URLSearchParams({ sysparm_query: 'user_name=javascript:gs.getUserName()',
1346
+ sysparm_fields: 'user_name', sysparm_limit: '1', sysparm_display_value: 'false' });
1347
+ await this._mfaExchange(`/api/now/table/sys_user?${params}`, {
1348
+ method: 'GET', headers: { Accept: 'application/json', 'X-UserToken': token },
1349
+ }, cookieJar, async response => {
1350
+ if (!response.ok) throw errMfaRejected();
1351
+ const payload = await response.json();
1352
+ const field = Array.isArray(payload?.result) && payload.result.length === 1 ? payload.result[0]?.user_name : null;
1353
+ const identity = typeof field === 'object' && field ? field.value : field;
1354
+ if (!username || identity !== username || identity === 'guest'
1355
+ || (this.username && identity !== this.username)) throw errMfaRejected();
1356
+ });
1357
+ return token;
1358
+ }
1359
+ throw errMfaRejected();
1360
+ }
1361
+
1220
1362
  async _getScriptsPageCSRF(cookies) {
1221
1363
  const endpoint = `${this.baseURL}/sys.scripts.do`;
1222
1364
  const html = await this.rawRequest(endpoint, {
@@ -26,9 +26,9 @@ export async function askConnectionPreferences(defaults, prompts = { confirm })
26
26
 
27
27
  export async function chooseConnectionPreferences(config, flags = {}, prompts = { confirm }) {
28
28
  const defaults = connectionPreferences(config, {}, flags);
29
- const summary = `Read-only: ${defaults.read_only ? 'yes' : 'no'} · Delete confirmations: ${defaults.skip_confirmations ? 'off' : 'on'} · Result totals: ${defaults.include_counts ? 'on' : 'off'}`;
30
- if (await prompts.confirm({ message: `${summary}\nUse these defaults for this connection?`, default: true })) return defaults;
31
- return askConnectionPreferences(defaults, prompts);
29
+ const summary = `${defaults.read_only ? 'read-only' : 'writes allowed'} · delete confirmations ${defaults.skip_confirmations ? 'off' : 'on'} · result totals ${defaults.include_counts ? 'on' : 'off'}`;
30
+ if (await prompts.confirm({ message: `Accept defaults? ${summary}`, default: true })) return defaults;
31
+ return connectionPreferences(config, await askConnectionPreferences(defaults, prompts), flags);
32
32
  }
33
33
 
34
34
  export async function configureDocumentation(config, prompts = { input, confirm }) {
@@ -0,0 +1,9 @@
1
+ // Table API reads omit reference URLs by default. Explicit provider parameters
2
+ // take precedence, including inspection callers that require a particular shape.
3
+ export function tableReadParams(params, { includeReferenceLinks = false } = {}) {
4
+ const query = new URLSearchParams(params);
5
+ if (!includeReferenceLinks && !query.has('sysparm_exclude_reference_link')) {
6
+ query.set('sysparm_exclude_reference_link', 'true');
7
+ }
8
+ return query;
9
+ }
package/src/welcome.js CHANGED
@@ -1,8 +1,7 @@
1
1
  // First-run welcome (issue #387).
2
2
  //
3
- // A brand-new install that runs bare `jsn` gets grouped help, which assumes
4
- // the reader already knows what to do with it. This adds a short orientation
5
- // above that help, exactly once, only when a human is reading it.
3
+ // A brand-new install gets a compact front door instead of the command catalog,
4
+ // exactly once, only when a human is reading it.
6
5
  //
7
6
  // Invariants (see docs/DECISIONS.md):
8
7
  // - at most once: a marker file in the XDG config dir records that the note
@@ -10,7 +9,7 @@
10
9
  // both print it;
11
10
  // - human terminal only: no --json/--quiet/--csv/--markdown/--get, no piped
12
11
  // output, no agent/CI environments;
13
- // - never instead of help: the grouped help below it is unchanged;
12
+ // - explicit help stays comprehensive; the first-run front door stands alone;
14
13
  // - never an instance or auth operation: the note only points at local and
15
14
  // interactive commands, so it cannot block setup or require credentials;
16
15
  // - nothing on this path reaches the network, prompts, or reads an instance;
@@ -39,21 +38,10 @@ const MIN_WIDTH = 24;
39
38
 
40
39
  const HUMAN_FORMATS = new Set(['', 'auto', 'styled']);
41
40
 
42
- /**
43
- * What a first run actually needs next. Every command here exists, is visible
44
- * to a profile-less install, and works without an instance:
45
- * - `jsn setup` opens the interactive add-connection wizard (and defaults);
46
- * - `jsn auth login <instance>` adds one connection without the wizard;
47
- * - `jsn --help` is the grouped command list this note sits above;
48
- * - `jsn docs search` queries ServiceNow documentation, not an instance;
49
- * - `jsn skill install` writes the bundled agent skill from local files.
50
- */
41
+ /** One obvious next action, plus secondary discovery; no command catalog. */
51
42
  const STEPS = [
52
- { command: 'jsn setup', detail: 'first connection + defaults, interactive' },
53
- { command: 'jsn auth login <instance>', detail: 'one connection, scriptable, no wizard' },
43
+ { command: 'jsn setup', detail: 'connect to ServiceNow' },
54
44
  { command: 'jsn --help', detail: 'every command and flag' },
55
- { command: 'jsn docs search <query>', detail: 'search ServiceNow documentation' },
56
- { command: 'jsn skill install', detail: 'install the jsn skill for your AI agent' },
57
45
  ];
58
46
 
59
47
  /**
@@ -128,12 +116,12 @@ function configLabels(env, configDir) {
128
116
  * @param {number} width
129
117
  * @returns {string[]}
130
118
  */
131
- function renderSteps(width) {
132
- const commandWidth = Math.max(...STEPS.map((step) => step.command.length));
119
+ function renderSteps(width, steps = STEPS) {
120
+ const commandWidth = Math.max(...steps.map((step) => step.command.length));
133
121
  const alignedColumn = 4 + commandWidth + 2;
134
- const oneLine = STEPS.every((step) => alignedColumn + step.detail.length <= width);
122
+ const oneLine = steps.every((step) => alignedColumn + step.detail.length <= width);
135
123
  const lines = [];
136
- for (const step of STEPS) {
124
+ for (const step of steps) {
137
125
  if (oneLine) {
138
126
  lines.push(` ${step.command.padEnd(commandWidth)} ${step.detail}`);
139
127
  continue;
@@ -145,8 +133,8 @@ function renderSteps(width) {
145
133
  }
146
134
 
147
135
  /**
148
- * The orientation text. Kept short: it must fit above the grouped help without
149
- * pushing it off the first screen, and it must stay inside 12 lines at 80
136
+ * The orientation text. Kept short: it stands alone on the first screen
137
+ * instead of the command catalog, and stays inside 12 lines at 80
150
138
  * columns.
151
139
  *
152
140
  * Everything shown is derived from local state: the version comes from the
@@ -177,11 +165,8 @@ export function welcomeLines({
177
165
  ...wrapText(title, width),
178
166
  ...wrapText(configLabel, width),
179
167
  '',
180
- ' Next steps',
168
+ ' Get started',
181
169
  ...renderSteps(width),
182
- '',
183
- ...wrapText('Nothing above needs an instance. jsn asks for credentials only when needed.', width),
184
- ...wrapText('Prints once. Hide it with JSN_NO_WELCOME=1. Update with jsn upgrade.', width),
185
170
  ];
186
171
  }
187
172
 
@@ -304,16 +289,29 @@ export function markWelcomeSeen(configDir = globalConfigDir()) {
304
289
  }
305
290
 
306
291
  /**
307
- * Show the welcome (above the caller's own help output) when this is a first
308
- * run, then record it. Returns the text that was shown, or '' when nothing was.
309
- *
310
- * The marker is claimed before anything is printed, so an interrupted run
311
- * (Ctrl-C) can leave the note unshown but never printed twice.
312
- *
313
- * @param {object} [opts] — same inputs as shouldShowWelcome, plus the
314
- * welcomeText inputs (columns, version)
315
- * @returns {string}
292
+ * Every human bare invocation gets a local-only home. The legacy welcome
293
+ * marker controls only the greeting, never whether the catalog is selected.
316
294
  */
295
+ export function maybeShowHome({ argv = {}, requestedFormat = '', cfg = {}, env = process.env,
296
+ configDir = globalConfigDir(), interactive = canPrompt(), columns = process.stdout?.columns } = {}) {
297
+ if (env.JSN_NO_WELCOME === '1' || !interactive || argv.get || !HUMAN_FORMATS.has(requestedFormat || '')) return '';
298
+ const width = layoutWidth(columns);
299
+ const selected = cfg.activeProfile || cfg.defaultProfile;
300
+ const profile = selected && cfg.profiles?.[selected] ? selected : undefined;
301
+ const steps = profile ? [
302
+ { command: 'jsn incidents list', detail: 'browse incidents' },
303
+ { command: 'jsn setup', detail: 'manage connections' },
304
+ { command: 'jsn --help', detail: 'every command and flag' },
305
+ ] : STEPS;
306
+ const greeting = shouldShowWelcome({ argv, requestedFormat, cfg, env, configDir, interactive })
307
+ && claimWelcome(configDir) !== 'taken';
308
+ const heading = profile ? `Profile: ${profile}` : greeting ? 'Welcome to jsn' : 'Get started';
309
+ const text = [...wrapText(heading, width), '', ...renderSteps(width, steps)].join('\n');
310
+ process.stdout.write(`${text}\n\n`);
311
+ return text;
312
+ }
313
+
314
+ /** Legacy once-only note API; bare CLI discovery uses maybeShowHome. */
317
315
  export function maybeShowWelcome(opts = {}) {
318
316
  if (!shouldShowWelcome(opts)) return '';
319
317
  const configDir = opts.configDir || globalConfigDir();