@jacebenson/jsn 5.5.9-dev.222.1 → 5.5.9-dev.223.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.222.1",
3
+ "version": "5.5.9-dev.223.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": {
@@ -46,6 +46,17 @@ function storageError(message) {
46
46
  error.code = 'credential_storage_error';
47
47
  return error;
48
48
  }
49
+ /**
50
+ * The plaintext warning belongs to the moment a credential is stored, not to
51
+ * every command that reads one back.
52
+ *
53
+ * It used to fire on the read path too, which meant once per process, which
54
+ * means once per command — every read, list, or search printed it on stderr.
55
+ * That is noise in a terminal and permanently in an agent transcript, and it
56
+ * told nobody anything they could act on at that moment. The storage mode is
57
+ * reported instead by `jsn auth status`, and the warning is emitted when the
58
+ * choice is actually made (login, setup, token save).
59
+ */
49
60
  let plaintextWarningShown = false;
50
61
  function warnPlaintext() {
51
62
  if (plaintextWarningShown) return;
@@ -251,7 +262,6 @@ export function loadCredentials(instance, username, injectedStore) {
251
262
  // Reads (including local status) never persist or migrate credentials. A
252
263
  // subsequent explicit login/save or token refresh performs verified retirement.
253
264
  if (!plaintextAllowed()) throw refusal();
254
- warnPlaintext();
255
265
  const creds = readPrivateState('credentials', key);
256
266
  return creds ? { ...creds, auth_source: 'file' } : null;
257
267
  }
@@ -278,10 +288,28 @@ export function saveCredentials(instance, creds, username, injectedStore) {
278
288
  return;
279
289
  }
280
290
  if (!plaintextAllowed()) throw secureFailure || refusal();
281
- warnPlaintext();
291
+ // Re-stamping last_seen after a successful call is bookkeeping, not a storage
292
+ // decision. Warning on it put the message on every command again, which is
293
+ // what this change is meant to stop; only a change to the secret material
294
+ // (a real login or token refresh) is worth the warning.
295
+ if (materialChanged(key, creds)) warnPlaintext();
282
296
  writePrivateState('credentials', key, creds);
283
297
  }
284
298
 
299
+ /** True when the incoming credential material differs from what is on disk. */
300
+ function materialChanged(key, creds) {
301
+ let previous;
302
+ try { previous = readPrivateState('credentials', key); } catch { return true; }
303
+ if (!previous) return true;
304
+ const material = (value) => {
305
+ // last_seen is bookkeeping; auth_source is derived by the loader and never
306
+ // part of the stored secret.
307
+ const { last_seen: _seen, auth_source: _source, ...rest } = value || {};
308
+ return JSON.stringify(rest, Object.keys(rest).sort());
309
+ };
310
+ return material(previous) !== material(creds);
311
+ }
312
+
285
313
  /**
286
314
  * Delete credentials for an instance keyed by <username>@<instance>.
287
315
  */
@@ -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) => {
@@ -65,6 +65,17 @@ export function renderAuthStatus(result, summary, { details = false } = {}) {
65
65
  if (profiles.some(profile => profile.read_only !== true)) lines.push(' Read/write: permits profile operations, subject to each command\'s guards.');
66
66
  if (profiles.some(profile => profile.skip_confirmations !== true)) lines.push(' Confirm: guarded deletes require confirmation; --force bypasses this prompt, not read-only.');
67
67
  if (profiles.some(profile => profile.skip_confirmations === true)) lines.push(' No prompt: profile skips standard delete confirmation; command-specific safeguards still apply.');
68
+ // Storage mode is a standing property of a profile, so it belongs in status
69
+ // rather than in a warning repeated on every command that reads credentials.
70
+ const plaintextProfiles = profiles.filter(profile => profile.auth_source === 'file' || profile.diagnostics?.auth_source === 'file');
71
+ if (plaintextProfiles.length) {
72
+ lines.push('', 'Credential storage:');
73
+ for (const profile of plaintextProfiles) {
74
+ const label = profile.name || 'profile';
75
+ lines.push(` ${label}: portable plaintext file; backups and copies can expose it.`
76
+ + ` Move it to the OS credential store: jsn auth login --profile ${quoteShellArg(label)}`);
77
+ }
78
+ }
68
79
  lines.push('ACCESS is a JSN profile setting, not ServiceNow ACL authorization.',
69
80
  'CREDENTIALS describes local availability; only CONNECTION Verified confirms the status probe succeeded.');
70
81
  if (profiles.some(profile => profile.diagnostics?.probe?.code === 'not_requested')) lines.push('', 'Connection not checked (--local).');
@@ -1,9 +1,12 @@
1
1
  // Intent comes from the task, never from the current provider preferences.
2
2
  import { assertSafeExactMatch, getStringField } from './helpers.js';
3
3
  import { errUsageHint } from './errors.js';
4
+ import { readEffectiveUpdateSet } from './context.js';
4
5
 
5
- export function contextFailure(message) {
6
- return errUsageHint(message, 'Supply --expect-scope and --expect-update-set from the task. Select context explicitly with scopes set / updatesets set, then retry. --force never overrides missing or mismatched intent.');
6
+ const CONTEXT_HINT = 'Supply --expect-scope and --expect-update-set from the task. Select context explicitly with scopes set / updatesets set, then retry. --force never overrides missing or mismatched intent.';
7
+
8
+ export function contextFailure(message, hint = CONTEXT_HINT) {
9
+ return errUsageHint(message, hint);
7
10
  }
8
11
  const raw = (record, key) => record?.[key]?.value ?? record?.[key];
9
12
  export async function exactContextRecord(sdk, table, field, identifier) {
@@ -25,14 +28,74 @@ export async function readWriteContext(sdk) {
25
28
  }));
26
29
  if (users.length !== 1 || !raw(users[0], 'sys_id') || !getStringField(users[0], 'user_name')) throw contextFailure('Current user is unknown.');
27
30
  const user = { sys_id: raw(users[0], 'sys_id'), user_name: getStringField(users[0], 'user_name') };
28
- async function preference(name) {
29
- const rows = await sdk.list('sys_user_preference', new URLSearchParams({
30
- sysparm_query: `user=${user.sys_id}^name=${name}`, sysparm_limit: '2', sysparm_fields: 'value',
31
- }));
32
- if (rows.length !== 1 || !raw(rows[0], 'value') || raw(rows[0], 'value') === '-') throw contextFailure(`Current ${name} preference is unknown.`);
31
+ /**
32
+ * Read one persisted capture-context preference.
33
+ *
34
+ * A missing row is not the same failure as an unreadable one. On a fresh
35
+ * instance nobody has ever picked an update set, so there is genuinely
36
+ * nothing to verify a customization write against — and the old message
37
+ * ("Current sys_update_set preference is unknown") named an internal
38
+ * preference key and pointed at --expect-* flags that cannot create a
39
+ * selection. An agent following that hint retries the same dead end. Each
40
+ * branch below says what is actually wrong and names the command that fixes
41
+ * it.
42
+ */
43
+ async function preference({ key, label, remediation, sessionTruth }) {
44
+ let rows;
45
+ try {
46
+ rows = await sdk.list('sys_user_preference', new URLSearchParams({
47
+ sysparm_query: `user=${user.sys_id}^name=${key}`, sysparm_limit: '2', sysparm_fields: 'value',
48
+ }));
49
+ } catch (error) {
50
+ throw contextFailure(
51
+ `Could not read the persisted ${label} for ${user.user_name}: ${error.message}`,
52
+ `Confirm the instance is reachable and retry. Do not retry the write until the selection can be read.`,
53
+ );
54
+ }
55
+ if (rows.length === 0) {
56
+ throw contextFailure(
57
+ `No ${label} is selected for ${user.user_name}, so there is no capture context to verify this write against.${await sessionNote(sessionTruth)}`,
58
+ `Select one first, then rerun the same command: ${remediation}. --expect-scope and --expect-update-set assert an existing selection; they cannot create one.`,
59
+ );
60
+ }
61
+ if (rows.length > 1) {
62
+ throw contextFailure(
63
+ `${rows.length} persisted ${label} preferences exist for ${user.user_name}, so the capture context is ambiguous.`,
64
+ `Resolve the duplicate preferences for this user, then retry: ${remediation}`,
65
+ );
66
+ }
67
+ if (!raw(rows[0], 'value') || raw(rows[0], 'value') === '-') {
68
+ throw contextFailure(
69
+ `The ${label} for ${user.user_name} is saved but empty, so the capture context is unreadable.`,
70
+ `Select one again, then rerun the same command: ${remediation}`,
71
+ );
72
+ }
33
73
  return raw(rows[0], 'value');
34
74
  }
35
- const [scopeId, setId] = await Promise.all([preference('apps.current_app'), preference('sys_update_set')]);
75
+ // Failure-path diagnostic only: the provider's session picker is a different
76
+ // source from the persisted preference, and saying so stops an agent from
77
+ // assuming a fresh session already has a set selected.
78
+ async function sessionNote(readSession) {
79
+ if (!readSession) return '';
80
+ try {
81
+ const effective = await readSession();
82
+ if (!effective?.sys_id) return '';
83
+ return `\nThe session picker reports "${effective.label || effective.name || effective.sys_id}" (${effective.sys_id}); that selection is not persisted for this user and is not used for a customization write.`;
84
+ } catch {
85
+ return '';
86
+ }
87
+ }
88
+ const [scopeId, setId] = await Promise.all([
89
+ preference({
90
+ key: 'apps.current_app', label: 'application scope',
91
+ remediation: 'jsn scopes set "<scope value or name>"',
92
+ }),
93
+ preference({
94
+ key: 'sys_update_set', label: 'update set',
95
+ remediation: 'jsn updatesets set "<update set name>"',
96
+ sessionTruth: () => readEffectiveUpdateSet(sdk),
97
+ }),
98
+ ]);
36
99
  const [scope, set] = await Promise.all([sdk.get('sys_scope', scopeId), sdk.get('sys_update_set', setId)]);
37
100
  const applicationId = raw(set, 'application');
38
101
  if (!getStringField(scope || {}, 'scope') || !getStringField(set || {}, 'name') || !applicationId || !getStringField(set || {}, 'state')) throw contextFailure('Capture context is incomplete or unreadable.');
@@ -48,7 +48,14 @@ export async function guardMutationContext(app, argv, { ask = confirm, rawArgs =
48
48
  }
49
49
  let context;
50
50
  try { context = await readWriteContext(app.sdk); }
51
- catch (error) { throw contextFailure(`Cannot verify capture context: ${error.message}`); }
51
+ catch (error) {
52
+ // A structured failure already explains which selection is missing and
53
+ // which command fixes it. Prefixing it with "Cannot verify capture
54
+ // context" buried that remediation and replaced it with the generic
55
+ // --expect-* hint, which cannot create a selection.
56
+ if (error?.hint) throw error;
57
+ throw contextFailure(`Cannot verify capture context: ${error.message}`);
58
+ }
52
59
  if (app.session?.username && context.user.user_name !== app.session.username) throw contextFailure('Current user differs from the selected profile.');
53
60
  const fail = message => { const error = contextFailure(message); error.context = context; throw error; };
54
61
  if (context.application_id !== context.update_set.application_id) fail('Selected scope and update set belong to different applications.');