@jacebenson/jsn 5.3.0-dev.135.1 → 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/package.json +1 -1
- package/src/app.js +2 -0
- package/src/auth-recovery.js +27 -12
- package/src/output.js +3 -0
- package/src/sdk.js +129 -13
- package/src/session-recovery.js +120 -0
package/package.json
CHANGED
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
|
}
|
package/src/auth-recovery.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
-
|
|
48
|
-
|
|
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);
|
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
|
-
|
|
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 &&
|
|
167
|
-
//
|
|
168
|
-
//
|
|
169
|
-
rejection =
|
|
170
|
-
|
|
171
|
-
|
|
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
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
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
|
-
|
|
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
|
+
}
|