@jacebenson/jsn 4.4.0-dev.114.1 → 4.4.0-dev.115.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 CHANGED
@@ -174,3 +174,35 @@ outcome: inspect requests before retrying. JSN does not automatically submit a
174
174
  second order. `create/list/show` retain their definition-management behavior.
175
175
 
176
176
  See the [Service Catalog API reference](https://www.servicenow.com/docs/r/api-reference/rest-apis/c_ServiceCatalogAPI.html).
177
+
178
+ ## Domain configuration and browser sessions
179
+
180
+ `jsn domains current` reports the selected profile's configured `X-Now-Domain`
181
+ header. `domains set <name-or-id>` and `domains set clear` configure that header
182
+ locally. Header effectiveness depends on the instance; clearing it does not
183
+ reset the actual server session domain.
184
+
185
+ With saved browser-session (`gck`) credentials, use these explicit commands:
186
+
187
+ ```bash
188
+ jsn domains session-current --profile example --json
189
+ jsn domains session-list --profile example --search '*Internal' --limit 20 --offset 0 --json
190
+ jsn domains session-reset --profile example --json
191
+ jsn domains session-list --profile example --json
192
+ jsn domains session-set <domain-sys-id> --profile example --json
193
+ ```
194
+
195
+ `session-list` returns one picker-visible page (`items`, `offset`, `limit`,
196
+ `next_offset`). Search matches a name prefix, or a substring with a leading `*`.
197
+ Visibility depends on the actual session domain. For cross-branch selection,
198
+ explicitly reset to global, then list and select a domain from that result.
199
+ Neither listing nor selecting silently resets the session. `session-current`
200
+ reports both `configured_domain` and `session_domain`.
201
+
202
+ **Session reset and selection may affect a browser sharing these credentials.**
203
+ Both commands verify the resulting domain with a separate readback. They leave
204
+ profile configuration unchanged and omit the configured domain header on picker
205
+ requests. Save the original domain ID from `session-current` if you intend to
206
+ restore it afterward. A failed readback can leave the session changed; inspect
207
+ `session-current` before retrying. These commands do not call `touch-session`.
208
+ Other authentication methods retain the existing profile configuration flow.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "4.4.0-dev.114.1",
3
+ "version": "4.4.0-dev.115.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": {
@@ -1,23 +1,74 @@
1
- // Domain separation commands — list/show/current/set
2
- //
3
- // Domain separation (plugin) adds a `domain` table holding the domain
4
- // hierarchy. Each domain-separated table's rows carry `sys_domain` +
5
- // `sys_domain_path`, and queries are auto-filtered to the session domain
6
- // plus its children. There is NO durable platform-side "current domain"
7
- // preference a CLI can write (the picker sets the in-memory session only,
8
- // and `sys_user.domain` is write-protected even for admin). So jsn stores
9
- // the chosen domain in the active profile and sends it on every request
10
- // via the `X-Now-Domain` header — the same scoping the platform applies
11
- // to its own picker sessions.
1
+ // Domain separation commands. Profile configuration sends X-Now-Domain;
2
+ // explicit session-* commands manage the server-side browser session instead.
3
+ // Header effectiveness depends on the instance and is not a session switch.
12
4
 
13
5
  import { getStringField, interactiveList, assertSafeExactMatch } from '../helpers.js';
14
6
  import { declareCapabilities } from '../capabilities.js';
15
7
 
16
8
  // `domains set` writes the chosen domain into the profile config.
17
- declareCapabilities('domains', { mutationSubcommands: ['set'] });
9
+ declareCapabilities('domains', { mutationSubcommands: ['set', 'session-set', 'session-reset'] });
18
10
 
19
11
  const DETAIL_FIELDS = 'sys_id,name,parent,sys_domain_path,description,active,sys_created_on,sys_updated_on';
20
12
 
13
+ async function sessionRequest(app, path, options = {}) {
14
+ const credentials = await app.sdk.authProvider?.getCredentials();
15
+ if (credentials?.auth_method !== 'gck') {
16
+ throw new Error('Session domain commands require browser-session (gck) credentials. Use domains set for profile header configuration.');
17
+ }
18
+ return app.sdk.request(`${app.sdk.baseURL}${path}`, { ...options, domain: '' });
19
+ }
20
+
21
+ export async function readSessionDomain(app) {
22
+ const response = await sessionRequest(app, '/api/now/ui/concoursepicker/current');
23
+ const current = response?.result?.currentDomain;
24
+ if (!current || typeof current.value !== 'string' || !current.value) {
25
+ throw new Error('Invalid session domain response: expected result.currentDomain.value.');
26
+ }
27
+ return current;
28
+ }
29
+
30
+ export async function listSessionDomains(app, { search = '', offset = 0, limit = 20 } = {}) {
31
+ if (!Number.isInteger(offset) || offset < 0 || !Number.isInteger(limit) || limit < 1 || limit > 100) {
32
+ throw new Error('Picker offset must be a nonnegative integer and limit must be between 1 and 100.');
33
+ }
34
+ const contains = search.startsWith('*');
35
+ const term = contains ? search.slice(1) : search;
36
+ if (term) assertSafeExactMatch(term);
37
+ const response = await sessionRequest(app, '/angular.do?sysparm_type=ref_list_data', {
38
+ method: 'POST',
39
+ body: JSON.stringify({
40
+ sysparm_domain: 'picker', table: 'domain', sysparm_for_impersonation: false,
41
+ qualifier: 'active=true', count: limit, start: offset,
42
+ p: `domain;q:name${contains ? 'CONTAINS' : 'STARTSWITH'}${term}^nameISNOTEMPTY;r:active=true`,
43
+ }),
44
+ });
45
+ const items = response?.items ?? response?.result?.items;
46
+ if (!Array.isArray(items)) throw new Error('Invalid domain picker response: expected items array.');
47
+ return { items, offset, limit, next_offset: items.length === limit ? offset + items.length : null };
48
+ }
49
+
50
+ export async function switchSessionDomain(app, value) {
51
+ if (value !== 'global' && !/^[a-f0-9]{32}$/i.test(value)) {
52
+ throw new Error('Supply a domain sys_id from session-list; use session-reset for global.');
53
+ }
54
+ // Probe before changing anything, so authentication/readback failures occur early.
55
+ await readSessionDomain(app);
56
+ await sessionRequest(app, '/api/now/ui/concoursepicker/domain', {
57
+ method: 'PUT', ...(value === 'global' ? {} : { body: JSON.stringify({ value }) }),
58
+ });
59
+ let current;
60
+ try {
61
+ current = await readSessionDomain(app);
62
+ } catch (err) {
63
+ err.message += ' The session may have changed; inspect domains session-current before retrying.';
64
+ throw err;
65
+ }
66
+ if (current.value !== value) {
67
+ throw new Error(`Session domain verification failed: expected ${value}, received ${current.value}. The session may have changed; inspect domains session-current before retrying.`);
68
+ }
69
+ return current;
70
+ }
71
+
21
72
  /**
22
73
  * Gate: domain separation must be installed. The `domain` table only
23
74
  * exists on instances with the plugin. A single cheap query detects it;
@@ -30,8 +81,11 @@ export async function isDomainSeparationInstalled(app) {
30
81
  params.set('sysparm_fields', 'sys_id,name');
31
82
  await app.sdk.list('domain', params);
32
83
  return true;
33
- } catch {
34
- return false;
84
+ } catch (err) {
85
+ // Only the platform's explicit invalid-table response establishes absence.
86
+ // Authentication, ACL, transport, and unrelated 404 errors must surface.
87
+ if ((!err.status || [400, 404].includes(err.status)) && /invalid table(?:\s+|:\s*)["'`]?domain\b/i.test(err.message)) return false;
88
+ throw err;
35
89
  }
36
90
  }
37
91
 
@@ -206,31 +260,71 @@ export function domainsCmd(wrap) {
206
260
  describe: 'Show the configured domain for this profile',
207
261
  handler: wrap(async (argv, app) => {
208
262
  await requireDomainSeparation(app);
209
- const domain = app._profileDomain(app.config);
263
+ const domain = app.session.domain;
210
264
  if (!domain) {
211
265
  app.ok({ domain: '', scoping: 'none' }, {
212
- summary: 'No domain configured — requests are not domain-scoped',
266
+ summary: 'No domain header configured — server session scoping may still apply',
213
267
  });
214
268
  return;
215
269
  }
216
270
  // Resolve the configured value to a display name if it's a sys_id
217
271
  let label = domain;
218
- try {
272
+ {
219
273
  const params = new URLSearchParams();
220
274
  params.set('sysparm_query', `sys_id=${domain}`);
221
275
  params.set('sysparm_limit', '1');
222
276
  params.set('sysparm_fields', 'sys_id,name');
223
277
  const records = await app.sdk.list('domain', params);
224
278
  if (records.length > 0) label = `${getStringField(records[0], 'name')} (${domain})`;
225
- } catch { /* non-fatal — show raw value */ }
279
+ }
226
280
  app.ok({ domain, scoping: 'X-Now-Domain header' }, {
227
281
  summary: `Configured domain: ${label}`,
228
282
  });
229
283
  }),
230
284
  })
285
+ .command({
286
+ command: 'session-current',
287
+ describe: 'Read actual browser-session domain (separate from profile configuration)',
288
+ handler: wrap(async (argv, app) => {
289
+ const current = await readSessionDomain(app);
290
+ app.ok({ configured_domain: app.session.domain, session_domain: current }, {
291
+ summary: `Session domain: ${current.displayValue || current.value}`,
292
+ });
293
+ }),
294
+ })
295
+ .command({
296
+ command: 'session-list',
297
+ describe: 'List picker-visible session domains; reset explicitly to global for cross-branch selection',
298
+ builder: y => y
299
+ .option('search', { type: 'string', default: '', describe: 'Name prefix; leading * searches by substring' })
300
+ .option('offset', { type: 'number', default: 0, describe: 'Picker page offset' })
301
+ .option('limit', { type: 'number', default: 20, describe: 'Picker page size' }),
302
+ handler: wrap(async (argv, app) => {
303
+ const page = await listSessionDomains(app, argv);
304
+ app.ok(page, { summary: `${page.items.length} picker-visible domain(s)` });
305
+ }),
306
+ })
307
+ .command({
308
+ command: 'session-set <domain>',
309
+ describe: 'Switch shared browser session to a picker domain sys_id and verify (may affect your browser)',
310
+ builder: y => y.positional('domain', { type: 'string', describe: 'Exact picker sys_id; use session-reset for global' }),
311
+ handler: wrap(async (argv, app) => {
312
+ if (!/^[a-f0-9]{32}$/i.test(argv.domain)) throw new Error('Supply a domain sys_id from session-list; use session-reset for global.');
313
+ const current = await switchSessionDomain(app, argv.domain);
314
+ app.ok({ session_domain: current }, { summary: `Session domain: ${current.displayValue || current.value}` });
315
+ }),
316
+ })
317
+ .command({
318
+ command: 'session-reset',
319
+ describe: 'Reset shared browser session to global and verify (may affect your browser)',
320
+ handler: wrap(async (argv, app) => {
321
+ const current = await switchSessionDomain(app, 'global');
322
+ app.ok({ session_domain: current }, { summary: 'Session domain reset to global' });
323
+ }),
324
+ })
231
325
  .command({
232
326
  command: 'set [domain]',
233
- describe: 'Set the configured domain for this profile (interactive picker when run bare; omit to clear)',
327
+ describe: 'Set the profile domain header (picker when bare; "clear" to unset)',
234
328
  handler: wrap(async (argv, app) => {
235
329
  await requireDomainSeparation(app);
236
330
  let domainArg = argv.domain;
@@ -240,27 +334,22 @@ export function domainsCmd(wrap) {
240
334
  domainArg = picked;
241
335
  } else if (domainArg.toLowerCase() === 'none' || domainArg.toLowerCase() === 'clear') {
242
336
  app.setDomain('');
243
- app.ok({ domain: '' }, { summary: 'Domain cleared — requests are no longer domain-scoped' });
337
+ app.ok({ domain: '' }, { summary: 'Domain header cleared — server session scoping may still apply' });
244
338
  return;
245
339
  }
246
340
 
247
341
  const sysID = await resolveDomainSysId(app, domainArg);
248
342
  app.setDomain(sysID);
249
343
  app.ok({ domain: sysID, name: domainArg }, {
250
- summary: `Configured domain: ${domainArg} — all requests scoped to it`,
344
+ summary: `Configured domain: ${domainArg} — X-Now-Domain header configured`,
251
345
  });
252
346
  }),
253
347
  });
254
348
  },
255
- handler: async (argv) => {
349
+ handler: wrap(async (argv, app) => {
256
350
  if (!argv._[1]) {
257
- const app = argv.app;
258
351
  let installed = false;
259
- try {
260
- if (app && app.sdk) installed = await isDomainSeparationInstalled(app);
261
- } catch {
262
- installed = false;
263
- }
352
+ if (app && app.sdk) installed = await isDomainSeparationInstalled(app);
264
353
  if (!installed) {
265
354
  if (app && app.sdk) {
266
355
  console.log('Domain separation is not installed on this instance.');
@@ -277,10 +366,12 @@ export function domainsCmd(wrap) {
277
366
  console.log(' current Show the configured domain for this profile');
278
367
  console.log(' set [domain] Configure the domain for this profile (picker when bare; "clear" to unset)');
279
368
  console.log('\nDomains are applied per-request via the X-Now-Domain header —');
280
- console.log('the platform filters every query to the domain and its children.');
369
+ console.log('header effectiveness depends on the instance.');
370
+ console.log('Use session-current/list/set/reset for browser-session domains.');
371
+ console.log('Session changes may affect a browser sharing these credentials.');
281
372
  console.log('Run "jsn domains <command> --help" for details.');
282
373
  }
283
- },
374
+ }),
284
375
  };
285
376
  }
286
377
 
package/src/sdk.js CHANGED
@@ -189,7 +189,7 @@ export class SDKClient {
189
189
  }
190
190
 
191
191
  async request(endpoint, opts = {}) {
192
- const { timeout = this.timeout, readOnly = false, touchLastSeen, ...requestOptions } = opts;
192
+ const { timeout = this.timeout, readOnly = false, touchLastSeen, domain = this.domain, ...requestOptions } = opts;
193
193
  if (readOnly && (requestOptions.method || 'GET').toUpperCase() !== 'GET') throw new Error('Read-only SDK requests require GET');
194
194
  return this._withAuthenticatedRequest(endpoint, requestOptions, {
195
195
  timeout,
@@ -199,7 +199,7 @@ export class SDKClient {
199
199
  if (requestOptions.body && typeof requestOptions.body === 'string') {
200
200
  req.headers.set('Content-Type', 'application/json');
201
201
  }
202
- if (this.domain) req.headers.set('X-Now-Domain', this.domain);
202
+ if (domain) req.headers.set('X-Now-Domain', domain);
203
203
  },
204
204
  }, async (resp) => {
205
205
  const body = await resp.text();