@jacebenson/jsn 5.5.9-dev.227.1 → 5.5.9-dev.228.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-dev.227.1",
3
+ "version": "5.5.9-dev.228.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": {
@@ -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,9 +41,12 @@ 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
  }
49
52
  /**
@@ -63,11 +66,37 @@ function warnPlaintext() {
63
66
  plaintextWarningShown = true;
64
67
  process.stderr.write('Warning: plaintext credential storage explicitly enabled for this process; credentials are portable and backups can expose them.\n');
65
68
  }
66
- function refusal() {
69
+ function refusal(classification = 'secure_storage_unavailable') {
67
70
  const repair = process.platform === 'win32'
68
71
  ? 'Windows Credential Manager requires Windows PowerShell 5.1 or PowerShell 7+ with FullLanguage/Add-Type and native API access allowed by policy.'
69
72
  : 'Unlock/install secret-tool and retry.';
70
- 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
+ );
71
100
  }
72
101
 
73
102
  // Validate broad ancestors without chmod: only the leaf secret directory must
@@ -86,7 +115,7 @@ function checkPath(target, directory, privateMode = false) {
86
115
  ((stat.mode & 0o022) !== 0 && !(directory && stat.uid === 0 && (stat.mode & 0o1000)))))) {
87
116
  throw storageError(posix
88
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.'
89
- : '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');
90
119
  }
91
120
  return stat;
92
121
  }
@@ -101,7 +130,7 @@ export function privateStateDirectories(dir, pathAPI = path) {
101
130
  }
102
131
  function privateStatePath(kind, key, create = false) {
103
132
  if (!['credentials', 'pkce'].includes(kind) || !/^[a-zA-Z0-9._@-]+$/.test(key) || key === '.' || key === '..') {
104
- throw storageError('Invalid credential/PKCE storage key.');
133
+ throw storageError('Invalid credential/PKCE storage key.', 'invalid_storage_key');
105
134
  }
106
135
  // Resolve once so traversal, leaf comparison and IO share the same path,
107
136
  // including when the configured XDG directory is relative.
@@ -127,12 +156,12 @@ export function readPrivateState(kind, key) {
127
156
  fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
128
157
  const before = checkPath(file, false, true);
129
158
  const opened = fs.fstatSync(fd);
130
- 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');
131
160
  return JSON.parse(fs.readFileSync(fd, 'utf8'));
132
161
  } catch (error) {
133
162
  if (error.code === 'ENOENT') return null;
134
163
  if (error.code === 'credential_storage_error') throw error;
135
- 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');
136
165
  } finally { if (fd !== undefined) fs.closeSync(fd); }
137
166
  }
138
167
  export function writePrivateState(kind, key, value) {
@@ -161,36 +190,42 @@ export function removePrivateState(kind, key) {
161
190
  // ─── Keyring via secret-tool (libsecret, same backend as Go's go-keyring) ───
162
191
 
163
192
  function keyringLookup(key, legacyKey) {
193
+ let result;
164
194
  try {
165
195
  // execFileSync with an arg array — no shell, so `key` can never
166
196
  // break out into command injection (issue #143 finding #2).
167
- const result = process.platform === 'win32'
197
+ result = process.platform === 'win32'
168
198
  ? (windowsCredentialOperation('read', key) ?? (legacyKey ? windowsCredentialOperation('read', legacyKey) : null))
169
199
  : execFileSync(
170
200
  'secret-tool',
171
201
  ['lookup', KEYRING_ATTR_SERVICE, KEYRING_SERVICE, KEYRING_ATTR_USERNAME, key],
172
202
  { stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf-8' }
173
203
  );
174
- const trimmed = result?.trim();
175
- if (!trimmed) return null;
176
- const parsed = JSON.parse(trimmed);
177
- // Spread all fields from keyring first, then normalize known fields
178
- // so username, password, and other extras are preserved.
179
- return {
180
- ...parsed,
181
- auth_method: parsed.auth_method || 'oauth',
182
- access_token: parsed.access_token || parsed.AccessToken || '',
183
- refresh_token: parsed.refresh_token || parsed.RefreshToken || '',
184
- expires_at: parsed.expires_at || parsed.ExpiresAt || 0,
185
- created_at: parsed.created_at || parsed.CreatedAt || 0,
186
- auth_source: parsed.auth_method === 'gck' ? 'gck' : 'keyring',
187
- };
188
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.
189
207
  if (process.platform === 'win32' && !plaintextAllowed()) {
190
- throw error.code === 'credential_storage_error' ? error : refusal();
208
+ throw error?.code === 'credential_storage_error' ? error : refusal();
191
209
  }
192
210
  return null;
193
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
+ };
194
229
  }
195
230
 
196
231
  function keyringStore(key, creds) {
@@ -207,20 +242,27 @@ function keyringStore(key, creds) {
207
242
  }
208
243
  }
209
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).
210
247
  function storeVerified(key, creds) {
211
248
  if (process.platform === 'win32') {
212
249
  const value = JSON.stringify(creds);
213
250
  windowsCredentialOperation('write', key, value);
214
- const readback = windowsCredentialOperation('read', key);
215
- 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';
216
258
  }
217
- if (!keyringStore(key, creds)) return false;
259
+ if (!keyringStore(key, creds)) return 'unavailable';
218
260
  try {
219
261
  const value = execFileSync('secret-tool',
220
262
  ['lookup', KEYRING_ATTR_SERVICE, KEYRING_SERVICE, KEYRING_ATTR_USERNAME, key],
221
263
  { stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf8' });
222
- return isDeepStrictEqual(JSON.parse(value), JSON.parse(JSON.stringify(creds)));
223
- } catch { return false; }
264
+ return isDeepStrictEqual(JSON.parse(value), JSON.parse(JSON.stringify(creds))) ? 'ok' : 'readback_failed';
265
+ } catch { return 'readback_failed'; }
224
266
  }
225
267
 
226
268
  function keyringDelete(key) {
@@ -259,9 +301,10 @@ export function loadCredentials(instance, username, injectedStore) {
259
301
  }
260
302
  const file = privateStatePath('credentials', key);
261
303
  if (!fs.existsSync(file)) return null;
262
- // Reads (including local status) never persist or migrate credentials. A
263
- // subsequent explicit login/save or token refresh performs verified retirement.
264
- if (!plaintextAllowed()) throw refusal();
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();
265
308
  const creds = readPrivateState('credentials', key);
266
309
  return creds ? { ...creds, auth_source: 'file' } : null;
267
310
  }
@@ -278,16 +321,16 @@ export function saveCredentials(instance, creds, username, injectedStore) {
278
321
  const key = username ? credKey(instance, username) : credKey(instance);
279
322
  // Stamp last_seen on every credential save
280
323
  creds.last_seen = creds.last_seen || Math.floor(Date.now() / 1000);
281
- let verified = false;
324
+ let status = 'unavailable';
282
325
  let secureFailure;
283
- try { verified = storeVerified(key, creds); }
326
+ try { status = storeVerified(key, creds); }
284
327
  catch (error) { secureFailure = error.code === 'credential_storage_error' ? error : refusal(); }
285
- if (verified) {
328
+ if (status === 'ok') {
286
329
  // Retire only this identity, and only after exact secure-store readback.
287
330
  removePrivateState('credentials', key);
288
331
  return;
289
332
  }
290
- if (!plaintextAllowed()) throw secureFailure || refusal();
333
+ if (!plaintextAllowed()) throw secureFailure || (status === 'readback_failed' ? readbackFailure() : refusal());
291
334
  // Re-stamping last_seen after a successful call is bookkeeping, not a storage
292
335
  // decision. Warning on it put the message on every command again, which is
293
336
  // what this change is meant to stop; only a change to the secret material
@@ -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
  }
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);
@@ -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)
@@ -922,10 +930,31 @@ export async function showAuthStatus(argv, app) {
922
930
  const instance = profile.instance_url;
923
931
  const authOptions = { authMethod: profile.auth_method, username: profile.username };
924
932
  const identityOptions = { username: profile.username, authMethod: profile.auth_method };
925
- const isAuth = app.auth.isAuthenticatedFor(instance, identityOptions);
926
- const lastSeen = app.auth.getLastSeen(instance, identityOptions);
927
- const authState = app.auth.getAuthState(instance, authOptions);
928
- 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;
929
958
  // Keep the established status field contract: unauthenticated
930
959
  // profiles omit auth_source, except legacy credentials retain
931
960
  // their historical `legacy` marker. getAuthState remains the
@@ -939,6 +968,13 @@ export async function showAuthStatus(argv, app) {
939
968
  let runtimeContext = argv.context ? { verified: false, status: 'not_attempted' } : undefined;
940
969
  if (argv.local) {
941
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
+ };
942
978
  } else if (!instance) {
943
979
  probe = app.auth.probeUnavailable?.('missing_instance') || { status: 'not_attempted', code: 'missing_instance', classification: 'unavailable' };
944
980
  } else {
@@ -1011,12 +1047,20 @@ export async function showAuthStatus(argv, app) {
1011
1047
  state: authState.state,
1012
1048
  probe,
1013
1049
  },
1050
+ ...(storage ? { storage } : {}),
1014
1051
  });
1015
1052
  }
1016
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
+
1017
1061
  const result = {
1018
1062
  default_instance: defaultInstance,
1019
- authenticated: app.auth.isAuthenticated(),
1063
+ authenticated,
1020
1064
  environment_auth: envToken ? true : undefined,
1021
1065
  profiles,
1022
1066
  };