@jacebenson/jsn 5.5.6-dev.204.1 → 5.5.6-dev.206.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 +1 -1
- package/src/app.js +0 -14
- package/src/auth.js +1 -0
- package/src/cli.js +0 -3
- package/src/sdk.js +1 -42
- package/src/commands/history.js +0 -57
- package/src/mutation-history.js +0 -75
package/package.json
CHANGED
package/src/app.js
CHANGED
|
@@ -7,7 +7,6 @@
|
|
|
7
7
|
// setEffectiveInstance() are thin session-backed shims kept for the many
|
|
8
8
|
// command handlers that already call them.
|
|
9
9
|
|
|
10
|
-
import { appendMutation } from './mutation-history.js';
|
|
11
10
|
import { AuthManager } from './auth.js';
|
|
12
11
|
import { createAuthRecovery } from './auth-recovery.js';
|
|
13
12
|
import { SDKClient } from './sdk.js';
|
|
@@ -65,7 +64,6 @@ export class App {
|
|
|
65
64
|
includeReferenceLinks: this._authArgv?.includeReferenceLinks === true,
|
|
66
65
|
username: session?.username || '',
|
|
67
66
|
recovery: createAuthRecovery({ app: this, session }),
|
|
68
|
-
onMutation: event => this.recordMutation(instance, session?.profileName, event),
|
|
69
67
|
canInteract: () => canUsePicker(this, this._authArgv || {}),
|
|
70
68
|
});
|
|
71
69
|
}
|
|
@@ -76,22 +74,10 @@ export class App {
|
|
|
76
74
|
return new SDKClient(instance, this.auth.createProfileProvider(instance, options), {
|
|
77
75
|
domain: options.domain ?? profile.domain ?? '',
|
|
78
76
|
username: options.username || '',
|
|
79
|
-
onMutation: event => this.recordMutation(instance, options.profileName || null, event),
|
|
80
77
|
canInteract: () => canUsePicker(this, this._authArgv || {}),
|
|
81
78
|
});
|
|
82
79
|
}
|
|
83
80
|
|
|
84
|
-
recordMutation(instance, profile, event) {
|
|
85
|
-
if (!this._authArgv) return;
|
|
86
|
-
try { appendMutation({ ...event, instance, profile, reason: this._authArgv.reason }); }
|
|
87
|
-
catch {
|
|
88
|
-
if (!this._historyWarningShown) {
|
|
89
|
-
process.stderr.write('Warning: local mutation history could not be saved. The remote result is unchanged.\n');
|
|
90
|
-
this._historyWarningShown = true;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
|
|
95
81
|
loadContext() {
|
|
96
82
|
this.context = contextFromSession(this.session, this.config);
|
|
97
83
|
}
|
package/src/auth.js
CHANGED
|
@@ -403,6 +403,7 @@ export class AuthManager {
|
|
|
403
403
|
*/
|
|
404
404
|
buildAuthURL(instanceURL, waitFile, username = this._activeUsername()) {
|
|
405
405
|
instanceURL = normalizeInstanceURL(instanceURL);
|
|
406
|
+
assertCredentialTransport(instanceURL);
|
|
406
407
|
const clientID = getOAuthClientID();
|
|
407
408
|
const pkce = generatePKCE();
|
|
408
409
|
savePKCEState(instanceURL, pkce, username);
|
package/src/cli.js
CHANGED
|
@@ -80,7 +80,6 @@ import { atfCmd } from './commands/atf.js';
|
|
|
80
80
|
import { scanCmd } from './commands/scan.js';
|
|
81
81
|
import { storeCmd } from './commands/store.js';
|
|
82
82
|
import { approvalsCmd } from './commands/approvals.js';
|
|
83
|
-
import { historyCmd } from './commands/history.js';
|
|
84
83
|
import { perfCmd } from './commands/perf.js';
|
|
85
84
|
import { customizationsCmd } from './commands/customizations.js';
|
|
86
85
|
import { midserversCmd } from './commands/midservers.js';
|
|
@@ -155,7 +154,6 @@ export function buildCLI() {
|
|
|
155
154
|
])
|
|
156
155
|
.options({
|
|
157
156
|
'all-commands': { type: 'boolean', describe: 'Show the full command list, including admin and developer tools' },
|
|
158
|
-
reason: { type: 'string', describe: 'Optional non-sensitive reason saved in local mutation history' },
|
|
159
157
|
|
|
160
158
|
force: {
|
|
161
159
|
type: 'boolean',
|
|
@@ -449,7 +447,6 @@ export function buildCLI() {
|
|
|
449
447
|
.command(approvalsCmd(wrap))
|
|
450
448
|
.command(skippedUpdatesCmd(wrap))
|
|
451
449
|
.command(perfCmd(wrap))
|
|
452
|
-
.command(historyCmd(wrap))
|
|
453
450
|
.command(customizationsCmd(wrap))
|
|
454
451
|
.command(midserversCmd(wrap))
|
|
455
452
|
.command(diffCmd(wrap))
|
package/src/sdk.js
CHANGED
|
@@ -83,7 +83,6 @@ export class SDKClient {
|
|
|
83
83
|
this.baseURL = baseURL.replace(/\/$/, '');
|
|
84
84
|
this.authProvider = authProvider;
|
|
85
85
|
this.recovery = opts.recovery;
|
|
86
|
-
this.onMutation = opts.onMutation;
|
|
87
86
|
this.timeout = opts.timeout || DEFAULT_TIMEOUT;
|
|
88
87
|
this.domain = opts.domain || '';
|
|
89
88
|
this.includeReferenceLinks = opts.includeReferenceLinks === true;
|
|
@@ -164,43 +163,7 @@ export class SDKClient {
|
|
|
164
163
|
// Keep the timeout alive through body consumption for text/JSON requests.
|
|
165
164
|
// Raw-response callers retain their existing timeout boundary at headers.
|
|
166
165
|
async _withAuthenticatedRequest(endpoint, opts, settings, consume = (response) => response) {
|
|
167
|
-
|
|
168
|
-
const match = url.pathname.match(/^\/api\/now\/table\/([^/]+)(?:\/([^/]+))?\/?$/);
|
|
169
|
-
const operation = { POST: 'create', PUT: 'update', PATCH: 'update', DELETE: 'delete' }[(opts.method || 'GET').toUpperCase()];
|
|
170
|
-
const event = match && operation && this.onMutation ? {
|
|
171
|
-
table: decodeURIComponent(match[1]), sys_id: match[2] ? decodeURIComponent(match[2]) : null, operation,
|
|
172
|
-
} : null;
|
|
173
|
-
let result;
|
|
174
|
-
try {
|
|
175
|
-
result = await this._performAuthenticatedRequest(endpoint, opts, settings, async response => {
|
|
176
|
-
if (event) event.http_status = response.status;
|
|
177
|
-
const value = await consume(response);
|
|
178
|
-
if (event && value instanceof Response && response.ok && operation === 'create') {
|
|
179
|
-
try { event.sys_id = (await response.clone().json())?.result?.sys_id || null; } catch { /* ID remains unknown. */ }
|
|
180
|
-
}
|
|
181
|
-
return value;
|
|
182
|
-
});
|
|
183
|
-
} catch (error) {
|
|
184
|
-
if (event && !error?.notSent && error?.name !== 'PromptCancelled') await this._reportMutation({ ...event, outcome: error.status >= 400 && error.status < 500 && error.status !== 408
|
|
185
|
-
? 'failed' : 'unknown', http_status: error.status || null });
|
|
186
|
-
throw error;
|
|
187
|
-
}
|
|
188
|
-
if (event) {
|
|
189
|
-
let body = result;
|
|
190
|
-
if (typeof body === 'string') { try { body = JSON.parse(body); } catch { body = null; } }
|
|
191
|
-
const id = body?.result?.sys_id;
|
|
192
|
-
if (typeof id === 'string') event.sys_id = id;
|
|
193
|
-
else if (typeof id?.value === 'string') event.sys_id = id.value;
|
|
194
|
-
await this._reportMutation({ ...event, outcome: event.http_status >= 400
|
|
195
|
-
? (event.http_status < 500 && event.http_status !== 408 ? 'failed' : 'unknown')
|
|
196
|
-
: (event.sys_id ? 'succeeded' : 'unknown') });
|
|
197
|
-
}
|
|
198
|
-
return result;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
async _reportMutation(event) {
|
|
202
|
-
// History failures must never change the outcome of a completed remote write.
|
|
203
|
-
try { await this.onMutation(event); } catch { /* App callback reports local storage failures. */ }
|
|
166
|
+
return this._performAuthenticatedRequest(endpoint, opts, settings, consume);
|
|
204
167
|
}
|
|
205
168
|
|
|
206
169
|
async _performAuthenticatedRequest(endpoint, opts, {
|
|
@@ -975,7 +938,6 @@ export class SDKClient {
|
|
|
975
938
|
form.set('sysparm_upload_prefix', '');
|
|
976
939
|
form.set('sysparm_referring_url', 'sys_remote_update_set_list.do');
|
|
977
940
|
form.set('attachFile', new Blob([xml], { type: 'application/xml' }), filename);
|
|
978
|
-
let outcome = 'unknown';
|
|
979
941
|
try {
|
|
980
942
|
await this.rawRequest(`${this.baseURL}/sys_upload.do`, { method: 'POST', body: form,
|
|
981
943
|
headers: { ...(cookies ? { Cookie: cookies } : {}), 'X-UserToken': csrf, Referer: formURL },
|
|
@@ -1001,12 +963,9 @@ export class SDKClient {
|
|
|
1001
963
|
const member = actual.get(expected.sys_id);
|
|
1002
964
|
return !member || getStringField(member, 'name') !== expected.name || getStringField(member, 'action') !== expected.action;
|
|
1003
965
|
})) throw new Error('Uploaded update set members did not match the XML export');
|
|
1004
|
-
outcome = 'succeeded';
|
|
1005
966
|
return { sys_id: importedID, state, count: members.length, link: `${this.baseURL}/sys_remote_update_set.do?sys_id=${importedID}` };
|
|
1006
967
|
} catch (error) {
|
|
1007
968
|
throw new AppError(CodeAPI, `XML import could not be verified: ${error.message}. It may have partially loaded; inspect Retrieved Update Sets before retrying. No automatic retry was attempted.`, 'Inspect Retrieved Update Sets before retrying.', 0, error);
|
|
1008
|
-
} finally {
|
|
1009
|
-
if (this.onMutation) await this._reportMutation({ table: 'sys_remote_update_set', sys_id: id, operation: 'create', outcome });
|
|
1010
969
|
}
|
|
1011
970
|
}
|
|
1012
971
|
|
package/src/commands/history.js
DELETED
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
import { declareCapabilities } from '../capabilities.js';
|
|
2
|
-
import { listHistory, pruneHistory } from '../mutation-history.js';
|
|
3
|
-
|
|
4
|
-
export function historyCmd(wrap) {
|
|
5
|
-
declareCapabilities('history', { noInstance: true, skipDailyChecks: true });
|
|
6
|
-
const list = wrap(async (argv, app) => {
|
|
7
|
-
const entries = listHistory({ ...argv, instance: argv['instance-url'], profile: argv['profile-name'] });
|
|
8
|
-
app.ok({ entries, retentionDays: 7, _formatted: renderHistory(entries, { details: argv.details }) });
|
|
9
|
-
});
|
|
10
|
-
const filters = b => b
|
|
11
|
-
.option('details', { type: 'boolean', default: false, describe: 'Show full record IDs, instance URLs and reasons' })
|
|
12
|
-
.option('since', { type: 'string', describe: 'Earliest ISO timestamp' })
|
|
13
|
-
.option('until', { type: 'string', describe: 'Latest ISO timestamp' })
|
|
14
|
-
.option('instance-url', { type: 'string', describe: 'Filter by instance origin' })
|
|
15
|
-
.option('profile-name', { type: 'string', describe: 'Filter by recorded profile name (including removed profiles)' })
|
|
16
|
-
.option('table', { type: 'string', describe: 'Filter by table' })
|
|
17
|
-
.option('operation', { choices: ['create', 'update', 'delete'], type: 'string' })
|
|
18
|
-
.option('record', { type: 'string', describe: 'Filter by full resolved sys_id' })
|
|
19
|
-
.option('limit', { type: 'number', default: 50, describe: 'Maximum entries (1–10000)' });
|
|
20
|
-
return { command: 'history [subcommand]', describe: 'Local seven-day mutation history (not a durable ServiceNow audit)',
|
|
21
|
-
builder: y => filters(y).command({ command: 'list', describe: 'List local mutations', builder: filters, handler: list })
|
|
22
|
-
.command({ command: 'prune', describe: 'Remove expired entries only', handler: wrap(async (_argv, app) => {
|
|
23
|
-
app.ok({ ...pruneHistory(), _formatted: 'Expired local history removed; seven days retained.' });
|
|
24
|
-
}) }), handler: list };
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export function renderHistory(entries, { details = false, timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone } = {}) {
|
|
28
|
-
if (!entries.length) return 'No local mutations in the last seven days.';
|
|
29
|
-
const date = new Intl.DateTimeFormat('en-GB', { timeZone, month: 'short', day: '2-digit',
|
|
30
|
-
hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });
|
|
31
|
-
// Strip terminal control characters from stored identifiers and labels.
|
|
32
|
-
// eslint-disable-next-line no-control-regex
|
|
33
|
-
const clean = value => String(value ?? '').replace(/[\x00-\x1f\x7f]/g, ' ');
|
|
34
|
-
const clip = (value, length) => value.length > length ? `${value.slice(0, length - 1)}…` : value;
|
|
35
|
-
const rows = entries.map(entry => {
|
|
36
|
-
let connection = entry.profile;
|
|
37
|
-
if (!connection) {
|
|
38
|
-
try { connection = new URL(entry.instance).host; } catch { connection = entry.instance; }
|
|
39
|
-
}
|
|
40
|
-
return [date.format(new Date(entry.timestamp)), entry.operation, clip(clean(entry.table), 22),
|
|
41
|
-
clip(clean(entry.sys_id || '(unknown)'), 12), entry.outcome, clip(clean(connection), 22)];
|
|
42
|
-
});
|
|
43
|
-
const headers = ['WHEN', 'ACTION', 'TABLE', 'RECORD', 'RESULT', 'CONNECTION'];
|
|
44
|
-
const widths = headers.map((header, i) => Math.max(header.length, ...rows.map(row => row[i].length)));
|
|
45
|
-
const format = row => row.map((cell, i) => cell.padEnd(widths[i])).join(' ').trimEnd();
|
|
46
|
-
const lines = [`Recent mutations · ${timeZone}`, '', format(headers)];
|
|
47
|
-
rows.forEach((row, i) => {
|
|
48
|
-
lines.push(format(row));
|
|
49
|
-
if (details) {
|
|
50
|
-
const entry = entries[i];
|
|
51
|
-
lines.push(` ${clean(entry.timestamp)} · ${clean(entry.table)}/${clean(entry.sys_id || '(unknown)')}`,
|
|
52
|
-
` ${clean(entry.instance)}${entry.reason ? ` · ${clean(entry.reason)}` : ''}`);
|
|
53
|
-
}
|
|
54
|
-
});
|
|
55
|
-
if (!details) lines.push('', 'Use --details for full IDs, URLs and reasons; --json for structured history.');
|
|
56
|
-
return lines.join('\n');
|
|
57
|
-
}
|
package/src/mutation-history.js
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
// Local convenience history, independent of documentation indexes and sync.
|
|
2
|
-
import Database from 'better-sqlite3';
|
|
3
|
-
import fs from 'node:fs';
|
|
4
|
-
import os from 'node:os';
|
|
5
|
-
import path from 'node:path';
|
|
6
|
-
import { errUsage } from './errors.js';
|
|
7
|
-
|
|
8
|
-
export const RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
|
|
9
|
-
const operations = ['create', 'update', 'delete'];
|
|
10
|
-
const outcomes = ['succeeded', 'failed', 'unknown'];
|
|
11
|
-
export function historyPath() {
|
|
12
|
-
return path.join(process.env.JSN_DATA_HOME || path.join(os.homedir(), '.jsn'), 'history.db');
|
|
13
|
-
}
|
|
14
|
-
function openHistory(filename, now) {
|
|
15
|
-
fs.mkdirSync(path.dirname(filename), { recursive: true, mode: 0o700 });
|
|
16
|
-
const db = new Database(filename);
|
|
17
|
-
try {
|
|
18
|
-
if (process.platform !== 'win32') fs.chmodSync(filename, 0o600);
|
|
19
|
-
db.pragma('busy_timeout = 3000');
|
|
20
|
-
db.exec(`CREATE TABLE IF NOT EXISTS mutation_history (
|
|
21
|
-
id INTEGER PRIMARY KEY, timestamp INTEGER NOT NULL, instance TEXT NOT NULL,
|
|
22
|
-
profile TEXT, table_name TEXT NOT NULL, sys_id TEXT, operation TEXT NOT NULL,
|
|
23
|
-
outcome TEXT NOT NULL, reason TEXT, http_status INTEGER
|
|
24
|
-
); CREATE INDEX IF NOT EXISTS mutation_history_time ON mutation_history(timestamp)`);
|
|
25
|
-
db.prepare('DELETE FROM mutation_history WHERE timestamp < ?').run(now - RETENTION_MS);
|
|
26
|
-
return db;
|
|
27
|
-
} catch (error) { db.close(); throw error; }
|
|
28
|
-
}
|
|
29
|
-
export function sanitizeReason(value) {
|
|
30
|
-
if (!value) return null;
|
|
31
|
-
// eslint-disable-next-line no-control-regex -- strip controls from user-supplied prose
|
|
32
|
-
return String(value).replace(/[\u0000-\u001f\u007f]/g, ' ')
|
|
33
|
-
.replace(/\b(?:Bearer|Basic)\s+\S+/gi, '[redacted]')
|
|
34
|
-
.replace(/\b(password|token|cookie|secret|authorization|access_token|sysparm_ck)\s*[:=]\s*(?:"[^"]*"|'[^']*'|\S+)/gi, '$1=[redacted]')
|
|
35
|
-
.slice(0, 1000);
|
|
36
|
-
}
|
|
37
|
-
export function appendMutation(event, { filename = historyPath(), now = Date.now() } = {}) {
|
|
38
|
-
if (!operations.includes(event.operation) || !outcomes.includes(event.outcome)) throw errUsage('Invalid history event');
|
|
39
|
-
const instance = new URL(event.instance).origin;
|
|
40
|
-
// Deliberate whitelist: never serialize SDK options, response bodies, or payloads.
|
|
41
|
-
const row = { timestamp: now, instance, profile: event.profile || null,
|
|
42
|
-
table_name: event.table, sys_id: event.sys_id || null, operation: event.operation,
|
|
43
|
-
outcome: event.outcome, reason: sanitizeReason(event.reason), http_status: event.http_status || null };
|
|
44
|
-
const db = openHistory(filename, now);
|
|
45
|
-
try {
|
|
46
|
-
db.prepare(`INSERT INTO mutation_history
|
|
47
|
-
(timestamp,instance,profile,table_name,sys_id,operation,outcome,reason,http_status)
|
|
48
|
-
VALUES (@timestamp,@instance,@profile,@table_name,@sys_id,@operation,@outcome,@reason,@http_status)`).run(row);
|
|
49
|
-
} finally { db.close(); }
|
|
50
|
-
}
|
|
51
|
-
export function pruneHistory({ filename = historyPath(), now = Date.now() } = {}) {
|
|
52
|
-
const db = openHistory(filename, now);
|
|
53
|
-
try { return { retentionDays: 7 }; } finally { db.close(); }
|
|
54
|
-
}
|
|
55
|
-
export function listHistory(filters = {}, { filename = historyPath(), now = Date.now() } = {}) {
|
|
56
|
-
const where = [], values = [];
|
|
57
|
-
for (const [key, column] of Object.entries({ instance: 'instance', profile: 'profile', table: 'table_name', operation: 'operation', record: 'sys_id' })) {
|
|
58
|
-
if (filters[key]) { where.push(`${column} = ?`); values.push(key === 'instance' ? new URL(filters[key]).origin : filters[key]); }
|
|
59
|
-
}
|
|
60
|
-
for (const [key, operator] of [['since', '>='], ['until', '<=']]) {
|
|
61
|
-
if (filters[key]) {
|
|
62
|
-
const time = Date.parse(filters[key]);
|
|
63
|
-
if (!Number.isFinite(time)) throw errUsage(`Invalid --${key} timestamp; use an ISO date`);
|
|
64
|
-
where.push(`timestamp ${operator} ?`); values.push(time);
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
const limit = filters.limit ?? 50;
|
|
68
|
-
if (!Number.isInteger(limit) || limit < 1 || limit > 10000) throw errUsage('--limit must be an integer from 1 to 10000');
|
|
69
|
-
const db = openHistory(filename, now);
|
|
70
|
-
try {
|
|
71
|
-
return db.prepare(`SELECT id,timestamp,instance,profile,table_name AS "table",sys_id,operation,outcome,reason,http_status
|
|
72
|
-
FROM mutation_history ${where.length ? `WHERE ${where.join(' AND ')}` : ''} ORDER BY timestamp DESC,id DESC LIMIT ?`)
|
|
73
|
-
.all(...values, limit).map(row => ({ ...row, timestamp: new Date(row.timestamp).toISOString() }));
|
|
74
|
-
} finally { db.close(); }
|
|
75
|
-
}
|