@jacebenson/jsn 5.5.1-dev.171.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/package.json +1 -1
- package/src/app.js +3 -1
- package/src/auth/mfa.js +85 -0
- package/src/errors.js +23 -1
- package/src/helpers.js +4 -1
- package/src/prompts.js +9 -0
- package/src/sdk.js +129 -16
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/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/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');
|
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, {
|