@jacebenson/jsn 5.5.10-dev.234.1 → 5.5.10-dev.235.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.10-dev.234.1",
3
+ "version": "5.5.10-dev.235.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": {
@@ -13,9 +13,12 @@ declareCapabilities('scan', { mutationSubcommands: [
13
13
  ] });
14
14
 
15
15
  const hint = (action, cmd, description) => ({ action, cmd, description });
16
- function report(app, argv, data, options) {
17
- const connection = argv.profile ? ` --profile ${quoteShellArg(argv.profile)}`
16
+ function connectionSuffix(argv) {
17
+ return argv.profile ? ` --profile ${quoteShellArg(argv.profile)}`
18
18
  : argv.instance ? ` --instance ${quoteShellArg(argv.instance)}` : '';
19
+ }
20
+ function report(app, argv, data, options) {
21
+ const connection = connectionSuffix(argv);
19
22
  app.ok(data, { ...options, breadcrumbs: options.breadcrumbs.map(item => ({ ...item, cmd: item.cmd + connection })) });
20
23
  }
21
24
  const rootHints = () => [hint('checks', 'jsn scan checks list', 'Browse available checks'),
@@ -32,6 +35,18 @@ const itemHints = (group, record) => {
32
35
  hint('delete', `jsn scan ${group} delete ${id}`, 'Delete this definition after confirmation')];
33
36
  };
34
37
 
38
+ // Structured recovery for a dispatched scan whose progress or results cannot be
39
+ // read. It records what was started so an operator can inspect it; resubmission
40
+ // is never recommended because the original execution may still be running.
41
+ function recoveryTarget(target = {}) {
42
+ return { kind: target.kind,
43
+ ...(target.sys_id ? { sys_id: target.sys_id } : {}),
44
+ ...(target.table ? { table: target.table } : {}),
45
+ ...(target.name ? { name: target.name } : {}),
46
+ ...(target.execution_id ? { execution_id: target.execution_id } : {}),
47
+ ...(target.combo_id ? { combo_id: target.combo_id } : {}) };
48
+ }
49
+
35
50
  function executionHints(data) {
36
51
  const id = data.execution_id;
37
52
  return [hint('status', `jsn scan status ${id}`, 'Read execution progress'),
@@ -188,6 +203,7 @@ export function scanCmd(wrap) {
188
203
  await confirmDelete(app, argv, `Start scan of ${plan.target.kind} ${plan.target.name || plan.target.sys_id || plan.target.execution_id || 'the full instance'}${plan.suite_id ? ` using suite ${plan.suite_id}` : ''}?`);
189
204
  const scheduled = await startScan(app.sdk, plan);
190
205
  let data = { ...scheduled, status: 'scheduled', terminal: false };
206
+ let phase = 'progress';
191
207
  if (argv.wait) {
192
208
  try {
193
209
  const deadline = Date.now() + argv.timeout * 1000;
@@ -199,12 +215,24 @@ export function scanCmd(wrap) {
199
215
  // The processor can return before its execution tracker is visible.
200
216
  data = { ...scheduled, status: 'scheduled', terminal: false };
201
217
  }
202
- if (data.terminal) { data = { ...scheduled, ...await scanResults(app.sdk, scheduled.execution_id) }; break; }
218
+ if (data.terminal) { phase = 'results'; data = { ...scheduled, ...await scanResults(app.sdk, scheduled.execution_id) }; break; }
203
219
  await new Promise(resolve => setTimeout(resolve, Math.min(2000, Math.max(0, deadline - Date.now()))));
204
220
  }
205
221
  if (!data.terminal) data.wait_timed_out = true;
206
222
  } catch (error) {
207
- throw errAPI(error.status || 0, `Scan ${scheduled.execution_id} was scheduled, but progress could not be read: ${error.message}. Use jsn scan status ${scheduled.execution_id}; do not resubmit automatically.`);
223
+ const id = scheduled.execution_id;
224
+ const connection = connectionSuffix(argv);
225
+ const statusCommand = `jsn scan status ${id}${connection}`;
226
+ // Provider errors may contain credentials or request payloads.
227
+ const wrapped = errAPI(error.status || 0, `Scan ${id} was scheduled, but ${phase} could not be read. Use ${statusCommand}; do not resubmit automatically.`);
228
+ // errAPI replaces the message for 401/403, so the dispatched id and
229
+ // the no-resubmit warning must also survive in the hint.
230
+ wrapped.hint = [wrapped.hint, `Scan ${id} was already dispatched; inspect it with "${statusCommand}" and do not resubmit automatically.`].filter(Boolean).join(' ');
231
+ wrapped.recovery = { execution_id: id, via: scheduled.via, phase,
232
+ target: recoveryTarget(plan.target), suite_id: scheduled.suite_id ?? null, status: 'unverified',
233
+ status_command: statusCommand,
234
+ results_command: `jsn scan results ${id}${connection}`, resubmit: 'forbidden' };
235
+ throw wrapped;
208
236
  }
209
237
  }
210
238
  const breadcrumbs = executionHints(data);
@@ -220,7 +248,14 @@ export function scanCmd(wrap) {
220
248
  builder: p => p.option('limit', { type: 'number', default: 50, describe: 'Maximum findings/check rows (1–200); truncation is reported' }),
221
249
  handler: wrap(async (argv, app) => {
222
250
  const data = await scanResults(app.sdk, argv.id, boundedLimit(argv.limit));
223
- report(app, argv, data, { summary: `Scan ${data.status}; ${data.findings_count ?? 'unknown'} findings; ${data.checks_executed ?? 'unknown'} recorded check executions${data.incomplete ? '; incomplete data' : ''}`, breadcrumbs: executionHints(data) });
251
+ const findings = data.findings_state === 'unretrieved'
252
+ ? `findings unretrieved (${data.findings_count} reported, 0 rows returned)`
253
+ : data.findings_state === 'mismatch'
254
+ ? `findings mismatch (${data.findings_count} reported, ${data.findings_retrieved} retrieved)`
255
+ : data.findings_state === 'truncated'
256
+ ? `findings truncated (${data.findings_retrieved} retrieved; count not reconciled)`
257
+ : `${data.findings_count ?? 'unknown'} findings`;
258
+ report(app, argv, data, { summary: `Scan ${data.status}; ${findings}; ${data.checks_executed ?? 'unknown'} recorded check executions${data.incomplete ? '; incomplete data' : ''}`, breadcrumbs: executionHints(data) });
224
259
  }) })
225
260
  .command({ command: 'cancel <id>', describe: 'Request cancellation of this scan after confirmation',
226
261
  handler: wrap(async (argv, app) => {
package/src/scan.js CHANGED
@@ -100,6 +100,34 @@ export async function scanAjax(sdk, method, parameters) {
100
100
  }
101
101
 
102
102
  const TERMINAL = new Set(['successful', 'failed', 'cancelled']);
103
+ // Execution tracker types that belong to Instance Scan. Exact matches only:
104
+ // no aliases or prefix matching, so unrelated trackers cannot be read as scans.
105
+ const SCAN_TRACKER_TYPES = new Set(['instance_scan', 'point_scan']);
106
+
107
+ // Read the execution back-reference from a result row without guessing: a
108
+ // non-empty value that is not a full sys_id is still "present, but not ours".
109
+ // Strings are checked by type so the legacy String.prototype.link is never read
110
+ // as a reference.
111
+ function hasResultBackReference(value) {
112
+ if (typeof value === 'string') return value !== '';
113
+ if (typeof value === 'object' && value !== null) return Boolean(raw(value) || value.link);
114
+ return false;
115
+ }
116
+
117
+ function resultBackReference(value) {
118
+ if (typeof value === 'object' && value !== null) return referenceId(value);
119
+ return isSysId(String(value ?? '')) ? String(value) : '';
120
+ }
121
+ // 'malformed' means a payload exists but could not be read as a reference.
122
+ // Parsing a reference is not verification: only results can verify linkage.
123
+ function resultLink(value) {
124
+ const text = raw(value);
125
+ if (!text) return { state: 'missing', id: '' };
126
+ try {
127
+ const id = referenceId(JSON.parse(text).result_id);
128
+ return id ? { state: 'linked', id } : { state: 'malformed', id: '' };
129
+ } catch { return { state: 'malformed', id: '' }; }
130
+ }
103
131
  const STATES = { '0': 'pending', '1': 'running', '2': 'successful', '3': 'failed', '4': 'cancelled',
104
132
  pending: 'pending', running: 'running', successful: 'successful', failed: 'failed',
105
133
  cancelled: 'cancelled', canceled: 'cancelled' };
@@ -108,19 +136,25 @@ export async function scanStatus(sdk, id, { allowInitializing = false } = {}) {
108
136
  requireId(id);
109
137
  const tracker = await sdk.get('sys_execution_tracker', id);
110
138
  if (!tracker) throw errNotFound('scan execution', id);
111
- if (!raw(tracker.type) && allowInitializing) return { execution_id: id, status: 'pending', terminal: false,
112
- percent_complete: null, message: 'Execution tracker is initializing', result_id: null };
113
- if (raw(tracker.type) === 'sys.instance_scan.queue') return { execution_id: id, status: 'pending', terminal: false,
114
- percent_complete: raw(tracker.percent_complete) ?? null, message: raw(tracker.message) || 'Scan is queued', result_id: null };
115
- if (raw(tracker.type) !== 'instance_scan') throw errUsage('This execution tracker is not an Instance Scan.');
139
+ // Missing or denied identity is not evidence that this is our execution.
140
+ const trackerId = tracker.sys_id === undefined || tracker.sys_id === null ? '' : String(raw(tracker.sys_id));
141
+ if (trackerId !== id) throw errUsage('The execution tracker identity does not match the requested execution.');
142
+ const type = String(raw(tracker.type) ?? '');
143
+ const link = resultLink(tracker.result);
144
+ if (!type && allowInitializing) return { execution_id: id, status: 'pending', terminal: false,
145
+ phase: 'initializing', percent_complete: null, message: 'Execution tracker is initializing', result_id: null,
146
+ execution_type: type, result_link: link.state };
147
+ if (type === 'sys.instance_scan.queue') return { execution_id: id, status: 'pending', terminal: false,
148
+ phase: 'queued', percent_complete: raw(tracker.percent_complete) ?? null, message: raw(tracker.message) || 'Scan is queued',
149
+ result_id: null, execution_type: type, result_link: link.state };
150
+ if (!SCAN_TRACKER_TYPES.has(type)) throw errUsage('This execution tracker is not an Instance Scan.');
116
151
  const state = STATES[String(raw(tracker.state)).toLowerCase()] || 'unknown';
117
- let resultId = '';
118
- if (raw(tracker.result)) {
119
- try { resultId = referenceId(JSON.parse(raw(tracker.result)).result_id); } catch { /* reported as unavailable below */ }
120
- }
121
- return { execution_id: id, status: state, terminal: TERMINAL.has(state),
152
+ // result_link only says the tracker's own result JSON parsed; a result row and
153
+ // its back-reference are verified in scanResults, never here.
154
+ return { execution_id: id, status: state, terminal: TERMINAL.has(state), phase: 'dispatched',
122
155
  percent_complete: raw(tracker.percent_complete) ?? null,
123
- message: raw(tracker.message) || '', result_id: resultId || null };
156
+ message: raw(tracker.message) || '', result_id: link.id || null,
157
+ execution_type: type, result_link: link.state };
124
158
  }
125
159
 
126
160
  async function resolveSuite(sdk, identifier) {
@@ -205,19 +239,44 @@ export async function startScan(sdk, plan) {
205
239
  export async function scanResults(sdk, id, limit = 50) {
206
240
  boundedLimit(limit);
207
241
  const status = await scanStatus(sdk, id);
208
- const data = { ...status, checks_executed: null, findings_count: null, checks: [], findings: [],
242
+ const data = { ...status, checks_executed: null, findings_count: null, findings_retrieved: null,
243
+ checks: [], findings: [], result_verified: false, back_reference: 'absent',
244
+ findings_state: 'unknown', checks_state: 'unknown',
209
245
  incomplete: !status.terminal, unavailable: [], truncated: {}, rerun_full: false, reusable_target: false };
210
246
  if (!status.result_id) { data.unavailable.push('scan_result'); data.incomplete = true; return data; }
211
247
  let result;
212
248
  try {
213
249
  result = await sdk.get('scan_result', status.result_id);
214
250
  if (!result) throw new Error('Result unavailable');
215
- data.scan_number = raw(result.number);
216
- const value = raw(result.finding_count);
217
- const count = Number(value);
218
- if ((typeof value === 'number' || (typeof value === 'string' && /^\d+$/.test(value))) && Number.isInteger(count) && count >= 0) data.findings_count = count;
219
- else { data.unavailable.push('scan_result.finding_count'); data.incomplete = true; }
251
+ // Require the exact linked identity, including when the field is denied.
252
+ const resultId = result.sys_id === undefined || result.sys_id === null ? '' : String(raw(result.sys_id));
253
+ if (resultId !== status.result_id) {
254
+ data.unavailable.push('scan_result.identity');
255
+ data.incomplete = true;
256
+ result = null;
257
+ }
220
258
  } catch { data.unavailable.push('scan_result'); data.incomplete = true; }
259
+ if (result) {
260
+ // The result row must point back to this execution. A point scan always
261
+ // records its execution id; a foreign or absent back-reference means the
262
+ // row cannot be trusted to describe this scan. Only a matching
263
+ // back-reference earns result_verified; a parsed id alone does not.
264
+ const present = hasResultBackReference(result.progress_id);
265
+ const matches = present && resultBackReference(result.progress_id) === status.execution_id;
266
+ data.back_reference = present ? (matches ? 'matched' : 'foreign') : 'absent';
267
+ if ((present && !matches) || (!present && status.execution_type === 'point_scan')) {
268
+ data.unavailable.push('scan_result.back_reference');
269
+ data.incomplete = true;
270
+ result = null;
271
+ } else {
272
+ data.result_verified = matches;
273
+ data.scan_number = raw(result.number);
274
+ const value = raw(result.finding_count);
275
+ const count = Number(value);
276
+ if ((typeof value === 'number' || (typeof value === 'string' && /^\d+$/.test(value))) && Number.isInteger(count) && count >= 0) data.findings_count = count;
277
+ else { data.unavailable.push('scan_result.finding_count'); data.incomplete = true; }
278
+ }
279
+ }
221
280
  for (const [key, table, fields] of [
222
281
  ['checks', 'scan_check_execution', ['check', 'message', 'execution_time']],
223
282
  ['findings', 'scan_finding', ['check', 'source_table', 'source', 'finding_details', 'count']],
@@ -225,11 +284,27 @@ export async function scanResults(sdk, id, limit = 50) {
225
284
  try {
226
285
  const rows = await sdk.listStrict(table, recordListParams({ limit: limit + 1,
227
286
  query: `result=${status.result_id}^ORDERBYsys_id`, fields, displayValue: 'all' }));
287
+ if (!Array.isArray(rows) || rows.some(row => !row || typeof row !== 'object' || Array.isArray(row))) {
288
+ throw new Error('Unreadable scan rows');
289
+ }
228
290
  data[key] = rows.slice(0, limit);
229
291
  data.truncated[key] = rows.length > limit;
292
+ if (key === 'findings') data.findings_retrieved = rows.length;
230
293
  if (key === 'checks' && !data.truncated[key] && status.terminal) data.checks_executed = rows.length;
231
294
  } catch { data.unavailable.push(table); data.incomplete = true; }
232
295
  }
296
+ // Reported counts must reconcile with retrieved rows. A positive count with
297
+ // nothing retrieved, or any other disagreement, is not a clean zero and its
298
+ // cause is not assumed. Truncated pages cannot be reconciled at all.
299
+ if (data.findings_count === null || data.unavailable.includes('scan_finding')) data.findings_state = 'unknown';
300
+ else if (data.truncated.findings) { data.findings_state = 'truncated'; data.incomplete = true; }
301
+ else if (data.findings_count > 0 && data.findings_retrieved === 0) { data.findings_state = 'unretrieved'; data.incomplete = true; }
302
+ else if (data.findings_count !== data.findings_retrieved) { data.findings_state = 'mismatch'; data.incomplete = true; }
303
+ else data.findings_state = 'verified';
304
+ if (data.unavailable.includes('scan_check_execution')) data.checks_state = 'unknown';
305
+ else if (data.truncated.checks) { data.checks_state = 'truncated'; data.incomplete = true; }
306
+ else if (data.checks.length === 0) data.checks_state = 'empty';
307
+ else data.checks_state = 'verified';
233
308
  const comboId = referenceId(result?.combo);
234
309
  if (comboId) {
235
310
  try { const combo = await sdk.get('scan_combo', comboId); if (combo) { data.reusable_target = true; data.rerun_full = !raw(combo.targets); } }