@jacebenson/jsn 5.2.0 → 5.3.0-dev.136.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 +72 -9
- package/package.json +1 -1
- package/skills/servicenow/SKILL.md +11 -1
- package/src/amb.js +370 -0
- package/src/app.js +10 -4
- package/src/auth-recovery.js +27 -12
- package/src/cli.js +11 -1
- package/src/command-audience.js +1 -1
- package/src/commands/cases.js +218 -0
- package/src/commands/catalog/enrich.js +151 -56
- package/src/commands/catalog-order.js +99 -23
- package/src/commands/catalog.js +6 -5
- package/src/commands/records.js +110 -1
- package/src/commands/store.js +312 -0
- package/src/commands/updatesets.js +253 -11
- package/src/errors.js +10 -3
- package/src/output.js +31 -1
- package/src/record-command-profiles.js +1 -1
- package/src/record-watch.js +206 -0
- package/src/sdk.js +195 -14
- package/src/session-recovery.js +120 -0
- package/src/store.js +588 -0
- package/src/update-set-apply.js +287 -0
- package/src/welcome.js +324 -0
package/src/output.js
CHANGED
|
@@ -167,6 +167,9 @@ export class OutputWriter {
|
|
|
167
167
|
resp.recovery = e.recovery;
|
|
168
168
|
if (Object.hasOwn(e, 'profile')) resp.profile = e.profile;
|
|
169
169
|
}
|
|
170
|
+
// Captured browser sessions cannot be renewed, so the machine envelope
|
|
171
|
+
// must carry the same recapture marker the in-process error exposes.
|
|
172
|
+
if (e.recapture_required) resp.recapture_required = true;
|
|
170
173
|
switch (format) {
|
|
171
174
|
case FormatJSON:
|
|
172
175
|
case FormatQuiet:
|
|
@@ -186,6 +189,33 @@ export class OutputWriter {
|
|
|
186
189
|
}
|
|
187
190
|
}
|
|
188
191
|
|
|
192
|
+
/**
|
|
193
|
+
* Write one item of an event stream (e.g. `records watch`).
|
|
194
|
+
*
|
|
195
|
+
* A stream cannot use the single-envelope `ok()`, so this method emits one
|
|
196
|
+
* compact JSON object per line — newline-delimited JSON, the shape agents
|
|
197
|
+
* and scripts can consume incrementally without buffering the whole run.
|
|
198
|
+
* Human formats print `opts.line` (domain-formatted by the command) and
|
|
199
|
+
* fall back to the JSON line when the command supplied none.
|
|
200
|
+
*
|
|
201
|
+
* `--get` stays meaningful: the path is resolved against each event, and
|
|
202
|
+
* a path that does not resolve emits `null` rather than aborting the
|
|
203
|
+
* stream mid-observation.
|
|
204
|
+
*/
|
|
205
|
+
writeEvent(data, opts = {}) {
|
|
206
|
+
const format = this.effectiveFormat();
|
|
207
|
+
if (format === FormatStyled || format === FormatMarkdown) {
|
|
208
|
+
this.writer.write(`${opts.line ?? JSON.stringify(data)}\n`);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
if (this.jqFilter) {
|
|
212
|
+
const value = resolvePath(data, this.jqFilter);
|
|
213
|
+
this.writer.write(`${JSON.stringify(value === undefined ? null : value)}\n`);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
this.writer.write(`${JSON.stringify(data)}\n`);
|
|
217
|
+
}
|
|
218
|
+
|
|
189
219
|
writeJSON(data, opts) {
|
|
190
220
|
const resp = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [] };
|
|
191
221
|
if (opts.notice) resp.notice = opts.notice;
|
|
@@ -385,7 +415,7 @@ export class OutputWriter {
|
|
|
385
415
|
let val = getDisplayValue(row[col]);
|
|
386
416
|
const width = colWidths[col] || 20;
|
|
387
417
|
|
|
388
|
-
if (j === 0 && instanceURL && table && row.sys_id) {
|
|
418
|
+
if (j === 0 && instanceURL && table && row.sys_id && isTTY(this.writer)) {
|
|
389
419
|
const url = getTableURL(instanceURL, table, row.sys_id);
|
|
390
420
|
val = hyperlink(val, url);
|
|
391
421
|
}
|
|
@@ -61,7 +61,7 @@ export default {
|
|
|
61
61
|
options: { singular: 'table', scopeValidation: true, showFields: ['name', 'label', 'super_class', 'create_access_controls', 'sys_scope', 'sys_created_on', 'sys_updated_on', 'sys_created_by', 'sys_updated_by', 'is_extendable'] } },
|
|
62
62
|
incidents: { table: 'incident', aliases: ['incident', 'inc'], columns: ['number', 'short_description', 'priority', 'state', 'assigned_to'], kind: 'ticket' },
|
|
63
63
|
changes: { table: 'change_request', aliases: ['change_request', 'chg'], columns: ['number', 'short_description', 'risk', 'state', 'assigned_to'], kind: 'ticket' },
|
|
64
|
-
requests: { table: 'sc_req_item', aliases: ['sc_req_item', 'req'], columns: ['number', 'short_description', 'stage', 'assigned_to'], kind: 'ticket' },
|
|
64
|
+
requests: { table: 'sc_req_item', aliases: ['sc_req_item', 'req'], columns: ['number', 'cat_item', 'short_description', 'stage', 'assigned_to'], kind: 'ticket' },
|
|
65
65
|
tasks: { table: 'sc_task', aliases: ['sc_task', 'task'], columns: ['number', 'short_description', 'state', 'assigned_to'], kind: 'ticket' },
|
|
66
66
|
uipolicies: { table: 'sys_ui_policy', aliases: ['uipolicy', 'up'], columns: ['short_description', 'table', 'sys_class_name', 'active'],
|
|
67
67
|
identifierField: 'short_description', options: { singular: 'UI policy', scopeValidation: true },
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// Record watching: bounded observation of one ServiceNow record over AMB.
|
|
2
|
+
//
|
|
3
|
+
// The AMB client (src/amb.js) owns the wire protocol. This module owns the
|
|
4
|
+
// observation session: what counts as an event, when to fetch the record to
|
|
5
|
+
// fill in detail the notification omitted, bounded duration, cancellation,
|
|
6
|
+
// reconnect backoff and — most importantly — honest gap reporting.
|
|
7
|
+
//
|
|
8
|
+
// A record-watcher subscription is best-effort delivery, not a durable
|
|
9
|
+
// stream. After a disconnect the platform does not replay what was missed,
|
|
10
|
+
// so this module reports a gap instead of pretending the event list is
|
|
11
|
+
// complete.
|
|
12
|
+
|
|
13
|
+
import { AppError, CodeUsage } from './errors.js';
|
|
14
|
+
import { normalizeRecordWatcherEvent, recordWatcherChannel } from './amb.js';
|
|
15
|
+
|
|
16
|
+
export const DEFAULT_RECONNECT_DELAYS = [1000, 2000, 4000, 8000, 16000, 30000];
|
|
17
|
+
|
|
18
|
+
function defaultSleep(ms, signal) {
|
|
19
|
+
return new Promise((resolve) => {
|
|
20
|
+
if (signal?.aborted) return resolve();
|
|
21
|
+
const timer = setTimeout(done, ms);
|
|
22
|
+
function done() {
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
signal?.removeEventListener('abort', done);
|
|
25
|
+
resolve();
|
|
26
|
+
}
|
|
27
|
+
if (signal) signal.addEventListener('abort', done, { once: true });
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Does the notification carry enough detail that a follow-up read is redundant? */
|
|
32
|
+
export function notificationHasDetail(event) {
|
|
33
|
+
return Boolean(event?.record) || (Array.isArray(event?.changes) && event.changes.length > 0);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Watch one record until a bound is reached, the caller cancels, or a fatal
|
|
38
|
+
* error occurs.
|
|
39
|
+
*
|
|
40
|
+
* @param {object} opts
|
|
41
|
+
* @param {{ start: Function, next: Function, stop: Function }} opts.client
|
|
42
|
+
* @param {string} opts.table
|
|
43
|
+
* @param {string} opts.sysID
|
|
44
|
+
* @param {string} [opts.query] — encoded query; defaults to `sys_id=<sysID>`
|
|
45
|
+
* @param {number} [opts.timeoutMs] — 0 means "until cancelled"
|
|
46
|
+
* @param {number} [opts.maxEvents] — 0 means unlimited
|
|
47
|
+
* @param {AbortSignal} [opts.signal]
|
|
48
|
+
* @param {'auto'|'always'|'never'} [opts.statePolicy]
|
|
49
|
+
* @param {() => Promise<object|null>} [opts.fetchState]
|
|
50
|
+
* @param {(event: object) => any} [opts.onEvent]
|
|
51
|
+
* @param {(status: object) => any} [opts.onStatus]
|
|
52
|
+
* @param {boolean} [opts.reconnect]
|
|
53
|
+
* @param {number[]} [opts.reconnectDelays]
|
|
54
|
+
* @param {() => number} [opts.now]
|
|
55
|
+
* @param {Function} [opts.sleep]
|
|
56
|
+
*/
|
|
57
|
+
export async function watchRecord({
|
|
58
|
+
client,
|
|
59
|
+
table,
|
|
60
|
+
sysID,
|
|
61
|
+
query,
|
|
62
|
+
timeoutMs = 0,
|
|
63
|
+
maxEvents = 0,
|
|
64
|
+
signal,
|
|
65
|
+
statePolicy = 'auto',
|
|
66
|
+
fetchState,
|
|
67
|
+
onEvent = () => {},
|
|
68
|
+
onStatus = () => {},
|
|
69
|
+
reconnect = true,
|
|
70
|
+
reconnectDelays = DEFAULT_RECONNECT_DELAYS,
|
|
71
|
+
now = () => Date.now(),
|
|
72
|
+
sleep = defaultSleep,
|
|
73
|
+
}) {
|
|
74
|
+
if (!client) throw new AppError(CodeUsage, 'Record watch needs an AMB client.');
|
|
75
|
+
if (!table) throw new AppError(CodeUsage, 'Record watch needs a table.');
|
|
76
|
+
if (!sysID) throw new AppError(CodeUsage, 'Record watch needs a record sys_id.');
|
|
77
|
+
if (!['auto', 'always', 'never'].includes(statePolicy)) {
|
|
78
|
+
throw new AppError(CodeUsage, `Unknown state policy: ${statePolicy}`);
|
|
79
|
+
}
|
|
80
|
+
if (timeoutMs < 0 || maxEvents < 0) throw new AppError(CodeUsage, 'Watch bounds cannot be negative.');
|
|
81
|
+
if (statePolicy !== 'never' && typeof fetchState !== 'function') {
|
|
82
|
+
throw new AppError(CodeUsage, 'State fetching is enabled but no record reader was supplied.');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const channel = recordWatcherChannel(table, query || `sys_id=${sysID}`);
|
|
86
|
+
const startedAt = now();
|
|
87
|
+
const startedISO = new Date(startedAt).toISOString();
|
|
88
|
+
const deadline = timeoutMs > 0 ? startedAt + timeoutMs : Infinity;
|
|
89
|
+
|
|
90
|
+
let events = 0;
|
|
91
|
+
let gaps = 0;
|
|
92
|
+
let attempts = 0;
|
|
93
|
+
let lastEventAt = null;
|
|
94
|
+
let connected = false;
|
|
95
|
+
let reason = 'timeout';
|
|
96
|
+
|
|
97
|
+
const finish = async (why) => {
|
|
98
|
+
reason = why;
|
|
99
|
+
try { await client.stop([channel]); } catch { /* unsubscription is best effort */ }
|
|
100
|
+
onStatus({ type: 'unsubscribed', reason: why });
|
|
101
|
+
const endedAt = now();
|
|
102
|
+
return {
|
|
103
|
+
type: 'watch_summary',
|
|
104
|
+
table,
|
|
105
|
+
sys_id: sysID,
|
|
106
|
+
channel,
|
|
107
|
+
reason: why,
|
|
108
|
+
events,
|
|
109
|
+
gaps,
|
|
110
|
+
reconnects: Math.max(0, gaps),
|
|
111
|
+
complete: gaps === 0 && reason !== 'error',
|
|
112
|
+
started_at: startedISO,
|
|
113
|
+
ended_at: new Date(endedAt).toISOString(),
|
|
114
|
+
duration_ms: Math.max(0, endedAt - startedAt),
|
|
115
|
+
last_event_at: lastEventAt,
|
|
116
|
+
};
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
onStatus({ type: 'connecting', table, sys_id: sysID, channel });
|
|
120
|
+
|
|
121
|
+
try {
|
|
122
|
+
while (true) {
|
|
123
|
+
const remaining = deadline - now();
|
|
124
|
+
if (remaining <= 0) return await finish('timeout');
|
|
125
|
+
if (signal?.aborted) return await finish('cancelled');
|
|
126
|
+
|
|
127
|
+
if (!connected) {
|
|
128
|
+
const session = await client.start([channel]);
|
|
129
|
+
connected = true;
|
|
130
|
+
attempts = 0;
|
|
131
|
+
const resumed = gaps > 0;
|
|
132
|
+
onStatus({
|
|
133
|
+
type: resumed ? 'reconnected' : 'subscribed',
|
|
134
|
+
channel,
|
|
135
|
+
...(session?.sessionStatus ? { session_status: session.sessionStatus } : {}),
|
|
136
|
+
// State the limitation, do not imply the stream was continuous.
|
|
137
|
+
...(resumed ? { may_have_missed_events: true, gaps } : {}),
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
let messages;
|
|
142
|
+
try {
|
|
143
|
+
messages = await client.next({ timeoutMs: Math.min(remaining, 60000), signal });
|
|
144
|
+
} catch (error) {
|
|
145
|
+
if (signal?.aborted) return await finish('cancelled');
|
|
146
|
+
if (deadline - now() <= 0) return await finish('timeout');
|
|
147
|
+
if (error?.fatal === true || !reconnect) throw error;
|
|
148
|
+
|
|
149
|
+
// A dropped connection is a real gap in observation, not a retry note.
|
|
150
|
+
gaps += 1;
|
|
151
|
+
const gapStart = lastEventAt || startedISO;
|
|
152
|
+
const gapAt = new Date(now()).toISOString();
|
|
153
|
+
onStatus({
|
|
154
|
+
type: 'gap',
|
|
155
|
+
at: gapAt,
|
|
156
|
+
since: gapStart,
|
|
157
|
+
reason: error?.message || String(error),
|
|
158
|
+
code: error?.code || null,
|
|
159
|
+
});
|
|
160
|
+
connected = false;
|
|
161
|
+
const wait = reconnectDelays[Math.min(attempts, reconnectDelays.length - 1)];
|
|
162
|
+
attempts += 1;
|
|
163
|
+
const waitedUntil = now() + wait;
|
|
164
|
+
while (now() < waitedUntil && !signal?.aborted && now() < deadline) {
|
|
165
|
+
await sleep(Math.min(wait, Math.max(1, waitedUntil - now())), signal);
|
|
166
|
+
}
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
for (const message of messages) {
|
|
171
|
+
if (signal?.aborted) return await finish('cancelled');
|
|
172
|
+
const event = normalizeRecordWatcherEvent(message, { table, sysID }, new Date(now()).toISOString());
|
|
173
|
+
// The channel query scopes delivery to this record. The live payload
|
|
174
|
+
// does not carry a sys_id (jsn fills it from the subscription), so this
|
|
175
|
+
// guard only bites on an instance that does send one — for example a
|
|
176
|
+
// table-level channel returning a different record.
|
|
177
|
+
if (event.sys_id && sysID && event.sys_id !== sysID) continue;
|
|
178
|
+
|
|
179
|
+
const shouldFetch = statePolicy === 'always'
|
|
180
|
+
|| (statePolicy === 'auto' && !notificationHasDetail(event));
|
|
181
|
+
if (shouldFetch) {
|
|
182
|
+
try {
|
|
183
|
+
const record = await fetchState();
|
|
184
|
+
event.state = { source: 'fetched', fetched_at: new Date(now()).toISOString(), record };
|
|
185
|
+
} catch (error) {
|
|
186
|
+
// Never let a failed follow-up read masquerade as a failed or
|
|
187
|
+
// complete event; keep the notification and record the problem.
|
|
188
|
+
event.state = null;
|
|
189
|
+
event.state_error = {
|
|
190
|
+
code: error?.code || null,
|
|
191
|
+
message: error?.message || String(error),
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
events += 1;
|
|
197
|
+
lastEventAt = event.received_at;
|
|
198
|
+
await onEvent(event);
|
|
199
|
+
if (maxEvents > 0 && events >= maxEvents) return await finish('max_events');
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
} catch (error) {
|
|
203
|
+
await finish('error');
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
}
|
package/src/sdk.js
CHANGED
|
@@ -2,10 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
import { batchRead } from './sdk-batch.js';
|
|
4
4
|
import { gunzipSync } from 'node:zlib';
|
|
5
|
-
import { AppError, CodeAPI, CodeAuth, errAuth, errAPI, errNetwork, errUsage } from './errors.js';
|
|
5
|
+
import { AppError, CodeAPI, CodeAuth, errAuth, errAuthHint, errAPI, errNetwork, errUsage } from './errors.js';
|
|
6
6
|
import { getStringField } from './helpers.js';
|
|
7
7
|
import { getAction, getStepTypes, createAction, updateAction, testAction } from './processflow-actions.js';
|
|
8
8
|
import { readSkippedBaseline, revertSkippedUpdate } from './skipped-update-provider.js';
|
|
9
|
+
import {
|
|
10
|
+
MAX_SESSION_REPLAYS, canReplayAfterRecovery, classifyAuthRejection, safeRequestLabel, sniffLoginBody,
|
|
11
|
+
} from './session-recovery.js';
|
|
12
|
+
import {
|
|
13
|
+
previewUpdateSet as previewRetrievedUpdateSet,
|
|
14
|
+
commitUpdateSet as commitRetrievedUpdateSet,
|
|
15
|
+
listPreviewProblems,
|
|
16
|
+
} from './update-set-apply.js';
|
|
9
17
|
|
|
10
18
|
const DEFAULT_TIMEOUT = 30000;
|
|
11
19
|
|
|
@@ -52,9 +60,17 @@ export class SDKClient {
|
|
|
52
60
|
this.onMutation = opts.onMutation;
|
|
53
61
|
this.timeout = opts.timeout || DEFAULT_TIMEOUT;
|
|
54
62
|
this.domain = opts.domain || '';
|
|
63
|
+
// Expected identity, used only to reject a recovery that lands on a
|
|
64
|
+
// different account. Never serialized.
|
|
65
|
+
this.username = opts.username || '';
|
|
55
66
|
this.oauthCookies = null;
|
|
56
67
|
this._sessionPromise = null;
|
|
57
68
|
this.sessionUserToken = '';
|
|
69
|
+
// Session state is versioned so concurrent requests can tell "my headers
|
|
70
|
+
// are from the session that was just replaced" apart from "this rejection
|
|
71
|
+
// is new". One recovery is in flight per client at a time.
|
|
72
|
+
this._sessionGeneration = 0;
|
|
73
|
+
this._recoveryPromise = null;
|
|
58
74
|
}
|
|
59
75
|
|
|
60
76
|
async _setAuth(req, { skipOAuthSession = false } = {}) {
|
|
@@ -148,8 +164,12 @@ export class SDKClient {
|
|
|
148
164
|
|
|
149
165
|
async _performAuthenticatedRequest(endpoint, opts, {
|
|
150
166
|
timeout = this.timeout, prepare, skipOAuthSession = false, normalizeErrors = false,
|
|
167
|
+
allowMutationReplay = false,
|
|
151
168
|
}, consume = (response) => response) {
|
|
152
|
-
|
|
169
|
+
const method = String(opts.method || 'GET').toUpperCase();
|
|
170
|
+
for (let attempt = 0; attempt <= MAX_SESSION_REPLAYS; attempt++) {
|
|
171
|
+
// Headers for this attempt belong to the session as it is right now.
|
|
172
|
+
const generation = this._sessionGeneration;
|
|
153
173
|
const controller = new AbortController();
|
|
154
174
|
const timer = setTimeout(() => controller.abort(), timeout);
|
|
155
175
|
let rejection;
|
|
@@ -158,14 +178,15 @@ export class SDKClient {
|
|
|
158
178
|
if (prepare) prepare(req);
|
|
159
179
|
await this._setAuth(req, { skipOAuthSession });
|
|
160
180
|
const response = await fetch(req);
|
|
161
|
-
if (!skipOAuthSession &&
|
|
162
|
-
//
|
|
163
|
-
//
|
|
164
|
-
rejection =
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
return await consume(response);
|
|
181
|
+
if (!skipOAuthSession && this.recovery) {
|
|
182
|
+
// A 401 is definitive; only then is the body sniffed for a login
|
|
183
|
+
// page. Provider bodies are cancelled, never echoed.
|
|
184
|
+
rejection = classifyAuthRejection(response, {
|
|
185
|
+
bodyText: response.status === 401 ? '' : await sniffLoginBody(response),
|
|
186
|
+
});
|
|
168
187
|
}
|
|
188
|
+
if (!rejection) return await consume(response);
|
|
189
|
+
await response.body?.cancel?.();
|
|
169
190
|
} catch (err) {
|
|
170
191
|
if (normalizeErrors) {
|
|
171
192
|
if (err.name === 'AbortError') throw errNetwork(new Error('Request timed out'));
|
|
@@ -177,17 +198,117 @@ export class SDKClient {
|
|
|
177
198
|
} finally {
|
|
178
199
|
clearTimeout(timer);
|
|
179
200
|
}
|
|
201
|
+
if (attempt >= MAX_SESSION_REPLAYS) throw this._authFailure(rejection);
|
|
202
|
+
// A write or stateful processor is only replayed when the rejection
|
|
203
|
+
// provably happened before execution.
|
|
204
|
+
if (!canReplayAfterRecovery(rejection, { method, allowMutationReplay })) {
|
|
205
|
+
throw this._unsafeReplayError(rejection, endpoint, method);
|
|
206
|
+
}
|
|
180
207
|
// Browser renewal has its own existing hard timeout. Never leave a
|
|
181
208
|
// request timeout running while waiting for the human to authenticate.
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
209
|
+
await this._recoverSession(rejection, generation);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
_authFailure(rejection) {
|
|
214
|
+
// The provider's error carries the actionable profile-specific guidance.
|
|
215
|
+
return this.recovery?.error || errAuth(`Authentication rejected${rejection?.status ? ` (HTTP ${rejection.status})` : ''}.`);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// Replace the cached session as one unit: cookies, user token and the
|
|
219
|
+
// in-flight warm-up promise cannot be mixed with a newly established one.
|
|
220
|
+
_invalidateSession() {
|
|
221
|
+
this.oauthCookies = null;
|
|
222
|
+
this.sessionUserToken = '';
|
|
223
|
+
this._sessionPromise = null;
|
|
224
|
+
this._sessionGeneration += 1;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Recover at most once for a rejection observed at `generation`.
|
|
229
|
+
* Concurrent callers share the same attempt; a caller whose session was
|
|
230
|
+
* already rotated by another request just replays with the new headers.
|
|
231
|
+
*/
|
|
232
|
+
async _recoverSession(rejection, generation) {
|
|
233
|
+
if (generation !== this._sessionGeneration) return true;
|
|
234
|
+
if (!this._recoveryPromise) {
|
|
235
|
+
this._recoveryPromise = (async () => {
|
|
236
|
+
const recovered = await this.recovery.recover(rejection);
|
|
237
|
+
if (!recovered) throw this._authFailure(rejection);
|
|
238
|
+
this._invalidateSession();
|
|
239
|
+
await this._verifyRecoveredSession();
|
|
240
|
+
})().finally(() => { this._recoveryPromise = null; });
|
|
241
|
+
}
|
|
242
|
+
await this._recoveryPromise;
|
|
243
|
+
return true;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Prove the fresh credentials actually work over the session path the failed
|
|
248
|
+
* operation needs — a cookie/CSRF session, not just a bearer probe — and
|
|
249
|
+
* that they still belong to the selected identity.
|
|
250
|
+
*/
|
|
251
|
+
async _verifyRecoveredSession() {
|
|
252
|
+
const params = new URLSearchParams({
|
|
253
|
+
sysparm_query: 'user_name=javascript:gs.getUserName()',
|
|
254
|
+
sysparm_fields: 'user_name', sysparm_limit: '1', sysparm_display_value: 'false',
|
|
255
|
+
});
|
|
256
|
+
const controller = new AbortController();
|
|
257
|
+
const timer = setTimeout(() => controller.abort(), this.timeout);
|
|
258
|
+
try {
|
|
259
|
+
const req = new Request(`${this.baseURL}/api/now/table/sys_user?${params}`, {
|
|
260
|
+
method: 'GET', headers: { Accept: 'application/json' }, redirect: 'manual', signal: controller.signal,
|
|
261
|
+
});
|
|
262
|
+
await this._setAuth(req);
|
|
263
|
+
const response = await fetch(req);
|
|
264
|
+
if (!response.ok) throw this._recoveryFailure('the re-established session was rejected');
|
|
265
|
+
const payload = await response.json().catch(() => null);
|
|
266
|
+
const record = Array.isArray(payload?.result) ? payload.result[0] : null;
|
|
267
|
+
const field = record?.user_name;
|
|
268
|
+
const verified = field && typeof field === 'object' ? (field.value ?? field.display_value) : field;
|
|
269
|
+
if (!verified) throw this._recoveryFailure('the re-established session did not identify a user');
|
|
270
|
+
if (this.username && String(verified) !== String(this.username)) {
|
|
271
|
+
// Identity is not leaked; the selected profile is the only useful fact.
|
|
272
|
+
throw this._recoveryFailure('the re-established session belongs to a different account');
|
|
186
273
|
}
|
|
187
|
-
|
|
274
|
+
return verified;
|
|
275
|
+
} catch (error) {
|
|
276
|
+
if (error?.code) throw error;
|
|
277
|
+
if (error?.name === 'AbortError') throw this._recoveryFailure('the session verification timed out');
|
|
278
|
+
throw this._recoveryFailure('the re-established session could not be verified');
|
|
279
|
+
} finally {
|
|
280
|
+
clearTimeout(timer);
|
|
188
281
|
}
|
|
189
282
|
}
|
|
190
283
|
|
|
284
|
+
_recoveryFailure(reason) {
|
|
285
|
+
const error = errAuth(`Session recovery failed: ${reason}.`);
|
|
286
|
+
const base = this.recovery?.error;
|
|
287
|
+
if (base) {
|
|
288
|
+
error.profile = base.profile ?? null;
|
|
289
|
+
if (base.recovery) error.recovery = base.recovery;
|
|
290
|
+
if (base.hint) error.hint = base.hint;
|
|
291
|
+
}
|
|
292
|
+
return error;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
_unsafeReplayError(rejection, endpoint, method) {
|
|
296
|
+
const where = `${method} ${safeRequestLabel(endpoint)}`;
|
|
297
|
+
const error = errAuth(
|
|
298
|
+
`The session for this request expired (${rejection.kind === 'http_401' ? 'HTTP 401' : 'login page returned'}), `
|
|
299
|
+
+ `but JSN cannot prove the ${where} request never executed, so it was not replayed.`,
|
|
300
|
+
);
|
|
301
|
+
const base = this.recovery?.error;
|
|
302
|
+
if (base) {
|
|
303
|
+
error.profile = base.profile ?? null;
|
|
304
|
+
if (base.recovery) error.recovery = base.recovery;
|
|
305
|
+
error.hint = `Confirm the operation did not run, then sign in and re-run it${base.recovery ? `: ${base.recovery}` : '.'}`;
|
|
306
|
+
} else {
|
|
307
|
+
error.hint = 'Confirm the operation did not run, then sign in and re-run it.';
|
|
308
|
+
}
|
|
309
|
+
return error;
|
|
310
|
+
}
|
|
311
|
+
|
|
191
312
|
async request(endpoint, opts = {}) {
|
|
192
313
|
const { timeout = this.timeout, readOnly = false, touchLastSeen, domain = this.domain, ...requestOptions } = opts;
|
|
193
314
|
if (readOnly && (requestOptions.method || 'GET').toUpperCase() !== 'GET') throw new Error('Read-only SDK requests require GET');
|
|
@@ -834,6 +955,32 @@ export class SDKClient {
|
|
|
834
955
|
}
|
|
835
956
|
}
|
|
836
957
|
|
|
958
|
+
/**
|
|
959
|
+
* Preview a loaded retrieved update set through the CICD Update Set API and
|
|
960
|
+
* wait for its progress tracker. Does not commit and does not resolve
|
|
961
|
+
* preview problems.
|
|
962
|
+
* @param {string} sysID - sys_remote_update_set sys_id
|
|
963
|
+
* @param {{timeoutMs?: number, pollMs?: number}} [opts]
|
|
964
|
+
*/
|
|
965
|
+
async previewUpdateSet(sysID, opts = {}) {
|
|
966
|
+
return previewRetrievedUpdateSet(this, sysID, opts);
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
/**
|
|
970
|
+
* Commit a previewed retrieved update set through the CICD Update Set API and
|
|
971
|
+
* wait for its progress tracker.
|
|
972
|
+
* @param {string} sysID - sys_remote_update_set sys_id
|
|
973
|
+
* @param {{timeoutMs?: number, pollMs?: number}} [opts]
|
|
974
|
+
*/
|
|
975
|
+
async commitUpdateSet(sysID, opts = {}) {
|
|
976
|
+
return commitRetrievedUpdateSet(this, sysID, opts);
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
/** Read sys_update_preview_problem rows for a retrieved update set. */
|
|
980
|
+
async listUpdateSetPreviewProblems(sysID, opts = {}) {
|
|
981
|
+
return listPreviewProblems(this, sysID, opts);
|
|
982
|
+
}
|
|
983
|
+
|
|
837
984
|
/**
|
|
838
985
|
* Execute a background script on the ServiceNow instance via sys.scripts.do.
|
|
839
986
|
* Uses a 3-step session-establishment flow compatible with OAuth tokens:
|
|
@@ -974,6 +1121,40 @@ export class SDKClient {
|
|
|
974
1121
|
return variables;
|
|
975
1122
|
}
|
|
976
1123
|
|
|
1124
|
+
/**
|
|
1125
|
+
* Session material for channels that authorize like a browser (AMB).
|
|
1126
|
+
*
|
|
1127
|
+
* AMB does not accept bearer/basic headers on subscribe; it needs the
|
|
1128
|
+
* cookies and X-UserToken of a UI session. gck credentials already carry
|
|
1129
|
+
* them; basic/oauth profiles obtain them by warming the same session the
|
|
1130
|
+
* SDK uses for UI calls. A bearer-token profile that cannot warm a session
|
|
1131
|
+
* is an actionable error, never a silent fallback.
|
|
1132
|
+
*/
|
|
1133
|
+
async ambSession() {
|
|
1134
|
+
if (!this.authProvider) throw errAuth('No authentication configured');
|
|
1135
|
+
const creds = await this.authProvider.getCredentials();
|
|
1136
|
+
if (!creds) throw errAuth('No valid credentials');
|
|
1137
|
+
if (creds.auth_method === 'gck') {
|
|
1138
|
+
if (!creds.cookies) {
|
|
1139
|
+
throw errAuthHint('This gck credential has no session cookies, so AMB cannot open a channel.',
|
|
1140
|
+
'Re-import the browser session: jsn auth login --browser');
|
|
1141
|
+
}
|
|
1142
|
+
return { cookies: creds.cookies, userToken: creds.access_token || '', authMethod: 'gck' };
|
|
1143
|
+
}
|
|
1144
|
+
if (creds.auth_method === 'basic' || creds.auth_method === 'token' || creds.auth_method === 'oauth') {
|
|
1145
|
+
const cookies = await this._warmSession();
|
|
1146
|
+
if (!cookies) {
|
|
1147
|
+
throw errAuthHint(
|
|
1148
|
+
`${creds.auth_method} credentials could not open a UI session, which AMB requires.`,
|
|
1149
|
+
'Record watching needs a browser session. Run "jsn auth login --browser" and use that profile, or ask an administrator whether AMB is enabled for this account.',
|
|
1150
|
+
);
|
|
1151
|
+
}
|
|
1152
|
+
return { cookies, userToken: this.sessionUserToken || '', authMethod: creds.auth_method };
|
|
1153
|
+
}
|
|
1154
|
+
throw errAuthHint(`Authentication method "${creds.auth_method}" cannot open an AMB session.`,
|
|
1155
|
+
'Use a browser-session (gck) profile: jsn auth login --browser');
|
|
1156
|
+
}
|
|
1157
|
+
|
|
977
1158
|
async _warmSession() {
|
|
978
1159
|
if (this.oauthCookies) return this.oauthCookies;
|
|
979
1160
|
if (!this._sessionPromise) {
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// Bounded authentication-session recovery: classify the response that ended a
|
|
2
|
+
// request, decide whether replaying it is safe, and read just enough of a
|
|
3
|
+
// browser-login page to recognise it. Nothing here logs or exposes a body.
|
|
4
|
+
//
|
|
5
|
+
// Retry contract (see docs/AUTH_LIFECYCLE.md, "Runtime authentication recovery"):
|
|
6
|
+
// * HTTP 401 is a definitive pre-execution rejection for any method — the
|
|
7
|
+
// provider refused the credentials before dispatching the operation.
|
|
8
|
+
// * A login redirect or a login page proves the same thing for reads, but it
|
|
9
|
+
// is a *heuristic* for a write or a stateful processor: JSN does not replay
|
|
10
|
+
// those unless the caller explicitly accepts the risk.
|
|
11
|
+
// * Everything else (403, 5xx, network, abort) is never recoverable here.
|
|
12
|
+
|
|
13
|
+
export const MAX_SESSION_REPLAYS = 1;
|
|
14
|
+
export const LOGIN_BODY_LIMIT = 64 * 1024;
|
|
15
|
+
|
|
16
|
+
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
17
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
18
|
+
const LOGIN_PATH = /(?:^|\/)login(?:\.do)?(?:\/|$)/i;
|
|
19
|
+
|
|
20
|
+
export function isSafeMethod(method) {
|
|
21
|
+
return SAFE_METHODS.has(String(method || 'GET').toUpperCase());
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** True when a URL (absolute or relative) points at the platform login page. */
|
|
25
|
+
export function isLoginURL(value) {
|
|
26
|
+
if (!value) return false;
|
|
27
|
+
try {
|
|
28
|
+
const url = new URL(String(value), 'https://instance.invalid/');
|
|
29
|
+
return LOGIN_PATH.test(url.pathname);
|
|
30
|
+
} catch {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A browser login form, not just any HTML page. Both the user field and either
|
|
37
|
+
* the password field or the login form action must be present, so an ordinary
|
|
38
|
+
* authenticated page that mentions `user_name` is not mistaken for a login.
|
|
39
|
+
*/
|
|
40
|
+
export function isLoginPage(contentType, bodyText) {
|
|
41
|
+
if (!/text\/html/i.test(String(contentType || ''))) return false;
|
|
42
|
+
const head = String(bodyText || '').slice(0, LOGIN_BODY_LIMIT);
|
|
43
|
+
if (!head) return false;
|
|
44
|
+
const hasUserField = /(?:name|id)=["']user_name["']/i.test(head);
|
|
45
|
+
const hasPasswordField = /(?:name|id)=["']user_password["']/i.test(head);
|
|
46
|
+
if (hasUserField && hasPasswordField) return true;
|
|
47
|
+
return /action=["'][^"']*login\.do/i.test(head);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Classify a completed response as an authentication rejection.
|
|
52
|
+
* Returns null for every ordinary response, including 403 and 5xx.
|
|
53
|
+
*/
|
|
54
|
+
export function classifyAuthRejection(response, { bodyText = '' } = {}) {
|
|
55
|
+
if (!response) return null;
|
|
56
|
+
if (response.status === 401) return { kind: 'http_401', status: 401 };
|
|
57
|
+
if (REDIRECT_STATUSES.has(response.status) && isLoginURL(response.headers?.get?.('location'))) {
|
|
58
|
+
return { kind: 'login_redirect', status: response.status };
|
|
59
|
+
}
|
|
60
|
+
if (response.redirected && isLoginURL(response.url)) {
|
|
61
|
+
return { kind: 'login_redirect', status: response.status };
|
|
62
|
+
}
|
|
63
|
+
if (response.ok && isLoginPage(response.headers?.get?.('content-type'), bodyText)) {
|
|
64
|
+
return { kind: 'login_page', status: response.status };
|
|
65
|
+
}
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Only 401 is a protocol-level guarantee that nothing ran. Login redirects and
|
|
71
|
+
* login pages are strong evidence for reads; a write is replayed only when the
|
|
72
|
+
* caller opted in explicitly (none of JSN's own write paths do).
|
|
73
|
+
*/
|
|
74
|
+
export function canReplayAfterRecovery(rejection, { method = 'GET', allowMutationReplay = false } = {}) {
|
|
75
|
+
if (!rejection) return false;
|
|
76
|
+
if (rejection.kind === 'http_401') return true;
|
|
77
|
+
return isSafeMethod(method) || allowMutationReplay === true;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Read a bounded prefix of an HTML response so a login page can be recognised
|
|
82
|
+
* without consuming the body the caller needs. Non-HTML responses cost nothing.
|
|
83
|
+
*/
|
|
84
|
+
export async function sniffLoginBody(response, limit = LOGIN_BODY_LIMIT) {
|
|
85
|
+
const contentType = response?.headers?.get?.('content-type') || '';
|
|
86
|
+
if (!/text\/html/i.test(contentType) || typeof response.clone !== 'function') return '';
|
|
87
|
+
const declared = Number(response.headers?.get?.('content-length'));
|
|
88
|
+
if (Number.isFinite(declared) && declared > limit) return '';
|
|
89
|
+
let clone;
|
|
90
|
+
try { clone = response.clone(); } catch { return ''; }
|
|
91
|
+
try {
|
|
92
|
+
const reader = clone.body?.getReader?.();
|
|
93
|
+
if (reader) {
|
|
94
|
+
const chunks = [];
|
|
95
|
+
let received = 0;
|
|
96
|
+
while (received < limit) {
|
|
97
|
+
const { done, value } = await reader.read();
|
|
98
|
+
if (done) break;
|
|
99
|
+
const chunk = Buffer.from(value);
|
|
100
|
+
chunks.push(chunk);
|
|
101
|
+
received += chunk.length;
|
|
102
|
+
}
|
|
103
|
+
await reader.cancel().catch(() => {});
|
|
104
|
+
return Buffer.concat(chunks).subarray(0, limit).toString('utf8');
|
|
105
|
+
}
|
|
106
|
+
const text = await clone.text();
|
|
107
|
+
return String(text || '').slice(0, limit);
|
|
108
|
+
} catch {
|
|
109
|
+
return '';
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Pathname only — query strings can carry tokens and are never echoed. */
|
|
114
|
+
export function safeRequestLabel(endpoint) {
|
|
115
|
+
try {
|
|
116
|
+
return new URL(String(endpoint), 'https://instance.invalid/').pathname || '/';
|
|
117
|
+
} catch {
|
|
118
|
+
return 'the requested endpoint';
|
|
119
|
+
}
|
|
120
|
+
}
|