@jacebenson/jsn 5.5.3-dev.178.1 → 5.5.3-dev.180.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.3-dev.178.1",
3
+ "version": "5.5.3-dev.180.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": {
@@ -1,3 +1,4 @@
1
+ import { searchFlows, formatFlowSearch } from '../flow-search.js';
1
2
  import fs from 'node:fs';
2
3
  import { formatRecordForDisplay, formatCommandList, getStringField, interactiveList } from '../helpers.js';
3
4
  import { discoverFlowContextFields, normalizeFlowContext, summarizeFlowContexts, formatFlowContextSummary, aggregateFlowContextMappings, mergeFlowContextStats, buildFlowContextQuery } from '../flow-context.js';
@@ -36,6 +37,7 @@ function describeOwned(counts) {
36
37
  const FLOW_COMMANDS = [
37
38
  { name: 'schemas', description: 'Read live trigger catalog and input schemas' },
38
39
  { name: 'catalog-variables [identifier]', description: 'List a catalog item\'s variables for a service_catalog trigger' },
40
+ { name: 'search <term>', description: 'Download, decode and search a private local flow cache (--refresh to rebuild)' },
39
41
  { name: 'list', description: 'List flows' },
40
42
  { name: 'executions', description: 'Show flow executions from sys_flow_context' },
41
43
  { name: 'show [identifier]', description: 'Show a flow: structure, inputs, steps and conditions' },
@@ -86,6 +88,26 @@ export function flowsCmd(wrap) {
86
88
  describe: 'Manage Flow Designer flows',
87
89
  builder: (yargs) => {
88
90
  return yargs
91
+ .command({
92
+ command: 'search <term>',
93
+ describe: 'Download/decode visible flows into a private cache and search literal text (first use can be slow)',
94
+ builder: y => y
95
+ .positional('term', { type: 'string', describe: 'Case-insensitive literal text to find in readable definitions' })
96
+ .option('refresh', { type: 'boolean', default: false, describe: 'Rebuild the decoded cache; warm searches still revalidate source access' }),
97
+ handler: wrap(async (argv, app) => {
98
+ app.requireInstance();
99
+ const session = app.session || {};
100
+ const result = await searchFlows({
101
+ sdk: app.sdk, term: argv.term, refresh: argv.refresh,
102
+ context: { profile: session.profileName, username: session.username, domain: session.domain, authMethod: session.profile?.auth_method },
103
+ progress: message => {
104
+ if (!argv.json && !argv.get && (!argv.format || ['auto', 'pretty', 'styled'].includes(argv.format))) process.stderr.write(`${message}\n`);
105
+ },
106
+ });
107
+ Object.defineProperty(result, '_formatted', { value: formatFlowSearch(result), enumerable: false });
108
+ app.ok(result, { summary: `${result.match_count} matching line(s) in ${result.matching_flows} flow(s); ${result.coverage.decoded}/${result.coverage.inventoried} definitions decoded${result.coverage.complete_visible_inventory ? '' : '; PARTIAL/UNKNOWN coverage'}` });
109
+ }),
110
+ })
89
111
  .command({
90
112
  command: 'schemas',
91
113
  describe: 'Read live trigger catalog and input schemas',
@@ -0,0 +1,179 @@
1
+ import { decodeGzipJson } from './sdk.js';
2
+ import fs from 'node:fs/promises';
3
+ import { constants } from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { createHash, randomUUID } from 'node:crypto';
7
+
8
+ const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
9
+ const field = value => String(value && typeof value === 'object' ? value.value ?? '' : value ?? '');
10
+ const TABLE = 'sys_hub_flow';
11
+
12
+ async function secureDirectory(directory) {
13
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
14
+ const stat = await fs.lstat(directory);
15
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (process.getuid && stat.uid !== process.getuid())) throw new Error('Unsafe flow cache directory');
16
+ await fs.chmod(directory, 0o700);
17
+ }
18
+
19
+ async function readCache(file) {
20
+ try {
21
+ const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
22
+ try {
23
+ const stat = await handle.stat();
24
+ if (!stat.isFile() || (stat.mode & 0o077) || (process.getuid && stat.uid !== process.getuid())) throw new Error('Unsafe flow cache file permissions');
25
+ const cache = JSON.parse(await handle.readFile('utf8'));
26
+ return cache.schema === 1 && Array.isArray(cache.flows) ? cache : null;
27
+ } finally { await handle.close(); }
28
+ } catch (error) {
29
+ if (error.code === 'ENOENT' || error instanceof SyntaxError) return null;
30
+ throw error;
31
+ }
32
+ }
33
+
34
+ async function writeCache(file, data) {
35
+ const temporary = `${file}.${randomUUID()}`;
36
+ try {
37
+ await fs.writeFile(temporary, JSON.stringify(data), { flag: 'wx', mode: 0o600 });
38
+ await fs.rename(temporary, file);
39
+ } finally { await fs.rm(temporary, { force: true }); }
40
+ }
41
+
42
+ export function formatFlowSearch(report) {
43
+ const { coverage: c, cache } = report;
44
+ return [
45
+ `${report.match_count} matching line(s) in ${report.matching_flows} flow(s)`,
46
+ ...(cache.disabled_reason ? [cache.disabled_reason] : []),
47
+ `Cache ${cache.state}; prior age ${cache.previous_age_seconds === null ? 'n/a' : `${Math.floor(cache.previous_age_seconds)}s`}; ${cache.reused_definitions} decoded definitions reused. Live source access revalidated.`,
48
+ `Visible inventory: provider ${c.provider_count ?? 'unknown'}, inventoried ${c.inventoried}, downloaded ${c.downloaded}, decoded ${c.decoded}. ${c.complete_visible_inventory ? 'Visible inventory accounted for.' : 'PARTIAL/UNKNOWN coverage.'}`,
49
+ c.scope,
50
+ ...report.matches.map(match => `${match.name} [${match.sys_id}] ${match.source} ${match.path}:${match.line}\n ${match.text}`),
51
+ ...report.failures.map(failure => `FAILED ${failure.stage}: ${failure.name || ''} ${failure.sys_id || ''} ${failure.message}`),
52
+ ].join('\n');
53
+ }
54
+
55
+ export async function searchFlows({ sdk, term, context = {}, refresh = false, cacheRoot, platform = process.platform, pageSize = 100, maxPages = 10000, progress = () => {} }) {
56
+ if (!String(term || '').trim()) throw new Error('A nonempty literal search term is required');
57
+ if (!Number.isInteger(pageSize) || pageSize < 1 || !Number.isInteger(maxPages) || maxPages < 1) throw new Error('Invalid flow pagination bounds');
58
+ const instance = new URL(sdk.baseURL).origin;
59
+ const directory = path.join(cacheRoot || process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'jsn', 'flow-search');
60
+ // Node's Windows mode bits cannot establish a private DACL. Do not touch
61
+ // cache paths (including existing files or reparse points) on that platform.
62
+ const diskCache = platform !== 'win32';
63
+ if (diskCache) await secureDirectory(directory);
64
+ const key = digest({ instance, profile: context.profile || '', username: context.username || '', authMethod: context.authMethod || '', domain: context.domain || '' });
65
+ const file = diskCache ? path.join(directory, `${key}.json`) : null;
66
+ const previous = !diskCache || refresh ? null : await readCache(file);
67
+ const previousById = new Map((previous?.flows || []).map(flow => [flow.sys_id, flow]));
68
+ if (!diskCache) progress('Disk cache disabled on Windows: private ACLs are not verified. Searching freshly downloaded definitions in memory only.');
69
+ if (diskCache) progress(previous ? 'Revalidating flow visibility and source permissions before reusing decoded cache.' : 'Downloading visible flow definitions and decoding a private local cache. First use can be slow; no instance records are changed.');
70
+ const failures = [];
71
+ const get = route => sdk.request(`${instance}${route}`, { method: 'GET' });
72
+ let expected;
73
+ try {
74
+ const response = await get(`/api/now/stats/${TABLE}?sysparm_count=true`);
75
+ const count = response?.result?.stats?.count;
76
+ if (!/^\d+$/.test(String(count))) throw new Error('Missing provider count');
77
+ expected = Number(count);
78
+ if (!Number.isSafeInteger(expected)) throw new Error('Invalid provider count');
79
+ } catch { expected = null; failures.push({ stage: 'inventory_count', message: 'Provider count unavailable; inventory completeness is unknown.' }); }
80
+ const rows = new Map();
81
+ let exhausted = false;
82
+ let offset = 0;
83
+ for (let page = 0; page < maxPages; page++) {
84
+ try {
85
+ const params = new URLSearchParams({ sysparm_query: 'ORDERBYsys_id', sysparm_fields: 'sys_id,name,type,sys_updated_on', sysparm_display_value: 'false', sysparm_limit: String(pageSize), sysparm_offset: String(offset) });
86
+ const response = await get(`/api/now/table/${TABLE}?${params}`);
87
+ if (!Array.isArray(response?.result)) throw new Error('Missing result array; source is unreadable');
88
+ const batch = response.result;
89
+ if (!batch.length) { exhausted = true; break; }
90
+ for (const row of batch) {
91
+ const id = field(row.sys_id);
92
+ if (!/^[0-9a-f]{32}$/i.test(id) || rows.has(id)) throw new Error('Missing/duplicate flow identity; unstable or ACL-filtered pagination');
93
+ rows.set(id, { sys_id: id, name: field(row.name), type: field(row.type), updated: field(row.sys_updated_on) });
94
+ }
95
+ offset += batch.length;
96
+ } catch (error) {
97
+ failures.push({ stage: 'inventory', message: error.message });
98
+ break;
99
+ }
100
+ }
101
+ if (expected !== null && exhausted && rows.size !== expected) failures.push({ stage: 'inventory', message: `Provider count ${expected} differs from ${rows.size} unique visible flow records; ACL filtering or concurrent changes may hide flows.` });
102
+ if (expected !== null) {
103
+ try {
104
+ const after = await get(`/api/now/stats/${TABLE}?sysparm_count=true`);
105
+ if (String(after?.result?.stats?.count) !== String(expected)) throw new Error('Provider count changed during inventory');
106
+ } catch { failures.push({ stage: 'inventory_count', message: 'Provider count changed or became unreadable during inventory; completeness is unknown.' }); }
107
+ }
108
+ if (!exhausted && !failures.some(f => f.stage === 'inventory')) failures.push({ stage: 'inventory', message: 'Pagination safety limit reached; inventory is partial.' });
109
+ const flows = [];
110
+ let downloaded = 0;
111
+ let reused = 0;
112
+ for (const row of rows.values()) {
113
+ let data;
114
+ try {
115
+ // A fresh source read is deliberately mandatory even on a cache hit. A
116
+ // profile/role fingerprint cannot detect field ACLs, impersonation or a
117
+ // revoked permission. Never release old source on a failed live read.
118
+ const response = await get(`/api/now/processflow/flow/${row.sys_id}`);
119
+ const code = response?.result?.errorCode;
120
+ if (response?.result?.errorMessage || (code != null && code !== '' && String(code) !== '0')) throw new Error('Provider refused the flow definition');
121
+ data = response?.result?.data;
122
+ if (data?.security?.can_read === false || data?.security?.can_read === 'false') throw new Error('403 Flow definition read denied');
123
+ if (!data || typeof data !== 'object') throw new Error('No readable ProcessFlow definition');
124
+ downloaded++;
125
+ } catch (error) {
126
+ failures.push({ ...row, stage: 'download', message: error.status === 403 || /403|forbidden/i.test(error.message) ? 'Access denied reading definition' : 'Definition download failed or unavailable', status: error.status || null });
127
+ continue;
128
+ }
129
+ try {
130
+ const sourceDigest = digest(data);
131
+ const cached = previousById.get(row.sys_id);
132
+ const entries = cached?.source_digest === sourceDigest && Array.isArray(cached.entries) ? cached.entries : decodeFlowSearchDefinition(data);
133
+ const unchanged = entries === cached?.entries;
134
+ if (unchanged) reused++;
135
+ flows.push({ ...row, source: `/api/now/processflow/flow/${row.sys_id}`, source_digest: sourceDigest, decoded_at: unchanged ? cached.decoded_at : new Date().toISOString(), entries });
136
+ } catch (error) { failures.push({ ...row, stage: 'decode', message: error.message }); }
137
+ }
138
+ const captured = new Date().toISOString();
139
+ if (diskCache) await writeCache(file, { schema: 1, captured_at: captured, flows });
140
+ const matches = [];
141
+ const needle = String(term).toLowerCase();
142
+ for (const flow of flows) for (const entry of flow.entries) {
143
+ entry.text.split(/\r?\n/).forEach((text, index) => {
144
+ if (text.toLowerCase().includes(needle)) matches.push({ sys_id: flow.sys_id, name: flow.name, source: flow.source, path: entry.path, line: index + 1, text });
145
+ });
146
+ }
147
+ const complete = exhausted && expected !== null && expected === rows.size && !failures.length;
148
+ return {
149
+ term, match_count: matches.length, matching_flows: new Set(matches.map(match => match.sys_id)).size, matches, failures,
150
+ cache: { state: !diskCache ? 'disabled' : refresh ? 'refreshed' : previous ? 'reused' : 'built', disabled_reason: diskCache ? null : 'Windows private cache ACLs are not verified; live in-memory search only', file, captured_at: captured, previous_age_seconds: previous ? Math.max(0, (Date.now() - Date.parse(previous.captured_at)) / 1000) : null, reused_definitions: reused, live_source_revalidation: true },
151
+ coverage: { provider_count: expected, inventoried: rows.size, downloaded, decoded: flows.length, complete_visible_inventory: complete, scope: 'ACL-visible sys_hub_flow ProcessFlow definitions only. Referenced custom action implementation scripts, inaccessible flows, and fields omitted by provider ACLs are not included. No instance-wide completeness claim.' },
152
+ };
153
+ }
154
+
155
+
156
+ // ProcessFlow returns the same definition graph used by flows show. Its values
157
+ // fields can contain the platform's base64-gzip JSON, not plain script text.
158
+ export function decodeFlowSearchDefinition(data) {
159
+ if (!data || typeof data !== 'object' || !['actionInstances', 'triggerInstances', 'flowLogicInstances', 'subFlowInstances'].some(key => Array.isArray(data[key]))) {
160
+ throw new Error('Unsupported definition: no ProcessFlow structure arrays');
161
+ }
162
+ const entries = [];
163
+ function walk(value, path, depth = 0) {
164
+ if (depth > 100) throw new Error(`Definition nesting exceeds decoder limit at ${path}`);
165
+ if (typeof value === 'string') {
166
+ if (value.trim().startsWith('H4sI')) {
167
+ const decoded = decodeGzipJson(value);
168
+ if (decoded === null) throw new Error(`Cannot decode gzip JSON at ${path}`);
169
+ walk(decoded, path, depth + 1);
170
+ } else if (value) entries.push({ path, text: value });
171
+ } else if (Array.isArray(value)) {
172
+ value.forEach((child, index) => walk(child, `${path}[${index}]`, depth + 1));
173
+ } else if (value && typeof value === 'object') {
174
+ for (const [key, child] of Object.entries(value)) walk(child, `${path}.${key}`, depth + 1);
175
+ }
176
+ }
177
+ walk(data, '$');
178
+ return entries;
179
+ }
package/src/output.js CHANGED
@@ -93,6 +93,7 @@ export class OutputWriter {
93
93
  constructor(opts = {}) {
94
94
  this.format = opts.format || FormatAuto;
95
95
  this.writer = opts.writer || process.stdout;
96
+ this.errorWriter = opts.errorWriter || process.stderr;
96
97
  this.jqFilter = opts.jqFilter || '';
97
98
  this.verbose = opts.verbose === true;
98
99
  this.raw = opts.raw === true;
@@ -289,14 +290,27 @@ export class OutputWriter {
289
290
  }
290
291
  }
291
292
 
292
- writeCSV(data, opts) {
293
- if (opts.summary && isTTY(this.writer)) {
294
- this.writer.write(opts.summary + '\n\n');
295
- }
293
+ writeCSV(data, _opts) {
294
+ // CSV stdout contains only the table, even on a terminal. Pagination is
295
+ // diagnostic output, not an extra row that spreadsheet readers must skip.
296
296
  if (Array.isArray(data)) {
297
297
  this.writeCSVTable(data);
298
298
  } else if (data && typeof data === 'object' && Array.isArray(data.records)) {
299
299
  this.writeCSVTable(data.records);
300
+ const page = data.pagination;
301
+ if (page?.hasMore === true) {
302
+ const count = data.records.length;
303
+ const total = Number.isSafeInteger(page.total) && page.total >= 0
304
+ ? ` of ${page.total}` : '';
305
+ const unknown = total ? '' : '; total unknown';
306
+ // List commands advance the requested window, including short pages.
307
+ // Do not guess an offset when the envelope lacks that context.
308
+ const nextOffset = Number.isSafeInteger(page.offset) && page.offset >= 0
309
+ && Number.isSafeInteger(page.limit) && page.limit > 0
310
+ && Number.isSafeInteger(page.offset + page.limit)
311
+ ? `; next offset ${page.offset + page.limit}` : '';
312
+ this.errorWriter.write(`CSV pagination: returned ${count}${total} records${unknown}; more available${nextOffset}.\n`);
313
+ }
300
314
  } else {
301
315
  this.writeCSVTable([data]);
302
316
  }