@jacebenson/jsn 5.5.6-dev.203.1 → 5.5.6-dev.204.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.6-dev.203.1",
3
+ "version": "5.5.6-dev.204.1",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
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
@@ -12,7 +12,7 @@ import { AuthManager } from './auth.js';
12
12
  import { createAuthRecovery } from './auth-recovery.js';
13
13
  import { SDKClient } from './sdk.js';
14
14
  import { OutputWriter, FormatAuto, FormatJSON, FormatMarkdown, FormatQuiet, FormatStyled, hyperlink } from './output.js';
15
- import { saveConfig } from './config.js';
15
+ import { saveConfig, isTrustedCredentialDestination } 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';
@@ -43,6 +43,9 @@ export class App {
43
43
  getUsername: () => this.session?.username || null,
44
44
  getEffectiveInstance: () => this.session?.instance || '',
45
45
  getAuthMethod: () => this.session?.profile?.auth_method || null,
46
+ isTrustedCredentialDestination: instance => isTrustedCredentialDestination(this.config, instance,
47
+ this._authArgv?.instance || this._sessionArgv?.instance || (this.session?.profileExplicit ? '' : this.session?.override),
48
+ this.session?.profileExplicit ? this.session.profileName : ''),
46
49
  });
47
50
 
48
51
  if (this.session.instance) {
@@ -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/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 });
@@ -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';
@@ -206,6 +207,7 @@ export class SDKClient {
206
207
  timeout = this.timeout, prepare, skipOAuthSession = false, normalizeErrors = false,
207
208
  allowMutationReplay = false, stateful = false,
208
209
  }, consume = (response) => response) {
210
+ assertCredentialDestination(endpoint, this.baseURL);
209
211
  const method = String(opts.method || 'GET').toUpperCase();
210
212
  for (let attempt = 0; attempt <= MAX_SESSION_REPLAYS; attempt++) {
211
213
  // Headers for this attempt belong to the session as it is right now.
@@ -214,7 +216,7 @@ export class SDKClient {
214
216
  let timer;
215
217
  let rejection;
216
218
  try {
217
- const req = new Request(endpoint, { ...opts, signal: controller.signal });
219
+ const req = new Request(endpoint, { ...opts, redirect: 'error', signal: controller.signal });
218
220
  if (prepare) prepare(req);
219
221
  // Header-authenticated REST skips UI warming for OAuth/token/GCK.
220
222
  // Basic must still check for TOTP before dispatch; internal bootstrap
@@ -297,6 +299,7 @@ export class SDKClient {
297
299
  * that they still belong to the selected identity.
298
300
  */
299
301
  async _verifyRecoveredSession() {
302
+ assertCredentialTransport(this.baseURL);
300
303
  const params = new URLSearchParams({
301
304
  sysparm_query: 'user_name=javascript:gs.getUserName()',
302
305
  sysparm_fields: 'user_name', sysparm_limit: '1', sysparm_display_value: 'false',
@@ -1183,6 +1186,7 @@ export class SDKClient {
1183
1186
  * is an actionable error, never a silent fallback.
1184
1187
  */
1185
1188
  async ambSession() {
1189
+ assertCredentialTransport(this.baseURL);
1186
1190
  if (!this.authProvider) throw errAuth('No authentication configured');
1187
1191
  const creds = await this.authProvider.getCredentials();
1188
1192
  if (!creds) throw errAuth('No valid credentials');
@@ -1222,19 +1226,21 @@ export class SDKClient {
1222
1226
  }
1223
1227
 
1224
1228
  async _initializeSession() {
1229
+ assertCredentialTransport(this.baseURL);
1225
1230
  let challenged = false;
1226
1231
  try {
1227
1232
  const creds = await this.authProvider.getCredentials();
1228
1233
  if (creds.auth_method === 'oauth') {
1229
1234
  const cookieJar = new Map();
1230
1235
  const login = `${this.baseURL}/angular.do?sysparm_type=get_user`;
1231
- collectSetCookies(cookieJar, await fetch(new Request(login, { method: 'POST' })));
1236
+ collectSetCookies(cookieJar, await fetch(new Request(login, { method: 'POST', redirect: 'error' })));
1232
1237
  const scopeEndpoint = `${this.baseURL}/api/now/table/sys_scope?sysparm_fields=sys_id%2Csys_class_name&sysparm_limit=1`;
1233
1238
  collectSetCookies(cookieJar, await this._fetchWithAuth(scopeEndpoint, {
1234
1239
  method: 'GET',
1235
1240
  headers: serializeCookies(cookieJar) ? { Cookie: serializeCookies(cookieJar) } : {},
1236
1241
  }));
1237
1242
  const finalLogin = await fetch(new Request(login, {
1243
+ redirect: 'error',
1238
1244
  method: 'POST',
1239
1245
  headers: serializeCookies(cookieJar) ? { Cookie: serializeCookies(cookieJar) } : {},
1240
1246
  }));
@@ -1284,6 +1290,7 @@ export class SDKClient {
1284
1290
  // Each network exchange, including its body, has a deadline independent of
1285
1291
  // human code entry. The race also bounds streams that do not honor abort.
1286
1292
  async _mfaExchange(path, options, cookieJar, consume = response => response) {
1293
+ assertCredentialTransport(this.baseURL);
1287
1294
  const controller = new AbortController();
1288
1295
  let timer;
1289
1296
  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)