@jacebenson/jsn 5.5.6-dev.203.1 → 5.5.6-dev.205.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/amb.js +15 -0
- package/src/app.js +4 -15
- package/src/auth/transport.js +22 -0
- package/src/auth.js +22 -2
- package/src/cli.js +0 -3
- package/src/config.js +18 -0
- package/src/midserver-install.js +3 -0
- package/src/sdk.js +10 -44
- package/src/session.js +6 -1
- package/src/commands/history.js +0 -57
- package/src/mutation-history.js +0 -75
package/package.json
CHANGED
package/src/amb.js
CHANGED
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
// src/record-watch.js.
|
|
21
21
|
|
|
22
22
|
import { AppError, CodeAPI, CodeAuth, CodeNetwork, CodeUsage } from './errors.js';
|
|
23
|
+
import { assertCredentialTransport, assertCredentialDestination } from './auth/transport.js';
|
|
23
24
|
|
|
24
25
|
const BAYEUX_VERSION = '1.0';
|
|
25
26
|
const DEFAULT_CONNECT_TIMEOUT = 60000;
|
|
@@ -164,8 +165,10 @@ export class AmbClient {
|
|
|
164
165
|
if (!baseUrl) throw new AmbError(CodeUsage, 'AMB needs an instance URL.');
|
|
165
166
|
if (typeof session !== 'function') throw new AmbError(CodeUsage, 'AMB needs a session provider.');
|
|
166
167
|
this.baseUrl = String(baseUrl).replace(/\/$/, '');
|
|
168
|
+
this.instanceOrigin = assertCredentialTransport(this.baseUrl).origin;
|
|
167
169
|
this.session = session;
|
|
168
170
|
this.fetchImpl = fetchImpl;
|
|
171
|
+
if (/^[a-z][a-z\d+.-]*:/i.test(path)) throw ambAuthError('AMB path must be an instance-local route');
|
|
169
172
|
this.path = path.startsWith('/') ? path : `/${path}`;
|
|
170
173
|
this.connectTimeoutMs = connectTimeoutMs;
|
|
171
174
|
this.requestTimeoutMs = requestTimeoutMs;
|
|
@@ -180,6 +183,7 @@ export class AmbClient {
|
|
|
180
183
|
async _send(messages, { op, timeoutMs, signal }) {
|
|
181
184
|
const endpoint = op === 'handshake' ? 'handshake' : 'connect';
|
|
182
185
|
const url = `${this.baseUrl}${this.path}/${endpoint}`;
|
|
186
|
+
this._validateDestination(url);
|
|
183
187
|
const headers = { Accept: 'application/json', 'Content-Type': 'application/json' };
|
|
184
188
|
const cookies = serializeCookies(this.cookieJar);
|
|
185
189
|
if (cookies) headers.Cookie = cookies;
|
|
@@ -195,6 +199,7 @@ export class AmbClient {
|
|
|
195
199
|
}
|
|
196
200
|
try {
|
|
197
201
|
const response = await this.fetchImpl(url, {
|
|
202
|
+
redirect: 'error',
|
|
198
203
|
method: 'POST',
|
|
199
204
|
headers,
|
|
200
205
|
body: JSON.stringify(messages),
|
|
@@ -282,6 +287,7 @@ export class AmbClient {
|
|
|
282
287
|
* delivery, and the gap is reported by the caller.
|
|
283
288
|
*/
|
|
284
289
|
async start(channels = []) {
|
|
290
|
+
this._validateDestination(`${this.baseUrl}${this.path}/handshake`);
|
|
285
291
|
const session = await this.session();
|
|
286
292
|
if (!session?.cookies) {
|
|
287
293
|
throw ambAuthError('AMB needs a browser session and the active profile has none.',
|
|
@@ -318,6 +324,15 @@ export class AmbClient {
|
|
|
318
324
|
return { clientId: this.clientId, sessionStatus: this.sessionStatus, channels: [...channels] };
|
|
319
325
|
}
|
|
320
326
|
|
|
327
|
+
_validateDestination(url) {
|
|
328
|
+
// AMB paths are local routes, never URL references. Reject ambiguous
|
|
329
|
+
// authority/backslash/query forms before asking the session for secrets.
|
|
330
|
+
if (!this.path.startsWith('/') || this.path.startsWith('//') || /[\\?#]/.test(this.path)) {
|
|
331
|
+
throw ambAuthError('AMB path must be an instance-local route');
|
|
332
|
+
}
|
|
333
|
+
assertCredentialDestination(url, this.instanceOrigin);
|
|
334
|
+
}
|
|
335
|
+
|
|
321
336
|
/**
|
|
322
337
|
* One long-poll: returns the non-meta Bayeux messages it received. A local
|
|
323
338
|
* timeout returns an empty array (the loop just polls again) unless the
|
package/src/app.js
CHANGED
|
@@ -7,12 +7,11 @@
|
|
|
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';
|
|
14
13
|
import { OutputWriter, FormatAuto, FormatJSON, FormatMarkdown, FormatQuiet, FormatStyled, hyperlink } from './output.js';
|
|
15
|
-
import { saveConfig } from './config.js';
|
|
14
|
+
import { saveConfig, isTrustedCredentialDestination } from './config.js';
|
|
16
15
|
import { resolveSession, applySession, contextFromSession, requireSessionInstance } from './session.js';
|
|
17
16
|
import { getCurrentUser, getCurrentApplication, getCurrentUpdateSet } from './context.js';
|
|
18
17
|
import { errUsage, errAuth } from './errors.js';
|
|
@@ -43,6 +42,9 @@ export class App {
|
|
|
43
42
|
getUsername: () => this.session?.username || null,
|
|
44
43
|
getEffectiveInstance: () => this.session?.instance || '',
|
|
45
44
|
getAuthMethod: () => this.session?.profile?.auth_method || null,
|
|
45
|
+
isTrustedCredentialDestination: instance => isTrustedCredentialDestination(this.config, instance,
|
|
46
|
+
this._authArgv?.instance || this._sessionArgv?.instance || (this.session?.profileExplicit ? '' : this.session?.override),
|
|
47
|
+
this.session?.profileExplicit ? this.session.profileName : ''),
|
|
46
48
|
});
|
|
47
49
|
|
|
48
50
|
if (this.session.instance) {
|
|
@@ -62,7 +64,6 @@ export class App {
|
|
|
62
64
|
includeReferenceLinks: this._authArgv?.includeReferenceLinks === true,
|
|
63
65
|
username: session?.username || '',
|
|
64
66
|
recovery: createAuthRecovery({ app: this, session }),
|
|
65
|
-
onMutation: event => this.recordMutation(instance, session?.profileName, event),
|
|
66
67
|
canInteract: () => canUsePicker(this, this._authArgv || {}),
|
|
67
68
|
});
|
|
68
69
|
}
|
|
@@ -73,22 +74,10 @@ export class App {
|
|
|
73
74
|
return new SDKClient(instance, this.auth.createProfileProvider(instance, options), {
|
|
74
75
|
domain: options.domain ?? profile.domain ?? '',
|
|
75
76
|
username: options.username || '',
|
|
76
|
-
onMutation: event => this.recordMutation(instance, options.profileName || null, event),
|
|
77
77
|
canInteract: () => canUsePicker(this, this._authArgv || {}),
|
|
78
78
|
});
|
|
79
79
|
}
|
|
80
80
|
|
|
81
|
-
recordMutation(instance, profile, event) {
|
|
82
|
-
if (!this._authArgv) return;
|
|
83
|
-
try { appendMutation({ ...event, instance, profile, reason: this._authArgv.reason }); }
|
|
84
|
-
catch {
|
|
85
|
-
if (!this._historyWarningShown) {
|
|
86
|
-
process.stderr.write('Warning: local mutation history could not be saved. The remote result is unchanged.\n');
|
|
87
|
-
this._historyWarningShown = true;
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
81
|
loadContext() {
|
|
93
82
|
this.context = contextFromSession(this.session, this.config);
|
|
94
83
|
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Credential transport policy. Only process state can enable legacy HTTP;
|
|
2
|
+
// project configuration must never relax this boundary.
|
|
3
|
+
import { errAuth } from '../errors.js';
|
|
4
|
+
|
|
5
|
+
export function assertCredentialTransport(destination) {
|
|
6
|
+
let url;
|
|
7
|
+
try { url = new URL(destination); } catch { throw errAuth('Invalid credential destination'); }
|
|
8
|
+
const hostname = url.hostname.toLowerCase();
|
|
9
|
+
const loopback = hostname === 'localhost' || hostname === '[::1]' || /^127(?:\.\d{1,3}){3}$/.test(hostname);
|
|
10
|
+
if (url.username || url.password || !['http:', 'https:'].includes(url.protocol)) throw errAuth('Invalid credential destination');
|
|
11
|
+
if (url.protocol !== 'https:' && !loopback && process.env.JSN_ALLOW_INSECURE_HTTP !== '1') {
|
|
12
|
+
throw errAuth('HTTPS is required for credential destinations (except loopback development). Set JSN_ALLOW_INSECURE_HTTP=1 in this process only to explicitly allow legacy HTTP.');
|
|
13
|
+
}
|
|
14
|
+
return url;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function assertCredentialDestination(destination, instance) {
|
|
18
|
+
const url = assertCredentialTransport(destination);
|
|
19
|
+
const origin = assertCredentialTransport(instance).origin;
|
|
20
|
+
if (url.origin !== origin) throw errAuth('Refusing to send credentials outside the configured instance origin');
|
|
21
|
+
return url;
|
|
22
|
+
}
|
package/src/auth.js
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
|
|
7
7
|
import fs from 'node:fs';
|
|
8
8
|
import { password as passwordPrompt } from './prompts.js';
|
|
9
|
-
import { normalizeInstanceURL } from './config.js';
|
|
9
|
+
import { normalizeInstanceURL, isTrustedCredentialDestination } from './config.js';
|
|
10
|
+
import { assertCredentialTransport } from './auth/transport.js';
|
|
10
11
|
import { errAuth } from './errors.js';
|
|
11
12
|
import { pendingBrowserLogin } from './browser-auth.js';
|
|
12
13
|
import { defaultCredentialStore } from './auth/credential-store.js';
|
|
@@ -86,6 +87,7 @@ export class AuthManager {
|
|
|
86
87
|
return (name && cfg.profiles?.[name]?.username) || null;
|
|
87
88
|
},
|
|
88
89
|
getEffectiveInstance: () => provider.getEffectiveInstance(),
|
|
90
|
+
isTrustedCredentialDestination: instance => isTrustedCredentialDestination(provider.config, instance),
|
|
89
91
|
getAuthMethod: () => {
|
|
90
92
|
const cfg = provider.config;
|
|
91
93
|
const name = cfg.activeProfile || cfg.defaultProfile;
|
|
@@ -323,15 +325,22 @@ export class AuthManager {
|
|
|
323
325
|
}
|
|
324
326
|
|
|
325
327
|
getCredentialsFor(instance, username, options = {}) {
|
|
328
|
+
assertCredentialTransport(instance);
|
|
326
329
|
const method = this._selectedMethod(options);
|
|
330
|
+
const assertAmbientTrust = () => {
|
|
331
|
+
if (this.identity.isTrustedCredentialDestination?.(instance) === false) {
|
|
332
|
+
throw errAuth('Project configuration cannot authorize an ambient credential destination. Select --instance explicitly or save the origin in global configuration.');
|
|
333
|
+
}
|
|
334
|
+
};
|
|
327
335
|
// With no configured method, preserve the legacy environment precedence:
|
|
328
336
|
// OAuth token first, then Basic credentials, then stored credentials.
|
|
329
337
|
if ((method === 'unconfigured' || method === 'oauth') && process.env.SERVICENOW_OAUTH_TOKEN) {
|
|
338
|
+
assertAmbientTrust();
|
|
330
339
|
return { auth_method: 'oauth', access_token: process.env.SERVICENOW_OAUTH_TOKEN, auth_source: 'env_token' };
|
|
331
340
|
}
|
|
332
341
|
if (method === 'unconfigured' || method === 'basic') {
|
|
333
342
|
const basicCreds = getBasicAuthFromEnv(instance);
|
|
334
|
-
if (basicCreds) return basicCreds;
|
|
343
|
+
if (basicCreds) { assertAmbientTrust(); return basicCreds; }
|
|
335
344
|
}
|
|
336
345
|
const credentialUsername = Object.hasOwn(options, 'username') ? options.username : (username ?? this._activeUsername());
|
|
337
346
|
const creds = this.credentialStore.load(instance, credentialUsername);
|
|
@@ -355,6 +364,7 @@ export class AuthManager {
|
|
|
355
364
|
|
|
356
365
|
async login(instanceURL, username = this._activeUsername()) {
|
|
357
366
|
instanceURL = normalizeInstanceURL(instanceURL);
|
|
367
|
+
assertCredentialTransport(instanceURL);
|
|
358
368
|
const clientID = getOAuthClientID();
|
|
359
369
|
const pkce = generatePKCE();
|
|
360
370
|
const authURL = buildAuthURL(instanceURL, clientID, pkce);
|
|
@@ -433,7 +443,11 @@ export class AuthManager {
|
|
|
433
443
|
*/
|
|
434
444
|
async loginWithPassword(instanceURL, username = this._activeUsername(), suppliedCredentials) {
|
|
435
445
|
instanceURL = normalizeInstanceURL(instanceURL);
|
|
446
|
+
assertCredentialTransport(instanceURL);
|
|
436
447
|
const envCreds = getBasicAuthFromEnv(instanceURL);
|
|
448
|
+
if (!suppliedCredentials && envCreds && this.identity.isTrustedCredentialDestination?.(instanceURL) === false) {
|
|
449
|
+
throw errAuth('Project configuration cannot authorize an ambient credential destination. Select --instance explicitly or save the origin in global configuration.');
|
|
450
|
+
}
|
|
437
451
|
const storedCreds = this.loadCredentials(instanceURL, username);
|
|
438
452
|
const creds = suppliedCredentials
|
|
439
453
|
? { auth_method: 'basic', ...suppliedCredentials }
|
|
@@ -464,6 +478,7 @@ export class AuthManager {
|
|
|
464
478
|
}
|
|
465
479
|
|
|
466
480
|
async loginWithBrowser(instanceURL, options = {}, username = this._activeUsername()) {
|
|
481
|
+
assertCredentialTransport(normalizeInstanceURL(instanceURL));
|
|
467
482
|
if (options.launch) {
|
|
468
483
|
const { launchBrowserSession } = await import('./browser-launch.js');
|
|
469
484
|
const credentials = await launchBrowserSession(instanceURL, {
|
|
@@ -486,6 +501,7 @@ export class AuthManager {
|
|
|
486
501
|
|
|
487
502
|
async _verifyBrowserSession(instanceURL, creds, username, { requireIdentity = false, signal, timeout = this.httpClient.timeout } = {}) {
|
|
488
503
|
instanceURL = normalizeInstanceURL(instanceURL);
|
|
504
|
+
assertCredentialTransport(instanceURL);
|
|
489
505
|
const query = new URLSearchParams({
|
|
490
506
|
sysparm_limit: '1',
|
|
491
507
|
sysparm_fields: 'user_name',
|
|
@@ -547,6 +563,7 @@ export class AuthManager {
|
|
|
547
563
|
}
|
|
548
564
|
|
|
549
565
|
async exchangeCode(instanceURL, clientID, code, pkce) {
|
|
566
|
+
assertCredentialTransport(instanceURL);
|
|
550
567
|
const tokenURL = `${instanceURL.replace(/\/$/, '')}/oauth_token.do`;
|
|
551
568
|
const body = new URLSearchParams();
|
|
552
569
|
body.set('grant_type', 'authorization_code');
|
|
@@ -556,6 +573,7 @@ export class AuthManager {
|
|
|
556
573
|
body.set('code_verifier', pkce.code_verifier);
|
|
557
574
|
|
|
558
575
|
const resp = await fetch(tokenURL, {
|
|
576
|
+
redirect: 'error',
|
|
559
577
|
method: 'POST',
|
|
560
578
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
561
579
|
body: body.toString(),
|
|
@@ -580,6 +598,7 @@ export class AuthManager {
|
|
|
580
598
|
}
|
|
581
599
|
|
|
582
600
|
async refreshToken(instance, creds, targetUsername = undefined) {
|
|
601
|
+
assertCredentialTransport(instance);
|
|
583
602
|
if (creds.auth_method !== 'oauth') {
|
|
584
603
|
throw errAuth(`Cannot refresh ${creds.auth_method || 'unconfigured'} credentials; only OAuth credentials support refresh`);
|
|
585
604
|
}
|
|
@@ -591,6 +610,7 @@ export class AuthManager {
|
|
|
591
610
|
body.set('refresh_token', creds.refresh_token);
|
|
592
611
|
|
|
593
612
|
const resp = await fetch(tokenURL, {
|
|
613
|
+
redirect: 'error',
|
|
594
614
|
method: 'POST',
|
|
595
615
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
596
616
|
body: body.toString(),
|
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/config.js
CHANGED
|
@@ -101,6 +101,12 @@ export function loadConfig(overrides = {}) {
|
|
|
101
101
|
const cfg = createConfig();
|
|
102
102
|
|
|
103
103
|
loadFromFile(cfg, globalConfigPath(), 'global');
|
|
104
|
+
// Preserve provenance outside the serializable/user-controlled config shape.
|
|
105
|
+
// A project can select an origin, but cannot authorize ambient secrets for it.
|
|
106
|
+
Object.defineProperty(cfg, 'credentialTrust', { value: {
|
|
107
|
+
profiles: structuredClone(cfg.profiles),
|
|
108
|
+
origin: normalizeInstanceURL(getEffectiveInstance(cfg)),
|
|
109
|
+
} });
|
|
104
110
|
loadFromFile(cfg, localConfigPath(), 'local');
|
|
105
111
|
loadFromEnv(cfg);
|
|
106
112
|
|
|
@@ -123,6 +129,18 @@ export function loadConfig(overrides = {}) {
|
|
|
123
129
|
return cfg;
|
|
124
130
|
}
|
|
125
131
|
|
|
132
|
+
export function isTrustedCredentialDestination(cfg, instance, explicitInstance = '', explicitProfile = '') {
|
|
133
|
+
const origin = normalizeInstanceURL(instance);
|
|
134
|
+
// Hand-built configs are a programmatic API, not project-file input.
|
|
135
|
+
if (!cfg?.credentialTrust) return true;
|
|
136
|
+
const selectedProfile = explicitProfile && Object.hasOwn(cfg.credentialTrust.profiles, explicitProfile)
|
|
137
|
+
? cfg.credentialTrust.profiles[explicitProfile]?.instance_url : '';
|
|
138
|
+
// Bind ambient secrets to the global default, not every saved account.
|
|
139
|
+
// Only explicit process selectors may opt into another saved origin.
|
|
140
|
+
const binding = explicitInstance || selectedProfile || process.env.SERVICENOW_INSTANCE_URL || cfg.credentialTrust.origin;
|
|
141
|
+
return Boolean(binding) && normalizeInstanceURL(binding) === origin;
|
|
142
|
+
}
|
|
143
|
+
|
|
126
144
|
export function saveConfig(cfg) {
|
|
127
145
|
const dir = globalConfigDir();
|
|
128
146
|
fs.mkdirSync(dir, { recursive: true, mode: 0o750 });
|
package/src/midserver-install.js
CHANGED
|
@@ -3,6 +3,7 @@ import os from 'node:os';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import process from 'node:process';
|
|
5
5
|
import { execFileSync } from 'node:child_process';
|
|
6
|
+
import { assertCredentialDestination } from './auth/transport.js';
|
|
6
7
|
|
|
7
8
|
const INSTALL_HOST = 'install.service-now.com';
|
|
8
9
|
|
|
@@ -41,9 +42,11 @@ export function buildMidRecipeUrl(releaseName) {
|
|
|
41
42
|
export async function validateMidCredentials(instanceURL, username, password, fetchImpl = fetch) {
|
|
42
43
|
if (!username || !password) throw new Error('MID Server username and password are required');
|
|
43
44
|
const endpoint = `${String(instanceURL).replace(/\/$/, '')}/api/now/table/sys_properties?sysparm_query=name=mid.version&sysparm_fields=value&sysparm_limit=1`;
|
|
45
|
+
assertCredentialDestination(endpoint, instanceURL);
|
|
44
46
|
let response;
|
|
45
47
|
try {
|
|
46
48
|
response = await fetchImpl(endpoint, {
|
|
49
|
+
redirect: 'error',
|
|
47
50
|
headers: {
|
|
48
51
|
Accept: 'application/json',
|
|
49
52
|
Authorization: `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`,
|
package/src/sdk.js
CHANGED
|
@@ -4,6 +4,7 @@ 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 { assertCredentialTransport, assertCredentialDestination } from './auth/transport.js';
|
|
7
8
|
import { canPrompt, getStringField } from './helpers.js';
|
|
8
9
|
import { errMfaRequired, errMfaRejected, isTerminalAuthError } from './errors.js';
|
|
9
10
|
import { buildMfaVerificationBody, extractMfaFormTokens, normalizeTotpCode, parseLoginStatus } from './auth/mfa.js';
|
|
@@ -82,7 +83,6 @@ export class SDKClient {
|
|
|
82
83
|
this.baseURL = baseURL.replace(/\/$/, '');
|
|
83
84
|
this.authProvider = authProvider;
|
|
84
85
|
this.recovery = opts.recovery;
|
|
85
|
-
this.onMutation = opts.onMutation;
|
|
86
86
|
this.timeout = opts.timeout || DEFAULT_TIMEOUT;
|
|
87
87
|
this.domain = opts.domain || '';
|
|
88
88
|
this.includeReferenceLinks = opts.includeReferenceLinks === true;
|
|
@@ -163,49 +163,14 @@ export class SDKClient {
|
|
|
163
163
|
// Keep the timeout alive through body consumption for text/JSON requests.
|
|
164
164
|
// Raw-response callers retain their existing timeout boundary at headers.
|
|
165
165
|
async _withAuthenticatedRequest(endpoint, opts, settings, consume = (response) => response) {
|
|
166
|
-
|
|
167
|
-
const match = url.pathname.match(/^\/api\/now\/table\/([^/]+)(?:\/([^/]+))?\/?$/);
|
|
168
|
-
const operation = { POST: 'create', PUT: 'update', PATCH: 'update', DELETE: 'delete' }[(opts.method || 'GET').toUpperCase()];
|
|
169
|
-
const event = match && operation && this.onMutation ? {
|
|
170
|
-
table: decodeURIComponent(match[1]), sys_id: match[2] ? decodeURIComponent(match[2]) : null, operation,
|
|
171
|
-
} : null;
|
|
172
|
-
let result;
|
|
173
|
-
try {
|
|
174
|
-
result = await this._performAuthenticatedRequest(endpoint, opts, settings, async response => {
|
|
175
|
-
if (event) event.http_status = response.status;
|
|
176
|
-
const value = await consume(response);
|
|
177
|
-
if (event && value instanceof Response && response.ok && operation === 'create') {
|
|
178
|
-
try { event.sys_id = (await response.clone().json())?.result?.sys_id || null; } catch { /* ID remains unknown. */ }
|
|
179
|
-
}
|
|
180
|
-
return value;
|
|
181
|
-
});
|
|
182
|
-
} catch (error) {
|
|
183
|
-
if (event && !error?.notSent && error?.name !== 'PromptCancelled') await this._reportMutation({ ...event, outcome: error.status >= 400 && error.status < 500 && error.status !== 408
|
|
184
|
-
? 'failed' : 'unknown', http_status: error.status || null });
|
|
185
|
-
throw error;
|
|
186
|
-
}
|
|
187
|
-
if (event) {
|
|
188
|
-
let body = result;
|
|
189
|
-
if (typeof body === 'string') { try { body = JSON.parse(body); } catch { body = null; } }
|
|
190
|
-
const id = body?.result?.sys_id;
|
|
191
|
-
if (typeof id === 'string') event.sys_id = id;
|
|
192
|
-
else if (typeof id?.value === 'string') event.sys_id = id.value;
|
|
193
|
-
await this._reportMutation({ ...event, outcome: event.http_status >= 400
|
|
194
|
-
? (event.http_status < 500 && event.http_status !== 408 ? 'failed' : 'unknown')
|
|
195
|
-
: (event.sys_id ? 'succeeded' : 'unknown') });
|
|
196
|
-
}
|
|
197
|
-
return result;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
async _reportMutation(event) {
|
|
201
|
-
// History failures must never change the outcome of a completed remote write.
|
|
202
|
-
try { await this.onMutation(event); } catch { /* App callback reports local storage failures. */ }
|
|
166
|
+
return this._performAuthenticatedRequest(endpoint, opts, settings, consume);
|
|
203
167
|
}
|
|
204
168
|
|
|
205
169
|
async _performAuthenticatedRequest(endpoint, opts, {
|
|
206
170
|
timeout = this.timeout, prepare, skipOAuthSession = false, normalizeErrors = false,
|
|
207
171
|
allowMutationReplay = false, stateful = false,
|
|
208
172
|
}, consume = (response) => response) {
|
|
173
|
+
assertCredentialDestination(endpoint, this.baseURL);
|
|
209
174
|
const method = String(opts.method || 'GET').toUpperCase();
|
|
210
175
|
for (let attempt = 0; attempt <= MAX_SESSION_REPLAYS; attempt++) {
|
|
211
176
|
// Headers for this attempt belong to the session as it is right now.
|
|
@@ -214,7 +179,7 @@ export class SDKClient {
|
|
|
214
179
|
let timer;
|
|
215
180
|
let rejection;
|
|
216
181
|
try {
|
|
217
|
-
const req = new Request(endpoint, { ...opts, signal: controller.signal });
|
|
182
|
+
const req = new Request(endpoint, { ...opts, redirect: 'error', signal: controller.signal });
|
|
218
183
|
if (prepare) prepare(req);
|
|
219
184
|
// Header-authenticated REST skips UI warming for OAuth/token/GCK.
|
|
220
185
|
// Basic must still check for TOTP before dispatch; internal bootstrap
|
|
@@ -297,6 +262,7 @@ export class SDKClient {
|
|
|
297
262
|
* that they still belong to the selected identity.
|
|
298
263
|
*/
|
|
299
264
|
async _verifyRecoveredSession() {
|
|
265
|
+
assertCredentialTransport(this.baseURL);
|
|
300
266
|
const params = new URLSearchParams({
|
|
301
267
|
sysparm_query: 'user_name=javascript:gs.getUserName()',
|
|
302
268
|
sysparm_fields: 'user_name', sysparm_limit: '1', sysparm_display_value: 'false',
|
|
@@ -972,7 +938,6 @@ export class SDKClient {
|
|
|
972
938
|
form.set('sysparm_upload_prefix', '');
|
|
973
939
|
form.set('sysparm_referring_url', 'sys_remote_update_set_list.do');
|
|
974
940
|
form.set('attachFile', new Blob([xml], { type: 'application/xml' }), filename);
|
|
975
|
-
let outcome = 'unknown';
|
|
976
941
|
try {
|
|
977
942
|
await this.rawRequest(`${this.baseURL}/sys_upload.do`, { method: 'POST', body: form,
|
|
978
943
|
headers: { ...(cookies ? { Cookie: cookies } : {}), 'X-UserToken': csrf, Referer: formURL },
|
|
@@ -998,12 +963,9 @@ export class SDKClient {
|
|
|
998
963
|
const member = actual.get(expected.sys_id);
|
|
999
964
|
return !member || getStringField(member, 'name') !== expected.name || getStringField(member, 'action') !== expected.action;
|
|
1000
965
|
})) throw new Error('Uploaded update set members did not match the XML export');
|
|
1001
|
-
outcome = 'succeeded';
|
|
1002
966
|
return { sys_id: importedID, state, count: members.length, link: `${this.baseURL}/sys_remote_update_set.do?sys_id=${importedID}` };
|
|
1003
967
|
} catch (error) {
|
|
1004
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);
|
|
1005
|
-
} finally {
|
|
1006
|
-
if (this.onMutation) await this._reportMutation({ table: 'sys_remote_update_set', sys_id: id, operation: 'create', outcome });
|
|
1007
969
|
}
|
|
1008
970
|
}
|
|
1009
971
|
|
|
@@ -1183,6 +1145,7 @@ export class SDKClient {
|
|
|
1183
1145
|
* is an actionable error, never a silent fallback.
|
|
1184
1146
|
*/
|
|
1185
1147
|
async ambSession() {
|
|
1148
|
+
assertCredentialTransport(this.baseURL);
|
|
1186
1149
|
if (!this.authProvider) throw errAuth('No authentication configured');
|
|
1187
1150
|
const creds = await this.authProvider.getCredentials();
|
|
1188
1151
|
if (!creds) throw errAuth('No valid credentials');
|
|
@@ -1222,19 +1185,21 @@ export class SDKClient {
|
|
|
1222
1185
|
}
|
|
1223
1186
|
|
|
1224
1187
|
async _initializeSession() {
|
|
1188
|
+
assertCredentialTransport(this.baseURL);
|
|
1225
1189
|
let challenged = false;
|
|
1226
1190
|
try {
|
|
1227
1191
|
const creds = await this.authProvider.getCredentials();
|
|
1228
1192
|
if (creds.auth_method === 'oauth') {
|
|
1229
1193
|
const cookieJar = new Map();
|
|
1230
1194
|
const login = `${this.baseURL}/angular.do?sysparm_type=get_user`;
|
|
1231
|
-
collectSetCookies(cookieJar, await fetch(new Request(login, { method: 'POST' })));
|
|
1195
|
+
collectSetCookies(cookieJar, await fetch(new Request(login, { method: 'POST', redirect: 'error' })));
|
|
1232
1196
|
const scopeEndpoint = `${this.baseURL}/api/now/table/sys_scope?sysparm_fields=sys_id%2Csys_class_name&sysparm_limit=1`;
|
|
1233
1197
|
collectSetCookies(cookieJar, await this._fetchWithAuth(scopeEndpoint, {
|
|
1234
1198
|
method: 'GET',
|
|
1235
1199
|
headers: serializeCookies(cookieJar) ? { Cookie: serializeCookies(cookieJar) } : {},
|
|
1236
1200
|
}));
|
|
1237
1201
|
const finalLogin = await fetch(new Request(login, {
|
|
1202
|
+
redirect: 'error',
|
|
1238
1203
|
method: 'POST',
|
|
1239
1204
|
headers: serializeCookies(cookieJar) ? { Cookie: serializeCookies(cookieJar) } : {},
|
|
1240
1205
|
}));
|
|
@@ -1284,6 +1249,7 @@ export class SDKClient {
|
|
|
1284
1249
|
// Each network exchange, including its body, has a deadline independent of
|
|
1285
1250
|
// human code entry. The race also bounds streams that do not honor abort.
|
|
1286
1251
|
async _mfaExchange(path, options, cookieJar, consume = response => response) {
|
|
1252
|
+
assertCredentialTransport(this.baseURL);
|
|
1287
1253
|
const controller = new AbortController();
|
|
1288
1254
|
let timer;
|
|
1289
1255
|
const deadline = new Promise((resolve, reject) => {
|
package/src/session.js
CHANGED
|
@@ -57,7 +57,12 @@ import { errUsage } from './errors.js';
|
|
|
57
57
|
*/
|
|
58
58
|
export function resolveSession(argv = {}, config) {
|
|
59
59
|
const cfg = config || {};
|
|
60
|
-
const profiles = cfg.profiles || {};
|
|
60
|
+
const profiles = { ...(cfg.profiles || {}) };
|
|
61
|
+
// Explicitly selecting a globally saved profile must not select a project
|
|
62
|
+
// shadow with the same name and a different destination.
|
|
63
|
+
if (argv.profile && cfg.credentialTrust?.profiles[argv.profile]) {
|
|
64
|
+
profiles[argv.profile] = cfg.credentialTrust.profiles[argv.profile];
|
|
65
|
+
}
|
|
61
66
|
|
|
62
67
|
// --profile selects the active profile for this run. Unknown names are
|
|
63
68
|
// surfaced as data (unknownProfile) — the caller (cli.js middleware)
|
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
|
-
}
|