@itphx/synth-backend 0.13.4 → 0.13.10

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.
Files changed (67) hide show
  1. package/dist/app/deps.d.ts +22 -1
  2. package/dist/app/deps.js +743 -63
  3. package/dist/app/listen.js +30 -35
  4. package/dist/app/mount-routes.js +405 -46
  5. package/dist/app/public-routes.d.ts +2 -0
  6. package/dist/app/public-routes.js +11 -0
  7. package/dist/app/sse-events.js +2 -0
  8. package/dist/app.d.ts +8 -1
  9. package/dist/app.js +45 -11
  10. package/dist/auth/api-key.d.ts +19 -0
  11. package/dist/auth/api-key.js +56 -0
  12. package/dist/auth/middleware.js +11 -15
  13. package/dist/auth/oidc.d.ts +46 -4
  14. package/dist/auth/oidc.js +55 -8
  15. package/dist/events/hub.d.ts +36 -2
  16. package/dist/events/hub.js +66 -4
  17. package/dist/events/visible-session-ids.d.ts +35 -0
  18. package/dist/events/visible-session-ids.js +29 -0
  19. package/dist/init.d.ts +1 -0
  20. package/dist/init.js +96 -0
  21. package/dist/lib/app-config.js +42 -1
  22. package/dist/lib/bind-host.d.ts +10 -0
  23. package/dist/lib/bind-host.js +32 -0
  24. package/dist/lib/i18n.js +24 -0
  25. package/dist/lib/principal-identity.d.ts +35 -0
  26. package/dist/lib/principal-identity.js +43 -0
  27. package/dist/lib/project-principal.d.ts +27 -0
  28. package/dist/lib/project-principal.js +27 -0
  29. package/dist/lib/recalc-can-summarize.js +8 -5
  30. package/dist/main.js +9 -2
  31. package/dist/middleware/rate-limiter.d.ts +4 -1
  32. package/dist/middleware/rate-limiter.js +15 -2
  33. package/dist/routes/agents.d.ts +3 -3
  34. package/dist/routes/agents.js +6 -2
  35. package/dist/routes/auth.js +38 -20
  36. package/dist/routes/llm.js +65 -7
  37. package/dist/routes/mcp-remote.d.ts +23 -0
  38. package/dist/routes/mcp-remote.js +152 -0
  39. package/dist/routes/mcp.d.ts +11 -6
  40. package/dist/routes/mcp.js +35 -6
  41. package/dist/routes/project-access.d.ts +61 -0
  42. package/dist/routes/project-access.js +62 -0
  43. package/dist/routes/projects.d.ts +42 -5
  44. package/dist/routes/projects.js +128 -17
  45. package/dist/routes/providers.d.ts +4 -1
  46. package/dist/routes/providers.js +19 -99
  47. package/dist/routes/queue.d.ts +7 -1
  48. package/dist/routes/queue.js +7 -1
  49. package/dist/routes/schedules.d.ts +46 -0
  50. package/dist/routes/schedules.js +10 -0
  51. package/dist/routes/sessions.d.ts +67 -6
  52. package/dist/routes/sessions.js +348 -208
  53. package/dist/routes/users.d.ts +14 -1
  54. package/dist/routes/users.js +91 -1
  55. package/package.json +5 -5
  56. package/dist/routes/audit.d.ts +0 -17
  57. package/dist/routes/audit.js +0 -64
  58. package/dist/routes/context.d.ts +0 -4
  59. package/dist/routes/context.js +0 -93
  60. package/dist/routes/debug.d.ts +0 -3
  61. package/dist/routes/debug.js +0 -30
  62. package/dist/routes/gateway-patterns.d.ts +0 -9
  63. package/dist/routes/gateway-patterns.js +0 -57
  64. package/dist/routes/logs.d.ts +0 -24
  65. package/dist/routes/logs.js +0 -100
  66. package/dist/routes/mcp-registry.d.ts +0 -28
  67. package/dist/routes/mcp-registry.js +0 -483
@@ -2,33 +2,17 @@
2
2
  // (включая SSE/долгоживущие стримы) и WebSocket `/ws/events` (ADR-008/009/024/089).
3
3
  // Вынесено из `app.ts` (ADR-095, шаг 4b) — «вынос по швам», без изменения поведения.
4
4
  import { createServer } from 'node:http';
5
- import { Readable } from 'node:stream';
6
5
  import { WebSocketServer } from 'ws';
6
+ // Node-адаптер core — **общий** контракт standalone и managed (ADR-017/ADR-018:
7
+ // общая логика HTTP живёт в core): `toWebRequest` с сигналом отключения клиента
8
+ // и `pumpBody` с отменой читателя. Своей копии здесь быть не должно — иначе
9
+ // отмена стримов/подписок снова разойдётся (утечка `attached_clients`).
10
+ import { pumpBody, toWebRequest } from '@itphx/synth-core';
7
11
  import { enqueueUserMessage, enqueueSteerMessage, isSessionVisible, parsePermissionPrincipal, resolveUserPrincipal } from '@itphx/synth-core';
8
12
  import { MESSAGE_MODEL_QUERY_PARAM, MESSAGE_MODEL_UNSUPPORTED_CLOSE_CODE, MESSAGE_MODEL_UNSUPPORTED_REASON, isSupportedMessageModelParam, parseSinceParam, } from '@itphx/synth-core';
9
13
  import { nowISO, MessageRole, generateStreamId, isSteerMode, DEFAULT_STEER_MODE, MAX_STEER_INJECTIONS_PER_TURN, STEERING_ERROR_CODES } from '@itphx/synth-shared';
10
14
  import { t } from '../lib/i18n.js';
11
- /**
12
- * Вспомогательная функция для конвертации Node Request в Web Request.
13
- */
14
- function toWebRequest(req) {
15
- const protocol = 'http';
16
- const host = req.headers.host || 'localhost';
17
- const url = `${protocol}://${host}${req.url || '/'}`;
18
- const headers = new Headers();
19
- for (const [k, v] of Object.entries(req.headers)) {
20
- if (v)
21
- headers.set(k, Array.isArray(v) ? v.join(', ') : v);
22
- }
23
- const method = req.method || 'GET';
24
- const noBody = ['GET', 'HEAD'].includes(method) || !req.headers['content-length'];
25
- return new Request(url, {
26
- method,
27
- headers,
28
- body: noBody ? undefined : Readable.toWeb(req),
29
- duplex: 'half',
30
- });
31
- }
15
+ import { groupsOf } from '../lib/project-principal.js';
32
16
  /**
33
17
  * Адаптер для auth.getCurrentUser из сырого IncomingMessage (WS upgrade).
34
18
  */
@@ -62,7 +46,18 @@ export function createBackendListen(deps) {
62
46
  // Создаем HTTP сервер с WebSocket
63
47
  const server = createServer(async (req, res) => {
64
48
  try {
65
- const webReq = toWebRequest(req);
49
+ // Сигнал отключения клиента для `c.req.raw.signal`: Node сообщает о
50
+ // закрытии соединения событием `close` ответа (в т.ч. по таймауту
51
+ // клиента). Без него хендлеры долгоживущих потоков (терминал, SSE) не
52
+ // узнают об уходе клиента и не снимают подписки — `attached_clients`
53
+ // растёт, idle-reaper не срабатывает. Контракт — core
54
+ // `server/app/http-server.ts` (та же логика в standalone).
55
+ const abort = new AbortController();
56
+ res.on('close', () => {
57
+ if (!res.writableFinished)
58
+ abort.abort();
59
+ });
60
+ const webReq = toWebRequest(req, abort.signal);
66
61
  const response = await app.fetch(webReq, {});
67
62
  if (!response) {
68
63
  res.writeHead(500);
@@ -77,24 +72,20 @@ export function createBackendListen(deps) {
77
72
  // вовсе — сбрасываем head принудительно.
78
73
  res.flushHeaders();
79
74
  if (response.body) {
80
- const reader = response.body.getReader();
81
- const pump = async () => {
82
- while (true) {
83
- const { done, value } = await reader.read();
84
- if (done)
85
- break;
86
- res.write(value);
87
- }
88
- res.end();
89
- };
90
- pump().catch(() => res.end());
75
+ // Прокачка — общая с standalone: при обрыве клиента читатель
76
+ // **отменяется** (`reader.cancel()`), иначе цикл `read()` висит вечно
77
+ // и подписка хендлера остаётся живой.
78
+ pumpBody(response.body.getReader(), res);
91
79
  }
92
80
  else {
93
81
  res.end();
94
82
  }
95
83
  }
96
84
  catch {
97
- res.writeHead(500);
85
+ // После аборта клиента ответ уже может быть частично отправлен —
86
+ // повторный `writeHead` дал бы `ERR_HEADERS_SENT` в обработчике.
87
+ if (!res.headersSent)
88
+ res.writeHead(500);
98
89
  res.end();
99
90
  }
100
91
  });
@@ -172,6 +163,7 @@ export function createBackendListen(deps) {
172
163
  userId: user.id,
173
164
  username: user.username,
174
165
  allSessions,
166
+ ...(groupsOf(user) ? { groups: groupsOf(user) } : {}),
175
167
  send(event) {
176
168
  if (replaying) {
177
169
  pending.push(event);
@@ -387,6 +379,9 @@ export function createBackendListen(deps) {
387
379
  kind: 'user',
388
380
  id: user.id,
389
381
  roles: user.roles ?? [],
382
+ // ADR-140 Ф2: группы аутентифицированного пользователя
383
+ // (снимок claim'а IdP); нет — групп нет (fail-closed).
384
+ groups: user.groups ?? [],
390
385
  };
391
386
  const claim = await registry.claim(approvalId, sid, responder, {
392
387
  ...(turnId ? { turnId } : {}),