@hubex/mcp 0.12.20261119 → 0.13.0

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/dist/auth.js CHANGED
@@ -6,7 +6,96 @@
6
6
  * - "service": a long-lived service token -> JWT via AUTHZ/AccessTokens.
7
7
  * Afterwards all three refresh the same way.
8
8
  */
9
+ import { SET_TOKEN_TOOL } from "./token-prompt.js";
9
10
  export const SELECT_TENANT_TOOL = "hubex_select_tenant";
11
+ /**
12
+ * Limit for each AUTHN/AUTHZ request. Together with HUBEX_REQUEST_TIMEOUT_MS it keeps
13
+ * a refresh plus the API call under the MCP client's default 60 s request timeout.
14
+ */
15
+ const AUTH_REQUEST_TIMEOUT_MS = 10_000;
16
+ /** How many times an auth request rejected with InvalidTenantMember is sent, same data each time. */
17
+ const TENANT_MEMBERSHIP_ATTEMPTS = 3;
18
+ const TENANT_MEMBERSHIP_RETRY_DELAY_MS = 1_000;
19
+ function waitForAuthentication(operation, signal) {
20
+ if (!signal)
21
+ return operation;
22
+ return new Promise((resolve, reject) => {
23
+ const onAbort = () => reject(signal.reason);
24
+ if (signal.aborted)
25
+ onAbort();
26
+ else
27
+ signal.addEventListener("abort", onAbort, { once: true });
28
+ void operation.finally(() => signal.removeEventListener("abort", onAbort)).then(resolve, reject);
29
+ });
30
+ }
31
+ class AuthHttpError extends Error {
32
+ status;
33
+ constructor(status, message) {
34
+ super(message);
35
+ this.status = status;
36
+ this.name = "AuthHttpError";
37
+ }
38
+ }
39
+ /** No complete response: a network failure, a timeout or a body cut off mid-transfer. */
40
+ class AuthTransportError extends Error {
41
+ constructor(message, options) {
42
+ super(message, options);
43
+ this.name = "AuthTransportError";
44
+ }
45
+ }
46
+ function readTenantMembershipFailure(body) {
47
+ let parsed;
48
+ try {
49
+ parsed = JSON.parse(body);
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ const failures = Array.isArray(parsed) ? parsed : [parsed];
55
+ return failures.find((failure) => typeof failure === "object" && failure !== null &&
56
+ "code" in failure && failure.code === "InvalidTenantMember");
57
+ }
58
+ function diagnosticId(value) {
59
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0)
60
+ return String(value);
61
+ return typeof value === "string" && /^\d{1,24}$/.test(value) ? value : undefined;
62
+ }
63
+ class TenantMembershipError extends AuthHttpError {
64
+ constructor(failure, config, request, options) {
65
+ const reason = failure.message === "Закончен период членства в тенанте"
66
+ ? "Закончился период членства пользователя в тенанте"
67
+ : "Членство пользователя в тенанте недействительно";
68
+ const recovery = config.authMode === "token"
69
+ ? `После восстановления доступа переподключи MCP для ввода свежего токена или передай его через ${SET_TOKEN_TOOL}.`
70
+ : "После восстановления доступа повтори вызов.";
71
+ const claims = typeof options.accessToken === "string" ? decodeJwt(options.accessToken) : undefined;
72
+ const selectedTenant = diagnosticId(options.tenantMember?.tenantID);
73
+ const requestTenant = selectedTenant ?? diagnosticId(claims?.TenantID);
74
+ const configuredTenant = diagnosticId(config.tenantId);
75
+ const tenant = configuredTenant && requestTenant && configuredTenant !== requestTenant
76
+ ? `Тенант ${selectedTenant ? "в запросе" : "в токене"} ${requestTenant}, в настройках ${configuredTenant}.`
77
+ : `Тенант ${requestTenant ?? configuredTenant ?? "не определён"}.`;
78
+ const identity = Object.entries({
79
+ accountId: diagnosticId(claims?.AccountID),
80
+ tenantMemberId: diagnosticId(options.tenantMember?.tenantMemberID ?? claims?.TenantMemberID),
81
+ userId: diagnosticId(options.tenantMember?.userID ?? claims?.UserID) ?? diagnosticId(config.userId),
82
+ }).flatMap(([label, value]) => value === undefined ? [] : [`${label} ${value}`]).join(", ");
83
+ const traceIdentifier = failure.traceIdentifier;
84
+ const trace = typeof traceIdentifier === "string" && /^[a-zA-Z0-9:_-]{1,128}$/.test(traceIdentifier)
85
+ ? `Идентификатор трассировки ${traceIdentifier}.`
86
+ : undefined;
87
+ super(401, [
88
+ `HubEx отклонил авторизацию. ${reason} (HTTP 401, ${failure.code}).`,
89
+ `Окружение ${config.env}, режим ${config.authMode}, applicationId ${config.applicationId}.`,
90
+ tenant,
91
+ identity ? `${identity}.` : undefined,
92
+ `Запрос ${request}.`,
93
+ trace,
94
+ `Обратись к администратору HubEx, чтобы проверить членство. ${recovery}`,
95
+ ].filter(Boolean).join("\n"));
96
+ this.name = "TenantMembershipError";
97
+ }
98
+ }
10
99
  /** Decode a JWT payload without verifying the signature (we only read claims). */
11
100
  export function decodeJwt(token) {
12
101
  const parts = token.split(".");
@@ -73,6 +162,7 @@ class RefreshingAuth {
73
162
  accessRejected = false;
74
163
  refreshToken;
75
164
  refreshExp; // seconds since epoch
165
+ tenantMembershipError;
76
166
  tenantId;
77
167
  inflight;
78
168
  constructor(config) {
@@ -88,9 +178,10 @@ class RefreshingAuth {
88
178
  setTenantChooser(choose) {
89
179
  this.chooser = choose;
90
180
  }
91
- async selectTenantMember(tenantID, userID) {
181
+ async selectTenantMember(tenantID, userID, signal) {
92
182
  if (this.inflight)
93
- await this.inflight.catch(() => undefined);
183
+ await waitForAuthentication(this.inflight.catch(() => undefined), signal);
184
+ signal?.throwIfAborted();
94
185
  const previous = this.chosen;
95
186
  this.chosen = { tenantID, userID };
96
187
  // Tokens of the previous user must not be reused or refreshed.
@@ -111,6 +202,8 @@ class RefreshingAuth {
111
202
  async acceptToken(token) {
112
203
  const trimmed = token.trim();
113
204
  assertUsableJwt(trimmed);
205
+ // A rejection of the previous token must not outlive it.
206
+ this.tenantMembershipError = undefined;
114
207
  this.refreshToken = undefined;
115
208
  this.refreshExp = undefined;
116
209
  this.absorb({ access_token: trimmed });
@@ -120,32 +213,55 @@ class RefreshingAuth {
120
213
  if (token === this.accessToken)
121
214
  this.accessRejected = true;
122
215
  }
123
- async getAccessToken() {
124
- if (this.accessToken && !this.accessRejected && !isExpired(this.accessExp)) {
125
- return this.accessToken;
126
- }
216
+ async getAccessToken(signal) {
217
+ signal?.throwIfAborted();
218
+ if (this.tenantMembershipError)
219
+ throw this.tenantMembershipError;
220
+ const current = this.usableAccessToken();
221
+ if (current)
222
+ return current;
127
223
  // De-duplicate concurrent acquisitions.
128
224
  if (!this.inflight) {
129
225
  this.inflight = this.acquire().finally(() => {
130
226
  this.inflight = undefined;
131
227
  });
132
228
  }
133
- return this.inflight;
229
+ return waitForAuthentication(this.inflight, signal);
230
+ }
231
+ usableAccessToken() {
232
+ if (this.accessToken && !this.accessRejected && !isExpired(this.accessExp))
233
+ return this.accessToken;
234
+ return undefined;
134
235
  }
135
236
  async acquire() {
136
- if (this.refreshToken && !isExpired(this.refreshExp)) {
237
+ const { refreshToken, accessToken } = this;
238
+ if (refreshToken && !isExpired(this.refreshExp)) {
239
+ let renewed;
240
+ let failure;
137
241
  try {
138
- return await this.renew();
242
+ renewed = await this.renew(refreshToken, accessToken);
243
+ }
244
+ catch (error) {
245
+ failure = error;
246
+ }
247
+ // A manually supplied token takes precedence over an older refresh response.
248
+ if (this.refreshToken !== refreshToken || this.accessToken !== accessToken) {
249
+ const current = this.usableAccessToken();
250
+ if (current)
251
+ return current;
252
+ throw new Error("Токен HubEx изменился во время обновления. Повтори вызов.");
139
253
  }
140
- catch (err) {
141
- // Not fatal: fall back to a full authentication exactly once.
142
- console.error(`[hubex-mcp] token refresh failed, re-authenticating: ${err.message}`);
143
- this.refreshToken = undefined;
144
- this.refreshExp = undefined;
254
+ if (renewed) {
255
+ this.absorb(renewed);
256
+ return renewed.access_token;
145
257
  }
258
+ if (failure instanceof TenantMembershipError)
259
+ this.rejectTenantMembership(failure);
260
+ if (!this.reauthenticatesAfterRefresh(failure))
261
+ throw failure;
262
+ console.error(`[hubex-mcp] token refresh failed, re-authenticating: ${failure.message}`);
146
263
  }
147
- else if (this.refreshToken) {
148
- // Протух — выбрасываем, иначе новый не будет запрошен после аутентификации.
264
+ if (refreshToken) {
149
265
  this.refreshToken = undefined;
150
266
  this.refreshExp = undefined;
151
267
  }
@@ -160,17 +276,37 @@ class RefreshingAuth {
160
276
  * the issuer options, and without it the new token silently gets the default
161
277
  * (shorter) lifetime. The refresh token itself is not rotated.
162
278
  */
163
- async renew() {
279
+ async renew(refreshToken, accessToken) {
164
280
  const result = await this.fetchJwt(`${this.config.apiBaseUrl}/AUTHZ/AccessTokens`, {
165
281
  method: "POST",
166
282
  headers: this.authHeaders({ "Content-Type": "application/json" }),
167
- body: JSON.stringify({ refreshJwt: this.refreshToken, accessJwt: this.accessToken }),
168
- });
169
- const token = this.absorb(result);
170
- if (!token) {
283
+ body: JSON.stringify({ refreshJwt: refreshToken, accessJwt: accessToken }),
284
+ }, { accessToken });
285
+ if (typeof result.access_token !== "string" || !result.access_token) {
171
286
  throw new Error("Refresh succeeded but no access_token was returned.");
172
287
  }
173
- return token;
288
+ if (result.refresh_token && typeof result.refresh_token !== "string") {
289
+ throw new Error("Refresh returned an invalid refresh_token.");
290
+ }
291
+ return result;
292
+ }
293
+ /**
294
+ * Whether a failed refresh drops the refresh token for a full authentication.
295
+ * AUTHZ/AccessTokens documents 400 and 401 as a rejection of the credentials sent.
296
+ * Anything else keeps it in "token" mode, where a full authentication means asking
297
+ * the user. Login and service tokens need nobody, so there it is kept only through
298
+ * an outage that a full authentication would hit as well; otherwise a refresh that
299
+ * keeps failing (403, a response without access_token) would block every call
300
+ * until the refresh token expires.
301
+ */
302
+ reauthenticatesAfterRefresh(failure) {
303
+ if (failure instanceof AuthHttpError && [400, 401].includes(failure.status))
304
+ return true;
305
+ if (this.config.authMode === "token")
306
+ return false;
307
+ const outage = failure instanceof AuthTransportError ||
308
+ (failure instanceof AuthHttpError && failure.status >= 500);
309
+ return !outage;
174
310
  }
175
311
  /** Full authentication: credentials from config, or a token from the user. */
176
312
  async authenticate() {
@@ -212,8 +348,10 @@ class RefreshingAuth {
212
348
  */
213
349
  async loginByPassword() {
214
350
  const basic = Buffer.from(`${encodeURIComponent(this.config.username)}:${encodeURIComponent(this.config.password)}`).toString("base64");
215
- const account = (await this.fetchJwt(`${this.config.apiBaseUrl}/AUTHN/Accounts/login`, { method: "POST", headers: this.authHeaders({ Authorization: `Basic ${basic}` }) }, `Проверь HUBEX_USERNAME и HUBEX_PASSWORD: учётная запись должна существовать в окружении ` +
216
- `HUBEX_ENV=${this.config.env}.`));
351
+ const account = (await this.fetchJwt(`${this.config.apiBaseUrl}/AUTHN/Accounts/login`, { method: "POST", headers: this.authHeaders({ Authorization: `Basic ${basic}` }) }, {
352
+ rejectHint: `Проверь HUBEX_USERNAME и HUBEX_PASSWORD: учётная запись должна существовать в окружении ` +
353
+ `HUBEX_ENV=${this.config.env}.`,
354
+ }));
217
355
  const member = await this.pickTenantMember(account.tenantEntities ?? []);
218
356
  // The chosen tenant, even when switching users: absorb() keeps a known tenant.
219
357
  this.tenantId = String(member.tenantID);
@@ -224,7 +362,7 @@ class RefreshingAuth {
224
362
  "Content-Type": "application/json",
225
363
  }),
226
364
  body: JSON.stringify({ tenantID: member.tenantID, tenantMemberID: member.tenantMemberID }),
227
- });
365
+ }, { accessToken: account.access_token, tenantMember: member });
228
366
  }
229
367
  /**
230
368
  * Narrows the account's tenant users by HUBEX_TENANT_ID / HUBEX_USER_ID. One
@@ -281,20 +419,36 @@ class RefreshingAuth {
281
419
  * would report success on a token that doesn't actually work.
282
420
  */
283
421
  async acquireRefreshToken() {
422
+ const accessToken = this.accessToken;
284
423
  try {
285
424
  const result = await this.fetchJwt(`${this.config.apiBaseUrl}/AUTHZ/RefreshTokens`, {
286
425
  method: "GET",
287
- headers: this.authHeaders({ Authorization: `Bearer ${this.accessToken}` }),
288
- });
289
- this.absorb(result);
426
+ headers: this.authHeaders({ Authorization: `Bearer ${accessToken}` }),
427
+ }, { accessToken });
428
+ if (this.accessToken === accessToken)
429
+ this.absorb(result);
290
430
  }
291
431
  catch (err) {
432
+ if (err instanceof TenantMembershipError) {
433
+ if (this.accessToken === accessToken)
434
+ this.rejectTenantMembership(err);
435
+ throw err;
436
+ }
292
437
  if (this.config.authMode === "token")
293
438
  throw err;
294
439
  console.error("[hubex-mcp] could not obtain a refresh token; will re-authenticate on expiry: " +
295
440
  `${err.message}`);
296
441
  }
297
442
  }
443
+ rejectTenantMembership(error) {
444
+ this.accessRejected = true;
445
+ this.refreshToken = undefined;
446
+ this.refreshExp = undefined;
447
+ if (this.config.authMode === "token")
448
+ this.tenantMembershipError = error;
449
+ console.error(`[hubex-mcp] ${error.message}`);
450
+ throw error;
451
+ }
298
452
  authHeaders(extra) {
299
453
  return {
300
454
  "X-Application-ID": this.config.applicationId,
@@ -302,12 +456,50 @@ class RefreshingAuth {
302
456
  ...extra,
303
457
  };
304
458
  }
305
- /** `rejectHint` replaces the default wrong-environment hint on 401/403/409. */
306
- async fetchJwt(url, init, rejectHint) {
307
- const res = await fetch(url, init);
459
+ /** Repeats the request unchanged while HubEx answers InvalidTenantMember, up to the attempt limit. */
460
+ async fetchJwt(url, init, options = {}) {
461
+ for (let attempt = 1;; attempt += 1) {
462
+ try {
463
+ return await this.fetchJwtOnce(url, init, options);
464
+ }
465
+ catch (error) {
466
+ if (!(error instanceof TenantMembershipError) || attempt >= TENANT_MEMBERSHIP_ATTEMPTS)
467
+ throw error;
468
+ console.error(`[hubex-mcp] ${init.method ?? "GET"} ${url}: InvalidTenantMember, ` +
469
+ `попытка ${attempt + 1} из ${TENANT_MEMBERSHIP_ATTEMPTS} через ${TENANT_MEMBERSHIP_RETRY_DELAY_MS} мс`);
470
+ await new Promise((resolve) => setTimeout(resolve, TENANT_MEMBERSHIP_RETRY_DELAY_MS));
471
+ }
472
+ }
473
+ }
474
+ async fetchJwtOnce(url, init, options) {
475
+ const request = `${init.method ?? "GET"} ${url}`;
476
+ const controller = new AbortController();
477
+ const timeout = setTimeout(() => controller.abort(), AUTH_REQUEST_TIMEOUT_MS);
478
+ let res;
479
+ let body;
480
+ try {
481
+ res = await fetch(url, { ...init, signal: controller.signal });
482
+ body = await res.text();
483
+ }
484
+ catch (error) {
485
+ const reason = controller.signal.aborted
486
+ ? `HubEx не ответил за ${AUTH_REQUEST_TIMEOUT_MS / 1000} с`
487
+ : res
488
+ ? `ответ HTTP ${res.status} оборван: ${error.message}`
489
+ : `запрос не дошёл до HubEx: ${error.message}`;
490
+ throw new AuthTransportError(`${request}: ${reason}.`, { cause: error });
491
+ }
492
+ finally {
493
+ clearTimeout(timeout);
494
+ }
308
495
  if (!res.ok) {
309
- const body = await res.text().catch(() => "");
310
- let message = `${init.method ?? "GET"} ${url} failed (HTTP ${res.status}): ${body.slice(0, 500)}`;
496
+ if (res.status === 401) {
497
+ const membershipFailure = readTenantMembershipFailure(body);
498
+ if (membershipFailure)
499
+ throw new TenantMembershipError(membershipFailure, this.config, request, options);
500
+ }
501
+ const { rejectHint } = options;
502
+ let message = `${request} failed (HTTP ${res.status}): ${body.slice(0, 500)}`;
311
503
  if (rejectHint && [401, 403, 409].includes(res.status)) {
312
504
  message += ` ${rejectHint}`;
313
505
  }
@@ -316,9 +508,14 @@ class RefreshingAuth {
316
508
  ` Сейчас выбрано окружение HUBEX_ENV=${this.config.env}. Если токен получен в другом ` +
317
509
  `окружении (dev/stg/prod), авторизация не пройдёт — проверь, что токен именно из ${this.config.env}.`;
318
510
  }
319
- throw new Error(message);
511
+ throw new AuthHttpError(res.status, message);
512
+ }
513
+ try {
514
+ return JSON.parse(body);
515
+ }
516
+ catch {
517
+ throw new Error(`${request}: HubEx вернул не JSON (HTTP ${res.status}).`);
320
518
  }
321
- return (await res.json());
322
519
  }
323
520
  /** Stores whatever the response carried; returns its access token, if any. */
324
521
  absorb(result) {
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Чтение и проверка элементов пакета: массив `items` из вызова инструмента или
3
+ * JSON/JSONL-файл `itemsFile`. Проверка идёт до отправки первого запроса:
4
+ * ошибка здесь не должна оставлять половину пакета выполненной.
5
+ */
6
+ import { readFile, stat } from "node:fs/promises";
7
+ import { extname, isAbsolute } from "node:path";
8
+ import { RESERVED_HEADERS } from "../http.js";
9
+ export const MAX_BATCH_ITEMS = 5000;
10
+ export const MAX_ITEMS_FILE_BYTES = 20 * 1024 * 1024;
11
+ const ITEM_KEYS = ["pathParams", "query", "body", "headers"];
12
+ function isPlainObject(value) {
13
+ return value !== null && typeof value === "object" && !Array.isArray(value);
14
+ }
15
+ function checkItemCount(items) {
16
+ if (items.length === 0) {
17
+ throw new Error("Пакет пустой: передай хотя бы один элемент.");
18
+ }
19
+ if (items.length > MAX_BATCH_ITEMS) {
20
+ throw new Error(`В пакете ${items.length} элементов, максимум ${MAX_BATCH_ITEMS}. ` +
21
+ `Раздели данные на несколько пакетов и запусти их по очереди.`);
22
+ }
23
+ }
24
+ async function readItemsFile(itemsFile) {
25
+ if (typeof itemsFile !== "string" || !isAbsolute(itemsFile)) {
26
+ throw new Error(`itemsFile должен быть строкой — абсолютный путь к файлу (получено: ${JSON.stringify(itemsFile)}). ` +
27
+ `Относительные пути не поддерживаются: укажи полный путь.`);
28
+ }
29
+ const extension = extname(itemsFile).toLowerCase();
30
+ if (extension !== ".json" && extension !== ".jsonl") {
31
+ throw new Error(`Файл ${itemsFile} должен иметь расширение .json или .jsonl ` +
32
+ `(.json — массив элементов, .jsonl — один элемент в строке).`);
33
+ }
34
+ let size;
35
+ try {
36
+ const info = await stat(itemsFile);
37
+ if (!info.isFile())
38
+ throw new Error(`${itemsFile} — не файл.`);
39
+ size = info.size;
40
+ }
41
+ catch (e) {
42
+ if (e.code === "ENOENT") {
43
+ throw new Error(`Файл ${itemsFile} не найден. Проверь путь: он должен быть абсолютным и существовать.`);
44
+ }
45
+ throw e;
46
+ }
47
+ if (size > MAX_ITEMS_FILE_BYTES) {
48
+ throw new Error(`Файл ${itemsFile} занимает ${Math.ceil(size / 1024 / 1024)} МБ, максимум ` +
49
+ `${MAX_ITEMS_FILE_BYTES / 1024 / 1024} МБ. Раздели данные на несколько файлов.`);
50
+ }
51
+ // BOM в начале файла (Excel, Блокнот Windows) ломает JSON.parse первой строки.
52
+ const text = (await readFile(itemsFile, "utf8")).replace(/^\uFEFF/, "");
53
+ if (extension === ".json") {
54
+ let parsed;
55
+ try {
56
+ parsed = JSON.parse(text);
57
+ }
58
+ catch (e) {
59
+ throw new Error(`Файл ${itemsFile} — некорректный JSON: ${e.message}`);
60
+ }
61
+ if (!Array.isArray(parsed)) {
62
+ throw new Error(`Файл ${itemsFile} должен содержать массив элементов пакета, а не ${isPlainObject(parsed) ? "объект" : "одиночное значение"}. ` +
63
+ `Для элемента на строку используй расширение .jsonl.`);
64
+ }
65
+ return parsed;
66
+ }
67
+ const items = [];
68
+ text.split("\n").forEach((line, i) => {
69
+ if (line.trim() === "")
70
+ return;
71
+ try {
72
+ items.push(JSON.parse(line));
73
+ }
74
+ catch (e) {
75
+ throw new Error(`Файл ${itemsFile}, строка ${i + 1}: некорректный JSON (${e.message}). ` +
76
+ `В .jsonl на каждой строке должен быть один JSON-элемент.`);
77
+ }
78
+ });
79
+ return items;
80
+ }
81
+ /** Элементы пакета из `items` или `itemsFile` (ровно одно из двух). */
82
+ export async function readBatchItems(args) {
83
+ const hasItems = args.items !== undefined && args.items !== null;
84
+ const hasFile = args.itemsFile !== undefined && args.itemsFile !== null;
85
+ if (hasItems === hasFile) {
86
+ throw new Error("Передай либо items, либо itemsFile — ровно одно из двух: items — массив элементов, " +
87
+ "itemsFile — абсолютный путь к .json/.jsonl.");
88
+ }
89
+ if (hasItems) {
90
+ if (!Array.isArray(args.items)) {
91
+ throw new Error("items должен быть массивом элементов вида { pathParams?, query?, body?, headers? }.");
92
+ }
93
+ checkItemCount(args.items);
94
+ return { items: args.items };
95
+ }
96
+ const items = await readItemsFile(args.itemsFile);
97
+ checkItemCount(items);
98
+ return { items, itemsFile: args.itemsFile };
99
+ }
100
+ /** Элемент пакета как вход запроса; ошибка называет индекс элемента (с нуля). */
101
+ export function toRequestInput(raw, index) {
102
+ const label = `Элемент ${index}`;
103
+ if (!isPlainObject(raw)) {
104
+ throw new Error(`${label}: ожидается объект { pathParams?, query?, body?, headers? }, получено ${raw === null ? "null" : Array.isArray(raw) ? "массив" : typeof raw}.`);
105
+ }
106
+ const keys = Object.keys(raw);
107
+ const unknown = keys.filter((k) => !ITEM_KEYS.includes(k));
108
+ if (unknown.length > 0) {
109
+ if (unknown.length === keys.length) {
110
+ throw new Error(`${label}: похоже на голое тело запроса (ключи: ${unknown.join(", ")}). ` +
111
+ `Оберни его в поле body: { "body": { ... } }. ` +
112
+ `Допустимые ключи элемента: ${ITEM_KEYS.join(", ")}.`);
113
+ }
114
+ throw new Error(`${label}: неизвестные ключи: ${unknown.join(", ")}. ` +
115
+ `Допустимые ключи элемента: ${ITEM_KEYS.join(", ")}. ` +
116
+ `Поля тела запроса клади внутрь body.`);
117
+ }
118
+ // null — то же, что отсутствие поля (как `args.pathParams ?? {}` в hubex_request_*).
119
+ const fields = Object.fromEntries(Object.entries(raw).filter(([, v]) => v !== null));
120
+ for (const key of ["pathParams", "query", "headers"]) {
121
+ if (fields[key] !== undefined && !isPlainObject(fields[key])) {
122
+ throw new Error(`${label}: поле ${key} должно быть объектом.`);
123
+ }
124
+ }
125
+ if (isPlainObject(fields.headers)) {
126
+ const bad = Object.entries(fields.headers)
127
+ .filter(([, v]) => typeof v !== "string")
128
+ .map(([k]) => k);
129
+ if (bad.length > 0) {
130
+ throw new Error(`${label}: значения headers должны быть строками, исправь: ${bad.join(", ")}.`);
131
+ }
132
+ // HubexClient отклонил бы такой заголовок уже при отправке — элемент упал бы
133
+ // посреди пакета, а не при проверке до старта.
134
+ const reserved = Object.keys(fields.headers).filter((name) => RESERVED_HEADERS.has(name.toLowerCase()));
135
+ if (reserved.length > 0) {
136
+ throw new Error(`${label}: заголовки ${reserved.join(", ")} подставляет сам сервер, переопределить их нельзя. ` +
137
+ `Убери их из headers.`);
138
+ }
139
+ }
140
+ return fields;
141
+ }