@jacebenson/jsn 5.5.10 → 5.5.11-dev.241.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 +25 -0
  2. package/package.json +1 -1
  3. package/src/access-analyzer.js +92 -0
  4. package/src/app.js +5 -0
  5. package/src/auth/credential-store.js +3 -3
  6. package/src/auth/windows-credential-store.ps1 +1 -1
  7. package/src/cli-adapter.js +53 -3
  8. package/src/cli.js +17 -3
  9. package/src/command-audience.js +3 -1
  10. package/src/command-families.js +10 -3
  11. package/src/commands/_generic.js +15 -5
  12. package/src/commands/_simple.js +14 -1
  13. package/src/commands/_ticket.js +7 -1
  14. package/src/commands/access-analyzer.js +37 -0
  15. package/src/commands/approvals.js +1 -1
  16. package/src/commands/atf.js +1 -1
  17. package/src/commands/auth.js +6 -0
  18. package/src/commands/cases.js +3 -0
  19. package/src/commands/catalog.js +1 -1
  20. package/src/commands/cmdb.js +3 -0
  21. package/src/commands/decisiontables.js +1 -1
  22. package/src/commands/discover.js +108 -8
  23. package/src/commands/document.js +31 -0
  24. package/src/commands/domains.js +1 -1
  25. package/src/commands/graphql.js +1 -1
  26. package/src/commands/groupmembers.js +1 -1
  27. package/src/commands/grouproles.js +1 -1
  28. package/src/commands/groups.js +1 -1
  29. package/src/commands/logs.js +3 -0
  30. package/src/commands/records.js +21 -0
  31. package/src/commands/rest.js +1 -1
  32. package/src/commands/scan.js +40 -5
  33. package/src/commands/scopes.js +1 -1
  34. package/src/commands/scrapi.js +1 -1
  35. package/src/commands/table-behavior.js +5 -0
  36. package/src/commands/tickets.js +9 -1
  37. package/src/commands/transactions.js +3 -0
  38. package/src/commands/updatesets.js +1 -1
  39. package/src/commands/users.js +1 -1
  40. package/src/context.js +19 -0
  41. package/src/help.js +3 -1
  42. package/src/instance-documentation.js +237 -0
  43. package/src/intended-context.js +30 -3
  44. package/src/output.js +15 -3
  45. package/src/query-cache.js +187 -0
  46. package/src/query-metadata.js +189 -0
  47. package/src/query-parse.js +201 -0
  48. package/src/query-validate.js +282 -0
  49. package/src/scan.js +92 -17
  50. package/src/sdk.js +3 -0
  51. package/src/table-behavior.js +1 -1
package/README.md CHANGED
@@ -28,6 +28,31 @@ jsn --help
28
28
 
29
29
  Instance reads use your selected profile; add `--profile <name>` to choose another. Documentation search needs no ServiceNow connection and uses the hosted service by default. Use `jsn <command> --help` for options or `jsn --all-commands --help` for the full reference.
30
30
 
31
+ ## Saved Access Analyzer evidence
32
+
33
+ ```sh
34
+ jsn access-analyzer list --limit 20 --profile <name>
35
+ jsn access-analyzer show <request-id> --json
36
+ jsn access-analyzer explain <result-id> --format styled
37
+ jsn access-analyzer show <request-id> --get data.request.user.value
38
+ ```
39
+
40
+ These commands read saved `sn_access_analyzer_request`,
41
+ `sn_access_analyzer_access_result`, and `sn_access_analyzer_debug_log` records.
42
+ They never evaluate access or save an analysis. The Access Analyzer application
43
+ and read permissions on its tables are required; denied or unavailable table
44
+ reads fail rather than appearing as empty evidence. ACL-filtered empty reads
45
+ cannot prove access or absence of saved data.
46
+
47
+ IDs must be exact 32-character hexadecimal sys_ids. Each command supports
48
+ `--limit` (1–200) and `--offset` (default 0). JSON includes `pagination.has_more`
49
+ and `next_offset` from one-row lookahead, not a total count. `show` preserves
50
+ per-operation execution IDs; these are not shared run IDs and do not imply
51
+ that outcomes belong to the request's last run. `explain` orders checks by log sequence then sys_id.
52
+ Raw reference values and display labels are retained in JSON; joins use raw IDs.
53
+ Passed, Blocked, Skipped and Undefined remain distinct. A record-availability
54
+ failure with Business Rule evidence is not automatically an ACL failure.
55
+
31
56
  ## Choose output
32
57
 
33
58
  Use the default terminal view for people, `--csv` or `--tsv` for flat rows, and `--json` when scripts need pagination, context, or errors. CSV/TSV do not fetch more pages or preserve both reference IDs and labels. Pagination notices go to stderr only when more results are explicitly known; silence does not prove completeness. JSON retains reference objects only if the command has not already flattened them. See [output details](https://jsn.jace.pro/docs/output/).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.10",
3
+ "version": "5.5.11-dev.241.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": {
@@ -0,0 +1,92 @@
1
+ import { errNotFound, errUsage } from './errors.js';
2
+
3
+ const REQUEST = 'sn_access_analyzer_request';
4
+ const RESULT = 'sn_access_analyzer_access_result';
5
+ const LOG = 'sn_access_analyzer_debug_log';
6
+ const fields = {
7
+ [REQUEST]: 'sys_id,analyze_by,analyzed_by,user,group,role,resource_type,target_table,target_record,target_field,target_ui_page,target_rest_endpoint,target_rest_endpoint_method,target_client_callable_script_include,operations,short_description,last_run,evaluated_using',
8
+ [RESULT]: 'sys_id,access_analyzer_request,analyzed_by,operation,overall_access,security_data_filter_result,acl_result,accesshandler_result,datafiltration_result,execution_time,execution_id,insights,read_only_field,script_execution,current_resource,current_resource_type,record_available',
9
+ [LOG]: 'sys_id,access_analyzer_request,access_result,type,path,status,roles,roles_result,condition_result,script_result,security_attribute,decision_type,record_ref,log_table_name,log_sequence,log_time,app,applies_to,is_acl_customized,script_execution,applies_to_condition_result,controlled_by_references_result,empty',
10
+ };
11
+
12
+ // Display labels are presentation only. Never use them as reference join keys.
13
+ export const rawAccessValue = value => value && typeof value === 'object' ? String(value.value ?? '') : String(value ?? '');
14
+ const text = value => value && typeof value === 'object' ? String(value.display_value ?? value.value ?? '') : String(value ?? '');
15
+ function validateId(id) {
16
+ if (typeof id !== 'string' || !/^[0-9a-f]{32}$/i.test(id)) throw errUsage('Provide a 32-character hexadecimal sys_id.');
17
+ }
18
+ function bounds(limit, offset) {
19
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 200) throw errUsage('--limit must be an integer from 1 to 200.');
20
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > Number.MAX_SAFE_INTEGER - 201) throw errUsage('--offset must be a nonnegative safe integer.');
21
+ }
22
+ async function read(sdk, table, query, limit, offset = 0) {
23
+ const params = new URLSearchParams({ sysparm_query: query, sysparm_fields: fields[table], sysparm_limit: String(limit), sysparm_offset: String(offset), sysparm_display_value: 'all' });
24
+ const rows = await sdk.listStrict(table, params);
25
+ if (!Array.isArray(rows) || rows.some(row => !row || typeof row !== 'object' || Array.isArray(row))) {
26
+ throw Object.assign(new Error(`Malformed table response for ${table}`), { code: 'malformed_response' });
27
+ }
28
+ return rows;
29
+ }
30
+ async function one(sdk, table, id) {
31
+ const rows = await read(sdk, table, `sys_id=${id}`, 1);
32
+ if (!rows.length) throw errNotFound(`Saved Access Analyzer record ${id} was not found or is not readable.`);
33
+ if (rawAccessValue(rows[0].sys_id) !== id) throw new Error('Access Analyzer returned a different record identity.');
34
+ return rows[0];
35
+ }
36
+ async function page(sdk, table, query, limit, offset) {
37
+ const rows = await read(sdk, table, query, limit + 1, offset);
38
+ const hasMore = rows.length > limit;
39
+ return { records: rows.slice(0, limit), count: Math.min(rows.length, limit), pagination: { limit, offset, has_more: hasMore, next_offset: hasMore ? offset + limit : null } };
40
+ }
41
+
42
+ export async function listAccessAnalyses(sdk, { limit = 20, offset = 0 } = {}) {
43
+ bounds(limit, offset);
44
+ return page(sdk, REQUEST, 'ORDERBYDESClast_run^ORDERBYsys_id', limit, offset);
45
+ }
46
+ export async function showAccessAnalysis(sdk, id, { limit = 50, offset = 0 } = {}) {
47
+ validateId(id);
48
+ bounds(limit, offset);
49
+ const request = await one(sdk, REQUEST, id);
50
+ const results = await page(sdk, RESULT, `access_analyzer_request=${rawAccessValue(request.sys_id)}^ORDERBYexecution_id^ORDERBYoperation^ORDERBYsys_id`, limit, offset);
51
+ assertAssociation(results.records, 'access_analyzer_request', rawAccessValue(request.sys_id));
52
+ // execution_id identifies an operation result, not a shared analysis run.
53
+ return { request, ...results };
54
+ }
55
+ export async function explainAccessResult(sdk, id, { limit = 50, offset = 0 } = {}) {
56
+ validateId(id);
57
+ bounds(limit, offset);
58
+ const result = await one(sdk, RESULT, id);
59
+ const checks = await page(sdk, LOG, `access_result=${rawAccessValue(result.sys_id)}^ORDERBYlog_sequence^ORDERBYsys_id`, limit, offset);
60
+ assertAssociation(checks.records, 'access_result', rawAccessValue(result.sys_id));
61
+ const notes = ['Saved evidence only; this command does not run an access evaluation.'];
62
+ if (['false', 'no'].includes(rawAccessValue(result.record_available).toLowerCase())) notes.push('The target record was unavailable. Business Rule/query filtering evidence is not itself an ACL failure.');
63
+ return { result, ...checks, notes };
64
+ }
65
+
66
+ function assertAssociation(rows, field, id) {
67
+ if (rows.some(row => rawAccessValue(row[field]) !== id)) throw new Error(`Access Analyzer returned a mismatched ${field} association.`);
68
+ }
69
+ function requestLine(row) {
70
+ const identity = ['analyze_by', 'analyzed_by', 'user', 'group', 'role'].map(key => text(row[key])).filter(Boolean).join(' / ') || '(identity unavailable)';
71
+ const target = ['resource_type', 'target_table', 'target_record', 'target_field', 'target_ui_page', 'target_rest_endpoint', 'target_rest_endpoint_method', 'target_client_callable_script_include'].map(key => text(row[key])).filter(value => value && value !== 'undefined').join(' / ') || '(target unavailable)';
72
+ return `${rawAccessValue(row.sys_id)} | ${identity}\n Target: ${target}\n Last run: ${text(row.last_run) || '(unavailable)'}`;
73
+ }
74
+ function outcome(row) {
75
+ return `${rawAccessValue(row.sys_id)} | ${text(row.operation) || '(operation unavailable)'}: ${text(row.overall_access) || '(undefined)'} | execution ${text(row.execution_id) || '(unavailable)'}\n ACL: ${text(row.acl_result) || '(undefined)'}; security data filter: ${text(row.security_data_filter_result) || '(undefined)'}; access handler: ${text(row.accesshandler_result) || '(undefined)'}; data filtration: ${text(row.datafiltration_result) || '(undefined)'}`;
76
+ }
77
+ export function formatAccessAnalysis(data, mode) {
78
+ const lines = ['Saved Access Analyzer evidence (read-only)'];
79
+ if (mode === 'list') lines.push(...data.records.map(requestLine));
80
+ if (mode === 'show') lines.push(requestLine(data.request), ...data.records.map(outcome));
81
+ if (mode === 'explain') {
82
+ lines.push(outcome(data.result), ...data.notes);
83
+ for (const row of data.records) {
84
+ lines.push(`${text(row.log_sequence)}. ${text(row.type)} ${text(row.path)}: ${text(row.status) || '(undefined)'} [${rawAccessValue(row.sys_id)}]`);
85
+ lines.push(` Referenced rule: ${text(row.record_ref) || '(unavailable)'}; table: ${text(row.log_table_name) || '(unavailable)'}; sys_id: ${rawAccessValue(row.record_ref) || '(unavailable)'}`);
86
+ lines.push(` Roles: ${text(row.roles)} (${text(row.roles_result) || '(undefined)'}); condition: ${text(row.condition_result) || '(undefined)'}; script: ${text(row.script_result) || '(undefined)'}; security attribute: ${text(row.security_attribute) || '(undefined)'}; decision: ${text(row.decision_type) || '(undefined)'}`);
87
+ }
88
+ }
89
+ if (!data.count) lines.push('No readable saved rows on this page. Empty results do not prove access or absence of ACL-filtered records.');
90
+ lines.push(`Page: ${data.count} rows, offset ${data.pagination.offset}${data.pagination.has_more ? `; more available, next offset ${data.pagination.next_offset}` : '; no further readable rows'}.`);
91
+ return lines.join('\n');
92
+ }
package/src/app.js CHANGED
@@ -15,6 +15,7 @@ import { saveConfig, isTrustedCredentialDestination } from './config.js';
15
15
  import { resolveSession, applySession, contextFromSession, requireSessionInstance } from './session.js';
16
16
  import { errUsage, errAuth } from './errors.js';
17
17
  import { canPrompt, canUsePicker } from './helpers.js';
18
+ import { queryDiagnostics, invalidateAfterMutation } from './query-validate.js';
18
19
  import { guardMutationContext } from './mutation-context.js';
19
20
 
20
21
 
@@ -64,6 +65,7 @@ export class App {
64
65
  recovery: createAuthRecovery({ app: this, session }),
65
66
  canInteract: () => canUsePicker(this, this._authArgv || {}),
66
67
  });
68
+ this.sdk.afterMetadataMutation = table => invalidateAfterMutation(this, table);
67
69
  }
68
70
 
69
71
  /** Build a profile-scoped SDK without leaking auth construction to commands. */
@@ -93,6 +95,9 @@ export class App {
93
95
  }
94
96
 
95
97
  ok(data, opts = {}) {
98
+ const diagnostics = queryDiagnostics(this.queryValidation);
99
+ if (diagnostics.query_validation && data && typeof data === 'object' && !Array.isArray(data)) data = Object.assign(data, diagnostics);
100
+ else if (diagnostics.query_validation) opts = { ...opts, meta: { ...opts.meta, ...diagnostics } };
96
101
  this.output.ok(data, this.mutationContext ? { ...opts, context: { ...opts.context, mutation: this.mutationContext } } : opts);
97
102
  }
98
103
 
@@ -69,8 +69,8 @@ function warnPlaintext() {
69
69
  function refusal(classification = 'secure_storage_unavailable') {
70
70
  const repair = process.platform === 'win32'
71
71
  ? 'Windows Credential Manager requires Windows PowerShell 5.1 or PowerShell 7+ with FullLanguage/Add-Type and native API access allowed by policy.'
72
- : 'Unlock/install secret-tool and retry.';
73
- return storageError(`Secure credential storage unavailable or readback failed. ${repair} Existing plaintext credentials are preserved. No plaintext fallback is enabled automatically.`, classification);
72
+ : 'Unlock/install secret-tool and retry. On Debian/Ubuntu (including WSL), run: sudo apt install libsecret-tools gnome-keyring. If already installed, ensure a running, unlocked keyring is available in your D-Bus session.';
73
+ return storageError(`Secure credential storage unavailable or readback failed. ${repair} Existing plaintext credentials are preserved. No plaintext fallback is enabled automatically. To explicitly allow unencrypted credential files, set ${PLAINTEXT_ENV}=1 in the environment of each jsn process that needs them. Only do this if your security policy permits it; backups can expose credentials.`, classification);
74
74
  }
75
75
 
76
76
  /**
@@ -88,7 +88,7 @@ function plaintextBlocked() {
88
88
  }
89
89
  function readbackFailure() {
90
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.',
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. To explicitly allow unencrypted credential files, set ${PLAINTEXT_ENV}=1 in the environment of each jsn process that needs them. Only do this if your security policy permits it; backups can expose credentials.`,
92
92
  'secure_readback_failed',
93
93
  );
94
94
  }
@@ -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'
@@ -105,7 +105,7 @@ class CommandNode {
105
105
  positional(name, config = {}) { node.positionals.set(name, { ...config, name }); return this; },
106
106
  demandCommand(count, message) { node.demand = { count, message }; return this; },
107
107
  middleware(fn) { node.middlewares.push(...(Array.isArray(fn) ? fn : [fn])); return this; },
108
- strict() { return this; },
108
+ strict() { node.strict = true; return this; },
109
109
  check() { return this; },
110
110
  usage(value) { node.usageText = value; return this; },
111
111
  epilogue(value) { node.epilogueText = value; return this; },
@@ -256,6 +256,10 @@ export class LocalCLI {
256
256
  catch (err) { this._fail(err.message, err); return { values: {}, positionals: [] }; }
257
257
  const argv = { _: path.map((n) => n.name) };
258
258
  for (const [key, value] of Object.entries(parsed.values)) {
259
+ if (opts.validate !== false && path.some(node => node.strict) && !Object.hasOwn(defs, key)) {
260
+ this._fail(`Unknown option: --${key}`);
261
+ return null;
262
+ }
259
263
  if (opts.validate !== false && key === 'q' && !options.has('q')) {
260
264
  this._fail('Option -q (--query) is not supported by this command.');
261
265
  return null;
@@ -312,7 +316,7 @@ export class LocalCLI {
312
316
  * help page. Machine discovery leaves it out, so the JSON schema and bytes
313
317
  * stay unchanged.
314
318
  */
315
- commandRegistry({ summaries = false, shallow = false } = {}) {
319
+ commandRegistry({ summaries = false, shallow = false, details = false } = {}) {
316
320
  const visible = (node) => !node.definition.hidden;
317
321
  const serialize = (node) => {
318
322
  if (!shallow) node.build();
@@ -333,7 +337,7 @@ export class LocalCLI {
333
337
  if (summaries) entry.summary = node.definition.summary || '';
334
338
  return entry;
335
339
  };
336
- return {
340
+ const registry = {
337
341
  commands: this.root.children.filter(visible).map(serialize),
338
342
  options: [...this.root.options.values()].map((spec) => ({
339
343
  name: spec.name,
@@ -343,6 +347,49 @@ export class LocalCLI {
343
347
  type: spec.type || 'boolean',
344
348
  })),
345
349
  };
350
+ // Opt-in action detail leaves the legacy command/group projection intact.
351
+ // Build every visible descendant, using the same option inheritance and
352
+ // signatures as dispatch. Hidden subtrees are never indexed.
353
+ if (details) {
354
+ registry.entries = [];
355
+ const visit = (node, ancestors = [], aliases = []) => {
356
+ if (!visible(node)) return;
357
+ // Dispatch resolves names as literal tokens, not positional patterns.
358
+ // A positional-headed declaration cannot yield a fixed canonical path
359
+ // after placeholder substitution. Keep it only in the legacy projection.
360
+ if (positionSpec(node.name).length) return;
361
+ node.build();
362
+ const nodes = [...ancestors, node];
363
+ const path = nodes.map(value => value.name);
364
+ const bindings = this._optionConfig(nodes);
365
+ const allOptions = [...new Set(bindings.values())];
366
+ const options = allOptions.filter(spec => !spec.hidden).map(spec => {
367
+ // An inherited alias can now belong to a different, hidden option.
368
+ // Advertise only tokens that still resolve to this visible spec.
369
+ const tokens = [...bindings].filter(([_name, bound]) => bound === spec).map(([name]) => name);
370
+ return { ...spec, token: tokens.includes(spec.name) ? spec.name : tokens[0],
371
+ alias: tokens.filter(name => name !== spec.name) };
372
+ });
373
+ const positions = positionSpec(node.definition.command || '').map(position => ({
374
+ ...position, ...node.positionals.get(position.name), name: position.name,
375
+ }));
376
+ registry.entries.push({
377
+ path, aliases: [...aliases, ...node.aliases],
378
+ description: node.definition.describe || '',
379
+ group: nodes[0].definition.describe || '',
380
+ table: nodes[0].definition.discovery?.table || '',
381
+ help: `jsn ${path.join(' ')} --help`,
382
+ parent: node.children.some(visible),
383
+ options, positions,
384
+ hiddenRequired: allOptions.some(spec => spec.hidden && spec.demandOption),
385
+ tasks: node.definition.discoveryTasks || [],
386
+ examples: node.definition.examples || [],
387
+ });
388
+ for (const child of node.children) visit(child, nodes, [...aliases, ...node.aliases]);
389
+ };
390
+ for (const node of this.root.children) visit(node);
391
+ }
392
+ return registry;
346
393
  }
347
394
 
348
395
  /** Structured child signatures for a parent node, built on demand. */
@@ -494,6 +541,9 @@ export class LocalCLI {
494
541
  }
495
542
  for (const spec of specs) if (spec.demandOption && argv[spec.name] === undefined) return this._fail(`Missing required argument: --${spec.name}`);
496
543
  for (const pos of positions) if (pos.required && argv[pos.name] === undefined) return this._fail(`Missing required argument: ${pos.name}`);
544
+ if (path.some(commandNode => commandNode.strict) && positionalIndex < parsed.positionals.length) {
545
+ return this._fail(`Unexpected argument: ${parsed.positionals[positionalIndex]}`);
546
+ }
497
547
  for (const middleware of this.middlewares) await middleware(argv);
498
548
  for (const commandNode of path) for (const middleware of commandNode.middlewares) await middleware(argv);
499
549
  if (node.definition.handler) await node.definition.handler(argv);
package/src/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- import { flowsCmd, workflowsCmd, midserversCmd, subscriptionsCmd, customizationsCmd, skippedUpdatesCmd, docsCmd, perfCmd } from './command-families.js';
1
+ import { accessAnalyzerCmd, flowsCmd, workflowsCmd, midserversCmd, subscriptionsCmd, customizationsCmd, skippedUpdatesCmd, docsCmd, perfCmd } from './command-families.js';
2
2
  import { visibleCommandRegistry } from './command-audience.js';
3
3
  // Root CLI using the local yargs-compatible adapter
4
4
 
@@ -12,7 +12,7 @@ import { resolveSession, applySession } from './session.js';
12
12
  import { renderHelp, renderTips } from './help.js';
13
13
  import { isMutationCommand, refreshMutationCommands } from './mutations.js';
14
14
  import { maybeShowHome } from './welcome.js';
15
- import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands } from './capabilities.js';
15
+ import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands, collectCapabilities } from './capabilities.js';
16
16
  import { guardExit, exitWithError, AppError, CodeUsage } from './errors.js';
17
17
  import { formatCommandList } from './helpers.js';
18
18
 
@@ -42,6 +42,7 @@ import { platformCmd } from './commands/platform.js';
42
42
  import { codesearchCmd } from './commands/codesearch.js';
43
43
  import { versionCmd } from './commands/version.js';
44
44
  import { upgradeCmd } from './commands/upgrade.js';
45
+ import { documentCmd } from './commands/document.js';
45
46
  import { skillCmd, checkSkill } from './commands/skill.js';
46
47
  import { getVersion, checkLatest, getReleaseChannel, getInstallCommand } from './commands/version.js';
47
48
 
@@ -115,6 +116,8 @@ export function resolveRequestedFormat(argv) {
115
116
  */
116
117
  const DISCOVERY_OWNED_ELSEWHERE = new Set(['auth', 'perf', 'skill', 'groupmembers', 'grouproles']);
117
118
 
119
+ import { validateReadQuery, assertWriteQuery } from './query-validate.js';
120
+
118
121
  function wrap(handler) {
119
122
  return async (argv) => {
120
123
  try {
@@ -123,6 +126,14 @@ function wrap(handler) {
123
126
  process.stderr.write('Error: App context not initialized.\n');
124
127
  process.exit(1);
125
128
  }
129
+ const caps = collectCapabilities().get(argv._?.[0]) || {};
130
+ app.queryValidation = null;
131
+ if (((typeof argv.query === 'string' && argv.query.trim()) || caps.filteredMutationSubcommands?.includes(argv._?.[1]))
132
+ && !caps.noInstance && caps.encodedQuery !== false) {
133
+ const target = typeof caps.queryTable === 'function' ? caps.queryTable(argv) : caps.queryTable || caps.table || argv.table;
134
+ const options = { table: target, query: argv.query, refresh: argv['refresh-metadata'] };
135
+ app.queryValidation = await (isMutationCommand(argv) ? assertWriteQuery : validateReadQuery)(app, options);
136
+ }
126
137
  await app.guardMutationContext(argv);
127
138
  await handler(argv, app);
128
139
  } catch (err) {
@@ -149,6 +160,7 @@ export function buildCLI() {
149
160
  },
150
161
  ])
151
162
  .options({
163
+ 'refresh-metadata': { type: 'boolean', describe: 'Refresh query metadata instead of reusing the five-minute cache' },
152
164
  'all-commands': { type: 'boolean', describe: 'Show the full command list, including admin and developer tools' },
153
165
 
154
166
  'expect-scope': { type: 'string', description: 'Intended customization scope, exact scope/name or sys_id' },
@@ -368,6 +380,7 @@ export function buildCLI() {
368
380
  // AUTOMATION — Async
369
381
  .command(flowsCmd(wrap))
370
382
  .command(workflowsCmd(wrap))
383
+ .command(accessAnalyzerCmd(wrap))
371
384
  .command(actionsCmd(wrap))
372
385
  .command(scriptactionsCmd(wrap))
373
386
  .command(scheduledjobsCmd(wrap))
@@ -456,7 +469,8 @@ export function buildCLI() {
456
469
  .command(docsCmd(wrap))
457
470
  .command(versionCmd(wrap))
458
471
  .command(upgradeCmd(wrap))
459
- .command(discoverCmd(wrap, (argv) => visibleCommandRegistry(cliInstance.commandRegistry(), app.config, argv)))
472
+ .command(documentCmd(wrap))
473
+ .command(discoverCmd(wrap, (argv) => visibleCommandRegistry(cliInstance.commandRegistry({ details: true }), app.config, argv)))
460
474
  .demandCommand(1, 'You must specify a command')
461
475
  .onParentDiscovery((argv, { path, subcommands }) => {
462
476
  // Reached only for a parent command that declares no default handler of
@@ -34,5 +34,7 @@ export function commandAudience(config, { instance, allCommands = false } = {})
34
34
 
35
35
  export function visibleCommandRegistry(registry, config, options = {}) {
36
36
  if (commandAudience(config, options) !== 'basic') return registry;
37
- return { ...registry, commands: registry.commands.filter(command => BASIC_COMMANDS.has(command.name)) };
37
+ return { ...registry, commands: registry.commands.filter(command => BASIC_COMMANDS.has(command.name)),
38
+ ...(registry.entries ? { entries: registry.entries.filter(entry => BASIC_COMMANDS.has(entry.path[0])) } : {}),
39
+ };
38
40
  }
@@ -8,12 +8,19 @@ import { declareCapabilities } from './capabilities.js';
8
8
  // and complete-discovery API without pre-parsing argv or a generated catalog.
9
9
  const require = createRequire(import.meta.url);
10
10
 
11
+ export const accessAnalyzerCmdDefinition = {
12
+ command: 'access-analyzer [subcommand]',
13
+ describe: 'Inspect saved Access Analyzer requests, outcomes and checks (read-only)',
14
+ };
15
+ declareCapabilities('access-analyzer', { queryTable: 'sn_access_analyzer_request', mutationSubcommands: [] });
16
+ export const accessAnalyzerCmd = wrap => ({ ...accessAnalyzerCmdDefinition, load: () => require('./commands/access-analyzer.js').accessAnalyzerCmd(wrap) });
17
+
11
18
  export const flowsCmdDefinition = {
12
19
  command: 'flows [subcommand]',
13
20
  aliases: ['flow'],
14
21
  describe: 'Manage Flow Designer flows',
15
22
  };
16
- declareCapabilities('flows', { transactionScopeOption: 'scope', mutationContextExemptSubcommands: ['test', 'unlock'], mutationSubcommands: ['clone', 'copy', 'create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
23
+ declareCapabilities('flows', { queryTable: argv => argv._?.[1] === 'executions' ? 'sys_flow_context' : 'sys_hub_flow', transactionScopeOption: 'scope', mutationContextExemptSubcommands: ['test', 'unlock'], mutationSubcommands: ['clone', 'copy', 'create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
17
24
  export const flowsCmd = wrap => ({ ...flowsCmdDefinition, load: () => require('./commands/flows.js').flowsCmd(wrap) });
18
25
 
19
26
  export const workflowsCmdDefinition = {
@@ -21,7 +28,7 @@ export const workflowsCmdDefinition = {
21
28
  aliases: ['workflow'],
22
29
  describe: 'Inspect legacy Workflow Editor workflows (read-only)',
23
30
  };
24
- declareCapabilities('workflows', { mutationSubcommands: [] });
31
+ declareCapabilities('workflows', { queryTable: 'wf_workflow', mutationSubcommands: [] });
25
32
  export const workflowsCmd = wrap => ({ ...workflowsCmdDefinition, load: () => require('./commands/workflows.js').workflowsCmd(wrap) });
26
33
 
27
34
  export const midserversCmdDefinition = {
@@ -29,7 +36,7 @@ export const midserversCmdDefinition = {
29
36
  aliases: ['midserver', 'mid'],
30
37
  describe: 'Manage ServiceNow MID Servers and run commands through them',
31
38
  };
32
- declareCapabilities('midservers', { mutationContext: 'operational', mutationSubcommands: ['add', 'remove', 'execute', 'start', 'stop', 'validate'] });
39
+ declareCapabilities('midservers', { queryTable: 'ecc_agent', mutationContext: 'operational', mutationSubcommands: ['add', 'remove', 'execute', 'start', 'stop', 'validate'] });
33
40
  export const midserversCmd = wrap => ({ ...midserversCmdDefinition, load: () => require('./commands/midservers.js').midserversCmd(wrap) });
34
41
 
35
42
  export const subscriptionsCmdDefinition = {
@@ -4,6 +4,7 @@ import { enrichRelatedLists, relatedListOptions } from '../related-lists.js';
4
4
 
5
5
  import { formatRecordForDisplay, findOmittedColumns, getStringField, buildRecordPayload, confirmDelete, interactiveList, canPrompt } from '../helpers.js';
6
6
  import { getRecord, listRecords, recordListParams, createRecord, updateRecord, deleteRecord, recordOptions } from '../records-engine.js';
7
+ import { validateReadQuery, queryDiagnostics, invalidateAfterMutation } from '../query-validate.js';
7
8
  import { unwrapSysId } from '../resolve-record.js';
8
9
  import { getCurrentUser, getCurrentApplication } from '../context.js';
9
10
  import { FormatAuto } from '../output.js';
@@ -135,6 +136,7 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
135
136
  handler: wrap(async (argv, app) => {
136
137
  const query = argv.query || '';
137
138
  const constrainedQuery = constrainQuery(query, extraQuery);
139
+ const verdict = await validateReadQuery(app, { table, query, refresh: argv['refresh-metadata'] });
138
140
  const columns = argv.columns ? argv.columns.split(',') : defaultColumns;
139
141
  const limit = argv.limit;
140
142
 
@@ -186,6 +188,7 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
186
188
  } : {}),
187
189
  records: argv.displayValues || opts.listProjection === 'full' ? records : records.map(r => formatRecordForDisplay(r, presentColumns)),
188
190
  context: { instance_url: app.getEffectiveInstance() },
191
+ ...queryDiagnostics(verdict),
189
192
  }, {
190
193
  summary: `${records.length} ${name}(s)`,
191
194
  breadcrumbs: buildHints(name, singular, readOnly),
@@ -232,18 +235,23 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
232
235
  .command({
233
236
  command: 'create',
234
237
  describe: `Create a new ${singular}`,
235
- builder: (y) => recordOptions(y, false)
236
- .option('data', { type: 'string', describe: 'JSON fields' })
237
- .option('data-file', { type: 'string', describe: 'Read JSON payload from file' })
238
- .option('data-stdin', { type: 'boolean', describe: 'Read JSON payload from stdin' })
239
- .option('field', { alias: 'f', type: 'string', array: true, describe: 'Set a field as name=value; repeatable' }),
238
+ builder: (y) => {
239
+ const command = recordOptions(y, false)
240
+ .option('data', { type: 'string', describe: 'JSON fields' })
241
+ .option('data-file', { type: 'string', describe: 'Read JSON payload from file' })
242
+ .option('data-stdin', { type: 'boolean', describe: 'Read JSON payload from stdin' })
243
+ .option('field', { alias: 'f', type: 'string', array: true, describe: 'Set a field as name=value; repeatable' });
244
+ return opts.createHelp ? command.epilogue(opts.createHelp) : command;
245
+ },
240
246
  handler: wrap(async (argv, app) => {
241
247
  const recordData = buildRecordPayload(argv);
242
248
  const record = await createRecord(app.sdk, { table, data: recordData });
249
+ invalidateAfterMutation(app, table);
243
250
  app.ok(record, {
244
251
  summary: `Created ${singular}`,
245
252
  breadcrumbs: [
246
253
  { action: 'show', cmd: `jsn ${name} show ${getStringField(record, 'name') || getStringField(record, 'sys_id')}`, description: `View the new ${singular}` },
254
+ ...(opts.createBreadcrumbs || []),
247
255
  ],
248
256
  });
249
257
  }),
@@ -266,6 +274,7 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
266
274
  const sysID = unwrapSysId(record);
267
275
  const recordData = buildRecordPayload(argv);
268
276
  const updated = await updateRecord(app.sdk, { table, record: { sys_id: sysID }, data: recordData });
277
+ invalidateAfterMutation(app, table);
269
278
  app.ok(updated, { summary: `Updated ${singular} ${id}` });
270
279
  }),
271
280
  })
@@ -286,6 +295,7 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
286
295
  await confirmDelete(app, argv, `Delete ${singular} '${recordName}'`);
287
296
 
288
297
  await deleteRecord(app.sdk, { table, record: { sys_id: sysID } });
298
+ invalidateAfterMutation(app, table);
289
299
  app.ok({ name: recordName, sys_id: sysID, deleted: true }, { summary: `Deleted ${singular} '${recordName}'` });
290
300
  }),
291
301
  });
@@ -48,7 +48,20 @@ async function fetchExtensionChain(sdk, record) {
48
48
 
49
49
  export { actionsCmd } from './actions.js';
50
50
 
51
- export const includesCmd = (wrap) => buildProfileCommand('includes', wrap);
51
+ export const includesCmd = (wrap) => buildProfileCommand('includes', wrap, {
52
+ createBreadcrumbs: [
53
+ { action: 'check-help', cmd: 'jsn scan checks create --help', description: 'Behavior is untested until the intended check runs. Review a suitable check.' },
54
+ { action: 'scan-help', cmd: 'jsn scan run --help', description: 'Choose an explicit target; verify intended-check execution and its assertion.' },
55
+ ],
56
+ createHelp: [
57
+ 'Behavior verification is a separate, explicitly approved operation, not performed by includes create.',
58
+ 'Review jsn scan checks create --help and jsn scan run --help. A suitable scripted Instance Scan check can execute intended behavior server-side without jsn eval, but still executes code; it is not a safety bypass.',
59
+ 'Supply the intended target and check identity. Method, inputs and expected value must come from the task, never inferred from submitted source.',
60
+ 'Confirm positive evidence that the intended check executed and its assertion passed. A completed scan or zero findings alone is not behavioral correctness. Skipped or unreadable execution remains unverified.',
61
+ 'Live end-to-end validation is unverified and blocked by #551. Do not assume script-only checks participate in record or update-set point scans. On an approved disposable target, a future verified example must demonstrate a deliberate assertion failure producing a finding, then a restored pass.',
62
+ 'Creation adds no check or scan, performs no storage readback, and does not verify capture.',
63
+ ].join('\n\n'),
64
+ });
52
65
 
53
66
  export const rulesCmd = (wrap) => buildProfileCommand('rules', wrap);
54
67
 
@@ -4,6 +4,7 @@ import { enrichRelatedLists, relatedListOptions } from '../related-lists.js';
4
4
 
5
5
  import { getStringField, formatRecordForDisplay, findOmittedColumns, buildQuerySuffix, resolveFieldsParam, confirmDelete, interactiveList, canPrompt, buildRecordPayload } from '../helpers.js';
6
6
  import { getRecord, listRecords, recordListParams, createRecord, updateRecord, deleteRecord, recordOptions } from '../records-engine.js';
7
+ import { validateReadQuery, queryDiagnostics, invalidateAfterMutation } from '../query-validate.js';
7
8
  import { resolveSysId } from '../resolve-record.js';
8
9
  import { FormatAuto } from '../output.js';
9
10
  import { declareCapabilities } from '../capabilities.js';
@@ -11,7 +12,7 @@ import { declareCapabilities } from '../capabilities.js';
11
12
  export function buildTicketCommands(table, displayName, alias, defaultColumns, stateMap, iconFn, wrap, opts = {}) {
12
13
  // Ticket-style CRUD: list/show are reads; create/update/delete mutate.
13
14
  // Root-level command only.
14
- declareCapabilities(displayName, { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
15
+ declareCapabilities(displayName, { queryTable: table, mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
15
16
  return {
16
17
  command: `${displayName} [subcommand]`,
17
18
  aliases: [table, alias],
@@ -30,6 +31,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
30
31
  .option('offset', { alias: 'o', type: 'number', default: 0, describe: 'Offset for pagination' }),
31
32
  handler: wrap(async (argv, app) => {
32
33
  const query = argv.query || '';
34
+ const verdict = await validateReadQuery(app, { table, query, refresh: argv['refresh-metadata'] });
33
35
  const columns = argv.columns ? argv.columns.split(',') : defaultColumns;
34
36
  const limit = argv.limit;
35
37
  const offset = argv.offset;
@@ -125,6 +127,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
125
127
  records: displayRecords,
126
128
  pagination: { limit, offset, hasMore: records.length === limit },
127
129
  context: { instance_url: app.getEffectiveInstance() },
130
+ ...queryDiagnostics(verdict),
128
131
  }, {
129
132
  summary: `${records.length} ${table}(s)`,
130
133
  breadcrumbs,
@@ -175,6 +178,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
175
178
  throw new Error('short_description is required (use --description, -f short_description=..., or --data)');
176
179
  }
177
180
  const record = await createRecord(app.sdk, { table, data: recordData });
181
+ invalidateAfterMutation(app, table);
178
182
  app.ok(record, {
179
183
  summary: `Created ${displayName} ${getStringField(record, 'number')}`,
180
184
  breadcrumbs: [
@@ -196,6 +200,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
196
200
  const recordData = buildRecordPayload(argv);
197
201
  const sysID = await resolveSysId(app.sdk, { table, identifier: number, identifierField: argv.identifierField, displayValues: argv.displayValues ?? opts.referenceMode, matchField: opts.identifierField || 'number', resource: displayName });
198
202
  const updated = await updateRecord(app.sdk, { table, record: { sys_id: sysID }, data: recordData });
203
+ invalidateAfterMutation(app, table);
199
204
  app.ok(updated, {
200
205
  summary: `Updated ${displayName} ${number}`,
201
206
  breadcrumbs: [
@@ -213,6 +218,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
213
218
  await confirmDelete(app, argv, `Delete ${displayName} ${number}`);
214
219
  const sysID = await resolveSysId(app.sdk, { table, identifier: number, identifierField: argv.identifierField, displayValues: argv.displayValues ?? opts.referenceMode, matchField: opts.identifierField || 'number', resource: displayName });
215
220
  await deleteRecord(app.sdk, { table, record: { sys_id: sysID } });
221
+ invalidateAfterMutation(app, table);
216
222
  app.ok({ number, message: `${displayName.charAt(0).toUpperCase() + displayName.slice(1)} deleted` }, {
217
223
  summary: `Deleted ${displayName} ${number}`,
218
224
  });
@@ -0,0 +1,37 @@
1
+ import { accessAnalyzerCmdDefinition } from '../command-families.js';
2
+ import { errUsage } from '../errors.js';
3
+ import { listAccessAnalyses, showAccessAnalysis, explainAccessResult, formatAccessAnalysis } from '../access-analyzer.js';
4
+
5
+ export function accessAnalyzerCmd(wrap) {
6
+ const commands = [
7
+ ['list', 'List saved access analyses, identities, targets and last runs', listAccessAnalyses],
8
+ ['show <request-id>', 'Show saved operation outcomes for a request sys_id', showAccessAnalysis],
9
+ ['explain <result-id>', 'Explain ordered saved checks for an operation result sys_id', explainAccessResult],
10
+ ];
11
+ return {
12
+ ...accessAnalyzerCmdDefinition,
13
+ builder: y => {
14
+ y = y.strict().middleware(argv => {
15
+ if (argv.subcommand) throw errUsage(`Unknown access-analyzer subcommand: ${argv.subcommand}`);
16
+ });
17
+ for (const [command, describe, read] of commands) {
18
+ const mode = command.split(' ')[0];
19
+ y = y.command({ command, describe,
20
+ builder: sub => {
21
+ if (mode !== 'list') sub = sub.positional(`${mode === 'show' ? 'request' : 'result'}-id`, { type: 'string', describe: 'Exact 32-character hexadecimal sys_id' });
22
+ return sub.option('limit', { type: 'number', default: mode === 'list' ? 20 : 50, describe: 'Page size (1–200)' })
23
+ .option('offset', { type: 'number', default: 0, describe: 'Nonnegative page offset' });
24
+ },
25
+ handler: wrap(async (argv, app) => {
26
+ app.requireInstance();
27
+ const options = { limit: argv.limit, offset: argv.offset };
28
+ const data = mode === 'list' ? await read(app.sdk, options) : await read(app.sdk, argv[mode === 'show' ? 'request-id' : 'result-id'], options);
29
+ Object.defineProperty(data, '_formatted', { value: formatAccessAnalysis(data, mode), enumerable: false });
30
+ app.ok(data, { summary: `${data.count} saved ${mode === 'list' ? 'analysis request(s)' : mode === 'show' ? 'operation result(s)' : 'check(s)'}${data.pagination.has_more ? ', more available' : ''}` });
31
+ }),
32
+ });
33
+ }
34
+ return y;
35
+ },
36
+ };
37
+ }
@@ -25,7 +25,7 @@ import { errUsage, errNotFound } from '../errors.js';
25
25
  import { declareCapabilities } from '../capabilities.js';
26
26
 
27
27
  // approve/reject/submit change approval state on records.
28
- declareCapabilities('approvals', { mutationContext: 'operational', mutationSubcommands: ['approve', 'reject', 'submit'] });
28
+ declareCapabilities('approvals', { queryTable: 'sysapproval_approver', mutationContext: 'operational', mutationSubcommands: ['approve', 'reject', 'submit'] });
29
29
 
30
30
  // Raw sysapproval_approver.state values (verified live).
31
31
  const APPROVAL_STATES = [
@@ -27,7 +27,7 @@ import { errUsage, errNotFound } from '../errors.js';
27
27
  import { declareCapabilities } from '../capabilities.js';
28
28
 
29
29
  // run/run-suite schedule tests that act on records (top-level only).
30
- declareCapabilities('atf', { mutationContext: 'operational', mutationSubcommands: ['run', 'run-suite'] });
30
+ declareCapabilities('atf', { queryTable: argv => argv._?.[1] === 'suites' ? 'sys_atf_test_suite' : 'sys_atf_test', mutationContext: 'operational', mutationSubcommands: ['run', 'run-suite'] });
31
31
 
32
32
  // sn_cicd progress statuses (now-sdk poller.ts)
33
33
  const PROGRESS_PENDING = '0';
@@ -1277,6 +1277,12 @@ export function authCmd(wrap) {
1277
1277
  .command({
1278
1278
  command: 'status',
1279
1279
  describe: 'Show authentication status (use --details for users and instance URLs)',
1280
+ discoveryTasks: [{
1281
+ phrases: ['current update set', 'selected scope', 'capture context', 'current capture context', 'current scope', 'current application scope', 'active scope', 'selected application scope', 'active update set', 'selected update set', 'capture set', 'which scope am I in'],
1282
+ args: ['--context', '--json'],
1283
+ description: 'Read the selected profile context, including scope and current capture update set; does not select or change them',
1284
+ }],
1285
+ examples: [{ args: ['--context', '--json'], description: 'Inspect the selected scope and capture update set' }],
1280
1286
  builder: sub => sub.option('local', {
1281
1287
  type: 'boolean', describe: 'Show saved credential state without contacting any instance',
1282
1288
  }).option('context', {