@jacebenson/jsn 5.5.1-dev.170.1 → 5.5.1-dev.172.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/README.md +1 -1
- package/package.json +1 -1
- package/src/app.js +3 -1
- package/src/auth/mfa.js +85 -0
- package/src/cli-adapter.js +8 -2
- package/src/cli.js +8 -2
- package/src/commands/approvals.js +1 -0
- package/src/commands/discover.js +1 -0
- package/src/commands/knowledge.js +1 -0
- package/src/commands/records.js +1 -0
- package/src/commands/setup.js +1 -0
- package/src/errors.js +23 -1
- package/src/help.js +93 -20
- package/src/helpers.js +4 -1
- package/src/prompts.js +9 -0
- package/src/record-command-profiles.js +8 -4
- package/src/record-profiles.js +1 -0
- package/src/sdk.js +129 -16
package/README.md
CHANGED
|
@@ -121,7 +121,7 @@ jsn records list --table incident --limit 10 --json
|
|
|
121
121
|
jsn flows list
|
|
122
122
|
```
|
|
123
123
|
|
|
124
|
-
Run `jsn --help` for the command
|
|
124
|
+
Run `jsn --help` for a concise command overview, or `jsn --all-commands --help` for the complete command and flag reference. See the [CLI guide](https://github.com/jacebenson/jsn/blob/main/docs/cli-guide.md) for authentication, output formats, development, and examples. The [docs site](https://jacebenson.github.io/jsn/) has feature guides.
|
|
125
125
|
|
|
126
126
|
## AI agents
|
|
127
127
|
|
package/package.json
CHANGED
package/src/app.js
CHANGED
|
@@ -16,7 +16,7 @@ import { saveConfig } from './config.js';
|
|
|
16
16
|
import { resolveSession, applySession, contextFromSession, requireSessionInstance } from './session.js';
|
|
17
17
|
import { getCurrentUser, getCurrentApplication, getCurrentUpdateSet } from './context.js';
|
|
18
18
|
import { errUsage, errAuth } from './errors.js';
|
|
19
|
-
import { canPrompt } from './helpers.js';
|
|
19
|
+
import { canPrompt, canUsePicker } from './helpers.js';
|
|
20
20
|
import { guardMutationContext } from './mutation-context.js';
|
|
21
21
|
import process from 'node:process';
|
|
22
22
|
|
|
@@ -63,6 +63,7 @@ export class App {
|
|
|
63
63
|
username: session?.username || '',
|
|
64
64
|
recovery: createAuthRecovery({ app: this, session }),
|
|
65
65
|
onMutation: event => this.recordMutation(instance, session?.profileName, event),
|
|
66
|
+
canInteract: () => canUsePicker(this, this._authArgv || {}),
|
|
66
67
|
});
|
|
67
68
|
}
|
|
68
69
|
|
|
@@ -73,6 +74,7 @@ export class App {
|
|
|
73
74
|
domain: options.domain ?? profile.domain ?? '',
|
|
74
75
|
username: options.username || '',
|
|
75
76
|
onMutation: event => this.recordMutation(instance, options.profileName || null, event),
|
|
77
|
+
canInteract: () => canUsePicker(this, this._authArgv || {}),
|
|
76
78
|
});
|
|
77
79
|
}
|
|
78
80
|
|
package/src/auth/mfa.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// ServiceNow TOTP challenge helpers for Basic authentication (issue #402).
|
|
2
|
+
//
|
|
3
|
+
// The flow mirrors the platform's own login page, as implemented by
|
|
4
|
+
// @servicenow/sdk-cli 4.13.0's UISession:
|
|
5
|
+
//
|
|
6
|
+
// 1. POST /angular.do?sysparm_type=view_form.login → JSON { status:
|
|
7
|
+
// 'mfa_code_required' } with a session cookie but no authenticated user.
|
|
8
|
+
// 2. GET /validate_multifactor_auth_code.do → HTML form holding
|
|
9
|
+
// sysparm_ck and sysparm_process_nonce.
|
|
10
|
+
// 3. POST /validate_mfa_code.do → 302 on success; 200 with
|
|
11
|
+
// x-mfa_token: invalid when the code is rejected.
|
|
12
|
+
// 4. POST /angular.do?sysparm_type=get_user → session user token.
|
|
13
|
+
//
|
|
14
|
+
// The wire shape is observed from that reference client, not verified here
|
|
15
|
+
// against a live MFA-enabled instance (none is available in this workspace).
|
|
16
|
+
// Only the exact challenge marker enters MFA. Once recognized, failures
|
|
17
|
+
// must remain terminal; callers may not fall back to Basic headers.
|
|
18
|
+
//
|
|
19
|
+
// Codes are ephemeral: these helpers return them only to the caller's request
|
|
20
|
+
// body. Nothing in this module logs, caches, or persists a code.
|
|
21
|
+
|
|
22
|
+
export const MFA_REQUIRED_STATUS = 'mfa_code_required';
|
|
23
|
+
export const MFA_INVALID_TOKEN_HEADER_VALUE = 'invalid';
|
|
24
|
+
|
|
25
|
+
/** Read the login endpoint's JSON body without trusting its content type. */
|
|
26
|
+
export function parseLoginStatus(body) {
|
|
27
|
+
if (typeof body !== 'string' || body.trim() === '') return null;
|
|
28
|
+
let parsed;
|
|
29
|
+
try {
|
|
30
|
+
parsed = JSON.parse(body);
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
|
|
35
|
+
const status = typeof parsed.status === 'string' ? parsed.status : '';
|
|
36
|
+
const message = typeof parsed.message === 'string' ? parsed.message : '';
|
|
37
|
+
return { status, message };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Extract the hidden anti-CSRF and nonce fields from the MFA validation page.
|
|
42
|
+
* Accepts either attribute order so a form-layout change does not break login.
|
|
43
|
+
*/
|
|
44
|
+
export function extractMfaFormTokens(html) {
|
|
45
|
+
const text = String(html ?? '');
|
|
46
|
+
const read = (name) => {
|
|
47
|
+
const pattern = new RegExp(
|
|
48
|
+
`name=["']${name}["'][^>]*value=["']([^"']+)["']|value=["']([^"']+)["'][^>]*name=["']${name}["']`,
|
|
49
|
+
'i',
|
|
50
|
+
);
|
|
51
|
+
const match = text.match(pattern);
|
|
52
|
+
return match ? (match[1] ?? match[2] ?? '') : '';
|
|
53
|
+
};
|
|
54
|
+
return { csrf: read('sysparm_ck'), processNonce: read('sysparm_process_nonce') };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The TOTP verification form body the platform page posts. */
|
|
58
|
+
export function buildMfaVerificationBody({ csrf, processNonce, code }) {
|
|
59
|
+
return new URLSearchParams({
|
|
60
|
+
sysparm_ck: csrf,
|
|
61
|
+
sysparm_process_nonce: processNonce,
|
|
62
|
+
sys_action: 'sysverb_validate_mfa_code',
|
|
63
|
+
sys_mfa_check_remembered_browser: 'false',
|
|
64
|
+
// Browser-fingerprint fields are only used for "remember this device";
|
|
65
|
+
// JSN authenticates one session at a time, so they stay empty.
|
|
66
|
+
bfp: '',
|
|
67
|
+
bfp_hash: '',
|
|
68
|
+
sys_web_authentication_successful: 'false',
|
|
69
|
+
sys_web_authentication_response: '',
|
|
70
|
+
sys_web_authn_registration_successful: 'false',
|
|
71
|
+
sys_web_authn_registration_skipped: 'false',
|
|
72
|
+
sys_mfa_factor_validate: 'TOTP',
|
|
73
|
+
sys_show_works_with_sn_enabled: 'true',
|
|
74
|
+
mfa_factor: 'mfa_TOTP_div',
|
|
75
|
+
txtResponse: code,
|
|
76
|
+
txtResponse_email: '',
|
|
77
|
+
txtResponse_sms: '',
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Trim human separators and require six decimal digits. */
|
|
82
|
+
export function normalizeTotpCode(value) {
|
|
83
|
+
const digits = String(value ?? '').replace(/[\s-]/g, '');
|
|
84
|
+
return /^\d{6}$/.test(digits) ? digits : '';
|
|
85
|
+
}
|
package/src/cli-adapter.js
CHANGED
|
@@ -293,12 +293,16 @@ export class LocalCLI {
|
|
|
293
293
|
* discovery output are generated from, so neither can drift away from the
|
|
294
294
|
* commands that actually exist. Builders run here (idempotently) because a
|
|
295
295
|
* parent's children are only registered when its builder is invoked.
|
|
296
|
+
*
|
|
297
|
+
* `summaries: true` adds the command's short summary for the concise human
|
|
298
|
+
* help page. Machine discovery leaves it out, so the JSON schema and bytes
|
|
299
|
+
* stay unchanged.
|
|
296
300
|
*/
|
|
297
|
-
commandRegistry() {
|
|
301
|
+
commandRegistry({ summaries = false } = {}) {
|
|
298
302
|
const visible = (node) => node.name !== this.completionCommand && !node.definition.hidden;
|
|
299
303
|
const serialize = (node) => {
|
|
300
304
|
node.build();
|
|
301
|
-
|
|
305
|
+
const entry = {
|
|
302
306
|
name: node.name,
|
|
303
307
|
command: node.definition.command || node.name,
|
|
304
308
|
aliases: [...node.aliases],
|
|
@@ -312,6 +316,8 @@ export class LocalCLI {
|
|
|
312
316
|
help: `jsn ${node.name} ${child.name} --help`,
|
|
313
317
|
})),
|
|
314
318
|
};
|
|
319
|
+
if (summaries) entry.summary = node.definition.summary || '';
|
|
320
|
+
return entry;
|
|
315
321
|
};
|
|
316
322
|
return {
|
|
317
323
|
commands: this.root.children.filter(visible).map(serialize),
|
package/src/cli.js
CHANGED
|
@@ -605,7 +605,11 @@ export function buildCLI() {
|
|
|
605
605
|
// non-interactive discovery retain their existing reference output.
|
|
606
606
|
const config = loadConfig(formatArgv);
|
|
607
607
|
const welcome = maybeShowHome({ argv: formatArgv, requestedFormat, cfg: config });
|
|
608
|
-
if (!welcome)
|
|
608
|
+
if (!welcome) {
|
|
609
|
+
const registry = visibleCommandRegistry(
|
|
610
|
+
cliInstance.commandRegistry({ summaries: true }), config, formatArgv);
|
|
611
|
+
process.stdout.write(renderHelp(config, registry, { full: formatArgv?.allCommands === true }) + '\n');
|
|
612
|
+
}
|
|
609
613
|
process.exit(0);
|
|
610
614
|
}
|
|
611
615
|
// Every other failure here (unknown command, missing required argument,
|
|
@@ -628,7 +632,9 @@ export function buildCLI() {
|
|
|
628
632
|
cliInstance.rootHelpRenderer = () => {
|
|
629
633
|
const options = cliInstance.parseGlobalOptions(process.argv.slice(2));
|
|
630
634
|
const config = loadConfig(options);
|
|
631
|
-
|
|
635
|
+
const registry = visibleCommandRegistry(
|
|
636
|
+
cliInstance.commandRegistry({ summaries: true }), config, options);
|
|
637
|
+
return renderHelp(config, registry, { full: options?.allCommands === true });
|
|
632
638
|
};
|
|
633
639
|
|
|
634
640
|
// Snapshot the root command names (plus aliases) for the completion
|
|
@@ -173,6 +173,7 @@ export function approvalsCmd(wrap) {
|
|
|
173
173
|
return {
|
|
174
174
|
command: 'approvals [subcommand]',
|
|
175
175
|
describe: 'Manage approval requests (list, approve, reject, submit, history)',
|
|
176
|
+
summary: 'List, approve, or reject approval requests',
|
|
176
177
|
builder: (yargs) => {
|
|
177
178
|
return yargs
|
|
178
179
|
.command({
|
package/src/commands/discover.js
CHANGED
|
@@ -20,6 +20,7 @@ export function discoverCmd(wrap, getRegistry) {
|
|
|
20
20
|
return {
|
|
21
21
|
command: 'discover [query]',
|
|
22
22
|
describe: 'Find commands by words in their names, aliases, descriptions, or configured table',
|
|
23
|
+
summary: 'Find commands by task word or table',
|
|
23
24
|
builder: y => y
|
|
24
25
|
.positional('query', { type: 'string', describe: 'Search words (quote multiple words)' })
|
|
25
26
|
.option('table', { type: 'string', describe: 'Find specialized commands configured for this exact table' })
|
|
@@ -26,6 +26,7 @@ export function knowledgeCmd(wrap) {
|
|
|
26
26
|
return {
|
|
27
27
|
command: 'knowledge [subcommand]', aliases: ['kb'],
|
|
28
28
|
describe: 'Search and read knowledge articles through the Knowledge API',
|
|
29
|
+
summary: 'Search and read knowledge articles',
|
|
29
30
|
handler: wrap(async (argv, app) => emit(app, argv,
|
|
30
31
|
{ subcommands: argv.subcommands || [], _formatted: formatCommandList({ title: 'Knowledge articles', commands: argv.subcommands || [] }) },
|
|
31
32
|
'Search and read knowledge articles', [{ action: 'search', cmd: 'jsn knowledge search <text>', description: 'Find accessible articles' }])),
|
package/src/commands/records.js
CHANGED
|
@@ -83,6 +83,7 @@ export function recordsCmd(wrap) {
|
|
|
83
83
|
return {
|
|
84
84
|
command: 'records [subcommand]',
|
|
85
85
|
describe: 'Query and manage records in any table (e.g. "records list --table incident --query priority=1")',
|
|
86
|
+
summary: 'Query any table when no specialized command fits',
|
|
86
87
|
builder: (yargs) => {
|
|
87
88
|
return yargs
|
|
88
89
|
.command({
|
package/src/commands/setup.js
CHANGED
|
@@ -121,6 +121,7 @@ export function setupCmd(wrap) {
|
|
|
121
121
|
return {
|
|
122
122
|
command: 'setup',
|
|
123
123
|
describe: 'Set up JSN defaults and manage ServiceNow connections (interactive)',
|
|
124
|
+
summary: 'Connect to ServiceNow and manage profiles',
|
|
124
125
|
builder: y => y.option('docs-source', { type: 'string', choices: ['snapshot', 'github', 'skip'], describe: 'Install optional documentation directly without the authentication wizard' })
|
|
125
126
|
.option('configure-defaults', { type: 'boolean', describe: 'Configure defaults for future connections without the hub' })
|
|
126
127
|
.option('configure-docs', { type: 'boolean', describe: 'Configure documentation without the hub' }).epilogue(setupHelp()),
|
package/src/errors.js
CHANGED
|
@@ -3,6 +3,28 @@
|
|
|
3
3
|
export const CodeUsage = 'usage_error';
|
|
4
4
|
export const CodeNotFound = 'not_found';
|
|
5
5
|
export const CodeAuth = 'auth_error';
|
|
6
|
+
export const CodeMfaRequired = 'mfa_required';
|
|
7
|
+
export const CodeMfaRejected = 'mfa_code_rejected';
|
|
8
|
+
|
|
9
|
+
// These errors are terminal for the invocation and precede operation dispatch.
|
|
10
|
+
export function errMfaRequired() {
|
|
11
|
+
const error = new AppError(CodeMfaRequired,
|
|
12
|
+
'Multi-factor authentication requires a six-digit authenticator code.',
|
|
13
|
+
'Re-run in an interactive terminal without --json/--get, or explicitly configure OAuth or a browser session with jsn auth login. JSN never stores TOTP seeds or generates codes.');
|
|
14
|
+
error.notSent = true;
|
|
15
|
+
return error;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function errMfaRejected() {
|
|
19
|
+
const error = new AppError(CodeMfaRejected, 'MFA verification could not establish the selected authenticated session.',
|
|
20
|
+
'The challenge failed, expired, or could not be verified. Re-run the command to start a new challenge.');
|
|
21
|
+
error.notSent = true;
|
|
22
|
+
return error;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function isTerminalAuthError(error) {
|
|
26
|
+
return error?.name === 'PromptCancelled' || error?.code === CodeMfaRequired || error?.code === CodeMfaRejected;
|
|
27
|
+
}
|
|
6
28
|
export const CodeForbidden = 'forbidden';
|
|
7
29
|
export const CodeRateLimit = 'rate_limited';
|
|
8
30
|
export const CodeNetwork = 'network_error';
|
|
@@ -237,7 +259,7 @@ export function renderAppError(err, { app = null, argv = null, identifier = '' }
|
|
|
237
259
|
if (err.name === 'PromptCancelled') return { stream: 'stderr', text: 'Cancelled.\n', exitCode: 0 };
|
|
238
260
|
const code = err.code || 'unknown';
|
|
239
261
|
|
|
240
|
-
if (code === CodeAuth) {
|
|
262
|
+
if (code === CodeAuth || code === CodeMfaRequired || code === CodeMfaRejected) {
|
|
241
263
|
if (resolveJsonMode(app, argv) && app) return { stream: 'stdout', text: null, exitCode: 1, appErr: true };
|
|
242
264
|
let text = `Error (auth): ${err.message}\n`;
|
|
243
265
|
if (err.hint) text += `\nHint: ${err.hint}\n`;
|
package/src/help.js
CHANGED
|
@@ -10,20 +10,49 @@
|
|
|
10
10
|
// (`approvals`, `cmdb`, `docs`, `perf`, `platform`, … were missing from the
|
|
11
11
|
// hand-written list while being fully registered).
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
const COMMON_COMMANDS = [
|
|
14
|
+
'incidents', 'requests', 'tasks', 'changes', 'approvals', 'knowledge', 'records', 'setup', 'discover',
|
|
15
|
+
];
|
|
16
|
+
|
|
17
|
+
const CONCISE_FLAGS = ['instance', 'profile', 'json'];
|
|
18
|
+
|
|
19
|
+
const CONCISE_EXAMPLES = [
|
|
20
|
+
'jsn incidents list --query "active=true" --limit 5',
|
|
21
|
+
'jsn records list --table incident --limit 5 --json',
|
|
22
|
+
'jsn discover catalog',
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
const CONCISE_MORE = [
|
|
26
|
+
{ label: 'jsn <command> <action> --help', description: 'Options for one command or action' },
|
|
27
|
+
{ label: 'jsn discover <word>', description: 'Find commands by task words' },
|
|
28
|
+
{ label: 'jsn discover --table <table>', description: 'Find commands configured for a table' },
|
|
29
|
+
{ label: 'jsn --all-commands --help', description: 'Every registered command and global flag' },
|
|
30
|
+
{ label: 'jsn --json', description: 'Registered command surface as JSON' },
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
function renderGroup(name, commands, width = helpWidth()) {
|
|
14
34
|
const lines = [`\n${name}`];
|
|
15
35
|
lines.push('─'.repeat(50));
|
|
36
|
+
let rows = [];
|
|
37
|
+
const flush = () => {
|
|
38
|
+
if (!rows.length) return;
|
|
39
|
+
lines.push(renderRows(rows, { width, indent: 2 }));
|
|
40
|
+
rows = [];
|
|
41
|
+
};
|
|
16
42
|
for (const cmd of commands) {
|
|
17
43
|
if (cmd.divider) {
|
|
44
|
+
flush();
|
|
18
45
|
lines.push('');
|
|
19
46
|
lines.push(` ${cmd.divider}`);
|
|
20
47
|
continue;
|
|
21
48
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
49
|
+
rows.push({
|
|
50
|
+
label: cmd.name,
|
|
51
|
+
description: cmd.desc,
|
|
52
|
+
note: cmd.alias ? `(${cmd.alias})` : '',
|
|
53
|
+
});
|
|
26
54
|
}
|
|
55
|
+
flush();
|
|
27
56
|
return lines.join('\n');
|
|
28
57
|
}
|
|
29
58
|
|
|
@@ -186,21 +215,57 @@ function rowsFor(hint, byName, used, config) {
|
|
|
186
215
|
return rows;
|
|
187
216
|
}
|
|
188
217
|
|
|
189
|
-
function renderFlags(options) {
|
|
218
|
+
function renderFlags(options, { full = false, width = helpWidth() } = {}) {
|
|
190
219
|
// Derived from the registered global options, so a new global flag cannot be
|
|
191
|
-
// missing from
|
|
192
|
-
|
|
193
|
-
|
|
220
|
+
// missing from the full reference (--get and --csv were, along with the csv
|
|
221
|
+
// format choice). The concise page shows only the flags needed to point a
|
|
222
|
+
// command at an instance and choose machine output.
|
|
223
|
+
const rows = [];
|
|
224
|
+
const specs = full
|
|
225
|
+
? options
|
|
226
|
+
: CONCISE_FLAGS.map((name) => options.find((spec) => spec.name === name)).filter(Boolean);
|
|
227
|
+
for (const spec of specs) {
|
|
194
228
|
if (spec.name === 'help') continue;
|
|
195
229
|
const alias = spec.alias.map(name => `${name.length === 1 ? '-' : '--'}${name}`).join(', ');
|
|
196
230
|
const label = `${alias ? `${alias}, ` : ''}--${spec.name}`;
|
|
197
231
|
const suffix = spec.name === 'format' && spec.choices.length
|
|
198
|
-
? `
|
|
199
|
-
: `
|
|
200
|
-
|
|
232
|
+
? `[string: ${spec.choices.join(', ')}]`
|
|
233
|
+
: `[${spec.type}]`;
|
|
234
|
+
rows.push({ label, description: spec.description, note: suffix });
|
|
201
235
|
}
|
|
202
|
-
|
|
203
|
-
return `\nFLAGS\n${
|
|
236
|
+
rows.push({ label: '--help', description: 'Show help', note: '[boolean]' });
|
|
237
|
+
return `\nFLAGS\n${renderRows(rows, { width, indent: 2 })}`;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* The ordinary root page: common task commands, a few flags, runnable
|
|
242
|
+
* examples, and pointers to the exhaustive reference and local discovery.
|
|
243
|
+
*/
|
|
244
|
+
function renderConciseHelp(config, registry, width) {
|
|
245
|
+
const commands = Array.isArray(registry?.commands) ? registry.commands : [];
|
|
246
|
+
const byName = new Map(commands.map((command) => [command.name, command]));
|
|
247
|
+
const common = COMMON_COMMANDS
|
|
248
|
+
.map((name) => byName.get(name))
|
|
249
|
+
.filter((command) => command && !isCapabilityHidden(command.name, config))
|
|
250
|
+
.map((command) => ({
|
|
251
|
+
name: command.name,
|
|
252
|
+
desc: command.summary || command.description || '',
|
|
253
|
+
}));
|
|
254
|
+
|
|
255
|
+
return [
|
|
256
|
+
'Usage: jsn <command> [options]',
|
|
257
|
+
'',
|
|
258
|
+
'Command-line interface for ServiceNow',
|
|
259
|
+
renderGroup('COMMON COMMANDS', common, width),
|
|
260
|
+
'',
|
|
261
|
+
'EXAMPLES',
|
|
262
|
+
...CONCISE_EXAMPLES.map((example) => ` ${example}`),
|
|
263
|
+
renderFlags(Array.isArray(registry?.options) ? registry.options : [], { width }),
|
|
264
|
+
'',
|
|
265
|
+
'MORE',
|
|
266
|
+
renderRows(CONCISE_MORE, { width, indent: 2 }),
|
|
267
|
+
'',
|
|
268
|
+
].join('\n');
|
|
204
269
|
}
|
|
205
270
|
|
|
206
271
|
export function renderTips() {
|
|
@@ -212,7 +277,7 @@ TIPS
|
|
|
212
277
|
Cross-table task searches and custom tables: "jsn records list --help"
|
|
213
278
|
Specialized commands offer configured columns, lookup, and table-specific views; inspect discovery results for details
|
|
214
279
|
Raw endpoints when needed: "jsn rest --help"; examples and intent guidance: "jsn discover --help"
|
|
215
|
-
Use "jsn <command> --help" for
|
|
280
|
+
Use "jsn <command> <action> --help" for options on one command or action
|
|
216
281
|
"jsn --json" prints the registered command surface as JSON for scripts and agents
|
|
217
282
|
|
|
218
283
|
LEARN MORE
|
|
@@ -223,14 +288,22 @@ LEARN MORE
|
|
|
223
288
|
}
|
|
224
289
|
|
|
225
290
|
/**
|
|
226
|
-
* Render
|
|
291
|
+
* Render root help.
|
|
292
|
+
*
|
|
293
|
+
* The ordinary page is a concise task directory. `full: true` (used by
|
|
294
|
+
* `--all-commands --help`) renders the exhaustive grouped reference: every
|
|
295
|
+
* visible registered command and every registered global option, plus the
|
|
296
|
+
* tips and picker details that would crowd the short page.
|
|
227
297
|
*
|
|
228
298
|
* @param {object} config — profile config (capability-conditioned hiding)
|
|
229
299
|
* @param {{commands: Array, options: Array}} [registry] — from
|
|
230
300
|
* `cli.commandRegistry()`. Without it only the hint tables render, which is
|
|
231
301
|
* the fallback for callers that have no registry (unit tests).
|
|
302
|
+
* @param {{full?: boolean, width?: number}} [opts]
|
|
232
303
|
*/
|
|
233
|
-
export function renderHelp(config, registry = null) {
|
|
304
|
+
export function renderHelp(config, registry = null, { full = false, width = helpWidth() } = {}) {
|
|
305
|
+
if (!full) return renderConciseHelp(config, registry, width);
|
|
306
|
+
|
|
234
307
|
const commands = Array.isArray(registry?.commands) ? registry.commands : [];
|
|
235
308
|
const byName = new Map(commands.map((command) => [command.name, command]));
|
|
236
309
|
const used = new Set();
|
|
@@ -238,14 +311,14 @@ export function renderHelp(config, registry = null) {
|
|
|
238
311
|
const sections = Object.entries(COMMAND_GROUPS)
|
|
239
312
|
.map(([name, hint]) => [name, rowsFor(hint, byName, used, config)])
|
|
240
313
|
.filter(([, rows]) => rows.some((row) => !row.divider))
|
|
241
|
-
.map(([name, rows]) => renderGroup(name, rows));
|
|
314
|
+
.map(([name, rows]) => renderGroup(name, rows, width));
|
|
242
315
|
|
|
243
316
|
// Anything registered that the hint tables don't place. This is the safety
|
|
244
317
|
// net that keeps help complete as commands are added at the root.
|
|
245
318
|
const unplaced = commands
|
|
246
319
|
.filter((command) => !used.has(command.name) && !isCapabilityHidden(command.name, config))
|
|
247
320
|
.map((command) => ({ name: command.name, alias: command.aliases[0] || '', desc: command.description || '' }));
|
|
248
|
-
if (unplaced.length) sections.push(renderGroup('MORE', unplaced));
|
|
321
|
+
if (unplaced.length) sections.push(renderGroup('MORE', unplaced, width));
|
|
249
322
|
|
|
250
323
|
return [
|
|
251
324
|
'Usage: jsn <command> [options]',
|
|
@@ -254,7 +327,7 @@ export function renderHelp(config, registry = null) {
|
|
|
254
327
|
'',
|
|
255
328
|
...sections,
|
|
256
329
|
'',
|
|
257
|
-
renderFlags(Array.isArray(registry?.options) ? registry.options : []),
|
|
330
|
+
renderFlags(Array.isArray(registry?.options) ? registry.options : [], { full: true, width }),
|
|
258
331
|
renderTips(),
|
|
259
332
|
'',
|
|
260
333
|
].join('\n');
|
package/src/helpers.js
CHANGED
|
@@ -5,7 +5,7 @@ import readline from 'node:readline';
|
|
|
5
5
|
import { paginatedSearch } from './paginated-search.js';
|
|
6
6
|
import { isTTY, FormatAuto } from './output.js';
|
|
7
7
|
import { getActiveProfile } from './config.js';
|
|
8
|
-
import { errConfirmationRequired } from './errors.js';
|
|
8
|
+
import { errConfirmationRequired, isTerminalAuthError } from './errors.js';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* Detect whether a human is actually available to answer interactive
|
|
@@ -420,6 +420,7 @@ export async function interactiveList({ app, table, singular, columns, limit = 5
|
|
|
420
420
|
try {
|
|
421
421
|
totalCount = await app.sdk.aggregateCount(table, query || '');
|
|
422
422
|
} catch (err) {
|
|
423
|
+
if (isTerminalAuthError(err)) throw err;
|
|
423
424
|
countError = err;
|
|
424
425
|
}
|
|
425
426
|
if (totalCount === 0) return null; // measured empty
|
|
@@ -435,6 +436,7 @@ export async function interactiveList({ app, table, singular, columns, limit = 5
|
|
|
435
436
|
if (!Array.isArray(probe)) throw new Error('list returned a non-array result');
|
|
436
437
|
if (probe.length === 0) return null; // the list itself confirms empty
|
|
437
438
|
} catch (err) {
|
|
439
|
+
if (isTerminalAuthError(err)) throw err;
|
|
438
440
|
// Both the count and the list failed — surface the failure instead of
|
|
439
441
|
// reporting an empty result nobody measured.
|
|
440
442
|
throw new Error(
|
|
@@ -467,6 +469,7 @@ export async function interactiveList({ app, table, singular, columns, limit = 5
|
|
|
467
469
|
value: formatValue ? formatValue(r) : r,
|
|
468
470
|
}));
|
|
469
471
|
} catch (err) {
|
|
472
|
+
if (isTerminalAuthError(err)) throw err;
|
|
470
473
|
console.error('serverSource error:', err.message || err);
|
|
471
474
|
return [];
|
|
472
475
|
}
|
package/src/prompts.js
CHANGED
|
@@ -30,6 +30,15 @@ export function cancellablePrompt(prompt) {
|
|
|
30
30
|
|
|
31
31
|
export const input = lazyPrompt('input');
|
|
32
32
|
export const password = lazyPrompt('password');
|
|
33
|
+
|
|
34
|
+
// Use the shared Escape contract and a masked prompt; codes stay ephemeral.
|
|
35
|
+
export async function mfaCode(config = {}, context = {}) {
|
|
36
|
+
return password({
|
|
37
|
+
...config, mask: '*',
|
|
38
|
+
validate: answer => /^\d{6}$/.test(String(answer ?? '').replace(/[\s-]/g, ''))
|
|
39
|
+
|| 'Enter the 6-digit code from your authenticator app.',
|
|
40
|
+
}, context);
|
|
41
|
+
}
|
|
33
42
|
export const select = lazyPrompt('select');
|
|
34
43
|
export const search = lazyPrompt('search');
|
|
35
44
|
export const confirm = lazyPrompt('confirm');
|
|
@@ -59,10 +59,14 @@ export default {
|
|
|
59
59
|
options: { singular: 'catalog UI policy', scopeValidation: true } },
|
|
60
60
|
tables: { table: 'sys_db_object', aliases: ['table', 't'], columns: ['name', 'label', 'super_class', 'create_access_controls'],
|
|
61
61
|
options: { singular: 'table', scopeValidation: true, showFields: ['name', 'label', 'super_class', 'create_access_controls', 'sys_scope', 'sys_created_on', 'sys_updated_on', 'sys_created_by', 'sys_updated_by', 'is_extendable'] } },
|
|
62
|
-
incidents: { table: 'incident', aliases: ['incident', 'inc'], columns: ['number', 'short_description', 'priority', 'state', 'assigned_to'], kind: 'ticket'
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
62
|
+
incidents: { table: 'incident', aliases: ['incident', 'inc'], columns: ['number', 'short_description', 'priority', 'state', 'assigned_to'], kind: 'ticket',
|
|
63
|
+
summary: 'List, show, create, or update incidents' },
|
|
64
|
+
changes: { table: 'change_request', aliases: ['change_request', 'chg'], columns: ['number', 'short_description', 'risk', 'state', 'assigned_to'], kind: 'ticket',
|
|
65
|
+
summary: 'Work with change requests' },
|
|
66
|
+
requests: { table: 'sc_req_item', aliases: ['sc_req_item', 'req'], columns: ['number', 'cat_item', 'short_description', 'stage', 'assigned_to'], kind: 'ticket',
|
|
67
|
+
summary: 'Work with requested items' },
|
|
68
|
+
tasks: { table: 'sc_task', aliases: ['sc_task', 'task'], columns: ['number', 'short_description', 'state', 'assigned_to'], kind: 'ticket',
|
|
69
|
+
summary: 'Work with catalog tasks' },
|
|
66
70
|
uipolicies: { table: 'sys_ui_policy', aliases: ['uipolicy', 'up'], columns: ['short_description', 'table', 'sys_class_name', 'active'],
|
|
67
71
|
identifierField: 'short_description', options: { singular: 'UI policy', scopeValidation: true },
|
|
68
72
|
relationships: { essential: [{ name: 'actions', table: 'sys_ui_policy_action', foreignKey: 'ui_policy', limit: 100, orderBy: 'order',
|
package/src/record-profiles.js
CHANGED
|
@@ -83,6 +83,7 @@ export function buildRecordProfile(definition, wrap, hooks = {}) {
|
|
|
83
83
|
? buildTicketCommands(profile.table, profile.name, profile.aliases.find(alias => alias !== profile.table), profile.columns, {}, null, wrap, options)
|
|
84
84
|
: buildDevCmd(profile.name, profile.table, profile.aliases, profile.columns, wrap, options);
|
|
85
85
|
command.aliases = [...profile.aliases];
|
|
86
|
+
command.summary = profile.summary || '';
|
|
86
87
|
command.recordProfile = profile;
|
|
87
88
|
command.discovery.benefits.push(
|
|
88
89
|
`Reference output: ${profile.output.references}; list projection: ${profile.output.listProjection}`,
|
package/src/sdk.js
CHANGED
|
@@ -4,7 +4,9 @@ import { batchRead } from './sdk-batch.js';
|
|
|
4
4
|
import { tableReadParams } from './table-read-params.js';
|
|
5
5
|
import { gunzipSync } from 'node:zlib';
|
|
6
6
|
import { AppError, CodeAPI, CodeAuth, errAuth, errAuthHint, errAPI, errNetwork, errUsage } from './errors.js';
|
|
7
|
-
import { getStringField } from './helpers.js';
|
|
7
|
+
import { canPrompt, getStringField } from './helpers.js';
|
|
8
|
+
import { errMfaRequired, errMfaRejected, isTerminalAuthError } from './errors.js';
|
|
9
|
+
import { buildMfaVerificationBody, extractMfaFormTokens, normalizeTotpCode, parseLoginStatus } from './auth/mfa.js';
|
|
8
10
|
import { getAction, getStepTypes, createAction, updateAction, testAction } from './processflow-actions.js';
|
|
9
11
|
import { readSkippedBaseline, revertSkippedUpdate } from './skipped-update-provider.js';
|
|
10
12
|
import {
|
|
@@ -43,6 +45,8 @@ function serializeCookies(cookieJar) {
|
|
|
43
45
|
// else (script processors, GraphQL, the concourse picker, xmlhttp.do, update-set
|
|
44
46
|
// export/import, binary attachment uploads) keeps the session bootstrap it
|
|
45
47
|
// needs, and JSN_ALWAYS_WARM_SESSION=1 restores it for every path.
|
|
48
|
+
// Basic is the exception: normal requests must first detect any TOTP challenge
|
|
49
|
+
// before a pending operation can be sent. See docs/AUTH_LIFECYCLE.md.
|
|
46
50
|
const STATELESS_REST_PREFIXES = ['/api/now/table/', '/api/now/stats/', '/api/now/v1/batch'];
|
|
47
51
|
|
|
48
52
|
export function needsUiSession(url, { stateful = false, forceSession = false } = {}) {
|
|
@@ -88,6 +92,13 @@ export class SDKClient {
|
|
|
88
92
|
this.oauthCookies = null;
|
|
89
93
|
this._sessionPromise = null;
|
|
90
94
|
this.sessionUserToken = '';
|
|
95
|
+
this._sessionFailure = null;
|
|
96
|
+
this._mfaRecognized = false;
|
|
97
|
+
this.canInteract = opts.canInteract || canPrompt;
|
|
98
|
+
this.promptMfaCode = opts.promptMfaCode || (async config => {
|
|
99
|
+
const { mfaCode } = await import('./prompts.js');
|
|
100
|
+
return mfaCode(config);
|
|
101
|
+
});
|
|
91
102
|
// Session state is versioned so concurrent requests can tell "my headers
|
|
92
103
|
// are from the session that was just replaced" apart from "this rejection
|
|
93
104
|
// is new". One recovery is in flight per client at a time.
|
|
@@ -95,7 +106,7 @@ export class SDKClient {
|
|
|
95
106
|
this._recoveryPromise = null;
|
|
96
107
|
}
|
|
97
108
|
|
|
98
|
-
async _setAuth(req, { skipOAuthSession = false } = {}) {
|
|
109
|
+
async _setAuth(req, { skipOAuthSession = false, basicSession = false } = {}) {
|
|
99
110
|
if (!this.authProvider) {
|
|
100
111
|
throw errAuth('No authentication configured');
|
|
101
112
|
}
|
|
@@ -111,14 +122,21 @@ export class SDKClient {
|
|
|
111
122
|
}
|
|
112
123
|
switch (creds.auth_method) {
|
|
113
124
|
case 'basic':
|
|
114
|
-
|
|
125
|
+
// Basic credentials may demand a login challenge even on stateless
|
|
126
|
+
// REST. Only explicit internal bootstrap requests bypass this gate.
|
|
127
|
+
if (this._sessionFailure) throw this._sessionFailure;
|
|
128
|
+
if (!skipOAuthSession || basicSession || this._mfaRecognized) {
|
|
115
129
|
const cookies = await this._warmSession();
|
|
116
|
-
|
|
130
|
+
// Stateless REST historically uses Basic. A non-challenge UI
|
|
131
|
+
// bootstrap (even one minting guest cookies/tokens) must not replace
|
|
132
|
+
// working REST credentials. Only verified MFA overrides that policy.
|
|
133
|
+
if (cookies && (!skipOAuthSession || this._mfaRecognized)) {
|
|
117
134
|
req.headers.set('Cookie', cookies);
|
|
118
135
|
if (this.sessionUserToken) req.headers.set('X-UserToken', this.sessionUserToken);
|
|
119
136
|
break;
|
|
120
137
|
}
|
|
121
138
|
}
|
|
139
|
+
if (this._mfaRecognized) throw errMfaRejected();
|
|
122
140
|
req.headers.set('Authorization', 'Basic ' + Buffer.from(`${creds.username}:${creds.password}`).toString('base64'));
|
|
123
141
|
break;
|
|
124
142
|
case 'token':
|
|
@@ -162,7 +180,7 @@ export class SDKClient {
|
|
|
162
180
|
return value;
|
|
163
181
|
});
|
|
164
182
|
} catch (error) {
|
|
165
|
-
if (event) await this._reportMutation({ ...event, outcome: error.status >= 400 && error.status < 500 && error.status !== 408
|
|
183
|
+
if (event && !error?.notSent && error?.name !== 'PromptCancelled') await this._reportMutation({ ...event, outcome: error.status >= 400 && error.status < 500 && error.status !== 408
|
|
166
184
|
? 'failed' : 'unknown', http_status: error.status || null });
|
|
167
185
|
throw error;
|
|
168
186
|
}
|
|
@@ -193,19 +211,20 @@ export class SDKClient {
|
|
|
193
211
|
// Headers for this attempt belong to the session as it is right now.
|
|
194
212
|
const generation = this._sessionGeneration;
|
|
195
213
|
const controller = new AbortController();
|
|
196
|
-
|
|
214
|
+
let timer;
|
|
197
215
|
let rejection;
|
|
198
216
|
try {
|
|
199
217
|
const req = new Request(endpoint, { ...opts, signal: controller.signal });
|
|
200
218
|
if (prepare) prepare(req);
|
|
201
|
-
//
|
|
202
|
-
//
|
|
203
|
-
//
|
|
219
|
+
// Header-authenticated REST skips UI warming for OAuth/token/GCK.
|
|
220
|
+
// Basic must still check for TOTP before dispatch; internal bootstrap
|
|
221
|
+
// requests explicitly bypass that check to avoid recursion.
|
|
204
222
|
const skipSession = skipOAuthSession || !needsUiSession(endpoint, {
|
|
205
223
|
stateful,
|
|
206
224
|
forceSession: process.env.JSN_ALWAYS_WARM_SESSION === '1',
|
|
207
225
|
});
|
|
208
|
-
await this._setAuth(req, { skipOAuthSession: skipSession });
|
|
226
|
+
await this._setAuth(req, { skipOAuthSession: skipSession, basicSession: !skipOAuthSession });
|
|
227
|
+
timer = setTimeout(() => controller.abort(), timeout);
|
|
209
228
|
const response = await fetch(req);
|
|
210
229
|
if (!skipOAuthSession && this.recovery) {
|
|
211
230
|
// A 401 is definitive; only then is the body sniffed for a login
|
|
@@ -377,7 +396,8 @@ export class SDKClient {
|
|
|
377
396
|
|
|
378
397
|
// Public raw-response seam for callers that must inspect non-2xx bodies.
|
|
379
398
|
async fetchResponse(endpoint, opts = {}) {
|
|
380
|
-
|
|
399
|
+
const { timeout = this.timeout, stateful = false, ...requestOptions } = opts;
|
|
400
|
+
return this._withAuthenticatedRequest(endpoint, requestOptions, { timeout, stateful });
|
|
381
401
|
}
|
|
382
402
|
|
|
383
403
|
async rawRequest(endpoint, opts = {}) {
|
|
@@ -1188,9 +1208,13 @@ export class SDKClient {
|
|
|
1188
1208
|
}
|
|
1189
1209
|
|
|
1190
1210
|
async _warmSession() {
|
|
1211
|
+
if (this._sessionFailure) throw this._sessionFailure;
|
|
1191
1212
|
if (this.oauthCookies) return this.oauthCookies;
|
|
1192
1213
|
if (!this._sessionPromise) {
|
|
1193
|
-
this._sessionPromise = this._initializeSession().
|
|
1214
|
+
this._sessionPromise = this._initializeSession().catch(error => {
|
|
1215
|
+
if (isTerminalAuthError(error)) this._sessionFailure = error;
|
|
1216
|
+
throw error;
|
|
1217
|
+
}).finally(() => {
|
|
1194
1218
|
this._sessionPromise = null;
|
|
1195
1219
|
});
|
|
1196
1220
|
}
|
|
@@ -1198,6 +1222,7 @@ export class SDKClient {
|
|
|
1198
1222
|
}
|
|
1199
1223
|
|
|
1200
1224
|
async _initializeSession() {
|
|
1225
|
+
let challenged = false;
|
|
1201
1226
|
try {
|
|
1202
1227
|
const creds = await this.authProvider.getCredentials();
|
|
1203
1228
|
if (creds.auth_method === 'oauth') {
|
|
@@ -1221,7 +1246,7 @@ export class SDKClient {
|
|
|
1221
1246
|
}
|
|
1222
1247
|
const endpoint = `${this.baseURL}/angular.do`;
|
|
1223
1248
|
const cookieJar = new Map();
|
|
1224
|
-
const
|
|
1249
|
+
const loginStatus = await this._mfaExchange('/angular.do?sysparm_type=view_form.login', {
|
|
1225
1250
|
method: 'POST',
|
|
1226
1251
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
1227
1252
|
body: new URLSearchParams({
|
|
@@ -1230,8 +1255,17 @@ export class SDKClient {
|
|
|
1230
1255
|
user_name: creds.username,
|
|
1231
1256
|
user_password: creds.password,
|
|
1232
1257
|
}).toString(),
|
|
1233
|
-
});
|
|
1234
|
-
|
|
1258
|
+
}, cookieJar, async response => parseLoginStatus(await response.text()));
|
|
1259
|
+
challenged = loginStatus?.status === 'mfa_code_required';
|
|
1260
|
+
if (challenged) {
|
|
1261
|
+
this._mfaRecognized = true;
|
|
1262
|
+
const token = await this._completeMfaChallenge(cookieJar, creds.username);
|
|
1263
|
+
if (!serializeCookies(cookieJar)) throw errMfaRejected();
|
|
1264
|
+
this.sessionUserToken = token;
|
|
1265
|
+
this.oauthCookies = serializeCookies(cookieJar);
|
|
1266
|
+
return this.oauthCookies;
|
|
1267
|
+
}
|
|
1268
|
+
if (this._mfaRecognized) throw errMfaRejected();
|
|
1235
1269
|
const refreshResp = await this._fetchWithAuth(`${endpoint}?sysparm_type=get_user`, {
|
|
1236
1270
|
method: 'POST',
|
|
1237
1271
|
headers: serializeCookies(cookieJar) ? { Cookie: serializeCookies(cookieJar) } : {},
|
|
@@ -1241,11 +1275,90 @@ export class SDKClient {
|
|
|
1241
1275
|
const cookies = serializeCookies(cookieJar);
|
|
1242
1276
|
this.oauthCookies = cookies;
|
|
1243
1277
|
return cookies;
|
|
1244
|
-
} catch {
|
|
1278
|
+
} catch (error) {
|
|
1279
|
+
if (challenged || this._mfaRecognized) throw isTerminalAuthError(error) ? error : errMfaRejected();
|
|
1245
1280
|
return '';
|
|
1246
1281
|
}
|
|
1247
1282
|
}
|
|
1248
1283
|
|
|
1284
|
+
// Each network exchange, including its body, has a deadline independent of
|
|
1285
|
+
// human code entry. The race also bounds streams that do not honor abort.
|
|
1286
|
+
async _mfaExchange(path, options, cookieJar, consume = response => response) {
|
|
1287
|
+
const controller = new AbortController();
|
|
1288
|
+
let timer;
|
|
1289
|
+
const deadline = new Promise((resolve, reject) => {
|
|
1290
|
+
timer = setTimeout(() => {
|
|
1291
|
+
controller.abort();
|
|
1292
|
+
reject(errMfaRejected());
|
|
1293
|
+
}, this.timeout);
|
|
1294
|
+
});
|
|
1295
|
+
try {
|
|
1296
|
+
return await Promise.race([deadline, (async () => {
|
|
1297
|
+
const response = await fetch(new Request(`${this.baseURL}${path}`, {
|
|
1298
|
+
...options, redirect: 'manual', signal: controller.signal,
|
|
1299
|
+
headers: { ...options.headers, Cookie: serializeCookies(cookieJar) },
|
|
1300
|
+
}));
|
|
1301
|
+
collectSetCookies(cookieJar, response);
|
|
1302
|
+
try {
|
|
1303
|
+
return await consume(response);
|
|
1304
|
+
} finally {
|
|
1305
|
+
if (!response.bodyUsed) await response.body?.cancel?.();
|
|
1306
|
+
}
|
|
1307
|
+
})()]);
|
|
1308
|
+
} finally {
|
|
1309
|
+
clearTimeout(timer);
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
async _completeMfaChallenge(cookieJar, username) {
|
|
1314
|
+
if (!this.canInteract()) throw errMfaRequired();
|
|
1315
|
+
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
1316
|
+
const code = normalizeTotpCode(await this.promptMfaCode({
|
|
1317
|
+
message: attempt === 1 ? 'Enter the 6-digit authenticator code:' : `Code rejected. Enter a new code (${attempt}/3):`,
|
|
1318
|
+
}));
|
|
1319
|
+
if (!code) continue;
|
|
1320
|
+
const tokens = await this._mfaExchange('/validate_multifactor_auth_code.do', { method: 'GET' }, cookieJar, async response => {
|
|
1321
|
+
if (!response.ok) throw errMfaRejected();
|
|
1322
|
+
return extractMfaFormTokens(await response.text());
|
|
1323
|
+
});
|
|
1324
|
+
if (!tokens.csrf || !tokens.processNonce) throw errMfaRejected();
|
|
1325
|
+
const accepted = await this._mfaExchange('/validate_mfa_code.do', {
|
|
1326
|
+
method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
1327
|
+
body: buildMfaVerificationBody({ ...tokens, code }).toString(),
|
|
1328
|
+
}, cookieJar, response => {
|
|
1329
|
+
if (response.headers.get('x-mfa_token') === 'invalid') return false;
|
|
1330
|
+
const location = response.headers.get('location') || '';
|
|
1331
|
+
const destination = new URL(location, this.baseURL);
|
|
1332
|
+
if (response.status !== 302 || !location || destination.origin !== new URL(this.baseURL).origin
|
|
1333
|
+
|| /login|logout|expired|multifactor|validate_mfa/i.test(destination.pathname)) throw errMfaRejected();
|
|
1334
|
+
return true;
|
|
1335
|
+
});
|
|
1336
|
+
if (!accepted) continue;
|
|
1337
|
+
const token = await this._mfaExchange('/angular.do?sysparm_type=get_user', { method: 'POST' }, cookieJar, async response => {
|
|
1338
|
+
const body = await response.text();
|
|
1339
|
+
const token = response.headers.get('x-usertoken-response');
|
|
1340
|
+
if (!response.ok || !token || /\bguest\b|login\.do|session_expired/i.test(body)) throw errMfaRejected();
|
|
1341
|
+
return token;
|
|
1342
|
+
});
|
|
1343
|
+
// A token is not identity proof. Use the same cookie/CSRF session and
|
|
1344
|
+
// compare the authenticated current user with the selected Basic user.
|
|
1345
|
+
const params = new URLSearchParams({ sysparm_query: 'user_name=javascript:gs.getUserName()',
|
|
1346
|
+
sysparm_fields: 'user_name', sysparm_limit: '1', sysparm_display_value: 'false' });
|
|
1347
|
+
await this._mfaExchange(`/api/now/table/sys_user?${params}`, {
|
|
1348
|
+
method: 'GET', headers: { Accept: 'application/json', 'X-UserToken': token },
|
|
1349
|
+
}, cookieJar, async response => {
|
|
1350
|
+
if (!response.ok) throw errMfaRejected();
|
|
1351
|
+
const payload = await response.json();
|
|
1352
|
+
const field = Array.isArray(payload?.result) && payload.result.length === 1 ? payload.result[0]?.user_name : null;
|
|
1353
|
+
const identity = typeof field === 'object' && field ? field.value : field;
|
|
1354
|
+
if (!username || identity !== username || identity === 'guest'
|
|
1355
|
+
|| (this.username && identity !== this.username)) throw errMfaRejected();
|
|
1356
|
+
});
|
|
1357
|
+
return token;
|
|
1358
|
+
}
|
|
1359
|
+
throw errMfaRejected();
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1249
1362
|
async _getScriptsPageCSRF(cookies) {
|
|
1250
1363
|
const endpoint = `${this.baseURL}/sys.scripts.do`;
|
|
1251
1364
|
const html = await this.rawRequest(endpoint, {
|