@jacebenson/jsn 5.3.0-dev.135.1 → 5.3.0-dev.137.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.3.0-dev.135.1",
3
+ "version": "5.3.0-dev.137.1",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/app.js CHANGED
@@ -59,6 +59,7 @@ export class App {
59
59
  username: session?.username, authMethod: session?.profile?.auth_method,
60
60
  }), {
61
61
  domain: session?.domain || '',
62
+ username: session?.username || '',
62
63
  recovery: createAuthRecovery({ app: this, session }),
63
64
  onMutation: event => this.recordMutation(instance, session?.profileName, event),
64
65
  });
@@ -69,6 +70,7 @@ export class App {
69
70
  const profile = options.profile || {};
70
71
  return new SDKClient(instance, this.auth.createProfileProvider(instance, options), {
71
72
  domain: options.domain ?? profile.domain ?? '',
73
+ username: options.username || '',
72
74
  onMutation: event => this.recordMutation(instance, options.profileName || null, event),
73
75
  });
74
76
  }
@@ -14,20 +14,34 @@ export function createAuthRecovery({ app, session, argv = () => app._authArgv ||
14
14
  const { instance, profileName, username, profile } = session;
15
15
  const target = profileName ? `--profile ${quoteShellArg(profileName)}` : quoteShellArg(instance);
16
16
  const label = profileName ? `profile ${quoteShellArg(profileName)}` : 'the active profile';
17
- function failure(method = profile?.auth_method) {
17
+ // A 401 is definitive. A login page/redirect is a session rejection too, but
18
+ // only the SDK may decide whether the rejected operation is safe to replay.
19
+ const rejectedKinds = new Set(['http_401', 'login_redirect', 'login_page']);
20
+ function failure(method = profile?.auth_method, kind = 'http_401') {
18
21
  const error = errAPI(401, '');
19
22
  const login = `jsn auth login ${target}`;
20
- error.message = `Authentication rejected for ${label} (HTTP 401).`;
23
+ const expired = kind !== 'http_401';
24
+ error.message = method === 'gck'
25
+ ? `The saved browser session for ${label} was rejected${expired ? ' (a login page was returned)' : ' (HTTP 401)'} and cannot be renewed by JSN. Recapture it to continue.`
26
+ : expired
27
+ ? `The saved session for ${label} expired (a login page was returned instead of the response).`
28
+ : `Authentication rejected for ${label} (HTTP 401).`;
21
29
  error.profile = profileName || null;
22
30
  error.recovery = method === 'basic'
23
31
  ? `jsn auth login --basic ${quoteShellArg(instance)}${profileName ? ` --profile ${quoteShellArg(profileName)}` : ''}`
24
32
  : method === 'gck' ? `jsn auth refresh ${target} --browser`
25
33
  : method === 'oauth' ? `jsn auth refresh ${target}` : login;
26
- error.hint = method === 'basic'
27
- ? `Set SN_USERNAME/SN_PASSWORD to the correct credentials, then run: ${error.recovery}`
28
- : method === 'oauth'
29
- ? `Run interactively: ${error.recovery}. If refresh fails, run: ${login}`
30
- : `Run: ${error.recovery}`;
34
+ if (method === 'gck') {
35
+ // Captured browser cookies are not renewable; only a new capture helps.
36
+ error.recapture_required = true;
37
+ error.hint = `Recapture the browser session, then re-run: ${error.recovery}`;
38
+ } else if (method === 'basic') {
39
+ error.hint = `Set SN_USERNAME/SN_PASSWORD to the correct credentials, then run: ${error.recovery}`;
40
+ } else if (method === 'oauth') {
41
+ error.hint = `Run interactively: ${error.recovery}. If refresh fails, run: ${login}`;
42
+ } else {
43
+ error.hint = `Run: ${error.recovery}`;
44
+ }
31
45
  return error;
32
46
  }
33
47
  // Keep the settled promise too: this provider gets only one recovery attempt.
@@ -43,12 +57,13 @@ export function createAuthRecovery({ app, session, argv = () => app._authArgv ||
43
57
  error.hint = `Run: ${error.recovery}`;
44
58
  return error;
45
59
  },
46
- async recover({ status }) {
47
- if (status !== 401) return false;
48
- return recoveryAttempt ??= recoverOnce();
60
+ async recover({ status, kind } = {}) {
61
+ const reason = kind ?? (status === 401 ? 'http_401' : null);
62
+ if (!rejectedKinds.has(reason)) return false;
63
+ return recoveryAttempt ??= recoverOnce(reason);
49
64
  },
50
65
  };
51
- async function recoverOnce() {
66
+ async function recoverOnce(kind) {
52
67
  let creds;
53
68
  try {
54
69
  creds = await app.auth.getCredentialsFor(instance, username, {
@@ -56,7 +71,7 @@ export function createAuthRecovery({ app, session, argv = () => app._authArgv ||
56
71
  });
57
72
  } catch { throw provider.error; }
58
73
  const method = profile?.auth_method || creds.auth_method;
59
- provider.error = failure(method);
74
+ provider.error = failure(method, kind);
60
75
  if (method === 'oauth' && creds.refresh_token) {
61
76
  try {
62
77
  await app.auth.refreshToken(instance, creds, username ?? null);
@@ -6,6 +6,7 @@ import { inspectFlow } from '../flow-inspection.js';
6
6
  import { publishFlows, publishFlowLifecycle, publishDoctor, flowStatus } from '../flow-publish.js';
7
7
  import { resolveRecord, unwrapSysId } from '../resolve-record.js';
8
8
  import { createFlowFromManifest, updateFlowFromManifest, readCurrentUpdateSet } from '../flow-create.js';
9
+ import { alignUpdateSetCapture } from '../context.js';
9
10
  import { EXCLUDED_TRIGGER_TYPES, SUPPORTED_TRIGGER_TYPES, readTriggerCatalog, readTriggerInputDefinitions } from '../flow-triggers.js';
10
11
  import { testFlow } from '../flow-test.js';
11
12
  import { errUsage } from '../errors.js';
@@ -331,6 +332,7 @@ export function flowsCmd(wrap) {
331
332
  }
332
333
  const result = await createFlowFromManifest(app.sdk, app.getEffectiveInstance(), manifest, {
333
334
  readUpdateSet: () => readCurrentUpdateSet(app.sdk),
335
+ ensureCapture: intended => alignUpdateSetCapture(app.sdk, intended),
334
336
  });
335
337
  app.ok({ ...result, trigger_guidance: triggerGuidance(result.trigger) }, {
336
338
  summary: `Created draft flow "${result.flow.name}" (${result.flow.id}) with trigger ${result.trigger?.type ?? 'unknown'} (${result.trigger?.id ?? 'no trigger id'}) without activation`,
@@ -368,6 +370,7 @@ export function flowsCmd(wrap) {
368
370
  const result = await updateFlowFromManifest(app.sdk, app.getEffectiveInstance(), argv.identifier, manifest, {
369
371
  preview: argv.preview,
370
372
  readUpdateSet: () => readCurrentUpdateSet(app.sdk),
373
+ ensureCapture: intended => alignUpdateSetCapture(app.sdk, intended),
371
374
  });
372
375
  const diff = result.changes.map(change => `${change.component}${change.order ? ` ${change.order}` : ''}.${change.input}: ${JSON.stringify(change.before)} -> ${JSON.stringify(change.after)}`).join('\n');
373
376
  const state = `${result.flow.status}${result.flow.active ? ', active' : ''}`;
package/src/context.js CHANGED
@@ -98,3 +98,86 @@ export async function setCurrentApplication(sdk, _userSysID, scopeSysID) {
98
98
  export async function setCurrentUpdateSet(sdk, _userSysID, updateSetSysID) {
99
99
  await selectContext(sdk, 'updateset', { sysId: updateSetSysID }, updateSetSysID);
100
100
  }
101
+
102
+ /**
103
+ * Read the update set this authenticated session will actually capture into.
104
+ *
105
+ * `sys_user_preference:user=<user>^name=sys_update_set` is the persisted
106
+ * choice; this endpoint reports the session's effective picker selection. They
107
+ * are different sources and can disagree in a freshly-warmed session, so the
108
+ * preference alone must not be treated as the provider's capture context.
109
+ */
110
+ export async function readEffectiveUpdateSet(sdk) {
111
+ const endpoint = `${sdk.baseURL}/api/now/ui/concoursepicker/updateset`;
112
+ const response = await sdk.request(endpoint, { method: 'GET', readOnly: true });
113
+ const current = response?.result?.current;
114
+ if (!current || typeof current !== 'object') {
115
+ throw new Error('Invalid update-set picker response: expected result.current.');
116
+ }
117
+ const sysId = typeof current.sysId === 'string' ? current.sysId : '';
118
+ return {
119
+ sys_id: sysId,
120
+ name: typeof current.name === 'string' ? current.name : '',
121
+ label: current.displayValue || current.name || sysId,
122
+ };
123
+ }
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
+ */
140
+ export async function alignUpdateSetCapture(sdk, intended) {
141
+ const intendedId = intended?.sys_id || '';
142
+ let effective;
143
+ try {
144
+ effective = await readEffectiveUpdateSet(sdk);
145
+ } catch (error) {
146
+ return {
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';
181
+ }
182
+ return report;
183
+ }
@@ -794,13 +794,23 @@ function unavailableCapture(reason) {
794
794
  return { available: false, status: 'unavailable', reason };
795
795
  }
796
796
 
797
+ // Reporting reads the persisted preference, but the provider captures into the
798
+ // session's effective selection. Reconcile the two before the first content
799
+ // write and carry the result into the payload so a save can never claim a set
800
+ // it did not use.
801
+ async function resolveCaptureContext(options, readUpdateSet) {
802
+ if (!options.ensureCapture) return undefined;
803
+ const intended = await readUpdateSet();
804
+ return options.ensureCapture(intended);
805
+ }
806
+
797
807
  async function addPostMutationCapture(snapshot, sdk, readUpdateSet, flowId) {
798
808
  const updateSet = await readUpdateSet();
799
809
  snapshot.after = updateSet;
800
810
  snapshot.capture_after = await readUpdateSetCapture(sdk, updateSet, flowId);
801
811
  }
802
812
 
803
- export async function readUpdateSetCapture(sdk, updateSet, flowId) {
813
+ export async function readUpdateSetCapture(sdk, updateSet, flowId, { locateElsewhere = false } = {}) {
804
814
  const updateSetId = idValue(updateSet?.sys_id || updateSet?.sysId);
805
815
  if (!updateSetId) return unavailableCapture('current update set has no selected sys_id (likely Default)');
806
816
  const rows = await sdk.list('sys_update_xml', new URLSearchParams({
@@ -810,13 +820,67 @@ export async function readUpdateSetCapture(sdk, updateSet, flowId) {
810
820
  sysparm_fields: 'sys_id,name,type,action,target_name,update_set,payload,xml',
811
821
  }));
812
822
  const matches = rows.filter(row => JSON.stringify(row).includes(flowId));
813
- return {
823
+ const capture = {
814
824
  available: true,
815
825
  status: matches.length ? 'captured' : 'missing',
816
826
  update_set: updateSet,
817
827
  count: matches.length,
818
828
  records: matches,
819
829
  };
830
+ if (!matches.length && locateElsewhere) {
831
+ capture.elsewhere = await findCaptureElsewhere(sdk, flowId, updateSetId);
832
+ const destinations = capture.elsewhere.update_sets || [];
833
+ capture.diagnosis = destinations.length
834
+ ? `Content was saved, but no update XML for this flow is in ${updateSet?.name || updateSetId}. `
835
+ + `${destinations.reduce((sum, set) => sum + set.count, 0)} matching record(s) are in `
836
+ + `${destinations.map(set => `${set.name || set.sys_id} (${set.sys_id})`).join(', ')}. `
837
+ + 'These may be historical captures and do not prove this save was routed elsewhere. '
838
+ + 'Capture can be asynchronous; re-check the intended set before completing or exporting it.'
839
+ : `Content was saved, but no update XML naming this flow was found in ${updateSet?.name || updateSetId} `
840
+ + `or by nameLIKE${flowId}. Capture may be absent or recorded under a different name; `
841
+ + 'inspect sys_update_xml for the flow sys_id before completing the set.';
842
+ }
843
+ return capture;
844
+ }
845
+
846
+ // The flow's own update XML is named `<table>_<sys_id>`, so the flow sys_id is
847
+ // searchable across every set. This locates candidate captures without moving
848
+ // records; a historical match alone cannot establish where this save landed.
849
+ async function findCaptureElsewhere(sdk, flowId, intendedSetId) {
850
+ const id = idValue(flowId);
851
+ // Only a single opaque token may reach the encoded query; never allow query
852
+ // operators such as ^ or = to be injected through a caller-supplied id.
853
+ if (!/^[0-9a-zA-Z_-]{1,64}$/.test(id)) {
854
+ return { checked: false, reason: 'flow identifier is not a safe exact token', update_sets: [] };
855
+ }
856
+ const params = new URLSearchParams({
857
+ sysparm_query: `nameLIKE${id}`,
858
+ sysparm_limit: '50',
859
+ sysparm_display_value: 'all',
860
+ sysparm_fields: 'sys_id,name,type,action,target_name,update_set,sys_created_on',
861
+ });
862
+ let rows;
863
+ try {
864
+ rows = await sdk.list('sys_update_xml', params);
865
+ } catch (error) {
866
+ return { checked: true, available: false, reason: error.message, update_sets: [] };
867
+ }
868
+ const bySet = new Map();
869
+ for (const row of rows) {
870
+ const raw = row.update_set;
871
+ const setId = idValue(raw);
872
+ if (!setId || setId === intendedSetId) continue;
873
+ const entry = bySet.get(setId) || { sys_id: setId, name: raw?.display_value || '', count: 0, records: [] };
874
+ entry.count += 1;
875
+ entry.records.push({
876
+ sys_id: idValue(row.sys_id),
877
+ name: row.name?.display_value || row.name || '',
878
+ action: row.action?.display_value || row.action || '',
879
+ sys_created_on: row.sys_created_on?.display_value || row.sys_created_on || '',
880
+ });
881
+ bySet.set(setId, entry);
882
+ }
883
+ return { checked: true, available: true, query: `nameLIKE${id}`, update_sets: [...bySet.values()] };
820
884
  }
821
885
 
822
886
  export async function createFlowFromManifest(sdk, instance, inputManifest, options = {}) {
@@ -825,6 +889,12 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
825
889
  const idFactory = options.idFactory || (() => randomUUID());
826
890
  const readUpdateSet = options.readUpdateSet || (async () => null);
827
891
  const snapshots = [];
892
+ let captureContext;
893
+ try {
894
+ captureContext = await resolveCaptureContext(options, readUpdateSet);
895
+ } catch (error) {
896
+ throw new Error(`Flow creation refused before any content write: capture context could not be established. ${error.message}`, { cause: error });
897
+ }
828
898
 
829
899
  let parentResponse;
830
900
  try {
@@ -885,7 +955,7 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
885
955
  instance, flowId, scope, type: 'Autosave', annotation: 'JSN flow create',
886
956
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
887
957
  const selectedUpdateSet = await readUpdateSet();
888
- const updateSetCapture = await readUpdateSetCapture(sdk, selectedUpdateSet, flowId);
958
+ const updateSetCapture = await readUpdateSetCapture(sdk, selectedUpdateSet, flowId, { locateElsewhere: true });
889
959
 
890
960
  const triggerReadback = findArray(processflow, 'triggerInstances')[0] || {};
891
961
  return {
@@ -895,6 +965,7 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
895
965
  processflow,
896
966
  definition_readback: { available: true, status: 'read_back', flow_id: flowId },
897
967
  version,
968
+ ...(captureContext ? { capture_context: captureContext } : {}),
898
969
  update_set_capture: updateSetCapture,
899
970
  update_set_mutations: snapshots,
900
971
  lifecycle: { published: false, supported: ['draft', 'autosave'], deferred: ['publish/activation', 'Flow Logic', 'subflows', 'flow variables', 'error handling'] },
@@ -984,6 +1055,12 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
984
1055
  deferred: DEFERRED_LIFECYCLE,
985
1056
  },
986
1057
  };
1058
+ let captureContext;
1059
+ try {
1060
+ captureContext = await resolveCaptureContext(options, readUpdateSet);
1061
+ } catch (error) {
1062
+ throw new Error(`Flow ${flowId} update refused before any content write: capture context could not be established. ${error.message}`, { cause: error });
1063
+ }
987
1064
  // Baseline the published runtime after the definition read (a legacy read can
988
1065
  // materialize a version row) and before the edit session exists.
989
1066
  const runtimeBefore = published ? await readFlowRuntime(sdk, instance, flowId, { scope, snapshotId }) : null;
@@ -1082,7 +1159,7 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1082
1159
  completedStage = 'runtime_verified';
1083
1160
  }
1084
1161
  const selectedUpdateSet = await readUpdateSet();
1085
- const updateSetCapture = await readUpdateSetCapture(sdk, selectedUpdateSet, flowId);
1162
+ const updateSetCapture = await readUpdateSetCapture(sdk, selectedUpdateSet, flowId, { locateElsewhere: true });
1086
1163
  // Report what the record says after the save, not the pre-edit label: a
1087
1164
  // published flow that now has a draft working copy must not look published
1088
1165
  // in the result. `active` and the snapshot pointers are the runtime gates.
@@ -1099,6 +1176,7 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1099
1176
  definition_readback: { available: true, status: 'read_back', flow_id: flowId },
1100
1177
  version,
1101
1178
  ...(runtime ? { runtime_preservation: runtime } : {}),
1179
+ ...(captureContext ? { capture_context: captureContext } : {}),
1102
1180
  update_set_capture: updateSetCapture,
1103
1181
  update_set_mutations: snapshots,
1104
1182
  lifecycle: {
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:
package/src/sdk.js CHANGED
@@ -6,6 +6,9 @@ import { AppError, CodeAPI, CodeAuth, errAuth, errAuthHint, errAPI, errNetwork,
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';
9
12
  import {
10
13
  previewUpdateSet as previewRetrievedUpdateSet,
11
14
  commitUpdateSet as commitRetrievedUpdateSet,
@@ -57,9 +60,17 @@ export class SDKClient {
57
60
  this.onMutation = opts.onMutation;
58
61
  this.timeout = opts.timeout || DEFAULT_TIMEOUT;
59
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 || '';
60
66
  this.oauthCookies = null;
61
67
  this._sessionPromise = null;
62
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;
63
74
  }
64
75
 
65
76
  async _setAuth(req, { skipOAuthSession = false } = {}) {
@@ -153,8 +164,12 @@ export class SDKClient {
153
164
 
154
165
  async _performAuthenticatedRequest(endpoint, opts, {
155
166
  timeout = this.timeout, prepare, skipOAuthSession = false, normalizeErrors = false,
167
+ allowMutationReplay = false,
156
168
  }, consume = (response) => response) {
157
- for (let attempt = 0; attempt < 2; attempt++) {
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;
158
173
  const controller = new AbortController();
159
174
  const timer = setTimeout(() => controller.abort(), timeout);
160
175
  let rejection;
@@ -163,14 +178,15 @@ export class SDKClient {
163
178
  if (prepare) prepare(req);
164
179
  await this._setAuth(req, { skipOAuthSession });
165
180
  const response = await fetch(req);
166
- if (!skipOAuthSession && response.status === 401 && this.recovery) {
167
- // Only a definitive HTTP rejection permits replay, including POST.
168
- // Do not consume/echo the provider's potentially sensitive body.
169
- rejection = { status: response.status, method: req.method, url: req.url };
170
- await response.body?.cancel();
171
- } else {
172
- 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
+ });
173
187
  }
188
+ if (!rejection) return await consume(response);
189
+ await response.body?.cancel?.();
174
190
  } catch (err) {
175
191
  if (normalizeErrors) {
176
192
  if (err.name === 'AbortError') throw errNetwork(new Error('Request timed out'));
@@ -182,15 +198,115 @@ export class SDKClient {
182
198
  } finally {
183
199
  clearTimeout(timer);
184
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
+ }
185
207
  // Browser renewal has its own existing hard timeout. Never leave a
186
208
  // request timeout running while waiting for the human to authenticate.
187
- if (attempt === 0 && await this.recovery.recover(rejection)) {
188
- this.oauthCookies = null;
189
- this.sessionUserToken = '';
190
- continue;
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');
191
273
  }
192
- throw this.recovery.error || errAPI(401, '');
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);
281
+ }
282
+ }
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.';
193
308
  }
309
+ return error;
194
310
  }
195
311
 
196
312
  async request(endpoint, opts = {}) {
@@ -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
+ }