@jacebenson/jsn 5.5.9 → 5.5.10-dev.230.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.9",
3
+ "version": "5.5.10-dev.230.1",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -18,6 +18,9 @@ Discover commands with `jsn --help`, `jsn discover "search words"`, and
18
18
  approval before using eval; avoid bypassing ServiceNow protections.
19
19
  - Honor delete confirmations. Get approval for destructive work and Global +
20
20
  Default mutations; use `--force` only for the approved operation.
21
+ - Deleting several records by filter is `jsn records delete-many`, not `eval`.
22
+ It previews without `--yes`, and a real delete requires the exact
23
+ `--expect-count` from that preview.
21
24
 
22
25
  For development:
23
26
 
@@ -62,6 +62,9 @@ const PROBE_FAILURES = {
62
62
  message: 'The authenticated probe could not be initialized for this profile.',
63
63
  hint: 'Check the profile configuration and run: jsn auth status again',
64
64
  },
65
+ storage_blocked: {
66
+ message: 'Credential storage is blocked for this profile; the authenticated probe was not attempted.',
67
+ },
65
68
  };
66
69
 
67
70
  const PROBE_CLASSIFICATIONS = {
@@ -70,6 +73,7 @@ const PROBE_CLASSIFICATIONS = {
70
73
  malformed_credentials: 'malformed', permission_denied: 'permission_denied', unauthorized: 'unauthorized',
71
74
  network: 'network_error', unknown: 'unknown',
72
75
  missing_instance: 'unavailable', sdk_construction_failed: 'configuration_error',
76
+ storage_blocked: 'storage_blocked',
73
77
  };
74
78
 
75
79
  export function probeFailure(code, status = 'failed') {
@@ -4,7 +4,7 @@ import crypto from 'node:crypto';
4
4
  import { isDeepStrictEqual } from 'node:util';
5
5
  import { execFileSync } from 'node:child_process';
6
6
  import { globalConfigDir } from '../config.js';
7
- import { windowsCredentialOperation, legacyWindowsKey } from './windows-credential-store.js';
7
+ import { windowsCredentialOperation, legacyWindowsKey, STORAGE_CLASSIFICATIONS, STORAGE_RECOVERY } from './windows-credential-store.js';
8
8
 
9
9
  // ─── Credential key helpers ───
10
10
 
@@ -41,22 +41,62 @@ const KEYRING_ATTR_USERNAME = 'username';
41
41
  // Only this process environment can authorize portable plaintext storage.
42
42
  const PLAINTEXT_ENV = 'JSN_ALLOW_PLAINTEXT_CREDENTIAL_STORAGE';
43
43
  function plaintextAllowed() { return process.env[PLAINTEXT_ENV] === '1'; }
44
- function storageError(message) {
44
+ function storageError(message, classification = 'secure_storage_unavailable') {
45
+ const safe = STORAGE_CLASSIFICATIONS.includes(classification) ? classification : 'secure_storage_unavailable';
45
46
  const error = new Error(message);
46
47
  error.code = 'credential_storage_error';
48
+ error.classification = safe;
49
+ error.recovery = STORAGE_RECOVERY[safe];
47
50
  return error;
48
51
  }
52
+ /**
53
+ * The plaintext warning belongs to the moment a credential is stored, not to
54
+ * every command that reads one back.
55
+ *
56
+ * It used to fire on the read path too, which meant once per process, which
57
+ * means once per command — every read, list, or search printed it on stderr.
58
+ * That is noise in a terminal and permanently in an agent transcript, and it
59
+ * told nobody anything they could act on at that moment. The storage mode is
60
+ * reported instead by `jsn auth status`, and the warning is emitted when the
61
+ * choice is actually made (login, setup, token save).
62
+ */
49
63
  let plaintextWarningShown = false;
50
64
  function warnPlaintext() {
51
65
  if (plaintextWarningShown) return;
52
66
  plaintextWarningShown = true;
53
67
  process.stderr.write('Warning: plaintext credential storage explicitly enabled for this process; credentials are portable and backups can expose them.\n');
54
68
  }
55
- function refusal() {
69
+ function refusal(classification = 'secure_storage_unavailable') {
56
70
  const repair = process.platform === 'win32'
57
71
  ? 'Windows Credential Manager requires Windows PowerShell 5.1 or PowerShell 7+ with FullLanguage/Add-Type and native API access allowed by policy.'
58
72
  : 'Unlock/install secret-tool and retry.';
59
- return storageError(`Secure credential storage unavailable or readback failed. ${repair} Existing plaintext credentials are preserved; to use or migrate them on a headless host, explicitly set ${PLAINTEXT_ENV}=1 for this process. Never commit or share credential files.`);
73
+ return storageError(`Secure credential storage unavailable or readback failed. ${repair} Existing plaintext credentials are preserved. No plaintext fallback is enabled automatically.`, classification);
74
+ }
75
+
76
+ /**
77
+ * A stored plaintext file is not a storage failure and must never be reported
78
+ * as one: the secure backend may be perfectly healthy. Reading it needs the
79
+ * exact process-local opt-in, which a status --local read never has, so the
80
+ * file is left untouched and the recovery is a fresh verified login.
81
+ */
82
+ function plaintextBlocked() {
83
+ return storageError(
84
+ 'Existing plaintext credentials are preserved; this process cannot read them and no plaintext fallback is enabled automatically. ' +
85
+ STORAGE_RECOVERY.plaintext_requires_recovery,
86
+ 'plaintext_requires_recovery',
87
+ );
88
+ }
89
+ function readbackFailure() {
90
+ return storageError(
91
+ 'Secure credential storage unavailable or readback failed. The secure entry could not be verified after writing. Existing plaintext credentials are preserved. No plaintext fallback is enabled automatically.',
92
+ 'secure_readback_failed',
93
+ );
94
+ }
95
+ function malformedSecureEntry() {
96
+ return storageError(
97
+ `Stored secure credential entry is malformed and cannot be used. ${STORAGE_RECOVERY.malformed_secure_entry}`,
98
+ 'malformed_secure_entry',
99
+ );
60
100
  }
61
101
 
62
102
  // Validate broad ancestors without chmod: only the leaf secret directory must
@@ -75,7 +115,7 @@ function checkPath(target, directory, privateMode = false) {
75
115
  ((stat.mode & 0o022) !== 0 && !(directory && stat.uid === 0 && (stat.mode & 0o1000)))))) {
76
116
  throw storageError(posix
77
117
  ? 'Unsafe credential/PKCE path: require owned regular 0600 files and private 0700 secret directories; reject symlinks, links and writable ancestors. Repair or move the path manually, then retry.'
78
- : 'Unsafe credential/PKCE path: require regular files/directories without symlinks, junctions or hard links. Windows ACL privacy must be managed separately.');
118
+ : 'Unsafe credential/PKCE path: require regular files/directories without symlinks, junctions or hard links. Windows ACL privacy must be managed separately.', 'storage_path_unsafe');
79
119
  }
80
120
  return stat;
81
121
  }
@@ -90,7 +130,7 @@ export function privateStateDirectories(dir, pathAPI = path) {
90
130
  }
91
131
  function privateStatePath(kind, key, create = false) {
92
132
  if (!['credentials', 'pkce'].includes(kind) || !/^[a-zA-Z0-9._@-]+$/.test(key) || key === '.' || key === '..') {
93
- throw storageError('Invalid credential/PKCE storage key.');
133
+ throw storageError('Invalid credential/PKCE storage key.', 'invalid_storage_key');
94
134
  }
95
135
  // Resolve once so traversal, leaf comparison and IO share the same path,
96
136
  // including when the configured XDG directory is relative.
@@ -116,12 +156,12 @@ export function readPrivateState(kind, key) {
116
156
  fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
117
157
  const before = checkPath(file, false, true);
118
158
  const opened = fs.fstatSync(fd);
119
- if (before.ino !== opened.ino || before.dev !== opened.dev) throw storageError('Credential/PKCE path changed while opening.');
159
+ if (before.ino !== opened.ino || before.dev !== opened.dev) throw storageError('Credential/PKCE path changed while opening.', 'storage_path_unsafe');
120
160
  return JSON.parse(fs.readFileSync(fd, 'utf8'));
121
161
  } catch (error) {
122
162
  if (error.code === 'ENOENT') return null;
123
163
  if (error.code === 'credential_storage_error') throw error;
124
- throw storageError('Unable to read credential/PKCE state safely; original file preserved.');
164
+ throw storageError('Unable to read credential/PKCE state safely; original file preserved.', 'storage_path_unsafe');
125
165
  } finally { if (fd !== undefined) fs.closeSync(fd); }
126
166
  }
127
167
  export function writePrivateState(kind, key, value) {
@@ -150,36 +190,42 @@ export function removePrivateState(kind, key) {
150
190
  // ─── Keyring via secret-tool (libsecret, same backend as Go's go-keyring) ───
151
191
 
152
192
  function keyringLookup(key, legacyKey) {
193
+ let result;
153
194
  try {
154
195
  // execFileSync with an arg array — no shell, so `key` can never
155
196
  // break out into command injection (issue #143 finding #2).
156
- const result = process.platform === 'win32'
197
+ result = process.platform === 'win32'
157
198
  ? (windowsCredentialOperation('read', key) ?? (legacyKey ? windowsCredentialOperation('read', legacyKey) : null))
158
199
  : execFileSync(
159
200
  'secret-tool',
160
201
  ['lookup', KEYRING_ATTR_SERVICE, KEYRING_SERVICE, KEYRING_ATTR_USERNAME, key],
161
202
  { stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf-8' }
162
203
  );
163
- const trimmed = result?.trim();
164
- if (!trimmed) return null;
165
- const parsed = JSON.parse(trimmed);
166
- // Spread all fields from keyring first, then normalize known fields
167
- // so username, password, and other extras are preserved.
168
- return {
169
- ...parsed,
170
- auth_method: parsed.auth_method || 'oauth',
171
- access_token: parsed.access_token || parsed.AccessToken || '',
172
- refresh_token: parsed.refresh_token || parsed.RefreshToken || '',
173
- expires_at: parsed.expires_at || parsed.ExpiresAt || 0,
174
- created_at: parsed.created_at || parsed.CreatedAt || 0,
175
- auth_source: parsed.auth_method === 'gck' ? 'gck' : 'keyring',
176
- };
177
204
  } catch (error) {
205
+ // Preserve the existing process-local plaintext opt-in. Without it, a
206
+ // Windows backend failure is a refusal, not a missing entry.
178
207
  if (process.platform === 'win32' && !plaintextAllowed()) {
179
- throw error.code === 'credential_storage_error' ? error : refusal();
208
+ throw error?.code === 'credential_storage_error' ? error : refusal();
180
209
  }
181
210
  return null;
182
211
  }
212
+ const trimmed = typeof result === 'string' ? result.trim() : result;
213
+ if (!trimmed) return null;
214
+ let parsed;
215
+ try { parsed = JSON.parse(trimmed); }
216
+ catch { throw malformedSecureEntry(); }
217
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw malformedSecureEntry();
218
+ // Spread all fields from keyring first, then normalize known fields
219
+ // so username, password, and other extras are preserved.
220
+ return {
221
+ ...parsed,
222
+ auth_method: parsed.auth_method || 'oauth',
223
+ access_token: parsed.access_token || parsed.AccessToken || '',
224
+ refresh_token: parsed.refresh_token || parsed.RefreshToken || '',
225
+ expires_at: parsed.expires_at || parsed.ExpiresAt || 0,
226
+ created_at: parsed.created_at || parsed.CreatedAt || 0,
227
+ auth_source: parsed.auth_method === 'gck' ? 'gck' : 'keyring',
228
+ };
183
229
  }
184
230
 
185
231
  function keyringStore(key, creds) {
@@ -196,20 +242,27 @@ function keyringStore(key, creds) {
196
242
  }
197
243
  }
198
244
 
245
+ // Returns 'ok', 'readback_failed' (backend accepted the write but the exact
246
+ // value did not come back) or 'unavailable' (no secure write happened).
199
247
  function storeVerified(key, creds) {
200
248
  if (process.platform === 'win32') {
201
249
  const value = JSON.stringify(creds);
202
250
  windowsCredentialOperation('write', key, value);
203
- const readback = windowsCredentialOperation('read', key);
204
- return isDeepStrictEqual(JSON.parse(readback), JSON.parse(value));
251
+ let readback;
252
+ try { readback = windowsCredentialOperation('read', key); }
253
+ catch (error) { throw error.code === 'credential_storage_error' ? error : refusal(); }
254
+ let parsed;
255
+ try { parsed = typeof readback === 'string' ? JSON.parse(readback) : null; }
256
+ catch { parsed = null; }
257
+ return parsed && isDeepStrictEqual(parsed, JSON.parse(value)) ? 'ok' : 'readback_failed';
205
258
  }
206
- if (!keyringStore(key, creds)) return false;
259
+ if (!keyringStore(key, creds)) return 'unavailable';
207
260
  try {
208
261
  const value = execFileSync('secret-tool',
209
262
  ['lookup', KEYRING_ATTR_SERVICE, KEYRING_SERVICE, KEYRING_ATTR_USERNAME, key],
210
263
  { stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf8' });
211
- return isDeepStrictEqual(JSON.parse(value), JSON.parse(JSON.stringify(creds)));
212
- } catch { return false; }
264
+ return isDeepStrictEqual(JSON.parse(value), JSON.parse(JSON.stringify(creds))) ? 'ok' : 'readback_failed';
265
+ } catch { return 'readback_failed'; }
213
266
  }
214
267
 
215
268
  function keyringDelete(key) {
@@ -248,10 +301,10 @@ export function loadCredentials(instance, username, injectedStore) {
248
301
  }
249
302
  const file = privateStatePath('credentials', key);
250
303
  if (!fs.existsSync(file)) return null;
251
- // Reads (including local status) never persist or migrate credentials. A
252
- // subsequent explicit login/save or token refresh performs verified retirement.
253
- if (!plaintextAllowed()) throw refusal();
254
- warnPlaintext();
304
+ // Reads (including local status) never persist, migrate, or open a legacy
305
+ // plaintext file. A subsequent explicit login/save performs verified
306
+ // retirement; the blocked file keeps its exact bytes until then.
307
+ if (!plaintextAllowed()) throw plaintextBlocked();
255
308
  const creds = readPrivateState('credentials', key);
256
309
  return creds ? { ...creds, auth_source: 'file' } : null;
257
310
  }
@@ -268,20 +321,38 @@ export function saveCredentials(instance, creds, username, injectedStore) {
268
321
  const key = username ? credKey(instance, username) : credKey(instance);
269
322
  // Stamp last_seen on every credential save
270
323
  creds.last_seen = creds.last_seen || Math.floor(Date.now() / 1000);
271
- let verified = false;
324
+ let status = 'unavailable';
272
325
  let secureFailure;
273
- try { verified = storeVerified(key, creds); }
326
+ try { status = storeVerified(key, creds); }
274
327
  catch (error) { secureFailure = error.code === 'credential_storage_error' ? error : refusal(); }
275
- if (verified) {
328
+ if (status === 'ok') {
276
329
  // Retire only this identity, and only after exact secure-store readback.
277
330
  removePrivateState('credentials', key);
278
331
  return;
279
332
  }
280
- if (!plaintextAllowed()) throw secureFailure || refusal();
281
- warnPlaintext();
333
+ if (!plaintextAllowed()) throw secureFailure || (status === 'readback_failed' ? readbackFailure() : refusal());
334
+ // Re-stamping last_seen after a successful call is bookkeeping, not a storage
335
+ // decision. Warning on it put the message on every command again, which is
336
+ // what this change is meant to stop; only a change to the secret material
337
+ // (a real login or token refresh) is worth the warning.
338
+ if (materialChanged(key, creds)) warnPlaintext();
282
339
  writePrivateState('credentials', key, creds);
283
340
  }
284
341
 
342
+ /** True when the incoming credential material differs from what is on disk. */
343
+ function materialChanged(key, creds) {
344
+ let previous;
345
+ try { previous = readPrivateState('credentials', key); } catch { return true; }
346
+ if (!previous) return true;
347
+ const material = (value) => {
348
+ // last_seen is bookkeeping; auth_source is derived by the loader and never
349
+ // part of the stored secret.
350
+ const { last_seen: _seen, auth_source: _source, ...rest } = value || {};
351
+ return JSON.stringify(rest, Object.keys(rest).sort());
352
+ };
353
+ return material(previous) !== material(creds);
354
+ }
355
+
285
356
  /**
286
357
  * Delete credentials for an instance keyed by <username>@<instance>.
287
358
  */
@@ -16,11 +16,34 @@ const stages = new Set([
16
16
  'input_encoding', 'output_encoding', 'native_compilation', 'request_decode',
17
17
  'native_read', 'native_write', 'native_delete',
18
18
  ]);
19
+
20
+ // Closed vocabulary for credential storage failures. Every storage error
21
+ // carries one of these so callers can tell an unavailable backend, an invalid
22
+ // secure entry, a failed readback and a deliberately blocked legacy plaintext
23
+ // file apart instead of seeing the one generic backend message.
24
+ export const STORAGE_CLASSIFICATIONS = Object.freeze([
25
+ 'plaintext_requires_recovery',
26
+ 'secure_storage_unavailable',
27
+ 'secure_readback_failed',
28
+ 'malformed_secure_entry',
29
+ 'storage_path_unsafe',
30
+ 'invalid_storage_key',
31
+ ]);
32
+ export const STORAGE_RECOVERY = Object.freeze({
33
+ plaintext_requires_recovery: 'Run `jsn auth login --profile <name>` to sign in again; the verified secure save retires the old credential file.',
34
+ secure_storage_unavailable: 'Restore the OS credential store for this account, then run `jsn auth login --profile <name>` to sign in again. Existing credential files are preserved.',
35
+ secure_readback_failed: 'Run `jsn auth login --profile <name>` to sign in again and verify secure storage. Existing credential files are preserved.',
36
+ malformed_secure_entry: 'Run `jsn auth login --profile <name>` to replace the unusable secure entry with fresh credentials. Existing credential files are preserved.',
37
+ storage_path_unsafe: 'Repair or move the credential path manually, then run `jsn auth login --profile <name>` to sign in again.',
38
+ invalid_storage_key: 'Select a profile whose username and instance produce a valid credential key, then run `jsn auth login --profile <name>`.',
39
+ });
19
40
  function failure(reason, stage) {
20
41
  const safeStage = stages.has(stage) ? stage : undefined;
21
42
  const diagnostic = safeStage ? ` Stage: ${safeStage}.` : '';
22
43
  const error = new Error(`Secure credential storage unavailable or readback failed. ${reason}${diagnostic} Existing plaintext credentials are preserved. No plaintext fallback is enabled automatically.`);
23
44
  error.code = 'credential_storage_error';
45
+ error.classification = 'secure_storage_unavailable';
46
+ error.recovery = STORAGE_RECOVERY.secure_storage_unavailable;
24
47
  if (safeStage) error.storageStage = safeStage;
25
48
  return error;
26
49
  }
@@ -1,5 +1,5 @@
1
1
  # Static command text: all request data (including secrets) arrives on stdin.
2
- # See GLOSSARY.md, Windows credential helper, for the policy contract.
2
+ # See site/docs/maintainers/domain-model.md, Windows credential helper, for the policy contract.
3
3
  $ErrorActionPreference = 'Stop'
4
4
  $ProgressPreference = 'SilentlyContinue'
5
5
  $stage = 'host_check'
package/src/auth.js CHANGED
@@ -19,6 +19,22 @@ import { normalizeAuthMethod, normalizeAuthSource, sourceMethod, probeFailure, c
19
19
  // `refreshable` refreshes at point of use; see isAuthenticated().
20
20
  const AUTHENTICATED_STATES = new Set(['available', 'refreshable']);
21
21
 
22
+ // Storage refusals are a closed vocabulary. They are reported as safe states
23
+ // here, but never as authenticated and never with the raw failure text.
24
+ function storageFailure(error) {
25
+ const classification = error?.classification || 'secure_storage_unavailable';
26
+ const blocked = classification === 'plaintext_requires_recovery';
27
+ return {
28
+ state: blocked ? 'blocked' : 'unavailable',
29
+ storage: {
30
+ status: blocked ? 'blocked' : 'unavailable',
31
+ classification,
32
+ ...(error?.storageStage ? { stage: error.storageStage } : {}),
33
+ recovery: error?.recovery || 'Run `jsn auth login --profile <name>` to sign in again.',
34
+ },
35
+ };
36
+ }
37
+
22
38
  // Preserve the public auth module API while implementation stays separated.
23
39
  export { sanitizeKeyPart } from './auth/credential-store.js';
24
40
  export { parseBrowserSessionInput } from './auth/browser-session.js';
@@ -149,13 +165,19 @@ export class AuthManager {
149
165
  */
150
166
  hasLegacyCredentials(instance, options = {}) {
151
167
  if (!instance) return false;
152
- const bareCreds = this.credentialStore.load(instance);
168
+ // This marker is advisory for status. A storage refusal must not turn it
169
+ // into a hard failure of the command that displays it.
170
+ let bareCreds;
171
+ try { bareCreds = this.credentialStore.load(instance); }
172
+ catch (error) { if (error?.code === 'credential_storage_error') return false; throw error; }
153
173
  if (!bareCreds) return false;
154
174
  // If active profile has a username, the bare key won't be found
155
175
  // by loadCredentials(instance, username). That's the legacy case.
156
176
  const username = this._usernameForOptions(options);
157
177
  if (!username) return false; // No username set — bare key IS the active path
158
- const userCreds = this.credentialStore.load(instance, username);
178
+ let userCreds;
179
+ try { userCreds = this.credentialStore.load(instance, username); }
180
+ catch (error) { if (error?.code === 'credential_storage_error') return false; throw error; }
159
181
  return !!bareCreds && !userCreds;
160
182
  }
161
183
 
@@ -233,7 +255,19 @@ export class AuthManager {
233
255
  classificationMethod = 'basic';
234
256
  credentials = basicCredentials;
235
257
  } else if (instance) {
236
- credentials = this.credentialStore.load(instance, this._usernameForOptions(options));
258
+ try {
259
+ credentials = this.credentialStore.load(instance, this._usernameForOptions(options));
260
+ } catch (error) {
261
+ if (error?.code !== 'credential_storage_error') throw error;
262
+ // Storage errors are reported, not thrown: status and
263
+ // isAuthenticated()/isAuthenticatedFor() must stay callable. Actual
264
+ // authenticated calls still fail loudly through getCredentialsFor().
265
+ return {
266
+ auth_method: method,
267
+ auth_source: 'unavailable',
268
+ ...storageFailure(error),
269
+ };
270
+ }
237
271
  if (credentials) {
238
272
  if (credentials.auth_method != null) {
239
273
  const storedMethod = normalizeAuthMethod(credentials.auth_method, '');
@@ -277,6 +311,14 @@ export class AuthManager {
277
311
  */
278
312
  async probeCurrentUser(instance = this.identity.getEffectiveInstance(), sdk, options = {}) {
279
313
  const authState = this.getAuthState(instance, options);
314
+ // A storage refusal is not a probe result and must not reach the SDK:
315
+ // no host contact, no token refresh, no credential read.
316
+ if (authState.storage) {
317
+ return {
318
+ ...probeFailure('storage_blocked', 'not_attempted'),
319
+ recovery: authState.storage.recovery,
320
+ };
321
+ }
280
322
  const method = authState.auth_method === 'unconfigured' ? null : authState.auth_method;
281
323
  const stateFailures = {
282
324
  missing: 'missing_credentials',
@@ -449,7 +491,11 @@ export class AuthManager {
449
491
  if (!suppliedCredentials && envCreds && this.identity.isTrustedCredentialDestination?.(instanceURL) === false) {
450
492
  throw errAuth('Project configuration cannot authorize an ambient credential destination. Select --instance explicitly or save the origin in global configuration.');
451
493
  }
452
- const storedCreds = this.loadCredentials(instanceURL, username);
494
+ // Advisory lookup only: a blocked legacy file must not prevent a fresh
495
+ // supplied login, which is the documented recovery route.
496
+ let storedCreds = null;
497
+ try { storedCreds = this.loadCredentials(instanceURL, username); }
498
+ catch (error) { if (error?.code !== 'credential_storage_error') throw error; }
453
499
  const creds = suppliedCredentials
454
500
  ? { auth_method: 'basic', ...suppliedCredentials }
455
501
  : envCreds || storedCreds;
@@ -662,7 +708,11 @@ export class AuthManager {
662
708
  */
663
709
  migrateLegacyCredential(instance, username) {
664
710
  if (!instance || !username) return false;
665
- const stored = this.credentialStore.load(instance);
711
+ let stored;
712
+ // Migration is opportunistic. A blocked or unavailable storage read must
713
+ // not undo the fresh login that already saved under the compound key.
714
+ try { stored = this.credentialStore.load(instance); }
715
+ catch (error) { if (error?.code === 'credential_storage_error') return false; throw error; }
666
716
  if (!stored || !stored.access_token) return false;
667
717
  stored.username = username;
668
718
  this.credentialStore.save(instance, stored, username);
@@ -144,7 +144,20 @@ export class LocalCLI {
144
144
  onParentDiscovery(fn) { this.parentDiscovery = fn; return this; }
145
145
  demandCommand(count, message) { this.root.demand = { count, message }; return this; }
146
146
  help() { this.helpEnabled = true; return this; }
147
- version() { return this; }
147
+ /**
148
+ * `--version`: print the tool's version and exit.
149
+ *
150
+ * A command's own version comes from the package manifest, so the root flag
151
+ * has to be answered by the parser before dispatch. `.version(false)` (used
152
+ * by the previous `jsn --version` wiring) silently removed the flag, so the
153
+ * token was tolerated as an unknown option and the page fell through to the
154
+ * root help — a script or agent asking "what version is this?" got 2 KB of
155
+ * help text instead of a version string.
156
+ */
157
+ version(value = false) {
158
+ this.versionText = value === false ? undefined : String(value);
159
+ return this;
160
+ }
148
161
  strictCommands() { this.strictCmd = true; return this; }
149
162
  strictOptions() { return this; }
150
163
  fail(fn) { this.failHandler = fn; return this; }
@@ -443,6 +456,13 @@ export class LocalCLI {
443
456
  const node = path.at(-1) || this.root;
444
457
  node.build();
445
458
  if (commandArgs.includes('--help') || commandArgs.includes('-h')) { this._help(node, path.map((n) => n.name)); return; }
459
+ // The root `--version` flag is answered here, before any command dispatch
460
+ // or demand-command failure, so `jsn --version` is a one-line answer.
461
+ if (this.versionText !== undefined && !path.length
462
+ && (commandArgs.includes('--version') || commandArgs.includes('-V'))) {
463
+ process.stdout.write(`${this.versionText}\n`);
464
+ return;
465
+ }
446
466
  const firstWord = this.args.find((arg, index) => !discoveryConsumed.has(index) && !arg.startsWith('-'));
447
467
  if (this.strictCmd && !path.length && firstWord && !this._lookup(this.root.children, firstWord)) {
448
468
  return this._fail(`Unknown command: ${firstWord}`);
package/src/cli.js CHANGED
@@ -486,8 +486,9 @@ export function buildCLI() {
486
486
  })(argv);
487
487
  })
488
488
  .epilogue(renderTips())
489
+ .option('version', { type: 'boolean', alias: 'V', describe: 'Show the jsn version' })
489
490
  .help('help', 'Show help')
490
- .version(false)
491
+ .version(getVersion())
491
492
  .strictCommands()
492
493
  .strictOptions(false)
493
494
  .fail((msg, err) => {
@@ -33,7 +33,7 @@ declareCapabilities('midservers', { mutationContext: 'operational', mutationSubc
33
33
  export const midserversCmd = wrap => ({ ...midserversCmdDefinition, load: () => require('./commands/midservers.js').midserversCmd(wrap) });
34
34
 
35
35
  export const subscriptionsCmdDefinition = {
36
- command: 'subscriptions [subcommand]', describe: 'Inspect local metering schedules and compare illustrative ITOM populations',
36
+ command: 'subscriptions [subcommand]', describe: 'Inspect subscription evidence, local schedules and illustrative ITOM populations',
37
37
  };
38
38
  declareCapabilities('subscriptions', { noInstance: true, skipDailyChecks: true, mutationSubcommands: [] });
39
39
  export const subscriptionsCmd = wrap => ({ ...subscriptionsCmdDefinition, load: () => require('./commands/subscriptions.js').subscriptionsCmd(wrap) });
@@ -22,7 +22,8 @@ export function renderAuthStatus(result, summary, { details = false } = {}) {
22
22
  const profiles = Array.isArray(result.profiles) ? result.profiles : [];
23
23
  if (!profiles.length) return 'No profiles configured.\nRun: jsn auth login <instance> --browser\n';
24
24
  const methods = { oauth: 'OAuth', basic: 'Basic', gck: 'Browser session' };
25
- const states = { available: 'Available', missing: 'Missing', expired: 'Expired', refreshable: 'Refresh required', malformed: 'Invalid' };
25
+ const states = { available: 'Available', missing: 'Missing', expired: 'Expired', refreshable: 'Refresh required', malformed: 'Invalid',
26
+ blocked: 'Storage blocked', unavailable: 'Storage unavailable' };
26
27
  const headings = ['PROFILE', 'AUTH', 'CREDENTIALS', 'CONNECTION', 'ACCESS', 'DELETES', 'COUNTS'];
27
28
  if (details) headings.push('USER', 'INSTANCE');
28
29
  const notes = [];
@@ -32,7 +33,8 @@ export function renderAuthStatus(result, summary, { details = false } = {}) {
32
33
  const label = profile.name || `Profile ${index + 1}`;
33
34
  const connection = profile.verified === true ? 'Verified'
34
35
  : probe.code === 'account_mismatch' ? 'User mismatch'
35
- : profile.verified === false ? 'Failed' : 'Not checked';
36
+ : profile.verified === false ? 'Failed'
37
+ : probe.code === 'storage_blocked' ? 'Not attempted' : 'Not checked';
36
38
  const row = [
37
39
  `${label}${profile.active ? ' *' : ''}${profile.default ? ' (default)' : ''}`,
38
40
  methods[diagnostics.auth_method] || 'Not configured',
@@ -47,7 +49,13 @@ export function renderAuthStatus(result, summary, { details = false } = {}) {
47
49
  row.push(`${user}${profile.verified_as && profile.verified_as !== user ? ` (session: ${profile.verified_as})` : ''}`, profile.instance || 'Not configured');
48
50
  }
49
51
  if (profile.verified !== true && probe.message) notes.push(`${label}: ${probe.message}`);
50
- if (profile.name && profile.verified !== true) {
52
+ if (profile.storage) {
53
+ const status = profile.storage.status === 'blocked' ? 'storage blocked' : 'storage unavailable';
54
+ // JSON keeps the fixed `<name>` placeholder; human output shows the
55
+ // concrete recovery command for this profile.
56
+ const recovery = profile.name ? profile.storage.recovery.replaceAll('<name>', profile.name) : profile.storage.recovery;
57
+ notes.push(`${label}: credentials ${status} (${profile.storage.classification}). ${recovery}`);
58
+ } else if (profile.name && profile.verified !== true) {
51
59
  const command = `jsn auth ${diagnostics.state === 'refreshable' ? 'refresh' : 'login'} --profile ${quoteShellArg(profile.name)}`;
52
60
  const hint = ['missing', 'expired', 'refreshable', 'malformed'].includes(diagnostics.state)
53
61
  || ['unauthorized', 'invalid_browser_session', 'refresh_failed', 'account_mismatch'].includes(probe.code)
@@ -65,6 +73,17 @@ export function renderAuthStatus(result, summary, { details = false } = {}) {
65
73
  if (profiles.some(profile => profile.read_only !== true)) lines.push(' Read/write: permits profile operations, subject to each command\'s guards.');
66
74
  if (profiles.some(profile => profile.skip_confirmations !== true)) lines.push(' Confirm: guarded deletes require confirmation; --force bypasses this prompt, not read-only.');
67
75
  if (profiles.some(profile => profile.skip_confirmations === true)) lines.push(' No prompt: profile skips standard delete confirmation; command-specific safeguards still apply.');
76
+ // Storage mode is a standing property of a profile, so it belongs in status
77
+ // rather than in a warning repeated on every command that reads credentials.
78
+ const plaintextProfiles = profiles.filter(profile => profile.auth_source === 'file' || profile.diagnostics?.auth_source === 'file');
79
+ if (plaintextProfiles.length) {
80
+ lines.push('', 'Credential storage:');
81
+ for (const profile of plaintextProfiles) {
82
+ const label = profile.name || 'profile';
83
+ lines.push(` ${label}: portable plaintext file; backups and copies can expose it.`
84
+ + ` Move it to the OS credential store: jsn auth login --profile ${quoteShellArg(label)}`);
85
+ }
86
+ }
68
87
  lines.push('ACCESS is a JSN profile setting, not ServiceNow ACL authorization.',
69
88
  'CREDENTIALS describes local availability; only CONNECTION Verified confirms the status probe succeeded.');
70
89
  if (profiles.some(profile => profile.diagnostics?.probe?.code === 'not_requested')) lines.push('', 'Connection not checked (--local).');
@@ -911,10 +930,31 @@ export async function showAuthStatus(argv, app) {
911
930
  const instance = profile.instance_url;
912
931
  const authOptions = { authMethod: profile.auth_method, username: profile.username };
913
932
  const identityOptions = { username: profile.username, authMethod: profile.auth_method };
914
- const isAuth = app.auth.isAuthenticatedFor(instance, identityOptions);
915
- const lastSeen = app.auth.getLastSeen(instance, identityOptions);
916
- const authState = app.auth.getAuthState(instance, authOptions);
917
- const legacy = !isAuth && app.auth.hasLegacyCredentials(instance, identityOptions) ? true : undefined;
933
+ // One profile's storage refusal must not abort the report for the others.
934
+ // Catch exactly credential_storage_error; anything else is still a bug.
935
+ let storage;
936
+ const recordStorage = (error) => {
937
+ if (error?.code !== 'credential_storage_error') throw error;
938
+ const classification = error.classification || 'secure_storage_unavailable';
939
+ const status = classification === 'plaintext_requires_recovery' ? 'blocked' : 'unavailable';
940
+ storage ||= {
941
+ status,
942
+ classification,
943
+ ...(error.storageStage ? { stage: error.storageStage } : {}),
944
+ recovery: error.recovery || `Run \`jsn auth login --profile ${name}\` to sign in again.`,
945
+ };
946
+ return status;
947
+ };
948
+ const attempt = (read, fallback) => {
949
+ try { return read(); } catch (error) { recordStorage(error); return fallback; }
950
+ };
951
+ let isAuth = attempt(() => app.auth.isAuthenticatedFor(instance, identityOptions), false) === true;
952
+ const lastSeen = attempt(() => app.auth.getLastSeen(instance, identityOptions), null);
953
+ const authState = attempt(() => app.auth.getAuthState(instance, authOptions), null)
954
+ || { auth_method: profile.auth_method || 'unconfigured', auth_source: 'unavailable', state: storage?.status || 'unavailable' };
955
+ if (authState.storage) storage ||= authState.storage;
956
+ if (storage) isAuth = false;
957
+ const legacy = !isAuth && attempt(() => app.auth.hasLegacyCredentials(instance, identityOptions), false) ? true : undefined;
918
958
  // Keep the established status field contract: unauthenticated
919
959
  // profiles omit auth_source, except legacy credentials retain
920
960
  // their historical `legacy` marker. getAuthState remains the
@@ -928,6 +968,13 @@ export async function showAuthStatus(argv, app) {
928
968
  let runtimeContext = argv.context ? { verified: false, status: 'not_attempted' } : undefined;
929
969
  if (argv.local) {
930
970
  probe = { status: 'not_attempted', code: 'not_requested', classification: 'not_checked' };
971
+ } else if (storage) {
972
+ // Blocked/unavailable storage is not a connection result, and it must
973
+ // not build an SDK or contact the instance.
974
+ probe = {
975
+ status: 'not_attempted', code: 'storage_blocked', classification: 'storage_blocked',
976
+ message: 'Credential storage is blocked; the connection probe was not attempted.',
977
+ };
931
978
  } else if (!instance) {
932
979
  probe = app.auth.probeUnavailable?.('missing_instance') || { status: 'not_attempted', code: 'missing_instance', classification: 'unavailable' };
933
980
  } else {
@@ -1000,12 +1047,20 @@ export async function showAuthStatus(argv, app) {
1000
1047
  state: authState.state,
1001
1048
  probe,
1002
1049
  },
1050
+ ...(storage ? { storage } : {}),
1003
1051
  });
1004
1052
  }
1005
1053
 
1054
+ // The global flag describes the selected profile; a storage refusal there
1055
+ // is reported, not thrown, so the report still includes every profile.
1056
+ let authenticated = false;
1057
+ try { authenticated = app.auth.isAuthenticated() === true; } catch (error) {
1058
+ if (error?.code !== 'credential_storage_error') throw error;
1059
+ }
1060
+
1006
1061
  const result = {
1007
1062
  default_instance: defaultInstance,
1008
- authenticated: app.auth.isAuthenticated(),
1063
+ authenticated,
1009
1064
  environment_auth: envToken ? true : undefined,
1010
1065
  profiles,
1011
1066
  };
@@ -97,6 +97,7 @@ export function flowsCmd(wrap) {
97
97
  builder: y => y
98
98
  .positional('term', { type: 'string', describe: 'Case-insensitive literal text to find in readable definitions' })
99
99
  .option('refresh', { type: 'boolean', default: false, describe: 'Rebuild the decoded cache; warm searches still revalidate source access' })
100
+ .option('concurrency', { type: 'number', default: 6, describe: 'Parallel definition downloads (1 = one at a time); instance reads still happen for every visible flow' })
100
101
  .epilogue(`Example:
101
102
  jsn flows search approval
102
103
  Interactive use can pick a flow; scripts pass the term.
@@ -105,7 +106,7 @@ Documentation: ${docLink('flows')}`),
105
106
  app.requireInstance();
106
107
  const session = app.session || {};
107
108
  const result = await searchFlows({
108
- sdk: app.sdk, term: argv.term, refresh: argv.refresh,
109
+ sdk: app.sdk, term: argv.term, refresh: argv.refresh, concurrency: argv.concurrency,
109
110
  context: { profile: session.profileName, username: session.username, domain: session.domain, authMethod: session.profile?.auth_method },
110
111
  progress: message => {
111
112
  if (!argv.json && !argv.get && (!argv.format || ['auto', 'pretty', 'styled'].includes(argv.format))) process.stderr.write(`${message}\n`);