@jacebenson/jsn 5.5.7-dev.215.1 → 5.5.7-dev.217.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/skills/servicenow/SKILL.md +9 -1
- package/src/app.js +4 -79
- package/src/capabilities.js +5 -0
- package/src/cli.js +5 -5
- package/src/commands/_generic.js +1 -0
- package/src/commands/_ticket.js +1 -1
- package/src/commands/actions.js +9 -4
- package/src/commands/approvals.js +1 -1
- package/src/commands/atf.js +1 -1
- package/src/commands/attachments.js +1 -1
- package/src/commands/auth.js +21 -2
- package/src/commands/decisiontables.js +4 -0
- package/src/commands/domains.js +1 -1
- package/src/commands/eval.js +11 -5
- package/src/commands/flows.js +15 -1
- package/src/commands/groupmembers.js +1 -1
- package/src/commands/grouproles.js +1 -1
- package/src/commands/groups.js +1 -1
- package/src/commands/midservers.js +1 -1
- package/src/commands/records.js +6 -0
- package/src/commands/scopes.js +1 -1
- package/src/commands/scrapi.js +2 -2
- package/src/commands/tickets.js +1 -1
- package/src/commands/users.js +1 -1
- package/src/config.js +1 -0
- package/src/context.js +8 -56
- package/src/flow-create.js +9 -0
- package/src/intended-context.js +68 -0
- package/src/mutation-context.js +69 -46
- package/src/output.js +1 -1
- package/src/sdk.js +34 -15
package/package.json
CHANGED
|
@@ -22,7 +22,15 @@ Discover commands with `jsn --help`, `jsn discover "search words"`, and
|
|
|
22
22
|
For development:
|
|
23
23
|
|
|
24
24
|
1. Choose or create the application scope and update set.
|
|
25
|
-
2.
|
|
25
|
+
2. Supply task-owned `--expect-scope <scope/name/id>` and
|
|
26
|
+
`--expect-update-set <name/id>` on customization writes, or explicitly save
|
|
27
|
+
profile-and-instance-bound `write_context` in local `.servicenow/config.json`.
|
|
28
|
+
Never derive intended values from current preferences. `--force` cannot bypass
|
|
29
|
+
missing intent, unknown context or mismatches. Domain-scoped customization
|
|
30
|
+
currently refuses, including `--expect-domain`, because `X-Now-Domain` does not
|
|
31
|
+
prove effective domain. Inspect with `auth status --context`; `--local` is offline.
|
|
32
|
+
Reads never print or fetch automatic context. Ordinary ticket/data edits do not
|
|
33
|
+
need customization expectations. Keep related development changes together.
|
|
26
34
|
3. Verify the results on the instance and report where changes were captured.
|
|
27
35
|
4. Offer to run relevant existing ATFs and instance scans, or create missing checks.
|
|
28
36
|
5. Ask whether anything else belongs in the update set. If the user confirms
|
package/src/app.js
CHANGED
|
@@ -10,14 +10,12 @@
|
|
|
10
10
|
import { AuthManager } from './auth.js';
|
|
11
11
|
import { createAuthRecovery } from './auth-recovery.js';
|
|
12
12
|
import { SDKClient } from './sdk.js';
|
|
13
|
-
import { OutputWriter, FormatAuto, FormatJSON, FormatMarkdown, FormatQuiet, FormatStyled
|
|
13
|
+
import { OutputWriter, FormatAuto, FormatJSON, FormatMarkdown, FormatQuiet, FormatStyled } from './output.js';
|
|
14
14
|
import { saveConfig, isTrustedCredentialDestination } from './config.js';
|
|
15
15
|
import { resolveSession, applySession, contextFromSession, requireSessionInstance } from './session.js';
|
|
16
|
-
import { getCurrentUser, getCurrentApplication, getCurrentUpdateSet } from './context.js';
|
|
17
16
|
import { errUsage, errAuth } from './errors.js';
|
|
18
17
|
import { canPrompt, canUsePicker } from './helpers.js';
|
|
19
18
|
import { guardMutationContext } from './mutation-context.js';
|
|
20
|
-
import process from 'node:process';
|
|
21
19
|
|
|
22
20
|
|
|
23
21
|
export class App {
|
|
@@ -86,85 +84,12 @@ export class App {
|
|
|
86
84
|
return this.session?.instance || '';
|
|
87
85
|
}
|
|
88
86
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
if (process.env.JSN_NO_HEADER) return;
|
|
92
|
-
if (this.output.getFormat() === FormatJSON || this.output.getFormat() === FormatQuiet) return;
|
|
93
|
-
|
|
94
|
-
// The banner is a terminal affordance, never data. `--get`/`--select`
|
|
95
|
-
// prints an extracted JSON value while the format still reports pretty, so
|
|
96
|
-
// a banner on stderr merged with `2>&1` landed in front of the JSON and
|
|
97
|
-
// broke `jsn ... 2>&1 | jq` / `json.load(sys.stdin)` at character 0. Skip
|
|
98
|
-
// it whenever an extraction was requested or stderr is not a terminal
|
|
99
|
-
// (nobody reads it there, and it costs five HTTP requests per command:
|
|
100
|
-
// user, application preference, update-set preference, scope, update set).
|
|
101
|
-
if (argv.get !== undefined && argv.get !== null && argv.get !== false) return;
|
|
102
|
-
if (process.stderr.isTTY !== true) return;
|
|
103
|
-
|
|
104
|
-
let userDisplayName = 'Unknown';
|
|
105
|
-
let userSysID = '';
|
|
106
|
-
|
|
107
|
-
try {
|
|
108
|
-
const user = await getCurrentUser(this.sdk);
|
|
109
|
-
if (user) {
|
|
110
|
-
userDisplayName = user.name || user.user_name;
|
|
111
|
-
userSysID = user.sys_id;
|
|
112
|
-
this.context.username = userDisplayName;
|
|
113
|
-
}
|
|
114
|
-
} catch {
|
|
115
|
-
// ignore
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
let displayUserName = userDisplayName;
|
|
119
|
-
if (displayUserName.length > 10) {
|
|
120
|
-
displayUserName = displayUserName.slice(0, 6) + '...';
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
// Both lookups depend on the user, but not on one another.
|
|
124
|
-
const [application, selectedUpdateSet] = userSysID ? await Promise.all([
|
|
125
|
-
getCurrentApplication(this.sdk, userSysID, { unknownWhenMissing: true }).catch(() => null),
|
|
126
|
-
getCurrentUpdateSet(this.sdk, userSysID).catch(() => null),
|
|
127
|
-
]) : [null, null];
|
|
128
|
-
const scope = application?.scope || 'unknown';
|
|
129
|
-
const updateSet = selectedUpdateSet?.name && selectedUpdateSet.name !== '-'
|
|
130
|
-
? selectedUpdateSet.name : 'unknown';
|
|
131
|
-
const updateSetSysID = selectedUpdateSet?.name && selectedUpdateSet.name !== '-'
|
|
132
|
-
? selectedUpdateSet.sys_id : '';
|
|
133
|
-
this.context.scope = scope;
|
|
134
|
-
this.context.updateSet = updateSet;
|
|
135
|
-
|
|
136
|
-
const instance = this.getEffectiveInstance();
|
|
137
|
-
const instanceLink = instance;
|
|
138
|
-
const userLink = `${instance}/sys_user_list.do?sysparm_query=sys_id=${userSysID}`;
|
|
139
|
-
const scopeLink = `${instance}/sys_scope.do?sysparm_query=scope=${scope}`;
|
|
140
|
-
const updateSetLink = updateSetSysID
|
|
141
|
-
? `${instance}/sys_update_set.do?sys_id=${updateSetSysID}`
|
|
142
|
-
: `${instance}/sys_update_set_list.do`;
|
|
143
|
-
|
|
144
|
-
const scopeFormatted = `[${scope}]`;
|
|
145
|
-
|
|
146
|
-
// Terminal hyperlinks are invisible in a TTY and garbage in a pipe, so the
|
|
147
|
-
// banner only wraps values when stderr is actually a terminal.
|
|
148
|
-
const link = (text, url) => (process.stderr.isTTY === true ? hyperlink(text, url) : text);
|
|
149
|
-
|
|
150
|
-
// Read-only profiles get a lock badge on every command run, so the
|
|
151
|
-
// armed safety is always visible (not just in `auth status`).
|
|
152
|
-
const roBadge = this.session?.readOnly === true ? ' 🔒' : '';
|
|
153
|
-
|
|
154
|
-
process.stderr.write('# Use `jsn scopes` to change scope, `jsn updatesets set` to change updateset\n');
|
|
155
|
-
process.stderr.write('PROFILE USER [SCOPE] UPDATE SET\n');
|
|
156
|
-
|
|
157
|
-
const profileStr = `${link(String(this.context.profileName).padEnd(9), instanceLink)}${roBadge}`;
|
|
158
|
-
const userStr = link(String(displayUserName).padEnd(9), userLink);
|
|
159
|
-
const scopeStr = link(String(scopeFormatted).padEnd(17), scopeLink);
|
|
160
|
-
const updateSetStr = link(String(updateSet), updateSetLink);
|
|
161
|
-
|
|
162
|
-
process.stderr.write(`${profileStr} ${userStr} ${scopeStr} ${updateSetStr}\n\n`);
|
|
163
|
-
|
|
164
|
-
}
|
|
87
|
+
// Retained for SDK consumers. Automatic context banners are retired.
|
|
88
|
+
async printContextHeader() {}
|
|
165
89
|
|
|
166
90
|
async guardMutationContext(argv) {
|
|
167
91
|
this.mutationContext = await guardMutationContext(this, argv);
|
|
92
|
+
if (this.sdk) this.sdk.mutationContext = this.mutationContext;
|
|
168
93
|
}
|
|
169
94
|
|
|
170
95
|
ok(data, opts = {}) {
|
package/src/capabilities.js
CHANGED
|
@@ -8,6 +8,11 @@
|
|
|
8
8
|
// // Subcommand verbs that mutate instance state. The mutation guard
|
|
9
9
|
// // (src/mutations.js) derives its command-path list from these.
|
|
10
10
|
// mutationSubcommands: ['create', 'update', 'delete'],
|
|
11
|
+
// // Omitted means conservative customization; operational skips capture
|
|
12
|
+
// // requirements, table follows sys_db_object ancestry to sys_metadata.
|
|
13
|
+
// mutationContext: 'table', table: 'sys_script',
|
|
14
|
+
// // Only declared flags are transaction overrides, not creation fields.
|
|
15
|
+
// transactionScopeOption: 'scope',
|
|
11
16
|
// // Command runs without a configured instance (joins the middleware
|
|
12
17
|
// // skip-list for the instance guard).
|
|
13
18
|
// noInstance: true,
|
package/src/cli.js
CHANGED
|
@@ -12,7 +12,7 @@ import { renderHelp, renderTips } from './help.js';
|
|
|
12
12
|
import { isMutationCommand, refreshMutationCommands } from './mutations.js';
|
|
13
13
|
import { maybeShowHome } from './welcome.js';
|
|
14
14
|
import { skippedUpdatesCmd } from './commands/skipped-updates.js';
|
|
15
|
-
import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands
|
|
15
|
+
import { isLocalPreview, noInstanceCommands, dailyCheckSkipCommands } from './capabilities.js';
|
|
16
16
|
import { guardExit, exitWithError, AppError, CodeUsage } from './errors.js';
|
|
17
17
|
import { formatCommandList } from './helpers.js';
|
|
18
18
|
|
|
@@ -158,6 +158,9 @@ export function buildCLI() {
|
|
|
158
158
|
.options({
|
|
159
159
|
'all-commands': { type: 'boolean', describe: 'Show the full command list, including admin and developer tools' },
|
|
160
160
|
|
|
161
|
+
'expect-scope': { type: 'string', description: 'Intended customization scope, exact scope/name or sys_id' },
|
|
162
|
+
'expect-update-set': { type: 'string', description: 'Intended in-progress capture set, exact name or sys_id' },
|
|
163
|
+
'expect-domain': { type: 'string', description: 'Intended domain; refuses writes when effective domain cannot be proven' },
|
|
161
164
|
force: {
|
|
162
165
|
type: 'boolean',
|
|
163
166
|
description: 'Approve Global + Default mutation context only after user approval; delete commands also use this for their separate confirmation',
|
|
@@ -354,10 +357,7 @@ export function buildCLI() {
|
|
|
354
357
|
}
|
|
355
358
|
}
|
|
356
359
|
|
|
357
|
-
//
|
|
358
|
-
if (!skipsContextHeader(argv)) {
|
|
359
|
-
await argv.app.printContextHeader(argv);
|
|
360
|
-
}
|
|
360
|
+
// Reads never probe or print runtime context. Writes use the guard result.
|
|
361
361
|
})
|
|
362
362
|
// CONFIGURATION
|
|
363
363
|
.command(setupCmd(wrap))
|
package/src/commands/_generic.js
CHANGED
|
@@ -99,6 +99,7 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
|
|
|
99
99
|
const readOnly = opts.readOnly || false;
|
|
100
100
|
// Capability declaration: the readOnly flag drives the mutation registry.
|
|
101
101
|
declareCapabilities(name, {
|
|
102
|
+
mutationContext: 'table', table,
|
|
102
103
|
mutationSubcommands: readOnly ? [] : ['create', 'update', 'delete'],
|
|
103
104
|
});
|
|
104
105
|
const scopeValidation = opts.scopeValidation || false;
|
package/src/commands/_ticket.js
CHANGED
|
@@ -11,7 +11,7 @@ import { declareCapabilities } from '../capabilities.js';
|
|
|
11
11
|
export function buildTicketCommands(table, displayName, alias, defaultColumns, stateMap, iconFn, wrap, opts = {}) {
|
|
12
12
|
// Ticket-style CRUD: list/show are reads; create/update/delete mutate.
|
|
13
13
|
// Root-level command only.
|
|
14
|
-
declareCapabilities(displayName, { mutationSubcommands: ['create', 'update', 'delete'] });
|
|
14
|
+
declareCapabilities(displayName, { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
|
|
15
15
|
return {
|
|
16
16
|
command: `${displayName} [subcommand]`,
|
|
17
17
|
aliases: [table, alias],
|
package/src/commands/actions.js
CHANGED
|
@@ -4,6 +4,7 @@ import { resolveRecord, unwrapSysId } from '../resolve-record.js';
|
|
|
4
4
|
import { declareCapabilities } from '../capabilities.js';
|
|
5
5
|
import { ACTION_TABLE, actionScope } from '../processflow-actions.js';
|
|
6
6
|
import { errUsage } from '../errors.js';
|
|
7
|
+
import { assertMutationScope } from '../intended-context.js';
|
|
7
8
|
import { cancelled, pickDesignerRecord, designerScope, guidedActionCreate, guidedActionEdit, guidedActionTestInputs, interactiveDesigner, hasDefinitionData, confirmDesignerMutation } from '../flow-designer-interactive.js';
|
|
8
9
|
|
|
9
10
|
const ACTION_COMMANDS = [
|
|
@@ -87,7 +88,7 @@ export const actionsCmd = wrap => {
|
|
|
87
88
|
{ action: 'list', cmd: 'jsn actions list', description: 'Back to actions' },
|
|
88
89
|
],
|
|
89
90
|
});
|
|
90
|
-
declareCapabilities('actions', { mutationSubcommands: ['create', 'update', 'edit', 'delete', 'test'] });
|
|
91
|
+
declareCapabilities('actions', { transactionScopeOption: 'scope', mutationContextExemptSubcommands: ['test'], mutationSubcommands: ['create', 'update', 'edit', 'delete', 'test'] });
|
|
91
92
|
// Retain the common wrap and output controller; domain failures get a
|
|
92
93
|
// structured error envelope and nonzero exit, never a success-shaped dispatch.
|
|
93
94
|
const run = handler => wrap(async (argv, app) => {
|
|
@@ -110,6 +111,7 @@ export const actionsCmd = wrap => {
|
|
|
110
111
|
const guided = !hasDefinitionData(argv) ? await guidedActionCreate(argv, app) : undefined;
|
|
111
112
|
const definition = guided?.definition ?? parseDataArg(argv);
|
|
112
113
|
const scope = guided?.scope ?? await designerScope(argv, app);
|
|
114
|
+
assertMutationScope(app.mutationContext, scope, 'Action creation');
|
|
113
115
|
const result = await app.sdk.createProcessFlowAction(scope, definition);
|
|
114
116
|
app.ok(result, { summary: `Created and verified action ${result.sys_id}` });
|
|
115
117
|
}),
|
|
@@ -152,9 +154,11 @@ export const actionsCmd = wrap => {
|
|
|
152
154
|
if (!hasDefinitionData(argv) && !interactiveDesigner(argv, app)) throw errUsage('Provide --data-file or --data for the full action definition in noninteractive mode');
|
|
153
155
|
const id = await actionID(argv, app);
|
|
154
156
|
if (id === undefined) return;
|
|
157
|
+
const scope = await actionScope(app.sdk, id, app.mutationContext?.application_id ?? argv.scope);
|
|
158
|
+
assertMutationScope(app.mutationContext, scope, 'Action target');
|
|
155
159
|
const definition = hasDefinitionData(argv) ? parseDataArg(argv)
|
|
156
|
-
: await guidedActionEdit(argv, app, await app.sdk.getProcessFlowAction(id,
|
|
157
|
-
const result = await app.sdk.updateProcessFlowAction(id,
|
|
160
|
+
: await guidedActionEdit(argv, app, await app.sdk.getProcessFlowAction(id, scope));
|
|
161
|
+
const result = await app.sdk.updateProcessFlowAction(id, scope, definition);
|
|
158
162
|
app.ok(result, { summary: `Saved and verified action ${id}` });
|
|
159
163
|
}),
|
|
160
164
|
})
|
|
@@ -216,7 +220,8 @@ export const actionsCmd = wrap => {
|
|
|
216
220
|
handler: run(async (argv, app) => {
|
|
217
221
|
const id = await actionID(argv, app);
|
|
218
222
|
if (id === undefined) return;
|
|
219
|
-
await actionScope(app.sdk, id, argv.scope);
|
|
223
|
+
const scope = await actionScope(app.sdk, id, app.mutationContext?.application_id ?? argv.scope);
|
|
224
|
+
assertMutationScope(app.mutationContext, scope, 'Action target');
|
|
220
225
|
await confirmDesignerMutation(argv, app, `Delete action '${id}'`);
|
|
221
226
|
await app.sdk.delete(ACTION_TABLE, id);
|
|
222
227
|
// Verify the exact target is absent. Do not interpret a 403 as deletion.
|
|
@@ -25,7 +25,7 @@ import { errUsage, errNotFound } from '../errors.js';
|
|
|
25
25
|
import { declareCapabilities } from '../capabilities.js';
|
|
26
26
|
|
|
27
27
|
// approve/reject/submit change approval state on records.
|
|
28
|
-
declareCapabilities('approvals', { mutationSubcommands: ['approve', 'reject', 'submit'] });
|
|
28
|
+
declareCapabilities('approvals', { mutationContext: 'operational', mutationSubcommands: ['approve', 'reject', 'submit'] });
|
|
29
29
|
|
|
30
30
|
// Raw sysapproval_approver.state values (verified live).
|
|
31
31
|
const APPROVAL_STATES = [
|
package/src/commands/atf.js
CHANGED
|
@@ -27,7 +27,7 @@ import { errUsage, errNotFound } from '../errors.js';
|
|
|
27
27
|
import { declareCapabilities } from '../capabilities.js';
|
|
28
28
|
|
|
29
29
|
// run/run-suite schedule tests that act on records (top-level only).
|
|
30
|
-
declareCapabilities('atf', { mutationSubcommands: ['run', 'run-suite'] });
|
|
30
|
+
declareCapabilities('atf', { mutationContext: 'operational', mutationSubcommands: ['run', 'run-suite'] });
|
|
31
31
|
|
|
32
32
|
// sn_cicd progress statuses (now-sdk poller.ts)
|
|
33
33
|
const PROGRESS_PENDING = '0';
|
|
@@ -4,7 +4,7 @@ import { confirmDelete, getStringField } from '../helpers.js';
|
|
|
4
4
|
import { errUsage } from '../errors.js';
|
|
5
5
|
import { declareCapabilities } from '../capabilities.js';
|
|
6
6
|
|
|
7
|
-
declareCapabilities('attachments', { mutationSubcommands: ['upload', 'add'] });
|
|
7
|
+
declareCapabilities('attachments', { mutationContext: 'operational', mutationSubcommands: ['upload', 'add'] });
|
|
8
8
|
const identifier = value => {
|
|
9
9
|
if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value)) throw errUsage('Supply a safe record or attachment sys_id.');
|
|
10
10
|
return value;
|
package/src/commands/auth.js
CHANGED
|
@@ -894,6 +894,8 @@ Examples:
|
|
|
894
894
|
}
|
|
895
895
|
|
|
896
896
|
export async function showAuthStatus(argv, app) {
|
|
897
|
+
if (argv.context && !argv.profile) argv = { ...argv, profile: app.session?.profileName || app.config.activeProfile || app.config.defaultProfile };
|
|
898
|
+
if (argv.context && !app.config.profiles?.[argv.profile]) throw errUsage('Select a configured profile for auth status --context.');
|
|
897
899
|
const configuredDefault = app.config.profiles?.[app.config.defaultProfile];
|
|
898
900
|
const defaultInstance = configuredDefault?.instance_url || app.config.instanceURL || '';
|
|
899
901
|
|
|
@@ -923,6 +925,7 @@ export async function showAuthStatus(argv, app) {
|
|
|
923
925
|
let verified = null;
|
|
924
926
|
let verifiedAt = null;
|
|
925
927
|
let probe;
|
|
928
|
+
let runtimeContext = argv.context ? { verified: false, status: 'not_attempted' } : undefined;
|
|
926
929
|
if (argv.local) {
|
|
927
930
|
probe = { status: 'not_attempted', code: 'not_requested', classification: 'not_checked' };
|
|
928
931
|
} else if (!instance) {
|
|
@@ -942,8 +945,17 @@ export async function showAuthStatus(argv, app) {
|
|
|
942
945
|
if (probe.status === 'succeeded' && user?.user_name) {
|
|
943
946
|
verified = true;
|
|
944
947
|
verifiedAt = user.user_name;
|
|
948
|
+
if (argv.context) {
|
|
949
|
+
try {
|
|
950
|
+
const { readWriteContext } = await import('../intended-context.js');
|
|
951
|
+
runtimeContext = { ...await readWriteContext(sdk), verified: true };
|
|
952
|
+
runtimeContext.domain.requested = profile.domain || null;
|
|
953
|
+
if (runtimeContext.user.user_name !== user.user_name) throw new Error('Context account mismatch');
|
|
954
|
+
} catch { runtimeContext = { verified: false, status: 'unavailable' }; }
|
|
955
|
+
}
|
|
945
956
|
if (profile.username && profile.username !== user.user_name) {
|
|
946
957
|
verified = false;
|
|
958
|
+
if (runtimeContext) runtimeContext = { verified: false, status: 'account_mismatch' };
|
|
947
959
|
probe = {
|
|
948
960
|
status: 'failed', code: 'account_mismatch', classification: 'account_mismatch',
|
|
949
961
|
message: 'The session account does not match the configured profile account.',
|
|
@@ -966,6 +978,7 @@ export async function showAuthStatus(argv, app) {
|
|
|
966
978
|
|
|
967
979
|
profiles.push({
|
|
968
980
|
name,
|
|
981
|
+
...(runtimeContext ? { context: runtimeContext } : {}),
|
|
969
982
|
instance,
|
|
970
983
|
username: profile.username || undefined,
|
|
971
984
|
active: name === (app.session?.profileName || app.config.activeProfile || app.config.defaultProfile),
|
|
@@ -1000,8 +1013,12 @@ export async function showAuthStatus(argv, app) {
|
|
|
1000
1013
|
const summary = `${profiles.length} ${profiles.length === 1 ? 'profile' : 'profiles'}`;
|
|
1001
1014
|
// Ship the styled view as _formatted (see renderAuthStatus); the
|
|
1002
1015
|
// OutputWriter prints it verbatim and suppresses the summary.
|
|
1003
|
-
result._formatted = renderAuthStatus(result, summary, { details: argv.details === true });
|
|
1004
|
-
if (
|
|
1016
|
+
result._formatted = renderAuthStatus(result, summary, { details: argv.details === true || argv.context === true });
|
|
1017
|
+
if (argv.context) result._formatted += profiles.map(p => {
|
|
1018
|
+
const c = p.context;
|
|
1019
|
+
return `\n${p.name}: ${c?.verified ? `user ${c.user.user_name}; scope ${c.scope}; update set ${c.update_set.name} (${c.update_set.sys_id}); domain unverified${c.domain.requested ? `, requested ${c.domain.requested}` : ''}` : `context ${c?.status || 'unavailable'}`}`;
|
|
1020
|
+
}).join('');
|
|
1021
|
+
if (!argv.details && !argv.context) {
|
|
1005
1022
|
delete result.default_instance;
|
|
1006
1023
|
result.profiles = profiles.map(({ instance: _instance, username: _username, verified_as: _verifiedAs, ...visible }) => visible);
|
|
1007
1024
|
}
|
|
@@ -1207,6 +1224,8 @@ export function authCmd(wrap) {
|
|
|
1207
1224
|
describe: 'Show authentication status (use --details for users and instance URLs)',
|
|
1208
1225
|
builder: sub => sub.option('local', {
|
|
1209
1226
|
type: 'boolean', describe: 'Show saved credential state without contacting any instance',
|
|
1227
|
+
}).option('context', {
|
|
1228
|
+
type: 'boolean', describe: 'Full context for selected/default profile, including live user, scope, capture set and domain verification limits; --local makes no requests',
|
|
1210
1229
|
}).option('details', {
|
|
1211
1230
|
type: 'boolean', describe: 'Include users and instance URLs in status output',
|
|
1212
1231
|
}),
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
|
+
import { assertMutationScope } from '../intended-context.js';
|
|
2
3
|
import { getStringField, formatRecordForDisplay, interactiveList, assertSafeExactMatch, confirmDelete } from '../helpers.js';
|
|
3
4
|
import { resolveRecord, unwrapSysId, isSysId } from '../resolve-record.js';
|
|
4
5
|
import { inspectDecisionTable } from '../decision-table-inspection.js';
|
|
@@ -19,6 +20,7 @@ export const decisiontablesCmd = (wrap) => {
|
|
|
19
20
|
.option('data', { type: 'string', describe: 'Complete decision-table JSON payload' })
|
|
20
21
|
.option('data-file', { type: 'string', describe: 'Read complete decision-table JSON payload from a file' });
|
|
21
22
|
const resolveExecutionScope = async (app) => {
|
|
23
|
+
if (app.mutationContext?.verified) return app.mutationContext.application_id;
|
|
22
24
|
const scope = app.context?.scope;
|
|
23
25
|
if (!scope) return 'global';
|
|
24
26
|
const scopeSysId = await app.sdk.resolveScope(scope);
|
|
@@ -32,6 +34,7 @@ export const decisiontablesCmd = (wrap) => {
|
|
|
32
34
|
const records = await app.sdk.list('sys_decision', params);
|
|
33
35
|
if (records.length === 0) throw new Error(`Decision table not found in active scope: ${identifier}`);
|
|
34
36
|
if (records.length > 1) throw new Error(`Decision table ${field} is ambiguous in active scope: ${identifier}`);
|
|
37
|
+
assertMutationScope(app.mutationContext, records[0].sys_scope, 'Decision table target');
|
|
35
38
|
return records[0];
|
|
36
39
|
};
|
|
37
40
|
const resolveDecisionTableForUpdate = async (app, identifier, scopeSysId) => {
|
|
@@ -42,6 +45,7 @@ export const decisiontablesCmd = (wrap) => {
|
|
|
42
45
|
const records = await app.sdk.list('sys_decision', params);
|
|
43
46
|
if (records.length === 0) throw new Error(`Decision table not found${scopeSysId === 'global' ? '' : ' in active scope'}: ${identifier}`);
|
|
44
47
|
if (records.length > 1) throw new Error(`Decision table ${field} is ambiguous: ${identifier}`);
|
|
48
|
+
assertMutationScope(app.mutationContext, records[0].sys_scope, 'Decision table target');
|
|
45
49
|
const id = unwrapSysId(records[0]);
|
|
46
50
|
if (!isSysId(id)) throw new Error(`Decision table returned an invalid identifier: ${identifier}`);
|
|
47
51
|
return id;
|
package/src/commands/domains.js
CHANGED
|
@@ -6,7 +6,7 @@ import { getStringField, interactiveList, assertSafeExactMatch } from '../helper
|
|
|
6
6
|
import { declareCapabilities } from '../capabilities.js';
|
|
7
7
|
|
|
8
8
|
// `domains set` writes the chosen domain into the profile config.
|
|
9
|
-
declareCapabilities('domains', { mutationSubcommands: ['set', 'session-set', 'session-reset'] });
|
|
9
|
+
declareCapabilities('domains', { mutationContext: 'operational', mutationSubcommands: ['set', 'session-set', 'session-reset'] });
|
|
10
10
|
|
|
11
11
|
const DETAIL_FIELDS = 'sys_id,name,parent,sys_domain_path,description,active,sys_created_on,sys_updated_on';
|
|
12
12
|
|
package/src/commands/eval.js
CHANGED
|
@@ -5,7 +5,7 @@ import { runRepl } from '../eval-repl.js';
|
|
|
5
5
|
|
|
6
6
|
// The whole command is a mutation surface (runs arbitrary server-side JS) —
|
|
7
7
|
// declared as `['']` so the root `jsn eval` command are gated.
|
|
8
|
-
declareCapabilities('eval', { mutationSubcommands: [''] });
|
|
8
|
+
declareCapabilities('eval', { transactionScopeOption: 'scope', mutationSubcommands: [''] });
|
|
9
9
|
|
|
10
10
|
export function evalCmd(wrap) {
|
|
11
11
|
return {
|
|
@@ -13,11 +13,17 @@ export function evalCmd(wrap) {
|
|
|
13
13
|
describe: 'Execute background scripts on the instance (--repl for interactive mode)',
|
|
14
14
|
builder: (yargs) => {
|
|
15
15
|
return yargs
|
|
16
|
+
.middleware(argv => {
|
|
17
|
+
if (!argv.repl) return;
|
|
18
|
+
const conflicts = ['script', 'file', 'stdin'].filter(key => argv[key]).map(key => `--${key}`);
|
|
19
|
+
if (conflicts.length) throw new Error(`--repl cannot be combined with ${conflicts.join(', ')}`);
|
|
20
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error('--repl needs an interactive terminal. Use --script, --file or --stdin for scripts and agents.');
|
|
21
|
+
})
|
|
16
22
|
.option('script', { alias: 's', type: 'string', describe: 'JavaScript code to execute (single-quote the script, double quotes inside: --script \'gs.log("Hello")\')' })
|
|
17
23
|
.option('file', { alias: 'f', type: 'string', describe: 'Read script from file (avoids shell quoting issues)' })
|
|
18
24
|
.option('stdin', { type: 'boolean', describe: 'Read script from stdin (pipe-friendly, e.g. cat script.js | jsn eval --stdin)' })
|
|
19
25
|
.option('repl', { type: 'boolean', default: false, describe: 'Interactive mode: type a script, submit with .exec (requires a terminal)' })
|
|
20
|
-
.option('scope', { alias: null, type: 'string', describe: 'Scope name or sys_id to run the script under (default:
|
|
26
|
+
.option('scope', { alias: null, type: 'string', describe: 'Scope name or sys_id to run the script under (default: verified intended scope)' })
|
|
21
27
|
// Script-mode flags (issue #177) — map to the Script Background form checkboxes
|
|
22
28
|
.option('rollback', { type: 'boolean', default: true, describe: 'Record rollback context (--no-rollback to skip)' })
|
|
23
29
|
.option('sandbox', { type: 'boolean', default: false, describe: 'Sandbox mode (KittyScript evaluator, single expression only — no DB writes)' })
|
|
@@ -26,12 +32,12 @@ export function evalCmd(wrap) {
|
|
|
26
32
|
},
|
|
27
33
|
handler: wrap(async (argv, app) => {
|
|
28
34
|
let script;
|
|
29
|
-
let scopeSysId = null;
|
|
35
|
+
let scopeSysId = app.mutationContext?.application_id || null;
|
|
30
36
|
|
|
31
37
|
// Resolve execution scope: explicit --scope wins; otherwise use the
|
|
32
38
|
// active scope from apps.current_app (same source as the banner);
|
|
33
39
|
// fall back to global only when no active scope exists.
|
|
34
|
-
let scope = argv.scope || '';
|
|
40
|
+
let scope = app.mutationContext?.scope || argv.scope || '';
|
|
35
41
|
if (!scope) {
|
|
36
42
|
try {
|
|
37
43
|
const user = await getCurrentUser(app.sdk);
|
|
@@ -46,7 +52,7 @@ export function evalCmd(wrap) {
|
|
|
46
52
|
}
|
|
47
53
|
}
|
|
48
54
|
|
|
49
|
-
if (scope) {
|
|
55
|
+
if (scope && !scopeSysId) {
|
|
50
56
|
scopeSysId = await app.sdk.resolveScope(scope);
|
|
51
57
|
if (!scopeSysId) {
|
|
52
58
|
throw new Error(`Scope not found: ${scope}`);
|
package/src/commands/flows.js
CHANGED
|
@@ -11,6 +11,7 @@ import { publishFlows, publishFlowLifecycle, publishDoctor, flowStatus } from '.
|
|
|
11
11
|
import { resolveRecord, unwrapSysId } from '../resolve-record.js';
|
|
12
12
|
import { createFlowFromManifest, updateFlowFromManifest, readCurrentUpdateSet, readCatalogItemVariables } from '../flow-create.js';
|
|
13
13
|
import { alignUpdateSetCapture } from '../context.js';
|
|
14
|
+
import { assertMutationScope, assertMutationRecordScope } from '../intended-context.js';
|
|
14
15
|
import { EXCLUDED_TRIGGER_TYPES, SUPPORTED_TRIGGER_TYPES, readTriggerCatalog, readTriggerInputDefinitions } from '../flow-triggers.js';
|
|
15
16
|
import { testFlow } from '../flow-test.js';
|
|
16
17
|
import { releaseOwnFlowSafeEdit } from '../flow-safe-edit.js';
|
|
@@ -74,7 +75,7 @@ function triggerGuidance(trigger) {
|
|
|
74
75
|
};
|
|
75
76
|
}
|
|
76
77
|
|
|
77
|
-
declareCapabilities('flows', { mutationSubcommands: ['clone', 'copy', 'create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
|
|
78
|
+
declareCapabilities('flows', { transactionScopeOption: 'scope', mutationContextExemptSubcommands: ['test', 'unlock'], mutationSubcommands: ['clone', 'copy', 'create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
|
|
78
79
|
|
|
79
80
|
function renderChecks(checks) {
|
|
80
81
|
return checks.map((c) => {
|
|
@@ -321,6 +322,7 @@ Documentation: ${docLink('flows')}`),
|
|
|
321
322
|
resource: argv.action ? 'Custom action' : 'Flow',
|
|
322
323
|
}));
|
|
323
324
|
|
|
325
|
+
await assertMutationRecordScope(app, argv.action ? 'sys_hub_action_type_definition' : 'sys_hub_flow', sysID);
|
|
324
326
|
await confirmDesignerMutation(argv, app, `Publish and activate ${argv.action ? 'action' : 'flow'} ${sysID}?`);
|
|
325
327
|
if (!argv.action) {
|
|
326
328
|
const lifecycle = await publishFlowLifecycle(app.sdk, app.getEffectiveInstance(), sysID);
|
|
@@ -408,7 +410,12 @@ Documentation: ${docLink('flows')}`),
|
|
|
408
410
|
app.requireInstance();
|
|
409
411
|
const identifier = await pickFlow(argv, app);
|
|
410
412
|
if (identifier === undefined) return;
|
|
413
|
+
if (app.mutationContext?.verified) {
|
|
414
|
+
const source = await resolveRecord(app.sdk, { table: 'sys_hub_flow', identifier, matchField: 'name', resource: 'Flow' });
|
|
415
|
+
assertMutationScope(app.mutationContext, source.sys_scope, 'Flow clone source');
|
|
416
|
+
}
|
|
411
417
|
const plan = await prepareFlowClone(app.sdk, app.getEffectiveInstance(), identifier, { ...argv, interactive: canUsePicker(app, argv) });
|
|
418
|
+
assertMutationScope(app.mutationContext, plan.scope, 'Flow clone');
|
|
412
419
|
await confirmDesignerMutation(argv, app,
|
|
413
420
|
`Clone ${plan.source.name} (${plan.source.id}) as ${JSON.stringify(plan.name)} in ${plan.scope}; inactive Draft, source unchanged`,
|
|
414
421
|
['flows', 'clone', plan.source.id, '--name', plan.name]);
|
|
@@ -437,6 +444,7 @@ Documentation: ${docLink('flows')}`),
|
|
|
437
444
|
} catch (error) {
|
|
438
445
|
throw new Error(`Invalid flow manifest JSON: ${error.message}`, { cause: error });
|
|
439
446
|
}
|
|
447
|
+
assertMutationScope(app.mutationContext, manifest.scope, 'Flow creation manifest');
|
|
440
448
|
const result = await createFlowFromManifest(app.sdk, app.getEffectiveInstance(), manifest, {
|
|
441
449
|
readUpdateSet: () => readCurrentUpdateSet(app.sdk),
|
|
442
450
|
ensureCapture: intended => alignUpdateSetCapture(app.sdk, intended),
|
|
@@ -482,6 +490,11 @@ Documentation: ${docLink('flows')}`),
|
|
|
482
490
|
} catch (error) {
|
|
483
491
|
throw new Error(`Invalid flow update manifest JSON: ${error.message}`, { cause: error });
|
|
484
492
|
}
|
|
493
|
+
if (!argv.preview && app.mutationContext?.verified) {
|
|
494
|
+
const target = await resolveRecord(app.sdk, { table: 'sys_hub_flow', identifier, matchField: 'name', resource: 'Flow' });
|
|
495
|
+
assertMutationScope(app.mutationContext, target.sys_scope, 'Flow update target');
|
|
496
|
+
if (manifest.scope !== undefined) assertMutationScope(app.mutationContext, manifest.scope, 'Flow update manifest');
|
|
497
|
+
}
|
|
485
498
|
if (!argv.preview) await confirmDesignerMutation(argv, app, `Update flow ${identifier}; unspecified components and inputs are preserved. A published flow is edited as its working definition: the published snapshot must stay unchanged.`);
|
|
486
499
|
const result = await updateFlowFromManifest(app.sdk, app.getEffectiveInstance(), argv.identifier, manifest, {
|
|
487
500
|
preview: argv.preview,
|
|
@@ -545,6 +558,7 @@ Documentation: ${docLink('flows')}`),
|
|
|
545
558
|
sysparm_limit: '1',
|
|
546
559
|
}));
|
|
547
560
|
if (!flow) throw errUsage(`Flow ${identifier} (${sysID}) was not found`);
|
|
561
|
+
assertMutationScope(app.mutationContext, flow.sys_scope, 'Flow deletion target');
|
|
548
562
|
const name = getStringField(flow, 'name');
|
|
549
563
|
const active = getStringField(flow, 'active') === 'true';
|
|
550
564
|
const counted = async () => {
|
|
@@ -3,7 +3,7 @@ import { declareCapabilities } from '../capabilities.js';
|
|
|
3
3
|
|
|
4
4
|
// add/remove write sys_user_grmember; the mutation guard (instance +
|
|
5
5
|
// read-only profile) and the delete confirmation both key off this.
|
|
6
|
-
declareCapabilities('groupmembers', { mutationSubcommands: ['add', 'remove'] });
|
|
6
|
+
declareCapabilities('groupmembers', { mutationContext: 'operational', mutationSubcommands: ['add', 'remove'] });
|
|
7
7
|
|
|
8
8
|
export function groupMembersCmd(wrap) {
|
|
9
9
|
return {
|
|
@@ -3,7 +3,7 @@ import { declareCapabilities } from '../capabilities.js';
|
|
|
3
3
|
|
|
4
4
|
// add/remove write sys_group_has_role; the mutation guard (instance +
|
|
5
5
|
// read-only profile) and the delete confirmation both key off this.
|
|
6
|
-
declareCapabilities('grouproles', { mutationSubcommands: ['add', 'remove'] });
|
|
6
|
+
declareCapabilities('grouproles', { mutationContext: 'operational', mutationSubcommands: ['add', 'remove'] });
|
|
7
7
|
|
|
8
8
|
export function groupRolesCmd(wrap) {
|
|
9
9
|
return {
|
package/src/commands/groups.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { formatRecordForDisplay, getStringField, interactiveList, resolveFieldsParam, assertSafeExactMatch, buildRecordPayload } from '../helpers.js';
|
|
2
2
|
import { declareCapabilities } from '../capabilities.js';
|
|
3
3
|
|
|
4
|
-
declareCapabilities('groups', { mutationSubcommands: ['create', 'update', 'delete'] });
|
|
4
|
+
declareCapabilities('groups', { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
|
|
5
5
|
|
|
6
6
|
export function groupsCmd(wrap) {
|
|
7
7
|
return {
|
|
@@ -20,7 +20,7 @@ const LIST_FIELDS = ['sys_id', 'name', 'status', 'host_name', 'ip_address', 'ver
|
|
|
20
20
|
const DEFAULT_TIMEOUT = 120000;
|
|
21
21
|
const DEFAULT_INTERVAL = 2000;
|
|
22
22
|
|
|
23
|
-
declareCapabilities('midservers', { mutationSubcommands: ['add', 'remove', 'execute', 'start', 'stop', 'validate'] });
|
|
23
|
+
declareCapabilities('midservers', { mutationContext: 'operational', mutationSubcommands: ['add', 'remove', 'execute', 'start', 'stop', 'validate'] });
|
|
24
24
|
|
|
25
25
|
function agentName(record) {
|
|
26
26
|
const name = getStringField(record, 'name');
|
package/src/commands/records.js
CHANGED
|
@@ -5,8 +5,10 @@ import { errUsage } from '../errors.js';
|
|
|
5
5
|
import { AmbClient } from '../amb.js';
|
|
6
6
|
import { watchRecord } from '../record-watch.js';
|
|
7
7
|
import { declareCapabilities } from '../capabilities.js';
|
|
8
|
+
import { assertMutationRecordScope, assertMutationScope } from '../intended-context.js';
|
|
8
9
|
|
|
9
10
|
declareCapabilities('records', {
|
|
11
|
+
mutationContext: 'table',
|
|
10
12
|
mutationSubcommands: ['create', 'update', 'delete', 'bulk'],
|
|
11
13
|
});
|
|
12
14
|
|
|
@@ -529,6 +531,10 @@ export function recordsCmd(wrap) {
|
|
|
529
531
|
offset += recs.length;
|
|
530
532
|
}
|
|
531
533
|
const targets = sysIDs.slice(0, argv.limit);
|
|
534
|
+
if (app.mutationContext?.verified) {
|
|
535
|
+
if (Object.hasOwn(set, 'sys_scope')) assertMutationScope(app.mutationContext, set.sys_scope, 'Bulk payload');
|
|
536
|
+
for (const id of targets) await assertMutationRecordScope(app, argv.table, id);
|
|
537
|
+
}
|
|
532
538
|
let updated = 0;
|
|
533
539
|
const failures = [];
|
|
534
540
|
for (const id of targets) {
|
package/src/commands/scopes.js
CHANGED
|
@@ -3,7 +3,7 @@ import { requireCurrentUserSysId, setCurrentApplication } from '../context.js';
|
|
|
3
3
|
import { declareCapabilities } from '../capabilities.js';
|
|
4
4
|
import { unwrapSysId } from '../resolve-record.js';
|
|
5
5
|
|
|
6
|
-
declareCapabilities('scopes', { mutationSubcommands: ['create', 'set'], mutationContextExemptSubcommands: ['
|
|
6
|
+
declareCapabilities('scopes', { mutationSubcommands: ['create', 'set'], mutationContextExemptSubcommands: ['set'] });
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* Resolve a scope identifier to a single sys_scope record.
|
package/src/commands/scrapi.js
CHANGED
|
@@ -14,7 +14,7 @@ import { declareCapabilities } from '../capabilities.js';
|
|
|
14
14
|
|
|
15
15
|
// `scrapi create` builds a full Scripted REST API in one call (list/show are
|
|
16
16
|
// reads). Registered at the root.
|
|
17
|
-
declareCapabilities('scrapi', { mutationSubcommands: ['create'] });
|
|
17
|
+
declareCapabilities('scrapi', { transactionScopeOption: 'scope', mutationSubcommands: ['create'] });
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* Parse a --resource flag value of the form:
|
|
@@ -257,7 +257,7 @@ export function scrapiCmd(wrap) {
|
|
|
257
257
|
const description = argv.description || '';
|
|
258
258
|
|
|
259
259
|
// 2. Resolve scope if provided
|
|
260
|
-
let scopeSysId = null;
|
|
260
|
+
let scopeSysId = app.mutationContext?.application_id || null;
|
|
261
261
|
if (argv.scope) {
|
|
262
262
|
scopeSysId = await app.sdk.resolveScope(argv.scope);
|
|
263
263
|
if (!scopeSysId) {
|
package/src/commands/tickets.js
CHANGED
|
@@ -4,7 +4,7 @@ import { getRecord, listRecords, recordListParams, createRecord, updateRecord, d
|
|
|
4
4
|
import { resolveSysId } from '../resolve-record.js';
|
|
5
5
|
import { declareCapabilities } from '../capabilities.js';
|
|
6
6
|
|
|
7
|
-
declareCapabilities('tickets', { mutationSubcommands: ['create', 'update', 'delete'] });
|
|
7
|
+
declareCapabilities('tickets', { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
|
|
8
8
|
|
|
9
9
|
export function ticketsCmd(wrap) {
|
|
10
10
|
return {
|
package/src/commands/users.js
CHANGED
|
@@ -2,7 +2,7 @@ import { formatRecordForDisplay, getStringField, interactiveList, resolveFieldsP
|
|
|
2
2
|
import { resolveRecord, resolveSysId } from '../resolve-record.js';
|
|
3
3
|
import { declareCapabilities } from '../capabilities.js';
|
|
4
4
|
|
|
5
|
-
declareCapabilities('users', { mutationSubcommands: ['create', 'update', 'delete'] });
|
|
5
|
+
declareCapabilities('users', { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
|
|
6
6
|
|
|
7
7
|
export function usersCmd(wrap) {
|
|
8
8
|
return {
|
package/src/config.js
CHANGED
|
@@ -58,6 +58,7 @@ function loadFromFile(cfg, filePath, source) {
|
|
|
58
58
|
if (fileCfg.connection_defaults && typeof fileCfg.connection_defaults === 'object') cfg.connectionDefaults = fileCfg.connection_defaults;
|
|
59
59
|
if (fileCfg.docs && typeof fileCfg.docs === 'object') cfg.docs = fileCfg.docs;
|
|
60
60
|
}
|
|
61
|
+
if (source === 'local' && Object.hasOwn(fileCfg, 'write_context')) cfg.writeContext = fileCfg.write_context;
|
|
61
62
|
if (fileCfg.instance_url) {
|
|
62
63
|
cfg.instanceURL = fileCfg.instance_url;
|
|
63
64
|
cfg.sources.instance_url = source;
|
package/src/context.js
CHANGED
|
@@ -122,62 +122,14 @@ export async function readEffectiveUpdateSet(sdk) {
|
|
|
122
122
|
};
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
-
/**
|
|
126
|
-
* Make the warmed session's effective capture set match the persisted choice
|
|
127
|
-
* before content writes, and verify the result.
|
|
128
|
-
*
|
|
129
|
-
* A fresh CLI invocation is a fresh authenticated session; the persisted
|
|
130
|
-
* preference is the user's intentional choice, but nothing guarantees the new
|
|
131
|
-
* session inherited it (`jsn updatesets create`/`set` may have selected the set
|
|
132
|
-
* in a session that has since ended). When the two disagree, re-apply the
|
|
133
|
-
* persisted selection through the same picker contract and verify it.
|
|
134
|
-
*
|
|
135
|
-
* Returns a report instead of throwing when the effective selection cannot be
|
|
136
|
-
* read at all (for example an auth mode that cannot keep a UI session). A
|
|
137
|
-
* readable-but-unalignable mismatch throws, so a content write never proceeds
|
|
138
|
-
* into a set the CLI would then wrongly report.
|
|
139
|
-
*/
|
|
125
|
+
/** Verify capture consistency without ever changing the session. */
|
|
140
126
|
export async function alignUpdateSetCapture(sdk, intended) {
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
intended: intended || null,
|
|
148
|
-
effective: null,
|
|
149
|
-
aligned: null,
|
|
150
|
-
action: 'unverified',
|
|
151
|
-
reason: `effective session selection could not be read: ${error.message}`,
|
|
152
|
-
};
|
|
153
|
-
}
|
|
154
|
-
const report = { intended: intended || null, effective, aligned: null, action: 'none' };
|
|
155
|
-
if (!intendedId) {
|
|
156
|
-
report.reason = 'no persisted update-set selection (Default or unreadable preference)';
|
|
157
|
-
return report;
|
|
158
|
-
}
|
|
159
|
-
if (effective.sys_id === intendedId) {
|
|
160
|
-
report.aligned = true;
|
|
161
|
-
return report;
|
|
162
|
-
}
|
|
163
|
-
try {
|
|
164
|
-
await setCurrentUpdateSet(sdk, null, intendedId);
|
|
165
|
-
} catch (error) {
|
|
166
|
-
const message = `Session capture context could not be aligned with the selected update set before any content write. `
|
|
167
|
-
+ `This session resolves to ${effective.sys_id || 'an empty selection'} (${effective.name || 'unknown'}), `
|
|
168
|
-
+ `but the persisted selection is ${intended?.name || intendedId} (${intendedId}). ${error.message} `
|
|
169
|
-
+ 'No content was written. Re-select explicitly with `jsn updatesets set` in an interactive session, '
|
|
170
|
-
+ 'or use an auth profile that keeps a UI session, then retry.';
|
|
171
|
-
const failure = new Error(message, { cause: error });
|
|
172
|
-
failure.capture_context = { ...report, aligned: false, action: 'select_failed' };
|
|
173
|
-
throw failure;
|
|
174
|
-
}
|
|
175
|
-
report.previous_effective = effective;
|
|
176
|
-
report.effective = await readEffectiveUpdateSet(sdk);
|
|
177
|
-
report.action = 'selected';
|
|
178
|
-
report.aligned = report.effective.sys_id === intendedId;
|
|
179
|
-
if (!report.aligned) {
|
|
180
|
-
report.reason = 'session still resolves to a different set after re-selection';
|
|
127
|
+
const effective = await readEffectiveUpdateSet(sdk);
|
|
128
|
+
const report = { intended: intended || null, effective, aligned: false, action: 'refused' };
|
|
129
|
+
if (!intended?.sys_id || effective.sys_id !== intended.sys_id) {
|
|
130
|
+
const error = new Error('Effective capture set differs from the persisted selection or is unknown. No context was switched; select it explicitly with jsn updatesets set.');
|
|
131
|
+
error.capture_context = report;
|
|
132
|
+
throw error;
|
|
181
133
|
}
|
|
182
|
-
return report;
|
|
134
|
+
return { ...report, aligned: true, action: 'none' };
|
|
183
135
|
}
|
package/src/flow-create.js
CHANGED
|
@@ -1914,6 +1914,10 @@ async function planManifestSteps({ manifest, beforeDefinition, existingActions,
|
|
|
1914
1914
|
export async function createFlowFromManifest(sdk, instance, inputManifest, options = {}) {
|
|
1915
1915
|
const manifest = validateFlowManifest(inputManifest);
|
|
1916
1916
|
const scope = manifest.scope;
|
|
1917
|
+
if (sdk.mutationContext?.verified) {
|
|
1918
|
+
const { assertMutationScope } = await import('./intended-context.js');
|
|
1919
|
+
assertMutationScope(sdk.mutationContext, scope, 'Flow creation transaction');
|
|
1920
|
+
}
|
|
1917
1921
|
const idFactory = options.idFactory || (() => randomUUID());
|
|
1918
1922
|
const readUpdateSet = options.readUpdateSet || (async () => null);
|
|
1919
1923
|
const snapshots = [];
|
|
@@ -2141,6 +2145,11 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
|
|
|
2141
2145
|
const published = !lifecycle.draft;
|
|
2142
2146
|
const targetScope = stringValue(target.flow.sys_scope) || stringValue(target.flow.scope);
|
|
2143
2147
|
const scope = manifest.scope ?? targetScope;
|
|
2148
|
+
if (sdk.mutationContext?.verified) {
|
|
2149
|
+
const { assertMutationScope } = await import('./intended-context.js');
|
|
2150
|
+
assertMutationScope(sdk.mutationContext, targetScope, 'Resolved flow target');
|
|
2151
|
+
assertMutationScope(sdk.mutationContext, scope, 'Flow update transaction');
|
|
2152
|
+
}
|
|
2144
2153
|
const readUpdateSet = options.readUpdateSet || (async () => null);
|
|
2145
2154
|
if (!scope) throw new Error(`Flow ${flowId} has no transaction scope`);
|
|
2146
2155
|
if (manifest.scope !== undefined && targetScope && manifest.scope !== targetScope) throw new Error(`Flow ${flowId} scope does not match the update manifest`);
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Intent comes from the task, never from the current provider preferences.
|
|
2
|
+
import { assertSafeExactMatch, getStringField } from './helpers.js';
|
|
3
|
+
import { errUsageHint } from './errors.js';
|
|
4
|
+
|
|
5
|
+
export function contextFailure(message) {
|
|
6
|
+
return errUsageHint(message, 'Supply --expect-scope and --expect-update-set from the task. Select context explicitly with scopes set / updatesets set, then retry. --force never overrides missing or mismatched intent.');
|
|
7
|
+
}
|
|
8
|
+
const raw = (record, key) => record?.[key]?.value ?? record?.[key];
|
|
9
|
+
export async function exactContextRecord(sdk, table, field, identifier) {
|
|
10
|
+
if (typeof identifier !== 'string' || !identifier.trim()) throw contextFailure(`Missing intended ${table} identifier.`);
|
|
11
|
+
assertSafeExactMatch(identifier);
|
|
12
|
+
const byId = /^[a-f0-9]{32}$/i.test(identifier) || identifier === 'global';
|
|
13
|
+
const records = await sdk.list(table, new URLSearchParams({
|
|
14
|
+
sysparm_query: `${byId ? 'sys_id' : field}=${identifier}${!byId && table === 'sys_scope' ? `^ORname=${identifier}` : ''}`,
|
|
15
|
+
sysparm_limit: '2', sysparm_display_value: 'all',
|
|
16
|
+
}));
|
|
17
|
+
if (records.length !== 1 || !raw(records[0], 'sys_id')) throw contextFailure(`Intended ${table} is missing, unreadable or ambiguous.`);
|
|
18
|
+
return records[0];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function readWriteContext(sdk) {
|
|
22
|
+
const users = await sdk.list('sys_user', new URLSearchParams({
|
|
23
|
+
sysparm_query: 'user_name=javascript:gs.getUserName()', sysparm_limit: '2',
|
|
24
|
+
sysparm_fields: 'sys_id,user_name,name', sysparm_display_value: 'all',
|
|
25
|
+
}));
|
|
26
|
+
if (users.length !== 1 || !raw(users[0], 'sys_id') || !getStringField(users[0], 'user_name')) throw contextFailure('Current user is unknown.');
|
|
27
|
+
const user = { sys_id: raw(users[0], 'sys_id'), user_name: getStringField(users[0], 'user_name') };
|
|
28
|
+
async function preference(name) {
|
|
29
|
+
const rows = await sdk.list('sys_user_preference', new URLSearchParams({
|
|
30
|
+
sysparm_query: `user=${user.sys_id}^name=${name}`, sysparm_limit: '2', sysparm_fields: 'value',
|
|
31
|
+
}));
|
|
32
|
+
if (rows.length !== 1 || !raw(rows[0], 'value') || raw(rows[0], 'value') === '-') throw contextFailure(`Current ${name} preference is unknown.`);
|
|
33
|
+
return raw(rows[0], 'value');
|
|
34
|
+
}
|
|
35
|
+
const [scopeId, setId] = await Promise.all([preference('apps.current_app'), preference('sys_update_set')]);
|
|
36
|
+
const [scope, set] = await Promise.all([sdk.get('sys_scope', scopeId), sdk.get('sys_update_set', setId)]);
|
|
37
|
+
const applicationId = raw(set, 'application');
|
|
38
|
+
if (!getStringField(scope || {}, 'scope') || !getStringField(set || {}, 'name') || !applicationId || !getStringField(set || {}, 'state')) throw contextFailure('Capture context is incomplete or unreadable.');
|
|
39
|
+
return {
|
|
40
|
+
user, scope: getStringField(scope, 'scope'), application_id: scopeId,
|
|
41
|
+
update_set: { sys_id: setId, name: getStringField(set, 'name'), state: getStringField(set, 'state'), application_id: applicationId },
|
|
42
|
+
source: 'fresh_preferences', domain: { verified: false, status: 'unverified', reason: 'X-Now-Domain is a request header, not proof of effective domain.' },
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function assertMutationScope(context, value, label = 'Mutation target') {
|
|
47
|
+
if (!context?.verified) return;
|
|
48
|
+
const scope = value?.value ?? value;
|
|
49
|
+
if (!scope || scope !== context.application_id) throw contextFailure(`${label} scope is unknown or differs from verified intended scope.`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function assertMutationRecordScope(app, table, id) {
|
|
53
|
+
if (!app.mutationContext?.verified) return;
|
|
54
|
+
const record = await app.sdk.get(table, id);
|
|
55
|
+
assertMutationScope(app.mutationContext, record?.sys_scope, 'Resolved target');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function intendedContext(app, argv) {
|
|
59
|
+
const saved = app.config.writeContext;
|
|
60
|
+
if (saved !== undefined) {
|
|
61
|
+
if (!saved || typeof saved !== 'object' || Array.isArray(saved)
|
|
62
|
+
|| !saved.profile || saved.profile !== app.session?.profileName
|
|
63
|
+
|| !saved.instance_url || saved.instance_url !== app.session?.instance) {
|
|
64
|
+
throw contextFailure('Task-local write_context must bind the selected profile and exact instance_url.');
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return { scope: argv.expectScope ?? saved?.scope, update_set: argv.expectUpdateSet ?? saved?.update_set, domain: argv.expectDomain ?? saved?.domain };
|
|
68
|
+
}
|
package/src/mutation-context.js
CHANGED
|
@@ -2,73 +2,96 @@
|
|
|
2
2
|
import process from 'node:process';
|
|
3
3
|
import { collectCapabilities } from './capabilities.js';
|
|
4
4
|
import { isMutationCommand } from './mutations.js';
|
|
5
|
-
import {
|
|
6
|
-
import { canUsePicker, getStringField, quoteShellArg } from './helpers.js';
|
|
5
|
+
import { canUsePicker, quoteShellArg } from './helpers.js';
|
|
7
6
|
import { confirm } from './prompts.js';
|
|
8
|
-
import { AppError, CodeConfirmationRequired
|
|
7
|
+
import { AppError, CodeConfirmationRequired } from './errors.js';
|
|
8
|
+
import { contextFailure, exactContextRecord, intendedContext, readWriteContext } from './intended-context.js';
|
|
9
9
|
|
|
10
10
|
export function needsMutationContext(argv) {
|
|
11
11
|
if (!isMutationCommand(argv)) return false;
|
|
12
12
|
const caps = collectCapabilities().get(argv._?.[0]) || {};
|
|
13
|
+
if (caps.mutationContext === 'operational') return false;
|
|
13
14
|
if (caps.mutationContextReadMethods?.includes(String(argv.method || 'GET').toUpperCase())) return false;
|
|
14
15
|
return !caps.mutationContextExemptSubcommands?.some(sub =>
|
|
15
16
|
sub.split(' ').every((part, index) => argv._?.[index + 1] === part));
|
|
16
17
|
}
|
|
17
18
|
|
|
18
|
-
|
|
19
|
-
|
|
19
|
+
// Table ancestry, not a command-name heuristic, decides generic record writes.
|
|
20
|
+
async function isCustomizationTable(sdk, table) {
|
|
21
|
+
if (!table) throw contextFailure('Cannot classify a write without its table.');
|
|
22
|
+
const seen = new Set();
|
|
23
|
+
let row = await exactContextRecord(sdk, 'sys_db_object', 'name', table);
|
|
24
|
+
for (let depth = 0; depth < 32; depth++) {
|
|
25
|
+
const name = row.name?.value ?? row.name;
|
|
26
|
+
if (!name || seen.has(name)) throw contextFailure('Table ancestry is incomplete or cyclic.');
|
|
27
|
+
if (name === 'sys_metadata') return true;
|
|
28
|
+
seen.add(name);
|
|
29
|
+
if (!Object.hasOwn(row, 'super_class')) throw contextFailure('Table ancestry is unreadable.');
|
|
30
|
+
const parent = row.super_class?.value ?? row.super_class;
|
|
31
|
+
if (!parent) return false;
|
|
32
|
+
row = await sdk.get('sys_db_object', parent);
|
|
33
|
+
if (!row) throw contextFailure('Table ancestry is unreadable.');
|
|
34
|
+
}
|
|
35
|
+
throw contextFailure('Table ancestry exceeds the verification bound.');
|
|
20
36
|
}
|
|
21
37
|
|
|
22
38
|
export async function guardMutationContext(app, argv, { ask = confirm, rawArgs = process.argv.slice(2) } = {}) {
|
|
23
39
|
if (!needsMutationContext(argv) || !app.sdk) return null;
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
40
|
+
const caps = collectCapabilities().get(argv._?.[0]) || {};
|
|
41
|
+
if (caps.mutationContext === 'table' && !await isCustomizationTable(app.sdk, caps.table || argv.table)) return null;
|
|
42
|
+
const expected = intendedContext(app, argv);
|
|
43
|
+
const interactive = canUsePicker(app, argv);
|
|
44
|
+
if (!interactive && (!expected.scope || !expected.update_set)) throw contextFailure('Noninteractive customization writes require intended scope and update set.');
|
|
45
|
+
// Header application is not an established effective-domain provider contract.
|
|
46
|
+
if (expected.domain !== undefined || app.session?.domain || app.session?.profile?.domain_separation || app.sdk.domain) {
|
|
47
|
+
throw contextFailure('Effective domain cannot be proven for customization writes. X-Now-Domain propagation does not verify domain selection; domain-scoped writes are not supported by this guard.');
|
|
48
|
+
}
|
|
49
|
+
let context;
|
|
50
|
+
try { context = await readWriteContext(app.sdk); }
|
|
51
|
+
catch (error) { throw contextFailure(`Cannot verify capture context: ${error.message}`); }
|
|
52
|
+
if (app.session?.username && context.user.user_name !== app.session.username) throw contextFailure('Current user differs from the selected profile.');
|
|
53
|
+
const fail = message => { const error = contextFailure(message); error.context = context; throw error; };
|
|
54
|
+
if (context.application_id !== context.update_set.application_id) fail('Selected scope and update set belong to different applications.');
|
|
55
|
+
if (!['in progress', 'in_progress'].includes(context.update_set.state.toLowerCase())) fail('Selected capture update set is not in progress.');
|
|
56
|
+
if (expected.scope !== undefined) {
|
|
57
|
+
const scope = await exactContextRecord(app.sdk, 'sys_scope', 'scope', expected.scope);
|
|
58
|
+
if ((scope.sys_id?.value ?? scope.sys_id) !== context.application_id) fail('Intended scope does not match fresh selected scope.');
|
|
33
59
|
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
if (!context.scope || !updateSet) context.diagnostics.push(diagnostic('capture_context_unknown',
|
|
38
|
-
'Capture context could not be determined. Identify the intended scope and update set before development changes.', 'jsn updatesets list'));
|
|
39
|
-
const appId = getStringField(updateSet || {}, 'application');
|
|
40
|
-
const rawAppId = updateSet?.application?.value || appId;
|
|
41
|
-
if (application?.appSysId && rawAppId && application.appSysId !== rawAppId) {
|
|
42
|
-
context.diagnostics.push(diagnostic('update_set_scope_mismatch',
|
|
43
|
-
`Selected scope ${context.scope} and update set ${updateSet.name} belong to different applications; changes may not be captured in this set.`,
|
|
44
|
-
`jsn scopes set ${quoteShellArg(rawAppId)}`));
|
|
60
|
+
if (caps.transactionScopeOption && argv[caps.transactionScopeOption] !== undefined) {
|
|
61
|
+
const scope = await exactContextRecord(app.sdk, 'sys_scope', 'scope', argv[caps.transactionScopeOption]);
|
|
62
|
+
if ((scope.sys_id?.value ?? scope.sys_id) !== context.application_id) fail('Command transaction scope differs from verified intended scope.');
|
|
45
63
|
}
|
|
46
|
-
if (
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
error.context = context; throw error;
|
|
64
|
+
if (expected.update_set !== undefined) {
|
|
65
|
+
const set = await exactContextRecord(app.sdk, 'sys_update_set', 'name', expected.update_set);
|
|
66
|
+
if ((set.sys_id?.value ?? set.sys_id) !== context.update_set.sys_id) fail('Intended update set does not match fresh selected update set.');
|
|
50
67
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
68
|
+
// Never align/switch a session implicitly. Persisted and effective selections
|
|
69
|
+
// are independent evidence; both must agree before customization can proceed.
|
|
70
|
+
const [scopeResponse, setResponse] = await Promise.all([
|
|
71
|
+
app.sdk.request(`${app.sdk.baseURL}/api/now/ui/concoursepicker/application`, { method: 'GET', readOnly: true }),
|
|
72
|
+
app.sdk.request(`${app.sdk.baseURL}/api/now/ui/concoursepicker/updateset`, { method: 'GET', readOnly: true }),
|
|
73
|
+
]);
|
|
74
|
+
if (scopeResponse?.result?.current !== context.application_id || setResponse?.result?.current?.sysId !== context.update_set.sys_id) fail('Effective session context is unknown or differs from the selected preferences. No context was switched.');
|
|
75
|
+
context.verified = true;
|
|
76
|
+
if (caps.mutationContext === 'table') context.table = caps.table || argv.table;
|
|
77
|
+
context.source = 'fresh_preferences_and_session';
|
|
78
|
+
context.expected = expected;
|
|
79
|
+
context.diagnostics = [];
|
|
80
|
+
context.approval_required = context.scope.toLowerCase() === 'global' && context.update_set.name.toLowerCase() === 'default';
|
|
81
|
+
context.approved = false;
|
|
82
|
+
if (interactive && (!expected.scope || !expected.update_set) && !context.approval_required) {
|
|
83
|
+
if (!await ask({ message: `Confirm customization in scope ${context.scope}; update set ${context.update_set.name} (${context.update_set.sys_id})?`, default: false })) fail('Customization context was not confirmed.');
|
|
84
|
+
context.approved = true;
|
|
85
|
+
}
|
|
86
|
+
if (context.approval_required) {
|
|
87
|
+
context.diagnostics.push({ code: 'global_default_update_set', severity: 'warning', message: 'Global + Default requires approval for this exact operation.' });
|
|
57
88
|
if (argv.force) context.approved = true;
|
|
58
|
-
else if (
|
|
59
|
-
context.approved = await ask({ message: `Scope: Global; update set: Default. ${context.diagnostics.at(-1).message} Approve this exact mutation: ${['jsn', ...rawArgs].map(quoteShellArg).join(' ')}?`, default: false });
|
|
60
|
-
}
|
|
89
|
+
else if (interactive) context.approved = await ask({ message: `Scope: Global; update set: Default. Approve this exact mutation: ${['jsn', ...rawArgs].map(quoteShellArg).join(' ')}?`, default: false });
|
|
61
90
|
if (!context.approved) {
|
|
62
|
-
const
|
|
63
|
-
const rerun = ['jsn', ...rawArgs.filter(arg => arg !== '--force')].map(quoteShellArg).join(' ') + (rawArgs.includes('--profile') ? '' : target);
|
|
64
|
-
const error = new AppError(CodeConfirmationRequired, 'Mutation in Global scope + Default update set requires explicit approval.',
|
|
65
|
-
`Select a dedicated set: jsn updatesets set; or jsn updatesets create --name "My Feature". Ask the user to approve this exact operation, then rerun: ${rerun} --force`);
|
|
91
|
+
const error = new AppError(CodeConfirmationRequired, 'Mutation in Global scope + Default update set requires explicit approval.', 'Select a dedicated set or obtain user approval for this exact operation, then rerun with --force and explicit expectations.');
|
|
66
92
|
error.context = context; throw error;
|
|
67
93
|
}
|
|
68
94
|
}
|
|
69
|
-
if (
|
|
70
|
-
process.stderr.write(`Mutation context: scope ${context.scope || 'unknown'}; update set ${updateSet?.name || 'unknown'}${updateSet?.sys_id ? ` (${updateSet.sys_id})` : ''}.\n`);
|
|
71
|
-
for (const item of context.diagnostics) process.stderr.write(`Warning (${item.code}): ${item.message} Run: ${item.remediation.command}\n`);
|
|
72
|
-
}
|
|
95
|
+
if (interactive) process.stderr.write(`Mutation context: scope ${context.scope}; update set ${context.update_set.name} (${context.update_set.sys_id}); user ${context.user.user_name}.\n`);
|
|
73
96
|
return context;
|
|
74
97
|
}
|
package/src/output.js
CHANGED
|
@@ -136,7 +136,7 @@ export class OutputWriter {
|
|
|
136
136
|
// typo looked like a successful empty result until the next tool in the
|
|
137
137
|
// pipeline failed to parse it. Present null/false/0/"" still print as-is.
|
|
138
138
|
if (this.jqFilter) {
|
|
139
|
-
const envelope = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [] };
|
|
139
|
+
const envelope = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [], ...(opts.context ? { context: opts.context } : {}) };
|
|
140
140
|
const value = resolvePath(envelope, this.jqFilter);
|
|
141
141
|
if (value === undefined) throw errExtractionNotFound(this.jqFilter);
|
|
142
142
|
const indent = this.verbose && !this.raw ? 2 : undefined;
|
package/src/sdk.js
CHANGED
|
@@ -39,15 +39,13 @@ function serializeCookies(cookieJar) {
|
|
|
39
39
|
return [...cookieJar].map(([name, value]) => `${name}=${value}`).join('; ');
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
-
//
|
|
43
|
-
//
|
|
44
|
-
//
|
|
45
|
-
//
|
|
46
|
-
//
|
|
47
|
-
//
|
|
48
|
-
//
|
|
49
|
-
// Basic is the exception: normal requests must first detect any TOTP challenge
|
|
50
|
-
// before a pending operation can be sent. See docs/AUTH_LIFECYCLE.md.
|
|
42
|
+
// Endpoint capability, not authentication policy: these REST surfaces can use
|
|
43
|
+
// header-only auth. OAuth now prefers the existing UI session even here because
|
|
44
|
+
// tables with ws_access=false reject Bearer while allowing the same user's UI
|
|
45
|
+
// session. JSN_ALWAYS_WARM_SESSION=0 opts OAuth out only on these paths;
|
|
46
|
+
// stateful:true, required UI endpoints and value 1 retain session precedence.
|
|
47
|
+
// Basic/TOTP, supplied token and GCK policies remain unchanged. Internal OAuth
|
|
48
|
+
// bootstrap must bypass warming to avoid recursion. See site/docs/guides/setup.md.
|
|
51
49
|
const STATELESS_REST_PREFIXES = ['/api/now/table/', '/api/now/stats/', '/api/now/v1/batch'];
|
|
52
50
|
|
|
53
51
|
export function needsUiSession(url, { stateful = false, forceSession = false } = {}) {
|
|
@@ -106,7 +104,7 @@ export class SDKClient {
|
|
|
106
104
|
this._recoveryPromise = null;
|
|
107
105
|
}
|
|
108
106
|
|
|
109
|
-
async _setAuth(req, { skipOAuthSession = false, basicSession = false } = {}) {
|
|
107
|
+
async _setAuth(req, { skipOAuthSession = false, basicSession = false, preferOAuthSession = false, oauthHeaderOnly = false } = {}) {
|
|
110
108
|
if (!this.authProvider) {
|
|
111
109
|
throw errAuth('No authentication configured');
|
|
112
110
|
}
|
|
@@ -141,14 +139,19 @@ export class SDKClient {
|
|
|
141
139
|
break;
|
|
142
140
|
case 'token':
|
|
143
141
|
case 'oauth':
|
|
144
|
-
if (!skipOAuthSession) {
|
|
142
|
+
if (!skipOAuthSession || creds.auth_method === 'oauth' && preferOAuthSession) {
|
|
145
143
|
const cookies = await this._warmSession();
|
|
146
144
|
if (cookies && this.sessionUserToken) {
|
|
145
|
+
if (creds.auth_method === 'oauth') req.headers.delete('Authorization');
|
|
147
146
|
req.headers.set('Cookie', cookies);
|
|
148
147
|
req.headers.set('X-UserToken', this.sessionUserToken);
|
|
149
148
|
break;
|
|
150
149
|
}
|
|
151
150
|
}
|
|
151
|
+
if (creds.auth_method === 'oauth' && oauthHeaderOnly) {
|
|
152
|
+
req.headers.delete('Cookie');
|
|
153
|
+
req.headers.delete('X-UserToken');
|
|
154
|
+
}
|
|
152
155
|
req.headers.set('Authorization', `Bearer ${creds.access_token}`);
|
|
153
156
|
break;
|
|
154
157
|
case 'gck':
|
|
@@ -181,14 +184,19 @@ export class SDKClient {
|
|
|
181
184
|
try {
|
|
182
185
|
const req = new Request(endpoint, { ...opts, redirect: 'error', signal: controller.signal });
|
|
183
186
|
if (prepare) prepare(req);
|
|
184
|
-
//
|
|
185
|
-
//
|
|
186
|
-
//
|
|
187
|
+
// Endpoint requirements and Basic challenge gates are unchanged. OAuth
|
|
188
|
+
// additionally prefers the UI session on otherwise stateless REST unless
|
|
189
|
+
// explicitly opted out. Internal bootstrap bypasses both to avoid recursion.
|
|
187
190
|
const skipSession = skipOAuthSession || !needsUiSession(endpoint, {
|
|
188
191
|
stateful,
|
|
189
192
|
forceSession: process.env.JSN_ALWAYS_WARM_SESSION === '1',
|
|
190
193
|
});
|
|
191
|
-
await this._setAuth(req, {
|
|
194
|
+
await this._setAuth(req, {
|
|
195
|
+
skipOAuthSession: skipSession,
|
|
196
|
+
basicSession: !skipOAuthSession,
|
|
197
|
+
preferOAuthSession: !skipOAuthSession && process.env.JSN_ALWAYS_WARM_SESSION !== '0',
|
|
198
|
+
oauthHeaderOnly: !skipOAuthSession && skipSession && process.env.JSN_ALWAYS_WARM_SESSION === '0',
|
|
199
|
+
});
|
|
192
200
|
timer = setTimeout(() => controller.abort(), timeout);
|
|
193
201
|
const response = await fetch(req);
|
|
194
202
|
if (!skipOAuthSession && this.recovery) {
|
|
@@ -423,7 +431,16 @@ export class SDKClient {
|
|
|
423
431
|
return result?.result || null;
|
|
424
432
|
}
|
|
425
433
|
|
|
434
|
+
async _guardTableMutation(table, id, data) {
|
|
435
|
+
const context = this.mutationContext;
|
|
436
|
+
if (!context?.verified || context.table !== table) return;
|
|
437
|
+
const { assertMutationScope } = await import('./intended-context.js');
|
|
438
|
+
if (id) assertMutationScope(context, (await this.get(table, id))?.sys_scope, 'Record target');
|
|
439
|
+
if (data && Object.hasOwn(data, 'sys_scope')) assertMutationScope(context, data.sys_scope, 'Record payload');
|
|
440
|
+
}
|
|
441
|
+
|
|
426
442
|
async create(table, data) {
|
|
443
|
+
await this._guardTableMutation(table, null, data);
|
|
427
444
|
const endpoint = `${this.baseURL}/api/now/table/${table}`;
|
|
428
445
|
const result = await this.request(endpoint, {
|
|
429
446
|
method: 'POST',
|
|
@@ -433,6 +450,7 @@ export class SDKClient {
|
|
|
433
450
|
}
|
|
434
451
|
|
|
435
452
|
async update(table, sysID, data) {
|
|
453
|
+
await this._guardTableMutation(table, sysID, data);
|
|
436
454
|
const endpoint = `${this.baseURL}/api/now/table/${table}/${sysID}`;
|
|
437
455
|
const result = await this.request(endpoint, {
|
|
438
456
|
method: 'PUT',
|
|
@@ -442,6 +460,7 @@ export class SDKClient {
|
|
|
442
460
|
}
|
|
443
461
|
|
|
444
462
|
async delete(table, sysID) {
|
|
463
|
+
await this._guardTableMutation(table, sysID);
|
|
445
464
|
const endpoint = `${this.baseURL}/api/now/table/${table}/${sysID}`;
|
|
446
465
|
await this.request(endpoint, { method: 'DELETE' });
|
|
447
466
|
}
|